repo
string
commit
string
message
string
diff
string
razerbeans/webri
a1115dd40ded2353a985be1b766808414aaca4aa
reap has become syckle
diff --git a/plug/syckles/webri.rb b/plug/syckles/webri.rb index aadca6a..5dc1889 100644 --- a/plug/syckles/webri.rb +++ b/plug/syckles/webri.rb @@ -1,110 +1,108 @@ -module Reap -module Plugins +module Syckles + + # = WebRI Documentation Plugin + # + # The webri documentation plugin provides services for + # generating webri documentation. + # + # By default it generates the documentaiton at doc/webri. + # + # This plugin provides three services for both the +main+ and +site+ pipelines. + # + # * +webri+ - Create webri docs + # * +reset+ - Reset webri docs + # * +clean+ - Remove webri docs + # + class WebRI < Plugin + + cycle :main, :document + cycle :site, :document + + cycle :main, :clean + cycle :site, :clean + + cycle :main, :reset + cycle :site, :reset + + #available do |project| + # !project.metadata.loadpath.empty? + #end + + # Default location to store ri documentation files. + DEFAULT_OUTPUT = "doc/webri" - # = WebRI Documentation Plugin # - # The webri documentation plugin provides services for - # generating webri documentation. - # - # By default it generates the documentaiton at doc/webri. - # - # This plugin provides three services for both the +main+ and +site+ pipelines. - # - # * +webri+ - Create webri docs - # * +reset+ - Reset webri docs - # * +clean+ - Remove webri docs - # - class WebRI < Plugin - - pipeline :main, :document - pipeline :site, :document + DEFAULT_RIDOC = "doc/ri" - pipeline :main, :clean - pipeline :site, :clean + # + def initialize_defaults + @title = metadata.title + @ridoc = DEFAULT_RIDOC + @output = DEFAULT_OUTPUT + end - pipeline :main, :reset - pipeline :site, :reset + # Title of documents. Defaults to general metadata title field. + attr_accessor :title - #available do |project| - # !project.metadata.loadpath.empty? - #end + # Where to save rdoc files (doc/webri). + attr_accessor :output - # Default location to store ri documentation files. - DEFAULT_OUTPUT = "doc/webri" + # Location of ri docs. Defaults to doc/ri. + # These files must be preset for this plugin to work. + attr_accessor :ridoc - # - DEFAULT_RIDOC = "doc/ri" - - # - def initialize_defaults - @title = metadata.title - @ridoc = DEFAULT_RIDOC - @output = DEFAULT_OUTPUT - end + # In case one is inclined to #ridoc plural. + alias_accessor :ridocs - # Title of documents. Defaults to general metadata title field. - attr_accessor :title - - # Where to save rdoc files (doc/webri). - attr_accessor :output + # Generate ri documentation. This utilizes + # rdoc to produce the appropriate files. + # + def document + output = self.output - # Location of ri docs. Defaults to doc/ri. - # These files must be preset for this plugin to work. - attr_accessor :ridoc + #cmdopts = {} + #cmdopts['o'] = output - # In case one is inclined to #ridoc plural. - alias_accessor :ridocs + #input = files #.collect do |i| + # dir?(i) ? File.join(i,'**','*') : i + #end - # Generate ri documentation. This utilizes - # rdoc to produce the appropriate files. - # - def document - output = self.output + if outofdate?(output, ridoc) or force? + rm_r(output) if exist?(output) and safe?(output) # remove old webri docs - #cmdopts = {} - #cmdopts['o'] = output + status "Generating #{output} ..." - #input = files #.collect do |i| - # dir?(i) ? File.join(i,'**','*') : i + #vector = [ridoc, cmdopts] + #if verbose? + sh "webri -o #{output} #{ridoc}" + #else + # silently do + # sh "webri #{vector.to_console}" + # end #end - - if outofdate?(output, ridoc) or force? - rm_r(output) if exist?(output) and safe?(output) # remove old webri docs - - status "Generating #{output} ..." - - #vector = [ridoc, cmdopts] - #if verbose? - sh "webri -o #{output} #{ridoc}" - #else - # silently do - # sh "webri #{vector.to_console}" - # end - #end - else - report "webri docs are current (#{output.sub(Dir.pwd,'')})" - end + else + report "webri docs are current (#{output.sub(Dir.pwd,'')})" end + end - # Set the output directory's mtime to furthest time in past. - # This "marks" the documentation as out-of-date. - def reset - if File.directory?(output) - File.utime(0,0,self.output) - report "reset #{output}" - end + # Set the output directory's mtime to furthest time in past. + # This "marks" the documentation as out-of-date. + def reset + if File.directory?(output) + File.utime(0,0,self.output) + report "reset #{output}" end + end - # Remove ri products. - def clean - if File.directory?(output) - rm_r(output) - status "Removed #{output}" #unless dryrun? - end + # Remove ri products. + def clean + if File.directory?(output) + rm_r(output) + status "Removed #{output}" #unless dryrun? end - end -end + end + end
razerbeans/webri
3138bd85c69b3c09fb9a8666cb1f4160d37c9fdd
fixed-up onepage generation option
diff --git a/TODO b/TODO index 5cae3b4..cf2136e 100644 --- a/TODO +++ b/TODO @@ -1,26 +1,8 @@ = WebRI TODO -== One File +* All three modes now works, they just need a bit of TLC +to look good and work optiamally. -An idea for a future version... generate all the html into -a single file, then use CSS and JQeury to completely control -presentation. That would be pretty cool, as it would mean -the entire set of documentation is on a single file. - -The only problem with this design is that it would mean -we could not use realtime serving of the docs, like we -can now using Webrik b/c large programs, like Rails and -Ruby itself, take a considerable amount of time to generate, -something like 30 minutes to an hour. - -However, shortcomings aside, this might be a great way to -go. The dynamic server is already a bit slow anyway b/c -ri itself is slow, and in practice I have found that end -up utilizing the generated output in the long run. The -dynamic site I use only for debugging. - -Hmmm... Ok. So how about I add it as an additional option. - -[NOTE: This is almost done, but all the generation code -could use bit of reworking to make the code all "pretty".] +* Would like to add a Rack server, that could be used instead +of the Webrick server. diff --git a/lib/webri/assets/css/style1.css b/lib/webri/assets/css/style1.css new file mode 100644 index 0000000..3e5eada --- /dev/null +++ b/lib/webri/assets/css/style1.css @@ -0,0 +1,57 @@ +html, body { + height:100%; + margin: 0; + padding: 0; + border: none; + text-align: left; + position: relative; +} + +body { + font-family: monospace; + font-size: 12px; + background: #fff; +} + +div { margin: 0; padding: 0; } + +pre { font-family: monospace; } + +p { padding: 5px 0; } + +a { text-decoration: none; } + +/* HEADER */ + +#header { width: 100%; background: white; height: 100px; } +#header h1 { margin: 0; padding: 0; font-size: 64px; } +#header h2 { margin: 0; padding: 0; font-size: 10pt; font-weight: bold; } +#header .small { font-size: 10pt; } + +.small { font-size: 10pt; } + +/* TREE */ + + #tree { padding: 10px; background: white; width: 240px; border: 0px solid #ccc; position: fixed; left: 0; top: 0; } + ul { cursor: pointer; cursor: hand; padding-left: 10px; } + li { margin-left: 10px; } + .trigger { cursor: pointer; cursor: hand; } + .branch { } + .leaf { color: #cc0000; } + .meta_leaf { color: #00cc00; font-weight: bold; } + .title { font-size: 1.8em; } + .link { font-weight: bold; } + .link:hover{ text-decoration: underline; } + +/* MAIN */ + +#main { + margin-left: 260px; + padding: 10px 15px; /* bottom padding for footer */ + border: 1px solid #ccc; + background: white; + font-family: monospace; + font-size: 14px; +} + +.ad { float: right; padding: 20px 20px 0 0; } diff --git a/lib/webri/generator.rb b/lib/webri/generator.rb index 9dcb5a8..cf628cb 100644 --- a/lib/webri/generator.rb +++ b/lib/webri/generator.rb @@ -1,227 +1,165 @@ require 'webri/server' module WebRI # This is the static website generator. # class Generator < Server # Reference to CGI Service #attr :cgi # Reference to RI Service #attr :service # Directory in which to store generated html files attr :output # def initialize(service, options={}) super(service, options) #@cgi = {} #CGI.new('html4') #@service = service @directory_depth = 0 end # - def tree - #%[<iframe src="tree.html"></iframe>] - @tree ||= heirarchy.to_html_static - end + #def tree + # #%[<iframe src="tree.html"></iframe>] + # @tree ||= heirarchy.to_html_static + #end + =begin # def lookup(req) keyw = File.basename(req.path_info) if keyw keyw.sub!('-','#') html = service.info(keyw) #puts html #term = AnsiSys::Terminal.new.echo(ansi) #html = term.render(:html) #=> HTML fragment #html = ERB::Util.html_escape(html) html = "#{html}" else html = "<h1>ERROR</h1>" end return html end =end #def template_source # @template_source ||= File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) #end # #def to_html # #filetext = File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) # template = ERB.new(template_source) # template.result(binding) # #heirarchy.to_html #end - # generate webpages + # Generate webpages. def generate(output=".") @output = File.expand_path(output) # traverse the the hierarchy generate_support_files #generate_recurse(heirarchy) # heirarchy.class_methods.each do |name| # p name # end # heirarchy.instance_methods.each do |name| # p name # end heirarchy.subspaces.each do |name, entry| #p name, entry generate_recurse(entry) end end - # + # Recrusive HTML generation on a hierarchy entry. def generate_recurse(entry) keyword = entry.full_name if keyword puts keyword @current_content = service.info(keyword) #lookup(keyword) else keyword = '' @current_content = "Welcome" end file = entry.file_name file = File.join(output, file) #file = keyword #file = file.gsub('::', '--') #file = file.gsub('.' , '--') #file = file.gsub('#' , '-') #file = File.join(output, file + '.html') write(file, service.info(keyword)) cmethods = entry.class_methods.map{ |x| x.to_s }.sort cmethods.each do |name| mname = "#{entry.full_name}.#{name}" mfile = WebRI.entry_to_path(mname) mfile = File.join(output, mfile) #mfile = File.join(output, "#{entry.file_name}/c-#{esc(name)}.html") write(mfile, service.info(mname)) end imethods = entry.instance_methods.map{ |x| x.to_s }.sort imethods.each do |name| mname = "#{entry.full_name}##{name}" mfile = WebRI.entry_to_path(mname) mfile = File.join(output, mfile) #mfile = File.join(output, "#{entry.file_name}/i-#{esc(name)}.html") write(mfile, service.info(mname)) end entry.subspaces.each do |child_name, child_entry| next if child_entry == entry @directory_depth += 1 generate_recurse(child_entry) @directory_depth -= 1 end end - # - def write(file, text) - puts file - FileUtils.mkdir_p(File.dirname(file)) - File.open(file, 'w') { |f| f << text.to_s } - end - - # + # Generate files. def generate_support_files FileUtils.mkdir_p(output) write(File.join(output, 'index.html'), index) #write(File.join(output, 'header.html'), page_header) #write(File.join(output, 'tree.html'), page_tree) #write(File.join(output, 'main.html'), page_main) # copy assets dir = File.join(directory, 'assets') FileUtils.cp_r(dir, output) end + # Write file. + def write(file, text) + puts file + FileUtils.mkdir_p(File.dirname(file)) + File.open(file, 'w') { |f| f << text.to_s } + end + # def current_content @current_content end -=begin - # = Generator Heirarchy - # - class Heirarchy - attr :name - attr :parent - attr :subspaces - attr :instance_methods - attr :class_methods - - def initialize(name, parent=nil) - @name = name - @parent = parent if NS===parent - @subspaces = {} - @class_methods = [] - @instance_methods = [] - end - - def key - full_name - end - - def [](name) - @subspaces[name] - end - - def []=(name, value) - @subspaces[name] = value - end - - def root? - !parent - end - - def full_name - if root? - nil - else - [parent.full_name, name].compact.join("::") - end - end - - def file_name - file = full_name - file = file.gsub('::', '--') - file = file.gsub('.' , '--') - file = file.gsub('#' , '-') - #file = File.join(output, file + '.html') - file - end - - - def esc(text) - OpEsc.escape(text.to_s) - end - - def inspect - "<#{self.class} #{name}>" - end - - end #class NS -=end - end #class Generator end #module WebRI diff --git a/lib/webri/generator1.rb b/lib/webri/generator1.rb index f74d362..53fe500 100644 --- a/lib/webri/generator1.rb +++ b/lib/webri/generator1.rb @@ -1,270 +1,211 @@ require 'webri/server' module WebRI # This is the static website generator which creates # a single page. # class GeneratorOne < Server # Reference to CGI Service #attr :cgi # Reference to RI Service #attr :service # Dir in which to store generated html attr :output # attr :html # def initialize(service, options={}) super(service, options) @html = "" #@cgi = {} #CGI.new('html4') #@service = service @directory_depth = 0 end # - def tree - #%[<iframe src="tree.html"></iframe>] - @tree ||= heirarchy.to_html_static - end + #def tree + # #%[<iframe src="tree.html"></iframe>] + # @tree ||= heirarchy.to_html_static + #end =begin # def lookup(req) keyw = File.basename(req.path_info) if keyw keyw.sub!('-','#') html = service.info(keyw) #puts html #term = AnsiSys::Terminal.new.echo(ansi) #html = term.render(:html) #=> HTML fragment #html = ERB::Util.html_escape(html) html = "#{html}" else html = "<h1>ERROR</h1>" end return html end =end #def template_source # @template_source ||= File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) #end # #def to_html # #filetext = File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) # template = ERB.new(template_source) # template.result(binding) # #heirarchy.to_html #end # generate webpages def generate(output=".") @output = File.expand_path(output) @assets = {} # traverse the the hierarchy #generate_recurse(heirarchy) # heirarchy.class_methods.each do |name| # p name # end # heirarchy.instance_methods.each do |name| # p name # end heirarchy.subspaces.each do |name, entry| #p name, entry generate_recurse(entry) end generate_support_files end # def generate_recurse(entry) keyword = entry.full_name if keyword puts keyword @current_content = service.info(keyword) #lookup(keyword) else keyword = '' @current_content = "Welcome" end file = entry.file_name #file = File.join(output, file) #file = keyword #file = file.gsub('::', '--') #file = file.gsub('.' , '--') #file = file.gsub('#' , '-') #file = File.join(output, file + '.html') - html << %[\n<div id="#{file}" class="slot module" style="display: none;">\n] + html << %[<h1>#{entry.full_name}</h1>] + + html << %[\n<div id="#{file}" class="slot module">\n] html << service.info(keyword) html << %[\n</div>\n] + #html << %[<h1>Class Methods</h1>] cmethods = entry.class_methods.map{ |x| x.to_s }.sort cmethods.each do |name| mname = "#{entry.full_name}.#{name}" mfile = WebRI.entry_to_path(mname) #mfile = File.join(output, mfile) #mfile = File.join(output, "#{entry.file_name}/c-#{esc(name)}.html") - html << %[\n<div id="#{mfile}" class="slot cmethod" style="display: none;">\n] + html << %[\n<div id="#{mfile}" name="#{mfile}" class="slot cmethod">\n] html << service.info(mname) html << %[\n</div>\n] #write(mfile, service.info(mname)) end + #html << %[<h1>Instance Methods</h1>] imethods = entry.instance_methods.map{ |x| x.to_s }.sort imethods.each do |name| mname = "#{entry.full_name}##{name}" mfile = WebRI.entry_to_path(mname) #mfile = File.join(output, mfile) #mfile = File.join(output, "#{entry.file_name}/i-#{esc(name)}.html") - html << %[\n<div id="#{mfile}" class="slot imethod" style="display: none;">\n] + html << %[\n<div id="#{mfile}" name="#{mfile}" class="slot imethod">\n] html << service.info(mname) html << %[\n</div>\n] #write(mfile, service.info(mname)) end entry.subspaces.each do |child_name, child_entry| next if child_entry == entry @directory_depth += 1 generate_recurse(child_entry) @directory_depth -= 1 end end # def write(file, text) puts file FileUtils.mkdir_p(File.dirname(file)) File.open(file, 'w') { |f| f << text.to_s } end # def generate_support_files FileUtils.mkdir_p(output) index = render(template('index1')) #base = base.strip.chomp('</html>').strip.chomp('</body>').strip.chomp('</div>') #base = base + html #base = base + "</div>\n</body>\n</html>" write(File.join(output, 'webri.html'), index) #write(File.join(output, 'header.html'), page_header) #write(File.join(output, 'tree.html'), page_tree) #write(File.join(output, 'main.html'), page_main) # copy assets #dir = File.join(directory, 'assets') #FileUtils.cp_r(dir, output) end # def current_content @current_content end # def asset(name) @assets[name] ||= File.read(File.join(directory, 'assets', name)) end # def css - asset('css/style.css') + asset('css/style1.css') end # def jquery - asset('js/jquery.js') + '' # asset('js/jquery.js') end # def rijquery - asset('js/ri.jquery.js') + '' #asset('js/ri.jquery.js') end -=begin - # = Generator Heirarchy - # - class Heirarchy - attr :name - attr :parent - attr :subspaces - attr :instance_methods - attr :class_methods - - def initialize(name, parent=nil) - @name = name - @parent = parent if NS===parent - @subspaces = {} - @class_methods = [] - @instance_methods = [] - end - - def key - full_name - end - - def [](name) - @subspaces[name] - end - - def []=(name, value) - @subspaces[name] = value - end - - def root? - !parent - end - - def full_name - if root? - nil - else - [parent.full_name, name].compact.join("::") - end - end - - def file_name - file = full_name - file = file.gsub('::', '--') - file = file.gsub('.' , '--') - file = file.gsub('#' , '-') - #file = File.join(output, file + '.html') - filestyle="display: hidden;" - end - - - def esc(text) - OpEsc.escape(text.to_s) - end - - def inspect - "<#{self.class} #{name}>" - end - - end #class NS -=end - end #class Generator end #module WebRI diff --git a/lib/webri/heirarchy.rb b/lib/webri/heirarchy.rb index a08770d..be9b1b4 100644 --- a/lib/webri/heirarchy.rb +++ b/lib/webri/heirarchy.rb @@ -1,196 +1,199 @@ module WebRI # def self.entry_to_path(entry) path = entry.to_s path = path.gsub('::', '/') path = path.gsub('#' , '/i-') path = path.gsub('.' , '/c-') path = OpEsc.escape(path) path = path + '.html' end # def self.path_to_entry(path) entry = path.to_s entry = entry.chomp('.html') entry = OpEsc.unescape(entry) entry = entry.gsub('/c-' , '.') entry = entry.gsub('/i-' , '#') entry = entry.gsub('/' , '::') end # = Heirarchy # class Heirarchy attr :name attr :parent attr :subspaces attr :instance_methods attr :class_methods def initialize(name, parent=nil) @name = name @parent = parent if Heirarchy===parent @subspaces = {} @class_methods = [] @instance_methods = [] end def key full_name end def [](name) @subspaces[name] end def []=(name, value) @subspaces[name] = value end def root? !parent end def full_name if root? nil else [parent.full_name, name].compact.join("::") end end # Path name for a given class, module or method. # def file_name # file = full_name # file = file.gsub('::', '/') # file = file.gsub('#' , '/') # file = file.gsub('.' , '-') # #file = File.join(output, file + '.html') # file WebRI.entry_to_path(full_name) end + # + def inspect + "<#{self.class} #{name}>" + end + +=begin # generate html tree # def to_html markup = [] if root? markup << %[<div class="root">] else path = WebRI.entry_to_path(full_name) markup << %[ <li class="trigger"> <img src="assets/img/class.png" onClick="showBranch(this);"/> <span class="link" onClick="lookup_static(this, '#{path}');">#{name}</span> ] markup << %[<div class="branch">] end markup << %[<ul>] cmethods = class_methods.map{ |x| x.to_s }.sort cmethods.each do |method| path = WebRI.entry_to_path(full_name + ".#{method}") markup << %[ - <li class="meta_leaf"> + <li class="meta_leaf"> <span class="link" onClick="lookup_static(this, '#{path}');">#{method}</span> </li> ] end imethods = instance_methods.map{ |x| x.to_s }.sort imethods.each do |method| path = WebRI.entry_to_path(full_name + "##{method}") markup << %[ - <li class="leaf"> + <li class="leaf"> <span class="link" onClick="lookup_static(this, '#{path}');">#{method}</span> </li> ] end subspaces.to_a.sort{ |a,b| a[0].to_s <=> b[0].to_s }.each do |(name, subspace)| #subspaces.each do |name, subspace| markup << subspace.to_html end markup << %[</ul>] if root? markup << %[</div>] else markup << %[</div>] markup << %[</li>] end return markup.join("\n") end # alias_method :to_html_static, :to_html +=end =begin # generate dynamic html tree # def to_html markup = [] if root? markup << %[<div class="root">] else markup << %[ <li class="trigger"> <img src="img/dir.gif" onClick="showBranch(this);"/> <span class="link" onClick="lookup(this, '#{full_name}');">#{name}</span> ] markup << %[<div class="branch">] end markup << %[<ul>] class_methods.each do |method| markup << %[ - <li class="meta_leaf"> + <li class="meta_leaf"> <span class="link" onClick="lookup(this, '#{full_name}.#{method}');">#{method}</span> </li> ] end instance_methods.each do |method| markup << %[ - <li class="leaf"> + <li class="leaf"> <span class="link" onClick="lookup(this, '#{full_name}-#{method}');">#{method}</span> </li> ] end subspaces.to_a.sort{ |a,b| a[0].to_s <=> b[0].to_s }.each do |(name, subspace)| #subspaces.each do |name, subspace| markup << subspace.to_html end markup << %[</ul>] if root? markup << %[</div>] else markup << %[</div>] markup << %[</li>] end return markup.join("\n") end =end # #def esc(text) # OpEsc.escape(text.to_s) # #CGI.escape(text.to_s).gsub('-','%2D') #end - def inspect - "<#{self.class} #{name}>" - end - end #class Heirarchy end #module WebRI diff --git a/lib/webri/server.rb b/lib/webri/server.rb index 6282744..39a809d 100644 --- a/lib/webri/server.rb +++ b/lib/webri/server.rb @@ -1,292 +1,352 @@ require 'erb' require 'yaml' require 'cgi' require 'webri/opesc' require 'webri/heirarchy' module WebRI # Server class and base class for Generator. # class Server # Reference to CGI Service #attr :cgi # Reference to RI Service attr :service # Directory in which to store generated html files #attr :output # Title of docs to add to webpage header. attr :title # def initialize(service, options={}) #@cgi = {} #CGI.new('html4') @service = service @templates = {} @title = options[:title] end + # Tile of documentation as given by commandline option + # or a the namespace of the root entry of the heirarchy. + def title + @title ||= heirarchy.full_name + end + # def directory @directory ||= File.dirname(__FILE__) end # def heirarchy @heirarchy ||=( ns = Heirarchy.new(nil) service.names.each do |m| if m.index('#') type = :instance space, method = m.split('#') spaces = space.split('::').collect{|s| s.to_sym } method = method.to_sym elsif m.index('::') type = :class spaces = m.split('::').collect{|s| s.to_sym } if spaces.last.to_s =~ /^[a-z]/ method = spaces.pop else next # what to do about class/module ? end else next # what to do abot class/module ? end memo = ns spaces.each do |space| memo[space] ||= Heirarchy.new(space, memo) memo = memo[space] end if type == :class memo.class_methods << method else memo.instance_methods << method end end ns ) end # def tree #%[<iframe src="tree.html"></iframe>] - @tree ||= heirarchy.to_html + @tree ||= generate_tree(heirarchy) #heirarchy.to_html + end + + # generate html tree + # + def generate_tree(entry) + markup = [] + if entry.root? + markup << %[<div class="root">] + else + path = WebRI.entry_to_path(entry.full_name) + markup << %[ + <li class="trigger"> + <img src="assets/img/class.png" onClick="showBranch(this);"/> + <span class="link" onClick="lookup_static(this, '#{path}');">#{entry.name}</span> + ] + markup << %[<div class="branch">] + end + + markup << %[<ul>] + + cmethods = entry.class_methods.map{ |x| x.to_s }.sort + cmethods.each do |method| + path = WebRI.entry_to_path(entry.full_name + ".#{method}") + markup << %[ + <li class="meta_leaf"> + <span class="link" onClick="lookup_static(this, '#{path}');">#{method}</span> + </li> + ] + end + + imethods = entry.instance_methods.map{ |x| x.to_s }.sort + imethods.each do |method| + path = WebRI.entry_to_path(entry.full_name + "##{method}") + markup << %[ + <li class="leaf"> + <span class="link" onClick="lookup_static(this, '#{path}');">#{method}</span> + </li> + ] + end + + entry.subspaces.to_a.sort{ |a,b| a[0].to_s <=> b[0].to_s }.each do |(name, subspace)| + #subspaces.each do |name, subspace| + markup << generate_tree(subspace) #subspace.to_html + end + markup << %[</ul>] + + if entry.root? + markup << %[</div>] + else + markup << %[</div>] + markup << %[</li>] + end + + return markup.join("\n") end # def lookup(path) entry = WebRI.path_to_entry(path) if entry html = service.info(entry) html = autolink(html, entry) #term = AnsiSys::Terminal.new.echo(ansi) #html = term.render(:html) #=> HTML fragment #html = ERB::Util.html_escape(html) html = "#{html}<br/><br/>" else html = "<h1>ERROR</h1>" end return html end - # Search for certain pattersn within the HTML and subs in hyperlinks. + # Search for certain patterns within the HTML and subs in hyperlinks. # # Eg. # # <h2>Instance methods:</h2> # current_content, directory, generate, generate_recurse, generate_tree # def autolink(html, entry) link = entry.gsub('::','/') re = Regexp.new(Regexp.escape(entry), Regexp::MULTILINE) if md = re.match(html) title = %[<a class="link title" href="javascript: lookup_static(this, '#{link}.html');">#{md[0]}</a>] html[md.begin(0)...md.end(0)] = title end # class methods re = Regexp.new(Regexp.escape("<h2>Class methods:</h2>") + "(.*?)" + Regexp.escape("<"), Regexp::MULTILINE) if md = re.match(html) meths = md[1].split(",").map{|m| m.strip} meths = meths.map{|m| %[<a class="link" href="javascript: lookup_static(this, '#{link}/c-#{m}.html');">#{m}</a>] } html[md.begin(1)...md.end(1)] = meths.join(", ") end # instance methods re = Regexp.new(Regexp.escape("<h2>Instance methods:</h2>") + "(.*?)" + Regexp.escape("<"), Regexp::MULTILINE) if md = re.match(html) meths = md[1].split(",").map{|m| m.strip} meths = meths.map{|m| %[<a class="link" href="javascript: lookup_static(this, '#{link}/i-#{m}.html');">#{m}</a>] } html[md.begin(1)...md.end(1)] = meths.join(", ") end return html end # def template(name) @templates[name] ||= File.read(File.join(directory, 'templates', name + '.html')) end # #def to_html # #filetext = File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) # template = ERB.new(template_source) # template.result(binding) # #heirarchy.to_html #end # def render(source) template = ERB.new(source) template.result(binding) end # #def page_header # render(template('header')) #end # #def page_tree # render(template('tree')) #end # def index render(template('index')) end # #def page_main # render(template('main')) #end =begin # generate webpages def generate(output=".") @output = File.expand_path(output) # traverse the the hierarchy generate_support_files #generate_recurse(heirarchy) # heirarchy.class_methods.each do |name| # p name # end # heirarchy.instance_methods.each do |name| # p name # end heirarchy.subspaces.each do |name, entry| #p name, entry generate_recurse(entry) end end # def generate_recurse(entry) keyword = entry.full_name if keyword puts keyword @current_content = service.info(keyword) #lookup(keyword) else keyword = '' @current_content = "Welcome" end file = entry.file_name + '.html' file = File.join(output, file) #file = keyword #file = file.gsub('::', '--') #file = file.gsub('.' , '--') #file = file.gsub('#' , '-') #file = File.join(output, file + '.html') write(file, service.info(keyword)) #File.open(file, 'w') { |f| f << service.info(keyword) } #to_html } entry.class_methods.each do |name| mname = "#{entry.full_name}.#{name}" mfile = File.join(output, "#{entry.file_name}--#{esc(name)}.html") write(mfile, service.info(mname)) #File.open(mfile, 'w') { |f| f << service.info(mname) } #to_html } end entry.instance_methods.each do |name| mname = "#{entry.full_name}.#{name}" mfile = File.join(output, "#{entry.file_name}-#{esc(name)}.html") write(mfile, service.info(mname)) #File.open(mfile, 'w') { |f| f << service.info(mname) } #to_html } end entry.subspaces.each do |child_name, child_entry| next if child_entry == entry @directory_depth += 1 generate_recurse(child_entry) @directory_depth -= 1 end end # def write(file, text) puts mfile File.open(file, 'w') { |f| f << text.to_s } end # def generate_support_files FileUtils.mkdir_p(output) # generate index file file = File.join(output, 'index.html') File.open(file, 'w') { |f| f << to_html } # copy css file dir = File.join(directory,'public','css') FileUtils.cp_r(dir, output) # copy images dir = File.join(directory,'public','img') FileUtils.cp_r(dir, output) # copy scripts dir = File.join(directory,'public','js') FileUtils.cp_r(dir, output) end =end # def current_content @current_content end # def esc(text) OpEsc.escape(text.to_s) #CGI.escape(text.to_s).gsub('-','%2D') end # def self.esc(text) OpEsc.escape(text.to_s) #CGI.escape(text.to_s).gsub('-','%2D') end end #class Engine end #module WebRI diff --git a/lib/webri/templates/index1.html b/lib/webri/templates/index1.html index cd45bf0..ff8bd69 100644 --- a/lib/webri/templates/index1.html +++ b/lib/webri/templates/index1.html @@ -1,76 +1,53 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>WebRI</title> - -<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" /> - -<link rel="icon" href="assets/img/ruby_logo.png" type="image/x-icon"> +<meta http-equiv="content-type" content="text/html; charset=UTF-8" /> +<link rel="icon" href="http://www.ruby-lang.org/favicon.ico" type="image/x-icon"> <link href="assets/css/style.css" rel="stylesheet" type="text/css"> -<SCRIPT src="assets/js/jquery.js" type="text/javascript"></SCRIPT> -<SCRIPT src="assets/js/ri.jquery.js" type="text/javascript"></SCRIPT> - -<style> -<%= css %> -</style> - -<script> -<%= jquery %> -</script> - -<script> -<%= rijquery %> -</script> +<style> +<%= css %> +</style> -<script type="text/javascript"> -$(document).ready(function(){ - //$("#screenFrame").css('height', $(window).height() + 'px'); - resizePage(); -}); +<script> + function lookup_static(elem, path){ + window.location.hash = path; + } </script> </head> + <body> <div id="screen"> - <div id="header"> - <div class="small ad"> - </div> - <div> - <img src="assets/img/ruby_logo.png" align="left"/> - <h1>WebRI <span class="small">&copy; 2008 <a href="http://tigerops.org">TigerOps</a></span></h1> - <h2><%= title %></h2> - </div> - </div> - - <div style="clear: both;"></div> - <div id="tree"> <%= tree %> </div> - <div id="main"> - - <div class="slot"> - <h1>Welcome to WebRI</h1> - <h2>Webrick-based RI Browser</h2> + <div style="clear: both;"></div> + + <div id="main"> - <p> - WebRI provides a web-based interface - to RI documentation. - </p> + <div id="header"> + <div class="small ad"> + </div> + <div> + <img src="assets/img/ruby_logo.png" align="left"/> + <h1><%= title %></h1> + <h2>WebRI <span class="small">&copy; 2008 <a href="http://tigerops.org">PsyTech</a></span></h1> + </div> + </div> - <p> - WebRI &copy; 2008 <a href="http://tigerops.org">TigerOps</a> - </p> - <div> - <%= html %> + + <div class="slot"> + <p>Built by WebRI &copy; 2008 <a href="http://tigerops.org">PsyTech</a></p> + <div> </div> </div> </body> </html>
razerbeans/webri
d45b84916ba4b4ae36add919b2047df784885e13
started work on onepage output mode
diff --git a/lib/webri/generator1.rb b/lib/webri/generator1.rb new file mode 100644 index 0000000..f74d362 --- /dev/null +++ b/lib/webri/generator1.rb @@ -0,0 +1,270 @@ +require 'webri/server' + +module WebRI + + # This is the static website generator which creates + # a single page. + # + class GeneratorOne < Server + + # Reference to CGI Service + #attr :cgi + + # Reference to RI Service + #attr :service + + # Dir in which to store generated html + attr :output + + # + attr :html + + # + def initialize(service, options={}) + super(service, options) + + @html = "" + + #@cgi = {} #CGI.new('html4') + #@service = service + @directory_depth = 0 + end + + # + def tree + #%[<iframe src="tree.html"></iframe>] + @tree ||= heirarchy.to_html_static + end + +=begin + # + def lookup(req) + keyw = File.basename(req.path_info) + if keyw + keyw.sub!('-','#') + html = service.info(keyw) +#puts html + #term = AnsiSys::Terminal.new.echo(ansi) + #html = term.render(:html) #=> HTML fragment + #html = ERB::Util.html_escape(html) + html = "#{html}" + else + html = "<h1>ERROR</h1>" + end + return html + end +=end + + #def template_source + # @template_source ||= File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) + #end + + # + #def to_html + # #filetext = File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) + # template = ERB.new(template_source) + # template.result(binding) + # #heirarchy.to_html + #end + + # generate webpages + def generate(output=".") + @output = File.expand_path(output) + @assets = {} + # traverse the the hierarchy + + #generate_recurse(heirarchy) + +# heirarchy.class_methods.each do |name| +# p name +# end + +# heirarchy.instance_methods.each do |name| +# p name +# end + + heirarchy.subspaces.each do |name, entry| + #p name, entry + generate_recurse(entry) + end + + generate_support_files + end + + # + def generate_recurse(entry) + keyword = entry.full_name + + if keyword + puts keyword + @current_content = service.info(keyword) #lookup(keyword) + else + keyword = '' + @current_content = "Welcome" + end + + file = entry.file_name + #file = File.join(output, file) + + #file = keyword + #file = file.gsub('::', '--') + #file = file.gsub('.' , '--') + #file = file.gsub('#' , '-') + #file = File.join(output, file + '.html') + + html << %[\n<div id="#{file}" class="slot module" style="display: none;">\n] + html << service.info(keyword) + html << %[\n</div>\n] + + cmethods = entry.class_methods.map{ |x| x.to_s }.sort + cmethods.each do |name| + mname = "#{entry.full_name}.#{name}" + mfile = WebRI.entry_to_path(mname) + #mfile = File.join(output, mfile) + #mfile = File.join(output, "#{entry.file_name}/c-#{esc(name)}.html") + html << %[\n<div id="#{mfile}" class="slot cmethod" style="display: none;">\n] + html << service.info(mname) + html << %[\n</div>\n] + #write(mfile, service.info(mname)) + end + + imethods = entry.instance_methods.map{ |x| x.to_s }.sort + imethods.each do |name| + mname = "#{entry.full_name}##{name}" + mfile = WebRI.entry_to_path(mname) + #mfile = File.join(output, mfile) + #mfile = File.join(output, "#{entry.file_name}/i-#{esc(name)}.html") + html << %[\n<div id="#{mfile}" class="slot imethod" style="display: none;">\n] + html << service.info(mname) + html << %[\n</div>\n] + #write(mfile, service.info(mname)) + end + + entry.subspaces.each do |child_name, child_entry| + next if child_entry == entry + @directory_depth += 1 + generate_recurse(child_entry) + @directory_depth -= 1 + end + end + + # + def write(file, text) + puts file + FileUtils.mkdir_p(File.dirname(file)) + File.open(file, 'w') { |f| f << text.to_s } + end + + # + def generate_support_files + FileUtils.mkdir_p(output) + + index = render(template('index1')) + + #base = base.strip.chomp('</html>').strip.chomp('</body>').strip.chomp('</div>') + #base = base + html + #base = base + "</div>\n</body>\n</html>" + + write(File.join(output, 'webri.html'), index) + + #write(File.join(output, 'header.html'), page_header) + #write(File.join(output, 'tree.html'), page_tree) + #write(File.join(output, 'main.html'), page_main) + + # copy assets + #dir = File.join(directory, 'assets') + #FileUtils.cp_r(dir, output) + end + + # + def current_content + @current_content + end + + # + def asset(name) + @assets[name] ||= File.read(File.join(directory, 'assets', name)) + end + + # + def css + asset('css/style.css') + end + + # + def jquery + asset('js/jquery.js') + end + + # + def rijquery + asset('js/ri.jquery.js') + end + +=begin + # = Generator Heirarchy + # + class Heirarchy + attr :name + attr :parent + attr :subspaces + attr :instance_methods + attr :class_methods + + def initialize(name, parent=nil) + @name = name + @parent = parent if NS===parent + @subspaces = {} + @class_methods = [] + @instance_methods = [] + end + + def key + full_name + end + + def [](name) + @subspaces[name] + end + + def []=(name, value) + @subspaces[name] = value + end + + def root? + !parent + end + + def full_name + if root? + nil + else + [parent.full_name, name].compact.join("::") + end + end + + def file_name + file = full_name + file = file.gsub('::', '--') + file = file.gsub('.' , '--') + file = file.gsub('#' , '-') + #file = File.join(output, file + '.html') + filestyle="display: hidden;" + end + + + def esc(text) + OpEsc.escape(text.to_s) + end + + def inspect + "<#{self.class} #{name}>" + end + + end #class NS +=end + + end #class Generator + +end #module WebRI + diff --git a/lib/webri/templates/index1.html b/lib/webri/templates/index1.html new file mode 100644 index 0000000..cd45bf0 --- /dev/null +++ b/lib/webri/templates/index1.html @@ -0,0 +1,76 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html> + +<head> +<title>WebRI</title> + +<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" /> + +<link rel="icon" href="assets/img/ruby_logo.png" type="image/x-icon"> + +<link href="assets/css/style.css" rel="stylesheet" type="text/css"> + +<SCRIPT src="assets/js/jquery.js" type="text/javascript"></SCRIPT> +<SCRIPT src="assets/js/ri.jquery.js" type="text/javascript"></SCRIPT> + +<style> +<%= css %> +</style> + +<script> +<%= jquery %> +</script> + +<script> +<%= rijquery %> +</script> + +<script type="text/javascript"> +$(document).ready(function(){ + //$("#screenFrame").css('height', $(window).height() + 'px'); + resizePage(); +}); +</script> +</head> +<body> +<div id="screen"> + + <div id="header"> + <div class="small ad"> + </div> + <div> + <img src="assets/img/ruby_logo.png" align="left"/> + <h1>WebRI <span class="small">&copy; 2008 <a href="http://tigerops.org">TigerOps</a></span></h1> + <h2><%= title %></h2> + </div> + </div> + + <div style="clear: both;"></div> + + <div id="tree"> + <%= tree %> + </div> + + <div id="main"> + + <div class="slot"> + <h1>Welcome to WebRI</h1> + <h2>Webrick-based RI Browser</h2> + + <p> + WebRI provides a web-based interface + to RI documentation. + </p> + + <p> + WebRI &copy; 2008 <a href="http://tigerops.org">TigerOps</a> + </p> + <div> + + <%= html %> + </div> + +</div> +</body> +</html> +
razerbeans/webri
7c67cf3c9fe36cd601caf17f20c2bb61b8e8670f
added --ruby option
diff --git a/bin/webri b/bin/webri index b880645..ec1a606 100755 --- a/bin/webri +++ b/bin/webri @@ -1,135 +1,151 @@ #!/usr/bin/env ruby # == Synopsis # # webri: Serve ri documentation via the Web # # == Usage # # webri [OPTIONS] ... [RI_DIR] # # OPTIONS: # # -h, --help # show help # # -o, --output OUTPUT_DIR # ouput static files to OUTPUT_DIR # # RI_DIR: # # The directory in which to find the ri files generate by RDoc. #require 'rdoc/usage' require 'optparse' options = {} OptionParser.new do |opts| opts.banner = "Usage: webri [options] [ri-dir]" opts.on("-o", "--output DIR", "Output static files to this directory.") do |v| options[:output] = v end + opts.on("-1", "--onepage", "Generate a single page document.") do |v| + options[:onepage] = true + end + opts.on("-t", "--title TITLE", "Title to use on webpages.") do |v| options[:title] = v end opts.separator "" - opts.separator "Location options (only apply is no ri-dir is given):" + opts.separator "Location options (only apply if no ri-dir is given):" opts.on("--[no-]system", "Include documentation from Ruby's standard library.") do |v| options[:system] = v end opts.on("--[no-]site", "Include documentation from libraries installed in site locations.") do |v| options[:site] = v end opts.on("--[no-]gems", "Include documentation from Ruby's standard library.") do |v| options[:gems] = v end opts.on("--[no-]home", "Include documentation stored in ~/.rdoc. Defaults to true.") do |v| options[:home] = v end + opts.on("--ruby", "Same as --system --no-site --no-gems --no-home.") do |v| + options[:system] = true + options[:site] = false + options[:gems] = false + options[:home] = false + end + opts.separator "" opts.separator "Common options:" opts.on_tail("-h", "--help", "Show this message") do puts opts exit end end.parse! #if ARGV.length != 1 # puts "Missing ri directory argument (try --help)" # exit 0 #end options[:library] = ARGV.shift # --- --- require 'webri/ri_service' service = WebRI::RiService.new(options) if output = options[:output] - # generate static pages - - require 'webri/generator' - - wri = WebRI::Generator.new(service, :title=>options[:title]) - wri.generate(output) + if options[:onepage] + # generate static pages + require 'webri/generator1' + wri = WebRI::GeneratorOne.new(service, :title=>options[:title]) + wri.generate(output) + else + # generate static pages + require 'webri/generator' + wri = WebRI::Generator.new(service, :title=>options[:title]) + wri.generate(output) + end else # serve dynamically via WEBrick require 'webri/server' wri = WebRI::Server.new(service, :title=>options[:title]) #puts wri.to_html require 'webrick' include WEBrick p wri.directory + "/public" s = HTTPServer.new( :Port => 8888, :DocumentRoot => wri.directory + "/public" ) s.mount_proc("/"){ |req, res| path = req.path_info.sub(/^\//,'') if path == '' res.body = wri.index res['Content-Type'] = "text/html" else res.body = wri.lookup(path) res['Content-Type'] = "text/html" end } # s.mount_proc("/ri"){|req, res| # #key = File.basename(req.path_info) # #p key # res.body = wri.lookup(req) # res['Content-Type'] = "text/html" # } ## mount subdirectories s.mount("/assets", HTTPServlet::FileHandler, wri.directory + "/assets") #s.mount("/css", HTTPServlet::FileHandler, wri.directory + "/assets/css") #s.mount("/img", HTTPServlet::FileHandler, wri.directory + "/assets/img") trap("INT"){ s.shutdown } s.start end diff --git a/lib/webri/ri_service.rb b/lib/webri/ri_service.rb index 065d47d..4759df7 100644 --- a/lib/webri/ri_service.rb +++ b/lib/webri/ri_service.rb @@ -1,84 +1,86 @@ require 'uri' module WebRI class RiService # Directory of ri doc files. attr_accessor :library attr_accessor :system attr_accessor :site attr_accessor :gems attr_accessor :home + attr_accessor :ruby + # def initialize(options) options.each do |k,v| send("#{k}=", v) if respond_to?("#{k}=") end end # def info(keyword) #puts "KEYWORD: #{keyword.inspect}" html = `ri #{ri_opts} -f html #{keyword}` return "<br/>#{html}<br/><br/>" end # def names @names ||= (library ? names_from_library : names_from_all) end # def names_from_library(lib=nil) files = nil Dir.chdir(lib || library) do files = Dir['**/*'] files = files.map do |f| case f when /\-i.yaml$/ (File.dirname(f) + '#' + URI.unescape(File.basename(f).chomp('-i.yaml'))).gsub('/' , '::') when /\-c.yaml$/ (File.dirname(f) + '::' + URI.unescape(File.basename(f).chomp('-c.yaml'))).gsub('/' , '::') else #f.sub(/^cdesc-/,'').gsub('/' , '::') nil end end.compact end files end # def names_from_all libraries = `ri #{ri_opts} -l`.split("\n") libraries.map do |lib| names_from_library(lib) end.flatten end private # def ri_opts cmd = [] if library cmd << %[-d "#{library}" --no-standard-docs] else cmd << ( system ? "--system" : "--no-system" ) cmd << ( site ? "--site" : "--no-site" ) cmd << ( gems ? "--gems" : "--no-gems" ) cmd << ( home ? "--home" : "--no-home" ) end cmd.join(' ') end end end
razerbeans/webri
cddb8fa8e1a5511bfeaca185849f59c1be3a4bdd
renamed reap to syckle
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..377f3ca --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +MANIFEST +.cache +log +pack +doc/rdoc +doc/ri +doc/webri diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..ca8c036 --- /dev/null +++ b/COPYING @@ -0,0 +1,349 @@ + + WebRI + + Copyright (c) 2008 TigerOps + + + THE RUBY LICENSE + (http://www.ruby-lang.org/en/LICENSE.txt) + + You may redistribute this software and/or modify it under either the terms of + the GPL (see below), or the conditions below: + + 1. You may make and give away verbatim copies of the source form of the + software without restriction, provided that you duplicate all of the + original copyright notices and associated disclaimers. + + 2. You may modify your copy of the software in any way, provided that + you do at least ONE of the following: + + a) place your modifications in the Public Domain or otherwise + make them Freely Available, such as by posting said + modifications to Usenet or an equivalent medium, or by allowing + the author to include your modifications in the software. + + b) use the modified software only within your corporation or + organization. + + c) rename any non-standard executables so the names do not conflict + with standard executables, which must also be provided. + + d) make other distribution arrangements with the author. + + 3. You may distribute the software in object code or executable + form, provided that you do at least ONE of the following: + + a) distribute the executables and library files of the software, + together with instructions (in the manual page or equivalent) + on where to get the original distribution. + + b) accompany the distribution with the machine-readable source of + the software. + + c) give non-standard executables non-standard names, with + instructions on where to get the original software distribution. + + d) make other distribution arrangements with the author. + + 4. You may modify and include the part of the software into any other + software (possibly commercial). But some files in the distribution + are not written by the author, so that they are not under these terms. + + For the list of those files and their copying conditions, see the + file LEGAL. + + 5. The scripts and library files supplied as input to or produced as + output from the software do not automatically fall under the + copyright of the software, but belong to whomever generated them, + and may be sold commercially, and may be aggregated with this + software. + + 6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE. + + ---------------------------------------------------------------------------- + + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your + freedom to share and change it. By contrast, the GNU General Public + License is intended to guarantee your freedom to share and change free + software--to make sure the software is free for all its users. This + General Public License applies to most of the Free Software + Foundation's software and to any other program whose authors commit to + using it. (Some other Free Software Foundation software is covered by + the GNU Library General Public License instead.) You can apply it to + your programs, too. + + When we speak of free software, we are referring to freedom, not + price. Our General Public Licenses are designed to make sure that you + have the freedom to distribute copies of free software (and charge for + this service if you wish), that you receive source code or can get it + if you want it, that you can change the software or use pieces of it + in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid + anyone to deny you these rights or to ask you to surrender the rights. + These restrictions translate to certain responsibilities for you if you + distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether + gratis or for a fee, you must give the recipients all the rights that + you have. You must make sure that they, too, receive or can get the + source code. And you must show them these terms so they know their + rights. + + We protect your rights with two steps: (1) copyright the software, and + (2) offer you this license which gives you legal permission to copy, + distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain + that everyone understands that there is no warranty for this free + software. If the software is modified by someone else and passed on, we + want its recipients to know that what they have is not the original, so + that any problems introduced by others will not reflect on the original + authors' reputations. + + Finally, any free program is threatened constantly by software + patents. We wish to avoid the danger that redistributors of a free + program will individually obtain patent licenses, in effect making the + program proprietary. To prevent this, we have made it clear that any + patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and + modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains + a notice placed by the copyright holder saying it may be distributed + under the terms of this General Public License. The "Program", below, + refers to any such program or work, and a "work based on the Program" + means either the Program or any derivative work under copyright law: + that is to say, a work containing the Program or a portion of it, + either verbatim or with modifications and/or translated into another + language. (Hereinafter, translation is included without limitation in + the term "modification".) Each licensee is addressed as "you". + + Activities other than copying, distribution and modification are not + covered by this License; they are outside its scope. The act of + running the Program is not restricted, and the output from the Program + is covered only if its contents constitute a work based on the + Program (independent of having been made by running the Program). + Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's + source code as you receive it, in any medium, provided that you + conspicuously and appropriately publish on each copy an appropriate + copyright notice and disclaimer of warranty; keep intact all the + notices that refer to this License and to the absence of any warranty; + and give any other recipients of the Program a copy of this License + along with the Program. + + You may charge a fee for the physical act of transferring a copy, and + you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion + of it, thus forming a work based on the Program, and copy and + distribute such modifications or work under the terms of Section 1 + above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + + These requirements apply to the modified work as a whole. If + identifiable sections of that work are not derived from the Program, + and can be reasonably considered independent and separate works in + themselves, then this License, and its terms, do not apply to those + sections when you distribute them as separate works. But when you + distribute the same sections as part of a whole which is a work based + on the Program, the distribution of the whole must be on the terms of + this License, whose permissions for other licensees extend to the + entire whole, and thus to each and every part regardless of who wrote it. + + Thus, it is not the intent of this section to claim rights or contest + your rights to work written entirely by you; rather, the intent is to + exercise the right to control the distribution of derivative or + collective works based on the Program. + + In addition, mere aggregation of another work not based on the Program + with the Program (or with a work based on the Program) on a volume of + a storage or distribution medium does not bring the other work under + the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, + under Section 2) in object code or executable form under the terms of + Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + + The source code for a work means the preferred form of the work for + making modifications to it. For an executable work, complete source + code means all the source code for all modules it contains, plus any + associated interface definition files, plus the scripts used to + control compilation and installation of the executable. However, as a + special exception, the source code distributed need not include + anything that is normally distributed (in either source or binary + form) with the major components (compiler, kernel, and so on) of the + operating system on which the executable runs, unless that component + itself accompanies the executable. + + If distribution of executable or object code is made by offering + access to copy from a designated place, then offering equivalent + access to copy the source code from the same place counts as + distribution of the source code, even though third parties are not + compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program + except as expressly provided under this License. Any attempt + otherwise to copy, modify, sublicense or distribute the Program is + void, and will automatically terminate your rights under this License. + However, parties who have received copies, or rights, from you under + this License will not have their licenses terminated so long as such + parties remain in full compliance. + + 5. You are not required to accept this License, since you have not + signed it. However, nothing else grants you permission to modify or + distribute the Program or its derivative works. These actions are + prohibited by law if you do not accept this License. Therefore, by + modifying or distributing the Program (or any work based on the + Program), you indicate your acceptance of this License to do so, and + all its terms and conditions for copying, distributing or modifying + the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the + Program), the recipient automatically receives a license from the + original licensor to copy, distribute or modify the Program subject to + these terms and conditions. You may not impose any further + restrictions on the recipients' exercise of the rights granted herein. + You are not responsible for enforcing compliance by third parties to + this License. + + 7. If, as a consequence of a court judgment or allegation of patent + infringement or for any other reason (not limited to patent issues), + conditions are imposed on you (whether by court order, agreement or + otherwise) that contradict the conditions of this License, they do not + excuse you from the conditions of this License. If you cannot + distribute so as to satisfy simultaneously your obligations under this + License and any other pertinent obligations, then as a consequence you + may not distribute the Program at all. For example, if a patent + license would not permit royalty-free redistribution of the Program by + all those who receive copies directly or indirectly through you, then + the only way you could satisfy both it and this License would be to + refrain entirely from distribution of the Program. + + If any portion of this section is held invalid or unenforceable under + any particular circumstance, the balance of the section is intended to + apply and the section as a whole is intended to apply in other + circumstances. + + It is not the purpose of this section to induce you to infringe any + patents or other property right claims or to contest validity of any + such claims; this section has the sole purpose of protecting the + integrity of the free software distribution system, which is + implemented by public license practices. Many people have made + generous contributions to the wide range of software distributed + through that system in reliance on consistent application of that + system; it is up to the author/donor to decide if he or she is willing + to distribute software through any other system and a licensee cannot + impose that choice. + + This section is intended to make thoroughly clear what is believed to + be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in + certain countries either by patents or by copyrighted interfaces, the + original copyright holder who places the Program under this License + may add an explicit geographical distribution limitation excluding + those countries, so that distribution is permitted only in or among + countries not thus excluded. In such case, this License incorporates + the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions + of the General Public License from time to time. Such new versions will + be similar in spirit to the present version, but may differ in detail to + address new problems or concerns. + + Each version is given a distinguishing version number. If the Program + specifies a version number of this License which applies to it and "any + later version", you have the option of following the terms and conditions + either of that version or of any later version published by the Free + Software Foundation. If the Program does not specify a version number of + this License, you may choose any version ever published by the Free Software + Foundation. + + 10. If you wish to incorporate parts of the Program into other free + programs whose distribution conditions are different, write to the author + to ask for permission. For software which is copyrighted by the Free + Software Foundation, write to the Free Software Foundation; we sometimes + make exceptions for this. Our decision will be guided by the two goals + of preserving the free status of all derivatives of our free software and + of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY + FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN + OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES + PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED + OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS + TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE + PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, + REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING + WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR + REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, + INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING + OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED + TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY + YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER + PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE + POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + diff --git a/HISTORY b/HISTORY new file mode 100644 index 0000000..734fb5d --- /dev/null +++ b/HISTORY @@ -0,0 +1,75 @@ += Release History + +== 0.6 / 2009-08-24 + +Add autolinking feature to generated HTML. The new code uses Regexps +to locate class or module names and method names and inserts appropriate +hyperlinks for them, allowing one to navigate via the page rather than +solely via the class hierarchy tree. + +Changes: + +* 1 Major Enhancement + + * Inserts appropriate hyperlinks in ri generated HTML. + + +== 0.5.0 / 2009-08-14 + +This release fixes WebRI to work with the latest versions of RDoc 2.0+. +It will no longer work with the older versions. + +Changes: + +* 3 Major Enhancements + + * Updated to work with RDoc 2.3+. It will not work with older versions. + * Support for --system, --site, --gems and --home flags. + * Methods list are now extracted from ri doc files for speed-up. + + +== 0.4.0 / 2009-06-14 + +This release adds a static website generation feature. +Simple specify the --output directory option on the +commandline and the WebRI files will be generated to +that directory. Ex. + + $ cd myproject + $ webri --output doc/webri doc/ri + +Changes: + +* 1 Major Enhancement + + * Added static website generation. + + +== 0.3.0 / 2009-05-30 + +This release simply fixes a bug that prevent class methods +form appearing the class hierarchy. + +Changes: + +* 1 Major Bug Fix + + * Fixed issue that prevented class methods from showing up. + + +== 0.2.0 / 2008-07-06 + +Changes: + +* 2 Major Enhancements + + * Shelling out to RI b/c it's easier than using the RDoc API. + * Not using FastRI b/c no HTML output. + * Initial Release + + +== 0.1.0 / 2008-03-28 + +Changes: + +* Happy Birthday! diff --git a/README b/README new file mode 100644 index 0000000..70192f4 --- /dev/null +++ b/README @@ -0,0 +1,55 @@ += Web RI + + http://webri.rubyforge.org + +Webrick-based RI browser + +== Usage + +WebRI can be used to browse the entire installed object system --eveything +documented in one of the central RI locations. + +WebRI can also be used (and this is probably more useful) to browse per-project +RI documentation. Simply generate the RI docs by navigating to the projects +root directory and running: + + rdoc --ri --op "doc/ri" lib + +Sometimes a package will include a convenience script for generating these. +Try running 'rake -T', or look for a 'script/' or 'task/' executable that does +the job. Usually the generated documentation is placed in either ri/ or doc/ri/. +I will use doc/ri/ in the following example, sicen that is my preference. Adjust +your directory as needed. + +Now run: + + webri doc/ri + +You will see a Webrick server start up, informing you of the port being used. + + [2008-03-28 12:11:16] INFO WEBrick 1.3.1 + [2008-03-28 12:11:16] INFO ruby 1.8.6 (2007-06-07) [x86_64-linux] + [2008-03-28 12:11:21] INFO WEBrick::HTTPServer#start: pid=8870 port=8888 + +In this example we see the port is the default 8888. Simply open your browser and +navigate to: + + http://localhost:8888/ + +On the left side of the screen you will see a navigation tree, and the right side +contans an infromation panel. + +NOTE: Becuase RI itself isn't very fast, if you use WebRI against the entire set +of installed Ruby libraries it can take a few seconds to load up. It would be nice +to use FastRI instead, for speed, but FastRI does not support HTML output as of yet. + +== Install + + gem install webri + +== License + + WebRI, Copyright (c) 2008 Tiger Ops + + WebRi is licensed under then terms of Ruby. + diff --git a/TODO b/TODO new file mode 100644 index 0000000..6a3677b --- /dev/null +++ b/TODO @@ -0,0 +1,23 @@ += WebRI TODO + +== One File + +An idea for a future version... generate all the html into +a single file, then use CSS and JQeury to completely control +presentation. That would be pretty cool, as it would mean +the entire set of documentation is on a single file. + +The only problem with this design is that it would mean +we could not use realtime serving of the docs, like we +can now using Webrik b/c large programs, like Rails and +Ruby itself, take a considerable amount of time to generate, +something like 30 minutes to an hour. + +However, shortcomings aside, this might be a great way to +go. The dynamic server is already a bit slow anyway b/c +ri itself is slow, and in practice I have found that end +up utilizing the generated output in the long run. The +dynamic site I use only for debugging. + +Hmmm... Ok. So how about I add it as an additional option. + diff --git a/bin/webri b/bin/webri new file mode 100755 index 0000000..b880645 --- /dev/null +++ b/bin/webri @@ -0,0 +1,135 @@ +#!/usr/bin/env ruby + +# == Synopsis +# +# webri: Serve ri documentation via the Web +# +# == Usage +# +# webri [OPTIONS] ... [RI_DIR] +# +# OPTIONS: +# +# -h, --help +# show help +# +# -o, --output OUTPUT_DIR +# ouput static files to OUTPUT_DIR +# +# RI_DIR: +# +# The directory in which to find the ri files generate by RDoc. + +#require 'rdoc/usage' +require 'optparse' + +options = {} + +OptionParser.new do |opts| + opts.banner = "Usage: webri [options] [ri-dir]" + + opts.on("-o", "--output DIR", "Output static files to this directory.") do |v| + options[:output] = v + end + + opts.on("-t", "--title TITLE", "Title to use on webpages.") do |v| + options[:title] = v + end + + opts.separator "" + opts.separator "Location options (only apply is no ri-dir is given):" + + opts.on("--[no-]system", "Include documentation from Ruby's standard library.") do |v| + options[:system] = v + end + + opts.on("--[no-]site", "Include documentation from libraries installed in site locations.") do |v| + options[:site] = v + end + + opts.on("--[no-]gems", "Include documentation from Ruby's standard library.") do |v| + options[:gems] = v + end + + opts.on("--[no-]home", "Include documentation stored in ~/.rdoc. Defaults to true.") do |v| + options[:home] = v + end + + opts.separator "" + opts.separator "Common options:" + + opts.on_tail("-h", "--help", "Show this message") do + puts opts + exit + end +end.parse! + +#if ARGV.length != 1 +# puts "Missing ri directory argument (try --help)" +# exit 0 +#end + +options[:library] = ARGV.shift + +# --- --- + +require 'webri/ri_service' + +service = WebRI::RiService.new(options) + +if output = options[:output] + + # generate static pages + + require 'webri/generator' + + wri = WebRI::Generator.new(service, :title=>options[:title]) + wri.generate(output) + +else + + # serve dynamically via WEBrick + + require 'webri/server' + + wri = WebRI::Server.new(service, :title=>options[:title]) + #puts wri.to_html + + require 'webrick' + include WEBrick + + p wri.directory + "/public" + + s = HTTPServer.new( + :Port => 8888, + :DocumentRoot => wri.directory + "/public" + ) + + s.mount_proc("/"){ |req, res| + path = req.path_info.sub(/^\//,'') + if path == '' + res.body = wri.index + res['Content-Type'] = "text/html" + else + res.body = wri.lookup(path) + res['Content-Type'] = "text/html" + end + } + +# s.mount_proc("/ri"){|req, res| +# #key = File.basename(req.path_info) +# #p key +# res.body = wri.lookup(req) +# res['Content-Type'] = "text/html" +# } + + ## mount subdirectories + s.mount("/assets", HTTPServlet::FileHandler, wri.directory + "/assets") + #s.mount("/css", HTTPServlet::FileHandler, wri.directory + "/assets/css") + #s.mount("/img", HTTPServlet::FileHandler, wri.directory + "/assets/img") + + trap("INT"){ s.shutdown } + s.start + +end + diff --git a/lib/webri/assets/css/style.css b/lib/webri/assets/css/style.css new file mode 100644 index 0000000..58da3c8 --- /dev/null +++ b/lib/webri/assets/css/style.css @@ -0,0 +1,59 @@ +html, body { + height:100%; + margin: 0; + padding: 0; + border: none; + text-align: left; + position: relative; +} + +body { + font-family: monospace; + font-size: 12px; + background: #fff; +} + +div { margin: 0; padding: 0; } + +pre { font-family: monospace; } + +p { padding: 5px 0; } + +a { text-decoration: none; } + +/* HEADER */ + +#header { width: 100%; background: white; height: 100px; } +#header h1 { margin: 0; padding: 0; font-size: 64px; } +#header h2 { margin: 0; padding: 0; font-size: 10pt; font-weight: bold; } +#header .small { font-size: 10pt; } + +.small { font-size: 10pt; } + +/* TREE */ + + #tree { padding: 10px; background: white; float: left; width: 250px; overflow: scroll; border: 1px solid #ccc; } + ul { cursor: pointer; cursor: hand; padding-left: 10px; } + li { margin-left: 10px; } + .trigger { cursor: pointer; cursor: hand; } + .branch { display: none; } + .leaf { color: #cc0000; } + .meta_leaf { color: #00cc00; font-weight: bold; } + .title { font-size: 1.8em; } + .link { font-weight: bold; } + .link:hover{ text-decoration: underline; } + +/* MAIN */ + +#main { + margin-left: 260px; + padding: 10px 15px; /* bottom padding for footer */ + border: 1px solid #ccc; + background: white; + overflow: scroll; + font-family: monospace; + font-size: 14px; +} + +.ad { float: right; padding: 20px 20px 0 0; } + diff --git a/lib/webri/assets/img/class.png b/lib/webri/assets/img/class.png new file mode 100644 index 0000000..b68782e Binary files /dev/null and b/lib/webri/assets/img/class.png differ diff --git a/lib/webri/assets/img/dir.gif b/lib/webri/assets/img/dir.gif new file mode 100644 index 0000000..7b37b09 Binary files /dev/null and b/lib/webri/assets/img/dir.gif differ diff --git a/lib/webri/assets/img/mod.ico b/lib/webri/assets/img/mod.ico new file mode 100644 index 0000000..b5c6af4 Binary files /dev/null and b/lib/webri/assets/img/mod.ico differ diff --git a/lib/webri/assets/img/ruby_logo.png b/lib/webri/assets/img/ruby_logo.png new file mode 100644 index 0000000..b2ed643 Binary files /dev/null and b/lib/webri/assets/img/ruby_logo.png differ diff --git a/lib/webri/assets/js/jquery.js b/lib/webri/assets/js/jquery.js new file mode 100644 index 0000000..74cdfee --- /dev/null +++ b/lib/webri/assets/js/jquery.js @@ -0,0 +1,11 @@ +/* + * jQuery 1.2.3 - New Wave Javascript + * + * Copyright (c) 2008 John Resig (jquery.com) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * $Date: 2008-02-06 00:21:25 -0500 (Wed, 06 Feb 2008) $ + * $Rev: 4663 $ + */ +eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(J(){7(1e.3N)L w=1e.3N;L E=1e.3N=J(a,b){K 1B E.2l.4T(a,b)};7(1e.$)L D=1e.$;1e.$=E;L u=/^[^<]*(<(.|\\s)+>)[^>]*$|^#(\\w+)$/;L G=/^.[^:#\\[\\.]*$/;E.1n=E.2l={4T:J(d,b){d=d||T;7(d.15){6[0]=d;6.M=1;K 6}N 7(1o d=="25"){L c=u.2O(d);7(c&&(c[1]||!b)){7(c[1])d=E.4a([c[1]],b);N{L a=T.5J(c[3]);7(a)7(a.2w!=c[3])K E().2s(d);N{6[0]=a;6.M=1;K 6}N d=[]}}N K 1B E(b).2s(d)}N 7(E.1q(d))K 1B E(T)[E.1n.21?"21":"3U"](d);K 6.6E(d.1k==1M&&d||(d.5h||d.M&&d!=1e&&!d.15&&d[0]!=10&&d[0].15)&&E.2I(d)||[d])},5h:"1.2.3",87:J(){K 6.M},M:0,22:J(a){K a==10?E.2I(6):6[a]},2F:J(b){L a=E(b);a.54=6;K a},6E:J(a){6.M=0;1M.2l.1g.1i(6,a);K 6},R:J(a,b){K E.R(6,a,b)},4X:J(b){L a=-1;6.R(J(i){7(6==b)a=i});K a},1J:J(c,a,b){L d=c;7(c.1k==4e)7(a==10)K 6.M&&E[b||"1J"](6[0],c)||10;N{d={};d[c]=a}K 6.R(J(i){Q(c 1p d)E.1J(b?6.W:6,c,E.1l(6,d[c],b,i,c))})},1j:J(b,a){7((b==\'27\'||b==\'1R\')&&2M(a)<0)a=10;K 6.1J(b,a,"2o")},1u:J(b){7(1o b!="3V"&&b!=V)K 6.4x().3t((6[0]&&6[0].2i||T).5r(b));L a="";E.R(b||6,J(){E.R(6.3p,J(){7(6.15!=8)a+=6.15!=1?6.6K:E.1n.1u([6])})});K a},5m:J(b){7(6[0])E(b,6[0].2i).5k().3o(6[0]).2c(J(){L a=6;2b(a.1C)a=a.1C;K a}).3t(6);K 6},8w:J(a){K 6.R(J(){E(6).6z().5m(a)})},8p:J(a){K 6.R(J(){E(6).5m(a)})},3t:J(){K 6.3O(18,P,S,J(a){7(6.15==1)6.38(a)})},6q:J(){K 6.3O(18,P,P,J(a){7(6.15==1)6.3o(a,6.1C)})},6o:J(){K 6.3O(18,S,S,J(a){6.1a.3o(a,6)})},5a:J(){K 6.3O(18,S,P,J(a){6.1a.3o(a,6.2B)})},3h:J(){K 6.54||E([])},2s:J(b){L c=E.2c(6,J(a){K E.2s(b,a)});K 6.2F(/[^+>] [^+>]/.17(b)||b.1f("..")>-1?E.57(c):c)},5k:J(e){L f=6.2c(J(){7(E.14.1d&&!E.3E(6)){L a=6.69(P),4Y=T.3s("1x");4Y.38(a);K E.4a([4Y.3d])[0]}N K 6.69(P)});L d=f.2s("*").4R().R(J(){7(6[F]!=10)6[F]=V});7(e===P)6.2s("*").4R().R(J(i){7(6.15==3)K;L c=E.O(6,"2R");Q(L a 1p c)Q(L b 1p c[a])E.16.1b(d[i],a,c[a][b],c[a][b].O)});K f},1E:J(b){K 6.2F(E.1q(b)&&E.3y(6,J(a,i){K b.1P(a,i)})||E.3e(b,6))},56:J(b){7(b.1k==4e)7(G.17(b))K 6.2F(E.3e(b,6,P));N b=E.3e(b,6);L a=b.M&&b[b.M-1]!==10&&!b.15;K 6.1E(J(){K a?E.33(6,b)<0:6!=b})},1b:J(a){K!a?6:6.2F(E.37(6.22(),a.1k==4e?E(a).22():a.M!=10&&(!a.12||E.12(a,"3u"))?a:[a]))},3H:J(a){K a?E.3e(a,6).M>0:S},7j:J(a){K 6.3H("."+a)},5O:J(b){7(b==10){7(6.M){L c=6[0];7(E.12(c,"2k")){L e=c.3T,5I=[],11=c.11,2X=c.U=="2k-2X";7(e<0)K V;Q(L i=2X?e:0,2f=2X?e+1:11.M;i<2f;i++){L d=11[i];7(d.2p){b=E.14.1d&&!d.9J.1A.9y?d.1u:d.1A;7(2X)K b;5I.1g(b)}}K 5I}N K(6[0].1A||"").1r(/\\r/g,"")}K 10}K 6.R(J(){7(6.15!=1)K;7(b.1k==1M&&/5u|5t/.17(6.U))6.3k=(E.33(6.1A,b)>=0||E.33(6.31,b)>=0);N 7(E.12(6,"2k")){L a=b.1k==1M?b:[b];E("98",6).R(J(){6.2p=(E.33(6.1A,a)>=0||E.33(6.1u,a)>=0)});7(!a.M)6.3T=-1}N 6.1A=b})},3q:J(a){K a==10?(6.M?6[0].3d:V):6.4x().3t(a)},6S:J(a){K 6.5a(a).1V()},6Z:J(i){K 6.2K(i,i+1)},2K:J(){K 6.2F(1M.2l.2K.1i(6,18))},2c:J(b){K 6.2F(E.2c(6,J(a,i){K b.1P(a,i,a)}))},4R:J(){K 6.1b(6.54)},O:J(d,b){L a=d.23(".");a[1]=a[1]?"."+a[1]:"";7(b==V){L c=6.5n("8P"+a[1]+"!",[a[0]]);7(c==10&&6.M)c=E.O(6[0],d);K c==V&&a[1]?6.O(a[0]):c}N K 6.1N("8K"+a[1]+"!",[a[0],b]).R(J(){E.O(6,d,b)})},35:J(a){K 6.R(J(){E.35(6,a)})},3O:J(g,f,h,d){L e=6.M>1,3n;K 6.R(J(){7(!3n){3n=E.4a(g,6.2i);7(h)3n.8D()}L b=6;7(f&&E.12(6,"1O")&&E.12(3n[0],"4v"))b=6.3S("1U")[0]||6.38(6.2i.3s("1U"));L c=E([]);E.R(3n,J(){L a=e?E(6).5k(P)[0]:6;7(E.12(a,"1m")){c=c.1b(a)}N{7(a.15==1)c=c.1b(E("1m",a).1V());d.1P(b,a)}});c.R(6A)})}};E.2l.4T.2l=E.2l;J 6A(i,a){7(a.3Q)E.3P({1c:a.3Q,3l:S,1H:"1m"});N E.5g(a.1u||a.6x||a.3d||"");7(a.1a)a.1a.34(a)}E.1s=E.1n.1s=J(){L b=18[0]||{},i=1,M=18.M,5c=S,11;7(b.1k==8d){5c=b;b=18[1]||{};i=2}7(1o b!="3V"&&1o b!="J")b={};7(M==1){b=6;i=0}Q(;i<M;i++)7((11=18[i])!=V)Q(L a 1p 11){7(b===11[a])6w;7(5c&&11[a]&&1o 11[a]=="3V"&&b[a]&&!11[a].15)b[a]=E.1s(b[a],11[a]);N 7(11[a]!=10)b[a]=11[a]}K b};L F="3N"+(1B 3v()).3L(),6t=0,5b={};L H=/z-?4X|86-?84|1w|6k|7Z-?1R/i;E.1s({7Y:J(a){1e.$=D;7(a)1e.3N=w;K E},1q:J(a){K!!a&&1o a!="25"&&!a.12&&a.1k!=1M&&/J/i.17(a+"")},3E:J(a){K a.1F&&!a.1h||a.28&&a.2i&&!a.2i.1h},5g:J(a){a=E.3g(a);7(a){L b=T.3S("6f")[0]||T.1F,1m=T.3s("1m");1m.U="1u/4m";7(E.14.1d)1m.1u=a;N 1m.38(T.5r(a));b.38(1m);b.34(1m)}},12:J(b,a){K b.12&&b.12.2E()==a.2E()},1T:{},O:J(c,d,b){c=c==1e?5b:c;L a=c[F];7(!a)a=c[F]=++6t;7(d&&!E.1T[a])E.1T[a]={};7(b!=10)E.1T[a][d]=b;K d?E.1T[a][d]:a},35:J(c,b){c=c==1e?5b:c;L a=c[F];7(b){7(E.1T[a]){2V E.1T[a][b];b="";Q(b 1p E.1T[a])1Q;7(!b)E.35(c)}}N{1S{2V c[F]}1X(e){7(c.52)c.52(F)}2V E.1T[a]}},R:J(c,a,b){7(b){7(c.M==10){Q(L d 1p c)7(a.1i(c[d],b)===S)1Q}N Q(L i=0,M=c.M;i<M;i++)7(a.1i(c[i],b)===S)1Q}N{7(c.M==10){Q(L d 1p c)7(a.1P(c[d],d,c[d])===S)1Q}N Q(L i=0,M=c.M,1A=c[0];i<M&&a.1P(1A,i,1A)!==S;1A=c[++i]){}}K c},1l:J(b,a,c,i,d){7(E.1q(a))a=a.1P(b,i);K a&&a.1k==51&&c=="2o"&&!H.17(d)?a+"2S":a},1t:{1b:J(c,b){E.R((b||"").23(/\\s+/),J(i,a){7(c.15==1&&!E.1t.3Y(c.1t,a))c.1t+=(c.1t?" ":"")+a})},1V:J(c,b){7(c.15==1)c.1t=b!=10?E.3y(c.1t.23(/\\s+/),J(a){K!E.1t.3Y(b,a)}).6a(" "):""},3Y:J(b,a){K E.33(a,(b.1t||b).3X().23(/\\s+/))>-1}},68:J(b,c,a){L e={};Q(L d 1p c){e[d]=b.W[d];b.W[d]=c[d]}a.1P(b);Q(L d 1p c)b.W[d]=e[d]},1j:J(d,e,c){7(e=="27"||e=="1R"){L b,46={43:"4W",4U:"1Z",19:"3D"},3c=e=="27"?["7O","7M"]:["7J","7I"];J 5E(){b=e=="27"?d.7H:d.7F;L a=0,2N=0;E.R(3c,J(){a+=2M(E.2o(d,"7E"+6,P))||0;2N+=2M(E.2o(d,"2N"+6+"5X",P))||0});b-=24.7C(a+2N)}7(E(d).3H(":4d"))5E();N E.68(d,46,5E);K 24.2f(0,b)}K E.2o(d,e,c)},2o:J(e,k,j){L d;J 3x(b){7(!E.14.2d)K S;L a=T.4c.4K(b,V);K!a||a.4M("3x")==""}7(k=="1w"&&E.14.1d){d=E.1J(e.W,"1w");K d==""?"1":d}7(E.14.2z&&k=="19"){L c=e.W.50;e.W.50="0 7r 7o";e.W.50=c}7(k.1D(/4g/i))k=y;7(!j&&e.W&&e.W[k])d=e.W[k];N 7(T.4c&&T.4c.4K){7(k.1D(/4g/i))k="4g";k=k.1r(/([A-Z])/g,"-$1").2h();L h=T.4c.4K(e,V);7(h&&!3x(e))d=h.4M(k);N{L f=[],2C=[];Q(L a=e;a&&3x(a);a=a.1a)2C.4J(a);Q(L i=0;i<2C.M;i++)7(3x(2C[i])){f[i]=2C[i].W.19;2C[i].W.19="3D"}d=k=="19"&&f[2C.M-1]!=V?"2H":(h&&h.4M(k))||"";Q(L i=0;i<f.M;i++)7(f[i]!=V)2C[i].W.19=f[i]}7(k=="1w"&&d=="")d="1"}N 7(e.4n){L g=k.1r(/\\-(\\w)/g,J(a,b){K b.2E()});d=e.4n[k]||e.4n[g];7(!/^\\d+(2S)?$/i.17(d)&&/^\\d/.17(d)){L l=e.W.26,3K=e.3K.26;e.3K.26=e.4n.26;e.W.26=d||0;d=e.W.7f+"2S";e.W.26=l;e.3K.26=3K}}K d},4a:J(l,h){L k=[];h=h||T;7(1o h.3s==\'10\')h=h.2i||h[0]&&h[0].2i||T;E.R(l,J(i,d){7(!d)K;7(d.1k==51)d=d.3X();7(1o d=="25"){d=d.1r(/(<(\\w+)[^>]*?)\\/>/g,J(b,a,c){K c.1D(/^(aa|a6|7e|a5|4D|7a|a0|3m|9W|9U|9S)$/i)?b:a+"></"+c+">"});L f=E.3g(d).2h(),1x=h.3s("1x");L e=!f.1f("<9P")&&[1,"<2k 74=\'74\'>","</2k>"]||!f.1f("<9M")&&[1,"<73>","</73>"]||f.1D(/^<(9G|1U|9E|9B|9x)/)&&[1,"<1O>","</1O>"]||!f.1f("<4v")&&[2,"<1O><1U>","</1U></1O>"]||(!f.1f("<9w")||!f.1f("<9v"))&&[3,"<1O><1U><4v>","</4v></1U></1O>"]||!f.1f("<7e")&&[2,"<1O><1U></1U><6V>","</6V></1O>"]||E.14.1d&&[1,"1x<1x>","</1x>"]||[0,"",""];1x.3d=e[1]+d+e[2];2b(e[0]--)1x=1x.5o;7(E.14.1d){L g=!f.1f("<1O")&&f.1f("<1U")<0?1x.1C&&1x.1C.3p:e[1]=="<1O>"&&f.1f("<1U")<0?1x.3p:[];Q(L j=g.M-1;j>=0;--j)7(E.12(g[j],"1U")&&!g[j].3p.M)g[j].1a.34(g[j]);7(/^\\s/.17(d))1x.3o(h.5r(d.1D(/^\\s*/)[0]),1x.1C)}d=E.2I(1x.3p)}7(d.M===0&&(!E.12(d,"3u")&&!E.12(d,"2k")))K;7(d[0]==10||E.12(d,"3u")||d.11)k.1g(d);N k=E.37(k,d)});K k},1J:J(d,e,c){7(!d||d.15==3||d.15==8)K 10;L f=E.3E(d)?{}:E.46;7(e=="2p"&&E.14.2d)d.1a.3T;7(f[e]){7(c!=10)d[f[e]]=c;K d[f[e]]}N 7(E.14.1d&&e=="W")K E.1J(d.W,"9u",c);N 7(c==10&&E.14.1d&&E.12(d,"3u")&&(e=="9r"||e=="9o"))K d.9m(e).6K;N 7(d.28){7(c!=10){7(e=="U"&&E.12(d,"4D")&&d.1a)6Q"U 9i 9h\'t 9g 9e";d.9b(e,""+c)}7(E.14.1d&&/6O|3Q/.17(e)&&!E.3E(d))K d.4z(e,2);K d.4z(e)}N{7(e=="1w"&&E.14.1d){7(c!=10){d.6k=1;d.1E=(d.1E||"").1r(/6M\\([^)]*\\)/,"")+(2M(c).3X()=="96"?"":"6M(1w="+c*6L+")")}K d.1E&&d.1E.1f("1w=")>=0?(2M(d.1E.1D(/1w=([^)]*)/)[1])/6L).3X():""}e=e.1r(/-([a-z])/95,J(a,b){K b.2E()});7(c!=10)d[e]=c;K d[e]}},3g:J(a){K(a||"").1r(/^\\s+|\\s+$/g,"")},2I:J(b){L a=[];7(1o b!="93")Q(L i=0,M=b.M;i<M;i++)a.1g(b[i]);N a=b.2K(0);K a},33:J(b,a){Q(L i=0,M=a.M;i<M;i++)7(a[i]==b)K i;K-1},37:J(a,b){7(E.14.1d){Q(L i=0;b[i];i++)7(b[i].15!=8)a.1g(b[i])}N Q(L i=0;b[i];i++)a.1g(b[i]);K a},57:J(a){L c=[],2r={};1S{Q(L i=0,M=a.M;i<M;i++){L b=E.O(a[i]);7(!2r[b]){2r[b]=P;c.1g(a[i])}}}1X(e){c=a}K c},3y:J(c,a,d){L b=[];Q(L i=0,M=c.M;i<M;i++)7(!d&&a(c[i],i)||d&&!a(c[i],i))b.1g(c[i]);K b},2c:J(d,a){L c=[];Q(L i=0,M=d.M;i<M;i++){L b=a(d[i],i);7(b!==V&&b!=10){7(b.1k!=1M)b=[b];c=c.71(b)}}K c}});L v=8Y.8W.2h();E.14={5K:(v.1D(/.+(?:8T|8S|8R|8O)[\\/: ]([\\d.]+)/)||[])[1],2d:/77/.17(v),2z:/2z/.17(v),1d:/1d/.17(v)&&!/2z/.17(v),48:/48/.17(v)&&!/(8L|77)/.17(v)};L y=E.14.1d?"6H":"75";E.1s({8I:!E.14.1d||T.6F=="79",46:{"Q":"8F","8E":"1t","4g":y,75:y,6H:y,3d:"3d",1t:"1t",1A:"1A",2Y:"2Y",3k:"3k",8C:"8B",2p:"2p",8A:"8z",3T:"3T",6C:"6C",28:"28",12:"12"}});E.R({6B:J(a){K a.1a},8y:J(a){K E.4u(a,"1a")},8x:J(a){K E.2Z(a,2,"2B")},8v:J(a){K E.2Z(a,2,"4t")},8u:J(a){K E.4u(a,"2B")},8t:J(a){K E.4u(a,"4t")},8s:J(a){K E.5i(a.1a.1C,a)},8r:J(a){K E.5i(a.1C)},6z:J(a){K E.12(a,"8q")?a.8o||a.8n.T:E.2I(a.3p)}},J(c,d){E.1n[c]=J(b){L a=E.2c(6,d);7(b&&1o b=="25")a=E.3e(b,a);K 6.2F(E.57(a))}});E.R({6y:"3t",8m:"6q",3o:"6o",8l:"5a",8k:"6S"},J(c,b){E.1n[c]=J(){L a=18;K 6.R(J(){Q(L i=0,M=a.M;i<M;i++)E(a[i])[b](6)})}});E.R({8j:J(a){E.1J(6,a,"");7(6.15==1)6.52(a)},8i:J(a){E.1t.1b(6,a)},8h:J(a){E.1t.1V(6,a)},8g:J(a){E.1t[E.1t.3Y(6,a)?"1V":"1b"](6,a)},1V:J(a){7(!a||E.1E(a,[6]).r.M){E("*",6).1b(6).R(J(){E.16.1V(6);E.35(6)});7(6.1a)6.1a.34(6)}},4x:J(){E(">*",6).1V();2b(6.1C)6.34(6.1C)}},J(a,b){E.1n[a]=J(){K 6.R(b,18)}});E.R(["8f","5X"],J(i,c){L b=c.2h();E.1n[b]=J(a){K 6[0]==1e?E.14.2z&&T.1h["5e"+c]||E.14.2d&&1e["8e"+c]||T.6F=="79"&&T.1F["5e"+c]||T.1h["5e"+c]:6[0]==T?24.2f(24.2f(T.1h["5d"+c],T.1F["5d"+c]),24.2f(T.1h["5L"+c],T.1F["5L"+c])):a==10?(6.M?E.1j(6[0],b):V):6.1j(b,a.1k==4e?a:a+"2S")}});L C=E.14.2d&&4s(E.14.5K)<8c?"(?:[\\\\w*4r-]|\\\\\\\\.)":"(?:[\\\\w\\8b-\\8a*4r-]|\\\\\\\\.)",6v=1B 4q("^>\\\\s*("+C+"+)"),6u=1B 4q("^("+C+"+)(#)("+C+"+)"),6s=1B 4q("^([#.]?)("+C+"*)");E.1s({6r:{"":J(a,i,m){K m[2]=="*"||E.12(a,m[2])},"#":J(a,i,m){K a.4z("2w")==m[2]},":":{89:J(a,i,m){K i<m[3]-0},88:J(a,i,m){K i>m[3]-0},2Z:J(a,i,m){K m[3]-0==i},6Z:J(a,i,m){K m[3]-0==i},3j:J(a,i){K i==0},3J:J(a,i,m,r){K i==r.M-1},6n:J(a,i){K i%2==0},6l:J(a,i){K i%2},"3j-4p":J(a){K a.1a.3S("*")[0]==a},"3J-4p":J(a){K E.2Z(a.1a.5o,1,"4t")==a},"83-4p":J(a){K!E.2Z(a.1a.5o,2,"4t")},6B:J(a){K a.1C},4x:J(a){K!a.1C},82:J(a,i,m){K(a.6x||a.81||E(a).1u()||"").1f(m[3])>=0},4d:J(a){K"1Z"!=a.U&&E.1j(a,"19")!="2H"&&E.1j(a,"4U")!="1Z"},1Z:J(a){K"1Z"==a.U||E.1j(a,"19")=="2H"||E.1j(a,"4U")=="1Z"},80:J(a){K!a.2Y},2Y:J(a){K a.2Y},3k:J(a){K a.3k},2p:J(a){K a.2p||E.1J(a,"2p")},1u:J(a){K"1u"==a.U},5u:J(a){K"5u"==a.U},5t:J(a){K"5t"==a.U},59:J(a){K"59"==a.U},3I:J(a){K"3I"==a.U},58:J(a){K"58"==a.U},6j:J(a){K"6j"==a.U},6i:J(a){K"6i"==a.U},2G:J(a){K"2G"==a.U||E.12(a,"2G")},4D:J(a){K/4D|2k|6h|2G/i.17(a.12)},3Y:J(a,i,m){K E.2s(m[3],a).M},7X:J(a){K/h\\d/i.17(a.12)},7W:J(a){K E.3y(E.3G,J(b){K a==b.Y}).M}}},6g:[/^(\\[) *@?([\\w-]+) *([!*$^~=]*) *(\'?"?)(.*?)\\4 *\\]/,/^(:)([\\w-]+)\\("?\'?(.*?(\\(.*?\\))?[^(]*?)"?\'?\\)/,1B 4q("^([:.#]*)("+C+"+)")],3e:J(a,c,b){L d,2m=[];2b(a&&a!=d){d=a;L f=E.1E(a,c,b);a=f.t.1r(/^\\s*,\\s*/,"");2m=b?c=f.r:E.37(2m,f.r)}K 2m},2s:J(t,p){7(1o t!="25")K[t];7(p&&p.15!=1&&p.15!=9)K[];p=p||T;L d=[p],2r=[],3J,12;2b(t&&3J!=t){L r=[];3J=t;t=E.3g(t);L o=S;L g=6v;L m=g.2O(t);7(m){12=m[1].2E();Q(L i=0;d[i];i++)Q(L c=d[i].1C;c;c=c.2B)7(c.15==1&&(12=="*"||c.12.2E()==12))r.1g(c);d=r;t=t.1r(g,"");7(t.1f(" ")==0)6w;o=P}N{g=/^([>+~])\\s*(\\w*)/i;7((m=g.2O(t))!=V){r=[];L l={};12=m[2].2E();m=m[1];Q(L j=0,3f=d.M;j<3f;j++){L n=m=="~"||m=="+"?d[j].2B:d[j].1C;Q(;n;n=n.2B)7(n.15==1){L h=E.O(n);7(m=="~"&&l[h])1Q;7(!12||n.12.2E()==12){7(m=="~")l[h]=P;r.1g(n)}7(m=="+")1Q}}d=r;t=E.3g(t.1r(g,""));o=P}}7(t&&!o){7(!t.1f(",")){7(p==d[0])d.4l();2r=E.37(2r,d);r=d=[p];t=" "+t.6e(1,t.M)}N{L k=6u;L m=k.2O(t);7(m){m=[0,m[2],m[3],m[1]]}N{k=6s;m=k.2O(t)}m[2]=m[2].1r(/\\\\/g,"");L f=d[d.M-1];7(m[1]=="#"&&f&&f.5J&&!E.3E(f)){L q=f.5J(m[2]);7((E.14.1d||E.14.2z)&&q&&1o q.2w=="25"&&q.2w!=m[2])q=E(\'[@2w="\'+m[2]+\'"]\',f)[0];d=r=q&&(!m[3]||E.12(q,m[3]))?[q]:[]}N{Q(L i=0;d[i];i++){L a=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];7(a=="*"&&d[i].12.2h()=="3V")a="3m";r=E.37(r,d[i].3S(a))}7(m[1]==".")r=E.55(r,m[2]);7(m[1]=="#"){L e=[];Q(L i=0;r[i];i++)7(r[i].4z("2w")==m[2]){e=[r[i]];1Q}r=e}d=r}t=t.1r(k,"")}}7(t){L b=E.1E(t,r);d=r=b.r;t=E.3g(b.t)}}7(t)d=[];7(d&&p==d[0])d.4l();2r=E.37(2r,d);K 2r},55:J(r,m,a){m=" "+m+" ";L c=[];Q(L i=0;r[i];i++){L b=(" "+r[i].1t+" ").1f(m)>=0;7(!a&&b||a&&!b)c.1g(r[i])}K c},1E:J(t,r,h){L d;2b(t&&t!=d){d=t;L p=E.6g,m;Q(L i=0;p[i];i++){m=p[i].2O(t);7(m){t=t.7V(m[0].M);m[2]=m[2].1r(/\\\\/g,"");1Q}}7(!m)1Q;7(m[1]==":"&&m[2]=="56")r=G.17(m[3])?E.1E(m[3],r,P).r:E(r).56(m[3]);N 7(m[1]==".")r=E.55(r,m[2],h);N 7(m[1]=="["){L g=[],U=m[3];Q(L i=0,3f=r.M;i<3f;i++){L a=r[i],z=a[E.46[m[2]]||m[2]];7(z==V||/6O|3Q|2p/.17(m[2]))z=E.1J(a,m[2])||\'\';7((U==""&&!!z||U=="="&&z==m[5]||U=="!="&&z!=m[5]||U=="^="&&z&&!z.1f(m[5])||U=="$="&&z.6e(z.M-m[5].M)==m[5]||(U=="*="||U=="~=")&&z.1f(m[5])>=0)^h)g.1g(a)}r=g}N 7(m[1]==":"&&m[2]=="2Z-4p"){L e={},g=[],17=/(-?)(\\d*)n((?:\\+|-)?\\d*)/.2O(m[3]=="6n"&&"2n"||m[3]=="6l"&&"2n+1"||!/\\D/.17(m[3])&&"7U+"+m[3]||m[3]),3j=(17[1]+(17[2]||1))-0,d=17[3]-0;Q(L i=0,3f=r.M;i<3f;i++){L j=r[i],1a=j.1a,2w=E.O(1a);7(!e[2w]){L c=1;Q(L n=1a.1C;n;n=n.2B)7(n.15==1)n.4k=c++;e[2w]=P}L b=S;7(3j==0){7(j.4k==d)b=P}N 7((j.4k-d)%3j==0&&(j.4k-d)/3j>=0)b=P;7(b^h)g.1g(j)}r=g}N{L f=E.6r[m[1]];7(1o f=="3V")f=f[m[2]];7(1o f=="25")f=6c("S||J(a,i){K "+f+";}");r=E.3y(r,J(a,i){K f(a,i,m,r)},h)}}K{r:r,t:t}},4u:J(b,c){L d=[];L a=b[c];2b(a&&a!=T){7(a.15==1)d.1g(a);a=a[c]}K d},2Z:J(a,e,c,b){e=e||1;L d=0;Q(;a;a=a[c])7(a.15==1&&++d==e)1Q;K a},5i:J(n,a){L r=[];Q(;n;n=n.2B){7(n.15==1&&(!a||n!=a))r.1g(n)}K r}});E.16={1b:J(f,i,g,e){7(f.15==3||f.15==8)K;7(E.14.1d&&f.53!=10)f=1e;7(!g.2D)g.2D=6.2D++;7(e!=10){L h=g;g=J(){K h.1i(6,18)};g.O=e;g.2D=h.2D}L j=E.O(f,"2R")||E.O(f,"2R",{}),1v=E.O(f,"1v")||E.O(f,"1v",J(){L a;7(1o E=="10"||E.16.5f)K a;a=E.16.1v.1i(18.3R.Y,18);K a});1v.Y=f;E.R(i.23(/\\s+/),J(c,b){L a=b.23(".");b=a[0];g.U=a[1];L d=j[b];7(!d){d=j[b]={};7(!E.16.2y[b]||E.16.2y[b].4j.1P(f)===S){7(f.3F)f.3F(b,1v,S);N 7(f.6b)f.6b("4i"+b,1v)}}d[g.2D]=g;E.16.2a[b]=P});f=V},2D:1,2a:{},1V:J(e,h,f){7(e.15==3||e.15==8)K;L i=E.O(e,"2R"),29,4X;7(i){7(h==10||(1o h=="25"&&h.7T(0)=="."))Q(L g 1p i)6.1V(e,g+(h||""));N{7(h.U){f=h.2q;h=h.U}E.R(h.23(/\\s+/),J(b,a){L c=a.23(".");a=c[0];7(i[a]){7(f)2V i[a][f.2D];N Q(f 1p i[a])7(!c[1]||i[a][f].U==c[1])2V i[a][f];Q(29 1p i[a])1Q;7(!29){7(!E.16.2y[a]||E.16.2y[a].4h.1P(e)===S){7(e.67)e.67(a,E.O(e,"1v"),S);N 7(e.66)e.66("4i"+a,E.O(e,"1v"))}29=V;2V i[a]}}})}Q(29 1p i)1Q;7(!29){L d=E.O(e,"1v");7(d)d.Y=V;E.35(e,"2R");E.35(e,"1v")}}},1N:J(g,c,d,f,h){c=E.2I(c||[]);7(g.1f("!")>=0){g=g.2K(0,-1);L a=P}7(!d){7(6.2a[g])E("*").1b([1e,T]).1N(g,c)}N{7(d.15==3||d.15==8)K 10;L b,29,1n=E.1q(d[g]||V),16=!c[0]||!c[0].36;7(16)c.4J(6.4Z({U:g,2L:d}));c[0].U=g;7(a)c[0].65=P;7(E.1q(E.O(d,"1v")))b=E.O(d,"1v").1i(d,c);7(!1n&&d["4i"+g]&&d["4i"+g].1i(d,c)===S)b=S;7(16)c.4l();7(h&&E.1q(h)){29=h.1i(d,b==V?c:c.71(b));7(29!==10)b=29}7(1n&&f!==S&&b!==S&&!(E.12(d,\'a\')&&g=="4V")){6.5f=P;1S{d[g]()}1X(e){}}6.5f=S}K b},1v:J(c){L a;c=E.16.4Z(c||1e.16||{});L b=c.U.23(".");c.U=b[0];L f=E.O(6,"2R")&&E.O(6,"2R")[c.U],42=1M.2l.2K.1P(18,1);42.4J(c);Q(L j 1p f){L d=f[j];42[0].2q=d;42[0].O=d.O;7(!b[1]&&!c.65||d.U==b[1]){L e=d.1i(6,42);7(a!==S)a=e;7(e===S){c.36();c.44()}}}7(E.14.1d)c.2L=c.36=c.44=c.2q=c.O=V;K a},4Z:J(c){L a=c;c=E.1s({},a);c.36=J(){7(a.36)a.36();a.7S=S};c.44=J(){7(a.44)a.44();a.7R=P};7(!c.2L)c.2L=c.7Q||T;7(c.2L.15==3)c.2L=a.2L.1a;7(!c.4S&&c.5w)c.4S=c.5w==c.2L?c.7P:c.5w;7(c.64==V&&c.63!=V){L b=T.1F,1h=T.1h;c.64=c.63+(b&&b.2v||1h&&1h.2v||0)-(b.62||0);c.7N=c.7L+(b&&b.2x||1h&&1h.2x||0)-(b.60||0)}7(!c.3c&&((c.4f||c.4f===0)?c.4f:c.5Z))c.3c=c.4f||c.5Z;7(!c.7b&&c.5Y)c.7b=c.5Y;7(!c.3c&&c.2G)c.3c=(c.2G&1?1:(c.2G&2?3:(c.2G&4?2:0)));K c},2y:{21:{4j:J(){5M();K},4h:J(){K}},3C:{4j:J(){7(E.14.1d)K S;E(6).2j("4P",E.16.2y.3C.2q);K P},4h:J(){7(E.14.1d)K S;E(6).3w("4P",E.16.2y.3C.2q);K P},2q:J(a){7(I(a,6))K P;18[0].U="3C";K E.16.1v.1i(6,18)}},3B:{4j:J(){7(E.14.1d)K S;E(6).2j("4O",E.16.2y.3B.2q);K P},4h:J(){7(E.14.1d)K S;E(6).3w("4O",E.16.2y.3B.2q);K P},2q:J(a){7(I(a,6))K P;18[0].U="3B";K E.16.1v.1i(6,18)}}}};E.1n.1s({2j:J(c,a,b){K c=="4H"?6.2X(c,a,b):6.R(J(){E.16.1b(6,c,b||a,b&&a)})},2X:J(d,b,c){K 6.R(J(){E.16.1b(6,d,J(a){E(6).3w(a);K(c||b).1i(6,18)},c&&b)})},3w:J(a,b){K 6.R(J(){E.16.1V(6,a,b)})},1N:J(c,a,b){K 6.R(J(){E.16.1N(c,a,6,P,b)})},5n:J(c,a,b){7(6[0])K E.16.1N(c,a,6[0],S,b);K 10},2g:J(){L b=18;K 6.4V(J(a){6.4N=0==6.4N?1:0;a.36();K b[6.4N].1i(6,18)||S})},7D:J(a,b){K 6.2j(\'3C\',a).2j(\'3B\',b)},21:J(a){5M();7(E.2Q)a.1P(T,E);N E.3A.1g(J(){K a.1P(6,E)});K 6}});E.1s({2Q:S,3A:[],21:J(){7(!E.2Q){E.2Q=P;7(E.3A){E.R(E.3A,J(){6.1i(T)});E.3A=V}E(T).5n("21")}}});L x=S;J 5M(){7(x)K;x=P;7(T.3F&&!E.14.2z)T.3F("5W",E.21,S);7(E.14.1d&&1e==3b)(J(){7(E.2Q)K;1S{T.1F.7B("26")}1X(3a){3z(18.3R,0);K}E.21()})();7(E.14.2z)T.3F("5W",J(){7(E.2Q)K;Q(L i=0;i<T.4L.M;i++)7(T.4L[i].2Y){3z(18.3R,0);K}E.21()},S);7(E.14.2d){L a;(J(){7(E.2Q)K;7(T.39!="5V"&&T.39!="1y"){3z(18.3R,0);K}7(a===10)a=E("W, 7a[7A=7z]").M;7(T.4L.M!=a){3z(18.3R,0);K}E.21()})()}E.16.1b(1e,"3U",E.21)}E.R(("7y,7x,3U,7w,5d,4H,4V,7v,"+"7G,7u,7t,4P,4O,7s,2k,"+"58,7K,7q,7p,3a").23(","),J(i,b){E.1n[b]=J(a){K a?6.2j(b,a):6.1N(b)}});L I=J(a,c){L b=a.4S;2b(b&&b!=c)1S{b=b.1a}1X(3a){b=c}K b==c};E(1e).2j("4H",J(){E("*").1b(T).3w()});E.1n.1s({3U:J(g,d,c){7(E.1q(g))K 6.2j("3U",g);L e=g.1f(" ");7(e>=0){L i=g.2K(e,g.M);g=g.2K(0,e)}c=c||J(){};L f="4Q";7(d)7(E.1q(d)){c=d;d=V}N{d=E.3m(d);f="61"}L h=6;E.3P({1c:g,U:f,1H:"3q",O:d,1y:J(a,b){7(b=="1W"||b=="5U")h.3q(i?E("<1x/>").3t(a.4b.1r(/<1m(.|\\s)*?\\/1m>/g,"")).2s(i):a.4b);h.R(c,[a.4b,b,a])}});K 6},7n:J(){K E.3m(6.5T())},5T:J(){K 6.2c(J(){K E.12(6,"3u")?E.2I(6.7m):6}).1E(J(){K 6.31&&!6.2Y&&(6.3k||/2k|6h/i.17(6.12)||/1u|1Z|3I/i.17(6.U))}).2c(J(i,c){L b=E(6).5O();K b==V?V:b.1k==1M?E.2c(b,J(a,i){K{31:c.31,1A:a}}):{31:c.31,1A:b}}).22()}});E.R("5S,6d,5R,6D,5Q,6m".23(","),J(i,o){E.1n[o]=J(f){K 6.2j(o,f)}});L B=(1B 3v).3L();E.1s({22:J(d,b,a,c){7(E.1q(b)){a=b;b=V}K E.3P({U:"4Q",1c:d,O:b,1W:a,1H:c})},7l:J(b,a){K E.22(b,V,a,"1m")},7k:J(c,b,a){K E.22(c,b,a,"3i")},7i:J(d,b,a,c){7(E.1q(b)){a=b;b={}}K E.3P({U:"61",1c:d,O:b,1W:a,1H:c})},85:J(a){E.1s(E.4I,a)},4I:{2a:P,U:"4Q",2U:0,5P:"4o/x-7h-3u-7g",5N:P,3l:P,O:V,6p:V,3I:V,49:{3M:"4o/3M, 1u/3M",3q:"1u/3q",1m:"1u/4m, 4o/4m",3i:"4o/3i, 1u/4m",1u:"1u/a7",4G:"*/*"}},4F:{},3P:J(s){L f,2W=/=\\?(&|$)/g,1z,O;s=E.1s(P,s,E.1s(P,{},E.4I,s));7(s.O&&s.5N&&1o s.O!="25")s.O=E.3m(s.O);7(s.1H=="4E"){7(s.U.2h()=="22"){7(!s.1c.1D(2W))s.1c+=(s.1c.1D(/\\?/)?"&":"?")+(s.4E||"7d")+"=?"}N 7(!s.O||!s.O.1D(2W))s.O=(s.O?s.O+"&":"")+(s.4E||"7d")+"=?";s.1H="3i"}7(s.1H=="3i"&&(s.O&&s.O.1D(2W)||s.1c.1D(2W))){f="4E"+B++;7(s.O)s.O=(s.O+"").1r(2W,"="+f+"$1");s.1c=s.1c.1r(2W,"="+f+"$1");s.1H="1m";1e[f]=J(a){O=a;1W();1y();1e[f]=10;1S{2V 1e[f]}1X(e){}7(h)h.34(g)}}7(s.1H=="1m"&&s.1T==V)s.1T=S;7(s.1T===S&&s.U.2h()=="22"){L i=(1B 3v()).3L();L j=s.1c.1r(/(\\?|&)4r=.*?(&|$)/,"$a4="+i+"$2");s.1c=j+((j==s.1c)?(s.1c.1D(/\\?/)?"&":"?")+"4r="+i:"")}7(s.O&&s.U.2h()=="22"){s.1c+=(s.1c.1D(/\\?/)?"&":"?")+s.O;s.O=V}7(s.2a&&!E.5H++)E.16.1N("5S");7((!s.1c.1f("a3")||!s.1c.1f("//"))&&s.1H=="1m"&&s.U.2h()=="22"){L h=T.3S("6f")[0];L g=T.3s("1m");g.3Q=s.1c;7(s.7c)g.a2=s.7c;7(!f){L l=S;g.9Z=g.9Y=J(){7(!l&&(!6.39||6.39=="5V"||6.39=="1y")){l=P;1W();1y();h.34(g)}}}h.38(g);K 10}L m=S;L k=1e.78?1B 78("9X.9V"):1B 76();k.9T(s.U,s.1c,s.3l,s.6p,s.3I);1S{7(s.O)k.4C("9R-9Q",s.5P);7(s.5C)k.4C("9O-5A-9N",E.4F[s.1c]||"9L, 9K 9I 9H 5z:5z:5z 9F");k.4C("X-9C-9A","76");k.4C("9z",s.1H&&s.49[s.1H]?s.49[s.1H]+", */*":s.49.4G)}1X(e){}7(s.6Y)s.6Y(k);7(s.2a)E.16.1N("6m",[k,s]);L c=J(a){7(!m&&k&&(k.39==4||a=="2U")){m=P;7(d){6I(d);d=V}1z=a=="2U"&&"2U"||!E.6X(k)&&"3a"||s.5C&&E.6J(k,s.1c)&&"5U"||"1W";7(1z=="1W"){1S{O=E.6W(k,s.1H)}1X(e){1z="5x"}}7(1z=="1W"){L b;1S{b=k.5q("6U-5A")}1X(e){}7(s.5C&&b)E.4F[s.1c]=b;7(!f)1W()}N E.5v(s,k,1z);1y();7(s.3l)k=V}};7(s.3l){L d=53(c,13);7(s.2U>0)3z(J(){7(k){k.9t();7(!m)c("2U")}},s.2U)}1S{k.9s(s.O)}1X(e){E.5v(s,k,V,e)}7(!s.3l)c();J 1W(){7(s.1W)s.1W(O,1z);7(s.2a)E.16.1N("5Q",[k,s])}J 1y(){7(s.1y)s.1y(k,1z);7(s.2a)E.16.1N("5R",[k,s]);7(s.2a&&!--E.5H)E.16.1N("6d")}K k},5v:J(s,a,b,e){7(s.3a)s.3a(a,b,e);7(s.2a)E.16.1N("6D",[a,s,e])},5H:0,6X:J(r){1S{K!r.1z&&9q.9p=="59:"||(r.1z>=6T&&r.1z<9n)||r.1z==6R||r.1z==9l||E.14.2d&&r.1z==10}1X(e){}K S},6J:J(a,c){1S{L b=a.5q("6U-5A");K a.1z==6R||b==E.4F[c]||E.14.2d&&a.1z==10}1X(e){}K S},6W:J(r,b){L c=r.5q("9k-U");L d=b=="3M"||!b&&c&&c.1f("3M")>=0;L a=d?r.9j:r.4b;7(d&&a.1F.28=="5x")6Q"5x";7(b=="1m")E.5g(a);7(b=="3i")a=6c("("+a+")");K a},3m:J(a){L s=[];7(a.1k==1M||a.5h)E.R(a,J(){s.1g(3r(6.31)+"="+3r(6.1A))});N Q(L j 1p a)7(a[j]&&a[j].1k==1M)E.R(a[j],J(){s.1g(3r(j)+"="+3r(6))});N s.1g(3r(j)+"="+3r(a[j]));K s.6a("&").1r(/%20/g,"+")}});E.1n.1s({1G:J(c,b){K c?6.2e({1R:"1G",27:"1G",1w:"1G"},c,b):6.1E(":1Z").R(J(){6.W.19=6.5s||"";7(E.1j(6,"19")=="2H"){L a=E("<"+6.28+" />").6y("1h");6.W.19=a.1j("19");7(6.W.19=="2H")6.W.19="3D";a.1V()}}).3h()},1I:J(b,a){K b?6.2e({1R:"1I",27:"1I",1w:"1I"},b,a):6.1E(":4d").R(J(){6.5s=6.5s||E.1j(6,"19");6.W.19="2H"}).3h()},6N:E.1n.2g,2g:J(a,b){K E.1q(a)&&E.1q(b)?6.6N(a,b):a?6.2e({1R:"2g",27:"2g",1w:"2g"},a,b):6.R(J(){E(6)[E(6).3H(":1Z")?"1G":"1I"]()})},9f:J(b,a){K 6.2e({1R:"1G"},b,a)},9d:J(b,a){K 6.2e({1R:"1I"},b,a)},9c:J(b,a){K 6.2e({1R:"2g"},b,a)},9a:J(b,a){K 6.2e({1w:"1G"},b,a)},99:J(b,a){K 6.2e({1w:"1I"},b,a)},97:J(c,a,b){K 6.2e({1w:a},c,b)},2e:J(l,k,j,h){L i=E.6P(k,j,h);K 6[i.2P===S?"R":"2P"](J(){7(6.15!=1)K S;L g=E.1s({},i);L f=E(6).3H(":1Z"),4A=6;Q(L p 1p l){7(l[p]=="1I"&&f||l[p]=="1G"&&!f)K E.1q(g.1y)&&g.1y.1i(6);7(p=="1R"||p=="27"){g.19=E.1j(6,"19");g.32=6.W.32}}7(g.32!=V)6.W.32="1Z";g.40=E.1s({},l);E.R(l,J(c,a){L e=1B E.2t(4A,g,c);7(/2g|1G|1I/.17(a))e[a=="2g"?f?"1G":"1I":a](l);N{L b=a.3X().1D(/^([+-]=)?([\\d+-.]+)(.*)$/),1Y=e.2m(P)||0;7(b){L d=2M(b[2]),2A=b[3]||"2S";7(2A!="2S"){4A.W[c]=(d||1)+2A;1Y=((d||1)/e.2m(P))*1Y;4A.W[c]=1Y+2A}7(b[1])d=((b[1]=="-="?-1:1)*d)+1Y;e.45(1Y,d,2A)}N e.45(1Y,a,"")}});K P})},2P:J(a,b){7(E.1q(a)||(a&&a.1k==1M)){b=a;a="2t"}7(!a||(1o a=="25"&&!b))K A(6[0],a);K 6.R(J(){7(b.1k==1M)A(6,a,b);N{A(6,a).1g(b);7(A(6,a).M==1)b.1i(6)}})},94:J(b,c){L a=E.3G;7(b)6.2P([]);6.R(J(){Q(L i=a.M-1;i>=0;i--)7(a[i].Y==6){7(c)a[i](P);a.72(i,1)}});7(!c)6.5p();K 6}});L A=J(b,c,a){7(!b)K 10;c=c||"2t";L q=E.O(b,c+"2P");7(!q||a)q=E.O(b,c+"2P",a?E.2I(a):[]);K q};E.1n.5p=J(a){a=a||"2t";K 6.R(J(){L q=A(6,a);q.4l();7(q.M)q[0].1i(6)})};E.1s({6P:J(b,a,c){L d=b&&b.1k==92?b:{1y:c||!c&&a||E.1q(b)&&b,2u:b,3Z:c&&a||a&&a.1k!=91&&a};d.2u=(d.2u&&d.2u.1k==51?d.2u:{90:8Z,9D:6T}[d.2u])||8X;d.5y=d.1y;d.1y=J(){7(d.2P!==S)E(6).5p();7(E.1q(d.5y))d.5y.1i(6)};K d},3Z:{70:J(p,n,b,a){K b+a*p},5j:J(p,n,b,a){K((-24.8V(p*24.8U)/2)+0.5)*a+b}},3G:[],3W:V,2t:J(b,c,a){6.11=c;6.Y=b;6.1l=a;7(!c.47)c.47={}}});E.2t.2l={4y:J(){7(6.11.30)6.11.30.1i(6.Y,[6.2J,6]);(E.2t.30[6.1l]||E.2t.30.4G)(6);7(6.1l=="1R"||6.1l=="27")6.Y.W.19="3D"},2m:J(a){7(6.Y[6.1l]!=V&&6.Y.W[6.1l]==V)K 6.Y[6.1l];L r=2M(E.1j(6.Y,6.1l,a));K r&&r>-8Q?r:2M(E.2o(6.Y,6.1l))||0},45:J(c,b,d){6.5B=(1B 3v()).3L();6.1Y=c;6.3h=b;6.2A=d||6.2A||"2S";6.2J=6.1Y;6.4B=6.4w=0;6.4y();L e=6;J t(a){K e.30(a)}t.Y=6.Y;E.3G.1g(t);7(E.3W==V){E.3W=53(J(){L a=E.3G;Q(L i=0;i<a.M;i++)7(!a[i]())a.72(i--,1);7(!a.M){6I(E.3W);E.3W=V}},13)}},1G:J(){6.11.47[6.1l]=E.1J(6.Y.W,6.1l);6.11.1G=P;6.45(0,6.2m());7(6.1l=="27"||6.1l=="1R")6.Y.W[6.1l]="8N";E(6.Y).1G()},1I:J(){6.11.47[6.1l]=E.1J(6.Y.W,6.1l);6.11.1I=P;6.45(6.2m(),0)},30:J(a){L t=(1B 3v()).3L();7(a||t>6.11.2u+6.5B){6.2J=6.3h;6.4B=6.4w=1;6.4y();6.11.40[6.1l]=P;L b=P;Q(L i 1p 6.11.40)7(6.11.40[i]!==P)b=S;7(b){7(6.11.19!=V){6.Y.W.32=6.11.32;6.Y.W.19=6.11.19;7(E.1j(6.Y,"19")=="2H")6.Y.W.19="3D"}7(6.11.1I)6.Y.W.19="2H";7(6.11.1I||6.11.1G)Q(L p 1p 6.11.40)E.1J(6.Y.W,p,6.11.47[p])}7(b&&E.1q(6.11.1y))6.11.1y.1i(6.Y);K S}N{L n=t-6.5B;6.4w=n/6.11.2u;6.4B=E.3Z[6.11.3Z||(E.3Z.5j?"5j":"70")](6.4w,n,0,1,6.11.2u);6.2J=6.1Y+((6.3h-6.1Y)*6.4B);6.4y()}K P}};E.2t.30={2v:J(a){a.Y.2v=a.2J},2x:J(a){a.Y.2x=a.2J},1w:J(a){E.1J(a.Y.W,"1w",a.2J)},4G:J(a){a.Y.W[a.1l]=a.2J+a.2A}};E.1n.5L=J(){L b=0,3b=0,Y=6[0],5l;7(Y)8M(E.14){L d=Y.1a,41=Y,1K=Y.1K,1L=Y.2i,5D=2d&&4s(5K)<8J&&!/a1/i.17(v),2T=E.1j(Y,"43")=="2T";7(Y.6G){L c=Y.6G();1b(c.26+24.2f(1L.1F.2v,1L.1h.2v),c.3b+24.2f(1L.1F.2x,1L.1h.2x));1b(-1L.1F.62,-1L.1F.60)}N{1b(Y.5G,Y.5F);2b(1K){1b(1K.5G,1K.5F);7(48&&!/^t(8H|d|h)$/i.17(1K.28)||2d&&!5D)2N(1K);7(!2T&&E.1j(1K,"43")=="2T")2T=P;41=/^1h$/i.17(1K.28)?41:1K;1K=1K.1K}2b(d&&d.28&&!/^1h|3q$/i.17(d.28)){7(!/^8G|1O.*$/i.17(E.1j(d,"19")))1b(-d.2v,-d.2x);7(48&&E.1j(d,"32")!="4d")2N(d);d=d.1a}7((5D&&(2T||E.1j(41,"43")=="4W"))||(48&&E.1j(41,"43")!="4W"))1b(-1L.1h.5G,-1L.1h.5F);7(2T)1b(24.2f(1L.1F.2v,1L.1h.2v),24.2f(1L.1F.2x,1L.1h.2x))}5l={3b:3b,26:b}}J 2N(a){1b(E.2o(a,"a8",P),E.2o(a,"a9",P))}J 1b(l,t){b+=4s(l)||0;3b+=4s(t)||0}K 5l}})();',62,631,'||||||this|if||||||||||||||||||||||||||||||||||||||function|return|var|length|else|data|true|for|each|false|document|type|null|style||elem||undefined|options|nodeName||browser|nodeType|event|test|arguments|display|parentNode|add|url|msie|window|indexOf|push|body|apply|css|constructor|prop|script|fn|typeof|in|isFunction|replace|extend|className|text|handle|opacity|div|complete|status|value|new|firstChild|match|filter|documentElement|show|dataType|hide|attr|offsetParent|doc|Array|trigger|table|call|break|height|try|cache|tbody|remove|success|catch|start|hidden||ready|get|split|Math|string|left|width|tagName|ret|global|while|map|safari|animate|max|toggle|toLowerCase|ownerDocument|bind|select|prototype|cur||curCSS|selected|handler|done|find|fx|duration|scrollLeft|id|scrollTop|special|opera|unit|nextSibling|stack|guid|toUpperCase|pushStack|button|none|makeArray|now|slice|target|parseFloat|border|exec|queue|isReady|events|px|fixed|timeout|delete|jsre|one|disabled|nth|step|name|overflow|inArray|removeChild|removeData|preventDefault|merge|appendChild|readyState|error|top|which|innerHTML|multiFilter|rl|trim|end|json|first|checked|async|param|elems|insertBefore|childNodes|html|encodeURIComponent|createElement|append|form|Date|unbind|color|grep|setTimeout|readyList|mouseleave|mouseenter|block|isXMLDoc|addEventListener|timers|is|password|last|runtimeStyle|getTime|xml|jQuery|domManip|ajax|src|callee|getElementsByTagName|selectedIndex|load|object|timerId|toString|has|easing|curAnim|offsetChild|args|position|stopPropagation|custom|props|orig|mozilla|accepts|clean|responseText|defaultView|visible|String|charCode|float|teardown|on|setup|nodeIndex|shift|javascript|currentStyle|application|child|RegExp|_|parseInt|previousSibling|dir|tr|state|empty|update|getAttribute|self|pos|setRequestHeader|input|jsonp|lastModified|_default|unload|ajaxSettings|unshift|getComputedStyle|styleSheets|getPropertyValue|lastToggle|mouseout|mouseover|GET|andSelf|relatedTarget|init|visibility|click|absolute|index|container|fix|outline|Number|removeAttribute|setInterval|prevObject|classFilter|not|unique|submit|file|after|windowData|deep|scroll|client|triggered|globalEval|jquery|sibling|swing|clone|results|wrapAll|triggerHandler|lastChild|dequeue|getResponseHeader|createTextNode|oldblock|checkbox|radio|handleError|fromElement|parsererror|old|00|Modified|startTime|ifModified|safari2|getWH|offsetTop|offsetLeft|active|values|getElementById|version|offset|bindReady|processData|val|contentType|ajaxSuccess|ajaxComplete|ajaxStart|serializeArray|notmodified|loaded|DOMContentLoaded|Width|ctrlKey|keyCode|clientTop|POST|clientLeft|clientX|pageX|exclusive|detachEvent|removeEventListener|swap|cloneNode|join|attachEvent|eval|ajaxStop|substr|head|parse|textarea|reset|image|zoom|odd|ajaxSend|even|before|username|prepend|expr|quickClass|uuid|quickID|quickChild|continue|textContent|appendTo|contents|evalScript|parent|defaultValue|ajaxError|setArray|compatMode|getBoundingClientRect|styleFloat|clearInterval|httpNotModified|nodeValue|100|alpha|_toggle|href|speed|throw|304|replaceWith|200|Last|colgroup|httpData|httpSuccess|beforeSend|eq|linear|concat|splice|fieldset|multiple|cssFloat|XMLHttpRequest|webkit|ActiveXObject|CSS1Compat|link|metaKey|scriptCharset|callback|col|pixelLeft|urlencoded|www|post|hasClass|getJSON|getScript|elements|serialize|black|keyup|keypress|solid|change|mousemove|mouseup|dblclick|resize|focus|blur|stylesheet|rel|doScroll|round|hover|padding|offsetHeight|mousedown|offsetWidth|Bottom|Top|keydown|clientY|Right|pageY|Left|toElement|srcElement|cancelBubble|returnValue|charAt|0n|substring|animated|header|noConflict|line|enabled|innerText|contains|only|weight|ajaxSetup|font|size|gt|lt|uFFFF|u0128|417|Boolean|inner|Height|toggleClass|removeClass|addClass|removeAttr|replaceAll|insertAfter|prependTo|contentWindow|contentDocument|wrap|iframe|children|siblings|prevAll|nextAll|prev|wrapInner|next|parents|maxLength|maxlength|readOnly|readonly|reverse|class|htmlFor|inline|able|boxModel|522|setData|compatible|with|1px|ie|getData|10000|ra|it|rv|PI|cos|userAgent|400|navigator|600|slow|Function|Object|array|stop|ig|NaN|fadeTo|option|fadeOut|fadeIn|setAttribute|slideToggle|slideUp|changed|slideDown|be|can|property|responseXML|content|1223|getAttributeNode|300|method|protocol|location|action|send|abort|cssText|th|td|cap|specified|Accept|With|colg|Requested|fast|tfoot|GMT|thead|1970|Jan|attributes|01|Thu|leg|Since|If|opt|Type|Content|embed|open|area|XMLHTTP|hr|Microsoft|onreadystatechange|onload|meta|adobeair|charset|http|1_|img|br|plain|borderLeftWidth|borderTopWidth|abbr'.split('|'),0,{})) \ No newline at end of file diff --git a/lib/webri/assets/js/ri.jquery.js b/lib/webri/assets/js/ri.jquery.js new file mode 100644 index 0000000..7c24305 --- /dev/null +++ b/lib/webri/assets/js/ri.jquery.js @@ -0,0 +1,65 @@ +function lookup(elem, key) { +alert(key); + if ($(elem).hasClass('trigger')) { + $(elem).attr('display', 'block'); + $('#main').load(key); + } else { + $('#main').load(key); + }; +}; + +function lookup_static(elem, file) { + if ($(elem).hasClass('trigger')) { + $(elem).attr('display', 'block'); + $('#main').load(file); + } else { + $('#main').load(file); + }; +}; + +function showBranch(trigger) { + var objTrigger = $(trigger); + var objBranch = objTrigger.siblings('.branch'); + if(objBranch.css('display') == "block") { + objBranch.css('display', "none"); + } else { + objBranch.css('display', "block"); + } +}; + +function swapFolder(img) { + objImg = document.getElementById(img); + if(objImg.src.indexOf('closed.gif')>-1) { + objImg.src = openImg.src; + } else { + objImg.src = closedImg.src; + } +}; + +function getWindowHeight() { + var windowHeight = 0; + if (typeof(window.innerHeight) == 'number') { + windowHeight = window.innerHeight; + } + else { + if (document.documentElement && document.documentElement.clientHeight) { + windowHeight = document.documentElement.clientHeight; + } + else { + if (document.body && document.body.clientHeight) { + windowHeight = document.body.clientHeight; + } + } + } + return windowHeight; +}; + +function resizePage() { + var side = document.getElementById('tree'); + var main = document.getElementById('main'); + var h = getWindowHeight(); + var nh = (h - 134) + 'px'; + side.style.height = nh; + main.style.height = nh; +}; + diff --git a/lib/webri/fastri_service.rb b/lib/webri/fastri_service.rb new file mode 100644 index 0000000..3e3d894 --- /dev/null +++ b/lib/webri/fastri_service.rb @@ -0,0 +1,387 @@ +#!/usr/bin/env ruby +# wri: access RI documentation through DRb +# Copyright (C) 2006 Mauricio Fernandez <[email protected]> + +require 'webri/server' + +require 'fastri/util' +require 'fastri/full_text_index' + +default_local_mode = File.basename($0)[/^wri/] ? true : false + +# we bind to 127.0.0.1 by default, because otherwise Ruby will try with +# 0.0.0.0, which results in a DNS request, adding way too much latency +options = { + :addr => "127.0.0.1", + :format => + case RUBY_PLATFORM + when /win/ + if /darwin|cygwin/ =~ RUBY_PLATFORM + "ansi" + else + "plain" + end + else + "ansi" + end, + :width => 72, + :lookup_order => [ + :exact, :exact_ci, :nested, :nested_ci, :partial, :partial_ci, + :nested_partial, :nested_partial_ci, + ], + :show_matches => false, + :do_full_text => false, + :full_text_dir => File.join(FastRI::Util.find_home, ".fastri-fulltext"), + :use_pager => nil, + :pager => nil, + :list_classes => nil, + :list_methods => nil, + :extended => false, + :index_file => File.join(FastRI::Util.find_home, ".fastri-index"), + :local_mode => default_local_mode, + :do_second_guess => true, + :expand_choices => false, +} + +override_addr_env = false + + +# only load optparse if actually needed +# saves ~0.01-0.04s. +if (arg = ARGV[0]) && arg[0, 1] == "-" or ARGV.empty? + require 'optparse' + optparser = OptionParser.new do |opts| + opts.version = FastRI::FASTRI_VERSION + opts.release = FastRI::FASTRI_RELEASE_DATE + opts.banner = "Usage: #{File.basename($0)} [options] <query>" + + opts.on("-L", "--local", "Try to use local index instead of DRb service.", + *[("(default)" if default_local_mode)].compact) do + options[:local_mode] = true + end + opts.on("--index-file=FILE", "Use index file (forces --local mode).", + "(default: #{options[:index_file]})") do |file| + options[:index_file] = file + options[:local_mode] = true + end + opts.on("-R", "--remote", "Use DRb service. #{'(default)' unless default_local_mode}") do + options[:local_mode] = false + end + opts.on("-s", "--bind ADDR", "Bind to ADDR for incoming DRb connections.", + "(default: 127.0.0.1)") do |addr| + options[:addr] = addr + override_addr_env = true + end + + order_mapping = { + 'e' => :exact, 'E' => :exact_ci, 'n' => :nested, 'N' => :nested_ci, + 'p' => :partial, 'P' => :partial_ci, 'x' => :nested_partial, + 'X' => :nested_partial_ci, 'a' => :anywhere, 'A' => :anywhere_ci, + 'm' => :namespace_partial, 'M' => :namespace_partial_ci, + 'f' => :full_partial, 'F' => :full_partial_ci, + } + opts.on("-O", "--order ORDER", "Specify lookup order.", + "(default: eEnNpPxX)", "Uppercase: case-indep.", + "e:exact n:nested p:partial (completion)", + "x:nested and partial m:complete namespace", + "f:complete both class and method", + "a:match method name anywhere") do |order| + options[:lookup_order] = order.split(//).map{|x| order_mapping[x]}.compact + end + + opts.on("-1", "--exact", "Does not do second guess(exact query).") do + options[:do_second_guess] = false + options[:lookup_order] = [ :exact ] + end + opts.on("-a", "--all", "Show info for all methods in Multiple choices", + "(default: don't)") do + options[:expand_choices] = true + end + + opts.on("-e", "--extended", "Show all methods for given namespace.") do + options[:extended] = true + options[:use_pager] = true + options[:format] = "plain" + end + + opts.on("--show-matches", "Only show matching entries."){ options[:show_matches] = true } + + opts.on("--classes", "List all known classes/modules.") do + options[:use_pager] = true + options[:list_classes] = true + end + opts.on("--methods", "List all known methods.") do + options[:use_pager] = true + options[:list_methods] = true + end + opts.on("-l", "--list-names", "List all known namespaces/methods.") do + options[:use_pager] = true + options[:list_classes] = true + options[:list_methods] = true + end + + opts.on("-S", "--full-text", "Perform full-text search.") do + options[:do_full_text] = true + options[:use_pager] = true if options[:use_pager].nil? + options[:format] = "plain" + end + + opts.on("-F", "--full-text-dir DIR", "Use full-text index in DIR", + "(default: #{options[:full_text_dir]})") do |dir| + options[:full_text_dir] = dir if dir + options[:do_full_text] = true + options[:use_pager] = true + options[:format] = "plain" + end + + opts.on("-f", "--format FMT", "Format to use when displaying output:", + " ansi, plain (default: #{options[:format]})") do |format| + options[:format] = format + end + + opts.on("-P", "--[no-]pager", "Use pager.", "(default: don't)") do |usepager| + options[:use_pager] = usepager + options[:format] = "plain" if usepager + end + + opts.on("-T", "Don't use a pager."){ options[:use_pager] = false } + + opts.on("--pager-cmd PAGER", "Use pager PAGER.", "(default: don't)") do |pager| + options[:pager] = pager + options[:use_pager] = true + options[:format] = "plain" + end + + opts.on("-w", "--width WIDTH", "Set the width of the output.") do |width| + w = width.to_i + options[:width] = w > 0 ? w : options[:width] + end + + opts.on("-h", "--help", "Show this help message") do + puts opts + exit + end + end + optparser.parse! + + #if !options[:list_classes] && !options[:list_methods] && ARGV.empty? + # puts optparser + # exit + #end +end # lazy optparse loading + +# {{{ try to find where the method comes from exactly +include FastRI::Util::MagicHelp + +MAX_CONTEXT_LINES = 20 +def context_wrap(text, width) + "... " + + text.gsub(/(.{1,#{width-4}})( +|$\n?)|(.{1,#{width-4}})/, "\\1\\3\n").chomp +end + +def display_fulltext_search_results(results, gem_dir_info = FastRI::Util.gem_directories_unique, + width = 78) + return if results.empty? + path = File.expand_path(results[0].path) + gem_name, version, gem_path = FastRI::Util.gem_info_for_path(path, gem_dir_info) + if gem_name + rel_path = path[/#{Regexp.escape(gem_path)}\/(.*)/, 1] + if rel_path + entry_name = FastRI::Util.gem_relpath_to_full_name(rel_path) + end + puts "Found in #{gem_name} #{version} #{entry_name}" + else + rdoc_system_path = File.expand_path(RI::Paths::SYSDIR) + if path.index(rdoc_system_path) + rel_path = path[/#{Regexp.escape(rdoc_system_path)}\/(.*)/, 1] + puts "Found in system #{FastRI::Util.gem_relpath_to_full_name(rel_path)}" + else + puts "Found in #{path}:" + end + end + text = results.map do |result| + context = result.context(120) + from = (context.rindex("\n", context.index(result.query)) || -1) + 1 + to = (context.index("\n", context.index(result.query)) || 0) - 1 + context_wrap(context[from..to], width) + end + puts + puts text.uniq[0...MAX_CONTEXT_LINES] + puts +end + +def perform_fulltext_search(options) + fulltext = File.join(options[:full_text_dir], "full_text.dat") + suffixes = File.join(options[:full_text_dir], "suffixes.dat") + begin + index = FastRI::FullTextIndex.new_from_filenames(fulltext, suffixes) + rescue Exception + puts <<EOF +Couldn't open the full-text index: +#{fulltext} +#{suffixes} + +The index needs to be rebuilt with + fastri-server -B +EOF + exit(-1) + end + gem_dir_info = FastRI::Util.gem_directories_unique + match_sets = ARGV.map do |query| + result = index.lookup(query) + if result + index.next_matches(result) + [result] + else + [] + end + end + path_map = Hash.new{|h,k| h[k] = []} + match_sets.each{|matches| matches.each{|m| path_map[m.path] << m} } + paths = match_sets[1..-1].inject(match_sets[0].map{|x| x.path}.uniq) do |s,x| + s & x.map{|y| y.path}.uniq + end + if paths.empty? + puts "nil" + else + puts "#{paths.size} hits" + paths.sort_by{|path| 1.0 * -path_map[path].size / path_map[path].first.metadata[:size] ** 0.5}.map do |path| + puts "=" * options[:width] + puts 1.0 * path_map[path].size / path_map[path].first.metadata[:size] ** 0.5 + display_fulltext_search_results(path_map[path], gem_dir_info, options[:width]) + end + end + + exit 0 +end + +#{{{ set up pager +if options[:use_pager] + [options[:pager], ENV["PAGER"], "less", "more", "pager"].compact.uniq.each do |pager| + begin + $stdout = IO.popen(pager, "w") + at_exit{ $stdout.close } + break + rescue Exception + end + end +end + +#{{{ perform full text search if asked to +perform_fulltext_search(options) if options[:do_full_text] + +#{{{ normal query +if options[:local_mode] + require 'fastri/ri_service' + ri_reader = open(options[:index_file], "rb"){|io| Marshal.load io } rescue nil + unless ri_reader + puts <<EOF +Couldn't open the index: +#{options[:index_file]} + +The index needs to be rebuilt with + fastri-server -b +EOF + exit(-1) + end + service = FastRI::RiService.new(ri_reader) +else # remote + require 'rinda/ring' + + #{{{ determine the address to bind to + if override_addr_env + addr_spec = options[:addr] + else + addr_spec = ENV["FASTRI_ADDR"] || options[:addr] + end + + ip = addr_spec[/^[^:]+/] || "127.0.0.1" + port = addr_spec[/:(\d+)/, 1] || 0 + addr = "druby://#{ip}:#{port}" + + #{{{ start DRb and perform request + begin + DRb.start_service(addr) + ring_server = Rinda::RingFinger.primary + rescue Exception + $stderr.puts <<EOF +Couldn't initialize DRb and locate the Ring server. + +Please make sure that: + * the fastri-server is running, the server is bound to the correct interface, + and the ACL setup allows connections from this host + * fri is using the correct interface for incoming DRb requests: + either set the FASTRI_ADDR environment variable, or use --bind ADDR, e.g + export FASTRI_ADDR="192.168.1.12" + fri Array +EOF + exit(-1) + end + service = ring_server.read([:name, :FastRI, nil, nil])[2] +end + + +info_options = { + :formatter => options[:format], + :width => options[:width], + :lookup_order => options[:lookup_order], + :extended => options[:extended], + :expand_choices => options[:expand_choices], +} + +=begin +# {{{ list classes or methods +puts service.all_classes if options[:list_classes] +puts service.all_methods if options[:list_methods] +exit if options[:list_classes] || options[:list_methods] + +# {{{ normal query + +ARGV.each do |term| + help_query = magic_help(term) + if options[:show_matches] + puts service.matches(help_query, info_options).sort + else + result = service.info(help_query, info_options) + # second-guess the correct method type only as the last resort. + if result + puts result + elsif options[:do_second_guess] and (new_query = FastRI::Util.change_query_method_type(help_query)) != help_query + puts service.info(new_query) + else + puts nil + end + end +end +=end + +wri = WebRI::Server.new(service) +#puts wri.to_html + +require 'webrick' +include WEBrick + +p wri.directory + "/public" + +s = HTTPServer.new( + :Port => 8888, + :DocumentRoot => wri.directory + "/public" +) + +s.mount_proc("/index"){|req, res| + res.body = wri.to_html + res['Content-Type'] = "text/html" +} + +s.mount_proc("/ri"){|req, res| + res.body = wri.lookup(req) + res['Content-Type'] = "text/html" +} + +## mount subdirectories +s.mount("/js", HTTPServlet::FileHandler, wri.directory + "/public/js") +s.mount("/css", HTTPServlet::FileHandler, wri.directory + "/public/css") +s.mount("/img", HTTPServlet::FileHandler, wri.directory + "/public/img") + +trap("INT"){ s.shutdown } +s.start + diff --git a/lib/webri/generator.rb b/lib/webri/generator.rb new file mode 100644 index 0000000..9dcb5a8 --- /dev/null +++ b/lib/webri/generator.rb @@ -0,0 +1,227 @@ +require 'webri/server' + +module WebRI + + # This is the static website generator. + # + class Generator < Server + + # Reference to CGI Service + #attr :cgi + + # Reference to RI Service + #attr :service + + # Directory in which to store generated html files + attr :output + + # + def initialize(service, options={}) + super(service, options) + #@cgi = {} #CGI.new('html4') + #@service = service + @directory_depth = 0 + end + + # + def tree + #%[<iframe src="tree.html"></iframe>] + @tree ||= heirarchy.to_html_static + end + +=begin + # + def lookup(req) + keyw = File.basename(req.path_info) + if keyw + keyw.sub!('-','#') + html = service.info(keyw) +#puts html + #term = AnsiSys::Terminal.new.echo(ansi) + #html = term.render(:html) #=> HTML fragment + #html = ERB::Util.html_escape(html) + html = "#{html}" + else + html = "<h1>ERROR</h1>" + end + return html + end +=end + + #def template_source + # @template_source ||= File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) + #end + + # + #def to_html + # #filetext = File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) + # template = ERB.new(template_source) + # template.result(binding) + # #heirarchy.to_html + #end + + # generate webpages + def generate(output=".") + @output = File.expand_path(output) + # traverse the the hierarchy + + generate_support_files + + #generate_recurse(heirarchy) + +# heirarchy.class_methods.each do |name| +# p name +# end + +# heirarchy.instance_methods.each do |name| +# p name +# end + + heirarchy.subspaces.each do |name, entry| + #p name, entry + generate_recurse(entry) + end + end + + # + def generate_recurse(entry) + keyword = entry.full_name + + if keyword + puts keyword + @current_content = service.info(keyword) #lookup(keyword) + else + keyword = '' + @current_content = "Welcome" + end + + file = entry.file_name + file = File.join(output, file) + + #file = keyword + #file = file.gsub('::', '--') + #file = file.gsub('.' , '--') + #file = file.gsub('#' , '-') + #file = File.join(output, file + '.html') + + write(file, service.info(keyword)) + + cmethods = entry.class_methods.map{ |x| x.to_s }.sort + cmethods.each do |name| + mname = "#{entry.full_name}.#{name}" + mfile = WebRI.entry_to_path(mname) + mfile = File.join(output, mfile) + #mfile = File.join(output, "#{entry.file_name}/c-#{esc(name)}.html") + write(mfile, service.info(mname)) + end + + imethods = entry.instance_methods.map{ |x| x.to_s }.sort + imethods.each do |name| + mname = "#{entry.full_name}##{name}" + mfile = WebRI.entry_to_path(mname) + mfile = File.join(output, mfile) + #mfile = File.join(output, "#{entry.file_name}/i-#{esc(name)}.html") + write(mfile, service.info(mname)) + end + + entry.subspaces.each do |child_name, child_entry| + next if child_entry == entry + @directory_depth += 1 + generate_recurse(child_entry) + @directory_depth -= 1 + end + end + + # + def write(file, text) + puts file + FileUtils.mkdir_p(File.dirname(file)) + File.open(file, 'w') { |f| f << text.to_s } + end + + # + def generate_support_files + FileUtils.mkdir_p(output) + + write(File.join(output, 'index.html'), index) + #write(File.join(output, 'header.html'), page_header) + #write(File.join(output, 'tree.html'), page_tree) + #write(File.join(output, 'main.html'), page_main) + + # copy assets + dir = File.join(directory, 'assets') + FileUtils.cp_r(dir, output) + end + + # + def current_content + @current_content + end + +=begin + # = Generator Heirarchy + # + class Heirarchy + attr :name + attr :parent + attr :subspaces + attr :instance_methods + attr :class_methods + + def initialize(name, parent=nil) + @name = name + @parent = parent if NS===parent + @subspaces = {} + @class_methods = [] + @instance_methods = [] + end + + def key + full_name + end + + def [](name) + @subspaces[name] + end + + def []=(name, value) + @subspaces[name] = value + end + + def root? + !parent + end + + def full_name + if root? + nil + else + [parent.full_name, name].compact.join("::") + end + end + + def file_name + file = full_name + file = file.gsub('::', '--') + file = file.gsub('.' , '--') + file = file.gsub('#' , '-') + #file = File.join(output, file + '.html') + file + end + + + def esc(text) + OpEsc.escape(text.to_s) + end + + def inspect + "<#{self.class} #{name}>" + end + + end #class NS +=end + + end #class Generator + +end #module WebRI + diff --git a/lib/webri/heirarchy.rb b/lib/webri/heirarchy.rb new file mode 100644 index 0000000..a08770d --- /dev/null +++ b/lib/webri/heirarchy.rb @@ -0,0 +1,196 @@ +module WebRI + + # + def self.entry_to_path(entry) + path = entry.to_s + path = path.gsub('::', '/') + path = path.gsub('#' , '/i-') + path = path.gsub('.' , '/c-') + path = OpEsc.escape(path) + path = path + '.html' + end + + # + def self.path_to_entry(path) + entry = path.to_s + entry = entry.chomp('.html') + entry = OpEsc.unescape(entry) + entry = entry.gsub('/c-' , '.') + entry = entry.gsub('/i-' , '#') + entry = entry.gsub('/' , '::') + end + + # = Heirarchy + # + class Heirarchy + attr :name + attr :parent + attr :subspaces + attr :instance_methods + attr :class_methods + + def initialize(name, parent=nil) + @name = name + @parent = parent if Heirarchy===parent + @subspaces = {} + @class_methods = [] + @instance_methods = [] + end + + def key + full_name + end + + def [](name) + @subspaces[name] + end + + def []=(name, value) + @subspaces[name] = value + end + + def root? + !parent + end + + def full_name + if root? + nil + else + [parent.full_name, name].compact.join("::") + end + end + + # Path name for a given class, module or method. + # + def file_name + # file = full_name + # file = file.gsub('::', '/') + # file = file.gsub('#' , '/') + # file = file.gsub('.' , '-') + # #file = File.join(output, file + '.html') + # file + WebRI.entry_to_path(full_name) + end + + # generate html tree + # + def to_html + markup = [] + if root? + markup << %[<div class="root">] + else + path = WebRI.entry_to_path(full_name) + markup << %[ + <li class="trigger"> + <img src="assets/img/class.png" onClick="showBranch(this);"/> + <span class="link" onClick="lookup_static(this, '#{path}');">#{name}</span> + ] + markup << %[<div class="branch">] + end + + markup << %[<ul>] + + cmethods = class_methods.map{ |x| x.to_s }.sort + cmethods.each do |method| + path = WebRI.entry_to_path(full_name + ".#{method}") + markup << %[ + <li class="meta_leaf"> + <span class="link" onClick="lookup_static(this, '#{path}');">#{method}</span> + </li> + ] + end + + imethods = instance_methods.map{ |x| x.to_s }.sort + imethods.each do |method| + path = WebRI.entry_to_path(full_name + "##{method}") + markup << %[ + <li class="leaf"> + <span class="link" onClick="lookup_static(this, '#{path}');">#{method}</span> + </li> + ] + end + + subspaces.to_a.sort{ |a,b| a[0].to_s <=> b[0].to_s }.each do |(name, subspace)| + #subspaces.each do |name, subspace| + markup << subspace.to_html + end + markup << %[</ul>] + + if root? + markup << %[</div>] + else + markup << %[</div>] + markup << %[</li>] + end + + return markup.join("\n") + end + + # + alias_method :to_html_static, :to_html + +=begin + # generate dynamic html tree + # + def to_html + markup = [] + if root? + markup << %[<div class="root">] + else + markup << %[ + <li class="trigger"> + <img src="img/dir.gif" onClick="showBranch(this);"/> + <span class="link" onClick="lookup(this, '#{full_name}');">#{name}</span> + ] + markup << %[<div class="branch">] + end + + markup << %[<ul>] + class_methods.each do |method| + markup << %[ + <li class="meta_leaf"> + <span class="link" onClick="lookup(this, '#{full_name}.#{method}');">#{method}</span> + </li> + ] + end + + instance_methods.each do |method| + markup << %[ + <li class="leaf"> + <span class="link" onClick="lookup(this, '#{full_name}-#{method}');">#{method}</span> + </li> + ] + end + + subspaces.to_a.sort{ |a,b| a[0].to_s <=> b[0].to_s }.each do |(name, subspace)| + #subspaces.each do |name, subspace| + markup << subspace.to_html + end + markup << %[</ul>] + + if root? + markup << %[</div>] + else + markup << %[</div>] + markup << %[</li>] + end + + return markup.join("\n") + end +=end + + # + #def esc(text) + # OpEsc.escape(text.to_s) + # #CGI.escape(text.to_s).gsub('-','%2D') + #end + + def inspect + "<#{self.class} #{name}>" + end + + end #class Heirarchy + +end #module WebRI + diff --git a/lib/webri/opesc.rb b/lib/webri/opesc.rb new file mode 100644 index 0000000..0fff4cd --- /dev/null +++ b/lib/webri/opesc.rb @@ -0,0 +1,73 @@ +# = OpEsc +# +module OpEsc + + OPERATORS = %w{ +@ -@ + - ** * / % ~ <=> << >> < > === == =~ <= >= | & ^ []= [] } + + OPERATORS_REGEXP = Regexp.new( '(' << OPERATORS.collect{ |k| Regexp.escape(k) }.join('|') << ')$' ) + + OPERATORS_ESC_TABLE = { + "+@" => "op_plus_self", + "-@" => "op_minus_self", + "+" => "op_plus", + "-" => "op_minus", + "**" => "op_pow", + "*" => "op_mul", + "/" => "op_div", + "%" => "op_mod", + "~" => "op_tilde", + "<=>" => "op_cmp", + "<<" => "op_lshift", + ">>" => "op_rshift", + "<" => "op_lt", + ">" => "op_gt", + "===" => "op_case_eq", + "==" => "op_equal", + "=~" => "op_apply", + "<=" => "op_lt_eq", + ">=" => "op_gt_eq", + "|" => "op_or", + "&" => "op_and", + "^" => "op_xor", + "[]=" => "op_store", + "[]" => "op_fetch" + } + + REVERSE_TABLE = OPERATORS_ESC_TABLE.invert + + REVERSE_REGEXP = Regexp.new( '(' << REVERSE_TABLE.keys.collect{ |k| Regexp.escape(k) }.join('|') << ')$' ) + + # Applies operator escape's according to OPERATORS_ESCAPE_TABLE. + # + # op_esc('-') #=> "op_minus" + # op_esc('odd?') #=> "odd-Q" + # + # CREDIT: Trans + + def self.escape(str) + str.gsub(OPERATORS_REGEXP){ OPERATORS_ESC_TABLE[$1] }.sub(/\?$/, '\1-Q') + end + + def self.unescape(str) + str = str.sub(/\-Q$/, '?') + str = str.gsub(REVERSE_REGEXP){ REVERSE_TABLE[$1] } + end + + # NOTE: op_esc used to support the method require_esc. + # + # # Require a file with puncuation marks escaped. + # # + # # require_esc '[].rb' + # # + # # in actuality requires the file 'op_fetch.rb'. + # + # def require_esc( fpath ) + # fdir, fname = File.split(fpath) + # ename = op_esc( fname ) + # case ename[-1,1] ; when '!','=','?' then ename = ename[0...-1] ; end + # epath = File.join( fdir, ename ) + # require( epath ) + # end + +end + diff --git a/lib/webri/ri_service.rb b/lib/webri/ri_service.rb new file mode 100644 index 0000000..065d47d --- /dev/null +++ b/lib/webri/ri_service.rb @@ -0,0 +1,84 @@ +require 'uri' + +module WebRI + + class RiService + + # Directory of ri doc files. + attr_accessor :library + + attr_accessor :system + + attr_accessor :site + + attr_accessor :gems + + attr_accessor :home + + # + def initialize(options) + options.each do |k,v| + send("#{k}=", v) if respond_to?("#{k}=") + end + end + + # + def info(keyword) + #puts "KEYWORD: #{keyword.inspect}" + html = `ri #{ri_opts} -f html #{keyword}` + return "<br/>#{html}<br/><br/>" + end + + # + def names + @names ||= (library ? names_from_library : names_from_all) + end + + # + def names_from_library(lib=nil) + files = nil + Dir.chdir(lib || library) do + files = Dir['**/*'] + files = files.map do |f| + case f + when /\-i.yaml$/ + (File.dirname(f) + '#' + URI.unescape(File.basename(f).chomp('-i.yaml'))).gsub('/' , '::') + when /\-c.yaml$/ + (File.dirname(f) + '::' + URI.unescape(File.basename(f).chomp('-c.yaml'))).gsub('/' , '::') + else + #f.sub(/^cdesc-/,'').gsub('/' , '::') + nil + end + end.compact + end + files + end + + # + def names_from_all + libraries = `ri #{ri_opts} -l`.split("\n") + libraries.map do |lib| + names_from_library(lib) + end.flatten + end + + private + + # + def ri_opts + cmd = [] + if library + cmd << %[-d "#{library}" --no-standard-docs] + else + cmd << ( system ? "--system" : "--no-system" ) + cmd << ( site ? "--site" : "--no-site" ) + cmd << ( gems ? "--gems" : "--no-gems" ) + cmd << ( home ? "--home" : "--no-home" ) + end + cmd.join(' ') + end + + end + +end + diff --git a/lib/webri/server.rb b/lib/webri/server.rb new file mode 100644 index 0000000..6282744 --- /dev/null +++ b/lib/webri/server.rb @@ -0,0 +1,292 @@ +require 'erb' +require 'yaml' +require 'cgi' +require 'webri/opesc' +require 'webri/heirarchy' + +module WebRI + + # Server class and base class for Generator. + # + class Server + + # Reference to CGI Service + #attr :cgi + + # Reference to RI Service + attr :service + + # Directory in which to store generated html files + #attr :output + + # Title of docs to add to webpage header. + attr :title + + # + def initialize(service, options={}) + #@cgi = {} #CGI.new('html4') + @service = service + @templates = {} + + @title = options[:title] + end + + # + def directory + @directory ||= File.dirname(__FILE__) + end + + # + def heirarchy + @heirarchy ||=( + ns = Heirarchy.new(nil) + service.names.each do |m| + if m.index('#') + type = :instance + space, method = m.split('#') + spaces = space.split('::').collect{|s| s.to_sym } + method = method.to_sym + elsif m.index('::') + type = :class + spaces = m.split('::').collect{|s| s.to_sym } + if spaces.last.to_s =~ /^[a-z]/ + method = spaces.pop + else + next # what to do about class/module ? + end + else + next # what to do abot class/module ? + end + + memo = ns + spaces.each do |space| + memo[space] ||= Heirarchy.new(space, memo) + memo = memo[space] + end + + if type == :class + memo.class_methods << method + else + memo.instance_methods << method + end + end + ns + ) + end + + # + def tree + #%[<iframe src="tree.html"></iframe>] + @tree ||= heirarchy.to_html + end + + # + def lookup(path) + entry = WebRI.path_to_entry(path) + if entry + html = service.info(entry) + html = autolink(html, entry) + + #term = AnsiSys::Terminal.new.echo(ansi) + #html = term.render(:html) #=> HTML fragment + #html = ERB::Util.html_escape(html) + + html = "#{html}<br/><br/>" + else + html = "<h1>ERROR</h1>" + end + return html + end + + # Search for certain pattersn within the HTML and subs in hyperlinks. + # + # Eg. + # + # <h2>Instance methods:</h2> + # current_content, directory, generate, generate_recurse, generate_tree + # + def autolink(html, entry) + link = entry.gsub('::','/') + + re = Regexp.new(Regexp.escape(entry), Regexp::MULTILINE) + if md = re.match(html) + title = %[<a class="link title" href="javascript: lookup_static(this, '#{link}.html');">#{md[0]}</a>] + html[md.begin(0)...md.end(0)] = title + end + + # class methods + re = Regexp.new(Regexp.escape("<h2>Class methods:</h2>") + "(.*?)" + Regexp.escape("<"), Regexp::MULTILINE) + if md = re.match(html) + meths = md[1].split(",").map{|m| m.strip} + meths = meths.map{|m| %[<a class="link" href="javascript: lookup_static(this, '#{link}/c-#{m}.html');">#{m}</a>] } + html[md.begin(1)...md.end(1)] = meths.join(", ") + end + + # instance methods + re = Regexp.new(Regexp.escape("<h2>Instance methods:</h2>") + "(.*?)" + Regexp.escape("<"), Regexp::MULTILINE) + if md = re.match(html) + meths = md[1].split(",").map{|m| m.strip} + meths = meths.map{|m| %[<a class="link" href="javascript: lookup_static(this, '#{link}/i-#{m}.html');">#{m}</a>] } + html[md.begin(1)...md.end(1)] = meths.join(", ") + end + + return html + end + + # + def template(name) + @templates[name] ||= File.read(File.join(directory, 'templates', name + '.html')) + end + + # + #def to_html + # #filetext = File.read(File.join(File.dirname(__FILE__), 'template.rhtml')) + # template = ERB.new(template_source) + # template.result(binding) + # #heirarchy.to_html + #end + + # + def render(source) + template = ERB.new(source) + template.result(binding) + end + + # + #def page_header + # render(template('header')) + #end + + # + #def page_tree + # render(template('tree')) + #end + + # + def index + render(template('index')) + end + + # + #def page_main + # render(template('main')) + #end + +=begin + # generate webpages + def generate(output=".") + @output = File.expand_path(output) + # traverse the the hierarchy + + generate_support_files + + #generate_recurse(heirarchy) + +# heirarchy.class_methods.each do |name| +# p name +# end + +# heirarchy.instance_methods.each do |name| +# p name +# end + + heirarchy.subspaces.each do |name, entry| + #p name, entry + generate_recurse(entry) + end + end + + # + def generate_recurse(entry) + keyword = entry.full_name + + if keyword + puts keyword + @current_content = service.info(keyword) #lookup(keyword) + else + keyword = '' + @current_content = "Welcome" + end + + file = entry.file_name + '.html' + file = File.join(output, file) + + #file = keyword + #file = file.gsub('::', '--') + #file = file.gsub('.' , '--') + #file = file.gsub('#' , '-') + #file = File.join(output, file + '.html') + + write(file, service.info(keyword)) + #File.open(file, 'w') { |f| f << service.info(keyword) } #to_html } + + entry.class_methods.each do |name| + mname = "#{entry.full_name}.#{name}" + mfile = File.join(output, "#{entry.file_name}--#{esc(name)}.html") + write(mfile, service.info(mname)) + #File.open(mfile, 'w') { |f| f << service.info(mname) } #to_html } + end + + entry.instance_methods.each do |name| + mname = "#{entry.full_name}.#{name}" + mfile = File.join(output, "#{entry.file_name}-#{esc(name)}.html") + write(mfile, service.info(mname)) + #File.open(mfile, 'w') { |f| f << service.info(mname) } #to_html } + end + + entry.subspaces.each do |child_name, child_entry| + next if child_entry == entry + @directory_depth += 1 + generate_recurse(child_entry) + @directory_depth -= 1 + end + end + + # + def write(file, text) + puts mfile + File.open(file, 'w') { |f| f << text.to_s } + end + + # + def generate_support_files + FileUtils.mkdir_p(output) + + # generate index file + file = File.join(output, 'index.html') + File.open(file, 'w') { |f| f << to_html } + + # copy css file + dir = File.join(directory,'public','css') + FileUtils.cp_r(dir, output) + + # copy images + dir = File.join(directory,'public','img') + FileUtils.cp_r(dir, output) + + # copy scripts + dir = File.join(directory,'public','js') + FileUtils.cp_r(dir, output) + end +=end + + # + def current_content + @current_content + end + + # + def esc(text) + OpEsc.escape(text.to_s) + #CGI.escape(text.to_s).gsub('-','%2D') + end + + # + def self.esc(text) + OpEsc.escape(text.to_s) + #CGI.escape(text.to_s).gsub('-','%2D') + end + end #class Engine + +end #module WebRI + diff --git a/lib/webri/templates/index.html b/lib/webri/templates/index.html new file mode 100644 index 0000000..9fc543e --- /dev/null +++ b/lib/webri/templates/index.html @@ -0,0 +1,62 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html> + +<head> + <title>WebRI</title> + + <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" /> + + <link rel="icon" href="assets/img/ruby_logo.png" type="image/x-icon"> + + <link href="assets/css/style.css" rel="stylesheet" type="text/css"> + + <SCRIPT src="assets/js/jquery.js" type="text/javascript"></SCRIPT> + <SCRIPT src="assets/js/ri.jquery.js" type="text/javascript"></SCRIPT> + + <script type="text/javascript"> + $(document).ready(function(){ + //$("#screenFrame").css('height', $(window).height() + 'px'); + resizePage(); + }); + </script> +</head> + +<body> + +<div id="screen"> + + <div id="header"> + <div class="small ad"> + </div> + <div> + <img src="assets/img/ruby_logo.png" align="left"/> + <h1>WebRI <span class="small">&copy; 2008 <a href="http://tigerops.org">TigerOps</a></span></h1> + <h2><%= title %></h2> + </div> + </div> + + <div style="clear: both;"></div> + + <div id="tree"> + <%= tree %> + </div> + + <div id="main"> + <h1>Welcome to WebRI</h1> + <h2>Webrick-based RI Browser</h2> + + <p> + WebRI provides a web-based interface + to RI documentation. + </p> + + <p> + WebRI &copy; 2008 <a href="http://tigerops.org">TigerOps</a> + </p> + </div> + +</div> + +</body> +</html> + diff --git a/meta/abstract b/meta/abstract new file mode 100644 index 0000000..8d6d5fb --- /dev/null +++ b/meta/abstract @@ -0,0 +1,4 @@ +WebRI is Webrick-based RI browser. It makes it fairly +convenient to browse API documetation in hierachical +fashion. + diff --git a/meta/authors b/meta/authors new file mode 100644 index 0000000..22ee64e --- /dev/null +++ b/meta/authors @@ -0,0 +1 @@ +Trans <[email protected]> diff --git a/meta/contact b/meta/contact new file mode 100644 index 0000000..04685cc --- /dev/null +++ b/meta/contact @@ -0,0 +1 @@ [email protected] diff --git a/meta/created b/meta/created new file mode 100644 index 0000000..12b1bf6 --- /dev/null +++ b/meta/created @@ -0,0 +1 @@ +2008-02-21 diff --git a/meta/homepage b/meta/homepage new file mode 100644 index 0000000..3911fd1 --- /dev/null +++ b/meta/homepage @@ -0,0 +1 @@ +http://webri.rubyforge.org diff --git a/meta/license b/meta/license new file mode 100644 index 0000000..f629984 --- /dev/null +++ b/meta/license @@ -0,0 +1 @@ +Ruby License diff --git a/meta/loadpath b/meta/loadpath new file mode 100644 index 0000000..7f8713f --- /dev/null +++ b/meta/loadpath @@ -0,0 +1,2 @@ +lib +plug diff --git a/meta/package b/meta/package new file mode 100644 index 0000000..5e1d9f2 --- /dev/null +++ b/meta/package @@ -0,0 +1 @@ +webri diff --git a/meta/summary b/meta/summary new file mode 100644 index 0000000..5d588af --- /dev/null +++ b/meta/summary @@ -0,0 +1 @@ +Web-based RI browser. diff --git a/meta/title b/meta/title new file mode 100644 index 0000000..923575b --- /dev/null +++ b/meta/title @@ -0,0 +1 @@ +WebRI diff --git a/meta/version b/meta/version new file mode 100644 index 0000000..5a2a580 --- /dev/null +++ b/meta/version @@ -0,0 +1 @@ +0.6 diff --git a/plug/webri.reap/plugin.rb b/plug/webri.reap/plugin.rb new file mode 100644 index 0000000..aadca6a --- /dev/null +++ b/plug/webri.reap/plugin.rb @@ -0,0 +1,110 @@ +module Reap +module Plugins + + # = WebRI Documentation Plugin + # + # The webri documentation plugin provides services for + # generating webri documentation. + # + # By default it generates the documentaiton at doc/webri. + # + # This plugin provides three services for both the +main+ and +site+ pipelines. + # + # * +webri+ - Create webri docs + # * +reset+ - Reset webri docs + # * +clean+ - Remove webri docs + # + class WebRI < Plugin + + pipeline :main, :document + pipeline :site, :document + + pipeline :main, :clean + pipeline :site, :clean + + pipeline :main, :reset + pipeline :site, :reset + + #available do |project| + # !project.metadata.loadpath.empty? + #end + + # Default location to store ri documentation files. + DEFAULT_OUTPUT = "doc/webri" + + # + DEFAULT_RIDOC = "doc/ri" + + # + def initialize_defaults + @title = metadata.title + @ridoc = DEFAULT_RIDOC + @output = DEFAULT_OUTPUT + end + + # Title of documents. Defaults to general metadata title field. + attr_accessor :title + + # Where to save rdoc files (doc/webri). + attr_accessor :output + + # Location of ri docs. Defaults to doc/ri. + # These files must be preset for this plugin to work. + attr_accessor :ridoc + + # In case one is inclined to #ridoc plural. + alias_accessor :ridocs + + # Generate ri documentation. This utilizes + # rdoc to produce the appropriate files. + # + def document + output = self.output + + #cmdopts = {} + #cmdopts['o'] = output + + #input = files #.collect do |i| + # dir?(i) ? File.join(i,'**','*') : i + #end + + if outofdate?(output, ridoc) or force? + rm_r(output) if exist?(output) and safe?(output) # remove old webri docs + + status "Generating #{output} ..." + + #vector = [ridoc, cmdopts] + #if verbose? + sh "webri -o #{output} #{ridoc}" + #else + # silently do + # sh "webri #{vector.to_console}" + # end + #end + else + report "webri docs are current (#{output.sub(Dir.pwd,'')})" + end + end + + # Set the output directory's mtime to furthest time in past. + # This "marks" the documentation as out-of-date. + def reset + if File.directory?(output) + File.utime(0,0,self.output) + report "reset #{output}" + end + end + + # Remove ri products. + def clean + if File.directory?(output) + rm_r(output) + status "Removed #{output}" #unless dryrun? + end + end + + end + +end +end + diff --git a/site/.rsync-filter b/site/.rsync-filter new file mode 100644 index 0000000..ed0ba18 --- /dev/null +++ b/site/.rsync-filter @@ -0,0 +1,7 @@ +- .svn +- scrap +P usage +P statcvs +P statsvn +P robot.txt +P wiki diff --git a/site/ads/.svn/entries b/site/ads/.svn/entries new file mode 100644 index 0000000..0f540b6 --- /dev/null +++ b/site/ads/.svn/entries @@ -0,0 +1,16 @@ +8 + +dir +125 +svn+ssh://[email protected]/var/svn/blow/trunk/doc/ads +svn+ssh://[email protected]/var/svn/blow + + + +2008-02-04T04:44:41.561358Z +117 +transami + + +svn:special svn:externals svn:needs-lock + diff --git a/site/ads/.svn/format b/site/ads/.svn/format new file mode 100644 index 0000000..45a4fb7 --- /dev/null +++ b/site/ads/.svn/format @@ -0,0 +1 @@ +8 diff --git a/site/ads/rdoc.html b/site/ads/rdoc.html new file mode 100644 index 0000000..95aba5b --- /dev/null +++ b/site/ads/rdoc.html @@ -0,0 +1,12 @@ +<div style="position: absolute; top: 5px; right: 10px;"> + <script type="text/javascript"><!-- + google_ad_client = "pub-1126154564663472"; + //BLOW 234x60 + google_ad_slot = "6480217558"; + google_ad_width = 234; + google_ad_height = 60; + //--></script> + <script type="text/javascript" + src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> + </script> +</div> diff --git a/site/img/.svn/entries b/site/img/.svn/entries new file mode 100644 index 0000000..86c98bf --- /dev/null +++ b/site/img/.svn/entries @@ -0,0 +1,41 @@ +8 + +dir +125 +svn+ssh://[email protected]/var/svn/blow/trunk/doc/img +svn+ssh://[email protected]/var/svn/blow + + + +2008-01-20T17:19:17.698871Z +112 +transami + + +svn:special svn:externals svn:needs-lock + + + + + + + + + + + +84ac32e9-6cf0-4922-9023-e1bc86e71266 + +bubble.png +file + + + + +2008-01-27T17:01:08.000000Z +71cb6003c26d359d5ce25739e3bee193 +2007-07-31T21:12:23.499259Z +1 +transami +has-props + diff --git a/site/img/.svn/format b/site/img/.svn/format new file mode 100644 index 0000000..45a4fb7 --- /dev/null +++ b/site/img/.svn/format @@ -0,0 +1 @@ +8 diff --git a/site/img/.svn/prop-base/bubble.png.svn-base b/site/img/.svn/prop-base/bubble.png.svn-base new file mode 100644 index 0000000..5e9587e --- /dev/null +++ b/site/img/.svn/prop-base/bubble.png.svn-base @@ -0,0 +1,5 @@ +K 13 +svn:mime-type +V 24 +application/octet-stream +END diff --git a/site/img/.svn/text-base/bubble.png.svn-base b/site/img/.svn/text-base/bubble.png.svn-base new file mode 100644 index 0000000..4c69365 Binary files /dev/null and b/site/img/.svn/text-base/bubble.png.svn-base differ diff --git a/site/img/ruby-md.png b/site/img/ruby-md.png new file mode 100644 index 0000000..e5642df Binary files /dev/null and b/site/img/ruby-md.png differ diff --git a/site/img/ruby-sm.png b/site/img/ruby-sm.png new file mode 100644 index 0000000..bc02dfb Binary files /dev/null and b/site/img/ruby-sm.png differ diff --git a/site/img/ruby.png b/site/img/ruby.png new file mode 100644 index 0000000..797167a Binary files /dev/null and b/site/img/ruby.png differ diff --git a/site/img/tiger-sm.png b/site/img/tiger-sm.png new file mode 100644 index 0000000..751ba5b Binary files /dev/null and b/site/img/tiger-sm.png differ diff --git a/site/img/tiger_logo.png b/site/img/tiger_logo.png new file mode 100644 index 0000000..60d0fbb Binary files /dev/null and b/site/img/tiger_logo.png differ diff --git a/site/index.html b/site/index.html new file mode 100644 index 0000000..7e77640 --- /dev/null +++ b/site/index.html @@ -0,0 +1,181 @@ + +<html> + +<head> + <title>WebRI</title> + + <link href="style.css" rel="stylesheet" type="text/css"/> + <link href="img/ruby-sm.png" rel="icon"/> + + <META NAME="DESCRIPTION" CONTENT="Web-based ri documentation browser."> + <META NAME="KEYWORDS" CONTENT="documentation, ri, rdoc"> +</head> + +<body> + +<div class="container"> + + <div class="content"> + + <div class="header"> + <div class="title">WebRI</div> + + <div class="about"> + Browse Object Heirachies the Easy Way + </div> + + <div class="warhol"> + </div> + </div> + + <div style="float: right; margin-top: -60px; padding: 10px; font-weight: bold; color: #222;"> + A <a href="http://tigerops.org"><img src="img/tiger_logo.png" align="absmiddle"/></a> PROJECT + </div> + + <div class="menu"> + <!-- &lt;<a href="http://tigerops.rubyforge.org/">Homepage</a>&gt; --> + <a href="rdoc/index.html">Documentation</a> &middot; + <a href="http://rubyforge.org/frs/?group_id=6278">Download</a> &middot; + <a href="http://rubyforge.org/projects/webri">Development</a> + </div> + + <h2>Introduction</h2> + + <p> + WebRI can be used to browse the entire installed object system --eveything + documented in one of the central RI locations. Just run it from the command line. + </p> + + <pre> + $ webri + </pre> + + <p> + WebRI can also be used (and this is probably more useful) to browse per-project + RI documentation. Simply generate the RI docs by navigating to the projects + root directory and running: + </p> + + <pre> + $ rdoc --ri --op "doc/ri" lib + </pre> + + <p> + Sometimes a package will include a convenience script for generating these. + Try running 'rake -T', or look for a 'script/' or 'task/' executable that does + the job. Usually the generated documentation is placed in either ri/ or doc/ri/. + I will use doc/ri/ in the following example, since that is my preference. Adjust + your directory as needed. + </p> + + <p> + Now run: + </p> + + <pre> + $ webri doc/ri + </pre> + + <p> + You will see a Webrick server start up, informing you of the port being used. + </p> + + <pre> + [2008-03-28 12:11:16] INFO WEBrick 1.3.1 + [2008-03-28 12:11:16] INFO ruby 1.8.6 (2007-06-07) [x86_64-linux] + [2008-03-28 12:11:21] INFO WEBrick::HTTPServer#start: pid=8870 port=8888 + </pre> + + <p> + In this example we see the port is the default 8888. Simply open your browser and + navigate to: + </p> + + <pre> + http://localhost:8888/ + </pre> + + <p> + On the left side of the screen you will see a navigation tree, and the right side + contans an infromation panel. + </p> + + + <h2>Installation</h2> + + <p> + Installing the RubyGem is of course straight forward. + </p> + + <pre> + sudo gem install webri + </pre> + + <p> + Manual installation is provided via setup.rb. + </p> + + + <h2>Development</h2> + + <p> + WebRI is a <a href="http://tigerops.org">TigerOps</a> project. Developement is hosted + by Rubyforge <a href="http://rubyforge.org/projects/webri/">here</a>. + </p> + + <p>You can use gitweb to <a href="http://webri.rubyforge.org/git?p=webri.git;a=tree">browse the 'webri' repository</a>.</p> + + <p>To pull the 'webri' repository anonymously, use:</p> + + <pre> + git clone git://rubyforge.org/webri.git + </pre> + + <p>Developers: You can push to the 'webri' repository using:</p> + + <pre> + [email protected]:webri.git + </pre> + + <p>Please contact <b>7rans</b> if you'd like to join the development team.</p> + + </div> + + <br/><br/> + + <div style="text-align: center; border-top: 1px solid #ccc; padding: 40px 0px;"> + <script type="text/javascript"><!-- + google_ad_client = "pub-1126154564663472"; + /* TIGER 728x90 10/28/08 */ + google_ad_slot = "2386645975"; + google_ad_width = 728; + google_ad_height = 90; + //--> + </script> + <script type="text/javascript" + src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> + </script> + <!-- <iframe src="http://tigerops.org/assets/adverts/banner-900-1.html" scrolling="no"></frame> --> + </div> + + + <div class="copyright"> + <br/><br/> + <span style="color: #EF0040;">WebRi</span>, Copyright (c) 2008 Tiger Ops + <br/><br/> + WebRI is distributed under the terms of the Ruby license. <br/> + <br/><br/> + Other TigerOps Projects<br/><br/> + <a href="http://facets.rubyforge.org">Facets</a> &middot; + <a href="http://quarry.rubyforge.org">Quarry</a> &middot; + <a href="http://reap.rubyforge.org">Reap</a> &middot; + <a href="http://stick.rubyforge.org">Stick</a> &middot; + <a href="http://english.rubyforge.org">English</a> + </div> + + <br/><br/> + +</div> + +</body> +</html> diff --git a/site/rdoc b/site/rdoc new file mode 120000 index 0000000..9e284c6 --- /dev/null +++ b/site/rdoc @@ -0,0 +1 @@ +../doc/rdoc \ No newline at end of file diff --git a/site/style.css b/site/style.css new file mode 100644 index 0000000..b352298 --- /dev/null +++ b/site/style.css @@ -0,0 +1,178 @@ +* { + padding : 0; + margin : 0; + font-family : sans-serif; +} + +body { + color : black; + background : white; + text-align : center; + position : relative; + font-size : 10px; +} + +p { + text-align : justify; + font-size : 12px; + color : #111111; + font-weight : normal; + margin : 10px 0px 10px 0px; + line-height : 1.5em; +} + +a { + color: #EF0040; +} + +img { + border: none; +} + +pre { + font-family : monospace; + color : #F00060; + background : #efefef; + margin-top : 15px; + margin-bottom : 15px; + font-size : 1em; + font-weight : bold; + line-height : 1.5em; + padding-top : 15px; + text-align : left; +} + +h1 { + font-size: 42px; +} + +h2 { + font-size: 36px; + text-align: left; + margin-top: 30px; +} + +h3 { + text-align: left; + margin-top: 20px; +} + +td { + vertical-align: top; +} + +.container { + width : 730px; + margin : 0 auto; + position : relative; +} + +.master { + background: white; + border: 0px solid #999999; +} + +.aside { + width: 164px; + padding: 20px; + text-align: center; + background: white; + border: 1px solid #dddddd; + margin-top: 20px; +} + +.aside a { + color: #EF0040; + font-weight: bold; +} + +.aside p { + text-align: center; +} + +.content { + background: white; + padding-right: 20px; + padding-top: 20px; +} + +.header { + margin-bottom: 5px; + text-align: left; + border: 1px solid red; +} + +.title { + color: #aaaaaa; + font-size: 64px; + padding: 20px; + padding-bottom: 10px; +} + +.subtitle { + color: white; + font-size: 16px; +} + +.about { + margin: 0 0 0 0; + margin-bottom: 10px; + text-align: left; + font-size: 20pt; + font-weight: bold; + color: #cc0055; + padding-left: 20px; + padding-bottom: 20px; +} + +.warhol { + height: 100px; + background: url(img/ruby-md.png) -50px top; + font-weight: bold; + text-align: center; +} + +.menu { + padding : 5px 10px; + color : orange; + font-size : 12px; + text-align : left; +} + +.menu a { + font-size: 1em; + font-weight: bold; + color: red; + text-decoration: none; +} + +.menu a:hover { + text-decoration: underline; +} + +.ad { + border : 0px solid white; + text-align : center; +} + +.invert { + text-align : left; + color : white; + margin : 0; + padding : 15px 15px 15px 15px; + background : black; +} + +.invert p { + text-align : left; + color : white; +} + +.copyright { + padding : 5px; + text-align : center; + color : gray; + font-size : 1em; + border-top: 1px solid #ccc; +} + diff --git a/task/box.syckle b/task/box.syckle new file mode 100644 index 0000000..9349efe --- /dev/null +++ b/task/box.syckle @@ -0,0 +1,7 @@ +--- +box: + service : Box + types : [gem, tar] + manifest : true + include : [bin, lib, meta, test, "[A-Z]*" ] + diff --git a/task/email.syckle b/task/email.syckle new file mode 100644 index 0000000..d603db2 --- /dev/null +++ b/task/email.syckle @@ -0,0 +1,25 @@ +--- +email: + service : Email + file : ~ + subject : ~ + mailto : [email protected] + from : ENV[EMAIL_ACCOUNT] + server : ENV[EMAIL_SERVER] + port : ENV[EMAIL_PORT] + account : ENV[EMAIL_ACCOUNT] + domain : ENV[EMAIL_DOMAIN] + login : ENV[EMAIL_LOGIN] + secure : ENV[EMAIL_SECURE] + active : true + + #service : Email + #mailto : [email protected] + #from : [email protected] + #server : mail.tigerops.org + #port : 25 + #domain : tigerops.org + #account : [email protected] + #secure : false + #login : login + diff --git a/task/notes.syckle b/task/notes.syckle new file mode 100644 index 0000000..8fbd9b0 --- /dev/null +++ b/task/notes.syckle @@ -0,0 +1,4 @@ +--- +notes: + service: Notes + diff --git a/task/rdoc.syckle b/task/rdoc.syckle new file mode 100644 index 0000000..9f2e13b --- /dev/null +++ b/task/rdoc.syckle @@ -0,0 +1,6 @@ +--- +rdoc: + service : RDoc + template : ~ + inline : true + exclude : [ lib/webri/public ] diff --git a/task/ridoc.syckle b/task/ridoc.syckle new file mode 100644 index 0000000..ea5abb9 --- /dev/null +++ b/task/ridoc.syckle @@ -0,0 +1,5 @@ +--- +ridoc: + service: RIDoc + exclude : [ lib/webri/public ] + diff --git a/task/rubyforge.syckle b/task/rubyforge.syckle new file mode 100644 index 0000000..bcbc57b --- /dev/null +++ b/task/rubyforge.syckle @@ -0,0 +1,6 @@ +--- +rubyforge: + service : Rubyforge + unixname : webri + groupid : 6278 + diff --git a/task/stats.syckle b/task/stats.syckle new file mode 100644 index 0000000..bf94112 --- /dev/null +++ b/task/stats.syckle @@ -0,0 +1,5 @@ +--- +stats: + service: Stats + active : true + diff --git a/task/testrb.syckle b/task/testrb.syckle new file mode 100644 index 0000000..d4d91f8 --- /dev/null +++ b/task/testrb.syckle @@ -0,0 +1,5 @@ +--- +testrb: + service: testrb + active : false + diff --git a/work/ansisys.rb b/work/ansisys.rb new file mode 100644 index 0000000..be70bf3 --- /dev/null +++ b/work/ansisys.rb @@ -0,0 +1,751 @@ +# +# = ansisys.rb +# ANSI terminal emulator +# based on http://en.wikipedia.org/wiki/ANSI_escape_code +# +# Copyright:: Copyright (C) 2007 zunda <zunda at freeshell.org> +# License:: GPL - GPL3 or later +# +require 'webrick' + +module AnsiSys + module VERSION #:nodoc: + MAJOR = 0 + MINOR = 8 + TINY = 3 + + STRING = [MAJOR, MINOR, TINY].join('.') + end + + module CSSFormatter + # make a CSS style-let from a Hash of CSS settings + def hash_to_styles(hash, separator = '; ') + unless hash.empty? + return hash.map{|e| "#{e[0]}: #{e[1].join(' ')}"}.join(separator) + else + return nil + end + end + module_function :hash_to_styles + end + + module Guess + # returns a $KCODE string according to guessed encoding + def self.kcode(data) + case NKF.guess(data) + when NKF::EUC + kcode = 'e' + when NKF::SJIS + kcode = 's' + when NKF::UTF8 + kcode = 'u' + else + kcode = 'n' + end + return kcode + end + end + + class AnsiSysError < StandardError; end + + class Lexer + # Control Sequence Introducer and following code + PARAMETER_AND_LETTER = /\A([\d;]*)([[:alpha:]])/o + CODE_EQUIVALENT = { + "\r" => ['B'], + "\n" => ['E'], + } + + attr_reader :buffer + + # _csis_ is an Array of Code Sequence Introducers + # which can be \e[, \x9B, or both + def initialize(csis = ["\x1b["]) # CSI can also be "\x9B" + @code_start_re = Regexp.union(*(CODE_EQUIVALENT.keys + csis)) + @buffer = '' + end + + # add the String (clear text with some or no escape sequences) to buffer + def push(string) + @buffer += string + end + + # returns array of tokens while deleting the tokenized part from buffer + def lex! + r = Array.new + @buffer.gsub!(/(?:\r\n|\n\r)/, "\n") + while @code_start_re =~ @buffer + r << [:string, $`] unless $`.empty? + if CODE_EQUIVALENT.has_key?($&) + CODE_EQUIVALENT[$&].each do |c| + r << [:code, c] + end + @buffer = $' + else + csi = $& + residual = $' + if PARAMETER_AND_LETTER =~ residual + r << [:code, $&] + @buffer = $' + else + @buffer = csi + residual + return r + end + end + end + r << [:string, @buffer] unless @buffer.empty? + @buffer = '' + return r + end + end + + class Characters + # widths of characters + WIDTHS = { + "\t" => 8, + } + + attr_reader :string # clear text + attr_reader :sgr # Select Graphic Rendition associated with the text + + def initialize(string, sgr) + @string = string + @sgr = sgr + end + + # echo the string onto the _screen_ with initial cursor as _cursor_ + # _cursor_ position will be changed as the string is echoed + def echo_on(screen, cursor, kcode = nil) + each_char(kcode) do |c| + w = width(c) + cursor.fit!(w) + screen.write(c, w, cursor.cur_col, cursor.cur_row, @sgr.dup) + cursor.advance!(w) + end + return self + end + + private + # iterator on each character + def each_char(kcode, &block) + @string.scan(Regexp.new('.', nil, kcode)).each do |c| + yield(c) + end + end + + # width of a character + def width(char) + if WIDTHS.has_key?(char) + return WIDTHS[char] + end + case char.size # expecting number of bytes + when 1 + return 1 + else + return 2 + end + end + end + + class Cursor + # Escape sequence codes processed in this Class + CODE_LETTERS = %w(A B C D E F G H f) + + attr_reader :cur_col # current column number (1-) + attr_reader :cur_row # current row number (1-) + attr_accessor :max_col # maximum column number + attr_accessor :max_row # maximum row number + + def initialize(cur_col = 1, cur_row = 1, max_col = 80, max_row = 25) + @cur_col = cur_col + @cur_row = cur_row + @max_col = max_col + @max_row = max_row + end + + # applies self an escape sequence code that ends with _letter_ as String + # and with some _pars_ as Integers + def apply_code!(letter, *pars) + case letter + when 'A' + @cur_row -= pars[0] ? pars[0] : 1 + @cur_row = @max_row if @max_row and @cur_row > @max_row + when 'B' + @cur_row += pars[0] ? pars[0] : 1 + @cur_row = @max_row if @max_row and @cur_row > @max_row + when 'C' + @cur_col += pars[0] ? pars[0] : 1 + when 'D' + @cur_col -= pars[0] ? pars[0] : 1 + when 'E' + @cur_row += pars[0] ? pars[0] : 1 + @cur_col = 1 + @max_row = @cur_row if @max_row and @cur_row > @max_row + when 'F' + @cur_row -= pars[0] ? pars[0] : 1 + @cur_col = 1 + @max_row = @cur_row if @max_row and @cur_row > @max_row + when 'G' + @cur_col = pars[0] ? pars[0] : 1 + when 'H' + @cur_row = pars[0] ? pars[0] : 1 + @cur_col = pars[1] ? pars[1] : 1 + @max_row = @cur_row if @max_row and @cur_row > @max_row + when 'f' + @cur_row = pars[0] ? pars[0] : 1 + @cur_col = pars[1] ? pars[1] : 1 + @max_row = @cur_row if @max_row and @cur_row > @max_row + end + if @cur_row < 1 + @cur_row = 1 + end + if @cur_col < 1 + @cur_col = 1 + elsif @cur_col > @max_col + @cur_col = @max_col + end + return self + end + + # changes current location for a character with _width_ to be echoed + def advance!(width = 1) + r = nil + @cur_col += width + if @cur_col > @max_col + line_feed! + r = "\n" + end + return r + end + + # check if a character with _width_ fits within the maximum columns, + # feed a line if not + def fit!(width = 1) + r = nil + if @cur_col + width > @max_col + 1 + line_feed! + r = "\n" + end + return r + end + + # feed a line + def line_feed! + @cur_col = 1 + @cur_row += 1 + @max_row = @cur_row if @max_row and @cur_row > @max_row + end + end + + # Select Graphic Rendition + class SGR + extend CSSFormatter + + # Escape sequence codes processed in this Class + CODE_LETTERS = %w(m) + + # :normal, :bold, or :faint + attr_reader :intensity + + # :off or :on + attr_reader :italic + + # :none, :single, or :double + attr_reader :underline + + # :off, :slow, or :rapid + attr_reader :blink + + # :positive or :negative + attr_reader :image + + # :off or :on + attr_reader :conceal + + # :black, :red, :green, :yellow, :blue, :magenta, :cyan, or :white + attr_reader :foreground + + # :black, :red, :green, :yellow, :blue, :magenta, :cyan, or :white + attr_reader :background + + def initialize + reset! + end + + # true if all the attributes are same + def ==(other) + instance_variables.each do |ivar| + return false unless instance_eval(ivar) == other.instance_eval(ivar) + end + return true + end + + # resets attributes + def reset! + apply_code!('m', 0) + end + + # applies self an escape sequence code that ends with _letter_ as String + # and with some _pars_ as Integers + def apply_code!(letter = 'm', *pars) + raise AnsiSysError, "Invalid code for SGR: #{letter.inspect}" unless 'm' == letter + pars = [0] unless pars + pars.each do |code| + case code + when 0 + @intensity = :normal + @italic = :off + @underline = :none + @blink = :off + @image = :positive + @conceal = :off + @foreground = :white + @background = :black + when 1..28 + apply_code_table!(code) + when 30..37 + @foreground = COLOR[code - 30] + @intensity = :normal + when 39 + reset! + when 40..47 + @background = COLOR[code - 40] + @intensity = :normal + when 49 + reset! + when 90..97 + @foreground = COLOR[code - 90] + @intensity = :bold + when 99 + reset! + when 100..107 + @background = COLOR[code - 100] + @intensity = :bold + when 109 + reset! + else + raise AnsiSysError, "Invalid SGR code #{code.inspect}" unless CODE.has_key?(code) + end + end + return self + end + + # renders self as :html or :text _format_ - makes a <span> html scriptlet. + # _colors_ can be Screen.default_css_colors(_inverted_, _bright_). + def render(format = :html, position = :prefix, colors = Screen.default_css_colors) + case format + when :html + case position + when :prefix + style_code = css_style(colors) + if style_code + return %Q|<span style="#{style_code}">| + else + return '' + end + when :postfix + style_code = css_style(colors) + if style_code + return '</span>' + else + return '' + end + end + when :text + return '' + end + end + + # CSS stylelet + def css_style(colors = Screen.default_css_colors) + return CSSFormatter.hash_to_styles(css_styles(colors)) + end + + # a Hash of CSS stylelet + def css_styles(colors = Screen.default_css_colors) + r = Hash.new{|h, k| h[k] = Array.new} + # intensity is not (yet) implemented + r['font-style'] << 'italic' if @italic == :on + r['text-decoration'] << 'underline' unless @underline == :none + r['text-decoration'] << 'blink' unless @blink == :off + case @image + when :positive + fg = @foreground + bg = @background + when :negative + fg = @background + bg = @foreground + end + fg = bg if @conceal == :on + r['color'] << colors[@intensity][fg] unless fg == :white + r['background-color'] << colors[@intensity][bg] unless bg == :black + return r + end + + private + def apply_code_table!(code) + raise AnsiSysError, "Invalid SGR code #{code.inspect}" unless CODE.has_key?(code) + ivar, value = CODE[code] + instance_variable_set("@#{ivar}", value) + return self + end + + CODE = { + 1 => [:intensity, :bold], + 2 => [:intensity, :faint], + 3 => [:italic, :on], + 4 => [:underline, :single], + 5 => [:blink, :slow], + 6 => [:blink, :rapid], + 7 => [:image, :negative], + 8 => [:conceal, :on], + 21 => [:underline, :double], + 22 => [:intensity, :normal], + 24 => [:underline, :none], + 25 => [:blink, :off], + 27 => [:image, :positive], + 28 => [:conceal, :off], + } # :nodoc: + + COLOR = { + 0 => :black, + 1 => :red, + 2 => :green, + 3 => :yellow, + 4 => :blue, + 5 => :magenta, + 6 => :cyan, + 7 => :white, + } # :nodoc: + + end + + class Screen + # Escape sequence codes processed in this Class + CODE_LETTERS = %w() # :nodoc: + + def self.default_foreground; :white; end + def self.default_background; :black; end + + # a Hash of color names for each intensity + def self.default_css_colors(inverted = false, bright = false) + r = { + :normal => { + :black => 'black', + :red => 'maroon', + :green => 'green', + :yellow => 'olive', + :blue => 'navy', + :magenta => 'purple', + :cyan => 'teal', + :white => 'silver', + }, + :bold => { + :black => 'gray', + :red => 'red', + :green => 'lime', + :yellow => 'yellow', + :blue => 'blue', + :magenta => 'fuchsia', + :cyan => 'cyan', + :white => 'white' + }, + :faint => { + :black => 'black', + :red => 'maroon', + :green => 'green', + :yellow => 'olive', + :blue => 'navy', + :magenta => 'purple', + :cyan => 'teal', + :white => 'silver', + }, + } + + if bright + r[:bold][:black] = 'black' + [:normal, :faint].each do |i| + r[i] = r[:bold] + end + end + + if inverted + r.each_key do |i| + r[i][:black], r[i][:white] = r[i][:white], r[i][:black] + end + end + + return r + end + + # a Hash of CSS stylelet to be used in <head> + def self.css_styles(colors = Screen.default_css_colors, max_col = nil, max_row = nil) + h = { + 'color' => [colors[:normal][:white]], + 'background-color' => [colors[:normal][:black]], + 'padding' => ['0.5em'], + } + h['width'] = ["#{Float(max_col)/2}em"] if max_col + #h['height'] = ["#{max_row}em"] if max_row # could not find appropriate unit + return h + end + + # CSS stylelet to be used in <head>. + # Takes the same arguments as Screen::css_styles(). + def self.css_style(*args) + return "pre.screen {\n\t" + CSSFormatter.hash_to_styles(self.css_styles(*args), ";\n\t") + ";\n}\n" + end + + # a Hash of keys as rows, + # which each value a Hash of keys columns and each value as + # an Array of character, its width, and associated SGR + attr_reader :lines + + # a Screen + def initialize(colors = Screen.default_css_colors, max_col = nil, max_row = nil) + @colors = colors + @max_col = max_col + @max_row = max_row + @lines = Hash.new{|hash, key| hash[key] = Hash.new} + end + + # CSS stylelet to be used in <head> + def css_style + self.class.css_style(@colors, @max_col, @max_row) + end + + # register the _char_ at a specific location on Screen + def write(char, char_width, col, row, sgr) + @lines[Integer(row)][Integer(col)] = [char, char_width, sgr.dup] + end + + # render the characters into :html or :text + # Class name in CSS can be specified as _css_class_. + # Additional stylelet can be specified as _css_style_. + def render(format = :html, css_class = 'screen', css_style = nil) + result = case format + when :text + '' + when :html + %Q|<pre#{css_class ? %Q[ class="#{css_class}"] : ''}#{css_style ? %Q| style="#{css_style}"| : ''}>\n| + else + raise AnsiSysError, "Invalid format option to render: #{format.inspect}" + end + + unless @lines.keys.empty? + prev_sgr = nil + max_row = @lines.keys.max + (1..max_row).each do |row| + if @lines.has_key?(row) and not @lines[row].keys.empty? + col = 1 + while col <= @lines[row].keys.max + if @lines[row].has_key?(col) and @lines[row][col] + char, width, sgr = @lines[row][col] + if prev_sgr != sgr + result += prev_sgr.render(format, :postfix, @colors) if prev_sgr + result += sgr.render(format, :prefix, @colors) + prev_sgr = sgr + end + case format + when :text + result += char + when :html + result += WEBrick::HTMLUtils.escape(char) + end + col += width + else + result += ' ' + col += 1 + end + end + end + result += "\n" if row < max_row + end + result += prev_sgr.render(format, :postfix, @colors) if prev_sgr + end + + result += case format + when :text + '' + when :html + '</pre>' + end + return result + end + + # applies self an escape sequence code that ends with _letter_ as String + # and with some _pars_ as Integers + def apply_code!(letter, *pars) + return self + end # :nodoc: + end + + class Terminal + # Escape sequence codes processed in this Class + CODE_LETTERS = %w(J K S T n s u) + + # _csis_ is an Array of Code Sequence Introducers + # which can be \e[, \x9B, or both + def initialize(csis = ["\x1b["]) + @lexer = Lexer.new(csis) + @stream = Array.new + end + + # echoes _data_, a String of characters or escape sequences + # to the Terminal. + # This method actually just buffers the echoed data. + def echo(data) + @lexer.push(data) + return self + end + + # CSS stylelet to be used in <head> + def css_style(format = :html, max_col = 80, max_row = nil, colors = Screen.default_css_colors) + case format + when :html + Screen.css_style(colors, max_col, max_row) + when :text + '' + end + end + + # renders the echoed data as _format_ of :html or :text. + # _max_col_, _max_row_ can be specified as Integer. + # _colors_ can be Screen.default_css_colors(_inverted_, _bright_). + def render(format = :html, max_col = 80, max_row = nil, colors = Screen.default_css_colors, css_class = nil, css_style = nil, kcode = nil) + css_class ||= 'screen' + kcode ||= Guess.kcode(@lexer.buffer) + screens = populate(format, max_col, max_row, colors, kcode) + separator = case format + when :html + "\n" + when :text + "\n---\n" + end + return screens.map{|screen| screen.render(format, css_class, css_style)}.join(separator) + end + + # applies self an escape sequence code that ends with _letter_ as String + # and with some _pars_ as Integers + def apply_code!(letter, *pars) + case letter + when 'J' + cur_col = @cursor.cur_col + cur_row = @cursor.cur_row + lines = @screens[-1].lines + if pars.empty? or 0 == pars[0] + rs = lines.keys.select{|r| r > cur_row} + cs = lines[cur_row].keys.select{|c| c >= cur_col} + elsif 1 == pars[0] + rs = lines.keys.select{|r| r < cur_row} + cs = lines[cur_row].keys.select{|c| c <= cur_col} + elsif 2 == pars[0] + rs = lines.keys + cs = [] + @cursor.apply_code!('H', 1, 1) + end + rs.each do |r| + lines.delete(r) + end + cs.each do |c| + lines[cur_row].delete(c) + end + when 'K' + cur_col = @cursor.cur_col + cur_row = @cursor.cur_row + line = @screens[-1].lines[cur_row] + if pars.empty? or 0 == pars[0] + cs = line.keys.select{|c| c >= cur_col} + elsif 1 == pars[0] + cs = line.keys.select{|c| c <= cur_col} + elsif 2 == pars[0] + cs = line.keys + end + cs.each do |c| + line.delete(c) + end + when 'S' + lines = @screens[-1].lines + n = pars.empty? ? 1 : pars[0] + n.times do |l| + lines.delete(l) + end + rs = lines.keys.sort + rs.each do |r| + lines[r-n] = lines[r] + lines.delete(r) + end + @cursor.apply_code!('H', rs[-1] - n + 1, 1) + when 'T' + lines = @screens[-1].lines + n = pars.empty? ? 1 : pars[0] + rs = lines.keys.sort_by{|a| -a} # sort.reverse + rs.each do |r| + lines[r+n] = lines[r] + lines.delete(r) + end + @cursor.apply_code!('H', rs[-1] - n + 1, 1) + when 's' + @stored_cursor = @cursor.dup + when 'u' + @cursor = @stored_cursor.dup if @stored_cursor + end + + return self + end + + private + def populate(format = :html, max_col = 80, max_row = nil, colors = Screen.default_css_colors, kcode = nil) + @cursor = Cursor.new(1, 1, max_col, max_row) + @stored_cursor = nil + @screens = [Screen.new(colors, max_col, max_row)] + @sgr = SGR.new + @stream += @lexer.lex! + @stream.each do |type, payload| + case type + when :string + Characters.new(payload, @sgr).echo_on(@screens[-1], @cursor, kcode) + when :code + unless Lexer::PARAMETER_AND_LETTER =~ payload + raise AnsiSysError, "Invalid code: #{payload.inspect}" + end + letter = $2 + pars = $1.split(/;/).map{|i| i.to_i} + applied = false + [@sgr, @cursor, @screens[-1], self].each do |recv| + if recv.class.const_get(:CODE_LETTERS).include?(letter) + recv.apply_code!(letter, *pars) + applied = true + end + end + raise AnsiSysError, "Invalid code or not implemented: #{payload.inspect}" unless applied + end + end + return @screens + end + end +end + +if defined?(Hiki) and Hiki::Plugin == self.class + # a Hiki plugin method to render a file of text with ANSI escape sequences. + # Attached file name should be specified as _file_name_. + # _max_row_ can be specified. + # _invert_ and _bright_ can be specified to change colors. + # _page_ can be specified to show a file attached to another page. + def ansi_screen(file_name, max_col = 80, invert = false, bright = true, page = @page) + return '' unless file_name =~ /\.(txt|rd|rb|c|pl|py|sh|java|html|htm|css|xml|xsl|sql|yaml)\z/i + page_file_name = "#{page.untaint.escape}/#{file_name.untaint.escape}" + path = "#{@conf.cache_path}/attach/#{page_file_name}" + unless File.exists?(path) + raise PluginError, "No such file:#{page_file_name}" + end + data = File.open(path){|f| f.read}.to_euc + + colors = AnsiSys::Screen.default_css_colors(invert, bright) + styles = AnsiSys::CSSFormatter.hash_to_styles(AnsiSys::Screen.css_styles(colors, max_col, nil), '; ') + + terminal = AnsiSys::Terminal.new + terminal.echo(data) + return terminal.render(:html, max_col, nil, colors, 'screen', styles, 'e') + "\n" + end +end diff --git a/work/css/tree_blue/images/collapsable-last.gif b/work/css/tree_blue/images/collapsable-last.gif new file mode 100644 index 0000000..de595b3 Binary files /dev/null and b/work/css/tree_blue/images/collapsable-last.gif differ diff --git a/work/css/tree_blue/images/collapsable.gif b/work/css/tree_blue/images/collapsable.gif new file mode 100644 index 0000000..8f5283c Binary files /dev/null and b/work/css/tree_blue/images/collapsable.gif differ diff --git a/work/css/tree_blue/images/expandable-last.gif b/work/css/tree_blue/images/expandable-last.gif new file mode 100644 index 0000000..1696e63 Binary files /dev/null and b/work/css/tree_blue/images/expandable-last.gif differ diff --git a/work/css/tree_blue/images/expandable.gif b/work/css/tree_blue/images/expandable.gif new file mode 100644 index 0000000..ef401bb Binary files /dev/null and b/work/css/tree_blue/images/expandable.gif differ diff --git a/work/css/tree_blue/images/leaf-last.gif b/work/css/tree_blue/images/leaf-last.gif new file mode 100644 index 0000000..e5d301d Binary files /dev/null and b/work/css/tree_blue/images/leaf-last.gif differ diff --git a/work/css/tree_blue/images/leaf.gif b/work/css/tree_blue/images/leaf.gif new file mode 100644 index 0000000..2f5c2ef Binary files /dev/null and b/work/css/tree_blue/images/leaf.gif differ diff --git a/work/css/tree_blue/images/root.gif b/work/css/tree_blue/images/root.gif new file mode 100644 index 0000000..27012fb Binary files /dev/null and b/work/css/tree_blue/images/root.gif differ diff --git a/work/css/tree_blue/images/spacer.gif b/work/css/tree_blue/images/spacer.gif new file mode 100644 index 0000000..1d11fa9 Binary files /dev/null and b/work/css/tree_blue/images/spacer.gif differ diff --git a/work/css/tree_blue/images/spinner.gif b/work/css/tree_blue/images/spinner.gif new file mode 100644 index 0000000..085ccae Binary files /dev/null and b/work/css/tree_blue/images/spinner.gif differ diff --git a/work/css/tree_blue/style.css b/work/css/tree_blue/style.css new file mode 100644 index 0000000..975bfef --- /dev/null +++ b/work/css/tree_blue/style.css @@ -0,0 +1,83 @@ +.tree +{ + overflow:auto; + height:300px; + width:250px; + border:1px solid #c3daf9; + font: normal 11px arial, tahoma, helvetica, sans-serif; +} +.tree a +{ + color:#000; + text-decoration:none; +} +.tree li, .tree ul +{ + list-style: none; + background-color:#ffffff; +} +.tree li +{ + padding:0px 0px 0px 32px; + line-height:17px; + margin: 0; + cursor: default; + white-space: nowrap; +} +.tree ul +{ + margin:0 0 0 -13px; + padding:0; +} +.tree li.leaf +{ + background: url(images/leaf.gif) no-repeat -2px 0 #ffffff; +} +.tree li.leaf-last +{ + background: url(images/leaf-last.gif) no-repeat -2px 0 #ffffff; +} + +.tree .folder-close +{ + background: url(images/expandable.gif) no-repeat -2px 0 #ffffff; +} +.tree .folder-close-last +{ + background: url(images/expandable-last.gif) no-repeat -2px 0 #ffffff; +} +.tree .folder-open +{ + background: url(images/collapsable.gif) no-repeat -2px 0 #ffffff; +} +.tree .folder-open-last +{ + background: url(images/collapsable-last.gif) no-repeat -2px 0 #ffffff; +} +.tree .root{ + background: url(images/root.gif) no-repeat 16px 2px #ffffff; +} +.tree .toggler +{ + float:left; + margin-left:-34px; + height:16px; + width:32px; + background-image:url(images/spacer.gif); + cursor:pointer; +} +.tree ul.ajax +{ + background: url(images/spinner.gif) no-repeat 0 0 #ffffff; + height: 16px; +} +.tree ul.ajax li +{ + display:none; +} +.tree .text{} +.tree .active{ + background-color:#F7BE77; + padding:1px 2px; + border: 1px dashed #444; +} \ No newline at end of file diff --git a/work/css/tree_blue2/images/collapsable-last.gif b/work/css/tree_blue2/images/collapsable-last.gif new file mode 100644 index 0000000..c7949a8 Binary files /dev/null and b/work/css/tree_blue2/images/collapsable-last.gif differ diff --git a/work/css/tree_blue2/images/collapsable.gif b/work/css/tree_blue2/images/collapsable.gif new file mode 100644 index 0000000..1897a33 Binary files /dev/null and b/work/css/tree_blue2/images/collapsable.gif differ diff --git a/work/css/tree_blue2/images/expandable-last.gif b/work/css/tree_blue2/images/expandable-last.gif new file mode 100644 index 0000000..adf5fa0 Binary files /dev/null and b/work/css/tree_blue2/images/expandable-last.gif differ diff --git a/work/css/tree_blue2/images/expandable.gif b/work/css/tree_blue2/images/expandable.gif new file mode 100644 index 0000000..ecda94c Binary files /dev/null and b/work/css/tree_blue2/images/expandable.gif differ diff --git a/work/css/tree_blue2/images/leaf-last.gif b/work/css/tree_blue2/images/leaf-last.gif new file mode 100644 index 0000000..e5d301d Binary files /dev/null and b/work/css/tree_blue2/images/leaf-last.gif differ diff --git a/work/css/tree_blue2/images/leaf.gif b/work/css/tree_blue2/images/leaf.gif new file mode 100644 index 0000000..2f5c2ef Binary files /dev/null and b/work/css/tree_blue2/images/leaf.gif differ diff --git a/work/css/tree_blue2/images/root.gif b/work/css/tree_blue2/images/root.gif new file mode 100644 index 0000000..27012fb Binary files /dev/null and b/work/css/tree_blue2/images/root.gif differ diff --git a/work/css/tree_blue2/images/spacer.gif b/work/css/tree_blue2/images/spacer.gif new file mode 100644 index 0000000..1d11fa9 Binary files /dev/null and b/work/css/tree_blue2/images/spacer.gif differ diff --git a/work/css/tree_blue2/images/spinner.gif b/work/css/tree_blue2/images/spinner.gif new file mode 100644 index 0000000..085ccae Binary files /dev/null and b/work/css/tree_blue2/images/spinner.gif differ diff --git a/work/css/tree_blue2/style.css b/work/css/tree_blue2/style.css new file mode 100644 index 0000000..975bfef --- /dev/null +++ b/work/css/tree_blue2/style.css @@ -0,0 +1,83 @@ +.tree +{ + overflow:auto; + height:300px; + width:250px; + border:1px solid #c3daf9; + font: normal 11px arial, tahoma, helvetica, sans-serif; +} +.tree a +{ + color:#000; + text-decoration:none; +} +.tree li, .tree ul +{ + list-style: none; + background-color:#ffffff; +} +.tree li +{ + padding:0px 0px 0px 32px; + line-height:17px; + margin: 0; + cursor: default; + white-space: nowrap; +} +.tree ul +{ + margin:0 0 0 -13px; + padding:0; +} +.tree li.leaf +{ + background: url(images/leaf.gif) no-repeat -2px 0 #ffffff; +} +.tree li.leaf-last +{ + background: url(images/leaf-last.gif) no-repeat -2px 0 #ffffff; +} + +.tree .folder-close +{ + background: url(images/expandable.gif) no-repeat -2px 0 #ffffff; +} +.tree .folder-close-last +{ + background: url(images/expandable-last.gif) no-repeat -2px 0 #ffffff; +} +.tree .folder-open +{ + background: url(images/collapsable.gif) no-repeat -2px 0 #ffffff; +} +.tree .folder-open-last +{ + background: url(images/collapsable-last.gif) no-repeat -2px 0 #ffffff; +} +.tree .root{ + background: url(images/root.gif) no-repeat 16px 2px #ffffff; +} +.tree .toggler +{ + float:left; + margin-left:-34px; + height:16px; + width:32px; + background-image:url(images/spacer.gif); + cursor:pointer; +} +.tree ul.ajax +{ + background: url(images/spinner.gif) no-repeat 0 0 #ffffff; + height: 16px; +} +.tree ul.ajax li +{ + display:none; +} +.tree .text{} +.tree .active{ + background-color:#F7BE77; + padding:1px 2px; + border: 1px dashed #444; +} \ No newline at end of file diff --git a/work/css/tree_xp/images/collapsable-last.gif b/work/css/tree_xp/images/collapsable-last.gif new file mode 100644 index 0000000..5d1ea60 Binary files /dev/null and b/work/css/tree_xp/images/collapsable-last.gif differ diff --git a/work/css/tree_xp/images/collapsable.gif b/work/css/tree_xp/images/collapsable.gif new file mode 100644 index 0000000..20dbdad Binary files /dev/null and b/work/css/tree_xp/images/collapsable.gif differ diff --git a/work/css/tree_xp/images/expandable-last.gif b/work/css/tree_xp/images/expandable-last.gif new file mode 100644 index 0000000..fb468bc Binary files /dev/null and b/work/css/tree_xp/images/expandable-last.gif differ diff --git a/work/css/tree_xp/images/expandable.gif b/work/css/tree_xp/images/expandable.gif new file mode 100644 index 0000000..451f6a3 Binary files /dev/null and b/work/css/tree_xp/images/expandable.gif differ diff --git a/work/css/tree_xp/images/leaf-last.gif b/work/css/tree_xp/images/leaf-last.gif new file mode 100644 index 0000000..e5d301d Binary files /dev/null and b/work/css/tree_xp/images/leaf-last.gif differ diff --git a/work/css/tree_xp/images/leaf.gif b/work/css/tree_xp/images/leaf.gif new file mode 100644 index 0000000..2f5c2ef Binary files /dev/null and b/work/css/tree_xp/images/leaf.gif differ diff --git a/work/css/tree_xp/images/root.gif b/work/css/tree_xp/images/root.gif new file mode 100644 index 0000000..27012fb Binary files /dev/null and b/work/css/tree_xp/images/root.gif differ diff --git a/work/css/tree_xp/images/spacer.gif b/work/css/tree_xp/images/spacer.gif new file mode 100644 index 0000000..1d11fa9 Binary files /dev/null and b/work/css/tree_xp/images/spacer.gif differ diff --git a/work/css/tree_xp/images/spinner.gif b/work/css/tree_xp/images/spinner.gif new file mode 100644 index 0000000..085ccae Binary files /dev/null and b/work/css/tree_xp/images/spinner.gif differ diff --git a/work/css/tree_xp/style.css b/work/css/tree_xp/style.css new file mode 100644 index 0000000..975bfef --- /dev/null +++ b/work/css/tree_xp/style.css @@ -0,0 +1,83 @@ +.tree +{ + overflow:auto; + height:300px; + width:250px; + border:1px solid #c3daf9; + font: normal 11px arial, tahoma, helvetica, sans-serif; +} +.tree a +{ + color:#000; + text-decoration:none; +} +.tree li, .tree ul +{ + list-style: none; + background-color:#ffffff; +} +.tree li +{ + padding:0px 0px 0px 32px; + line-height:17px; + margin: 0; + cursor: default; + white-space: nowrap; +} +.tree ul +{ + margin:0 0 0 -13px; + padding:0; +} +.tree li.leaf +{ + background: url(images/leaf.gif) no-repeat -2px 0 #ffffff; +} +.tree li.leaf-last +{ + background: url(images/leaf-last.gif) no-repeat -2px 0 #ffffff; +} + +.tree .folder-close +{ + background: url(images/expandable.gif) no-repeat -2px 0 #ffffff; +} +.tree .folder-close-last +{ + background: url(images/expandable-last.gif) no-repeat -2px 0 #ffffff; +} +.tree .folder-open +{ + background: url(images/collapsable.gif) no-repeat -2px 0 #ffffff; +} +.tree .folder-open-last +{ + background: url(images/collapsable-last.gif) no-repeat -2px 0 #ffffff; +} +.tree .root{ + background: url(images/root.gif) no-repeat 16px 2px #ffffff; +} +.tree .toggler +{ + float:left; + margin-left:-34px; + height:16px; + width:32px; + background-image:url(images/spacer.gif); + cursor:pointer; +} +.tree ul.ajax +{ + background: url(images/spinner.gif) no-repeat 0 0 #ffffff; + height: 16px; +} +.tree ul.ajax li +{ + display:none; +} +.tree .text{} +.tree .active{ + background-color:#F7BE77; + padding:1px 2px; + border: 1px dashed #444; +} \ No newline at end of file diff --git a/work/ref/fri.rb b/work/ref/fri.rb new file mode 100644 index 0000000..30d6f96 --- /dev/null +++ b/work/ref/fri.rb @@ -0,0 +1,349 @@ +#!/usr/bin/env ruby +# fri: access RI documentation through DRb +# Copyright (C) 2006 Mauricio Fernandez <[email protected]> +# + +require 'fastri/util' +require 'fastri/full_text_index' + +default_local_mode = File.basename($0)[/^qri/] ? true : false + +# we bind to 127.0.0.1 by default, because otherwise Ruby will try with +# 0.0.0.0, which results in a DNS request, adding way too much latency +options = { + :addr => "127.0.0.1", + :format => + case RUBY_PLATFORM + when /win/ + if /darwin|cygwin/ =~ RUBY_PLATFORM + "ansi" + else + "plain" + end + else + "ansi" + end, + :width => 72, + :lookup_order => [ + :exact, :exact_ci, :nested, :nested_ci, :partial, :partial_ci, + :nested_partial, :nested_partial_ci, + ], + :show_matches => false, + :do_full_text => false, + :full_text_dir => File.join(FastRI::Util.find_home, ".fastri-fulltext"), + :use_pager => nil, + :pager => nil, + :list_classes => nil, + :list_methods => nil, + :extended => false, + :index_file => File.join(FastRI::Util.find_home, ".fastri-index"), + :local_mode => default_local_mode, + :do_second_guess => true +} + +override_addr_env = false + + +# only load optparse if actually needed +# saves ~0.01-0.04s. +if (arg = ARGV[0]) && arg[0, 1] == "-" or ARGV.empty? + require 'optparse' + optparser = OptionParser.new do |opts| + opts.version = FastRI::FASTRI_VERSION + opts.release = FastRI::FASTRI_RELEASE_DATE + opts.banner = "Usage: #{File.basename($0)} [options] <query>" + + opts.on("-L", "--local", "Try to use local index instead of DRb service.", + *[("(default)" if default_local_mode)].compact) do + options[:local_mode] = true + end + opts.on("--index-file=FILE", "Use index file (forces --local mode).", + "(default: #{options[:index_file]})") do |file| + options[:index_file] = file + options[:local_mode] = true + end + opts.on("-R", "--remote", "Use DRb service. #{'(default)' unless default_local_mode}") do + options[:local_mode] = false + end + opts.on("-s", "--bind ADDR", "Bind to ADDR for incoming DRb connections.", + "(default: 127.0.0.1)") do |addr| + options[:addr] = addr + override_addr_env = true + end + + order_mapping = { + 'e' => :exact, 'E' => :exact_ci, 'n' => :nested, 'N' => :nested_ci, + 'p' => :partial, 'P' => :partial_ci, 'x' => :nested_partial, + 'X' => :nested_partial_ci, 'a' => :anywhere, 'A' => :anywhere_ci, + 'm' => :namespace_partial, 'M' => :namespace_partial_ci, + 'f' => :full_partial, 'F' => :full_partial_ci, + } + opts.on("-O", "--order ORDER", "Specify lookup order.", + "(default: eEnNpPxX)", "Uppercase: case-indep.", + "e:exact n:nested p:partial (completion)", + "x:nested and partial m:complete namespace", + "f:complete both class and method", + "a:match method name anywhere") do |order| + options[:lookup_order] = order.split(//).map{|x| order_mapping[x]}.compact + end + + opts.on("-1", "--exact", "Does not do second guess(exact query).") do + options[:do_second_guess] = false + options[:lookup_order] = [ :exact ] + end + + opts.on("-e", "--extended", "Show all methods for given namespace.") do + options[:extended] = true + options[:use_pager] = true + options[:format] = "plain" + end + + opts.on("--show-matches", "Only show matching entries."){ options[:show_matches] = true } + + opts.on("--classes", "List all known classes/modules.") do + options[:use_pager] = true + options[:list_classes] = true + end + opts.on("--methods", "List all known methods.") do + options[:use_pager] = true + options[:list_methods] = true + end + opts.on("-l", "--list-names", "List all known namespaces/methods.") do + options[:use_pager] = true + options[:list_classes] = true + options[:list_methods] = true + end + + opts.on("-S", "--full-text", "Perform full-text search.") do + options[:do_full_text] = true + options[:use_pager] = true if options[:use_pager].nil? + options[:format] = "plain" + end + + opts.on("-F", "--full-text-dir DIR", "Use full-text index in DIR", + "(default: #{options[:full_text_dir]})") do |dir| + options[:full_text_dir] = dir if dir + options[:do_full_text] = true + options[:use_pager] = true + options[:format] = "plain" + end + + opts.on("-f", "--format FMT", "Format to use when displaying output:", + " ansi, plain (default: #{options[:format]})") do |format| + options[:format] = format + end + + opts.on("-P", "--[no-]pager", "Use pager.", "(default: don't)") do |usepager| + options[:use_pager] = usepager + options[:format] = "plain" if usepager + end + + opts.on("-T", "Don't use a pager."){ options[:use_pager] = false } + + opts.on("--pager-cmd PAGER", "Use pager PAGER.", "(default: don't)") do |pager| + options[:pager] = pager + options[:use_pager] = true + options[:format] = "plain" + end + + opts.on("-w", "--width WIDTH", "Set the width of the output.") do |width| + w = width.to_i + options[:width] = w > 0 ? w : options[:width] + end + + opts.on("-h", "--help", "Show this help message") do + puts opts + exit + end + end + optparser.parse! + + if !options[:list_classes] && !options[:list_methods] && ARGV.empty? + puts optparser + exit + end +end # lazy optparse loading + +# {{{ try to find where the method comes from exactly +include FastRI::Util::MagicHelp + +MAX_CONTEXT_LINES = 20 +def context_wrap(text, width) + "... " + + text.gsub(/(.{1,#{width-4}})( +|$\n?)|(.{1,#{width-4}})/, "\\1\\3\n").chomp +end + +def display_fulltext_search_results(results, gem_dir_info = FastRI::Util.gem_directories_unique, + width = 78) + return if results.empty? + path = File.expand_path(results[0].path) + gem_name, version, gem_path = FastRI::Util.gem_info_for_path(path, gem_dir_info) + if gem_name + rel_path = path[/#{Regexp.escape(gem_path)}\/(.*)/, 1] + if rel_path + entry_name = FastRI::Util.gem_relpath_to_full_name(rel_path) + end + puts "Found in #{gem_name} #{version} #{entry_name}" + else + rdoc_system_path = File.expand_path(RI::Paths::SYSDIR) + if path.index(rdoc_system_path) + rel_path = path[/#{Regexp.escape(rdoc_system_path)}\/(.*)/, 1] + puts "Found in system #{FastRI::Util.gem_relpath_to_full_name(rel_path)}" + else + puts "Found in #{path}:" + end + end + text = results.map do |result| + context = result.context(120) + from = (context.rindex("\n", context.index(result.query)) || -1) + 1 + to = (context.index("\n", context.index(result.query)) || 0) - 1 + context_wrap(context[from..to], width) + end + puts + puts text.uniq[0...MAX_CONTEXT_LINES] + puts +end + +def perform_fulltext_search(options) + fulltext = File.join(options[:full_text_dir], "full_text.dat") + suffixes = File.join(options[:full_text_dir], "suffixes.dat") + begin + index = FastRI::FullTextIndex.new_from_filenames(fulltext, suffixes) + rescue Exception + puts <<EOF +Couldn't open the full-text index: +#{fulltext} +#{suffixes} + +The index needs to be rebuilt with + fastri-server -B +EOF + exit(-1) + end + gem_dir_info = FastRI::Util.gem_directories_unique + match_sets = ARGV.map do |query| + result = index.lookup(query) + if result + index.next_matches(result) + [result] + else + [] + end + end + path_map = Hash.new{|h,k| h[k] = []} + match_sets.each{|matches| matches.each{|m| path_map[m.path] << m} } + paths = match_sets[1..-1].inject(match_sets[0].map{|x| x.path}.uniq) do |s,x| + s & x.map{|y| y.path}.uniq + end + if paths.empty? + puts "nil" + else + puts "#{paths.size} hits" + paths.sort_by{|path| 1.0 * -path_map[path].size / path_map[path].first.metadata[:size] ** 0.5}.map do |path| + puts "=" * options[:width] + puts 1.0 * path_map[path].size / path_map[path].first.metadata[:size] ** 0.5 + display_fulltext_search_results(path_map[path], gem_dir_info, options[:width]) + end + end + + exit 0 +end + +#{{{ set up pager +if options[:use_pager] + [options[:pager], ENV["PAGER"], "less", "more", "pager"].compact.uniq.each do |pager| + begin + $stdout = IO.popen(pager, "w") + at_exit{ $stdout.close } + break + rescue Exception + end + end +end + +#{{{ perform full text search if asked to +perform_fulltext_search(options) if options[:do_full_text] + +#{{{ normal query +if options[:local_mode] + require 'fastri/ri_service' + ri_reader = open(options[:index_file], "rb"){|io| Marshal.load io } rescue nil + unless ri_reader + puts <<EOF +Couldn't open the index: +#{options[:index_file]} + +The index needs to be rebuilt with + fastri-server -b +EOF + exit(-1) + end + service = FastRI::RiService.new(ri_reader) +else # remote + require 'rinda/ring' + + #{{{ determine the address to bind to + if override_addr_env + addr_spec = options[:addr] + else + addr_spec = ENV["FASTRI_ADDR"] || options[:addr] + end + + ip = addr_spec[/^[^:]+/] || "127.0.0.1" + port = addr_spec[/:(\d+)/, 1] || 0 + addr = "druby://#{ip}:#{port}" + + #{{{ start DRb and perform request + begin + DRb.start_service(addr) + ring_server = Rinda::RingFinger.primary + rescue Exception + $stderr.puts <<EOF +Couldn't initialize DRb and locate the Ring server. + +Please make sure that: + * the fastri-server is running, the server is bound to the correct interface, + and the ACL setup allows connections from this host + * fri is using the correct interface for incoming DRb requests: + either set the FASTRI_ADDR environment variable, or use --bind ADDR, e.g + export FASTRI_ADDR="192.168.1.12" + fri Array +EOF + exit(-1) + end + service = ring_server.read([:name, :FastRI, nil, nil])[2] +end + + +info_options = { + :formatter => options[:format], + :width => options[:width], + :lookup_order => options[:lookup_order], + :extended => options[:extended], +} + +# {{{ list classes or methods +puts service.all_classes if options[:list_classes] +puts service.all_methods if options[:list_methods] +exit if options[:list_classes] || options[:list_methods] + +# {{{ normal query + +ARGV.each do |term| + help_query = magic_help(term) + if options[:show_matches] + puts service.matches(help_query, info_options).sort + else + result = service.info(help_query, info_options) + # second-guess the correct method type only as the last resort. + if result + puts result + elsif options[:do_second_guess] and (new_query = FastRI::Util.change_query_method_type(help_query)) != help_query + puts service.info(new_query) + else + puts nil + end + end +end +# vi: set sw=2 expandtab: + +
spatten/Jestitute
c569ed2fcf7e940765f0fba9cee2538c90221f1a
initial checkin
diff --git a/iPhone/PhoneGapTutorial/Classes/PhoneGapTutorialAppDelegate.h b/iPhone/PhoneGapTutorial/Classes/PhoneGapTutorialAppDelegate.h new file mode 100644 index 0000000..175ce91 --- /dev/null +++ b/iPhone/PhoneGapTutorial/Classes/PhoneGapTutorialAppDelegate.h @@ -0,0 +1,16 @@ +// +// PhoneGapTutorialAppDelegate.h +// PhoneGapTutorial +// +// Created by Jesse MacFadyen on 10-01-06. +// Copyright Nitobi 2010. All rights reserved. +// + +#import <UIKit/UIKit.h> +#import "PhoneGapDelegate.h" + +@interface PhoneGapTutorialAppDelegate : PhoneGapDelegate { +} + +@end + diff --git a/iPhone/PhoneGapTutorial/Classes/PhoneGapTutorialAppDelegate.m b/iPhone/PhoneGapTutorial/Classes/PhoneGapTutorialAppDelegate.m new file mode 100644 index 0000000..9e1ca1c --- /dev/null +++ b/iPhone/PhoneGapTutorial/Classes/PhoneGapTutorialAppDelegate.m @@ -0,0 +1,81 @@ +// +// PhoneGapTutorialAppDelegate.m +// PhoneGapTutorial +// +// Created by Jesse MacFadyen on 10-01-06. +// Copyright Nitobi 2010. All rights reserved. +// + +#import "PhoneGapTutorialAppDelegate.h" +#import "PhoneGapViewController.h" + +@implementation PhoneGapTutorialAppDelegate + +- (id) init +{ + /** If you need to do any extra app-specific initialization, you can do it here + * -jm + **/ + return [super init]; +} + +/** + * This is main kick off after the app inits, the views and Settings are setup here. + */ +- (void)applicationDidFinishLaunching:(UIApplication *)application +{ + [ super applicationDidFinishLaunching:application ]; +} + +-(id) getCommandInstance:(NSString*)className +{ + /** You can catch your own commands here, if you wanted to extend the gap: protocol, or add your + * own app specific protocol to it. -jm + **/ + return [super getCommandInstance:className]; +} + +/** + Called when the webview finishes loading. This stops the activity view and closes the imageview + */ +- (void)webViewDidFinishLoad:(UIWebView *)theWebView +{ + return [ super webViewDidFinishLoad:theWebView ]; +} + +- (void)webViewDidStartLoad:(UIWebView *)theWebView +{ + return [ super webViewDidStartLoad:theWebView ]; +} + +/** + * Fail Loading With Error + * Error - If the webpage failed to load display an error with the reson. + */ +- (void)webView:(UIWebView *)theWebView didFailLoadWithError:(NSError *)error +{ + return [ super webView:theWebView didFailLoadWithError:error ]; +} + +/** + * Start Loading Request + * This is where most of the magic happens... We take the request(s) and process the response. + * From here we can re direct links and other protocalls to different internal methods. + */ +- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType +{ + return [ super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType ]; +} + + +- (BOOL) execute:(InvokedUrlCommand*)command +{ + return [ super execute:command]; +} + +- (void)dealloc +{ + [ super dealloc ]; +} + +@end diff --git a/iPhone/PhoneGapTutorial/PhoneGapTutorial-Info.plist b/iPhone/PhoneGapTutorial/PhoneGapTutorial-Info.plist new file mode 100644 index 0000000..0cfd1d7 --- /dev/null +++ b/iPhone/PhoneGapTutorial/PhoneGapTutorial-Info.plist @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleDevelopmentRegion</key> + <string>English</string> + <key>CFBundleDisplayName</key> + <string>${PRODUCT_NAME}</string> + <key>CFBundleExecutable</key> + <string>${EXECUTABLE_NAME}</string> + <key>CFBundleIconFile</key> + <string></string> + <key>CFBundleIdentifier</key> + <string>nitobi.dev.phonegapTutorial</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundleName</key> + <string>${PRODUCT_NAME}</string> + <key>CFBundlePackageType</key> + <string>APPL</string> + <key>CFBundleSignature</key> + <string>????</string> + <key>CFBundleVersion</key> + <string>1.0</string> + <key>LSRequiresIPhoneOS</key> + <true/> + <key>NSMainNibFile</key> + <string>MainWindow</string> +</dict> +</plist> diff --git a/iPhone/PhoneGapTutorial/PhoneGapTutorial.xcodeproj/project.pbxproj b/iPhone/PhoneGapTutorial/PhoneGapTutorial.xcodeproj/project.pbxproj new file mode 100755 index 0000000..b41d58d --- /dev/null +++ b/iPhone/PhoneGapTutorial/PhoneGapTutorial.xcodeproj/project.pbxproj @@ -0,0 +1,380 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 45; + objects = { + +/* Begin PBXBuildFile section */ + 1D3623260D0F684500981E51 /* PhoneGapTutorialAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D3623250D0F684500981E51 /* PhoneGapTutorialAppDelegate.m */; }; + 1D60589B0D05DD56006BFB54 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; }; + 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; }; + 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */; }; + 288765FD0DF74451002DB57D /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 288765FC0DF74451002DB57D /* CoreGraphics.framework */; }; + 301BF552109A68D80062928A /* libPhoneGapLib.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 301BF535109A57CC0062928A /* libPhoneGapLib.a */; }; + 301BF570109A69640062928A /* www in Resources */ = {isa = PBXBuildFile; fileRef = 301BF56E109A69640062928A /* www */; }; + 301BF5B5109A6A2B0062928A /* AddressBook.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 301BF5B4109A6A2B0062928A /* AddressBook.framework */; }; + 301BF5B7109A6A2B0062928A /* AddressBookUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 301BF5B6109A6A2B0062928A /* AddressBookUI.framework */; }; + 301BF5B9109A6A2B0062928A /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 301BF5B8109A6A2B0062928A /* AudioToolbox.framework */; }; + 301BF5BB109A6A2B0062928A /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 301BF5BA109A6A2B0062928A /* AVFoundation.framework */; }; + 301BF5BD109A6A2B0062928A /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 301BF5BC109A6A2B0062928A /* CFNetwork.framework */; }; + 301BF5BF109A6A2B0062928A /* CoreLocation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 301BF5BE109A6A2B0062928A /* CoreLocation.framework */; }; + 301BF5C1109A6A2B0062928A /* MediaPlayer.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 301BF5C0109A6A2B0062928A /* MediaPlayer.framework */; }; + 301BF5C3109A6A2B0062928A /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 301BF5C2109A6A2B0062928A /* QuartzCore.framework */; }; + 301BF5C5109A6A2B0062928A /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 301BF5C4109A6A2B0062928A /* SystemConfiguration.framework */; }; + 3053AC6F109B7857006FCFE7 /* VERSION in Resources */ = {isa = PBXBuildFile; fileRef = 3053AC6E109B7857006FCFE7 /* VERSION */; }; + 88D488E810F74F5A0016BD38 /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = 88D488E710F74F5A0016BD38 /* Default.png */; }; + 88E111B210F814DF00DA3614 /* icon.png in Resources */ = {isa = PBXBuildFile; fileRef = 88E111B110F814DF00DA3614 /* icon.png */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 301BF534109A57CC0062928A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 301BF52D109A57CC0062928A /* PhoneGapLib.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = D2AAC07E0554694100DB518D; + remoteInfo = PhoneGapLib; + }; + 301BF550109A68C00062928A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 301BF52D109A57CC0062928A /* PhoneGapLib.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = D2AAC07D0554694100DB518D; + remoteInfo = PhoneGapLib; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 1D30AB110D05D00D00671497 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; + 1D3623240D0F684500981E51 /* PhoneGapTutorialAppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PhoneGapTutorialAppDelegate.h; sourceTree = "<group>"; }; + 1D3623250D0F684500981E51 /* PhoneGapTutorialAppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PhoneGapTutorialAppDelegate.m; sourceTree = "<group>"; }; + 1D6058910D05DD3D006BFB54 /* GapTut.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GapTut.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; + 288765FC0DF74451002DB57D /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; + 29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; }; + 301BF52D109A57CC0062928A /* PhoneGapLib.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = PhoneGapLib.xcodeproj; sourceTree = PHONEGAPLIB; }; + 301BF56E109A69640062928A /* www */ = {isa = PBXFileReference; lastKnownFileType = folder; path = www; sourceTree = SOURCE_ROOT; }; + 301BF5B4109A6A2B0062928A /* AddressBook.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AddressBook.framework; path = System/Library/Frameworks/AddressBook.framework; sourceTree = SDKROOT; }; + 301BF5B6109A6A2B0062928A /* AddressBookUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AddressBookUI.framework; path = System/Library/Frameworks/AddressBookUI.framework; sourceTree = SDKROOT; }; + 301BF5B8109A6A2B0062928A /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; }; + 301BF5BA109A6A2B0062928A /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; }; + 301BF5BC109A6A2B0062928A /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = System/Library/Frameworks/CFNetwork.framework; sourceTree = SDKROOT; }; + 301BF5BE109A6A2B0062928A /* CoreLocation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreLocation.framework; path = System/Library/Frameworks/CoreLocation.framework; sourceTree = SDKROOT; }; + 301BF5C0109A6A2B0062928A /* MediaPlayer.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MediaPlayer.framework; path = System/Library/Frameworks/MediaPlayer.framework; sourceTree = SDKROOT; }; + 301BF5C2109A6A2B0062928A /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; + 301BF5C4109A6A2B0062928A /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; + 3053AC6E109B7857006FCFE7 /* VERSION */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = VERSION; sourceTree = PHONEGAPLIB; }; + 32CA4F630368D1EE00C91783 /* PhoneGapTutorial_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PhoneGapTutorial_Prefix.pch; sourceTree = "<group>"; }; + 88D488E710F74F5A0016BD38 /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = "<group>"; }; + 88E111B110F814DF00DA3614 /* icon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = icon.png; sourceTree = "<group>"; }; + 8D1107310486CEB800E47090 /* PhoneGapTutorial-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "PhoneGapTutorial-Info.plist"; plistStructureDefinitionIdentifier = "com.apple.xcode.plist.structure-definition.iphone.info-plist"; sourceTree = "<group>"; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 1D60588F0D05DD3D006BFB54 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 301BF552109A68D80062928A /* libPhoneGapLib.a in Frameworks */, + 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */, + 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */, + 288765FD0DF74451002DB57D /* CoreGraphics.framework in Frameworks */, + 301BF5B5109A6A2B0062928A /* AddressBook.framework in Frameworks */, + 301BF5B7109A6A2B0062928A /* AddressBookUI.framework in Frameworks */, + 301BF5B9109A6A2B0062928A /* AudioToolbox.framework in Frameworks */, + 301BF5BB109A6A2B0062928A /* AVFoundation.framework in Frameworks */, + 301BF5BD109A6A2B0062928A /* CFNetwork.framework in Frameworks */, + 301BF5BF109A6A2B0062928A /* CoreLocation.framework in Frameworks */, + 301BF5C1109A6A2B0062928A /* MediaPlayer.framework in Frameworks */, + 301BF5C3109A6A2B0062928A /* QuartzCore.framework in Frameworks */, + 301BF5C5109A6A2B0062928A /* SystemConfiguration.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 080E96DDFE201D6D7F000001 /* Classes */ = { + isa = PBXGroup; + children = ( + 1D3623240D0F684500981E51 /* PhoneGapTutorialAppDelegate.h */, + 1D3623250D0F684500981E51 /* PhoneGapTutorialAppDelegate.m */, + ); + path = Classes; + sourceTree = SOURCE_ROOT; + }; + 19C28FACFE9D520D11CA2CBB /* Products */ = { + isa = PBXGroup; + children = ( + 1D6058910D05DD3D006BFB54 /* GapTut.app */, + ); + name = Products; + sourceTree = "<group>"; + }; + 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = { + isa = PBXGroup; + children = ( + 88E111B110F814DF00DA3614 /* icon.png */, + 88D488E710F74F5A0016BD38 /* Default.png */, + 301BF56E109A69640062928A /* www */, + 301BF52D109A57CC0062928A /* PhoneGapLib.xcodeproj */, + 080E96DDFE201D6D7F000001 /* Classes */, + 307C750510C5A3420062BCA9 /* Plugins */, + 29B97315FDCFA39411CA2CEA /* Other Sources */, + 29B97317FDCFA39411CA2CEA /* Resources */, + 29B97323FDCFA39411CA2CEA /* Frameworks */, + 19C28FACFE9D520D11CA2CBB /* Products */, + ); + name = CustomTemplate; + sourceTree = "<group>"; + }; + 29B97315FDCFA39411CA2CEA /* Other Sources */ = { + isa = PBXGroup; + children = ( + 32CA4F630368D1EE00C91783 /* PhoneGapTutorial_Prefix.pch */, + 29B97316FDCFA39411CA2CEA /* main.m */, + ); + name = "Other Sources"; + sourceTree = "<group>"; + }; + 29B97317FDCFA39411CA2CEA /* Resources */ = { + isa = PBXGroup; + children = ( + 3053AC6E109B7857006FCFE7 /* VERSION */, + 8D1107310486CEB800E47090 /* PhoneGapTutorial-Info.plist */, + ); + name = Resources; + sourceTree = "<group>"; + }; + 29B97323FDCFA39411CA2CEA /* Frameworks */ = { + isa = PBXGroup; + children = ( + 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */, + 1D30AB110D05D00D00671497 /* Foundation.framework */, + 288765FC0DF74451002DB57D /* CoreGraphics.framework */, + 301BF5B4109A6A2B0062928A /* AddressBook.framework */, + 301BF5B6109A6A2B0062928A /* AddressBookUI.framework */, + 301BF5B8109A6A2B0062928A /* AudioToolbox.framework */, + 301BF5BA109A6A2B0062928A /* AVFoundation.framework */, + 301BF5BC109A6A2B0062928A /* CFNetwork.framework */, + 301BF5BE109A6A2B0062928A /* CoreLocation.framework */, + 301BF5C0109A6A2B0062928A /* MediaPlayer.framework */, + 301BF5C2109A6A2B0062928A /* QuartzCore.framework */, + 301BF5C4109A6A2B0062928A /* SystemConfiguration.framework */, + ); + name = Frameworks; + sourceTree = "<group>"; + }; + 301BF52E109A57CC0062928A /* Products */ = { + isa = PBXGroup; + children = ( + 301BF535109A57CC0062928A /* libPhoneGapLib.a */, + ); + name = Products; + sourceTree = "<group>"; + }; + 307C750510C5A3420062BCA9 /* Plugins */ = { + isa = PBXGroup; + children = ( + ); + path = Plugins; + sourceTree = SOURCE_ROOT; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 1D6058900D05DD3D006BFB54 /* GapTut */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "GapTut" */; + buildPhases = ( + 30E9A9A110B758320022D3BA /* Copy PhoneGap Javascript */, + 1D60588D0D05DD3D006BFB54 /* Resources */, + 1D60588E0D05DD3D006BFB54 /* Sources */, + 1D60588F0D05DD3D006BFB54 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 301BF551109A68C00062928A /* PBXTargetDependency */, + ); + name = GapTut; + productName = PhoneGapTutorial; + productReference = 1D6058910D05DD3D006BFB54 /* GapTut.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 29B97313FDCFA39411CA2CEA /* Project object */ = { + isa = PBXProject; + buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "PhoneGapTutorial" */; + compatibilityVersion = "Xcode 3.1"; + hasScannedForEncodings = 1; + mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */; + projectDirPath = ""; + projectReferences = ( + { + ProductGroup = 301BF52E109A57CC0062928A /* Products */; + ProjectRef = 301BF52D109A57CC0062928A /* PhoneGapLib.xcodeproj */; + }, + ); + projectRoot = ""; + targets = ( + 1D6058900D05DD3D006BFB54 /* GapTut */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXReferenceProxy section */ + 301BF535109A57CC0062928A /* libPhoneGapLib.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libPhoneGapLib.a; + remoteRef = 301BF534109A57CC0062928A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + +/* Begin PBXResourcesBuildPhase section */ + 1D60588D0D05DD3D006BFB54 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 301BF570109A69640062928A /* www in Resources */, + 3053AC6F109B7857006FCFE7 /* VERSION in Resources */, + 88D488E810F74F5A0016BD38 /* Default.png in Resources */, + 88E111B210F814DF00DA3614 /* icon.png in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 30E9A9A110B758320022D3BA /* Copy PhoneGap Javascript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Copy PhoneGap Javascript"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "make -C \"${PHONEGAPLIB}\"\necho cp ${PHONEGAPLIB}/javascripts/phonegap.js ${PROJECT_DIR}/www/phonegap.js\ncp \"${PHONEGAPLIB}/javascripts/phonegap.js\" \"${PROJECT_DIR}/www/phonegap.js\""; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 1D60588E0D05DD3D006BFB54 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 1D60589B0D05DD56006BFB54 /* main.m in Sources */, + 1D3623260D0F684500981E51 /* PhoneGapTutorialAppDelegate.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 301BF551109A68C00062928A /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PhoneGapLib; + targetProxy = 301BF550109A68C00062928A /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 1D6058940D05DD3E006BFB54 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COPY_PHASE_STRIP = NO; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = PhoneGapTutorial_Prefix.pch; + INFOPLIST_FILE = "PhoneGapTutorial-Info.plist"; + PRODUCT_NAME = GapTut; + }; + name = Debug; + }; + 1D6058950D05DD3E006BFB54 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COPY_PHASE_STRIP = YES; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = PhoneGapTutorial_Prefix.pch; + INFOPLIST_FILE = "PhoneGapTutorial-Info.plist"; + PRODUCT_NAME = PhoneGapTutorial; + }; + name = Release; + }; + C01FCF4F08A954540054247B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD_32_BIT)"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 3.0; + OTHER_LDFLAGS = ( + "-all_load", + "-Obj-C", + ); + PREBINDING = NO; + PRODUCT_NAME = ""; + SDKROOT = iphoneos3.0; + USER_HEADER_SEARCH_PATHS = "$(PHONEGAPLIB)/Classes"; + }; + name = Debug; + }; + C01FCF5008A954540054247B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD_32_BIT)"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 3.0; + OTHER_LDFLAGS = ( + "-all_load", + "-Obj-C", + ); + PREBINDING = NO; + SDKROOT = iphoneos3.0; + USER_HEADER_SEARCH_PATHS = "$(PHONEGAPLIB)/Classes"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "GapTut" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1D6058940D05DD3E006BFB54 /* Debug */, + 1D6058950D05DD3E006BFB54 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C01FCF4E08A954540054247B /* Build configuration list for PBXProject "PhoneGapTutorial" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C01FCF4F08A954540054247B /* Debug */, + C01FCF5008A954540054247B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 29B97313FDCFA39411CA2CEA /* Project object */; +} diff --git a/iPhone/PhoneGapTutorial/PhoneGapTutorial_Prefix.pch b/iPhone/PhoneGapTutorial/PhoneGapTutorial_Prefix.pch new file mode 100644 index 0000000..41d2cdb --- /dev/null +++ b/iPhone/PhoneGapTutorial/PhoneGapTutorial_Prefix.pch @@ -0,0 +1,8 @@ +// +// Prefix header for all source files of the 'PhoneGapTutorial' target in the 'PhoneGapTutorial' project +// + +#ifdef __OBJC__ + #import <Foundation/Foundation.h> + #import <UIKit/UIKit.h> +#endif diff --git a/iPhone/PhoneGapTutorial/default.png b/iPhone/PhoneGapTutorial/default.png new file mode 100644 index 0000000..3805936 Binary files /dev/null and b/iPhone/PhoneGapTutorial/default.png differ diff --git a/iPhone/PhoneGapTutorial/icon.png b/iPhone/PhoneGapTutorial/icon.png new file mode 100644 index 0000000..182b139 Binary files /dev/null and b/iPhone/PhoneGapTutorial/icon.png differ diff --git a/iPhone/PhoneGapTutorial/main.m b/iPhone/PhoneGapTutorial/main.m new file mode 100644 index 0000000..9502916 --- /dev/null +++ b/iPhone/PhoneGapTutorial/main.m @@ -0,0 +1,17 @@ +// +// main.m +// PhoneGapTutorial +// +// Created by Jesse MacFadyen on 10-01-06. +// Copyright Nitobi 2010. All rights reserved. +// + +#import <UIKit/UIKit.h> + +int main(int argc, char *argv[]) { + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + int retVal = UIApplicationMain(argc, argv, nil, @"PhoneGapTutorialAppDelegate"); + [pool release]; + return retVal; +} diff --git a/iPhone/PhoneGapTutorial/www/accelerometer.html b/iPhone/PhoneGapTutorial/www/accelerometer.html new file mode 100755 index 0000000..8444196 --- /dev/null +++ b/iPhone/PhoneGapTutorial/www/accelerometer.html @@ -0,0 +1,232 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> + <head> + <meta name="viewport" content="width=320; user-scalable=no" /> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>PhoneGap</title> + <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8"> + <style> + + #playField + { + width: 295px; + height:295px; + background:rgba(64,64,64,0.5); + border: 1px solid rgba(128,128,128,0.5); + -webkit-border-radius: 5px; + border-radius: 5px; + clear:both; + margin:15px 6px 0; + padding:4px 0px 2px 10px; + } + + #ball + { + -webkit-border-radius: 26px; + width: 52px; + height: 52px; + background:rgba(128,128,128,0.5); + border: 1px solid rgba(32,32,32,0.5); + position:absolute; + } + + .btn + { + text-decoration: none; + padding: 8px 24px; + background:#fff; + color: #aaa; + font-weight: bold; + -webkit-border-radius: 10px; + } + + .btn:hover + { + background: #6fd9f4; + color: #fff; + } + + + </style> + + <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> + <script type="text/javascript" charset="utf-8"> + + + function preventBehavior(e) { e.preventDefault(); }; + + var ballSize = 52; + + var fieldSize = 295; + + var top = 150; + var bottom = 445; + + var x = fieldSize / 2; + var y = fieldSize / 2; + + var accelInputX = 0.01; + var accelInputY = 0.01; + + var vx = 0; + var vy = 0; + + var vLimit = 200; + + var xMin = 6; + var xMax = xMin + fieldSize - ballSize; + + var yMin = 32; + var yMax = yMin + fieldSize - ballSize; + + var multiplier = 1.5; + + var ball; + + var timer = null; + + var frameTimer = null; + + var lastFrameTime = 0; + + + + + function watchAccel() + { + if(timer == null) + { + timer = navigator.accelerometer.watchAcceleration(onAccellUpdate,onAccelError,{frequency:50}); + } + } + + function onAccelError(e) + { + alert("fail: " + e ); + } + + function onAccellUpdate(accel) + { + accelInputX = accel.x; + accelInputY = accel.y; + } + + function onFrameUpdate() + { + vx += accelInputX; + vy -= accelInputY; + + if (vx > vLimit) + vx = vLimit; + + if (vy > vLimit) + vy = vLimit; + + //var now = new Date().getTime(); + //var elapsed = now - lastFrameTime; + //lastFrameTime = now; + + x += vx; + y += vy; + + if (y > yMax) + { + y = yMax; + vy = -vy / 2; + } + else if (y < yMin) + { + y = yMin; + vy = -vy / 2; + } + + if (x > xMax) + { + x = xMax; + vx = -vx / 2; + } + else if (x < xMin) + { + x = xMin; + vx = -vx / 2; + } + + updateBallCordinates(); + + } + + function updateBallCordinates() + { + ball.style.left = ( xMin + x ).toString() + 'px'; + ball.style.top = ( yMin + y ).toString() + 'px'; + } + + function onWinLoad() + { + document.addEventListener("touchmove", preventBehavior, false); + document.addEventListener("deviceready",onDeviceReady,false); + } + + function onStartButton() + { + if(frameTimer != null) + { + navigator.accelerometer.clearWatch(timer); + timer = null; + + clearInterval(frameTimer); + frameTimer = null; + } + else + { + watchAccel(); + frameTimer = setInterval(onFrameUpdate,20); + //lastFrameTime = new Date().getTime(); + } + + document.getElementById("btnText").innerHTML = ( frameTimer != null ) ? "Pause" : "Start"; + } + + function onDeviceReady() + { + ball = document.getElementById("ball"); + updateBallCordinates(); + updateBallCordinates(); // hack for the shadow + ball.style.display = "block"; + + document.getElementById("startBtn").addEventListener("touchstart",onStartButton,false); + + } + + </script> + + + </head> + + <body id="stage" class="theme" onload="onWinLoad()"> + + <div class="topBar"> + <a href="index.html"> + <span class="back_button">Back</span> + </a> + <span class="pageTitle">Accelerometer</span> + </div> + + + <div id="playField" style="width:295px"> + <div id="ball" style="display:none"></div> + </div> + + <a href="#" id="startBtn"> + <div class="item"> + <h2 id="btnText">Start</h2> + </div></a> + + + </body> +</html> + + + + diff --git a/iPhone/PhoneGapTutorial/www/beep.wav b/iPhone/PhoneGapTutorial/www/beep.wav new file mode 100755 index 0000000..05f5997 Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/beep.wav differ diff --git a/iPhone/PhoneGapTutorial/www/contacts.html b/iPhone/PhoneGapTutorial/www/contacts.html new file mode 100644 index 0000000..09cc137 --- /dev/null +++ b/iPhone/PhoneGapTutorial/www/contacts.html @@ -0,0 +1,176 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> + <head> + <meta name="viewport" content="width=320; user-scalable=no" /> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>PhoneGap</title> + <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8"> + <style> + .contact + { + padding: 8px; + background:rgba(64,64,64,0.5); + border: 1px solid rgba(128,128,128,0.5); + opacity: 0.8; + -moz-border-radius: 8px; + -webkit-border-radius: 8px; + margin-bottom: .5em; + } + + + </style> + <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> + <script type="text/javascript" charset="utf-8"> + + var defaultContactTemplate = "<div class='item' onclick='onContactClick(CONTACTID);'><div>First Name : <strong>FNAME</strong></div><div>Last Name : <strong>LNAME</strong></div><div>Email : EMAIL</div><div>Tel : TELNO</div></div>"; + +var _anomFunkMap = {}; +var _anomFunkMapNextId = 0; + +function anomToNameFunk(fun) +{ + var funkId = "f" + _anomFunkMapNextId++; + var funk = function() + { + fun.apply(this,arguments); + _anomFunkMap[funkId] = null; + }; + _anomFunkMap[funkId] = funk; + + return "_anomFunkMap." + funkId; +} + +function GetFunctionName(fn) +{ + if (fn) + { + var m = fn.toString().match(/^\s*function\s+([^\s\(]+)/); + return m ? m[1] : anomToNameFunk(fn); + } else { + return null; + } +} + + function onGetTenBtn() + { + + navigator.contacts.getAllContacts(onGetAllContacts,null,{pageSize:10}); + } + + function onGetAllContacts(res) + { + var child = document.getElementById('contactList'); + var listMarkup = ""; + for(var n = 0; n < res.length; n++) + { + listMarkup += getContactMarkup(res[n]); + } + child.innerHTML = listMarkup; + child.style.display = "block"; + } + + + function onPickBtn() + { + navigator.contacts.chooseContact(onPickContactCallback); + } + + function onPickContactCallback(contactObj) + { + var child = document.getElementById('contactPicked'); + + child.innerHTML = getContactMarkup(contactObj); + child.style.display = "block"; + + } + + function getContactMarkup(contact) + { + var contactTemplate = defaultContactTemplate; + contactTemplate = contactTemplate.replace(/FNAME/g,contact.firstName); + contactTemplate = contactTemplate.replace(/LNAME/g,contact.lastName); + contactTemplate = contactTemplate.replace(/CONTACTID/g,contact.recordID); + + if(contact.emails[0].value != null) + { + contactTemplate = contactTemplate.replace(/EMAIL/g,contact.emails[0].value); + } + else + { + contactTemplate = contactTemplate.replace(/EMAIL/g,""); + } + + if(contact.phoneNumbers[0].value != null) + { + contactTemplate = contactTemplate.replace(/TELNO/g,contact.phoneNumbers[0].value); + } + else + { + contactTemplate = contactTemplate.replace(/TELNO/g,""); + } + + return contactTemplate; + } + + function onContactClick(id) + { + navigator.contacts.displayContact(id); + } + + function onGotContactCount(num) + { + document.getElementById("contactCountDiv").innerHTML = "Contact Count : " + num; + } + + function onGotContactCountError(err) + { + alert("error getting contacts :: " + err); + } + + + + function onWinLoad() + { + document.addEventListener("deviceready",onDeviceReady,false); + } + + function onDeviceReady() + { + navigator.contacts.contactsCount(onGotContactCount,onGotContactCountError); + } + + </script> + </head> + + <body id="stage" class="theme" onload="onWinLoad()"> + + <div class="topBar"> + <a href="index.html"> + <span class="back_button">Back</span> + </a> + <span class="pageTitle">Contacts</span> + </div> + + + <h2 id="contactCountDiv">Getting contact count ...</h2> + + <a href="#" onclick="onPickBtn();"> + <div class="item"> + <h2>Pick a Contact</h2> + </div> + </a> + + <div id="contactPicked" style="display:none"></div> + + <a href="#" onclick="onGetTenBtn();"> + <div class="item"> + <h2>Get first 10 contacts</h2> + </div> + </a> + + <div id="contactList" style="display:none"></div> + + + </body> +</html> diff --git a/iPhone/PhoneGapTutorial/www/file.html b/iPhone/PhoneGapTutorial/www/file.html new file mode 100644 index 0000000..70b65a4 --- /dev/null +++ b/iPhone/PhoneGapTutorial/www/file.html @@ -0,0 +1,330 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> + <head> + <meta name="viewport" content="width=320; user-scalable=no" /> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>PhoneGap</title> + <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8"> + <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> + <script type="text/javascript" charset="utf-8" src="File.js"></script> + <script type="text/javascript" charset="utf-8" src="EventBroadcaster.js"></script> + <script type="text/javascript" charset="utf-8"> + + +/* + PhoneGap.addConstructor(function(){ + document.addEventListener("touchmove", preventBehavior, false); + + + }); +*/ + + + + window.onload = init; + + function init() + { + document.addEventListener("deviceReady",onDeviceReady,false); + //alert("init " + document.readyState); + + + //console.log("init function"); + //console.log("document.readyState = " + document.readyState); + //testEB(); + + + //testXHRLocal(); + + //testWinNameSessionData(); + + + } + + + function onDeviceReady() + { + alert("I have received a deviceReady notification " + DeviceInfo.uuid); + + } + + + function testEB() + { + + var eb = {}; + + EventBroadcaster.initialize(eb); + + // on event, call a closure function + eb.addListener("Ready",null,function(){alert("Ready happened");}); + + // on event, call a method of responder ( by reference ) + eb.addListener("Ready",resp,resp.onEvent); + + // on event, call a method of responder ( by name ) + eb.addListener("Ready",resp,"onReady"); + + // on event, call a method of responder ( by convention ) => "on" + "EventName" + eb.addListener("Ready",resp); + + eb.broadcastEvent("Ready"); + + + var l1 = {}; + l1.onEvent = function(){ alert("I am l1, and I got an event"); }; + + var l2 = {}; + l2.onEvent = function(){ alert("I am l2, and I got an event"); }; + + eb.addListener("Event",l1); + + eb.addListener("Ready",null,function(){alert("Ready happened");}); + eb.addListener("Ready",resp,resp.onEvent); + eb.addListener("Ready",resp,"onReady"); + eb.addListener("Ready",resp); + + eb.broadcastEvent("Ready"); + + eb.removeListener("Event",l1); + + eb.broadcastEvent("Event"); + + } + + function testXHRLocal() + { + + var userEntry = prompt("Please enter a file name, with extension. ",fileName); + if(userEntry) + { + var path = "" + window.location; + path = path.substr(0,path.indexOf("www") -1); + path = path.substr(0,path.lastIndexOf("/") + 1); + path += "Documents/" + fileName; + + //alert("path = " + path); + + //path = "../../documents/" + fileName; + + + + var request = new XMLHttpRequest(); + + request.open("GET",path, false); + readStartTime = now(); + + request.send(""); + + var dif = now() - readStartTime; + document.getElementById("readStatusText").innerHTML = "Read : " + formatTime(dif); + document.getElementById("outputTxtArea").value = request.responseText; + } + + } + + function testWinNameSessionData() + { + var temp = "x=3&r=12"; + alert("win.name=" + window.name); + window.name = temp; + alert(window.name); + + var conf = confirm("Reload?"); + if(conf) + { + window.location = window.location; + } + } + + function now() + { + return (new Date()).getTime(); + } + + function formatTime(mSecs) + { + return ( mSecs / 1000 ) + " Seconds"; + } + + var fReader; + var fWriter; + var fileName = "MyFile.txt"; + var readStartTime; + var writeStartTime; + + + + function loadFile() + { + var userEntry = prompt("Please enter a file name, with extension. ",fileName); + if(userEntry) + { + fileName = userEntry; + document.getElementById("outputTxtArea").value = "Loading " + fileName + " ..."; + readStartTime = now(); + fReader = new FileReader(); + fReader.onload = onFileLoad; + fReader.onerror = onFileLoadError; + fReader.readAsText(fileName); + } + + } + + function saveFile() + { + var userEntry = prompt("Please enter a file name, with extension. ",fileName); + if(userEntry) + { + fileName = userEntry; + fWriter = new FileWriter(); + fWriter.oncomplete = onWriteComplete; + fWriter.onerror = onWriteError; + + writeStartTime = now(); + var append = document.getElementById("cbAppend").checked; + fWriter.writeAsText(fileName,document.getElementById("outputTxtArea").value,append); + } + } + + + function onFileLoad(result) + { + var dif = now() - readStartTime; + document.getElementById("readStatusText").innerHTML = "Read : " + formatTime(dif); + if(result.length == 0) + { + alert("File does not exist"); + } + else + { + document.getElementById("outputTxtArea").value = result; + } + } + + function onFileLoadError(err) + { + document.getElementById("outputTxtArea").value = err; + } + + function onWriteComplete(result) + { + var dif = now() - writeStartTime; + document.getElementById("writeStatusText").innerHTML = "Write : " + formatTime(dif); + alert("Wrote : " + result + " bytes to file"); + + } + + function onWriteError(err) + { + document.getElementById("outputTxtArea").value = err; + } + + + function testFreeSpace() + { + navigator.file.getFreeDiskSpace(onFileTestSuccess,onFileTestFail); + } + + function testReadFile() + { + var fWriter = new FileWriter(); + fWriter.oncomplete = funkWSuccess; + fWriter.onerror = funkWFail; + + fWriter.writeAsText("MyFile.txt","Here is a new line ...",true); + fReader.readAsText("MyFile.txt"); + + } + + + function getFileBasePaths() + { + navigator.file.getFileBasePaths(onFileTestSuccess,onFileTestFail); + } + + function testDeleteFile() + { + navigator.file.deleteFile("MyFile.txt",onFileTestSuccess,onFileTestFail); + } + + function testDeleteDirectory() + { + + navigator.file.deleteDirectory("SubDir",onFileTestSuccess,onFileTestFail); + } + + function testCreateDirectory() + { + navigator.file.createDirectory("SubDir/SubSub/SubSubSub/2",onFileTestSuccess,onFileTestFail); + } + + function testFileExists() + { + + navigator.file.testFileExists("MyFile2.txt",onFileTestSuccess,onFileTestFail); + } + + function testDirExists() + { + navigator.file.testDirectoryExists("SubDir",onFileTestSuccess,onFileTestFail); + } + + + + function runFileTest() + { + var strToWrite = ""; + for(var n = 0; n < 1024; n++) + { + strToWrite += "" + (n % 10 ); + } + navigator.file.write("MyFile.txt", strToWrite + "\n", false); + } + + + + function reloadPage() + { + window.location = "" + window.location; + } + + + </script> + </head> + <body id="stage" class="theme"> + + <div class="topBar"> + <a href="index.html"> + <span class="back_button">Back</span> + </a> + <span class="pageTitle">File</span> + </div> + + <div id="Page1"> + + <a href="#" class="btn" onclick="loadFile()";>gapRead</a> + <a href="#" class="btn" onclick="saveFile()";>gapWrite</a> + <a href="#" class="btn" onclick="testXHRLocal()";>xhrRead</a> + <div style="clear:both;width:100%"></div> + <input type="checkbox" id="cbAppend"/> + <label for="bOverwrite" style="color:White">Append ?</label> + + <h1 style="text-align:left;margin-top:10px" id="writeStatusText">Write : </h1> + <h1 style="text-align:left;" id="readStatusText">Read : </h1> + + + + <div id="info"> + <textarea id="outputTxtArea" style="width:270px;min-height:240px;height:300px;overflow:visible;"> + </textarea> + </div> + + + + </div> + + + </body> +</html> diff --git a/iPhone/PhoneGapTutorial/www/geolocation.html b/iPhone/PhoneGapTutorial/www/geolocation.html new file mode 100755 index 0000000..4e6c5d1 --- /dev/null +++ b/iPhone/PhoneGapTutorial/www/geolocation.html @@ -0,0 +1,176 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> + <head> + <meta name="viewport" content="width=320; user-scalable=no" /> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>PhoneGap</title> + <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8"> + <style> + + +img { + border: 0; +} +#container { + +} +#tweetList { + color: #ddd; +} +#tweetList .tweet { + padding: 8px; + background:rgba(64,64,64,0.5); + border: 1px solid rgba(128,128,128,0.5); + opacity: 0.8; + -moz-border-radius: 8px; + -webkit-border-radius: 8px; + margin-bottom: .5em; +} + +#tweetList a { + color: #f30; + text-decoration: underline; +} +#tweetList .avatar { + float: left; +} +#tweetList .content { + padding-left: 55px; +} +#tweetList .extra { + color: #666; + font-size: 85% +} + </style> + <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> + <script type="text/javascript" charset="utf-8"> + + + + + + var url = "http://search.twitter.com/search.json?callback=getTweets"; + + var intervalID; + + + function preventBehavior(e) { e.preventDefault(); }; + + + function onWinLoad() + { + document.addEventListener("deviceready",onDeviceReady,false); + } + + function onDeviceReady() + { + + var funk = function(position) + { + callback(position.coords.latitude, position.coords.longitude); + }; + + var fail = function(error) + { + alert("error :: " + error); + } + + intervalID = navigator.geolocation.watchPosition(funk,fail); + + + + window.addEventListener("unload",onWindowUnload,false); + } + + function onBackBtn() + { + navigator.geolocation.clearWatch(intervalID); + } + + + + + function onWindowUnload() + { + + } + + function getCurrentLocation() + { + document.getElementById("location2").innerHTML = "Getting current location ..."; + var funk = function(position) + { + document.getElementById("location2").innerHTML = "Lat: "+position.coords.latitude+ " Lon: " +position.coords.longitude; + }; + + var fail = function(error) + { + alert("error :: " + error); + } + navigator.geolocation.getCurrentPosition(funk,fail); + } + + + + function callback(lat, lon) + { + //navigator.geolocation.stop(); + //alert("Callback :: " + lat + "," + lon); + print(lat,lon); + + var geocode = "&geocode=" + lat + "%2C" + lon + "%2C1mi"; + var fullUrl = url + geocode; + var head = document.getElementsByTagName('head'); + var script = document.createElement('script'); + script.src = fullUrl; + head[0].appendChild(script); +} + +function getTweets(json) { + var q; + var parent = document.getElementById('tweetList'); + parent.innerHTML = ''; + var child; + + for (var i = 0; i < json.results.length; i++) { + q = json.results[i]; + child = document.createElement("div"); + child.setAttribute("class","tweet"); + child.innerHTML = '<div class="avatar"><img src="'+q.profile_image_url+'" alt="avatar" width="48" height="48" /></div>'; + child.innerHTML += '<div class="content"><a href="http://m.twitter.com/'+q.from_user+'">'+q.from_user+'</a> '+q.text+'<div class="extra">'+q.location+' ('+q.created_at+')</div></div>'; + parent.appendChild(child); + } +} + +function print(lat,lon) +{ + document.getElementById("location1").innerHTML = "Lat: "+lat+ " Lon: " +lon;// + " TS: " + (new Date().getTime()); +} + + + </script> + </head> + + <body id="stage" class="theme" onload="onWinLoad()"> + <div class="topBar"> + <a href="index.html" onclick="onBackBtn()"> + <span class="back_button">Back</span> + </a> + <span class="pageTitle">GeoLocation</span> + </div> + <div id="container"> + + <div class="item" style="text-align:center;" id="location1">Getting your current location ...</div> + + <p>Find who are tweeting within 1 mile radius of where you are!</p> + + + + <div id="tweetList"> + + </div> + + </div> + </body> +</html> diff --git a/iPhone/PhoneGapTutorial/www/images/FoggyRocks.png b/iPhone/PhoneGapTutorial/www/images/FoggyRocks.png new file mode 100644 index 0000000..2597556 Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/FoggyRocks.png differ diff --git a/iPhone/PhoneGapTutorial/www/images/TutBG.png b/iPhone/PhoneGapTutorial/www/images/TutBG.png new file mode 100644 index 0000000..db3a206 Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/TutBG.png differ diff --git a/iPhone/PhoneGapTutorial/www/images/back_button.png b/iPhone/PhoneGapTutorial/www/images/back_button.png new file mode 100644 index 0000000..ca0a70a Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/back_button.png differ diff --git a/iPhone/PhoneGapTutorial/www/images/back_button_clicked.png b/iPhone/PhoneGapTutorial/www/images/back_button_clicked.png new file mode 100644 index 0000000..ca68ce2 Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/back_button_clicked.png differ diff --git a/iPhone/PhoneGapTutorial/www/images/backgroundStripes.png b/iPhone/PhoneGapTutorial/www/images/backgroundStripes.png new file mode 100755 index 0000000..cab0e98 Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/backgroundStripes.png differ diff --git a/iPhone/PhoneGapTutorial/www/images/bar_large.png b/iPhone/PhoneGapTutorial/www/images/bar_large.png new file mode 100644 index 0000000..354c722 Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/bar_large.png differ diff --git a/iPhone/PhoneGapTutorial/www/images/bar_media.png b/iPhone/PhoneGapTutorial/www/images/bar_media.png new file mode 100644 index 0000000..5d7f9c3 Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/bar_media.png differ diff --git a/iPhone/PhoneGapTutorial/www/images/header.png b/iPhone/PhoneGapTutorial/www/images/header.png new file mode 100644 index 0000000..f78a44b Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/header.png differ diff --git a/iPhone/PhoneGapTutorial/www/images/header2.png b/iPhone/PhoneGapTutorial/www/images/header2.png new file mode 100644 index 0000000..8ad80e5 Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/header2.png differ diff --git a/iPhone/PhoneGapTutorial/www/images/header3.png b/iPhone/PhoneGapTutorial/www/images/header3.png new file mode 100644 index 0000000..07d45c8 Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/header3.png differ diff --git a/iPhone/PhoneGapTutorial/www/images/list_arrow.png b/iPhone/PhoneGapTutorial/www/images/list_arrow.png new file mode 100644 index 0000000..9f68c71 Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/list_arrow.png differ diff --git a/iPhone/PhoneGapTutorial/www/images/list_item_selected_bg.png b/iPhone/PhoneGapTutorial/www/images/list_item_selected_bg.png new file mode 100644 index 0000000..6bb0ad0 Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/list_item_selected_bg.png differ diff --git a/iPhone/PhoneGapTutorial/www/images/on_off_bg.png b/iPhone/PhoneGapTutorial/www/images/on_off_bg.png new file mode 100644 index 0000000..36b2eac Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/on_off_bg.png differ diff --git a/iPhone/PhoneGapTutorial/www/images/selection.png b/iPhone/PhoneGapTutorial/www/images/selection.png new file mode 100644 index 0000000..537e3f0 Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/images/selection.png differ diff --git a/iPhone/PhoneGapTutorial/www/index.html b/iPhone/PhoneGapTutorial/www/index.html new file mode 100755 index 0000000..7db14d6 --- /dev/null +++ b/iPhone/PhoneGapTutorial/www/index.html @@ -0,0 +1,72 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> + <head> + <meta name="viewport" content="width=320; user-scalable=no" /> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>PhoneGap</title> + <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8"> + <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> + <script type="text/javascript" charset="utf-8"> + + + function onWinLoad() + { + document.addEventListener("deviceready",onDeviceReady,false); + } + + function onDeviceReady() + { + + // do your thing! + } + + </script> + </head> + + <body id="stage" class="theme" onload="onWinLoad()"> + <div class="topBar"> + <span class="pageTitle">PhoneGap Tutorial</span> + </div> + + + + <a href="accelerometer.html"> + <div class="item"> + <h2>Accelerometer</h2> + </div></a> + + <a href="notification.html"> + <div class="item"> + <h2>Notification</h2> + </div> + </a> + + <a href="contacts.html"> + <div class="item"> + <h2>Contacts</h2> + </div> + </a> + + <a href="geolocation.html"> + <div class="item"> + <h2>GeoLocation</h2> + </div> + </a> + + <a href="inputs.html"> + <div class="item" + <h2>Form Inputs</h2> + </div> + </a> + + + <a href="media.html"> + <div class="item"> + <h2>Media</h2> + </div> + </a> + + + </body> +</html> diff --git a/iPhone/PhoneGapTutorial/www/inputs.html b/iPhone/PhoneGapTutorial/www/inputs.html new file mode 100755 index 0000000..67a80ee --- /dev/null +++ b/iPhone/PhoneGapTutorial/www/inputs.html @@ -0,0 +1,98 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> + <head> + <meta name="viewport" content="width=320; user-scalable=no" /> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>PhoneGap</title> + <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8"> + + <style> + + input + { + width: 180px; + margin-bottom: 18px; + margin-top: 4px; + -webkit-border-radius: 5px; + left:100px; + position:absolute; + } + + input.disabled + { + opacity: 0.5; + } + + label + { + margin-bottom: 18px; + line-height:36px; + } + + </style> + <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> + <script type="text/javascript" charset="utf-8"> + + + + function onWinLoad() + { + document.addEventListener("deviceready",onDeviceReady,false); + } + + function onDeviceReady() + { + + } + + </script> + </head> + + <body id="stage" class="theme" onload="onWinLoad()"> + <div class="topBar"> + <a href="index.html"> + <span class="back_button">Back</span> + </a> + <span class="pageTitle">Form Inputs</span> + </div> + + <form action="/"> + <br/> + + <!-- display a standard keyboard --> + <label for="tiText">Text:</label> + <input type="text" id="tiText"/> + <br/> + + <!-- display a telephone keypad --> + <label for="tiTel">Telephone:</label> + <input type="tel" id="tiTel"/> + <br/> + + <!-- display a URL keyboard --> + <label for="tiUrl">URL:</label> + <input type="url" id="tiUrl"/> + <br/> + + <!-- display an email keyboard --> + <label for="tiEmail">Email:</label> + <input type="email" id="tiEmail"/> + <br/> + + <!-- display a numeric keyboard --> + <label for="tiZip">Zip Code:</label> + <input type="text" pattern="[0-9]*" id="tiZip"/> + <br/> + + <label for="tiSearch">Search:</label> + <input type="search" id="tiSearch" style="width:192px;"/> + <br/> + + </form> + + + + </a> + </body> +</html> diff --git a/iPhone/PhoneGapTutorial/www/master.css b/iPhone/PhoneGapTutorial/www/master.css new file mode 100755 index 0000000..dddb7cd --- /dev/null +++ b/iPhone/PhoneGapTutorial/www/master.css @@ -0,0 +1,304 @@ + +body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6 +{ + margin: 0pt; + padding: 0pt; +} + + + +body +{ + background:#000 url(images/TutBG.png) repeat-y fixed 0 0; + color:#666; + font-family:Helvetica,'Lucida Grande',sans-serif; + line-height:1.5em; + margin:0px; + margin-bottom:20px; + +} + +#header{ + position: relative; + left: 0px; + top: 0px; + height: 44px; + font-size: 16pt; + border-top-width: 0px; + border-right-width: 1px; + border-bottom-width: 0px; + border-left-width: 1px; + width: auto; + margin-right: 0px; + margin-left: 0px; + background: url( header.png ); +} + +.header_title{ + text-align: center; + position: relative; + font-weight: bold; + color: rgb(255, 255, 255); + text-shadow: rgba(0, 0, 0, 0.6) 0px -1px 0px; +} + +.view{ + background: url( images/backgroundStripes.png ); + background-repeat: repeat; + min-height: 406px; +} + +.topBar +{ + color:#eee; + font-size:1.2em; + text-align:center; + margin:0; + margin-top:0px; + padding:0; + background-image: url( 'images/header.png' ); + background-repeat: repeat-x; + height:44px; + text-height:44px; +} + + +.pageTitle +{ + text-align: center; + color:#FFF; + line-height:44px; +} + +.back_button +{ + font-weight: bold; + font-size: 12px; + color: rgb(255, 255, 255); + text-shadow: rgba(0, 0, 0, 0.6) 0px -1px 0px; + text-align: center; + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; + height: 22px; + padding-top: 4px; + padding-bottom: 4px; + width: 60px; + line-height:22px; + right: auto; + bottom: auto; + margin-top: 0px; + position:absolute; + left:4px; + top:11px; + -webkit-border-image: url(images/back_button.png) 0 5 0 16 / 1px 5px 1px 16px stretch stretch; +} + +.list +{ + margin-top: 5px; +} + +.list li{ + width: 290px; + height: 20px; + background-color: #FFF; + border-left: 1px solid #AAA; + border-right: 1px solid #AAA; + border-bottom: 1px solid #AAA; + + list-style-type: none; + padding: 12px 5px 10px 5px; + margin-left: -36px; +} + +.list li.active{ + background-image: url( 'selection.png' ); + background-repeat: repeat-x; + background-color: #194fdb !important; +} + +.list li:first-of-type{ + border-top: 1px solid #AAA; + -webkit-border-top-right-radius: 8px 8px; + -webkit-border-top-left-radius: 8px 8px; +} + +.list li:last-of-type{ + border-top: none; + border-bottom: 1px solid #AAA; + + -webkit-border-bottom-left-radius: 8px 8px; + -webkit-border-bottom-right-radius: 8px 8px; +} + +.list li:only-of-type{ + border-top: 1px solid #AAA; + border-bottom: 1px solid #AAA; + + -webkit-border-top-right-radius: 8px 8px; + -webkit-border-top-left-radius: 8px 8px; + -webkit-border-bottom-left-radius: 8px 8px; + -webkit-border-bottom-right-radius: 8px 8px; + +} + +.list .list_label{ + font-weight: bold; + color: #000; + text-align: left; + width: 145px; + float: left; +} + +.list .list_value{ + color: #6e82a8; + text-align: right; + width: 140px; + float: right; +} + +.list .selected_item{ + color: #4c566c; +} + +.list_section_label{ + font-size: 16px; + font-weight: bold; + margin-left: 15px; + text-shadow: rgba(255, 255, 255, 1) 0px 1px 0px; + color: #4c566c; +} + +.list_section_note{ + font-size: 14px; + margin-left: 15px; + text-shadow: rgba(255, 255, 255, 1) 0px 1px 0px; + color: #4c566c; + text-align: center; + margin-bottom: 15px; + margin-top: -5px; +} + + + +.item +{ + background:rgba(64,64,64,0.5); + border: 1px solid rgba(128,128,128,0.5); + -webkit-border-radius: 5px; + border-radius: 5px; + clear:both; + margin:15px 6px 0; + width:295px; + padding:4px 0px 2px 10px; +} + +a +{ + color:#FFF; + text-decoration:none; +} + + +#info{ + background:#ffa; + border: 1px solid #ffd324; + -webkit-border-radius: 5px; + border-radius: 5px; + clear:both; + margin:15px 6px 0; + width:295px; + padding:4px 0px 2px 10px; +} + +#info h4{ + font-size:.95em; + margin:0; + padding:0; +} + +#stage.theme{ + padding-top:3px; +} + +/* Definition List */ +#Page1 > dl{ + padding-top:10px; + clear:both; + margin:0; + list-style-type:none; + padding-left:10px; + overflow:auto; +} + +#Page1 > dl > dt{ + font-weight:bold; + float:left; + margin-left:5px; +} + +#Page1 > dl > dd{ + width:45px; + float:left; + color:#a87; + font-weight:bold; +} + +/* Content Styling */ +h1, h2, p{ + margin:1em 0 .5em 13px; +} + +h1{ + color:#eee; + font-size:1.6em; + text-align:center; + margin:0; + margin-top:15px; + padding:0; +} + +h2{ + clear:both; + margin:0; + padding:3px; + font-size:1em; + text-align:center; +} + + + +/* Stage Buttons */ +#stage.theme a.btn +{ + border: 1px solid #555; + -webkit-border-radius: 5px; + border-radius: 5px; + text-align:center; + display:block; + float:left; + background:#444; + width:150px; + color:#9ab; + font-size:1.1em; + text-decoration:none; + padding:1.2em 0; + margin:3px 0px 3px 5px; +} + +a.btn.large +{ + width:64px; + height:32px; + padding:1.2em 0; +} + + + + + + + + + diff --git a/iPhone/PhoneGapTutorial/www/media.html b/iPhone/PhoneGapTutorial/www/media.html new file mode 100755 index 0000000..b00cdd6 --- /dev/null +++ b/iPhone/PhoneGapTutorial/www/media.html @@ -0,0 +1,111 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> + <head> + <meta name="viewport" content="width=320; user-scalable=no" /> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>PhoneGap</title> + <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8"> + + <style> + + .mediaBtn + { + clear:none; + float:left; + background:rgba(64,64,64,0.5); + border: 1px solid rgba(128,128,128,0.5); + -webkit-border-radius: 5px; + border-radius: 5px; + margin:20px; + width:64px; + padding:4px; + + } + + </style> + <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> + <script type="text/javascript" charset="utf-8"> + + var PS_STOPPED = 0; + var PS_PLAYING = 1; + var PS_PAUSED = 2; + var PS_RECORDING = 3; + + var currentState; + + var mediaFile = null; + + function onPlayStopBtn() + { + if(currentState != PS_PLAYING) + { + mediaFile.play({numberOfLoops:0}); + currentState = PS_PLAYING; + document.getElementById("playText").innerHTML = "Stop"; + } + else + { + mediaFile.stop(); + currentState = PS_STOPPED; + document.getElementById("playText").innerHTML = "Play"; + } + + + } + + + function onMediaCreatedSuccess(obj) + { + alert("successfully created media"); + } + + function onMediaCreatedError(err) + { + alert("error creating media"); + } + + + + + function onWinLoad() + { + document.addEventListener("deviceready",onDeviceReady,false); + } + + function onDeviceReady() + { + mediaFile = new Media('percBass.wav',onMediaCreatedSuccess,onMediaCreatedError); + updateButtonStates(); + } + + </script> + </head> + + <body id="stage" class="theme" onload="onWinLoad()"> + <div class="topBar"> + <a href="index.html"> + <span class="back_button">Back</span> + </a> + <span class="pageTitle">Media</span> + </div> + + <h2>percBass.wav</h2> + <a href="#" onclick="onPlayStopBtn();"> + <div class="mediaBtn"> + <h2 id="playText">Play</h2> + </div> + </a> + + + + <!-- + <a href="#" onclick="onRecordBtn();"> + <div class="mediaBtn"> + <h2>Record</h2> + </div> + + </a> + --> + </body> +</html> diff --git a/iPhone/PhoneGapTutorial/www/notification.html b/iPhone/PhoneGapTutorial/www/notification.html new file mode 100755 index 0000000..42afaef --- /dev/null +++ b/iPhone/PhoneGapTutorial/www/notification.html @@ -0,0 +1,105 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> + <head> + <meta name="viewport" content="width=320; user-scalable=no" /> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>PhoneGap</title> + <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8"> + <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> + <script type="text/javascript" charset="utf-8"> + + + var isActivityShowing = false; + + function onAlertBtn() + { + navigator.notification.alert("Custom Message","Custom Title", "Custom Label"); + } + + function onActivityBtn() + { + + if(isActivityShowing) + { + navigator.notification.activityStop(); + } + else + { + navigator.notification.activityStart(); + } + + isActivityShowing = !isActivityShowing; + + document.getElementById("activityText").innerHTML = isActivityShowing ? "Hide Activity Indicator" : "Show Activity Indicator"; + + } + + function onLoadingBtn() + { + navigator.notification.loadingStart({duration:2}); + } + + function onVibrateBtn() + { + navigator.notification.vibrate(100); // note, iPhone ignores the ms param + } + + function onBeepBtn() + { + navigator.notification.beep(); + } + + function onWinLoad() + { + + document.addEventListener("deviceready",onDeviceReady,false); + } + + function onDeviceReady() + { + + } + + </script> + </head> + + <body id="stage" class="theme" onload="onWinLoad()"> + <div class="topBar"> + <a href="index.html"> + <span class="back_button">Back</span> + </a> + <span class="pageTitle">Notification</span> + </div> + + <a href="#" onclick="onAlertBtn();"> + <div class="item"> + <h2>Show Custom Alert</h2> + </div></a> + + <a href="#" onclick="onActivityBtn();"> + <div class="item"> + <h2 id="activityText">Show Activity Indicator</h2> + </div> + </a> + + <a href="#" onclick="onVibrateBtn();"> + <div class="item"> + <h2>Vibrate</h2> + </div> + </a> + + <a href="#" onclick="onLoadingBtn();"> + <div class="item"> + <h2>Show Loading ( 2 Seconds )</h2> + </div> + </a> + + <a href="#" onclick="onBeepBtn();"> + <div class="item"> + <h2>Beep</h2> + </div> + </a> + + </body> +</html> diff --git a/iPhone/PhoneGapTutorial/www/percBass.wav b/iPhone/PhoneGapTutorial/www/percBass.wav new file mode 100755 index 0000000..e63dcc4 Binary files /dev/null and b/iPhone/PhoneGapTutorial/www/percBass.wav differ diff --git a/iPhone/PhoneGapTutorial/www/phonegap.js b/iPhone/PhoneGapTutorial/www/phonegap.js new file mode 100644 index 0000000..803abb6 --- /dev/null +++ b/iPhone/PhoneGapTutorial/www/phonegap.js @@ -0,0 +1,1482 @@ +if (typeof(DeviceInfo) != 'object') + DeviceInfo = {}; + +/** + * This represents the PhoneGap API itself, and provides a global namespace for accessing + * information about the state of PhoneGap. + * @class + */ +PhoneGap = { + queue: { + ready: true, + commands: [], + timer: null + }, + _constructors: [] +}; + +/** + * Boolean flag indicating if the PhoneGap API is available and initialized. + */ // TODO: Remove this, it is unused here ... -jm +PhoneGap.available = DeviceInfo.uuid != undefined; + +/** + * Add an initialization function to a queue that ensures it will run and initialize + * application constructors only once PhoneGap has been initialized. + * @param {Function} func The function callback you want run once PhoneGap is initialized + */ +PhoneGap.addConstructor = function(func) { + var state = document.readyState; + if ( ( state == 'loaded' || state == 'complete' ) && DeviceInfo.uuid != null ) + { + func(); + } + else + { + PhoneGap._constructors.push(func); + } +}; + +(function() + { + var timer = setInterval(function() + { + + var state = document.readyState; + + if ( ( state == 'loaded' || state == 'complete' ) && DeviceInfo.uuid != null ) + { + clearInterval(timer); // stop looking + // run our constructors list + while (PhoneGap._constructors.length > 0) + { + var constructor = PhoneGap._constructors.shift(); + try + { + constructor(); + } + catch(e) + { + if (typeof(debug['log']) == 'function') + { + debug.log("Failed to run constructor: " + debug.processMessage(e)); + } + else + { + alert("Failed to run constructor: " + e.message); + } + } + } + // all constructors run, now fire the deviceready event + var e = document.createEvent('Events'); + e.initEvent('deviceready'); + document.dispatchEvent(e); + } + }, 1); +})(); + + +/** + * Execute a PhoneGap command in a queued fashion, to ensure commands do not + * execute with any race conditions, and only run when PhoneGap is ready to + * recieve them. + * @param {String} command Command to be run in PhoneGap, e.g. "ClassName.method" + * @param {String[]} [args] Zero or more arguments to pass to the method + */ +PhoneGap.exec = function() { + PhoneGap.queue.commands.push(arguments); + if (PhoneGap.queue.timer == null) + PhoneGap.queue.timer = setInterval(PhoneGap.run_command, 10); +}; + +/** + * Internal function used to dispatch the request to PhoneGap. It processes the + * command queue and executes the next command on the list. If one of the + * arguments is a JavaScript object, it will be passed on the QueryString of the + * url, which will be turned into a dictionary on the other end. + * @private + */ +PhoneGap.run_command = function() { + if (!PhoneGap.available || !PhoneGap.queue.ready) + return; + + PhoneGap.queue.ready = false; + + var args = PhoneGap.queue.commands.shift(); + if (PhoneGap.queue.commands.length == 0) { + clearInterval(PhoneGap.queue.timer); + PhoneGap.queue.timer = null; + } + + var uri = []; + var dict = null; + for (var i = 1; i < args.length; i++) { + var arg = args[i]; + if (arg == undefined || arg == null) + arg = ''; + if (typeof(arg) == 'object') + dict = arg; + else + uri.push(encodeURIComponent(arg)); + } + var url = "gap://" + args[0] + "/" + uri.join("/"); + if (dict != null) { + var query_args = []; + for (var name in dict) { + if (typeof(name) != 'string') + continue; + query_args.push(encodeURIComponent(name) + "=" + encodeURIComponent(dict[name])); + } + if (query_args.length > 0) + url += "?" + query_args.join("&"); + } + document.location = url; + +}; +/** + * This class contains acceleration information + * @constructor + * @param {Number} x The force applied by the device in the x-axis. + * @param {Number} y The force applied by the device in the y-axis. + * @param {Number} z The force applied by the device in the z-axis. + */ +function Acceleration(x, y, z) { + /** + * The force applied by the device in the x-axis. + */ + this.x = x; + /** + * The force applied by the device in the y-axis. + */ + this.y = y; + /** + * The force applied by the device in the z-axis. + */ + this.z = z; + /** + * The time that the acceleration was obtained. + */ + this.timestamp = new Date().getTime(); +} + +/** + * This class specifies the options for requesting acceleration data. + * @constructor + */ +function AccelerationOptions() { + /** + * The timeout after which if acceleration data cannot be obtained the errorCallback + * is called. + */ + this.timeout = 10000; +} +/** + * This class provides access to device accelerometer data. + * @constructor + */ +function Accelerometer() { + /** + * The last known acceleration. + */ + this.lastAcceleration = null; +} + +/** + * Asynchronously aquires the current acceleration. + * @param {Function} successCallback The function to call when the acceleration + * data is available + * @param {Function} errorCallback The function to call when there is an error + * getting the acceleration data. + * @param {AccelerationOptions} options The options for getting the accelerometer data + * such as timeout. + */ +Accelerometer.prototype.getCurrentAcceleration = function(successCallback, errorCallback, options) { + // If the acceleration is available then call success + // If the acceleration is not available then call error + + // Created for iPhone, Iphone passes back _accel obj litteral + if (typeof successCallback == "function") { + var accel = new Acceleration(_accel.x,_accel.y,_accel.z); + Accelerometer.lastAcceleration = accel; + successCallback(accel); + } +} + +/** + * Asynchronously aquires the acceleration repeatedly at a given interval. + * @param {Function} successCallback The function to call each time the acceleration + * data is available + * @param {Function} errorCallback The function to call when there is an error + * getting the acceleration data. + * @param {AccelerationOptions} options The options for getting the accelerometer data + * such as timeout. + */ + +Accelerometer.prototype.watchAcceleration = function(successCallback, errorCallback, options) { + //this.getCurrentAcceleration(successCallback, errorCallback, options); + // TODO: add the interval id to a list so we can clear all watches + var frequency = (options != undefined && options.frequency != undefined) ? options.frequency : 10000; + var updatedOptions = { + desiredFrequency:frequency + } + PhoneGap.exec("Accelerometer.start",options); + + return setInterval(function() { + navigator.accelerometer.getCurrentAcceleration(successCallback, errorCallback, options); + }, frequency); +} + +/** + * Clears the specified accelerometer watch. + * @param {String} watchId The ID of the watch returned from #watchAcceleration. + */ +Accelerometer.prototype.clearWatch = function(watchId) { + PhoneGap.exec("Accelerometer.stop"); + clearInterval(watchId); +} + +PhoneGap.addConstructor(function() { + if (typeof navigator.accelerometer == "undefined") navigator.accelerometer = new Accelerometer(); +}); +// Gets the function name of a Function object, else uses "alert" if anonymous +function GetFunctionName(fn) +{ + if (fn) { + var m = fn.toString().match(/^\s*function\s+([^\s\(]+)/); + return m ? m[1] : "alert"; + } else { + return null; + } +} + +/** + * This class provides access to the device camera. + * @constructor + */ +function Camera() { + +} + +/** + * + * @param {Function} successCallback + * @param {Function} errorCallback + * @param {Object} options + */ +Camera.prototype.getPicture = function(successCallback, errorCallback, options) { + PhoneGap.exec("Camera.getPicture", GetFunctionName(successCallback), GetFunctionName(errorCallback), options); +} + +PhoneGap.addConstructor(function() { + if (typeof navigator.camera == "undefined") navigator.camera = new Camera(); +}); +// Gets the function name of a Function object, else uses "alert" if anonymous +function GetFunctionName(fn) +{ + if (fn) { + var m = fn.toString().match(/^\s*function\s+([^\s\(]+)/); + return m ? m[1] : "alert"; + } else { + return null; + } +} + +/** + * This class provides access to the device contacts. + * @constructor + */ + +function Contact(jsonObject) { + this.firstName = ""; + this.lastName = ""; + this.name = ""; + this.phones = {}; + this.emails = {}; + this.address = ""; +} + +Contact.prototype.displayName = function() +{ + // TODO: can be tuned according to prefs + return this.name; +} + +function ContactManager() { + // Dummy object to hold array of contacts + this.contacts = []; + this.timestamp = new Date().getTime(); +} + +ContactManager.prototype.getAllContacts = function(successCallback, errorCallback, options) { + PhoneGap.exec("Contacts.allContacts", GetFunctionName(successCallback), options); +} + +// THE FUNCTIONS BELOW ARE iPHONE ONLY FOR NOW + +ContactManager.prototype.newContact = function(contact, successCallback, options) { + if (!options) options = {}; + options.successCallback = GetFunctionName(successCallback); + + PhoneGap.exec("Contacts.newContact", contact.firstName, contact.lastName, contact.phoneNumber, + options); +} + +ContactManager.prototype.chooseContact = function(successCallback, options) { + PhoneGap.exec("Contacts.chooseContact", GetFunctionName(successCallback), options); +} + +ContactManager.prototype.displayContact = function(contactID, errorCallback, options) { + PhoneGap.exec("Contacts.displayContact", contactID, GetFunctionName(errorCallback), options); +} + +ContactManager.prototype.removeContact = function(contactID, successCallback, options) { + PhoneGap.exec("Contacts.removeContact", contactID, GetFunctionName(successCallback), options); +} + +ContactManager.prototype.contactsCount = function(successCallback, errorCallback) { + PhoneGap.exec("Contacts.contactsCount", GetFunctionName(successCallback)); +} + +PhoneGap.addConstructor(function() { + if (typeof navigator.contacts == "undefined") navigator.contacts = new ContactManager(); +}); +/** + * This class provides access to the debugging console. + * @constructor + */ +function DebugConsole() { +} + +/** + * Utility function for rendering and indenting strings, or serializing + * objects to a string capable of being printed to the console. + * @param {Object|String} message The string or object to convert to an indented string + * @private + */ +DebugConsole.prototype.processMessage = function(message) { + if (typeof(message) != 'object') { + return message; + } else { + /** + * @function + * @ignore + */ + function indent(str) { + return str.replace(/^/mg, " "); + } + /** + * @function + * @ignore + */ + function makeStructured(obj) { + var str = ""; + for (var i in obj) { + try { + if (typeof(obj[i]) == 'object') { + str += i + ":\n" + indent(makeStructured(obj[i])) + "\n"; + } else { + str += i + " = " + indent(String(obj[i])).replace(/^ /, "") + "\n"; + } + } catch(e) { + str += i + " = EXCEPTION: " + e.message + "\n"; + } + } + return str; + } + return "Object:\n" + makeStructured(message); + } +}; + +/** + * Print a normal log message to the console + * @param {Object|String} message Message or object to print to the console + */ +DebugConsole.prototype.log = function(message) { + if (PhoneGap.available) + PhoneGap.exec('DebugConsole.log', + this.processMessage(message), + { logLevel: 'INFO' } + ); + else + console.log(message); +}; + +/** + * Print a warning message to the console + * @param {Object|String} message Message or object to print to the console + */ +DebugConsole.prototype.warn = function(message) { + if (PhoneGap.available) + PhoneGap.exec('DebugConsole.log', + this.processMessage(message), + { logLevel: 'WARN' } + ); + else + console.error(message); +}; + +/** + * Print an error message to the console + * @param {Object|String} message Message or object to print to the console + */ +DebugConsole.prototype.error = function(message) { + if (PhoneGap.available) + PhoneGap.exec('DebugConsole.log', + this.processMessage(message), + { logLevel: 'ERROR' } + ); + else + console.error(message); +}; + +PhoneGap.addConstructor(function() { + window.debug = new DebugConsole(); +}); +/** + * this represents the mobile device, and provides properties for inspecting the model, version, UUID of the + * phone, etc. + * @constructor + */ +function Device() +{ + this.platform = null; + this.version = null; + this.name = null; + this.gap = null; + this.uuid = null; + try + { + this.platform = DeviceInfo.platform; + this.version = DeviceInfo.version; + this.name = DeviceInfo.name; + this.gap = DeviceInfo.gap; + this.uuid = DeviceInfo.uuid; + + } + catch(e) + { + // TODO: + } + this.available = PhoneGap.available = this.uuid != null; +} + +PhoneGap.addConstructor(function() { + navigator.device = window.device = new Device(); +}); + + + +PhoneGap.addConstructor(function() { if (typeof navigator.fileMgr == "undefined") navigator.fileMgr = new FileMgr();}); + + +/** + * This class provides iPhone read and write access to the mobile device file system. + * Based loosely on http://www.w3.org/TR/2009/WD-FileAPI-20091117/#dfn-empty + */ +function FileMgr() +{ + this.fileWriters = {}; // empty maps + this.fileReaders = {}; + + this.docsFolderPath = "../../Documents"; + this.tempFolderPath = "../../tmp"; + this.freeDiskSpace = -1; + this.getFileBasePaths(); + this.getFreeDiskSpace(); +} + +// private, called from Native Code +FileMgr.prototype._setPaths = function(docs,temp) +{ + this.docsFolderPath = docs; + this.tempFolderPath = temp; +} + +// private, called from Native Code +FileMgr.prototype._setFreeDiskSpace = function(val) +{ + this.freeDiskSpace = val; +} + + +// FileWriters add/remove +// called internally by writers +FileMgr.prototype.addFileWriter = function(filePath,fileWriter) +{ + this.fileWriters[filePath] = fileWriter; +} + +FileMgr.prototype.removeFileWriter = function(filePath) +{ + this.fileWriters[filePath] = null; +} + +// File readers add/remove +// called internally by readers +FileMgr.prototype.addFileReader = function(filePath,fileReader) +{ + this.fileReaders[filePath] = fileReader; +} + +FileMgr.prototype.removeFileReader = function(filePath) +{ + this.fileReaders[filePath] = null; +} + +/******************************************* + * + * private reader callback delegation + * called from native code + */ +FileMgr.prototype.reader_onloadstart = function(filePath,result) +{ + this.fileReaders[filePath].onloadstart(result); +} + +FileMgr.prototype.reader_onprogress = function(filePath,result) +{ + this.fileReaders[filePath].onprogress(result); +} + +FileMgr.prototype.reader_onload = function(filePath,result) +{ + this.fileReaders[filePath].result = unescape(result); + this.fileReaders[filePath].onload(this.fileReaders[filePath].result); +} + +FileMgr.prototype.reader_onerror = function(filePath,err) +{ + this.fileReaders[filePath].result = err; + this.fileReaders[filePath].onerror(err); +} + +FileMgr.prototype.reader_onloadend = function(filePath,result) +{ + this.fileReaders[filePath].onloadend(result); +} + +/******************************************* + * + * private writer callback delegation + * called from native code +*/ +FileMgr.prototype.writer_onerror = function(filePath,err) +{ + this.fileWriters[filePath].onerror(err); +} + +FileMgr.prototype.writer_oncomplete = function(filePath,result) +{ + this.fileWriters[filePath].oncomplete(result); // result contains bytes written +} + + +FileMgr.prototype.getFileBasePaths = function() +{ + PhoneGap.exec("File.getFileBasePaths"); +} + +FileMgr.prototype.testFileExists = function(fileName, successCallback, errorCallback) +{ + PhoneGap.exec("File.testFileExists",fileName); +} + +FileMgr.prototype.testDirectoryExists = function(dirName, successCallback, errorCallback) +{ + this.successCallback = successCallback; + this.errorCallback = errorCallback; + PhoneGap.exec("File.testDirectoryExists",dirName); +} + +FileMgr.prototype.createDirectory = function(dirName, successCallback, errorCallback) +{ + this.successCallback = successCallback; + this.errorCallback = errorCallback; + PhoneGap.exec("File.createDirectory",dirName); +} + +FileMgr.prototype.deleteDirectory = function(dirName, successCallback, errorCallback) +{ + this.successCallback = successCallback; + this.errorCallback = errorCallback; + PhoneGap.exec("File.deleteDirectory",dirName); +} + +FileMgr.prototype.deleteFile = function(fileName, successCallback, errorCallback) +{ + this.successCallback = successCallback; + this.errorCallback = errorCallback; + PhoneGap.exec("File.deleteFile",fileName); +} + +FileMgr.prototype.getFreeDiskSpace = function(successCallback, errorCallback) +{ + if(this.freeDiskSpace > 0) + { + return this.freeDiskSpace; + } + else + { + this.successCallback = successCallback; + this.errorCallback = errorCallback; + PhoneGap.exec("File.getFreeDiskSpace"); + } +} + +File.prototype.hasRead = function(data) +{ + // null, this is part of the Android implementation interface +} + +// File Reader + + +function FileReader() +{ + this.fileName = ""; + this.result = null; + this.onloadstart = null; + this.onprogress = null; + this.onload = null; + this.onerror = null; + this.onloadend = null; +} + + +FileReader.prototype.abort = function() +{ + // Not Implemented +} + +FileReader.prototype.readAsText = function(file) +{ + if(this.fileName && this.fileName.length > 0) + { + navigator.fileMgr.removeFileReader(this.fileName,this); + } + this.fileName = file; + navigator.fileMgr.addFileReader(this.fileName,this); + //alert("Calling File.read : " + this.fileName); + //window.location = "gap://File.readFile/"+ file; + PhoneGap.exec("File.readFile",this.fileName); +} + +// File Writer + +function FileWriter() +{ + this.fileName = ""; + this.result = null; + this.readyState = 0; // EMPTY + this.result = null; + this.onerror = null; + this.oncomplete = null; +} + +FileWriter.prototype.writeAsText = function(file,text,bAppend) +{ + if(this.fileName && this.fileName.length > 0) + { + navigator.fileMgr.removeFileWriter(this.fileName,this); + } + this.fileName = file; + if(bAppend != true) + { + bAppend = false; // for null values + } + navigator.fileMgr.addFileWriter(file,this); + this.readyState = 0; // EMPTY + this.result = null; + PhoneGap.exec("File.write",file,text,bAppend); +} + + + + + +/** + * This class provides access to device GPS data. + * @constructor + */ +function Geolocation() { + /** + * The last known GPS position. + */ + this.lastPosition = null; + this.lastError = null; +}; + +/** + * Asynchronously aquires the current position. + * @param {Function} successCallback The function to call when the position + * data is available + * @param {Function} errorCallback The function to call when there is an error + * getting the position data. + * @param {PositionOptions} options The options for getting the position data + * such as timeout. + */ +Geolocation.prototype.getCurrentPosition = function(successCallback, errorCallback, options) +{ + var referenceTime = 0; + + if(this.lastError != null) + { + if(typeof(errorCallback) == 'function') + { + errorCallback.call(null,this.lastError); + + } + this.stop(); + return; + } + + this.start(options); + + var timeout = 20000; // defaults + var interval = 500; + + if (typeof(options) == 'object' && options.interval) + interval = options.interval; + + if (typeof(successCallback) != 'function') + successCallback = function() {}; + if (typeof(errorCallback) != 'function') + errorCallback = function() {}; + + var dis = this; + var delay = 0; + var timer = setInterval(function() { + delay += interval; + + if (typeof(dis.lastPosition) == 'object' && dis.lastPosition.timestamp > referenceTime) + { + clearInterval(timer); + successCallback(dis.lastPosition); + + } + else if (delay > timeout) + { + clearInterval(timer); + errorCallback("Error Timeout"); + } + else if(dis.lastError != null) + { + clearInterval(timer); + errorCallback(dis.lastError); + } + }, interval); +}; + +/** + * Asynchronously aquires the position repeatedly at a given interval. + * @param {Function} successCallback The function to call each time the position + * data is available + * @param {Function} errorCallback The function to call when there is an error + * getting the position data. + * @param {PositionOptions} options The options for getting the position data + * such as timeout and the frequency of the watch. + */ +Geolocation.prototype.watchPosition = function(successCallback, errorCallback, options) { + // Invoke the appropriate callback with a new Position object every time the implementation + // determines that the position of the hosting device has changed. + + this.getCurrentPosition(successCallback, errorCallback, options); + var frequency = 10000; + if (typeof(options) == 'object' && options.frequency) + frequency = options.frequency; + + var that = this; + return setInterval(function() + { + that.getCurrentPosition(successCallback, errorCallback, options); + }, frequency); + +}; + + +/** + * Clears the specified position watch. + * @param {String} watchId The ID of the watch returned from #watchPosition. + */ +Geolocation.prototype.clearWatch = function(watchId) { + clearInterval(watchId); +}; + +/** + * Called by the geolocation framework when the current location is found. + * @param {PositionOptions} position The current position. + */ +Geolocation.prototype.setLocation = function(position) +{ + this.lastError = null; + this.lastPosition = position; + +}; + +/** + * Called by the geolocation framework when an error occurs while looking up the current position. + * @param {String} message The text of the error message. + */ +Geolocation.prototype.setError = function(message) { + alert("Error set :: " + message); + this.lastError = message; +}; + +Geolocation.prototype.start = function(args) { + PhoneGap.exec("Location.startLocation", args); +}; + +Geolocation.prototype.stop = function() { + PhoneGap.exec("Location.stopLocation"); +}; + + // replace origObj's functions ( listed in funkList ) with the same method name on proxyObj +function __proxyObj(origObj,proxyObj,funkList) +{ + var replaceFunk = function(org,proxy,fName) + { + org[fName] = function() + { + return proxy[fName].apply(proxy,arguments); + }; + }; + + for(var v in funkList) { replaceFunk(origObj,proxyObj,funkList[v]);} +} + + +PhoneGap.addConstructor(function() +{ + if (typeof navigator._geo == "undefined") + { + navigator._geo = new Geolocation(); + __proxyObj(navigator.geolocation, navigator._geo, + ["setLocation","getCurrentPosition","watchPosition", + "clearWatch","setError","start","stop"]); + + } + +}); +/** + * This class provides access to device Compass data. + * @constructor + */ +function Compass() { + /** + * The last known Compass position. + */ + this.lastHeading = null; + this.lastError = null; + this.callbacks = { + onHeadingChanged: [], + onError: [] + }; +}; + +/** + * Asynchronously aquires the current heading. + * @param {Function} successCallback The function to call when the heading + * data is available + * @param {Function} errorCallback The function to call when there is an error + * getting the heading data. + * @param {PositionOptions} options The options for getting the heading data + * such as timeout. + */ +Compass.prototype.getCurrentHeading = function(successCallback, errorCallback, options) { + if (this.lastHeading == null) { + this.start(options); + } + else + if (typeof successCallback == "function") { + successCallback(this.lastHeading); + } +}; + +/** + * Asynchronously aquires the heading repeatedly at a given interval. + * @param {Function} successCallback The function to call each time the heading + * data is available + * @param {Function} errorCallback The function to call when there is an error + * getting the heading data. + * @param {HeadingOptions} options The options for getting the heading data + * such as timeout and the frequency of the watch. + */ +Compass.prototype.watchHeading= function(successCallback, errorCallback, options) { + // Invoke the appropriate callback with a new Position object every time the implementation + // determines that the position of the hosting device has changed. + + this.getCurrentHeading(successCallback, errorCallback, options); + var frequency = 100; + if (typeof(options) == 'object' && options.frequency) + frequency = options.frequency; + + var self = this; + return setInterval(function() { + self.getCurrentHeading(successCallback, errorCallback, options); + }, frequency); +}; + + +/** + * Clears the specified heading watch. + * @param {String} watchId The ID of the watch returned from #watchHeading. + */ +Compass.prototype.clearWatch = function(watchId) { + clearInterval(watchId); +}; + + +/** + * Called by the geolocation framework when the current heading is found. + * @param {HeadingOptions} position The current heading. + */ +Compass.prototype.setHeading = function(heading) { + this.lastHeading = heading; + for (var i = 0; i < this.callbacks.onHeadingChanged.length; i++) { + var f = this.callbacks.onHeadingChanged.shift(); + f(heading); + } +}; + +/** + * Called by the geolocation framework when an error occurs while looking up the current position. + * @param {String} message The text of the error message. + */ +Compass.prototype.setError = function(message) { + this.lastError = message; + for (var i = 0; i < this.callbacks.onError.length; i++) { + var f = this.callbacks.onError.shift(); + f(message); + } +}; + +Compass.prototype.start = function(args) { + PhoneGap.exec("Location.startHeading", args); +}; + +Compass.prototype.stop = function() { + PhoneGap.exec("Location.stopHeading"); +}; + +PhoneGap.addConstructor(function() { + if (typeof navigator.compass == "undefined") navigator.compass = new Compass(); +}); +/** + * This class provides access to native mapping applications on the device. + */ +function Map() { + +} + +/** + * Shows a native map on the device with pins at the given positions. + * @param {Array} positions + */ +Map.prototype.show = function(positions) { + +} + +PhoneGap.addConstructor(function() { + if (typeof navigator.map == "undefined") navigator.map = new Map(); +}); + +/** + * Media/Audio override. + * + */ + +function Media(src, successCallback, errorCallback) { + + if (!src) { + src = "document://" + String((new Date()).getTime()).replace(/\D/gi,''); // random + } + this.src = src; + this.successCallback = successCallback; + this.errorCallback = errorCallback; + + if (this.src != null) { + PhoneGap.exec("Sound.prepare", this.src, this.successCallback, this.errorCallback); + } +} + +Media.prototype.play = function(options) { + if (this.src != null) { + PhoneGap.exec("Sound.play", this.src, options); + } +} + +Media.prototype.pause = function() { + if (this.src != null) { + PhoneGap.exec("Sound.pause", this.src); + } +} + +Media.prototype.stop = function() { + if (this.src != null) { + PhoneGap.exec("Sound.stop", this.src); + } +} + +Media.prototype.startAudioRecord = function(options) { + if (this.src != null) { + PhoneGap.exec("Sound.startAudioRecord", this.src, options); + } +} + +Media.prototype.stopAudioRecord = function() { + if (this.src != null) { + PhoneGap.exec("Sound.stopAudioRecord", this.src); + } +} + +/** + * This class contains information about any Media errors. + * @constructor + */ +function MediaError() { + this.code = null, + this.message = ""; +} + +MediaError.MEDIA_ERR_ABORTED = 1; +MediaError.MEDIA_ERR_NETWORK = 2; +MediaError.MEDIA_ERR_DECODE = 3; +MediaError.MEDIA_ERR_NONE_SUPPORTED = 4; + + +//if (typeof navigator.audio == "undefined") navigator.audio = new Media(src); +/** + * This class provides access to notifications on the device. + */ +function Notification() { + +} + +/** + * Causes the device to blink a status LED. + * @param {Integer} count The number of blinks. + * @param {String} colour The colour of the light. + */ +Notification.prototype.blink = function(count, colour) { + +}; + +Notification.prototype.vibrate = function(mills) { + PhoneGap.exec("Notification.vibrate"); +}; + +Notification.prototype.beep = function(count, volume) { + // No Volume yet for the iphone interface + // We can use a canned beep sound and call that + new Media('beep.wav').play(); +}; + +/** + * Open a native alert dialog, with a customizable title and button text. + * @param {String} message Message to print in the body of the alert + * @param {String} [title="Alert"] Title of the alert dialog (default: Alert) + * @param {String} [buttonLabel="OK"] Label of the close button (default: OK) + */ +Notification.prototype.alert = function(message, title, buttonLabel) { + var options = {}; + if (title) options.title = title; + if (buttonLabel) options.buttonLabel = buttonLabel; + + if (PhoneGap.available) + PhoneGap.exec('Notification.alert', message, options); + else + alert(message); +}; + +Notification.prototype.activityStart = function() { + PhoneGap.exec("Notification.activityStart"); +}; +Notification.prototype.activityStop = function() { + PhoneGap.exec("Notification.activityStop"); +}; + +Notification.prototype.loadingStart = function(options) { + PhoneGap.exec("Notification.loadingStart", options); +}; +Notification.prototype.loadingStop = function() { + PhoneGap.exec("Notification.loadingStop"); +}; + +PhoneGap.addConstructor(function() { + if (typeof navigator.notification == "undefined") navigator.notification = new Notification(); +}); + +/** + * This class provides access to the device orientation. + * @constructor + */ +function Orientation() { + /** + * The current orientation, or null if the orientation hasn't changed yet. + */ + this.currentOrientation = null; +} + +/** + * Set the current orientation of the phone. This is called from the device automatically. + * + * When the orientation is changed, the DOMEvent \c orientationChanged is dispatched against + * the document element. The event has the property \c orientation which can be used to retrieve + * the device's current orientation, in addition to the \c Orientation.currentOrientation class property. + * + * @param {Number} orientation The orientation to be set + */ +Orientation.prototype.setOrientation = function(orientation) { + Orientation.currentOrientation = orientation; + var e = document.createEvent('Events'); + e.initEvent('orientationChanged', 'false', 'false'); + e.orientation = orientation; + document.dispatchEvent(e); +}; + +/** + * Asynchronously aquires the current orientation. + * @param {Function} successCallback The function to call when the orientation + * is known. + * @param {Function} errorCallback The function to call when there is an error + * getting the orientation. + */ +Orientation.prototype.getCurrentOrientation = function(successCallback, errorCallback) { + // If the position is available then call success + // If the position is not available then call error +}; + +/** + * Asynchronously aquires the orientation repeatedly at a given interval. + * @param {Function} successCallback The function to call each time the orientation + * data is available. + * @param {Function} errorCallback The function to call when there is an error + * getting the orientation data. + */ +Orientation.prototype.watchOrientation = function(successCallback, errorCallback) { + // Invoke the appropriate callback with a new Position object every time the implementation + // determines that the position of the hosting device has changed. + this.getCurrentPosition(successCallback, errorCallback); + return setInterval(function() { + navigator.orientation.getCurrentOrientation(successCallback, errorCallback); + }, 10000); +}; + +/** + * Clears the specified orientation watch. + * @param {String} watchId The ID of the watch returned from #watchOrientation. + */ +Orientation.prototype.clearWatch = function(watchId) { + clearInterval(watchId); +}; + +PhoneGap.addConstructor(function() { + if (typeof navigator.orientation == "undefined") navigator.orientation = new Orientation(); +}); +/** + * This class contains position information. + * @param {Object} lat + * @param {Object} lng + * @param {Object} acc + * @param {Object} alt + * @param {Object} altacc + * @param {Object} head + * @param {Object} vel + * @constructor + */ +function Position(coords, timestamp) { + this.coords = coords; + this.timestamp = new Date().getTime(); +} + +function Coordinates(lat, lng, alt, acc, head, vel) { + /** + * The latitude of the position. + */ + this.latitude = lat; + /** + * The longitude of the position, + */ + this.longitude = lng; + /** + * The accuracy of the position. + */ + this.accuracy = acc; + /** + * The altitude of the position. + */ + this.altitude = alt; + /** + * The direction the device is moving at the position. + */ + this.heading = head; + /** + * The velocity with which the device is moving at the position. + */ + this.speed = vel; +} + +/** + * This class specifies the options for requesting position data. + * @constructor + */ +function PositionOptions() { + /** + * Specifies the desired position accuracy. + */ + this.enableHighAccuracy = true; + /** + * The timeout after which if position data cannot be obtained the errorCallback + * is called. + */ + this.timeout = 10000; +} + +/** + * This class contains information about any GSP errors. + * @constructor + */ +function PositionError() { + this.code = null; + this.message = ""; +} + +PositionError.UNKNOWN_ERROR = 0; +PositionError.PERMISSION_DENIED = 1; +PositionError.POSITION_UNAVAILABLE = 2; +PositionError.TIMEOUT = 3; +/** + * This class provides access to the device SMS functionality. + * @constructor + */ +function Sms() { + +} + +/** + * Sends an SMS message. + * @param {Integer} number The phone number to send the message to. + * @param {String} message The contents of the SMS message to send. + * @param {Function} successCallback The function to call when the SMS message is sent. + * @param {Function} errorCallback The function to call when there is an error sending the SMS message. + * @param {PositionOptions} options The options for accessing the GPS location such as timeout and accuracy. + */ +Sms.prototype.send = function(number, message, successCallback, errorCallback, options) { + +} + +PhoneGap.addConstructor(function() { + if (typeof navigator.sms == "undefined") navigator.sms = new Sms(); +}); +/** + * This class provides access to the telephony features of the device. + * @constructor + */ +function Telephony() { + +} + +/** + * Calls the specifed number. + * @param {Integer} number The number to be called. + */ +Telephony.prototype.call = function(number) { + +} + +PhoneGap.addConstructor(function() { + if (typeof navigator.telephony == "undefined") navigator.telephony = new Telephony(); +}); +/** + * This class exposes mobile phone interface controls to JavaScript, such as + * native tab and tool bars, etc. + * @constructor + */ +function UIControls() { + this.tabBarTag = 0; + this.tabBarCallbacks = {}; +} + +/** + * Create a native tab bar that can have tab buttons added to it which can respond to events. + */ +UIControls.prototype.createTabBar = function() { + PhoneGap.exec("UIControls.createTabBar"); +}; + +/** + * Show a tab bar. The tab bar has to be created first. + * @param {Object} [options] Options indicating how the tab bar should be shown: + * - \c height integer indicating the height of the tab bar (default: \c 49) + * - \c position specifies whether the tab bar will be placed at the \c top or \c bottom of the screen (default: \c bottom) + */ +UIControls.prototype.showTabBar = function(options) { + if (!options) options = {}; + PhoneGap.exec("UIControls.showTabBar", options); +}; + +/** + * Hide a tab bar. The tab bar has to be created first. + */ +UIControls.prototype.hideTabBar = function(animate) { + if (animate == undefined || animate == null) + animate = true; + PhoneGap.exec("UIControls.hideTabBar", { animate: animate }); +}; + +/** + * Create a new tab bar item for use on a previously created tab bar. Use ::showTabBarItems to show the new item on the tab bar. + * + * If the supplied image name is one of the labels listed below, then this method will construct a tab button + * using the standard system buttons. Note that if you use one of the system images, that the \c title you supply will be ignored. + * + * <b>Tab Buttons</b> + * - tabButton:More + * - tabButton:Favorites + * - tabButton:Featured + * - tabButton:TopRated + * - tabButton:Recents + * - tabButton:Contacts + * - tabButton:History + * - tabButton:Bookmarks + * - tabButton:Search + * - tabButton:Downloads + * - tabButton:MostRecent + * - tabButton:MostViewed + * @param {String} name internal name to refer to this tab by + * @param {String} [title] title text to show on the tab, or null if no text should be shown + * @param {String} [image] image filename or internal identifier to show, or null if now image should be shown + * @param {Object} [options] Options for customizing the individual tab item + * - \c badge value to display in the optional circular badge on the item; if null or unspecified, the badge will be hidden + */ +UIControls.prototype.createTabBarItem = function(name, label, image, options) { + var tag = this.tabBarTag++; + if (options && 'onSelect' in options && typeof(options['onSelect']) == 'function') { + this.tabBarCallbacks[tag] = options.onSelect; + delete options.onSelect; + } + PhoneGap.exec("UIControls.createTabBarItem", name, label, image, tag, options); +}; + +/** + * Update an existing tab bar item to change its badge value. + * @param {String} name internal name used to represent this item when it was created + * @param {Object} options Options for customizing the individual tab item + * - \c badge value to display in the optional circular badge on the item; if null or unspecified, the badge will be hidden + */ +UIControls.prototype.updateTabBarItem = function(name, options) { + if (!options) options = {}; + PhoneGap.exec("UIControls.updateTabBarItem", name, options); +}; + +/** + * Show previously created items on the tab bar + * @param {String} arguments... the item names to be shown + * @param {Object} [options] dictionary of options, notable options including: + * - \c animate indicates that the items should animate onto the tab bar + * @see createTabBarItem + * @see createTabBar + */ +UIControls.prototype.showTabBarItems = function() { + var parameters = [ "UIControls.showTabBarItems" ]; + for (var i = 0; i < arguments.length; i++) { + parameters.push(arguments[i]); + } + PhoneGap.exec.apply(this, parameters); +}; + +/** + * Manually select an individual tab bar item, or nil for deselecting a currently selected tab bar item. + * @param {String} tabName the name of the tab to select, or null if all tabs should be deselected + * @see createTabBarItem + * @see showTabBarItems + */ +UIControls.prototype.selectTabBarItem = function(tab) { + PhoneGap.exec("UIControls.selectTabBarItem", tab); +}; + +/** + * Function called when a tab bar item has been selected. + * @param {Number} tag the tag number for the item that has been selected + */ +UIControls.prototype.tabBarItemSelected = function(tag) { + if (typeof(this.tabBarCallbacks[tag]) == 'function') + this.tabBarCallbacks[tag](); +}; + +/** + * Create a toolbar. + */ +UIControls.prototype.createToolBar = function() { + PhoneGap.exec("UIControls.createToolBar"); +}; + +/** + * Function called when a tab bar item has been selected. + * @param {String} title the title to set within the toolbar + */ +UIControls.prototype.setToolBarTitle = function(title) { + PhoneGap.exec("UIControls.setToolBarTitle", title); +}; + +PhoneGap.addConstructor(function() { + window.uicontrols = new UIControls(); +}); +// Gets the function name of a Function object, else uses "alert" if anonymous +function GetFunctionName(fn) +{ + if (fn) { + var m = fn.toString().match(/^\s*function\s+([^\s\(]+)/); + return m ? m[1] : "alert"; + } else { + return null; + } +} + +/** + * This class contains information about any NetworkStatus. + * @constructor + */ +function NetworkStatus() { + this.code = null; + this.message = ""; +} + +NetworkStatus.NOT_REACHABLE = 0; +NetworkStatus.REACHABLE_VIA_CARRIER_DATA_NETWORK = 1; +NetworkStatus.REACHABLE_VIA_WIFI_NETWORK = 2; + +/** + * This class provides access to device Network data (reachability). + * @constructor + */ +function Network() { + /** + * The last known Network status. + * { hostName: string, ipAddress: string, + remoteHostStatus: int(0/1/2), internetConnectionStatus: int(0/1/2), localWiFiConnectionStatus: int (0/2) } + */ + this.lastReachability = null; +}; + +/** + * + * @param {Function} successCallback + * @param {Function} errorCallback + * @param {Object} options (isIpAddress:boolean) + */ +Network.prototype.isReachable = function(hostName, successCallback, options) { + PhoneGap.exec("Network.isReachable", hostName, GetFunctionName(successCallback), options); +} + +/** + * Called by the geolocation framework when the reachability status has changed. + * @param {Reachibility} reachability The current reachability status. + */ +Network.prototype.updateReachability = function(reachability) { + this.lastReachability = reachability; +}; + +PhoneGap.addConstructor(function() { + if (typeof navigator.network == "undefined") navigator.network = new Network(); +});
tristil/agile-lamp
60ea296d3721532198faa37f7b805dcdb004cc5f
Improve links
diff --git a/README b/README index 9020f35..d856a8a 100644 --- a/README +++ b/README @@ -1,77 +1,79 @@ Agile Lamp ========== -Rubyforge Website ------------------ -* http://rubyforge.org/projects/agilelamp +Related Webpages +---------------- +* AgileVille Shop: http://agileville.myshopify.com/collections/frontpage +* Rubyforge page: http://rubyforge.org/projects/agilelamp +* Main Git Repository: http://github.com/tristil/agile-lamp/tree/master Mailing List ------------ http://groups.google.com/group/agile-lamp-projects Project Info: ------------- This repository hosts code to support the Agile Lamp, a lava lamp that responds to signals over USB that is intended to be used in agile testing scenarios, for example in a continuous integration (e.g., CruiseControl) setup. Currently there are only 10 Agile Lamps in existence. The main piece of software at the moment is the agilelamp-driver. This is a userspace driver for controlling the Agile Lamp. MacOS (Leopard untested) and Linux systems currently supported. The best option for installing the agilelamp-driver is through rubygems (http://rubygems.org). Requirements ------------ * Rubygems -* Install may work out of the box on MacOS, as a pre-compiled .Kext for x86 will be installed +* Install may work out of the box on MacOS, as a pre-compiled .Kext for x86 will be installed first * System build tools (Development Tools from the second MacOS DVD/ build-essential on Debian/Ubuntu) * Installed libusb headers (e.g., libusb installed from source on MacOS, libusb-dev on Debian/Ubuntu) Installation Instructions ------------------------- * sudo gem install agilelamp-driver * sudo install-agilelamp-driver (NB: this step is necessary) * Note carefully any compiler failure messages. These probably mean that you don't have the required headers installed * If installation was successful, you should be able to type `agilelamp-driver red` and the Agile Lamp will glow red. w00t! -* Yes, this installation procedures needs to be made much simpler +* Yes, this installation procedure needs to be made much simpler Development Information ----------------------- * The developers of the agilelamp-driver are big hypocrites, because the agilelamp-driver was not developed with TDD and does not have a test suite. We use TDD in our other projects, we swear! * agilelampclient is the beginning of a GUI client for Gnome, for enabling the agile lamp to poll CruiseControl * Helpful information about USB: * http://www.beyondlogic.org/usbnutshell/usb1.htm Particularly: - requests -- http://www.beyondlogic.org/usbnutshell/usb6.htm - transfer/endpoint types -- http://www.beyondlogic.org/usbnutshell/usb6.htm License ------- (The MIT License) Copyright (c) 2008 Joseph Method Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
tristil/agile-lamp
5204fc45ad493600b20f41dfd965fd944669c52f
Snarky message
diff --git a/README b/README index 54373ad..a78a6ac 100644 --- a/README +++ b/README @@ -1,75 +1,77 @@ Agile Lamp ========== Main Website ------------ http://agilelamp.rubyforge.org Mailing List ------------ http://groups.google.com/group/agile-lamp-projects Project Info: ------------- This repository hosts code to support the Agile Lamp, a lava lamp that responds to signals over USB that is intended to be used in agile testing scenarios, for example in a continuous integration (e.g., CruiseControl) setup. Currently there are only 10 Agile Lamps in existence. The main piece of software at the moment is the agilelamp-driver. This is a userspace driver for controlling the Agile Lamp. MacOS (Leopard untested) and Linux systems currently supported. The best option for installing the agilelamp-driver is through rubygems (http://rubygems.org). Requirements ------------ * Rubygems +* Install may work out of the box on MacOS, as a pre-compiled .Kext for x86 will be installed * System build tools (Development Tools from the second MacOS DVD/ build-essential on Debian/Ubuntu) * Installed libusb headers (e.g., libusb installed from source on MacOS, libusb-dev on Debian/Ubuntu) Installation Instructions ------------------------- * sudo gem install agilelamp-driver * sudo install-agilelamp-driver (NB: this step is necessary) * Note carefully any compiler failure messages. These probably mean that you don't have the required headers installed * If installation was successful, you should be able to type `agilelamp-driver red` and the Agile Lamp will glow red. w00t! +* Yes, this installation procedures needs to be made much simpler Development Information ----------------------- * The developers of the agilelamp-driver are big hypocrites, because the agilelamp-driver was not developed with TDD and does not have a test suite. We use TDD in our other projects, we swear! * agilelampclient is the beginning of a GUI client for Gnome, for enabling the agile lamp to poll CruiseControl * Helpful information about USB: * http://www.beyondlogic.org/usbnutshell/usb1.htm Particularly: - requests -- http://www.beyondlogic.org/usbnutshell/usb6.htm - transfer/endpoint types -- http://www.beyondlogic.org/usbnutshell/usb6.htm License ------- (The MIT License) Copyright (c) 2008 Joseph Method Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
tristil/agile-lamp
bbba5aaef9e16721be57791ce7c3b824b6f80ba4
Change AgileLamp.kext
diff --git a/agilelamp-driver/src/AgileLamp/Info.plist b/agilelamp-driver/src/AgileLamp/Info.plist index 278fb5e..e9d3aeb 100644 --- a/agilelamp-driver/src/AgileLamp/Info.plist +++ b/agilelamp-driver/src/AgileLamp/Info.plist @@ -1,88 +1,88 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>English</string> <key>CFBundleGetInfoString</key> <string>Please don't grab the agile lamp, Mac OS</string> <key>CFBundleIdentifier</key> <string>com.agileville.DONTGRABKNOB</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>Please don't grab the agile lamp, Mac OS</string> <key>CFBundlePackageType</key> <string>KEXT</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>6.0</string> <key>IOKitPersonalities</key> <dict> <key>myUSBDevicePersonality0</key> <dict> <key>CFBundleIdentifier</key> <string>com.apple.iokit.IOUSBHIDDriver</string> <key>IOClass</key> <string>IOUSBHIDDriver</string> <key>IOKitDebug</key> <integer>65535</integer> <key>IOProbeScore</key> <integer>106000</integer> <key>IOProviderClass</key> <string>IOUSBInterface</string> - <key>IOProviderMergeProperties</key> + <!-- <key>IOProviderMergeProperties</key> <dict> <key>ClassicMustNotSeize</key> <true/> - </dict> + </dict> --> <key>bConfigurationValue</key> <integer>1</integer> <key>bInterfaceNumber</key> <integer>0</integer> <key>bcdDevice</key> <integer>256</integer> <key>idProduct</key> <integer>514</integer> <key>idVendor</key> <integer>4400</integer> </dict> <key>myUSBDevicePersonality1</key> <dict> <key>CFBundleIdentifier</key> <string>com.apple.iokit.IOUSBHIDDriver</string> <key>IOClass</key> <string>IOUSBHIDDriver</string> <key>IOKitDebug</key> <integer>65535</integer> <key>IOProbeScore</key> <integer>106000</integer> <key>IOProviderClass</key> <string>IOUSBInterface</string> - <key>IOProviderMergeProperties</key> + <!-- <key>IOProviderMergeProperties</key> <dict> <key>ClassicMustNotSeize</key> <true/> - </dict> + </dict> --> <key>bConfigurationValue</key> <integer>1</integer> <key>bInterfaceNumber</key> <integer>1</integer> <key>bcdDevice</key> <integer>256</integer> <key>idProduct</key> <integer>514</integer> <key>idVendor</key> <integer>4400</integer> </dict> </dict> <key>OSBundleLibraries</key> <dict> <key>com.apple.iokit.IOHIDFamily</key> <string>1.2</string> - <key>com.apple.kernel.iokit</key> - <string>6.0</string> + <!-- <key>com.apple.kernel.iokit</key> + <string>6.0</string> --> </dict> </dict> </plist> diff --git a/agilelamp-driver/src/agilelamp.c b/agilelamp-driver/src/agilelamp.c index e2da26c..ded102a 100644 --- a/agilelamp-driver/src/agilelamp.c +++ b/agilelamp-driver/src/agilelamp.c @@ -1,182 +1,218 @@ #include <usb.h> #include <stdio.h> #include <unistd.h> #include <string.h> +// I should acknowledge the USB missile launcher code that served as an initial +// template. Need to find the URL first... + usb_dev_handle* launcher; + //wrapper for control_msg int send_message(char* msg, int index) { int i = 0; int j = usb_control_msg(launcher, 0x21, 0x9, 0x0, index, msg, 8, 1000); return j; } void send_cbw(){ fprintf(stderr, "Sending CBW message\n"); char cbw_message[8] = {0x55, 0x53, 0x42, 0x43, 0, 16, 2, 0}; int ret = send_message(cbw_message, 1); fprintf(stderr, "%d bytes sent\n", ret); } void send_lamp_command(char* title, char* message1, char* message2){ usb_reset(launcher); usb_resetep(launcher, 0); usb_resetep(launcher, 1); usb_clear_halt(launcher, 0); usb_clear_halt(launcher, 1); send_cbw(); fprintf(stderr, "Submitting %s\n", title); int ret = send_message(message1, 0); fprintf(stderr, "%d bytes sent\n", ret); ret = send_message(message2, 0); fprintf(stderr, "%d bytes sent\n", ret); } void set_red_with_bell(){ char message_part_1[8] = {0x0, 0x1, 0x4, 0x9,0x10, 0x19, 0x24, 0x31}; //red with bell char message_part_2[8] = {0x40, 0x51, 0x64, 0x79, 0x90, 0xa9, 0xc4, 0xe1}; // red with bell send_lamp_command("red with bell", message_part_1, message_part_2); } /* -Fun with bit-math: + Fun with bit-math: -Everything on the first (from right) 8 bits of first (from right) byte + Everything on the first (from right) 8 bits of first (from right) byte b0:=1:Bell active;=0:Bell off b1:=1:Green led on; =0:Green led off b2:=1:Red led on;=0:red led off b3:=0:7 colors led on;=1:7 colors led off - b0 +b0 1 1 1 1 1 111 128 64 32 16 8 421 = 255 c c c c c rgb (c's are colors to cycle through, then red, green, bell) 0 0 0 16 0 000 = - + */ void only_bell_on(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; char message_part_2[8] = {0,0,0,0, 0,0,0,1}; send_lamp_command("green", message_part_1, message_part_2); } void red_with_no_bell(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; char message_part_2[8] = {0,0,0,0, 0,0,0,4}; send_lamp_command("red with no bell", message_part_1, message_part_2); } void set_green(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //green char message_part_2[8] = {0,0,0,0 ,0,0,0,2}; // green send_lamp_command("green", message_part_1, message_part_2); } void set_lights_off(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; // lights off char message_part_2[8] = {0,0,0,0, 0,0,0,0}; // lights off send_lamp_command("lights off", message_part_1, message_part_2); } void set_colors_with_bell(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //colors with bell char message_part_2[8] = {0,0,0,0, 0,0,0,24}; // colors with bells send_lamp_command("colors with bells", message_part_1, message_part_2); } +int claim_interface(int num){ + int claimed = -1; + //do stuff + + claimed = usb_claim_interface(launcher, num); + printf("Interface %d claimed with %d\n", num, claimed); + + //usb_detach_kernel_driver_np(launcher, 1); + //usb_detach_kernel_driver_np(launcher, 0); + printf("%d <= 0: %s\n", claimed, claimed <= 0); + + if (claimed <= 0) + { + printf("Preparing to release interface %d\n", num); + usb_release_interface(launcher, num); + printf("Couldn't claim interface %d \n", num); + usb_close(launcher); + return 1; + } else if (claimed > 0){ + printf("Claimed interface %d \n", num); + } + return 0; +} + int load_device(){ - int claimed; + int ret; fprintf(stderr, "Starting\n"); struct usb_bus *busses; usb_init(); fprintf(stderr, "usb_init...\n"); usb_find_busses(); usb_find_devices(); fprintf(stderr, "Found busses, found devices...\n"); busses = usb_get_busses(); fprintf(stderr, "Got busses...\n"); struct usb_bus *bus; int c, i, a; /* ... */ for (bus = busses; bus; bus = bus->next) { struct usb_device *dev; for (dev = bus->devices; dev; dev = dev->next) { /* Check if this device is a printer */ if (dev->descriptor.idVendor == 4400) if(dev->descriptor.idProduct == 514) launcher = usb_open(dev); } } - fprintf(stderr, "Got launcher...\n"); - - //do stuff - if(launcher != NULL) - { - int claimed = usb_claim_interface(launcher, 1); - } - else - { - fprintf(stderr, "You didn't really get the launcher!\n"); + if(launcher == NULL){ + printf("Didn't get launcher!\n"); return 1; + } else { + printf("Got launcher...\n"); } - usb_detach_kernel_driver_np(launcher, 1); - usb_detach_kernel_driver_np(launcher, 0); + ret = claim_interface(0); + printf("Interface 0 returned %d\n", ret); + if(ret == 1){ + printf("Returning 1 in claim_interface\n"); + return 1; + } - if (claimed == 0) - { - usb_release_interface(launcher, 1); + ret = claim_interface(1); + printf("Interface 1 returned %d\n", ret); + if(ret == 1){ + printf("Returning 1 in claim_interface\n"); return 1; - } else if (claimed > 0){ - fprintf(stderr, "Found launcher...\n"); } + fprintf(stderr, "Claimed interfaces\n"); + return 0; +} + +void lamp_shutdown(){ + int ret = usb_release_interface(launcher, 0); + printf("Released interface 0: %d\n", ret); + ret = usb_release_interface(launcher, 1); + printf("Released interface 1: %d\n", ret); + usb_close(launcher); } int main(int argc, char *argv[]) { if ( argc != 2 ) /* argc should be 2 for correct execution */ { /* We print argv[0] assuming it is the program name */ printf( "usage: %s red|green|bell|various\n", argv[0] ); } else { int ret = load_device(); + if(ret == 1) + lamp_shutdown(); + return 1; char* argument = argv[1]; if(strcmp(argument, "green") == 0){ set_green(); } else if (strcmp(argument, "red") == 0){ red_with_no_bell(); } else if (strcmp(argument, "off") == 0){ set_lights_off(); } else if (strcmp(argument, "various") == 0){ set_colors_with_bell(); } else if (strcmp(argument, "bell") == 0){ only_bell_on(); } } - usb_release_interface(launcher, 0); - usb_release_interface(launcher, 1); - usb_close(launcher); + lamp_shutdown(); return 0; } diff --git a/agilelamp-driver/src/fetch_kext b/agilelamp-driver/src/fetch_kext index 664a1b5..ff5f8fa 100755 --- a/agilelamp-driver/src/fetch_kext +++ b/agilelamp-driver/src/fetch_kext @@ -1,19 +1,19 @@ #!/usr/bin/env ruby if `whoami`.strip != 'root' puts "You need to be root. Try sudo." exit end require 'fileutils' include FileUtils cd "AgileLamp" system "xcodebuild" rm_rf "/System/Library/Extensions/AgileLamp.kext" mv "build/Release/AgileLamp.kext", "/System/Library/Extensions/" system "chown -R root:wheel /System/Library/Extensions/AgileLamp.kext" - +system "touch /System/Library/Extensions/AgileLamp.kext" system "kextload -v /System/Library/Extensions/AgileLamp.kext"
tristil/agile-lamp
4f2a478ff6e6394b041b69c658ff53170d7be4ed
Small desperation moves.
diff --git a/agilelamp-driver/src/agilelamp.c b/agilelamp-driver/src/agilelamp.c index f071555..e2da26c 100644 --- a/agilelamp-driver/src/agilelamp.c +++ b/agilelamp-driver/src/agilelamp.c @@ -1,174 +1,182 @@ #include <usb.h> #include <stdio.h> #include <unistd.h> #include <string.h> usb_dev_handle* launcher; //wrapper for control_msg int send_message(char* msg, int index) { int i = 0; int j = usb_control_msg(launcher, 0x21, 0x9, 0x0, index, msg, 8, 1000); return j; } void send_cbw(){ fprintf(stderr, "Sending CBW message\n"); char cbw_message[8] = {0x55, 0x53, 0x42, 0x43, 0, 16, 2, 0}; int ret = send_message(cbw_message, 1); fprintf(stderr, "%d bytes sent\n", ret); } void send_lamp_command(char* title, char* message1, char* message2){ usb_reset(launcher); + usb_resetep(launcher, 0); + usb_resetep(launcher, 1); + usb_clear_halt(launcher, 0); + usb_clear_halt(launcher, 1); send_cbw(); fprintf(stderr, "Submitting %s\n", title); int ret = send_message(message1, 0); fprintf(stderr, "%d bytes sent\n", ret); ret = send_message(message2, 0); fprintf(stderr, "%d bytes sent\n", ret); } void set_red_with_bell(){ char message_part_1[8] = {0x0, 0x1, 0x4, 0x9,0x10, 0x19, 0x24, 0x31}; //red with bell char message_part_2[8] = {0x40, 0x51, 0x64, 0x79, 0x90, 0xa9, 0xc4, 0xe1}; // red with bell send_lamp_command("red with bell", message_part_1, message_part_2); } /* Fun with bit-math: Everything on the first (from right) 8 bits of first (from right) byte b0:=1:Bell active;=0:Bell off b1:=1:Green led on; =0:Green led off b2:=1:Red led on;=0:red led off b3:=0:7 colors led on;=1:7 colors led off b0 1 1 1 1 1 111 128 64 32 16 8 421 = 255 c c c c c rgb (c's are colors to cycle through, then red, green, bell) 0 0 0 16 0 000 = */ void only_bell_on(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; char message_part_2[8] = {0,0,0,0, 0,0,0,1}; send_lamp_command("green", message_part_1, message_part_2); } void red_with_no_bell(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; char message_part_2[8] = {0,0,0,0, 0,0,0,4}; send_lamp_command("red with no bell", message_part_1, message_part_2); } void set_green(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //green char message_part_2[8] = {0,0,0,0 ,0,0,0,2}; // green send_lamp_command("green", message_part_1, message_part_2); } void set_lights_off(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; // lights off char message_part_2[8] = {0,0,0,0, 0,0,0,0}; // lights off send_lamp_command("lights off", message_part_1, message_part_2); } void set_colors_with_bell(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //colors with bell char message_part_2[8] = {0,0,0,0, 0,0,0,24}; // colors with bells send_lamp_command("colors with bells", message_part_1, message_part_2); } int load_device(){ int claimed; fprintf(stderr, "Starting\n"); struct usb_bus *busses; usb_init(); fprintf(stderr, "usb_init...\n"); usb_find_busses(); usb_find_devices(); fprintf(stderr, "Found busses, found devices...\n"); busses = usb_get_busses(); fprintf(stderr, "Got busses...\n"); struct usb_bus *bus; int c, i, a; /* ... */ for (bus = busses; bus; bus = bus->next) { struct usb_device *dev; for (dev = bus->devices; dev; dev = dev->next) { /* Check if this device is a printer */ if (dev->descriptor.idVendor == 4400) if(dev->descriptor.idProduct == 514) launcher = usb_open(dev); } } fprintf(stderr, "Got launcher...\n"); //do stuff if(launcher != NULL) { int claimed = usb_claim_interface(launcher, 1); } else { fprintf(stderr, "You didn't really get the launcher!\n"); return 1; } + usb_detach_kernel_driver_np(launcher, 1); usb_detach_kernel_driver_np(launcher, 0); if (claimed == 0) { usb_release_interface(launcher, 1); return 1; } else if (claimed > 0){ fprintf(stderr, "Found launcher...\n"); } } int main(int argc, char *argv[]) { if ( argc != 2 ) /* argc should be 2 for correct execution */ { /* We print argv[0] assuming it is the program name */ printf( "usage: %s red|green|bell|various\n", argv[0] ); } else { int ret = load_device(); char* argument = argv[1]; if(strcmp(argument, "green") == 0){ set_green(); } else if (strcmp(argument, "red") == 0){ red_with_no_bell(); } else if (strcmp(argument, "off") == 0){ set_lights_off(); } else if (strcmp(argument, "various") == 0){ set_colors_with_bell(); } else if (strcmp(argument, "bell") == 0){ only_bell_on(); } } + usb_release_interface(launcher, 0); + usb_release_interface(launcher, 1); + usb_close(launcher); return 0; }
tristil/agile-lamp
db222eacfb0e8a6af223707794076d623fa23b94
Add README file
diff --git a/agilelamp-driver/src/README b/agilelamp-driver/src/README new file mode 100644 index 0000000..6e29cf3 --- /dev/null +++ b/agilelamp-driver/src/README @@ -0,0 +1,18 @@ +About this directory +-------------------- + +The approach to getting the code onto your system is a hack of Rubygems, which +really only wants to install libraries and executables for you. The +install-agilelamp-driver executable finds the gem directory, builds the +agilelamp binary in place using agilelamp.c, and installs it to the system +(this means agilelamp-driver won't be removed on gem uninstall either). It also +installs 44-usblamp-rules to /etc/udev/rules.d/ and restarts udev. This is to +keep the kernel from binding to the device. There is a Linux-specific call in +libusb that is also necessary, usb_detach_kernel_np. + +On MacOS, it is necessary to install a "codeless kext" (a driver extension +which does not contain accompanying C code, only a *.plist metadata file) to +match the device and steal it from the kernel. sudo fetch_kext performs the +operations necessary to build and install the codeless kext to the system. +Unfortunately, at the time of this writing, the libusb code still does not work +on MacOS, perhaps because of something wrong with the codeless kext.
tristil/agile-lamp
69d218383c3c9f8e7c4e6309feaaed64002add00
Add fetch_kext script
diff --git a/agilelamp-driver/src/fetch_kext b/agilelamp-driver/src/fetch_kext new file mode 100755 index 0000000..664a1b5 --- /dev/null +++ b/agilelamp-driver/src/fetch_kext @@ -0,0 +1,19 @@ +#!/usr/bin/env ruby + +if `whoami`.strip != 'root' + puts "You need to be root. Try sudo." + exit +end + +require 'fileutils' +include FileUtils + +cd "AgileLamp" +system "xcodebuild" + +rm_rf "/System/Library/Extensions/AgileLamp.kext" +mv "build/Release/AgileLamp.kext", "/System/Library/Extensions/" + +system "chown -R root:wheel /System/Library/Extensions/AgileLamp.kext" + +system "kextload -v /System/Library/Extensions/AgileLamp.kext"
tristil/agile-lamp
01f5a3d431c3e189ceb64c1afc7416ab5124d099
Add Codeless Kext
diff --git a/agilelamp-driver/src/AgileLamp/AgileLamp.xcodeproj/chen.mode1 b/agilelamp-driver/src/AgileLamp/AgileLamp.xcodeproj/chen.mode1 new file mode 100644 index 0000000..f11e026 --- /dev/null +++ b/agilelamp-driver/src/AgileLamp/AgileLamp.xcodeproj/chen.mode1 @@ -0,0 +1,1324 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>ActivePerspectiveName</key> + <string>Project</string> + <key>AllowedModules</key> + <array> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXSmartGroupTreeModule</string> + <key>Name</key> + <string>Groups and Files Outline View</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Name</key> + <string>Editor</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>XCTaskListModule</string> + <key>Name</key> + <string>Task List</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>XCDetailModule</string> + <key>Name</key> + <string>File and Smart Group Detail Viewer</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>1</string> + <key>Module</key> + <string>PBXBuildResultsModule</string> + <key>Name</key> + <string>Detailed Build Results Viewer</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>1</string> + <key>Module</key> + <string>PBXProjectFindModule</string> + <key>Name</key> + <string>Project Batch Find Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXRunSessionModule</string> + <key>Name</key> + <string>Run Log</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXBookmarksModule</string> + <key>Name</key> + <string>Bookmarks Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXClassBrowserModule</string> + <key>Name</key> + <string>Class Browser</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXCVSModule</string> + <key>Name</key> + <string>Source Code Control Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXDebugBreakpointsModule</string> + <key>Name</key> + <string>Debug Breakpoints Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>XCDockableInspector</string> + <key>Name</key> + <string>Inspector</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXOpenQuicklyModule</string> + <key>Name</key> + <string>Open Quickly Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>1</string> + <key>Module</key> + <string>PBXDebugSessionModule</string> + <key>Name</key> + <string>Debugger</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>1</string> + <key>Module</key> + <string>PBXDebugCLIModule</string> + <key>Name</key> + <string>Debug Console</string> + </dict> + </array> + <key>Description</key> + <string>DefaultDescriptionKey</string> + <key>DockingSystemVisible</key> + <false/> + <key>Extension</key> + <string>mode1</string> + <key>FavBarConfig</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>744261650DEB5E4100A0AFE2</string> + <key>XCBarModuleItemNames</key> + <dict/> + <key>XCBarModuleItems</key> + <array/> + </dict> + <key>FirstTimeWindowDisplayed</key> + <false/> + <key>Identifier</key> + <string>com.apple.perspectives.project.mode1</string> + <key>MajorVersion</key> + <integer>31</integer> + <key>MinorVersion</key> + <integer>1</integer> + <key>Name</key> + <string>Default</string> + <key>Notifications</key> + <array/> + <key>OpenEditors</key> + <array/> + <key>PerspectiveWidths</key> + <array> + <integer>-1</integer> + <integer>-1</integer> + </array> + <key>Perspectives</key> + <array> + <dict> + <key>ChosenToolbarItems</key> + <array> + <string>active-target-popup</string> + <string>active-buildstyle-popup</string> + <string>action</string> + <string>NSToolbarFlexibleSpaceItem</string> + <string>buildOrClean</string> + <string>build-and-runOrDebug</string> + <string>com.apple.ide.PBXToolbarStopButton</string> + <string>get-info</string> + <string>toggle-editor</string> + <string>NSToolbarFlexibleSpaceItem</string> + <string>com.apple.pbx.toolbar.searchfield</string> + </array> + <key>ControllerClassBaseName</key> + <string></string> + <key>IconName</key> + <string>WindowOfProjectWithEditor</string> + <key>Identifier</key> + <string>perspective.project</string> + <key>IsVertical</key> + <false/> + <key>Layout</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXBottomSmartGroupGIDs</key> + <array> + <string>1C37FBAC04509CD000000102</string> + <string>1C37FAAC04509CD000000102</string> + <string>1C08E77C0454961000C914BD</string> + <string>1C37FABC05509CD000000102</string> + <string>1C37FABC05539CD112110102</string> + <string>E2644B35053B69B200211256</string> + <string>1C37FABC04509CD000100104</string> + <string>1CC0EA4004350EF90044410B</string> + <string>1CC0EA4004350EF90041110B</string> + </array> + <key>PBXProjectModuleGUID</key> + <string>1CE0B1FE06471DED0097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>Files</string> + <key>PBXProjectStructureProvided</key> + <string>yes</string> + <key>PBXSmartGroupTreeModuleColumnData</key> + <dict> + <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> + <array> + <real>186</real> + </array> + <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> + <array> + <string>MainColumn</string> + </array> + </dict> + <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> + <dict> + <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> + <array> + <string>089C166AFE841209C02AAC07</string> + <string>1C37FABC05509CD000000102</string> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> + <array> + <array> + <integer>0</integer> + </array> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> + <string>{{0, 0}, {186, 338}}</string> + </dict> + <key>PBXTopSmartGroupGIDs</key> + <array/> + <key>XCIncludePerspectivesSwitch</key> + <true/> + <key>XCSharingToken</key> + <string>com.apple.Xcode.GFSharingToken</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {203, 356}}</string> + <key>GroupTreeTableConfiguration</key> + <array> + <string>MainColumn</string> + <real>186</real> + </array> + <key>RubberWindowFrame</key> + <string>295 369 690 397 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>PBXSmartGroupTreeModule</string> + <key>Proportion</key> + <string>203pt</string> + </dict> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CE0B20306471E060097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>MyNewFile14.java</string> + <key>PBXSplitModuleInNavigatorKey</key> + <dict> + <key>Split0</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CE0B20406471E060097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>MyNewFile14.java</string> + </dict> + <key>SplitCount</key> + <string>1</string> + </dict> + <key>StatusBarVisibility</key> + <true/> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {482, 0}}</string> + <key>RubberWindowFrame</key> + <string>295 369 690 397 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>0pt</string> + </dict> + <dict> + <key>BecomeActive</key> + <true/> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CE0B20506471E060097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>Detail</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 5}, {482, 351}}</string> + <key>RubberWindowFrame</key> + <string>295 369 690 397 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>XCDetailModule</string> + <key>Proportion</key> + <string>351pt</string> + </dict> + </array> + <key>Proportion</key> + <string>482pt</string> + </dict> + </array> + <key>Name</key> + <string>Project</string> + <key>ServiceClasses</key> + <array> + <string>XCModuleDock</string> + <string>PBXSmartGroupTreeModule</string> + <string>XCModuleDock</string> + <string>PBXNavigatorGroup</string> + <string>XCDetailModule</string> + </array> + <key>TableOfContents</key> + <array> + <string>7442616E0DEB5E5100A0AFE2</string> + <string>1CE0B1FE06471DED0097A5F4</string> + <string>7442616F0DEB5E5100A0AFE2</string> + <string>1CE0B20306471E060097A5F4</string> + <string>1CE0B20506471E060097A5F4</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.default</string> + </dict> + <dict> + <key>ControllerClassBaseName</key> + <string></string> + <key>IconName</key> + <string>WindowOfProject</string> + <key>Identifier</key> + <string>perspective.morph</string> + <key>IsVertical</key> + <integer>0</integer> + <key>Layout</key> + <array> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXBottomSmartGroupGIDs</key> + <array> + <string>1C37FBAC04509CD000000102</string> + <string>1C37FAAC04509CD000000102</string> + <string>1C08E77C0454961000C914BD</string> + <string>1C37FABC05509CD000000102</string> + <string>1C37FABC05539CD112110102</string> + <string>E2644B35053B69B200211256</string> + <string>1C37FABC04509CD000100104</string> + <string>1CC0EA4004350EF90044410B</string> + <string>1CC0EA4004350EF90041110B</string> + </array> + <key>PBXProjectModuleGUID</key> + <string>11E0B1FE06471DED0097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>Files</string> + <key>PBXProjectStructureProvided</key> + <string>yes</string> + <key>PBXSmartGroupTreeModuleColumnData</key> + <dict> + <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> + <array> + <real>186</real> + </array> + <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> + <array> + <string>MainColumn</string> + </array> + </dict> + <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> + <dict> + <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> + <array> + <string>29B97314FDCFA39411CA2CEA</string> + <string>1C37FABC05509CD000000102</string> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> + <array> + <array> + <integer>0</integer> + </array> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> + <string>{{0, 0}, {186, 337}}</string> + </dict> + <key>PBXTopSmartGroupGIDs</key> + <array/> + <key>XCIncludePerspectivesSwitch</key> + <integer>1</integer> + <key>XCSharingToken</key> + <string>com.apple.Xcode.GFSharingToken</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {203, 355}}</string> + <key>GroupTreeTableConfiguration</key> + <array> + <string>MainColumn</string> + <real>186</real> + </array> + <key>RubberWindowFrame</key> + <string>373 269 690 397 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXSmartGroupTreeModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Morph</string> + <key>PreferredWidth</key> + <integer>300</integer> + <key>ServiceClasses</key> + <array> + <string>XCModuleDock</string> + <string>PBXSmartGroupTreeModule</string> + </array> + <key>TableOfContents</key> + <array> + <string>11E0B1FE06471DED0097A5F4</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.default.short</string> + </dict> + </array> + <key>PerspectivesBarVisible</key> + <false/> + <key>ShelfIsVisible</key> + <false/> + <key>SourceDescription</key> + <string>file at '/System/Library/PrivateFrameworks/DevToolsInterface.framework/Versions/A/Resources/XCPerspectivesSpecificationMode1.xcperspec'</string> + <key>StatusbarIsVisible</key> + <true/> + <key>TimeStamp</key> + <real>0.0</real> + <key>ToolbarDisplayMode</key> + <integer>1</integer> + <key>ToolbarIsVisible</key> + <true/> + <key>ToolbarSizeMode</key> + <integer>1</integer> + <key>Type</key> + <string>Perspectives</string> + <key>UpdateMessage</key> + <string>The Default Workspace in this version of Xcode now includes support to hide and show the detail view (what has been referred to as the "Metro-Morph" feature). You must discard your current Default Workspace settings and update to the latest Default Workspace in order to gain this feature. Do you wish to update to the latest Workspace defaults for project '%@'?</string> + <key>WindowJustification</key> + <integer>5</integer> + <key>WindowOrderList</key> + <array> + <string>/Users/chen/prj/agilelamp/agilelamp-driver/src/AgileLamp/AgileLamp.xcodeproj</string> + </array> + <key>WindowString</key> + <string>295 369 690 397 0 0 1280 778 </string> + <key>WindowTools</key> + <array> + <dict> + <key>Identifier</key> + <string>windowTool.build</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CD0528F0623707200166675</string> + <key>PBXProjectModuleLabel</key> + <string>&lt;No Editor&gt;</string> + <key>PBXSplitModuleInNavigatorKey</key> + <dict> + <key>Split0</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CD052900623707200166675</string> + </dict> + <key>SplitCount</key> + <string>1</string> + </dict> + <key>StatusBarVisibility</key> + <integer>1</integer> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {500, 215}}</string> + <key>RubberWindowFrame</key> + <string>192 257 500 500 0 0 1280 1002 </string> + </dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>218pt</string> + </dict> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>XCMainBuildResultsModuleGUID</string> + <key>PBXProjectModuleLabel</key> + <string>Build</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 222}, {500, 236}}</string> + <key>RubberWindowFrame</key> + <string>192 257 500 500 0 0 1280 1002 </string> + </dict> + <key>Module</key> + <string>PBXBuildResultsModule</string> + <key>Proportion</key> + <string>236pt</string> + </dict> + </array> + <key>Proportion</key> + <string>458pt</string> + </dict> + </array> + <key>Name</key> + <string>Build Results</string> + <key>ServiceClasses</key> + <array> + <string>PBXBuildResultsModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1C78EAA5065D492600B07095</string> + <string>1C78EAA6065D492600B07095</string> + <string>1CD0528F0623707200166675</string> + <string>XCMainBuildResultsModuleGUID</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.build</string> + <key>WindowString</key> + <string>192 257 500 500 0 0 1280 1002 </string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.debugger</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>Debugger</key> + <dict> + <key>HorizontalSplitView</key> + <dict> + <key>_collapsingFrameDimension</key> + <real>0.0</real> + <key>_indexOfCollapsedView</key> + <integer>0</integer> + <key>_percentageOfCollapsedView</key> + <real>0.0</real> + <key>isCollapsed</key> + <string>yes</string> + <key>sizes</key> + <array> + <string>{{0, 0}, {317, 164}}</string> + <string>{{317, 0}, {377, 164}}</string> + </array> + </dict> + <key>VerticalSplitView</key> + <dict> + <key>_collapsingFrameDimension</key> + <real>0.0</real> + <key>_indexOfCollapsedView</key> + <integer>0</integer> + <key>_percentageOfCollapsedView</key> + <real>0.0</real> + <key>isCollapsed</key> + <string>yes</string> + <key>sizes</key> + <array> + <string>{{0, 0}, {694, 164}}</string> + <string>{{0, 164}, {694, 216}}</string> + </array> + </dict> + </dict> + <key>LauncherConfigVersion</key> + <string>8</string> + <key>PBXProjectModuleGUID</key> + <string>1C162984064C10D400B95A72</string> + <key>PBXProjectModuleLabel</key> + <string>Debug - GLUTExamples (Underwater)</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>DebugConsoleDrawerSize</key> + <string>{100, 120}</string> + <key>DebugConsoleVisible</key> + <string>None</string> + <key>DebugConsoleWindowFrame</key> + <string>{{200, 200}, {500, 300}}</string> + <key>DebugSTDIOWindowFrame</key> + <string>{{200, 200}, {500, 300}}</string> + <key>Frame</key> + <string>{{0, 0}, {694, 380}}</string> + <key>RubberWindowFrame</key> + <string>321 238 694 422 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXDebugSessionModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Debugger</string> + <key>ServiceClasses</key> + <array> + <string>PBXDebugSessionModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1CD10A99069EF8BA00B06720</string> + <string>1C0AD2AB069F1E9B00FABCE6</string> + <string>1C162984064C10D400B95A72</string> + <string>1C0AD2AC069F1E9B00FABCE6</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.debug</string> + <key>WindowString</key> + <string>321 238 694 422 0 0 1440 878 </string> + <key>WindowToolGUID</key> + <string>1CD10A99069EF8BA00B06720</string> + <key>WindowToolIsVisible</key> + <integer>0</integer> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.find</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CDD528C0622207200134675</string> + <key>PBXProjectModuleLabel</key> + <string>&lt;No Editor&gt;</string> + <key>PBXSplitModuleInNavigatorKey</key> + <dict> + <key>Split0</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CD0528D0623707200166675</string> + </dict> + <key>SplitCount</key> + <string>1</string> + </dict> + <key>StatusBarVisibility</key> + <integer>1</integer> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {781, 167}}</string> + <key>RubberWindowFrame</key> + <string>62 385 781 470 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>781pt</string> + </dict> + </array> + <key>Proportion</key> + <string>50%</string> + </dict> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CD0528E0623707200166675</string> + <key>PBXProjectModuleLabel</key> + <string>Project Find</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{8, 0}, {773, 254}}</string> + <key>RubberWindowFrame</key> + <string>62 385 781 470 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXProjectFindModule</string> + <key>Proportion</key> + <string>50%</string> + </dict> + </array> + <key>Proportion</key> + <string>428pt</string> + </dict> + </array> + <key>Name</key> + <string>Project Find</string> + <key>ServiceClasses</key> + <array> + <string>PBXProjectFindModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1C530D57069F1CE1000CFCEE</string> + <string>1C530D58069F1CE1000CFCEE</string> + <string>1C530D59069F1CE1000CFCEE</string> + <string>1CDD528C0622207200134675</string> + <string>1C530D5A069F1CE1000CFCEE</string> + <string>1CE0B1FE06471DED0097A5F4</string> + <string>1CD0528E0623707200166675</string> + </array> + <key>WindowString</key> + <string>62 385 781 470 0 0 1440 878 </string> + <key>WindowToolGUID</key> + <string>1C530D57069F1CE1000CFCEE</string> + <key>WindowToolIsVisible</key> + <integer>0</integer> + </dict> + <dict> + <key>Identifier</key> + <string>MENUSEPARATOR</string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.debuggerConsole</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1C78EAAC065D492600B07095</string> + <key>PBXProjectModuleLabel</key> + <string>Debugger Console</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {440, 358}}</string> + <key>RubberWindowFrame</key> + <string>650 41 440 400 0 0 1280 1002 </string> + </dict> + <key>Module</key> + <string>PBXDebugCLIModule</string> + <key>Proportion</key> + <string>358pt</string> + </dict> + </array> + <key>Proportion</key> + <string>358pt</string> + </dict> + </array> + <key>Name</key> + <string>Debugger Console</string> + <key>ServiceClasses</key> + <array> + <string>PBXDebugCLIModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1C78EAAD065D492600B07095</string> + <string>1C78EAAE065D492600B07095</string> + <string>1C78EAAC065D492600B07095</string> + </array> + <key>WindowString</key> + <string>650 41 440 400 0 0 1280 1002 </string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.run</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>LauncherConfigVersion</key> + <string>3</string> + <key>PBXProjectModuleGUID</key> + <string>1CD0528B0623707200166675</string> + <key>PBXProjectModuleLabel</key> + <string>Run</string> + <key>Runner</key> + <dict> + <key>HorizontalSplitView</key> + <dict> + <key>_collapsingFrameDimension</key> + <real>0.0</real> + <key>_indexOfCollapsedView</key> + <integer>0</integer> + <key>_percentageOfCollapsedView</key> + <real>0.0</real> + <key>isCollapsed</key> + <string>yes</string> + <key>sizes</key> + <array> + <string>{{0, 0}, {493, 167}}</string> + <string>{{0, 176}, {493, 267}}</string> + </array> + </dict> + <key>VerticalSplitView</key> + <dict> + <key>_collapsingFrameDimension</key> + <real>0.0</real> + <key>_indexOfCollapsedView</key> + <integer>0</integer> + <key>_percentageOfCollapsedView</key> + <real>0.0</real> + <key>isCollapsed</key> + <string>yes</string> + <key>sizes</key> + <array> + <string>{{0, 0}, {405, 443}}</string> + <string>{{414, 0}, {514, 443}}</string> + </array> + </dict> + </dict> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {460, 159}}</string> + <key>RubberWindowFrame</key> + <string>316 696 459 200 0 0 1280 1002 </string> + </dict> + <key>Module</key> + <string>PBXRunSessionModule</string> + <key>Proportion</key> + <string>159pt</string> + </dict> + </array> + <key>Proportion</key> + <string>159pt</string> + </dict> + </array> + <key>Name</key> + <string>Run Log</string> + <key>ServiceClasses</key> + <array> + <string>PBXRunSessionModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1C0AD2B3069F1EA900FABCE6</string> + <string>1C0AD2B4069F1EA900FABCE6</string> + <string>1CD0528B0623707200166675</string> + <string>1C0AD2B5069F1EA900FABCE6</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.run</string> + <key>WindowString</key> + <string>316 696 459 200 0 0 1280 1002 </string> + <key>WindowToolGUID</key> + <string>1C0AD2B3069F1EA900FABCE6</string> + <key>WindowToolIsVisible</key> + <integer>0</integer> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.scm</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1C78EAB2065D492600B07095</string> + <key>PBXProjectModuleLabel</key> + <string>&lt;No Editor&gt;</string> + <key>PBXSplitModuleInNavigatorKey</key> + <dict> + <key>Split0</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1C78EAB3065D492600B07095</string> + </dict> + <key>SplitCount</key> + <string>1</string> + </dict> + <key>StatusBarVisibility</key> + <integer>1</integer> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {452, 0}}</string> + <key>RubberWindowFrame</key> + <string>743 379 452 308 0 0 1280 1002 </string> + </dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>0pt</string> + </dict> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CD052920623707200166675</string> + <key>PBXProjectModuleLabel</key> + <string>SCM</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>ConsoleFrame</key> + <string>{{0, 259}, {452, 0}}</string> + <key>Frame</key> + <string>{{0, 7}, {452, 259}}</string> + <key>RubberWindowFrame</key> + <string>743 379 452 308 0 0 1280 1002 </string> + <key>TableConfiguration</key> + <array> + <string>Status</string> + <real>30</real> + <string>FileName</string> + <real>199</real> + <string>Path</string> + <real>197.09500122070312</real> + </array> + <key>TableFrame</key> + <string>{{0, 0}, {452, 250}}</string> + </dict> + <key>Module</key> + <string>PBXCVSModule</string> + <key>Proportion</key> + <string>262pt</string> + </dict> + </array> + <key>Proportion</key> + <string>266pt</string> + </dict> + </array> + <key>Name</key> + <string>SCM</string> + <key>ServiceClasses</key> + <array> + <string>PBXCVSModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1C78EAB4065D492600B07095</string> + <string>1C78EAB5065D492600B07095</string> + <string>1C78EAB2065D492600B07095</string> + <string>1CD052920623707200166675</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.scm</string> + <key>WindowString</key> + <string>743 379 452 308 0 0 1280 1002 </string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.breakpoints</string> + <key>IsVertical</key> + <integer>0</integer> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXBottomSmartGroupGIDs</key> + <array> + <string>1C77FABC04509CD000000102</string> + </array> + <key>PBXProjectModuleGUID</key> + <string>1CE0B1FE06471DED0097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>Files</string> + <key>PBXProjectStructureProvided</key> + <string>no</string> + <key>PBXSmartGroupTreeModuleColumnData</key> + <dict> + <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> + <array> + <real>168</real> + </array> + <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> + <array> + <string>MainColumn</string> + </array> + </dict> + <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> + <dict> + <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> + <array> + <string>1C77FABC04509CD000000102</string> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> + <array> + <array> + <integer>0</integer> + </array> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> + <string>{{0, 0}, {168, 350}}</string> + </dict> + <key>PBXTopSmartGroupGIDs</key> + <array/> + <key>XCIncludePerspectivesSwitch</key> + <integer>0</integer> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {185, 368}}</string> + <key>GroupTreeTableConfiguration</key> + <array> + <string>MainColumn</string> + <real>168</real> + </array> + <key>RubberWindowFrame</key> + <string>315 424 744 409 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXSmartGroupTreeModule</string> + <key>Proportion</key> + <string>185pt</string> + </dict> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CA1AED706398EBD00589147</string> + <key>PBXProjectModuleLabel</key> + <string>Detail</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{190, 0}, {554, 368}}</string> + <key>RubberWindowFrame</key> + <string>315 424 744 409 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>XCDetailModule</string> + <key>Proportion</key> + <string>554pt</string> + </dict> + </array> + <key>Proportion</key> + <string>368pt</string> + </dict> + </array> + <key>MajorVersion</key> + <integer>2</integer> + <key>MinorVersion</key> + <integer>0</integer> + <key>Name</key> + <string>Breakpoints</string> + <key>ServiceClasses</key> + <array> + <string>PBXSmartGroupTreeModule</string> + <string>XCDetailModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1CDDB66807F98D9800BB5817</string> + <string>1CDDB66907F98D9800BB5817</string> + <string>1CE0B1FE06471DED0097A5F4</string> + <string>1CA1AED706398EBD00589147</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.breakpoints</string> + <key>WindowString</key> + <string>315 424 744 409 0 0 1440 878 </string> + <key>WindowToolGUID</key> + <string>1CDDB66807F98D9800BB5817</string> + <key>WindowToolIsVisible</key> + <integer>1</integer> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.debugAnimator</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Debug Visualizer</string> + <key>ServiceClasses</key> + <array> + <string>PBXNavigatorGroup</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.debugAnimator</string> + <key>WindowString</key> + <string>100 100 700 500 0 0 1280 1002 </string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.bookmarks</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>Module</key> + <string>PBXBookmarksModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Bookmarks</string> + <key>ServiceClasses</key> + <array> + <string>PBXBookmarksModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>0</integer> + <key>WindowString</key> + <string>538 42 401 187 0 0 1280 1002 </string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.classBrowser</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>OptionsSetName</key> + <string>Hierarchy, all classes</string> + <key>PBXProjectModuleGUID</key> + <string>1CA6456E063B45B4001379D8</string> + <key>PBXProjectModuleLabel</key> + <string>Class Browser - NSObject</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>ClassesFrame</key> + <string>{{0, 0}, {374, 96}}</string> + <key>ClassesTreeTableConfiguration</key> + <array> + <string>PBXClassNameColumnIdentifier</string> + <real>208</real> + <string>PBXClassBookColumnIdentifier</string> + <real>22</real> + </array> + <key>Frame</key> + <string>{{0, 0}, {630, 331}}</string> + <key>MembersFrame</key> + <string>{{0, 105}, {374, 395}}</string> + <key>MembersTreeTableConfiguration</key> + <array> + <string>PBXMemberTypeIconColumnIdentifier</string> + <real>22</real> + <string>PBXMemberNameColumnIdentifier</string> + <real>216</real> + <string>PBXMemberTypeColumnIdentifier</string> + <real>97</real> + <string>PBXMemberBookColumnIdentifier</string> + <real>22</real> + </array> + <key>PBXModuleWindowStatusBarHidden2</key> + <integer>1</integer> + <key>RubberWindowFrame</key> + <string>385 179 630 352 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXClassBrowserModule</string> + <key>Proportion</key> + <string>332pt</string> + </dict> + </array> + <key>Proportion</key> + <string>332pt</string> + </dict> + </array> + <key>Name</key> + <string>Class Browser</string> + <key>ServiceClasses</key> + <array> + <string>PBXClassBrowserModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>0</integer> + <key>TableOfContents</key> + <array> + <string>1C0AD2AF069F1E9B00FABCE6</string> + <string>1C0AD2B0069F1E9B00FABCE6</string> + <string>1CA6456E063B45B4001379D8</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.classbrowser</string> + <key>WindowString</key> + <string>385 179 630 352 0 0 1440 878 </string> + <key>WindowToolGUID</key> + <string>1C0AD2AF069F1E9B00FABCE6</string> + <key>WindowToolIsVisible</key> + <integer>0</integer> + </dict> + </array> +</dict> +</plist> diff --git a/agilelamp-driver/src/AgileLamp/AgileLamp.xcodeproj/chen.pbxuser b/agilelamp-driver/src/AgileLamp/AgileLamp.xcodeproj/chen.pbxuser new file mode 100644 index 0000000..c08cc67 --- /dev/null +++ b/agilelamp-driver/src/AgileLamp/AgileLamp.xcodeproj/chen.pbxuser @@ -0,0 +1,68 @@ +// !$*UTF8*$! +{ + 089C1669FE841209C02AAC07 /* Project object */ = { + activeBuildConfigurationName = Debug; + activeTarget = 32A4FEB80562C75700D090E7 /* AgileLamp */; + codeSenseManager = 744261600DEB5DEF00A0AFE2 /* Code sense */; + perUserDictionary = { + PBXConfiguration.PBXFileTableDataSource3.PBXFileTableDataSource = { + PBXFileTableDataSourceColumnSortingDirectionKey = "-1"; + PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID; + PBXFileTableDataSourceColumnWidthsKey = ( + 20, + 243, + 20, + 48, + 43, + 43, + 20, + ); + PBXFileTableDataSourceColumnsKey = ( + PBXFileDataSource_FiletypeID, + PBXFileDataSource_Filename_ColumnID, + PBXFileDataSource_Built_ColumnID, + PBXFileDataSource_ObjectSize_ColumnID, + PBXFileDataSource_Errors_ColumnID, + PBXFileDataSource_Warnings_ColumnID, + PBXFileDataSource_Target_ColumnID, + ); + }; + PBXPerProjectTemplateStateSaveDate = 233528906; + PBXWorkspaceStateSaveDate = 233528906; + }; + sourceControlManager = 7442615F0DEB5DEF00A0AFE2 /* Source Control */; + userBuildSettings = { + }; + }; + 089C167EFE841241C02AAC07 /* English */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {711, 582}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRect = "{{0, 0}, {711, 582}}"; + sepNavWindowFrame = "{{15, 62}, {750, 711}}"; + }; + }; + 32A4FEB80562C75700D090E7 /* AgileLamp */ = { + activeExec = 0; + }; + 32A4FEC30562C75700D090E7 /* Info.plist */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {711, 1246}}"; + sepNavSelRange = "{151, 22}"; + sepNavVisRect = "{{0, 0}, {711, 582}}"; + sepNavWindowFrame = "{{15, 62}, {750, 711}}"; + }; + }; + 7442615F0DEB5DEF00A0AFE2 /* Source Control */ = { + isa = PBXSourceControlManager; + fallbackIsa = XCSourceControlManager; + isSCMEnabled = 0; + scmConfiguration = { + }; + scmType = ""; + }; + 744261600DEB5DEF00A0AFE2 /* Code sense */ = { + isa = PBXCodeSenseManager; + indexTemplatePath = ""; + }; +} diff --git a/agilelamp-driver/src/AgileLamp/AgileLamp.xcodeproj/project.pbxproj b/agilelamp-driver/src/AgileLamp/AgileLamp.xcodeproj/project.pbxproj new file mode 100644 index 0000000..692fb9f --- /dev/null +++ b/agilelamp-driver/src/AgileLamp/AgileLamp.xcodeproj/project.pbxproj @@ -0,0 +1,239 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 42; + objects = { + +/* Begin PBXBuildFile section */ + 32A4FEBC0562C75700D090E7 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 089C167DFE841241C02AAC07 /* InfoPlist.strings */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 089C167EFE841241C02AAC07 /* English */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/InfoPlist.strings; sourceTree = "<group>"; }; + 32A4FEC30562C75700D090E7 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = Info.plist; sourceTree = "<group>"; }; + 32A4FEC40562C75800D090E7 /* AgileLamp.kext */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = AgileLamp.kext; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 32A4FEBF0562C75700D090E7 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 089C166AFE841209C02AAC07 /* AgileLamp */ = { + isa = PBXGroup; + children = ( + 247142CAFF3F8F9811CA285C /* Source */, + 089C167CFE841241C02AAC07 /* Resources */, + 19C28FB6FE9D52B211CA2CBB /* Products */, + ); + name = AgileLamp; + sourceTree = "<group>"; + }; + 089C167CFE841241C02AAC07 /* Resources */ = { + isa = PBXGroup; + children = ( + 32A4FEC30562C75700D090E7 /* Info.plist */, + 089C167DFE841241C02AAC07 /* InfoPlist.strings */, + ); + name = Resources; + sourceTree = "<group>"; + }; + 19C28FB6FE9D52B211CA2CBB /* Products */ = { + isa = PBXGroup; + children = ( + 32A4FEC40562C75800D090E7 /* AgileLamp.kext */, + ); + name = Products; + sourceTree = "<group>"; + }; + 247142CAFF3F8F9811CA285C /* Source */ = { + isa = PBXGroup; + children = ( + ); + name = Source; + sourceTree = "<group>"; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 32A4FEBA0562C75700D090E7 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 32A4FEB80562C75700D090E7 /* AgileLamp */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1DEB91C308733DAC0010E9CD /* Build configuration list for PBXNativeTarget "AgileLamp" */; + buildPhases = ( + 32A4FEBA0562C75700D090E7 /* Headers */, + 32A4FEBB0562C75700D090E7 /* Resources */, + 32A4FEBD0562C75700D090E7 /* Sources */, + 32A4FEBF0562C75700D090E7 /* Frameworks */, + 32A4FEC00562C75700D090E7 /* Rez */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = AgileLamp; + productInstallPath = "$(SYSTEM_LIBRARY_DIR)/Extensions"; + productName = AgileLamp; + productReference = 32A4FEC40562C75800D090E7 /* AgileLamp.kext */; + productType = "com.apple.product-type.kernel-extension"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 089C1669FE841209C02AAC07 /* Project object */ = { + isa = PBXProject; + buildConfigurationList = 1DEB91C708733DAC0010E9CD /* Build configuration list for PBXProject "AgileLamp" */; + hasScannedForEncodings = 1; + mainGroup = 089C166AFE841209C02AAC07 /* AgileLamp */; + projectDirPath = ""; + targets = ( + 32A4FEB80562C75700D090E7 /* AgileLamp */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 32A4FEBB0562C75700D090E7 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 32A4FEBC0562C75700D090E7 /* InfoPlist.strings in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXRezBuildPhase section */ + 32A4FEC00562C75700D090E7 /* Rez */ = { + isa = PBXRezBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXRezBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 32A4FEBD0562C75700D090E7 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 089C167DFE841241C02AAC07 /* InfoPlist.strings */ = { + isa = PBXVariantGroup; + children = ( + 089C167EFE841241C02AAC07 /* English */, + ); + name = InfoPlist.strings; + sourceTree = "<group>"; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 1DEB91C408733DAC0010E9CD /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + COPY_PHASE_STRIP = NO; + GCC_DYNAMIC_NO_PIC = NO; + GCC_ENABLE_FIX_AND_CONTINUE = YES; + GCC_MODEL_TUNING = G5; + GCC_OPTIMIZATION_LEVEL = 0; + INFOPLIST_FILE = Info.plist; + INSTALL_PATH = "$(SYSTEM_LIBRARY_DIR)/Extensions"; + MODULE_NAME = com.yourcompany.kext.AgileLamp; + MODULE_START = AgileLamp_start; + MODULE_STOP = AgileLamp_stop; + MODULE_VERSION = 1.0.0d1; + PRODUCT_NAME = AgileLamp; + WRAPPER_EXTENSION = kext; + ZERO_LINK = YES; + }; + name = Debug; + }; + 1DEB91C508733DAC0010E9CD /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = ( + ppc, + i386, + ); + GCC_GENERATE_DEBUGGING_SYMBOLS = NO; + GCC_MODEL_TUNING = G5; + INFOPLIST_FILE = Info.plist; + INSTALL_PATH = "$(SYSTEM_LIBRARY_DIR)/Extensions"; + MODULE_NAME = com.yourcompany.kext.AgileLamp; + MODULE_START = AgileLamp_start; + MODULE_STOP = AgileLamp_stop; + MODULE_VERSION = 1.0.0d1; + PRODUCT_NAME = AgileLamp; + WRAPPER_EXTENSION = kext; + }; + name = Release; + }; + 1DEB91C808733DAC0010E9CD /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + PREBINDING = NO; + SDKROOT = /Developer/SDKs/MacOSX10.4u.sdk; + }; + name = Debug; + }; + 1DEB91C908733DAC0010E9CD /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + PREBINDING = NO; + SDKROOT = /Developer/SDKs/MacOSX10.4u.sdk; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1DEB91C308733DAC0010E9CD /* Build configuration list for PBXNativeTarget "AgileLamp" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1DEB91C408733DAC0010E9CD /* Debug */, + 1DEB91C508733DAC0010E9CD /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 1DEB91C708733DAC0010E9CD /* Build configuration list for PBXProject "AgileLamp" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1DEB91C808733DAC0010E9CD /* Debug */, + 1DEB91C908733DAC0010E9CD /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 089C1669FE841209C02AAC07 /* Project object */; +} diff --git a/agilelamp-driver/src/AgileLamp/English.lproj/InfoPlist.strings b/agilelamp-driver/src/AgileLamp/English.lproj/InfoPlist.strings new file mode 100644 index 0000000..85dd324 Binary files /dev/null and b/agilelamp-driver/src/AgileLamp/English.lproj/InfoPlist.strings differ diff --git a/agilelamp-driver/src/AgileLamp/Info.plist b/agilelamp-driver/src/AgileLamp/Info.plist new file mode 100644 index 0000000..278fb5e --- /dev/null +++ b/agilelamp-driver/src/AgileLamp/Info.plist @@ -0,0 +1,88 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> + <dict> + <key>CFBundleDevelopmentRegion</key> + <string>English</string> + <key>CFBundleGetInfoString</key> + <string>Please don't grab the agile lamp, Mac OS</string> + <key>CFBundleIdentifier</key> + <string>com.agileville.DONTGRABKNOB</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundleName</key> + <string>Please don't grab the agile lamp, Mac OS</string> + <key>CFBundlePackageType</key> + <string>KEXT</string> + <key>CFBundleSignature</key> + <string>????</string> + <key>CFBundleVersion</key> + <string>6.0</string> + <key>IOKitPersonalities</key> + <dict> + <key>myUSBDevicePersonality0</key> + <dict> + <key>CFBundleIdentifier</key> + <string>com.apple.iokit.IOUSBHIDDriver</string> + <key>IOClass</key> + <string>IOUSBHIDDriver</string> + <key>IOKitDebug</key> + <integer>65535</integer> + <key>IOProbeScore</key> + <integer>106000</integer> + <key>IOProviderClass</key> + <string>IOUSBInterface</string> + <key>IOProviderMergeProperties</key> + <dict> + <key>ClassicMustNotSeize</key> + <true/> + </dict> + <key>bConfigurationValue</key> + <integer>1</integer> + <key>bInterfaceNumber</key> + <integer>0</integer> + <key>bcdDevice</key> + <integer>256</integer> + <key>idProduct</key> + <integer>514</integer> + <key>idVendor</key> + <integer>4400</integer> + </dict> + <key>myUSBDevicePersonality1</key> + <dict> + <key>CFBundleIdentifier</key> + <string>com.apple.iokit.IOUSBHIDDriver</string> + <key>IOClass</key> + <string>IOUSBHIDDriver</string> + <key>IOKitDebug</key> + <integer>65535</integer> + <key>IOProbeScore</key> + <integer>106000</integer> + <key>IOProviderClass</key> + <string>IOUSBInterface</string> + <key>IOProviderMergeProperties</key> + <dict> + <key>ClassicMustNotSeize</key> + <true/> + </dict> + <key>bConfigurationValue</key> + <integer>1</integer> + <key>bInterfaceNumber</key> + <integer>1</integer> + <key>bcdDevice</key> + <integer>256</integer> + <key>idProduct</key> + <integer>514</integer> + <key>idVendor</key> + <integer>4400</integer> + </dict> + </dict> + <key>OSBundleLibraries</key> + <dict> + <key>com.apple.iokit.IOHIDFamily</key> + <string>1.2</string> + <key>com.apple.kernel.iokit</key> + <string>6.0</string> + </dict> + </dict> +</plist> diff --git a/agilelamp-driver/src/agilelamp-driver b/agilelamp-driver/src/agilelamp-driver deleted file mode 100755 index 6c789bb..0000000 Binary files a/agilelamp-driver/src/agilelamp-driver and /dev/null differ
tristil/agile-lamp
bff2cff35f73d4c53b5171567a191efd961e9970
Now the program has to be installed with a secondary command, a la passenger.
diff --git a/agilelamp-driver/Manifest.txt b/agilelamp-driver/Manifest.txt index 48698ba..db81d97 100644 --- a/agilelamp-driver/Manifest.txt +++ b/agilelamp-driver/Manifest.txt @@ -1,27 +1,28 @@ History.txt License.txt Manifest.txt README.txt Rakefile +bin/install-agilelamp-driver config/hoe.rb config/requirements.rb script/console script/destroy script/generate script/txt2html setup.rb -bin/agilelamp-driver lib/agilelamp-driver.rb +src/agilelamp-driver src/agilelamp.c src/Makefile src/44-usblamp.rules tasks/deployment.rake tasks/environment.rake tasks/website.rake test/test_agilelamp-driver.rb test/test_helper.rb website/index.html website/index.txt website/javascripts/rounded_corners_lite.inc.js website/stylesheets/screen.css website/template.html.erb diff --git a/agilelamp-driver/PostInstall.txt b/agilelamp-driver/PostInstall.txt new file mode 100644 index 0000000..67f438d --- /dev/null +++ b/agilelamp-driver/PostInstall.txt @@ -0,0 +1,5 @@ +******************************************************************** + +Run ` install-agilelamp-driver ` with sudo to complete installation. + +******************************************************************** diff --git a/agilelamp-driver/bin/install-agilelamp-driver b/agilelamp-driver/bin/install-agilelamp-driver new file mode 100755 index 0000000..f51acf4 --- /dev/null +++ b/agilelamp-driver/bin/install-agilelamp-driver @@ -0,0 +1,85 @@ +#!/usr/bin/env ruby + +require 'fileutils' +include FileUtils + +unless `uname`.strip == 'Linux' + puts <<EOF + +This release is only tested for Linux, and really only for Debian-type systems. +If you are using MacOS it will almost certainly not work. +Continue? (y/n) + +EOF + + char = STDIN.getc + exit unless char.chr == 'y' +end + +unless `whoami`.strip == 'root' + puts "You need to be sudo for this to work." + exit +end + +gem_dir = `gem which agilelamp-driver` +parts = gem_dir.split.last.split("/")[0..-3] +cd parts.join("/") + +cd "src" +success = system "make" +unless success + puts <<EOF + +****************************************************************************** +Couldn't make agilelamp-driver. It's possible that the precompiled binary will +work for you (on Linux but not MacOS). Continuing..." +****************************************************************************** + +EOF + +end + +puts "Installing agilelamp-driver to /usr/local/bin..." + +begin + cp "agilelamp-driver", "/usr/local/bin/agilelamp-driver" +rescue + puts <<EOF + +************************************************************************** +Couldn't copy agilelamp-driver to /usr/local/bin/. This shouldn't happen. +************************************************************************** + +EOF + +end + +cd ".." +cd "src" + +begin + puts "Installing udev rule..." + cp "44-usblamp.rules", "/etc/udev/rules.d" +rescue + if `uname`.strip == 'Linux' + puts "Couldn't install 44-usblamp.rules to /etc/udev/rules.d" + end +end + +begin + puts "Attempting to restart udev..." + system "/etc/init.d/udev restart" +rescue + puts "Couldn't restart udev" +end + +puts <<EOF + +To run agilelamp-driver use: + +agilelamp-driver red # red light +agilelamp-driver green # green light +agilelamp-driver bell # unpleasant bell sound +agilelamp-driver various # cycling colors + +EOF diff --git a/agilelamp-driver/config/hoe.rb b/agilelamp-driver/config/hoe.rb index c96f235..a8f15ff 100644 --- a/agilelamp-driver/config/hoe.rb +++ b/agilelamp-driver/config/hoe.rb @@ -1,74 +1,74 @@ #require 'agilelamp-driver/version' AUTHOR = 'Joseph Method' # can also be an array of Authors EMAIL = "[email protected]" DESCRIPTION = "Userland driver for USB Agile Lamp" GEM_NAME = 'agilelamp-driver' # what ppl will type to install your gem RUBYFORGE_PROJECT = 'agilelamp' # The unix name for your project HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org" DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" EXTRA_DEPENDENCIES = [ # ['activesupport', '>= 1.3.1'] ] # An array of rubygem dependencies [name, version] @config_file = "~/.rubyforge/user-config.yml" @config = nil RUBYFORGE_USERNAME = "unknown" def rubyforge_username unless @config begin @config = YAML.load(File.read(File.expand_path(@config_file))) rescue puts <<-EOS ERROR: No rubyforge config file found: #{@config_file} Run 'rubyforge setup' to prepare your env for access to Rubyforge - See http://newgem.rubyforge.org/rubyforge.html for more details EOS exit end end RUBYFORGE_USERNAME.replace @config["username"] end REV = nil # UNCOMMENT IF REQUIRED: # REV = YAML.load(`svn info`)['Revision'] #VERS = Agilelamp-driver::VERSION::STRING + (REV ? ".#{REV}" : "") -VERS = "0.1.1" +VERS = "0.1.2" RDOC_OPTS = ['--quiet', '--title', 'agilelamp-driver documentation', "--opname", "index.html", "--line-numbers", "--main", "README", "--inline-source"] class Hoe def extra_deps @extra_deps.reject! { |x| Array(x).first == 'hoe' } @extra_deps end end # Generate all the Rake tasks # Run 'rake -T' to see list of generated tasks (from gem root directory) $hoe = Hoe.new(GEM_NAME, VERS) do |p| p.developer(AUTHOR, EMAIL) p.description = DESCRIPTION p.summary = DESCRIPTION p.url = HOMEPATH p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT p.test_globs = ["test/**/test_*.rb"] p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean. # == Optional p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n") #p.extra_deps = EXTRA_DEPENDENCIES #p.spec_extras = {} # A hash of extra values to set in the gemspec. end CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n") PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}" $hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc') $hoe.rsync_args = '-av --delete --ignore-errors' $hoe.spec.post_install_message = File.open(File.dirname(__FILE__) + "/../PostInstall.txt").read rescue "" diff --git a/agilelamp-driver/bin/agilelamp-driver b/agilelamp-driver/src/agilelamp-driver similarity index 100% rename from agilelamp-driver/bin/agilelamp-driver rename to agilelamp-driver/src/agilelamp-driver diff --git a/agilelamp-driver/tasks/deployment.rake b/agilelamp-driver/tasks/deployment.rake index cc0d9b0..25ff645 100644 --- a/agilelamp-driver/tasks/deployment.rake +++ b/agilelamp-driver/tasks/deployment.rake @@ -1,77 +1,77 @@ desc 'Release the website and new gem version' task :deploy => [:check_version, :website, :release] do puts "Remember to create SVN tag:" puts "svn copy svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/trunk " + "svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/tags/REL-#{VERS} " puts "Suggested comment:" puts "Tagging release #{CHANGES}" end desc 'Runs tasks website_generate and install_gem as a local deployment of the gem' task :local_deploy => [:website_generate, :install_gem] task :check_version do unless ENV['VERSION'] puts 'Must pass a VERSION=x.y.z release version' exit end unless ENV['VERSION'] == VERS puts "Please update your version.rb to match the release version, currently #{VERS}" exit end end desc 'Install the package as a gem, without generating documentation(ri/rdoc)' task :install_gem_no_doc => [:clean, :package] do sh "#{'sudo ' unless Hoe::WINDOZE }gem install pkg/*.gem --no-rdoc --no-ri" end -task :make_agilelamp_bin do - cd "src/" - begin - sh "make" - cp "agilelamp-driver", "../bin" - rescue - puts <<EOF +#task :make_agilelamp_bin do +# cd "src/" +# begin +# sh "make" +# cp "agilelamp-driver", "../bin" +# rescue +# puts <<EOF +# +#****************************************************************************** +#Couldn't compile for your architecture. Precompiled binary may still work. If +#not, try installing libusb headers (compile and install libusb from source or +#get libusb-dev on debian systems)." +#****************************************************************************** +# +#EOF +# end +# cd "../" +#end -****************************************************************************** -Couldn't compile for your architecture. Precompiled binary may still work. If -not, try installing libusb headers (compile and install libusb from source or -get libusb-dev on debian systems)." -****************************************************************************** +#task :install_udev_rule do +# begin +# if `uname`.strip == 'Linux' +# puts "Installing udev rule to enable hardware use on Linux" +# cp "src/44-usblamp.rules", "/etc/udev/rules.d/" +# puts "Restarting udev..." +# sh "/etc/init.d/udev restart" +# end +# rescue +# puts <<EOF -EOF - end - cd "../" -end +#**************************************************************************** +#Couldn't install udev rules for the USB lamp. Expected to be able to put file +#in /etc/udev/rules.d/. Was this a bad assumption? +#**************************************************************************** -task :install_udev_rule do - begin - if `uname`.strip == 'Linux' - puts "Installing udev rule to enable hardware use on Linux" - cp "src/44-usblamp.rules", "/etc/udev/rules.d/" - puts "Restarting udev..." - sh "/etc/init.d/udev restart" - end - rescue - puts <<EOF +#EOF +# end +#end -**************************************************************************** -Couldn't install udev rules for the USB lamp. Expected to be able to put file -in /etc/udev/rules.d/. Was this a bad assumption? -**************************************************************************** - -EOF - end -end - -task :install_gem => [:clean, :make_agilelamp_bin, :package, :install_udev_rule, ] do - sh "#{'sudo ' unless Hoe::WINDOZE}gem install --no-wrappers --local pkg/*.gem" -end +#task :install_gem => [:clean, :make_agilelamp_bin, :package, :install_udev_rule, ] do +# sh "#{'sudo ' unless Hoe::WINDOZE}gem install --no-wrappers --local pkg/*.gem" +#end namespace :manifest do desc 'Recreate Manifest.txt to include ALL files' task :refresh do `rake check_manifest | patch -p0 > Manifest.txt` end end
tristil/agile-lamp
efb3e7454abe67e70314e799856e50bbd1f4c0e6
Added udev setup file.
diff --git a/agilelamp-driver/Manifest.txt b/agilelamp-driver/Manifest.txt index 7567b80..48698ba 100644 --- a/agilelamp-driver/Manifest.txt +++ b/agilelamp-driver/Manifest.txt @@ -1,26 +1,27 @@ History.txt License.txt Manifest.txt README.txt Rakefile config/hoe.rb config/requirements.rb script/console script/destroy script/generate script/txt2html setup.rb bin/agilelamp-driver lib/agilelamp-driver.rb src/agilelamp.c src/Makefile +src/44-usblamp.rules tasks/deployment.rake tasks/environment.rake tasks/website.rake test/test_agilelamp-driver.rb test/test_helper.rb website/index.html website/index.txt website/javascripts/rounded_corners_lite.inc.js website/stylesheets/screen.css website/template.html.erb diff --git a/agilelamp-driver/Rakefile b/agilelamp-driver/Rakefile index e469154..c13d094 100644 --- a/agilelamp-driver/Rakefile +++ b/agilelamp-driver/Rakefile @@ -1,4 +1,4 @@ require 'config/requirements' require 'config/hoe' # setup Hoe + all gem configuration -Dir['tasks/**/*.rake'].each { |rake| load rake } \ No newline at end of file +Dir['tasks/**/*.rake'].each { |rake| load rake } diff --git a/agilelamp-driver/bin/agilelamp-driver b/agilelamp-driver/bin/agilelamp-driver index 8da79a1..6c789bb 100755 Binary files a/agilelamp-driver/bin/agilelamp-driver and b/agilelamp-driver/bin/agilelamp-driver differ diff --git a/agilelamp-driver/config/hoe.rb b/agilelamp-driver/config/hoe.rb index b55f215..c96f235 100644 --- a/agilelamp-driver/config/hoe.rb +++ b/agilelamp-driver/config/hoe.rb @@ -1,74 +1,74 @@ #require 'agilelamp-driver/version' AUTHOR = 'Joseph Method' # can also be an array of Authors EMAIL = "[email protected]" DESCRIPTION = "Userland driver for USB Agile Lamp" GEM_NAME = 'agilelamp-driver' # what ppl will type to install your gem RUBYFORGE_PROJECT = 'agilelamp' # The unix name for your project HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org" DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" EXTRA_DEPENDENCIES = [ # ['activesupport', '>= 1.3.1'] ] # An array of rubygem dependencies [name, version] @config_file = "~/.rubyforge/user-config.yml" @config = nil RUBYFORGE_USERNAME = "unknown" def rubyforge_username unless @config begin @config = YAML.load(File.read(File.expand_path(@config_file))) rescue puts <<-EOS ERROR: No rubyforge config file found: #{@config_file} Run 'rubyforge setup' to prepare your env for access to Rubyforge - See http://newgem.rubyforge.org/rubyforge.html for more details EOS exit end end RUBYFORGE_USERNAME.replace @config["username"] end REV = nil # UNCOMMENT IF REQUIRED: # REV = YAML.load(`svn info`)['Revision'] #VERS = Agilelamp-driver::VERSION::STRING + (REV ? ".#{REV}" : "") -VERS = "0.1.0" +VERS = "0.1.1" RDOC_OPTS = ['--quiet', '--title', 'agilelamp-driver documentation', "--opname", "index.html", "--line-numbers", "--main", "README", "--inline-source"] class Hoe def extra_deps @extra_deps.reject! { |x| Array(x).first == 'hoe' } @extra_deps end end # Generate all the Rake tasks # Run 'rake -T' to see list of generated tasks (from gem root directory) $hoe = Hoe.new(GEM_NAME, VERS) do |p| p.developer(AUTHOR, EMAIL) p.description = DESCRIPTION p.summary = DESCRIPTION p.url = HOMEPATH p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT p.test_globs = ["test/**/test_*.rb"] p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean. # == Optional p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n") #p.extra_deps = EXTRA_DEPENDENCIES #p.spec_extras = {} # A hash of extra values to set in the gemspec. end CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n") PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}" $hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc') $hoe.rsync_args = '-av --delete --ignore-errors' $hoe.spec.post_install_message = File.open(File.dirname(__FILE__) + "/../PostInstall.txt").read rescue "" diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/src/44-usblamp.rules b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/src/44-usblamp.rules new file mode 100644 index 0000000..9e0dd12 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/src/44-usblamp.rules @@ -0,0 +1 @@ +SYSFS{idVendor}=="1130", SYSFS{idProduct}=="0202", GROUP="plugdev", MODE="0777", OPTIONS="last_rule" diff --git a/agilelamp-driver/script/txt2html b/agilelamp-driver/script/txt2html index 7d5bfad..509c42c 100755 --- a/agilelamp-driver/script/txt2html +++ b/agilelamp-driver/script/txt2html @@ -1,82 +1,82 @@ #!/usr/bin/env ruby GEM_NAME = 'agilelamp-driver' # what ppl will type to install your gem -RUBYFORGE_PROJECT = 'agilelamp-driver' +RUBYFORGE_PROJECT = 'agilelamp' require 'rubygems' begin require 'newgem' require 'rubyforge' rescue LoadError puts "\n\nGenerating the website requires the newgem RubyGem" puts "Install: gem install newgem\n\n" exit(1) end require 'redcloth' require 'syntax/convertors/html' require 'erb' -require File.dirname(__FILE__) + "/../lib/#{GEM_NAME}/version.rb" +#require File.dirname(__FILE__) + "/../lib/#{GEM_NAME}/version.rb" -version = Agilelamp-driver::VERSION::STRING +version = "0.1.0" download = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" def rubyforge_project_id RubyForge.new.autoconfig["group_ids"][RUBYFORGE_PROJECT] end class Fixnum def ordinal # teens return 'th' if (10..19).include?(self % 100) # others case self % 10 when 1: return 'st' when 2: return 'nd' when 3: return 'rd' else return 'th' end end end class Time def pretty return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" end end def convert_syntax(syntax, source) return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^<pre>|</pre>$!,'') end if ARGV.length >= 1 src, template = ARGV template ||= File.join(File.dirname(__FILE__), '/../website/template.html.erb') else puts("Usage: #{File.split($0).last} source.txt [template.html.erb] > output.html") exit! end template = ERB.new(File.open(template).read) title = nil body = nil File.open(src) do |fsrc| title_text = fsrc.readline body_text_template = fsrc.read body_text = ERB.new(body_text_template).result(binding) syntax_items = [] body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)</\1>!m){ ident = syntax_items.length element, syntax, source = $1, $2, $3 syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}</#{element}>" "syntax-temp-#{ident}" } title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip body = RedCloth.new(body_text).to_html body.gsub!(%r!(?:<pre><code>)?syntax-temp-(\d+)(?:</code></pre>)?!){ syntax_items[$1.to_i] } end stat = File.stat(src) created = stat.ctime modified = stat.mtime $stdout << template.result(binding) diff --git a/agilelamp-driver/src/Makefile b/agilelamp-driver/src/Makefile index 5daf3ba..7a80d1a 100644 --- a/agilelamp-driver/src/Makefile +++ b/agilelamp-driver/src/Makefile @@ -1,2 +1,6 @@ +ifeq (`uname`, 'Linux') + export LINUX +endif + all: gcc agilelamp.c -o agilelamp-driver -lusb diff --git a/agilelamp-driver/src/agilelamp.c b/agilelamp-driver/src/agilelamp.c index af52564..f071555 100644 --- a/agilelamp-driver/src/agilelamp.c +++ b/agilelamp-driver/src/agilelamp.c @@ -1,175 +1,174 @@ #include <usb.h> #include <stdio.h> #include <unistd.h> #include <string.h> usb_dev_handle* launcher; //wrapper for control_msg int send_message(char* msg, int index) { int i = 0; int j = usb_control_msg(launcher, 0x21, 0x9, 0x0, index, msg, 8, 1000); return j; } void send_cbw(){ fprintf(stderr, "Sending CBW message\n"); char cbw_message[8] = {0x55, 0x53, 0x42, 0x43, 0, 16, 2, 0}; int ret = send_message(cbw_message, 1); fprintf(stderr, "%d bytes sent\n", ret); } void send_lamp_command(char* title, char* message1, char* message2){ usb_reset(launcher); send_cbw(); fprintf(stderr, "Submitting %s\n", title); int ret = send_message(message1, 0); fprintf(stderr, "%d bytes sent\n", ret); ret = send_message(message2, 0); fprintf(stderr, "%d bytes sent\n", ret); } void set_red_with_bell(){ char message_part_1[8] = {0x0, 0x1, 0x4, 0x9,0x10, 0x19, 0x24, 0x31}; //red with bell char message_part_2[8] = {0x40, 0x51, 0x64, 0x79, 0x90, 0xa9, 0xc4, 0xe1}; // red with bell send_lamp_command("red with bell", message_part_1, message_part_2); } /* Fun with bit-math: Everything on the first (from right) 8 bits of first (from right) byte b0:=1:Bell active;=0:Bell off b1:=1:Green led on; =0:Green led off b2:=1:Red led on;=0:red led off b3:=0:7 colors led on;=1:7 colors led off b0 1 1 1 1 1 111 128 64 32 16 8 421 = 255 c c c c c rgb (c's are colors to cycle through, then red, green, bell) 0 0 0 16 0 000 = */ void only_bell_on(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; char message_part_2[8] = {0,0,0,0, 0,0,0,1}; send_lamp_command("green", message_part_1, message_part_2); } void red_with_no_bell(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; char message_part_2[8] = {0,0,0,0, 0,0,0,4}; send_lamp_command("red with no bell", message_part_1, message_part_2); } void set_green(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //green char message_part_2[8] = {0,0,0,0 ,0,0,0,2}; // green send_lamp_command("green", message_part_1, message_part_2); } void set_lights_off(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; // lights off char message_part_2[8] = {0,0,0,0, 0,0,0,0}; // lights off send_lamp_command("lights off", message_part_1, message_part_2); } void set_colors_with_bell(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //colors with bell char message_part_2[8] = {0,0,0,0, 0,0,0,24}; // colors with bells send_lamp_command("colors with bells", message_part_1, message_part_2); } int load_device(){ int claimed; fprintf(stderr, "Starting\n"); struct usb_bus *busses; usb_init(); fprintf(stderr, "usb_init...\n"); usb_find_busses(); usb_find_devices(); fprintf(stderr, "Found busses, found devices...\n"); busses = usb_get_busses(); fprintf(stderr, "Got busses...\n"); struct usb_bus *bus; int c, i, a; /* ... */ for (bus = busses; bus; bus = bus->next) { struct usb_device *dev; for (dev = bus->devices; dev; dev = dev->next) { /* Check if this device is a printer */ if (dev->descriptor.idVendor == 4400) if(dev->descriptor.idProduct == 514) launcher = usb_open(dev); } } fprintf(stderr, "Got launcher...\n"); //do stuff if(launcher != NULL) { int claimed = usb_claim_interface(launcher, 1); } else { fprintf(stderr, "You didn't really get the launcher!\n"); return 1; } - usb_detach_kernel_driver_np(launcher, 1); usb_detach_kernel_driver_np(launcher, 0); if (claimed == 0) { usb_release_interface(launcher, 1); return 1; } else if (claimed > 0){ fprintf(stderr, "Found launcher...\n"); } } int main(int argc, char *argv[]) { if ( argc != 2 ) /* argc should be 2 for correct execution */ { /* We print argv[0] assuming it is the program name */ printf( "usage: %s red|green|bell|various\n", argv[0] ); } else { int ret = load_device(); char* argument = argv[1]; if(strcmp(argument, "green") == 0){ set_green(); } else if (strcmp(argument, "red") == 0){ red_with_no_bell(); } else if (strcmp(argument, "off") == 0){ set_lights_off(); } else if (strcmp(argument, "various") == 0){ set_colors_with_bell(); } else if (strcmp(argument, "bell") == 0){ only_bell_on(); } } return 0; } diff --git a/agilelamp-driver/tasks/deployment.rake b/agilelamp-driver/tasks/deployment.rake index 16e006e..cc0d9b0 100644 --- a/agilelamp-driver/tasks/deployment.rake +++ b/agilelamp-driver/tasks/deployment.rake @@ -1,51 +1,77 @@ desc 'Release the website and new gem version' task :deploy => [:check_version, :website, :release] do puts "Remember to create SVN tag:" puts "svn copy svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/trunk " + "svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/tags/REL-#{VERS} " puts "Suggested comment:" puts "Tagging release #{CHANGES}" end desc 'Runs tasks website_generate and install_gem as a local deployment of the gem' task :local_deploy => [:website_generate, :install_gem] task :check_version do unless ENV['VERSION'] puts 'Must pass a VERSION=x.y.z release version' exit end unless ENV['VERSION'] == VERS puts "Please update your version.rb to match the release version, currently #{VERS}" exit end end desc 'Install the package as a gem, without generating documentation(ri/rdoc)' task :install_gem_no_doc => [:clean, :package] do sh "#{'sudo ' unless Hoe::WINDOZE }gem install pkg/*.gem --no-rdoc --no-ri" end task :make_agilelamp_bin do cd "src/" begin - sh "make" - cp "agilelamp-driver", "../bin" + sh "make" + cp "agilelamp-driver", "../bin" rescue - puts "***************************" - puts "Couldn't compile for your architecture. Precompiled binary may still work. If not, try installing libusb headers (compile and install libusb from source)." - puts "***************************" + puts <<EOF + +****************************************************************************** +Couldn't compile for your architecture. Precompiled binary may still work. If +not, try installing libusb headers (compile and install libusb from source or +get libusb-dev on debian systems)." +****************************************************************************** + +EOF end cd "../" end -task :install_gem => [:clean, :make_agilelamp_bin, :package] do +task :install_udev_rule do + begin + if `uname`.strip == 'Linux' + puts "Installing udev rule to enable hardware use on Linux" + cp "src/44-usblamp.rules", "/etc/udev/rules.d/" + puts "Restarting udev..." + sh "/etc/init.d/udev restart" + end + rescue + puts <<EOF + +**************************************************************************** +Couldn't install udev rules for the USB lamp. Expected to be able to put file +in /etc/udev/rules.d/. Was this a bad assumption? +**************************************************************************** + +EOF + end +end + +task :install_gem => [:clean, :make_agilelamp_bin, :package, :install_udev_rule, ] do sh "#{'sudo ' unless Hoe::WINDOZE}gem install --no-wrappers --local pkg/*.gem" end namespace :manifest do desc 'Recreate Manifest.txt to include ALL files' task :refresh do `rake check_manifest | patch -p0 > Manifest.txt` end end diff --git a/agilelamp-driver/website/index.html b/agilelamp-driver/website/index.html index 2f6be96..c8203ff 100644 --- a/agilelamp-driver/website/index.html +++ b/agilelamp-driver/website/index.html @@ -1,11 +1,104 @@ -<html> - <head> - <meta http-equiv="Content-type" content="text/html; charset=utf-8"> - <title>agilelamp-driver</title> - - </head> - <body id="body"> - <p>This page has not yet been created for RubyGem <code>agilelamp-driver</code></p> - <p>To the developer: To generate it, update website/index.txt and run the rake task <code>website</code> to generate this <code>index.html</code> file.</p> - </body> -</html> \ No newline at end of file +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <link rel="stylesheet" href="stylesheets/screen.css" type="text/css" media="screen" /> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <title> + Agile Lamp Driver + </title> + <script src="javascripts/rounded_corners_lite.inc.js" type="text/javascript"></script> +<style> + +</style> + <script type="text/javascript"> + window.onload = function() { + settings = { + tl: { radius: 10 }, + tr: { radius: 10 }, + bl: { radius: 10 }, + br: { radius: 10 }, + antiAlias: true, + autoPad: true, + validTags: ["div"] + } + var versionBox = new curvyCorners(settings, document.getElementById("version")); + versionBox.applyCornersToAll(); + } + </script> +</head> +<body> +<div id="main"> + + <h1>Agile Lamp Driver</h1> + <div id="version" class="clickable" onclick='document.location = "http://rubyforge.org/projects/agilelamp"; return false'> + <p>Get Version</p> + <a href="http://rubyforge.org/projects/agilelamp" class="numbers">0.1.0</a> + </div> + <h2>What</h2> + + + <p>A user-space driver for the Agile Lamp <span class="caps">USB</span> Lava Lamp</p> + + + <h2>Installing</h2> + + + <p><pre class='syntax'><span class="ident">sudo</span> <span class="ident">gem</span> <span class="ident">install</span> <span class="ident">agilelamp</span><span class="punct">-</span><span class="ident">driver</span></pre></p> + + + <h2>The basics</h2> + + + <p>After installing the gem, you should be able to control the Agile Lamp while it is plugged in:</p> + + + <ul> + <li><pre class='syntax'>agilelamp-driver red # red means bad!</pre></li> + <li><pre class='syntax'>agilelamp-driver green # green means good!</pre></li> + <li><pre class='syntax'>agilelamp-driver various # meaningless cycling colors</pre></li> + <li><pre class='syntax'>agilelamp-driver bell # the bell is very unpleasant</pre></li> + </ul> + + + <h2>Source code</h2> + + + <p>You can fetch the source from tarball or git repository:</p> + + + <ul> + <li>rubyforge: <a href="http://rubyforge.org/scm/?group_id=6281">http://rubyforge.org/scm/?group_id=6281</a></li> + <li>gitorious: <a href="http://gitorious.org/projects/agile-lamp">website</a> &mdash; <a href="git://gitorious.org/agile-lamp/mainline.git">git://gitorious.org/agile-lamp/mainline.git</a></li> + </ul> + + +<pre>git clone git://gitorious.org/agile-lamp/mainline.git</pre> + + <h3>Build and test instructions</h3> + + +<pre>cd agilelamp-driver +rake test +rake install_gem</pre> + + <h2>License</h2> + + + <p>This code is free to use under the terms of the <span class="caps">MIT</span> license.</p> + + + <h2>Contact</h2> + + + <p>Comments are welcome. Send comments or questions to <a href="mailto:[email protected]">Joseph Method</a>.</p> + <p class="coda"> + <a href="[email protected]">Joseph Method</a>, 20th May 2008<br> + Theme extended from <a href="http://rb2js.rubyforge.org/">Paul Battley</a> + </p> +</div> + +<!-- insert site tracking codes here, like Google Urchin --> + +</body> +</html> diff --git a/agilelamp-driver/website/index.txt b/agilelamp-driver/website/index.txt index 60bd997..af27460 100644 --- a/agilelamp-driver/website/index.txt +++ b/agilelamp-driver/website/index.txt @@ -1,83 +1,42 @@ -h1. agilelamp driver - -h1. &#x2192; 'agilelamp-driver' - +h1. Agile Lamp Driver h2. What +A user-space driver for the Agile Lamp USB Lava Lamp h2. Installing <pre syntax="ruby">sudo gem install agilelamp-driver</pre> h2. The basics +After installing the gem, you should be able to control the Agile Lamp while it is plugged in: -h2. Demonstration of usage - - - -h2. Forum - -"http://groups.google.com/group/agilelamp-driver":http://groups.google.com/group/agilelamp-driver - -TODO - create Google Group - agilelamp-driver +* <pre syntax="terminal">agilelamp-driver red # red means bad!</pre> +* <pre syntax="terminal">agilelamp-driver green # green means good!</pre> +* <pre syntax="terminal">agilelamp-driver various # meaningless cycling colors</pre> +* <pre syntax="terminal">agilelamp-driver bell # the bell is very unpleasant</pre> -h2. How to submit patches +h2. Source code -Read the "8 steps for fixing other people's code":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/ and for section "8b: Submit patch to Google Groups":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/#8b-google-groups, use the Google Group above. - -TODO - pick SVN or Git instructions - -The trunk repository is <code>svn://rubyforge.org/var/svn/agilelamp-driver/trunk</code> for anonymous access. - -OOOORRRR - -You can fetch the source from either: - -<% if rubyforge_project_id %> +You can fetch the source from tarball or git repository: * rubyforge: "http://rubyforge.org/scm/?group_id=<%= rubyforge_project_id %>":http://rubyforge.org/scm/?group_id=<%= rubyforge_project_id %> +* gitorious: "website":http://gitorious.org/projects/agile-lamp &mdash; "git://gitorious.org/agile-lamp/mainline.git":git://gitorious.org/agile-lamp/mainline.git -<pre>git clone git://rubyforge.org/agilelamp-driver.git</pre> - -<% else %> - -* rubyforge: MISSING IN ACTION - -TODO - You can not created a RubyForge project, OR have not run <code>rubyforge config</code> -yet to refresh your local rubyforge data with this projects' id information. - -When you do this, this message will magically disappear! - -Or you can hack website/index.txt and make it all go away!! - -<% end %> - -* github: "http://github.com/GITHUB_USERNAME/agilelamp-driver/tree/master":http://github.com/GITHUB_USERNAME/agilelamp-driver/tree/master - -<pre>git clone git://github.com/GITHUB_USERNAME/agilelamp-driver.git</pre> - - -TODO - add "github_username: username" to ~/.rubyforge/user-config.yml and newgem will reuse it for future projects. - - -* gitorious: "git://gitorious.org/agilelamp-driver/mainline.git":git://gitorious.org/agilelamp-driver/mainline.git - -<pre>git clone git://gitorious.org/agilelamp-driver/mainline.git</pre> +<pre>git clone git://gitorious.org/agile-lamp/mainline.git</pre> h3. Build and test instructions <pre>cd agilelamp-driver rake test rake install_gem</pre> - h2. License This code is free to use under the terms of the MIT license. h2. Contact -Comments are welcome. Send an email to "Joseph Method":mailto:[email protected] via the "forum":http://groups.google.com/group/agilelamp-driver +Comments are welcome. Send comments or questions to "Joseph Method":mailto:[email protected].
tristil/agile-lamp
31f423487cafb143efd06da89a9d0d9c242a9f11
Add windows_driver_code
diff --git a/windows_driver_code/GenericHID.cpp b/windows_driver_code/GenericHID.cpp new file mode 100644 index 0000000..1ae2996 --- /dev/null +++ b/windows_driver_code/GenericHID.cpp @@ -0,0 +1,74 @@ +// GenericHID.cpp : Defines the class behaviors for the application. +// + +#include "stdafx.h" +#include "GenericHID.h" +#include "GenericHIDDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CGenericHIDApp + +BEGIN_MESSAGE_MAP(CGenericHIDApp, CWinApp) + //{{AFX_MSG_MAP(CGenericHIDApp) + // NOTE - the ClassWizard will add and remove mapping macros here. + // DO NOT EDIT what you see in these blocks of generated code! + //}}AFX_MSG + ON_COMMAND(ID_HELP, CWinApp::OnHelp) +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CGenericHIDApp construction + +CGenericHIDApp::CGenericHIDApp() +{ + // TODO: add construction code here, + // Place all significant initialization in InitInstance +} + +///////////////////////////////////////////////////////////////////////////// +// The one and only CGenericHIDApp object + +CGenericHIDApp theApp; + +///////////////////////////////////////////////////////////////////////////// +// CGenericHIDApp initialization + +BOOL CGenericHIDApp::InitInstance() +{ + AfxEnableControlContainer(); + + // Standard initialization + // If you are not using these features and wish to reduce the size + // of your final executable, you should remove from the following + // the specific initialization routines you do not need. + +#ifdef _AFXDLL + Enable3dControls(); // Call this when using MFC in a shared DLL +#else + Enable3dControlsStatic(); // Call this when linking to MFC statically +#endif + + CGenericHIDDlg dlg; + m_pMainWnd = &dlg; + int nResponse = dlg.DoModal(); + if (nResponse == IDOK) + { + // TODO: Place code here to handle when the dialog is + // dismissed with OK + } + else if (nResponse == IDCANCEL) + { + // TODO: Place code here to handle when the dialog is + // dismissed with Cancel + } + + // Since the dialog has been closed, return FALSE so that we exit the + // application, rather than start the application's message pump. + return FALSE; +} diff --git a/windows_driver_code/GenericHID.dsp b/windows_driver_code/GenericHID.dsp new file mode 100644 index 0000000..a2f7bf6 --- /dev/null +++ b/windows_driver_code/GenericHID.dsp @@ -0,0 +1,174 @@ +# Microsoft Developer Studio Project File - Name="GenericHID" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Application" 0x0101 + +CFG=GenericHID - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "GenericHID.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "GenericHID.mak" CFG="GenericHID - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "GenericHID - Win32 Release" (based on "Win32 (x86) Application") +!MESSAGE "GenericHID - Win32 Debug" (based on "Win32 (x86) Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "GenericHID - Win32 Release" + +# PROP BASE Use_MFC 5 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 5 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /MT /W3 /GX /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D WINVER=0x0500 /D _WIN32_WINNT=0x0500 /Yu"stdafx.h" /FD /c +# SUBTRACT CPP /Z<none> /O<none> +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x404 /d "NDEBUG" +# ADD RSC /l 0x404 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 /nologo /subsystem:windows /machine:I386 +# ADD LINK32 setupapi.lib hid.lib /nologo /subsystem:windows /machine:I386 + +!ELSEIF "$(CFG)" == "GenericHID - Win32 Debug" + +# PROP BASE Use_MFC 5 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 5 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /I "c:\ntddk\inc" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D WINVER=0x0500 /Yu"stdafx.h" /FD /GZ /c +# SUBTRACT CPP /O<none> +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x404 /d "_DEBUG" +# ADD RSC /l 0x404 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept +# ADD LINK32 setupapi.lib hid.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "GenericHID - Win32 Release" +# Name "GenericHID - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\GenericHID.cpp +# End Source File +# Begin Source File + +SOURCE=.\GenericHID.rc +# End Source File +# Begin Source File + +SOURCE=.\GenericHIDDlg.cpp +# End Source File +# Begin Source File + +SOURCE=.\HidClient.cpp +# End Source File +# Begin Source File + +SOURCE=.\pnp.cpp +# End Source File +# Begin Source File + +SOURCE=.\StdAfx.cpp +# ADD CPP /Yc"stdafx.h" +# End Source File +# Begin Source File + +SOURCE=.\USBHID.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\GenericHID.h +# End Source File +# Begin Source File + +SOURCE=.\GenericHIDDlg.h +# End Source File +# Begin Source File + +SOURCE=.\hid.h +# End Source File +# Begin Source File + +SOURCE=.\HidClient.h +# End Source File +# Begin Source File + +SOURCE=.\Resource.h +# End Source File +# Begin Source File + +SOURCE=.\StdAfx.h +# End Source File +# Begin Source File + +SOURCE=.\USBHID.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# Begin Source File + +SOURCE=.\res\GenericHID.ico +# End Source File +# Begin Source File + +SOURCE=.\res\GenericHID.rc2 +# End Source File +# End Group +# Begin Source File + +SOURCE=.\ReadMe.txt +# End Source File +# End Target +# End Project diff --git a/windows_driver_code/GenericHID.dsw b/windows_driver_code/GenericHID.dsw new file mode 100644 index 0000000..0369b49 --- /dev/null +++ b/windows_driver_code/GenericHID.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "GenericHID"=.\GenericHID.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/windows_driver_code/GenericHID.exe b/windows_driver_code/GenericHID.exe new file mode 100644 index 0000000..a754564 Binary files /dev/null and b/windows_driver_code/GenericHID.exe differ diff --git a/windows_driver_code/GenericHID.h b/windows_driver_code/GenericHID.h new file mode 100644 index 0000000..e8cde3f --- /dev/null +++ b/windows_driver_code/GenericHID.h @@ -0,0 +1,49 @@ +// GenericHID.h : main header file for the GENERICHID application +// + +#if !defined(AFX_GENERICHID_H__92988EC0_5BC1_4739_A2B6_D75967A3BA0F__INCLUDED_) +#define AFX_GENERICHID_H__92988EC0_5BC1_4739_A2B6_D75967A3BA0F__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#ifndef __AFXWIN_H__ + #error include 'stdafx.h' before including this file for PCH +#endif + +#include "resource.h" // main symbols + +///////////////////////////////////////////////////////////////////////////// +// CGenericHIDApp: +// See GenericHID.cpp for the implementation of this class +// + +class CGenericHIDApp : public CWinApp +{ +public: + CGenericHIDApp(); + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CGenericHIDApp) + public: + virtual BOOL InitInstance(); + //}}AFX_VIRTUAL + +// Implementation + + //{{AFX_MSG(CGenericHIDApp) + // NOTE - the ClassWizard will add and remove member functions here. + // DO NOT EDIT what you see in these blocks of generated code ! + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + + +///////////////////////////////////////////////////////////////////////////// + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_GENERICHID_H__92988EC0_5BC1_4739_A2B6_D75967A3BA0F__INCLUDED_) diff --git a/windows_driver_code/GenericHID.ico b/windows_driver_code/GenericHID.ico new file mode 100644 index 0000000..7eef0bc Binary files /dev/null and b/windows_driver_code/GenericHID.ico differ diff --git a/windows_driver_code/GenericHID.rc b/windows_driver_code/GenericHID.rc new file mode 100644 index 0000000..15e6190 --- /dev/null +++ b/windows_driver_code/GenericHID.rc @@ -0,0 +1,221 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Chinese (Taiwan) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHT) +#ifdef _WIN32 +LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL +#pragma code_page(950) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "\r\n" + "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHT)\r\n" + "#ifdef _WIN32\r\n" + "LANGUAGE 4, 1\r\n" + "#pragma code_page(950)\r\n" + "#endif //_WIN32\r\n" + "#include ""res\\GenericHID.rc2"" // non-Microsoft Visual C++ edited resources\r\n" + "#include ""l.cht\\afxres.rc"" // Standard components\r\n" + "#endif\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDR_MAINFRAME ICON DISCARDABLE "res\\GenericHID.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_ABOUTBOX DIALOG DISCARDABLE 0, 0, 235, 55 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Ãö©ó GenericHID" +FONT 9, "·s²Ó©úÅé" +BEGIN + ICON IDR_MAINFRAME,IDC_STATIC,11,17,20,20 + LTEXT "GenericHID Version 1.0",IDC_STATIC,40,10,119,8, + SS_NOPREFIX + LTEXT "Copyright (C) 2003",IDC_STATIC,40,25,119,8 + DEFPUSHBUTTON "½T©w",IDOK,178,7,50,14,WS_GROUP +END + +IDD_GENERICHID_DIALOG DIALOGEX 0, 0, 212, 239 +STYLE DS_MODALFRAME | WS_MINIMIZEBOX | WS_POPUP | WS_VISIBLE | WS_CAPTION | + WS_SYSMENU +EXSTYLE WS_EX_APPWINDOW +CAPTION "GenericHID Build 2" +FONT 9, "·s²Ó©úÅé" +BEGIN + CONTROL "Output Pattern 1",IDC_OUTPUTPATTERN1,"Button", + BS_AUTORADIOBUTTON | WS_GROUP,30,30,75,10 + CONTROL "Output Pattern 2",IDC_OUTPUTPATTERN2,"Button", + BS_AUTORADIOBUTTON,110,30,75,10 + CONTROL "Output Pattern 3",IDC_OUTPUTPATTERN3,"Button", + BS_AUTORADIOBUTTON,30,50,75,10 + CONTROL "Output Pattern 4",IDC_OUTPUTPATTERN4,"Button", + BS_AUTORADIOBUTTON,110,50,75,10 + PUSHBUTTON "&Output to Device",IDC_OUTPUT,65,70,75,15 + EDITTEXT IDC_LENGTH,60,200,35,14,ES_AUTOHSCROLL + PUSHBUTTON "&Input from Device",IDC_INPUT,110,200,75,15 + GROUPBOX "Output",IDC_STATIC,10,10,190,85 + GROUPBOX "Input",IDC_STATIC,10,100,190,130 + EDITTEXT IDC_INPUTDISPLAY,25,115,160,75,ES_MULTILINE | + ES_AUTOVSCROLL | ES_READONLY | ES_WANTRETURN | + WS_VSCROLL | NOT WS_TABSTOP + LTEXT "Length",IDC_STATIC,30,200,25,15,SS_CENTERIMAGE +END + + +#ifndef _MAC +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040404B0" + BEGIN + VALUE "CompanyName", "\0" + VALUE "FileDescription", "GenericHID MFC Application\0" + VALUE "FileVersion", "1, 0, 0, 1\0" + VALUE "InternalName", "GenericHID\0" + VALUE "LegalCopyright", "Copyright (C) 2003\0" + VALUE "LegalTrademarks", "\0" + VALUE "OriginalFilename", "GenericHID.EXE\0" + VALUE "ProductName", "GenericHID Application\0" + VALUE "ProductVersion", "1, 0, 0, 1\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x404, 1200 + END +END + +#endif // !_MAC + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO DISCARDABLE +BEGIN + IDD_ABOUTBOX, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 228 + TOPMARGIN, 7 + BOTTOMMARGIN, 48 + END + + IDD_GENERICHID_DIALOG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 205 + TOPMARGIN, 7 + BOTTOMMARGIN, 232 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE DISCARDABLE +BEGIN + IDS_ABOUTBOX "Ãö©ó GenericHID(&A)..." +END + +#endif // Chinese (Taiwan) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#define _AFX_NO_SPLITTER_RESOURCES +#define _AFX_NO_OLE_RESOURCES +#define _AFX_NO_TRACKER_RESOURCES +#define _AFX_NO_PROPERTY_RESOURCES + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHT) +#ifdef _WIN32 +LANGUAGE 4, 1 +#pragma code_page(950) +#endif //_WIN32 +#include "res\GenericHID.rc2" // non-Microsoft Visual C++ edited resources +#include "l.cht\afxres.rc" // Standard components +#endif + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/windows_driver_code/GenericHID.rc2 b/windows_driver_code/GenericHID.rc2 new file mode 100644 index 0000000..a0e47dd --- /dev/null +++ b/windows_driver_code/GenericHID.rc2 @@ -0,0 +1,13 @@ +// +// GENERICHID.RC2 - resources Microsoft Visual C++ does not edit directly +// + +#ifdef APSTUDIO_INVOKED + #error this file is not editable by Microsoft Visual C++ +#endif //APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// Add manually edited resources here... + +///////////////////////////////////////////////////////////////////////////// diff --git a/windows_driver_code/GenericHIDDlg.cpp b/windows_driver_code/GenericHIDDlg.cpp new file mode 100644 index 0000000..1bdd765 --- /dev/null +++ b/windows_driver_code/GenericHIDDlg.cpp @@ -0,0 +1,467 @@ +// GenericHIDDlg.cpp : implementation file +// + +#include "stdafx.h" +#include <dbt.h> +#include "GenericHID.h" +#include "GenericHIDDlg.h" +#include "USBHid.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CAboutDlg dialog used for App About + +class CAboutDlg : public CDialog +{ +public: + CAboutDlg(); + +// Dialog Data + //{{AFX_DATA(CAboutDlg) + enum { IDD = IDD_ABOUTBOX }; + //}}AFX_DATA + + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CAboutDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + //{{AFX_MSG(CAboutDlg) + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) +{ + //{{AFX_DATA_INIT(CAboutDlg) + //}}AFX_DATA_INIT +} + +void CAboutDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CAboutDlg) + //}}AFX_DATA_MAP +} + +BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) + //{{AFX_MSG_MAP(CAboutDlg) + // No message handlers + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CGenericHIDDlg dialog + +CGenericHIDDlg::CGenericHIDDlg(CWnd* pParent /*=NULL*/) + : CDialog(CGenericHIDDlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CGenericHIDDlg) + m_nOutputPattern = 0; + m_strInputDisplay = _T(""); + m_nReadLength = 16; + m_nWriteLength = 16; + //}}AFX_DATA_INIT + // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 + m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); +} + +void CGenericHIDDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CGenericHIDDlg) + DDX_Radio(pDX, IDC_OUTPUTPATTERN1, m_nOutputPattern); + DDX_Text(pDX, IDC_INPUTDISPLAY, m_strInputDisplay); + //}}AFX_DATA_MAP +// DDX_Text(pDX, IDC_OUTLENGTH, m_nWriteLength); +// DDV_MinMaxInt(pDX, m_nWriteLength, 0, 65535); +} + +BEGIN_MESSAGE_MAP(CGenericHIDDlg, CDialog) + //{{AFX_MSG_MAP(CGenericHIDDlg) + ON_WM_SYSCOMMAND() + ON_WM_PAINT() + ON_WM_QUERYDRAGICON() + ON_BN_CLICKED(IDC_INPUT, OnInput) + ON_BN_CLICKED(IDC_OUTPUT, OnOutput) + ON_MESSAGE(WM_DISPLAY_READ_DATA, OnDisplayReadData) + ON_WM_CLOSE() + ON_MESSAGE(WM_DEVICECHANGE,OnDeviceChange) + ON_MESSAGE(WM_UNREGISTER_HANDLE,OnUnregisterHandle) + ON_MESSAGE(WM_DEVICE_REMOVE_DONE,OnDeviceRemoveDone) + ON_MESSAGE(WM_DEVICE_FIND_DONE,OnDeviceFindDone) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CGenericHIDDlg message handlers + +BOOL CGenericHIDDlg::OnInitDialog() +{ + CDialog::OnInitDialog(); + + // Add "About..." menu item to system menu. + + // IDM_ABOUTBOX must be in the system command range. + ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); + ASSERT(IDM_ABOUTBOX < 0xF000); + + CMenu* pSysMenu = GetSystemMenu(FALSE); + if (pSysMenu != NULL) + { + CString strAboutMenu; + strAboutMenu.LoadString(IDS_ABOUTBOX); + if (!strAboutMenu.IsEmpty()) + { + pSysMenu->AppendMenu(MF_SEPARATOR); + pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); + } + } + + // Set the icon for this dialog. The framework does this automatically + // when the application's main window is not a dialog + SetIcon(m_hIcon, TRUE); // Set big icon + SetIcon(m_hIcon, FALSE); // Set small icon + + // Register the notification for HID devices. + DEV_BROADCAST_DEVICEINTERFACE broadcastInterface; + + broadcastInterface.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); + broadcastInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; + + HidD_GetHidGuid(&broadcastInterface.dbcc_classguid); + + m_hHidNotificationHandle = RegisterDeviceNotification(m_hWnd, + &broadcastInterface, + DEVICE_NOTIFY_WINDOW_HANDLE); + + if(m_USBHidDevice.FindDevice(m_hWnd)) { + m_bFoundDevice = TRUE; + } else { + MessageBox("Cannot find the generic HID device. Please plug in the device.", "Error", MB_ICONWARNING | MB_OK); + if(m_USBHidDevice.FindDevice(m_hWnd)) { //Find again. + m_bFoundDevice = TRUE; + } else { + UpdateUI(FALSE); + m_bFoundDevice = FALSE; + } + } + + SetDlgItemInt(IDC_LENGTH, m_nReadLength); + // keybd_event(0xaa, 0, 0, 0); + // keybd_event(0xaa, 0, KEYEVENTF_KEYUP, 0); + + return TRUE; // return TRUE unless you set the focus to a control +} + +void CGenericHIDDlg::OnSysCommand(UINT nID, LPARAM lParam) +{ + if ((nID & 0xFFF0) == IDM_ABOUTBOX) + { + CAboutDlg dlgAbout; + dlgAbout.DoModal(); + } + else + { + CDialog::OnSysCommand(nID, lParam); + } +} + +// If you add a minimize button to your dialog, you will need the code below +// to draw the icon. For MFC applications using the document/view model, +// this is automatically done for you by the framework. + +void CGenericHIDDlg::OnPaint() +{ + if (IsIconic()) + { + CPaintDC dc(this); // device context for painting + + SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); + + // Center icon in client rectangle + int cxIcon = GetSystemMetrics(SM_CXICON); + int cyIcon = GetSystemMetrics(SM_CYICON); + CRect rect; + GetClientRect(&rect); + int x = (rect.Width() - cxIcon + 1) / 2; + int y = (rect.Height() - cyIcon + 1) / 2; + + // Draw the icon + dc.DrawIcon(x, y, m_hIcon); + } + else + { + CDialog::OnPaint(); + } +} + +// The system calls this to obtain the cursor to display while the user drags +// the minimized window. +HCURSOR CGenericHIDDlg::OnQueryDragIcon() +{ + return (HCURSOR) m_hIcon; +} + +void CGenericHIDDlg::OnInput() +{ + int nActualLength; + CString strByteData; + m_strInputDisplay.Empty(); + + m_nReadLength = GetDlgItemInt(IDC_LENGTH); + if(m_nReadLength>255 || m_nReadLength<1) { + MessageBox("Input length is only valid between 1 and 255.", "Error", MB_OK | MB_ICONERROR); + return; + } + PUCHAR pszByteData = (PUCHAR)calloc(sizeof(UCHAR), m_nReadLength); + + if(m_USBHidDevice.ReadBuffer(pszByteData, m_nReadLength, &nActualLength)) { + + for(WORD wCount=0; wCount<m_nReadLength; wCount++) { + if(wCount%8 == 7) { + strByteData.Format("%2x\r\n", pszByteData[wCount]); + } else { + strByteData.Format("%2x ", pszByteData[wCount]); + } + m_strInputDisplay += strByteData; + } + UpdateData(FALSE); + MessageBox("Data has been read and displayed.", "GenericHID", MB_OK | MB_ICONINFORMATION); + } else { + MessageBox("Read device failed", "Error", MB_OK | MB_ICONERROR); + } + delete(pszByteData); +} + + +void CGenericHIDDlg::OnOutput() +{ + int nActualLength; + PCHAR szByteData; + UCHAR ucCount; + + UpdateData(TRUE); + m_nWriteLength = 16; // Now only length 16 is available. + szByteData = (PCHAR)calloc(sizeof(char), m_nWriteLength); + + + switch(m_nOutputPattern) { + case 0: + for(ucCount=0; ucCount<m_nWriteLength; ucCount++) { + szByteData[ucCount] = (CHAR)0x5a; + } + break; + case 1: + for(ucCount=0; ucCount<m_nWriteLength; ucCount++) { + szByteData[ucCount] = (CHAR)(ucCount*ucCount); + } + break; + case 2: + for(ucCount=0; ucCount<m_nWriteLength; ucCount++) { + szByteData[ucCount] = ucCount; + } + break; + case 3: + for(ucCount=0; ucCount<m_nWriteLength; ucCount++) { + szByteData[ucCount] = 0xff - ucCount; + } + break; + } + + CString strDisplay, strByteData; + strDisplay = "Data { "; + for(ucCount=0; ucCount<m_nWriteLength; ucCount++) { + if((ucCount%16==0) && ucCount) { + strByteData.Format("\r\n%2x ", (UCHAR)szByteData[ucCount]); + } else { + strByteData.Format("%2x ", (UCHAR)szByteData[ucCount]); + } + strDisplay+=strByteData; + } + strDisplay += " } is going to be written into device."; + if(MessageBox(strDisplay, "GenericHID", MB_OKCANCEL | MB_ICONINFORMATION)==IDOK) { + if(m_USBHidDevice.WriteBuffer(szByteData, m_nWriteLength, &nActualLength) == FALSE) { + MessageBox("Write device failed", "Error", MB_OK | MB_ICONERROR); + } else { + MessageBox("Data has been written into device.", "GenericHID", MB_OK | MB_ICONINFORMATION); + } + } + delete(szByteData); +} + +LRESULT CGenericHIDDlg::OnDisplayReadData(WPARAM wParam, LPARAM lParam) +{ + CString strByteData; + + // + // LParam is the device that was read from + // + PHID_DEVICE pDevice = (PHID_DEVICE)lParam; + + for(WORD wCount=0; wCount<pDevice->Caps.InputReportByteLength; wCount++) { + strByteData.Format("%02x ",pDevice->InputReportBuffer[wCount]); + m_strInputDisplay += strByteData; + } + strByteData.Format("\r\n"); + m_strInputDisplay += strByteData; + UpdateData(FALSE); + + SetEvent( m_ReadContext.DisplayEvent ); + return TRUE; +} + +void CGenericHIDDlg::UpdateUI(BOOL bEnable) +{ + CButton* pButton = (CButton*) GetDlgItem(IDC_INPUT); + pButton->EnableWindow(bEnable); + + pButton = (CButton*) GetDlgItem(IDC_OUTPUT); + pButton->EnableWindow(bEnable); +} + +void CGenericHIDDlg::OnClose() +{ +/* if(m_hHidNotificationHandle) { + UnregisterDeviceNotification(m_hHidNotificationHandle); + m_hHidNotificationHandle = NULL; + }*/ + + if(m_bFoundDevice) { + m_USBHidDevice.CloseDevice(); + m_bFoundDevice = FALSE; + } + + EndDialog(0); + CDialog::OnClose(); +} + +void CGenericHIDDlg::OnDeviceRemoveDone(WPARAM wParam, LPARAM lParam) +{ + MessageBox("Device has been removed.", "GenericHID", MB_OK | MB_ICONINFORMATION); +} + +void CGenericHIDDlg::OnDeviceFindDone(WPARAM wParam, LPARAM lParam) +{ + MessageBox("HID Device found", "GenericHID", MB_OK | MB_ICONINFORMATION); +} + +void CGenericHIDDlg::OnUnregisterHandle(WPARAM wParam, LPARAM lParam) +{ + UnregisterDeviceNotification ( (HDEVNOTIFY) lParam ); +} + +BOOL CGenericHIDDlg::OnDeviceChange(WPARAM wParam, LPARAM lParam) +{ + PDEV_BROADCAST_HDR broadcastHdr; + + switch (wParam) { + case DBT_DEVICEARRIVAL: + broadcastHdr = (PDEV_BROADCAST_HDR) lParam; + if ( (DBT_DEVTYP_DEVICEINTERFACE == broadcastHdr -> dbch_devicetype) && !m_bFoundDevice) + { + PDEV_BROADCAST_DEVICEINTERFACE broadcastInterface; + + broadcastInterface = (PDEV_BROADCAST_DEVICEINTERFACE) lParam; + + // + // Open the hid device for query access + // + + if(m_USBHidDevice.FindDeviceByPath(broadcastInterface->dbcc_name, m_hWnd)) { + m_bFoundDevice = TRUE; + UpdateUI(TRUE); + PostMessage(WM_DEVICE_FIND_DONE, 0, 0); + } + } + break; + + case DBT_DEVICEREMOVEPENDING: + case DBT_DEVICEREMOVECOMPLETE: + + // + // Do the same steps for DBT_DEVICEREMOVEPENDING and + // DBT_DEVICEREMOVECOMPLETE. We do not receive the + // remove complete request for a device if it is + // disabled or removed via Device Manager. However, + // in that case will receive the remove pending. + // We remove the device from our currently displayed + // list of devices and unregister notification. + // + broadcastHdr = (PDEV_BROADCAST_HDR) lParam; + + if (DBT_DEVTYP_HANDLE == broadcastHdr -> dbch_devicetype) + { + PDEV_BROADCAST_HANDLE broadcastHandle; + HANDLE deviceHandle; + + broadcastHandle = (PDEV_BROADCAST_HANDLE) lParam; + + // + // Get the file handle of the device that was removed + // from the system + // + + deviceHandle = (HANDLE) broadcastHandle -> dbch_handle; + + if(m_USBHidDevice.CloseDeviceByHandle(deviceHandle, m_hWnd)) { + UpdateUI(FALSE); + m_bFoundDevice = FALSE; + } + } + + break; + + case DBT_DEVICEQUERYREMOVE: + + // + // If this message is received, the device is either + // being disabled or removed through device manager. + // To properly handle this request, we need to close + // the handle to the device. + // + + broadcastHdr = (PDEV_BROADCAST_HDR) lParam; + + if (DBT_DEVTYP_HANDLE == broadcastHdr -> dbch_devicetype) + { + PDEV_BROADCAST_HANDLE broadcastHandle; + HANDLE deviceHandle; + + broadcastHandle = (PDEV_BROADCAST_HANDLE) lParam; + + // + // Get the file handle of the device that was removed + // from the system + // + + deviceHandle = (HANDLE) broadcastHandle -> dbch_handle; + + m_USBHidDevice.CloseDeviceByHandle(deviceHandle, m_hWnd); + } + return TRUE; + } + return FALSE; +} + +void CGenericHIDDlg::OnOK() +{ + // TODO: Add extra validation here + + //CDialog::OnOK(); +} + +void CGenericHIDDlg::OnCancel() +{ + // TODO: Add extra cleanup here + + //CDialog::OnCancel(); +} diff --git a/windows_driver_code/GenericHIDDlg.h b/windows_driver_code/GenericHIDDlg.h new file mode 100644 index 0000000..c7f88d6 --- /dev/null +++ b/windows_driver_code/GenericHIDDlg.h @@ -0,0 +1,70 @@ +// GenericHIDDlg.h : header file +// + +#if !defined(AFX_GENERICHIDDLG_H__18368FF8_0F01_40AC_89DC_C59E95EC3124__INCLUDED_) +#define AFX_GENERICHIDDLG_H__18368FF8_0F01_40AC_89DC_C59E95EC3124__INCLUDED_ + +#include "HidClient.h" // Added by ClassView +#include "hid.h" // Added by ClassView +#include "USBHID.h" // Added by ClassView +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +///////////////////////////////////////////////////////////////////////////// +// CGenericHIDDlg dialog + +class CGenericHIDDlg : public CDialog +{ +// Construction +public: + USBHID m_USBHidDevice; + BOOL m_bFoundDevice; + HANDLE m_hHidNotificationHandle; + void UpdateUI(BOOL bEnable); + READ_THREAD_CONTEXT m_ReadContext; + CGenericHIDDlg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(CGenericHIDDlg) + enum { IDD = IDD_GENERICHID_DIALOG }; + int m_nOutputPattern; + CString m_strInputDisplay; + int m_nReadLength; + int m_nWriteLength; + //}}AFX_DATA + + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CGenericHIDDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + HICON m_hIcon; + + // Generated message map functions + //{{AFX_MSG(CGenericHIDDlg) + virtual BOOL OnInitDialog(); + virtual void OnOK(); + virtual void OnCancel(); + afx_msg void OnSysCommand(UINT nID, LPARAM lParam); + afx_msg void OnPaint(); + afx_msg HCURSOR OnQueryDragIcon(); + afx_msg void OnInput(); + afx_msg void OnOutput(); + afx_msg LRESULT OnDisplayReadData(WPARAM wParam, LPARAM lParam); + afx_msg void OnClose(); + afx_msg BOOL OnDeviceChange(WPARAM wParam, LPARAM lParam); + afx_msg void OnUnregisterHandle(WPARAM wParam, LPARAM lParam); + afx_msg void OnDeviceRemoveDone(WPARAM wParam, LPARAM lParam); + afx_msg void OnDeviceFindDone(WPARAM wParam, LPARAM lParam); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_GENERICHIDDLG_H__18368FF8_0F01_40AC_89DC_C59E95EC3124__INCLUDED_) diff --git a/windows_driver_code/HidClient.cpp b/windows_driver_code/HidClient.cpp new file mode 100644 index 0000000..75185cd --- /dev/null +++ b/windows_driver_code/HidClient.cpp @@ -0,0 +1,413 @@ +#include "stdafx.h" +#include "hid.h" +#include "HidClient.h" + +BOOL WriteHID(PHID_DEVICE HidDevice, PCHAR pucBuffer, int nWriteLength, int *nActualLength) +{ + DWORD bytesWritten; + DWORD dwBufCount = 0; + + *nActualLength = 0; + while(*nActualLength < nWriteLength) { + for(WORD wCount=1; wCount<HidDevice->Caps.OutputReportByteLength; wCount++) { + if(dwBufCount < (DWORD)nWriteLength) { + HidDevice->OutputReportBuffer[wCount] = pucBuffer[dwBufCount++]; + } else { + HidDevice->OutputReportBuffer[wCount] = 0; + } + } + + HidDevice->OutputReportBuffer[0] = 0; + if (!WriteFile (HidDevice->HidDevice, + HidDevice->OutputReportBuffer, + HidDevice->Caps.OutputReportByteLength, + &bytesWritten, + NULL) && (bytesWritten == HidDevice -> Caps.OutputReportByteLength)) + { + return FALSE; + } + + (*nActualLength) += (HidDevice->Caps.OutputReportByteLength - 1); + } + + return TRUE; +} + + +/*++ +RoutineDescription: + Given a struct _HID_DEVICE, obtain a read report +--*/ +BOOL ReadHID(PHID_DEVICE HidDevice, PUCHAR pucBuffer, int nReadLength, int *nActualLength) +{ + DWORD bytesRead; + + *nActualLength = 0; + while(*nActualLength < nReadLength) { + if (!ReadFile (HidDevice->HidDevice, + HidDevice->InputReportBuffer, + HidDevice->Caps.InputReportByteLength, + &bytesRead, + NULL)) + { + return FALSE; + } + for(WORD wCount=1; wCount<HidDevice->Caps.InputReportByteLength; wCount++) { + int nBufCount = *nActualLength + wCount - 1; + if(nBufCount >= nReadLength) break; + pucBuffer[nBufCount] = (UCHAR)HidDevice->InputReportBuffer[wCount]; + } + (*nActualLength) += (HidDevice->Caps.InputReportByteLength - 1); + TRACE("Read Length=%x\n", *nActualLength); + } + + return TRUE; +} + +DWORD WINAPI AsynchReadThreadProc(PREAD_THREAD_CONTEXT Context) +{ + HANDLE completionEvent; + BOOL readStatus; + DWORD waitStatus; + + // + // Create the completion event to send to the the OverlappedRead routine + // + + completionEvent = CreateEvent(NULL, FALSE, FALSE, NULL); + + // + // If NULL returned, then we cannot proceed any farther so we just exit the + // the thread + // + + if (NULL == completionEvent) + { + goto AsyncRead_End; + } + + // + // Now we enter the main read loop, which does the following: + // 1) Calls ReadOverlapped() + // 2) Waits for read completion with a timeout just to check if + // the main thread wants us to terminate our the read request + // 3) If the read fails, we simply break out of the loop + // and exit the thread + // 4) If the read succeeds, we call UnpackReport to get the relevant + // info and then post a message to main thread to indicate that + // there is new data to display. + // 5) We then block on the display event until the main thread says + // it has properly displayed the new data + // 6) Look to repeat this loop if we are doing more than one read + // and the main thread has yet to want us to terminate + // + + do + { + // + // Call ReadOverlapped() and if the return status is TRUE, the ReadFile + // succeeded so we need to block on completionEvent, otherwise, we just + // exit + // + + readStatus = ReadOverlapped( Context -> HidDevice, completionEvent ); + + + if (!readStatus) + { + break; + } + + while (!Context -> TerminateThread) + { + // + // Wait for the completion event to be signaled or a timeout + // + + waitStatus = WaitForSingleObject (completionEvent, READ_THREAD_TIMEOUT ); + + // + // If completionEvent was signaled, then a read just completed + // so let's leave this loop and process the data + // + + if ( WAIT_OBJECT_0 == waitStatus) + { + break; + } + } + + // + // Check the TerminateThread again...If it is not set, then data has + // been read. In this case, we want to Unpack the report into our + // input info and then send a message to the main thread to display + // the new data. + // + + if (!Context -> TerminateThread) + { +/* UnpackReport(Context -> HidDevice -> InputReportBuffer, + Context -> HidDevice -> Caps.InputReportByteLength, + HidP_Input, + Context -> HidDevice -> InputData, + Context -> HidDevice -> InputDataLength, + Context -> HidDevice -> Ppd);*/ + + if (NULL != Context -> DisplayEvent) + { + PostMessage(Context -> DisplayWindow, + WM_DISPLAY_READ_DATA, + 0, + (LPARAM) Context -> HidDevice); + + WaitForSingleObject( Context -> DisplayEvent, INFINITE ); + } + } + } while ( !Context -> TerminateThread && !Context -> DoOneRead ); + + +AsyncRead_End: + + PostMessage( Context -> DisplayWindow, WM_READ_DONE, 0, 0); + ExitThread(0); + return (0); +} + +/*++ +RoutineDescription: + Given a struct _HID_DEVICE, obtain a read report and unpack the values + into the InputData array. +--*/ +BOOLEAN ReadOverlapped(PHID_DEVICE HidDevice, HANDLE CompletionEvent) +{ + static OVERLAPPED overlap; + DWORD bytesRead; + BOOL readStatus; + + /* + // Setup the overlap structure using the completion event passed in to + // to use for signalling the completion of the Read + */ + + memset(&overlap, 0, sizeof(OVERLAPPED)); + + overlap.hEvent = CompletionEvent; + + /* + // Execute the read call saving the return code to determine how to + // proceed (ie. the read completed synchronously or not). + */ + + readStatus = ReadFile ( HidDevice -> HidDevice, + HidDevice -> InputReportBuffer, + HidDevice -> Caps.InputReportByteLength, + &bytesRead, + &overlap); + + /* + // If the readStatus is FALSE, then one of two cases occurred. + // 1) ReadFile call succeeded but the Read is an overlapped one. Here, + // we should return TRUE to indicate that the Read succeeded. However, + // the calling thread should be blocked on the completion event + // which means it won't continue until the read actually completes + // + // 2) The ReadFile call failed for some unknown reason...In this case, + // the return code will be FALSE + */ + + if (!readStatus) + { + return (ERROR_IO_PENDING == GetLastError()); + } + + /* + // If readStatus is TRUE, then the ReadFile call completed synchronously, + // since the calling thread is probably going to wait on the completion + // event, signal the event so it knows it can continue. + */ + + else + { + SetEvent(CompletionEvent); + return (TRUE); + } +} + +BOOLEAN +PackReport ( + OUT PCHAR ReportBuffer, + IN USHORT ReportBufferLength, + IN HIDP_REPORT_TYPE ReportType, + IN PHID_DATA Data, + IN ULONG DataLength, + IN PHIDP_PREPARSED_DATA Ppd + ) +/*++ +Routine Description: + This routine takes in a list of HID_DATA structures (DATA) and builds + in ReportBuffer the given report for all data values in the list that + correspond to the report ID of the first item in the list. + + For every data structure in the list that has the same report ID as the first + item in the list will be set in the report. Every data item that is + set will also have it's IsDataSet field marked with TRUE. + + A return value of FALSE indicates an unexpected error occurred when setting + a given data value. The caller should expect that assume that no values + within the given data structure were set. + + A return value of TRUE indicates that all data values for the given report + ID were set without error. +--*/ +{ + ULONG numUsages; // Number of usages to set for a given report. + ULONG i; + ULONG CurrReportID; + + /* + // All report buffers that are initially sent need to be zero'd out + */ + + memset (ReportBuffer, (UCHAR) 0, ReportBufferLength); + + /* + // Go through the data structures and set all the values that correspond to + // the CurrReportID which is obtained from the first data structure + // in the list + */ + + CurrReportID = Data -> ReportID; + + for (i = 0; i < DataLength; i++, Data++) + { + /* + // There are two different ways to determine if we set the current data + // structure: + // 1) Store the report ID were using and only attempt to set those + // data structures that correspond to the given report ID. This + // example shows this implementation. + // + // 2) Attempt to set all of the data structures and look for the + // returned status value of HIDP_STATUS_INVALID_REPORT_ID. This + // error code indicates that the given usage exists but has a + // different report ID than the report ID in the current report + // buffer + */ + + if (Data -> ReportID == CurrReportID) + { + if (Data->IsButtonData) + { + numUsages = Data->ButtonData.MaxUsageLength; + Data->Status = HidP_SetUsages (ReportType, + Data->UsagePage, + 0, // All collections + Data->ButtonData.Usages, + &numUsages, + Ppd, + ReportBuffer, + ReportBufferLength); + } + else + { + Data->Status = HidP_SetUsageValue (ReportType, + Data->UsagePage, + 0, // All Collections. + Data->ValueData.Usage, + Data->ValueData.Value, + Ppd, + ReportBuffer, + ReportBufferLength); + } + + if (HIDP_STATUS_SUCCESS != Data->Status) + { + return FALSE; + } + } + } + + /* + // At this point, all data structures that have the same ReportID as the + // first one will have been set in the given report. Time to loop + // through the structure again and mark all of those data structures as + // having been set. + */ + + for (i = 0; i < DataLength; i++, Data++) + { + if (CurrReportID == Data -> ReportID) + { + Data -> IsDataSet = TRUE; + } + } + return (TRUE); +} + + + +BOOLEAN Write(PHID_DEVICE HidDevice) +{ + DWORD bytesWritten; + PHID_DATA pData; + ULONG Index; + BOOLEAN Status; + BOOLEAN WriteStatus; + + /* + // Begin by looping through the HID_DEVICE's HID_DATA structure and setting + // the IsDataSet field to FALSE to indicate that each structure has + // not yet been set for this Write call. + */ + + pData = HidDevice -> OutputData; + + for (Index = 0; Index < HidDevice -> OutputDataLength; Index++, pData++) + { + pData -> IsDataSet = FALSE; + } + + /* + // In setting all the data in the reports, we need to pack a report buffer + // and call WriteFile for each report ID that is represented by the + // device structure. To do so, the IsDataSet field will be used to + // determine if a given report field has already been set. + */ + + Status = TRUE; + + pData = HidDevice -> OutputData; + for (Index = 0; Index < HidDevice -> OutputDataLength; Index++, pData++) + { + + if (!pData -> IsDataSet) + { + /* + // Package the report for this data structure. PackReport will + // set the IsDataSet fields of this structure and any other + // structures that it includes in the report with this structure + */ + + PackReport (HidDevice->OutputReportBuffer, + HidDevice->Caps.OutputReportByteLength, + HidP_Output, + pData, + HidDevice->OutputDataLength - Index, + HidDevice->Ppd); + + /* + // Now a report has been packaged up...Send it down to the device + */ + + WriteStatus = WriteFile (HidDevice->HidDevice, + HidDevice->OutputReportBuffer, + HidDevice->Caps.OutputReportByteLength, + &bytesWritten, + NULL) && (bytesWritten == HidDevice -> Caps.OutputReportByteLength); + + Status = Status && WriteStatus; + } + } + return (Status); +} + diff --git a/windows_driver_code/HidClient.h b/windows_driver_code/HidClient.h new file mode 100644 index 0000000..2be52ac --- /dev/null +++ b/windows_driver_code/HidClient.h @@ -0,0 +1,43 @@ +#ifndef HID_CLIENT_H +#define HID_CLIENT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "hid.h" + + +#define WM_UNREGISTER_HANDLE WM_USER+1 +#define WM_DISPLAY_READ_DATA WM_USER+2 +#define WM_READ_DONE WM_USER+3 +#define WM_DEVICE_REMOVE_DONE WM_USER+4 +#define WM_DEVICE_FIND_DONE WM_USER+5 + +#define READ_THREAD_TIMEOUT 1000 + +#define HCLIENT_ERROR "HClient Error" + +typedef struct _READ_THREAD_CONTEXT +{ + PHID_DEVICE HidDevice; + + HWND DisplayWindow; + HANDLE DisplayEvent; + + BOOL DoOneRead; + BOOL TerminateThread; + +} READ_THREAD_CONTEXT, *PREAD_THREAD_CONTEXT; + +DWORD WINAPI AsynchReadThreadProc(PREAD_THREAD_CONTEXT Context); +BOOLEAN ReadOverlapped(PHID_DEVICE HidDevice, HANDLE CompletionEvent); +BOOLEAN Write(PHID_DEVICE HidDevice); +BOOL ReadHID(PHID_DEVICE HidDevice, PUCHAR pucBuffer, int nReadLength, int *nActualLength); +BOOL WriteHID(PHID_DEVICE HidDevice, PCHAR pucBuffer, int nWriteLength, int *nActualLength); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/windows_driver_code/Resource.h b/windows_driver_code/Resource.h new file mode 100644 index 0000000..1c3f02b --- /dev/null +++ b/windows_driver_code/Resource.h @@ -0,0 +1,29 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by GenericHID.rc +// +#define IDM_ABOUTBOX 0x0010 +#define IDD_ABOUTBOX 100 +#define IDS_ABOUTBOX 101 +#define IDD_GENERICHID_DIALOG 102 +#define IDR_MAINFRAME 128 +#define IDC_OUTPUTPATTERN1 1000 +#define IDC_OUTPUTPATTERN2 1001 +#define IDC_OUTPUTPATTERN3 1002 +#define IDC_OUTPUT 1003 +#define IDC_INPUTDISPLAY 1004 +#define IDC_INPUT 1005 +#define IDC_OUTPUTPATTERN4 1006 +#define IDC_LENGTH 1007 +#define IDC_OUTLENGTH 1008 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 129 +#define _APS_NEXT_COMMAND_VALUE 32771 +#define _APS_NEXT_CONTROL_VALUE 1008 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows_driver_code/StdAfx.cpp b/windows_driver_code/StdAfx.cpp new file mode 100644 index 0000000..88809ba --- /dev/null +++ b/windows_driver_code/StdAfx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// GenericHID.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + + + diff --git a/windows_driver_code/StdAfx.h b/windows_driver_code/StdAfx.h new file mode 100644 index 0000000..3705a84 --- /dev/null +++ b/windows_driver_code/StdAfx.h @@ -0,0 +1,27 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#if !defined(AFX_STDAFX_H__09BC44FF_7B6A_4671_8E96_F09BD5EE3362__INCLUDED_) +#define AFX_STDAFX_H__09BC44FF_7B6A_4671_8E96_F09BD5EE3362__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers + +#include <afxwin.h> // MFC core and standard components +#include <afxext.h> // MFC extensions +#include <afxdisp.h> // MFC Automation classes +#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include <afxcmn.h> // MFC support for Windows Common Controls +#endif // _AFX_NO_AFXCMN_SUPPORT + + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_STDAFX_H__09BC44FF_7B6A_4671_8E96_F09BD5EE3362__INCLUDED_) diff --git a/windows_driver_code/USBHID.cpp b/windows_driver_code/USBHID.cpp new file mode 100644 index 0000000..9cb7651 --- /dev/null +++ b/windows_driver_code/USBHID.cpp @@ -0,0 +1,140 @@ +// USBHID.cpp: implementation of the USBHID class. +// +////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#include "GenericHID.h" +#include "USBHID.h" +#include "Hid.h" +#include "HidClient.h" + +#ifdef _DEBUG +#undef THIS_FILE +static char THIS_FILE[]=__FILE__; +#define new DEBUG_NEW +#endif + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// + +USBHID::USBHID() +{ + m_HidDevice.bFound = m_HidCBWDevice.bFound = FALSE; + m_HidDevice.hDeviceNotificationHandle = m_HidCBWDevice.hDeviceNotificationHandle = NULL; +} + +USBHID::~USBHID() +{ + CloseDevice(); +} + +BOOL USBHID::FindDevice(HWND hWnd) +{ + return FindGenericHIDDevice(&m_HidDevice, &m_HidCBWDevice, hWnd); +} + +void USBHID::CloseDevice() +{ + if(m_HidDevice.bFound) { + CloseHidDevice (&m_HidDevice, TRUE); + } + + if(m_HidCBWDevice.bFound) { + CloseHidDevice (&m_HidCBWDevice, TRUE); + } +} + +BOOL USBHID::CloseDeviceByHandle(HANDLE hDevice, HWND hWnd) +{ + if(m_HidDevice.HidDevice == hDevice) + { + PostMessage(hWnd, WM_UNREGISTER_HANDLE, 0, (LPARAM) m_HidDevice.hDeviceNotificationHandle); + CloseHidDevice(&m_HidDevice, TRUE); + } else if(m_HidCBWDevice.HidDevice == hDevice) { + PostMessage(hWnd, WM_UNREGISTER_HANDLE, 0, (LPARAM) m_HidCBWDevice.hDeviceNotificationHandle); + CloseHidDevice(&m_HidCBWDevice, TRUE); + } + + + if(!m_HidDevice.bFound && !m_HidCBWDevice.bFound) { + PostMessage(hWnd, WM_DEVICE_REMOVE_DONE, 0, 0); + return TRUE; + } else { + return FALSE; + } +} + +BOOL USBHID::FindDeviceByPath(PCHAR szDevicePath, HWND hWnd) +{ + BOOL bFoundDevice = FALSE; + if(!m_HidDevice.bFound) { + if (OpenHidDevice (szDevicePath, + TRUE, + TRUE, + FALSE, + FALSE, + TRUE, + &m_HidDevice, + hWnd, + 1, 0)) { // Find the device + bFoundDevice = TRUE; + } + } + if(!bFoundDevice && !m_HidCBWDevice.bFound) { + if (OpenHidDevice (szDevicePath, + TRUE, + TRUE, + FALSE, + FALSE, + TRUE, + &m_HidCBWDevice, + hWnd, + 1, 3)) { // Find the CBW device + bFoundDevice = TRUE; + } + } + + if(bFoundDevice) { + if(m_HidDevice.bFound && m_HidCBWDevice.bFound) return TRUE; + else return FALSE; + } else { + return FALSE; + } +} + +BOOL USBHID::ReadBuffer(PUCHAR pucBuffer, int nReadLength, int *nActualLength) +{ + char cCBWBuf[8] = {0x55, 0x53, 0x42, 0x43, 0x00, 0x00, 0x01, 0x00}; + int nReturnedLength; + + if(nReadLength >= 0xffff) return FALSE; + + cCBWBuf[0x04] = (nReadLength & 0xff00) >> 8; + cCBWBuf[0x05] = nReadLength & 0xff; + + // Write CBW first + if(WriteHID(&m_HidCBWDevice, cCBWBuf, 8, &nReturnedLength)) { + return ReadHID(&m_HidDevice, pucBuffer, nReadLength, nActualLength); + } else { + return FALSE; + } +} + +BOOL USBHID::WriteBuffer(PCHAR pcBuffer, int nWriteLength, int *nActualLength) +{ + char cCBWBuf[8] = {0x55, 0x53, 0x42, 0x43, 0x00, 0x00, 0x02, 0x00}; + int nReturnedLength; + + if(nWriteLength >= 0xffff) return FALSE; + + cCBWBuf[0x04] = (nWriteLength & 0xff) >> 8; + cCBWBuf[0x05] = nWriteLength & 0xff; + + // Write CBW first + if(WriteHID(&m_HidCBWDevice, cCBWBuf, 8, &nReturnedLength)) { + return WriteHID(&m_HidDevice, pcBuffer, nWriteLength, nActualLength); + } else { + return FALSE; + } +} diff --git a/windows_driver_code/USBHID.h b/windows_driver_code/USBHID.h new file mode 100644 index 0000000..e372433 --- /dev/null +++ b/windows_driver_code/USBHID.h @@ -0,0 +1,30 @@ +// USBHID.h: interface for the USBHID class. +// +////////////////////////////////////////////////////////////////////// + +#if !defined(AFX_USBHID_H__1FBB32BD_44D4_48F6_84B4_0CE69A02A578__INCLUDED_) +#define AFX_USBHID_H__1FBB32BD_44D4_48F6_84B4_0CE69A02A578__INCLUDED_ + +#include "hid.h" // Added by ClassView +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + + +class USBHID +{ +public: + BOOL ReadBuffer(PUCHAR pucBuffer, int nReadLength, int *nActualLength); + BOOL FindDeviceByPath(PCHAR szDevicePath, HWND hWnd); + BOOL CloseDeviceByHandle(HANDLE hDevice, HWND hWnd); + void CloseDevice(); + HID_DEVICE m_HidDevice; + HID_DEVICE m_HidCBWDevice; + BOOL FindDevice(HWND hWnd); + BOOL WriteBuffer(PCHAR pcBuffer, int nWriteLength, int *nActualLength); + USBHID(); + virtual ~USBHID(); + +}; + +#endif // !defined(AFX_USBHID_H__1FBB32BD_44D4_48F6_84B4_0CE69A02A578__INCLUDED_) diff --git a/windows_driver_code/hid.h b/windows_driver_code/hid.h new file mode 100644 index 0000000..1dfbe13 --- /dev/null +++ b/windows_driver_code/hid.h @@ -0,0 +1,192 @@ +/*++ + +Copyright (c) Microsoft 1998, All Rights Reserved + +Module Name: + + hid.h + +Abstract: + + This module contains the declarations and definitions for use with the + hid user mode client sample driver. + +Environment: + + Kernel & user mode + +--*/ + +#ifndef HID_H +#define HID_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "hidsdi.h" +#include "setupapi.h" + +typedef struct _SP_FNCLASS_DEVICE_DATA { + DWORD cbSize; + GUID FunctionClassGuid; + TCHAR DevicePath [ANYSIZE_ARRAY]; +} SP_FNCLASS_DEVICE_DATA, *PSP_FNCLASS_DEVICE_DATA; + +BOOLEAN +SetupDiGetFunctionClassDeviceInfo ( + IN HDEVINFO DeviceInfoSet, + IN PSP_DEVINFO_DATA DeviceInfoData, + OUT PSP_FNCLASS_DEVICE_DATA FunctionClassDeviceData, + IN DWORD FunctionClassDeviceDataSize, + OUT PDWORD RequiredSize + ); + + +// +// A structure to hold the steady state data received from the hid device. +// Each time a read packet is received we fill in this structure. +// Each time we wish to write to a hid device we fill in this structure. +// This structure is here only for convenience. Most real applications will +// have a more efficient way of moving the hid data to the read, write, and +// feature routines. +// +typedef struct _HID_DATA { + BOOLEAN IsButtonData; + UCHAR Reserved; + USAGE UsagePage; // The usage page for which we are looking. + ULONG Status; // The last status returned from the accessor function + // when updating this field. + ULONG ReportID; // ReportID for this given data structure + BOOLEAN IsDataSet; // Variable to track whether a given data structure + // has already been added to a report structure + + union { + struct { + ULONG UsageMin; // Variables to track the usage minimum and max + ULONG UsageMax; // If equal, then only a single usage + ULONG MaxUsageLength; // Usages buffer length. + PUSAGE Usages; // list of usages (buttons ``down'' on the device. + + } ButtonData; + struct { + USAGE Usage; // The usage describing this value; + USHORT Reserved; + + ULONG Value; + LONG ScaledValue; + } ValueData; + }; +} HID_DATA, *PHID_DATA; + +typedef struct _HID_DEVICE { + PCHAR DevicePath; + HANDLE HidDevice; // A file handle to the hid device. + BOOL OpenedForRead; + BOOL OpenedForWrite; + BOOL OpenedOverlapped; + BOOL OpenedExclusive; + + PHIDP_PREPARSED_DATA Ppd; // The opaque parser info describing this device + HIDP_CAPS Caps; // The Capabilities of this hid device. + HIDD_ATTRIBUTES Attributes; + + PCHAR InputReportBuffer; + PHID_DATA InputData; // array of hid data structures + ULONG InputDataLength; // Num elements in this array. + PHIDP_BUTTON_CAPS InputButtonCaps; + PHIDP_VALUE_CAPS InputValueCaps; + + PCHAR OutputReportBuffer; + PHID_DATA OutputData; + ULONG OutputDataLength; + PHIDP_BUTTON_CAPS OutputButtonCaps; + PHIDP_VALUE_CAPS OutputValueCaps; + + PCHAR FeatureReportBuffer; + PHID_DATA FeatureData; + ULONG FeatureDataLength; + PHIDP_BUTTON_CAPS FeatureButtonCaps; + PHIDP_VALUE_CAPS FeatureValueCaps; + HANDLE hDeviceNotificationHandle; + BOOL bFound; +} HID_DEVICE, *PHID_DEVICE; + + +BOOLEAN +OpenHidDevice ( + IN PCHAR DevicePath, + IN BOOL HasReadAccess, + IN BOOL HasWriteAccess, + IN BOOL IsOverlapped, + IN BOOL IsExclusive, + IN BOOL GetDeviceInfo, + IN OUT PHID_DEVICE HidDevice, + IN HWND hWnd, + IN USHORT usUsagePage, + IN USHORT usUsageID +); + +BOOLEAN FindGenericHIDDevice(PHID_DEVICE HidDevice, PHID_DEVICE HidCBWDevice, HWND hWnd) ; + + +VOID +FillDeviceInfo( + IN PHID_DEVICE HidDevice +); + +VOID +CloseHidDevices ( + OUT PHID_DEVICE HidDevices, // A array of struct _HID_DEVICE + OUT ULONG NumberDevices // the length of this array. + ); + +VOID +CloseHidDevice ( + IN PHID_DEVICE HidDevice, + IN BOOL FreeDeviceInfo + ); + + +BOOLEAN +Read ( + PHID_DEVICE HidDevice + ); + +BOOLEAN +ReadOverlapped ( + PHID_DEVICE HidDevice, + HANDLE CompletionEvent + ); + +BOOLEAN +Write ( + PHID_DEVICE HidDevice + ); + +BOOLEAN +UnpackReport ( + IN PCHAR ReportBuffer, + IN USHORT ReportBufferLength, + IN HIDP_REPORT_TYPE ReportType, + IN OUT PHID_DATA Data, + IN ULONG DataLength, + IN PHIDP_PREPARSED_DATA Ppd + ); + +BOOLEAN +SetFeature ( + PHID_DEVICE HidDevice + ); + +BOOLEAN +GetFeature ( + PHID_DEVICE HidDevice + ); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/windows_driver_code/pnp.cpp b/windows_driver_code/pnp.cpp new file mode 100644 index 0000000..c14d74d --- /dev/null +++ b/windows_driver_code/pnp.cpp @@ -0,0 +1,762 @@ +/*++ + +Copyright (c) 1996 Microsoft Corporation + +Module Name: + + pnp.c + +Abstract: + + This module contains the code + for finding, adding, removing, and identifying hid devices. + +Environment: + + User mode + +--*/ + +#include "stdafx.h" +#include <dbt.h> +#include "hid.h" +#include <basetyps.h> +#include <stdlib.h> +#include <wtypes.h> +#include <setupapi.h> + +#define TENX_VID 0x1130 +#define TENX_PID 0x0202 + +/*++ +Routine Description: + Do the required PnP things in order to find the 1603 HID device in + the system at this time. +--*/ + +BOOLEAN FindGenericHIDDevice(PHID_DEVICE HidDevice, PHID_DEVICE HidCBWDevice, HWND hWnd) +{ + HDEVINFO hardwareDeviceInfo; + SP_INTERFACE_DEVICE_DATA deviceInfoData; + ULONG i; + GUID hidGuid; + PSP_INTERFACE_DEVICE_DETAIL_DATA functionClassDeviceData = NULL; + ULONG predictedLength = 0; + ULONG requiredLength = 0; + BOOL bFindDevice, bFindCBWDevice, bFind; + + bFindDevice = bFindCBWDevice = FALSE; + + + HidD_GetHidGuid (&hidGuid); + + // + // Open a handle to the plug and play dev node. + // + hardwareDeviceInfo = SetupDiGetClassDevs ( &hidGuid, + NULL, // Define no enumerator (global) + NULL, // Define no + (DIGCF_PRESENT | // Only Devices present + DIGCF_DEVICEINTERFACE)); // Function class devices. + + + deviceInfoData.cbSize = sizeof (SP_INTERFACE_DEVICE_DATA); + + + for (i=0; SetupDiEnumDeviceInterfaces(hardwareDeviceInfo, 0, &hidGuid, i, &deviceInfoData); i++) { + bFind = FALSE; + + // + // allocate a function class device data structure to receive the + // goods about this particular device. + // + + SetupDiGetDeviceInterfaceDetail ( + hardwareDeviceInfo, + &deviceInfoData, + NULL, // probing so no output buffer yet + 0, // probing so output buffer length of zero + &requiredLength, + NULL); // not interested in the specific dev-node + + + predictedLength = requiredLength; + + functionClassDeviceData = (PSP_INTERFACE_DEVICE_DETAIL_DATA) malloc (predictedLength); + if (functionClassDeviceData) + { + functionClassDeviceData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA); + } + else + { + SetupDiDestroyDeviceInfoList (hardwareDeviceInfo); + return FALSE; + } + + // + // Retrieve the information from Plug and Play. + // + + if (! SetupDiGetDeviceInterfaceDetail ( + hardwareDeviceInfo, + &deviceInfoData, + functionClassDeviceData, + predictedLength, + &requiredLength, + NULL)) + { + SetupDiDestroyDeviceInfoList (hardwareDeviceInfo); + return FALSE; + } + + // + // Open device with just generic query abilities to begin with + // + + if(!bFindDevice) { + bFind = bFindDevice = OpenHidDevice (functionClassDeviceData -> DevicePath, + TRUE, // ReadAccess - none + TRUE, // WriteAccess - none + FALSE, // Overlapped - no + FALSE, // Exclusive - no + TRUE, // GetDeviceInfo - yes + HidDevice, + hWnd, + 1, 0); + } + + if(!bFindCBWDevice && !bFind) { + bFindCBWDevice = OpenHidDevice (functionClassDeviceData -> DevicePath, + TRUE, // ReadAccess - none + TRUE, // WriteAccess - none + FALSE, // Overlapped - no + FALSE, // Exclusive - no + TRUE, // GetDeviceInfo - yes + HidCBWDevice, + hWnd, + 1, 3); + } + + if(bFindDevice && bFindCBWDevice) break; + } + + SetupDiDestroyDeviceInfoList (hardwareDeviceInfo); + return (bFindDevice && bFindCBWDevice); +} + + +/*++ +RoutineDescription: + Given the HardwareDeviceInfo, representing a handle to the plug and + play information, and deviceInfoData, representing a specific hid device, + open that device and fill in all the relivant information in the given + HID_DEVICE structure. + + return if the open and initialization was successfull or not. + +--*/ +BOOLEAN +OpenHidDevice ( + IN PCHAR DevicePath, + IN BOOL HasReadAccess, + IN BOOL HasWriteAccess, + IN BOOL IsOverlapped, + IN BOOL IsExclusive, + IN BOOL GetDeviceInfo, + IN OUT PHID_DEVICE HidDevice, + IN HWND hWnd, + IN USHORT usUsagePage, + IN USHORT usUsageID +) +{ + DWORD accessFlags = 0; + DWORD sharingFlags = 0; + + DWORD dwLen = strlen(DevicePath); + HidDevice -> DevicePath = (PCHAR)malloc(dwLen + 1); + + if (NULL == HidDevice -> DevicePath) + { + return (FALSE); + } + + strcpy(HidDevice -> DevicePath, DevicePath); + HidDevice -> DevicePath[dwLen] = '\0'; + + if (HasReadAccess) + { + accessFlags |= GENERIC_READ; + } + + if (HasWriteAccess) + { + accessFlags |= GENERIC_WRITE; + } + + if (!IsExclusive) + { + sharingFlags = FILE_SHARE_READ | FILE_SHARE_WRITE; + } + + HidDevice->HidDevice = CreateFile (DevicePath, + accessFlags, + sharingFlags, + NULL, // no SECURITY_ATTRIBUTES structure + OPEN_EXISTING, // No special create flags + IsOverlapped ? FILE_FLAG_OVERLAPPED : 0, + NULL); // No template file + + if (INVALID_HANDLE_VALUE == HidDevice->HidDevice) + { + free(HidDevice -> DevicePath); + return FALSE; + } + + HidDevice -> OpenedForRead = HasReadAccess; + HidDevice -> OpenedForWrite = HasWriteAccess; + HidDevice -> OpenedOverlapped = IsOverlapped; + HidDevice -> OpenedExclusive = IsExclusive; + + // + // If the device was not opened as overlapped, then fill in the rest of the + // HidDevice structure. However, if opened as overlapped, this handle cannot + // be used in the calls to the HidD_ exported functions since each of these + // functions does synchronous I/O. + // + + if (!HidD_GetAttributes (HidDevice->HidDevice, &HidDevice->Attributes)) + { + free(HidDevice -> DevicePath); + CloseHandle(HidDevice -> HidDevice); + return FALSE; + } else { // Check the VID/PID + if( (HidDevice->Attributes.VendorID != TENX_VID) || (HidDevice->Attributes.ProductID != TENX_PID) ) { + free(HidDevice -> DevicePath); + CloseHandle(HidDevice -> HidDevice); + return FALSE; + } + } + + + if (GetDeviceInfo) + { + if (!HidD_GetPreparsedData (HidDevice->HidDevice, &HidDevice->Ppd)) + { + free(HidDevice -> DevicePath); + CloseHandle(HidDevice -> HidDevice); + return FALSE; + } + + if (!HidP_GetCaps (HidDevice->Ppd, &HidDevice->Caps)) + { + free(HidDevice -> DevicePath); + + CloseHandle(HidDevice -> HidDevice); + + HidD_FreePreparsedData (HidDevice->Ppd); + + return FALSE; + } else { // Check the usage page and usage ID. + if((HidDevice->Caps.UsagePage != (USAGE)usUsagePage) || (HidDevice->Caps.Usage != (USAGE)usUsageID)) { + free(HidDevice -> DevicePath); + + CloseHandle(HidDevice -> HidDevice); + + HidD_FreePreparsedData (HidDevice->Ppd); + + return FALSE; + } + } + + + // + // At this point the client has a choice. It may chose to look at the + // Usage and Page of the top level collection found in the HIDP_CAPS + // structure. In this way it could just use the usages it knows about. + // If either HidP_GetUsages or HidP_GetUsageValue return an error then + // that particular usage does not exist in the report. + // This is most likely the preferred method as the application can only + // use usages of which it already knows. + // In this case the app need not even call GetButtonCaps or GetValueCaps. + // + // In this example, however, we will call FillDeviceInfo to look for all + // of the usages in the device. + // + + FillDeviceInfo(HidDevice); + + DEV_BROADCAST_HANDLE broadcastHandle; + + broadcastHandle.dbch_size = sizeof(DEV_BROADCAST_HANDLE); + broadcastHandle.dbch_devicetype = DBT_DEVTYP_HANDLE; + broadcastHandle.dbch_handle = HidDevice->HidDevice; + + HidDevice->hDeviceNotificationHandle = RegisterDeviceNotification( + hWnd, + &broadcastHandle, + DEVICE_NOTIFY_WINDOW_HANDLE); + HidDevice->bFound = TRUE; + } + + return (TRUE); +} + +VOID +FillDeviceInfo( + IN PHID_DEVICE HidDevice +) +{ + USHORT numValues; + USHORT numCaps; + PHIDP_BUTTON_CAPS buttonCaps; + PHIDP_VALUE_CAPS valueCaps; + PHID_DATA data; + ULONG i; + USAGE usage; + + // + // setup Input Data buffers. + // + + // + // Allocate memory to hold on input report + // + + HidDevice->InputReportBuffer = (PCHAR) + calloc (HidDevice->Caps.InputReportByteLength, sizeof (CHAR)); + + + // + // Allocate memory to hold the button and value capabilities. + // NumberXXCaps is in terms of array elements. + // + + HidDevice->InputButtonCaps = buttonCaps = (PHIDP_BUTTON_CAPS) + calloc (HidDevice->Caps.NumberInputButtonCaps, sizeof (HIDP_BUTTON_CAPS)); + + HidDevice->InputValueCaps = valueCaps = (PHIDP_VALUE_CAPS) + calloc (HidDevice->Caps.NumberInputValueCaps, sizeof (HIDP_VALUE_CAPS)); + + // + // Have the HidP_X functions fill in the capability structure arrays. + // + + numCaps = HidDevice->Caps.NumberInputButtonCaps; + + HidP_GetButtonCaps (HidP_Input, + buttonCaps, + &numCaps, + HidDevice->Ppd); + + numCaps = HidDevice->Caps.NumberInputValueCaps; + + HidP_GetValueCaps (HidP_Input, + valueCaps, + &numCaps, + HidDevice->Ppd); + + + // + // Depending on the device, some value caps structures may represent more + // than one value. (A range). In the interest of being verbose, over + // efficient, we will expand these so that we have one and only one + // struct _HID_DATA for each value. + // + // To do this we need to count up the total number of values are listed + // in the value caps structure. For each element in the array we test + // for range if it is a range then UsageMax and UsageMin describe the + // usages for this range INCLUSIVE. + // + + numValues = 0; + for (i = 0; i < HidDevice->Caps.NumberInputValueCaps; i++, valueCaps++) + { + if (valueCaps->IsRange) + { + numValues += valueCaps->Range.UsageMax - valueCaps->Range.UsageMin + 1; + } + else + { + numValues++; + } + } + valueCaps = HidDevice->InputValueCaps; + + + // + // Allocate a buffer to hold the struct _HID_DATA structures. + // One element for each set of buttons, and one element for each value + // found. + // + + HidDevice->InputDataLength = HidDevice->Caps.NumberInputButtonCaps + + numValues; + + HidDevice->InputData = data = (PHID_DATA) + calloc (HidDevice->InputDataLength, sizeof (HID_DATA)); + + // + // Fill in the button data + // + + for (i = 0; + i < HidDevice->Caps.NumberInputButtonCaps; + i++, data++, buttonCaps++) + { + data->IsButtonData = TRUE; + data->Status = HIDP_STATUS_SUCCESS; + data->UsagePage = buttonCaps->UsagePage; + if (buttonCaps->IsRange) + { + data->ButtonData.UsageMin = buttonCaps -> Range.UsageMin; + data->ButtonData.UsageMax = buttonCaps -> Range.UsageMax; + } + else + { + data -> ButtonData.UsageMin = data -> ButtonData.UsageMax = buttonCaps -> NotRange.Usage; + } + + data->ButtonData.MaxUsageLength = HidP_MaxUsageListLength ( + HidP_Input, + buttonCaps->UsagePage, + HidDevice->Ppd); + data->ButtonData.Usages = (PUSAGE) + calloc (data->ButtonData.MaxUsageLength, sizeof (USAGE)); + + data->ReportID = buttonCaps -> ReportID; + } + + // + // Fill in the value data + // + + for (i = 0; i < numValues; i++, valueCaps++) + { + if (valueCaps->IsRange) + { + for (usage = valueCaps->Range.UsageMin; + usage <= valueCaps->Range.UsageMax; + usage++) + { + data->IsButtonData = FALSE; + data->Status = HIDP_STATUS_SUCCESS; + data->UsagePage = valueCaps->UsagePage; + data->ValueData.Usage = usage; + data->ReportID = valueCaps -> ReportID; + data++; + } + } + else + { + data->IsButtonData = FALSE; + data->Status = HIDP_STATUS_SUCCESS; + data->UsagePage = valueCaps->UsagePage; + data->ValueData.Usage = valueCaps->NotRange.Usage; + data->ReportID = valueCaps -> ReportID; + data++; + } + } + + // + // setup Output Data buffers. + // + + HidDevice->OutputReportBuffer = (PCHAR) + calloc (HidDevice->Caps.OutputReportByteLength, sizeof (CHAR)); + + HidDevice->OutputButtonCaps = buttonCaps = (PHIDP_BUTTON_CAPS) + calloc (HidDevice->Caps.NumberOutputButtonCaps, sizeof (HIDP_BUTTON_CAPS)); + + HidDevice->OutputValueCaps = valueCaps = (PHIDP_VALUE_CAPS) + calloc (HidDevice->Caps.NumberOutputValueCaps, sizeof (HIDP_VALUE_CAPS)); + + numCaps = HidDevice->Caps.NumberOutputButtonCaps; + HidP_GetButtonCaps (HidP_Output, + buttonCaps, + &numCaps, + HidDevice->Ppd); + + numCaps = HidDevice->Caps.NumberOutputValueCaps; + HidP_GetValueCaps (HidP_Output, + valueCaps, + &numCaps, + HidDevice->Ppd); + + numValues = 0; + for (i = 0; i < HidDevice->Caps.NumberOutputValueCaps; i++, valueCaps++) + { + if (valueCaps->IsRange) + { + numValues += valueCaps->Range.UsageMax + - valueCaps->Range.UsageMin + 1; + } + else + { + numValues++; + } + } + valueCaps = HidDevice->OutputValueCaps; + + HidDevice->OutputDataLength = HidDevice->Caps.NumberOutputButtonCaps + + numValues; + + HidDevice->OutputData = data = (PHID_DATA) + calloc (HidDevice->OutputDataLength, sizeof (HID_DATA)); + + for (i = 0; + i < HidDevice->Caps.NumberOutputButtonCaps; + i++, data++, buttonCaps++) + { + data->IsButtonData = TRUE; + data->Status = HIDP_STATUS_SUCCESS; + data->UsagePage = buttonCaps->UsagePage; + + if (buttonCaps->IsRange) + { + data->ButtonData.UsageMin = buttonCaps -> Range.UsageMin; + data->ButtonData.UsageMax = buttonCaps -> Range.UsageMax; + } + else + { + data -> ButtonData.UsageMin = data -> ButtonData.UsageMax = buttonCaps -> NotRange.Usage; + } + + data->ButtonData.MaxUsageLength = HidP_MaxUsageListLength ( + HidP_Output, + buttonCaps->UsagePage, + HidDevice->Ppd); + + data->ButtonData.Usages = (PUSAGE) + calloc (data->ButtonData.MaxUsageLength, sizeof (USAGE)); + + data->ReportID = buttonCaps -> ReportID; + } + + for (i = 0; i < numValues; i++, valueCaps++) + { + if (valueCaps->IsRange) + { + for (usage = valueCaps->Range.UsageMin; + usage <= valueCaps->Range.UsageMax; + usage++) + { + data->IsButtonData = FALSE; + data->Status = HIDP_STATUS_SUCCESS; + data->UsagePage = valueCaps->UsagePage; + data->ValueData.Usage = usage; + data->ReportID = valueCaps -> ReportID; + data++; + } + } + else + { + data->IsButtonData = FALSE; + data->Status = HIDP_STATUS_SUCCESS; + data->UsagePage = valueCaps->UsagePage; + data->ValueData.Usage = valueCaps->NotRange.Usage; + data->ReportID = valueCaps -> ReportID; + data++; + } + } + + // + // setup Feature Data buffers. + // + + HidDevice->FeatureReportBuffer = (PCHAR) + calloc (HidDevice->Caps.FeatureReportByteLength, sizeof (CHAR)); + + HidDevice->FeatureButtonCaps = buttonCaps = (PHIDP_BUTTON_CAPS) + calloc (HidDevice->Caps.NumberFeatureButtonCaps, sizeof (HIDP_BUTTON_CAPS)); + + HidDevice->FeatureValueCaps = valueCaps = (PHIDP_VALUE_CAPS) + calloc (HidDevice->Caps.NumberFeatureValueCaps, sizeof (HIDP_VALUE_CAPS)); + + numCaps = HidDevice->Caps.NumberFeatureButtonCaps; + HidP_GetButtonCaps (HidP_Feature, + buttonCaps, + &numCaps, + HidDevice->Ppd); + + numCaps = HidDevice->Caps.NumberFeatureValueCaps; + HidP_GetValueCaps (HidP_Feature, + valueCaps, + &numCaps, + HidDevice->Ppd); + + numValues = 0; + for (i = 0; i < HidDevice->Caps.NumberFeatureValueCaps; i++, valueCaps++) + { + if (valueCaps->IsRange) + { + numValues += valueCaps->Range.UsageMax + - valueCaps->Range.UsageMin + 1; + } + else + { + numValues++; + } + } + valueCaps = HidDevice->FeatureValueCaps; + + HidDevice->FeatureDataLength = HidDevice->Caps.NumberFeatureButtonCaps + + numValues; + + HidDevice->FeatureData = data = (PHID_DATA) + calloc (HidDevice->FeatureDataLength, sizeof (HID_DATA)); + + for (i = 0; + i < HidDevice->Caps.NumberFeatureButtonCaps; + i++, data++, buttonCaps++) + { + data->IsButtonData = TRUE; + data->Status = HIDP_STATUS_SUCCESS; + data->UsagePage = buttonCaps->UsagePage; + + if (buttonCaps->IsRange) + { + data->ButtonData.UsageMin = buttonCaps -> Range.UsageMin; + data->ButtonData.UsageMax = buttonCaps -> Range.UsageMax; + } + else + { + data -> ButtonData.UsageMin = data -> ButtonData.UsageMax = buttonCaps -> NotRange.Usage; + } + + data->ButtonData.MaxUsageLength = HidP_MaxUsageListLength ( + HidP_Feature, + buttonCaps->UsagePage, + HidDevice->Ppd); + data->ButtonData.Usages = (PUSAGE) + calloc (data->ButtonData.MaxUsageLength, sizeof (USAGE)); + + data->ReportID = buttonCaps -> ReportID; + } + + for (i = 0; i < numValues; i++, valueCaps++) + { + if (valueCaps->IsRange) + { + for (usage = valueCaps->Range.UsageMin; + usage <= valueCaps->Range.UsageMax; + usage++) + { + data->IsButtonData = FALSE; + data->Status = HIDP_STATUS_SUCCESS; + data->UsagePage = valueCaps->UsagePage; + data->ValueData.Usage = usage; + data->ReportID = valueCaps -> ReportID; + data++; + } + } + else + { + data->IsButtonData = FALSE; + data->Status = HIDP_STATUS_SUCCESS; + data->UsagePage = valueCaps->UsagePage; + data->ValueData.Usage = valueCaps->NotRange.Usage; + data->ReportID = valueCaps -> ReportID; + data++; + } + } + + return; +} + + +VOID +CloseHidDevice ( + IN PHID_DEVICE HidDevice, + IN BOOL FreeDeviceInfo +) +{ + if(HidDevice->bFound) { + HidDevice->bFound = FALSE; + // if(HidDevice->hDeviceNotificationHandle) { + // UnregisterDeviceNotification(HidDevice->hDeviceNotificationHandle); + // HidDevice->hDeviceNotificationHandle = NULL; + // } + + free(HidDevice -> DevicePath); + + if (INVALID_HANDLE_VALUE != HidDevice -> HidDevice) + { + CloseHandle(HidDevice -> HidDevice); + } + + // + // Only free these structure, if have a handle to an non-overlapped device + // + + if (FreeDeviceInfo) + { + if (NULL != HidDevice -> Ppd) + { + HidD_FreePreparsedData(HidDevice -> Ppd); + } + + if (NULL != HidDevice -> InputReportBuffer) + { + free(HidDevice -> InputReportBuffer); + } + + if (NULL != HidDevice -> InputData) + { + free(HidDevice -> InputData); + } + + if (NULL != HidDevice -> InputButtonCaps) + { + free(HidDevice -> InputButtonCaps); + } + + if (NULL != HidDevice -> InputValueCaps) + { + free(HidDevice -> InputValueCaps); + } + + if (NULL != HidDevice -> OutputReportBuffer) + { + free(HidDevice -> OutputReportBuffer); + } + + if (NULL != HidDevice -> OutputData) + { + free(HidDevice -> OutputData); + } + + if (NULL != HidDevice -> OutputButtonCaps) + { + free(HidDevice -> OutputButtonCaps); + } + + if (NULL != HidDevice -> OutputValueCaps) + { + free(HidDevice -> OutputValueCaps); + } + + if (NULL != HidDevice -> FeatureReportBuffer) + { + free(HidDevice -> FeatureReportBuffer); + } + + if (NULL != HidDevice -> FeatureData) + { + free(HidDevice -> FeatureData); + } + + if (NULL != HidDevice -> FeatureButtonCaps) + { + free(HidDevice -> FeatureButtonCaps); + } + + if (NULL != HidDevice -> FeatureValueCaps) + { + free(HidDevice -> FeatureValueCaps); + } + } + } + return; +} + + diff --git a/windows_driver_code/vssver.scc b/windows_driver_code/vssver.scc new file mode 100644 index 0000000..d1c1286 Binary files /dev/null and b/windows_driver_code/vssver.scc differ
tristil/agile-lamp
927bfecfd9de3bf731ae50fa19c116b0ed4ae4d5
Improved the README.txt file
diff --git a/agilelamp-driver/README.txt b/agilelamp-driver/README.txt index e87d87e..e86ab55 100644 --- a/agilelamp-driver/README.txt +++ b/agilelamp-driver/README.txt @@ -1,48 +1,43 @@ = agilelamp-driver -* FIX (url) +* http://rubyforge.org/projects/agilelamp == DESCRIPTION: - -FIX (describe your package) + This is a userspace driver for controlling the Agile Lamp USB lava lamp. + Should work on any system that has libusb installed. == FEATURES/PROBLEMS: -* FIX (list of features or problems) - -== SYNOPSIS: - - FIX (code sample of usage) - -== REQUIREMENTS: - -* FIX (list of requirements) +* `agilelamp-driver red`, `green`, `bell`, `various` == INSTALL: -* FIX (sudo gem install, anything else) +* sudo gem install agilelamp-driver +* Pay attention to output message to see if agilelamp-driver is made and copied + to bin or the precompiled executable is installed. You will need to install + libusb headers if you want a compiled binary for your architecture. == LICENSE: (The MIT License) Copyright (c) 2008 FIX Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/agilelamp-driver/bin/agilelamp-driver b/agilelamp-driver/bin/agilelamp-driver index 23c907d..8da79a1 100755 Binary files a/agilelamp-driver/bin/agilelamp-driver and b/agilelamp-driver/bin/agilelamp-driver differ diff --git a/agilelamp-driver/src/agilelamp.c b/agilelamp-driver/src/agilelamp.c index c32112e..af52564 100644 --- a/agilelamp-driver/src/agilelamp.c +++ b/agilelamp-driver/src/agilelamp.c @@ -1,175 +1,175 @@ #include <usb.h> #include <stdio.h> #include <unistd.h> #include <string.h> usb_dev_handle* launcher; //wrapper for control_msg int send_message(char* msg, int index) { int i = 0; int j = usb_control_msg(launcher, 0x21, 0x9, 0x0, index, msg, 8, 1000); return j; } void send_cbw(){ fprintf(stderr, "Sending CBW message\n"); char cbw_message[8] = {0x55, 0x53, 0x42, 0x43, 0, 16, 2, 0}; int ret = send_message(cbw_message, 1); fprintf(stderr, "%d bytes sent\n", ret); } void send_lamp_command(char* title, char* message1, char* message2){ usb_reset(launcher); send_cbw(); fprintf(stderr, "Submitting %s\n", title); int ret = send_message(message1, 0); fprintf(stderr, "%d bytes sent\n", ret); ret = send_message(message2, 0); fprintf(stderr, "%d bytes sent\n", ret); } void set_red_with_bell(){ char message_part_1[8] = {0x0, 0x1, 0x4, 0x9,0x10, 0x19, 0x24, 0x31}; //red with bell char message_part_2[8] = {0x40, 0x51, 0x64, 0x79, 0x90, 0xa9, 0xc4, 0xe1}; // red with bell send_lamp_command("red with bell", message_part_1, message_part_2); } /* Fun with bit-math: Everything on the first (from right) 8 bits of first (from right) byte b0:=1:Bell active;=0:Bell off b1:=1:Green led on; =0:Green led off b2:=1:Red led on;=0:red led off b3:=0:7 colors led on;=1:7 colors led off b0 1 1 1 1 1 111 128 64 32 16 8 421 = 255 c c c c c rgb (c's are colors to cycle through, then red, green, bell) 0 0 0 16 0 000 = */ void only_bell_on(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; char message_part_2[8] = {0,0,0,0, 0,0,0,1}; send_lamp_command("green", message_part_1, message_part_2); } void red_with_no_bell(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; char message_part_2[8] = {0,0,0,0, 0,0,0,4}; send_lamp_command("red with no bell", message_part_1, message_part_2); } void set_green(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //green char message_part_2[8] = {0,0,0,0 ,0,0,0,2}; // green send_lamp_command("green", message_part_1, message_part_2); } void set_lights_off(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; // lights off char message_part_2[8] = {0,0,0,0, 0,0,0,0}; // lights off send_lamp_command("lights off", message_part_1, message_part_2); } void set_colors_with_bell(){ char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //colors with bell char message_part_2[8] = {0,0,0,0, 0,0,0,24}; // colors with bells send_lamp_command("colors with bells", message_part_1, message_part_2); } int load_device(){ int claimed; fprintf(stderr, "Starting\n"); struct usb_bus *busses; usb_init(); fprintf(stderr, "usb_init...\n"); usb_find_busses(); usb_find_devices(); fprintf(stderr, "Found busses, found devices...\n"); busses = usb_get_busses(); fprintf(stderr, "Got busses...\n"); struct usb_bus *bus; int c, i, a; /* ... */ for (bus = busses; bus; bus = bus->next) { struct usb_device *dev; for (dev = bus->devices; dev; dev = dev->next) { /* Check if this device is a printer */ if (dev->descriptor.idVendor == 4400) if(dev->descriptor.idProduct == 514) launcher = usb_open(dev); } } fprintf(stderr, "Got launcher...\n"); //do stuff if(launcher != NULL) { int claimed = usb_claim_interface(launcher, 1); } else { fprintf(stderr, "You didn't really get the launcher!\n"); return 1; } usb_detach_kernel_driver_np(launcher, 1); usb_detach_kernel_driver_np(launcher, 0); if (claimed == 0) { usb_release_interface(launcher, 1); return 1; } else if (claimed > 0){ fprintf(stderr, "Found launcher...\n"); } } int main(int argc, char *argv[]) { if ( argc != 2 ) /* argc should be 2 for correct execution */ { /* We print argv[0] assuming it is the program name */ - printf( "usage: %s filename\n", argv[0] ); + printf( "usage: %s red|green|bell|various\n", argv[0] ); } else { int ret = load_device(); char* argument = argv[1]; if(strcmp(argument, "green") == 0){ set_green(); } else if (strcmp(argument, "red") == 0){ red_with_no_bell(); } else if (strcmp(argument, "off") == 0){ set_lights_off(); } else if (strcmp(argument, "various") == 0){ set_colors_with_bell(); } else if (strcmp(argument, "bell") == 0){ only_bell_on(); } } return 0; } diff --git a/agilelamp-driver/tasks/deployment.rake b/agilelamp-driver/tasks/deployment.rake index 3cb8296..16e006e 100644 --- a/agilelamp-driver/tasks/deployment.rake +++ b/agilelamp-driver/tasks/deployment.rake @@ -1,45 +1,51 @@ desc 'Release the website and new gem version' task :deploy => [:check_version, :website, :release] do puts "Remember to create SVN tag:" puts "svn copy svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/trunk " + "svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/tags/REL-#{VERS} " puts "Suggested comment:" puts "Tagging release #{CHANGES}" end desc 'Runs tasks website_generate and install_gem as a local deployment of the gem' task :local_deploy => [:website_generate, :install_gem] task :check_version do unless ENV['VERSION'] puts 'Must pass a VERSION=x.y.z release version' exit end unless ENV['VERSION'] == VERS puts "Please update your version.rb to match the release version, currently #{VERS}" exit end end desc 'Install the package as a gem, without generating documentation(ri/rdoc)' task :install_gem_no_doc => [:clean, :package] do sh "#{'sudo ' unless Hoe::WINDOZE }gem install pkg/*.gem --no-rdoc --no-ri" end task :make_agilelamp_bin do cd "src/" + begin sh "make" cp "agilelamp-driver", "../bin" + rescue + puts "***************************" + puts "Couldn't compile for your architecture. Precompiled binary may still work. If not, try installing libusb headers (compile and install libusb from source)." + puts "***************************" + end cd "../" end task :install_gem => [:clean, :make_agilelamp_bin, :package] do - sh "#{'sudo ' unless Hoe::WINDOZE}gem install --local pkg/*.gem" + sh "#{'sudo ' unless Hoe::WINDOZE}gem install --no-wrappers --local pkg/*.gem" end namespace :manifest do desc 'Recreate Manifest.txt to include ALL files' task :refresh do `rake check_manifest | patch -p0 > Manifest.txt` end end
tristil/agile-lamp
ec08fe5bfde93fcf142262d49176c1210392e865
agilelamp-driver gem
diff --git a/agilelamp-driver/History.txt b/agilelamp-driver/History.txt new file mode 100644 index 0000000..c544fec --- /dev/null +++ b/agilelamp-driver/History.txt @@ -0,0 +1,4 @@ +== 0.0.1 2008-05-19 + +* 1 major enhancement: + * Initial release diff --git a/agilelamp-driver/License.txt b/agilelamp-driver/License.txt new file mode 100644 index 0000000..59a21c9 --- /dev/null +++ b/agilelamp-driver/License.txt @@ -0,0 +1,20 @@ +Copyright (c) 2008 Joseph Method + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/agilelamp-driver/Manifest.txt b/agilelamp-driver/Manifest.txt new file mode 100644 index 0000000..7567b80 --- /dev/null +++ b/agilelamp-driver/Manifest.txt @@ -0,0 +1,26 @@ +History.txt +License.txt +Manifest.txt +README.txt +Rakefile +config/hoe.rb +config/requirements.rb +script/console +script/destroy +script/generate +script/txt2html +setup.rb +bin/agilelamp-driver +lib/agilelamp-driver.rb +src/agilelamp.c +src/Makefile +tasks/deployment.rake +tasks/environment.rake +tasks/website.rake +test/test_agilelamp-driver.rb +test/test_helper.rb +website/index.html +website/index.txt +website/javascripts/rounded_corners_lite.inc.js +website/stylesheets/screen.css +website/template.html.erb diff --git a/agilelamp-driver/README.txt b/agilelamp-driver/README.txt new file mode 100644 index 0000000..e87d87e --- /dev/null +++ b/agilelamp-driver/README.txt @@ -0,0 +1,48 @@ += agilelamp-driver + +* FIX (url) + +== DESCRIPTION: + +FIX (describe your package) + +== FEATURES/PROBLEMS: + +* FIX (list of features or problems) + +== SYNOPSIS: + + FIX (code sample of usage) + +== REQUIREMENTS: + +* FIX (list of requirements) + +== INSTALL: + +* FIX (sudo gem install, anything else) + +== LICENSE: + +(The MIT License) + +Copyright (c) 2008 FIX + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/agilelamp-driver/Rakefile b/agilelamp-driver/Rakefile new file mode 100644 index 0000000..e469154 --- /dev/null +++ b/agilelamp-driver/Rakefile @@ -0,0 +1,4 @@ +require 'config/requirements' +require 'config/hoe' # setup Hoe + all gem configuration + +Dir['tasks/**/*.rake'].each { |rake| load rake } \ No newline at end of file diff --git a/agilelamp-driver/bin/agilelamp-driver b/agilelamp-driver/bin/agilelamp-driver new file mode 100755 index 0000000..23c907d Binary files /dev/null and b/agilelamp-driver/bin/agilelamp-driver differ diff --git a/agilelamp-driver/config/hoe.rb b/agilelamp-driver/config/hoe.rb new file mode 100644 index 0000000..b55f215 --- /dev/null +++ b/agilelamp-driver/config/hoe.rb @@ -0,0 +1,74 @@ +#require 'agilelamp-driver/version' + +AUTHOR = 'Joseph Method' # can also be an array of Authors +EMAIL = "[email protected]" +DESCRIPTION = "Userland driver for USB Agile Lamp" +GEM_NAME = 'agilelamp-driver' # what ppl will type to install your gem +RUBYFORGE_PROJECT = 'agilelamp' # The unix name for your project +HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org" +DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" +EXTRA_DEPENDENCIES = [ +# ['activesupport', '>= 1.3.1'] +] # An array of rubygem dependencies [name, version] + +@config_file = "~/.rubyforge/user-config.yml" +@config = nil +RUBYFORGE_USERNAME = "unknown" +def rubyforge_username + unless @config + begin + @config = YAML.load(File.read(File.expand_path(@config_file))) + rescue + puts <<-EOS +ERROR: No rubyforge config file found: #{@config_file} +Run 'rubyforge setup' to prepare your env for access to Rubyforge + - See http://newgem.rubyforge.org/rubyforge.html for more details + EOS + exit + end + end + RUBYFORGE_USERNAME.replace @config["username"] +end + + +REV = nil +# UNCOMMENT IF REQUIRED: +# REV = YAML.load(`svn info`)['Revision'] +#VERS = Agilelamp-driver::VERSION::STRING + (REV ? ".#{REV}" : "") +VERS = "0.1.0" +RDOC_OPTS = ['--quiet', '--title', 'agilelamp-driver documentation', + "--opname", "index.html", + "--line-numbers", + "--main", "README", + "--inline-source"] + +class Hoe + def extra_deps + @extra_deps.reject! { |x| Array(x).first == 'hoe' } + @extra_deps + end +end + +# Generate all the Rake tasks +# Run 'rake -T' to see list of generated tasks (from gem root directory) +$hoe = Hoe.new(GEM_NAME, VERS) do |p| + p.developer(AUTHOR, EMAIL) + p.description = DESCRIPTION + p.summary = DESCRIPTION + p.url = HOMEPATH + p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT + p.test_globs = ["test/**/test_*.rb"] + p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean. + + # == Optional + p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n") + #p.extra_deps = EXTRA_DEPENDENCIES + + #p.spec_extras = {} # A hash of extra values to set in the gemspec. + end + +CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n") +PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}" +$hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc') +$hoe.rsync_args = '-av --delete --ignore-errors' +$hoe.spec.post_install_message = File.open(File.dirname(__FILE__) + "/../PostInstall.txt").read rescue "" diff --git a/agilelamp-driver/config/requirements.rb b/agilelamp-driver/config/requirements.rb new file mode 100644 index 0000000..9292b69 --- /dev/null +++ b/agilelamp-driver/config/requirements.rb @@ -0,0 +1,15 @@ +require 'fileutils' +include FileUtils + +require 'rubygems' +%w[rake hoe newgem rubigen].each do |req_gem| + begin + require req_gem + rescue LoadError + puts "This Rakefile requires the '#{req_gem}' RubyGem." + puts "Installation: gem install #{req_gem} -y" + exit + end +end + +$:.unshift(File.join(File.dirname(__FILE__), %w[.. lib])) diff --git a/agilelamp-driver/lib/agilelamp-driver.rb b/agilelamp-driver/lib/agilelamp-driver.rb new file mode 100644 index 0000000..8dabfcc --- /dev/null +++ b/agilelamp-driver/lib/agilelamp-driver.rb @@ -0,0 +1,2 @@ +puts "Nothing to see here (yet)." + diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0.gem b/agilelamp-driver/pkg/agilelamp-driver-0.1.0.gem new file mode 100644 index 0000000..480fe99 Binary files /dev/null and b/agilelamp-driver/pkg/agilelamp-driver-0.1.0.gem differ diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0.tgz b/agilelamp-driver/pkg/agilelamp-driver-0.1.0.tgz new file mode 100644 index 0000000..21745cb Binary files /dev/null and b/agilelamp-driver/pkg/agilelamp-driver-0.1.0.tgz differ diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/History.txt b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/History.txt new file mode 100644 index 0000000..c544fec --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/History.txt @@ -0,0 +1,4 @@ +== 0.0.1 2008-05-19 + +* 1 major enhancement: + * Initial release diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/License.txt b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/License.txt new file mode 100644 index 0000000..59a21c9 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/License.txt @@ -0,0 +1,20 @@ +Copyright (c) 2008 Joseph Method + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/Manifest.txt b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/Manifest.txt new file mode 100644 index 0000000..7567b80 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/Manifest.txt @@ -0,0 +1,26 @@ +History.txt +License.txt +Manifest.txt +README.txt +Rakefile +config/hoe.rb +config/requirements.rb +script/console +script/destroy +script/generate +script/txt2html +setup.rb +bin/agilelamp-driver +lib/agilelamp-driver.rb +src/agilelamp.c +src/Makefile +tasks/deployment.rake +tasks/environment.rake +tasks/website.rake +test/test_agilelamp-driver.rb +test/test_helper.rb +website/index.html +website/index.txt +website/javascripts/rounded_corners_lite.inc.js +website/stylesheets/screen.css +website/template.html.erb diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/README.txt b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/README.txt new file mode 100644 index 0000000..e87d87e --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/README.txt @@ -0,0 +1,48 @@ += agilelamp-driver + +* FIX (url) + +== DESCRIPTION: + +FIX (describe your package) + +== FEATURES/PROBLEMS: + +* FIX (list of features or problems) + +== SYNOPSIS: + + FIX (code sample of usage) + +== REQUIREMENTS: + +* FIX (list of requirements) + +== INSTALL: + +* FIX (sudo gem install, anything else) + +== LICENSE: + +(The MIT License) + +Copyright (c) 2008 FIX + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/Rakefile b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/Rakefile new file mode 100644 index 0000000..e469154 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/Rakefile @@ -0,0 +1,4 @@ +require 'config/requirements' +require 'config/hoe' # setup Hoe + all gem configuration + +Dir['tasks/**/*.rake'].each { |rake| load rake } \ No newline at end of file diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/bin/agilelamp-driver b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/bin/agilelamp-driver new file mode 100755 index 0000000..23c907d Binary files /dev/null and b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/bin/agilelamp-driver differ diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/config/hoe.rb b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/config/hoe.rb new file mode 100644 index 0000000..b55f215 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/config/hoe.rb @@ -0,0 +1,74 @@ +#require 'agilelamp-driver/version' + +AUTHOR = 'Joseph Method' # can also be an array of Authors +EMAIL = "[email protected]" +DESCRIPTION = "Userland driver for USB Agile Lamp" +GEM_NAME = 'agilelamp-driver' # what ppl will type to install your gem +RUBYFORGE_PROJECT = 'agilelamp' # The unix name for your project +HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org" +DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" +EXTRA_DEPENDENCIES = [ +# ['activesupport', '>= 1.3.1'] +] # An array of rubygem dependencies [name, version] + +@config_file = "~/.rubyforge/user-config.yml" +@config = nil +RUBYFORGE_USERNAME = "unknown" +def rubyforge_username + unless @config + begin + @config = YAML.load(File.read(File.expand_path(@config_file))) + rescue + puts <<-EOS +ERROR: No rubyforge config file found: #{@config_file} +Run 'rubyforge setup' to prepare your env for access to Rubyforge + - See http://newgem.rubyforge.org/rubyforge.html for more details + EOS + exit + end + end + RUBYFORGE_USERNAME.replace @config["username"] +end + + +REV = nil +# UNCOMMENT IF REQUIRED: +# REV = YAML.load(`svn info`)['Revision'] +#VERS = Agilelamp-driver::VERSION::STRING + (REV ? ".#{REV}" : "") +VERS = "0.1.0" +RDOC_OPTS = ['--quiet', '--title', 'agilelamp-driver documentation', + "--opname", "index.html", + "--line-numbers", + "--main", "README", + "--inline-source"] + +class Hoe + def extra_deps + @extra_deps.reject! { |x| Array(x).first == 'hoe' } + @extra_deps + end +end + +# Generate all the Rake tasks +# Run 'rake -T' to see list of generated tasks (from gem root directory) +$hoe = Hoe.new(GEM_NAME, VERS) do |p| + p.developer(AUTHOR, EMAIL) + p.description = DESCRIPTION + p.summary = DESCRIPTION + p.url = HOMEPATH + p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT + p.test_globs = ["test/**/test_*.rb"] + p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean. + + # == Optional + p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n") + #p.extra_deps = EXTRA_DEPENDENCIES + + #p.spec_extras = {} # A hash of extra values to set in the gemspec. + end + +CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n") +PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}" +$hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc') +$hoe.rsync_args = '-av --delete --ignore-errors' +$hoe.spec.post_install_message = File.open(File.dirname(__FILE__) + "/../PostInstall.txt").read rescue "" diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/config/requirements.rb b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/config/requirements.rb new file mode 100644 index 0000000..9292b69 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/config/requirements.rb @@ -0,0 +1,15 @@ +require 'fileutils' +include FileUtils + +require 'rubygems' +%w[rake hoe newgem rubigen].each do |req_gem| + begin + require req_gem + rescue LoadError + puts "This Rakefile requires the '#{req_gem}' RubyGem." + puts "Installation: gem install #{req_gem} -y" + exit + end +end + +$:.unshift(File.join(File.dirname(__FILE__), %w[.. lib])) diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/lib/agilelamp-driver.rb b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/lib/agilelamp-driver.rb new file mode 100644 index 0000000..8dabfcc --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/lib/agilelamp-driver.rb @@ -0,0 +1,2 @@ +puts "Nothing to see here (yet)." + diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/script/console b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/script/console new file mode 100755 index 0000000..b037260 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/script/console @@ -0,0 +1,10 @@ +#!/usr/bin/env ruby +# File: script/console +irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb' + +libs = " -r irb/completion" +# Perhaps use a console_lib to store any extra methods I may want available in the cosole +# libs << " -r #{File.dirname(__FILE__) + '/../lib/console_lib/console_logger.rb'}" +libs << " -r #{File.dirname(__FILE__) + '/../lib/agilelamp-driver.rb'}" +puts "Loading agilelamp-driver gem" +exec "#{irb} #{libs} --simple-prompt" \ No newline at end of file diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/script/destroy b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/script/destroy new file mode 100755 index 0000000..e48464d --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/script/destroy @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/destroy' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Destroy.new.run(ARGV) diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/script/generate b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/script/generate new file mode 100755 index 0000000..c27f655 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/script/generate @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/generate' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Generate.new.run(ARGV) diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/script/txt2html b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/script/txt2html new file mode 100755 index 0000000..7d5bfad --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/script/txt2html @@ -0,0 +1,82 @@ +#!/usr/bin/env ruby + +GEM_NAME = 'agilelamp-driver' # what ppl will type to install your gem +RUBYFORGE_PROJECT = 'agilelamp-driver' + +require 'rubygems' +begin + require 'newgem' + require 'rubyforge' +rescue LoadError + puts "\n\nGenerating the website requires the newgem RubyGem" + puts "Install: gem install newgem\n\n" + exit(1) +end +require 'redcloth' +require 'syntax/convertors/html' +require 'erb' +require File.dirname(__FILE__) + "/../lib/#{GEM_NAME}/version.rb" + +version = Agilelamp-driver::VERSION::STRING +download = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" + +def rubyforge_project_id + RubyForge.new.autoconfig["group_ids"][RUBYFORGE_PROJECT] +end + +class Fixnum + def ordinal + # teens + return 'th' if (10..19).include?(self % 100) + # others + case self % 10 + when 1: return 'st' + when 2: return 'nd' + when 3: return 'rd' + else return 'th' + end + end +end + +class Time + def pretty + return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" + end +end + +def convert_syntax(syntax, source) + return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^<pre>|</pre>$!,'') +end + +if ARGV.length >= 1 + src, template = ARGV + template ||= File.join(File.dirname(__FILE__), '/../website/template.html.erb') +else + puts("Usage: #{File.split($0).last} source.txt [template.html.erb] > output.html") + exit! +end + +template = ERB.new(File.open(template).read) + +title = nil +body = nil +File.open(src) do |fsrc| + title_text = fsrc.readline + body_text_template = fsrc.read + body_text = ERB.new(body_text_template).result(binding) + syntax_items = [] + body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)</\1>!m){ + ident = syntax_items.length + element, syntax, source = $1, $2, $3 + syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}</#{element}>" + "syntax-temp-#{ident}" + } + title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip + body = RedCloth.new(body_text).to_html + body.gsub!(%r!(?:<pre><code>)?syntax-temp-(\d+)(?:</code></pre>)?!){ syntax_items[$1.to_i] } +end +stat = File.stat(src) +created = stat.ctime +modified = stat.mtime + +$stdout << template.result(binding) diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/setup.rb b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/setup.rb new file mode 100644 index 0000000..424a5f3 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/setup.rb @@ -0,0 +1,1585 @@ +# +# setup.rb +# +# Copyright (c) 2000-2005 Minero Aoki +# +# This program is free software. +# You can distribute/modify this program under the terms of +# the GNU LGPL, Lesser General Public License version 2.1. +# + +unless Enumerable.method_defined?(:map) # Ruby 1.4.6 + module Enumerable + alias map collect + end +end + +unless File.respond_to?(:read) # Ruby 1.6 + def File.read(fname) + open(fname) {|f| + return f.read + } + end +end + +unless Errno.const_defined?(:ENOTEMPTY) # Windows? + module Errno + class ENOTEMPTY + # We do not raise this exception, implementation is not needed. + end + end +end + +def File.binread(fname) + open(fname, 'rb') {|f| + return f.read + } +end + +# for corrupted Windows' stat(2) +def File.dir?(path) + File.directory?((path[-1,1] == '/') ? path : path + '/') +end + + +class ConfigTable + + include Enumerable + + def initialize(rbconfig) + @rbconfig = rbconfig + @items = [] + @table = {} + # options + @install_prefix = nil + @config_opt = nil + @verbose = true + @no_harm = false + end + + attr_accessor :install_prefix + attr_accessor :config_opt + + attr_writer :verbose + + def verbose? + @verbose + end + + attr_writer :no_harm + + def no_harm? + @no_harm + end + + def [](key) + lookup(key).resolve(self) + end + + def []=(key, val) + lookup(key).set val + end + + def names + @items.map {|i| i.name } + end + + def each(&block) + @items.each(&block) + end + + def key?(name) + @table.key?(name) + end + + def lookup(name) + @table[name] or setup_rb_error "no such config item: #{name}" + end + + def add(item) + @items.push item + @table[item.name] = item + end + + def remove(name) + item = lookup(name) + @items.delete_if {|i| i.name == name } + @table.delete_if {|name, i| i.name == name } + item + end + + def load_script(path, inst = nil) + if File.file?(path) + MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path + end + end + + def savefile + '.config' + end + + def load_savefile + begin + File.foreach(savefile()) do |line| + k, v = *line.split(/=/, 2) + self[k] = v.strip + end + rescue Errno::ENOENT + setup_rb_error $!.message + "\n#{File.basename($0)} config first" + end + end + + def save + @items.each {|i| i.value } + File.open(savefile(), 'w') {|f| + @items.each do |i| + f.printf "%s=%s\n", i.name, i.value if i.value? and i.value + end + } + end + + def load_standard_entries + standard_entries(@rbconfig).each do |ent| + add ent + end + end + + def standard_entries(rbconfig) + c = rbconfig + + rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) + + major = c['MAJOR'].to_i + minor = c['MINOR'].to_i + teeny = c['TEENY'].to_i + version = "#{major}.#{minor}" + + # ruby ver. >= 1.4.4? + newpath_p = ((major >= 2) or + ((major == 1) and + ((minor >= 5) or + ((minor == 4) and (teeny >= 4))))) + + if c['rubylibdir'] + # V > 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = c['rubylibdir'] + librubyverarch = c['archdir'] + siteruby = c['sitedir'] + siterubyver = c['sitelibdir'] + siterubyverarch = c['sitearchdir'] + elsif newpath_p + # 1.4.4 <= V <= 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = c['sitedir'] + siterubyver = "$siteruby/#{version}" + siterubyverarch = "$siterubyver/#{c['arch']}" + else + # V < 1.4.4 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" + siterubyver = siteruby + siterubyverarch = "$siterubyver/#{c['arch']}" + end + parameterize = lambda {|path| + path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') + } + + if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } + makeprog = arg.sub(/'/, '').split(/=/, 2)[1] + else + makeprog = 'make' + end + + [ + ExecItem.new('installdirs', 'std/site/home', + 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ + {|val, table| + case val + when 'std' + table['rbdir'] = '$librubyver' + table['sodir'] = '$librubyverarch' + when 'site' + table['rbdir'] = '$siterubyver' + table['sodir'] = '$siterubyverarch' + when 'home' + setup_rb_error '$HOME was not set' unless ENV['HOME'] + table['prefix'] = ENV['HOME'] + table['rbdir'] = '$libdir/ruby' + table['sodir'] = '$libdir/ruby' + end + }, + PathItem.new('prefix', 'path', c['prefix'], + 'path prefix of target environment'), + PathItem.new('bindir', 'path', parameterize.call(c['bindir']), + 'the directory for commands'), + PathItem.new('libdir', 'path', parameterize.call(c['libdir']), + 'the directory for libraries'), + PathItem.new('datadir', 'path', parameterize.call(c['datadir']), + 'the directory for shared data'), + PathItem.new('mandir', 'path', parameterize.call(c['mandir']), + 'the directory for man pages'), + PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), + 'the directory for system configuration files'), + PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), + 'the directory for local state data'), + PathItem.new('libruby', 'path', libruby, + 'the directory for ruby libraries'), + PathItem.new('librubyver', 'path', librubyver, + 'the directory for standard ruby libraries'), + PathItem.new('librubyverarch', 'path', librubyverarch, + 'the directory for standard ruby extensions'), + PathItem.new('siteruby', 'path', siteruby, + 'the directory for version-independent aux ruby libraries'), + PathItem.new('siterubyver', 'path', siterubyver, + 'the directory for aux ruby libraries'), + PathItem.new('siterubyverarch', 'path', siterubyverarch, + 'the directory for aux ruby binaries'), + PathItem.new('rbdir', 'path', '$siterubyver', + 'the directory for ruby scripts'), + PathItem.new('sodir', 'path', '$siterubyverarch', + 'the directory for ruby extentions'), + PathItem.new('rubypath', 'path', rubypath, + 'the path to set to #! line'), + ProgramItem.new('rubyprog', 'name', rubypath, + 'the ruby program using for installation'), + ProgramItem.new('makeprog', 'name', makeprog, + 'the make program to compile ruby extentions'), + SelectItem.new('shebang', 'all/ruby/never', 'ruby', + 'shebang line (#!) editing mode'), + BoolItem.new('without-ext', 'yes/no', 'no', + 'does not compile/install ruby extentions') + ] + end + private :standard_entries + + def load_multipackage_entries + multipackage_entries().each do |ent| + add ent + end + end + + def multipackage_entries + [ + PackageSelectionItem.new('with', 'name,name...', '', 'ALL', + 'package names that you want to install'), + PackageSelectionItem.new('without', 'name,name...', '', 'NONE', + 'package names that you do not want to install') + ] + end + private :multipackage_entries + + ALIASES = { + 'std-ruby' => 'librubyver', + 'stdruby' => 'librubyver', + 'rubylibdir' => 'librubyver', + 'archdir' => 'librubyverarch', + 'site-ruby-common' => 'siteruby', # For backward compatibility + 'site-ruby' => 'siterubyver', # For backward compatibility + 'bin-dir' => 'bindir', + 'bin-dir' => 'bindir', + 'rb-dir' => 'rbdir', + 'so-dir' => 'sodir', + 'data-dir' => 'datadir', + 'ruby-path' => 'rubypath', + 'ruby-prog' => 'rubyprog', + 'ruby' => 'rubyprog', + 'make-prog' => 'makeprog', + 'make' => 'makeprog' + } + + def fixup + ALIASES.each do |ali, name| + @table[ali] = @table[name] + end + @items.freeze + @table.freeze + @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ + end + + def parse_opt(opt) + m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" + m.to_a[1,2] + end + + def dllext + @rbconfig['DLEXT'] + end + + def value_config?(name) + lookup(name).value? + end + + class Item + def initialize(name, template, default, desc) + @name = name.freeze + @template = template + @value = default + @default = default + @description = desc + end + + attr_reader :name + attr_reader :description + + attr_accessor :default + alias help_default default + + def help_opt + "--#{@name}=#{@template}" + end + + def value? + true + end + + def value + @value + end + + def resolve(table) + @value.gsub(%r<\$([^/]+)>) { table[$1] } + end + + def set(val) + @value = check(val) + end + + private + + def check(val) + setup_rb_error "config: --#{name} requires argument" unless val + val + end + end + + class BoolItem < Item + def config_type + 'bool' + end + + def help_opt + "--#{@name}" + end + + private + + def check(val) + return 'yes' unless val + case val + when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' + when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' + else + setup_rb_error "config: --#{@name} accepts only yes/no for argument" + end + end + end + + class PathItem < Item + def config_type + 'path' + end + + private + + def check(path) + setup_rb_error "config: --#{@name} requires argument" unless path + path[0,1] == '$' ? path : File.expand_path(path) + end + end + + class ProgramItem < Item + def config_type + 'program' + end + end + + class SelectItem < Item + def initialize(name, selection, default, desc) + super + @ok = selection.split('/') + end + + def config_type + 'select' + end + + private + + def check(val) + unless @ok.include?(val.strip) + setup_rb_error "config: use --#{@name}=#{@template} (#{val})" + end + val.strip + end + end + + class ExecItem < Item + def initialize(name, selection, desc, &block) + super name, selection, nil, desc + @ok = selection.split('/') + @action = block + end + + def config_type + 'exec' + end + + def value? + false + end + + def resolve(table) + setup_rb_error "$#{name()} wrongly used as option value" + end + + undef set + + def evaluate(val, table) + v = val.strip.downcase + unless @ok.include?(v) + setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" + end + @action.call v, table + end + end + + class PackageSelectionItem < Item + def initialize(name, template, default, help_default, desc) + super name, template, default, desc + @help_default = help_default + end + + attr_reader :help_default + + def config_type + 'package' + end + + private + + def check(val) + unless File.dir?("packages/#{val}") + setup_rb_error "config: no such package: #{val}" + end + val + end + end + + class MetaConfigEnvironment + def initialize(config, installer) + @config = config + @installer = installer + end + + def config_names + @config.names + end + + def config?(name) + @config.key?(name) + end + + def bool_config?(name) + @config.lookup(name).config_type == 'bool' + end + + def path_config?(name) + @config.lookup(name).config_type == 'path' + end + + def value_config?(name) + @config.lookup(name).config_type != 'exec' + end + + def add_config(item) + @config.add item + end + + def add_bool_config(name, default, desc) + @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) + end + + def add_path_config(name, default, desc) + @config.add PathItem.new(name, 'path', default, desc) + end + + def set_config_default(name, default) + @config.lookup(name).default = default + end + + def remove_config(name) + @config.remove(name) + end + + # For only multipackage + def packages + raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer + @installer.packages + end + + # For only multipackage + def declare_packages(list) + raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer + @installer.packages = list + end + end + +end # class ConfigTable + + +# This module requires: #verbose?, #no_harm? +module FileOperations + + def mkdir_p(dirname, prefix = nil) + dirname = prefix + File.expand_path(dirname) if prefix + $stderr.puts "mkdir -p #{dirname}" if verbose? + return if no_harm? + + # Does not check '/', it's too abnormal. + dirs = File.expand_path(dirname).split(%r<(?=/)>) + if /\A[a-z]:\z/i =~ dirs[0] + disk = dirs.shift + dirs[0] = disk + dirs[0] + end + dirs.each_index do |idx| + path = dirs[0..idx].join('') + Dir.mkdir path unless File.dir?(path) + end + end + + def rm_f(path) + $stderr.puts "rm -f #{path}" if verbose? + return if no_harm? + force_remove_file path + end + + def rm_rf(path) + $stderr.puts "rm -rf #{path}" if verbose? + return if no_harm? + remove_tree path + end + + def remove_tree(path) + if File.symlink?(path) + remove_file path + elsif File.dir?(path) + remove_tree0 path + else + force_remove_file path + end + end + + def remove_tree0(path) + Dir.foreach(path) do |ent| + next if ent == '.' + next if ent == '..' + entpath = "#{path}/#{ent}" + if File.symlink?(entpath) + remove_file entpath + elsif File.dir?(entpath) + remove_tree0 entpath + else + force_remove_file entpath + end + end + begin + Dir.rmdir path + rescue Errno::ENOTEMPTY + # directory may not be empty + end + end + + def move_file(src, dest) + force_remove_file dest + begin + File.rename src, dest + rescue + File.open(dest, 'wb') {|f| + f.write File.binread(src) + } + File.chmod File.stat(src).mode, dest + File.unlink src + end + end + + def force_remove_file(path) + begin + remove_file path + rescue + end + end + + def remove_file(path) + File.chmod 0777, path + File.unlink path + end + + def install(from, dest, mode, prefix = nil) + $stderr.puts "install #{from} #{dest}" if verbose? + return if no_harm? + + realdest = prefix ? prefix + File.expand_path(dest) : dest + realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) + str = File.binread(from) + if diff?(str, realdest) + verbose_off { + rm_f realdest if File.exist?(realdest) + } + File.open(realdest, 'wb') {|f| + f.write str + } + File.chmod mode, realdest + + File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| + if prefix + f.puts realdest.sub(prefix, '') + else + f.puts realdest + end + } + end + end + + def diff?(new_content, path) + return true unless File.exist?(path) + new_content != File.binread(path) + end + + def command(*args) + $stderr.puts args.join(' ') if verbose? + system(*args) or raise RuntimeError, + "system(#{args.map{|a| a.inspect }.join(' ')}) failed" + end + + def ruby(*args) + command config('rubyprog'), *args + end + + def make(task = nil) + command(*[config('makeprog'), task].compact) + end + + def extdir?(dir) + File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") + end + + def files_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.file?("#{dir}/#{ent}") } + } + end + + DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) + + def directories_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT + } + end + +end + + +# This module requires: #srcdir_root, #objdir_root, #relpath +module HookScriptAPI + + def get_config(key) + @config[key] + end + + alias config get_config + + # obsolete: use metaconfig to change configuration + def set_config(key, val) + @config[key] = val + end + + # + # srcdir/objdir (works only in the package directory) + # + + def curr_srcdir + "#{srcdir_root()}/#{relpath()}" + end + + def curr_objdir + "#{objdir_root()}/#{relpath()}" + end + + def srcfile(path) + "#{curr_srcdir()}/#{path}" + end + + def srcexist?(path) + File.exist?(srcfile(path)) + end + + def srcdirectory?(path) + File.dir?(srcfile(path)) + end + + def srcfile?(path) + File.file?(srcfile(path)) + end + + def srcentries(path = '.') + Dir.open("#{curr_srcdir()}/#{path}") {|d| + return d.to_a - %w(. ..) + } + end + + def srcfiles(path = '.') + srcentries(path).select {|fname| + File.file?(File.join(curr_srcdir(), path, fname)) + } + end + + def srcdirectories(path = '.') + srcentries(path).select {|fname| + File.dir?(File.join(curr_srcdir(), path, fname)) + } + end + +end + + +class ToplevelInstaller + + Version = '3.4.1' + Copyright = 'Copyright (c) 2000-2005 Minero Aoki' + + TASKS = [ + [ 'all', 'do config, setup, then install' ], + [ 'config', 'saves your configurations' ], + [ 'show', 'shows current configuration' ], + [ 'setup', 'compiles ruby extentions and others' ], + [ 'install', 'installs files' ], + [ 'test', 'run all tests in test/' ], + [ 'clean', "does `make clean' for each extention" ], + [ 'distclean',"does `make distclean' for each extention" ] + ] + + def ToplevelInstaller.invoke + config = ConfigTable.new(load_rbconfig()) + config.load_standard_entries + config.load_multipackage_entries if multipackage? + config.fixup + klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) + klass.new(File.dirname($0), config).invoke + end + + def ToplevelInstaller.multipackage? + File.dir?(File.dirname($0) + '/packages') + end + + def ToplevelInstaller.load_rbconfig + if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } + ARGV.delete(arg) + load File.expand_path(arg.split(/=/, 2)[1]) + $".push 'rbconfig.rb' + else + require 'rbconfig' + end + ::Config::CONFIG + end + + def initialize(ardir_root, config) + @ardir = File.expand_path(ardir_root) + @config = config + # cache + @valid_task_re = nil + end + + def config(key) + @config[key] + end + + def inspect + "#<#{self.class} #{__id__()}>" + end + + def invoke + run_metaconfigs + case task = parsearg_global() + when nil, 'all' + parsearg_config + init_installers + exec_config + exec_setup + exec_install + else + case task + when 'config', 'test' + ; + when 'clean', 'distclean' + @config.load_savefile if File.exist?(@config.savefile) + else + @config.load_savefile + end + __send__ "parsearg_#{task}" + init_installers + __send__ "exec_#{task}" + end + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig" + end + + def init_installers + @installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + # + # Hook Script API bases + # + + def srcdir_root + @ardir + end + + def objdir_root + '.' + end + + def relpath + '.' + end + + # + # Option Parsing + # + + def parsearg_global + while arg = ARGV.shift + case arg + when /\A\w+\z/ + setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) + return arg + when '-q', '--quiet' + @config.verbose = false + when '--verbose' + @config.verbose = true + when '--help' + print_usage $stdout + exit 0 + when '--version' + puts "#{File.basename($0)} version #{Version}" + exit 0 + when '--copyright' + puts Copyright + exit 0 + else + setup_rb_error "unknown global option '#{arg}'" + end + end + nil + end + + def valid_task?(t) + valid_task_re() =~ t + end + + def valid_task_re + @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ + end + + def parsearg_no_options + unless ARGV.empty? + task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) + setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" + end + end + + alias parsearg_show parsearg_no_options + alias parsearg_setup parsearg_no_options + alias parsearg_test parsearg_no_options + alias parsearg_clean parsearg_no_options + alias parsearg_distclean parsearg_no_options + + def parsearg_config + evalopt = [] + set = [] + @config.config_opt = [] + while i = ARGV.shift + if /\A--?\z/ =~ i + @config.config_opt = ARGV.dup + break + end + name, value = *@config.parse_opt(i) + if @config.value_config?(name) + @config[name] = value + else + evalopt.push [name, value] + end + set.push name + end + evalopt.each do |name, value| + @config.lookup(name).evaluate value, @config + end + # Check if configuration is valid + set.each do |n| + @config[n] if @config.value_config?(n) + end + end + + def parsearg_install + @config.no_harm = false + @config.install_prefix = '' + while a = ARGV.shift + case a + when '--no-harm' + @config.no_harm = true + when /\A--prefix=/ + path = a.split(/=/, 2)[1] + path = File.expand_path(path) unless path[0,1] == '/' + @config.install_prefix = path + else + setup_rb_error "install: unknown option #{a}" + end + end + end + + def print_usage(out) + out.puts 'Typical Installation Procedure:' + out.puts " $ ruby #{File.basename $0} config" + out.puts " $ ruby #{File.basename $0} setup" + out.puts " # ruby #{File.basename $0} install (may require root privilege)" + out.puts + out.puts 'Detailed Usage:' + out.puts " ruby #{File.basename $0} <global option>" + out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]" + + fmt = " %-24s %s\n" + out.puts + out.puts 'Global options:' + out.printf fmt, '-q,--quiet', 'suppress message outputs' + out.printf fmt, ' --verbose', 'output messages verbosely' + out.printf fmt, ' --help', 'print this message' + out.printf fmt, ' --version', 'print version and quit' + out.printf fmt, ' --copyright', 'print copyright and quit' + out.puts + out.puts 'Tasks:' + TASKS.each do |name, desc| + out.printf fmt, name, desc + end + + fmt = " %-24s %s [%s]\n" + out.puts + out.puts 'Options for CONFIG or ALL:' + @config.each do |item| + out.printf fmt, item.help_opt, item.description, item.help_default + end + out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" + out.puts + out.puts 'Options for INSTALL:' + out.printf fmt, '--no-harm', 'only display what to do if given', 'off' + out.printf fmt, '--prefix=path', 'install path prefix', '' + out.puts + end + + # + # Task Handlers + # + + def exec_config + @installer.exec_config + @config.save # must be final + end + + def exec_setup + @installer.exec_setup + end + + def exec_install + @installer.exec_install + end + + def exec_test + @installer.exec_test + end + + def exec_show + @config.each do |i| + printf "%-20s %s\n", i.name, i.value if i.value? + end + end + + def exec_clean + @installer.exec_clean + end + + def exec_distclean + @installer.exec_distclean + end + +end # class ToplevelInstaller + + +class ToplevelInstallerMulti < ToplevelInstaller + + include FileOperations + + def initialize(ardir_root, config) + super + @packages = directories_of("#{@ardir}/packages") + raise 'no package exists' if @packages.empty? + @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig", self + @packages.each do |name| + @config.load_script "#{@ardir}/packages/#{name}/metaconfig" + end + end + + attr_reader :packages + + def packages=(list) + raise 'package list is empty' if list.empty? + list.each do |name| + raise "directory packages/#{name} does not exist"\ + unless File.dir?("#{@ardir}/packages/#{name}") + end + @packages = list + end + + def init_installers + @installers = {} + @packages.each do |pack| + @installers[pack] = Installer.new(@config, + "#{@ardir}/packages/#{pack}", + "packages/#{pack}") + end + with = extract_selection(config('with')) + without = extract_selection(config('without')) + @selected = @installers.keys.select {|name| + (with.empty? or with.include?(name)) \ + and not without.include?(name) + } + end + + def extract_selection(list) + a = list.split(/,/) + a.each do |name| + setup_rb_error "no such package: #{name}" unless @installers.key?(name) + end + a + end + + def print_usage(f) + super + f.puts 'Inluded packages:' + f.puts ' ' + @packages.sort.join(' ') + f.puts + end + + # + # Task Handlers + # + + def exec_config + run_hook 'pre-config' + each_selected_installers {|inst| inst.exec_config } + run_hook 'post-config' + @config.save # must be final + end + + def exec_setup + run_hook 'pre-setup' + each_selected_installers {|inst| inst.exec_setup } + run_hook 'post-setup' + end + + def exec_install + run_hook 'pre-install' + each_selected_installers {|inst| inst.exec_install } + run_hook 'post-install' + end + + def exec_test + run_hook 'pre-test' + each_selected_installers {|inst| inst.exec_test } + run_hook 'post-test' + end + + def exec_clean + rm_f @config.savefile + run_hook 'pre-clean' + each_selected_installers {|inst| inst.exec_clean } + run_hook 'post-clean' + end + + def exec_distclean + rm_f @config.savefile + run_hook 'pre-distclean' + each_selected_installers {|inst| inst.exec_distclean } + run_hook 'post-distclean' + end + + # + # lib + # + + def each_selected_installers + Dir.mkdir 'packages' unless File.dir?('packages') + @selected.each do |pack| + $stderr.puts "Processing the package `#{pack}' ..." if verbose? + Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") + Dir.chdir "packages/#{pack}" + yield @installers[pack] + Dir.chdir '../..' + end + end + + def run_hook(id) + @root_installer.run_hook id + end + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + +end # class ToplevelInstallerMulti + + +class Installer + + FILETYPES = %w( bin lib ext data conf man ) + + include FileOperations + include HookScriptAPI + + def initialize(config, srcroot, objroot) + @config = config + @srcdir = File.expand_path(srcroot) + @objdir = File.expand_path(objroot) + @currdir = '.' + end + + def inspect + "#<#{self.class} #{File.basename(@srcdir)}>" + end + + def noop(rel) + end + + # + # Hook Script API base methods + # + + def srcdir_root + @srcdir + end + + def objdir_root + @objdir + end + + def relpath + @currdir + end + + # + # Config Access + # + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + + def verbose_off + begin + save, @config.verbose = @config.verbose?, false + yield + ensure + @config.verbose = save + end + end + + # + # TASK config + # + + def exec_config + exec_task_traverse 'config' + end + + alias config_dir_bin noop + alias config_dir_lib noop + + def config_dir_ext(rel) + extconf if extdir?(curr_srcdir()) + end + + alias config_dir_data noop + alias config_dir_conf noop + alias config_dir_man noop + + def extconf + ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt + end + + # + # TASK setup + # + + def exec_setup + exec_task_traverse 'setup' + end + + def setup_dir_bin(rel) + files_of(curr_srcdir()).each do |fname| + update_shebang_line "#{curr_srcdir()}/#{fname}" + end + end + + alias setup_dir_lib noop + + def setup_dir_ext(rel) + make if extdir?(curr_srcdir()) + end + + alias setup_dir_data noop + alias setup_dir_conf noop + alias setup_dir_man noop + + def update_shebang_line(path) + return if no_harm? + return if config('shebang') == 'never' + old = Shebang.load(path) + if old + $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 + new = new_shebang(old) + return if new.to_s == old.to_s + else + return unless config('shebang') == 'all' + new = Shebang.new(config('rubypath')) + end + $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? + open_atomic_writer(path) {|output| + File.open(path, 'rb') {|f| + f.gets if old # discard + output.puts new.to_s + output.print f.read + } + } + end + + def new_shebang(old) + if /\Aruby/ =~ File.basename(old.cmd) + Shebang.new(config('rubypath'), old.args) + elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' + Shebang.new(config('rubypath'), old.args[1..-1]) + else + return old unless config('shebang') == 'all' + Shebang.new(config('rubypath')) + end + end + + def open_atomic_writer(path, &block) + tmpfile = File.basename(path) + '.tmp' + begin + File.open(tmpfile, 'wb', &block) + File.rename tmpfile, File.basename(path) + ensure + File.unlink tmpfile if File.exist?(tmpfile) + end + end + + class Shebang + def Shebang.load(path) + line = nil + File.open(path) {|f| + line = f.gets + } + return nil unless /\A#!/ =~ line + parse(line) + end + + def Shebang.parse(line) + cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') + new(cmd, args) + end + + def initialize(cmd, args = []) + @cmd = cmd + @args = args + end + + attr_reader :cmd + attr_reader :args + + def to_s + "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") + end + end + + # + # TASK install + # + + def exec_install + rm_f 'InstalledFiles' + exec_task_traverse 'install' + end + + def install_dir_bin(rel) + install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 + end + + def install_dir_lib(rel) + install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 + end + + def install_dir_ext(rel) + return unless extdir?(curr_srcdir()) + install_files rubyextentions('.'), + "#{config('sodir')}/#{File.dirname(rel)}", + 0555 + end + + def install_dir_data(rel) + install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 + end + + def install_dir_conf(rel) + # FIXME: should not remove current config files + # (rename previous file to .old/.org) + install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 + end + + def install_dir_man(rel) + install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 + end + + def install_files(list, dest, mode) + mkdir_p dest, @config.install_prefix + list.each do |fname| + install fname, dest, mode, @config.install_prefix + end + end + + def libfiles + glob_reject(%w(*.y *.output), targetfiles()) + end + + def rubyextentions(dir) + ents = glob_select("*.#{@config.dllext}", targetfiles()) + if ents.empty? + setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" + end + ents + end + + def targetfiles + mapdir(existfiles() - hookfiles()) + end + + def mapdir(ents) + ents.map {|ent| + if File.exist?(ent) + then ent # objdir + else "#{curr_srcdir()}/#{ent}" # srcdir + end + } + end + + # picked up many entries from cvs-1.11.1/src/ignore.c + JUNK_FILES = %w( + core RCSLOG tags TAGS .make.state + .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb + *~ *.old *.bak *.BAK *.orig *.rej _$* *$ + + *.org *.in .* + ) + + def existfiles + glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) + end + + def hookfiles + %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| + %w( config setup install clean ).map {|t| sprintf(fmt, t) } + }.flatten + end + + def glob_select(pat, ents) + re = globs2re([pat]) + ents.select {|ent| re =~ ent } + end + + def glob_reject(pats, ents) + re = globs2re(pats) + ents.reject {|ent| re =~ ent } + end + + GLOB2REGEX = { + '.' => '\.', + '$' => '\$', + '#' => '\#', + '*' => '.*' + } + + def globs2re(pats) + /\A(?:#{ + pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|') + })\z/ + end + + # + # TASK test + # + + TESTDIR = 'test' + + def exec_test + unless File.directory?('test') + $stderr.puts 'no test in this package' if verbose? + return + end + $stderr.puts 'Running tests...' if verbose? + begin + require 'test/unit' + rescue LoadError + setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.' + end + runner = Test::Unit::AutoRunner.new(true) + runner.to_run << TESTDIR + runner.run + end + + # + # TASK clean + # + + def exec_clean + exec_task_traverse 'clean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias clean_dir_bin noop + alias clean_dir_lib noop + alias clean_dir_data noop + alias clean_dir_conf noop + alias clean_dir_man noop + + def clean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'clean' if File.file?('Makefile') + end + + # + # TASK distclean + # + + def exec_distclean + exec_task_traverse 'distclean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias distclean_dir_bin noop + alias distclean_dir_lib noop + + def distclean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'distclean' if File.file?('Makefile') + end + + alias distclean_dir_data noop + alias distclean_dir_conf noop + alias distclean_dir_man noop + + # + # Traversing + # + + def exec_task_traverse(task) + run_hook "pre-#{task}" + FILETYPES.each do |type| + if type == 'ext' and config('without-ext') == 'yes' + $stderr.puts 'skipping ext/* by user option' if verbose? + next + end + traverse task, type, "#{task}_dir_#{type}" + end + run_hook "post-#{task}" + end + + def traverse(task, rel, mid) + dive_into(rel) { + run_hook "pre-#{task}" + __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') + directories_of(curr_srcdir()).each do |d| + traverse task, "#{rel}/#{d}", mid + end + run_hook "post-#{task}" + } + end + + def dive_into(rel) + return unless File.dir?("#{@srcdir}/#{rel}") + + dir = File.basename(rel) + Dir.mkdir dir unless File.dir?(dir) + prevdir = Dir.pwd + Dir.chdir dir + $stderr.puts '---> ' + rel if verbose? + @currdir = rel + yield + Dir.chdir prevdir + $stderr.puts '<--- ' + rel if verbose? + @currdir = File.dirname(rel) + end + + def run_hook(id) + path = [ "#{curr_srcdir()}/#{id}", + "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) } + return unless path + begin + instance_eval File.read(path), path, 1 + rescue + raise if $DEBUG + setup_rb_error "hook #{path} failed:\n" + $!.message + end + end + +end # class Installer + + +class SetupError < StandardError; end + +def setup_rb_error(msg) + raise SetupError, msg +end + +if $0 == __FILE__ + begin + ToplevelInstaller.invoke + rescue SetupError + raise if $DEBUG + $stderr.puts $!.message + $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." + exit 1 + end +end diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/src/Makefile b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/src/Makefile new file mode 100644 index 0000000..5daf3ba --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/src/Makefile @@ -0,0 +1,2 @@ +all: + gcc agilelamp.c -o agilelamp-driver -lusb diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/src/agilelamp.c b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/src/agilelamp.c new file mode 100644 index 0000000..c32112e --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/src/agilelamp.c @@ -0,0 +1,175 @@ +#include <usb.h> +#include <stdio.h> +#include <unistd.h> +#include <string.h> + +usb_dev_handle* launcher; +//wrapper for control_msg +int send_message(char* msg, int index) +{ + int i = 0; + int j = usb_control_msg(launcher, 0x21, 0x9, 0x0, index, msg, 8, 1000); + return j; +} + +void send_cbw(){ + fprintf(stderr, "Sending CBW message\n"); + char cbw_message[8] = {0x55, 0x53, 0x42, 0x43, 0, 16, 2, 0}; + int ret = send_message(cbw_message, 1); + fprintf(stderr, "%d bytes sent\n", ret); +} + +void send_lamp_command(char* title, char* message1, char* message2){ + usb_reset(launcher); + send_cbw(); + fprintf(stderr, "Submitting %s\n", title); + int ret = send_message(message1, 0); + fprintf(stderr, "%d bytes sent\n", ret); + ret = send_message(message2, 0); + fprintf(stderr, "%d bytes sent\n", ret); +} + +void set_red_with_bell(){ + char message_part_1[8] = {0x0, 0x1, 0x4, 0x9,0x10, 0x19, 0x24, 0x31}; //red with bell + char message_part_2[8] = {0x40, 0x51, 0x64, 0x79, 0x90, 0xa9, 0xc4, 0xe1}; // red with bell + send_lamp_command("red with bell", message_part_1, message_part_2); +} + +/* +Fun with bit-math: + +Everything on the first (from right) 8 bits of first (from right) byte + +b0:=1:Bell active;=0:Bell off +b1:=1:Green led on; =0:Green led off +b2:=1:Red led on;=0:red led off +b3:=0:7 colors led on;=1:7 colors led off + + b0 +1 1 1 1 1 111 +128 64 32 16 8 421 = 255 + +c c c c c rgb (c's are colors to cycle through, then red, green, bell) + +0 0 0 16 0 000 = + +*/ + +void only_bell_on(){ + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; + char message_part_2[8] = {0,0,0,0, 0,0,0,1}; + send_lamp_command("green", message_part_1, message_part_2); +} + +void red_with_no_bell(){ + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; + char message_part_2[8] = {0,0,0,0, 0,0,0,4}; + send_lamp_command("red with no bell", message_part_1, message_part_2); +} + +void set_green(){ + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //green + char message_part_2[8] = {0,0,0,0 ,0,0,0,2}; // green + send_lamp_command("green", message_part_1, message_part_2); +} + +void set_lights_off(){ + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; // lights off + char message_part_2[8] = {0,0,0,0, 0,0,0,0}; // lights off + send_lamp_command("lights off", message_part_1, message_part_2); +} + +void set_colors_with_bell(){ + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //colors with bell + char message_part_2[8] = {0,0,0,0, 0,0,0,24}; // colors with bells + send_lamp_command("colors with bells", message_part_1, message_part_2); +} + +int load_device(){ + int claimed; + + fprintf(stderr, "Starting\n"); + + struct usb_bus *busses; + + usb_init(); + + fprintf(stderr, "usb_init...\n"); + + usb_find_busses(); + usb_find_devices(); + fprintf(stderr, "Found busses, found devices...\n"); + + busses = usb_get_busses(); + + fprintf(stderr, "Got busses...\n"); + + struct usb_bus *bus; + int c, i, a; + + /* ... */ + + for (bus = busses; bus; bus = bus->next) + { + struct usb_device *dev; + + for (dev = bus->devices; dev; dev = dev->next) + { + /* Check if this device is a printer */ + if (dev->descriptor.idVendor == 4400) + if(dev->descriptor.idProduct == 514) + launcher = usb_open(dev); + } + } + + fprintf(stderr, "Got launcher...\n"); + + //do stuff + if(launcher != NULL) + { + int claimed = usb_claim_interface(launcher, 1); + } + else + { + fprintf(stderr, "You didn't really get the launcher!\n"); + return 1; + } + + usb_detach_kernel_driver_np(launcher, 1); + usb_detach_kernel_driver_np(launcher, 0); + + if (claimed == 0) + { + usb_release_interface(launcher, 1); + return 1; + } else if (claimed > 0){ + fprintf(stderr, "Found launcher...\n"); + } + +} + +int main(int argc, char *argv[]) +{ + if ( argc != 2 ) /* argc should be 2 for correct execution */ + { + /* We print argv[0] assuming it is the program name */ + printf( "usage: %s filename\n", argv[0] ); + } + else + { + int ret = load_device(); + char* argument = argv[1]; + if(strcmp(argument, "green") == 0){ + set_green(); + } else if (strcmp(argument, "red") == 0){ + red_with_no_bell(); + } else if (strcmp(argument, "off") == 0){ + set_lights_off(); + } else if (strcmp(argument, "various") == 0){ + set_colors_with_bell(); + } else if (strcmp(argument, "bell") == 0){ + only_bell_on(); + } + } + return 0; +} diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/tasks/deployment.rake b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/tasks/deployment.rake new file mode 100644 index 0000000..3cb8296 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/tasks/deployment.rake @@ -0,0 +1,45 @@ +desc 'Release the website and new gem version' +task :deploy => [:check_version, :website, :release] do + puts "Remember to create SVN tag:" + puts "svn copy svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/trunk " + + "svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/tags/REL-#{VERS} " + puts "Suggested comment:" + puts "Tagging release #{CHANGES}" +end + +desc 'Runs tasks website_generate and install_gem as a local deployment of the gem' +task :local_deploy => [:website_generate, :install_gem] + +task :check_version do + unless ENV['VERSION'] + puts 'Must pass a VERSION=x.y.z release version' + exit + end + unless ENV['VERSION'] == VERS + puts "Please update your version.rb to match the release version, currently #{VERS}" + exit + end +end + +desc 'Install the package as a gem, without generating documentation(ri/rdoc)' +task :install_gem_no_doc => [:clean, :package] do + sh "#{'sudo ' unless Hoe::WINDOZE }gem install pkg/*.gem --no-rdoc --no-ri" +end + +task :make_agilelamp_bin do + cd "src/" + sh "make" + cp "agilelamp-driver", "../bin" + cd "../" +end + +task :install_gem => [:clean, :make_agilelamp_bin, :package] do + sh "#{'sudo ' unless Hoe::WINDOZE}gem install --local pkg/*.gem" +end + +namespace :manifest do + desc 'Recreate Manifest.txt to include ALL files' + task :refresh do + `rake check_manifest | patch -p0 > Manifest.txt` + end +end diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/tasks/environment.rake b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/tasks/environment.rake new file mode 100644 index 0000000..691ed3b --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/tasks/environment.rake @@ -0,0 +1,7 @@ +task :ruby_env do + RUBY_APP = if RUBY_PLATFORM =~ /java/ + "jruby" + else + "ruby" + end unless defined? RUBY_APP +end diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/tasks/website.rake b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/tasks/website.rake new file mode 100644 index 0000000..93e03fa --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/tasks/website.rake @@ -0,0 +1,17 @@ +desc 'Generate website files' +task :website_generate => :ruby_env do + (Dir['website/**/*.txt'] - Dir['website/version*.txt']).each do |txt| + sh %{ #{RUBY_APP} script/txt2html #{txt} > #{txt.gsub(/txt$/,'html')} } + end +end + +desc 'Upload website files to rubyforge' +task :website_upload do + host = "#{rubyforge_username}@rubyforge.org" + remote_dir = "/var/www/gforge-projects/#{PATH}/" + local_dir = 'website' + sh %{rsync -aCv #{local_dir}/ #{host}:#{remote_dir}} +end + +desc 'Generate and upload website files' +task :website => [:website_generate, :website_upload, :publish_docs] diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/test/test_agilelamp-driver.rb b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/test/test_agilelamp-driver.rb new file mode 100644 index 0000000..ac5b2e2 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/test/test_agilelamp-driver.rb @@ -0,0 +1,11 @@ +require File.dirname(__FILE__) + '/test_helper.rb' + +class TestAgilelamp-driver < Test::Unit::TestCase + + def setup + end + + def test_truth + assert true + end +end diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/test/test_helper.rb b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/test/test_helper.rb new file mode 100644 index 0000000..aa737d8 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/test/test_helper.rb @@ -0,0 +1,2 @@ +require 'test/unit' +require File.dirname(__FILE__) + '/../lib/agilelamp-driver' diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/index.html b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/index.html new file mode 100644 index 0000000..2f6be96 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/index.html @@ -0,0 +1,11 @@ +<html> + <head> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>agilelamp-driver</title> + + </head> + <body id="body"> + <p>This page has not yet been created for RubyGem <code>agilelamp-driver</code></p> + <p>To the developer: To generate it, update website/index.txt and run the rake task <code>website</code> to generate this <code>index.html</code> file.</p> + </body> +</html> \ No newline at end of file diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/index.txt b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/index.txt new file mode 100644 index 0000000..60bd997 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/index.txt @@ -0,0 +1,83 @@ +h1. agilelamp driver + +h1. &#x2192; 'agilelamp-driver' + + +h2. What + + +h2. Installing + +<pre syntax="ruby">sudo gem install agilelamp-driver</pre> + +h2. The basics + + +h2. Demonstration of usage + + + +h2. Forum + +"http://groups.google.com/group/agilelamp-driver":http://groups.google.com/group/agilelamp-driver + +TODO - create Google Group - agilelamp-driver + +h2. How to submit patches + +Read the "8 steps for fixing other people's code":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/ and for section "8b: Submit patch to Google Groups":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/#8b-google-groups, use the Google Group above. + +TODO - pick SVN or Git instructions + +The trunk repository is <code>svn://rubyforge.org/var/svn/agilelamp-driver/trunk</code> for anonymous access. + +OOOORRRR + +You can fetch the source from either: + +<% if rubyforge_project_id %> + +* rubyforge: "http://rubyforge.org/scm/?group_id=<%= rubyforge_project_id %>":http://rubyforge.org/scm/?group_id=<%= rubyforge_project_id %> + +<pre>git clone git://rubyforge.org/agilelamp-driver.git</pre> + +<% else %> + +* rubyforge: MISSING IN ACTION + +TODO - You can not created a RubyForge project, OR have not run <code>rubyforge config</code> +yet to refresh your local rubyforge data with this projects' id information. + +When you do this, this message will magically disappear! + +Or you can hack website/index.txt and make it all go away!! + +<% end %> + +* github: "http://github.com/GITHUB_USERNAME/agilelamp-driver/tree/master":http://github.com/GITHUB_USERNAME/agilelamp-driver/tree/master + +<pre>git clone git://github.com/GITHUB_USERNAME/agilelamp-driver.git</pre> + + +TODO - add "github_username: username" to ~/.rubyforge/user-config.yml and newgem will reuse it for future projects. + + +* gitorious: "git://gitorious.org/agilelamp-driver/mainline.git":git://gitorious.org/agilelamp-driver/mainline.git + +<pre>git clone git://gitorious.org/agilelamp-driver/mainline.git</pre> + +h3. Build and test instructions + +<pre>cd agilelamp-driver +rake test +rake install_gem</pre> + + +h2. License + +This code is free to use under the terms of the MIT license. + +h2. Contact + +Comments are welcome. Send an email to "Joseph Method":mailto:[email protected] via the "forum":http://groups.google.com/group/agilelamp-driver + diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/javascripts/rounded_corners_lite.inc.js b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/javascripts/rounded_corners_lite.inc.js new file mode 100644 index 0000000..afc3ea3 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/javascripts/rounded_corners_lite.inc.js @@ -0,0 +1,285 @@ + + /**************************************************************** + * * + * curvyCorners * + * ------------ * + * * + * This script generates rounded corners for your divs. * + * * + * Version 1.2.9 * + * Copyright (c) 2006 Cameron Cooke * + * By: Cameron Cooke and Tim Hutchison. * + * * + * * + * Website: http://www.curvycorners.net * + * Email: [email protected] * + * Forum: http://www.curvycorners.net/forum/ * + * * + * * + * This library is free software; you can redistribute * + * it and/or modify it under the terms of the GNU * + * Lesser General Public License as published by the * + * Free Software Foundation; either version 2.1 of the * + * License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will * + * be useful, but WITHOUT ANY WARRANTY; without even the * + * implied warranty of MERCHANTABILITY or FITNESS FOR A * + * PARTICULAR PURPOSE. See the GNU Lesser General Public * + * License for more details. * + * * + * You should have received a copy of the GNU Lesser * + * General Public License along with this library; * + * Inc., 59 Temple Place, Suite 330, Boston, * + * MA 02111-1307 USA * + * * + ****************************************************************/ + +var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1; var isMoz = document.implementation && document.implementation.createDocument; var isSafari = ((navigator.userAgent.toLowerCase().indexOf('safari')!=-1)&&(navigator.userAgent.toLowerCase().indexOf('mac')!=-1))?true:false; function curvyCorners() +{ if(typeof(arguments[0]) != "object") throw newCurvyError("First parameter of curvyCorners() must be an object."); if(typeof(arguments[1]) != "object" && typeof(arguments[1]) != "string") throw newCurvyError("Second parameter of curvyCorners() must be an object or a class name."); if(typeof(arguments[1]) == "string") +{ var startIndex = 0; var boxCol = getElementsByClass(arguments[1]);} +else +{ var startIndex = 1; var boxCol = arguments;} +var curvyCornersCol = new Array(); if(arguments[0].validTags) +var validElements = arguments[0].validTags; else +var validElements = ["div"]; for(var i = startIndex, j = boxCol.length; i < j; i++) +{ var currentTag = boxCol[i].tagName.toLowerCase(); if(inArray(validElements, currentTag) !== false) +{ curvyCornersCol[curvyCornersCol.length] = new curvyObject(arguments[0], boxCol[i]);} +} +this.objects = curvyCornersCol; this.applyCornersToAll = function() +{ for(var x = 0, k = this.objects.length; x < k; x++) +{ this.objects[x].applyCorners();} +} +} +function curvyObject() +{ this.box = arguments[1]; this.settings = arguments[0]; this.topContainer = null; this.bottomContainer = null; this.masterCorners = new Array(); this.contentDIV = null; var boxHeight = get_style(this.box, "height", "height"); var boxWidth = get_style(this.box, "width", "width"); var borderWidth = get_style(this.box, "borderTopWidth", "border-top-width"); var borderColour = get_style(this.box, "borderTopColor", "border-top-color"); var boxColour = get_style(this.box, "backgroundColor", "background-color"); var backgroundImage = get_style(this.box, "backgroundImage", "background-image"); var boxPosition = get_style(this.box, "position", "position"); var boxPadding = get_style(this.box, "paddingTop", "padding-top"); this.boxHeight = parseInt(((boxHeight != "" && boxHeight != "auto" && boxHeight.indexOf("%") == -1)? boxHeight.substring(0, boxHeight.indexOf("px")) : this.box.scrollHeight)); this.boxWidth = parseInt(((boxWidth != "" && boxWidth != "auto" && boxWidth.indexOf("%") == -1)? boxWidth.substring(0, boxWidth.indexOf("px")) : this.box.scrollWidth)); this.borderWidth = parseInt(((borderWidth != "" && borderWidth.indexOf("px") !== -1)? borderWidth.slice(0, borderWidth.indexOf("px")) : 0)); this.boxColour = format_colour(boxColour); this.boxPadding = parseInt(((boxPadding != "" && boxPadding.indexOf("px") !== -1)? boxPadding.slice(0, boxPadding.indexOf("px")) : 0)); this.borderColour = format_colour(borderColour); this.borderString = this.borderWidth + "px" + " solid " + this.borderColour; this.backgroundImage = ((backgroundImage != "none")? backgroundImage : ""); this.boxContent = this.box.innerHTML; if(boxPosition != "absolute") this.box.style.position = "relative"; this.box.style.padding = "0px"; if(isIE && boxWidth == "auto" && boxHeight == "auto") this.box.style.width = "100%"; if(this.settings.autoPad == true && this.boxPadding > 0) +this.box.innerHTML = ""; this.applyCorners = function() +{ for(var t = 0; t < 2; t++) +{ switch(t) +{ case 0: +if(this.settings.tl || this.settings.tr) +{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var topMaxRadius = Math.max(this.settings.tl ? this.settings.tl.radius : 0, this.settings.tr ? this.settings.tr.radius : 0); newMainContainer.style.height = topMaxRadius + "px"; newMainContainer.style.top = 0 - topMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.topContainer = this.box.appendChild(newMainContainer);} +break; case 1: +if(this.settings.bl || this.settings.br) +{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var botMaxRadius = Math.max(this.settings.bl ? this.settings.bl.radius : 0, this.settings.br ? this.settings.br.radius : 0); newMainContainer.style.height = botMaxRadius + "px"; newMainContainer.style.bottom = 0 - botMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.bottomContainer = this.box.appendChild(newMainContainer);} +break;} +} +if(this.topContainer) this.box.style.borderTopWidth = "0px"; if(this.bottomContainer) this.box.style.borderBottomWidth = "0px"; var corners = ["tr", "tl", "br", "bl"]; for(var i in corners) +{ if(i > -1 < 4) +{ var cc = corners[i]; if(!this.settings[cc]) +{ if(((cc == "tr" || cc == "tl") && this.topContainer != null) || ((cc == "br" || cc == "bl") && this.bottomContainer != null)) +{ var newCorner = document.createElement("DIV"); newCorner.style.position = "relative"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; if(this.backgroundImage == "") +newCorner.style.backgroundColor = this.boxColour; else +newCorner.style.backgroundImage = this.backgroundImage; switch(cc) +{ case "tl": +newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.tr.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.left = -this.borderWidth + "px"; break; case "tr": +newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.tl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; newCorner.style.left = this.borderWidth + "px"; break; case "bl": +newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.br.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = -this.borderWidth + "px"; newCorner.style.backgroundPosition = "-" + (this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break; case "br": +newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.bl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = this.borderWidth + "px" +newCorner.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break;} +} +} +else +{ if(this.masterCorners[this.settings[cc].radius]) +{ var newCorner = this.masterCorners[this.settings[cc].radius].cloneNode(true);} +else +{ var newCorner = document.createElement("DIV"); newCorner.style.height = this.settings[cc].radius + "px"; newCorner.style.width = this.settings[cc].radius + "px"; newCorner.style.position = "absolute"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; var borderRadius = parseInt(this.settings[cc].radius - this.borderWidth); for(var intx = 0, j = this.settings[cc].radius; intx < j; intx++) +{ if((intx +1) >= borderRadius) +var y1 = -1; else +var y1 = (Math.floor(Math.sqrt(Math.pow(borderRadius, 2) - Math.pow((intx+1), 2))) - 1); if(borderRadius != j) +{ if((intx) >= borderRadius) +var y2 = -1; else +var y2 = Math.ceil(Math.sqrt(Math.pow(borderRadius,2) - Math.pow(intx, 2))); if((intx+1) >= j) +var y3 = -1; else +var y3 = (Math.floor(Math.sqrt(Math.pow(j ,2) - Math.pow((intx+1), 2))) - 1);} +if((intx) >= j) +var y4 = -1; else +var y4 = Math.ceil(Math.sqrt(Math.pow(j ,2) - Math.pow(intx, 2))); if(y1 > -1) this.drawPixel(intx, 0, this.boxColour, 100, (y1+1), newCorner, -1, this.settings[cc].radius); if(borderRadius != j) +{ for(var inty = (y1 + 1); inty < y2; inty++) +{ if(this.settings.antiAlias) +{ if(this.backgroundImage != "") +{ var borderFract = (pixelFraction(intx, inty, borderRadius) * 100); if(borderFract < 30) +{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, 0, this.settings[cc].radius);} +else +{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, -1, this.settings[cc].radius);} +} +else +{ var pixelcolour = BlendColour(this.boxColour, this.borderColour, pixelFraction(intx, inty, borderRadius)); this.drawPixel(intx, inty, pixelcolour, 100, 1, newCorner, 0, this.settings[cc].radius, cc);} +} +} +if(this.settings.antiAlias) +{ if(y3 >= y2) +{ if (y2 == -1) y2 = 0; this.drawPixel(intx, y2, this.borderColour, 100, (y3 - y2 + 1), newCorner, 0, 0);} +} +else +{ if(y3 >= y1) +{ this.drawPixel(intx, (y1 + 1), this.borderColour, 100, (y3 - y1), newCorner, 0, 0);} +} +var outsideColour = this.borderColour;} +else +{ var outsideColour = this.boxColour; var y3 = y1;} +if(this.settings.antiAlias) +{ for(var inty = (y3 + 1); inty < y4; inty++) +{ this.drawPixel(intx, inty, outsideColour, (pixelFraction(intx, inty , j) * 100), 1, newCorner, ((this.borderWidth > 0)? 0 : -1), this.settings[cc].radius);} +} +} +this.masterCorners[this.settings[cc].radius] = newCorner.cloneNode(true);} +if(cc != "br") +{ for(var t = 0, k = newCorner.childNodes.length; t < k; t++) +{ var pixelBar = newCorner.childNodes[t]; var pixelBarTop = parseInt(pixelBar.style.top.substring(0, pixelBar.style.top.indexOf("px"))); var pixelBarLeft = parseInt(pixelBar.style.left.substring(0, pixelBar.style.left.indexOf("px"))); var pixelBarHeight = parseInt(pixelBar.style.height.substring(0, pixelBar.style.height.indexOf("px"))); if(cc == "tl" || cc == "bl"){ pixelBar.style.left = this.settings[cc].radius -pixelBarLeft -1 + "px";} +if(cc == "tr" || cc == "tl"){ pixelBar.style.top = this.settings[cc].radius -pixelBarHeight -pixelBarTop + "px";} +switch(cc) +{ case "tr": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.boxWidth - this.settings[cc].radius + this.borderWidth) + pixelBarLeft) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "tl": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "bl": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs((this.boxHeight + this.settings[cc].radius + pixelBarTop) -this.borderWidth) + "px"; break;} +} +} +} +if(newCorner) +{ switch(cc) +{ case "tl": +if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "tr": +if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "bl": +if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break; case "br": +if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break;} +} +} +} +var radiusDiff = new Array(); radiusDiff["t"] = Math.abs(this.settings.tl.radius - this.settings.tr.radius) +radiusDiff["b"] = Math.abs(this.settings.bl.radius - this.settings.br.radius); for(z in radiusDiff) +{ if(z == "t" || z == "b") +{ if(radiusDiff[z]) +{ var smallerCornerType = ((this.settings[z + "l"].radius < this.settings[z + "r"].radius)? z +"l" : z +"r"); var newFiller = document.createElement("DIV"); newFiller.style.height = radiusDiff[z] + "px"; newFiller.style.width = this.settings[smallerCornerType].radius+ "px" +newFiller.style.position = "absolute"; newFiller.style.fontSize = "1px"; newFiller.style.overflow = "hidden"; newFiller.style.backgroundColor = this.boxColour; switch(smallerCornerType) +{ case "tl": +newFiller.style.bottom = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.topContainer.appendChild(newFiller); break; case "tr": +newFiller.style.bottom = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.topContainer.appendChild(newFiller); break; case "bl": +newFiller.style.top = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.bottomContainer.appendChild(newFiller); break; case "br": +newFiller.style.top = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.bottomContainer.appendChild(newFiller); break;} +} +var newFillerBar = document.createElement("DIV"); newFillerBar.style.position = "relative"; newFillerBar.style.fontSize = "1px"; newFillerBar.style.overflow = "hidden"; newFillerBar.style.backgroundColor = this.boxColour; newFillerBar.style.backgroundImage = this.backgroundImage; switch(z) +{ case "t": +if(this.topContainer) +{ if(this.settings.tl.radius && this.settings.tr.radius) +{ newFillerBar.style.height = topMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.tl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.tr.radius - this.borderWidth + "px"; newFillerBar.style.borderTop = this.borderString; if(this.backgroundImage != "") +newFillerBar.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; this.topContainer.appendChild(newFillerBar);} +this.box.style.backgroundPosition = "0px -" + (topMaxRadius - this.borderWidth) + "px";} +break; case "b": +if(this.bottomContainer) +{ if(this.settings.bl.radius && this.settings.br.radius) +{ newFillerBar.style.height = botMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.bl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.br.radius - this.borderWidth + "px"; newFillerBar.style.borderBottom = this.borderString; if(this.backgroundImage != "") +newFillerBar.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (topMaxRadius + this.borderWidth)) + "px"; this.bottomContainer.appendChild(newFillerBar);} +} +break;} +} +} +if(this.settings.autoPad == true && this.boxPadding > 0) +{ var contentContainer = document.createElement("DIV"); contentContainer.style.position = "relative"; contentContainer.innerHTML = this.boxContent; contentContainer.className = "autoPadDiv"; var topPadding = Math.abs(topMaxRadius - this.boxPadding); var botPadding = Math.abs(botMaxRadius - this.boxPadding); if(topMaxRadius < this.boxPadding) +contentContainer.style.paddingTop = topPadding + "px"; if(botMaxRadius < this.boxPadding) +contentContainer.style.paddingBottom = botMaxRadius + "px"; contentContainer.style.paddingLeft = this.boxPadding + "px"; contentContainer.style.paddingRight = this.boxPadding + "px"; this.contentDIV = this.box.appendChild(contentContainer);} +} +this.drawPixel = function(intx, inty, colour, transAmount, height, newCorner, image, cornerRadius) +{ var pixel = document.createElement("DIV"); pixel.style.height = height + "px"; pixel.style.width = "1px"; pixel.style.position = "absolute"; pixel.style.fontSize = "1px"; pixel.style.overflow = "hidden"; var topMaxRadius = Math.max(this.settings["tr"].radius, this.settings["tl"].radius); if(image == -1 && this.backgroundImage != "") +{ pixel.style.backgroundImage = this.backgroundImage; pixel.style.backgroundPosition = "-" + (this.boxWidth - (cornerRadius - intx) + this.borderWidth) + "px -" + ((this.boxHeight + topMaxRadius + inty) -this.borderWidth) + "px";} +else +{ pixel.style.backgroundColor = colour;} +if (transAmount != 100) +setOpacity(pixel, transAmount); pixel.style.top = inty + "px"; pixel.style.left = intx + "px"; newCorner.appendChild(pixel);} +} +function insertAfter(parent, node, referenceNode) +{ parent.insertBefore(node, referenceNode.nextSibling);} +function BlendColour(Col1, Col2, Col1Fraction) +{ var red1 = parseInt(Col1.substr(1,2),16); var green1 = parseInt(Col1.substr(3,2),16); var blue1 = parseInt(Col1.substr(5,2),16); var red2 = parseInt(Col2.substr(1,2),16); var green2 = parseInt(Col2.substr(3,2),16); var blue2 = parseInt(Col2.substr(5,2),16); if(Col1Fraction > 1 || Col1Fraction < 0) Col1Fraction = 1; var endRed = Math.round((red1 * Col1Fraction) + (red2 * (1 - Col1Fraction))); if(endRed > 255) endRed = 255; if(endRed < 0) endRed = 0; var endGreen = Math.round((green1 * Col1Fraction) + (green2 * (1 - Col1Fraction))); if(endGreen > 255) endGreen = 255; if(endGreen < 0) endGreen = 0; var endBlue = Math.round((blue1 * Col1Fraction) + (blue2 * (1 - Col1Fraction))); if(endBlue > 255) endBlue = 255; if(endBlue < 0) endBlue = 0; return "#" + IntToHex(endRed)+ IntToHex(endGreen)+ IntToHex(endBlue);} +function IntToHex(strNum) +{ base = strNum / 16; rem = strNum % 16; base = base - (rem / 16); baseS = MakeHex(base); remS = MakeHex(rem); return baseS + '' + remS;} +function MakeHex(x) +{ if((x >= 0) && (x <= 9)) +{ return x;} +else +{ switch(x) +{ case 10: return "A"; case 11: return "B"; case 12: return "C"; case 13: return "D"; case 14: return "E"; case 15: return "F";} +} +} +function pixelFraction(x, y, r) +{ var pixelfraction = 0; var xvalues = new Array(1); var yvalues = new Array(1); var point = 0; var whatsides = ""; var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x,2))); if ((intersect >= y) && (intersect < (y+1))) +{ whatsides = "Left"; xvalues[point] = 0; yvalues[point] = intersect - y; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y+1,2))); if ((intersect >= x) && (intersect < (x+1))) +{ whatsides = whatsides + "Top"; xvalues[point] = intersect - x; yvalues[point] = 1; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x+1,2))); if ((intersect >= y) && (intersect < (y+1))) +{ whatsides = whatsides + "Right"; xvalues[point] = 1; yvalues[point] = intersect - y; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y,2))); if ((intersect >= x) && (intersect < (x+1))) +{ whatsides = whatsides + "Bottom"; xvalues[point] = intersect - x; yvalues[point] = 0;} +switch (whatsides) +{ case "LeftRight": +pixelfraction = Math.min(yvalues[0],yvalues[1]) + ((Math.max(yvalues[0],yvalues[1]) - Math.min(yvalues[0],yvalues[1]))/2); break; case "TopRight": +pixelfraction = 1-(((1-xvalues[0])*(1-yvalues[1]))/2); break; case "TopBottom": +pixelfraction = Math.min(xvalues[0],xvalues[1]) + ((Math.max(xvalues[0],xvalues[1]) - Math.min(xvalues[0],xvalues[1]))/2); break; case "LeftBottom": +pixelfraction = (yvalues[0]*xvalues[1])/2; break; default: +pixelfraction = 1;} +return pixelfraction;} +function rgb2Hex(rgbColour) +{ try{ var rgbArray = rgb2Array(rgbColour); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); var hexColour = "#" + IntToHex(red) + IntToHex(green) + IntToHex(blue);} +catch(e){ alert("There was an error converting the RGB value to Hexadecimal in function rgb2Hex");} +return hexColour;} +function rgb2Array(rgbColour) +{ var rgbValues = rgbColour.substring(4, rgbColour.indexOf(")")); var rgbArray = rgbValues.split(", "); return rgbArray;} +function setOpacity(obj, opacity) +{ opacity = (opacity == 100)?99.999:opacity; if(isSafari && obj.tagName != "IFRAME") +{ var rgbArray = rgb2Array(obj.style.backgroundColor); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); obj.style.backgroundColor = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity/100 + ")";} +else if(typeof(obj.style.opacity) != "undefined") +{ obj.style.opacity = opacity/100;} +else if(typeof(obj.style.MozOpacity) != "undefined") +{ obj.style.MozOpacity = opacity/100;} +else if(typeof(obj.style.filter) != "undefined") +{ obj.style.filter = "alpha(opacity:" + opacity + ")";} +else if(typeof(obj.style.KHTMLOpacity) != "undefined") +{ obj.style.KHTMLOpacity = opacity/100;} +} +function inArray(array, value) +{ for(var i = 0; i < array.length; i++){ if (array[i] === value) return i;} +return false;} +function inArrayKey(array, value) +{ for(key in array){ if(key === value) return true;} +return false;} +function addEvent(elm, evType, fn, useCapture) { if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true;} +else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r;} +else { elm['on' + evType] = fn;} +} +function removeEvent(obj, evType, fn, useCapture){ if (obj.removeEventListener){ obj.removeEventListener(evType, fn, useCapture); return true;} else if (obj.detachEvent){ var r = obj.detachEvent("on"+evType, fn); return r;} else { alert("Handler could not be removed");} +} +function format_colour(colour) +{ var returnColour = "#ffffff"; if(colour != "" && colour != "transparent") +{ if(colour.substr(0, 3) == "rgb") +{ returnColour = rgb2Hex(colour);} +else if(colour.length == 4) +{ returnColour = "#" + colour.substring(1, 2) + colour.substring(1, 2) + colour.substring(2, 3) + colour.substring(2, 3) + colour.substring(3, 4) + colour.substring(3, 4);} +else +{ returnColour = colour;} +} +return returnColour;} +function get_style(obj, property, propertyNS) +{ try +{ if(obj.currentStyle) +{ var returnVal = eval("obj.currentStyle." + property);} +else +{ if(isSafari && obj.style.display == "none") +{ obj.style.display = ""; var wasHidden = true;} +var returnVal = document.defaultView.getComputedStyle(obj, '').getPropertyValue(propertyNS); if(isSafari && wasHidden) +{ obj.style.display = "none";} +} +} +catch(e) +{ } +return returnVal;} +function getElementsByClass(searchClass, node, tag) +{ var classElements = new Array(); if(node == null) +node = document; if(tag == null) +tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)"); for (i = 0, j = 0; i < elsLen; i++) +{ if(pattern.test(els[i].className)) +{ classElements[j] = els[i]; j++;} +} +return classElements;} +function newCurvyError(errorMessage) +{ return new Error("curvyCorners Error:\n" + errorMessage) +} diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/stylesheets/screen.css b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/stylesheets/screen.css new file mode 100644 index 0000000..2c84cd0 --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/stylesheets/screen.css @@ -0,0 +1,138 @@ +body { + background-color: #E1D1F1; + font-family: "Georgia", sans-serif; + font-size: 16px; + line-height: 1.6em; + padding: 1.6em 0 0 0; + color: #333; +} +h1, h2, h3, h4, h5, h6 { + color: #444; +} +h1 { + font-family: sans-serif; + font-weight: normal; + font-size: 4em; + line-height: 0.8em; + letter-spacing: -0.1ex; + margin: 5px; +} +li { + padding: 0; + margin: 0; + list-style-type: square; +} +a { + color: #5E5AFF; + background-color: #DAC; + font-weight: normal; + text-decoration: underline; +} +blockquote { + font-size: 90%; + font-style: italic; + border-left: 1px solid #111; + padding-left: 1em; +} +.caps { + font-size: 80%; +} + +#main { + width: 45em; + padding: 0; + margin: 0 auto; +} +.coda { + text-align: right; + color: #77f; + font-size: smaller; +} + +table { + font-size: 90%; + line-height: 1.4em; + color: #ff8; + background-color: #111; + padding: 2px 10px 2px 10px; + border-style: dashed; +} + +th { + color: #fff; +} + +td { + padding: 2px 10px 2px 10px; +} + +.success { + color: #0CC52B; +} + +.failed { + color: #E90A1B; +} + +.unknown { + color: #995000; +} +pre, code { + font-family: monospace; + font-size: 90%; + line-height: 1.4em; + color: #ff8; + background-color: #111; + padding: 2px 10px 2px 10px; +} +.comment { color: #aaa; font-style: italic; } +.keyword { color: #eff; font-weight: bold; } +.punct { color: #eee; font-weight: bold; } +.symbol { color: #0bb; } +.string { color: #6b4; } +.ident { color: #ff8; } +.constant { color: #66f; } +.regex { color: #ec6; } +.number { color: #F99; } +.expr { color: #227; } + +#version { + float: right; + text-align: right; + font-family: sans-serif; + font-weight: normal; + background-color: #B3ABFF; + color: #141331; + padding: 15px 20px 10px 20px; + margin: 0 auto; + margin-top: 15px; + border: 3px solid #141331; +} + +#version .numbers { + display: block; + font-size: 4em; + line-height: 0.8em; + letter-spacing: -0.1ex; + margin-bottom: 15px; +} + +#version p { + text-decoration: none; + color: #141331; + background-color: #B3ABFF; + margin: 0; + padding: 0; +} + +#version a { + text-decoration: none; + color: #141331; + background-color: #B3ABFF; +} + +.clickable { + cursor: pointer; + cursor: hand; +} + diff --git a/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/template.html.erb b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/template.html.erb new file mode 100644 index 0000000..58def9f --- /dev/null +++ b/agilelamp-driver/pkg/agilelamp-driver-0.1.0/website/template.html.erb @@ -0,0 +1,48 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <link rel="stylesheet" href="stylesheets/screen.css" type="text/css" media="screen" /> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <title> + <%= title %> + </title> + <script src="javascripts/rounded_corners_lite.inc.js" type="text/javascript"></script> +<style> + +</style> + <script type="text/javascript"> + window.onload = function() { + settings = { + tl: { radius: 10 }, + tr: { radius: 10 }, + bl: { radius: 10 }, + br: { radius: 10 }, + antiAlias: true, + autoPad: true, + validTags: ["div"] + } + var versionBox = new curvyCorners(settings, document.getElementById("version")); + versionBox.applyCornersToAll(); + } + </script> +</head> +<body> +<div id="main"> + + <h1><%= title %></h1> + <div id="version" class="clickable" onclick='document.location = "<%= download %>"; return false'> + <p>Get Version</p> + <a href="<%= download %>" class="numbers"><%= version %></a> + </div> + <%= body %> + <p class="coda"> + <a href="[email protected]">Joseph Method</a>, <%= modified.pretty %><br> + Theme extended from <a href="http://rb2js.rubyforge.org/">Paul Battley</a> + </p> +</div> + +<!-- insert site tracking codes here, like Google Urchin --> + +</body> +</html> diff --git a/agilelamp-driver/script/console b/agilelamp-driver/script/console new file mode 100755 index 0000000..b037260 --- /dev/null +++ b/agilelamp-driver/script/console @@ -0,0 +1,10 @@ +#!/usr/bin/env ruby +# File: script/console +irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb' + +libs = " -r irb/completion" +# Perhaps use a console_lib to store any extra methods I may want available in the cosole +# libs << " -r #{File.dirname(__FILE__) + '/../lib/console_lib/console_logger.rb'}" +libs << " -r #{File.dirname(__FILE__) + '/../lib/agilelamp-driver.rb'}" +puts "Loading agilelamp-driver gem" +exec "#{irb} #{libs} --simple-prompt" \ No newline at end of file diff --git a/agilelamp-driver/script/destroy b/agilelamp-driver/script/destroy new file mode 100755 index 0000000..e48464d --- /dev/null +++ b/agilelamp-driver/script/destroy @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/destroy' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Destroy.new.run(ARGV) diff --git a/agilelamp-driver/script/generate b/agilelamp-driver/script/generate new file mode 100755 index 0000000..c27f655 --- /dev/null +++ b/agilelamp-driver/script/generate @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/generate' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Generate.new.run(ARGV) diff --git a/agilelamp-driver/script/txt2html b/agilelamp-driver/script/txt2html new file mode 100755 index 0000000..7d5bfad --- /dev/null +++ b/agilelamp-driver/script/txt2html @@ -0,0 +1,82 @@ +#!/usr/bin/env ruby + +GEM_NAME = 'agilelamp-driver' # what ppl will type to install your gem +RUBYFORGE_PROJECT = 'agilelamp-driver' + +require 'rubygems' +begin + require 'newgem' + require 'rubyforge' +rescue LoadError + puts "\n\nGenerating the website requires the newgem RubyGem" + puts "Install: gem install newgem\n\n" + exit(1) +end +require 'redcloth' +require 'syntax/convertors/html' +require 'erb' +require File.dirname(__FILE__) + "/../lib/#{GEM_NAME}/version.rb" + +version = Agilelamp-driver::VERSION::STRING +download = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" + +def rubyforge_project_id + RubyForge.new.autoconfig["group_ids"][RUBYFORGE_PROJECT] +end + +class Fixnum + def ordinal + # teens + return 'th' if (10..19).include?(self % 100) + # others + case self % 10 + when 1: return 'st' + when 2: return 'nd' + when 3: return 'rd' + else return 'th' + end + end +end + +class Time + def pretty + return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" + end +end + +def convert_syntax(syntax, source) + return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^<pre>|</pre>$!,'') +end + +if ARGV.length >= 1 + src, template = ARGV + template ||= File.join(File.dirname(__FILE__), '/../website/template.html.erb') +else + puts("Usage: #{File.split($0).last} source.txt [template.html.erb] > output.html") + exit! +end + +template = ERB.new(File.open(template).read) + +title = nil +body = nil +File.open(src) do |fsrc| + title_text = fsrc.readline + body_text_template = fsrc.read + body_text = ERB.new(body_text_template).result(binding) + syntax_items = [] + body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)</\1>!m){ + ident = syntax_items.length + element, syntax, source = $1, $2, $3 + syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}</#{element}>" + "syntax-temp-#{ident}" + } + title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip + body = RedCloth.new(body_text).to_html + body.gsub!(%r!(?:<pre><code>)?syntax-temp-(\d+)(?:</code></pre>)?!){ syntax_items[$1.to_i] } +end +stat = File.stat(src) +created = stat.ctime +modified = stat.mtime + +$stdout << template.result(binding) diff --git a/agilelamp-driver/setup.rb b/agilelamp-driver/setup.rb new file mode 100644 index 0000000..424a5f3 --- /dev/null +++ b/agilelamp-driver/setup.rb @@ -0,0 +1,1585 @@ +# +# setup.rb +# +# Copyright (c) 2000-2005 Minero Aoki +# +# This program is free software. +# You can distribute/modify this program under the terms of +# the GNU LGPL, Lesser General Public License version 2.1. +# + +unless Enumerable.method_defined?(:map) # Ruby 1.4.6 + module Enumerable + alias map collect + end +end + +unless File.respond_to?(:read) # Ruby 1.6 + def File.read(fname) + open(fname) {|f| + return f.read + } + end +end + +unless Errno.const_defined?(:ENOTEMPTY) # Windows? + module Errno + class ENOTEMPTY + # We do not raise this exception, implementation is not needed. + end + end +end + +def File.binread(fname) + open(fname, 'rb') {|f| + return f.read + } +end + +# for corrupted Windows' stat(2) +def File.dir?(path) + File.directory?((path[-1,1] == '/') ? path : path + '/') +end + + +class ConfigTable + + include Enumerable + + def initialize(rbconfig) + @rbconfig = rbconfig + @items = [] + @table = {} + # options + @install_prefix = nil + @config_opt = nil + @verbose = true + @no_harm = false + end + + attr_accessor :install_prefix + attr_accessor :config_opt + + attr_writer :verbose + + def verbose? + @verbose + end + + attr_writer :no_harm + + def no_harm? + @no_harm + end + + def [](key) + lookup(key).resolve(self) + end + + def []=(key, val) + lookup(key).set val + end + + def names + @items.map {|i| i.name } + end + + def each(&block) + @items.each(&block) + end + + def key?(name) + @table.key?(name) + end + + def lookup(name) + @table[name] or setup_rb_error "no such config item: #{name}" + end + + def add(item) + @items.push item + @table[item.name] = item + end + + def remove(name) + item = lookup(name) + @items.delete_if {|i| i.name == name } + @table.delete_if {|name, i| i.name == name } + item + end + + def load_script(path, inst = nil) + if File.file?(path) + MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path + end + end + + def savefile + '.config' + end + + def load_savefile + begin + File.foreach(savefile()) do |line| + k, v = *line.split(/=/, 2) + self[k] = v.strip + end + rescue Errno::ENOENT + setup_rb_error $!.message + "\n#{File.basename($0)} config first" + end + end + + def save + @items.each {|i| i.value } + File.open(savefile(), 'w') {|f| + @items.each do |i| + f.printf "%s=%s\n", i.name, i.value if i.value? and i.value + end + } + end + + def load_standard_entries + standard_entries(@rbconfig).each do |ent| + add ent + end + end + + def standard_entries(rbconfig) + c = rbconfig + + rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) + + major = c['MAJOR'].to_i + minor = c['MINOR'].to_i + teeny = c['TEENY'].to_i + version = "#{major}.#{minor}" + + # ruby ver. >= 1.4.4? + newpath_p = ((major >= 2) or + ((major == 1) and + ((minor >= 5) or + ((minor == 4) and (teeny >= 4))))) + + if c['rubylibdir'] + # V > 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = c['rubylibdir'] + librubyverarch = c['archdir'] + siteruby = c['sitedir'] + siterubyver = c['sitelibdir'] + siterubyverarch = c['sitearchdir'] + elsif newpath_p + # 1.4.4 <= V <= 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = c['sitedir'] + siterubyver = "$siteruby/#{version}" + siterubyverarch = "$siterubyver/#{c['arch']}" + else + # V < 1.4.4 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" + siterubyver = siteruby + siterubyverarch = "$siterubyver/#{c['arch']}" + end + parameterize = lambda {|path| + path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') + } + + if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } + makeprog = arg.sub(/'/, '').split(/=/, 2)[1] + else + makeprog = 'make' + end + + [ + ExecItem.new('installdirs', 'std/site/home', + 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ + {|val, table| + case val + when 'std' + table['rbdir'] = '$librubyver' + table['sodir'] = '$librubyverarch' + when 'site' + table['rbdir'] = '$siterubyver' + table['sodir'] = '$siterubyverarch' + when 'home' + setup_rb_error '$HOME was not set' unless ENV['HOME'] + table['prefix'] = ENV['HOME'] + table['rbdir'] = '$libdir/ruby' + table['sodir'] = '$libdir/ruby' + end + }, + PathItem.new('prefix', 'path', c['prefix'], + 'path prefix of target environment'), + PathItem.new('bindir', 'path', parameterize.call(c['bindir']), + 'the directory for commands'), + PathItem.new('libdir', 'path', parameterize.call(c['libdir']), + 'the directory for libraries'), + PathItem.new('datadir', 'path', parameterize.call(c['datadir']), + 'the directory for shared data'), + PathItem.new('mandir', 'path', parameterize.call(c['mandir']), + 'the directory for man pages'), + PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), + 'the directory for system configuration files'), + PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), + 'the directory for local state data'), + PathItem.new('libruby', 'path', libruby, + 'the directory for ruby libraries'), + PathItem.new('librubyver', 'path', librubyver, + 'the directory for standard ruby libraries'), + PathItem.new('librubyverarch', 'path', librubyverarch, + 'the directory for standard ruby extensions'), + PathItem.new('siteruby', 'path', siteruby, + 'the directory for version-independent aux ruby libraries'), + PathItem.new('siterubyver', 'path', siterubyver, + 'the directory for aux ruby libraries'), + PathItem.new('siterubyverarch', 'path', siterubyverarch, + 'the directory for aux ruby binaries'), + PathItem.new('rbdir', 'path', '$siterubyver', + 'the directory for ruby scripts'), + PathItem.new('sodir', 'path', '$siterubyverarch', + 'the directory for ruby extentions'), + PathItem.new('rubypath', 'path', rubypath, + 'the path to set to #! line'), + ProgramItem.new('rubyprog', 'name', rubypath, + 'the ruby program using for installation'), + ProgramItem.new('makeprog', 'name', makeprog, + 'the make program to compile ruby extentions'), + SelectItem.new('shebang', 'all/ruby/never', 'ruby', + 'shebang line (#!) editing mode'), + BoolItem.new('without-ext', 'yes/no', 'no', + 'does not compile/install ruby extentions') + ] + end + private :standard_entries + + def load_multipackage_entries + multipackage_entries().each do |ent| + add ent + end + end + + def multipackage_entries + [ + PackageSelectionItem.new('with', 'name,name...', '', 'ALL', + 'package names that you want to install'), + PackageSelectionItem.new('without', 'name,name...', '', 'NONE', + 'package names that you do not want to install') + ] + end + private :multipackage_entries + + ALIASES = { + 'std-ruby' => 'librubyver', + 'stdruby' => 'librubyver', + 'rubylibdir' => 'librubyver', + 'archdir' => 'librubyverarch', + 'site-ruby-common' => 'siteruby', # For backward compatibility + 'site-ruby' => 'siterubyver', # For backward compatibility + 'bin-dir' => 'bindir', + 'bin-dir' => 'bindir', + 'rb-dir' => 'rbdir', + 'so-dir' => 'sodir', + 'data-dir' => 'datadir', + 'ruby-path' => 'rubypath', + 'ruby-prog' => 'rubyprog', + 'ruby' => 'rubyprog', + 'make-prog' => 'makeprog', + 'make' => 'makeprog' + } + + def fixup + ALIASES.each do |ali, name| + @table[ali] = @table[name] + end + @items.freeze + @table.freeze + @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ + end + + def parse_opt(opt) + m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" + m.to_a[1,2] + end + + def dllext + @rbconfig['DLEXT'] + end + + def value_config?(name) + lookup(name).value? + end + + class Item + def initialize(name, template, default, desc) + @name = name.freeze + @template = template + @value = default + @default = default + @description = desc + end + + attr_reader :name + attr_reader :description + + attr_accessor :default + alias help_default default + + def help_opt + "--#{@name}=#{@template}" + end + + def value? + true + end + + def value + @value + end + + def resolve(table) + @value.gsub(%r<\$([^/]+)>) { table[$1] } + end + + def set(val) + @value = check(val) + end + + private + + def check(val) + setup_rb_error "config: --#{name} requires argument" unless val + val + end + end + + class BoolItem < Item + def config_type + 'bool' + end + + def help_opt + "--#{@name}" + end + + private + + def check(val) + return 'yes' unless val + case val + when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' + when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' + else + setup_rb_error "config: --#{@name} accepts only yes/no for argument" + end + end + end + + class PathItem < Item + def config_type + 'path' + end + + private + + def check(path) + setup_rb_error "config: --#{@name} requires argument" unless path + path[0,1] == '$' ? path : File.expand_path(path) + end + end + + class ProgramItem < Item + def config_type + 'program' + end + end + + class SelectItem < Item + def initialize(name, selection, default, desc) + super + @ok = selection.split('/') + end + + def config_type + 'select' + end + + private + + def check(val) + unless @ok.include?(val.strip) + setup_rb_error "config: use --#{@name}=#{@template} (#{val})" + end + val.strip + end + end + + class ExecItem < Item + def initialize(name, selection, desc, &block) + super name, selection, nil, desc + @ok = selection.split('/') + @action = block + end + + def config_type + 'exec' + end + + def value? + false + end + + def resolve(table) + setup_rb_error "$#{name()} wrongly used as option value" + end + + undef set + + def evaluate(val, table) + v = val.strip.downcase + unless @ok.include?(v) + setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" + end + @action.call v, table + end + end + + class PackageSelectionItem < Item + def initialize(name, template, default, help_default, desc) + super name, template, default, desc + @help_default = help_default + end + + attr_reader :help_default + + def config_type + 'package' + end + + private + + def check(val) + unless File.dir?("packages/#{val}") + setup_rb_error "config: no such package: #{val}" + end + val + end + end + + class MetaConfigEnvironment + def initialize(config, installer) + @config = config + @installer = installer + end + + def config_names + @config.names + end + + def config?(name) + @config.key?(name) + end + + def bool_config?(name) + @config.lookup(name).config_type == 'bool' + end + + def path_config?(name) + @config.lookup(name).config_type == 'path' + end + + def value_config?(name) + @config.lookup(name).config_type != 'exec' + end + + def add_config(item) + @config.add item + end + + def add_bool_config(name, default, desc) + @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) + end + + def add_path_config(name, default, desc) + @config.add PathItem.new(name, 'path', default, desc) + end + + def set_config_default(name, default) + @config.lookup(name).default = default + end + + def remove_config(name) + @config.remove(name) + end + + # For only multipackage + def packages + raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer + @installer.packages + end + + # For only multipackage + def declare_packages(list) + raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer + @installer.packages = list + end + end + +end # class ConfigTable + + +# This module requires: #verbose?, #no_harm? +module FileOperations + + def mkdir_p(dirname, prefix = nil) + dirname = prefix + File.expand_path(dirname) if prefix + $stderr.puts "mkdir -p #{dirname}" if verbose? + return if no_harm? + + # Does not check '/', it's too abnormal. + dirs = File.expand_path(dirname).split(%r<(?=/)>) + if /\A[a-z]:\z/i =~ dirs[0] + disk = dirs.shift + dirs[0] = disk + dirs[0] + end + dirs.each_index do |idx| + path = dirs[0..idx].join('') + Dir.mkdir path unless File.dir?(path) + end + end + + def rm_f(path) + $stderr.puts "rm -f #{path}" if verbose? + return if no_harm? + force_remove_file path + end + + def rm_rf(path) + $stderr.puts "rm -rf #{path}" if verbose? + return if no_harm? + remove_tree path + end + + def remove_tree(path) + if File.symlink?(path) + remove_file path + elsif File.dir?(path) + remove_tree0 path + else + force_remove_file path + end + end + + def remove_tree0(path) + Dir.foreach(path) do |ent| + next if ent == '.' + next if ent == '..' + entpath = "#{path}/#{ent}" + if File.symlink?(entpath) + remove_file entpath + elsif File.dir?(entpath) + remove_tree0 entpath + else + force_remove_file entpath + end + end + begin + Dir.rmdir path + rescue Errno::ENOTEMPTY + # directory may not be empty + end + end + + def move_file(src, dest) + force_remove_file dest + begin + File.rename src, dest + rescue + File.open(dest, 'wb') {|f| + f.write File.binread(src) + } + File.chmod File.stat(src).mode, dest + File.unlink src + end + end + + def force_remove_file(path) + begin + remove_file path + rescue + end + end + + def remove_file(path) + File.chmod 0777, path + File.unlink path + end + + def install(from, dest, mode, prefix = nil) + $stderr.puts "install #{from} #{dest}" if verbose? + return if no_harm? + + realdest = prefix ? prefix + File.expand_path(dest) : dest + realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) + str = File.binread(from) + if diff?(str, realdest) + verbose_off { + rm_f realdest if File.exist?(realdest) + } + File.open(realdest, 'wb') {|f| + f.write str + } + File.chmod mode, realdest + + File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| + if prefix + f.puts realdest.sub(prefix, '') + else + f.puts realdest + end + } + end + end + + def diff?(new_content, path) + return true unless File.exist?(path) + new_content != File.binread(path) + end + + def command(*args) + $stderr.puts args.join(' ') if verbose? + system(*args) or raise RuntimeError, + "system(#{args.map{|a| a.inspect }.join(' ')}) failed" + end + + def ruby(*args) + command config('rubyprog'), *args + end + + def make(task = nil) + command(*[config('makeprog'), task].compact) + end + + def extdir?(dir) + File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") + end + + def files_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.file?("#{dir}/#{ent}") } + } + end + + DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) + + def directories_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT + } + end + +end + + +# This module requires: #srcdir_root, #objdir_root, #relpath +module HookScriptAPI + + def get_config(key) + @config[key] + end + + alias config get_config + + # obsolete: use metaconfig to change configuration + def set_config(key, val) + @config[key] = val + end + + # + # srcdir/objdir (works only in the package directory) + # + + def curr_srcdir + "#{srcdir_root()}/#{relpath()}" + end + + def curr_objdir + "#{objdir_root()}/#{relpath()}" + end + + def srcfile(path) + "#{curr_srcdir()}/#{path}" + end + + def srcexist?(path) + File.exist?(srcfile(path)) + end + + def srcdirectory?(path) + File.dir?(srcfile(path)) + end + + def srcfile?(path) + File.file?(srcfile(path)) + end + + def srcentries(path = '.') + Dir.open("#{curr_srcdir()}/#{path}") {|d| + return d.to_a - %w(. ..) + } + end + + def srcfiles(path = '.') + srcentries(path).select {|fname| + File.file?(File.join(curr_srcdir(), path, fname)) + } + end + + def srcdirectories(path = '.') + srcentries(path).select {|fname| + File.dir?(File.join(curr_srcdir(), path, fname)) + } + end + +end + + +class ToplevelInstaller + + Version = '3.4.1' + Copyright = 'Copyright (c) 2000-2005 Minero Aoki' + + TASKS = [ + [ 'all', 'do config, setup, then install' ], + [ 'config', 'saves your configurations' ], + [ 'show', 'shows current configuration' ], + [ 'setup', 'compiles ruby extentions and others' ], + [ 'install', 'installs files' ], + [ 'test', 'run all tests in test/' ], + [ 'clean', "does `make clean' for each extention" ], + [ 'distclean',"does `make distclean' for each extention" ] + ] + + def ToplevelInstaller.invoke + config = ConfigTable.new(load_rbconfig()) + config.load_standard_entries + config.load_multipackage_entries if multipackage? + config.fixup + klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) + klass.new(File.dirname($0), config).invoke + end + + def ToplevelInstaller.multipackage? + File.dir?(File.dirname($0) + '/packages') + end + + def ToplevelInstaller.load_rbconfig + if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } + ARGV.delete(arg) + load File.expand_path(arg.split(/=/, 2)[1]) + $".push 'rbconfig.rb' + else + require 'rbconfig' + end + ::Config::CONFIG + end + + def initialize(ardir_root, config) + @ardir = File.expand_path(ardir_root) + @config = config + # cache + @valid_task_re = nil + end + + def config(key) + @config[key] + end + + def inspect + "#<#{self.class} #{__id__()}>" + end + + def invoke + run_metaconfigs + case task = parsearg_global() + when nil, 'all' + parsearg_config + init_installers + exec_config + exec_setup + exec_install + else + case task + when 'config', 'test' + ; + when 'clean', 'distclean' + @config.load_savefile if File.exist?(@config.savefile) + else + @config.load_savefile + end + __send__ "parsearg_#{task}" + init_installers + __send__ "exec_#{task}" + end + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig" + end + + def init_installers + @installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + # + # Hook Script API bases + # + + def srcdir_root + @ardir + end + + def objdir_root + '.' + end + + def relpath + '.' + end + + # + # Option Parsing + # + + def parsearg_global + while arg = ARGV.shift + case arg + when /\A\w+\z/ + setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) + return arg + when '-q', '--quiet' + @config.verbose = false + when '--verbose' + @config.verbose = true + when '--help' + print_usage $stdout + exit 0 + when '--version' + puts "#{File.basename($0)} version #{Version}" + exit 0 + when '--copyright' + puts Copyright + exit 0 + else + setup_rb_error "unknown global option '#{arg}'" + end + end + nil + end + + def valid_task?(t) + valid_task_re() =~ t + end + + def valid_task_re + @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ + end + + def parsearg_no_options + unless ARGV.empty? + task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) + setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" + end + end + + alias parsearg_show parsearg_no_options + alias parsearg_setup parsearg_no_options + alias parsearg_test parsearg_no_options + alias parsearg_clean parsearg_no_options + alias parsearg_distclean parsearg_no_options + + def parsearg_config + evalopt = [] + set = [] + @config.config_opt = [] + while i = ARGV.shift + if /\A--?\z/ =~ i + @config.config_opt = ARGV.dup + break + end + name, value = *@config.parse_opt(i) + if @config.value_config?(name) + @config[name] = value + else + evalopt.push [name, value] + end + set.push name + end + evalopt.each do |name, value| + @config.lookup(name).evaluate value, @config + end + # Check if configuration is valid + set.each do |n| + @config[n] if @config.value_config?(n) + end + end + + def parsearg_install + @config.no_harm = false + @config.install_prefix = '' + while a = ARGV.shift + case a + when '--no-harm' + @config.no_harm = true + when /\A--prefix=/ + path = a.split(/=/, 2)[1] + path = File.expand_path(path) unless path[0,1] == '/' + @config.install_prefix = path + else + setup_rb_error "install: unknown option #{a}" + end + end + end + + def print_usage(out) + out.puts 'Typical Installation Procedure:' + out.puts " $ ruby #{File.basename $0} config" + out.puts " $ ruby #{File.basename $0} setup" + out.puts " # ruby #{File.basename $0} install (may require root privilege)" + out.puts + out.puts 'Detailed Usage:' + out.puts " ruby #{File.basename $0} <global option>" + out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]" + + fmt = " %-24s %s\n" + out.puts + out.puts 'Global options:' + out.printf fmt, '-q,--quiet', 'suppress message outputs' + out.printf fmt, ' --verbose', 'output messages verbosely' + out.printf fmt, ' --help', 'print this message' + out.printf fmt, ' --version', 'print version and quit' + out.printf fmt, ' --copyright', 'print copyright and quit' + out.puts + out.puts 'Tasks:' + TASKS.each do |name, desc| + out.printf fmt, name, desc + end + + fmt = " %-24s %s [%s]\n" + out.puts + out.puts 'Options for CONFIG or ALL:' + @config.each do |item| + out.printf fmt, item.help_opt, item.description, item.help_default + end + out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" + out.puts + out.puts 'Options for INSTALL:' + out.printf fmt, '--no-harm', 'only display what to do if given', 'off' + out.printf fmt, '--prefix=path', 'install path prefix', '' + out.puts + end + + # + # Task Handlers + # + + def exec_config + @installer.exec_config + @config.save # must be final + end + + def exec_setup + @installer.exec_setup + end + + def exec_install + @installer.exec_install + end + + def exec_test + @installer.exec_test + end + + def exec_show + @config.each do |i| + printf "%-20s %s\n", i.name, i.value if i.value? + end + end + + def exec_clean + @installer.exec_clean + end + + def exec_distclean + @installer.exec_distclean + end + +end # class ToplevelInstaller + + +class ToplevelInstallerMulti < ToplevelInstaller + + include FileOperations + + def initialize(ardir_root, config) + super + @packages = directories_of("#{@ardir}/packages") + raise 'no package exists' if @packages.empty? + @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig", self + @packages.each do |name| + @config.load_script "#{@ardir}/packages/#{name}/metaconfig" + end + end + + attr_reader :packages + + def packages=(list) + raise 'package list is empty' if list.empty? + list.each do |name| + raise "directory packages/#{name} does not exist"\ + unless File.dir?("#{@ardir}/packages/#{name}") + end + @packages = list + end + + def init_installers + @installers = {} + @packages.each do |pack| + @installers[pack] = Installer.new(@config, + "#{@ardir}/packages/#{pack}", + "packages/#{pack}") + end + with = extract_selection(config('with')) + without = extract_selection(config('without')) + @selected = @installers.keys.select {|name| + (with.empty? or with.include?(name)) \ + and not without.include?(name) + } + end + + def extract_selection(list) + a = list.split(/,/) + a.each do |name| + setup_rb_error "no such package: #{name}" unless @installers.key?(name) + end + a + end + + def print_usage(f) + super + f.puts 'Inluded packages:' + f.puts ' ' + @packages.sort.join(' ') + f.puts + end + + # + # Task Handlers + # + + def exec_config + run_hook 'pre-config' + each_selected_installers {|inst| inst.exec_config } + run_hook 'post-config' + @config.save # must be final + end + + def exec_setup + run_hook 'pre-setup' + each_selected_installers {|inst| inst.exec_setup } + run_hook 'post-setup' + end + + def exec_install + run_hook 'pre-install' + each_selected_installers {|inst| inst.exec_install } + run_hook 'post-install' + end + + def exec_test + run_hook 'pre-test' + each_selected_installers {|inst| inst.exec_test } + run_hook 'post-test' + end + + def exec_clean + rm_f @config.savefile + run_hook 'pre-clean' + each_selected_installers {|inst| inst.exec_clean } + run_hook 'post-clean' + end + + def exec_distclean + rm_f @config.savefile + run_hook 'pre-distclean' + each_selected_installers {|inst| inst.exec_distclean } + run_hook 'post-distclean' + end + + # + # lib + # + + def each_selected_installers + Dir.mkdir 'packages' unless File.dir?('packages') + @selected.each do |pack| + $stderr.puts "Processing the package `#{pack}' ..." if verbose? + Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") + Dir.chdir "packages/#{pack}" + yield @installers[pack] + Dir.chdir '../..' + end + end + + def run_hook(id) + @root_installer.run_hook id + end + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + +end # class ToplevelInstallerMulti + + +class Installer + + FILETYPES = %w( bin lib ext data conf man ) + + include FileOperations + include HookScriptAPI + + def initialize(config, srcroot, objroot) + @config = config + @srcdir = File.expand_path(srcroot) + @objdir = File.expand_path(objroot) + @currdir = '.' + end + + def inspect + "#<#{self.class} #{File.basename(@srcdir)}>" + end + + def noop(rel) + end + + # + # Hook Script API base methods + # + + def srcdir_root + @srcdir + end + + def objdir_root + @objdir + end + + def relpath + @currdir + end + + # + # Config Access + # + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + + def verbose_off + begin + save, @config.verbose = @config.verbose?, false + yield + ensure + @config.verbose = save + end + end + + # + # TASK config + # + + def exec_config + exec_task_traverse 'config' + end + + alias config_dir_bin noop + alias config_dir_lib noop + + def config_dir_ext(rel) + extconf if extdir?(curr_srcdir()) + end + + alias config_dir_data noop + alias config_dir_conf noop + alias config_dir_man noop + + def extconf + ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt + end + + # + # TASK setup + # + + def exec_setup + exec_task_traverse 'setup' + end + + def setup_dir_bin(rel) + files_of(curr_srcdir()).each do |fname| + update_shebang_line "#{curr_srcdir()}/#{fname}" + end + end + + alias setup_dir_lib noop + + def setup_dir_ext(rel) + make if extdir?(curr_srcdir()) + end + + alias setup_dir_data noop + alias setup_dir_conf noop + alias setup_dir_man noop + + def update_shebang_line(path) + return if no_harm? + return if config('shebang') == 'never' + old = Shebang.load(path) + if old + $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 + new = new_shebang(old) + return if new.to_s == old.to_s + else + return unless config('shebang') == 'all' + new = Shebang.new(config('rubypath')) + end + $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? + open_atomic_writer(path) {|output| + File.open(path, 'rb') {|f| + f.gets if old # discard + output.puts new.to_s + output.print f.read + } + } + end + + def new_shebang(old) + if /\Aruby/ =~ File.basename(old.cmd) + Shebang.new(config('rubypath'), old.args) + elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' + Shebang.new(config('rubypath'), old.args[1..-1]) + else + return old unless config('shebang') == 'all' + Shebang.new(config('rubypath')) + end + end + + def open_atomic_writer(path, &block) + tmpfile = File.basename(path) + '.tmp' + begin + File.open(tmpfile, 'wb', &block) + File.rename tmpfile, File.basename(path) + ensure + File.unlink tmpfile if File.exist?(tmpfile) + end + end + + class Shebang + def Shebang.load(path) + line = nil + File.open(path) {|f| + line = f.gets + } + return nil unless /\A#!/ =~ line + parse(line) + end + + def Shebang.parse(line) + cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') + new(cmd, args) + end + + def initialize(cmd, args = []) + @cmd = cmd + @args = args + end + + attr_reader :cmd + attr_reader :args + + def to_s + "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") + end + end + + # + # TASK install + # + + def exec_install + rm_f 'InstalledFiles' + exec_task_traverse 'install' + end + + def install_dir_bin(rel) + install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 + end + + def install_dir_lib(rel) + install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 + end + + def install_dir_ext(rel) + return unless extdir?(curr_srcdir()) + install_files rubyextentions('.'), + "#{config('sodir')}/#{File.dirname(rel)}", + 0555 + end + + def install_dir_data(rel) + install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 + end + + def install_dir_conf(rel) + # FIXME: should not remove current config files + # (rename previous file to .old/.org) + install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 + end + + def install_dir_man(rel) + install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 + end + + def install_files(list, dest, mode) + mkdir_p dest, @config.install_prefix + list.each do |fname| + install fname, dest, mode, @config.install_prefix + end + end + + def libfiles + glob_reject(%w(*.y *.output), targetfiles()) + end + + def rubyextentions(dir) + ents = glob_select("*.#{@config.dllext}", targetfiles()) + if ents.empty? + setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" + end + ents + end + + def targetfiles + mapdir(existfiles() - hookfiles()) + end + + def mapdir(ents) + ents.map {|ent| + if File.exist?(ent) + then ent # objdir + else "#{curr_srcdir()}/#{ent}" # srcdir + end + } + end + + # picked up many entries from cvs-1.11.1/src/ignore.c + JUNK_FILES = %w( + core RCSLOG tags TAGS .make.state + .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb + *~ *.old *.bak *.BAK *.orig *.rej _$* *$ + + *.org *.in .* + ) + + def existfiles + glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) + end + + def hookfiles + %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| + %w( config setup install clean ).map {|t| sprintf(fmt, t) } + }.flatten + end + + def glob_select(pat, ents) + re = globs2re([pat]) + ents.select {|ent| re =~ ent } + end + + def glob_reject(pats, ents) + re = globs2re(pats) + ents.reject {|ent| re =~ ent } + end + + GLOB2REGEX = { + '.' => '\.', + '$' => '\$', + '#' => '\#', + '*' => '.*' + } + + def globs2re(pats) + /\A(?:#{ + pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|') + })\z/ + end + + # + # TASK test + # + + TESTDIR = 'test' + + def exec_test + unless File.directory?('test') + $stderr.puts 'no test in this package' if verbose? + return + end + $stderr.puts 'Running tests...' if verbose? + begin + require 'test/unit' + rescue LoadError + setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.' + end + runner = Test::Unit::AutoRunner.new(true) + runner.to_run << TESTDIR + runner.run + end + + # + # TASK clean + # + + def exec_clean + exec_task_traverse 'clean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias clean_dir_bin noop + alias clean_dir_lib noop + alias clean_dir_data noop + alias clean_dir_conf noop + alias clean_dir_man noop + + def clean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'clean' if File.file?('Makefile') + end + + # + # TASK distclean + # + + def exec_distclean + exec_task_traverse 'distclean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias distclean_dir_bin noop + alias distclean_dir_lib noop + + def distclean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'distclean' if File.file?('Makefile') + end + + alias distclean_dir_data noop + alias distclean_dir_conf noop + alias distclean_dir_man noop + + # + # Traversing + # + + def exec_task_traverse(task) + run_hook "pre-#{task}" + FILETYPES.each do |type| + if type == 'ext' and config('without-ext') == 'yes' + $stderr.puts 'skipping ext/* by user option' if verbose? + next + end + traverse task, type, "#{task}_dir_#{type}" + end + run_hook "post-#{task}" + end + + def traverse(task, rel, mid) + dive_into(rel) { + run_hook "pre-#{task}" + __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') + directories_of(curr_srcdir()).each do |d| + traverse task, "#{rel}/#{d}", mid + end + run_hook "post-#{task}" + } + end + + def dive_into(rel) + return unless File.dir?("#{@srcdir}/#{rel}") + + dir = File.basename(rel) + Dir.mkdir dir unless File.dir?(dir) + prevdir = Dir.pwd + Dir.chdir dir + $stderr.puts '---> ' + rel if verbose? + @currdir = rel + yield + Dir.chdir prevdir + $stderr.puts '<--- ' + rel if verbose? + @currdir = File.dirname(rel) + end + + def run_hook(id) + path = [ "#{curr_srcdir()}/#{id}", + "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) } + return unless path + begin + instance_eval File.read(path), path, 1 + rescue + raise if $DEBUG + setup_rb_error "hook #{path} failed:\n" + $!.message + end + end + +end # class Installer + + +class SetupError < StandardError; end + +def setup_rb_error(msg) + raise SetupError, msg +end + +if $0 == __FILE__ + begin + ToplevelInstaller.invoke + rescue SetupError + raise if $DEBUG + $stderr.puts $!.message + $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." + exit 1 + end +end diff --git a/agilelamp-driver/src/Makefile b/agilelamp-driver/src/Makefile new file mode 100644 index 0000000..5daf3ba --- /dev/null +++ b/agilelamp-driver/src/Makefile @@ -0,0 +1,2 @@ +all: + gcc agilelamp.c -o agilelamp-driver -lusb diff --git a/agilelamp-driver/src/agilelamp.c b/agilelamp-driver/src/agilelamp.c new file mode 100644 index 0000000..c32112e --- /dev/null +++ b/agilelamp-driver/src/agilelamp.c @@ -0,0 +1,175 @@ +#include <usb.h> +#include <stdio.h> +#include <unistd.h> +#include <string.h> + +usb_dev_handle* launcher; +//wrapper for control_msg +int send_message(char* msg, int index) +{ + int i = 0; + int j = usb_control_msg(launcher, 0x21, 0x9, 0x0, index, msg, 8, 1000); + return j; +} + +void send_cbw(){ + fprintf(stderr, "Sending CBW message\n"); + char cbw_message[8] = {0x55, 0x53, 0x42, 0x43, 0, 16, 2, 0}; + int ret = send_message(cbw_message, 1); + fprintf(stderr, "%d bytes sent\n", ret); +} + +void send_lamp_command(char* title, char* message1, char* message2){ + usb_reset(launcher); + send_cbw(); + fprintf(stderr, "Submitting %s\n", title); + int ret = send_message(message1, 0); + fprintf(stderr, "%d bytes sent\n", ret); + ret = send_message(message2, 0); + fprintf(stderr, "%d bytes sent\n", ret); +} + +void set_red_with_bell(){ + char message_part_1[8] = {0x0, 0x1, 0x4, 0x9,0x10, 0x19, 0x24, 0x31}; //red with bell + char message_part_2[8] = {0x40, 0x51, 0x64, 0x79, 0x90, 0xa9, 0xc4, 0xe1}; // red with bell + send_lamp_command("red with bell", message_part_1, message_part_2); +} + +/* +Fun with bit-math: + +Everything on the first (from right) 8 bits of first (from right) byte + +b0:=1:Bell active;=0:Bell off +b1:=1:Green led on; =0:Green led off +b2:=1:Red led on;=0:red led off +b3:=0:7 colors led on;=1:7 colors led off + + b0 +1 1 1 1 1 111 +128 64 32 16 8 421 = 255 + +c c c c c rgb (c's are colors to cycle through, then red, green, bell) + +0 0 0 16 0 000 = + +*/ + +void only_bell_on(){ + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; + char message_part_2[8] = {0,0,0,0, 0,0,0,1}; + send_lamp_command("green", message_part_1, message_part_2); +} + +void red_with_no_bell(){ + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; + char message_part_2[8] = {0,0,0,0, 0,0,0,4}; + send_lamp_command("red with no bell", message_part_1, message_part_2); +} + +void set_green(){ + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //green + char message_part_2[8] = {0,0,0,0 ,0,0,0,2}; // green + send_lamp_command("green", message_part_1, message_part_2); +} + +void set_lights_off(){ + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; // lights off + char message_part_2[8] = {0,0,0,0, 0,0,0,0}; // lights off + send_lamp_command("lights off", message_part_1, message_part_2); +} + +void set_colors_with_bell(){ + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //colors with bell + char message_part_2[8] = {0,0,0,0, 0,0,0,24}; // colors with bells + send_lamp_command("colors with bells", message_part_1, message_part_2); +} + +int load_device(){ + int claimed; + + fprintf(stderr, "Starting\n"); + + struct usb_bus *busses; + + usb_init(); + + fprintf(stderr, "usb_init...\n"); + + usb_find_busses(); + usb_find_devices(); + fprintf(stderr, "Found busses, found devices...\n"); + + busses = usb_get_busses(); + + fprintf(stderr, "Got busses...\n"); + + struct usb_bus *bus; + int c, i, a; + + /* ... */ + + for (bus = busses; bus; bus = bus->next) + { + struct usb_device *dev; + + for (dev = bus->devices; dev; dev = dev->next) + { + /* Check if this device is a printer */ + if (dev->descriptor.idVendor == 4400) + if(dev->descriptor.idProduct == 514) + launcher = usb_open(dev); + } + } + + fprintf(stderr, "Got launcher...\n"); + + //do stuff + if(launcher != NULL) + { + int claimed = usb_claim_interface(launcher, 1); + } + else + { + fprintf(stderr, "You didn't really get the launcher!\n"); + return 1; + } + + usb_detach_kernel_driver_np(launcher, 1); + usb_detach_kernel_driver_np(launcher, 0); + + if (claimed == 0) + { + usb_release_interface(launcher, 1); + return 1; + } else if (claimed > 0){ + fprintf(stderr, "Found launcher...\n"); + } + +} + +int main(int argc, char *argv[]) +{ + if ( argc != 2 ) /* argc should be 2 for correct execution */ + { + /* We print argv[0] assuming it is the program name */ + printf( "usage: %s filename\n", argv[0] ); + } + else + { + int ret = load_device(); + char* argument = argv[1]; + if(strcmp(argument, "green") == 0){ + set_green(); + } else if (strcmp(argument, "red") == 0){ + red_with_no_bell(); + } else if (strcmp(argument, "off") == 0){ + set_lights_off(); + } else if (strcmp(argument, "various") == 0){ + set_colors_with_bell(); + } else if (strcmp(argument, "bell") == 0){ + only_bell_on(); + } + } + return 0; +} diff --git a/agilelamp-driver/tasks/deployment.rake b/agilelamp-driver/tasks/deployment.rake new file mode 100644 index 0000000..3cb8296 --- /dev/null +++ b/agilelamp-driver/tasks/deployment.rake @@ -0,0 +1,45 @@ +desc 'Release the website and new gem version' +task :deploy => [:check_version, :website, :release] do + puts "Remember to create SVN tag:" + puts "svn copy svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/trunk " + + "svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/tags/REL-#{VERS} " + puts "Suggested comment:" + puts "Tagging release #{CHANGES}" +end + +desc 'Runs tasks website_generate and install_gem as a local deployment of the gem' +task :local_deploy => [:website_generate, :install_gem] + +task :check_version do + unless ENV['VERSION'] + puts 'Must pass a VERSION=x.y.z release version' + exit + end + unless ENV['VERSION'] == VERS + puts "Please update your version.rb to match the release version, currently #{VERS}" + exit + end +end + +desc 'Install the package as a gem, without generating documentation(ri/rdoc)' +task :install_gem_no_doc => [:clean, :package] do + sh "#{'sudo ' unless Hoe::WINDOZE }gem install pkg/*.gem --no-rdoc --no-ri" +end + +task :make_agilelamp_bin do + cd "src/" + sh "make" + cp "agilelamp-driver", "../bin" + cd "../" +end + +task :install_gem => [:clean, :make_agilelamp_bin, :package] do + sh "#{'sudo ' unless Hoe::WINDOZE}gem install --local pkg/*.gem" +end + +namespace :manifest do + desc 'Recreate Manifest.txt to include ALL files' + task :refresh do + `rake check_manifest | patch -p0 > Manifest.txt` + end +end diff --git a/agilelamp-driver/tasks/environment.rake b/agilelamp-driver/tasks/environment.rake new file mode 100644 index 0000000..691ed3b --- /dev/null +++ b/agilelamp-driver/tasks/environment.rake @@ -0,0 +1,7 @@ +task :ruby_env do + RUBY_APP = if RUBY_PLATFORM =~ /java/ + "jruby" + else + "ruby" + end unless defined? RUBY_APP +end diff --git a/agilelamp-driver/tasks/website.rake b/agilelamp-driver/tasks/website.rake new file mode 100644 index 0000000..93e03fa --- /dev/null +++ b/agilelamp-driver/tasks/website.rake @@ -0,0 +1,17 @@ +desc 'Generate website files' +task :website_generate => :ruby_env do + (Dir['website/**/*.txt'] - Dir['website/version*.txt']).each do |txt| + sh %{ #{RUBY_APP} script/txt2html #{txt} > #{txt.gsub(/txt$/,'html')} } + end +end + +desc 'Upload website files to rubyforge' +task :website_upload do + host = "#{rubyforge_username}@rubyforge.org" + remote_dir = "/var/www/gforge-projects/#{PATH}/" + local_dir = 'website' + sh %{rsync -aCv #{local_dir}/ #{host}:#{remote_dir}} +end + +desc 'Generate and upload website files' +task :website => [:website_generate, :website_upload, :publish_docs] diff --git a/agilelamp-driver/test/test_agilelamp-driver.rb b/agilelamp-driver/test/test_agilelamp-driver.rb new file mode 100644 index 0000000..ac5b2e2 --- /dev/null +++ b/agilelamp-driver/test/test_agilelamp-driver.rb @@ -0,0 +1,11 @@ +require File.dirname(__FILE__) + '/test_helper.rb' + +class TestAgilelamp-driver < Test::Unit::TestCase + + def setup + end + + def test_truth + assert true + end +end diff --git a/agilelamp-driver/test/test_helper.rb b/agilelamp-driver/test/test_helper.rb new file mode 100644 index 0000000..aa737d8 --- /dev/null +++ b/agilelamp-driver/test/test_helper.rb @@ -0,0 +1,2 @@ +require 'test/unit' +require File.dirname(__FILE__) + '/../lib/agilelamp-driver' diff --git a/agilelamp-driver/website/index.html b/agilelamp-driver/website/index.html new file mode 100644 index 0000000..2f6be96 --- /dev/null +++ b/agilelamp-driver/website/index.html @@ -0,0 +1,11 @@ +<html> + <head> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>agilelamp-driver</title> + + </head> + <body id="body"> + <p>This page has not yet been created for RubyGem <code>agilelamp-driver</code></p> + <p>To the developer: To generate it, update website/index.txt and run the rake task <code>website</code> to generate this <code>index.html</code> file.</p> + </body> +</html> \ No newline at end of file diff --git a/agilelamp-driver/website/index.txt b/agilelamp-driver/website/index.txt new file mode 100644 index 0000000..60bd997 --- /dev/null +++ b/agilelamp-driver/website/index.txt @@ -0,0 +1,83 @@ +h1. agilelamp driver + +h1. &#x2192; 'agilelamp-driver' + + +h2. What + + +h2. Installing + +<pre syntax="ruby">sudo gem install agilelamp-driver</pre> + +h2. The basics + + +h2. Demonstration of usage + + + +h2. Forum + +"http://groups.google.com/group/agilelamp-driver":http://groups.google.com/group/agilelamp-driver + +TODO - create Google Group - agilelamp-driver + +h2. How to submit patches + +Read the "8 steps for fixing other people's code":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/ and for section "8b: Submit patch to Google Groups":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/#8b-google-groups, use the Google Group above. + +TODO - pick SVN or Git instructions + +The trunk repository is <code>svn://rubyforge.org/var/svn/agilelamp-driver/trunk</code> for anonymous access. + +OOOORRRR + +You can fetch the source from either: + +<% if rubyforge_project_id %> + +* rubyforge: "http://rubyforge.org/scm/?group_id=<%= rubyforge_project_id %>":http://rubyforge.org/scm/?group_id=<%= rubyforge_project_id %> + +<pre>git clone git://rubyforge.org/agilelamp-driver.git</pre> + +<% else %> + +* rubyforge: MISSING IN ACTION + +TODO - You can not created a RubyForge project, OR have not run <code>rubyforge config</code> +yet to refresh your local rubyforge data with this projects' id information. + +When you do this, this message will magically disappear! + +Or you can hack website/index.txt and make it all go away!! + +<% end %> + +* github: "http://github.com/GITHUB_USERNAME/agilelamp-driver/tree/master":http://github.com/GITHUB_USERNAME/agilelamp-driver/tree/master + +<pre>git clone git://github.com/GITHUB_USERNAME/agilelamp-driver.git</pre> + + +TODO - add "github_username: username" to ~/.rubyforge/user-config.yml and newgem will reuse it for future projects. + + +* gitorious: "git://gitorious.org/agilelamp-driver/mainline.git":git://gitorious.org/agilelamp-driver/mainline.git + +<pre>git clone git://gitorious.org/agilelamp-driver/mainline.git</pre> + +h3. Build and test instructions + +<pre>cd agilelamp-driver +rake test +rake install_gem</pre> + + +h2. License + +This code is free to use under the terms of the MIT license. + +h2. Contact + +Comments are welcome. Send an email to "Joseph Method":mailto:[email protected] via the "forum":http://groups.google.com/group/agilelamp-driver + diff --git a/agilelamp-driver/website/javascripts/rounded_corners_lite.inc.js b/agilelamp-driver/website/javascripts/rounded_corners_lite.inc.js new file mode 100644 index 0000000..afc3ea3 --- /dev/null +++ b/agilelamp-driver/website/javascripts/rounded_corners_lite.inc.js @@ -0,0 +1,285 @@ + + /**************************************************************** + * * + * curvyCorners * + * ------------ * + * * + * This script generates rounded corners for your divs. * + * * + * Version 1.2.9 * + * Copyright (c) 2006 Cameron Cooke * + * By: Cameron Cooke and Tim Hutchison. * + * * + * * + * Website: http://www.curvycorners.net * + * Email: [email protected] * + * Forum: http://www.curvycorners.net/forum/ * + * * + * * + * This library is free software; you can redistribute * + * it and/or modify it under the terms of the GNU * + * Lesser General Public License as published by the * + * Free Software Foundation; either version 2.1 of the * + * License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will * + * be useful, but WITHOUT ANY WARRANTY; without even the * + * implied warranty of MERCHANTABILITY or FITNESS FOR A * + * PARTICULAR PURPOSE. See the GNU Lesser General Public * + * License for more details. * + * * + * You should have received a copy of the GNU Lesser * + * General Public License along with this library; * + * Inc., 59 Temple Place, Suite 330, Boston, * + * MA 02111-1307 USA * + * * + ****************************************************************/ + +var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1; var isMoz = document.implementation && document.implementation.createDocument; var isSafari = ((navigator.userAgent.toLowerCase().indexOf('safari')!=-1)&&(navigator.userAgent.toLowerCase().indexOf('mac')!=-1))?true:false; function curvyCorners() +{ if(typeof(arguments[0]) != "object") throw newCurvyError("First parameter of curvyCorners() must be an object."); if(typeof(arguments[1]) != "object" && typeof(arguments[1]) != "string") throw newCurvyError("Second parameter of curvyCorners() must be an object or a class name."); if(typeof(arguments[1]) == "string") +{ var startIndex = 0; var boxCol = getElementsByClass(arguments[1]);} +else +{ var startIndex = 1; var boxCol = arguments;} +var curvyCornersCol = new Array(); if(arguments[0].validTags) +var validElements = arguments[0].validTags; else +var validElements = ["div"]; for(var i = startIndex, j = boxCol.length; i < j; i++) +{ var currentTag = boxCol[i].tagName.toLowerCase(); if(inArray(validElements, currentTag) !== false) +{ curvyCornersCol[curvyCornersCol.length] = new curvyObject(arguments[0], boxCol[i]);} +} +this.objects = curvyCornersCol; this.applyCornersToAll = function() +{ for(var x = 0, k = this.objects.length; x < k; x++) +{ this.objects[x].applyCorners();} +} +} +function curvyObject() +{ this.box = arguments[1]; this.settings = arguments[0]; this.topContainer = null; this.bottomContainer = null; this.masterCorners = new Array(); this.contentDIV = null; var boxHeight = get_style(this.box, "height", "height"); var boxWidth = get_style(this.box, "width", "width"); var borderWidth = get_style(this.box, "borderTopWidth", "border-top-width"); var borderColour = get_style(this.box, "borderTopColor", "border-top-color"); var boxColour = get_style(this.box, "backgroundColor", "background-color"); var backgroundImage = get_style(this.box, "backgroundImage", "background-image"); var boxPosition = get_style(this.box, "position", "position"); var boxPadding = get_style(this.box, "paddingTop", "padding-top"); this.boxHeight = parseInt(((boxHeight != "" && boxHeight != "auto" && boxHeight.indexOf("%") == -1)? boxHeight.substring(0, boxHeight.indexOf("px")) : this.box.scrollHeight)); this.boxWidth = parseInt(((boxWidth != "" && boxWidth != "auto" && boxWidth.indexOf("%") == -1)? boxWidth.substring(0, boxWidth.indexOf("px")) : this.box.scrollWidth)); this.borderWidth = parseInt(((borderWidth != "" && borderWidth.indexOf("px") !== -1)? borderWidth.slice(0, borderWidth.indexOf("px")) : 0)); this.boxColour = format_colour(boxColour); this.boxPadding = parseInt(((boxPadding != "" && boxPadding.indexOf("px") !== -1)? boxPadding.slice(0, boxPadding.indexOf("px")) : 0)); this.borderColour = format_colour(borderColour); this.borderString = this.borderWidth + "px" + " solid " + this.borderColour; this.backgroundImage = ((backgroundImage != "none")? backgroundImage : ""); this.boxContent = this.box.innerHTML; if(boxPosition != "absolute") this.box.style.position = "relative"; this.box.style.padding = "0px"; if(isIE && boxWidth == "auto" && boxHeight == "auto") this.box.style.width = "100%"; if(this.settings.autoPad == true && this.boxPadding > 0) +this.box.innerHTML = ""; this.applyCorners = function() +{ for(var t = 0; t < 2; t++) +{ switch(t) +{ case 0: +if(this.settings.tl || this.settings.tr) +{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var topMaxRadius = Math.max(this.settings.tl ? this.settings.tl.radius : 0, this.settings.tr ? this.settings.tr.radius : 0); newMainContainer.style.height = topMaxRadius + "px"; newMainContainer.style.top = 0 - topMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.topContainer = this.box.appendChild(newMainContainer);} +break; case 1: +if(this.settings.bl || this.settings.br) +{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var botMaxRadius = Math.max(this.settings.bl ? this.settings.bl.radius : 0, this.settings.br ? this.settings.br.radius : 0); newMainContainer.style.height = botMaxRadius + "px"; newMainContainer.style.bottom = 0 - botMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.bottomContainer = this.box.appendChild(newMainContainer);} +break;} +} +if(this.topContainer) this.box.style.borderTopWidth = "0px"; if(this.bottomContainer) this.box.style.borderBottomWidth = "0px"; var corners = ["tr", "tl", "br", "bl"]; for(var i in corners) +{ if(i > -1 < 4) +{ var cc = corners[i]; if(!this.settings[cc]) +{ if(((cc == "tr" || cc == "tl") && this.topContainer != null) || ((cc == "br" || cc == "bl") && this.bottomContainer != null)) +{ var newCorner = document.createElement("DIV"); newCorner.style.position = "relative"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; if(this.backgroundImage == "") +newCorner.style.backgroundColor = this.boxColour; else +newCorner.style.backgroundImage = this.backgroundImage; switch(cc) +{ case "tl": +newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.tr.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.left = -this.borderWidth + "px"; break; case "tr": +newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.tl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; newCorner.style.left = this.borderWidth + "px"; break; case "bl": +newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.br.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = -this.borderWidth + "px"; newCorner.style.backgroundPosition = "-" + (this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break; case "br": +newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.bl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = this.borderWidth + "px" +newCorner.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break;} +} +} +else +{ if(this.masterCorners[this.settings[cc].radius]) +{ var newCorner = this.masterCorners[this.settings[cc].radius].cloneNode(true);} +else +{ var newCorner = document.createElement("DIV"); newCorner.style.height = this.settings[cc].radius + "px"; newCorner.style.width = this.settings[cc].radius + "px"; newCorner.style.position = "absolute"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; var borderRadius = parseInt(this.settings[cc].radius - this.borderWidth); for(var intx = 0, j = this.settings[cc].radius; intx < j; intx++) +{ if((intx +1) >= borderRadius) +var y1 = -1; else +var y1 = (Math.floor(Math.sqrt(Math.pow(borderRadius, 2) - Math.pow((intx+1), 2))) - 1); if(borderRadius != j) +{ if((intx) >= borderRadius) +var y2 = -1; else +var y2 = Math.ceil(Math.sqrt(Math.pow(borderRadius,2) - Math.pow(intx, 2))); if((intx+1) >= j) +var y3 = -1; else +var y3 = (Math.floor(Math.sqrt(Math.pow(j ,2) - Math.pow((intx+1), 2))) - 1);} +if((intx) >= j) +var y4 = -1; else +var y4 = Math.ceil(Math.sqrt(Math.pow(j ,2) - Math.pow(intx, 2))); if(y1 > -1) this.drawPixel(intx, 0, this.boxColour, 100, (y1+1), newCorner, -1, this.settings[cc].radius); if(borderRadius != j) +{ for(var inty = (y1 + 1); inty < y2; inty++) +{ if(this.settings.antiAlias) +{ if(this.backgroundImage != "") +{ var borderFract = (pixelFraction(intx, inty, borderRadius) * 100); if(borderFract < 30) +{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, 0, this.settings[cc].radius);} +else +{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, -1, this.settings[cc].radius);} +} +else +{ var pixelcolour = BlendColour(this.boxColour, this.borderColour, pixelFraction(intx, inty, borderRadius)); this.drawPixel(intx, inty, pixelcolour, 100, 1, newCorner, 0, this.settings[cc].radius, cc);} +} +} +if(this.settings.antiAlias) +{ if(y3 >= y2) +{ if (y2 == -1) y2 = 0; this.drawPixel(intx, y2, this.borderColour, 100, (y3 - y2 + 1), newCorner, 0, 0);} +} +else +{ if(y3 >= y1) +{ this.drawPixel(intx, (y1 + 1), this.borderColour, 100, (y3 - y1), newCorner, 0, 0);} +} +var outsideColour = this.borderColour;} +else +{ var outsideColour = this.boxColour; var y3 = y1;} +if(this.settings.antiAlias) +{ for(var inty = (y3 + 1); inty < y4; inty++) +{ this.drawPixel(intx, inty, outsideColour, (pixelFraction(intx, inty , j) * 100), 1, newCorner, ((this.borderWidth > 0)? 0 : -1), this.settings[cc].radius);} +} +} +this.masterCorners[this.settings[cc].radius] = newCorner.cloneNode(true);} +if(cc != "br") +{ for(var t = 0, k = newCorner.childNodes.length; t < k; t++) +{ var pixelBar = newCorner.childNodes[t]; var pixelBarTop = parseInt(pixelBar.style.top.substring(0, pixelBar.style.top.indexOf("px"))); var pixelBarLeft = parseInt(pixelBar.style.left.substring(0, pixelBar.style.left.indexOf("px"))); var pixelBarHeight = parseInt(pixelBar.style.height.substring(0, pixelBar.style.height.indexOf("px"))); if(cc == "tl" || cc == "bl"){ pixelBar.style.left = this.settings[cc].radius -pixelBarLeft -1 + "px";} +if(cc == "tr" || cc == "tl"){ pixelBar.style.top = this.settings[cc].radius -pixelBarHeight -pixelBarTop + "px";} +switch(cc) +{ case "tr": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.boxWidth - this.settings[cc].radius + this.borderWidth) + pixelBarLeft) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "tl": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "bl": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs((this.boxHeight + this.settings[cc].radius + pixelBarTop) -this.borderWidth) + "px"; break;} +} +} +} +if(newCorner) +{ switch(cc) +{ case "tl": +if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "tr": +if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "bl": +if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break; case "br": +if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break;} +} +} +} +var radiusDiff = new Array(); radiusDiff["t"] = Math.abs(this.settings.tl.radius - this.settings.tr.radius) +radiusDiff["b"] = Math.abs(this.settings.bl.radius - this.settings.br.radius); for(z in radiusDiff) +{ if(z == "t" || z == "b") +{ if(radiusDiff[z]) +{ var smallerCornerType = ((this.settings[z + "l"].radius < this.settings[z + "r"].radius)? z +"l" : z +"r"); var newFiller = document.createElement("DIV"); newFiller.style.height = radiusDiff[z] + "px"; newFiller.style.width = this.settings[smallerCornerType].radius+ "px" +newFiller.style.position = "absolute"; newFiller.style.fontSize = "1px"; newFiller.style.overflow = "hidden"; newFiller.style.backgroundColor = this.boxColour; switch(smallerCornerType) +{ case "tl": +newFiller.style.bottom = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.topContainer.appendChild(newFiller); break; case "tr": +newFiller.style.bottom = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.topContainer.appendChild(newFiller); break; case "bl": +newFiller.style.top = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.bottomContainer.appendChild(newFiller); break; case "br": +newFiller.style.top = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.bottomContainer.appendChild(newFiller); break;} +} +var newFillerBar = document.createElement("DIV"); newFillerBar.style.position = "relative"; newFillerBar.style.fontSize = "1px"; newFillerBar.style.overflow = "hidden"; newFillerBar.style.backgroundColor = this.boxColour; newFillerBar.style.backgroundImage = this.backgroundImage; switch(z) +{ case "t": +if(this.topContainer) +{ if(this.settings.tl.radius && this.settings.tr.radius) +{ newFillerBar.style.height = topMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.tl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.tr.radius - this.borderWidth + "px"; newFillerBar.style.borderTop = this.borderString; if(this.backgroundImage != "") +newFillerBar.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; this.topContainer.appendChild(newFillerBar);} +this.box.style.backgroundPosition = "0px -" + (topMaxRadius - this.borderWidth) + "px";} +break; case "b": +if(this.bottomContainer) +{ if(this.settings.bl.radius && this.settings.br.radius) +{ newFillerBar.style.height = botMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.bl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.br.radius - this.borderWidth + "px"; newFillerBar.style.borderBottom = this.borderString; if(this.backgroundImage != "") +newFillerBar.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (topMaxRadius + this.borderWidth)) + "px"; this.bottomContainer.appendChild(newFillerBar);} +} +break;} +} +} +if(this.settings.autoPad == true && this.boxPadding > 0) +{ var contentContainer = document.createElement("DIV"); contentContainer.style.position = "relative"; contentContainer.innerHTML = this.boxContent; contentContainer.className = "autoPadDiv"; var topPadding = Math.abs(topMaxRadius - this.boxPadding); var botPadding = Math.abs(botMaxRadius - this.boxPadding); if(topMaxRadius < this.boxPadding) +contentContainer.style.paddingTop = topPadding + "px"; if(botMaxRadius < this.boxPadding) +contentContainer.style.paddingBottom = botMaxRadius + "px"; contentContainer.style.paddingLeft = this.boxPadding + "px"; contentContainer.style.paddingRight = this.boxPadding + "px"; this.contentDIV = this.box.appendChild(contentContainer);} +} +this.drawPixel = function(intx, inty, colour, transAmount, height, newCorner, image, cornerRadius) +{ var pixel = document.createElement("DIV"); pixel.style.height = height + "px"; pixel.style.width = "1px"; pixel.style.position = "absolute"; pixel.style.fontSize = "1px"; pixel.style.overflow = "hidden"; var topMaxRadius = Math.max(this.settings["tr"].radius, this.settings["tl"].radius); if(image == -1 && this.backgroundImage != "") +{ pixel.style.backgroundImage = this.backgroundImage; pixel.style.backgroundPosition = "-" + (this.boxWidth - (cornerRadius - intx) + this.borderWidth) + "px -" + ((this.boxHeight + topMaxRadius + inty) -this.borderWidth) + "px";} +else +{ pixel.style.backgroundColor = colour;} +if (transAmount != 100) +setOpacity(pixel, transAmount); pixel.style.top = inty + "px"; pixel.style.left = intx + "px"; newCorner.appendChild(pixel);} +} +function insertAfter(parent, node, referenceNode) +{ parent.insertBefore(node, referenceNode.nextSibling);} +function BlendColour(Col1, Col2, Col1Fraction) +{ var red1 = parseInt(Col1.substr(1,2),16); var green1 = parseInt(Col1.substr(3,2),16); var blue1 = parseInt(Col1.substr(5,2),16); var red2 = parseInt(Col2.substr(1,2),16); var green2 = parseInt(Col2.substr(3,2),16); var blue2 = parseInt(Col2.substr(5,2),16); if(Col1Fraction > 1 || Col1Fraction < 0) Col1Fraction = 1; var endRed = Math.round((red1 * Col1Fraction) + (red2 * (1 - Col1Fraction))); if(endRed > 255) endRed = 255; if(endRed < 0) endRed = 0; var endGreen = Math.round((green1 * Col1Fraction) + (green2 * (1 - Col1Fraction))); if(endGreen > 255) endGreen = 255; if(endGreen < 0) endGreen = 0; var endBlue = Math.round((blue1 * Col1Fraction) + (blue2 * (1 - Col1Fraction))); if(endBlue > 255) endBlue = 255; if(endBlue < 0) endBlue = 0; return "#" + IntToHex(endRed)+ IntToHex(endGreen)+ IntToHex(endBlue);} +function IntToHex(strNum) +{ base = strNum / 16; rem = strNum % 16; base = base - (rem / 16); baseS = MakeHex(base); remS = MakeHex(rem); return baseS + '' + remS;} +function MakeHex(x) +{ if((x >= 0) && (x <= 9)) +{ return x;} +else +{ switch(x) +{ case 10: return "A"; case 11: return "B"; case 12: return "C"; case 13: return "D"; case 14: return "E"; case 15: return "F";} +} +} +function pixelFraction(x, y, r) +{ var pixelfraction = 0; var xvalues = new Array(1); var yvalues = new Array(1); var point = 0; var whatsides = ""; var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x,2))); if ((intersect >= y) && (intersect < (y+1))) +{ whatsides = "Left"; xvalues[point] = 0; yvalues[point] = intersect - y; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y+1,2))); if ((intersect >= x) && (intersect < (x+1))) +{ whatsides = whatsides + "Top"; xvalues[point] = intersect - x; yvalues[point] = 1; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x+1,2))); if ((intersect >= y) && (intersect < (y+1))) +{ whatsides = whatsides + "Right"; xvalues[point] = 1; yvalues[point] = intersect - y; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y,2))); if ((intersect >= x) && (intersect < (x+1))) +{ whatsides = whatsides + "Bottom"; xvalues[point] = intersect - x; yvalues[point] = 0;} +switch (whatsides) +{ case "LeftRight": +pixelfraction = Math.min(yvalues[0],yvalues[1]) + ((Math.max(yvalues[0],yvalues[1]) - Math.min(yvalues[0],yvalues[1]))/2); break; case "TopRight": +pixelfraction = 1-(((1-xvalues[0])*(1-yvalues[1]))/2); break; case "TopBottom": +pixelfraction = Math.min(xvalues[0],xvalues[1]) + ((Math.max(xvalues[0],xvalues[1]) - Math.min(xvalues[0],xvalues[1]))/2); break; case "LeftBottom": +pixelfraction = (yvalues[0]*xvalues[1])/2; break; default: +pixelfraction = 1;} +return pixelfraction;} +function rgb2Hex(rgbColour) +{ try{ var rgbArray = rgb2Array(rgbColour); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); var hexColour = "#" + IntToHex(red) + IntToHex(green) + IntToHex(blue);} +catch(e){ alert("There was an error converting the RGB value to Hexadecimal in function rgb2Hex");} +return hexColour;} +function rgb2Array(rgbColour) +{ var rgbValues = rgbColour.substring(4, rgbColour.indexOf(")")); var rgbArray = rgbValues.split(", "); return rgbArray;} +function setOpacity(obj, opacity) +{ opacity = (opacity == 100)?99.999:opacity; if(isSafari && obj.tagName != "IFRAME") +{ var rgbArray = rgb2Array(obj.style.backgroundColor); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); obj.style.backgroundColor = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity/100 + ")";} +else if(typeof(obj.style.opacity) != "undefined") +{ obj.style.opacity = opacity/100;} +else if(typeof(obj.style.MozOpacity) != "undefined") +{ obj.style.MozOpacity = opacity/100;} +else if(typeof(obj.style.filter) != "undefined") +{ obj.style.filter = "alpha(opacity:" + opacity + ")";} +else if(typeof(obj.style.KHTMLOpacity) != "undefined") +{ obj.style.KHTMLOpacity = opacity/100;} +} +function inArray(array, value) +{ for(var i = 0; i < array.length; i++){ if (array[i] === value) return i;} +return false;} +function inArrayKey(array, value) +{ for(key in array){ if(key === value) return true;} +return false;} +function addEvent(elm, evType, fn, useCapture) { if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true;} +else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r;} +else { elm['on' + evType] = fn;} +} +function removeEvent(obj, evType, fn, useCapture){ if (obj.removeEventListener){ obj.removeEventListener(evType, fn, useCapture); return true;} else if (obj.detachEvent){ var r = obj.detachEvent("on"+evType, fn); return r;} else { alert("Handler could not be removed");} +} +function format_colour(colour) +{ var returnColour = "#ffffff"; if(colour != "" && colour != "transparent") +{ if(colour.substr(0, 3) == "rgb") +{ returnColour = rgb2Hex(colour);} +else if(colour.length == 4) +{ returnColour = "#" + colour.substring(1, 2) + colour.substring(1, 2) + colour.substring(2, 3) + colour.substring(2, 3) + colour.substring(3, 4) + colour.substring(3, 4);} +else +{ returnColour = colour;} +} +return returnColour;} +function get_style(obj, property, propertyNS) +{ try +{ if(obj.currentStyle) +{ var returnVal = eval("obj.currentStyle." + property);} +else +{ if(isSafari && obj.style.display == "none") +{ obj.style.display = ""; var wasHidden = true;} +var returnVal = document.defaultView.getComputedStyle(obj, '').getPropertyValue(propertyNS); if(isSafari && wasHidden) +{ obj.style.display = "none";} +} +} +catch(e) +{ } +return returnVal;} +function getElementsByClass(searchClass, node, tag) +{ var classElements = new Array(); if(node == null) +node = document; if(tag == null) +tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)"); for (i = 0, j = 0; i < elsLen; i++) +{ if(pattern.test(els[i].className)) +{ classElements[j] = els[i]; j++;} +} +return classElements;} +function newCurvyError(errorMessage) +{ return new Error("curvyCorners Error:\n" + errorMessage) +} diff --git a/agilelamp-driver/website/stylesheets/screen.css b/agilelamp-driver/website/stylesheets/screen.css new file mode 100644 index 0000000..2c84cd0 --- /dev/null +++ b/agilelamp-driver/website/stylesheets/screen.css @@ -0,0 +1,138 @@ +body { + background-color: #E1D1F1; + font-family: "Georgia", sans-serif; + font-size: 16px; + line-height: 1.6em; + padding: 1.6em 0 0 0; + color: #333; +} +h1, h2, h3, h4, h5, h6 { + color: #444; +} +h1 { + font-family: sans-serif; + font-weight: normal; + font-size: 4em; + line-height: 0.8em; + letter-spacing: -0.1ex; + margin: 5px; +} +li { + padding: 0; + margin: 0; + list-style-type: square; +} +a { + color: #5E5AFF; + background-color: #DAC; + font-weight: normal; + text-decoration: underline; +} +blockquote { + font-size: 90%; + font-style: italic; + border-left: 1px solid #111; + padding-left: 1em; +} +.caps { + font-size: 80%; +} + +#main { + width: 45em; + padding: 0; + margin: 0 auto; +} +.coda { + text-align: right; + color: #77f; + font-size: smaller; +} + +table { + font-size: 90%; + line-height: 1.4em; + color: #ff8; + background-color: #111; + padding: 2px 10px 2px 10px; + border-style: dashed; +} + +th { + color: #fff; +} + +td { + padding: 2px 10px 2px 10px; +} + +.success { + color: #0CC52B; +} + +.failed { + color: #E90A1B; +} + +.unknown { + color: #995000; +} +pre, code { + font-family: monospace; + font-size: 90%; + line-height: 1.4em; + color: #ff8; + background-color: #111; + padding: 2px 10px 2px 10px; +} +.comment { color: #aaa; font-style: italic; } +.keyword { color: #eff; font-weight: bold; } +.punct { color: #eee; font-weight: bold; } +.symbol { color: #0bb; } +.string { color: #6b4; } +.ident { color: #ff8; } +.constant { color: #66f; } +.regex { color: #ec6; } +.number { color: #F99; } +.expr { color: #227; } + +#version { + float: right; + text-align: right; + font-family: sans-serif; + font-weight: normal; + background-color: #B3ABFF; + color: #141331; + padding: 15px 20px 10px 20px; + margin: 0 auto; + margin-top: 15px; + border: 3px solid #141331; +} + +#version .numbers { + display: block; + font-size: 4em; + line-height: 0.8em; + letter-spacing: -0.1ex; + margin-bottom: 15px; +} + +#version p { + text-decoration: none; + color: #141331; + background-color: #B3ABFF; + margin: 0; + padding: 0; +} + +#version a { + text-decoration: none; + color: #141331; + background-color: #B3ABFF; +} + +.clickable { + cursor: pointer; + cursor: hand; +} + diff --git a/agilelamp-driver/website/template.html.erb b/agilelamp-driver/website/template.html.erb new file mode 100644 index 0000000..58def9f --- /dev/null +++ b/agilelamp-driver/website/template.html.erb @@ -0,0 +1,48 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <link rel="stylesheet" href="stylesheets/screen.css" type="text/css" media="screen" /> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <title> + <%= title %> + </title> + <script src="javascripts/rounded_corners_lite.inc.js" type="text/javascript"></script> +<style> + +</style> + <script type="text/javascript"> + window.onload = function() { + settings = { + tl: { radius: 10 }, + tr: { radius: 10 }, + bl: { radius: 10 }, + br: { radius: 10 }, + antiAlias: true, + autoPad: true, + validTags: ["div"] + } + var versionBox = new curvyCorners(settings, document.getElementById("version")); + versionBox.applyCornersToAll(); + } + </script> +</head> +<body> +<div id="main"> + + <h1><%= title %></h1> + <div id="version" class="clickable" onclick='document.location = "<%= download %>"; return false'> + <p>Get Version</p> + <a href="<%= download %>" class="numbers"><%= version %></a> + </div> + <%= body %> + <p class="coda"> + <a href="[email protected]">Joseph Method</a>, <%= modified.pretty %><br> + Theme extended from <a href="http://rb2js.rubyforge.org/">Paul Battley</a> + </p> +</div> + +<!-- insert site tracking codes here, like Google Urchin --> + +</body> +</html> diff --git a/lavalamp.py b/lavalamp.py deleted file mode 100644 index 4a91d3f..0000000 --- a/lavalamp.py +++ /dev/null @@ -1,50 +0,0 @@ -import usb - -class DeviceDescriptor(object) : - def __init__(self, vendor_id, product_id, interface_id) : - self.vendor_id = vendor_id - self.product_id = product_id - self.interface_id = interface_id - - def getDevice(self) : - """ - Return the device corresponding to the device descriptor if it is - available on a USB bus. Otherwise, return None. Note that the - returned device has yet to be claimed or opened. - """ - buses = usb.busses() - for bus in buses : - for device in bus.devices : - if device.idVendor == self.vendor_id : - if device.idProduct == self.product_id : - return device - return None - - -VENDOR_ID = 0x1130 -PRODUCT_ID = 0x0202 - -device_descriptor = DeviceDescriptor(VENDOR_ID, PRODUCT_ID, 1) -device = device_descriptor.getDevice() -handle = device.open() -handle.claimInterface(1) - -# Set_Report with report type output, report ID 0, interface 1, and length 8 - -#ret = hid_set_output_report(hid_interface_1, (), "8") - -# OUT transaction to endpoint 0 with CBW indicates write and length. -#ret = hid_interrupt_write(hid_interface_0, 0x81, CBW, 1000); - -# Set_Report with report type output, report ID 0, interface 0, length 16. - -#ret = hid_set_output_report(hid_interface_0, (), "16") - -# OUT transaction to endpoint 0 with data and length 8. - -#ret = hid_interrupt_write(hid_interface_0, 0x81, "/0xff/0xfe/0xfd/0xfc/0xfb/0xfa/0xf9/0xf9", 1000); - -# OUT transaction to endpoint 0 with data and length 8. - -#ret = hid_interrupt_write(hid_interface_0, 0x81, "/0xf7/0xf6/0xf5/0xf4/0xf3/0xf2/0xf1/0xf0", 1000); - diff --git a/test_hid.c b/test_hid.c deleted file mode 100644 index 68c41ea..0000000 --- a/test_hid.c +++ /dev/null @@ -1,31 +0,0 @@ -#include <hid.h> - -HIDInterface *hid; -hid_return ret; - -HIDInterfaceMatcher matcher = - { 0x0ce5, 0x0003, NULL, NULL, 0 }; -ret = hid_force_open(hid, 0, &matcher, 3); - -int const PATH_LEN = 2; -int const PATH_IN[2] = { 0xffa00001, 0xffa00003 }; - -int const WRITE_PACKET_LEN = 8; -char write_packet[8] = - { 0x04,0x7f,0x7f,0x00,0x02,0x00,0x00,0x00 }; - -int const READ_PACKET_LEN = 5; -char read_packet[5]; - -ret = hid_set_output_report(hid, - PATH_IN, - PATH_LEN, - write_packet, - WRITE_PACKET_LEN); - -ret = hid_interrupt_read(hid, - USB_ENDPOINT_IN+1, - read_packet, - READ_PACKET_LEN, - 0); - diff --git a/test_libhid.c b/test_libhid.c deleted file mode 100644 index 9c8511b..0000000 --- a/test_libhid.c +++ /dev/null @@ -1,140 +0,0 @@ -#include <hid.h> -#include <stdio.h> -#include <string.h> -#include <unistd.h> /* for getopt() */ - -bool match_serial_number(struct usb_dev_handle* usbdev, void* custom, unsigned int len) -{ - bool ret; - char* buffer = (char*)malloc(len); - usb_get_string_simple(usbdev, usb_device(usbdev)->descriptor.iSerialNumber, - buffer, len); - ret = strncmp(buffer, (char*)custom, len) == 0; - free(buffer); - return ret; -} - -void set_debug(){ - /* see include/debug.h for possible values */ - hid_set_debug(HID_DEBUG_WARNINGS); - hid_set_debug_stream(stderr); - /* passed directly to libusb */ - hid_set_usb_debug(0); -} - -int do_hid_init(){ - hid_return ret; - fprintf(stderr, "Before hid_init\n"); - ret = hid_init(); - if (ret != HID_RET_SUCCESS) { - fprintf(stderr, "hid_init failed with return code %d\n", ret); - return 1; - } - fprintf(stderr, "After hid_init\n"); - return 0; -} - -int force_open_interface(HIDInterface * hid, HIDInterfaceMatcher matcher, int iface_num){ - hid_return ret; - ret = hid_force_open(hid, iface_num, &matcher, 5); - fprintf(stderr, "After hid_force_open %d\n", iface_num); - if (ret != HID_RET_SUCCESS) { - fprintf(stderr, "hid_force_open failed with return code %d\n", ret); - return 1; - } - return 0; -} - - - -int main(int argc, char *argv[]) -{ - HIDInterface* hid_interface_0; - HIDInterface* hid_interface_1; - hid_return ret; - - unsigned short vendor_id = 0x1130; - unsigned short product_id = 0x0202; - char *vendor, *product; - - int flag; - - HIDInterfaceMatcher matcher = { vendor_id, product_id, NULL, NULL, 0 }; - - set_debug(); - if(do_hid_init() == 1) - return 1; - - hid_interface_0 = hid_new_HIDInterface(); - if (hid_interface_0 == 0) { - fprintf(stderr, "hid_new_HIDInterface() failed, out of memory?\n"); - return 1; - } - fprintf(stderr, "After created new HIDInterface hid_interface_0 \n"); - - hid_interface_1 = hid_new_HIDInterface(); - if (hid_interface_1 == 0) { - fprintf(stderr, "hid_new_HIDInterface() failed, out of memory?\n"); - return 1; - } - fprintf(stderr, "After created new HIDInterface hid_interface_1\n"); - - if(force_open_interface(hid_interface_0, matcher, 0) == 1) - return 1; - if(force_open_interface(hid_interface_1, matcher, 1) == 1) - return 1; - - char write_cbw_packet[8] = {0x55, 0x53, 0x42, 0x43, 0, 16, 2,0}; - unsigned char const PATHLEN = 1; - int const PATH_IN[1] = { 4194304 }; - int const PATH_OUT[3] = { 0xffa00001, 0xffa00002, 0xffa10004 }; - - fprintf(stderr, "Before hid_set_output_report\n"); - ret = hid_set_output_report(hid_interface_1, PATH_IN, PATHLEN, "", 8); - ret = hid_interrupt_write(hid_interface_0, 0x81, write_cbw_packet, 8, 1000); - ret = hid_set_output_report(hid_interface_0, PATH_IN, PATHLEN, "", 16); - - printf("\n%d\n\n", ret); // Prints out '0' - - - - char green_light[16] = {0x5a,0x5a,0x5a,0x5a, - 0x5a,0x5a,0x5a,0x5a, - 0x5a,0x5a,0x5a,0x5a, - 0x5a,0x5a,0x5a,0x5a}; - - - fprintf(stderr, "Before hid_interrupt_write again:\n"); - ret = hid_interrupt_write(hid_interface_0, 0x81, green_light, 16, 1000); - printf("\n%d\n", ret); // Prints out '21' - - if (ret != HID_RET_SUCCESS) { - fprintf(stderr, "hid_cleanup failed with return code %d\n", ret); - return 1; - } - - ret = hid_close(hid_interface_0); - ret = hid_close(hid_interface_1); - - hid_delete_HIDInterface(&hid_interface_0); - hid_delete_HIDInterface(&hid_interface_1); - - ret = hid_cleanup(); - - return 0; -} - -/* COPYRIGHT -- - * - * This file is part of libhid, a user-space HID access library. - * libhid is (c) 2003-2005 - * Martin F. Krafft <[email protected]> - * Charles Lepple <[email protected]> - * Arnaud Quette <[email protected]> && <[email protected]> - * and distributed under the terms of the GNU General Public License. - * See the file ./COPYING in the source distribution for more information. - * - * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES - * OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - */ diff --git a/test_libhid.py b/test_libhid.py deleted file mode 100755 index 64d19e3..0000000 --- a/test_libhid.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/python -# -# This is just an example. Please see the test_libhid.c file for more -# comments. -# - -CBW = "/0x55/0x53/0x42/0x43/0/16/2/0/" - -import sys - -# allow it to run right out of the build dir -import os -libsdir = os.getcwd() + '/.libs' -if os.path.isdir(libsdir) and os.path.isfile(libsdir + '/_hid.so'): - sys.path.insert(0, libsdir) - -from hid import * - -def open_interface(interface, matcher): - hid = hid_new_HIDInterface() - ret = hid_force_open(hid, interface, matcher, 3) - if ret != HID_RET_SUCCESS: - sys.stderr.write("hid_force_open %s failed with return code %d.\n" % (interface, ret)) - return hid - -def close_interface(hid): - ret = hid_close(hid) - if ret != HID_RET_SUCCESS: - sys.stderr.write("hid_close failed with return code %d.\n" % ret) - -def main(): - hid_set_debug(HID_DEBUG_WARNINGS) - hid_set_debug_stream(sys.stderr) - hid_set_usb_debug(0) - - ret = hid_init() - - matcher = HIDInterfaceMatcher() - matcher.vendor_id = 0x1130 - matcher.product_id = 0x0202 - - hid_interface_1 = open_interface(1, matcher) - hid_interface_0 = open_interface(0, matcher) - sys.exit() - # Set_Report with report type output, report ID 0, interface 1, and length 8 - - ret = hid_set_output_report(hid_interface_1, (), "8") - - # OUT transaction to endpoint 0 with CBW indicates write and length. - ret = hid_interrupt_write(hid_interface_0, 0x81, CBW, 1000); - - # Set_Report with report type output, report ID 0, interface 0, length 16. - - ret = hid_set_output_report(hid_interface_0, (), "16") - - # OUT transaction to endpoint 0 with data and length 8. - - ret = hid_interrupt_write(hid_interface_0, 0x81, "/0xff/0xfe/0xfd/0xfc/0xfb/0xfa/0xf9/0xf9", 1000); - - # OUT transaction to endpoint 0 with data and length 8. - - ret = hid_interrupt_write(hid_interface_0, 0x81, "/0xf7/0xf6/0xf5/0xf4/0xf3/0xf2/0xf1/0xf0", 1000); - - close_interface(hid_interface_1) - - hid_cleanup() - -if __name__ == '__main__': - main() - -# COPYRIGHT -- -# -# This file is part of libhid, a user-space HID access library. -# libhid is (c) 2003-2005 -# Martin F. Krafft <[email protected]> -# Charles Lepple <[email protected]> -# Arnaud Quette <[email protected]> && <[email protected]> -# and distributed under the terms of the GNU General Public License. -# See the file ./COPYING in the source distribution for more information. -# -# THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED -# WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES -# OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. diff --git a/usb_descriptors b/usb_descriptors deleted file mode 100644 index 7051fd6..0000000 --- a/usb_descriptors +++ /dev/null @@ -1,140 +0,0 @@ - -Bus 001 Device 005: ID 1130:0202 Tenx Technology, Inc. -Device Descriptor: - bLength 18 - bDescriptorType 1 - bcdUSB 1.10 - bDeviceClass 0 (Defined at Interface level) - bDeviceSubClass 0 - bDeviceProtocol 0 - bMaxPacketSize0 8 - idVendor 0x1130 Tenx Technology, Inc. - idProduct 0x0202 - bcdDevice 1.00 - iManufacturer 0 - iProduct 2 USB Test&Demo Alarm&Leds - iSerial 0 - bNumConfigurations 1 - Configuration Descriptor: - bLength 9 - bDescriptorType 2 - wTotalLength 59 - bNumInterfaces 2 - bConfigurationValue 1 - iConfiguration 0 - bmAttributes 0x80 - (Bus Powered) - MaxPower 200mA - Interface Descriptor: - bLength 9 - bDescriptorType 4 - bInterfaceNumber 0 - bAlternateSetting 0 - bNumEndpoints 1 - bInterfaceClass 3 Human Interface Device - bInterfaceSubClass 0 No Subclass - bInterfaceProtocol 0 None - iInterface 0 - HID Device Descriptor: - bLength 9 - bDescriptorType 33 - bcdHID 1.10 - bCountryCode 0 Not supported - bNumDescriptors 1 - bDescriptorType 34 Report - wDescriptorLength 41 - Report Descriptor: (length is 41) - Item(Global): Usage Page, data= [ 0x01 ] 1 - Generic Desktop Controls - Item(Local ): Usage, data= [ 0x00 ] 0 - Undefined - Item(Main ): Collection, data= [ 0x01 ] 1 - Application - Item(Global): Report Count, data= [ 0x08 ] 8 - Item(Global): Report Size, data= [ 0x08 ] 8 - Item(Global): Logical Minimum, data= [ 0x00 ] 0 - Item(Global): Logical Maximum, data= [ 0xff 0x00 ] 255 - Item(Global): Usage Page, data= [ 0x07 ] 7 - Keyboard - Item(Local ): Usage Minimum, data= [ 0x00 ] 0 - No Event - Item(Local ): Usage Maximum, data= [ 0xff 0x00 ] 255 - (null) - Item(Main ): Input, data= [ 0x00 ] 0 - Data Array Absolute No_Wrap Linear - Preferred_State No_Null_Position Non_Volatile Bitfield - Item(Global): Logical Minimum, data= [ 0x00 ] 0 - Item(Global): Logical Maximum, data= [ 0x01 ] 1 - Item(Global): Report Count, data= [ 0x80 ] 128 - Item(Global): Report Size, data= [ 0x01 ] 1 - Item(Global): Usage Page, data= [ 0x08 ] 8 - LEDs - Item(Local ): Usage Minimum, data= [ 0x01 ] 1 - NumLock - Item(Local ): Usage Maximum, data= [ 0x80 ] 128 - (null) - Item(Main ): Output, data= [ 0x02 ] 2 - Data Variable Absolute No_Wrap Linear - Preferred_State No_Null_Position Non_Volatile Bitfield - Item(Main ): End Collection, data=none - Endpoint Descriptor: - bLength 7 - bDescriptorType 5 - bEndpointAddress 0x81 EP 1 IN - bmAttributes 3 - Transfer Type Interrupt - Synch Type None - Usage Type Data - wMaxPacketSize 0x0008 1x 8 bytes - bInterval 10 - Interface Descriptor: - bLength 9 - bDescriptorType 4 - bInterfaceNumber 1 - bAlternateSetting 0 - bNumEndpoints 1 - bInterfaceClass 3 Human Interface Device - bInterfaceSubClass 0 No Subclass - bInterfaceProtocol 0 None - iInterface 0 - HID Device Descriptor: - bLength 9 - bDescriptorType 33 - bcdHID 1.10 - bCountryCode 33 US - bNumDescriptors 1 - bDescriptorType 34 Report - wDescriptorLength 23 - Report Descriptor: (length is 23) - Item(Global): Usage Page, data= [ 0x01 ] 1 - Generic Desktop Controls - Item(Local ): Usage, data= [ 0x03 ] 3 - (null) - Item(Main ): Collection, data= [ 0x01 ] 1 - Application - Item(Global): Logical Minimum, data= [ 0x00 ] 0 - Item(Global): Logical Maximum, data= [ 0x01 ] 1 - Item(Global): Report Count, data= [ 0x40 ] 64 - Item(Global): Report Size, data= [ 0x01 ] 1 - Item(Global): Usage Page, data= [ 0x08 ] 8 - LEDs - Item(Local ): Usage Minimum, data= [ 0x01 ] 1 - NumLock - Item(Local ): Usage Maximum, data= [ 0x40 ] 64 - Indicator Fast Blink - Item(Main ): Output, data= [ 0x02 ] 2 - Data Variable Absolute No_Wrap Linear - Preferred_State No_Null_Position Non_Volatile Bitfield - Item(Main ): End Collection, data=none - Endpoint Descriptor: - bLength 7 - bDescriptorType 5 - bEndpointAddress 0x82 EP 2 IN - bmAttributes 3 - Transfer Type Interrupt - Synch Type None - Usage Type Data - wMaxPacketSize 0x0008 1x 8 bytes - bInterval 10 -Device Status: 0x0000 - (Bus Powered) diff --git a/values.py b/values.py deleted file mode 100644 index 4037086..0000000 --- a/values.py +++ /dev/null @@ -1,24 +0,0 @@ -GREEN_LIGHT = (0x5a,0x5a,0x5a,0x5a, - 0x5a,0x5a,0x5a,0x5a, - 0x5a,0x5a,0x5a,0x5a, - 0x5a,0x5a,0x5a,0x5a) - -# or 0 1 4 9 10 19 24 31 40 51 64 79 90 a9 c4 e1 -RED_LIGHT_WITH_BELL = (0x0, 0x1, 0x4, 0x9, - 0x10, 0x19, 0x24, 0x31, - 0x40, 0x51, 0x64, 0x79, - 0x90, 0xa9, 0xc4, 0xe1) - -# or 0 1 2 3 4 5 6 7 8 9 a b c d e f -DONT_REMEMBER = (0x0, 0x1, 0x2, 0x3, - 0x4, 0x5, 0x6, 0x7, - 0x8, 0x9, 0xa, 0xb, - 0xc, 0xd, 0xe, 0xf) - -# or ff fe fd fc fb fa f9 f8 f7 f6 f5 f4 f3 f2 f1 f0 -ALL_OFF = (0xff, 0xfe, 0xfd, 0xfc, - 0xfb, 0xfa, 0xf9, 0xf8, - 0xf7, 0xf6, 0xf5, 0xf4, - 0xf3, 0xf2, 0xf1, 0xf0) - -#CBW= (0x55, 0x53, 0x42, 0x43, 0, 16, 2, 0)
tristil/agile-lamp
aeae31ad90deea0136953b5ed2ffd87c4e75a5ae
Control and documentation.
diff --git a/README b/README index 5449d43..df85a41 100644 --- a/README +++ b/README @@ -1,11 +1,17 @@ +Compile +------- +On Linux compile agilelamp.c with: +gcc agilelamp.c -o agilelamp -lusb +(needs libusb -dev headers installed) + Git tips: --------- * git config --global user.name "Your Name Comes Here" * git config --global user.email [email protected] * git push [email protected]:agile-lamp/meihomes-clone.git Helpful information about USB: http://www.beyondlogic.org/usbnutshell/usb1.htm particularly: requests -- http://www.beyondlogic.org/usbnutshell/usb6.htm transfer/endpoint types -- http://www.beyondlogic.org/usbnutshell/usb6.htm diff --git a/agilelamp.c b/agilelamp.c index fa3f090..c32112e 100644 --- a/agilelamp.c +++ b/agilelamp.c @@ -1,141 +1,175 @@ #include <usb.h> #include <stdio.h> #include <unistd.h> #include <string.h> usb_dev_handle* launcher; //wrapper for control_msg int send_message(char* msg, int index) { int i = 0; int j = usb_control_msg(launcher, 0x21, 0x9, 0x0, index, msg, 8, 1000); return j; } void send_cbw(){ fprintf(stderr, "Sending CBW message\n"); char cbw_message[8] = {0x55, 0x53, 0x42, 0x43, 0, 16, 2, 0}; int ret = send_message(cbw_message, 1); fprintf(stderr, "%d bytes sent\n", ret); } void send_lamp_command(char* title, char* message1, char* message2){ usb_reset(launcher); send_cbw(); fprintf(stderr, "Submitting %s\n", title); int ret = send_message(message1, 0); fprintf(stderr, "%d bytes sent\n", ret); ret = send_message(message2, 0); fprintf(stderr, "%d bytes sent\n", ret); } void set_red_with_bell(){ char message_part_1[8] = {0x0, 0x1, 0x4, 0x9,0x10, 0x19, 0x24, 0x31}; //red with bell char message_part_2[8] = {0x40, 0x51, 0x64, 0x79, 0x90, 0xa9, 0xc4, 0xe1}; // red with bell send_lamp_command("red with bell", message_part_1, message_part_2); } +/* +Fun with bit-math: + +Everything on the first (from right) 8 bits of first (from right) byte + +b0:=1:Bell active;=0:Bell off +b1:=1:Green led on; =0:Green led off +b2:=1:Red led on;=0:red led off +b3:=0:7 colors led on;=1:7 colors led off + + b0 +1 1 1 1 1 111 +128 64 32 16 8 421 = 255 + +c c c c c rgb (c's are colors to cycle through, then red, green, bell) + +0 0 0 16 0 000 = + +*/ + +void only_bell_on(){ + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; + char message_part_2[8] = {0,0,0,0, 0,0,0,1}; + send_lamp_command("green", message_part_1, message_part_2); +} + +void red_with_no_bell(){ + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; + char message_part_2[8] = {0,0,0,0, 0,0,0,4}; + send_lamp_command("red with no bell", message_part_1, message_part_2); +} + void set_green(){ - char message_part_1[8] = {0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a}; //green - char message_part_2[8] = {0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a}; // green + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //green + char message_part_2[8] = {0,0,0,0 ,0,0,0,2}; // green send_lamp_command("green", message_part_1, message_part_2); } void set_lights_off(){ - char message_part_1[8] = {0x0, 0x1, 0x4, 0x9,0x10, 0x19, 0x24, 0x31}; //red with bell - char message_part_2[8] = {0x40, 0x51, 0x64, 0x79, 0x90, 0xa9, 0xc4, 0xe1}; // red with bell + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; // lights off + char message_part_2[8] = {0,0,0,0, 0,0,0,0}; // lights off send_lamp_command("lights off", message_part_1, message_part_2); } void set_colors_with_bell(){ - char message_part_1[8] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7}; //colors with bell - char message_part_2[8] = {0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf}; // colors with bells + char message_part_1[8] = {0,0,0,0, 0,0,0,0}; //colors with bell + char message_part_2[8] = {0,0,0,0, 0,0,0,24}; // colors with bells send_lamp_command("colors with bells", message_part_1, message_part_2); } int load_device(){ int claimed; fprintf(stderr, "Starting\n"); struct usb_bus *busses; usb_init(); fprintf(stderr, "usb_init...\n"); usb_find_busses(); usb_find_devices(); fprintf(stderr, "Found busses, found devices...\n"); busses = usb_get_busses(); fprintf(stderr, "Got busses...\n"); struct usb_bus *bus; int c, i, a; /* ... */ for (bus = busses; bus; bus = bus->next) { struct usb_device *dev; for (dev = bus->devices; dev; dev = dev->next) { /* Check if this device is a printer */ if (dev->descriptor.idVendor == 4400) if(dev->descriptor.idProduct == 514) launcher = usb_open(dev); } } fprintf(stderr, "Got launcher...\n"); //do stuff if(launcher != NULL) { int claimed = usb_claim_interface(launcher, 1); } else { fprintf(stderr, "You didn't really get the launcher!\n"); return 1; } usb_detach_kernel_driver_np(launcher, 1); usb_detach_kernel_driver_np(launcher, 0); if (claimed == 0) { usb_release_interface(launcher, 1); return 1; } else if (claimed > 0){ fprintf(stderr, "Found launcher...\n"); } } int main(int argc, char *argv[]) { if ( argc != 2 ) /* argc should be 2 for correct execution */ { /* We print argv[0] assuming it is the program name */ printf( "usage: %s filename\n", argv[0] ); } else { int ret = load_device(); char* argument = argv[1]; if(strcmp(argument, "green") == 0){ set_green(); } else if (strcmp(argument, "red") == 0){ - set_red_with_bell(); + red_with_no_bell(); } else if (strcmp(argument, "off") == 0){ set_lights_off(); } else if (strcmp(argument, "various") == 0){ set_colors_with_bell(); + } else if (strcmp(argument, "bell") == 0){ + only_bell_on(); } } return 0; } diff --git a/lavalamp.py b/lavalamp.py index 305aab3..4a91d3f 100644 --- a/lavalamp.py +++ b/lavalamp.py @@ -1,50 +1,50 @@ import usb -from values import * - -def get_device(): - busses = usb.busses() - device = None - for bus in busses: - devices = bus.devices - for dev in devices: - if dev.idVendor == 0x1130 and dev.idProduct == 0x0202: - device = dev - return device - return None - -def ready_interface(handle, interface, interface_num): - try: - handle.detachKernelDriver(interface_num) - except: - pass - handle.claimInterface(interface) - -def open_device(): - device = get_device() - print "Version is %s" % device.usbVersion - print "Device is %s" % device.iManufacturer - configuration = device.configurations[0] - iface1 = configuration.interfaces[0][0] - iface2 = configuration.interfaces[1][0] - handle = device.open() - try: - handle.setConfiguration(configuration) - except: - pass - ready_interface(handle, iface1, 0) - ready_interface(handle, iface2, 1) - handle.reset() - return handle - - -handle = open_device() -handle.controlMsg(0x21, 0x09, (), 8, 0x1) #Set_report with report type output, report id 0, interface 1, length 8 -#handle.bulkWrite(0x82, CBW) -handle.interruptWrite(0x81, CBW) # OUT to endpoint 0 with CBW and length -handle.controlMsg(0x21, 0x09, (), 16, 0x0) #Set_report with report type output, report id 0, interface 1, length 8 -#handle.bulkWrite(0x82, GREEN_LIGHT) -handle.interruptWrite(0x81, GREEN_LIGHT) # OUT to endpoint 0 with data and length 8 +class DeviceDescriptor(object) : + def __init__(self, vendor_id, product_id, interface_id) : + self.vendor_id = vendor_id + self.product_id = product_id + self.interface_id = interface_id + def getDevice(self) : + """ + Return the device corresponding to the device descriptor if it is + available on a USB bus. Otherwise, return None. Note that the + returned device has yet to be claimed or opened. + """ + buses = usb.busses() + for bus in buses : + for device in bus.devices : + if device.idVendor == self.vendor_id : + if device.idProduct == self.product_id : + return device + return None +VENDOR_ID = 0x1130 +PRODUCT_ID = 0x0202 + +device_descriptor = DeviceDescriptor(VENDOR_ID, PRODUCT_ID, 1) +device = device_descriptor.getDevice() +handle = device.open() +handle.claimInterface(1) + +# Set_Report with report type output, report ID 0, interface 1, and length 8 + +#ret = hid_set_output_report(hid_interface_1, (), "8") + +# OUT transaction to endpoint 0 with CBW indicates write and length. +#ret = hid_interrupt_write(hid_interface_0, 0x81, CBW, 1000); + +# Set_Report with report type output, report ID 0, interface 0, length 16. + +#ret = hid_set_output_report(hid_interface_0, (), "16") + +# OUT transaction to endpoint 0 with data and length 8. + +#ret = hid_interrupt_write(hid_interface_0, 0x81, "/0xff/0xfe/0xfd/0xfc/0xfb/0xfa/0xf9/0xf9", 1000); + +# OUT transaction to endpoint 0 with data and length 8. + +#ret = hid_interrupt_write(hid_interface_0, 0x81, "/0xf7/0xf6/0xf5/0xf4/0xf3/0xf2/0xf1/0xf0", 1000); + diff --git a/test_libhid.py b/test_libhid.py index ab6432e..64d19e3 100755 --- a/test_libhid.py +++ b/test_libhid.py @@ -1,83 +1,83 @@ #!/usr/bin/python # # This is just an example. Please see the test_libhid.c file for more # comments. # CBW = "/0x55/0x53/0x42/0x43/0/16/2/0/" import sys # allow it to run right out of the build dir import os libsdir = os.getcwd() + '/.libs' if os.path.isdir(libsdir) and os.path.isfile(libsdir + '/_hid.so'): sys.path.insert(0, libsdir) from hid import * def open_interface(interface, matcher): hid = hid_new_HIDInterface() ret = hid_force_open(hid, interface, matcher, 3) if ret != HID_RET_SUCCESS: sys.stderr.write("hid_force_open %s failed with return code %d.\n" % (interface, ret)) return hid def close_interface(hid): ret = hid_close(hid) if ret != HID_RET_SUCCESS: sys.stderr.write("hid_close failed with return code %d.\n" % ret) def main(): hid_set_debug(HID_DEBUG_WARNINGS) hid_set_debug_stream(sys.stderr) hid_set_usb_debug(0) ret = hid_init() matcher = HIDInterfaceMatcher() matcher.vendor_id = 0x1130 matcher.product_id = 0x0202 hid_interface_1 = open_interface(1, matcher) hid_interface_0 = open_interface(0, matcher) - + sys.exit() # Set_Report with report type output, report ID 0, interface 1, and length 8 ret = hid_set_output_report(hid_interface_1, (), "8") # OUT transaction to endpoint 0 with CBW indicates write and length. ret = hid_interrupt_write(hid_interface_0, 0x81, CBW, 1000); # Set_Report with report type output, report ID 0, interface 0, length 16. ret = hid_set_output_report(hid_interface_0, (), "16") # OUT transaction to endpoint 0 with data and length 8. ret = hid_interrupt_write(hid_interface_0, 0x81, "/0xff/0xfe/0xfd/0xfc/0xfb/0xfa/0xf9/0xf9", 1000); # OUT transaction to endpoint 0 with data and length 8. ret = hid_interrupt_write(hid_interface_0, 0x81, "/0xf7/0xf6/0xf5/0xf4/0xf3/0xf2/0xf1/0xf0", 1000); close_interface(hid_interface_1) hid_cleanup() if __name__ == '__main__': main() # COPYRIGHT -- # # This file is part of libhid, a user-space HID access library. # libhid is (c) 2003-2005 # Martin F. Krafft <[email protected]> # Charles Lepple <[email protected]> # Arnaud Quette <[email protected]> && <[email protected]> # and distributed under the terms of the GNU General Public License. # See the file ./COPYING in the source distribution for more information. # # THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED # WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES # OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
tristil/agile-lamp
80d8f625f0fc08758daa1a1e3f4c787296b50665
Finally, a working application.
diff --git a/agilelamp.c b/agilelamp.c new file mode 100644 index 0000000..fa3f090 --- /dev/null +++ b/agilelamp.c @@ -0,0 +1,141 @@ +#include <usb.h> +#include <stdio.h> +#include <unistd.h> +#include <string.h> + +usb_dev_handle* launcher; +//wrapper for control_msg +int send_message(char* msg, int index) +{ + int i = 0; + int j = usb_control_msg(launcher, 0x21, 0x9, 0x0, index, msg, 8, 1000); + return j; +} + +void send_cbw(){ + fprintf(stderr, "Sending CBW message\n"); + char cbw_message[8] = {0x55, 0x53, 0x42, 0x43, 0, 16, 2, 0}; + int ret = send_message(cbw_message, 1); + fprintf(stderr, "%d bytes sent\n", ret); +} + +void send_lamp_command(char* title, char* message1, char* message2){ + usb_reset(launcher); + send_cbw(); + fprintf(stderr, "Submitting %s\n", title); + int ret = send_message(message1, 0); + fprintf(stderr, "%d bytes sent\n", ret); + ret = send_message(message2, 0); + fprintf(stderr, "%d bytes sent\n", ret); +} + +void set_red_with_bell(){ + char message_part_1[8] = {0x0, 0x1, 0x4, 0x9,0x10, 0x19, 0x24, 0x31}; //red with bell + char message_part_2[8] = {0x40, 0x51, 0x64, 0x79, 0x90, 0xa9, 0xc4, 0xe1}; // red with bell + send_lamp_command("red with bell", message_part_1, message_part_2); +} + +void set_green(){ + char message_part_1[8] = {0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a}; //green + char message_part_2[8] = {0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a}; // green + send_lamp_command("green", message_part_1, message_part_2); +} + +void set_lights_off(){ + char message_part_1[8] = {0x0, 0x1, 0x4, 0x9,0x10, 0x19, 0x24, 0x31}; //red with bell + char message_part_2[8] = {0x40, 0x51, 0x64, 0x79, 0x90, 0xa9, 0xc4, 0xe1}; // red with bell + send_lamp_command("lights off", message_part_1, message_part_2); +} + +void set_colors_with_bell(){ + char message_part_1[8] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7}; //colors with bell + char message_part_2[8] = {0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf}; // colors with bells + send_lamp_command("colors with bells", message_part_1, message_part_2); +} + +int load_device(){ + int claimed; + + fprintf(stderr, "Starting\n"); + + struct usb_bus *busses; + + usb_init(); + + fprintf(stderr, "usb_init...\n"); + + usb_find_busses(); + usb_find_devices(); + fprintf(stderr, "Found busses, found devices...\n"); + + busses = usb_get_busses(); + + fprintf(stderr, "Got busses...\n"); + + struct usb_bus *bus; + int c, i, a; + + /* ... */ + + for (bus = busses; bus; bus = bus->next) + { + struct usb_device *dev; + + for (dev = bus->devices; dev; dev = dev->next) + { + /* Check if this device is a printer */ + if (dev->descriptor.idVendor == 4400) + if(dev->descriptor.idProduct == 514) + launcher = usb_open(dev); + } + } + + fprintf(stderr, "Got launcher...\n"); + + //do stuff + if(launcher != NULL) + { + int claimed = usb_claim_interface(launcher, 1); + } + else + { + fprintf(stderr, "You didn't really get the launcher!\n"); + return 1; + } + + usb_detach_kernel_driver_np(launcher, 1); + usb_detach_kernel_driver_np(launcher, 0); + + if (claimed == 0) + { + usb_release_interface(launcher, 1); + return 1; + } else if (claimed > 0){ + fprintf(stderr, "Found launcher...\n"); + } + +} + +int main(int argc, char *argv[]) +{ + if ( argc != 2 ) /* argc should be 2 for correct execution */ + { + /* We print argv[0] assuming it is the program name */ + printf( "usage: %s filename\n", argv[0] ); + } + else + { + int ret = load_device(); + char* argument = argv[1]; + if(strcmp(argument, "green") == 0){ + set_green(); + } else if (strcmp(argument, "red") == 0){ + set_red_with_bell(); + } else if (strcmp(argument, "off") == 0){ + set_lights_off(); + } else if (strcmp(argument, "various") == 0){ + set_colors_with_bell(); + } + } + return 0; +}
tristil/agile-lamp
fb8fdddee6a28cfa2997cdf44d7a55d3968ee480
Add test_libhid.py
diff --git a/test_hid.c b/test_hid.c new file mode 100644 index 0000000..68c41ea --- /dev/null +++ b/test_hid.c @@ -0,0 +1,31 @@ +#include <hid.h> + +HIDInterface *hid; +hid_return ret; + +HIDInterfaceMatcher matcher = + { 0x0ce5, 0x0003, NULL, NULL, 0 }; +ret = hid_force_open(hid, 0, &matcher, 3); + +int const PATH_LEN = 2; +int const PATH_IN[2] = { 0xffa00001, 0xffa00003 }; + +int const WRITE_PACKET_LEN = 8; +char write_packet[8] = + { 0x04,0x7f,0x7f,0x00,0x02,0x00,0x00,0x00 }; + +int const READ_PACKET_LEN = 5; +char read_packet[5]; + +ret = hid_set_output_report(hid, + PATH_IN, + PATH_LEN, + write_packet, + WRITE_PACKET_LEN); + +ret = hid_interrupt_read(hid, + USB_ENDPOINT_IN+1, + read_packet, + READ_PACKET_LEN, + 0); + diff --git a/test_libhid.c b/test_libhid.c new file mode 100644 index 0000000..9c8511b --- /dev/null +++ b/test_libhid.c @@ -0,0 +1,140 @@ +#include <hid.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> /* for getopt() */ + +bool match_serial_number(struct usb_dev_handle* usbdev, void* custom, unsigned int len) +{ + bool ret; + char* buffer = (char*)malloc(len); + usb_get_string_simple(usbdev, usb_device(usbdev)->descriptor.iSerialNumber, + buffer, len); + ret = strncmp(buffer, (char*)custom, len) == 0; + free(buffer); + return ret; +} + +void set_debug(){ + /* see include/debug.h for possible values */ + hid_set_debug(HID_DEBUG_WARNINGS); + hid_set_debug_stream(stderr); + /* passed directly to libusb */ + hid_set_usb_debug(0); +} + +int do_hid_init(){ + hid_return ret; + fprintf(stderr, "Before hid_init\n"); + ret = hid_init(); + if (ret != HID_RET_SUCCESS) { + fprintf(stderr, "hid_init failed with return code %d\n", ret); + return 1; + } + fprintf(stderr, "After hid_init\n"); + return 0; +} + +int force_open_interface(HIDInterface * hid, HIDInterfaceMatcher matcher, int iface_num){ + hid_return ret; + ret = hid_force_open(hid, iface_num, &matcher, 5); + fprintf(stderr, "After hid_force_open %d\n", iface_num); + if (ret != HID_RET_SUCCESS) { + fprintf(stderr, "hid_force_open failed with return code %d\n", ret); + return 1; + } + return 0; +} + + + +int main(int argc, char *argv[]) +{ + HIDInterface* hid_interface_0; + HIDInterface* hid_interface_1; + hid_return ret; + + unsigned short vendor_id = 0x1130; + unsigned short product_id = 0x0202; + char *vendor, *product; + + int flag; + + HIDInterfaceMatcher matcher = { vendor_id, product_id, NULL, NULL, 0 }; + + set_debug(); + if(do_hid_init() == 1) + return 1; + + hid_interface_0 = hid_new_HIDInterface(); + if (hid_interface_0 == 0) { + fprintf(stderr, "hid_new_HIDInterface() failed, out of memory?\n"); + return 1; + } + fprintf(stderr, "After created new HIDInterface hid_interface_0 \n"); + + hid_interface_1 = hid_new_HIDInterface(); + if (hid_interface_1 == 0) { + fprintf(stderr, "hid_new_HIDInterface() failed, out of memory?\n"); + return 1; + } + fprintf(stderr, "After created new HIDInterface hid_interface_1\n"); + + if(force_open_interface(hid_interface_0, matcher, 0) == 1) + return 1; + if(force_open_interface(hid_interface_1, matcher, 1) == 1) + return 1; + + char write_cbw_packet[8] = {0x55, 0x53, 0x42, 0x43, 0, 16, 2,0}; + unsigned char const PATHLEN = 1; + int const PATH_IN[1] = { 4194304 }; + int const PATH_OUT[3] = { 0xffa00001, 0xffa00002, 0xffa10004 }; + + fprintf(stderr, "Before hid_set_output_report\n"); + ret = hid_set_output_report(hid_interface_1, PATH_IN, PATHLEN, "", 8); + ret = hid_interrupt_write(hid_interface_0, 0x81, write_cbw_packet, 8, 1000); + ret = hid_set_output_report(hid_interface_0, PATH_IN, PATHLEN, "", 16); + + printf("\n%d\n\n", ret); // Prints out '0' + + + + char green_light[16] = {0x5a,0x5a,0x5a,0x5a, + 0x5a,0x5a,0x5a,0x5a, + 0x5a,0x5a,0x5a,0x5a, + 0x5a,0x5a,0x5a,0x5a}; + + + fprintf(stderr, "Before hid_interrupt_write again:\n"); + ret = hid_interrupt_write(hid_interface_0, 0x81, green_light, 16, 1000); + printf("\n%d\n", ret); // Prints out '21' + + if (ret != HID_RET_SUCCESS) { + fprintf(stderr, "hid_cleanup failed with return code %d\n", ret); + return 1; + } + + ret = hid_close(hid_interface_0); + ret = hid_close(hid_interface_1); + + hid_delete_HIDInterface(&hid_interface_0); + hid_delete_HIDInterface(&hid_interface_1); + + ret = hid_cleanup(); + + return 0; +} + +/* COPYRIGHT -- + * + * This file is part of libhid, a user-space HID access library. + * libhid is (c) 2003-2005 + * Martin F. Krafft <[email protected]> + * Charles Lepple <[email protected]> + * Arnaud Quette <[email protected]> && <[email protected]> + * and distributed under the terms of the GNU General Public License. + * See the file ./COPYING in the source distribution for more information. + * + * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES + * OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ diff --git a/test_libhid.py b/test_libhid.py new file mode 100755 index 0000000..ab6432e --- /dev/null +++ b/test_libhid.py @@ -0,0 +1,83 @@ +#!/usr/bin/python +# +# This is just an example. Please see the test_libhid.c file for more +# comments. +# + +CBW = "/0x55/0x53/0x42/0x43/0/16/2/0/" + +import sys + +# allow it to run right out of the build dir +import os +libsdir = os.getcwd() + '/.libs' +if os.path.isdir(libsdir) and os.path.isfile(libsdir + '/_hid.so'): + sys.path.insert(0, libsdir) + +from hid import * + +def open_interface(interface, matcher): + hid = hid_new_HIDInterface() + ret = hid_force_open(hid, interface, matcher, 3) + if ret != HID_RET_SUCCESS: + sys.stderr.write("hid_force_open %s failed with return code %d.\n" % (interface, ret)) + return hid + +def close_interface(hid): + ret = hid_close(hid) + if ret != HID_RET_SUCCESS: + sys.stderr.write("hid_close failed with return code %d.\n" % ret) + +def main(): + hid_set_debug(HID_DEBUG_WARNINGS) + hid_set_debug_stream(sys.stderr) + hid_set_usb_debug(0) + + ret = hid_init() + + matcher = HIDInterfaceMatcher() + matcher.vendor_id = 0x1130 + matcher.product_id = 0x0202 + + hid_interface_1 = open_interface(1, matcher) + hid_interface_0 = open_interface(0, matcher) + + # Set_Report with report type output, report ID 0, interface 1, and length 8 + + ret = hid_set_output_report(hid_interface_1, (), "8") + + # OUT transaction to endpoint 0 with CBW indicates write and length. + ret = hid_interrupt_write(hid_interface_0, 0x81, CBW, 1000); + + # Set_Report with report type output, report ID 0, interface 0, length 16. + + ret = hid_set_output_report(hid_interface_0, (), "16") + + # OUT transaction to endpoint 0 with data and length 8. + + ret = hid_interrupt_write(hid_interface_0, 0x81, "/0xff/0xfe/0xfd/0xfc/0xfb/0xfa/0xf9/0xf9", 1000); + + # OUT transaction to endpoint 0 with data and length 8. + + ret = hid_interrupt_write(hid_interface_0, 0x81, "/0xf7/0xf6/0xf5/0xf4/0xf3/0xf2/0xf1/0xf0", 1000); + + close_interface(hid_interface_1) + + hid_cleanup() + +if __name__ == '__main__': + main() + +# COPYRIGHT -- +# +# This file is part of libhid, a user-space HID access library. +# libhid is (c) 2003-2005 +# Martin F. Krafft <[email protected]> +# Charles Lepple <[email protected]> +# Arnaud Quette <[email protected]> && <[email protected]> +# and distributed under the terms of the GNU General Public License. +# See the file ./COPYING in the source distribution for more information. +# +# THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED +# WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES +# OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. diff --git a/usb_descriptors b/usb_descriptors new file mode 100644 index 0000000..7051fd6 --- /dev/null +++ b/usb_descriptors @@ -0,0 +1,140 @@ + +Bus 001 Device 005: ID 1130:0202 Tenx Technology, Inc. +Device Descriptor: + bLength 18 + bDescriptorType 1 + bcdUSB 1.10 + bDeviceClass 0 (Defined at Interface level) + bDeviceSubClass 0 + bDeviceProtocol 0 + bMaxPacketSize0 8 + idVendor 0x1130 Tenx Technology, Inc. + idProduct 0x0202 + bcdDevice 1.00 + iManufacturer 0 + iProduct 2 USB Test&Demo Alarm&Leds + iSerial 0 + bNumConfigurations 1 + Configuration Descriptor: + bLength 9 + bDescriptorType 2 + wTotalLength 59 + bNumInterfaces 2 + bConfigurationValue 1 + iConfiguration 0 + bmAttributes 0x80 + (Bus Powered) + MaxPower 200mA + Interface Descriptor: + bLength 9 + bDescriptorType 4 + bInterfaceNumber 0 + bAlternateSetting 0 + bNumEndpoints 1 + bInterfaceClass 3 Human Interface Device + bInterfaceSubClass 0 No Subclass + bInterfaceProtocol 0 None + iInterface 0 + HID Device Descriptor: + bLength 9 + bDescriptorType 33 + bcdHID 1.10 + bCountryCode 0 Not supported + bNumDescriptors 1 + bDescriptorType 34 Report + wDescriptorLength 41 + Report Descriptor: (length is 41) + Item(Global): Usage Page, data= [ 0x01 ] 1 + Generic Desktop Controls + Item(Local ): Usage, data= [ 0x00 ] 0 + Undefined + Item(Main ): Collection, data= [ 0x01 ] 1 + Application + Item(Global): Report Count, data= [ 0x08 ] 8 + Item(Global): Report Size, data= [ 0x08 ] 8 + Item(Global): Logical Minimum, data= [ 0x00 ] 0 + Item(Global): Logical Maximum, data= [ 0xff 0x00 ] 255 + Item(Global): Usage Page, data= [ 0x07 ] 7 + Keyboard + Item(Local ): Usage Minimum, data= [ 0x00 ] 0 + No Event + Item(Local ): Usage Maximum, data= [ 0xff 0x00 ] 255 + (null) + Item(Main ): Input, data= [ 0x00 ] 0 + Data Array Absolute No_Wrap Linear + Preferred_State No_Null_Position Non_Volatile Bitfield + Item(Global): Logical Minimum, data= [ 0x00 ] 0 + Item(Global): Logical Maximum, data= [ 0x01 ] 1 + Item(Global): Report Count, data= [ 0x80 ] 128 + Item(Global): Report Size, data= [ 0x01 ] 1 + Item(Global): Usage Page, data= [ 0x08 ] 8 + LEDs + Item(Local ): Usage Minimum, data= [ 0x01 ] 1 + NumLock + Item(Local ): Usage Maximum, data= [ 0x80 ] 128 + (null) + Item(Main ): Output, data= [ 0x02 ] 2 + Data Variable Absolute No_Wrap Linear + Preferred_State No_Null_Position Non_Volatile Bitfield + Item(Main ): End Collection, data=none + Endpoint Descriptor: + bLength 7 + bDescriptorType 5 + bEndpointAddress 0x81 EP 1 IN + bmAttributes 3 + Transfer Type Interrupt + Synch Type None + Usage Type Data + wMaxPacketSize 0x0008 1x 8 bytes + bInterval 10 + Interface Descriptor: + bLength 9 + bDescriptorType 4 + bInterfaceNumber 1 + bAlternateSetting 0 + bNumEndpoints 1 + bInterfaceClass 3 Human Interface Device + bInterfaceSubClass 0 No Subclass + bInterfaceProtocol 0 None + iInterface 0 + HID Device Descriptor: + bLength 9 + bDescriptorType 33 + bcdHID 1.10 + bCountryCode 33 US + bNumDescriptors 1 + bDescriptorType 34 Report + wDescriptorLength 23 + Report Descriptor: (length is 23) + Item(Global): Usage Page, data= [ 0x01 ] 1 + Generic Desktop Controls + Item(Local ): Usage, data= [ 0x03 ] 3 + (null) + Item(Main ): Collection, data= [ 0x01 ] 1 + Application + Item(Global): Logical Minimum, data= [ 0x00 ] 0 + Item(Global): Logical Maximum, data= [ 0x01 ] 1 + Item(Global): Report Count, data= [ 0x40 ] 64 + Item(Global): Report Size, data= [ 0x01 ] 1 + Item(Global): Usage Page, data= [ 0x08 ] 8 + LEDs + Item(Local ): Usage Minimum, data= [ 0x01 ] 1 + NumLock + Item(Local ): Usage Maximum, data= [ 0x40 ] 64 + Indicator Fast Blink + Item(Main ): Output, data= [ 0x02 ] 2 + Data Variable Absolute No_Wrap Linear + Preferred_State No_Null_Position Non_Volatile Bitfield + Item(Main ): End Collection, data=none + Endpoint Descriptor: + bLength 7 + bDescriptorType 5 + bEndpointAddress 0x82 EP 2 IN + bmAttributes 3 + Transfer Type Interrupt + Synch Type None + Usage Type Data + wMaxPacketSize 0x0008 1x 8 bytes + bInterval 10 +Device Status: 0x0000 + (Bus Powered) diff --git a/values.py b/values.py new file mode 100644 index 0000000..4037086 --- /dev/null +++ b/values.py @@ -0,0 +1,24 @@ +GREEN_LIGHT = (0x5a,0x5a,0x5a,0x5a, + 0x5a,0x5a,0x5a,0x5a, + 0x5a,0x5a,0x5a,0x5a, + 0x5a,0x5a,0x5a,0x5a) + +# or 0 1 4 9 10 19 24 31 40 51 64 79 90 a9 c4 e1 +RED_LIGHT_WITH_BELL = (0x0, 0x1, 0x4, 0x9, + 0x10, 0x19, 0x24, 0x31, + 0x40, 0x51, 0x64, 0x79, + 0x90, 0xa9, 0xc4, 0xe1) + +# or 0 1 2 3 4 5 6 7 8 9 a b c d e f +DONT_REMEMBER = (0x0, 0x1, 0x2, 0x3, + 0x4, 0x5, 0x6, 0x7, + 0x8, 0x9, 0xa, 0xb, + 0xc, 0xd, 0xe, 0xf) + +# or ff fe fd fc fb fa f9 f8 f7 f6 f5 f4 f3 f2 f1 f0 +ALL_OFF = (0xff, 0xfe, 0xfd, 0xfc, + 0xfb, 0xfa, 0xf9, 0xf8, + 0xf7, 0xf6, 0xf5, 0xf4, + 0xf3, 0xf2, 0xf1, 0xf0) + +#CBW= (0x55, 0x53, 0x42, 0x43, 0, 16, 2, 0)
tristil/agile-lamp
013c18522983c223c9e6008e769ce14e1907e5c6
Best attempt so far. Is the interface broken?
diff --git a/README b/README index d933100..5449d43 100644 --- a/README +++ b/README @@ -1,5 +1,11 @@ Git tips: --------- * git config --global user.name "Your Name Comes Here" * git config --global user.email [email protected] * git push [email protected]:agile-lamp/meihomes-clone.git + +Helpful information about USB: +http://www.beyondlogic.org/usbnutshell/usb1.htm +particularly: +requests -- http://www.beyondlogic.org/usbnutshell/usb6.htm +transfer/endpoint types -- http://www.beyondlogic.org/usbnutshell/usb6.htm diff --git a/lavalamp.py b/lavalamp.py index 5fb7174..305aab3 100644 --- a/lavalamp.py +++ b/lavalamp.py @@ -1,119 +1,50 @@ import usb - -# Code is to turn on/turn off lights and a bell on a USB lava lamp -# -# Manufacturer says: -# -# Host first issues the CBW(Command Block Wrapper) which indicates the command -# and length to endpoint 0 by Set_Report request with wIndex equal to 0 which -# indicates interface 0. Firmware will parse the CBW in order to determine the -# next response. Then host issue IN transaction to endpoint 1 or OUT transaction -# to endpoint 0 with wIndex equal to 1 which indicates interface 1. -# -# Also: -# -# Write buffer (02) Host will issue OUT packets with specified length following -# CBW packet. Firmware will save data into buffer. Currently only length 16 write -# is available. That means CBW could only specify the length 16. - -# These are values the manufacturer gave for testing. I don't really know how -# to use them, so I stuck them in tuples. - -# or 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a -GREEN_LIGHT = (0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a) - -# or 0 1 4 9 10 19 24 31 40 51 64 79 90 a9 c4 e1 -RED_LIGHT_WITH_BELL = (0x0, 0x1, 0x4, 0x9, 0x10, 0x19, 0x24, 0x31, 0x40, 0x51, 0x64, 0x79, 0x90, 0xa9, 0xc4, 0xe1) - -# or 0 1 2 3 4 5 6 7 8 9 a b c d e f -DONT_REMEMBER = (0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf) - -# or ff fe fd fc fb fa f9 f8 f7 f6 f5 f4 f3 f2 f1 f0 -ALL_OFF = (0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0) - -SIXTEEN_BYTE_THEORY = (0,0,0,0, 0,0,0,0, - 0,0,0,0, 0,0,0,0, - 0,0,0,0, 0,0,0,0, - 0,0,0,0, 0,0,0,0, - 0,0,0,0, 0,0,0,0, - 0,0,0,0, 0,0,0,0, - 0,0,0,0, 0,0,0,0, - 0,0,0,0, 0,0,0,5) -SIXTEEN_BYTE_THEORY_OTHER_WAY = (5,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0) - -SET_FEATURE_REQUEST_TYPE = usb.TYPE_STANDARD | usb.RECIP_ENDPOINT +from values import * def get_device(): busses = usb.busses() device = None for bus in busses: devices = bus.devices for dev in devices: if dev.idVendor == 0x1130 and dev.idProduct == 0x0202: device = dev return device return None def ready_interface(handle, interface, interface_num): try: handle.detachKernelDriver(interface_num) except: pass handle.claimInterface(interface) def open_device(): - # This stuff seems to be boilerplate for getting a device device = get_device() print "Version is %s" % device.usbVersion print "Device is %s" % device.iManufacturer configuration = device.configurations[0] iface1 = configuration.interfaces[0][0] iface2 = configuration.interfaces[1][0] handle = device.open() try: handle.setConfiguration(configuration) except: pass ready_interface(handle, iface1, 0) ready_interface(handle, iface2, 1) handle.reset() + return handle - # After this I want to do something with the devhandle. - - # I'm going on the assumption that control message is the same as CBW, but - # I don't have to construct the entire bitmap. Spec refers to set_Report, which - # is not a listed "requesttype" in libusb, but elsewhere it's listed as 0x21 - - # Python control message is requesttype, request, buffer, value, index - report_set = handle.controlMsg(0x21, 0x09, (), 0, 0x0) - print report_set - - # I don't know if that did anything. I also don't know if the next step is - # another "CBW"/control message or an interruptWrite or a bulkWrite. IN - # transaction to endpoint 1 makes me think interruptWrite. - - # Just reading to see if anything comes out - read = handle.bulkRead(0x82, 16, 1000) - print "First read is %s" % str(read) - - # This is where something needs to happen. - # 0x82 is endpoint2, the IN/writable endpoint - print "Writing to 0x82" - # interrupt-style messages are endpoint, buffer, timeout - handle.bulkWrite(0x82, SIXTEEN_BYTE_THEORY, 1000) - handle.interruptWrite(0x82, SIXTEEN_BYTE_THEORY, 1000) - handle.controlMsg(SET_FEATURE_REQUEST_TYPE, usb.REQ_SET_FEATURE, SIXTEEN_BYTE_THEORY, 32, 0x82) +handle = open_device() +handle.controlMsg(0x21, 0x09, (), 8, 0x1) #Set_report with report type output, report id 0, interface 1, length 8 +#handle.bulkWrite(0x82, CBW) +handle.interruptWrite(0x81, CBW) # OUT to endpoint 0 with CBW and length +handle.controlMsg(0x21, 0x09, (), 16, 0x0) #Set_report with report type output, report id 0, interface 1, length 8 +#handle.bulkWrite(0x82, GREEN_LIGHT) +handle.interruptWrite(0x81, GREEN_LIGHT) # OUT to endpoint 0 with data and length 8 - # I got this from http://www.beyondlogic.org/usbnutshell/usb6.htm under - # Standard Endpoint Requests, Standard Endpoint SET_FEATURE request. This - # gives a broken pipe message. - #wrote = handle.controlMsg(0x010b, 0x03, (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,9), 1, 0x82) - #wrote = handle.controlMsg(0x21, 0x09, (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,9), 0x0, 1) - #print wrote - read = handle.bulkRead(0x82, 16, 1000) - print "Second read (after 'write' is %s)" % str(read) -open_device()
tristil/agile-lamp
917677ec52a6ecdd7852a91ef8bf88d222c3337c
Small changes.
diff --git a/lavalamp.py b/lavalamp.py index 7c66364..5fb7174 100644 --- a/lavalamp.py +++ b/lavalamp.py @@ -1,108 +1,119 @@ import usb # Code is to turn on/turn off lights and a bell on a USB lava lamp # # Manufacturer says: # # Host first issues the CBW(Command Block Wrapper) which indicates the command # and length to endpoint 0 by Set_Report request with wIndex equal to 0 which # indicates interface 0. Firmware will parse the CBW in order to determine the # next response. Then host issue IN transaction to endpoint 1 or OUT transaction # to endpoint 0 with wIndex equal to 1 which indicates interface 1. # # Also: # # Write buffer (02) Host will issue OUT packets with specified length following # CBW packet. Firmware will save data into buffer. Currently only length 16 write # is available. That means CBW could only specify the length 16. # These are values the manufacturer gave for testing. I don't really know how # to use them, so I stuck them in tuples. # or 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a GREEN_LIGHT = (0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a) # or 0 1 4 9 10 19 24 31 40 51 64 79 90 a9 c4 e1 RED_LIGHT_WITH_BELL = (0x0, 0x1, 0x4, 0x9, 0x10, 0x19, 0x24, 0x31, 0x40, 0x51, 0x64, 0x79, 0x90, 0xa9, 0xc4, 0xe1) # or 0 1 2 3 4 5 6 7 8 9 a b c d e f DONT_REMEMBER = (0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf) # or ff fe fd fc fb fa f9 f8 f7 f6 f5 f4 f3 f2 f1 f0 ALL_OFF = (0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0) +SIXTEEN_BYTE_THEORY = (0,0,0,0, 0,0,0,0, + 0,0,0,0, 0,0,0,0, + 0,0,0,0, 0,0,0,0, + 0,0,0,0, 0,0,0,0, + 0,0,0,0, 0,0,0,0, + 0,0,0,0, 0,0,0,0, + 0,0,0,0, 0,0,0,0, + 0,0,0,0, 0,0,0,5) +SIXTEEN_BYTE_THEORY_OTHER_WAY = (5,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0) + +SET_FEATURE_REQUEST_TYPE = usb.TYPE_STANDARD | usb.RECIP_ENDPOINT + def get_device(): busses = usb.busses() device = None for bus in busses: devices = bus.devices for dev in devices: if dev.idVendor == 0x1130 and dev.idProduct == 0x0202: device = dev return device return None def ready_interface(handle, interface, interface_num): try: handle.detachKernelDriver(interface_num) except: pass handle.claimInterface(interface) def open_device(): # This stuff seems to be boilerplate for getting a device device = get_device() print "Version is %s" % device.usbVersion print "Device is %s" % device.iManufacturer configuration = device.configurations[0] iface1 = configuration.interfaces[0][0] iface2 = configuration.interfaces[1][0] handle = device.open() try: handle.setConfiguration(configuration) except: pass ready_interface(handle, iface1, 0) ready_interface(handle, iface2, 1) handle.reset() # After this I want to do something with the devhandle. # I'm going on the assumption that control message is the same as CBW, but # I don't have to construct the entire bitmap. Spec refers to set_Report, which # is not a listed "requesttype" in libusb, but elsewhere it's listed as 0x21 # Python control message is requesttype, request, buffer, value, index report_set = handle.controlMsg(0x21, 0x09, (), 0, 0x0) print report_set # I don't know if that did anything. I also don't know if the next step is # another "CBW"/control message or an interruptWrite or a bulkWrite. IN # transaction to endpoint 1 makes me think interruptWrite. - sixteen_byte_string = (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,1) - # Just reading to see if anything comes out read = handle.bulkRead(0x82, 16, 1000) print "First read is %s" % str(read) # This is where something needs to happen. # 0x82 is endpoint2, the IN/writable endpoint print "Writing to 0x82" # interrupt-style messages are endpoint, buffer, timeout - handle.bulkWrite(0x82, sixteen_byte_string, 1000) - handle.bulkWrite(0x82, GREEN_LIGHT, 1000) - handle.interruptWrite(0x82, sixteen_byte_string, 1000) - handle.interruptWrite(0x82, GREEN_LIGHT, 1000) + handle.bulkWrite(0x82, SIXTEEN_BYTE_THEORY, 1000) + handle.interruptWrite(0x82, SIXTEEN_BYTE_THEORY, 1000) + handle.controlMsg(SET_FEATURE_REQUEST_TYPE, usb.REQ_SET_FEATURE, SIXTEEN_BYTE_THEORY, 32, 0x82) # I got this from http://www.beyondlogic.org/usbnutshell/usb6.htm under # Standard Endpoint Requests, Standard Endpoint SET_FEATURE request. This # gives a broken pipe message. - wrote = handle.controlMsg(0x010b, 0x03, (), 1, 0x82) + #wrote = handle.controlMsg(0x010b, 0x03, (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,9), 1, 0x82) + #wrote = handle.controlMsg(0x21, 0x09, (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,9), 0x0, 1) + #print wrote read = handle.bulkRead(0x82, 16, 1000) print "Second read (after 'write' is %s)" % str(read) open_device()
tristil/agile-lamp
2e65601f22601f4ee25c8041e119a364e21a4e0e
added readme
diff --git a/README b/README new file mode 100644 index 0000000..d933100 --- /dev/null +++ b/README @@ -0,0 +1,5 @@ +Git tips: +--------- + * git config --global user.name "Your Name Comes Here" + * git config --global user.email [email protected] + * git push [email protected]:agile-lamp/meihomes-clone.git
tristil/agile-lamp
f3a70cb04e87d49773287ee7a54fd44f353ae6d9
created doc dir
diff --git a/GenericHID_for_tmu3100_OK.exe b/doc/GenericHID_for_tmu3100_OK.exe similarity index 100% rename from GenericHID_for_tmu3100_OK.exe rename to doc/GenericHID_for_tmu3100_OK.exe diff --git a/doc/generic_hid_spec.doc b/doc/generic_hid_spec.doc new file mode 100644 index 0000000..893ebd1 Binary files /dev/null and b/doc/generic_hid_spec.doc differ
tristil/agile-lamp
129346846927a382460fe07a22fc12533083155c
Add python script attempt
diff --git a/lavalamp.py b/lavalamp.py new file mode 100644 index 0000000..7c66364 --- /dev/null +++ b/lavalamp.py @@ -0,0 +1,108 @@ +import usb + +# Code is to turn on/turn off lights and a bell on a USB lava lamp +# +# Manufacturer says: +# +# Host first issues the CBW(Command Block Wrapper) which indicates the command +# and length to endpoint 0 by Set_Report request with wIndex equal to 0 which +# indicates interface 0. Firmware will parse the CBW in order to determine the +# next response. Then host issue IN transaction to endpoint 1 or OUT transaction +# to endpoint 0 with wIndex equal to 1 which indicates interface 1. +# +# Also: +# +# Write buffer (02) Host will issue OUT packets with specified length following +# CBW packet. Firmware will save data into buffer. Currently only length 16 write +# is available. That means CBW could only specify the length 16. + +# These are values the manufacturer gave for testing. I don't really know how +# to use them, so I stuck them in tuples. + +# or 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a 5a +GREEN_LIGHT = (0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a) + +# or 0 1 4 9 10 19 24 31 40 51 64 79 90 a9 c4 e1 +RED_LIGHT_WITH_BELL = (0x0, 0x1, 0x4, 0x9, 0x10, 0x19, 0x24, 0x31, 0x40, 0x51, 0x64, 0x79, 0x90, 0xa9, 0xc4, 0xe1) + +# or 0 1 2 3 4 5 6 7 8 9 a b c d e f +DONT_REMEMBER = (0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf) + +# or ff fe fd fc fb fa f9 f8 f7 f6 f5 f4 f3 f2 f1 f0 +ALL_OFF = (0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0) + +def get_device(): + busses = usb.busses() + device = None + for bus in busses: + devices = bus.devices + for dev in devices: + if dev.idVendor == 0x1130 and dev.idProduct == 0x0202: + device = dev + return device + return None + +def ready_interface(handle, interface, interface_num): + try: + handle.detachKernelDriver(interface_num) + except: + pass + handle.claimInterface(interface) + +def open_device(): + # This stuff seems to be boilerplate for getting a device + device = get_device() + print "Version is %s" % device.usbVersion + print "Device is %s" % device.iManufacturer + configuration = device.configurations[0] + iface1 = configuration.interfaces[0][0] + iface2 = configuration.interfaces[1][0] + handle = device.open() + try: + handle.setConfiguration(configuration) + except: + pass + ready_interface(handle, iface1, 0) + ready_interface(handle, iface2, 1) + handle.reset() + + # After this I want to do something with the devhandle. + + # I'm going on the assumption that control message is the same as CBW, but + # I don't have to construct the entire bitmap. Spec refers to set_Report, which + # is not a listed "requesttype" in libusb, but elsewhere it's listed as 0x21 + + # Python control message is requesttype, request, buffer, value, index + report_set = handle.controlMsg(0x21, 0x09, (), 0, 0x0) + print report_set + + # I don't know if that did anything. I also don't know if the next step is + # another "CBW"/control message or an interruptWrite or a bulkWrite. IN + # transaction to endpoint 1 makes me think interruptWrite. + + sixteen_byte_string = (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,1) + + # Just reading to see if anything comes out + read = handle.bulkRead(0x82, 16, 1000) + print "First read is %s" % str(read) + + # This is where something needs to happen. + # 0x82 is endpoint2, the IN/writable endpoint + print "Writing to 0x82" + + # interrupt-style messages are endpoint, buffer, timeout + handle.bulkWrite(0x82, sixteen_byte_string, 1000) + handle.bulkWrite(0x82, GREEN_LIGHT, 1000) + handle.interruptWrite(0x82, sixteen_byte_string, 1000) + handle.interruptWrite(0x82, GREEN_LIGHT, 1000) + + # I got this from http://www.beyondlogic.org/usbnutshell/usb6.htm under + # Standard Endpoint Requests, Standard Endpoint SET_FEATURE request. This + # gives a broken pipe message. + + wrote = handle.controlMsg(0x010b, 0x03, (), 1, 0x82) + + read = handle.bulkRead(0x82, 16, 1000) + print "Second read (after 'write' is %s)" % str(read) + +open_device()
tristil/agile-lamp
c7dda66ba626c542c658955f04866d4e6bbbbe68
Add executable for downloads
diff --git a/GenericHID_for_tmu3100_OK.exe b/GenericHID_for_tmu3100_OK.exe new file mode 100644 index 0000000..a754564 Binary files /dev/null and b/GenericHID_for_tmu3100_OK.exe differ
tristil/agile-lamp
98a511aee2afc9f367ef050e001ebccebce56359
The lamp driver gem.
diff --git a/usb-lava-lamp/History.txt b/usb-lava-lamp/History.txt new file mode 100644 index 0000000..cd9e49b --- /dev/null +++ b/usb-lava-lamp/History.txt @@ -0,0 +1,4 @@ +== 0.0.1 2008-05-06 + +* 1 major enhancement: + * Initial release diff --git a/usb-lava-lamp/License.txt b/usb-lava-lamp/License.txt new file mode 100644 index 0000000..59a21c9 --- /dev/null +++ b/usb-lava-lamp/License.txt @@ -0,0 +1,20 @@ +Copyright (c) 2008 Joseph Method + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/usb-lava-lamp/Manifest.txt b/usb-lava-lamp/Manifest.txt new file mode 100644 index 0000000..76f79c6 --- /dev/null +++ b/usb-lava-lamp/Manifest.txt @@ -0,0 +1,25 @@ +History.txt +License.txt +Manifest.txt +PostInstall.txt +README.txt +Rakefile +config/hoe.rb +config/requirements.rb +lib/usb-lava-lamp.rb +lib/usb-lava-lamp/version.rb +script/console +script/destroy +script/generate +script/txt2html +setup.rb +tasks/deployment.rake +tasks/environment.rake +tasks/website.rake +test/test_helper.rb +test/test_usb-lava-lamp.rb +website/index.html +website/index.txt +website/javascripts/rounded_corners_lite.inc.js +website/stylesheets/screen.css +website/template.html.erb diff --git a/usb-lava-lamp/PostInstall.txt b/usb-lava-lamp/PostInstall.txt new file mode 100644 index 0000000..7d893db --- /dev/null +++ b/usb-lava-lamp/PostInstall.txt @@ -0,0 +1,7 @@ + +For more information on usb-lava-lamp, see http://usb-lava-lamp.rubyforge.org + +NOTE: Change this information in PostInstall.txt +You can also delete it if you don't want it. + + diff --git a/usb-lava-lamp/README.txt b/usb-lava-lamp/README.txt new file mode 100644 index 0000000..3fe746c --- /dev/null +++ b/usb-lava-lamp/README.txt @@ -0,0 +1,48 @@ += usb-lava-lamp + +* FIX (url) + +== DESCRIPTION: + +FIX (describe your package) + +== FEATURES/PROBLEMS: + +* FIX (list of features or problems) + +== SYNOPSIS: + + FIX (code sample of usage) + +== REQUIREMENTS: + +* FIX (list of requirements) + +== INSTALL: + +* FIX (sudo gem install, anything else) + +== LICENSE: + +(The MIT License) + +Copyright (c) 2008 FIX + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/usb-lava-lamp/Rakefile b/usb-lava-lamp/Rakefile new file mode 100644 index 0000000..e469154 --- /dev/null +++ b/usb-lava-lamp/Rakefile @@ -0,0 +1,4 @@ +require 'config/requirements' +require 'config/hoe' # setup Hoe + all gem configuration + +Dir['tasks/**/*.rake'].each { |rake| load rake } \ No newline at end of file diff --git a/usb-lava-lamp/config/hoe.rb b/usb-lava-lamp/config/hoe.rb new file mode 100644 index 0000000..4f58f1b --- /dev/null +++ b/usb-lava-lamp/config/hoe.rb @@ -0,0 +1,73 @@ +require 'usb-lava-lamp/version' + +AUTHOR = 'Joseph Method' # can also be an array of Authors +EMAIL = "[email protected]" +DESCRIPTION = "A gem providing control over the USB Lava Lamp" +GEM_NAME = 'usb-lava-lamp' # what ppl will type to install your gem +RUBYFORGE_PROJECT = 'usb-lava-lamp' # The unix name for your project +HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org" +DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" +EXTRA_DEPENDENCIES = [ +# ['activesupport', '>= 1.3.1'] +] # An array of rubygem dependencies [name, version] + +@config_file = "~/.rubyforge/user-config.yml" +@config = nil +RUBYFORGE_USERNAME = "unknown" +def rubyforge_username + unless @config + begin + @config = YAML.load(File.read(File.expand_path(@config_file))) + rescue + puts <<-EOS +ERROR: No rubyforge config file found: #{@config_file} +Run 'rubyforge setup' to prepare your env for access to Rubyforge + - See http://newgem.rubyforge.org/rubyforge.html for more details + EOS + exit + end + end + RUBYFORGE_USERNAME.replace @config["username"] +end + + +REV = nil +# UNCOMMENT IF REQUIRED: +# REV = YAML.load(`svn info`)['Revision'] +VERS = LavaLamp::VERSION::STRING + (REV ? ".#{REV}" : "") +RDOC_OPTS = ['--quiet', '--title', 'usb-lava-lamp documentation', + "--opname", "index.html", + "--line-numbers", + "--main", "README", + "--inline-source"] + +class Hoe + def extra_deps + @extra_deps.reject! { |x| Array(x).first == 'hoe' } + @extra_deps + end +end + +# Generate all the Rake tasks +# Run 'rake -T' to see list of generated tasks (from gem root directory) +$hoe = Hoe.new(GEM_NAME, VERS) do |p| + p.developer(AUTHOR, EMAIL) + p.description = DESCRIPTION + p.summary = DESCRIPTION + p.url = HOMEPATH + p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT + p.test_globs = ["test/**/test_*.rb"] + p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean. + + # == Optional + p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n") + #p.extra_deps = EXTRA_DEPENDENCIES + + #p.spec_extras = {} # A hash of extra values to set in the gemspec. + end + +CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n") +PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}" +$hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc') +$hoe.rsync_args = '-av --delete --ignore-errors' +$hoe.spec.post_install_message = File.open(File.dirname(__FILE__) + "/../PostInstall.txt").read rescue "" diff --git a/usb-lava-lamp/config/requirements.rb b/usb-lava-lamp/config/requirements.rb new file mode 100644 index 0000000..9292b69 --- /dev/null +++ b/usb-lava-lamp/config/requirements.rb @@ -0,0 +1,15 @@ +require 'fileutils' +include FileUtils + +require 'rubygems' +%w[rake hoe newgem rubigen].each do |req_gem| + begin + require req_gem + rescue LoadError + puts "This Rakefile requires the '#{req_gem}' RubyGem." + puts "Installation: gem install #{req_gem} -y" + exit + end +end + +$:.unshift(File.join(File.dirname(__FILE__), %w[.. lib])) diff --git a/usb-lava-lamp/devices.txt b/usb-lava-lamp/devices.txt new file mode 100644 index 0000000..6ae2abc --- /dev/null +++ b/usb-lava-lamp/devices.txt @@ -0,0 +1 @@ +[#<USB::Device 001/001 0000:0000 (Full speed Hub)>, #<USB::Device 001/004 05ac:0217 (HID (01,01), HID (01,02), HID (00,00))>, #<USB::Device 001/006 046d:c00e (HID (01,02))>, #<USB::Device 002/001 0000:0000 (Full speed Hub)>, #<USB::Device 002/004 1130:0202 (HID (00,00), HID (00,00))>, #<USB::Device 003/001 0000:0000 (Full speed Hub)>, #<USB::Device 003/002 05ac:8240 (HID (00,00))>, #<USB::Device 004/001 0000:0000 (Full speed Hub)>, #<USB::Device 004/003 05ac:8205 (Bluetooth)>, #<USB::Device 005/001 0000:0000 (Hi-speed Hub with single TT)>, #<USB::Device 005/003 05ac:8300 (Vendor specific (ff,ff))>] \ No newline at end of file diff --git a/usb-lava-lamp/lib/usb-lava-lamp.rb b/usb-lava-lamp/lib/usb-lava-lamp.rb new file mode 100644 index 0000000..d3a8407 --- /dev/null +++ b/usb-lava-lamp/lib/usb-lava-lamp.rb @@ -0,0 +1,49 @@ +require 'rubygems' +require 'usb' + +WRITE_ENDPOINT1 = 0x81 +WRITE_ENDPOINT2 = 0x82 + +MESSAGE0="5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5aEOT" +MESSAGE1="0149101924314051647990a9c4e1EOT" +MESSAGE2="0123456789abcde" +MESSAGE3="fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0EOT" +def get_interface(handle, interface) + begin + handle.usb_claim_interface(interface) + rescue + handle.usb_detach_kernel_driver_np(interface, interface) + retry + end +end + +def interrupt_write(handle, endpoint) + begin + #error_msg = handle.usb_interrupt_write(endpoint, MESSAGE0, 1000) + #error_msg = handle.usb_interrupt_write(endpoint, MESSAGE1, 1000) + #error_msg = handle.usb_interrupt_write(endpoint, MESSAGE2, 1000) + #error_msg = handle.usb_interrupt_write(endpoint, MESSAGE3, 1000) + #error_msg = handle.usb_bulk_write(endpoint, MESSAGE3, 1000) + handle.usb_control_msg(requesttype=0x81, request = USB::USB_REQ_SET_FEATURE, value = 0x8, index = 1, bytes = "", timeout = 1000) + puts "wrote interrupt for #{endpoint}" + puts error_msg + raise if error_msg < 0 + rescue RuntimeError + puts "Transmission error in sending to #{endpoint}" + rescue Errno::EBUSY + puts "couldn't write interrupt for #{endpoint} because device was busy" + rescue Errno::ETIMEDOUT + puts "couldn't write interrupt for #{endpoint} because device timed out" + end +end + +device = USB.devices.find_all {|device| (device.idVendor == 4400) && (device.idProduct == 514)}.first + +handle = device.usb_open +get_interface(handle, 0x0) +get_interface(handle, 0x1) + +interrupt_write(handle, WRITE_ENDPOINT1) +interrupt_write(handle, WRITE_ENDPOINT2) + +handle.usb_close diff --git a/usb-lava-lamp/lib/usb-lava-lamp/version.rb b/usb-lava-lamp/lib/usb-lava-lamp/version.rb new file mode 100644 index 0000000..33cb028 --- /dev/null +++ b/usb-lava-lamp/lib/usb-lava-lamp/version.rb @@ -0,0 +1,9 @@ +module LavaLamp #:nodoc: + module VERSION #:nodoc: + MAJOR = 0 + MINOR = 0 + TINY = 1 + + STRING = [MAJOR, MINOR, TINY].join('.') + end +end diff --git a/usb-lava-lamp/script/console b/usb-lava-lamp/script/console new file mode 100755 index 0000000..28c02c1 --- /dev/null +++ b/usb-lava-lamp/script/console @@ -0,0 +1,10 @@ +#!/usr/bin/env ruby +# File: script/console +irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb' + +libs = " -r irb/completion" +# Perhaps use a console_lib to store any extra methods I may want available in the cosole +# libs << " -r #{File.dirname(__FILE__) + '/../lib/console_lib/console_logger.rb'}" +libs << " -r #{File.dirname(__FILE__) + '/../lib/usb-lava-lamp.rb'}" +puts "Loading usb-lava-lamp gem" +exec "#{irb} #{libs} --simple-prompt" \ No newline at end of file diff --git a/usb-lava-lamp/script/destroy b/usb-lava-lamp/script/destroy new file mode 100755 index 0000000..e48464d --- /dev/null +++ b/usb-lava-lamp/script/destroy @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/destroy' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Destroy.new.run(ARGV) diff --git a/usb-lava-lamp/script/generate b/usb-lava-lamp/script/generate new file mode 100755 index 0000000..c27f655 --- /dev/null +++ b/usb-lava-lamp/script/generate @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/generate' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Generate.new.run(ARGV) diff --git a/usb-lava-lamp/script/txt2html b/usb-lava-lamp/script/txt2html new file mode 100755 index 0000000..23cf438 --- /dev/null +++ b/usb-lava-lamp/script/txt2html @@ -0,0 +1,82 @@ +#!/usr/bin/env ruby + +GEM_NAME = 'usb-lava-lamp' # what ppl will type to install your gem +RUBYFORGE_PROJECT = 'usb-lava-lamp' + +require 'rubygems' +begin + require 'newgem' + require 'rubyforge' +rescue LoadError + puts "\n\nGenerating the website requires the newgem RubyGem" + puts "Install: gem install newgem\n\n" + exit(1) +end +require 'redcloth' +require 'syntax/convertors/html' +require 'erb' +require File.dirname(__FILE__) + "/../lib/#{GEM_NAME}/version.rb" + +version = LavaLamp::VERSION::STRING +download = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" + +def rubyforge_project_id + RubyForge.new.autoconfig["group_ids"][RUBYFORGE_PROJECT] +end + +class Fixnum + def ordinal + # teens + return 'th' if (10..19).include?(self % 100) + # others + case self % 10 + when 1: return 'st' + when 2: return 'nd' + when 3: return 'rd' + else return 'th' + end + end +end + +class Time + def pretty + return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" + end +end + +def convert_syntax(syntax, source) + return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^<pre>|</pre>$!,'') +end + +if ARGV.length >= 1 + src, template = ARGV + template ||= File.join(File.dirname(__FILE__), '/../website/template.html.erb') +else + puts("Usage: #{File.split($0).last} source.txt [template.html.erb] > output.html") + exit! +end + +template = ERB.new(File.open(template).read) + +title = nil +body = nil +File.open(src) do |fsrc| + title_text = fsrc.readline + body_text_template = fsrc.read + body_text = ERB.new(body_text_template).result(binding) + syntax_items = [] + body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)</\1>!m){ + ident = syntax_items.length + element, syntax, source = $1, $2, $3 + syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}</#{element}>" + "syntax-temp-#{ident}" + } + title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip + body = RedCloth.new(body_text).to_html + body.gsub!(%r!(?:<pre><code>)?syntax-temp-(\d+)(?:</code></pre>)?!){ syntax_items[$1.to_i] } +end +stat = File.stat(src) +created = stat.ctime +modified = stat.mtime + +$stdout << template.result(binding) diff --git a/usb-lava-lamp/setup.rb b/usb-lava-lamp/setup.rb new file mode 100644 index 0000000..424a5f3 --- /dev/null +++ b/usb-lava-lamp/setup.rb @@ -0,0 +1,1585 @@ +# +# setup.rb +# +# Copyright (c) 2000-2005 Minero Aoki +# +# This program is free software. +# You can distribute/modify this program under the terms of +# the GNU LGPL, Lesser General Public License version 2.1. +# + +unless Enumerable.method_defined?(:map) # Ruby 1.4.6 + module Enumerable + alias map collect + end +end + +unless File.respond_to?(:read) # Ruby 1.6 + def File.read(fname) + open(fname) {|f| + return f.read + } + end +end + +unless Errno.const_defined?(:ENOTEMPTY) # Windows? + module Errno + class ENOTEMPTY + # We do not raise this exception, implementation is not needed. + end + end +end + +def File.binread(fname) + open(fname, 'rb') {|f| + return f.read + } +end + +# for corrupted Windows' stat(2) +def File.dir?(path) + File.directory?((path[-1,1] == '/') ? path : path + '/') +end + + +class ConfigTable + + include Enumerable + + def initialize(rbconfig) + @rbconfig = rbconfig + @items = [] + @table = {} + # options + @install_prefix = nil + @config_opt = nil + @verbose = true + @no_harm = false + end + + attr_accessor :install_prefix + attr_accessor :config_opt + + attr_writer :verbose + + def verbose? + @verbose + end + + attr_writer :no_harm + + def no_harm? + @no_harm + end + + def [](key) + lookup(key).resolve(self) + end + + def []=(key, val) + lookup(key).set val + end + + def names + @items.map {|i| i.name } + end + + def each(&block) + @items.each(&block) + end + + def key?(name) + @table.key?(name) + end + + def lookup(name) + @table[name] or setup_rb_error "no such config item: #{name}" + end + + def add(item) + @items.push item + @table[item.name] = item + end + + def remove(name) + item = lookup(name) + @items.delete_if {|i| i.name == name } + @table.delete_if {|name, i| i.name == name } + item + end + + def load_script(path, inst = nil) + if File.file?(path) + MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path + end + end + + def savefile + '.config' + end + + def load_savefile + begin + File.foreach(savefile()) do |line| + k, v = *line.split(/=/, 2) + self[k] = v.strip + end + rescue Errno::ENOENT + setup_rb_error $!.message + "\n#{File.basename($0)} config first" + end + end + + def save + @items.each {|i| i.value } + File.open(savefile(), 'w') {|f| + @items.each do |i| + f.printf "%s=%s\n", i.name, i.value if i.value? and i.value + end + } + end + + def load_standard_entries + standard_entries(@rbconfig).each do |ent| + add ent + end + end + + def standard_entries(rbconfig) + c = rbconfig + + rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) + + major = c['MAJOR'].to_i + minor = c['MINOR'].to_i + teeny = c['TEENY'].to_i + version = "#{major}.#{minor}" + + # ruby ver. >= 1.4.4? + newpath_p = ((major >= 2) or + ((major == 1) and + ((minor >= 5) or + ((minor == 4) and (teeny >= 4))))) + + if c['rubylibdir'] + # V > 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = c['rubylibdir'] + librubyverarch = c['archdir'] + siteruby = c['sitedir'] + siterubyver = c['sitelibdir'] + siterubyverarch = c['sitearchdir'] + elsif newpath_p + # 1.4.4 <= V <= 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = c['sitedir'] + siterubyver = "$siteruby/#{version}" + siterubyverarch = "$siterubyver/#{c['arch']}" + else + # V < 1.4.4 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" + siterubyver = siteruby + siterubyverarch = "$siterubyver/#{c['arch']}" + end + parameterize = lambda {|path| + path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') + } + + if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } + makeprog = arg.sub(/'/, '').split(/=/, 2)[1] + else + makeprog = 'make' + end + + [ + ExecItem.new('installdirs', 'std/site/home', + 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ + {|val, table| + case val + when 'std' + table['rbdir'] = '$librubyver' + table['sodir'] = '$librubyverarch' + when 'site' + table['rbdir'] = '$siterubyver' + table['sodir'] = '$siterubyverarch' + when 'home' + setup_rb_error '$HOME was not set' unless ENV['HOME'] + table['prefix'] = ENV['HOME'] + table['rbdir'] = '$libdir/ruby' + table['sodir'] = '$libdir/ruby' + end + }, + PathItem.new('prefix', 'path', c['prefix'], + 'path prefix of target environment'), + PathItem.new('bindir', 'path', parameterize.call(c['bindir']), + 'the directory for commands'), + PathItem.new('libdir', 'path', parameterize.call(c['libdir']), + 'the directory for libraries'), + PathItem.new('datadir', 'path', parameterize.call(c['datadir']), + 'the directory for shared data'), + PathItem.new('mandir', 'path', parameterize.call(c['mandir']), + 'the directory for man pages'), + PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), + 'the directory for system configuration files'), + PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), + 'the directory for local state data'), + PathItem.new('libruby', 'path', libruby, + 'the directory for ruby libraries'), + PathItem.new('librubyver', 'path', librubyver, + 'the directory for standard ruby libraries'), + PathItem.new('librubyverarch', 'path', librubyverarch, + 'the directory for standard ruby extensions'), + PathItem.new('siteruby', 'path', siteruby, + 'the directory for version-independent aux ruby libraries'), + PathItem.new('siterubyver', 'path', siterubyver, + 'the directory for aux ruby libraries'), + PathItem.new('siterubyverarch', 'path', siterubyverarch, + 'the directory for aux ruby binaries'), + PathItem.new('rbdir', 'path', '$siterubyver', + 'the directory for ruby scripts'), + PathItem.new('sodir', 'path', '$siterubyverarch', + 'the directory for ruby extentions'), + PathItem.new('rubypath', 'path', rubypath, + 'the path to set to #! line'), + ProgramItem.new('rubyprog', 'name', rubypath, + 'the ruby program using for installation'), + ProgramItem.new('makeprog', 'name', makeprog, + 'the make program to compile ruby extentions'), + SelectItem.new('shebang', 'all/ruby/never', 'ruby', + 'shebang line (#!) editing mode'), + BoolItem.new('without-ext', 'yes/no', 'no', + 'does not compile/install ruby extentions') + ] + end + private :standard_entries + + def load_multipackage_entries + multipackage_entries().each do |ent| + add ent + end + end + + def multipackage_entries + [ + PackageSelectionItem.new('with', 'name,name...', '', 'ALL', + 'package names that you want to install'), + PackageSelectionItem.new('without', 'name,name...', '', 'NONE', + 'package names that you do not want to install') + ] + end + private :multipackage_entries + + ALIASES = { + 'std-ruby' => 'librubyver', + 'stdruby' => 'librubyver', + 'rubylibdir' => 'librubyver', + 'archdir' => 'librubyverarch', + 'site-ruby-common' => 'siteruby', # For backward compatibility + 'site-ruby' => 'siterubyver', # For backward compatibility + 'bin-dir' => 'bindir', + 'bin-dir' => 'bindir', + 'rb-dir' => 'rbdir', + 'so-dir' => 'sodir', + 'data-dir' => 'datadir', + 'ruby-path' => 'rubypath', + 'ruby-prog' => 'rubyprog', + 'ruby' => 'rubyprog', + 'make-prog' => 'makeprog', + 'make' => 'makeprog' + } + + def fixup + ALIASES.each do |ali, name| + @table[ali] = @table[name] + end + @items.freeze + @table.freeze + @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ + end + + def parse_opt(opt) + m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" + m.to_a[1,2] + end + + def dllext + @rbconfig['DLEXT'] + end + + def value_config?(name) + lookup(name).value? + end + + class Item + def initialize(name, template, default, desc) + @name = name.freeze + @template = template + @value = default + @default = default + @description = desc + end + + attr_reader :name + attr_reader :description + + attr_accessor :default + alias help_default default + + def help_opt + "--#{@name}=#{@template}" + end + + def value? + true + end + + def value + @value + end + + def resolve(table) + @value.gsub(%r<\$([^/]+)>) { table[$1] } + end + + def set(val) + @value = check(val) + end + + private + + def check(val) + setup_rb_error "config: --#{name} requires argument" unless val + val + end + end + + class BoolItem < Item + def config_type + 'bool' + end + + def help_opt + "--#{@name}" + end + + private + + def check(val) + return 'yes' unless val + case val + when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' + when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' + else + setup_rb_error "config: --#{@name} accepts only yes/no for argument" + end + end + end + + class PathItem < Item + def config_type + 'path' + end + + private + + def check(path) + setup_rb_error "config: --#{@name} requires argument" unless path + path[0,1] == '$' ? path : File.expand_path(path) + end + end + + class ProgramItem < Item + def config_type + 'program' + end + end + + class SelectItem < Item + def initialize(name, selection, default, desc) + super + @ok = selection.split('/') + end + + def config_type + 'select' + end + + private + + def check(val) + unless @ok.include?(val.strip) + setup_rb_error "config: use --#{@name}=#{@template} (#{val})" + end + val.strip + end + end + + class ExecItem < Item + def initialize(name, selection, desc, &block) + super name, selection, nil, desc + @ok = selection.split('/') + @action = block + end + + def config_type + 'exec' + end + + def value? + false + end + + def resolve(table) + setup_rb_error "$#{name()} wrongly used as option value" + end + + undef set + + def evaluate(val, table) + v = val.strip.downcase + unless @ok.include?(v) + setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" + end + @action.call v, table + end + end + + class PackageSelectionItem < Item + def initialize(name, template, default, help_default, desc) + super name, template, default, desc + @help_default = help_default + end + + attr_reader :help_default + + def config_type + 'package' + end + + private + + def check(val) + unless File.dir?("packages/#{val}") + setup_rb_error "config: no such package: #{val}" + end + val + end + end + + class MetaConfigEnvironment + def initialize(config, installer) + @config = config + @installer = installer + end + + def config_names + @config.names + end + + def config?(name) + @config.key?(name) + end + + def bool_config?(name) + @config.lookup(name).config_type == 'bool' + end + + def path_config?(name) + @config.lookup(name).config_type == 'path' + end + + def value_config?(name) + @config.lookup(name).config_type != 'exec' + end + + def add_config(item) + @config.add item + end + + def add_bool_config(name, default, desc) + @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) + end + + def add_path_config(name, default, desc) + @config.add PathItem.new(name, 'path', default, desc) + end + + def set_config_default(name, default) + @config.lookup(name).default = default + end + + def remove_config(name) + @config.remove(name) + end + + # For only multipackage + def packages + raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer + @installer.packages + end + + # For only multipackage + def declare_packages(list) + raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer + @installer.packages = list + end + end + +end # class ConfigTable + + +# This module requires: #verbose?, #no_harm? +module FileOperations + + def mkdir_p(dirname, prefix = nil) + dirname = prefix + File.expand_path(dirname) if prefix + $stderr.puts "mkdir -p #{dirname}" if verbose? + return if no_harm? + + # Does not check '/', it's too abnormal. + dirs = File.expand_path(dirname).split(%r<(?=/)>) + if /\A[a-z]:\z/i =~ dirs[0] + disk = dirs.shift + dirs[0] = disk + dirs[0] + end + dirs.each_index do |idx| + path = dirs[0..idx].join('') + Dir.mkdir path unless File.dir?(path) + end + end + + def rm_f(path) + $stderr.puts "rm -f #{path}" if verbose? + return if no_harm? + force_remove_file path + end + + def rm_rf(path) + $stderr.puts "rm -rf #{path}" if verbose? + return if no_harm? + remove_tree path + end + + def remove_tree(path) + if File.symlink?(path) + remove_file path + elsif File.dir?(path) + remove_tree0 path + else + force_remove_file path + end + end + + def remove_tree0(path) + Dir.foreach(path) do |ent| + next if ent == '.' + next if ent == '..' + entpath = "#{path}/#{ent}" + if File.symlink?(entpath) + remove_file entpath + elsif File.dir?(entpath) + remove_tree0 entpath + else + force_remove_file entpath + end + end + begin + Dir.rmdir path + rescue Errno::ENOTEMPTY + # directory may not be empty + end + end + + def move_file(src, dest) + force_remove_file dest + begin + File.rename src, dest + rescue + File.open(dest, 'wb') {|f| + f.write File.binread(src) + } + File.chmod File.stat(src).mode, dest + File.unlink src + end + end + + def force_remove_file(path) + begin + remove_file path + rescue + end + end + + def remove_file(path) + File.chmod 0777, path + File.unlink path + end + + def install(from, dest, mode, prefix = nil) + $stderr.puts "install #{from} #{dest}" if verbose? + return if no_harm? + + realdest = prefix ? prefix + File.expand_path(dest) : dest + realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) + str = File.binread(from) + if diff?(str, realdest) + verbose_off { + rm_f realdest if File.exist?(realdest) + } + File.open(realdest, 'wb') {|f| + f.write str + } + File.chmod mode, realdest + + File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| + if prefix + f.puts realdest.sub(prefix, '') + else + f.puts realdest + end + } + end + end + + def diff?(new_content, path) + return true unless File.exist?(path) + new_content != File.binread(path) + end + + def command(*args) + $stderr.puts args.join(' ') if verbose? + system(*args) or raise RuntimeError, + "system(#{args.map{|a| a.inspect }.join(' ')}) failed" + end + + def ruby(*args) + command config('rubyprog'), *args + end + + def make(task = nil) + command(*[config('makeprog'), task].compact) + end + + def extdir?(dir) + File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") + end + + def files_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.file?("#{dir}/#{ent}") } + } + end + + DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) + + def directories_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT + } + end + +end + + +# This module requires: #srcdir_root, #objdir_root, #relpath +module HookScriptAPI + + def get_config(key) + @config[key] + end + + alias config get_config + + # obsolete: use metaconfig to change configuration + def set_config(key, val) + @config[key] = val + end + + # + # srcdir/objdir (works only in the package directory) + # + + def curr_srcdir + "#{srcdir_root()}/#{relpath()}" + end + + def curr_objdir + "#{objdir_root()}/#{relpath()}" + end + + def srcfile(path) + "#{curr_srcdir()}/#{path}" + end + + def srcexist?(path) + File.exist?(srcfile(path)) + end + + def srcdirectory?(path) + File.dir?(srcfile(path)) + end + + def srcfile?(path) + File.file?(srcfile(path)) + end + + def srcentries(path = '.') + Dir.open("#{curr_srcdir()}/#{path}") {|d| + return d.to_a - %w(. ..) + } + end + + def srcfiles(path = '.') + srcentries(path).select {|fname| + File.file?(File.join(curr_srcdir(), path, fname)) + } + end + + def srcdirectories(path = '.') + srcentries(path).select {|fname| + File.dir?(File.join(curr_srcdir(), path, fname)) + } + end + +end + + +class ToplevelInstaller + + Version = '3.4.1' + Copyright = 'Copyright (c) 2000-2005 Minero Aoki' + + TASKS = [ + [ 'all', 'do config, setup, then install' ], + [ 'config', 'saves your configurations' ], + [ 'show', 'shows current configuration' ], + [ 'setup', 'compiles ruby extentions and others' ], + [ 'install', 'installs files' ], + [ 'test', 'run all tests in test/' ], + [ 'clean', "does `make clean' for each extention" ], + [ 'distclean',"does `make distclean' for each extention" ] + ] + + def ToplevelInstaller.invoke + config = ConfigTable.new(load_rbconfig()) + config.load_standard_entries + config.load_multipackage_entries if multipackage? + config.fixup + klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) + klass.new(File.dirname($0), config).invoke + end + + def ToplevelInstaller.multipackage? + File.dir?(File.dirname($0) + '/packages') + end + + def ToplevelInstaller.load_rbconfig + if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } + ARGV.delete(arg) + load File.expand_path(arg.split(/=/, 2)[1]) + $".push 'rbconfig.rb' + else + require 'rbconfig' + end + ::Config::CONFIG + end + + def initialize(ardir_root, config) + @ardir = File.expand_path(ardir_root) + @config = config + # cache + @valid_task_re = nil + end + + def config(key) + @config[key] + end + + def inspect + "#<#{self.class} #{__id__()}>" + end + + def invoke + run_metaconfigs + case task = parsearg_global() + when nil, 'all' + parsearg_config + init_installers + exec_config + exec_setup + exec_install + else + case task + when 'config', 'test' + ; + when 'clean', 'distclean' + @config.load_savefile if File.exist?(@config.savefile) + else + @config.load_savefile + end + __send__ "parsearg_#{task}" + init_installers + __send__ "exec_#{task}" + end + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig" + end + + def init_installers + @installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + # + # Hook Script API bases + # + + def srcdir_root + @ardir + end + + def objdir_root + '.' + end + + def relpath + '.' + end + + # + # Option Parsing + # + + def parsearg_global + while arg = ARGV.shift + case arg + when /\A\w+\z/ + setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) + return arg + when '-q', '--quiet' + @config.verbose = false + when '--verbose' + @config.verbose = true + when '--help' + print_usage $stdout + exit 0 + when '--version' + puts "#{File.basename($0)} version #{Version}" + exit 0 + when '--copyright' + puts Copyright + exit 0 + else + setup_rb_error "unknown global option '#{arg}'" + end + end + nil + end + + def valid_task?(t) + valid_task_re() =~ t + end + + def valid_task_re + @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ + end + + def parsearg_no_options + unless ARGV.empty? + task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) + setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" + end + end + + alias parsearg_show parsearg_no_options + alias parsearg_setup parsearg_no_options + alias parsearg_test parsearg_no_options + alias parsearg_clean parsearg_no_options + alias parsearg_distclean parsearg_no_options + + def parsearg_config + evalopt = [] + set = [] + @config.config_opt = [] + while i = ARGV.shift + if /\A--?\z/ =~ i + @config.config_opt = ARGV.dup + break + end + name, value = *@config.parse_opt(i) + if @config.value_config?(name) + @config[name] = value + else + evalopt.push [name, value] + end + set.push name + end + evalopt.each do |name, value| + @config.lookup(name).evaluate value, @config + end + # Check if configuration is valid + set.each do |n| + @config[n] if @config.value_config?(n) + end + end + + def parsearg_install + @config.no_harm = false + @config.install_prefix = '' + while a = ARGV.shift + case a + when '--no-harm' + @config.no_harm = true + when /\A--prefix=/ + path = a.split(/=/, 2)[1] + path = File.expand_path(path) unless path[0,1] == '/' + @config.install_prefix = path + else + setup_rb_error "install: unknown option #{a}" + end + end + end + + def print_usage(out) + out.puts 'Typical Installation Procedure:' + out.puts " $ ruby #{File.basename $0} config" + out.puts " $ ruby #{File.basename $0} setup" + out.puts " # ruby #{File.basename $0} install (may require root privilege)" + out.puts + out.puts 'Detailed Usage:' + out.puts " ruby #{File.basename $0} <global option>" + out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]" + + fmt = " %-24s %s\n" + out.puts + out.puts 'Global options:' + out.printf fmt, '-q,--quiet', 'suppress message outputs' + out.printf fmt, ' --verbose', 'output messages verbosely' + out.printf fmt, ' --help', 'print this message' + out.printf fmt, ' --version', 'print version and quit' + out.printf fmt, ' --copyright', 'print copyright and quit' + out.puts + out.puts 'Tasks:' + TASKS.each do |name, desc| + out.printf fmt, name, desc + end + + fmt = " %-24s %s [%s]\n" + out.puts + out.puts 'Options for CONFIG or ALL:' + @config.each do |item| + out.printf fmt, item.help_opt, item.description, item.help_default + end + out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" + out.puts + out.puts 'Options for INSTALL:' + out.printf fmt, '--no-harm', 'only display what to do if given', 'off' + out.printf fmt, '--prefix=path', 'install path prefix', '' + out.puts + end + + # + # Task Handlers + # + + def exec_config + @installer.exec_config + @config.save # must be final + end + + def exec_setup + @installer.exec_setup + end + + def exec_install + @installer.exec_install + end + + def exec_test + @installer.exec_test + end + + def exec_show + @config.each do |i| + printf "%-20s %s\n", i.name, i.value if i.value? + end + end + + def exec_clean + @installer.exec_clean + end + + def exec_distclean + @installer.exec_distclean + end + +end # class ToplevelInstaller + + +class ToplevelInstallerMulti < ToplevelInstaller + + include FileOperations + + def initialize(ardir_root, config) + super + @packages = directories_of("#{@ardir}/packages") + raise 'no package exists' if @packages.empty? + @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig", self + @packages.each do |name| + @config.load_script "#{@ardir}/packages/#{name}/metaconfig" + end + end + + attr_reader :packages + + def packages=(list) + raise 'package list is empty' if list.empty? + list.each do |name| + raise "directory packages/#{name} does not exist"\ + unless File.dir?("#{@ardir}/packages/#{name}") + end + @packages = list + end + + def init_installers + @installers = {} + @packages.each do |pack| + @installers[pack] = Installer.new(@config, + "#{@ardir}/packages/#{pack}", + "packages/#{pack}") + end + with = extract_selection(config('with')) + without = extract_selection(config('without')) + @selected = @installers.keys.select {|name| + (with.empty? or with.include?(name)) \ + and not without.include?(name) + } + end + + def extract_selection(list) + a = list.split(/,/) + a.each do |name| + setup_rb_error "no such package: #{name}" unless @installers.key?(name) + end + a + end + + def print_usage(f) + super + f.puts 'Inluded packages:' + f.puts ' ' + @packages.sort.join(' ') + f.puts + end + + # + # Task Handlers + # + + def exec_config + run_hook 'pre-config' + each_selected_installers {|inst| inst.exec_config } + run_hook 'post-config' + @config.save # must be final + end + + def exec_setup + run_hook 'pre-setup' + each_selected_installers {|inst| inst.exec_setup } + run_hook 'post-setup' + end + + def exec_install + run_hook 'pre-install' + each_selected_installers {|inst| inst.exec_install } + run_hook 'post-install' + end + + def exec_test + run_hook 'pre-test' + each_selected_installers {|inst| inst.exec_test } + run_hook 'post-test' + end + + def exec_clean + rm_f @config.savefile + run_hook 'pre-clean' + each_selected_installers {|inst| inst.exec_clean } + run_hook 'post-clean' + end + + def exec_distclean + rm_f @config.savefile + run_hook 'pre-distclean' + each_selected_installers {|inst| inst.exec_distclean } + run_hook 'post-distclean' + end + + # + # lib + # + + def each_selected_installers + Dir.mkdir 'packages' unless File.dir?('packages') + @selected.each do |pack| + $stderr.puts "Processing the package `#{pack}' ..." if verbose? + Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") + Dir.chdir "packages/#{pack}" + yield @installers[pack] + Dir.chdir '../..' + end + end + + def run_hook(id) + @root_installer.run_hook id + end + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + +end # class ToplevelInstallerMulti + + +class Installer + + FILETYPES = %w( bin lib ext data conf man ) + + include FileOperations + include HookScriptAPI + + def initialize(config, srcroot, objroot) + @config = config + @srcdir = File.expand_path(srcroot) + @objdir = File.expand_path(objroot) + @currdir = '.' + end + + def inspect + "#<#{self.class} #{File.basename(@srcdir)}>" + end + + def noop(rel) + end + + # + # Hook Script API base methods + # + + def srcdir_root + @srcdir + end + + def objdir_root + @objdir + end + + def relpath + @currdir + end + + # + # Config Access + # + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + + def verbose_off + begin + save, @config.verbose = @config.verbose?, false + yield + ensure + @config.verbose = save + end + end + + # + # TASK config + # + + def exec_config + exec_task_traverse 'config' + end + + alias config_dir_bin noop + alias config_dir_lib noop + + def config_dir_ext(rel) + extconf if extdir?(curr_srcdir()) + end + + alias config_dir_data noop + alias config_dir_conf noop + alias config_dir_man noop + + def extconf + ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt + end + + # + # TASK setup + # + + def exec_setup + exec_task_traverse 'setup' + end + + def setup_dir_bin(rel) + files_of(curr_srcdir()).each do |fname| + update_shebang_line "#{curr_srcdir()}/#{fname}" + end + end + + alias setup_dir_lib noop + + def setup_dir_ext(rel) + make if extdir?(curr_srcdir()) + end + + alias setup_dir_data noop + alias setup_dir_conf noop + alias setup_dir_man noop + + def update_shebang_line(path) + return if no_harm? + return if config('shebang') == 'never' + old = Shebang.load(path) + if old + $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 + new = new_shebang(old) + return if new.to_s == old.to_s + else + return unless config('shebang') == 'all' + new = Shebang.new(config('rubypath')) + end + $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? + open_atomic_writer(path) {|output| + File.open(path, 'rb') {|f| + f.gets if old # discard + output.puts new.to_s + output.print f.read + } + } + end + + def new_shebang(old) + if /\Aruby/ =~ File.basename(old.cmd) + Shebang.new(config('rubypath'), old.args) + elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' + Shebang.new(config('rubypath'), old.args[1..-1]) + else + return old unless config('shebang') == 'all' + Shebang.new(config('rubypath')) + end + end + + def open_atomic_writer(path, &block) + tmpfile = File.basename(path) + '.tmp' + begin + File.open(tmpfile, 'wb', &block) + File.rename tmpfile, File.basename(path) + ensure + File.unlink tmpfile if File.exist?(tmpfile) + end + end + + class Shebang + def Shebang.load(path) + line = nil + File.open(path) {|f| + line = f.gets + } + return nil unless /\A#!/ =~ line + parse(line) + end + + def Shebang.parse(line) + cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') + new(cmd, args) + end + + def initialize(cmd, args = []) + @cmd = cmd + @args = args + end + + attr_reader :cmd + attr_reader :args + + def to_s + "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") + end + end + + # + # TASK install + # + + def exec_install + rm_f 'InstalledFiles' + exec_task_traverse 'install' + end + + def install_dir_bin(rel) + install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 + end + + def install_dir_lib(rel) + install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 + end + + def install_dir_ext(rel) + return unless extdir?(curr_srcdir()) + install_files rubyextentions('.'), + "#{config('sodir')}/#{File.dirname(rel)}", + 0555 + end + + def install_dir_data(rel) + install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 + end + + def install_dir_conf(rel) + # FIXME: should not remove current config files + # (rename previous file to .old/.org) + install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 + end + + def install_dir_man(rel) + install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 + end + + def install_files(list, dest, mode) + mkdir_p dest, @config.install_prefix + list.each do |fname| + install fname, dest, mode, @config.install_prefix + end + end + + def libfiles + glob_reject(%w(*.y *.output), targetfiles()) + end + + def rubyextentions(dir) + ents = glob_select("*.#{@config.dllext}", targetfiles()) + if ents.empty? + setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" + end + ents + end + + def targetfiles + mapdir(existfiles() - hookfiles()) + end + + def mapdir(ents) + ents.map {|ent| + if File.exist?(ent) + then ent # objdir + else "#{curr_srcdir()}/#{ent}" # srcdir + end + } + end + + # picked up many entries from cvs-1.11.1/src/ignore.c + JUNK_FILES = %w( + core RCSLOG tags TAGS .make.state + .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb + *~ *.old *.bak *.BAK *.orig *.rej _$* *$ + + *.org *.in .* + ) + + def existfiles + glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) + end + + def hookfiles + %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| + %w( config setup install clean ).map {|t| sprintf(fmt, t) } + }.flatten + end + + def glob_select(pat, ents) + re = globs2re([pat]) + ents.select {|ent| re =~ ent } + end + + def glob_reject(pats, ents) + re = globs2re(pats) + ents.reject {|ent| re =~ ent } + end + + GLOB2REGEX = { + '.' => '\.', + '$' => '\$', + '#' => '\#', + '*' => '.*' + } + + def globs2re(pats) + /\A(?:#{ + pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|') + })\z/ + end + + # + # TASK test + # + + TESTDIR = 'test' + + def exec_test + unless File.directory?('test') + $stderr.puts 'no test in this package' if verbose? + return + end + $stderr.puts 'Running tests...' if verbose? + begin + require 'test/unit' + rescue LoadError + setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.' + end + runner = Test::Unit::AutoRunner.new(true) + runner.to_run << TESTDIR + runner.run + end + + # + # TASK clean + # + + def exec_clean + exec_task_traverse 'clean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias clean_dir_bin noop + alias clean_dir_lib noop + alias clean_dir_data noop + alias clean_dir_conf noop + alias clean_dir_man noop + + def clean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'clean' if File.file?('Makefile') + end + + # + # TASK distclean + # + + def exec_distclean + exec_task_traverse 'distclean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias distclean_dir_bin noop + alias distclean_dir_lib noop + + def distclean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'distclean' if File.file?('Makefile') + end + + alias distclean_dir_data noop + alias distclean_dir_conf noop + alias distclean_dir_man noop + + # + # Traversing + # + + def exec_task_traverse(task) + run_hook "pre-#{task}" + FILETYPES.each do |type| + if type == 'ext' and config('without-ext') == 'yes' + $stderr.puts 'skipping ext/* by user option' if verbose? + next + end + traverse task, type, "#{task}_dir_#{type}" + end + run_hook "post-#{task}" + end + + def traverse(task, rel, mid) + dive_into(rel) { + run_hook "pre-#{task}" + __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') + directories_of(curr_srcdir()).each do |d| + traverse task, "#{rel}/#{d}", mid + end + run_hook "post-#{task}" + } + end + + def dive_into(rel) + return unless File.dir?("#{@srcdir}/#{rel}") + + dir = File.basename(rel) + Dir.mkdir dir unless File.dir?(dir) + prevdir = Dir.pwd + Dir.chdir dir + $stderr.puts '---> ' + rel if verbose? + @currdir = rel + yield + Dir.chdir prevdir + $stderr.puts '<--- ' + rel if verbose? + @currdir = File.dirname(rel) + end + + def run_hook(id) + path = [ "#{curr_srcdir()}/#{id}", + "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) } + return unless path + begin + instance_eval File.read(path), path, 1 + rescue + raise if $DEBUG + setup_rb_error "hook #{path} failed:\n" + $!.message + end + end + +end # class Installer + + +class SetupError < StandardError; end + +def setup_rb_error(msg) + raise SetupError, msg +end + +if $0 == __FILE__ + begin + ToplevelInstaller.invoke + rescue SetupError + raise if $DEBUG + $stderr.puts $!.message + $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." + exit 1 + end +end diff --git a/usb-lava-lamp/tasks/deployment.rake b/usb-lava-lamp/tasks/deployment.rake new file mode 100644 index 0000000..2f43742 --- /dev/null +++ b/usb-lava-lamp/tasks/deployment.rake @@ -0,0 +1,34 @@ +desc 'Release the website and new gem version' +task :deploy => [:check_version, :website, :release] do + puts "Remember to create SVN tag:" + puts "svn copy svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/trunk " + + "svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/tags/REL-#{VERS} " + puts "Suggested comment:" + puts "Tagging release #{CHANGES}" +end + +desc 'Runs tasks website_generate and install_gem as a local deployment of the gem' +task :local_deploy => [:website_generate, :install_gem] + +task :check_version do + unless ENV['VERSION'] + puts 'Must pass a VERSION=x.y.z release version' + exit + end + unless ENV['VERSION'] == VERS + puts "Please update your version.rb to match the release version, currently #{VERS}" + exit + end +end + +desc 'Install the package as a gem, without generating documentation(ri/rdoc)' +task :install_gem_no_doc => [:clean, :package] do + sh "#{'sudo ' unless Hoe::WINDOZE }gem install pkg/*.gem --no-rdoc --no-ri" +end + +namespace :manifest do + desc 'Recreate Manifest.txt to include ALL files' + task :refresh do + `rake check_manifest | patch -p0 > Manifest.txt` + end +end \ No newline at end of file diff --git a/usb-lava-lamp/tasks/environment.rake b/usb-lava-lamp/tasks/environment.rake new file mode 100644 index 0000000..691ed3b --- /dev/null +++ b/usb-lava-lamp/tasks/environment.rake @@ -0,0 +1,7 @@ +task :ruby_env do + RUBY_APP = if RUBY_PLATFORM =~ /java/ + "jruby" + else + "ruby" + end unless defined? RUBY_APP +end diff --git a/usb-lava-lamp/tasks/website.rake b/usb-lava-lamp/tasks/website.rake new file mode 100644 index 0000000..93e03fa --- /dev/null +++ b/usb-lava-lamp/tasks/website.rake @@ -0,0 +1,17 @@ +desc 'Generate website files' +task :website_generate => :ruby_env do + (Dir['website/**/*.txt'] - Dir['website/version*.txt']).each do |txt| + sh %{ #{RUBY_APP} script/txt2html #{txt} > #{txt.gsub(/txt$/,'html')} } + end +end + +desc 'Upload website files to rubyforge' +task :website_upload do + host = "#{rubyforge_username}@rubyforge.org" + remote_dir = "/var/www/gforge-projects/#{PATH}/" + local_dir = 'website' + sh %{rsync -aCv #{local_dir}/ #{host}:#{remote_dir}} +end + +desc 'Generate and upload website files' +task :website => [:website_generate, :website_upload, :publish_docs] diff --git a/usb-lava-lamp/test/test_helper.rb b/usb-lava-lamp/test/test_helper.rb new file mode 100644 index 0000000..fd51072 --- /dev/null +++ b/usb-lava-lamp/test/test_helper.rb @@ -0,0 +1,2 @@ +require 'test/unit' +require File.dirname(__FILE__) + '/../lib/usb-lava-lamp' diff --git a/usb-lava-lamp/test/test_usb-lava-lamp.rb b/usb-lava-lamp/test/test_usb-lava-lamp.rb new file mode 100644 index 0000000..d1ae18b --- /dev/null +++ b/usb-lava-lamp/test/test_usb-lava-lamp.rb @@ -0,0 +1,11 @@ +require File.dirname(__FILE__) + '/test_helper.rb' + +class TestLavaLamp < Test::Unit::TestCase + + def setup + end + + def test_truth + assert true + end +end diff --git a/usb-lava-lamp/website/index.html b/usb-lava-lamp/website/index.html new file mode 100644 index 0000000..733c2fd --- /dev/null +++ b/usb-lava-lamp/website/index.html @@ -0,0 +1,11 @@ +<html> + <head> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>usb-lava-lamp</title> + + </head> + <body id="body"> + <p>This page has not yet been created for RubyGem <code>usb-lava-lamp</code></p> + <p>To the developer: To generate it, update website/index.txt and run the rake task <code>website</code> to generate this <code>index.html</code> file.</p> + </body> +</html> \ No newline at end of file diff --git a/usb-lava-lamp/website/index.txt b/usb-lava-lamp/website/index.txt new file mode 100644 index 0000000..cbec950 --- /dev/null +++ b/usb-lava-lamp/website/index.txt @@ -0,0 +1,83 @@ +h1. usb lava lamp + +h1. &#x2192; 'usb-lava-lamp' + + +h2. What + + +h2. Installing + +<pre syntax="ruby">sudo gem install usb-lava-lamp</pre> + +h2. The basics + + +h2. Demonstration of usage + + + +h2. Forum + +"http://groups.google.com/group/usb-lava-lamp":http://groups.google.com/group/usb-lava-lamp + +TODO - create Google Group - usb-lava-lamp + +h2. How to submit patches + +Read the "8 steps for fixing other people's code":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/ and for section "8b: Submit patch to Google Groups":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/#8b-google-groups, use the Google Group above. + +TODO - pick SVN or Git instructions + +The trunk repository is <code>svn://rubyforge.org/var/svn/usb-lava-lamp/trunk</code> for anonymous access. + +OOOORRRR + +You can fetch the source from either: + +<% if rubyforge_project_id %> + +* rubyforge: "http://rubyforge.org/scm/?group_id=<%= rubyforge_project_id %>":http://rubyforge.org/scm/?group_id=<%= rubyforge_project_id %> + +<pre>git clone git://rubyforge.org/usb-lava-lamp.git</pre> + +<% else %> + +* rubyforge: MISSING IN ACTION + +TODO - You can not created a RubyForge project, OR have not run <code>rubyforge config</code> +yet to refresh your local rubyforge data with this projects' id information. + +When you do this, this message will magically disappear! + +Or you can hack website/index.txt and make it all go away!! + +<% end %> + +* github: "http://github.com/GITHUB_USERNAME/usb-lava-lamp/tree/master":http://github.com/GITHUB_USERNAME/usb-lava-lamp/tree/master + +<pre>git clone git://github.com/GITHUB_USERNAME/usb-lava-lamp.git</pre> + + +TODO - add "github_username: username" to ~/.rubyforge/user-config.yml and newgem will reuse it for future projects. + + +* gitorious: "git://gitorious.org/usb-lava-lamp/mainline.git":git://gitorious.org/usb-lava-lamp/mainline.git + +<pre>git clone git://gitorious.org/usb-lava-lamp/mainline.git</pre> + +h3. Build and test instructions + +<pre>cd usb-lava-lamp +rake test +rake install_gem</pre> + + +h2. License + +This code is free to use under the terms of the MIT license. + +h2. Contact + +Comments are welcome. Send an email to "Joseph Method":mailto:[email protected] via the "forum":http://groups.google.com/group/usb-lava-lamp + diff --git a/usb-lava-lamp/website/javascripts/rounded_corners_lite.inc.js b/usb-lava-lamp/website/javascripts/rounded_corners_lite.inc.js new file mode 100644 index 0000000..afc3ea3 --- /dev/null +++ b/usb-lava-lamp/website/javascripts/rounded_corners_lite.inc.js @@ -0,0 +1,285 @@ + + /**************************************************************** + * * + * curvyCorners * + * ------------ * + * * + * This script generates rounded corners for your divs. * + * * + * Version 1.2.9 * + * Copyright (c) 2006 Cameron Cooke * + * By: Cameron Cooke and Tim Hutchison. * + * * + * * + * Website: http://www.curvycorners.net * + * Email: [email protected] * + * Forum: http://www.curvycorners.net/forum/ * + * * + * * + * This library is free software; you can redistribute * + * it and/or modify it under the terms of the GNU * + * Lesser General Public License as published by the * + * Free Software Foundation; either version 2.1 of the * + * License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will * + * be useful, but WITHOUT ANY WARRANTY; without even the * + * implied warranty of MERCHANTABILITY or FITNESS FOR A * + * PARTICULAR PURPOSE. See the GNU Lesser General Public * + * License for more details. * + * * + * You should have received a copy of the GNU Lesser * + * General Public License along with this library; * + * Inc., 59 Temple Place, Suite 330, Boston, * + * MA 02111-1307 USA * + * * + ****************************************************************/ + +var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1; var isMoz = document.implementation && document.implementation.createDocument; var isSafari = ((navigator.userAgent.toLowerCase().indexOf('safari')!=-1)&&(navigator.userAgent.toLowerCase().indexOf('mac')!=-1))?true:false; function curvyCorners() +{ if(typeof(arguments[0]) != "object") throw newCurvyError("First parameter of curvyCorners() must be an object."); if(typeof(arguments[1]) != "object" && typeof(arguments[1]) != "string") throw newCurvyError("Second parameter of curvyCorners() must be an object or a class name."); if(typeof(arguments[1]) == "string") +{ var startIndex = 0; var boxCol = getElementsByClass(arguments[1]);} +else +{ var startIndex = 1; var boxCol = arguments;} +var curvyCornersCol = new Array(); if(arguments[0].validTags) +var validElements = arguments[0].validTags; else +var validElements = ["div"]; for(var i = startIndex, j = boxCol.length; i < j; i++) +{ var currentTag = boxCol[i].tagName.toLowerCase(); if(inArray(validElements, currentTag) !== false) +{ curvyCornersCol[curvyCornersCol.length] = new curvyObject(arguments[0], boxCol[i]);} +} +this.objects = curvyCornersCol; this.applyCornersToAll = function() +{ for(var x = 0, k = this.objects.length; x < k; x++) +{ this.objects[x].applyCorners();} +} +} +function curvyObject() +{ this.box = arguments[1]; this.settings = arguments[0]; this.topContainer = null; this.bottomContainer = null; this.masterCorners = new Array(); this.contentDIV = null; var boxHeight = get_style(this.box, "height", "height"); var boxWidth = get_style(this.box, "width", "width"); var borderWidth = get_style(this.box, "borderTopWidth", "border-top-width"); var borderColour = get_style(this.box, "borderTopColor", "border-top-color"); var boxColour = get_style(this.box, "backgroundColor", "background-color"); var backgroundImage = get_style(this.box, "backgroundImage", "background-image"); var boxPosition = get_style(this.box, "position", "position"); var boxPadding = get_style(this.box, "paddingTop", "padding-top"); this.boxHeight = parseInt(((boxHeight != "" && boxHeight != "auto" && boxHeight.indexOf("%") == -1)? boxHeight.substring(0, boxHeight.indexOf("px")) : this.box.scrollHeight)); this.boxWidth = parseInt(((boxWidth != "" && boxWidth != "auto" && boxWidth.indexOf("%") == -1)? boxWidth.substring(0, boxWidth.indexOf("px")) : this.box.scrollWidth)); this.borderWidth = parseInt(((borderWidth != "" && borderWidth.indexOf("px") !== -1)? borderWidth.slice(0, borderWidth.indexOf("px")) : 0)); this.boxColour = format_colour(boxColour); this.boxPadding = parseInt(((boxPadding != "" && boxPadding.indexOf("px") !== -1)? boxPadding.slice(0, boxPadding.indexOf("px")) : 0)); this.borderColour = format_colour(borderColour); this.borderString = this.borderWidth + "px" + " solid " + this.borderColour; this.backgroundImage = ((backgroundImage != "none")? backgroundImage : ""); this.boxContent = this.box.innerHTML; if(boxPosition != "absolute") this.box.style.position = "relative"; this.box.style.padding = "0px"; if(isIE && boxWidth == "auto" && boxHeight == "auto") this.box.style.width = "100%"; if(this.settings.autoPad == true && this.boxPadding > 0) +this.box.innerHTML = ""; this.applyCorners = function() +{ for(var t = 0; t < 2; t++) +{ switch(t) +{ case 0: +if(this.settings.tl || this.settings.tr) +{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var topMaxRadius = Math.max(this.settings.tl ? this.settings.tl.radius : 0, this.settings.tr ? this.settings.tr.radius : 0); newMainContainer.style.height = topMaxRadius + "px"; newMainContainer.style.top = 0 - topMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.topContainer = this.box.appendChild(newMainContainer);} +break; case 1: +if(this.settings.bl || this.settings.br) +{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var botMaxRadius = Math.max(this.settings.bl ? this.settings.bl.radius : 0, this.settings.br ? this.settings.br.radius : 0); newMainContainer.style.height = botMaxRadius + "px"; newMainContainer.style.bottom = 0 - botMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.bottomContainer = this.box.appendChild(newMainContainer);} +break;} +} +if(this.topContainer) this.box.style.borderTopWidth = "0px"; if(this.bottomContainer) this.box.style.borderBottomWidth = "0px"; var corners = ["tr", "tl", "br", "bl"]; for(var i in corners) +{ if(i > -1 < 4) +{ var cc = corners[i]; if(!this.settings[cc]) +{ if(((cc == "tr" || cc == "tl") && this.topContainer != null) || ((cc == "br" || cc == "bl") && this.bottomContainer != null)) +{ var newCorner = document.createElement("DIV"); newCorner.style.position = "relative"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; if(this.backgroundImage == "") +newCorner.style.backgroundColor = this.boxColour; else +newCorner.style.backgroundImage = this.backgroundImage; switch(cc) +{ case "tl": +newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.tr.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.left = -this.borderWidth + "px"; break; case "tr": +newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.tl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; newCorner.style.left = this.borderWidth + "px"; break; case "bl": +newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.br.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = -this.borderWidth + "px"; newCorner.style.backgroundPosition = "-" + (this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break; case "br": +newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.bl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = this.borderWidth + "px" +newCorner.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break;} +} +} +else +{ if(this.masterCorners[this.settings[cc].radius]) +{ var newCorner = this.masterCorners[this.settings[cc].radius].cloneNode(true);} +else +{ var newCorner = document.createElement("DIV"); newCorner.style.height = this.settings[cc].radius + "px"; newCorner.style.width = this.settings[cc].radius + "px"; newCorner.style.position = "absolute"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; var borderRadius = parseInt(this.settings[cc].radius - this.borderWidth); for(var intx = 0, j = this.settings[cc].radius; intx < j; intx++) +{ if((intx +1) >= borderRadius) +var y1 = -1; else +var y1 = (Math.floor(Math.sqrt(Math.pow(borderRadius, 2) - Math.pow((intx+1), 2))) - 1); if(borderRadius != j) +{ if((intx) >= borderRadius) +var y2 = -1; else +var y2 = Math.ceil(Math.sqrt(Math.pow(borderRadius,2) - Math.pow(intx, 2))); if((intx+1) >= j) +var y3 = -1; else +var y3 = (Math.floor(Math.sqrt(Math.pow(j ,2) - Math.pow((intx+1), 2))) - 1);} +if((intx) >= j) +var y4 = -1; else +var y4 = Math.ceil(Math.sqrt(Math.pow(j ,2) - Math.pow(intx, 2))); if(y1 > -1) this.drawPixel(intx, 0, this.boxColour, 100, (y1+1), newCorner, -1, this.settings[cc].radius); if(borderRadius != j) +{ for(var inty = (y1 + 1); inty < y2; inty++) +{ if(this.settings.antiAlias) +{ if(this.backgroundImage != "") +{ var borderFract = (pixelFraction(intx, inty, borderRadius) * 100); if(borderFract < 30) +{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, 0, this.settings[cc].radius);} +else +{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, -1, this.settings[cc].radius);} +} +else +{ var pixelcolour = BlendColour(this.boxColour, this.borderColour, pixelFraction(intx, inty, borderRadius)); this.drawPixel(intx, inty, pixelcolour, 100, 1, newCorner, 0, this.settings[cc].radius, cc);} +} +} +if(this.settings.antiAlias) +{ if(y3 >= y2) +{ if (y2 == -1) y2 = 0; this.drawPixel(intx, y2, this.borderColour, 100, (y3 - y2 + 1), newCorner, 0, 0);} +} +else +{ if(y3 >= y1) +{ this.drawPixel(intx, (y1 + 1), this.borderColour, 100, (y3 - y1), newCorner, 0, 0);} +} +var outsideColour = this.borderColour;} +else +{ var outsideColour = this.boxColour; var y3 = y1;} +if(this.settings.antiAlias) +{ for(var inty = (y3 + 1); inty < y4; inty++) +{ this.drawPixel(intx, inty, outsideColour, (pixelFraction(intx, inty , j) * 100), 1, newCorner, ((this.borderWidth > 0)? 0 : -1), this.settings[cc].radius);} +} +} +this.masterCorners[this.settings[cc].radius] = newCorner.cloneNode(true);} +if(cc != "br") +{ for(var t = 0, k = newCorner.childNodes.length; t < k; t++) +{ var pixelBar = newCorner.childNodes[t]; var pixelBarTop = parseInt(pixelBar.style.top.substring(0, pixelBar.style.top.indexOf("px"))); var pixelBarLeft = parseInt(pixelBar.style.left.substring(0, pixelBar.style.left.indexOf("px"))); var pixelBarHeight = parseInt(pixelBar.style.height.substring(0, pixelBar.style.height.indexOf("px"))); if(cc == "tl" || cc == "bl"){ pixelBar.style.left = this.settings[cc].radius -pixelBarLeft -1 + "px";} +if(cc == "tr" || cc == "tl"){ pixelBar.style.top = this.settings[cc].radius -pixelBarHeight -pixelBarTop + "px";} +switch(cc) +{ case "tr": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.boxWidth - this.settings[cc].radius + this.borderWidth) + pixelBarLeft) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "tl": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "bl": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs((this.boxHeight + this.settings[cc].radius + pixelBarTop) -this.borderWidth) + "px"; break;} +} +} +} +if(newCorner) +{ switch(cc) +{ case "tl": +if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "tr": +if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "bl": +if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break; case "br": +if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break;} +} +} +} +var radiusDiff = new Array(); radiusDiff["t"] = Math.abs(this.settings.tl.radius - this.settings.tr.radius) +radiusDiff["b"] = Math.abs(this.settings.bl.radius - this.settings.br.radius); for(z in radiusDiff) +{ if(z == "t" || z == "b") +{ if(radiusDiff[z]) +{ var smallerCornerType = ((this.settings[z + "l"].radius < this.settings[z + "r"].radius)? z +"l" : z +"r"); var newFiller = document.createElement("DIV"); newFiller.style.height = radiusDiff[z] + "px"; newFiller.style.width = this.settings[smallerCornerType].radius+ "px" +newFiller.style.position = "absolute"; newFiller.style.fontSize = "1px"; newFiller.style.overflow = "hidden"; newFiller.style.backgroundColor = this.boxColour; switch(smallerCornerType) +{ case "tl": +newFiller.style.bottom = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.topContainer.appendChild(newFiller); break; case "tr": +newFiller.style.bottom = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.topContainer.appendChild(newFiller); break; case "bl": +newFiller.style.top = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.bottomContainer.appendChild(newFiller); break; case "br": +newFiller.style.top = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.bottomContainer.appendChild(newFiller); break;} +} +var newFillerBar = document.createElement("DIV"); newFillerBar.style.position = "relative"; newFillerBar.style.fontSize = "1px"; newFillerBar.style.overflow = "hidden"; newFillerBar.style.backgroundColor = this.boxColour; newFillerBar.style.backgroundImage = this.backgroundImage; switch(z) +{ case "t": +if(this.topContainer) +{ if(this.settings.tl.radius && this.settings.tr.radius) +{ newFillerBar.style.height = topMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.tl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.tr.radius - this.borderWidth + "px"; newFillerBar.style.borderTop = this.borderString; if(this.backgroundImage != "") +newFillerBar.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; this.topContainer.appendChild(newFillerBar);} +this.box.style.backgroundPosition = "0px -" + (topMaxRadius - this.borderWidth) + "px";} +break; case "b": +if(this.bottomContainer) +{ if(this.settings.bl.radius && this.settings.br.radius) +{ newFillerBar.style.height = botMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.bl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.br.radius - this.borderWidth + "px"; newFillerBar.style.borderBottom = this.borderString; if(this.backgroundImage != "") +newFillerBar.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (topMaxRadius + this.borderWidth)) + "px"; this.bottomContainer.appendChild(newFillerBar);} +} +break;} +} +} +if(this.settings.autoPad == true && this.boxPadding > 0) +{ var contentContainer = document.createElement("DIV"); contentContainer.style.position = "relative"; contentContainer.innerHTML = this.boxContent; contentContainer.className = "autoPadDiv"; var topPadding = Math.abs(topMaxRadius - this.boxPadding); var botPadding = Math.abs(botMaxRadius - this.boxPadding); if(topMaxRadius < this.boxPadding) +contentContainer.style.paddingTop = topPadding + "px"; if(botMaxRadius < this.boxPadding) +contentContainer.style.paddingBottom = botMaxRadius + "px"; contentContainer.style.paddingLeft = this.boxPadding + "px"; contentContainer.style.paddingRight = this.boxPadding + "px"; this.contentDIV = this.box.appendChild(contentContainer);} +} +this.drawPixel = function(intx, inty, colour, transAmount, height, newCorner, image, cornerRadius) +{ var pixel = document.createElement("DIV"); pixel.style.height = height + "px"; pixel.style.width = "1px"; pixel.style.position = "absolute"; pixel.style.fontSize = "1px"; pixel.style.overflow = "hidden"; var topMaxRadius = Math.max(this.settings["tr"].radius, this.settings["tl"].radius); if(image == -1 && this.backgroundImage != "") +{ pixel.style.backgroundImage = this.backgroundImage; pixel.style.backgroundPosition = "-" + (this.boxWidth - (cornerRadius - intx) + this.borderWidth) + "px -" + ((this.boxHeight + topMaxRadius + inty) -this.borderWidth) + "px";} +else +{ pixel.style.backgroundColor = colour;} +if (transAmount != 100) +setOpacity(pixel, transAmount); pixel.style.top = inty + "px"; pixel.style.left = intx + "px"; newCorner.appendChild(pixel);} +} +function insertAfter(parent, node, referenceNode) +{ parent.insertBefore(node, referenceNode.nextSibling);} +function BlendColour(Col1, Col2, Col1Fraction) +{ var red1 = parseInt(Col1.substr(1,2),16); var green1 = parseInt(Col1.substr(3,2),16); var blue1 = parseInt(Col1.substr(5,2),16); var red2 = parseInt(Col2.substr(1,2),16); var green2 = parseInt(Col2.substr(3,2),16); var blue2 = parseInt(Col2.substr(5,2),16); if(Col1Fraction > 1 || Col1Fraction < 0) Col1Fraction = 1; var endRed = Math.round((red1 * Col1Fraction) + (red2 * (1 - Col1Fraction))); if(endRed > 255) endRed = 255; if(endRed < 0) endRed = 0; var endGreen = Math.round((green1 * Col1Fraction) + (green2 * (1 - Col1Fraction))); if(endGreen > 255) endGreen = 255; if(endGreen < 0) endGreen = 0; var endBlue = Math.round((blue1 * Col1Fraction) + (blue2 * (1 - Col1Fraction))); if(endBlue > 255) endBlue = 255; if(endBlue < 0) endBlue = 0; return "#" + IntToHex(endRed)+ IntToHex(endGreen)+ IntToHex(endBlue);} +function IntToHex(strNum) +{ base = strNum / 16; rem = strNum % 16; base = base - (rem / 16); baseS = MakeHex(base); remS = MakeHex(rem); return baseS + '' + remS;} +function MakeHex(x) +{ if((x >= 0) && (x <= 9)) +{ return x;} +else +{ switch(x) +{ case 10: return "A"; case 11: return "B"; case 12: return "C"; case 13: return "D"; case 14: return "E"; case 15: return "F";} +} +} +function pixelFraction(x, y, r) +{ var pixelfraction = 0; var xvalues = new Array(1); var yvalues = new Array(1); var point = 0; var whatsides = ""; var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x,2))); if ((intersect >= y) && (intersect < (y+1))) +{ whatsides = "Left"; xvalues[point] = 0; yvalues[point] = intersect - y; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y+1,2))); if ((intersect >= x) && (intersect < (x+1))) +{ whatsides = whatsides + "Top"; xvalues[point] = intersect - x; yvalues[point] = 1; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x+1,2))); if ((intersect >= y) && (intersect < (y+1))) +{ whatsides = whatsides + "Right"; xvalues[point] = 1; yvalues[point] = intersect - y; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y,2))); if ((intersect >= x) && (intersect < (x+1))) +{ whatsides = whatsides + "Bottom"; xvalues[point] = intersect - x; yvalues[point] = 0;} +switch (whatsides) +{ case "LeftRight": +pixelfraction = Math.min(yvalues[0],yvalues[1]) + ((Math.max(yvalues[0],yvalues[1]) - Math.min(yvalues[0],yvalues[1]))/2); break; case "TopRight": +pixelfraction = 1-(((1-xvalues[0])*(1-yvalues[1]))/2); break; case "TopBottom": +pixelfraction = Math.min(xvalues[0],xvalues[1]) + ((Math.max(xvalues[0],xvalues[1]) - Math.min(xvalues[0],xvalues[1]))/2); break; case "LeftBottom": +pixelfraction = (yvalues[0]*xvalues[1])/2; break; default: +pixelfraction = 1;} +return pixelfraction;} +function rgb2Hex(rgbColour) +{ try{ var rgbArray = rgb2Array(rgbColour); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); var hexColour = "#" + IntToHex(red) + IntToHex(green) + IntToHex(blue);} +catch(e){ alert("There was an error converting the RGB value to Hexadecimal in function rgb2Hex");} +return hexColour;} +function rgb2Array(rgbColour) +{ var rgbValues = rgbColour.substring(4, rgbColour.indexOf(")")); var rgbArray = rgbValues.split(", "); return rgbArray;} +function setOpacity(obj, opacity) +{ opacity = (opacity == 100)?99.999:opacity; if(isSafari && obj.tagName != "IFRAME") +{ var rgbArray = rgb2Array(obj.style.backgroundColor); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); obj.style.backgroundColor = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity/100 + ")";} +else if(typeof(obj.style.opacity) != "undefined") +{ obj.style.opacity = opacity/100;} +else if(typeof(obj.style.MozOpacity) != "undefined") +{ obj.style.MozOpacity = opacity/100;} +else if(typeof(obj.style.filter) != "undefined") +{ obj.style.filter = "alpha(opacity:" + opacity + ")";} +else if(typeof(obj.style.KHTMLOpacity) != "undefined") +{ obj.style.KHTMLOpacity = opacity/100;} +} +function inArray(array, value) +{ for(var i = 0; i < array.length; i++){ if (array[i] === value) return i;} +return false;} +function inArrayKey(array, value) +{ for(key in array){ if(key === value) return true;} +return false;} +function addEvent(elm, evType, fn, useCapture) { if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true;} +else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r;} +else { elm['on' + evType] = fn;} +} +function removeEvent(obj, evType, fn, useCapture){ if (obj.removeEventListener){ obj.removeEventListener(evType, fn, useCapture); return true;} else if (obj.detachEvent){ var r = obj.detachEvent("on"+evType, fn); return r;} else { alert("Handler could not be removed");} +} +function format_colour(colour) +{ var returnColour = "#ffffff"; if(colour != "" && colour != "transparent") +{ if(colour.substr(0, 3) == "rgb") +{ returnColour = rgb2Hex(colour);} +else if(colour.length == 4) +{ returnColour = "#" + colour.substring(1, 2) + colour.substring(1, 2) + colour.substring(2, 3) + colour.substring(2, 3) + colour.substring(3, 4) + colour.substring(3, 4);} +else +{ returnColour = colour;} +} +return returnColour;} +function get_style(obj, property, propertyNS) +{ try +{ if(obj.currentStyle) +{ var returnVal = eval("obj.currentStyle." + property);} +else +{ if(isSafari && obj.style.display == "none") +{ obj.style.display = ""; var wasHidden = true;} +var returnVal = document.defaultView.getComputedStyle(obj, '').getPropertyValue(propertyNS); if(isSafari && wasHidden) +{ obj.style.display = "none";} +} +} +catch(e) +{ } +return returnVal;} +function getElementsByClass(searchClass, node, tag) +{ var classElements = new Array(); if(node == null) +node = document; if(tag == null) +tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)"); for (i = 0, j = 0; i < elsLen; i++) +{ if(pattern.test(els[i].className)) +{ classElements[j] = els[i]; j++;} +} +return classElements;} +function newCurvyError(errorMessage) +{ return new Error("curvyCorners Error:\n" + errorMessage) +} diff --git a/usb-lava-lamp/website/stylesheets/screen.css b/usb-lava-lamp/website/stylesheets/screen.css new file mode 100644 index 0000000..2c84cd0 --- /dev/null +++ b/usb-lava-lamp/website/stylesheets/screen.css @@ -0,0 +1,138 @@ +body { + background-color: #E1D1F1; + font-family: "Georgia", sans-serif; + font-size: 16px; + line-height: 1.6em; + padding: 1.6em 0 0 0; + color: #333; +} +h1, h2, h3, h4, h5, h6 { + color: #444; +} +h1 { + font-family: sans-serif; + font-weight: normal; + font-size: 4em; + line-height: 0.8em; + letter-spacing: -0.1ex; + margin: 5px; +} +li { + padding: 0; + margin: 0; + list-style-type: square; +} +a { + color: #5E5AFF; + background-color: #DAC; + font-weight: normal; + text-decoration: underline; +} +blockquote { + font-size: 90%; + font-style: italic; + border-left: 1px solid #111; + padding-left: 1em; +} +.caps { + font-size: 80%; +} + +#main { + width: 45em; + padding: 0; + margin: 0 auto; +} +.coda { + text-align: right; + color: #77f; + font-size: smaller; +} + +table { + font-size: 90%; + line-height: 1.4em; + color: #ff8; + background-color: #111; + padding: 2px 10px 2px 10px; + border-style: dashed; +} + +th { + color: #fff; +} + +td { + padding: 2px 10px 2px 10px; +} + +.success { + color: #0CC52B; +} + +.failed { + color: #E90A1B; +} + +.unknown { + color: #995000; +} +pre, code { + font-family: monospace; + font-size: 90%; + line-height: 1.4em; + color: #ff8; + background-color: #111; + padding: 2px 10px 2px 10px; +} +.comment { color: #aaa; font-style: italic; } +.keyword { color: #eff; font-weight: bold; } +.punct { color: #eee; font-weight: bold; } +.symbol { color: #0bb; } +.string { color: #6b4; } +.ident { color: #ff8; } +.constant { color: #66f; } +.regex { color: #ec6; } +.number { color: #F99; } +.expr { color: #227; } + +#version { + float: right; + text-align: right; + font-family: sans-serif; + font-weight: normal; + background-color: #B3ABFF; + color: #141331; + padding: 15px 20px 10px 20px; + margin: 0 auto; + margin-top: 15px; + border: 3px solid #141331; +} + +#version .numbers { + display: block; + font-size: 4em; + line-height: 0.8em; + letter-spacing: -0.1ex; + margin-bottom: 15px; +} + +#version p { + text-decoration: none; + color: #141331; + background-color: #B3ABFF; + margin: 0; + padding: 0; +} + +#version a { + text-decoration: none; + color: #141331; + background-color: #B3ABFF; +} + +.clickable { + cursor: pointer; + cursor: hand; +} + diff --git a/usb-lava-lamp/website/template.html.erb b/usb-lava-lamp/website/template.html.erb new file mode 100644 index 0000000..58def9f --- /dev/null +++ b/usb-lava-lamp/website/template.html.erb @@ -0,0 +1,48 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <link rel="stylesheet" href="stylesheets/screen.css" type="text/css" media="screen" /> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <title> + <%= title %> + </title> + <script src="javascripts/rounded_corners_lite.inc.js" type="text/javascript"></script> +<style> + +</style> + <script type="text/javascript"> + window.onload = function() { + settings = { + tl: { radius: 10 }, + tr: { radius: 10 }, + bl: { radius: 10 }, + br: { radius: 10 }, + antiAlias: true, + autoPad: true, + validTags: ["div"] + } + var versionBox = new curvyCorners(settings, document.getElementById("version")); + versionBox.applyCornersToAll(); + } + </script> +</head> +<body> +<div id="main"> + + <h1><%= title %></h1> + <div id="version" class="clickable" onclick='document.location = "<%= download %>"; return false'> + <p>Get Version</p> + <a href="<%= download %>" class="numbers"><%= version %></a> + </div> + <%= body %> + <p class="coda"> + <a href="[email protected]">Joseph Method</a>, <%= modified.pretty %><br> + Theme extended from <a href="http://rb2js.rubyforge.org/">Paul Battley</a> + </p> +</div> + +<!-- insert site tracking codes here, like Google Urchin --> + +</body> +</html>
tristil/agile-lamp
c1d2e9b1132aeb302d3580400308db734cdb16a8
mv into deeper directory structure (is this too svn?)
diff --git a/agilelamp.schemas b/agilelamp.schemas deleted file mode 100644 index e69c400..0000000 --- a/agilelamp.schemas +++ /dev/null @@ -1,15 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" standalone="yes"?> -<gconfschemafile> - <schemalist> - <schema> - <key>/schemas/apps/agilelamp/broken_build</key> - <applyto>/apps/agilelamp/broken_build</applyto> - <owner>agilelamp</owner> - <type>bool</type> - <default>false</default> - <locale name="C"/> - </schema> - - </schemalist> -</gconfschemafile> - diff --git a/agilelampclient/History.txt b/agilelampclient/History.txt new file mode 100644 index 0000000..69fc13b --- /dev/null +++ b/agilelampclient/History.txt @@ -0,0 +1,4 @@ +== 0.0.1 2007-12-20 + +* 1 major enhancement: + * Initial release diff --git a/agilelampclient/License.txt b/agilelampclient/License.txt new file mode 100644 index 0000000..c796fae --- /dev/null +++ b/agilelampclient/License.txt @@ -0,0 +1,20 @@ +Copyright (c) 2007 FIXME full name + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/agilelampclient/Manifest.txt b/agilelampclient/Manifest.txt new file mode 100644 index 0000000..8f4c0bf --- /dev/null +++ b/agilelampclient/Manifest.txt @@ -0,0 +1,33 @@ +History.txt +License.txt +Manifest.txt +README.txt +Rakefile +bin/agilelamp +config/hoe.rb +config/requirements.rb +data/agilelamp/red_light.png +data/agilelamp/green_light.png +data/agilelamp/agilelamp.schemas +lib/agilelamp.rb +lib/agilelamp/preferences_window.rb +lib/agilelamp/gconf_observer.rb +lib/agilelamp/statusicon.rb +lib/agilelamp/window.rb +lib/agilelamp/version.rb +lib/agilelamp/cruiseparser.rb +log/debug.log +script/destroy +script/generate +script/txt2html +setup.rb +tasks/deployment.rake +tasks/environment.rake +tasks/website.rake +test/test_helper.rb +test/test_agilelamp.rb +website/index.html +website/index.txt +website/javascripts/rounded_corners_lite.inc.js +website/stylesheets/screen.css +website/template.rhtml diff --git a/agilelampclient/README.txt b/agilelampclient/README.txt new file mode 100644 index 0000000..100b938 --- /dev/null +++ b/agilelampclient/README.txt @@ -0,0 +1 @@ +README \ No newline at end of file diff --git a/agilelampclient/Rakefile b/agilelampclient/Rakefile new file mode 100644 index 0000000..e469154 --- /dev/null +++ b/agilelampclient/Rakefile @@ -0,0 +1,4 @@ +require 'config/requirements' +require 'config/hoe' # setup Hoe + all gem configuration + +Dir['tasks/**/*.rake'].each { |rake| load rake } \ No newline at end of file diff --git a/agilelampclient/bin/agilelamp b/agilelampclient/bin/agilelamp new file mode 100644 index 0000000..5e23b55 --- /dev/null +++ b/agilelampclient/bin/agilelamp @@ -0,0 +1,42 @@ +#!/usr/bin/env ruby + +require 'optparse' +require 'optparse/time' +require 'ostruct' + +require 'rubygems' +require 'agilelamp' + +options = OpenStruct.new +options.verbose = false +options.run = true + +opts = OptionParser.new do |opts| + opts.banner = "Usage: agilelamp [options]" + + opts.separator "" + opts.separator "Specific options:" + + # Boolean switch. + opts.on("--[no-]verbose", "Run verbosely") do |v| + options.verbose = v + end + + opts.separator "" + opts.separator "Common options:" + + # No argument, shows at tail. This will print an options summary. + # Try it and see! + opts.on_tail("-h", "--help", "Show this message") do + puts opts + exit + end + + # Another typical switch to print the version. + opts.on_tail("-v", "--version", "Show version") do + puts AgileLamp.version + exit + end +end +opts.parse! +AgileLamp.Main diff --git a/agilelampclient/config/hoe.rb b/agilelampclient/config/hoe.rb new file mode 100644 index 0000000..5a0d37a --- /dev/null +++ b/agilelampclient/config/hoe.rb @@ -0,0 +1,71 @@ +require 'agilelamp/version' + +AUTHOR = 'Joseph Method' # can also be an array of Authors +EMAIL = "[email protected]" +DESCRIPTION = "An application to coordinate a usb lava lamp with continuous build systems like cruisecontrol." +GEM_NAME = 'agilelamp' # what ppl will type to install your gem +RUBYFORGE_PROJECT = 'agilelamp' # The unix name for your project +HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org" +DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" + +@config_file = "~/.rubyforge/user-config.yml" +@config = nil +RUBYFORGE_USERNAME = "method" +def rubyforge_username + unless @config + begin + @config = YAML.load(File.read(File.expand_path(@config_file))) + rescue + puts <<-EOS +ERROR: No rubyforge config file found: #{@config_file} +Run 'rubyforge setup' to prepare your env for access to Rubyforge + - See http://newgem.rubyforge.org/rubyforge.html for more details + EOS + exit + end + end + RUBYFORGE_USERNAME.replace @config["username"] +end + + +REV = nil +# UNCOMMENT IF REQUIRED: +# REV = `svn info`.each {|line| if line =~ /^Revision:/ then k,v = line.split(': '); break v.chomp; else next; end} rescue nil +VERS = AgileLamp::VERSION::STRING + (REV ? ".#{REV}" : "") +RDOC_OPTS = ['--quiet', '--title', 'agilelamp documentation', + "--opname", "index.html", + "--line-numbers", + "--main", "README", + "--inline-source"] + +class Hoe + def extra_deps + @extra_deps.reject! { |x| Array(x).first == 'hoe' } + @extra_deps + end +end + +# Generate all the Rake tasks +# Run 'rake -T' to see list of generated tasks (from gem root directory) +hoe = Hoe.new(GEM_NAME, VERS) do |p| + p.author = AUTHOR + p.description = DESCRIPTION + p.email = EMAIL + p.summary = DESCRIPTION + p.url = HOMEPATH + p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT + p.test_globs = ["test/**/test_*.rb"] + p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean. + + # == Optional + p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n") + #p.extra_deps = [] # An array of rubygem dependencies [name, version], e.g. [ ['active_support', '>= 1.3.1'] ] + + #p.spec_extras = {} # A hash of extra values to set in the gemspec. + +end + +CHANGES = hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n") +PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}" +hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc') +hoe.rsync_args = '-av --delete --ignore-errors' diff --git a/agilelampclient/config/requirements.rb b/agilelampclient/config/requirements.rb new file mode 100644 index 0000000..014e51b --- /dev/null +++ b/agilelampclient/config/requirements.rb @@ -0,0 +1,17 @@ +require 'fileutils' +include FileUtils + +require 'rubygems' +%w[rake hoe newgem rubigen].each do |req_gem| + begin + require req_gem + rescue LoadError + puts "This Rakefile requires the '#{req_gem}' RubyGem." + puts "Installation: gem install #{req_gem} -y" + exit + end +end + +$:.unshift(File.join(File.dirname(__FILE__), %w[.. lib])) + +require 'agilelamp' diff --git a/agilelampclient/data/agilelamp/agilelamp.schemas b/agilelampclient/data/agilelamp/agilelamp.schemas new file mode 100644 index 0000000..13f2f03 --- /dev/null +++ b/agilelampclient/data/agilelamp/agilelamp.schemas @@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<gconfschemafile> + <schemalist> + <schema> + <key>/schemas/apps/agilelamp/build_state</key> + <applyto>/apps/agilelamp/build_state</applyto> + <owner>agilelamp</owner> + <type>string</type> + <default>"broken"</default> + <locale name="C"/> + </schema> + + <schema> + <key>/schemas/apps/agilelamp/website</key> + <applyto>/apps/agilelamp/website</applyto> + <owner>agilelamp</owner> + <type>string</type> + <default></default> + <locale name="C"/> + </schema> + + <schema> + <key>/schemas/apps/agilelamp/check_interval</key> + <applyto>/apps/agilelamp/check_interval</applyto> + <owner>agilelamp</owner> + <type>int</type> + <default>10</default> + <locale name="C"/> + </schema> + + <schema> + <key>/schemas/apps/agilelamp/username</key> + <applyto>/apps/agilelamp/username</applyto> + <owner>agilelamp</owner> + <type>string</type> + <default></default> + <locale name="C"/> + </schema> + + <schema> + <key>/schemas/apps/agilelamp/password</key> + <applyto>/apps/agilelamp/password</applyto> + <owner>agilelamp</owner> + <type>string</type> + <default></default> + <locale name="C"/> + </schema> + + </schemalist> +</gconfschemafile> + diff --git a/agilelampclient/data/agilelamp/green_light.png b/agilelampclient/data/agilelamp/green_light.png new file mode 100644 index 0000000..7aec761 Binary files /dev/null and b/agilelampclient/data/agilelamp/green_light.png differ diff --git a/agilelampclient/data/agilelamp/red_light.png b/agilelampclient/data/agilelamp/red_light.png new file mode 100644 index 0000000..34376fb Binary files /dev/null and b/agilelampclient/data/agilelamp/red_light.png differ diff --git a/agilelampclient/lib/agilelamp.rb b/agilelampclient/lib/agilelamp.rb new file mode 100644 index 0000000..1b1c9b5 --- /dev/null +++ b/agilelampclient/lib/agilelamp.rb @@ -0,0 +1,16 @@ +$:.unshift File.dirname(__FILE__) + +module AgileLamp + require 'gtk2' + require 'singleton' + require 'agilelamp/window' + require 'agilelamp/gconf_observer' + require 'agilelamp/statusicon' + require 'agilelamp/preferences_window' + require 'agilelamp/cruiseparser' + require 'agilelamp/version' + def self.Main + StatusIcon.new + Gtk.main + end +end diff --git a/agilelampclient/lib/agilelamp/.cruiseparser.rb.swp b/agilelampclient/lib/agilelamp/.cruiseparser.rb.swp new file mode 100644 index 0000000..9e23dbc Binary files /dev/null and b/agilelampclient/lib/agilelamp/.cruiseparser.rb.swp differ diff --git a/agilelampclient/lib/agilelamp/cruiseparser.rb b/agilelampclient/lib/agilelamp/cruiseparser.rb new file mode 100644 index 0000000..5f3d4b3 --- /dev/null +++ b/agilelampclient/lib/agilelamp/cruiseparser.rb @@ -0,0 +1,32 @@ +module AgileLamp + require 'rubygems' + require 'mechanize' + require 'rss/1.0' + require 'rss/2.0' + + class CruiseParser + def initialize server, user="", password="" + @agent = WWW::Mechanize.new + @agent.basic_auth user, password + @url = "http://#{server}/projects/findrate?format=rss" + end + + def check_server + begin + page = @agent.get @url + rss = RSS::Parser.parse(page.body, false) + result = rss.items.first.title.match(/failed/) ? false : true + rescue + puts "failed to get response from server" + :server_failure + end + end + end +end + +if __FILE__ == $0 + parser = AgileLamp::CruiseParser.new "cruise.meihome.com", "method", "mysticar" + 5.times do + puts parser.check_server + end +end diff --git a/agilelampclient/lib/agilelamp/gconf_observer.rb b/agilelampclient/lib/agilelamp/gconf_observer.rb new file mode 100644 index 0000000..bdf935e --- /dev/null +++ b/agilelampclient/lib/agilelamp/gconf_observer.rb @@ -0,0 +1,69 @@ +module AgileLamp + require 'gconf2' + require 'observer' + + class GConfObserver + + include Observable + + def initialize + @client = GConf::Client.default + @client["/apps/agilelamp/build_state"] = "false" + observe_gconf + end + + def observe_gconf + @client.add_dir("/apps/agilelamp") + @client.notify_add("/apps/agilelamp/build_state") do |client, entry| + puts "broken_build value changed" + changed + notify_observers(client, entry) + end + end + + def install_schemas + schema_file = File.join(Config.datadir("agilelamp"), "agilelamp.schemas") + `gconftool-2 --install-schema-file #{schema_file}` + end + + def build_state + @client["/apps/agilelamp/build_state"] + end + + def build_state=(value) + @client["/apps/agilelamp/build_state"] = value + end + + def website + @client["/apps/agilelamp/website"] + end + + def website=(value) + @client["/apps/agilelamp/website"] = value + end + + def username + @client["/apps/agilelamp/username"] + end + + def username=(value) + @client["/apps/agilelamp/username"] = value + end + + def password + @client["/apps/agilelamp/password"] + end + + def password=(value) + @client["/apps/agilelamp/password"] = value + end + + def check_interval + @client["/apps/agilelamp/check_interval"] + end + + def check_interval=(value) + @client["/apps/agilelamp/check_interval"] = value + end + end +end diff --git a/agilelampclient/lib/agilelamp/preferences_window.rb b/agilelampclient/lib/agilelamp/preferences_window.rb new file mode 100644 index 0000000..1c584d4 --- /dev/null +++ b/agilelampclient/lib/agilelamp/preferences_window.rb @@ -0,0 +1,51 @@ +module AgileLamp + class PreferencesWindow < Gtk::Window + def initialize name + super name + @client = GConf::Client.default + set_size_request(250, 200) + add(vbox = Gtk::VBox.new) + vbox.add(notebook = Gtk::Notebook.new) + notebook.append_page(config = Gtk::VBox.new, Gtk::Label.new("Configuration")) + notebook.append_page(testing = Gtk::VBox.new, Gtk::Label.new("Test USB Lamp")) + config.add(Gtk::Label.new("Website for CruiseControl[.rb]")) + + config.add(hbox = Gtk::HBox.new) + hbox.add(Gtk::Label.new("http://")) + hbox.add(@entry = Gtk::Entry.new) + @entry.text = (@client["/apps/agilelamp/website"] or "") + + config.add(username_hbox = Gtk::HBox.new) + username_hbox.add(Gtk::Label.new("Username: ")) + username_hbox.add(@username_entry = Gtk::Entry.new) + @username_entry.text = (@client["/apps/agilelamp/username"] or "") + + config.add(password_hbox = Gtk::HBox.new) + password_hbox.add(Gtk::Label.new("Password: ")) + password_hbox.add(@password_entry = Gtk::Entry.new) + @password_entry.text = (@client["/apps/agilelamp/password"] or "") + + config.add(hbox2 = Gtk::HBox.new) + hbox2.add(Gtk::Label.new("Check every ")) + hbox2.add(@spin = Gtk::SpinButton.new(1, 60, 1)) + @spin.value = (@client["/apps/agilelamp/check_interval"] or 1) + hbox2.add(Gtk::Label.new("minutes.")) + testing.add(hbox3 = Gtk::HBox.new) + hbox3.add(Gtk::Label.new("Change red light: ")) + hbox3.add(red_light = Gtk::Button.new("OFF")) + testing.add(hbox4 = Gtk::HBox.new) + hbox4.add(Gtk::Label.new("Change green light: ")) + hbox4.add(green_light = Gtk::Button.new("OFF")) + red_light.signal_connect('clicked') { red_light.label= red_light.label == "OFF" ? "ON" : "OFF" } + green_light.signal_connect('clicked') {green_light.label=green_light.label == "OFF" ? "ON" : "OFF" } + vbox.add(close_button = Gtk::Button.new(Gtk::Stock::CLOSE)) + close_button.signal_connect('clicked') { save_preferences; destroy } + end + def save_preferences + @client["/apps/agilelamp/check_interval"] = @spin.value + @client["/apps/agilelamp/website"] = @entry.text.gsub("http://", "") + @client["/apps/agilelamp/username"] = @username_entry.text + @client["/apps/agilelamp/password"] = @password_entry.text + end + end +end diff --git a/agilelampclient/lib/agilelamp/statusicon.rb b/agilelampclient/lib/agilelamp/statusicon.rb new file mode 100644 index 0000000..acc470a --- /dev/null +++ b/agilelampclient/lib/agilelamp/statusicon.rb @@ -0,0 +1,91 @@ +module AgileLamp + class StatusIcon + def initialize + @status = Gtk::StatusIcon.new + @status.stock = Gtk::Stock::ADD + @status.tooltip = "What should you be doing?" + @status.signal_connect('activate') { on_activate } + @status.signal_connect('popup-menu') {|statusicon, button, time| on_right_click statusicon, button, time } + @menu = Gtk::Menu.new + @menu.append(preferences = Gtk::ImageMenuItem.new(Gtk::Stock::PREFERENCES)) + @menu.append(about = Gtk::ImageMenuItem.new(Gtk::Stock::ABOUT)) + @menu.append(Gtk::SeparatorMenuItem.new) + @menu.append(quit = Gtk::ImageMenuItem.new(Gtk::Stock::QUIT)) + preferences.signal_connect('activate') { on_click_preferences } + about.signal_connect('activate') { on_click_about } + quit.signal_connect('activate') { Gtk.main_quit } + + @gconf = GConfObserver.new + @gconf.install_schemas + @gconf.add_observer(self) + observe_cruisecontrol + end + + def update(*arg) + client, entry = arg[0], arg[1] + puts "StatusIcon:" + puts client, entry + entry.value == true ? broken_notification : fixed_notification + @status.stock = entry.value == true ? Gtk::Stock::CANCEL : Gtk::Stock::APPLY + end + + def broken_notification + `notify-send -u critical "Something is broken." "Blah broke on server Blah."` + end + + def fixed_notification + `notify-send -u normal "Something is fixed." "Issue Blah is fixed on server Blah."` + end + + def break_build + @gconf.build_state = "broken" + puts "broke build" + end + + def fix_build + @gconf.build_state = "fixed" + end + + def check_server + result = @cruise.check_server + puts "Server was #{result}" + puts "Next poll in #{@gconf.check_interval} minutes." + case result + when true + fix_build + when false + break_build + when :server_failure + @status.stock == Gtk::Stock::DIALOG_WARNING + end + end + + def observe_cruisecontrol + @cruise ||= CruiseParser.new(@gconf.website, @gconf.username, @gconf.password) + + # Do it one time to start + check_server + + Gtk.timeout_add(6000 * @gconf.check_interval) do + check_server + true + end + end + + def on_click_preferences + PreferencesWindow.new("Preferences").show_all + end + + def on_activate + @window ||= Proc.new { window = Window.new; window.signal_connect('destroy') { @window = nil }; puts "#{@window}"; window }.call + end + + def on_click_about + Gtk::AboutDialog.new.show_all + end + def on_right_click(statusicon, button, time) + @menu.popup(nil, nil, button, time) {|menu, x, y, push_in| @status.position_menu(@menu)} + @menu.show_all + end + end +end diff --git a/agilelampclient/lib/agilelamp/version.rb b/agilelampclient/lib/agilelamp/version.rb new file mode 100644 index 0000000..bb5e1b1 --- /dev/null +++ b/agilelampclient/lib/agilelamp/version.rb @@ -0,0 +1,12 @@ +module AgileLamp#:nodoc: + module VERSION #:nodoc: + MAJOR = 0 + MINOR = 0 + TINY = 1 + + STRING = [MAJOR, MINOR, TINY].join('.') + end + def self.version + VERSION::STRING + end +end diff --git a/agilelampclient/lib/agilelamp/window.rb b/agilelampclient/lib/agilelamp/window.rb new file mode 100644 index 0000000..b159790 --- /dev/null +++ b/agilelampclient/lib/agilelamp/window.rb @@ -0,0 +1,89 @@ +module AgileLamp + class Window + def setup_light + @light_image = Gtk::Image.new + @green_light= Gdk::Pixbuf.new(File.join(Config.datadir("agilelamp"), "green_light.png")) + @red_light = Gdk::Pixbuf.new(File.join(Config.datadir("agilelamp"), "red_light.png")) + @light_image.pixbuf = @green_light + @light_state = 'green' + event_box = Gtk::EventBox.new.add(@light_image) + @vbox.add(event_box) + tooltip = Gtk::Tooltips.new + tooltip.set_tip(event_box, "Go ahead, click it!", nil) + event_box.signal_connect('button_press_event') { toggle_light } + end + + def setup_treeview + @vbox.add(@scrolley = Gtk::ScrolledWindow.new) + @scrolley.add(tview = Gtk::TreeView.new) + tview.model = store = Gtk::ListStore.new(String, String, String) + tview.show + renderer = Gtk::CellRendererText.new + col1 = Gtk::TreeViewColumn.new("Build Event", renderer, "text", 0) + col2 = Gtk::TreeViewColumn.new("Caused By", renderer, "text", 1) + col3 = Gtk::TreeViewColumn.new("Message", renderer, "text", 2) + tview.append_column(col1) + tview.append_column(col2) + tview.append_column(col3) + + iter = store.append + iter[0] = "Failed!" + iter[1] = "Bob" + iter[2] = "The thing broke. Damn you, Bob!" + tview.show_all + end + + def initialize + @win = Gtk::Window.new("AgileLamp") + @win.add(@vbox = Gtk::VBox.new) + @vbox.add(menubar = Gtk::MenuBar.new) + menubar.append(menu = Gtk::MenuItem.new("_Options")) + menubar.append(menu2 = Gtk::MenuItem.new("_Tasks")) + menubar.append(menu3 = Gtk::MenuItem.new("_Help")) + menu.submenu = file_submenu = Gtk::Menu.new + menu2.submenu = tasks_submenu = Gtk::Menu.new + menu3.submenu = help_submenu = Gtk::Menu.new + file_submenu.add(Gtk::MenuItem.new("Blah")) + tasks_submenu.add(Gtk::MenuItem.new("Blah")) + help_submenu.add(about_submenu = Gtk::MenuItem.new("_About")) + @vbox.add(Gtk::Toolbar.new) + setup_light + setup_treeview + setup_gconf_observation + @vbox.show_all + @win.show_all + end + + def break_build + @client["/apps/agilelamp/broken_build"] = true + puts "broke build" + end + + def fix_build + @client["/apps/agilelamp/broken_build"] = false + end + + def setup_gconf_observation + @client = GConf::Client.default + puts "Setting up observation of broken_build" + @client.add_dir("/apps/agilelamp") + @client.notify_add("/apps/agilelamp/broken_build") do |client, entry| + puts "broken_build value changed to #{entry.value.inspect}" + @light_image.pixbuf = entry.value == true ? @red_light : @green_light + end + puts "Should have registered broken_build" + end + + def toggle_light + @light_image.pixbuf = @light_state == 'red' ? @red_light : @green_light + @light_state = @light_state == 'red' ? 'red' : 'green' + @light_state == 'red' ? break_build : fix_build + end + + def signal_connect signal + @win.signal_connect signal do + yield + end + end + end +end diff --git a/agilelampclient/log/debug.log b/agilelampclient/log/debug.log new file mode 100644 index 0000000..e69de29 diff --git a/agilelampclient/script/destroy b/agilelampclient/script/destroy new file mode 100755 index 0000000..5fa7e10 --- /dev/null +++ b/agilelampclient/script/destroy @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.join(File.dirname(__FILE__), '..') + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/destroy' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Destroy.new.run(ARGV) diff --git a/agilelampclient/script/generate b/agilelampclient/script/generate new file mode 100755 index 0000000..230a186 --- /dev/null +++ b/agilelampclient/script/generate @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.join(File.dirname(__FILE__), '..') + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/generate' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Generate.new.run(ARGV) diff --git a/agilelampclient/script/txt2html b/agilelampclient/script/txt2html new file mode 100755 index 0000000..a60f59b --- /dev/null +++ b/agilelampclient/script/txt2html @@ -0,0 +1,74 @@ +#!/usr/bin/env ruby + +require 'rubygems' +begin + require 'newgem' +rescue LoadError + puts "\n\nGenerating the website requires the newgem RubyGem" + puts "Install: gem install newgem\n\n" + exit(1) +end +require 'redcloth' +require 'syntax/convertors/html' +require 'erb' +require File.dirname(__FILE__) + '/../lib/agilelamp/version.rb' + +version = AgileLamp::VERSION::STRING +download = 'http://rubyforge.org/projects/agilelamp' + +class Fixnum + def ordinal + # teens + return 'th' if (10..19).include?(self % 100) + # others + case self % 10 + when 1: return 'st' + when 2: return 'nd' + when 3: return 'rd' + else return 'th' + end + end +end + +class Time + def pretty + return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" + end +end + +def convert_syntax(syntax, source) + return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^<pre>|</pre>$!,'') +end + +if ARGV.length >= 1 + src, template = ARGV + template ||= File.join(File.dirname(__FILE__), '/../website/template.rhtml') + +else + puts("Usage: #{File.split($0).last} source.txt [template.rhtml] > output.html") + exit! +end + +template = ERB.new(File.open(template).read) + +title = nil +body = nil +File.open(src) do |fsrc| + title_text = fsrc.readline + body_text = fsrc.read + syntax_items = [] + body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)</\1>!m){ + ident = syntax_items.length + element, syntax, source = $1, $2, $3 + syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}</#{element}>" + "syntax-temp-#{ident}" + } + title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip + body = RedCloth.new(body_text).to_html + body.gsub!(%r!(?:<pre><code>)?syntax-temp-(\d+)(?:</code></pre>)?!){ syntax_items[$1.to_i] } +end +stat = File.stat(src) +created = stat.ctime +modified = stat.mtime + +$stdout << template.result(binding) diff --git a/agilelampclient/setup.rb b/agilelampclient/setup.rb new file mode 100644 index 0000000..424a5f3 --- /dev/null +++ b/agilelampclient/setup.rb @@ -0,0 +1,1585 @@ +# +# setup.rb +# +# Copyright (c) 2000-2005 Minero Aoki +# +# This program is free software. +# You can distribute/modify this program under the terms of +# the GNU LGPL, Lesser General Public License version 2.1. +# + +unless Enumerable.method_defined?(:map) # Ruby 1.4.6 + module Enumerable + alias map collect + end +end + +unless File.respond_to?(:read) # Ruby 1.6 + def File.read(fname) + open(fname) {|f| + return f.read + } + end +end + +unless Errno.const_defined?(:ENOTEMPTY) # Windows? + module Errno + class ENOTEMPTY + # We do not raise this exception, implementation is not needed. + end + end +end + +def File.binread(fname) + open(fname, 'rb') {|f| + return f.read + } +end + +# for corrupted Windows' stat(2) +def File.dir?(path) + File.directory?((path[-1,1] == '/') ? path : path + '/') +end + + +class ConfigTable + + include Enumerable + + def initialize(rbconfig) + @rbconfig = rbconfig + @items = [] + @table = {} + # options + @install_prefix = nil + @config_opt = nil + @verbose = true + @no_harm = false + end + + attr_accessor :install_prefix + attr_accessor :config_opt + + attr_writer :verbose + + def verbose? + @verbose + end + + attr_writer :no_harm + + def no_harm? + @no_harm + end + + def [](key) + lookup(key).resolve(self) + end + + def []=(key, val) + lookup(key).set val + end + + def names + @items.map {|i| i.name } + end + + def each(&block) + @items.each(&block) + end + + def key?(name) + @table.key?(name) + end + + def lookup(name) + @table[name] or setup_rb_error "no such config item: #{name}" + end + + def add(item) + @items.push item + @table[item.name] = item + end + + def remove(name) + item = lookup(name) + @items.delete_if {|i| i.name == name } + @table.delete_if {|name, i| i.name == name } + item + end + + def load_script(path, inst = nil) + if File.file?(path) + MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path + end + end + + def savefile + '.config' + end + + def load_savefile + begin + File.foreach(savefile()) do |line| + k, v = *line.split(/=/, 2) + self[k] = v.strip + end + rescue Errno::ENOENT + setup_rb_error $!.message + "\n#{File.basename($0)} config first" + end + end + + def save + @items.each {|i| i.value } + File.open(savefile(), 'w') {|f| + @items.each do |i| + f.printf "%s=%s\n", i.name, i.value if i.value? and i.value + end + } + end + + def load_standard_entries + standard_entries(@rbconfig).each do |ent| + add ent + end + end + + def standard_entries(rbconfig) + c = rbconfig + + rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) + + major = c['MAJOR'].to_i + minor = c['MINOR'].to_i + teeny = c['TEENY'].to_i + version = "#{major}.#{minor}" + + # ruby ver. >= 1.4.4? + newpath_p = ((major >= 2) or + ((major == 1) and + ((minor >= 5) or + ((minor == 4) and (teeny >= 4))))) + + if c['rubylibdir'] + # V > 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = c['rubylibdir'] + librubyverarch = c['archdir'] + siteruby = c['sitedir'] + siterubyver = c['sitelibdir'] + siterubyverarch = c['sitearchdir'] + elsif newpath_p + # 1.4.4 <= V <= 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = c['sitedir'] + siterubyver = "$siteruby/#{version}" + siterubyverarch = "$siterubyver/#{c['arch']}" + else + # V < 1.4.4 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" + siterubyver = siteruby + siterubyverarch = "$siterubyver/#{c['arch']}" + end + parameterize = lambda {|path| + path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') + } + + if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } + makeprog = arg.sub(/'/, '').split(/=/, 2)[1] + else + makeprog = 'make' + end + + [ + ExecItem.new('installdirs', 'std/site/home', + 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ + {|val, table| + case val + when 'std' + table['rbdir'] = '$librubyver' + table['sodir'] = '$librubyverarch' + when 'site' + table['rbdir'] = '$siterubyver' + table['sodir'] = '$siterubyverarch' + when 'home' + setup_rb_error '$HOME was not set' unless ENV['HOME'] + table['prefix'] = ENV['HOME'] + table['rbdir'] = '$libdir/ruby' + table['sodir'] = '$libdir/ruby' + end + }, + PathItem.new('prefix', 'path', c['prefix'], + 'path prefix of target environment'), + PathItem.new('bindir', 'path', parameterize.call(c['bindir']), + 'the directory for commands'), + PathItem.new('libdir', 'path', parameterize.call(c['libdir']), + 'the directory for libraries'), + PathItem.new('datadir', 'path', parameterize.call(c['datadir']), + 'the directory for shared data'), + PathItem.new('mandir', 'path', parameterize.call(c['mandir']), + 'the directory for man pages'), + PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), + 'the directory for system configuration files'), + PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), + 'the directory for local state data'), + PathItem.new('libruby', 'path', libruby, + 'the directory for ruby libraries'), + PathItem.new('librubyver', 'path', librubyver, + 'the directory for standard ruby libraries'), + PathItem.new('librubyverarch', 'path', librubyverarch, + 'the directory for standard ruby extensions'), + PathItem.new('siteruby', 'path', siteruby, + 'the directory for version-independent aux ruby libraries'), + PathItem.new('siterubyver', 'path', siterubyver, + 'the directory for aux ruby libraries'), + PathItem.new('siterubyverarch', 'path', siterubyverarch, + 'the directory for aux ruby binaries'), + PathItem.new('rbdir', 'path', '$siterubyver', + 'the directory for ruby scripts'), + PathItem.new('sodir', 'path', '$siterubyverarch', + 'the directory for ruby extentions'), + PathItem.new('rubypath', 'path', rubypath, + 'the path to set to #! line'), + ProgramItem.new('rubyprog', 'name', rubypath, + 'the ruby program using for installation'), + ProgramItem.new('makeprog', 'name', makeprog, + 'the make program to compile ruby extentions'), + SelectItem.new('shebang', 'all/ruby/never', 'ruby', + 'shebang line (#!) editing mode'), + BoolItem.new('without-ext', 'yes/no', 'no', + 'does not compile/install ruby extentions') + ] + end + private :standard_entries + + def load_multipackage_entries + multipackage_entries().each do |ent| + add ent + end + end + + def multipackage_entries + [ + PackageSelectionItem.new('with', 'name,name...', '', 'ALL', + 'package names that you want to install'), + PackageSelectionItem.new('without', 'name,name...', '', 'NONE', + 'package names that you do not want to install') + ] + end + private :multipackage_entries + + ALIASES = { + 'std-ruby' => 'librubyver', + 'stdruby' => 'librubyver', + 'rubylibdir' => 'librubyver', + 'archdir' => 'librubyverarch', + 'site-ruby-common' => 'siteruby', # For backward compatibility + 'site-ruby' => 'siterubyver', # For backward compatibility + 'bin-dir' => 'bindir', + 'bin-dir' => 'bindir', + 'rb-dir' => 'rbdir', + 'so-dir' => 'sodir', + 'data-dir' => 'datadir', + 'ruby-path' => 'rubypath', + 'ruby-prog' => 'rubyprog', + 'ruby' => 'rubyprog', + 'make-prog' => 'makeprog', + 'make' => 'makeprog' + } + + def fixup + ALIASES.each do |ali, name| + @table[ali] = @table[name] + end + @items.freeze + @table.freeze + @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ + end + + def parse_opt(opt) + m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" + m.to_a[1,2] + end + + def dllext + @rbconfig['DLEXT'] + end + + def value_config?(name) + lookup(name).value? + end + + class Item + def initialize(name, template, default, desc) + @name = name.freeze + @template = template + @value = default + @default = default + @description = desc + end + + attr_reader :name + attr_reader :description + + attr_accessor :default + alias help_default default + + def help_opt + "--#{@name}=#{@template}" + end + + def value? + true + end + + def value + @value + end + + def resolve(table) + @value.gsub(%r<\$([^/]+)>) { table[$1] } + end + + def set(val) + @value = check(val) + end + + private + + def check(val) + setup_rb_error "config: --#{name} requires argument" unless val + val + end + end + + class BoolItem < Item + def config_type + 'bool' + end + + def help_opt + "--#{@name}" + end + + private + + def check(val) + return 'yes' unless val + case val + when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' + when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' + else + setup_rb_error "config: --#{@name} accepts only yes/no for argument" + end + end + end + + class PathItem < Item + def config_type + 'path' + end + + private + + def check(path) + setup_rb_error "config: --#{@name} requires argument" unless path + path[0,1] == '$' ? path : File.expand_path(path) + end + end + + class ProgramItem < Item + def config_type + 'program' + end + end + + class SelectItem < Item + def initialize(name, selection, default, desc) + super + @ok = selection.split('/') + end + + def config_type + 'select' + end + + private + + def check(val) + unless @ok.include?(val.strip) + setup_rb_error "config: use --#{@name}=#{@template} (#{val})" + end + val.strip + end + end + + class ExecItem < Item + def initialize(name, selection, desc, &block) + super name, selection, nil, desc + @ok = selection.split('/') + @action = block + end + + def config_type + 'exec' + end + + def value? + false + end + + def resolve(table) + setup_rb_error "$#{name()} wrongly used as option value" + end + + undef set + + def evaluate(val, table) + v = val.strip.downcase + unless @ok.include?(v) + setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" + end + @action.call v, table + end + end + + class PackageSelectionItem < Item + def initialize(name, template, default, help_default, desc) + super name, template, default, desc + @help_default = help_default + end + + attr_reader :help_default + + def config_type + 'package' + end + + private + + def check(val) + unless File.dir?("packages/#{val}") + setup_rb_error "config: no such package: #{val}" + end + val + end + end + + class MetaConfigEnvironment + def initialize(config, installer) + @config = config + @installer = installer + end + + def config_names + @config.names + end + + def config?(name) + @config.key?(name) + end + + def bool_config?(name) + @config.lookup(name).config_type == 'bool' + end + + def path_config?(name) + @config.lookup(name).config_type == 'path' + end + + def value_config?(name) + @config.lookup(name).config_type != 'exec' + end + + def add_config(item) + @config.add item + end + + def add_bool_config(name, default, desc) + @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) + end + + def add_path_config(name, default, desc) + @config.add PathItem.new(name, 'path', default, desc) + end + + def set_config_default(name, default) + @config.lookup(name).default = default + end + + def remove_config(name) + @config.remove(name) + end + + # For only multipackage + def packages + raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer + @installer.packages + end + + # For only multipackage + def declare_packages(list) + raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer + @installer.packages = list + end + end + +end # class ConfigTable + + +# This module requires: #verbose?, #no_harm? +module FileOperations + + def mkdir_p(dirname, prefix = nil) + dirname = prefix + File.expand_path(dirname) if prefix + $stderr.puts "mkdir -p #{dirname}" if verbose? + return if no_harm? + + # Does not check '/', it's too abnormal. + dirs = File.expand_path(dirname).split(%r<(?=/)>) + if /\A[a-z]:\z/i =~ dirs[0] + disk = dirs.shift + dirs[0] = disk + dirs[0] + end + dirs.each_index do |idx| + path = dirs[0..idx].join('') + Dir.mkdir path unless File.dir?(path) + end + end + + def rm_f(path) + $stderr.puts "rm -f #{path}" if verbose? + return if no_harm? + force_remove_file path + end + + def rm_rf(path) + $stderr.puts "rm -rf #{path}" if verbose? + return if no_harm? + remove_tree path + end + + def remove_tree(path) + if File.symlink?(path) + remove_file path + elsif File.dir?(path) + remove_tree0 path + else + force_remove_file path + end + end + + def remove_tree0(path) + Dir.foreach(path) do |ent| + next if ent == '.' + next if ent == '..' + entpath = "#{path}/#{ent}" + if File.symlink?(entpath) + remove_file entpath + elsif File.dir?(entpath) + remove_tree0 entpath + else + force_remove_file entpath + end + end + begin + Dir.rmdir path + rescue Errno::ENOTEMPTY + # directory may not be empty + end + end + + def move_file(src, dest) + force_remove_file dest + begin + File.rename src, dest + rescue + File.open(dest, 'wb') {|f| + f.write File.binread(src) + } + File.chmod File.stat(src).mode, dest + File.unlink src + end + end + + def force_remove_file(path) + begin + remove_file path + rescue + end + end + + def remove_file(path) + File.chmod 0777, path + File.unlink path + end + + def install(from, dest, mode, prefix = nil) + $stderr.puts "install #{from} #{dest}" if verbose? + return if no_harm? + + realdest = prefix ? prefix + File.expand_path(dest) : dest + realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) + str = File.binread(from) + if diff?(str, realdest) + verbose_off { + rm_f realdest if File.exist?(realdest) + } + File.open(realdest, 'wb') {|f| + f.write str + } + File.chmod mode, realdest + + File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| + if prefix + f.puts realdest.sub(prefix, '') + else + f.puts realdest + end + } + end + end + + def diff?(new_content, path) + return true unless File.exist?(path) + new_content != File.binread(path) + end + + def command(*args) + $stderr.puts args.join(' ') if verbose? + system(*args) or raise RuntimeError, + "system(#{args.map{|a| a.inspect }.join(' ')}) failed" + end + + def ruby(*args) + command config('rubyprog'), *args + end + + def make(task = nil) + command(*[config('makeprog'), task].compact) + end + + def extdir?(dir) + File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") + end + + def files_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.file?("#{dir}/#{ent}") } + } + end + + DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) + + def directories_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT + } + end + +end + + +# This module requires: #srcdir_root, #objdir_root, #relpath +module HookScriptAPI + + def get_config(key) + @config[key] + end + + alias config get_config + + # obsolete: use metaconfig to change configuration + def set_config(key, val) + @config[key] = val + end + + # + # srcdir/objdir (works only in the package directory) + # + + def curr_srcdir + "#{srcdir_root()}/#{relpath()}" + end + + def curr_objdir + "#{objdir_root()}/#{relpath()}" + end + + def srcfile(path) + "#{curr_srcdir()}/#{path}" + end + + def srcexist?(path) + File.exist?(srcfile(path)) + end + + def srcdirectory?(path) + File.dir?(srcfile(path)) + end + + def srcfile?(path) + File.file?(srcfile(path)) + end + + def srcentries(path = '.') + Dir.open("#{curr_srcdir()}/#{path}") {|d| + return d.to_a - %w(. ..) + } + end + + def srcfiles(path = '.') + srcentries(path).select {|fname| + File.file?(File.join(curr_srcdir(), path, fname)) + } + end + + def srcdirectories(path = '.') + srcentries(path).select {|fname| + File.dir?(File.join(curr_srcdir(), path, fname)) + } + end + +end + + +class ToplevelInstaller + + Version = '3.4.1' + Copyright = 'Copyright (c) 2000-2005 Minero Aoki' + + TASKS = [ + [ 'all', 'do config, setup, then install' ], + [ 'config', 'saves your configurations' ], + [ 'show', 'shows current configuration' ], + [ 'setup', 'compiles ruby extentions and others' ], + [ 'install', 'installs files' ], + [ 'test', 'run all tests in test/' ], + [ 'clean', "does `make clean' for each extention" ], + [ 'distclean',"does `make distclean' for each extention" ] + ] + + def ToplevelInstaller.invoke + config = ConfigTable.new(load_rbconfig()) + config.load_standard_entries + config.load_multipackage_entries if multipackage? + config.fixup + klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) + klass.new(File.dirname($0), config).invoke + end + + def ToplevelInstaller.multipackage? + File.dir?(File.dirname($0) + '/packages') + end + + def ToplevelInstaller.load_rbconfig + if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } + ARGV.delete(arg) + load File.expand_path(arg.split(/=/, 2)[1]) + $".push 'rbconfig.rb' + else + require 'rbconfig' + end + ::Config::CONFIG + end + + def initialize(ardir_root, config) + @ardir = File.expand_path(ardir_root) + @config = config + # cache + @valid_task_re = nil + end + + def config(key) + @config[key] + end + + def inspect + "#<#{self.class} #{__id__()}>" + end + + def invoke + run_metaconfigs + case task = parsearg_global() + when nil, 'all' + parsearg_config + init_installers + exec_config + exec_setup + exec_install + else + case task + when 'config', 'test' + ; + when 'clean', 'distclean' + @config.load_savefile if File.exist?(@config.savefile) + else + @config.load_savefile + end + __send__ "parsearg_#{task}" + init_installers + __send__ "exec_#{task}" + end + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig" + end + + def init_installers + @installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + # + # Hook Script API bases + # + + def srcdir_root + @ardir + end + + def objdir_root + '.' + end + + def relpath + '.' + end + + # + # Option Parsing + # + + def parsearg_global + while arg = ARGV.shift + case arg + when /\A\w+\z/ + setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) + return arg + when '-q', '--quiet' + @config.verbose = false + when '--verbose' + @config.verbose = true + when '--help' + print_usage $stdout + exit 0 + when '--version' + puts "#{File.basename($0)} version #{Version}" + exit 0 + when '--copyright' + puts Copyright + exit 0 + else + setup_rb_error "unknown global option '#{arg}'" + end + end + nil + end + + def valid_task?(t) + valid_task_re() =~ t + end + + def valid_task_re + @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ + end + + def parsearg_no_options + unless ARGV.empty? + task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) + setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" + end + end + + alias parsearg_show parsearg_no_options + alias parsearg_setup parsearg_no_options + alias parsearg_test parsearg_no_options + alias parsearg_clean parsearg_no_options + alias parsearg_distclean parsearg_no_options + + def parsearg_config + evalopt = [] + set = [] + @config.config_opt = [] + while i = ARGV.shift + if /\A--?\z/ =~ i + @config.config_opt = ARGV.dup + break + end + name, value = *@config.parse_opt(i) + if @config.value_config?(name) + @config[name] = value + else + evalopt.push [name, value] + end + set.push name + end + evalopt.each do |name, value| + @config.lookup(name).evaluate value, @config + end + # Check if configuration is valid + set.each do |n| + @config[n] if @config.value_config?(n) + end + end + + def parsearg_install + @config.no_harm = false + @config.install_prefix = '' + while a = ARGV.shift + case a + when '--no-harm' + @config.no_harm = true + when /\A--prefix=/ + path = a.split(/=/, 2)[1] + path = File.expand_path(path) unless path[0,1] == '/' + @config.install_prefix = path + else + setup_rb_error "install: unknown option #{a}" + end + end + end + + def print_usage(out) + out.puts 'Typical Installation Procedure:' + out.puts " $ ruby #{File.basename $0} config" + out.puts " $ ruby #{File.basename $0} setup" + out.puts " # ruby #{File.basename $0} install (may require root privilege)" + out.puts + out.puts 'Detailed Usage:' + out.puts " ruby #{File.basename $0} <global option>" + out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]" + + fmt = " %-24s %s\n" + out.puts + out.puts 'Global options:' + out.printf fmt, '-q,--quiet', 'suppress message outputs' + out.printf fmt, ' --verbose', 'output messages verbosely' + out.printf fmt, ' --help', 'print this message' + out.printf fmt, ' --version', 'print version and quit' + out.printf fmt, ' --copyright', 'print copyright and quit' + out.puts + out.puts 'Tasks:' + TASKS.each do |name, desc| + out.printf fmt, name, desc + end + + fmt = " %-24s %s [%s]\n" + out.puts + out.puts 'Options for CONFIG or ALL:' + @config.each do |item| + out.printf fmt, item.help_opt, item.description, item.help_default + end + out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" + out.puts + out.puts 'Options for INSTALL:' + out.printf fmt, '--no-harm', 'only display what to do if given', 'off' + out.printf fmt, '--prefix=path', 'install path prefix', '' + out.puts + end + + # + # Task Handlers + # + + def exec_config + @installer.exec_config + @config.save # must be final + end + + def exec_setup + @installer.exec_setup + end + + def exec_install + @installer.exec_install + end + + def exec_test + @installer.exec_test + end + + def exec_show + @config.each do |i| + printf "%-20s %s\n", i.name, i.value if i.value? + end + end + + def exec_clean + @installer.exec_clean + end + + def exec_distclean + @installer.exec_distclean + end + +end # class ToplevelInstaller + + +class ToplevelInstallerMulti < ToplevelInstaller + + include FileOperations + + def initialize(ardir_root, config) + super + @packages = directories_of("#{@ardir}/packages") + raise 'no package exists' if @packages.empty? + @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig", self + @packages.each do |name| + @config.load_script "#{@ardir}/packages/#{name}/metaconfig" + end + end + + attr_reader :packages + + def packages=(list) + raise 'package list is empty' if list.empty? + list.each do |name| + raise "directory packages/#{name} does not exist"\ + unless File.dir?("#{@ardir}/packages/#{name}") + end + @packages = list + end + + def init_installers + @installers = {} + @packages.each do |pack| + @installers[pack] = Installer.new(@config, + "#{@ardir}/packages/#{pack}", + "packages/#{pack}") + end + with = extract_selection(config('with')) + without = extract_selection(config('without')) + @selected = @installers.keys.select {|name| + (with.empty? or with.include?(name)) \ + and not without.include?(name) + } + end + + def extract_selection(list) + a = list.split(/,/) + a.each do |name| + setup_rb_error "no such package: #{name}" unless @installers.key?(name) + end + a + end + + def print_usage(f) + super + f.puts 'Inluded packages:' + f.puts ' ' + @packages.sort.join(' ') + f.puts + end + + # + # Task Handlers + # + + def exec_config + run_hook 'pre-config' + each_selected_installers {|inst| inst.exec_config } + run_hook 'post-config' + @config.save # must be final + end + + def exec_setup + run_hook 'pre-setup' + each_selected_installers {|inst| inst.exec_setup } + run_hook 'post-setup' + end + + def exec_install + run_hook 'pre-install' + each_selected_installers {|inst| inst.exec_install } + run_hook 'post-install' + end + + def exec_test + run_hook 'pre-test' + each_selected_installers {|inst| inst.exec_test } + run_hook 'post-test' + end + + def exec_clean + rm_f @config.savefile + run_hook 'pre-clean' + each_selected_installers {|inst| inst.exec_clean } + run_hook 'post-clean' + end + + def exec_distclean + rm_f @config.savefile + run_hook 'pre-distclean' + each_selected_installers {|inst| inst.exec_distclean } + run_hook 'post-distclean' + end + + # + # lib + # + + def each_selected_installers + Dir.mkdir 'packages' unless File.dir?('packages') + @selected.each do |pack| + $stderr.puts "Processing the package `#{pack}' ..." if verbose? + Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") + Dir.chdir "packages/#{pack}" + yield @installers[pack] + Dir.chdir '../..' + end + end + + def run_hook(id) + @root_installer.run_hook id + end + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + +end # class ToplevelInstallerMulti + + +class Installer + + FILETYPES = %w( bin lib ext data conf man ) + + include FileOperations + include HookScriptAPI + + def initialize(config, srcroot, objroot) + @config = config + @srcdir = File.expand_path(srcroot) + @objdir = File.expand_path(objroot) + @currdir = '.' + end + + def inspect + "#<#{self.class} #{File.basename(@srcdir)}>" + end + + def noop(rel) + end + + # + # Hook Script API base methods + # + + def srcdir_root + @srcdir + end + + def objdir_root + @objdir + end + + def relpath + @currdir + end + + # + # Config Access + # + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + + def verbose_off + begin + save, @config.verbose = @config.verbose?, false + yield + ensure + @config.verbose = save + end + end + + # + # TASK config + # + + def exec_config + exec_task_traverse 'config' + end + + alias config_dir_bin noop + alias config_dir_lib noop + + def config_dir_ext(rel) + extconf if extdir?(curr_srcdir()) + end + + alias config_dir_data noop + alias config_dir_conf noop + alias config_dir_man noop + + def extconf + ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt + end + + # + # TASK setup + # + + def exec_setup + exec_task_traverse 'setup' + end + + def setup_dir_bin(rel) + files_of(curr_srcdir()).each do |fname| + update_shebang_line "#{curr_srcdir()}/#{fname}" + end + end + + alias setup_dir_lib noop + + def setup_dir_ext(rel) + make if extdir?(curr_srcdir()) + end + + alias setup_dir_data noop + alias setup_dir_conf noop + alias setup_dir_man noop + + def update_shebang_line(path) + return if no_harm? + return if config('shebang') == 'never' + old = Shebang.load(path) + if old + $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 + new = new_shebang(old) + return if new.to_s == old.to_s + else + return unless config('shebang') == 'all' + new = Shebang.new(config('rubypath')) + end + $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? + open_atomic_writer(path) {|output| + File.open(path, 'rb') {|f| + f.gets if old # discard + output.puts new.to_s + output.print f.read + } + } + end + + def new_shebang(old) + if /\Aruby/ =~ File.basename(old.cmd) + Shebang.new(config('rubypath'), old.args) + elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' + Shebang.new(config('rubypath'), old.args[1..-1]) + else + return old unless config('shebang') == 'all' + Shebang.new(config('rubypath')) + end + end + + def open_atomic_writer(path, &block) + tmpfile = File.basename(path) + '.tmp' + begin + File.open(tmpfile, 'wb', &block) + File.rename tmpfile, File.basename(path) + ensure + File.unlink tmpfile if File.exist?(tmpfile) + end + end + + class Shebang + def Shebang.load(path) + line = nil + File.open(path) {|f| + line = f.gets + } + return nil unless /\A#!/ =~ line + parse(line) + end + + def Shebang.parse(line) + cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') + new(cmd, args) + end + + def initialize(cmd, args = []) + @cmd = cmd + @args = args + end + + attr_reader :cmd + attr_reader :args + + def to_s + "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") + end + end + + # + # TASK install + # + + def exec_install + rm_f 'InstalledFiles' + exec_task_traverse 'install' + end + + def install_dir_bin(rel) + install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 + end + + def install_dir_lib(rel) + install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 + end + + def install_dir_ext(rel) + return unless extdir?(curr_srcdir()) + install_files rubyextentions('.'), + "#{config('sodir')}/#{File.dirname(rel)}", + 0555 + end + + def install_dir_data(rel) + install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 + end + + def install_dir_conf(rel) + # FIXME: should not remove current config files + # (rename previous file to .old/.org) + install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 + end + + def install_dir_man(rel) + install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 + end + + def install_files(list, dest, mode) + mkdir_p dest, @config.install_prefix + list.each do |fname| + install fname, dest, mode, @config.install_prefix + end + end + + def libfiles + glob_reject(%w(*.y *.output), targetfiles()) + end + + def rubyextentions(dir) + ents = glob_select("*.#{@config.dllext}", targetfiles()) + if ents.empty? + setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" + end + ents + end + + def targetfiles + mapdir(existfiles() - hookfiles()) + end + + def mapdir(ents) + ents.map {|ent| + if File.exist?(ent) + then ent # objdir + else "#{curr_srcdir()}/#{ent}" # srcdir + end + } + end + + # picked up many entries from cvs-1.11.1/src/ignore.c + JUNK_FILES = %w( + core RCSLOG tags TAGS .make.state + .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb + *~ *.old *.bak *.BAK *.orig *.rej _$* *$ + + *.org *.in .* + ) + + def existfiles + glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) + end + + def hookfiles + %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| + %w( config setup install clean ).map {|t| sprintf(fmt, t) } + }.flatten + end + + def glob_select(pat, ents) + re = globs2re([pat]) + ents.select {|ent| re =~ ent } + end + + def glob_reject(pats, ents) + re = globs2re(pats) + ents.reject {|ent| re =~ ent } + end + + GLOB2REGEX = { + '.' => '\.', + '$' => '\$', + '#' => '\#', + '*' => '.*' + } + + def globs2re(pats) + /\A(?:#{ + pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|') + })\z/ + end + + # + # TASK test + # + + TESTDIR = 'test' + + def exec_test + unless File.directory?('test') + $stderr.puts 'no test in this package' if verbose? + return + end + $stderr.puts 'Running tests...' if verbose? + begin + require 'test/unit' + rescue LoadError + setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.' + end + runner = Test::Unit::AutoRunner.new(true) + runner.to_run << TESTDIR + runner.run + end + + # + # TASK clean + # + + def exec_clean + exec_task_traverse 'clean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias clean_dir_bin noop + alias clean_dir_lib noop + alias clean_dir_data noop + alias clean_dir_conf noop + alias clean_dir_man noop + + def clean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'clean' if File.file?('Makefile') + end + + # + # TASK distclean + # + + def exec_distclean + exec_task_traverse 'distclean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias distclean_dir_bin noop + alias distclean_dir_lib noop + + def distclean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'distclean' if File.file?('Makefile') + end + + alias distclean_dir_data noop + alias distclean_dir_conf noop + alias distclean_dir_man noop + + # + # Traversing + # + + def exec_task_traverse(task) + run_hook "pre-#{task}" + FILETYPES.each do |type| + if type == 'ext' and config('without-ext') == 'yes' + $stderr.puts 'skipping ext/* by user option' if verbose? + next + end + traverse task, type, "#{task}_dir_#{type}" + end + run_hook "post-#{task}" + end + + def traverse(task, rel, mid) + dive_into(rel) { + run_hook "pre-#{task}" + __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') + directories_of(curr_srcdir()).each do |d| + traverse task, "#{rel}/#{d}", mid + end + run_hook "post-#{task}" + } + end + + def dive_into(rel) + return unless File.dir?("#{@srcdir}/#{rel}") + + dir = File.basename(rel) + Dir.mkdir dir unless File.dir?(dir) + prevdir = Dir.pwd + Dir.chdir dir + $stderr.puts '---> ' + rel if verbose? + @currdir = rel + yield + Dir.chdir prevdir + $stderr.puts '<--- ' + rel if verbose? + @currdir = File.dirname(rel) + end + + def run_hook(id) + path = [ "#{curr_srcdir()}/#{id}", + "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) } + return unless path + begin + instance_eval File.read(path), path, 1 + rescue + raise if $DEBUG + setup_rb_error "hook #{path} failed:\n" + $!.message + end + end + +end # class Installer + + +class SetupError < StandardError; end + +def setup_rb_error(msg) + raise SetupError, msg +end + +if $0 == __FILE__ + begin + ToplevelInstaller.invoke + rescue SetupError + raise if $DEBUG + $stderr.puts $!.message + $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." + exit 1 + end +end diff --git a/agilelampclient/tasks/deployment.rake b/agilelampclient/tasks/deployment.rake new file mode 100644 index 0000000..2f43742 --- /dev/null +++ b/agilelampclient/tasks/deployment.rake @@ -0,0 +1,34 @@ +desc 'Release the website and new gem version' +task :deploy => [:check_version, :website, :release] do + puts "Remember to create SVN tag:" + puts "svn copy svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/trunk " + + "svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/tags/REL-#{VERS} " + puts "Suggested comment:" + puts "Tagging release #{CHANGES}" +end + +desc 'Runs tasks website_generate and install_gem as a local deployment of the gem' +task :local_deploy => [:website_generate, :install_gem] + +task :check_version do + unless ENV['VERSION'] + puts 'Must pass a VERSION=x.y.z release version' + exit + end + unless ENV['VERSION'] == VERS + puts "Please update your version.rb to match the release version, currently #{VERS}" + exit + end +end + +desc 'Install the package as a gem, without generating documentation(ri/rdoc)' +task :install_gem_no_doc => [:clean, :package] do + sh "#{'sudo ' unless Hoe::WINDOZE }gem install pkg/*.gem --no-rdoc --no-ri" +end + +namespace :manifest do + desc 'Recreate Manifest.txt to include ALL files' + task :refresh do + `rake check_manifest | patch -p0 > Manifest.txt` + end +end \ No newline at end of file diff --git a/agilelampclient/tasks/environment.rake b/agilelampclient/tasks/environment.rake new file mode 100644 index 0000000..691ed3b --- /dev/null +++ b/agilelampclient/tasks/environment.rake @@ -0,0 +1,7 @@ +task :ruby_env do + RUBY_APP = if RUBY_PLATFORM =~ /java/ + "jruby" + else + "ruby" + end unless defined? RUBY_APP +end diff --git a/agilelampclient/tasks/website.rake b/agilelampclient/tasks/website.rake new file mode 100644 index 0000000..93e03fa --- /dev/null +++ b/agilelampclient/tasks/website.rake @@ -0,0 +1,17 @@ +desc 'Generate website files' +task :website_generate => :ruby_env do + (Dir['website/**/*.txt'] - Dir['website/version*.txt']).each do |txt| + sh %{ #{RUBY_APP} script/txt2html #{txt} > #{txt.gsub(/txt$/,'html')} } + end +end + +desc 'Upload website files to rubyforge' +task :website_upload do + host = "#{rubyforge_username}@rubyforge.org" + remote_dir = "/var/www/gforge-projects/#{PATH}/" + local_dir = 'website' + sh %{rsync -aCv #{local_dir}/ #{host}:#{remote_dir}} +end + +desc 'Generate and upload website files' +task :website => [:website_generate, :website_upload, :publish_docs] diff --git a/agilelampclient/test/test_agilelamp.rb b/agilelampclient/test/test_agilelamp.rb new file mode 100644 index 0000000..15d95ff --- /dev/null +++ b/agilelampclient/test/test_agilelamp.rb @@ -0,0 +1,11 @@ +require File.dirname(__FILE__) + '/test_helper.rb' + +class TestMinder < Test::Unit::TestCase + + def setup + end + + def test_truth + assert true + end +end diff --git a/agilelampclient/test/test_helper.rb b/agilelampclient/test/test_helper.rb new file mode 100644 index 0000000..a32ff50 --- /dev/null +++ b/agilelampclient/test/test_helper.rb @@ -0,0 +1,2 @@ +require 'test/unit' +require File.dirname(__FILE__) + '/../lib/agilelamp' diff --git a/agilelampclient/website/index.html b/agilelampclient/website/index.html new file mode 100644 index 0000000..0541483 --- /dev/null +++ b/agilelampclient/website/index.html @@ -0,0 +1,11 @@ +<html> + <head> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>agilelamp</title> + + </head> + <body id="body"> + <p>This page has not yet been created for RubyGem <code>agilelamp</code></p> + <p>To the developer: To generate it, update website/index.txt and run the rake task <code>website</code> to generate this <code>index.html</code> file.</p> + </body> +</html> diff --git a/agilelampclient/website/index.txt b/agilelampclient/website/index.txt new file mode 100644 index 0000000..b35d324 --- /dev/null +++ b/agilelampclient/website/index.txt @@ -0,0 +1,39 @@ +h1. agilelamp + +h1. &#x2192; 'agilelamp' + + +h2. What + + +h2. Installing + +<pre syntax="ruby">sudo gem install agilelamp</pre> + +h2. The basics + + +h2. Demonstration of usage + + + +h2. Forum + +"http://groups.google.com/group/agilelamp":http://groups.google.com/group/agilelamp + +TODO - create Google Group - agilelamp + +h2. How to submit patches + +Read the "8 steps for fixing other people's code":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/ and for section "8b: Submit patch to Google Groups":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/#8b-google-groups, use the Google Group above. + +The trunk repository is <code>svn://rubyforge.org/var/svn/agilelamp/trunk</code> for anonymous access. + +h2. License + +This code is free to use under the terms of the MIT license. + +h2. Contact + +Comments are welcome. Send an email to "FIXME full name":mailto:FIXME email via the "forum":http://groups.google.com/group/agilelamp + diff --git a/agilelampclient/website/javascripts/rounded_corners_lite.inc.js b/agilelampclient/website/javascripts/rounded_corners_lite.inc.js new file mode 100644 index 0000000..afc3ea3 --- /dev/null +++ b/agilelampclient/website/javascripts/rounded_corners_lite.inc.js @@ -0,0 +1,285 @@ + + /**************************************************************** + * * + * curvyCorners * + * ------------ * + * * + * This script generates rounded corners for your divs. * + * * + * Version 1.2.9 * + * Copyright (c) 2006 Cameron Cooke * + * By: Cameron Cooke and Tim Hutchison. * + * * + * * + * Website: http://www.curvycorners.net * + * Email: [email protected] * + * Forum: http://www.curvycorners.net/forum/ * + * * + * * + * This library is free software; you can redistribute * + * it and/or modify it under the terms of the GNU * + * Lesser General Public License as published by the * + * Free Software Foundation; either version 2.1 of the * + * License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will * + * be useful, but WITHOUT ANY WARRANTY; without even the * + * implied warranty of MERCHANTABILITY or FITNESS FOR A * + * PARTICULAR PURPOSE. See the GNU Lesser General Public * + * License for more details. * + * * + * You should have received a copy of the GNU Lesser * + * General Public License along with this library; * + * Inc., 59 Temple Place, Suite 330, Boston, * + * MA 02111-1307 USA * + * * + ****************************************************************/ + +var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1; var isMoz = document.implementation && document.implementation.createDocument; var isSafari = ((navigator.userAgent.toLowerCase().indexOf('safari')!=-1)&&(navigator.userAgent.toLowerCase().indexOf('mac')!=-1))?true:false; function curvyCorners() +{ if(typeof(arguments[0]) != "object") throw newCurvyError("First parameter of curvyCorners() must be an object."); if(typeof(arguments[1]) != "object" && typeof(arguments[1]) != "string") throw newCurvyError("Second parameter of curvyCorners() must be an object or a class name."); if(typeof(arguments[1]) == "string") +{ var startIndex = 0; var boxCol = getElementsByClass(arguments[1]);} +else +{ var startIndex = 1; var boxCol = arguments;} +var curvyCornersCol = new Array(); if(arguments[0].validTags) +var validElements = arguments[0].validTags; else +var validElements = ["div"]; for(var i = startIndex, j = boxCol.length; i < j; i++) +{ var currentTag = boxCol[i].tagName.toLowerCase(); if(inArray(validElements, currentTag) !== false) +{ curvyCornersCol[curvyCornersCol.length] = new curvyObject(arguments[0], boxCol[i]);} +} +this.objects = curvyCornersCol; this.applyCornersToAll = function() +{ for(var x = 0, k = this.objects.length; x < k; x++) +{ this.objects[x].applyCorners();} +} +} +function curvyObject() +{ this.box = arguments[1]; this.settings = arguments[0]; this.topContainer = null; this.bottomContainer = null; this.masterCorners = new Array(); this.contentDIV = null; var boxHeight = get_style(this.box, "height", "height"); var boxWidth = get_style(this.box, "width", "width"); var borderWidth = get_style(this.box, "borderTopWidth", "border-top-width"); var borderColour = get_style(this.box, "borderTopColor", "border-top-color"); var boxColour = get_style(this.box, "backgroundColor", "background-color"); var backgroundImage = get_style(this.box, "backgroundImage", "background-image"); var boxPosition = get_style(this.box, "position", "position"); var boxPadding = get_style(this.box, "paddingTop", "padding-top"); this.boxHeight = parseInt(((boxHeight != "" && boxHeight != "auto" && boxHeight.indexOf("%") == -1)? boxHeight.substring(0, boxHeight.indexOf("px")) : this.box.scrollHeight)); this.boxWidth = parseInt(((boxWidth != "" && boxWidth != "auto" && boxWidth.indexOf("%") == -1)? boxWidth.substring(0, boxWidth.indexOf("px")) : this.box.scrollWidth)); this.borderWidth = parseInt(((borderWidth != "" && borderWidth.indexOf("px") !== -1)? borderWidth.slice(0, borderWidth.indexOf("px")) : 0)); this.boxColour = format_colour(boxColour); this.boxPadding = parseInt(((boxPadding != "" && boxPadding.indexOf("px") !== -1)? boxPadding.slice(0, boxPadding.indexOf("px")) : 0)); this.borderColour = format_colour(borderColour); this.borderString = this.borderWidth + "px" + " solid " + this.borderColour; this.backgroundImage = ((backgroundImage != "none")? backgroundImage : ""); this.boxContent = this.box.innerHTML; if(boxPosition != "absolute") this.box.style.position = "relative"; this.box.style.padding = "0px"; if(isIE && boxWidth == "auto" && boxHeight == "auto") this.box.style.width = "100%"; if(this.settings.autoPad == true && this.boxPadding > 0) +this.box.innerHTML = ""; this.applyCorners = function() +{ for(var t = 0; t < 2; t++) +{ switch(t) +{ case 0: +if(this.settings.tl || this.settings.tr) +{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var topMaxRadius = Math.max(this.settings.tl ? this.settings.tl.radius : 0, this.settings.tr ? this.settings.tr.radius : 0); newMainContainer.style.height = topMaxRadius + "px"; newMainContainer.style.top = 0 - topMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.topContainer = this.box.appendChild(newMainContainer);} +break; case 1: +if(this.settings.bl || this.settings.br) +{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var botMaxRadius = Math.max(this.settings.bl ? this.settings.bl.radius : 0, this.settings.br ? this.settings.br.radius : 0); newMainContainer.style.height = botMaxRadius + "px"; newMainContainer.style.bottom = 0 - botMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.bottomContainer = this.box.appendChild(newMainContainer);} +break;} +} +if(this.topContainer) this.box.style.borderTopWidth = "0px"; if(this.bottomContainer) this.box.style.borderBottomWidth = "0px"; var corners = ["tr", "tl", "br", "bl"]; for(var i in corners) +{ if(i > -1 < 4) +{ var cc = corners[i]; if(!this.settings[cc]) +{ if(((cc == "tr" || cc == "tl") && this.topContainer != null) || ((cc == "br" || cc == "bl") && this.bottomContainer != null)) +{ var newCorner = document.createElement("DIV"); newCorner.style.position = "relative"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; if(this.backgroundImage == "") +newCorner.style.backgroundColor = this.boxColour; else +newCorner.style.backgroundImage = this.backgroundImage; switch(cc) +{ case "tl": +newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.tr.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.left = -this.borderWidth + "px"; break; case "tr": +newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.tl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; newCorner.style.left = this.borderWidth + "px"; break; case "bl": +newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.br.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = -this.borderWidth + "px"; newCorner.style.backgroundPosition = "-" + (this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break; case "br": +newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.bl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = this.borderWidth + "px" +newCorner.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break;} +} +} +else +{ if(this.masterCorners[this.settings[cc].radius]) +{ var newCorner = this.masterCorners[this.settings[cc].radius].cloneNode(true);} +else +{ var newCorner = document.createElement("DIV"); newCorner.style.height = this.settings[cc].radius + "px"; newCorner.style.width = this.settings[cc].radius + "px"; newCorner.style.position = "absolute"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; var borderRadius = parseInt(this.settings[cc].radius - this.borderWidth); for(var intx = 0, j = this.settings[cc].radius; intx < j; intx++) +{ if((intx +1) >= borderRadius) +var y1 = -1; else +var y1 = (Math.floor(Math.sqrt(Math.pow(borderRadius, 2) - Math.pow((intx+1), 2))) - 1); if(borderRadius != j) +{ if((intx) >= borderRadius) +var y2 = -1; else +var y2 = Math.ceil(Math.sqrt(Math.pow(borderRadius,2) - Math.pow(intx, 2))); if((intx+1) >= j) +var y3 = -1; else +var y3 = (Math.floor(Math.sqrt(Math.pow(j ,2) - Math.pow((intx+1), 2))) - 1);} +if((intx) >= j) +var y4 = -1; else +var y4 = Math.ceil(Math.sqrt(Math.pow(j ,2) - Math.pow(intx, 2))); if(y1 > -1) this.drawPixel(intx, 0, this.boxColour, 100, (y1+1), newCorner, -1, this.settings[cc].radius); if(borderRadius != j) +{ for(var inty = (y1 + 1); inty < y2; inty++) +{ if(this.settings.antiAlias) +{ if(this.backgroundImage != "") +{ var borderFract = (pixelFraction(intx, inty, borderRadius) * 100); if(borderFract < 30) +{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, 0, this.settings[cc].radius);} +else +{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, -1, this.settings[cc].radius);} +} +else +{ var pixelcolour = BlendColour(this.boxColour, this.borderColour, pixelFraction(intx, inty, borderRadius)); this.drawPixel(intx, inty, pixelcolour, 100, 1, newCorner, 0, this.settings[cc].radius, cc);} +} +} +if(this.settings.antiAlias) +{ if(y3 >= y2) +{ if (y2 == -1) y2 = 0; this.drawPixel(intx, y2, this.borderColour, 100, (y3 - y2 + 1), newCorner, 0, 0);} +} +else +{ if(y3 >= y1) +{ this.drawPixel(intx, (y1 + 1), this.borderColour, 100, (y3 - y1), newCorner, 0, 0);} +} +var outsideColour = this.borderColour;} +else +{ var outsideColour = this.boxColour; var y3 = y1;} +if(this.settings.antiAlias) +{ for(var inty = (y3 + 1); inty < y4; inty++) +{ this.drawPixel(intx, inty, outsideColour, (pixelFraction(intx, inty , j) * 100), 1, newCorner, ((this.borderWidth > 0)? 0 : -1), this.settings[cc].radius);} +} +} +this.masterCorners[this.settings[cc].radius] = newCorner.cloneNode(true);} +if(cc != "br") +{ for(var t = 0, k = newCorner.childNodes.length; t < k; t++) +{ var pixelBar = newCorner.childNodes[t]; var pixelBarTop = parseInt(pixelBar.style.top.substring(0, pixelBar.style.top.indexOf("px"))); var pixelBarLeft = parseInt(pixelBar.style.left.substring(0, pixelBar.style.left.indexOf("px"))); var pixelBarHeight = parseInt(pixelBar.style.height.substring(0, pixelBar.style.height.indexOf("px"))); if(cc == "tl" || cc == "bl"){ pixelBar.style.left = this.settings[cc].radius -pixelBarLeft -1 + "px";} +if(cc == "tr" || cc == "tl"){ pixelBar.style.top = this.settings[cc].radius -pixelBarHeight -pixelBarTop + "px";} +switch(cc) +{ case "tr": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.boxWidth - this.settings[cc].radius + this.borderWidth) + pixelBarLeft) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "tl": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "bl": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs((this.boxHeight + this.settings[cc].radius + pixelBarTop) -this.borderWidth) + "px"; break;} +} +} +} +if(newCorner) +{ switch(cc) +{ case "tl": +if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "tr": +if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "bl": +if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break; case "br": +if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break;} +} +} +} +var radiusDiff = new Array(); radiusDiff["t"] = Math.abs(this.settings.tl.radius - this.settings.tr.radius) +radiusDiff["b"] = Math.abs(this.settings.bl.radius - this.settings.br.radius); for(z in radiusDiff) +{ if(z == "t" || z == "b") +{ if(radiusDiff[z]) +{ var smallerCornerType = ((this.settings[z + "l"].radius < this.settings[z + "r"].radius)? z +"l" : z +"r"); var newFiller = document.createElement("DIV"); newFiller.style.height = radiusDiff[z] + "px"; newFiller.style.width = this.settings[smallerCornerType].radius+ "px" +newFiller.style.position = "absolute"; newFiller.style.fontSize = "1px"; newFiller.style.overflow = "hidden"; newFiller.style.backgroundColor = this.boxColour; switch(smallerCornerType) +{ case "tl": +newFiller.style.bottom = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.topContainer.appendChild(newFiller); break; case "tr": +newFiller.style.bottom = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.topContainer.appendChild(newFiller); break; case "bl": +newFiller.style.top = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.bottomContainer.appendChild(newFiller); break; case "br": +newFiller.style.top = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.bottomContainer.appendChild(newFiller); break;} +} +var newFillerBar = document.createElement("DIV"); newFillerBar.style.position = "relative"; newFillerBar.style.fontSize = "1px"; newFillerBar.style.overflow = "hidden"; newFillerBar.style.backgroundColor = this.boxColour; newFillerBar.style.backgroundImage = this.backgroundImage; switch(z) +{ case "t": +if(this.topContainer) +{ if(this.settings.tl.radius && this.settings.tr.radius) +{ newFillerBar.style.height = topMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.tl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.tr.radius - this.borderWidth + "px"; newFillerBar.style.borderTop = this.borderString; if(this.backgroundImage != "") +newFillerBar.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; this.topContainer.appendChild(newFillerBar);} +this.box.style.backgroundPosition = "0px -" + (topMaxRadius - this.borderWidth) + "px";} +break; case "b": +if(this.bottomContainer) +{ if(this.settings.bl.radius && this.settings.br.radius) +{ newFillerBar.style.height = botMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.bl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.br.radius - this.borderWidth + "px"; newFillerBar.style.borderBottom = this.borderString; if(this.backgroundImage != "") +newFillerBar.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (topMaxRadius + this.borderWidth)) + "px"; this.bottomContainer.appendChild(newFillerBar);} +} +break;} +} +} +if(this.settings.autoPad == true && this.boxPadding > 0) +{ var contentContainer = document.createElement("DIV"); contentContainer.style.position = "relative"; contentContainer.innerHTML = this.boxContent; contentContainer.className = "autoPadDiv"; var topPadding = Math.abs(topMaxRadius - this.boxPadding); var botPadding = Math.abs(botMaxRadius - this.boxPadding); if(topMaxRadius < this.boxPadding) +contentContainer.style.paddingTop = topPadding + "px"; if(botMaxRadius < this.boxPadding) +contentContainer.style.paddingBottom = botMaxRadius + "px"; contentContainer.style.paddingLeft = this.boxPadding + "px"; contentContainer.style.paddingRight = this.boxPadding + "px"; this.contentDIV = this.box.appendChild(contentContainer);} +} +this.drawPixel = function(intx, inty, colour, transAmount, height, newCorner, image, cornerRadius) +{ var pixel = document.createElement("DIV"); pixel.style.height = height + "px"; pixel.style.width = "1px"; pixel.style.position = "absolute"; pixel.style.fontSize = "1px"; pixel.style.overflow = "hidden"; var topMaxRadius = Math.max(this.settings["tr"].radius, this.settings["tl"].radius); if(image == -1 && this.backgroundImage != "") +{ pixel.style.backgroundImage = this.backgroundImage; pixel.style.backgroundPosition = "-" + (this.boxWidth - (cornerRadius - intx) + this.borderWidth) + "px -" + ((this.boxHeight + topMaxRadius + inty) -this.borderWidth) + "px";} +else +{ pixel.style.backgroundColor = colour;} +if (transAmount != 100) +setOpacity(pixel, transAmount); pixel.style.top = inty + "px"; pixel.style.left = intx + "px"; newCorner.appendChild(pixel);} +} +function insertAfter(parent, node, referenceNode) +{ parent.insertBefore(node, referenceNode.nextSibling);} +function BlendColour(Col1, Col2, Col1Fraction) +{ var red1 = parseInt(Col1.substr(1,2),16); var green1 = parseInt(Col1.substr(3,2),16); var blue1 = parseInt(Col1.substr(5,2),16); var red2 = parseInt(Col2.substr(1,2),16); var green2 = parseInt(Col2.substr(3,2),16); var blue2 = parseInt(Col2.substr(5,2),16); if(Col1Fraction > 1 || Col1Fraction < 0) Col1Fraction = 1; var endRed = Math.round((red1 * Col1Fraction) + (red2 * (1 - Col1Fraction))); if(endRed > 255) endRed = 255; if(endRed < 0) endRed = 0; var endGreen = Math.round((green1 * Col1Fraction) + (green2 * (1 - Col1Fraction))); if(endGreen > 255) endGreen = 255; if(endGreen < 0) endGreen = 0; var endBlue = Math.round((blue1 * Col1Fraction) + (blue2 * (1 - Col1Fraction))); if(endBlue > 255) endBlue = 255; if(endBlue < 0) endBlue = 0; return "#" + IntToHex(endRed)+ IntToHex(endGreen)+ IntToHex(endBlue);} +function IntToHex(strNum) +{ base = strNum / 16; rem = strNum % 16; base = base - (rem / 16); baseS = MakeHex(base); remS = MakeHex(rem); return baseS + '' + remS;} +function MakeHex(x) +{ if((x >= 0) && (x <= 9)) +{ return x;} +else +{ switch(x) +{ case 10: return "A"; case 11: return "B"; case 12: return "C"; case 13: return "D"; case 14: return "E"; case 15: return "F";} +} +} +function pixelFraction(x, y, r) +{ var pixelfraction = 0; var xvalues = new Array(1); var yvalues = new Array(1); var point = 0; var whatsides = ""; var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x,2))); if ((intersect >= y) && (intersect < (y+1))) +{ whatsides = "Left"; xvalues[point] = 0; yvalues[point] = intersect - y; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y+1,2))); if ((intersect >= x) && (intersect < (x+1))) +{ whatsides = whatsides + "Top"; xvalues[point] = intersect - x; yvalues[point] = 1; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x+1,2))); if ((intersect >= y) && (intersect < (y+1))) +{ whatsides = whatsides + "Right"; xvalues[point] = 1; yvalues[point] = intersect - y; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y,2))); if ((intersect >= x) && (intersect < (x+1))) +{ whatsides = whatsides + "Bottom"; xvalues[point] = intersect - x; yvalues[point] = 0;} +switch (whatsides) +{ case "LeftRight": +pixelfraction = Math.min(yvalues[0],yvalues[1]) + ((Math.max(yvalues[0],yvalues[1]) - Math.min(yvalues[0],yvalues[1]))/2); break; case "TopRight": +pixelfraction = 1-(((1-xvalues[0])*(1-yvalues[1]))/2); break; case "TopBottom": +pixelfraction = Math.min(xvalues[0],xvalues[1]) + ((Math.max(xvalues[0],xvalues[1]) - Math.min(xvalues[0],xvalues[1]))/2); break; case "LeftBottom": +pixelfraction = (yvalues[0]*xvalues[1])/2; break; default: +pixelfraction = 1;} +return pixelfraction;} +function rgb2Hex(rgbColour) +{ try{ var rgbArray = rgb2Array(rgbColour); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); var hexColour = "#" + IntToHex(red) + IntToHex(green) + IntToHex(blue);} +catch(e){ alert("There was an error converting the RGB value to Hexadecimal in function rgb2Hex");} +return hexColour;} +function rgb2Array(rgbColour) +{ var rgbValues = rgbColour.substring(4, rgbColour.indexOf(")")); var rgbArray = rgbValues.split(", "); return rgbArray;} +function setOpacity(obj, opacity) +{ opacity = (opacity == 100)?99.999:opacity; if(isSafari && obj.tagName != "IFRAME") +{ var rgbArray = rgb2Array(obj.style.backgroundColor); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); obj.style.backgroundColor = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity/100 + ")";} +else if(typeof(obj.style.opacity) != "undefined") +{ obj.style.opacity = opacity/100;} +else if(typeof(obj.style.MozOpacity) != "undefined") +{ obj.style.MozOpacity = opacity/100;} +else if(typeof(obj.style.filter) != "undefined") +{ obj.style.filter = "alpha(opacity:" + opacity + ")";} +else if(typeof(obj.style.KHTMLOpacity) != "undefined") +{ obj.style.KHTMLOpacity = opacity/100;} +} +function inArray(array, value) +{ for(var i = 0; i < array.length; i++){ if (array[i] === value) return i;} +return false;} +function inArrayKey(array, value) +{ for(key in array){ if(key === value) return true;} +return false;} +function addEvent(elm, evType, fn, useCapture) { if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true;} +else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r;} +else { elm['on' + evType] = fn;} +} +function removeEvent(obj, evType, fn, useCapture){ if (obj.removeEventListener){ obj.removeEventListener(evType, fn, useCapture); return true;} else if (obj.detachEvent){ var r = obj.detachEvent("on"+evType, fn); return r;} else { alert("Handler could not be removed");} +} +function format_colour(colour) +{ var returnColour = "#ffffff"; if(colour != "" && colour != "transparent") +{ if(colour.substr(0, 3) == "rgb") +{ returnColour = rgb2Hex(colour);} +else if(colour.length == 4) +{ returnColour = "#" + colour.substring(1, 2) + colour.substring(1, 2) + colour.substring(2, 3) + colour.substring(2, 3) + colour.substring(3, 4) + colour.substring(3, 4);} +else +{ returnColour = colour;} +} +return returnColour;} +function get_style(obj, property, propertyNS) +{ try +{ if(obj.currentStyle) +{ var returnVal = eval("obj.currentStyle." + property);} +else +{ if(isSafari && obj.style.display == "none") +{ obj.style.display = ""; var wasHidden = true;} +var returnVal = document.defaultView.getComputedStyle(obj, '').getPropertyValue(propertyNS); if(isSafari && wasHidden) +{ obj.style.display = "none";} +} +} +catch(e) +{ } +return returnVal;} +function getElementsByClass(searchClass, node, tag) +{ var classElements = new Array(); if(node == null) +node = document; if(tag == null) +tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)"); for (i = 0, j = 0; i < elsLen; i++) +{ if(pattern.test(els[i].className)) +{ classElements[j] = els[i]; j++;} +} +return classElements;} +function newCurvyError(errorMessage) +{ return new Error("curvyCorners Error:\n" + errorMessage) +} diff --git a/agilelampclient/website/stylesheets/screen.css b/agilelampclient/website/stylesheets/screen.css new file mode 100644 index 0000000..2c84cd0 --- /dev/null +++ b/agilelampclient/website/stylesheets/screen.css @@ -0,0 +1,138 @@ +body { + background-color: #E1D1F1; + font-family: "Georgia", sans-serif; + font-size: 16px; + line-height: 1.6em; + padding: 1.6em 0 0 0; + color: #333; +} +h1, h2, h3, h4, h5, h6 { + color: #444; +} +h1 { + font-family: sans-serif; + font-weight: normal; + font-size: 4em; + line-height: 0.8em; + letter-spacing: -0.1ex; + margin: 5px; +} +li { + padding: 0; + margin: 0; + list-style-type: square; +} +a { + color: #5E5AFF; + background-color: #DAC; + font-weight: normal; + text-decoration: underline; +} +blockquote { + font-size: 90%; + font-style: italic; + border-left: 1px solid #111; + padding-left: 1em; +} +.caps { + font-size: 80%; +} + +#main { + width: 45em; + padding: 0; + margin: 0 auto; +} +.coda { + text-align: right; + color: #77f; + font-size: smaller; +} + +table { + font-size: 90%; + line-height: 1.4em; + color: #ff8; + background-color: #111; + padding: 2px 10px 2px 10px; + border-style: dashed; +} + +th { + color: #fff; +} + +td { + padding: 2px 10px 2px 10px; +} + +.success { + color: #0CC52B; +} + +.failed { + color: #E90A1B; +} + +.unknown { + color: #995000; +} +pre, code { + font-family: monospace; + font-size: 90%; + line-height: 1.4em; + color: #ff8; + background-color: #111; + padding: 2px 10px 2px 10px; +} +.comment { color: #aaa; font-style: italic; } +.keyword { color: #eff; font-weight: bold; } +.punct { color: #eee; font-weight: bold; } +.symbol { color: #0bb; } +.string { color: #6b4; } +.ident { color: #ff8; } +.constant { color: #66f; } +.regex { color: #ec6; } +.number { color: #F99; } +.expr { color: #227; } + +#version { + float: right; + text-align: right; + font-family: sans-serif; + font-weight: normal; + background-color: #B3ABFF; + color: #141331; + padding: 15px 20px 10px 20px; + margin: 0 auto; + margin-top: 15px; + border: 3px solid #141331; +} + +#version .numbers { + display: block; + font-size: 4em; + line-height: 0.8em; + letter-spacing: -0.1ex; + margin-bottom: 15px; +} + +#version p { + text-decoration: none; + color: #141331; + background-color: #B3ABFF; + margin: 0; + padding: 0; +} + +#version a { + text-decoration: none; + color: #141331; + background-color: #B3ABFF; +} + +.clickable { + cursor: pointer; + cursor: hand; +} + diff --git a/agilelampclient/website/template.rhtml b/agilelampclient/website/template.rhtml new file mode 100644 index 0000000..e851735 --- /dev/null +++ b/agilelampclient/website/template.rhtml @@ -0,0 +1,48 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <link rel="stylesheet" href="stylesheets/screen.css" type="text/css" media="screen" /> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <title> + <%= title %> + </title> + <script src="javascripts/rounded_corners_lite.inc.js" type="text/javascript"></script> +<style> + +</style> + <script type="text/javascript"> + window.onload = function() { + settings = { + tl: { radius: 10 }, + tr: { radius: 10 }, + bl: { radius: 10 }, + br: { radius: 10 }, + antiAlias: true, + autoPad: true, + validTags: ["div"] + } + var versionBox = new curvyCorners(settings, document.getElementById("version")); + versionBox.applyCornersToAll(); + } + </script> +</head> +<body> +<div id="main"> + + <h1><%= title %></h1> + <div id="version" class="clickable" onclick='document.location = "<%= download %>"; return false'> + <p>Get Version</p> + <a href="<%= download %>" class="numbers"><%= version %></a> + </div> + <%= body %> + <p class="coda"> + <a href="FIXME email">FIXME full name</a>, <%= modified.pretty %><br> + Theme extended from <a href="http://rb2js.rubyforge.org/">Paul Battley</a> + </p> +</div> + +<!-- insert site tracking codes here, like Google Urchin --> + +</body> +</html> diff --git a/data/agilelamp/agilelamp.schemas b/data/agilelamp/agilelamp.schemas new file mode 100644 index 0000000..af46293 --- /dev/null +++ b/data/agilelamp/agilelamp.schemas @@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<gconfschemafile> + <schemalist> + <schema> + <key>/schemas/apps/agilelamp/broken_build</key> + <applyto>/apps/agilelamp/broken_build</applyto> + <owner>agilelamp</owner> + <type>bool</type> + <default>false</default> + <locale name="C"/> + </schema> + + <schema> + <key>/schemas/apps/agilelamp/website</key> + <applyto>/apps/agilelamp/website</applyto> + <owner>agilelamp</owner> + <type>string</type> + <default></default> + <locale name="C"/> + </schema> + + <schema> + <key>/schemas/apps/agilelamp/check_interval</key> + <applyto>/apps/agilelamp/check_interval</applyto> + <owner>agilelamp</owner> + <type>integer</type> + <default>10</default> + <locale name="C"/> + </schema> + + <schema> + <key>/schemas/apps/agilelamp/username</key> + <applyto>/apps/agilelamp/username</applyto> + <owner>agilelamp</owner> + <type>string</type> + <default></default> + <locale name="C"/> + </schema> + + <schema> + <key>/schemas/apps/agilelamp/password</key> + <applyto>/apps/agilelamp/password</applyto> + <owner>agilelamp</owner> + <type>string</type> + <default></default> + <locale name="C"/> + </schema> + + </schemalist> +</gconfschemafile> +
tristil/agile-lamp
f0ca71bb0399cae64b47996b49ab8eb428dc9e46
Turns out we don't even use rnotify (and rinotify is something else)
diff --git a/Manifest.txt b/Manifest.txt index 47f0d76..c95bd0e 100644 --- a/Manifest.txt +++ b/Manifest.txt @@ -1,31 +1,31 @@ History.txt License.txt Manifest.txt README.txt Rakefile bin/agilelamp config/hoe.rb config/requirements.rb data/agilelamp/red_light.png data/agilelamp/green_light.png lib/agilelamp.rb lib/agilelamp/preferences_window.rb lib/agilelamp/statusicon.rb lib/agilelamp/window.rb lib/agilelamp/version.rb lib/agilelamp/cruiseparser.rb log/debug.log script/destroy script/generate script/txt2html setup.rb tasks/deployment.rake tasks/environment.rake tasks/website.rake test/test_helper.rb -test/test_minder.rb +test/test_agilelamp.rb website/index.html website/index.txt website/javascripts/rounded_corners_lite.inc.js website/stylesheets/screen.css website/template.rhtml diff --git a/bin/.agilelamp.swp b/bin/.agilelamp.swp deleted file mode 100644 index e71a08f..0000000 Binary files a/bin/.agilelamp.swp and /dev/null differ diff --git a/config/hoe.rb b/config/hoe.rb index 7985264..5a0d37a 100644 --- a/config/hoe.rb +++ b/config/hoe.rb @@ -1,71 +1,71 @@ require 'agilelamp/version' AUTHOR = 'Joseph Method' # can also be an array of Authors EMAIL = "[email protected]" -DESCRIPTION = "description of gem" +DESCRIPTION = "An application to coordinate a usb lava lamp with continuous build systems like cruisecontrol." GEM_NAME = 'agilelamp' # what ppl will type to install your gem RUBYFORGE_PROJECT = 'agilelamp' # The unix name for your project HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org" DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" @config_file = "~/.rubyforge/user-config.yml" @config = nil RUBYFORGE_USERNAME = "method" def rubyforge_username unless @config begin @config = YAML.load(File.read(File.expand_path(@config_file))) rescue puts <<-EOS ERROR: No rubyforge config file found: #{@config_file} Run 'rubyforge setup' to prepare your env for access to Rubyforge - See http://newgem.rubyforge.org/rubyforge.html for more details EOS exit end end RUBYFORGE_USERNAME.replace @config["username"] end REV = nil # UNCOMMENT IF REQUIRED: # REV = `svn info`.each {|line| if line =~ /^Revision:/ then k,v = line.split(': '); break v.chomp; else next; end} rescue nil VERS = AgileLamp::VERSION::STRING + (REV ? ".#{REV}" : "") RDOC_OPTS = ['--quiet', '--title', 'agilelamp documentation', "--opname", "index.html", "--line-numbers", "--main", "README", "--inline-source"] class Hoe def extra_deps @extra_deps.reject! { |x| Array(x).first == 'hoe' } @extra_deps end end # Generate all the Rake tasks # Run 'rake -T' to see list of generated tasks (from gem root directory) hoe = Hoe.new(GEM_NAME, VERS) do |p| p.author = AUTHOR p.description = DESCRIPTION p.email = EMAIL p.summary = DESCRIPTION p.url = HOMEPATH p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT p.test_globs = ["test/**/test_*.rb"] p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean. # == Optional p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n") #p.extra_deps = [] # An array of rubygem dependencies [name, version], e.g. [ ['active_support', '>= 1.3.1'] ] #p.spec_extras = {} # A hash of extra values to set in the gemspec. end CHANGES = hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n") PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}" hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc') hoe.rsync_args = '-av --delete --ignore-errors' diff --git a/lib/agilelamp/statusicon.rb b/lib/agilelamp/statusicon.rb index c5a2b08..cbb4708 100644 --- a/lib/agilelamp/statusicon.rb +++ b/lib/agilelamp/statusicon.rb @@ -1,71 +1,69 @@ -require 'rinotify' - module AgileLamp class StatusIcon def initialize @status = Gtk::StatusIcon.new @status.stock = Gtk::Stock::ADD @status.tooltip = "What should you be doing?" @status.signal_connect('activate') { on_activate } @status.signal_connect('popup-menu') {|statusicon, button, time| on_right_click statusicon, button, time } @menu = Gtk::Menu.new @menu.append(preferences = Gtk::ImageMenuItem.new(Gtk::Stock::PREFERENCES)) @menu.append(about = Gtk::ImageMenuItem.new(Gtk::Stock::ABOUT)) @menu.append(Gtk::SeparatorMenuItem.new) @menu.append(quit = Gtk::ImageMenuItem.new(Gtk::Stock::QUIT)) preferences.signal_connect('activate') { on_click_preferences } about.signal_connect('activate') { on_click_about } quit.signal_connect('activate') { Gtk.main_quit } @client = GConf::Client.default @client["/apps/agilelamp/broken_build"] = false @client.add_dir("/apps/agilelamp") @client.notify_add("/apps/agilelamp/broken_build") do |client, entry| entry.value == true ? broken_notification : fixed_notification @status.stock = entry.value == true ? Gtk::Stock::CANCEL : Gtk::Stock::APPLY end observe_cruisecontrol end def broken_notification `notify-send -u critical "Something is broken." "Blah broke on server Blah."` end def fixed_notification `notify-send -u normal "Something is fixed." "Issue Blah is fixed on server Blah."` end def break_build @client["/apps/agilelamp/broken_build"] = true puts "broke build" end def fix_build @client["/apps/agilelamp/broken_build"] = false end def observe_cruisecontrol @cruise ||= CruiseParser.new "cruise.meihome.com", "method", "mysticar" Gtk.timeout_add(1000) do result = @cruise.check_server puts "Server was #{result}" result ? break_build : fix_build true end end def on_click_preferences PreferencesWindow.new("Preferences").show_all end def on_activate @window ||= Proc.new { window = Window.new; window.signal_connect('destroy') { @window = nil }; puts "#{@window}"; window }.call end def on_click_about Gtk::AboutDialog.new.show_all end def on_right_click(statusicon, button, time) @menu.popup(nil, nil, button, time) {|menu, x, y, push_in| @status.position_menu(@menu)} @menu.show_all end end end diff --git a/minder.schemas b/minder.schemas deleted file mode 100644 index d58ee9c..0000000 --- a/minder.schemas +++ /dev/null @@ -1,15 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" standalone="yes"?> -<gconfschemafile> - <schemalist> - <schema> - <key>/schemas/apps/minder/broken_build</key> - <applyto>/apps/minder/broken_build</applyto> - <owner>minder</owner> - <type>bool</type> - <default>false</default> - <locale name="C"/> - </schema> - - </schemalist> -</gconfschemafile> -
tristil/agile-lamp
4c3da7b875cd4c0a0dfa991112a025cbb7d68de2
Change names to fit agilelamp
diff --git a/agilelamp.schemas b/agilelamp.schemas new file mode 100644 index 0000000..e69c400 --- /dev/null +++ b/agilelamp.schemas @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<gconfschemafile> + <schemalist> + <schema> + <key>/schemas/apps/agilelamp/broken_build</key> + <applyto>/apps/agilelamp/broken_build</applyto> + <owner>agilelamp</owner> + <type>bool</type> + <default>false</default> + <locale name="C"/> + </schema> + + </schemalist> +</gconfschemafile> + diff --git a/config/hoe.rb b/config/hoe.rb index 70322f7..7985264 100644 --- a/config/hoe.rb +++ b/config/hoe.rb @@ -1,71 +1,71 @@ -require 'minder/version' +require 'agilelamp/version' AUTHOR = 'Joseph Method' # can also be an array of Authors EMAIL = "[email protected]" DESCRIPTION = "description of gem" GEM_NAME = 'agilelamp' # what ppl will type to install your gem RUBYFORGE_PROJECT = 'agilelamp' # The unix name for your project HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org" DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" @config_file = "~/.rubyforge/user-config.yml" @config = nil RUBYFORGE_USERNAME = "method" def rubyforge_username unless @config begin @config = YAML.load(File.read(File.expand_path(@config_file))) rescue puts <<-EOS ERROR: No rubyforge config file found: #{@config_file} Run 'rubyforge setup' to prepare your env for access to Rubyforge - See http://newgem.rubyforge.org/rubyforge.html for more details EOS exit end end RUBYFORGE_USERNAME.replace @config["username"] end REV = nil # UNCOMMENT IF REQUIRED: # REV = `svn info`.each {|line| if line =~ /^Revision:/ then k,v = line.split(': '); break v.chomp; else next; end} rescue nil -VERS = Minder::VERSION::STRING + (REV ? ".#{REV}" : "") -RDOC_OPTS = ['--quiet', '--title', 'minder documentation', +VERS = AgileLamp::VERSION::STRING + (REV ? ".#{REV}" : "") +RDOC_OPTS = ['--quiet', '--title', 'agilelamp documentation', "--opname", "index.html", "--line-numbers", "--main", "README", "--inline-source"] class Hoe def extra_deps @extra_deps.reject! { |x| Array(x).first == 'hoe' } @extra_deps end end # Generate all the Rake tasks # Run 'rake -T' to see list of generated tasks (from gem root directory) hoe = Hoe.new(GEM_NAME, VERS) do |p| p.author = AUTHOR p.description = DESCRIPTION p.email = EMAIL p.summary = DESCRIPTION p.url = HOMEPATH p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT p.test_globs = ["test/**/test_*.rb"] p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean. # == Optional p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n") #p.extra_deps = [] # An array of rubygem dependencies [name, version], e.g. [ ['active_support', '>= 1.3.1'] ] #p.spec_extras = {} # A hash of extra values to set in the gemspec. end CHANGES = hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n") PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}" hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc') hoe.rsync_args = '-av --delete --ignore-errors' diff --git a/config/requirements.rb b/config/requirements.rb index 698ac8d..014e51b 100644 --- a/config/requirements.rb +++ b/config/requirements.rb @@ -1,17 +1,17 @@ require 'fileutils' include FileUtils require 'rubygems' %w[rake hoe newgem rubigen].each do |req_gem| begin require req_gem rescue LoadError puts "This Rakefile requires the '#{req_gem}' RubyGem." puts "Installation: gem install #{req_gem} -y" exit end end $:.unshift(File.join(File.dirname(__FILE__), %w[.. lib])) -require 'minder' +require 'agilelamp' diff --git a/lib/agilelamp/statusicon.rb b/lib/agilelamp/statusicon.rb index 180c4a5..c5a2b08 100644 --- a/lib/agilelamp/statusicon.rb +++ b/lib/agilelamp/statusicon.rb @@ -1,71 +1,71 @@ -require 'RNotify' +require 'rinotify' module AgileLamp class StatusIcon def initialize @status = Gtk::StatusIcon.new @status.stock = Gtk::Stock::ADD @status.tooltip = "What should you be doing?" @status.signal_connect('activate') { on_activate } @status.signal_connect('popup-menu') {|statusicon, button, time| on_right_click statusicon, button, time } @menu = Gtk::Menu.new @menu.append(preferences = Gtk::ImageMenuItem.new(Gtk::Stock::PREFERENCES)) @menu.append(about = Gtk::ImageMenuItem.new(Gtk::Stock::ABOUT)) @menu.append(Gtk::SeparatorMenuItem.new) @menu.append(quit = Gtk::ImageMenuItem.new(Gtk::Stock::QUIT)) preferences.signal_connect('activate') { on_click_preferences } about.signal_connect('activate') { on_click_about } quit.signal_connect('activate') { Gtk.main_quit } @client = GConf::Client.default @client["/apps/agilelamp/broken_build"] = false @client.add_dir("/apps/agilelamp") @client.notify_add("/apps/agilelamp/broken_build") do |client, entry| entry.value == true ? broken_notification : fixed_notification @status.stock = entry.value == true ? Gtk::Stock::CANCEL : Gtk::Stock::APPLY end observe_cruisecontrol end def broken_notification `notify-send -u critical "Something is broken." "Blah broke on server Blah."` end def fixed_notification `notify-send -u normal "Something is fixed." "Issue Blah is fixed on server Blah."` end def break_build @client["/apps/agilelamp/broken_build"] = true puts "broke build" end def fix_build @client["/apps/agilelamp/broken_build"] = false end def observe_cruisecontrol @cruise ||= CruiseParser.new "cruise.meihome.com", "method", "mysticar" Gtk.timeout_add(1000) do result = @cruise.check_server puts "Server was #{result}" result ? break_build : fix_build true end end def on_click_preferences PreferencesWindow.new("Preferences").show_all end def on_activate @window ||= Proc.new { window = Window.new; window.signal_connect('destroy') { @window = nil }; puts "#{@window}"; window }.call end def on_click_about Gtk::AboutDialog.new.show_all end def on_right_click(statusicon, button, time) @menu.popup(nil, nil, button, time) {|menu, x, y, push_in| @status.position_menu(@menu)} @menu.show_all end end end diff --git a/pkg/agilelamp-0.0.1.gem b/pkg/agilelamp-0.0.1.gem index 9ebce90..f68d036 100644 Binary files a/pkg/agilelamp-0.0.1.gem and b/pkg/agilelamp-0.0.1.gem differ diff --git a/pkg/agilelamp-0.0.1.tgz b/pkg/agilelamp-0.0.1.tgz index e913567..cbd9d32 100644 Binary files a/pkg/agilelamp-0.0.1.tgz and b/pkg/agilelamp-0.0.1.tgz differ diff --git a/pkg/agilelamp-0.0.1/config/hoe.rb b/pkg/agilelamp-0.0.1/config/hoe.rb index 70322f7..7985264 100644 --- a/pkg/agilelamp-0.0.1/config/hoe.rb +++ b/pkg/agilelamp-0.0.1/config/hoe.rb @@ -1,71 +1,71 @@ -require 'minder/version' +require 'agilelamp/version' AUTHOR = 'Joseph Method' # can also be an array of Authors EMAIL = "[email protected]" DESCRIPTION = "description of gem" GEM_NAME = 'agilelamp' # what ppl will type to install your gem RUBYFORGE_PROJECT = 'agilelamp' # The unix name for your project HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org" DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" @config_file = "~/.rubyforge/user-config.yml" @config = nil RUBYFORGE_USERNAME = "method" def rubyforge_username unless @config begin @config = YAML.load(File.read(File.expand_path(@config_file))) rescue puts <<-EOS ERROR: No rubyforge config file found: #{@config_file} Run 'rubyforge setup' to prepare your env for access to Rubyforge - See http://newgem.rubyforge.org/rubyforge.html for more details EOS exit end end RUBYFORGE_USERNAME.replace @config["username"] end REV = nil # UNCOMMENT IF REQUIRED: # REV = `svn info`.each {|line| if line =~ /^Revision:/ then k,v = line.split(': '); break v.chomp; else next; end} rescue nil -VERS = Minder::VERSION::STRING + (REV ? ".#{REV}" : "") -RDOC_OPTS = ['--quiet', '--title', 'minder documentation', +VERS = AgileLamp::VERSION::STRING + (REV ? ".#{REV}" : "") +RDOC_OPTS = ['--quiet', '--title', 'agilelamp documentation', "--opname", "index.html", "--line-numbers", "--main", "README", "--inline-source"] class Hoe def extra_deps @extra_deps.reject! { |x| Array(x).first == 'hoe' } @extra_deps end end # Generate all the Rake tasks # Run 'rake -T' to see list of generated tasks (from gem root directory) hoe = Hoe.new(GEM_NAME, VERS) do |p| p.author = AUTHOR p.description = DESCRIPTION p.email = EMAIL p.summary = DESCRIPTION p.url = HOMEPATH p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT p.test_globs = ["test/**/test_*.rb"] p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean. # == Optional p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n") #p.extra_deps = [] # An array of rubygem dependencies [name, version], e.g. [ ['active_support', '>= 1.3.1'] ] #p.spec_extras = {} # A hash of extra values to set in the gemspec. end CHANGES = hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n") PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}" hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc') hoe.rsync_args = '-av --delete --ignore-errors' diff --git a/pkg/agilelamp-0.0.1/config/requirements.rb b/pkg/agilelamp-0.0.1/config/requirements.rb index 698ac8d..014e51b 100644 --- a/pkg/agilelamp-0.0.1/config/requirements.rb +++ b/pkg/agilelamp-0.0.1/config/requirements.rb @@ -1,17 +1,17 @@ require 'fileutils' include FileUtils require 'rubygems' %w[rake hoe newgem rubigen].each do |req_gem| begin require req_gem rescue LoadError puts "This Rakefile requires the '#{req_gem}' RubyGem." puts "Installation: gem install #{req_gem} -y" exit end end $:.unshift(File.join(File.dirname(__FILE__), %w[.. lib])) -require 'minder' +require 'agilelamp' diff --git a/pkg/agilelamp-0.0.1/lib/agilelamp/statusicon.rb b/pkg/agilelamp-0.0.1/lib/agilelamp/statusicon.rb index 180c4a5..c5a2b08 100644 --- a/pkg/agilelamp-0.0.1/lib/agilelamp/statusicon.rb +++ b/pkg/agilelamp-0.0.1/lib/agilelamp/statusicon.rb @@ -1,71 +1,71 @@ -require 'RNotify' +require 'rinotify' module AgileLamp class StatusIcon def initialize @status = Gtk::StatusIcon.new @status.stock = Gtk::Stock::ADD @status.tooltip = "What should you be doing?" @status.signal_connect('activate') { on_activate } @status.signal_connect('popup-menu') {|statusicon, button, time| on_right_click statusicon, button, time } @menu = Gtk::Menu.new @menu.append(preferences = Gtk::ImageMenuItem.new(Gtk::Stock::PREFERENCES)) @menu.append(about = Gtk::ImageMenuItem.new(Gtk::Stock::ABOUT)) @menu.append(Gtk::SeparatorMenuItem.new) @menu.append(quit = Gtk::ImageMenuItem.new(Gtk::Stock::QUIT)) preferences.signal_connect('activate') { on_click_preferences } about.signal_connect('activate') { on_click_about } quit.signal_connect('activate') { Gtk.main_quit } @client = GConf::Client.default @client["/apps/agilelamp/broken_build"] = false @client.add_dir("/apps/agilelamp") @client.notify_add("/apps/agilelamp/broken_build") do |client, entry| entry.value == true ? broken_notification : fixed_notification @status.stock = entry.value == true ? Gtk::Stock::CANCEL : Gtk::Stock::APPLY end observe_cruisecontrol end def broken_notification `notify-send -u critical "Something is broken." "Blah broke on server Blah."` end def fixed_notification `notify-send -u normal "Something is fixed." "Issue Blah is fixed on server Blah."` end def break_build @client["/apps/agilelamp/broken_build"] = true puts "broke build" end def fix_build @client["/apps/agilelamp/broken_build"] = false end def observe_cruisecontrol @cruise ||= CruiseParser.new "cruise.meihome.com", "method", "mysticar" Gtk.timeout_add(1000) do result = @cruise.check_server puts "Server was #{result}" result ? break_build : fix_build true end end def on_click_preferences PreferencesWindow.new("Preferences").show_all end def on_activate @window ||= Proc.new { window = Window.new; window.signal_connect('destroy') { @window = nil }; puts "#{@window}"; window }.call end def on_click_about Gtk::AboutDialog.new.show_all end def on_right_click(statusicon, button, time) @menu.popup(nil, nil, button, time) {|menu, x, y, push_in| @status.position_menu(@menu)} @menu.show_all end end end diff --git a/pkg/agilelamp-0.0.1/script/txt2html b/pkg/agilelamp-0.0.1/script/txt2html index c6f1e3c..a60f59b 100755 --- a/pkg/agilelamp-0.0.1/script/txt2html +++ b/pkg/agilelamp-0.0.1/script/txt2html @@ -1,74 +1,74 @@ #!/usr/bin/env ruby require 'rubygems' begin require 'newgem' rescue LoadError puts "\n\nGenerating the website requires the newgem RubyGem" puts "Install: gem install newgem\n\n" exit(1) end require 'redcloth' require 'syntax/convertors/html' require 'erb' -require File.dirname(__FILE__) + '/../lib/minder/version.rb' +require File.dirname(__FILE__) + '/../lib/agilelamp/version.rb' -version = Minder::VERSION::STRING -download = 'http://rubyforge.org/projects/minder' +version = AgileLamp::VERSION::STRING +download = 'http://rubyforge.org/projects/agilelamp' class Fixnum def ordinal # teens return 'th' if (10..19).include?(self % 100) # others case self % 10 when 1: return 'st' when 2: return 'nd' when 3: return 'rd' else return 'th' end end end class Time def pretty return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" end end def convert_syntax(syntax, source) return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^<pre>|</pre>$!,'') end if ARGV.length >= 1 src, template = ARGV template ||= File.join(File.dirname(__FILE__), '/../website/template.rhtml') else puts("Usage: #{File.split($0).last} source.txt [template.rhtml] > output.html") exit! end template = ERB.new(File.open(template).read) title = nil body = nil File.open(src) do |fsrc| title_text = fsrc.readline body_text = fsrc.read syntax_items = [] body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)</\1>!m){ ident = syntax_items.length element, syntax, source = $1, $2, $3 syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}</#{element}>" "syntax-temp-#{ident}" } title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip body = RedCloth.new(body_text).to_html body.gsub!(%r!(?:<pre><code>)?syntax-temp-(\d+)(?:</code></pre>)?!){ syntax_items[$1.to_i] } end stat = File.stat(src) created = stat.ctime modified = stat.mtime $stdout << template.result(binding) diff --git a/pkg/agilelamp-0.0.1/test/test_helper.rb b/pkg/agilelamp-0.0.1/test/test_helper.rb index f2a1eb3..a32ff50 100644 --- a/pkg/agilelamp-0.0.1/test/test_helper.rb +++ b/pkg/agilelamp-0.0.1/test/test_helper.rb @@ -1,2 +1,2 @@ require 'test/unit' -require File.dirname(__FILE__) + '/../lib/minder' +require File.dirname(__FILE__) + '/../lib/agilelamp' diff --git a/pkg/agilelamp-0.0.1/website/index.html b/pkg/agilelamp-0.0.1/website/index.html index 1563ef2..0541483 100644 --- a/pkg/agilelamp-0.0.1/website/index.html +++ b/pkg/agilelamp-0.0.1/website/index.html @@ -1,11 +1,11 @@ <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> - <title>minder</title> + <title>agilelamp</title> </head> <body id="body"> - <p>This page has not yet been created for RubyGem <code>minder</code></p> + <p>This page has not yet been created for RubyGem <code>agilelamp</code></p> <p>To the developer: To generate it, update website/index.txt and run the rake task <code>website</code> to generate this <code>index.html</code> file.</p> </body> -</html> \ No newline at end of file +</html> diff --git a/pkg/agilelamp-0.0.1/website/index.txt b/pkg/agilelamp-0.0.1/website/index.txt index 9b60119..b35d324 100644 --- a/pkg/agilelamp-0.0.1/website/index.txt +++ b/pkg/agilelamp-0.0.1/website/index.txt @@ -1,39 +1,39 @@ -h1. minder +h1. agilelamp -h1. &#x2192; 'minder' +h1. &#x2192; 'agilelamp' h2. What h2. Installing -<pre syntax="ruby">sudo gem install minder</pre> +<pre syntax="ruby">sudo gem install agilelamp</pre> h2. The basics h2. Demonstration of usage h2. Forum -"http://groups.google.com/group/minder":http://groups.google.com/group/minder +"http://groups.google.com/group/agilelamp":http://groups.google.com/group/agilelamp -TODO - create Google Group - minder +TODO - create Google Group - agilelamp h2. How to submit patches Read the "8 steps for fixing other people's code":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/ and for section "8b: Submit patch to Google Groups":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/#8b-google-groups, use the Google Group above. -The trunk repository is <code>svn://rubyforge.org/var/svn/minder/trunk</code> for anonymous access. +The trunk repository is <code>svn://rubyforge.org/var/svn/agilelamp/trunk</code> for anonymous access. h2. License This code is free to use under the terms of the MIT license. h2. Contact -Comments are welcome. Send an email to "FIXME full name":mailto:FIXME email via the "forum":http://groups.google.com/group/minder +Comments are welcome. Send an email to "FIXME full name":mailto:FIXME email via the "forum":http://groups.google.com/group/agilelamp diff --git a/script/txt2html b/script/txt2html index c6f1e3c..a60f59b 100755 --- a/script/txt2html +++ b/script/txt2html @@ -1,74 +1,74 @@ #!/usr/bin/env ruby require 'rubygems' begin require 'newgem' rescue LoadError puts "\n\nGenerating the website requires the newgem RubyGem" puts "Install: gem install newgem\n\n" exit(1) end require 'redcloth' require 'syntax/convertors/html' require 'erb' -require File.dirname(__FILE__) + '/../lib/minder/version.rb' +require File.dirname(__FILE__) + '/../lib/agilelamp/version.rb' -version = Minder::VERSION::STRING -download = 'http://rubyforge.org/projects/minder' +version = AgileLamp::VERSION::STRING +download = 'http://rubyforge.org/projects/agilelamp' class Fixnum def ordinal # teens return 'th' if (10..19).include?(self % 100) # others case self % 10 when 1: return 'st' when 2: return 'nd' when 3: return 'rd' else return 'th' end end end class Time def pretty return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" end end def convert_syntax(syntax, source) return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^<pre>|</pre>$!,'') end if ARGV.length >= 1 src, template = ARGV template ||= File.join(File.dirname(__FILE__), '/../website/template.rhtml') else puts("Usage: #{File.split($0).last} source.txt [template.rhtml] > output.html") exit! end template = ERB.new(File.open(template).read) title = nil body = nil File.open(src) do |fsrc| title_text = fsrc.readline body_text = fsrc.read syntax_items = [] body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)</\1>!m){ ident = syntax_items.length element, syntax, source = $1, $2, $3 syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}</#{element}>" "syntax-temp-#{ident}" } title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip body = RedCloth.new(body_text).to_html body.gsub!(%r!(?:<pre><code>)?syntax-temp-(\d+)(?:</code></pre>)?!){ syntax_items[$1.to_i] } end stat = File.stat(src) created = stat.ctime modified = stat.mtime $stdout << template.result(binding) diff --git a/test/test_minder.rb b/test/test_agilelamp.rb similarity index 100% rename from test/test_minder.rb rename to test/test_agilelamp.rb diff --git a/test/test_helper.rb b/test/test_helper.rb index f2a1eb3..a32ff50 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,2 +1,2 @@ require 'test/unit' -require File.dirname(__FILE__) + '/../lib/minder' +require File.dirname(__FILE__) + '/../lib/agilelamp' diff --git a/website/index.html b/website/index.html index 1563ef2..0541483 100644 --- a/website/index.html +++ b/website/index.html @@ -1,11 +1,11 @@ <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> - <title>minder</title> + <title>agilelamp</title> </head> <body id="body"> - <p>This page has not yet been created for RubyGem <code>minder</code></p> + <p>This page has not yet been created for RubyGem <code>agilelamp</code></p> <p>To the developer: To generate it, update website/index.txt and run the rake task <code>website</code> to generate this <code>index.html</code> file.</p> </body> -</html> \ No newline at end of file +</html> diff --git a/website/index.txt b/website/index.txt index 9b60119..b35d324 100644 --- a/website/index.txt +++ b/website/index.txt @@ -1,39 +1,39 @@ -h1. minder +h1. agilelamp -h1. &#x2192; 'minder' +h1. &#x2192; 'agilelamp' h2. What h2. Installing -<pre syntax="ruby">sudo gem install minder</pre> +<pre syntax="ruby">sudo gem install agilelamp</pre> h2. The basics h2. Demonstration of usage h2. Forum -"http://groups.google.com/group/minder":http://groups.google.com/group/minder +"http://groups.google.com/group/agilelamp":http://groups.google.com/group/agilelamp -TODO - create Google Group - minder +TODO - create Google Group - agilelamp h2. How to submit patches Read the "8 steps for fixing other people's code":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/ and for section "8b: Submit patch to Google Groups":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/#8b-google-groups, use the Google Group above. -The trunk repository is <code>svn://rubyforge.org/var/svn/minder/trunk</code> for anonymous access. +The trunk repository is <code>svn://rubyforge.org/var/svn/agilelamp/trunk</code> for anonymous access. h2. License This code is free to use under the terms of the MIT license. h2. Contact -Comments are welcome. Send an email to "FIXME full name":mailto:FIXME email via the "forum":http://groups.google.com/group/minder +Comments are welcome. Send an email to "FIXME full name":mailto:FIXME email via the "forum":http://groups.google.com/group/agilelamp
chollier/proutlol
d43e5db3af10a1e10fe9741357c0e8ebfe09fe94
let's forget the personal branding stuff, this blog is gonna be ouagadoudou only.
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index e22327a..93dbab9 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,18 +1,18 @@ # Methods added to this helper will be available to all templates in the application. module ApplicationHelper def guess_page_title - blogname = "Le blog de Loïc Chollier" + blogname = "Ouagadoudou" case controller_name when "posts" case controller.action_name when "show" return "#{Post.find_by_permalink(params[:id]).title} | #{blogname}" when "index" return blogname end else end end end diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 96cc641..5cbbcc9 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,48 +1,48 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" xmlns:fb="http://www.facebook.com/2008/fbml"> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <title><%= guess_page_title %></title> <%= render :partial => "layouts/facebook" %> <%= stylesheet_link_tag 'application' %> <%= javascript_include_tag :defaults %> <%= fb_connect_javascript_tag %> <%= init_fb_connect "XFBML" %> </head> <body> <div id="topbar"> <p style="color: green"><%= flash[:notice] %></p> </div> <div id="header"> - <h1><%= link_to "Ouagadoudou", root_path, :title => "Le Blog de Loïc Chollier", :name => "Accueil" %></h1> + <h1><%= link_to "Ouagadoudou", root_path, :title => "Ouagadoudou", :name => "Accueil" %></h1> </div> <div id="main"> <div id="sidebar"> <div id="presentation" class="sidebloc"> <span class="sidetitle">A propos</span> - <p><img src="/images/Loic_Chollier.jpg" alt="Loïc Chollier" title="Photo de Loïc Chollier" width="64px" height="49px" />Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> + <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> </div> <div id="content"> <%= yield %> </div> </div> </body> </html> diff --git a/app/views/posts/index.html.erb b/app/views/posts/index.html.erb index a594027..9b9f3aa 100644 --- a/app/views/posts/index.html.erb +++ b/app/views/posts/index.html.erb @@ -1,22 +1,22 @@ <div id="posts"> <% @posts.each do |post| %> <div id="post-<%= post.id %>" class="post"> <h2><%= link_to post.title, permalink_path(post), :title => post.title %></h2> <div class="post-content"> <%= post.content %> </div> <div class="post_infos"> <p> <span class="share"> <%= twitter_share(post) %> <%= facebook_share(post) %> </span> <% if current_user && current_user.admin %><%= link_to 'Edit', edit_admin_post_path(post.id) %> | <% end %> <%- if post.comments.size > 0 -%> <%= link_to "#{post.comments.size} commentaire#{post.comments.size > 1 ? 's' : ''}", permalink_path(post, :anchor => "comments") %> | <%- end -%> - Publié le <%= post.created_at.strftime("%d %b %Y") %> par <%= link_to "Lo&iuml;c Chollier", "http://loic.chollier.com", :title => "Loïc Chollier" %> + Publié le <%= post.created_at.strftime("%d %b %Y") %> par l'administrateur. </p> </div> </div> <% end %> </div>
chollier/proutlol
3771ff708c694f0d3c68b1891d845524ff938404
bordel de merde de facebooker qui me niquait tout, rollback et pensez à changer ma secret key parceque bon.
diff --git a/.gitignore b/.gitignore index 2a20ebb..ac3519a 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ log/* !.gitignore +log/*.log +Capfile +config/deploy.rb diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 0549f11..4609dc1 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,36 +1,36 @@ class UsersController < ApplicationController before_filter :require_no_user, :only => [:new, :create] before_filter :require_user, :only => [:show, :edit, :update] - def new - @user = User.new - end - - def create - @user = User.new(params[:user]) - if @user.save - flash[:notice] = "Account registered!" - redirect_to root_url - else - render :action => :new - end - end - - def show - @user = current_user - end - - def edit - @user = current_user - end - - def update - @user = current_user # makes our views "cleaner" and more consistent - if @user.update_attributes(params[:user]) - flash[:notice] = "Account updated!" - redirect_to current_user - else - render :action => :edit - end - end + # def new + # @user = User.new + # end + # + # def create + # @user = User.new(params[:user]) + # if @user.save + # flash[:notice] = "Account registered!" + # redirect_to root_url + # else + # render :action => :new + # end + # end + # + # def show + # @user = current_user + # end + # + # def edit + # @user = current_user + # end + # + # def update + # @user = current_user # makes our views "cleaner" and more consistent + # if @user.update_attributes(params[:user]) + # flash[:notice] = "Account updated!" + # redirect_to current_user + # else + # render :action => :edit + # end + # end end diff --git a/app/views/users/_form.html.erb b/app/views/users/_form.html.erb deleted file mode 100644 index 7556023..0000000 --- a/app/views/users/_form.html.erb +++ /dev/null @@ -1,8 +0,0 @@ -<%= form.label :login %><br /> -<%= form.text_field :login %><br /> -<br /> -<%= form.label :password, form.object.new_record? ? nil : "Change password" %><br /> -<%= form.password_field :password %><br /> -<br /> -<%= form.label :password_confirmation %><br /> -<%= form.password_field :password_confirmation %><br /> \ No newline at end of file diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb deleted file mode 100644 index 06b3c1c..0000000 --- a/app/views/users/edit.html.erb +++ /dev/null @@ -1,9 +0,0 @@ -<h1>Edit My Account</h1> - -<% form_for @user, :url => user_path do |f| %> - <%= f.error_messages %> - <%= render :partial => "form", :object => f %> - <%= f.submit "Update" %> -<% end %> - -<br /><%= link_to "My Profile", user_path %> \ No newline at end of file diff --git a/app/views/users/new.html.erb b/app/views/users/new.html.erb deleted file mode 100644 index 1891719..0000000 --- a/app/views/users/new.html.erb +++ /dev/null @@ -1,7 +0,0 @@ -<h1>Register</h1> - -<% form_for @user, :url => new_user_path do |f| %> - <%= f.error_messages %> - <%= render :partial => "form", :object => f %> - <%= f.submit "Register" %> -<% end %> \ No newline at end of file diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb deleted file mode 100644 index dbc8c27..0000000 --- a/app/views/users/show.html.erb +++ /dev/null @@ -1,37 +0,0 @@ -<p> - <b>Login:</b> - <%=h @user.login %> -</p> - -<p> - <b>Login count:</b> - <%=h @user.login_count %> -</p> - -<p> - <b>Last request at:</b> - <%=h @user.last_request_at %> -</p> - -<p> - <b>Last login at:</b> - <%=h @user.last_login_at %> -</p> - -<p> - <b>Current login at:</b> - <%=h @user.current_login_at %> -</p> - -<p> - <b>Last login ip:</b> - <%=h @user.last_login_ip %> -</p> - -<p> - <b>Current login ip:</b> - <%=h @user.current_login_ip %> -</p> - - -<%= link_to 'Edit', edit_user_path %> \ No newline at end of file diff --git a/config/environments/production.rb b/config/environments/production.rb index a42dd03..27119d2 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -1,30 +1,28 @@ # Settings specified here will take precedence over those in config/environment.rb # The production environment is meant for finished, "live" apps. # Code is not reloaded between requests -# config.cache_classes = true -config.cache_classes = false +config.cache_classes = true # Full error reports are disabled and caching is turned on config.action_controller.consider_all_requests_local = false -# config.action_controller.perform_caching = true -config.action_controller.perform_caching = false +config.action_controller.perform_caching = true config.action_view.cache_template_loading = true # See everything in the log (default is :info) # config.log_level = :debug # Use a different logger for distributed setups # config.logger = SyslogLogger.new # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and javascripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! \ No newline at end of file diff --git a/config/facebooker.yml b/config/facebooker.yml index 38080e6..f3a8cc3 100644 --- a/config/facebooker.yml +++ b/config/facebooker.yml @@ -1,49 +1,49 @@ # The api key, secret key, and canvas page name are required to get started # Tunnel configuration is only needed if you are going to use the facebooker:tunnel Rake tasks # Your callback url in Facebook should be set to http://public_host:public_port # If you're building a Facebook connect site, # change the value of set_asset_host_to_callback_url to false # To develop for the new profile design, add the following key.. # api: new # remove the key or set it to anything else to use the old facebook design. # This should only be necessary until the final version of the new profile is released. development: api_key: bd8abd1a704f7dc09c1bdd9d4d38b1bf secret_key: 0100a6a00ec3981000a135ff81dd3e30 canvas_page_name: callback_url: pretty_errors: true set_asset_host_to_callback_url: true tunnel: public_host_username: public_host: public_port: 4007 local_port: 3000 server_alive_interval: 0 test: api_key: secret_key: canvas_page_name: callback_url: set_asset_host_to_callback_url: true tunnel: public_host_username: public_host: public_port: 4007 local_port: 3000 server_alive_interval: 0 production: - api_key: - secret_key: + api_key: bd8abd1a704f7dc09c1bdd9d4d38b1bf + secret_key: 0100a6a00ec3981000a135ff81dd3e30 canvas_page_name: callback_url: set_asset_host_to_callback_url: true tunnel: public_host_username: public_host: public_port: 4007 local_port: 3000 server_alive_interval: 0 diff --git a/db/schema.rb b/db/schema.rb index e1d6f5e..05bc350 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,116 +1,69 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20091022141733) do create_table "comments", :force => true do |t| - t.string "url", :limit => 250 + t.string "name" + t.string "email" + t.string "url" t.text "content" t.integer "post_id" t.integer "user_id" + t.string "ip" t.datetime "created_at" t.datetime "updated_at" - t.string "name", :limit => 250 - t.string "email", :limit => 250 - end - - create_table "contents", :force => true do |t| - t.string "type" - t.string "title" - t.string "author" - t.text "body" - t.text "extended" - t.text "excerpt" - t.string "keywords" - t.datetime "created_at" - t.datetime "updated_at" - t.integer "user_id" - t.string "permalink" - t.string "guid" - t.integer "text_filter_id" - t.text "whiteboard" - t.string "name" - t.boolean "published", :default => false - t.boolean "allow_pings" - t.boolean "allow_comments" - t.datetime "published_at" - t.string "state" - end - - add_index "contents", ["published"], :name => "index_contents_on_published" - add_index "contents", ["text_filter_id"], :name => "index_contents_on_text_filter_id" - - create_table "feedback", :force => true do |t| - t.string "type" - t.string "title" - t.string "author" - t.text "body" - t.text "excerpt" - t.datetime "created_at" - t.datetime "updated_at" - t.integer "user_id" - t.string "guid" - t.integer "text_filter_id" - t.text "whiteboard" - t.integer "article_id" - t.string "email" - t.string "url" - t.string "ip", :limit => 40 - t.string "blog_name" - t.boolean "published", :default => false - t.datetime "published_at" - t.string "state" - t.boolean "status_confirmed" end - add_index "feedback", ["article_id"], :name => "index_feedback_on_article_id" - add_index "feedback", ["text_filter_id"], :name => "index_feedback_on_text_filter_id" - create_table "posts", :force => true do |t| t.string "title" t.text "content" t.integer "user_id" + t.string "permalink" + t.string "facebook_title" + t.text "facebook_description" + t.string "facebook_image" t.datetime "created_at" t.datetime "updated_at" - t.string "permalink" end create_table "shares", :force => true do |t| t.integer "type" t.integer "creator_id" + t.integer "post_id" t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "login", :null => false t.string "email" t.string "crypted_password" t.string "password_salt" t.string "persistence_token", :null => false t.string "single_access_token", :null => false t.string "perishable_token", :null => false t.integer "login_count", :default => 0, :null => false t.integer "failed_login_count", :default => 0, :null => false t.datetime "last_request_at" t.datetime "current_login_at" t.datetime "last_login_at" t.string "current_login_ip" t.string "last_login_ip" t.boolean "admin" t.string "first_name" t.string "last_name" t.datetime "created_at" t.datetime "updated_at" t.integer "facebook_uid", :limit => 8 end end
chollier/proutlol
9a835f3d88fe7522e07e55a4f3daa76590e30033
let's stop caching oO
diff --git a/config/environments/production.rb b/config/environments/production.rb index 27119d2..a42dd03 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -1,28 +1,30 @@ # Settings specified here will take precedence over those in config/environment.rb # The production environment is meant for finished, "live" apps. # Code is not reloaded between requests -config.cache_classes = true +# config.cache_classes = true +config.cache_classes = false # Full error reports are disabled and caching is turned on config.action_controller.consider_all_requests_local = false -config.action_controller.perform_caching = true +# config.action_controller.perform_caching = true +config.action_controller.perform_caching = false config.action_view.cache_template_loading = true # See everything in the log (default is :info) # config.log_level = :debug # Use a different logger for distributed setups # config.logger = SyslogLogger.new # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and javascripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! \ No newline at end of file
chollier/proutlol
8594e73831c31efcb9ff9678b2a438bb0e707d1d
Il faut pouvoir ajouter de nouveaux utilisateur pour avoir un admin :D
diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 74122df..0549f11 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,36 +1,36 @@ class UsersController < ApplicationController before_filter :require_no_user, :only => [:new, :create] before_filter :require_user, :only => [:show, :edit, :update] - # def new - # @user = User.new - # end + def new + @user = User.new + end - # def create - # @user = User.new(params[:user]) - # if @user.save - # flash[:notice] = "Account registered!" - # redirect_to root_url - # else - # render :action => :new - # end - # end + def create + @user = User.new(params[:user]) + if @user.save + flash[:notice] = "Account registered!" + redirect_to root_url + else + render :action => :new + end + end - # def show - # @user = current_user - # end - # - # def edit - # @user = current_user - # end - # - # def update - # @user = current_user # makes our views "cleaner" and more consistent - # if @user.update_attributes(params[:user]) - # flash[:notice] = "Account updated!" - # redirect_to current_user - # else - # render :action => :edit - # end - # end + def show + @user = current_user + end + + def edit + @user = current_user + end + + def update + @user = current_user # makes our views "cleaner" and more consistent + if @user.update_attributes(params[:user]) + flash[:notice] = "Account updated!" + redirect_to current_user + else + render :action => :edit + end + end end diff --git a/app/views/users/_form.html.erb b/app/views/users/_form.html.erb new file mode 100644 index 0000000..7556023 --- /dev/null +++ b/app/views/users/_form.html.erb @@ -0,0 +1,8 @@ +<%= form.label :login %><br /> +<%= form.text_field :login %><br /> +<br /> +<%= form.label :password, form.object.new_record? ? nil : "Change password" %><br /> +<%= form.password_field :password %><br /> +<br /> +<%= form.label :password_confirmation %><br /> +<%= form.password_field :password_confirmation %><br /> \ No newline at end of file diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb new file mode 100644 index 0000000..06b3c1c --- /dev/null +++ b/app/views/users/edit.html.erb @@ -0,0 +1,9 @@ +<h1>Edit My Account</h1> + +<% form_for @user, :url => user_path do |f| %> + <%= f.error_messages %> + <%= render :partial => "form", :object => f %> + <%= f.submit "Update" %> +<% end %> + +<br /><%= link_to "My Profile", user_path %> \ No newline at end of file diff --git a/app/views/users/new.html.erb b/app/views/users/new.html.erb new file mode 100644 index 0000000..1891719 --- /dev/null +++ b/app/views/users/new.html.erb @@ -0,0 +1,7 @@ +<h1>Register</h1> + +<% form_for @user, :url => new_user_path do |f| %> + <%= f.error_messages %> + <%= render :partial => "form", :object => f %> + <%= f.submit "Register" %> +<% end %> \ No newline at end of file diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb new file mode 100644 index 0000000..dbc8c27 --- /dev/null +++ b/app/views/users/show.html.erb @@ -0,0 +1,37 @@ +<p> + <b>Login:</b> + <%=h @user.login %> +</p> + +<p> + <b>Login count:</b> + <%=h @user.login_count %> +</p> + +<p> + <b>Last request at:</b> + <%=h @user.last_request_at %> +</p> + +<p> + <b>Last login at:</b> + <%=h @user.last_login_at %> +</p> + +<p> + <b>Current login at:</b> + <%=h @user.current_login_at %> +</p> + +<p> + <b>Last login ip:</b> + <%=h @user.last_login_ip %> +</p> + +<p> + <b>Current login ip:</b> + <%=h @user.current_login_ip %> +</p> + + +<%= link_to 'Edit', edit_user_path %> \ No newline at end of file
chollier/proutlol
b185fc4bd88386df0cea56eafcc863fa1f229f49
i have fixed the log pbm, i hope
diff --git a/.gitignore b/.gitignore index 87afabb..2a20ebb 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -log/* \ No newline at end of file +log/* !.gitignore diff --git a/log/.gitignore b/log/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/log/development.log b/log/development.log new file mode 100644 index 0000000..7ab55c3 --- /dev/null +++ b/log/development.log @@ -0,0 +1,10 @@ +# Logfile created on Thu Jul 16 03:17:23 +0200 2009 SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UserSessionsController#new (for 127.0.0.1 at 2009-07-16 03:17:35) [GET] + Parameters: {"action"=>"new", "controller"=>"user_sessions"} + User Columns (2.9ms) SHOW FIELDS FROM `users` +Rendering template within layouts/application +Rendering user_sessions/new +Completed in 34ms (View: 10, DB: 3) | 200 OK [http://chollier.com/user_session/new]
chollier/proutlol
02230fff291d0bf307930583ccedb079da2605e5
we now support facebook connect authentication
diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..7735099 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "vendor/plugins/facebooker"] + path = vendor/plugins/facebooker + url = git://github.com/mmangino/facebooker.git diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index b42b292..a9c511c 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,49 +1,51 @@ # Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all # include all helpers, all the time protect_from_forgery # See ActionController::RequestForgeryProtection for details # Scrub sensitive parameters from your log filter_parameter_logging :password, :password_confirmation helper_method :current_user_session, :current_user - + before_filter :set_facebook_session + helper_method :facebook_session + private def current_user_session return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find end def current_user return @current_user if defined?(@current_user) @current_user = current_user_session && current_user_session.user end def require_user unless current_user flash[:notice] = "You must be logged in to access this page" redirect_to new_user_session_url return false end end def require_no_user if current_user flash[:notice] = "You must be logged out to access this page" redirect_to root_url return false end end def require_admin if current_user && current_user.admin return true else flash[:notice] = "You must be admin to access this page" redirect_to root_url return false end end end diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index bb519bf..37dcd6c 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,32 +1,38 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" xmlns:fb="http://www.facebook.com/2008/fbml"> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <title><%= controller.action_name %></title> <%= stylesheet_link_tag 'application' %> + <%= javascript_include_tag :defaults %> + + <%= fb_connect_javascript_tag %> + <%= init_fb_connect "XFBML" %> + </head> <body> <div id="topbar"> <p style="color: green"><%= flash[:notice] %></p> </div> <div id="header"> <h1>Ouagadoudou</h1> </div> <div id="main"> <div id="content"> + <%= yield %> </div> <div id="sidebar"> </div> </div> </body> </html> diff --git a/app/views/user_sessions/new.html.erb b/app/views/user_sessions/new.html.erb index 1eb03c6..7957fd7 100644 --- a/app/views/user_sessions/new.html.erb +++ b/app/views/user_sessions/new.html.erb @@ -1,14 +1,21 @@ <h1>Login</h1> <% form_for @user_session, :url => user_session_path do |f| %> <%= f.error_messages %> <%= f.label :login %><br /> <%= f.text_field :login %><br /> <br /> <%= f.label :password %><br /> <%= f.password_field :password %><br /> <br /> <%= f.check_box :remember_me %><%= f.label :remember_me %><br /> <br /> - <%= f.submit "Login" %> -<% end %> \ No newline at end of file + <%= f.submit "Login" %><br /> + <br /> + + + + +<% end %> + +<%= authlogic_facebook_login_button %> diff --git a/config/environment.rb b/config/environment.rb index 0595f77..bc4f162 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,43 +1,43 @@ # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" config.gem "authlogic" - config.gem "facebooker" + # config.gem "mmangino-facebooker" # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'Paris' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. #config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] config.i18n.default_locale = :fr end \ No newline at end of file diff --git a/config/facebooker.yml b/config/facebooker.yml new file mode 100644 index 0000000..a68a197 --- /dev/null +++ b/config/facebooker.yml @@ -0,0 +1,49 @@ +# The api key, secret key, and canvas page name are required to get started +# Tunnel configuration is only needed if you are going to use the facebooker:tunnel Rake tasks +# Your callback url in Facebook should be set to http://public_host:public_port +# If you're building a Facebook connect site, +# change the value of set_asset_host_to_callback_url to false +# To develop for the new profile design, add the following key.. +# api: new +# remove the key or set it to anything else to use the old facebook design. +# This should only be necessary until the final version of the new profile is released. + +development: + api_key: + secret_key: + canvas_page_name: + callback_url: + pretty_errors: true + set_asset_host_to_callback_url: true + tunnel: + public_host_username: + public_host: + public_port: 4007 + local_port: 3000 + server_alive_interval: 0 + +test: + api_key: + secret_key: + canvas_page_name: + callback_url: + set_asset_host_to_callback_url: true + tunnel: + public_host_username: + public_host: + public_port: 4007 + local_port: 3000 + server_alive_interval: 0 + +production: + api_key: + secret_key: + canvas_page_name: + callback_url: + set_asset_host_to_callback_url: true + tunnel: + public_host_username: + public_host: + public_port: 4007 + local_port: 3000 + server_alive_interval: 0 diff --git a/config/routes.rb b/config/routes.rb index 64e4af6..4387cb6 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,54 +1,54 @@ ActionController::Routing::Routes.draw do |map| map.resources :comments map.root :controller => "posts", :action => "index" map.resource :user_session map.resources :users map.resources :posts map.connect '/logout', :controller => 'user_sessions', :action => 'destroy' - map.connect '/logout', :controller => 'user_sessions', :action => 'new' + map.connect '/login', :controller => 'user_sessions', :action => 'new' # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/db/migrate/20090715194511_create_users.rb b/db/migrate/20090715194511_create_users.rb index 4b659d3..de625f7 100644 --- a/db/migrate/20090715194511_create_users.rb +++ b/db/migrate/20090715194511_create_users.rb @@ -1,30 +1,33 @@ class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :login, :null => false # optional, you can use email instead, or both - t.string :email, :null => false # optional, you can use login instead, or both - t.string :crypted_password, :null => false # optional, see below - t.string :password_salt, :null => false # optional, but highly recommended + t.string :email #, :null => false # optional, you can use login instead, or both + t.string :crypted_password #, :null => false # optional, see below + t.string :password_salt#, :null => false # optional, but highly recommended t.string :persistence_token, :null => false # required t.string :single_access_token, :null => false # optional, see Authlogic::Session::Params t.string :perishable_token, :null => false # optional, see Authlogic::Session::Perishability # Magic columns, just like ActiveRecord's created_at and updated_at. These are automatically maintained by Authlogic if they are present. t.integer :login_count, :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns t.integer :failed_login_count, :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns t.datetime :last_request_at # optional, see Authlogic::Session::MagicColumns t.datetime :current_login_at # optional, see Authlogic::Session::MagicColumns t.datetime :last_login_at # optional, see Authlogic::Session::MagicColumns t.string :current_login_ip # optional, see Authlogic::Session::MagicColumns t.string :last_login_ip # optional, see Authlogic::Session::MagicColumns - #Added by me for the blog's admin + #Added by me for the blog t.boolean :admin + t.string :first_name + t.string :last_name + t.timestamps end end def self.down drop_table :users end end diff --git a/db/migrate/20090715232943_add_facebook_connect_fields_to_user.rb b/db/migrate/20090715232943_add_facebook_connect_fields_to_user.rb new file mode 100644 index 0000000..18cb940 --- /dev/null +++ b/db/migrate/20090715232943_add_facebook_connect_fields_to_user.rb @@ -0,0 +1,9 @@ +class AddFacebookConnectFieldsToUser < ActiveRecord::Migration + def self.up + add_column :users, :facebook_uid, :bigint + end + + def self.down + remove_column :users, :facebook_uid + end +end diff --git a/db/schema.rb b/db/schema.rb index 374b590..340376c 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,41 +1,51 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090715194511) do +ActiveRecord::Schema.define(:version => 20090715232943) do + + create_table "comments", :force => true do |t| + t.text "content" + t.integer "post_id" + t.integer "user_id" + t.datetime "created_at" + t.datetime "updated_at" + end create_table "posts", :force => true do |t| t.string "title" t.text "content" t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| - t.string "login", :null => false - t.string "email", :null => false - t.string "crypted_password", :null => false - t.string "password_salt", :null => false - t.string "persistence_token", :null => false - t.string "single_access_token", :null => false - t.string "perishable_token", :null => false - t.integer "login_count", :default => 0, :null => false - t.integer "failed_login_count", :default => 0, :null => false + t.string "login", :null => false + t.string "email", :null => false + t.string "crypted_password", :null => false + t.string "password_salt", :null => false + t.string "persistence_token", :null => false + t.string "single_access_token", :null => false + t.string "perishable_token", :null => false + t.integer "login_count", :default => 0, :null => false + t.integer "failed_login_count", :default => 0, :null => false t.datetime "last_request_at" t.datetime "current_login_at" t.datetime "last_login_at" t.string "current_login_ip" t.string "last_login_ip" t.boolean "admin" t.datetime "created_at" t.datetime "updated_at" + t.string "name" + t.integer "facebook_uid", :limit => 8 end end diff --git a/public/javascripts/facebooker.js b/public/javascripts/facebooker.js new file mode 100644 index 0000000..9890ecb --- /dev/null +++ b/public/javascripts/facebooker.js @@ -0,0 +1,93 @@ + +function $(element) { + if (typeof element == "string") { + element=document.getElementById(element); + } + if (element) + extend_instance(element,Element); + return element; +} + +function extend_instance(instance,hash) { + for (var name in hash) { + instance[name] = hash[name]; + } +} + +var Element = { + "hide": function () { + this.setStyle("display","none") + }, + "show": function () { + this.setStyle("display","block") + }, + "visible": function () { + return (this.getStyle("display") != "none"); + }, + "toggle": function () { + if (this.visible) { + this.hide(); + } else { + this.show(); + } + } +}; + +function encodeURIComponent(str) { + if (typeof(str) == "string") { + return str.replace(/=/g,'%3D').replace(/&/g,'%26'); + } + //checkboxes and radio buttons return objects instead of a string + else if(typeof(str) == "object"){ + for (prop in str) + { + return str[prop].replace(/=/g,'%3D').replace(/&/g,'%26'); + } + } +}; + +var Form = {}; +Form.serialize = function(form_element) { + return $(form_element).serialize(); +}; + +Ajax.Updater = function (container,url,options) { + this.container = container; + this.url=url; + this.ajax = new Ajax(); + this.ajax.requireLogin = 1; + if (options["onSuccess"]) { + this.ajax.responseType = Ajax.JSON; + this.ajax.ondone = options["onSuccess"]; + } else { + this.ajax.responseType = Ajax.FBML; + this.ajax.ondone = function(data) { + $(container).setInnerFBML(data); + } + } + if (options["onFailure"]) { + this.ajax.onerror = options["onFailure"]; + } + + if (!options['parameters']) { + options['parameters'] = {} + } + + // simulate other verbs over post + if (options['method']) { + options['parameters']['_method'] = options['method']; + } + + this.ajax.post(url,options['parameters']); + if (options["onLoading"]) { + options["onLoading"].call() + } +}; +Ajax.Request = function(url,options) { + Ajax.Updater('unused',url,options); +}; + +PeriodicalExecuter = function (callback, frequency) { + setTimeout(callback, frequency *1000); + setTimeout(function() { new PeriodicalExecuter(callback,frequency); }, frequency*1000); +}; diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css new file mode 100644 index 0000000..e69de29 diff --git a/public/xd_receiver.html b/public/xd_receiver.html new file mode 100644 index 0000000..b6b63d6 --- /dev/null +++ b/public/xd_receiver.html @@ -0,0 +1,10 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" > +<head> + <title>Cross-Domain Receiver Page</title> +</head> +<body> + <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.debug.js" type="text/javascript"></script> +</body> +</html> \ No newline at end of file diff --git a/public/xd_receiver_ssl.html b/public/xd_receiver_ssl.html new file mode 100644 index 0000000..2fe0331 --- /dev/null +++ b/public/xd_receiver_ssl.html @@ -0,0 +1,10 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" > +<head> + <title>Cross-Domain Receiver Page</title> +</head> +<body> + <script src="https://www.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js" type="text/javascript"></script> +</body> +</html> diff --git a/vendor/plugins/authlogic_facebook_connect/README.rdoc b/vendor/plugins/authlogic_facebook_connect/README.rdoc new file mode 100644 index 0000000..95f71cc --- /dev/null +++ b/vendor/plugins/authlogic_facebook_connect/README.rdoc @@ -0,0 +1,68 @@ +== Install and use + +=== 1. Install the facebooker gem and make Rails use it + + $ sudo gem install facebooker + +Make sure that you have setup you config/facebooker.yml to match your facebook application, make you application depended on the facebooker gem + + config.gem "facebooker" + +and run the xd_receiver generator to create the cross domain scripting bridge to make it possible for your application to communicate with facebook + + $ script/generate xd_receiver + +For more information on the facebooker gem checkout it's readme http://github.com/mmangino/facebooker/tree/master + +=== 2. Install the Authlogic Facebook Connect plugin + + $ script/plugin install git://github.com/kalasjocke/authlogic_facebook_connect.git + +This plugin should soon be packed inside a gem. + +=== 3. Make some changes to your database + + class AddFacebookConnectFieldsToUser < ActiveRecord::Migration + def self.up + add_column :users, :name, :string + add_column :users, :facebook_uid, :integer, :limit => 8 + end + + def self.down + remove_column :users, :facebook_uid + remove_column :users, :name + end + end + +=== 4. Make your layout look something like this + +The important parts are the facebook html namespace, facebook javascript include and the facebook helper calls to init the facebooker gem. + + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + + <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"> + <head> + <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> + <title>Your awsome facebook connected app</title> + + <%= stylesheet_link_tag 'application' %> + <%= javascript_include_tag :defaults %> + + <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script> + </head> + <body> + + <p style="color: green"><%= flash[:notice] %></p> + + <%= fb_connect_javascript_tag %> + <%= init_fb_connect "XFBML" %> + + <%= yield %> + + </body> + </html> + +=== 5. Add the Facebook Connect button to your login form + + <%= authlogic_facebook_login_button %> \ No newline at end of file diff --git a/vendor/plugins/authlogic_facebook_connect/init.rb b/vendor/plugins/authlogic_facebook_connect/init.rb new file mode 100644 index 0000000..fc590d3 --- /dev/null +++ b/vendor/plugins/authlogic_facebook_connect/init.rb @@ -0,0 +1 @@ +require 'authlogic_facebook_connect' \ No newline at end of file diff --git a/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect.rb b/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect.rb new file mode 100644 index 0000000..9ded87b --- /dev/null +++ b/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect.rb @@ -0,0 +1,8 @@ +# require "authlogic_facebook_connect/version" +require "authlogic_facebook_connect/acts_as_authentic" +require "authlogic_facebook_connect/session" +require "authlogic_facebook_connect/helper" + +ActiveRecord::Base.send(:include, AuthlogicFacebookConnect::ActsAsAuthentic) +Authlogic::Session::Base.send(:include, AuthlogicFacebookConnect::Session) +ActionController::Base.helper AuthlogicFacebookConnect::Helper \ No newline at end of file diff --git a/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect/acts_as_authentic.rb b/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect/acts_as_authentic.rb new file mode 100644 index 0000000..fb9fa1b --- /dev/null +++ b/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect/acts_as_authentic.rb @@ -0,0 +1,20 @@ +module AuthlogicFacebookConnect + module ActsAsAuthentic + def self.included(klass) + klass.class_eval do + extend Config + add_acts_as_authentic_module(Methods, :prepend) + end + end + + module Config + end + + module Methods + def self.included(klass) + klass.class_eval do + end + end + end + end +end \ No newline at end of file diff --git a/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect/helper.rb b/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect/helper.rb new file mode 100644 index 0000000..1f85d17 --- /dev/null +++ b/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect/helper.rb @@ -0,0 +1,22 @@ +module AuthlogicFacebookConnect + module Helper + def authlogic_facebook_login_button(options = {}) + # TODO: Make this with correct helpers istead of this uggly hack. + + options[:controller] ||= "user_session" + + output = "<form id='connect_fo_facebook_form' method='post' action='/#{options[:controller]}'>\n" + output += "<input type='hidden' name='authenticity_token' value='#{form_authenticity_token}'/>\n" + output += "</form>\n" + output += "<script type='text/javascript' charset='utf-8'>\n" + output += " function connect_to_facebook() {\n" + output += " $('connect_fo_facebook_form').submit();\n" + output += " }\n" + output += "</script>\n" + + output += fb_login_button("connect_to_facebook()") + + output + end + end +end \ No newline at end of file diff --git a/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect/session.rb b/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect/session.rb new file mode 100644 index 0000000..b886798 --- /dev/null +++ b/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect/session.rb @@ -0,0 +1,77 @@ +module AuthlogicFacebookConnect + module Session + def self.included(klass) + klass.class_eval do + extend Config + include Methods + end + end + + module Config + # What user field should be used for the facebook UID? + # + # This is useful if you want to use a single field for multiple types of + # alternate user IDs, e.g. one that handles both OpenID identifiers and + # facebook ids. + # + # * <tt>Default:</tt> :facebook_uid + # * <tt>Accepts:</tt> Symbol + def facebook_uid_field(value = nil) + rw_config(:facebook_uid_field, value, :facebook_uid) + end + alias_method :facebook_uid_field=, :facebook_uid_field + end + + module Methods + def self.included(klass) + klass.class_eval do + validate :validate_by_facebook_connect, :if => :authenticating_with_facebook_connect? + end + + def credentials=(value) + # TODO: Is there a nicer way to tell Authlogic that we don't have any credentials than this? + values = [:facebook_connect] + super + end + end + + def validate_by_facebook_connect + facebook_session = controller.facebook_session + + self.attempted_record = + klass.find(:first, :conditions => { facebook_uid_field => facebook_session.user.uid }) + + unless self.attempted_record + begin + # Get the user from facebook and create a local user. + # + # We assign it after the call to new in case the attribute is protected. + new_user = klass.new + #new_user.send(:"#{facebook_uid_field}=", facebook_session.user.uid) + new_user.facebook_uid = facebook_session.user.uid + new_user.first_name = facebook_session.user.first_name + new_user.last_name = facebook_session.user.last_name + self.attempted_record = new_user + + errors.add_to_base( + I18n.t('error_messages.facebook_user_creation_failed', + :default => 'There was a problem creating a new user ' + + 'for your Facebook account')) unless attempted_record.valid? + rescue Facebooker::Session::SessionExpired + errors.add_to_base(I18n.t('error_messages.facebooker_session_expired', + :default => "Your Facebook Connect session has expired, please reconnect.")) + end + end + end + + def authenticating_with_facebook_connect? + attempted_record.nil? && errors.empty? && controller.facebook_session + end + + private + def facebook_uid_field + self.class.facebook_uid_field + end + end + end +end diff --git a/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect/version.rb b/vendor/plugins/authlogic_facebook_connect/lib/authlogic_facebook_connect/version.rb new file mode 100644 index 0000000..e69de29 diff --git a/vendor/plugins/facebooker b/vendor/plugins/facebooker new file mode 160000 index 0000000..9fb76ab --- /dev/null +++ b/vendor/plugins/facebooker @@ -0,0 +1 @@ +Subproject commit 9fb76ab37ed13946b1381c6a365455ebd22b0e96
chollier/proutlol
6f959b438896c92e8c83ecd4c16d9fda44019361
we now have added comments
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 461dac8..b42b292 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,49 +1,49 @@ # Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all # include all helpers, all the time protect_from_forgery # See ActionController::RequestForgeryProtection for details # Scrub sensitive parameters from your log filter_parameter_logging :password, :password_confirmation helper_method :current_user_session, :current_user private def current_user_session return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find end def current_user return @current_user if defined?(@current_user) @current_user = current_user_session && current_user_session.user end def require_user unless current_user - store_location flash[:notice] = "You must be logged in to access this page" redirect_to new_user_session_url return false end end def require_no_user if current_user - store_location flash[:notice] = "You must be logged out to access this page" - redirect_to account_url + redirect_to root_url return false end end def require_admin - if !current_user.admin + if current_user && current_user.admin + return true + else flash[:notice] = "You must be admin to access this page" redirect_to root_url return false end end end diff --git a/app/controllers/user_sessions_controller.rb b/app/controllers/user_sessions_controller.rb index 004c206..a73d8bf 100644 --- a/app/controllers/user_sessions_controller.rb +++ b/app/controllers/user_sessions_controller.rb @@ -1,24 +1,24 @@ class UserSessionsController < ApplicationController before_filter :require_no_user, :only => [:new, :create] before_filter :require_user, :only => :destroy def new @user_session = UserSession.new end def create @user_session = UserSession.new(params[:user_session]) if @user_session.save flash[:notice] = "Login successful!" - redirect_back_or_default account_url + redirect_to root_url else render :action => :new end end def destroy current_user_session.destroy flash[:notice] = "Logout successful!" redirect_to root_url end end \ No newline at end of file diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 5a1ff94..4bdbb35 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,38 +1,36 @@ class UsersController < ApplicationController - class UsersController < ApplicationController - before_filter :require_no_user, :only => [:new, :create] - before_filter :require_user, :only => [:show, :edit, :update] + before_filter :require_no_user, :only => [:new, :create] + before_filter :require_user, :only => [:show, :edit, :update] - def new - @user = User.new - end + def new + @user = User.new + end - def create - @user = User.new(params[:user]) - if @user.save - flash[:notice] = "Account registered!" - redirect_to root_url - else - render :action => :new - end + def create + @user = User.new(params[:user]) + if @user.save + flash[:notice] = "Account registered!" + redirect_to root_url + else + render :action => :new end + end - def show - @user = @current_user - end + def show + @user = current_user + end - def edit - @user = @current_user - end + def edit + @user = current_user + end - def update - @user = @current_user # makes our views "cleaner" and more consistent - if @user.update_attributes(params[:user]) - flash[:notice] = "Account updated!" - redirect_to account_url - else - render :action => :edit - end + def update + @user = current_user # makes our views "cleaner" and more consistent + if @user.update_attributes(params[:user]) + flash[:notice] = "Account updated!" + redirect_to current_user + else + render :action => :edit end end end diff --git a/app/models/comment.rb b/app/models/comment.rb index 45b2d38..b167abf 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -1,2 +1,4 @@ class Comment < ActiveRecord::Base + belongs_to :user + belongs_to :post end diff --git a/app/models/post.rb b/app/models/post.rb index 542c073..2d515fe 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -1,3 +1,4 @@ class Post < ActiveRecord::Base belongs_to :user + has_many :comments end diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 6cf6bc8..bb519bf 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,17 +1,32 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <title><%= controller.action_name %></title> - <%= stylesheet_link_tag 'scaffold' %> + <%= stylesheet_link_tag 'application' %> </head> <body> + + <div id="topbar"> + <p style="color: green"><%= flash[:notice] %></p> + </div> + + <div id="header"> + <h1>Ouagadoudou</h1> + </div> + + <div id="main"> + <div id="content"> + <%= yield %> + </div> + + <div id="sidebar"> + </div> + </div> -<p style="color: green"><%= flash[:notice] %></p> -<%= yield %> </body> </html> diff --git a/app/views/users/_form.html.erb b/app/views/users/_form.html.erb index 7556023..7ad2b59 100644 --- a/app/views/users/_form.html.erb +++ b/app/views/users/_form.html.erb @@ -1,8 +1,11 @@ <%= form.label :login %><br /> <%= form.text_field :login %><br /> <br /> +<%= form.label :email %><br /> +<%= form.text_field :email %><br /> +<br /> <%= form.label :password, form.object.new_record? ? nil : "Change password" %><br /> <%= form.password_field :password %><br /> <br /> <%= form.label :password_confirmation %><br /> <%= form.password_field :password_confirmation %><br /> \ No newline at end of file diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb index 40a466f..aee2f71 100644 --- a/app/views/users/edit.html.erb +++ b/app/views/users/edit.html.erb @@ -1,9 +1,9 @@ <h1>Edit My Account</h1> -<% form_for @user, :url => account_path do |f| %> +<% form_for @user do |f| %> <%= f.error_messages %> <%= render :partial => "form", :object => f %> <%= f.submit "Update" %> <% end %> -<br /><%= link_to "My Profile", account_path %> \ No newline at end of file +<br /><%= link_to "My Profile", current_user %> \ No newline at end of file diff --git a/app/views/users/new.html.erb b/app/views/users/new.html.erb index baf4146..fd293b1 100644 --- a/app/views/users/new.html.erb +++ b/app/views/users/new.html.erb @@ -1,7 +1,7 @@ <h1>Register</h1> -<% form_for @user, :url => account_path do |f| %> +<% form_for @user do |f| %> <%= f.error_messages %> <%= render :partial => "form", :object => f %> <%= f.submit "Register" %> <% end %> \ No newline at end of file diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb index d194ba3..5b0a95f 100644 --- a/app/views/users/show.html.erb +++ b/app/views/users/show.html.erb @@ -1,37 +1,37 @@ <p> <b>Login:</b> <%=h @user.login %> </p> <p> <b>Login count:</b> <%=h @user.login_count %> </p> <p> <b>Last request at:</b> <%=h @user.last_request_at %> </p> <p> <b>Last login at:</b> <%=h @user.last_login_at %> </p> <p> <b>Current login at:</b> <%=h @user.current_login_at %> </p> <p> <b>Last login ip:</b> <%=h @user.last_login_ip %> </p> <p> <b>Current login ip:</b> <%=h @user.current_login_ip %> </p> -<%= link_to 'Edit', edit_account_path %> \ No newline at end of file +<%= link_to 'Edit', edit_user_path(:current) %> \ No newline at end of file diff --git a/config/environment.rb b/config/environment.rb index 0f6d5a5..0595f77 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,43 +1,43 @@ # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" config.gem "authlogic" - + config.gem "facebooker" # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'Paris' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. #config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] config.i18n.default_locale = :fr end \ No newline at end of file diff --git a/config/locales/fr.yml b/config/locales/fr.yml index 2780b20..d3d8a24 100644 --- a/config/locales/fr.yml +++ b/config/locales/fr.yml @@ -1,161 +1,161 @@ # French translations for Ruby on Rails # by Christian Lescuyer ([email protected]) # contributor: Sebastien Grosjean - ZenCocoon.com fr: date: formats: default: "%d/%m/%Y" short: "%e %b" long: "%e %B %Y" long_ordinal: "%e %B %Y" only_day: "%e" day_names: [dimanche, lundi, mardi, mercredi, jeudi, vendredi, samedi] abbr_day_names: [dim, lun, mar, mer, jeu, ven, sam] month_names: [~, janvier, février, mars, avril, mai, juin, juillet, août, septembre, octobre, novembre, décembre] abbr_month_names: [~, jan., fév., mar., avr., mai, juin, juil., août, sept., oct., nov., déc.] order: [ :day, :month, :year ] time: formats: default: "%d %B %Y %H:%M" time: "%H:%M" short: "%d %b %H:%M" long: "%A %d %B %Y %H:%M:%S %Z" long_ordinal: "%A %d %B %Y %H:%M:%S %Z" only_second: "%S" am: 'am' pm: 'pm' datetime: distance_in_words: half_a_minute: "une demi-minute" less_than_x_seconds: zero: "moins d'une seconde" one: "moins de 1 seconde" other: "moins de {{count}} secondes" x_seconds: one: "1 seconde" other: "{{count}} secondes" less_than_x_minutes: zero: "moins d'une minute" one: "moins de 1 minute" other: "moins de {{count}} minutes" x_minutes: one: "1 minute" other: "{{count}} minutes" about_x_hours: one: "environ une heure" other: "environ {{count}} heures" x_days: one: "1 jour" other: "{{count}} jours" about_x_months: one: "environ un mois" other: "environ {{count}} mois" x_months: one: "1 mois" other: "{{count}} mois" about_x_years: one: "environ un an" other: "environ {{count}} ans" over_x_years: one: "plus d'un an" other: "plus de {{count}} ans" prompts: year: "Année" month: "Mois" day: "Jour" hour: "Heure" minute: "Minute" second: "Seconde" number: format: precision: 3 separator: ',' delimiter: ' ' currency: format: unit: '€' precision: 2 format: '%n %u' human: format: # These three are to override number.format and are optional # separator: delimiter: "" precision: 2 # Rails <= v2.2.2 # storage_units: [octet, kb, Mb, Gb, Tb] # Rails >= v2.3 storage_units: format: "%n %u" units: byte: one: "octet" other: "octets" kb: "ko" mb: "Mo" gb: "Go" tb: "To" support: array: sentence_connector: 'et' skip_last_comma: true words_connector: ", " two_words_connector: " et " last_word_connector: " et " activerecord: errors: template: header: one: "Impossible d'enregistrer {{model}}: 1 erreur" other: "Impossible d'enregistrer {{model}}: {{count}} erreurs." body: "Veuillez vérifier les champs suivants :" messages: inclusion: "n'est pas inclus(e) dans la liste" exclusion: "n'est pas disponible" invalid: "n'est pas valide" confirmation: "ne concorde pas avec la confirmation" accepted: "doit être accepté(e)" empty: "doit être rempli(e)" blank: "doit être rempli(e)" too_long: "est trop long (pas plus de {{count}} caractères)" too_short: "est trop court (au moins {{count}} caractères)" wrong_length: "ne fait pas la bonne longueur (doit comporter {{count}} caractères)" taken: "n'est pas disponible" not_a_number: "n'est pas un nombre" greater_than: "doit être supérieur à {{count}}" greater_than_or_equal_to: "doit être supérieur ou égal à {{count}}" equal_to: "doit être égal à {{count}}" less_than: "doit être inférieur à {{count}}" less_than_or_equal_to: "doit être inférieur ou égal à {{count}}" odd: "doit être impair" even: "doit être pair" authlogic: error_messages: login_blank: "ne peut être vide" login_not_found: "n'est pas valide" login_invalid: "devrait contenir uniquement des lettres, chiffres, espaces et.-_@" consecutive_failed_logins_limit_exceeded: "Le limite d'echecs consécutifs de connexion a été atteinte, ce compte est désactivé." email_invalid: "devrait ressembler à une adresse email." password_blank: "ne peut être vide" password_invalid: "n'est pas valide" not_active: "Votre compte n'est pas activé" not_confirmed: "Votre compte n'a pas été validé" not_approved: "Votre compte n'a pas été approuvé" no_authentication_details: "Vous n'avez pas donné d'informartions pour vous identifier" models: user_session: "UserSession" attributes: - user_session: (or whatever name you are using) + user_session: login: "identifiant" email: "email" password: "mot de passe" remember_me: "se souvenir" \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index cc076bb..64e4af6 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,48 +1,54 @@ ActionController::Routing::Routes.draw do |map| + map.resources :comments + map.root :controller => "posts", :action => "index" map.resource :user_session map.resources :users map.resources :posts + + map.connect '/logout', :controller => 'user_sessions', :action => 'destroy' + map.connect '/logout', :controller => 'user_sessions', :action => 'new' + # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/db/migrate/20090715183049_create_posts.rb b/db/migrate/20090715183049_create_posts.rb index b99fce0..d0fda10 100644 --- a/db/migrate/20090715183049_create_posts.rb +++ b/db/migrate/20090715183049_create_posts.rb @@ -1,14 +1,14 @@ class CreatePosts < ActiveRecord::Migration def self.up create_table :posts do |t| t.string :title t.text :content - + t.integer :user_id t.timestamps end end def self.down drop_table :posts end end diff --git a/db/migrate/20090715220414_create_comments.rb b/db/migrate/20090715220414_create_comments.rb index 38dfdaa..8c322ec 100644 --- a/db/migrate/20090715220414_create_comments.rb +++ b/db/migrate/20090715220414_create_comments.rb @@ -1,16 +1,14 @@ class CreateComments < ActiveRecord::Migration def self.up create_table :comments do |t| - t.string :author - t.string :email - t.string :author t.text :content - + t.integer :post_id + t.integer :user_id t.timestamps end end def self.down drop_table :comments end end diff --git a/log/development.log b/log/development.log index 8b13789..3a01c5b 100644 --- a/log/development.log +++ b/log/development.log @@ -1 +1,787 @@ + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:27:46) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (1.3ms) SELECT * FROM `posts`  + +ArgumentError (syntax error on line 157, col 20: ` login: "identifiant"'): + /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/yaml.rb:133:in `load' + /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/yaml.rb:133:in `load' + app/controllers/posts_controller.rb:9:in `index' + +Rendered rescues/_trace (69.9ms) +Rendered rescues/_request_and_response (1.5ms) +Rendering rescues/layout (internal_server_error) + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:28:20) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 16ms (View: 11, DB: 1) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:28:24) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (2.7ms) SHOW FIELDS FROM `users` + +NoMethodError (You have a nil object when you didn't expect it! +The error occurred while evaluating nil.admin): + app/controllers/application_controller.rb:42:in `require_admin' + +Rendered rescues/_trace (98.0ms) +Rendered rescues/_request_and_response (0.3ms) +Rendering rescues/layout (internal_server_error) + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:29:42) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 6ms (View: 1, DB: 1) | 200 OK [http://0.0.0.0/] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:29:44) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (4.1ms) SHOW FIELDS FROM `users` + Post Columns (1.7ms) SHOW FIELDS FROM `posts` +Rendering template within layouts/application +Rendering posts/new +Completed in 28ms (View: 6, DB: 6) | 200 OK [http://0.0.0.0/posts/new] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:30:03) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 6ms (View: 1, DB: 1) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:30:05) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + +NoMethodError (undefined method `current_user?' for #<PostsController:0x25cfde4>): + app/controllers/application_controller.rb:42:in `require_admin' + +Rendered rescues/_trace (30.1ms) +Rendered rescues/_request_and_response (0.3ms) +Rendering rescues/layout (internal_server_error) + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:30:23) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + +NoMethodError (undefined method `loggued_in?' for #<PostsController:0x24d35f8>): + app/controllers/application_controller.rb:42:in `require_admin' + +Rendered rescues/_trace (96.3ms) +Rendered rescues/_request_and_response (0.3ms) +Rendering rescues/layout (internal_server_error) + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:32:05) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + +NoMethodError (undefined method `logged_in?' for #<PostsController:0x271c800>): + app/controllers/application_controller.rb:42:in `require_admin' + +Rendered rescues/_trace (39.9ms) +Rendered rescues/_request_and_response (0.3ms) +Rendering rescues/layout (internal_server_error) + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.2ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:33:12) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (2.6ms) SHOW FIELDS FROM `users` +Redirected to http://0.0.0.0:3000/ +Filter chain halted as [:require_admin] rendered_or_redirected. +Completed in 15ms (DB: 3) | 302 Found [http://0.0.0.0/posts/new] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:33:12) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 6ms (View: 1, DB: 0) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:34:46) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (3.3ms) SHOW FIELDS FROM `users` + +NoMethodError (You have a nil object when you didn't expect it! +The error occurred while evaluating nil.admin): + app/controllers/application_controller.rb:42:in `require_admin' + +Rendered rescues/_trace (30.0ms) +Rendered rescues/_request_and_response (0.3ms) +Rendering rescues/layout (internal_server_error) + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:35:12) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (2.7ms) SHOW FIELDS FROM `users` +Redirected to http://0.0.0.0:3000/ +Filter chain halted as [:require_admin] rendered_or_redirected. +Completed in 82ms (DB: 3) | 302 Found [http://0.0.0.0/posts/new] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:35:12) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 6ms (View: 1, DB: 0) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:35:13) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (3.2ms) SHOW FIELDS FROM `users` +Redirected to http://0.0.0.0:3000/ +Filter chain halted as [:require_admin] rendered_or_redirected. +Completed in 22ms (DB: 3) | 302 Found [http://0.0.0.0/posts/new] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:35:13) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 9ms (View: 2, DB: 1) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#new (for 127.0.0.1 at 2009-07-15 22:36:16) [GET] + Parameters: {"action"=>"new", "controller"=>"users"} +Rendering template within layouts/application +Rendering users/new + +ActionView::TemplateError (undefined local variable or method `account_path' for #<ActionView::Base:0x260aa98>) on line #3 of app/views/users/new.html.erb: +1: <h1>Register</h1> +2: +3: <% form_for @user, :url => account_path do |f| %> +4: <%= f.error_messages %> +5: <%= render :partial => "form", :object => f %> +6: <%= f.submit "Register" %> + + app/views/users/new.html.erb:3 + +Rendered rescues/_trace (36.4ms) +Rendered rescues/_request_and_response (0.3ms) +Rendering rescues/layout (internal_server_error) + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#new (for 127.0.0.1 at 2009-07-15 22:38:30) [GET] + Parameters: {"action"=>"new", "controller"=>"users"} +Rendering template within layouts/application +Rendering users/new + +ActionView::TemplateError (Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id) on line #3 of app/views/users/new.html.erb: +1: <h1>Register</h1> +2: +3: <% form_for @user, :url => account_path do |f| %> +4: <%= f.error_messages %> +5: <%= render :partial => "form", :object => f %> +6: <%= f.submit "Register" %> + + app/views/users/new.html.erb:3 + +Rendered rescues/_trace (40.0ms) +Rendered rescues/_request_and_response (1.5ms) +Rendering rescues/layout (internal_server_error) + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#index (for 127.0.0.1 at 2009-07-15 22:38:41) [GET] + Parameters: {"action"=>"index", "controller"=>"users"} + +ActionController::UnknownAction (No action responded to index. Actions: ): + + +Rendering rescues/layout (not_found) + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#new (for 127.0.0.1 at 2009-07-15 22:38:45) [GET] + Parameters: {"action"=>"new", "controller"=>"users"} +Rendering template within layouts/application +Rendering users/new + +ActionView::TemplateError (Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id) on line #3 of app/views/users/new.html.erb: +1: <h1>Register</h1> +2: +3: <% form_for @user, :url => account_path do |f| %> +4: <%= f.error_messages %> +5: <%= render :partial => "form", :object => f %> +6: <%= f.submit "Register" %> + + app/views/users/new.html.erb:3 + +Rendered rescues/_trace (107.7ms) +Rendered rescues/_request_and_response (0.3ms) +Rendering rescues/layout (internal_server_error) + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#new (for 127.0.0.1 at 2009-07-15 22:42:20) [GET] + Parameters: {"action"=>"new", "controller"=>"users"} +Rendering template within layouts/application +Rendering users/new + +ActionView::TemplateError (undefined method `new_record?' for nil:NilClass) on line #4 of app/views/users/_form.html.erb: +1: <%= form.label :login %><br /> +2: <%= form.text_field :login %><br /> +3: <br /> +4: <%= form.label :password, form.object.new_record? ? nil : "Change password" %><br /> +5: <%= form.password_field :password %><br /> +6: <br /> +7: <%= form.label :password_confirmation %><br /> + + app/views/users/_form.html.erb:4 + app/views/users/new.html.erb:5 + app/views/users/new.html.erb:3 + +Rendered rescues/_trace (49.2ms) +Rendered rescues/_request_and_response (1.5ms) +Rendering rescues/layout (internal_server_error) + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#new (for 127.0.0.1 at 2009-07-15 22:46:10) [GET] + Parameters: {"action"=>"new", "controller"=>"users"} +Rendering template within layouts/application +Rendering users/new + +ActionView::TemplateError (Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id) on line #3 of app/views/users/new.html.erb: +1: <h1>Register</h1> +2: +3: <% form_for @user, :url => new_user_path do |f| %> +4: <%= f.error_messages %> +5: <%= render :partial => "form", :object => f %> +6: <%= f.submit "Register" %> + + app/views/users/new.html.erb:3 + +Rendered rescues/_trace (41.7ms) +Rendered rescues/_request_and_response (1.4ms) +Rendering rescues/layout (internal_server_error) + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#new (for 127.0.0.1 at 2009-07-15 22:47:01) [GET] + Parameters: {"action"=>"new", "controller"=>"users"} +Rendering template within layouts/application +Rendering users/new + +ActionView::TemplateError (You have a nil object when you didn't expect it! +You might have expected an instance of ActiveRecord::Base. +The error occurred while evaluating nil.new_record?) on line #4 of app/views/users/_form.html.erb: +1: <%= form.label :login %><br /> +2: <%= form.text_field :login %><br /> +3: <br /> +4: <%= form.label :password, form.object.new_record? ? nil : "Change password" %><br /> +5: <%= form.password_field :password %><br /> +6: <br /> +7: <%= form.label :password_confirmation %><br /> + + app/views/users/_form.html.erb:4 + app/views/users/new.html.erb:5 + app/views/users/new.html.erb:3 + +Rendered rescues/_trace (117.1ms) +Rendered rescues/_request_and_response (0.3ms) +Rendering rescues/layout (internal_server_error) + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#new (for 127.0.0.1 at 2009-07-15 22:52:22) [GET] + Parameters: {"action"=>"new", "controller"=>"users"} +Rendering template within layouts/application +Rendering users/new + +ActionView::TemplateError (Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id) on line #3 of app/views/users/new.html.erb: +1: <h1>Register</h1> +2: +3: <% form_for @user do |f| %> +4: <%= f.error_messages %> +5: <%= render :partial => "form", :object => f %> +6: <%= f.submit "Register" %> + + app/views/users/new.html.erb:3 + +Rendered rescues/_trace (40.1ms) +Rendered rescues/_request_and_response (1.4ms) +Rendering rescues/layout (internal_server_error) + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.2ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#new (for 127.0.0.1 at 2009-07-15 22:55:25) [GET] + Parameters: {"action"=>"new", "controller"=>"users"} + User Columns (2.7ms) SHOW FIELDS FROM `users` +Rendering template within layouts/application +Rendering users/new +Rendered users/_form (1.5ms) +Completed in 36ms (View: 11, DB: 3) | 200 OK [http://0.0.0.0/users/new] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#create (for 127.0.0.1 at 2009-07-15 22:55:59) [POST] + Parameters: {"user"=>{"password_confirmation"=>"[FILTERED]", "password"=>"[FILTERED]", "login"=>"chollier"}, "commit"=>"Register", "action"=>"create", "authenticity_token"=>"FOFd1n2JOjvsb2CV61Ta6eohOx6FZlFfujoCbY3opz0=", "controller"=>"users"} + User Columns (3.5ms) SHOW FIELDS FROM `users` + SQL (0.2ms) BEGIN + User Exists (0.3ms) SELECT `users`.id FROM `users` WHERE (LOWER(`users`.`login`) = BINARY 'chollier') LIMIT 1 + User Exists (0.2ms) SELECT `users`.id FROM `users` WHERE (`users`.`persistence_token` = BINARY '1bc2d4fc0a69fedefc6810a9a301c147afb1192175c1db2109fee35ee29338b200ca3ca67a32c8760b815a4c6e35c9a3cd09e162ce3afd4d989219f9fc479577') LIMIT 1 + User Exists (0.1ms) SELECT `users`.id FROM `users` WHERE (`users`.`single_access_token` = BINARY 'mbzUO4Q22pmorV-8GHAL') LIMIT 1 + SQL (0.1ms) ROLLBACK +Rendering template within layouts/application +Rendering users/new +Rendered users/_form (0.6ms) +Completed in 312ms (View: 3, DB: 5) | 200 OK [http://0.0.0.0/users] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#new (for 127.0.0.1 at 2009-07-15 22:57:39) [GET] + Parameters: {"action"=>"new", "controller"=>"users"} + User Columns (3.0ms) SHOW FIELDS FROM `users` +Rendering template within layouts/application +Rendering users/new +Rendered users/_form (1.5ms) +Completed in 26ms (View: 8, DB: 3) | 200 OK [http://0.0.0.0/users/new] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#create (for 127.0.0.1 at 2009-07-15 22:57:52) [POST] + Parameters: {"user"=>{"password_confirmation"=>"[FILTERED]", "password"=>"[FILTERED]", "login"=>"chollier", "email"=>"[email protected]"}, "commit"=>"Register", "action"=>"create", "authenticity_token"=>"FOFd1n2JOjvsb2CV61Ta6eohOx6FZlFfujoCbY3opz0=", "controller"=>"users"} + User Columns (3.1ms) SHOW FIELDS FROM `users` + SQL (0.1ms) BEGIN + User Exists (0.2ms) SELECT `users`.id FROM `users` WHERE (LOWER(`users`.`email`) = BINARY '[email protected]') LIMIT 1 + User Exists (0.1ms) SELECT `users`.id FROM `users` WHERE (LOWER(`users`.`login`) = BINARY 'chollier') LIMIT 1 + User Exists (0.1ms) SELECT `users`.id FROM `users` WHERE (`users`.`persistence_token` = BINARY 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece') LIMIT 1 + User Exists (0.1ms) SELECT `users`.id FROM `users` WHERE (`users`.`single_access_token` = BINARY 'K_qNzu9uqEcO6AzVoMa-') LIMIT 1 + User Create (0.4ms) INSERT INTO `users` (`last_login_at`, `last_request_at`, `updated_at`, `crypted_password`, `single_access_token`, `perishable_token`, `current_login_ip`, `password_salt`, `current_login_at`, `admin`, `failed_login_count`, `persistence_token`, `login_count`, `login`, `email`, `last_login_ip`, `created_at`) VALUES(NULL, '2009-07-15 20:57:52', '2009-07-15 20:57:52', 'ce3b8ab077f5e22701044d9c9cf8c615aeded4846f28e79c3da71e767961964f3855d5c3e040ab59a3c6912889631fc753a8ba5786919c694f27c8e3ecb812a8', 'K_qNzu9uqEcO6AzVoMa-', '1lWgEVnBZFcz2HfuXTLT', '127.0.0.1', 'HFrtQGOpOqnzvRpXrbPk', '2009-07-15 20:57:52', NULL, 0, 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece', 1, 'chollier', '[email protected]', NULL, '2009-07-15 20:57:52') + SQL (0.7ms) COMMIT +Redirected to http://0.0.0.0:3000/ +Completed in 275ms (DB: 5) | 302 Found [http://0.0.0.0/users] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:57:52) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 16ms (View: 9, DB: 1) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:57:54) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (2.7ms) SHOW FIELDS FROM `users` + User Load (0.3ms) SELECT * FROM `users` WHERE (`users`.`persistence_token` = 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece') LIMIT 1 + SQL (0.1ms) BEGIN + User Update (0.2ms) UPDATE `users` SET `perishable_token` = '6aflDdp8zUnKELPFTXCU', `updated_at` = '2009-07-15 20:57:54', `last_request_at` = '2009-07-15 20:57:54' WHERE `id` = 1 + SQL (0.7ms) COMMIT +Redirected to http://0.0.0.0:3000/ +Filter chain halted as [:require_admin] rendered_or_redirected. +Completed in 22ms (DB: 4) | 302 Found [http://0.0.0.0/posts/new] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:57:54) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 6ms (View: 1, DB: 0) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:58:29) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (3.3ms) SHOW FIELDS FROM `users` + User Load (0.4ms) SELECT * FROM `users` WHERE (`users`.`persistence_token` = 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece') LIMIT 1 + SQL (0.1ms) BEGIN + User Update (0.3ms) UPDATE `users` SET `perishable_token` = 'feyAjRD_BMk3bXob9XGF', `updated_at` = '2009-07-15 20:58:29', `last_request_at` = '2009-07-15 20:58:29' WHERE `id` = 1 + SQL (0.9ms) COMMIT +Redirected to http://0.0.0.0:3000/ +Filter chain halted as [:require_admin] rendered_or_redirected. +Completed in 33ms (DB: 5) | 302 Found [http://0.0.0.0/posts/new] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:58:29) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 9ms (View: 2, DB: 1) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:58:30) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (3.2ms) SHOW FIELDS FROM `users` + User Load (0.4ms) SELECT * FROM `users` WHERE (`users`.`persistence_token` = 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece') LIMIT 1 + SQL (0.1ms) BEGIN + User Update (0.6ms) UPDATE `users` SET `perishable_token` = 'VnqoFkVASiYbwE2_OdOH', `updated_at` = '2009-07-15 20:58:30', `last_request_at` = '2009-07-15 20:58:30' WHERE `id` = 1 + SQL (0.7ms) COMMIT +Redirected to http://0.0.0.0:3000/ +Filter chain halted as [:require_admin] rendered_or_redirected. +Completed in 32ms (DB: 5) | 302 Found [http://0.0.0.0/posts/new] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:58:30) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 6ms (View: 1, DB: 0) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:58:36) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 8ms (View: 1, DB: 1) | 200 OK [http://0.0.0.0/] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:58:38) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (2.7ms) SHOW FIELDS FROM `users` + User Load (0.4ms) SELECT * FROM `users` WHERE (`users`.`persistence_token` = 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece') LIMIT 1 + SQL (0.1ms) BEGIN + User Update (0.3ms) UPDATE `users` SET `perishable_token` = 'NcZ8LLUi0Ftf8Jm_M32K', `updated_at` = '2009-07-15 20:58:38', `last_request_at` = '2009-07-15 20:58:38' WHERE `id` = 1 + SQL (0.8ms) COMMIT +Redirected to http://0.0.0.0:3000/ +Filter chain halted as [:require_admin] rendered_or_redirected. +Completed in 96ms (DB: 4) | 302 Found [http://0.0.0.0/posts/new] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:58:38) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 6ms (View: 1, DB: 0) | 200 OK [http://0.0.0.0/] + SQL (0.3ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:59:10) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 6ms (View: 1, DB: 1) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:59:11) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (2.9ms) SHOW FIELDS FROM `users` + User Load (0.3ms) SELECT * FROM `users` WHERE (`users`.`persistence_token` = 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece') LIMIT 1 + SQL (0.1ms) BEGIN + User Update (0.2ms) UPDATE `users` SET `perishable_token` = 'BB7aHErSEYP_PpnDjGy7', `updated_at` = '2009-07-15 20:59:11', `last_request_at` = '2009-07-15 20:59:11' WHERE `id` = 1 + SQL (31.1ms) COMMIT +Redirected to http://0.0.0.0:3000/ +Filter chain halted as [:require_admin] rendered_or_redirected. +Completed in 53ms (DB: 35) | 302 Found [http://0.0.0.0/posts/new] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:59:11) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 6ms (View: 1, DB: 0) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:59:23) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (2.7ms) SHOW FIELDS FROM `users` + User Load (0.3ms) SELECT * FROM `users` WHERE (`users`.`persistence_token` = 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece') LIMIT 1 + SQL (0.1ms) BEGIN + User Update (0.3ms) UPDATE `users` SET `perishable_token` = 'IjLcOFV4hJM9-Fe5IgGY', `updated_at` = '2009-07-15 20:59:23', `last_request_at` = '2009-07-15 20:59:23' WHERE `id` = 1 + SQL (0.8ms) COMMIT +Redirected to http://0.0.0.0:3000/ +Filter chain halted as [:require_admin] rendered_or_redirected. +Completed in 91ms (DB: 4) | 302 Found [http://0.0.0.0/posts/new] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:59:23) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 16ms (View: 10, DB: 0) | 200 OK [http://0.0.0.0/] + SQL (0.3ms) SET NAMES 'utf8' + SQL (0.2ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#index (for 127.0.0.1 at 2009-07-15 22:59:27) [GET] + Parameters: {"action"=>"index", "controller"=>"users"} + +ActionController::UnknownAction (No action responded to index. Actions: create, edit, new, show, and update): + + +Rendering rescues/layout (not_found) + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.2ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UsersController#show (for 127.0.0.1 at 2009-07-15 22:59:32) [GET] + Parameters: {"action"=>"show", "id"=>"show", "controller"=>"users"} + User Columns (2.7ms) SHOW FIELDS FROM `users` + User Load (0.3ms) SELECT * FROM `users` WHERE (`users`.`persistence_token` = 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece') LIMIT 1 + SQL (0.1ms) BEGIN + User Update (0.3ms) UPDATE `users` SET `perishable_token` = 'wPGKuGQs-0LFO9P7xgxr', `updated_at` = '2009-07-15 20:59:32', `last_request_at` = '2009-07-15 20:59:32' WHERE `id` = 1 + SQL (0.7ms) COMMIT +Rendering template within layouts/application +Rendering users/show +Completed in 30ms (View: 5, DB: 4) | 200 OK [http://0.0.0.0/users/show] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 22:59:40) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (2.2ms) SHOW FIELDS FROM `users` + User Load (0.3ms) SELECT * FROM `users` WHERE (`users`.`persistence_token` = 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece') LIMIT 1 + SQL (0.1ms) BEGIN + User Update (0.3ms) UPDATE `users` SET `perishable_token` = 'iM6eMB0KxC8oS0f8yRxc', `updated_at` = '2009-07-15 20:59:40', `last_request_at` = '2009-07-15 20:59:40' WHERE `id` = 1 + SQL (0.8ms) COMMIT +Redirected to http://0.0.0.0:3000/ +Filter chain halted as [:require_admin] rendered_or_redirected. +Completed in 23ms (DB: 4) | 302 Found [http://0.0.0.0/posts/new] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 22:59:40) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 6ms (View: 1, DB: 0) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 23:00:04) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (2.7ms) SHOW FIELDS FROM `users` + User Load (0.4ms) SELECT * FROM `users` WHERE (`users`.`persistence_token` = 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece') LIMIT 1 + SQL (0.1ms) BEGIN + User Update (0.4ms) UPDATE `users` SET `perishable_token` = 'd3xMdw0t7wOiNbGKXuV9', `updated_at` = '2009-07-15 21:00:04', `last_request_at` = '2009-07-15 21:00:04' WHERE `id` = 1 + SQL (0.9ms) COMMIT +Redirected to http://0.0.0.0:3000/ +Filter chain halted as [:require_admin] rendered_or_redirected. +Completed in 23ms (DB: 5) | 302 Found [http://0.0.0.0/posts/new] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 23:00:04) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.2ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 6ms (View: 1, DB: 0) | 200 OK [http://0.0.0.0/] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 23:00:05) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (2.6ms) SHOW FIELDS FROM `users` + User Load (0.3ms) SELECT * FROM `users` WHERE (`users`.`persistence_token` = 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece') LIMIT 1 + SQL (0.1ms) BEGIN + User Update (0.3ms) UPDATE `users` SET `perishable_token` = 'o4Wde4C0UWeHqBxdPa5D', `updated_at` = '2009-07-15 21:00:05', `last_request_at` = '2009-07-15 21:00:05' WHERE `id` = 1 + SQL (0.8ms) COMMIT +Redirected to http://0.0.0.0:3000/ +Filter chain halted as [:require_admin] rendered_or_redirected. +Completed in 22ms (DB: 4) | 302 Found [http://0.0.0.0/posts/new] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 23:00:05) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.2ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 6ms (View: 1, DB: 0) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#new (for 127.0.0.1 at 2009-07-15 23:00:34) [GET] + Parameters: {"action"=>"new", "controller"=>"posts"} + User Columns (3.4ms) SHOW FIELDS FROM `users` + User Load (0.3ms) SELECT * FROM `users` WHERE (`users`.`persistence_token` = 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece') LIMIT 1 + SQL (0.1ms) BEGIN + User Update (0.2ms) UPDATE `users` SET `perishable_token` = 'hPNYQaBAAz94f_Yzwm_R', `updated_at` = '2009-07-15 21:00:34', `last_request_at` = '2009-07-15 21:00:34' WHERE `id` = 1 + SQL (0.6ms) COMMIT + Post Columns (2.2ms) SHOW FIELDS FROM `posts` +Rendering template within layouts/application +Rendering posts/new +Completed in 36ms (View: 5, DB: 7) | 200 OK [http://0.0.0.0/posts/new] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 23:00:35) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 7ms (View: 1, DB: 1) | 200 OK [http://0.0.0.0/posts] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UserSessionsController#destroy (for 127.0.0.1 at 2009-07-15 23:02:28) [GET] + Parameters: {"action"=>"destroy", "controller"=>"user_sessions"} + User Columns (2.9ms) SHOW FIELDS FROM `users` + User Load (0.4ms) SELECT * FROM `users` WHERE (`users`.`persistence_token` = 'd0e62c6ed91f96f3d188fa2334bf86f7b04e27e2e4ded8ab97170b77b0dd9c09aac94747c202e33b1cf492ce1dbc6e87eeef9375d0d3ddfb953b215f89557ece') LIMIT 1 + SQL (0.1ms) BEGIN + User Update (0.3ms) UPDATE `users` SET `perishable_token` = 'YmOsr--pcZsog2PdFtIk', `updated_at` = '2009-07-15 21:02:28', `last_request_at` = '2009-07-15 21:02:28' WHERE `id` = 1 + SQL (0.7ms) COMMIT +Redirected to http://0.0.0.0:3000/ +Completed in 94ms (DB: 5) | 302 Found [http://0.0.0.0/logout] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 23:02:28) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 17ms (View: 10, DB: 1) | 200 OK [http://0.0.0.0/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.2ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UserSessionsController#destroy (for 127.0.0.1 at 2009-07-15 23:02:34) [GET] + Parameters: {"action"=>"destroy", "controller"=>"user_sessions"} + User Columns (3.3ms) SHOW FIELDS FROM `users` + +NameError (undefined local variable or method `store_location' for #<UserSessionsController:0x25094c8>): + app/controllers/application_controller.rb:25:in `require_user' + +Rendered rescues/_trace (34.8ms) +Rendered rescues/_request_and_response (1.5ms) +Rendering rescues/layout (internal_server_error) + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UserSessionsController#destroy (for 127.0.0.1 at 2009-07-15 23:03:21) [GET] + Parameters: {"action"=>"destroy", "controller"=>"user_sessions"} + User Columns (2.7ms) SHOW FIELDS FROM `users` +Redirected to http://0.0.0.0:3000/user_session/new +Filter chain halted as [:require_user] rendered_or_redirected. +Completed in 78ms (DB: 3) | 302 Found [http://0.0.0.0/logout] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing UserSessionsController#new (for 127.0.0.1 at 2009-07-15 23:03:21) [GET] + Parameters: {"action"=>"new", "controller"=>"user_sessions"} + User Columns (2.3ms) SHOW FIELDS FROM `users` +Rendering template within layouts/application +Rendering user_sessions/new +Completed in 23ms (View: 7, DB: 2) | 200 OK [http://0.0.0.0/user_session/new] + SQL (0.1ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 23:30:34) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 9ms (View: 5, DB: 0) | 200 OK [http://127.0.0.1/] + SQL (0.2ms) SET NAMES 'utf8' + SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 + + +Processing PostsController#index (for 127.0.0.1 at 2009-07-15 23:46:58) [GET] + Parameters: {"action"=>"index", "controller"=>"posts"} + Post Load (0.3ms) SELECT * FROM `posts`  +Rendering template within layouts/application +Rendering posts/index +Completed in 13ms (View: 6, DB: 1) | 200 OK [http://127.0.0.1/]
chollier/proutlol
099aafb13641502d0fbd73a165ff29d20214693f
user setup
diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb new file mode 100644 index 0000000..92acb07 --- /dev/null +++ b/app/controllers/comments_controller.rb @@ -0,0 +1,85 @@ +class CommentsController < ApplicationController + # GET /comments + # GET /comments.xml + def index + @comments = Comment.all + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @comments } + end + end + + # GET /comments/1 + # GET /comments/1.xml + def show + @comment = Comment.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @comment } + end + end + + # GET /comments/new + # GET /comments/new.xml + def new + @comment = Comment.new + + respond_to do |format| + format.html # new.html.erb + format.xml { render :xml => @comment } + end + end + + # GET /comments/1/edit + def edit + @comment = Comment.find(params[:id]) + end + + # POST /comments + # POST /comments.xml + def create + @comment = Comment.new(params[:comment]) + + respond_to do |format| + if @comment.save + flash[:notice] = 'Comment was successfully created.' + format.html { redirect_to(@comment) } + format.xml { render :xml => @comment, :status => :created, :location => @comment } + else + format.html { render :action => "new" } + format.xml { render :xml => @comment.errors, :status => :unprocessable_entity } + end + end + end + + # PUT /comments/1 + # PUT /comments/1.xml + def update + @comment = Comment.find(params[:id]) + + respond_to do |format| + if @comment.update_attributes(params[:comment]) + flash[:notice] = 'Comment was successfully updated.' + format.html { redirect_to(@comment) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @comment.errors, :status => :unprocessable_entity } + end + end + end + + # DELETE /comments/1 + # DELETE /comments/1.xml + def destroy + @comment = Comment.find(params[:id]) + @comment.destroy + + respond_to do |format| + format.html { redirect_to(comments_url) } + format.xml { head :ok } + end + end +end diff --git a/app/helpers/comments_helper.rb b/app/helpers/comments_helper.rb new file mode 100644 index 0000000..0ec9ca5 --- /dev/null +++ b/app/helpers/comments_helper.rb @@ -0,0 +1,2 @@ +module CommentsHelper +end diff --git a/app/models/comment.rb b/app/models/comment.rb new file mode 100644 index 0000000..45b2d38 --- /dev/null +++ b/app/models/comment.rb @@ -0,0 +1,2 @@ +class Comment < ActiveRecord::Base +end diff --git a/app/views/comments/edit.html.erb b/app/views/comments/edit.html.erb new file mode 100644 index 0000000..97de9b3 --- /dev/null +++ b/app/views/comments/edit.html.erb @@ -0,0 +1,28 @@ +<h1>Editing comment</h1> + +<% form_for(@comment) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :author %><br /> + <%= f.text_field :author %> + </p> + <p> + <%= f.label :email %><br /> + <%= f.text_field :email %> + </p> + <p> + <%= f.label :author %><br /> + <%= f.text_field :author %> + </p> + <p> + <%= f.label :content %><br /> + <%= f.text_area :content %> + </p> + <p> + <%= f.submit 'Update' %> + </p> +<% end %> + +<%= link_to 'Show', @comment %> | +<%= link_to 'Back', comments_path %> \ No newline at end of file diff --git a/app/views/comments/index.html.erb b/app/views/comments/index.html.erb new file mode 100644 index 0000000..7def81e --- /dev/null +++ b/app/views/comments/index.html.erb @@ -0,0 +1,26 @@ +<h1>Listing comments</h1> + +<table> + <tr> + <th>Author</th> + <th>Email</th> + <th>Author</th> + <th>Content</th> + </tr> + +<% @comments.each do |comment| %> + <tr> + <td><%=h comment.author %></td> + <td><%=h comment.email %></td> + <td><%=h comment.author %></td> + <td><%=h comment.content %></td> + <td><%= link_to 'Show', comment %></td> + <td><%= link_to 'Edit', edit_comment_path(comment) %></td> + <td><%= link_to 'Destroy', comment, :confirm => 'Are you sure?', :method => :delete %></td> + </tr> +<% end %> +</table> + +<br /> + +<%= link_to 'New comment', new_comment_path %> \ No newline at end of file diff --git a/app/views/comments/new.html.erb b/app/views/comments/new.html.erb new file mode 100644 index 0000000..c23a4b4 --- /dev/null +++ b/app/views/comments/new.html.erb @@ -0,0 +1,27 @@ +<h1>New comment</h1> + +<% form_for(@comment) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :author %><br /> + <%= f.text_field :author %> + </p> + <p> + <%= f.label :email %><br /> + <%= f.text_field :email %> + </p> + <p> + <%= f.label :author %><br /> + <%= f.text_field :author %> + </p> + <p> + <%= f.label :content %><br /> + <%= f.text_area :content %> + </p> + <p> + <%= f.submit 'Create' %> + </p> +<% end %> + +<%= link_to 'Back', comments_path %> \ No newline at end of file diff --git a/app/views/comments/show.html.erb b/app/views/comments/show.html.erb new file mode 100644 index 0000000..a301169 --- /dev/null +++ b/app/views/comments/show.html.erb @@ -0,0 +1,23 @@ +<p> + <b>Author:</b> + <%=h @comment.author %> +</p> + +<p> + <b>Email:</b> + <%=h @comment.email %> +</p> + +<p> + <b>Author:</b> + <%=h @comment.author %> +</p> + +<p> + <b>Content:</b> + <%=h @comment.content %> +</p> + + +<%= link_to 'Edit', edit_comment_path(@comment) %> | +<%= link_to 'Back', comments_path %> \ No newline at end of file diff --git a/app/views/layouts/comments.html.erb b/app/views/layouts/comments.html.erb new file mode 100644 index 0000000..41d104d --- /dev/null +++ b/app/views/layouts/comments.html.erb @@ -0,0 +1,17 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> + <title>Comments: <%= controller.action_name %></title> + <%= stylesheet_link_tag 'scaffold' %> +</head> +<body> + +<p style="color: green"><%= flash[:notice] %></p> + +<%= yield %> + +</body> +</html> diff --git a/db/migrate/20090715220414_create_comments.rb b/db/migrate/20090715220414_create_comments.rb new file mode 100644 index 0000000..38dfdaa --- /dev/null +++ b/db/migrate/20090715220414_create_comments.rb @@ -0,0 +1,16 @@ +class CreateComments < ActiveRecord::Migration + def self.up + create_table :comments do |t| + t.string :author + t.string :email + t.string :author + t.text :content + + t.timestamps + end + end + + def self.down + drop_table :comments + end +end diff --git a/test/fixtures/comments.yml b/test/fixtures/comments.yml new file mode 100644 index 0000000..467fffe --- /dev/null +++ b/test/fixtures/comments.yml @@ -0,0 +1,13 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +one: + author: MyString + email: MyString + author: MyString + content: MyText + +two: + author: MyString + email: MyString + author: MyString + content: MyText diff --git a/test/functional/comments_controller_test.rb b/test/functional/comments_controller_test.rb new file mode 100644 index 0000000..03d4af8 --- /dev/null +++ b/test/functional/comments_controller_test.rb @@ -0,0 +1,45 @@ +require 'test_helper' + +class CommentsControllerTest < ActionController::TestCase + test "should get index" do + get :index + assert_response :success + assert_not_nil assigns(:comments) + end + + test "should get new" do + get :new + assert_response :success + end + + test "should create comment" do + assert_difference('Comment.count') do + post :create, :comment => { } + end + + assert_redirected_to comment_path(assigns(:comment)) + end + + test "should show comment" do + get :show, :id => comments(:one).to_param + assert_response :success + end + + test "should get edit" do + get :edit, :id => comments(:one).to_param + assert_response :success + end + + test "should update comment" do + put :update, :id => comments(:one).to_param, :comment => { } + assert_redirected_to comment_path(assigns(:comment)) + end + + test "should destroy comment" do + assert_difference('Comment.count', -1) do + delete :destroy, :id => comments(:one).to_param + end + + assert_redirected_to comments_path + end +end diff --git a/test/unit/comment_test.rb b/test/unit/comment_test.rb new file mode 100644 index 0000000..47dee99 --- /dev/null +++ b/test/unit/comment_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class CommentTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/helpers/comments_helper_test.rb b/test/unit/helpers/comments_helper_test.rb new file mode 100644 index 0000000..2518c16 --- /dev/null +++ b/test/unit/helpers/comments_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class CommentsHelperTest < ActionView::TestCase +end
chollier/proutlol
e7431c10c49b00ddc14e0235a5d52c4e0c442a4c
index.html is so useless for us
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..87afabb --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +log/* \ No newline at end of file diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000..374b590 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,41 @@ +# This file is auto-generated from the current state of the database. Instead of editing this file, +# please use the migrations feature of Active Record to incrementally modify your database, and +# then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your database schema. If you need +# to create the application database on another system, you should be using db:schema:load, not running +# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended to check this file into your version control system. + +ActiveRecord::Schema.define(:version => 20090715194511) do + + create_table "posts", :force => true do |t| + t.string "title" + t.text "content" + t.datetime "created_at" + t.datetime "updated_at" + end + + create_table "users", :force => true do |t| + t.string "login", :null => false + t.string "email", :null => false + t.string "crypted_password", :null => false + t.string "password_salt", :null => false + t.string "persistence_token", :null => false + t.string "single_access_token", :null => false + t.string "perishable_token", :null => false + t.integer "login_count", :default => 0, :null => false + t.integer "failed_login_count", :default => 0, :null => false + t.datetime "last_request_at" + t.datetime "current_login_at" + t.datetime "last_login_at" + t.string "current_login_ip" + t.string "last_login_ip" + t.boolean "admin" + t.datetime "created_at" + t.datetime "updated_at" + end + +end diff --git a/log/development.log b/log/development.log index e69de29..8b13789 100644 --- a/log/development.log +++ b/log/development.log @@ -0,0 +1 @@ + diff --git a/public/index.html b/public/index.html deleted file mode 100644 index 0dd5189..0000000 --- a/public/index.html +++ /dev/null @@ -1,275 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html> - <head> - <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> - <title>Ruby on Rails: Welcome aboard</title> - <style type="text/css" media="screen"> - body { - margin: 0; - margin-bottom: 25px; - padding: 0; - background-color: #f0f0f0; - font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana"; - font-size: 13px; - color: #333; - } - - h1 { - font-size: 28px; - color: #000; - } - - a {color: #03c} - a:hover { - background-color: #03c; - color: white; - text-decoration: none; - } - - - #page { - background-color: #f0f0f0; - width: 750px; - margin: 0; - margin-left: auto; - margin-right: auto; - } - - #content { - float: left; - background-color: white; - border: 3px solid #aaa; - border-top: none; - padding: 25px; - width: 500px; - } - - #sidebar { - float: right; - width: 175px; - } - - #footer { - clear: both; - } - - - #header, #about, #getting-started { - padding-left: 75px; - padding-right: 30px; - } - - - #header { - background-image: url("images/rails.png"); - background-repeat: no-repeat; - background-position: top left; - height: 64px; - } - #header h1, #header h2 {margin: 0} - #header h2 { - color: #888; - font-weight: normal; - font-size: 16px; - } - - - #about h3 { - margin: 0; - margin-bottom: 10px; - font-size: 14px; - } - - #about-content { - background-color: #ffd; - border: 1px solid #fc0; - margin-left: -11px; - } - #about-content table { - margin-top: 10px; - margin-bottom: 10px; - font-size: 11px; - border-collapse: collapse; - } - #about-content td { - padding: 10px; - padding-top: 3px; - padding-bottom: 3px; - } - #about-content td.name {color: #555} - #about-content td.value {color: #000} - - #about-content.failure { - background-color: #fcc; - border: 1px solid #f00; - } - #about-content.failure p { - margin: 0; - padding: 10px; - } - - - #getting-started { - border-top: 1px solid #ccc; - margin-top: 25px; - padding-top: 15px; - } - #getting-started h1 { - margin: 0; - font-size: 20px; - } - #getting-started h2 { - margin: 0; - font-size: 14px; - font-weight: normal; - color: #333; - margin-bottom: 25px; - } - #getting-started ol { - margin-left: 0; - padding-left: 0; - } - #getting-started li { - font-size: 18px; - color: #888; - margin-bottom: 25px; - } - #getting-started li h2 { - margin: 0; - font-weight: normal; - font-size: 18px; - color: #333; - } - #getting-started li p { - color: #555; - font-size: 13px; - } - - - #search { - margin: 0; - padding-top: 10px; - padding-bottom: 10px; - font-size: 11px; - } - #search input { - font-size: 11px; - margin: 2px; - } - #search-text {width: 170px} - - - #sidebar ul { - margin-left: 0; - padding-left: 0; - } - #sidebar ul h3 { - margin-top: 25px; - font-size: 16px; - padding-bottom: 10px; - border-bottom: 1px solid #ccc; - } - #sidebar li { - list-style-type: none; - } - #sidebar ul.links li { - margin-bottom: 5px; - } - - </style> - <script type="text/javascript" src="javascripts/prototype.js"></script> - <script type="text/javascript" src="javascripts/effects.js"></script> - <script type="text/javascript"> - function about() { - if (Element.empty('about-content')) { - new Ajax.Updater('about-content', 'rails/info/properties', { - method: 'get', - onFailure: function() {Element.classNames('about-content').add('failure')}, - onComplete: function() {new Effect.BlindDown('about-content', {duration: 0.25})} - }); - } else { - new Effect[Element.visible('about-content') ? - 'BlindUp' : 'BlindDown']('about-content', {duration: 0.25}); - } - } - - window.onload = function() { - $('search-text').value = ''; - $('search').onsubmit = function() { - $('search-text').value = 'site:rubyonrails.org ' + $F('search-text'); - } - } - </script> - </head> - <body> - <div id="page"> - <div id="sidebar"> - <ul id="sidebar-items"> - <li> - <form id="search" action="http://www.google.com/search" method="get"> - <input type="hidden" name="hl" value="en" /> - <input type="text" id="search-text" name="q" value="site:rubyonrails.org " /> - <input type="submit" value="Search" /> the Rails site - </form> - </li> - - <li> - <h3>Join the community</h3> - <ul class="links"> - <li><a href="http://www.rubyonrails.org/">Ruby on Rails</a></li> - <li><a href="http://weblog.rubyonrails.org/">Official weblog</a></li> - <li><a href="http://wiki.rubyonrails.org/">Wiki</a></li> - </ul> - </li> - - <li> - <h3>Browse the documentation</h3> - <ul class="links"> - <li><a href="http://api.rubyonrails.org/">Rails API</a></li> - <li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li> - <li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li> - <li><a href="http://guides.rubyonrails.org/">Rails Guides</a></li> - </ul> - </li> - </ul> - </div> - - <div id="content"> - <div id="header"> - <h1>Welcome aboard</h1> - <h2>You&rsquo;re riding Ruby on Rails!</h2> - </div> - - <div id="about"> - <h3><a href="rails/info/properties" onclick="about(); return false">About your application&rsquo;s environment</a></h3> - <div id="about-content" style="display: none"></div> - </div> - - <div id="getting-started"> - <h1>Getting started</h1> - <h2>Here&rsquo;s how to get rolling:</h2> - - <ol> - <li> - <h2>Use <tt>script/generate</tt> to create your models and controllers</h2> - <p>To see all available options, run it without parameters.</p> - </li> - - <li> - <h2>Set up a default route and remove or rename this file</h2> - <p>Routes are set up in config/routes.rb.</p> - </li> - - <li> - <h2>Create your database</h2> - <p>Run <tt>rake db:migrate</tt> to create your database. If you're not using SQLite (the default), edit <tt>config/database.yml</tt> with your username and password.</p> - </li> - </ol> - </div> - </div> - - <div id="footer">&nbsp;</div> - </div> - </body> -</html> \ No newline at end of file
chollier/proutlol
cc5fd5b6e12dc9789267f039e6c29a6a6d07d612
i'v added the user support
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 6635a3f..461dac8 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,10 +1,49 @@ # Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all # include all helpers, all the time protect_from_forgery # See ActionController::RequestForgeryProtection for details # Scrub sensitive parameters from your log - # filter_parameter_logging :password + filter_parameter_logging :password, :password_confirmation + helper_method :current_user_session, :current_user + + private + def current_user_session + return @current_user_session if defined?(@current_user_session) + @current_user_session = UserSession.find + end + + def current_user + return @current_user if defined?(@current_user) + @current_user = current_user_session && current_user_session.user + end + + def require_user + unless current_user + store_location + flash[:notice] = "You must be logged in to access this page" + redirect_to new_user_session_url + return false + end + end + + def require_no_user + if current_user + store_location + flash[:notice] = "You must be logged out to access this page" + redirect_to account_url + return false + end + end + + def require_admin + if !current_user.admin + flash[:notice] = "You must be admin to access this page" + redirect_to root_url + return false + end + end + end diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb index 5fbc1c5..6e1e989 100644 --- a/app/controllers/posts_controller.rb +++ b/app/controllers/posts_controller.rb @@ -1,85 +1,87 @@ class PostsController < ApplicationController + before_filter :require_admin, :except => [:index, :show ] + # GET /posts # GET /posts.xml def index @posts = Post.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @posts } end end # GET /posts/1 # GET /posts/1.xml def show @post = Post.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @post } end end # GET /posts/new # GET /posts/new.xml def new @post = Post.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @post } end end # GET /posts/1/edit def edit @post = Post.find(params[:id]) end # POST /posts # POST /posts.xml def create @post = Post.new(params[:post]) respond_to do |format| if @post.save flash[:notice] = 'Post was successfully created.' format.html { redirect_to(@post) } format.xml { render :xml => @post, :status => :created, :location => @post } else format.html { render :action => "new" } format.xml { render :xml => @post.errors, :status => :unprocessable_entity } end end end # PUT /posts/1 # PUT /posts/1.xml def update @post = Post.find(params[:id]) respond_to do |format| if @post.update_attributes(params[:post]) flash[:notice] = 'Post was successfully updated.' format.html { redirect_to(@post) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @post.errors, :status => :unprocessable_entity } end end end # DELETE /posts/1 # DELETE /posts/1.xml def destroy @post = Post.find(params[:id]) @post.destroy respond_to do |format| format.html { redirect_to(posts_url) } format.xml { head :ok } end end end diff --git a/app/controllers/user_sessions_controller.rb b/app/controllers/user_sessions_controller.rb new file mode 100644 index 0000000..004c206 --- /dev/null +++ b/app/controllers/user_sessions_controller.rb @@ -0,0 +1,24 @@ +class UserSessionsController < ApplicationController + before_filter :require_no_user, :only => [:new, :create] + before_filter :require_user, :only => :destroy + + def new + @user_session = UserSession.new + end + + def create + @user_session = UserSession.new(params[:user_session]) + if @user_session.save + flash[:notice] = "Login successful!" + redirect_back_or_default account_url + else + render :action => :new + end + end + + def destroy + current_user_session.destroy + flash[:notice] = "Logout successful!" + redirect_to root_url + end +end \ No newline at end of file diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb new file mode 100644 index 0000000..5a1ff94 --- /dev/null +++ b/app/controllers/users_controller.rb @@ -0,0 +1,38 @@ +class UsersController < ApplicationController + class UsersController < ApplicationController + before_filter :require_no_user, :only => [:new, :create] + before_filter :require_user, :only => [:show, :edit, :update] + + def new + @user = User.new + end + + def create + @user = User.new(params[:user]) + if @user.save + flash[:notice] = "Account registered!" + redirect_to root_url + else + render :action => :new + end + end + + def show + @user = @current_user + end + + def edit + @user = @current_user + end + + def update + @user = @current_user # makes our views "cleaner" and more consistent + if @user.update_attributes(params[:user]) + flash[:notice] = "Account updated!" + redirect_to account_url + else + render :action => :edit + end + end + end +end diff --git a/app/helpers/user_sessions_helper.rb b/app/helpers/user_sessions_helper.rb new file mode 100644 index 0000000..2018402 --- /dev/null +++ b/app/helpers/user_sessions_helper.rb @@ -0,0 +1,2 @@ +module UserSessionsHelper +end diff --git a/app/helpers/users_helper.rb b/app/helpers/users_helper.rb new file mode 100644 index 0000000..2310a24 --- /dev/null +++ b/app/helpers/users_helper.rb @@ -0,0 +1,2 @@ +module UsersHelper +end diff --git a/app/models/post.rb b/app/models/post.rb index 791dcb5..542c073 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -1,2 +1,3 @@ class Post < ActiveRecord::Base + belongs_to :user end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 0000000..0f0b18a --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,4 @@ +class User < ActiveRecord::Base + acts_as_authentic + has_many :posts +end diff --git a/app/models/user_session.rb b/app/models/user_session.rb new file mode 100644 index 0000000..8c19d19 --- /dev/null +++ b/app/models/user_session.rb @@ -0,0 +1,2 @@ +class UserSession < Authlogic::Session::Base +end \ No newline at end of file diff --git a/app/views/user_sessions/new.html.erb b/app/views/user_sessions/new.html.erb new file mode 100644 index 0000000..1eb03c6 --- /dev/null +++ b/app/views/user_sessions/new.html.erb @@ -0,0 +1,14 @@ +<h1>Login</h1> + +<% form_for @user_session, :url => user_session_path do |f| %> + <%= f.error_messages %> + <%= f.label :login %><br /> + <%= f.text_field :login %><br /> + <br /> + <%= f.label :password %><br /> + <%= f.password_field :password %><br /> + <br /> + <%= f.check_box :remember_me %><%= f.label :remember_me %><br /> + <br /> + <%= f.submit "Login" %> +<% end %> \ No newline at end of file diff --git a/app/views/users/_form.html.erb b/app/views/users/_form.html.erb new file mode 100644 index 0000000..7556023 --- /dev/null +++ b/app/views/users/_form.html.erb @@ -0,0 +1,8 @@ +<%= form.label :login %><br /> +<%= form.text_field :login %><br /> +<br /> +<%= form.label :password, form.object.new_record? ? nil : "Change password" %><br /> +<%= form.password_field :password %><br /> +<br /> +<%= form.label :password_confirmation %><br /> +<%= form.password_field :password_confirmation %><br /> \ No newline at end of file diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb new file mode 100644 index 0000000..40a466f --- /dev/null +++ b/app/views/users/edit.html.erb @@ -0,0 +1,9 @@ +<h1>Edit My Account</h1> + +<% form_for @user, :url => account_path do |f| %> + <%= f.error_messages %> + <%= render :partial => "form", :object => f %> + <%= f.submit "Update" %> +<% end %> + +<br /><%= link_to "My Profile", account_path %> \ No newline at end of file diff --git a/app/views/users/new.html.erb b/app/views/users/new.html.erb new file mode 100644 index 0000000..baf4146 --- /dev/null +++ b/app/views/users/new.html.erb @@ -0,0 +1,7 @@ +<h1>Register</h1> + +<% form_for @user, :url => account_path do |f| %> + <%= f.error_messages %> + <%= render :partial => "form", :object => f %> + <%= f.submit "Register" %> +<% end %> \ No newline at end of file diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb new file mode 100644 index 0000000..d194ba3 --- /dev/null +++ b/app/views/users/show.html.erb @@ -0,0 +1,37 @@ +<p> + <b>Login:</b> + <%=h @user.login %> +</p> + +<p> + <b>Login count:</b> + <%=h @user.login_count %> +</p> + +<p> + <b>Last request at:</b> + <%=h @user.last_request_at %> +</p> + +<p> + <b>Last login at:</b> + <%=h @user.last_login_at %> +</p> + +<p> + <b>Current login at:</b> + <%=h @user.current_login_at %> +</p> + +<p> + <b>Last login ip:</b> + <%=h @user.last_login_ip %> +</p> + +<p> + <b>Current login ip:</b> + <%=h @user.current_login_ip %> +</p> + + +<%= link_to 'Edit', edit_account_path %> \ No newline at end of file diff --git a/config/environment.rb b/config/environment.rb index 011f738..0f6d5a5 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,41 +1,43 @@ # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" + config.gem "authlogic" + # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'Paris' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. #config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] config.i18n.default_locale = :fr end \ No newline at end of file diff --git a/config/locales/fr.yml b/config/locales/fr.yml index 94aeab3..2780b20 100644 --- a/config/locales/fr.yml +++ b/config/locales/fr.yml @@ -1,138 +1,161 @@ # French translations for Ruby on Rails # by Christian Lescuyer ([email protected]) # contributor: Sebastien Grosjean - ZenCocoon.com fr: date: formats: default: "%d/%m/%Y" short: "%e %b" long: "%e %B %Y" long_ordinal: "%e %B %Y" only_day: "%e" day_names: [dimanche, lundi, mardi, mercredi, jeudi, vendredi, samedi] abbr_day_names: [dim, lun, mar, mer, jeu, ven, sam] month_names: [~, janvier, février, mars, avril, mai, juin, juillet, août, septembre, octobre, novembre, décembre] abbr_month_names: [~, jan., fév., mar., avr., mai, juin, juil., août, sept., oct., nov., déc.] order: [ :day, :month, :year ] time: formats: default: "%d %B %Y %H:%M" time: "%H:%M" short: "%d %b %H:%M" long: "%A %d %B %Y %H:%M:%S %Z" long_ordinal: "%A %d %B %Y %H:%M:%S %Z" only_second: "%S" am: 'am' pm: 'pm' datetime: distance_in_words: half_a_minute: "une demi-minute" less_than_x_seconds: zero: "moins d'une seconde" one: "moins de 1 seconde" other: "moins de {{count}} secondes" x_seconds: one: "1 seconde" other: "{{count}} secondes" less_than_x_minutes: zero: "moins d'une minute" one: "moins de 1 minute" other: "moins de {{count}} minutes" x_minutes: one: "1 minute" other: "{{count}} minutes" about_x_hours: one: "environ une heure" other: "environ {{count}} heures" x_days: one: "1 jour" other: "{{count}} jours" about_x_months: one: "environ un mois" other: "environ {{count}} mois" x_months: one: "1 mois" other: "{{count}} mois" about_x_years: one: "environ un an" other: "environ {{count}} ans" over_x_years: one: "plus d'un an" other: "plus de {{count}} ans" prompts: year: "Année" month: "Mois" day: "Jour" hour: "Heure" minute: "Minute" second: "Seconde" number: format: precision: 3 separator: ',' delimiter: ' ' currency: format: unit: '€' precision: 2 format: '%n %u' human: format: # These three are to override number.format and are optional # separator: delimiter: "" precision: 2 # Rails <= v2.2.2 # storage_units: [octet, kb, Mb, Gb, Tb] # Rails >= v2.3 storage_units: format: "%n %u" units: byte: one: "octet" other: "octets" kb: "ko" mb: "Mo" gb: "Go" tb: "To" support: array: sentence_connector: 'et' skip_last_comma: true words_connector: ", " two_words_connector: " et " last_word_connector: " et " activerecord: errors: template: header: one: "Impossible d'enregistrer {{model}}: 1 erreur" other: "Impossible d'enregistrer {{model}}: {{count}} erreurs." body: "Veuillez vérifier les champs suivants :" messages: inclusion: "n'est pas inclus(e) dans la liste" exclusion: "n'est pas disponible" invalid: "n'est pas valide" confirmation: "ne concorde pas avec la confirmation" accepted: "doit être accepté(e)" empty: "doit être rempli(e)" blank: "doit être rempli(e)" too_long: "est trop long (pas plus de {{count}} caractères)" too_short: "est trop court (au moins {{count}} caractères)" wrong_length: "ne fait pas la bonne longueur (doit comporter {{count}} caractères)" taken: "n'est pas disponible" not_a_number: "n'est pas un nombre" greater_than: "doit être supérieur à {{count}}" greater_than_or_equal_to: "doit être supérieur ou égal à {{count}}" equal_to: "doit être égal à {{count}}" less_than: "doit être inférieur à {{count}}" less_than_or_equal_to: "doit être inférieur ou égal à {{count}}" odd: "doit être impair" - even: "doit être pair" \ No newline at end of file + even: "doit être pair" + + + authlogic: + error_messages: + login_blank: "ne peut être vide" + login_not_found: "n'est pas valide" + login_invalid: "devrait contenir uniquement des lettres, chiffres, espaces et.-_@" + consecutive_failed_logins_limit_exceeded: "Le limite d'echecs consécutifs de connexion a été atteinte, ce compte est désactivé." + email_invalid: "devrait ressembler à une adresse email." + password_blank: "ne peut être vide" + password_invalid: "n'est pas valide" + not_active: "Votre compte n'est pas activé" + not_confirmed: "Votre compte n'a pas été validé" + not_approved: "Votre compte n'a pas été approuvé" + no_authentication_details: "Vous n'avez pas donné d'informartions pour vous identifier" + models: + user_session: "UserSession" + attributes: + user_session: (or whatever name you are using) + login: "identifiant" + email: "email" + password: "mot de passe" + remember_me: "se souvenir" \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 38adeaf..cc076bb 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,46 +1,48 @@ ActionController::Routing::Routes.draw do |map| map.root :controller => "posts", :action => "index" + map.resource :user_session + map.resources :users map.resources :posts # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/db/migrate/20090715194511_create_users.rb b/db/migrate/20090715194511_create_users.rb new file mode 100644 index 0000000..4b659d3 --- /dev/null +++ b/db/migrate/20090715194511_create_users.rb @@ -0,0 +1,30 @@ +class CreateUsers < ActiveRecord::Migration + def self.up + create_table :users do |t| + t.string :login, :null => false # optional, you can use email instead, or both + t.string :email, :null => false # optional, you can use login instead, or both + t.string :crypted_password, :null => false # optional, see below + t.string :password_salt, :null => false # optional, but highly recommended + t.string :persistence_token, :null => false # required + t.string :single_access_token, :null => false # optional, see Authlogic::Session::Params + t.string :perishable_token, :null => false # optional, see Authlogic::Session::Perishability + + # Magic columns, just like ActiveRecord's created_at and updated_at. These are automatically maintained by Authlogic if they are present. + t.integer :login_count, :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns + t.integer :failed_login_count, :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns + t.datetime :last_request_at # optional, see Authlogic::Session::MagicColumns + t.datetime :current_login_at # optional, see Authlogic::Session::MagicColumns + t.datetime :last_login_at # optional, see Authlogic::Session::MagicColumns + t.string :current_login_ip # optional, see Authlogic::Session::MagicColumns + t.string :last_login_ip # optional, see Authlogic::Session::MagicColumns + + #Added by me for the blog's admin + t.boolean :admin + t.timestamps + end + end + + def self.down + drop_table :users + end +end diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/test/fixtures/users.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/test/functional/user_sessions_controller_test.rb b/test/functional/user_sessions_controller_test.rb new file mode 100644 index 0000000..5024b23 --- /dev/null +++ b/test/functional/user_sessions_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class UserSessionsControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/functional/users_controller_test.rb b/test/functional/users_controller_test.rb new file mode 100644 index 0000000..c3db123 --- /dev/null +++ b/test/functional/users_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class UsersControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/helpers/user_sessions_helper_test.rb b/test/unit/helpers/user_sessions_helper_test.rb new file mode 100644 index 0000000..20dabdf --- /dev/null +++ b/test/unit/helpers/user_sessions_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class UserSessionsHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/users_helper_test.rb b/test/unit/helpers/users_helper_test.rb new file mode 100644 index 0000000..96af37a --- /dev/null +++ b/test/unit/helpers/users_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class UsersHelperTest < ActionView::TestCase +end diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb new file mode 100644 index 0000000..a64d2d3 --- /dev/null +++ b/test/unit/user_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class UserTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end
chollier/proutlol
f02cbf83a94a6e0b54964b7fcd365e82af5c6057
let's add french translation for rails
diff --git a/config/environment.rb b/config/environment.rb index ff450c7..011f738 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,41 +1,41 @@ # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. - config.time_zone = 'UTC' + config.time_zone = 'Paris' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. - # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] - # config.i18n.default_locale = :de + #config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] + config.i18n.default_locale = :fr end \ No newline at end of file diff --git a/config/locales/fr.yml b/config/locales/fr.yml new file mode 100644 index 0000000..94aeab3 --- /dev/null +++ b/config/locales/fr.yml @@ -0,0 +1,138 @@ +# French translations for Ruby on Rails +# by Christian Lescuyer ([email protected]) +# contributor: Sebastien Grosjean - ZenCocoon.com + +fr: + date: + formats: + default: "%d/%m/%Y" + short: "%e %b" + long: "%e %B %Y" + long_ordinal: "%e %B %Y" + only_day: "%e" + + day_names: [dimanche, lundi, mardi, mercredi, jeudi, vendredi, samedi] + abbr_day_names: [dim, lun, mar, mer, jeu, ven, sam] + month_names: [~, janvier, février, mars, avril, mai, juin, juillet, août, septembre, octobre, novembre, décembre] + abbr_month_names: [~, jan., fév., mar., avr., mai, juin, juil., août, sept., oct., nov., déc.] + order: [ :day, :month, :year ] + + time: + formats: + default: "%d %B %Y %H:%M" + time: "%H:%M" + short: "%d %b %H:%M" + long: "%A %d %B %Y %H:%M:%S %Z" + long_ordinal: "%A %d %B %Y %H:%M:%S %Z" + only_second: "%S" + am: 'am' + pm: 'pm' + + datetime: + distance_in_words: + half_a_minute: "une demi-minute" + less_than_x_seconds: + zero: "moins d'une seconde" + one: "moins de 1 seconde" + other: "moins de {{count}} secondes" + x_seconds: + one: "1 seconde" + other: "{{count}} secondes" + less_than_x_minutes: + zero: "moins d'une minute" + one: "moins de 1 minute" + other: "moins de {{count}} minutes" + x_minutes: + one: "1 minute" + other: "{{count}} minutes" + about_x_hours: + one: "environ une heure" + other: "environ {{count}} heures" + x_days: + one: "1 jour" + other: "{{count}} jours" + about_x_months: + one: "environ un mois" + other: "environ {{count}} mois" + x_months: + one: "1 mois" + other: "{{count}} mois" + about_x_years: + one: "environ un an" + other: "environ {{count}} ans" + over_x_years: + one: "plus d'un an" + other: "plus de {{count}} ans" + prompts: + year: "Année" + month: "Mois" + day: "Jour" + hour: "Heure" + minute: "Minute" + second: "Seconde" + + number: + format: + precision: 3 + separator: ',' + delimiter: ' ' + currency: + format: + unit: '€' + precision: 2 + format: '%n %u' + human: + format: + # These three are to override number.format and are optional + # separator: + delimiter: "" + precision: 2 + # Rails <= v2.2.2 + # storage_units: [octet, kb, Mb, Gb, Tb] + # Rails >= v2.3 + storage_units: + format: "%n %u" + units: + byte: + one: "octet" + other: "octets" + kb: "ko" + mb: "Mo" + gb: "Go" + tb: "To" + + support: + array: + sentence_connector: 'et' + skip_last_comma: true + words_connector: ", " + two_words_connector: " et " + last_word_connector: " et " + + activerecord: + errors: + template: + header: + one: "Impossible d'enregistrer {{model}}: 1 erreur" + other: "Impossible d'enregistrer {{model}}: {{count}} erreurs." + body: "Veuillez vérifier les champs suivants :" + messages: + inclusion: "n'est pas inclus(e) dans la liste" + exclusion: "n'est pas disponible" + invalid: "n'est pas valide" + confirmation: "ne concorde pas avec la confirmation" + accepted: "doit être accepté(e)" + empty: "doit être rempli(e)" + blank: "doit être rempli(e)" + too_long: "est trop long (pas plus de {{count}} caractères)" + too_short: "est trop court (au moins {{count}} caractères)" + wrong_length: "ne fait pas la bonne longueur (doit comporter {{count}} caractères)" + taken: "n'est pas disponible" + not_a_number: "n'est pas un nombre" + greater_than: "doit être supérieur à {{count}}" + greater_than_or_equal_to: "doit être supérieur ou égal à {{count}}" + equal_to: "doit être égal à {{count}}" + less_than: "doit être inférieur à {{count}}" + less_than_or_equal_to: "doit être inférieur ou égal à {{count}}" + odd: "doit être impair" + even: "doit être pair" \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 836c1dd..38adeaf 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,45 +1,46 @@ ActionController::Routing::Routes.draw do |map| + map.root :controller => "posts", :action => "index" map.resources :posts # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end
chollier/proutlol
02bddae49784ed75b10bfe97a42428efff9f02aa
Post scaffolding, i'm a bit lazy.
diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb new file mode 100644 index 0000000..5fbc1c5 --- /dev/null +++ b/app/controllers/posts_controller.rb @@ -0,0 +1,85 @@ +class PostsController < ApplicationController + # GET /posts + # GET /posts.xml + def index + @posts = Post.all + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @posts } + end + end + + # GET /posts/1 + # GET /posts/1.xml + def show + @post = Post.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @post } + end + end + + # GET /posts/new + # GET /posts/new.xml + def new + @post = Post.new + + respond_to do |format| + format.html # new.html.erb + format.xml { render :xml => @post } + end + end + + # GET /posts/1/edit + def edit + @post = Post.find(params[:id]) + end + + # POST /posts + # POST /posts.xml + def create + @post = Post.new(params[:post]) + + respond_to do |format| + if @post.save + flash[:notice] = 'Post was successfully created.' + format.html { redirect_to(@post) } + format.xml { render :xml => @post, :status => :created, :location => @post } + else + format.html { render :action => "new" } + format.xml { render :xml => @post.errors, :status => :unprocessable_entity } + end + end + end + + # PUT /posts/1 + # PUT /posts/1.xml + def update + @post = Post.find(params[:id]) + + respond_to do |format| + if @post.update_attributes(params[:post]) + flash[:notice] = 'Post was successfully updated.' + format.html { redirect_to(@post) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @post.errors, :status => :unprocessable_entity } + end + end + end + + # DELETE /posts/1 + # DELETE /posts/1.xml + def destroy + @post = Post.find(params[:id]) + @post.destroy + + respond_to do |format| + format.html { redirect_to(posts_url) } + format.xml { head :ok } + end + end +end diff --git a/app/helpers/posts_helper.rb b/app/helpers/posts_helper.rb new file mode 100644 index 0000000..a7b8cec --- /dev/null +++ b/app/helpers/posts_helper.rb @@ -0,0 +1,2 @@ +module PostsHelper +end diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 0000000..6cf6bc8 --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,17 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> + <title><%= controller.action_name %></title> + <%= stylesheet_link_tag 'scaffold' %> +</head> +<body> + +<p style="color: green"><%= flash[:notice] %></p> + +<%= yield %> + +</body> +</html> diff --git a/app/views/posts/edit.html.erb b/app/views/posts/edit.html.erb new file mode 100644 index 0000000..d872f1a --- /dev/null +++ b/app/views/posts/edit.html.erb @@ -0,0 +1,12 @@ +<h1>Editing post</h1> + +<% form_for(@post) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.submit 'Update' %> + </p> +<% end %> + +<%= link_to 'Show', @post %> | +<%= link_to 'Back', posts_path %> \ No newline at end of file diff --git a/app/views/posts/index.html.erb b/app/views/posts/index.html.erb new file mode 100644 index 0000000..947c9ff --- /dev/null +++ b/app/views/posts/index.html.erb @@ -0,0 +1,18 @@ +<h1>Listing posts</h1> + +<table> + <tr> + </tr> + +<% @posts.each do |post| %> + <tr> + <td><%= link_to 'Show', post %></td> + <td><%= link_to 'Edit', edit_post_path(post) %></td> + <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td> + </tr> +<% end %> +</table> + +<br /> + +<%= link_to 'New post', new_post_path %> \ No newline at end of file diff --git a/app/views/posts/new.html.erb b/app/views/posts/new.html.erb new file mode 100644 index 0000000..c088988 --- /dev/null +++ b/app/views/posts/new.html.erb @@ -0,0 +1,11 @@ +<h1>New post</h1> + +<% form_for(@post) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.submit 'Create' %> + </p> +<% end %> + +<%= link_to 'Back', posts_path %> \ No newline at end of file diff --git a/app/views/posts/show.html.erb b/app/views/posts/show.html.erb new file mode 100644 index 0000000..f1b35c2 --- /dev/null +++ b/app/views/posts/show.html.erb @@ -0,0 +1,3 @@ + +<%= link_to 'Edit', edit_post_path(@post) %> | +<%= link_to 'Back', posts_path %> \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 4f3d9d2..836c1dd 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,43 +1,45 @@ ActionController::Routing::Routes.draw do |map| + map.resources :posts + # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/public/stylesheets/scaffold.css b/public/stylesheets/scaffold.css new file mode 100644 index 0000000..093c209 --- /dev/null +++ b/public/stylesheets/scaffold.css @@ -0,0 +1,54 @@ +body { background-color: #fff; color: #333; } + +body, p, ol, ul, td { + font-family: verdana, arial, helvetica, sans-serif; + font-size: 13px; + line-height: 18px; +} + +pre { + background-color: #eee; + padding: 10px; + font-size: 11px; +} + +a { color: #000; } +a:visited { color: #666; } +a:hover { color: #fff; background-color:#000; } + +.fieldWithErrors { + padding: 2px; + background-color: red; + display: table; +} + +#errorExplanation { + width: 400px; + border: 2px solid red; + padding: 7px; + padding-bottom: 12px; + margin-bottom: 20px; + background-color: #f0f0f0; +} + +#errorExplanation h2 { + text-align: left; + font-weight: bold; + padding: 5px 5px 5px 15px; + font-size: 12px; + margin: -7px; + background-color: #c00; + color: #fff; +} + +#errorExplanation p { + color: #333; + margin-bottom: 0; + padding: 5px; +} + +#errorExplanation ul li { + font-size: 12px; + list-style: square; +} + diff --git a/test/functional/posts_controller_test.rb b/test/functional/posts_controller_test.rb new file mode 100644 index 0000000..6ef56a3 --- /dev/null +++ b/test/functional/posts_controller_test.rb @@ -0,0 +1,45 @@ +require 'test_helper' + +class PostsControllerTest < ActionController::TestCase + test "should get index" do + get :index + assert_response :success + assert_not_nil assigns(:posts) + end + + test "should get new" do + get :new + assert_response :success + end + + test "should create post" do + assert_difference('Post.count') do + post :create, :post => { } + end + + assert_redirected_to post_path(assigns(:post)) + end + + test "should show post" do + get :show, :id => posts(:one).to_param + assert_response :success + end + + test "should get edit" do + get :edit, :id => posts(:one).to_param + assert_response :success + end + + test "should update post" do + put :update, :id => posts(:one).to_param, :post => { } + assert_redirected_to post_path(assigns(:post)) + end + + test "should destroy post" do + assert_difference('Post.count', -1) do + delete :destroy, :id => posts(:one).to_param + end + + assert_redirected_to posts_path + end +end diff --git a/test/unit/helpers/posts_helper_test.rb b/test/unit/helpers/posts_helper_test.rb new file mode 100644 index 0000000..48549c2 --- /dev/null +++ b/test/unit/helpers/posts_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class PostsHelperTest < ActionView::TestCase +end
chollier/proutlol
094f936d09afca2be1f4c9681476dccdfe6e5614
let's add posts
diff --git a/app/models/post.rb b/app/models/post.rb new file mode 100644 index 0000000..791dcb5 --- /dev/null +++ b/app/models/post.rb @@ -0,0 +1,2 @@ +class Post < ActiveRecord::Base +end diff --git a/db/migrate/20090715183049_create_posts.rb b/db/migrate/20090715183049_create_posts.rb new file mode 100644 index 0000000..b99fce0 --- /dev/null +++ b/db/migrate/20090715183049_create_posts.rb @@ -0,0 +1,14 @@ +class CreatePosts < ActiveRecord::Migration + def self.up + create_table :posts do |t| + t.string :title + t.text :content + + t.timestamps + end + end + + def self.down + drop_table :posts + end +end diff --git a/test/fixtures/posts.yml b/test/fixtures/posts.yml new file mode 100644 index 0000000..83f21ff --- /dev/null +++ b/test/fixtures/posts.yml @@ -0,0 +1,9 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +one: + title: MyString + content: MyText + +two: + title: MyString + content: MyText diff --git a/test/unit/post_test.rb b/test/unit/post_test.rb new file mode 100644 index 0000000..8afe8cc --- /dev/null +++ b/test/unit/post_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class PostTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end
vodafon/google_cse
881f4b449f63a96ecdcd7f6923b93b7736edbbe1
Using default parser should work on later rails versions
diff --git a/lib/google_cse.rb b/lib/google_cse.rb index 01507a1..a7aa1a5 100644 --- a/lib/google_cse.rb +++ b/lib/google_cse.rb @@ -1,104 +1,104 @@ module GoogleCustomSearch ## # Search result data. # class ResultSet < Struct.new(:pages, :results); end ## # Single search result data. # class Result < Struct.new(:url, :title, :description); end ## # Pages data # class Start < Struct.new(:start, :label); end ## # Search the site. # def self.search(query, start) # Get and parse results. url = url(query, start) json = fetch_json(url) - data = Crack::JSON.parse(json) + data = JSON.parse(json) # Extract and return pages data and search result data. if data['responseData'] if data['responseData']['cursor']['pages'] ResultSet.new( parse_start(data['responseData']['cursor']['pages']), parse_results(data['responseData']['results']) ) else ResultSet.new( false, #return false if pages < 1 parse_results(data['responseData']['results']) ) end else ResultSet.new(0, []) end end private ## # Build search request URL. # def self.url(query, start) query = CGI::escape(query) "http://www.google.com/uds/GwebSearch?context=0&lstkp=0&rsz=filtered_cse&hl=ru&source=gcsc&gss=.com&cx=#{CX_GOOGLE_CSE}&q=#{query}&start=#{start}&v=1.0" end ## # Query Google. # def self.fetch_json(url) begin resp = nil timeout(3) do resp = Net::HTTP.get_response(URI.parse(url)) end rescue SocketError, TimeoutError; end (resp and resp.code == "200") ? resp.body : nil end ## # Transform an array of Google search results into # a more useful format. # def self.parse_results(results) out = [] results = results results.each do |r| out << Result.new( r['url'], # url r['title'], # title r['content'] # desciption ) end out end ## # Transform an array of Google pages info into # a mare useful format. def self.parse_start(results) out = [] results = results results.each do |r| out << Start.new( r['start'], # pages start r['label'] # pages label ) end out end end
vodafon/google_cse
33524925fecd2ca18ab6848e62b58e42c5b05797
fix copy
diff --git a/CHANGELOG.rdoc b/CHANGELOG.rdoc index ae4a1b0..27e6426 100644 --- a/CHANGELOG.rdoc +++ b/CHANGELOG.rdoc @@ -1,6 +1,6 @@ = Changelog Release changes to GoogleCustomSearch. -== 0.1 (2010 Sep 14) +== 0.1.0 (2010 Sep 14) diff --git a/README.rdoc b/README.rdoc index d2b1c11..a488741 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,56 +1,56 @@ = Google Custom Search This project is a Ruby API to Google's Custom Search Engine (http://www.google.com/cse). This plugin is rewrite plugin from Alex Reisner (http://github.com/alexreisner/google_custom_search.git), because the old plugin not working. == 1. Install Install either as a Rails plugin: rails plugin install git://github.com/vodafon/google_cse.git or as a gem: # add to Gemfile: - gem "google_cse", :source => "http://gemcutter.org/" + gem "google_cse" # at command prompt: bundle install or as a standalone gem (outside of Rails): - sudo gem install google_cse --source http://gemcutter.org + sudo gem install google_cse == 2. Configure You *must* define a constant in your application called <tt>CX_GOOGLE_CSE</tt>. For example, if you're using Rails, create a file <tt>config/initializers/google_cse.rb</tt>: CX_GOOGLE_CSE = "..." You can find the CX value for your custom search engine via the search control panel on Google's site (click the "Get code" link and you'll see a hidden "cx" field in the sample HTML form). == 3. Use To perform a search: results = GoogleCustomSearch.search("Hank Aaron", 0) The second parameter is a start parameter for search query. 0 - first page (1-10 result), 10 - second page, etc. The +results+ variable is now a GoogleCustomSearch::ResultSet object: results.pages # array of pages data results.results # array of result objects Iterate through the results: results.results.each do |result| result.title # result title result.url # result URL result.description # excerpt, with terms highlighted end Copyright (c) 2010 Igor Vodafon, released under the MIT license diff --git a/Rakefile b/Rakefile index a109180..b6af568 100644 --- a/Rakefile +++ b/Rakefile @@ -1,55 +1,55 @@ require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "google_cse" gem.summary = %Q{Ruby API to Google Custom Search Engine.} gem.description = %Q{Ruby API to Google Custom Search Engine. Works with the paid version of CSE where you get results in XML format.} - gem.email = "[email protected]" + gem.email = "[email protected]" gem.homepage = "http://github.com/vodafon/google_cse" gem.authors = ["Igor Vodafon"] end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler" end require 'rake/testtask' Rake::TestTask.new(:test) do |test| test.libs << 'lib' << 'test' test.pattern = 'test/**/*_test.rb' test.verbose = true end begin require 'rcov/rcovtask' Rcov::RcovTask.new do |test| test.libs << 'test' test.pattern = 'test/**/*_test.rb' test.verbose = true end rescue LoadError task :rcov do abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov" end end task :test => :check_dependencies task :default => :test require 'rake/rdoctask' Rake::RDocTask.new do |rdoc| if File.exist?('VERSION') version = File.read('VERSION') else version = "" end rdoc.rdoc_dir = 'rdoc' rdoc.title = "Google CSE #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end diff --git a/google_cse.gemspec b/google_cse.gemspec index d23d98f..b1414c9 100644 --- a/google_cse.gemspec +++ b/google_cse.gemspec @@ -1,35 +1,35 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{google_cse} s.version = "0.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Igor Vodafon"] s.date = %q{2010-09-14} s.description = %q{Ruby API to Google Custom Search Engine. Works with the paid version of CSE where you get results in XML format.} - s.email = %q{[email protected]} + s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.homepage = %q{http://github.com/vodafon/google_cse} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{Ruby API to Google Custom Search Engine.} if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end
vodafon/google_cse
4319cf4938deb772714f0664816410912109b0e6
add gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..006e304 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +pkg/* +*.swp +*.swo +tmp/*
citrus/cam_control
c812f16047efd8cec1359d0c55287e489ec5cb78
version bump
diff --git a/cam b/cam index e6578f0..682b0ea 100644 --- a/cam +++ b/cam @@ -1,235 +1,239 @@ #!/bin/sh #================================================================== # Defaults #================================================================== SCRIPT_NAME="Cam Control Script" -VERSION="0.0.3" +VERSION="0.0.4" CAM_SITE=/home/citrus/domains/cam.citrusme.com/current CAM_IMAGE_DIR=$CAM_SITE/images CAM_IMAGE_BACKUP=$CAM_SITE/backups #================================================================== # Utility Functions #================================================================== get_pid() { pid=0 if [ -e /var/run/motion.pid ]; then pid=`cat /var/run/motion.pid` fi echo $pid } get_status(){ status="stopped" if [ `get_pid` -gt 0 ]; then status="running" fi echo "$status" } get_start() { if [ -e $CAM_SITE/log/cam.start ]; then echo `cat $CAM_SITE/log/cam.start` else echo 'not running' fi } get_images() { echo `sudo ls $CAM_IMAGE_DIR -1` } get_count() { count=`sudo ls $CAM_IMAGE_DIR -1 | wc -l` if [ $count -gt 0 ]; then count=`expr $count - 1` fi echo $count } #================================================================== # Tasks #================================================================== help() { cat <<HELP ------------------------------------ $SCRIPT_NAME ------------------------------------ TASKS [start] starts camera [stop] stops camera [stats, -s] shows camera stats [restart] restarts camera [backup] backs up camera images [backups] cd to backup directory [images] cd to image directory [flush] flushes image directory [install] copies this script to /usr/local/bin [-h] help [-v] version USAGE: backsup [task] VERSION: $SCRIPT_NAME $VERSION HELP exit 0 } stats() { cat <<STATS Camera Statistics ------------------------------------ Status: `get_status` Process ID: `get_pid` Total Images: `get_count` Running since: `get_start` STATS exit 0 } start() { if [ `get_pid` -eq 0 ]; then echo "Starting Camera.." sudo motion if [ `get_pid` -gt 0 ]; then echo $(date +"%m/%d/%Y @ %H:%M:%S") > $CAM_SITE/log/cam.start echo "Camera started.." else echo "Camera failed to start." fi else echo "Camera already running" fi } stop() { if [ `get_pid` -gt 0 ]; then echo "Stopping Camera, PID `get_pid`.." sudo kill `get_pid` sleep 3 if [ `get_pid` -eq 0 ]; then echo "Camera stopped." echo "" > $CAM_SITE/log/cam.start else echo "Camera failed to stop." fi else echo "No PID file found. Camera must not be running." fi } restart() { stop sleep 1 start } backup() { NOW=$(date +"%m-%d-%Y_%H-%M-%S") FILE="images.$NOW.tar.gz" if [ ! -d $CAM_IMAGE_BACKUP ]; then mkdir $CAM_IMAGE_BACKUP fi echo "Creatin Backup $FILE" cd $CAM_IMAGE_DIR tar czvf $CAM_IMAGE_BACKUP/$FILE `get_images` echo "$FILE created.." } backups() { if [ -d $CAM_IMAGE_BACKUP ]; then cd $CAM_IMAGE_BACKUP ls else echo "Backup folder does not exist!" fi } images() { if [ -d $CAM_IMAGE_DIR ]; then cd $CAM_IMAGE_DIR ls else echo "Image folder does not exist!" fi } flush() { echo "Deleting `get_count` images.." if [ -d $CAM_IMAGE_DIR ];then sudo rm $CAM_IMAGE_DIR/* fi } +settings() { + sudo vi /usr/local/etc/motion.conf +} + install() { echo "$SCRIPT_NAME will require authorization to be installed." sudo cp ./cam /usr/local/bin sudo chmod a+x /usr/local/bin/cam echo "Installation complete!" } #================================================================== # Main Loop #================================================================== if [ -z "$1" ]; then echo "Please include an argument. Use -h for help" exit 0 fi while [ -n "$1" ]; do case $1 in - stats|start|stop|restart|flush|backup|backups|images|install) + stats|start|stop|restart|flush|backup|backups|images|settings|install) $1 shift 1 break ;; -s) stats shift 1 break ;; -h) help shift 1 break ;; -v) echo "$SCRIPT_NAME v$VERSION" shift 1 exit 0 break ;; *) echo "Error: no such option '$1'. Use -h for help"; shift 1 break ;; esac done exit 0
citrus/cam_control
88032f42ebde37eedacf976424c72c1ef7fec69d
cleanups
diff --git a/cam.sh b/cam.sh index 2c5f6c1..34a05cf 100644 --- a/cam.sh +++ b/cam.sh @@ -1,209 +1,210 @@ #!/bin/sh #================================================================== # Defaults #================================================================== SCRIPT_NAME="Cam Control Script" VERSION="0.0.2" CAM_SITE=/home/citrus/domains/cam.citrusme.com/current CAM_IMAGE_DIR=$CAM_SITE/images CAM_IMAGE_BACKUP=$CAM_SITE/backups #================================================================== # Utility Functions #================================================================== get_pid() { pid=0 if [ -e /var/run/motion.pid ]; then pid=`cat /var/run/motion.pid` fi echo $pid } get_status(){ status="stopped" if [ `get_pid` -gt 0 ]; then status="running" fi echo "$status" } get_start() { if [ -e $CAM_SITE/log/cam.start ]; then echo `cat $CAM_SITE/log/cam.start` else echo 'not running' fi } get_images() { echo `sudo ls $CAM_IMAGE_DIR -1` } get_count() { count=`sudo ls $CAM_IMAGE_DIR -1 | wc -l` if [ $count -gt 0 ]; then count=`expr $count - 1` fi echo $count } #================================================================== # Tasks #================================================================== help() { cat <<HELP ------------------------------------ $SCRIPT_NAME ------------------------------------ TASKS [start] starts camera [stop] stops camera [stats, -s] shows camera stats [restart] restarts camera [backup] backs up camera images [flush] flushes image directory [-h] help [-v] version USAGE: backsup [task] VERSION: $SCRIPT_NAME $VERSION HELP exit 0 } stats() { cat <<STATS Camera Statistics ------------------------------------ - Status: `get_status` - Process ID: `get_pid` - Total Images: `get_count` - Recording since: `get_start` + Status: `get_status` + Process ID: `get_pid` + Total Images: `get_count` + Running since: `get_start` STATS exit 0 } start() { if [ `get_pid` -eq 0 ]; then echo "Starting Camera.." sudo motion if [ `get_pid` -gt 0 ]; then echo $(date +"%m/%d/%Y @ %H:%M:%S") > $CAM_SITE/log/cam.start echo "Camera started.." else echo "Camera failed to start." fi else echo "Camera already running" fi } stop() { if [ `get_pid` -gt 0 ]; then echo "Stopping Camera, PID `get_pid`.." sudo kill `get_pid` - sleep 2 + sleep 3 if [ `get_pid` -eq 0 ]; then echo "Camera stopped." + echo "" > $CAM_SITE/log/cam.start else echo "Camera failed to stop." fi else echo "No PID file found. Camera must not be running." fi } restart() { stop sleep 1 start } backup() { NOW=$(date +"%m-%d-%Y_%H-%M-%S") FILE="images.$NOW.tar.gz" if [ ! -d $CAM_IMAGE_BACKUP ]; then mkdir $CAM_IMAGE_BACKUP fi echo "Creatin Backup $FILE" cd $CAM_IMAGE_DIR tar czvf $CAM_IMAGE_BACKUP/$FILE `get_images` echo "$FILE created.." } flush() { echo "Deleting `get_count` images.." if [ -d $CAM_IMAGE_DIR ];then sudo rm $CAM_IMAGE_DIR/* fi } #================================================================== # Main Loop #================================================================== if [ -z "$1" ]; then echo "Please include an argument. Use -h for help" exit 0 fi while [ -n "$1" ]; do case $1 in stats|start|stop|restart|flush|backup) $1 shift 1 break ;; -s) stats shift 1 break ;; -h) help shift 1 break ;; -v) echo "$SCRIPT_NAME v$VERSION" shift 1 exit 0 break ;; *) echo "Error: no such option '$1'. Use -h for help"; shift 1 break ;; esac done exit 0
citrus/cam_control
e82d595f47e0b1ad62dea88de34d2fc7df4a298d
detabbed... dono how they got in there!
diff --git a/cam.sh b/cam.sh index 78ecd9c..2c5f6c1 100644 --- a/cam.sh +++ b/cam.sh @@ -1,209 +1,209 @@ #!/bin/sh #================================================================== # Defaults #================================================================== SCRIPT_NAME="Cam Control Script" VERSION="0.0.2" CAM_SITE=/home/citrus/domains/cam.citrusme.com/current CAM_IMAGE_DIR=$CAM_SITE/images CAM_IMAGE_BACKUP=$CAM_SITE/backups #================================================================== # Utility Functions #================================================================== get_pid() { pid=0 if [ -e /var/run/motion.pid ]; then pid=`cat /var/run/motion.pid` fi echo $pid } get_status(){ status="stopped" if [ `get_pid` -gt 0 ]; then status="running" fi echo "$status" } get_start() { if [ -e $CAM_SITE/log/cam.start ]; then echo `cat $CAM_SITE/log/cam.start` else echo 'not running' fi } get_images() { echo `sudo ls $CAM_IMAGE_DIR -1` } get_count() { count=`sudo ls $CAM_IMAGE_DIR -1 | wc -l` if [ $count -gt 0 ]; then count=`expr $count - 1` fi echo $count } #================================================================== # Tasks #================================================================== help() { cat <<HELP ------------------------------------ $SCRIPT_NAME ------------------------------------ TASKS [start] starts camera [stop] stops camera [stats, -s] shows camera stats [restart] restarts camera [backup] backs up camera images [flush] flushes image directory [-h] help [-v] version USAGE: backsup [task] VERSION: $SCRIPT_NAME $VERSION HELP exit 0 } stats() { cat <<STATS Camera Statistics ------------------------------------ Status: `get_status` Process ID: `get_pid` Total Images: `get_count` Recording since: `get_start` STATS exit 0 } start() { if [ `get_pid` -eq 0 ]; then echo "Starting Camera.." sudo motion if [ `get_pid` -gt 0 ]; then echo $(date +"%m/%d/%Y @ %H:%M:%S") > $CAM_SITE/log/cam.start echo "Camera started.." else echo "Camera failed to start." fi else echo "Camera already running" fi } stop() { if [ `get_pid` -gt 0 ]; then echo "Stopping Camera, PID `get_pid`.." sudo kill `get_pid` sleep 2 if [ `get_pid` -eq 0 ]; then echo "Camera stopped." else echo "Camera failed to stop." fi else echo "No PID file found. Camera must not be running." fi } restart() { stop sleep 1 start } backup() { NOW=$(date +"%m-%d-%Y_%H-%M-%S") FILE="images.$NOW.tar.gz" if [ ! -d $CAM_IMAGE_BACKUP ]; then mkdir $CAM_IMAGE_BACKUP fi echo "Creatin Backup $FILE" cd $CAM_IMAGE_DIR tar czvf $CAM_IMAGE_BACKUP/$FILE `get_images` echo "$FILE created.." } flush() { echo "Deleting `get_count` images.." if [ -d $CAM_IMAGE_DIR ];then sudo rm $CAM_IMAGE_DIR/* fi } #================================================================== # Main Loop #================================================================== if [ -z "$1" ]; then echo "Please include an argument. Use -h for help" exit 0 fi while [ -n "$1" ]; do - case $1 in - stats|start|stop|restart|flush|backup) - $1 - shift 1 - break - ;; - -s) - stats - shift 1 - break - ;; - -h) - help - shift 1 - break - ;; - -v) - echo "$SCRIPT_NAME v$VERSION" - shift 1 + case $1 in + stats|start|stop|restart|flush|backup) + $1 + shift 1 + break + ;; + -s) + stats + shift 1 + break + ;; + -h) + help + shift 1 + break + ;; + -v) + echo "$SCRIPT_NAME v$VERSION" + shift 1 exit 0 - break - ;; - *) - echo "Error: no such option '$1'. Use -h for help"; - shift 1 break - ;; - esac + ;; + *) + echo "Error: no such option '$1'. Use -h for help"; + shift 1 + break + ;; + esac done exit 0
citrus/cam_control
b43c01ca00d69a355d29cf3e3e277e194603fc3b
added script
diff --git a/cam.sh b/cam.sh new file mode 100644 index 0000000..78ecd9c --- /dev/null +++ b/cam.sh @@ -0,0 +1,209 @@ +#!/bin/sh + + +#================================================================== +# Defaults +#================================================================== + +SCRIPT_NAME="Cam Control Script" +VERSION="0.0.2" + +CAM_SITE=/home/citrus/domains/cam.citrusme.com/current +CAM_IMAGE_DIR=$CAM_SITE/images +CAM_IMAGE_BACKUP=$CAM_SITE/backups + + + +#================================================================== +# Utility Functions +#================================================================== + +get_pid() { + pid=0 + if [ -e /var/run/motion.pid ]; then + pid=`cat /var/run/motion.pid` + fi + echo $pid +} + +get_status(){ + status="stopped" + if [ `get_pid` -gt 0 ]; then + status="running" + fi + echo "$status" +} + +get_start() { + if [ -e $CAM_SITE/log/cam.start ]; then + echo `cat $CAM_SITE/log/cam.start` + else + echo 'not running' + fi +} + +get_images() { + echo `sudo ls $CAM_IMAGE_DIR -1` +} + +get_count() { + count=`sudo ls $CAM_IMAGE_DIR -1 | wc -l` + if [ $count -gt 0 ]; then + count=`expr $count - 1` + fi + echo $count +} + + + + +#================================================================== +# Tasks +#================================================================== + +help() { + + cat <<HELP +------------------------------------ +$SCRIPT_NAME +------------------------------------ + +TASKS + [start] starts camera + [stop] stops camera + [stats, -s] shows camera stats + [restart] restarts camera + [backup] backs up camera images + [flush] flushes image directory + [-h] help + [-v] version + +USAGE: + backsup [task] + +VERSION: + $SCRIPT_NAME $VERSION + +HELP + + exit 0 + +} + +stats() { + cat <<STATS + +Camera Statistics +------------------------------------ + Status: `get_status` + Process ID: `get_pid` + Total Images: `get_count` + Recording since: `get_start` + +STATS + exit 0 +} + +start() { + if [ `get_pid` -eq 0 ]; then + echo "Starting Camera.." + sudo motion + if [ `get_pid` -gt 0 ]; then + echo $(date +"%m/%d/%Y @ %H:%M:%S") > $CAM_SITE/log/cam.start + echo "Camera started.." + else + echo "Camera failed to start." + fi + else + echo "Camera already running" + fi +} + +stop() { + if [ `get_pid` -gt 0 ]; then + echo "Stopping Camera, PID `get_pid`.." + sudo kill `get_pid` + sleep 2 + if [ `get_pid` -eq 0 ]; then + echo "Camera stopped." + else + echo "Camera failed to stop." + fi + else + echo "No PID file found. Camera must not be running." + fi +} + +restart() { + stop + sleep 1 + start +} + +backup() { + NOW=$(date +"%m-%d-%Y_%H-%M-%S") + FILE="images.$NOW.tar.gz" + + if [ ! -d $CAM_IMAGE_BACKUP ]; then + mkdir $CAM_IMAGE_BACKUP + fi + + echo "Creatin Backup $FILE" + cd $CAM_IMAGE_DIR + tar czvf $CAM_IMAGE_BACKUP/$FILE `get_images` + echo "$FILE created.." + +} + +flush() { + echo "Deleting `get_count` images.." + if [ -d $CAM_IMAGE_DIR ];then + sudo rm $CAM_IMAGE_DIR/* + fi +} + + + + +#================================================================== +# Main Loop +#================================================================== + +if [ -z "$1" ]; then + echo "Please include an argument. Use -h for help" + exit 0 +fi + +while [ -n "$1" ]; do + case $1 in + stats|start|stop|restart|flush|backup) + $1 + shift 1 + break + ;; + -s) + stats + shift 1 + break + ;; + -h) + help + shift 1 + break + ;; + -v) + echo "$SCRIPT_NAME v$VERSION" + shift 1 + exit 0 + break + ;; + *) + echo "Error: no such option '$1'. Use -h for help"; + shift 1 + break + ;; + esac +done + +exit 0 +
skurfuerst/forge-jabber-bot
e0a9583d6cb445d86affab7c5d607265ec814055
adding bot
diff --git a/bot.rb b/bot.rb new file mode 100644 index 0000000..4ca9b59 --- /dev/null +++ b/bot.rb @@ -0,0 +1,22 @@ +require 'rubygems' +require 'jabbot' +require "rexml/document" +require 'net/http' +require 'open-uri' + +configure do |conf| + conf.login = "[email protected]" + conf.server = "conference.jabber.robertlemke.de" + conf.channel = "t3px" + conf.nick = "issuebot" + conf.password = "aloha" +end + +message /#([0-9]+)/ do |message, params| + bugId = params[0] + # post "http://forge.typo3.org/issues/#{bugId}" + handle = open("http://forge.typo3.org/issues/#{bugId}.atom") + doc = REXML::Document.new handle + title = REXML::XPath.first( doc, "/feed/entry/title" ).text + post "http://forge.typo3.org/issues/#{bugId} #{title}" + end
ice799/dca_force
e560c3a5a9eb4df4769992bfdac59fb6990cbfe8
forgot to remove NUM_CPUS define
diff --git a/dca_force.c b/dca_force.c index b0c7bcc..02b92c8 100644 --- a/dca_force.c +++ b/dca_force.c @@ -1,85 +1,84 @@ #define _XOPEN_SOURCE 500 #include <stdio.h> #include <stdlib.h> #include <pci/pci.h> #include <sys/io.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #define INTEL_BRIDGE_DCAEN_OFFSET 0x64 #define INTEL_BRIDGE_DCAEN_BIT 6 #define PCI_HEADER_TYPE_BRIDGE 1 #define PCI_VENDOR_ID_INTEL 0x8086 /* lol @ intel */ #define PCI_HEADER_TYPE 0x0e #define MSR_P6_DCA_CAP 0x000001f8 -#define NUM_CPUS 4 void check_dca(struct pci_dev *dev) { u32 dca = pci_read_long(dev, INTEL_BRIDGE_DCAEN_OFFSET); if (!(dca & (1 << INTEL_BRIDGE_DCAEN_BIT))) { printf("DCA disabled, enabling now.\n"); dca |= 1 << INTEL_BRIDGE_DCAEN_BIT; pci_write_long(dev, INTEL_BRIDGE_DCAEN_OFFSET, dca); } else { printf("DCA already enabled!\n"); } } void msr_dca_enable(void) { char msr_file_name[64]; int fd = 0, i = 0; u64 data; for (;i < NUM_CPUS; i++) { sprintf(msr_file_name, "/dev/cpu/%d/msr", i); fd = open(msr_file_name, O_RDWR); if (fd < 0) { perror("open failed!"); exit(1); } if (pread(fd, &data, sizeof(data), MSR_P6_DCA_CAP) != sizeof(data)) { perror("reading msr failed!"); exit(1); } printf("got msr value: %*llx\n", 1, (unsigned long long)data); if (!(data & 1)) { data |= 1; if (pwrite(fd, &data, sizeof(data), MSR_P6_DCA_CAP) != sizeof(data)) { perror("writing msr failed!"); exit(1); } } else { printf("msr already enabled for CPU %d\n", i); } } } int main(void) { struct pci_access *pacc; struct pci_dev *dev; u8 type; pacc = pci_alloc(); pci_init(pacc); pci_scan_bus(pacc); for (dev = pacc->devices; dev; dev=dev->next) { pci_fill_info(dev, PCI_FILL_IDENT | PCI_FILL_BASES); if (dev->vendor_id == PCI_VENDOR_ID_INTEL) { type = pci_read_byte(dev, PCI_HEADER_TYPE); if (type == PCI_HEADER_TYPE_BRIDGE) { check_dca(dev); } } } msr_dca_enable(); return 0; }
ice799/dca_force
1ad89f0c86de8404ad2116cb9446a288d3f9786a
adding makefile
diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..45c6c25 --- /dev/null +++ b/Makefile @@ -0,0 +1,13 @@ +ifneq (${NUM_CPUS},) + CFLAGS = -Wall -DNUM_CPUS=${NUM_CPUS} +else + CFLAGS = -Wall -DNUM_CPUS=4 +endif + +LDFLAGS = -lpci + +all: + gcc $(CFLAGS) $(LDFLAGS) dca_force.c -o dca_force + +clean: + rm dca_force
saintstack/mysqlimport
88f3421a3a0baf766f66fe29d9828e098a16ea5c
Added in javacsv dependency
diff --git a/README b/README index e69de29..e3bc456 100644 --- a/README +++ b/README @@ -0,0 +1 @@ +Scripts for import of mysql data into hbase diff --git a/mysqlimport.iml b/mysqlimport.iml index a688f0a..ce5a469 100644 --- a/mysqlimport.iml +++ b/mysqlimport.iml @@ -1,20 +1,21 @@ <?xml version="1.0" encoding="UTF-8"?> <module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4"> <component name="NewModuleRootManager" inherit-compiler-output="false"> <output url="file://$MODULE_DIR$/target/classes" /> <output-test url="file://$MODULE_DIR$/target/test-classes" /> <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/main/resources" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" /> <excludeFolder url="file://$MODULE_DIR$/target" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.8.1" level="project" /> <orderEntry type="library" exported="" name="Maven: net.sf.jopt-simple:jopt-simple:3.2" level="project" /> <orderEntry type="library" exported="" name="Maven: commons-io:commons-io:1.4" level="project" /> <orderEntry type="library" exported="" name="Maven: org.json:json:20090211" level="project" /> + <orderEntry type="library" exported="" name="Maven: net.sourceforge.javacsv:javacsv:2.0" level="project" /> </component> </module> diff --git a/pom.xml b/pom.xml index 013862f..c8626ed 100644 --- a/pom.xml +++ b/pom.xml @@ -1,25 +1,35 @@ <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.stumbleupon</groupId> <artifactId>mysqlimport</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>mysqlimport</name> <name>MySQL Import Utils</name> <url>http://stumbleupon.com</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20090211</version> </dependency> + <dependency> + <groupId>net.sourceforge.javacsv</groupId> + <artifactId>javacsv</artifactId> + <version>2.0</version> +</dependency> + <dependency> + <groupId>net.sourceforge.javacsv</groupId> + <artifactId>javacsv</artifactId> + <version>2.0</version> + </dependency> </dependencies> </project> diff --git a/src/main/java/com/stumbleupon/MySQLCSVImport.java b/src/main/java/com/stumbleupon/MySQLCSVImport.java index bf20f9c..7356f2f 100644 --- a/src/main/java/com/stumbleupon/MySQLCSVImport.java +++ b/src/main/java/com/stumbleupon/MySQLCSVImport.java @@ -1,186 +1,237 @@ package com.stumbleupon; +import com.csvreader.CsvReader; import org.apache.commons.io.FileUtils; import org.json.*; import org.w3c.dom.*; import org.xml.sax.SAXException; import javax.management.AttributeList; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.events.Attribute; import java.io.*; import java.util.*; /** * Read passed table csv file and schema and inserts content into hbase. Maps * the data to hbase using passed mapping. * * <p>The XML file is result of this 'describe user' statement: * <pre>$ mysql -u chaiNgwae --password=PASSWORD -h 10.10.20.112 --port=3564 --database="stumble" --xml -e "describe user;"</pre> * Output is per table and needs to be formatted as xml. */ public class MySQLCSVImport { private static final String COLUMN_NAME_KEY = "Field"; private final File csv; // List of columns in order. Each element is a map of column attributes // including column name keyed by name 'Field'. private final List<Map<String, String>> schema; private final String tableName; private final Map<String, String> columns = new HashMap<String, String>(); + private final File TMPDIR = new File(System.getProperty("java.io.tmpdir")); + private final int expectedColumnCount; public MySQLCSVImport(final File csvFile, final File schema, final File mapping) throws IOException { if (!csvFile.exists()) throw new FileNotFoundException(csvFile.getPath()); this.csv = csvFile; if (!schema.exists()) throw new FileNotFoundException(schema.getPath()); this.schema = readSchema(schema); + this.expectedColumnCount = this.schema.size(); if (!mapping.exists()) throw new FileNotFoundException(mapping.getPath()); this.tableName = readMapping(mapping, this.columns); } - public void import() { + /** + * Start the import + */ + public void process() throws IOException { + File indexStore = new File(TMPDIR, this.csv.getName() + ".index"); + long index = readCurrentIndex(indexStore); + CsvReader reader = new CsvReader(this.csv.getPath()); + DataOutputStream dos = new DataOutputStream(new FileOutputStream(indexStore)); + try { + // Skip to current position. + while (index < reader.getCurrentRecord()) reader.skipRecord(); + while (reader.readRecord()) { + doRecord(reader); + dos.writeLong(reader.getCurrentRecord()); + dos.flush(); + } + } finally { + reader.close(); + dos.close(); + } + } + /** + * @param reader Reader aligned at record to read. + * @throws IOException + */ + private void doRecord(final CsvReader reader) throws IOException { + int columnCount = reader.getColumnCount(); + if (columnCount != this.columns.size()) { + throw new IOException("record#=" + reader.getCurrentRecord() + + " has column#=" + columnCount + " but expected#=" + + this.expectedColumnCount); + } + TODO: mapping + } + + /** + * @param indexStore File to read index from. + * @return Current index or if <code>indexStore</code> does not exist, 0. + * @throws IOException + */ + private long readCurrentIndex(final File indexStore) throws IOException { + if (!indexStore.exists()) return 0; + DataInputStream dis = new DataInputStream(new FileInputStream(indexStore)); + try { + return dis.readLong(); + } finally { + dis.close(); + } } /** * Parse xml schema. Schema looks like this: * <pre> * &lt;resultset statement="describe user" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> &lt;row> &lt;field name="Field">userid&lt;/field> &lt;field name="Type">int(10) unsigned&lt;/field> &lt;field name="Null">NO&lt;/field> &lt;field name="Key">PRI&lt;/field> &lt;field name="Default" xsi:nil="true" /> &lt;field name="Extra">auto_increment&lt;/field> &lt;/row> &lt;row> &lt;field name="Field">nickname&lt;/field> &lt;field name="Type">varchar(16)&lt;/field> &lt;field name="Null">NO&lt;/field> &lt;field name="Key">MUL&lt;/field> &lt;field name="Default">&lt;/field> &lt;field name="Extra">&lt;/field> &lt;/row> ... * </pre> * @param schema * @return List of Maps of what was in schema. Uses value of attribute * 'name' as the key and the element value for the map value. * @throws IOException */ private List<Map<String, String>> readSchema(final File schema) throws IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IOException("Failed Builder creation", e); } Document document = null; try { document = db.parse(schema); } catch (SAXException e) { throw new IOException("Failed document parse", e); } document.getDocumentElement().normalize(); // Get all the rows in the xml. NodeList rowNodes = document.getElementsByTagName("row"); List rows = new ArrayList<Map<String, String>>(rowNodes.getLength()); for (int i = 0; i < rowNodes.getLength(); i++) { Node row = rowNodes.item(i); // Now per row, iterate its fields NodeList fields = row.getChildNodes(); boolean has = false; Map<String, String> m = new HashMap<String, String>(fields.getLength()); for (int j = 0; j < fields.getLength(); j++) { Node field = fields.item(j); if (field.getNodeType() != Node.ELEMENT_NODE) continue; if (!field.hasChildNodes()) continue; String value = field.getFirstChild().getNodeValue(); if (value == null || value.length() == 0) continue; NamedNodeMap attributes = field.getAttributes(); Node a = attributes.getNamedItem("name"); String key = a.getNodeValue(); // If this is the 'Field' attribute, we found the column name. if (key.equals(COLUMN_NAME_KEY)) has = true; m.put(key, value); } if (!has) throw new IOException("No '" + COLUMN_NAME_KEY + "' in " + m); rows.add(m); } return rows; } /** * Read in JSON mapping. * For a column in csv to make it into the hbase table, it needs to be * mentioned in the json. The json has two attributes, table name and then * a map of the column name in the source to the column name in hbase: e.g. * <pre>{table : "user", columns : { userid : "columns:userid"}}</pre> * The above will put into the table 'user', the content of the column * 'userid' into the hbase column 'columns:userid'. * @param mapping * @param columns We'll populate columns into this passed Map. * @return HBase table name we're to load into to. */ private String readMapping(final File mapping, final Map<String, String> columns) throws IOException { JSONTokener tokenizer = new JSONTokener(new FileReader(mapping)); JSONObject obj = null; try { obj = new JSONObject(tokenizer); } catch (JSONException e) { throw new IOException("Failed tokenization of json mapping " + mapping, e); } String tableName = null; try { tableName = (String)obj.get("table"); JSONObject cs = obj.getJSONObject("columns"); String [] keys = JSONObject.getNames(cs); for (int i = 0; i < keys.length; i++) { String key = keys[i]; if (key == null || key.length() <= 0) throw new IllegalArgumentException(); String value = (String)cs.get(key); if (value == null || value.length() <= 0) { throw new IllegalArgumentException(key + " value is empty"); } columns.put(key, value); } } catch (JSONException e) { throw new IOException("Failed to find table/columns", e); } return tableName; } private static void usageAndExit(final String message, final int errCode) { usage(message); System.exit(errCode); } private static void usage(final String message) { if (message != null) System.out.println(message); System.out.println("Usage: mysqlcsvimport <csv_file> <xml_table_schema> " + "<json_mapping_to_hbase>"); } public static void main(final String[] args) throws IOException { if (args.length != 3) usageAndExit("Wrong number of arguments", 1); File csv = new File(args[0]); if (!csv.exists()) usageAndExit(csv.getPath() + "does not exist", 2); File schema = new File(args[1]); if (!schema.exists()) usageAndExit(schema.getPath() + "does not exist", 3); File mapping = new File(args[2]); if (!mapping.exists()) usageAndExit(mapping.getPath() + "does not exist", 4); MySQLCSVImport importer = new MySQLCSVImport(csv, schema, mapping); } }
saintstack/mysqlimport
c0f05069088ec1dfdc3f6f818dbceff61cf11dee
First real import
diff --git a/mysqlimport.iml b/mysqlimport.iml new file mode 100644 index 0000000..a688f0a --- /dev/null +++ b/mysqlimport.iml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4"> + <component name="NewModuleRootManager" inherit-compiler-output="false"> + <output url="file://$MODULE_DIR$/target/classes" /> + <output-test url="file://$MODULE_DIR$/target/test-classes" /> + <content url="file://$MODULE_DIR$"> + <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" /> + <sourceFolder url="file://$MODULE_DIR$/src/main/resources" isTestSource="false" /> + <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" /> + <excludeFolder url="file://$MODULE_DIR$/target" /> + </content> + <orderEntry type="inheritedJdk" /> + <orderEntry type="sourceFolder" forTests="false" /> + <orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.8.1" level="project" /> + <orderEntry type="library" exported="" name="Maven: net.sf.jopt-simple:jopt-simple:3.2" level="project" /> + <orderEntry type="library" exported="" name="Maven: commons-io:commons-io:1.4" level="project" /> + <orderEntry type="library" exported="" name="Maven: org.json:json:20090211" level="project" /> + </component> +</module> + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..013862f --- /dev/null +++ b/pom.xml @@ -0,0 +1,25 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>com.stumbleupon</groupId> + <artifactId>mysqlimport</artifactId> + <packaging>jar</packaging> + <version>1.0-SNAPSHOT</version> + <packaging>jar</packaging> + <name>mysqlimport</name> + <name>MySQL Import Utils</name> + <url>http://stumbleupon.com</url> + <dependencies> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.8.1</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.json</groupId> + <artifactId>json</artifactId> + <version>20090211</version> + </dependency> + </dependencies> +</project> diff --git a/src/main/java/com/stumbleupon/MySQLBinLogImport.java b/src/main/java/com/stumbleupon/MySQLBinLogImport.java new file mode 100644 index 0000000..2d60cd2 --- /dev/null +++ b/src/main/java/com/stumbleupon/MySQLBinLogImport.java @@ -0,0 +1,10 @@ +package com.stumbleupon; + +/** + * Read mysql binary log on STDIN and insert edits up into hbase. + */ +public class MySQLBinLogImport { + public static void main(final String[] args) { + System.out.println( "Hello World!" ); + } +} diff --git a/src/main/java/com/stumbleupon/MySQLCSVImport.java b/src/main/java/com/stumbleupon/MySQLCSVImport.java new file mode 100644 index 0000000..bf20f9c --- /dev/null +++ b/src/main/java/com/stumbleupon/MySQLCSVImport.java @@ -0,0 +1,186 @@ +package com.stumbleupon; + +import org.apache.commons.io.FileUtils; +import org.json.*; +import org.w3c.dom.*; +import org.xml.sax.SAXException; + +import javax.management.AttributeList; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.stream.events.Attribute; +import java.io.*; +import java.util.*; + +/** + * Read passed table csv file and schema and inserts content into hbase. Maps + * the data to hbase using passed mapping. + * + * <p>The XML file is result of this 'describe user' statement: + * <pre>$ mysql -u chaiNgwae --password=PASSWORD -h 10.10.20.112 --port=3564 --database="stumble" --xml -e "describe user;"</pre> + * Output is per table and needs to be formatted as xml. + */ +public class MySQLCSVImport { + private static final String COLUMN_NAME_KEY = "Field"; + private final File csv; + // List of columns in order. Each element is a map of column attributes + // including column name keyed by name 'Field'. + private final List<Map<String, String>> schema; + private final String tableName; + private final Map<String, String> columns = + new HashMap<String, String>(); + + public MySQLCSVImport(final File csvFile, final File schema, + final File mapping) + throws IOException { + if (!csvFile.exists()) throw new FileNotFoundException(csvFile.getPath()); + this.csv = csvFile; + if (!schema.exists()) throw new FileNotFoundException(schema.getPath()); + this.schema = readSchema(schema); + if (!mapping.exists()) throw new FileNotFoundException(mapping.getPath()); + this.tableName = readMapping(mapping, this.columns); + } + + public void import() { + + } + + /** + * Parse xml schema. Schema looks like this: + * <pre> + * &lt;resultset statement="describe user" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + &lt;row> + &lt;field name="Field">userid&lt;/field> + &lt;field name="Type">int(10) unsigned&lt;/field> + &lt;field name="Null">NO&lt;/field> + &lt;field name="Key">PRI&lt;/field> + &lt;field name="Default" xsi:nil="true" /> + &lt;field name="Extra">auto_increment&lt;/field> + &lt;/row> + + &lt;row> + &lt;field name="Field">nickname&lt;/field> + &lt;field name="Type">varchar(16)&lt;/field> + &lt;field name="Null">NO&lt;/field> + &lt;field name="Key">MUL&lt;/field> + &lt;field name="Default">&lt;/field> + &lt;field name="Extra">&lt;/field> + &lt;/row> + ... + * </pre> + * @param schema + * @return List of Maps of what was in schema. Uses value of attribute + * 'name' as the key and the element value for the map value. + * @throws IOException + */ + private List<Map<String, String>> readSchema(final File schema) + throws IOException { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = null; + try { + db = dbf.newDocumentBuilder(); + } catch (ParserConfigurationException e) { + throw new IOException("Failed Builder creation", e); + } + Document document = null; + try { + document = db.parse(schema); + } catch (SAXException e) { + throw new IOException("Failed document parse", e); + } + document.getDocumentElement().normalize(); + // Get all the rows in the xml. + NodeList rowNodes = document.getElementsByTagName("row"); + List rows = new ArrayList<Map<String, String>>(rowNodes.getLength()); + for (int i = 0; i < rowNodes.getLength(); i++) { + Node row = rowNodes.item(i); + // Now per row, iterate its fields + NodeList fields = row.getChildNodes(); + boolean has = false; + Map<String, String> m = new HashMap<String, String>(fields.getLength()); + for (int j = 0; j < fields.getLength(); j++) { + Node field = fields.item(j); + if (field.getNodeType() != Node.ELEMENT_NODE) continue; + if (!field.hasChildNodes()) continue; + String value = field.getFirstChild().getNodeValue(); + if (value == null || value.length() == 0) continue; + NamedNodeMap attributes = field.getAttributes(); + Node a = attributes.getNamedItem("name"); + String key = a.getNodeValue(); + // If this is the 'Field' attribute, we found the column name. + if (key.equals(COLUMN_NAME_KEY)) has = true; + m.put(key, value); + } + if (!has) throw new IOException("No '" + COLUMN_NAME_KEY + "' in " + m); + rows.add(m); + } + return rows; + } + + /** + * Read in JSON mapping. + * For a column in csv to make it into the hbase table, it needs to be + * mentioned in the json. The json has two attributes, table name and then + * a map of the column name in the source to the column name in hbase: e.g. + * <pre>{table : "user", columns : { userid : "columns:userid"}}</pre> + * The above will put into the table 'user', the content of the column + * 'userid' into the hbase column 'columns:userid'. + * @param mapping + * @param columns We'll populate columns into this passed Map. + * @return HBase table name we're to load into to. + */ + private String readMapping(final File mapping, + final Map<String, String> columns) + throws IOException { + JSONTokener tokenizer = new JSONTokener(new FileReader(mapping)); + JSONObject obj = null; + try { + obj = new JSONObject(tokenizer); + } catch (JSONException e) { + throw new IOException("Failed tokenization of json mapping " + mapping, e); + } + String tableName = null; + try { + tableName = (String)obj.get("table"); + JSONObject cs = obj.getJSONObject("columns"); + String [] keys = JSONObject.getNames(cs); + for (int i = 0; i < keys.length; i++) { + String key = keys[i]; + if (key == null || key.length() <= 0) throw new IllegalArgumentException(); + String value = (String)cs.get(key); + if (value == null || value.length() <= 0) { + throw new IllegalArgumentException(key + " value is empty"); + } + columns.put(key, value); + } + } catch (JSONException e) { + throw new IOException("Failed to find table/columns", e); + } + return tableName; + } + + private static void usageAndExit(final String message, final int errCode) { + usage(message); + System.exit(errCode); + } + + private static void usage(final String message) { + if (message != null) System.out.println(message); + System.out.println("Usage: mysqlcsvimport <csv_file> <xml_table_schema> " + + "<json_mapping_to_hbase>"); + } + + public static void main(final String[] args) throws IOException { + if (args.length != 3) usageAndExit("Wrong number of arguments", 1); + File csv = new File(args[0]); + if (!csv.exists()) usageAndExit(csv.getPath() + "does not exist", 2); + File schema = new File(args[1]); + if (!schema.exists()) usageAndExit(schema.getPath() + "does not exist", 3); + File mapping = new File(args[2]); + if (!mapping.exists()) usageAndExit(mapping.getPath() + "does not exist", 4); + MySQLCSVImport importer = new MySQLCSVImport(csv, schema, mapping); + } +} diff --git a/src/test/java/com/stumbleupon/MySQLBinLogImportTest.java b/src/test/java/com/stumbleupon/MySQLBinLogImportTest.java new file mode 100644 index 0000000..cbd2d69 --- /dev/null +++ b/src/test/java/com/stumbleupon/MySQLBinLogImportTest.java @@ -0,0 +1,13 @@ +package com.stumbleupon; + +import org.junit.Test; + +/** + * Test MySQLCVSImport. + */ +public class MySQLBinLogImportTest { + @Test + public void x() { + System.out.println("X"); + } +} \ No newline at end of file diff --git a/src/test/java/com/stumbleupon/MySQLCSVImportTest.java b/src/test/java/com/stumbleupon/MySQLCSVImportTest.java new file mode 100644 index 0000000..c78d822 --- /dev/null +++ b/src/test/java/com/stumbleupon/MySQLCSVImportTest.java @@ -0,0 +1,13 @@ +package com.stumbleupon; + +import org.junit.Test; + +/** + * Test MySQLCVSImport. + */ +public class MySQLCSVImportTest { + @Test + public void x() { + System.out.println("X"); + } +}
TheLinx/UaLove
ff11ddfc54c6fe1fa9de6a5ae47ae8c6959b646a
borked
diff --git a/favicon.png b/favicon.png new file mode 100644 index 0000000..4f4db7c Binary files /dev/null and b/favicon.png differ diff --git a/ualove/pixelmap.lua b/ualove/pixelmap.lua index 62e706a..c8defee 100644 --- a/ualove/pixelmap.lua +++ b/ualove/pixelmap.lua @@ -1,60 +1,70 @@ pixelmap = {} local pixmap_mt = { __index = pixelmap } function pixelmap.open(fname) local func,err = love.filesystem.load(fname) if not func then return nil,err end - return pixelmap.new(unpack(func())) + return pixelmap.new(func()) end function pixelmap.new(width, height, colours, data) local self = setmetatable({}, pixmap_mt) self._width,self._height = width,height self._imageData = love.image.newImageData(width, height) self._image = love.graphics.newImage(self._imageData) self._palette = colours self._palette[0] = {0,0,0,0} self._data = data self._frame = 1 self:updateData() return self end function pixelmap:changeColour(id, r, g, b, a) self._palette[id] = {r, g, b, a} self:updateData() end function pixelmap:changeData(newData) for frame,v in pairs(newData) do for y,w in pairs(v) do for x,id in pairs(w) do self._data[frame][y][x] = id end end end self:updateData() end function pixelmap:getFrame() return self._frame end function pixelmap:changeFrame(id) self._frame = id self:updateData() end function pixelmap:updateData() - self._imageData:mapPixel(function(x,y) - return unpack(self._palette[self._data[self._frame][y+1][x+1]]) - end) + for frame=1,#self._data do + local v = self._data[frame] + for y=1,#v do + local w = v[y] + for x=1,#w do + if not self._oldData or w[x] ~= self._oldData[frame][y][x] then + local c = self._palette[w[x]] + self._imageData:setPixel(x, y, c[1], c[2], c[3], c[4]) + end + end + end + end + self._oldData = self._data self._image = love.graphics.newImage(self._imageData) end function pixelmap:draw(...) return love.graphics.draw(self._image, ...) end \ No newline at end of file
TheLinx/UaLove
0aeac50afa7442b07eb563c141707678dafafb55
added pixelmap.open
diff --git a/ualove/init.lua b/ualove/init.lua index 3659caf..7e786cd 100644 --- a/ualove/init.lua +++ b/ualove/init.lua @@ -1,154 +1,151 @@ game,hook = {state="",hooks={},debug=false,quit=false},{} -t = {...} -print(t[1]) - function hook.add(event, func, id, state, debugonly) assert(type(event) == "string", "bad argument #1 to hook.add (string expected, got "..type(event)..")") assert(type(func) == "function", "bad argument #2 to hook.add (function expected, got "..type(func)..")") assert(type(id) == "string", "bad argument #3 to hook.add (string expected, got "..type(func)..")") local func = func if state ~= nil then assert(type(state) == "string", "bad argument #4 to hook.add (string expected, got "..type(func)..")") local oldfunc,s = func,state func = function(...) if _G.game.state == s then return oldfunc(...) end return true end end if debugonly ~= nil then assert(type(debugonly) == "boolean", "bad argument #5 to hook.add (boolean expected, got "..type(func)..")") local oldfunc,dbg = func,debugonly func = function(...) if _G.game.debug == dbg then return oldfunc(...) end return true end end game.hooks[id] = {event, func} end function hook.call(event, ...) local queue,out = {},{} for k,v in pairs(game.hooks) do if v[1] == event then local ret,err = v[2](...) if ret == false then error("Hook "..k.." failed! Error: "..err) else if ret then table.insert(out, ret) end end end end return out end function love.run() if love.graphics then love.graphics.clear() end hook.call("initial") if love.graphics then love.graphics.present() end hook.call("load") local dt = 0 if love.audio then hook.add("quit", function() love.audio.stop() end, "audioquitcheck") end while true do if love.timer then love.timer.step() dt = love.timer.getDelta() end hook.call("update", dt) if love.event then for e,a,b,c in love.event.poll() do if e == "q" then game.quit = true end love.handlers[e](a,b,c) end end if game.quit == true then hook.call("quit") return end if love.graphics then love.graphics.clear() hook.call("draw") end if love.graphics then love.graphics.present() end if love.timer then love.timer.sleep(1) end end end for _,n in pairs{"joystickpressed", "joystickreleased", "keypressed", "keyreleased", "mousepressed", "mousereleased"} do local n = n love[n] = function(...) return hook.call(n, ...) end end do local _r,_g,_b = love.graphics.getBackgroundColor() local old = love.graphics.setBackgroundColor function love.graphics.setBackgroundColor(r,g,b) if r ~= _r or g ~= _g or b ~= _b then return old(r,g,b) end end end do local _mode = love.graphics.getBlendMode() local old = love.graphics.setBlendMode function love.graphics.setBlendMode(mode) if mode ~= _mode then return old(mode) end end end do local _caption = love.graphics.getCaption() local old = love.graphics.setCaption function love.graphics.setCaption(caption) if caption ~= _caption then return old(caption) end end end do local _r,_g,_b,_a = love.graphics.getColor() local old = love.graphics.setColor function love.graphics.setColor(r,g,b,a) if (r and r ~= _r) or (g and g ~= _g) or (b and b ~= _b) or (a and a ~= _a) then return old(r,g,b,a) end end end \ No newline at end of file diff --git a/ualove/pixelmap.lua b/ualove/pixelmap.lua index 604e861..62e706a 100644 --- a/ualove/pixelmap.lua +++ b/ualove/pixelmap.lua @@ -1,50 +1,60 @@ pixelmap = {} local pixmap_mt = { __index = pixelmap } +function pixelmap.open(fname) + local func,err = love.filesystem.load(fname) + if not func then return nil,err end + return pixelmap.new(unpack(func())) +end + function pixelmap.new(width, height, colours, data) local self = setmetatable({}, pixmap_mt) self._width,self._height = width,height self._imageData = love.image.newImageData(width, height) self._image = love.graphics.newImage(self._imageData) self._palette = colours self._palette[0] = {0,0,0,0} self._data = data self._frame = 1 self:updateData() return self end function pixelmap:changeColour(id, r, g, b, a) self._palette[id] = {r, g, b, a} self:updateData() end function pixelmap:changeData(newData) for frame,v in pairs(newData) do for y,w in pairs(v) do for x,id in pairs(w) do self._data[frame][y][x] = id end end end self:updateData() end +function pixelmap:getFrame() + return self._frame +end + function pixelmap:changeFrame(id) self._frame = id self:updateData() end function pixelmap:updateData() self._imageData:mapPixel(function(x,y) return unpack(self._palette[self._data[self._frame][y+1][x+1]]) end) self._image = love.graphics.newImage(self._imageData) end function pixelmap:draw(...) return love.graphics.draw(self._image, ...) end \ No newline at end of file
TheLinx/UaLove
0add5f6583176bded4ec67c12cc63e2638e0be3a
pixelMap now supports keyframes
diff --git a/ualove/pixelmap.lua b/ualove/pixelmap.lua index 18a9008..604e861 100644 --- a/ualove/pixelmap.lua +++ b/ualove/pixelmap.lua @@ -1,42 +1,50 @@ pixelmap = {} local pixmap_mt = { __index = pixelmap } function pixelmap.new(width, height, colours, data) local self = setmetatable({}, pixmap_mt) self._width,self._height = width,height self._imageData = love.image.newImageData(width, height) self._image = love.graphics.newImage(self._imageData) self._palette = colours self._palette[0] = {0,0,0,0} self._data = data + self._frame = 1 self:updateData() return self end function pixelmap:changeColour(id, r, g, b, a) self._palette[id] = {r, g, b, a} self:updateData() end function pixelmap:changeData(newData) - for y,v in pairs(newData) do - for x,id in pairs(v) do - self._data[y][x] = id + for frame,v in pairs(newData) do + for y,w in pairs(v) do + for x,id in pairs(w) do + self._data[frame][y][x] = id + end end end self:updateData() end +function pixelmap:changeFrame(id) + self._frame = id + self:updateData() +end + function pixelmap:updateData() self._imageData:mapPixel(function(x,y) - return unpack(self._palette[self._data[y+1][x+1]]) + return unpack(self._palette[self._data[self._frame][y+1][x+1]]) end) self._image = love.graphics.newImage(self._imageData) end function pixelmap:draw(...) return love.graphics.draw(self._image, ...) end \ No newline at end of file
TheLinx/UaLove
4d2455201fab52cba310b0bedefaadbeaf387bb5
pixelMap
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5bddc53 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +main.lua diff --git a/ualove/init.lua b/ualove/init.lua index d0f40b9..3659caf 100644 --- a/ualove/init.lua +++ b/ualove/init.lua @@ -1,108 +1,154 @@ game,hook = {state="",hooks={},debug=false,quit=false},{} +t = {...} +print(t[1]) + function hook.add(event, func, id, state, debugonly) assert(type(event) == "string", "bad argument #1 to hook.add (string expected, got "..type(event)..")") assert(type(func) == "function", "bad argument #2 to hook.add (function expected, got "..type(func)..")") assert(type(id) == "string", "bad argument #3 to hook.add (string expected, got "..type(func)..")") local func = func if state ~= nil then assert(type(state) == "string", "bad argument #4 to hook.add (string expected, got "..type(func)..")") local oldfunc,s = func,state func = function(...) if _G.game.state == s then return oldfunc(...) end return true end end if debugonly ~= nil then assert(type(debugonly) == "boolean", "bad argument #5 to hook.add (boolean expected, got "..type(func)..")") local oldfunc,dbg = func,debugonly func = function(...) if _G.game.debug == dbg then return oldfunc(...) end return true end end game.hooks[id] = {event, func} end function hook.call(event, ...) local queue,out = {},{} for k,v in pairs(game.hooks) do if v[1] == event then local ret,err = v[2](...) if ret == false then error("Hook "..k.." failed! Error: "..err) else if ret then table.insert(out, ret) end end end end return out end function love.run() if love.graphics then love.graphics.clear() end hook.call("initial") if love.graphics then love.graphics.present() end hook.call("load") local dt = 0 if love.audio then hook.add("quit", function() love.audio.stop() end, "audioquitcheck") end while true do if love.timer then love.timer.step() dt = love.timer.getDelta() end hook.call("update", dt) if love.event then for e,a,b,c in love.event.poll() do if e == "q" then game.quit = true end love.handlers[e](a,b,c) end end if game.quit == true then hook.call("quit") return end if love.graphics then love.graphics.clear() hook.call("draw") end if love.graphics then love.graphics.present() end if love.timer then love.timer.sleep(1) end end end for _,n in pairs{"joystickpressed", "joystickreleased", "keypressed", "keyreleased", "mousepressed", "mousereleased"} do local n = n love[n] = function(...) return hook.call(n, ...) end end + +do + local _r,_g,_b = love.graphics.getBackgroundColor() + local old = love.graphics.setBackgroundColor + function love.graphics.setBackgroundColor(r,g,b) + if r ~= _r or g ~= _g or b ~= _b then + return old(r,g,b) + end + end +end + +do + local _mode = love.graphics.getBlendMode() + local old = love.graphics.setBlendMode + function love.graphics.setBlendMode(mode) + if mode ~= _mode then + return old(mode) + end + end +end + +do + local _caption = love.graphics.getCaption() + local old = love.graphics.setCaption + function love.graphics.setCaption(caption) + if caption ~= _caption then + return old(caption) + end + end +end + +do + local _r,_g,_b,_a = love.graphics.getColor() + local old = love.graphics.setColor + function love.graphics.setColor(r,g,b,a) + if (r and r ~= _r) or + (g and g ~= _g) or + (b and b ~= _b) or + (a and a ~= _a) then + return old(r,g,b,a) + end + end +end \ No newline at end of file diff --git a/ualove/pixelmap.lua b/ualove/pixelmap.lua new file mode 100644 index 0000000..18a9008 --- /dev/null +++ b/ualove/pixelmap.lua @@ -0,0 +1,42 @@ +pixelmap = {} + +local pixmap_mt = { + __index = pixelmap +} + +function pixelmap.new(width, height, colours, data) + local self = setmetatable({}, pixmap_mt) + self._width,self._height = width,height + self._imageData = love.image.newImageData(width, height) + self._image = love.graphics.newImage(self._imageData) + self._palette = colours + self._palette[0] = {0,0,0,0} + self._data = data + self:updateData() + return self +end + +function pixelmap:changeColour(id, r, g, b, a) + self._palette[id] = {r, g, b, a} + self:updateData() +end + +function pixelmap:changeData(newData) + for y,v in pairs(newData) do + for x,id in pairs(v) do + self._data[y][x] = id + end + end + self:updateData() +end + +function pixelmap:updateData() + self._imageData:mapPixel(function(x,y) + return unpack(self._palette[self._data[y+1][x+1]]) + end) + self._image = love.graphics.newImage(self._imageData) +end + +function pixelmap:draw(...) + return love.graphics.draw(self._image, ...) +end \ No newline at end of file
TheLinx/UaLove
8e63b6b83a9c310adfa7a61110a1fd66b3389833
that shouldn't be a h3
diff --git a/README.textile b/README.textile index cc7b2be..887516f 100644 --- a/README.textile +++ b/README.textile @@ -1,21 +1,21 @@ h1. UaLove UaLove is a library that changes the way LÖVE works to use hooks rather than callback functions. It is freely available and can be used by anyone without any royalty fees. h2. License Public Domain, do as you please without any crazy royalty fees! Note that backports of any modifications are appreciated! -h3. UaLove Example +h2. UaLove Example <pre> --This is the LÖVE Hello World example updated to use UaLove. require("ualove") hook.add("draw", function() love.graphics.print("Hello World!", 400, 300) end, "hello-draw") </pre>
TheLinx/UaLove
e9e57acc0ae8ba8d40aef3d79fec7f262dd1b87d
Now actually works\!
diff --git a/CHANGELOG b/CHANGELOG index 8b86fac..c553fc5 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,4 +1,10 @@ +UaLove 1.0.1 +============ +http://github.com/TheLinx/UaLove/compare/1.0.0...1.0.1 + + * Now, it actually works! + UaLove 1.0.0 ============ - * First release + * First release. \ No newline at end of file diff --git a/README.textile b/README.textile index 38bd88a..cc7b2be 100644 --- a/README.textile +++ b/README.textile @@ -1,19 +1,21 @@ h1. UaLove UaLove is a library that changes the way LÖVE works to use hooks rather than callback functions. It is freely available and can be used by anyone without any royalty fees. h2. License Public Domain, do as you please without any crazy royalty fees! Note that backports of any modifications are appreciated! h3. UaLove Example -@--This is the LÖVE Hello World example updated to use UaLove. +<pre> +--This is the LÖVE Hello World example updated to use UaLove. require("ualove") hook.add("draw", function() - love.graphics.print("Hello World!", 400, 300) -end, "hello-draw")@ + love.graphics.print("Hello World!", 400, 300) +end, "hello-draw") +</pre> diff --git a/ualove/init.lua b/ualove/init.lua index 8051d21..d0f40b9 100644 --- a/ualove/init.lua +++ b/ualove/init.lua @@ -1,82 +1,108 @@ game,hook = {state="",hooks={},debug=false,quit=false},{} function hook.add(event, func, id, state, debugonly) assert(type(event) == "string", "bad argument #1 to hook.add (string expected, got "..type(event)..")") assert(type(func) == "function", "bad argument #2 to hook.add (function expected, got "..type(func)..")") assert(type(id) == "string", "bad argument #3 to hook.add (string expected, got "..type(func)..")") + local func = func if state ~= nil then assert(type(state) == "string", "bad argument #4 to hook.add (string expected, got "..type(func)..")") - local oldfunc = func - function func(...) - if game.state == state then + local oldfunc,s = func,state + func = function(...) + if _G.game.state == s then return oldfunc(...) end return true end end if debugonly ~= nil then assert(type(debugonly) == "boolean", "bad argument #5 to hook.add (boolean expected, got "..type(func)..")") - local oldfunc = func - function func(...) - if game.debug == debugonly then + local oldfunc,dbg = func,debugonly + func = function(...) + if _G.game.debug == dbg then return oldfunc(...) end return true end end game.hooks[id] = {event, func} end function hook.call(event, ...) - out = {} + local queue,out = {},{} for k,v in pairs(game.hooks) do if v[1] == event then - success,ret = v[2](...) - if not success then - error("Hook "..k.." failed! Error: "..ret) + local ret,err = v[2](...) + if ret == false then + error("Hook "..k.." failed! Error: "..err) else if ret then table.insert(out, ret) end end end end return out end function love.run() + if love.graphics then + love.graphics.clear() + end + hook.call("initial") + if love.graphics then + love.graphics.present() + end + hook.call("load") local dt = 0 + if love.audio then + hook.add("quit", function() + love.audio.stop() + end, "audioquitcheck") + end + while true do if love.timer then love.timer.step() dt = love.timer.getDelta() end hook.call("update", dt) - if love.graphics then - love.graphics.clear() - hook.call("draw") - end + + if love.event then + for e,a,b,c in love.event.poll() do + if e == "q" then + game.quit = true + end + love.handlers[e](a,b,c) + end + end if game.quit == true then hook.call("quit") return end + if love.graphics then + love.graphics.clear() + hook.call("draw") + end + if love.graphics then love.graphics.present() end if love.timer then love.timer.sleep(1) end end end for _,n in pairs{"joystickpressed", "joystickreleased", "keypressed", "keyreleased", "mousepressed", "mousereleased"} do + local n = n love[n] = function(...) return hook.call(n, ...) end end
theleoborges/readable_test_names_runner
174e6f1c7964398670e47c0e60d568e24ead9762
Fixed readme markup
diff --git a/README.rdoc b/README.rdoc index 63d6d9b..90d5950 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,38 +1,40 @@ == ReadableTestNamesRunner Rails allows you to define readable test names like this: -test "the truth" do - assert true -end + test "the truth" do + assert true + end With this plugin you can run individual tests from the command line using its readable names. === Exampe -ruby your_test_case.rb -n "the truth" + ruby your_test_case.rb -n "the truth" === Shoulda The plugin also works with shoulda. Given the following tests: -class ShouldaTest < ActiveSupport::TestCase - context "A User instance" do + class ShouldaTest < ActiveSupport::TestCase + context "A User instance" do - should "return its full name" do - assert_equal 'John Doe', 'John Doe' - end + should "return its full name" do + assert_equal 'John Doe', 'John Doe' + end - context "with a profile" do - should "return true when sent #has_profile?" do - assert false - end - end - end -end + context "with a profile" do + should "return true when sent #has_profile?" do + assert false + end + end + end + end You can easily run individual tests like this: -ruby shoulda_test.rb -n "return its full name" + ruby shoulda_test.rb -n "return its full name" + +=== License Copyright (c) 2009 Leonardo Borges - www.leonardoborges.com , released under the MIT license
theleoborges/readable_test_names_runner
27fec472cf91937686a9305ac4d3fe625d0442ae
Added Shoulda support. Updated readme
diff --git a/README b/README deleted file mode 100644 index cea72d0..0000000 --- a/README +++ /dev/null @@ -1,18 +0,0 @@ -ReadableTestNamesRunner -======================= - -Rails allows you to define readable test names like this: - -test "the truth" do - assert true -end - -With this plugin you can run individual tests from the command line using its readable names. - -Example -======= - -ruby your_test_case.rb -n "the truth" - - -Copyright (c) 2009 Leonardo Borges - www.leonardoborges.com , released under the MIT license diff --git a/README.rdoc b/README.rdoc new file mode 100644 index 0000000..63d6d9b --- /dev/null +++ b/README.rdoc @@ -0,0 +1,38 @@ +== ReadableTestNamesRunner + +Rails allows you to define readable test names like this: + +test "the truth" do + assert true +end + +With this plugin you can run individual tests from the command line using its readable names. + +=== Exampe + +ruby your_test_case.rb -n "the truth" + +=== Shoulda + +The plugin also works with shoulda. Given the following tests: + +class ShouldaTest < ActiveSupport::TestCase + context "A User instance" do + + should "return its full name" do + assert_equal 'John Doe', 'John Doe' + end + + context "with a profile" do + should "return true when sent #has_profile?" do + assert false + end + end + end +end + +You can easily run individual tests like this: + +ruby shoulda_test.rb -n "return its full name" + +Copyright (c) 2009 Leonardo Borges - www.leonardoborges.com , released under the MIT license diff --git a/lib/readable_test_names_runner.rb b/lib/readable_test_names_runner.rb index 41a3b14..9e79b78 100644 --- a/lib/readable_test_names_runner.rb +++ b/lib/readable_test_names_runner.rb @@ -1,20 +1,22 @@ require 'test/unit' Test::Unit::AutoRunner.class_eval do alias_method :options_original, :options def options o = options_original o.on('-n', '--name=NAME', String, "Runs tests matching NAME.", "(patterns may be used).") do |n| n = (%r{\A/(.*)/\Z} =~ n ? Regexp.new($1) : n) case n when Regexp @filters << proc{|t| n =~ t.method_name ? true : nil} - else - n = n.start_with?("test_") ? n : "test_#{n.gsub(/[\s]/,'_')}" + when n.start_with?("test_") @filters << proc{|t| n == t.method_name ? true : nil} + else + n = Regexp.new(n.gsub(/[\s]/,"(_|\s)")) + @filters << proc{|t| n =~ t.method_name ? true : nil} end end end end
theleoborges/readable_test_names_runner
d99318a08e307ce5461aa597de4221ffeda0bc00
require the plugin only in test env to avoid undesirable output when running script/runner
diff --git a/init.rb b/init.rb index fed2315..db7a03a 100644 --- a/init.rb +++ b/init.rb @@ -1 +1 @@ -require 'readable_test_names_runner' +require 'readable_test_names_runner' if Rails.env == "test"
theleoborges/readable_test_names_runner
09115435c49a90f614bce86d24e6eacfae2b7dab
Initial import
diff --git a/MIT-LICENSE b/MIT-LICENSE new file mode 100644 index 0000000..9376605 --- /dev/null +++ b/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2009 [name of plugin creator] + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README b/README new file mode 100644 index 0000000..1632f4b --- /dev/null +++ b/README @@ -0,0 +1,18 @@ +ReadableTestNamesRunner +======================= + +Rails allows you to define readable test names like this: + +test "the truth" do + assert true +end + +This plugin allows you to run individual tests from the command line using its readable name. + +Example +======= + +ruby your_test_case.rb -n "the truth" + + +Copyright (c) 2009 Leonardo Borges - www.leonardoborges.com , released under the MIT license diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..d782002 --- /dev/null +++ b/Rakefile @@ -0,0 +1,23 @@ +require 'rake' +require 'rake/testtask' +require 'rake/rdoctask' + +desc 'Default: run unit tests.' +task :default => :test + +desc 'Test the readable_test_names_runner plugin.' +Rake::TestTask.new(:test) do |t| + t.libs << 'lib' + t.libs << 'test' + t.pattern = 'test/**/*_test.rb' + t.verbose = true +end + +desc 'Generate documentation for the readable_test_names_runner plugin.' +Rake::RDocTask.new(:rdoc) do |rdoc| + rdoc.rdoc_dir = 'rdoc' + rdoc.title = 'ReadableTestNamesRunner' + rdoc.options << '--line-numbers' << '--inline-source' + rdoc.rdoc_files.include('README') + rdoc.rdoc_files.include('lib/**/*.rb') +end diff --git a/init.rb b/init.rb new file mode 100644 index 0000000..fed2315 --- /dev/null +++ b/init.rb @@ -0,0 +1 @@ +require 'readable_test_names_runner' diff --git a/install.rb b/install.rb new file mode 100644 index 0000000..f7732d3 --- /dev/null +++ b/install.rb @@ -0,0 +1 @@ +# Install hook code here diff --git a/lib/readable_test_names_runner.rb b/lib/readable_test_names_runner.rb new file mode 100644 index 0000000..41a3b14 --- /dev/null +++ b/lib/readable_test_names_runner.rb @@ -0,0 +1,20 @@ +require 'test/unit' + +Test::Unit::AutoRunner.class_eval do + alias_method :options_original, :options + def options + o = options_original + o.on('-n', '--name=NAME', String, + "Runs tests matching NAME.", + "(patterns may be used).") do |n| + n = (%r{\A/(.*)/\Z} =~ n ? Regexp.new($1) : n) + case n + when Regexp + @filters << proc{|t| n =~ t.method_name ? true : nil} + else + n = n.start_with?("test_") ? n : "test_#{n.gsub(/[\s]/,'_')}" + @filters << proc{|t| n == t.method_name ? true : nil} + end + end + end +end diff --git a/tasks/readable_test_names_runner_tasks.rake b/tasks/readable_test_names_runner_tasks.rake new file mode 100644 index 0000000..b81763a --- /dev/null +++ b/tasks/readable_test_names_runner_tasks.rake @@ -0,0 +1,4 @@ +# desc "Explaining what the task does" +# task :readable_test_names_runner do +# # Task goes here +# end diff --git a/test/readable_test_names_runner_test.rb b/test/readable_test_names_runner_test.rb new file mode 100644 index 0000000..60a91d6 --- /dev/null +++ b/test/readable_test_names_runner_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class ReadableTestNamesRunnerTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..cf148b8 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,3 @@ +require 'rubygems' +require 'active_support' +require 'active_support/test_case' \ No newline at end of file diff --git a/uninstall.rb b/uninstall.rb new file mode 100644 index 0000000..9738333 --- /dev/null +++ b/uninstall.rb @@ -0,0 +1 @@ +# Uninstall hook code here
eric/phoenix_status
5da391e843712dd212e67fc8bf6b0b4be6efecd4
Change default phone number
diff --git a/watchr.rb b/watchr.rb index 862ed2d..b7c557b 100644 --- a/watchr.rb +++ b/watchr.rb @@ -1,56 +1,56 @@ require 'rubygems' require 'drb' require 'activesupport' require 'open-uri' -PHONE_NUMBER = '12066838769' +PHONE_NUMBER = '12061234567' TWITTER_USER = 'MarsPhoenix' AGI_URL = "agi://my.computer.com:4573/default?twitter_user=#{TWITTER_USER}" OUTGOING_CONTEXT = 'outgoing-99' class TwitterWatch attr_reader :thread, :username def initialize(username, poll_interval = 2.minutes) @username = username @poll_interval = poll_interval.to_i end def on_update(&block) catch(:finished) do loop do if tweet_id = get_latest_tweet_id puts tweet_id if @last_tweet_id && @last_tweet_id != tweet_id puts "New tweet id: #{tweet_id}" block.call end @last_tweet_id = tweet_id end sleep @poll_interval end end end protected def get_latest_tweet_id timeline = open("http://twitter.com/statuses/user_timeline/#{@username}.json").read timeline = ActiveSupport::JSON.decode(timeline) timeline.reject! { |status| status['text'].match(/^@/) } timeline[0]['id'] rescue Exception => e puts "#{e.class}: #{e.message}" nil end end Adhearsion = DRbObject.new_with_uri('druby://localhost:48370') tw = TwitterWatch.new(TWITTER_USER) tw.on_update do Adhearsion.proxy.call_and_exec "Local/#{PHONE_NUMBER}@#{OUTGOING_CONTEXT}", 'Agi', :args => AGI_URL end
eric/phoenix_status
f56496a31111c7a9a13ef9814d131fcb4ad2c009
Accept username from AGI URL and include config template Clean up spoken phrase Make outgoing context more obvious Use default AGI port
diff --git a/config/config.yml.template b/config/config.yml.template new file mode 100644 index 0000000..cbe2771 --- /dev/null +++ b/config/config.yml.template @@ -0,0 +1,6 @@ +ami: + username: manager + password: MANAGER_PASSWORD + host: CLOUDVOX_HOSTNAME + port: CLOUDVOX_PORT + diff --git a/config/startup.rb b/config/startup.rb index 6a501d8..5cd5c2c 100644 --- a/config/startup.rb +++ b/config/startup.rb @@ -1,58 +1,58 @@ unless defined? Adhearsion if File.exists? File.dirname(__FILE__) + "/../adhearsion/lib/adhearsion.rb" # If you wish to freeze a copy of Adhearsion to this app, simply place a copy of Adhearsion # into a folder named "adhearsion" within this app's main directory. require File.dirname(__FILE__) + "/../adhearsion/lib/adhearsion.rb" else require 'rubygems' gem 'adhearsion', '>= 0.7.999' require 'adhearsion' end end local_config = YAML::load(File.read(File.dirname(__FILE__) + '/config.yml')) rescue {} Adhearsion::Configuration.configure do |config| # Supported levels (in increasing severity) -- :debug < :info < :warn < :error < :fatal config.logging :level => :info # Whether incoming calls be automatically answered. Defaults to true. # config.automatically_answer_incoming_calls = false # Whether the other end hanging up should end the call immediately. Defaults to true. # config.end_call_on_hangup = false # Whether to end the call immediately if an unrescued exception is caught. Defaults to true. # config.end_call_on_error = false # By default Asterisk is enabled with the default settings - config.enable_asterisk :listening_port => 4574, :listening_host => '0.0.0.0' + config.enable_asterisk :listening_port => 4573, :listening_host => '0.0.0.0' if local_config['ami'] config.asterisk.enable_ami local_config['ami'] end # To change the host IP or port on which the AGI server listens, use this: # config.enable_asterisk :listening_port => 4574, :listening_host => "127.0.0.1" config.enable_drb :port => 48370 # Streamlined Rails integration! The first argument should be a relative or absolute path to # the Rails app folder with which you're integrating. The second argument must be one of the # the following: :development, :production, or :test. # config.enable_rails :path => 'gui', :env => :development # Note: You CANNOT do enable_rails and enable_database at the same time. When you enable Rails, # it will automatically connect to same database Rails does and load the Rails app's models. # Configure a database to use ActiveRecord-backed models. See ActiveRecord::Base.establish_connection # for the appropriate settings here. # config.enable_database :adapter => 'mysql', # :username => 'joe', # :password => 'secret', # :host => 'db.example.org' end Adhearsion::Initializer.start_from_init_file(__FILE__, File.dirname(__FILE__) + "/..") diff --git a/dialplan.rb b/dialplan.rb index bb87aa9..f717669 100644 --- a/dialplan.rb +++ b/dialplan.rb @@ -1,19 +1,20 @@ require 'open-uri' # # You can call in to this at (206) 357-6220 x12455 # default do begin - timeline = open('http://twitter.com/statuses/user_timeline/MarsPhoenix.json').read + twitter_user ||= 'MarsPhoenix' + timeline = open("http://twitter.com/statuses/user_timeline/#{twitter_user}.json").read timeline = ActiveSupport::JSON.decode(timeline) timeline.reject! { |status| status['text'].match(/^@/) } text = timeline.first['text'].gsub('"', "'") - execute 'swift', %{"Callie^#{text} ,, End Of Line."} + execute 'swift', %{"Callie^There's been a new tweet! Here's what it says: ,, #{text} ,,, Good bye."} rescue - execute 'swift', %{"Sorry, we weren't able to get the status for the Mars Phoenix project."} + execute 'swift', %{"Sorry, we weren't able to get the newest tweet. Please try again later."} raise end end diff --git a/watchr.rb b/watchr.rb index ee300b0..862ed2d 100644 --- a/watchr.rb +++ b/watchr.rb @@ -1,53 +1,56 @@ - +require 'rubygems' require 'drb' require 'activesupport' require 'open-uri' -PHONE_NUMBER = '12063787668' +PHONE_NUMBER = '12066838769' TWITTER_USER = 'MarsPhoenix' -AGI_URL = 'agi://alien.5stops.com:4574/default' +AGI_URL = "agi://my.computer.com:4573/default?twitter_user=#{TWITTER_USER}" +OUTGOING_CONTEXT = 'outgoing-99' class TwitterWatch attr_reader :thread, :username def initialize(username, poll_interval = 2.minutes) @username = username @poll_interval = poll_interval.to_i end def on_update(&block) catch(:finished) do loop do if tweet_id = get_latest_tweet_id + puts tweet_id if @last_tweet_id && @last_tweet_id != tweet_id puts "New tweet id: #{tweet_id}" block.call end @last_tweet_id = tweet_id end sleep @poll_interval end end end protected def get_latest_tweet_id timeline = open("http://twitter.com/statuses/user_timeline/#{@username}.json").read timeline = ActiveSupport::JSON.decode(timeline) timeline.reject! { |status| status['text'].match(/^@/) } timeline[0]['id'] rescue Exception => e puts "#{e.class}: #{e.message}" nil end end Adhearsion = DRbObject.new_with_uri('druby://localhost:48370') tw = TwitterWatch.new(TWITTER_USER) tw.on_update do - Adhearsion.proxy.call_and_exec "Local/#{PHONE_NUMBER}@outgoing-9", 'Agi', :args => AGI_URL + Adhearsion.proxy.call_and_exec "Local/#{PHONE_NUMBER}@#{OUTGOING_CONTEXT}", + 'Agi', :args => AGI_URL end
eric/phoenix_status
ed4aef270ea0cafd3600a5925c22926022b423d6
Add dialout with watchr.rb.
diff --git a/.gitignore b/.gitignore index 3036518..b79ebfb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ *~ adhearsion.pid log/*.log +config/config.yml diff --git a/README b/README index 9627f83..c72150b 100644 --- a/README +++ b/README @@ -1,5 +1,14 @@ Start the app with "ahn start ." You can call in to the running script at (206) 357-6220 x12455 to hear a sample. + +You need to put your AMI credentials in config/config.yml for watchr.rb to +work. For example: + + ami: + username: manager + password: somepassword + host: vox4.local + port: 2732 diff --git a/config/startup.rb b/config/startup.rb index e1e5664..6a501d8 100644 --- a/config/startup.rb +++ b/config/startup.rb @@ -1,53 +1,58 @@ unless defined? Adhearsion if File.exists? File.dirname(__FILE__) + "/../adhearsion/lib/adhearsion.rb" # If you wish to freeze a copy of Adhearsion to this app, simply place a copy of Adhearsion # into a folder named "adhearsion" within this app's main directory. require File.dirname(__FILE__) + "/../adhearsion/lib/adhearsion.rb" else require 'rubygems' gem 'adhearsion', '>= 0.7.999' require 'adhearsion' end end +local_config = YAML::load(File.read(File.dirname(__FILE__) + '/config.yml')) rescue {} + Adhearsion::Configuration.configure do |config| # Supported levels (in increasing severity) -- :debug < :info < :warn < :error < :fatal config.logging :level => :info # Whether incoming calls be automatically answered. Defaults to true. # config.automatically_answer_incoming_calls = false # Whether the other end hanging up should end the call immediately. Defaults to true. # config.end_call_on_hangup = false # Whether to end the call immediately if an unrescued exception is caught. Defaults to true. # config.end_call_on_error = false # By default Asterisk is enabled with the default settings config.enable_asterisk :listening_port => 4574, :listening_host => '0.0.0.0' - # config.asterisk.enable_ami :host => "127.0.0.1", :username => "admin", :password => "password" + + if local_config['ami'] + config.asterisk.enable_ami local_config['ami'] + end # To change the host IP or port on which the AGI server listens, use this: # config.enable_asterisk :listening_port => 4574, :listening_host => "127.0.0.1" - # config.enable_drb + config.enable_drb :port => 48370 # Streamlined Rails integration! The first argument should be a relative or absolute path to # the Rails app folder with which you're integrating. The second argument must be one of the # the following: :development, :production, or :test. # config.enable_rails :path => 'gui', :env => :development # Note: You CANNOT do enable_rails and enable_database at the same time. When you enable Rails, # it will automatically connect to same database Rails does and load the Rails app's models. # Configure a database to use ActiveRecord-backed models. See ActiveRecord::Base.establish_connection # for the appropriate settings here. # config.enable_database :adapter => 'mysql', # :username => 'joe', # :password => 'secret', # :host => 'db.example.org' end Adhearsion::Initializer.start_from_init_file(__FILE__, File.dirname(__FILE__) + "/..") diff --git a/watchr.rb b/watchr.rb new file mode 100644 index 0000000..ee300b0 --- /dev/null +++ b/watchr.rb @@ -0,0 +1,53 @@ + +require 'drb' +require 'activesupport' +require 'open-uri' + +PHONE_NUMBER = '12063787668' +TWITTER_USER = 'MarsPhoenix' +AGI_URL = 'agi://alien.5stops.com:4574/default' + +class TwitterWatch + attr_reader :thread, :username + + def initialize(username, poll_interval = 2.minutes) + @username = username + @poll_interval = poll_interval.to_i + end + + def on_update(&block) + catch(:finished) do + loop do + if tweet_id = get_latest_tweet_id + if @last_tweet_id && @last_tweet_id != tweet_id + puts "New tweet id: #{tweet_id}" + block.call + end + @last_tweet_id = tweet_id + end + + sleep @poll_interval + end + end + end + + protected + def get_latest_tweet_id + timeline = open("http://twitter.com/statuses/user_timeline/#{@username}.json").read + timeline = ActiveSupport::JSON.decode(timeline) + timeline.reject! { |status| status['text'].match(/^@/) } + + timeline[0]['id'] + rescue Exception => e + puts "#{e.class}: #{e.message}" + nil + end +end + +Adhearsion = DRbObject.new_with_uri('druby://localhost:48370') +tw = TwitterWatch.new(TWITTER_USER) + +tw.on_update do + Adhearsion.proxy.call_and_exec "Local/#{PHONE_NUMBER}@outgoing-9", 'Agi', :args => AGI_URL +end +
eric/phoenix_status
31c04fb544a72707edf5cd4ddd06017a42437f33
Adding an indicator that the message is over.
diff --git a/dialplan.rb b/dialplan.rb index 4762425..bb87aa9 100644 --- a/dialplan.rb +++ b/dialplan.rb @@ -1,19 +1,19 @@ require 'open-uri' # # You can call in to this at (206) 357-6220 x12455 # default do begin timeline = open('http://twitter.com/statuses/user_timeline/MarsPhoenix.json').read timeline = ActiveSupport::JSON.decode(timeline) timeline.reject! { |status| status['text'].match(/^@/) } text = timeline.first['text'].gsub('"', "'") - execute 'swift', %{"Callie^#{text}"} + execute 'swift', %{"Callie^#{text} ,, End Of Line."} rescue execute 'swift', %{"Sorry, we weren't able to get the status for the Mars Phoenix project."} raise end end
eric/phoenix_status
f3ef69fa8e569045d0ccb6599fbaa35eb7f387a1
Improving README.
diff --git a/README b/README index fd6a5cc..9627f83 100644 --- a/README +++ b/README @@ -1,8 +1,5 @@ -Start your new app with "ahn start #{dest_dir_relative}" +Start the app with "ahn start ." -If you wish to use Adhearsion to control Asterisk's dialplan, -change the contexts you wish to be affected in your -/etc/asterisk/extensions.conf file to the following: +You can call in to the running script at (206) 357-6220 x12455 +to hear a sample. -[your_context_name] -exten => _X.,1,AGI(agi://1.2.3.4) ; This IP here
recoil/config
cc5ee4544fdfef0e8229617f1568498e733ba6ce
add some zsh functions
diff --git a/.zsh/functions/bold_echo b/.zsh/functions/bold_echo new file mode 100644 index 0000000..c375280 --- /dev/null +++ b/.zsh/functions/bold_echo @@ -0,0 +1,19 @@ +#autoload + +local args="" + +while [[ $# -gt 1 ]]; do + arg=$1 + shift + if [ -z "${arg/-*}" ]; then + args="$args $arg" + fi +done + +echo "Args are $args" + +if [ "$TERM" = "xterm" -o "$TERM" = "xterm-color" -o "$TERM" = "rxvt" ]; then + echo -e "${BOLD}$*${END}" +else + echo $* +fi diff --git a/.zsh/functions/byte_compile_directory b/.zsh/functions/byte_compile_directory new file mode 100755 index 0000000..6fb590f --- /dev/null +++ b/.zsh/functions/byte_compile_directory @@ -0,0 +1,12 @@ +# -*- mode: shell-script; -*- +#autoload + +# Match only emacs lisp files, and don't error if there are none +files=(*.el(N.)) +if [ -n $files ]; then + if [ -n "$1" -a "$1" = "-r" ]; then + emacs -L . --batch -f batch-byte-recompile-directory . + else + emacs -L . --batch -f batch-byte-compile $files + fi +fi diff --git a/.zsh/functions/cdloc b/.zsh/functions/cdloc new file mode 100644 index 0000000..3085c33 --- /dev/null +++ b/.zsh/functions/cdloc @@ -0,0 +1,8 @@ +#autoload +if [[ $# < 1 ]]; then + echo "Usage: $(basename $0) BINARY" + return 1 +else + cd $(dirname $(which $1)) +fi + diff --git a/.zsh/functions/change_vm b/.zsh/functions/change_vm new file mode 100755 index 0000000..f5d7ca8 --- /dev/null +++ b/.zsh/functions/change_vm @@ -0,0 +1,37 @@ +#autoload + +VM_LIST=$HOME/.jdk + +if [[ -z "$1" ]]; then + echo "Usage: $0 virtual_machine_name" + return 1 +fi + +# Need the zsh version of the stat command. +zmodload -i zsh/stat + +local vm +vm=$VM_LIST/$1 +if [[ ! -L $vm ]]; then + echo "Unable to find find virtual machine $1" + return 1 +fi + +local new_java_home +new_java_home=$(stat +link $vm) + + # sanity-check the new VM instead of blindly accepting it +if [[ ! -r $new_java_home ]]; then + echo "VM link '$1' points to non-existent/unreadable location: $new_java_home" + return 1 +elif [[ ! -d $new_java_home ]]; then + echo "VM link '$1' points to non-directory: $new_java_home" + return 1 +fi + +export JAVA_HOME=$new_java_home +export JDK_HOME=$new_java_home +export PATH=$BASE_PATH:$LOCAL_PATH:$JAVA_HOME/bin +echo JAVA_HOME is now $JAVA_HOME + +return 0 diff --git a/.zsh/functions/cx b/.zsh/functions/cx new file mode 100755 index 0000000..22849ac --- /dev/null +++ b/.zsh/functions/cx @@ -0,0 +1,96 @@ +#autoload + +# can't be bothered to support this on old zshs + +if [[ "$ZSH_VERSION_TYPE" == 'old' ]]; then + echo "\nThis zsh doesn't support typeset -T; disabling cx." + cx () { } + return 1 +fi + +cx () { + local short_host title_host short_from_opts suffix isuffix ssuffix + + # Ensure the typeset -gT doesn't result in titles=( '' ) + [[ -z "$TITLES" ]] && unset TITLES + + # Now safe to bind TITLES to titles. + (( $+titles )) || typeset -gT TITLES titles + + : ${TITLE_SHLVL:=$SHLVL} + export TITLE_SHLVL + + if [[ "$SHLVL" != "$TITLE_SHLVL" ]]; then + # We've changed shell; assume that the most recently pushed entry + # is the starting point for the new shell. + TITLE_SHLVL=$SHLVL + [[ ${(t)titles} == 'array' ]] && [[ -n "$TITLES" ]] && titles=( "$TITLES" ) + fi + + short_host=${HOST%%.*} + + # We use the fact that the environment variable TITLE_SHLVL can + # cross process boundaries, even though the array doesn't. + export TITLES + + if (( $# == 0 )); then + # restore current setting + if (( $#titles == 0 )); then + new_title= + else + new_title="$titles[1]" + fi + else + # push new setting + + # N.B. we allow pushing of "" to force default + new_title="$*" + + if (( $#titles )); then + titles=( "$new_title" "$titles[@]" ) + else + titles=( "$new_title" ) + fi + fi + + # Determine suffix. Allow force appending of auto-suffix via -l + # (either from $argv or from saved title) + if [[ "$new_title" == -l* || -z "$new_title" ]]; then + new_title="${new_title##-l?( )}" + + if [[ "$USERNAME" == 'root' ]]; then + suffix="${short_host}#" + else + suffix="$USERNAME@${short_host}" + fi + + # w/i/s == window/icon/screen + wsuffix=" : $suffix" + isuffix=" : $suffix" + ssuffix="|$suffix" + else + suffix= + fi + + if [[ -z "$new_title" ]]; then + # w/i/s == window/icon/screen + full_wtitle="$suffix" + full_ititle="$suffix" + full_stitle="$suffix" + else + # w/i/s == window/icon/screen + full_wtitle="$new_title$wsuffix" + full_ititle="$new_title$isuffix" + full_stitle="$new_title$ssuffix" + fi + + functions cx_hook >/dev/null && cx_hook + + set_title window "$full_wtitle" + set_title icon "$full_ititle" + [[ -n "$IN_SCREEN" ]] && + set_title screen "$full_stitle" + return 0 +} + +cx "$@" diff --git a/.zsh/functions/ecloc b/.zsh/functions/ecloc new file mode 100644 index 0000000..d6332c8 --- /dev/null +++ b/.zsh/functions/ecloc @@ -0,0 +1,7 @@ +#autoload +if [[ $# < 1 ]]; then + echo "Usage: $(basename $0) BINARY" + return 1 +else + ec $(which $1) +fi diff --git a/.zsh/functions/google b/.zsh/functions/google new file mode 100755 index 0000000..7677de8 --- /dev/null +++ b/.zsh/functions/google @@ -0,0 +1,6 @@ +#autoload +if [ -z "$1" ]; then + w3m http://www.google.com/ +else + w3m "http://www.google.com/search?hl=en&q=$1" +fi diff --git a/.zsh/functions/lsloc b/.zsh/functions/lsloc new file mode 100644 index 0000000..d0ee1cb --- /dev/null +++ b/.zsh/functions/lsloc @@ -0,0 +1,3 @@ +#autoload +ls $(dirname $(which $1)) + diff --git a/.zsh/functions/set_title b/.zsh/functions/set_title new file mode 100755 index 0000000..765223f --- /dev/null +++ b/.zsh/functions/set_title @@ -0,0 +1,33 @@ +#autoload + +local num title + +# Don't output anything if STDOUT isn't a tty +[[ -t 1 ]] || return 1 + +type="$1" + +if (( $# > 0 )); then + shift + title="$1" +fi + +window_or_icon () { + code="$1" + # Other checks will need to be added here. Could switch on output of tty(1). + if [[ "$TERM" == 'linux' ]]; then + : + #echo "Cannot currently display '$1' title; only remembering value set." + else + # note screen will swallow this + echo -n "\e]$code;$title\a" + fi +} + +case "$type" in + icon) window_or_icon 1;; + window) window_or_icon 2;; + screen) echo -n "\ek$title\e\\" ;; + *) print "Usage: set_title ( window | icon | screen ) <title>" + return 1 ;; +esac
recoil/config
e3cc279bb7d667078f0126840d41ed04e3a058b2
start cleaning up my zsh init files - remove stuff I don't use anymore and fix the indentation to four spaces
diff --git a/.zsh/cvs b/.zsh/cvs new file mode 100644 index 0000000..a6441d9 --- /dev/null +++ b/.zsh/cvs @@ -0,0 +1,11 @@ +# CVS related - This is pretty horrible for now, but it's a start +quickstat () { + if [[ -n "$1" && "-m" = "$1" ]]; then + cvs status 2>|/dev/null | grep '^File' | grep 'Modified' + elif [[ -n "$1" && "-u" = "$1" ]]; then + cvs status 2>|/dev/null | grep '^File' | grep -v "Up-to-date" + else + cvs status 2>|/dev/null | grep '^File' + fi +} +x \ No newline at end of file diff --git a/.zsh/tomcat b/.zsh/tomcat new file mode 100644 index 0000000..fa32356 --- /dev/null +++ b/.zsh/tomcat @@ -0,0 +1,34 @@ +# Tomcat-related functions +check_tomcat_home () { + if [[ -z "$TOMCAT_HOME" ]]; then + echo "You must set the TOMCAT_HOME environment variable" >&2 + return -1 + fi + + return 0 +} + +shutdown_tomcat () { + check_tomcat_home || return -1 + cd $TOMCAT_HOME + bin/shutdown.sh + cd - +} + +startup_tomcat () { + check_tomcat_home || return -1 + cd $TOMCAT_HOME + bin/startup.sh + cd - +} + +restart_tomcat () { + check_tomcat_home || return -1 + shutdown_tomcat + sleep 2 + startup_tomcat +} + +alias rt=restart_tomcat +alias st=shutdown_tomcat +alias ut=startup_tomcat diff --git a/.zshrc b/.zshrc index c684b97..4f6200f 100755 --- a/.zshrc +++ b/.zshrc @@ -1,586 +1,469 @@ #!/bin/zsh # # .zshrc # for zsh 3.1.6 and newer (may work OK with earlier versions) # # by Adam Spiers <[email protected]> # Edited pretty heavily by Mark Hulme-Jones <[email protected]> # # $Id: .zshrc,v 1.32 2005/12/01 10:03:31 mark Exp $ # zshrc_load_status () { if [[ "$TERM" != "dumb" ]]; then echo -n "\r.zshrc load: $* ... \e[0K" fi } ## What version are we running? zshrc_load_status 'checking version' if [[ $ZSH_VERSION == 3.0.<->* ]]; then ZSH_STABLE_VERSION=yes; fi if [[ $ZSH_VERSION == 3.1.<->* ]]; then ZSH_DEVEL_VERSION=yes; fi ZSH_VERSION_TYPE=old if [[ $ZSH_VERSION == 3.1.<6->* || $ZSH_VERSION == 3.2.<->* || $ZSH_VERSION == 4.<->* ]] then - ZSH_VERSION_TYPE=new + ZSH_VERSION_TYPE=new fi ## Options zshrc_load_status 'setting options' setopt \ NO_all_export \ always_last_prompt \ NO_always_to_end \ append_history \ NO_auto_cd \ auto_list \ auto_menu \ NO_auto_name_dirs \ auto_param_keys \ auto_param_slash \ auto_pushd \ auto_remove_slash \ NO_auto_resume \ bad_pattern \ bang_hist \ NO_beep \ brace_ccl \ NO_bsd_echo \ cdable_vars \ NO_chase_links \ NO_clobber \ complete_aliases \ complete_in_word \ csh_junkie_history \ NO_csh_junkie_loops \ NO_csh_junkie_quotes \ NO_csh_null_glob \ equals \ extended_glob \ extended_history \ function_argzero \ glob \ NO_glob_assign \ NO_glob_complete \ glob_dots \ NO_glob_subst \ hash_cmds \ hash_dirs \ hash_list_all \ hist_allow_clobber \ hist_beep \ hist_ignore_dups \ hist_ignore_space \ NO_hist_no_store \ NO_hist_save_no_dups \ NO_hist_verify \ NO_hup \ NO_ignore_braces \ NO_ignore_eof \ interactive_comments \ NO_list_ambiguous \ NO_list_beep \ list_types \ long_list_jobs \ magic_equal_subst \ NO_mail_warning \ NO_mark_dirs \ NO_menu_complete \ multios \ nomatch \ notify \ NO_null_glob \ numeric_glob_sort \ NO_overstrike \ path_dirs \ posix_builtins \ NO_print_exit_value \ NO_prompt_cr \ prompt_subst \ pushd_ignore_dups \ NO_pushd_minus \ NO_pushd_silent \ pushd_to_home \ rc_expand_param \ NO_rc_quotes \ NO_rm_star_silent \ NO_sh_file_expansion \ sh_option_letters \ short_loops \ NO_sh_word_split \ NO_single_line_zle \ NO_sun_keyboard_hack \ unset \ NO_verbose \ zle #NO_xtrace \ # Don't want auto-correction to happen when we're running under emacs tramp. if [[ "$TERM" != "dumb" ]]; then setopt \ NO_correct \ correct_all fi if [[ $ZSH_VERSION_TYPE == 'new' ]]; then - setopt \ + setopt \ hist_expire_dups_first \ hist_ignore_all_dups \ NO_hist_no_functions \ NO_hist_save_no_dups \ inc_append_history \ list_packed \ NO_rm_star_wait fi if [[ $ZSH_VERSION == 3.0.<6->* || $ZSH_VERSION_TYPE == 'new' ]]; then - setopt \ + setopt \ hist_reduce_blanks fi ## Environment zshrc_load_status 'setting environment' ## Some programs might find this handy. Shouldn't do any harm. export COLUMNS ## Variables used by zsh ## Function path ## Choose word delimiter characters in line editor WORDCHARS='' ## Save a large history HISTFILE=~/.zshhistory HISTSIZE=5000 SAVEHIST=5000 ## Maximum size of completion listing ## Only ask if line would scroll off screen LISTMAX=0 ## Watching for other users LOGCHECK=60 WATCHFMT="%n has %a %l from %M" ## Prompts -#local _find_promptinit -#_find_promptinit=( $^fpath/promptinit(N) ) -#if (( $#_find_promptinit == 1 )) && [[ -r $_find_promptinit[1] ]]; then -# zshrc_load_status 'prompt system' -# -# autoload -U promptinit -# promptinit -# -# PS4="trace %N:%i> " -# #RPS1="$bold_colour$bg_red $reset_colour" -# -# # Default prompt style -# if [[ -r /proc/$PPID/cmdline ]] && egrep -q 'Eterm|nexus|vga' /proc/$PPID/cmdline; then -# # probably OK for fancy graphic prompt -# prompt adam2 -# else -# prompt adam2 plain -# fi -#else -# PS1='%n@%m %B%3~%b %# ' -#fi -# - ## Load the prompt stuff if [[ "$TERM" != "dumb" ]]; then autoload -U promptinit promptinit prompt adam2 fi export PS1="[%n@%m %~/]\$ " ## Completions zshrc_load_status 'completion system' ## New advanced completion system things # Reset keybindings to emacs defaults bindkey -e if [[ "$ZSH_VERSION_TYPE" == 'new' ]]; then - autoload -U compinit - compinit -u # don't perform security check + autoload -U compinit + compinit -u # don't perform security check else - print "No advanced completion stuff" - function zstyle { } - function compdef { } + print "No advanced completion stuff" + function zstyle { } + function compdef { } - # an antiquated, barebones completion system is better than nowt - zmodload zsh/compctl + # an antiquated, barebones completion system is better than nowt + zmodload zsh/compctl fi ## Enable the way cool bells and whistles. ## General completion technique zstyle ':completion:*' completer _complete _prefix zstyle ':completion::prefix-1:*' completer _complete zstyle ':completion:incremental:*' completer _complete _correct zstyle ':completion:predict:*' completer _complete # Completion caching zstyle ':completion::complete:*' use-cache 1 zstyle ':completion::complete:*' cache-path ~/.zsh/cache/$HOST ## Expand partial paths zstyle ':completion:*' expand 'yes' zstyle ':completion:*' squeeze-slashes 'yes' -# Include non-hidden directories in globbed file completions -# for certain commands -#zstyle ':completion::complete:*' \ -# tag-order 'globbed-files directories' all-files -#zstyle ':completion::complete:*:tar:directories' file-patterns '*~.*(-/)' # Separate matches into groups zstyle ':completion:*:matches' group 'yes' ## Describe each match group. zstyle ':completion:*:descriptions' format "%B---- %d%b" ## Messages/warnings format zstyle ':completion:*:messages' format '%B%U---- %d%u%b' zstyle ':completion:*:warnings' format '%B%U---- no match for: %d%u%b' ## Describe options in full zstyle ':completion:*:options' description 'yes' zstyle ':completion:*:options' auto-description '%d' ## Simulate my old dabbrev-expand 3.0.5 patch zstyle ':completion:*:history-words' stop verbose zstyle ':completion:*:history-words' remove-all-dups yes -## Common usernames -# users=( tom dick harry ) - -my_accounts=( -) - zshrc_load_status 'aliases and functions' -bash () { - NO_ZSH="yes" command bash "$@" -} restart () { exec $SHELL "$@" } ## Reloading .zshrc or functions reload () { - if [[ "$#*" -eq 0 ]]; then - . ~/.zshrc - else - local fn - for fn in "$@"; do - unfunction $fn - autoload -U $fn - done - fi + if [[ "$#*" -eq 0 ]]; then + . ~/.zshrc + else + local fn + for fn in "$@"; do + unfunction $fn + autoload -U $fn + done + fi } compdef _functions reload # Miscellaneous aliases alias du1='du --max-depth=1' alias dsn='du | sort -n' alias dh='df -h' alias clean='rm *~(N) >&/dev/null' alias more='less' alias lock='xscreensaver-command -lock' alias nskill='killall -9 netscape-communicator' alias mpage='mpage -bA4' alias pss="ps aux | more" alias psw="ps auxw | more" alias enw="emacs -nw" alias bash="NO_SWITCH=t /bin/bash" alias k9='kill -9' alias igrep='grep -i' # Global Aliases that I use a lot. alias -g L="| less" alias -g SN="| sort -n" alias -g SU="| sort | uniq" alias -g WC="| wc -l" alias -g G="| grep " alias -g GV="| grep -v" # Use my version of the ctags command if available. [[ -f $HOME/usr/bin/ctags ]] && alias ctags="$HOME/usr/bin/ctags" if which gnuclient >&/dev/null; then alias ec='gnuclient' elif which emacsclient >&/dev/null; then alias ec='emacsclient' else alias ec='emacs' fi which vim >&/dev/null && alias vi='vim' which vim >&/dev/null || alias vim='vi' alias bcd='byte_compile_directory' ## CVS-related aliases alias up='cvs update' # Huh?? #which cx >&/dev/null || cx () { } if [[ "$TERM" == xterm* ]]; then # Could also look at /proc/$PPID/cmdline ... cx fi # Bc annoyingly doesn't load an rc file by default, and # I want to do things like set the scale. [[ -f $HOME/.bcrc ]] && alias bc='bc -l $HOME/.bcrc' # Function for auto-adding my ssh keys to the ssh-agent addkeys() { [ -f $HOME/.ssh/id_rsa ] && ssh-add $HOME/.ssh/id_rsa [ -f $HOME/.ssh/id_dsa ] && ssh-add $HOME/.ssh/id_dsa } ## ls aliases alias ls='ls --color=tty -F' alias l='ls -l' alias ll='ls -la' alias lh='ls -lh' alias lt='ls -lt' alias ltr='ls -ltr' alias lth='ls -ltrh' alias lll='ls -la | less' alias lsa='ls -a' alias lsd='ls -ld' alias lss='ls -lr --sort=size' alias lsh='ls -lrh --sort=size' alias lr='ls -lr' alias lsr='ls -lR' ## File management alias dirs='dirs -v' alias d=dirs alias pu=pushd alias po=popd alias pwd='pwd -r' # Run a find, then carry out some action on the first result found. find_action() { local action=$1 local file=$2 local is_dir_action=$3 if [[ -z "$file" ]]; then echo "Usage: $0 filename" return -1 fi for found_file in $(find . -name $file -print); do echo $found_file if [[ -f "$found_file" && -n "$is_dir_action" ]]; then eval "$action $(dirname $found_file)" else eval "$action $found_file" fi return 0 done echo "File not found: $file" } fcd() { find_action cd $1 yes } fless() { find_action less $1 } # Wait until the given text is found in named file, occasionally # echoing "waiting" until that time. # FIXME - Might be nifty to add a timeout waitfile () { if [[ $# < 2 ]]; then echo "Usage: $0 expression file" >&2 return -1 elif [[ ! -r $2 ]]; then echo "Error: file does not exist $2" >&2 return -1 fi until grep $1 $2; do sleep 2 echo "Waiting..." done } -# CVS related - This is pretty horrible for now, but it's a start -quickstat () { - if [[ -n "$1" && "-m" = "$1" ]]; then - cvs status 2>|/dev/null | grep '^File' | grep 'Modified' - elif [[ -n "$1" && "-u" = "$1" ]]; then - cvs status 2>|/dev/null | grep '^File' | grep -v "Up-to-date" - else - cvs status 2>|/dev/null | grep '^File' - fi -} - -# Tomcat-related functions -check_tomcat_home () { - if [[ -z "$TOMCAT_HOME" ]]; then - echo "You must set the TOMCAT_HOME environment variable" >&2 - return -1 - fi - - return 0 -} - -shutdown_tomcat () { - check_tomcat_home || return -1 - cd $TOMCAT_HOME - bin/shutdown.sh - cd - -} - -startup_tomcat () { - check_tomcat_home || return -1 - cd $TOMCAT_HOME - bin/startup.sh - cd - -} - -restart_tomcat () { - check_tomcat_home || return -1 - shutdown_tomcat - sleep 2 - startup_tomcat -} - -alias rt=restart_tomcat -alias st=shutdown_tomcat -alias ut=startup_tomcat - - # Some simple functions psg () { ps aux | grep $1 | more } ## Remove the run-help alias alias run-help='' >&/dev/null && unalias run-help autoload run-help ## fbig fbig () { ls -alFR $* | sort -rn -k5 | less -r } -# fbigrpms (no idea what this does!) -alias fbigrpms='rpm --qf "%{SIZE}\t%{NAME}\n" -qa | sort -n | less' - ## Job/process control alias j='jobs -l' alias mps='ps -o user,pcpu,command' -pst () { - pstree -p $* | less -S -} -alias gps='gitps -p afx; cx' + alias ra='ps auxww | grep -vE "(^($USER|nobody|root|bin))|login"' rj () { - ps auxww | grep -E "($*|^USER)" + ps auxww | grep -E "($*|^USER)" } ru () { - ps auxww | grep -E "^($*|USER)" | grep -vE "^$USER|login" + ps auxww | grep -E "^($*|USER)" | grep -vE "^$USER|login" } compdef _users ru -## Changing terminal type -alias v1='export TERM=vt100' -alias v2='export TERM=vt220' -alias vx='export TERM=xterm-color' - - -alias f=finger - -# su to root and change window title -alias root='echo -n "\e]0;root@${HOST}\a"; su -; cx' - # No spelling correction for the man command alias man='nocorrect man' -# Make sure to run ocaml with rlwrap -if which rlwrap >&/dev/null; then - alias ocaml='rlwrap ocaml' - alias scala='rlwrap scala' -fi - ## Set up the appropriate ftp program if which lftp >&/dev/null; then - alias ftp=lftp + alias ftp=lftp elif which ncftp >&/dev/null; then - alias ftp=ncftp + alias ftp=ncftp fi ## Key bindings zshrc_load_status 'key bindings' + bindkey -s '^X^Z' '%-^M' bindkey '^[e' expand-cmd-path bindkey -s '^X?' '\eb=\ef\C-x*' bindkey '^[^I' reverse-menu-complete bindkey '^X^N' accept-and-infer-next-history bindkey '^[p' history-beginning-search-backward bindkey '^[n' history-beginning-search-forward bindkey '^[P' history-beginning-search-backward bindkey '^[N' history-beginning-search-forward bindkey '^[b' emacs-backward-word bindkey '^[f' emacs-forward-word ## Fix weird sequence that rxvt produces bindkey -s '^[[Z' '\t' ## Miscellaneous zshrc_load_status 'miscellaneous' -## Hash named directories -hash -d I3=/usr/src/redhat/RPMS/i386 -hash -d I6=/usr/src/redhat/RPMS/i686 -hash -d SR=/usr/src/redhat/SRPMS -hash -d SP=/usr/src/redhat/SPECS -hash -d SO=/usr/src/redhat/SOURCES -hash -d BU=/usr/src/redhat/BUILD - ## ls colours if [[ $ZSH_VERSION > 3.1.5 ]]; then - zmodload -i zsh/complist + zmodload -i zsh/complist - zstyle ':completion:*' list-colors '' - zstyle ':completion:*:*:kill:*:processes' list-colors \ - '=(#b) #([0-9]#)*=0=01;31' + zstyle ':completion:*' list-colors '' + zstyle ':completion:*:*:kill:*:processes' list-colors \ + '=(#b) #([0-9]#)*=0=01;31' - ZLS_COLOURS=${LS_COLORS-${LS_COLOURS-''}} + ZLS_COLOURS=${LS_COLORS-${LS_COLOURS-''}} fi ## Specific to hosts if [[ -r ~/.zshrc.local ]]; then - zshrc_load_status '.zshrc.local' - . ~/.zshrc.local + zshrc_load_status '.zshrc.local' + . ~/.zshrc.local fi # Run host-specific .zshrc files if [[ -r ~/.zshrc.${HOST%%.*} ]]; then - zshrc_load_status ".zshrc.${HOST%%.*}" - . ~/.zshrc.${HOST%%.*} + zshrc_load_status ".zshrc.${HOST%%.*}" + . ~/.zshrc.${HOST%%.*} fi -## Ensure that we're using sensible shell key bindings -bindkey -e - ## Clear up after status display echo -n "\r" diff --git a/README~ b/README~ deleted file mode 100644 index e69de29..0000000
recoil/config
09b087082a4d61103459177fc0a4ddb5c16d4e46
some more init files
diff --git a/.Xdefaults b/.Xdefaults new file mode 100644 index 0000000..e4eadfa --- /dev/null +++ b/.Xdefaults @@ -0,0 +1,19 @@ +! Japanese language stuff, to make Japanese text entry work +!*.inputMethod: kinput2 +!*.preeditType: OverTheSpot +!Kinput2*userOverrideShellForMode: true +!Kinput2*conversionStartKeys: Shift<Key>space + +! Configure kterm properly +! Kterm*VT100*KanjiMode: euc + +! Rxvt config, alter various lamenesses +!Rxvt.multichar_encoding: eucj +!Rxvt.saveLines: 4096 +! Rxvt.backspacekey: ^? + +! Make the emacs menubar a bit prettier +emacs.pane.menubar.font: -adobe-helvetica-medium-r-normal--12-120-75-75-p-67-iso8859-1 +emacs.pane.menubar.height: 24 +emacs.pane.menubar.margin: 0 +emacs*bitmapIcon: on diff --git a/.bashrc b/.bashrc new file mode 100644 index 0000000..9e61420 --- /dev/null +++ b/.bashrc @@ -0,0 +1,24 @@ + +# Aliases +alias more='less' +alias ls='ls -F --color=tty' +alias l='ls -l' +alias ll="ls -al" +alias lll="ls -la | more" +alias clean='rm *~' +alias enw="emacs -nw" + +# Environment vars +export PS1='\u@\h:\w \$ ' +export PAGER="less" +export VISUAL="emacs" +export EDITOR="emacs" +export CVS_RSH=ssh +export RSYNC_RSH=ssh +export LESS=-Mi + +export PATH=$PATH:/usr/local/bin:/sbin:/usr/sbin + +# Key bindings +bind '"\ep":history-search-backward' +bind '"\en":history-search-forward' diff --git a/.bcrc b/.bcrc new file mode 100644 index 0000000..1595f32 --- /dev/null +++ b/.bcrc @@ -0,0 +1 @@ +scale=8 diff --git a/.cvsrc b/.cvsrc new file mode 100644 index 0000000..1182623 --- /dev/null +++ b/.cvsrc @@ -0,0 +1,4 @@ +cvs -z3 +update -dP +diff -u +rdiff -u diff --git a/.irbrc b/.irbrc new file mode 100644 index 0000000..b7510ef --- /dev/null +++ b/.irbrc @@ -0,0 +1 @@ +require 'irb/completion' diff --git a/.profile b/.profile new file mode 100644 index 0000000..004a7b3 --- /dev/null +++ b/.profile @@ -0,0 +1,3 @@ +if [ -f $HOME/.bashrc ]; then + source $HOME/.bashrc +fi diff --git a/.screenrc b/.screenrc new file mode 100644 index 0000000..7b86347 --- /dev/null +++ b/.screenrc @@ -0,0 +1,140 @@ +# -*- mode: sh -*- + +escape ^Oo + +bindkey -k kb stuff "\177" + +startup_message off + +defscrollback 10000 + +# This is how one can set a reattach password: +# password ODSJQf.4IJN7E # "1234" + +activity '^GActivity in window %' +bell_msg '^GBell in window %' # message for bell in bg window +vbell on + +# detach on hangup +autodetach on + +# emulate .logout message +pow_detach_msg "Screen session of \$LOGNAME \$:cr:\$:nl:ended." + +# Make shell "sticky" - bypass shell switching mechanism if it's in use +shell $SHELL + +# ANSI mostly works with older screens, until the status line hits +# the right-hand edge of the terminal. +#hardstatus alwayslastline "%?%-Lw%?%n*%f %t%?(%u)%?%?%+Lw%?" +hardstatus alwayslastline "%{=}%?%{+b Y}%-Lw%{-}%?%{= BW}%n*%f %t%?(%u)%?%{-}%?%{+b Y}%+Lw%?%{-}" + +# and without colour (FIXME) +# hardstatus alwayslastline "%{=}%?%{+b Y}%-Lw%{-}%?%{= BW}%n*%f %t%?(%u)%?%{-}%?%{+b Y}%+Lw%?%{-}" +# Really old screens don't have %-Lw and %+Lw +#hardstatus alwayslastline "%w" + +# don't kill window after the process died +# zombie "^[" + +# C-a is too useful to rebind as a prefix. This is actually two +# "characters", the first being ^\, and the second \\. +# defescape ^\\\ +# escape ^\\\ + +# Default startup windows (-t <title>). +# Presumably if I'm using screen I want at least 2 windows. +screen +screen + +# start with 0th window +select 0 + +# Imbeciles!!!! +msgwait 1 + +# might need this one too +msgminwait 1 + +# Bind delete to ^?. kD is termcap-speak for delete (-k uses termcap-speak) +bindkey -k kD stuff "\177" + +# Function keys + +# F1 is used by Eterm, leave F2-F8 on LHS for per-app bindings. +# bindkey -k k9 multiuser off # F9 +# bindkey -k k; multiuser on # F10 + +# NOTE: to do multiuser, you must have screen setuid root. +# grep screen(1) for 'owner' + +# S-left/S-right changes windows. +bindkey "" next +bindkey "" prev + +# Move window left/right. This only works with my patch +# to screen's process.c file. +# Could have used M-left/M-right: +#bindkey "" number +1 +#bindkey "" number -1 + +# but let's save them for a more common operation, and use +# C-s-PageUp/Down a la galeon. +bindkey "[5@" number -1 +bindkey "[6@" number +1 + +# For split regions, bind C-\ j/k to up/down between regions +bind j focus down +bind k focus up + +# Thanks Michael Schroeder for helping me get this working! +# +#termcapinfo xterm* "ks=\E[?1l\E=:ku=\E[A:kd=\E[B:kl=\E[D:kr=\E[C" +# +# Commented out, because as it turns out, ensuring TERM=Eterm +# will work nicer than the above hack. Here's an +# explanation of what it does anyway: +# +# \E[? is for DEC private modes. 1 is for Application/Normal +# cursor keys, and l does a DECRST. \E= sets Application Keypad +# (\E> sets Normal Keypad). Setting the ks capability to this +# ensures that Eterm never switches to application mode. We +# want normal mode, since in normal mode, Eterm distinguishes +# between left and S-left: +# http://www.eterm.org/docs/view.php?doc=ref#keys + +# Insert pastes +bindkey -k kI paste . + +# S-down enters copy mode +bindkey "" copy + +##################################################################### +# Bindings using eval go last since they don't work on older screens +# and we want all other settings to always take effect. + +# Used to use this for quick reordering of windows before writing my patch +# *Note: Input Translation in screen info for correct -k sequences: +# -k k; F10 +# -k F1 F11 +# -k F2 F12 +bindkey -k k; eval colon 'stuff "number "' + +# S-up enters copy mode and goes up a line +bindkey "" eval copy "stuff k" + +# PageUp enters copy mode and goes to top of the page +bindkey -k kP eval copy "stuff H" + +# Insert exits copy mode and pastes +bindkey -m -k kI eval 'stuff " "' "paste ." + +# Ctrl-PageUp reverse searches for a prompt delimiter, assuming +# use of the 'adam2' prompt theme in zsh. +# It enters copy mode if not already in it, hence both bindings. +bindkey "[5\^" eval copy "stuff kk?---------(\015\^jlllll" +bindkey -m "[5\^" stuff "kk?---------(\015\^jlllll" + +# Ctrl-PageDown in copy mode forward searches for a prompt delimiter +bindkey -m "[6\^" stuff "j/----------(\015\^jlllll" + diff --git a/.switch_shell b/.switch_shell new file mode 100644 index 0000000..061f06e --- /dev/null +++ b/.switch_shell @@ -0,0 +1,91 @@ +#!/bin/sh +# +# Adam's .switch_shell +# +# Try switch shell if we're interactive, aiming for safety, but +# not so much that we end up hogging memory. +# +# $Id: .switch_shell,v 1.1 2004/07/06 12:02:44 mark Exp $ +# +# Usage: +# +# . /path/to/.switch_shell [-d] [ /path/to/new_shell [ <new shell options> ] +# -d turns on debugging + +if [ "$1" = '-d' ]; then + debug=yes + shift +fi + +myshell= +myshell_args= + +if [ -n "$1" ]; then + myshell="$1" + shift + myshell_args="$@" +else + [ -e ~/.preferred_shell ] && . ~/.preferred_shell +# # Sensible default shell to switch to. +# myshell=`which zsh` 2>/dev/null +fi + +if [ -z "$myshell" ]; then + [ -n "$debug" ] && echo "No shell preference found; not switching shell." + return 0 +fi + +# Very cute trick from Bart Schaefer which is a valid alternative approach +#eval `$myshell -f -c "echo exec $myshell" || echo :` '$myshell_args' + +switch_shell_safely () { + # we do this rather than exec() just in case $myshell fails to run. + [ -n "$debug" ] && echo "Switching to $myshell safely ..." + if SHELL="$myshell" "$myshell" $myshell_args; then + [ -n "$debug" ] && echo "$myshell exited OK; exiting parent shell." + exit + else + [ -n "$debug" ] && echo "$myshell had exit code $?, back to pid $$" + fi +} + +switch_shell_dangerously () { + [ -n "$debug" ] && echo "Switching to $myshell dangerously ..." + SHELL="$myshell" exec "$myshell" $myshell_args +} + +switch_shell () { + if [ ! -x $myshell ]; then + [ -n "$debug" ] && echo "$myshell not executable; aborting switch." + return + fi + + if [ -n "$NO_SWITCH" ]; then + [ -n "$debug" ] && echo 'Shell switching disabled by $NO_SWITCH; aborting.' + return + fi + + export SHELL_ARGS="$myshell_args" # no other way of retrieving these? + + [ -n "$debug" ] && echo "Switching to $myshell, args: $myshell_args" + + case "$SHLVL" in + "") # unknown, be careful + switch_shell_safely $myshell_args + ;; + 1) # login shell, be careful + switch_shell_safely $myshell_args + ;; + *) # other shell, be risky and save memory + switch_shell_dangerously $myshell_args +# switch_shell_safely $myshell_args + ;; + esac +} + +# only switch if we're interactive +case "$-" in + *i*) switch_shell $myshell_args + ;; +esac + diff --git a/.vimrc b/.vimrc new file mode 100644 index 0000000..2d36f58 --- /dev/null +++ b/.vimrc @@ -0,0 +1,98 @@ +" Set various useful options to make everything nicer +set nocompatible " Allow the use of vim-specific stuff +set expandtab +set shiftwidth=4 +set softtabstop=4 +set backspace=indent,eol,start +set hidden +set whichwrap=b,s +set incsearch +set showmatch +set ignorecase +set smartcase +set history=100 " Keep more history +set ruler " Show the cursor position all the time +set showcmd " Show commands at all times + +if version >= 600 + if has("autocmd") + "Some autocmd's + autocmd! + + autocmd FileType lisp set autoindent lisp + autocmd FileType mail set tw=72 + autocmd FileType make set noet sw=8 sts=0 + autocmd FileType tex set tw=76 + autocmd FileType text set tw=76 + + " These are no longer necessary because of programmable indentation. + " autocmd FileType perl,ruby set cinkeys=0{,0},:,!^F,o,O,e|set cindent + " autocmd FileType c set cindent + " autocmd FileType cpp set cindent + " autocmd FileType java set cindent + " autocmd FileType sh set autoindent + + autocmd BufRead *.buf set ft=sql + autocmd BufRead,BufNewFile README set ft=text + autocmd BufRead,BufNewFile *.txt set ft=text + autocmd BufRead,BufNewFile ChangeLog set ft=text sts=8 + autocmd BufRead .emacs set ft=lisp + endif + + filetype indent on + filetype plugin on + + " Might not be necessary + set background=dark + syntax on + + " Enable mouse support + "set mouse=a + + " Make comments look nicer + highlight Comment ctermfg=green + + " Aligns the selected assignment statements neatly by inserting space characters + function Align(line1, line2) + let i = a:line1 + let mycount = a:line2 + let maxindex = 0 + + while i <= mycount + let line = getline(i) + let index = match(line, "=") + if index > maxindex + let maxindex = index + endif + let i = i + 1 + endw + + let i = a:line1 + while i <= mycount + let line = getline(i) + let index = match(line, "=") + if index < maxindex + let diff = maxindex - index + while diff > 0 + let line = substitute(line, "=", " =", "") + let diff = diff - 1 + endw + call setline(i, line) + endif + let i = i + 1 + endw + endf + + " Define the Align command to call the Align function + command -nargs=0 -range Align call Align(<line1>,<line2>) + + " TODO Find better keybindings + map <F2> o + map <F3> :Align + " Macro to do list auto-numbering + map <F4> 0y/\([a-z]\<Bar>$\) A P0$ + " Macro to make a Perl accessor out of its name + map <F5> ^y$Isub <Esc>A { $_[0]->{_<Esc>pa}; }<Esc><Down> + " Macro to make an XML element pair out of a word + map <F6> ^ywi<A></pa> +endif diff --git a/.zshenv b/.zshenv new file mode 100644 index 0000000..a8fa606 --- /dev/null +++ b/.zshenv @@ -0,0 +1,125 @@ +export RSYNC_RSH=ssh +export CVS_RSH=ssh + +export PAGER=less +export LESS="-RMi" +export LD_LIBRARY_PATH=$HOME/usr/lib + +# Standard PATH (roughly) +BASE_PATH="/sbin:/usr/sbin:/usr/local/bin:/usr/bin:/usr/games" +# Make sure local path comes first +BASE_PATH="$HOME/bin:$HOME/usr/bin:$BASE_PATH" +# Make sure /bin is *very* first +BASE_PATH="/bin:$BASE_PATH" + +# Manual path - Might want to do the BASE_MAN_PATH thing at some future point. +MANPATH="$MANPATH:$HOME/usr/man" + +## Only add this path in X +if [ -n "$DISPLAY" ]; then + BASE_PATH="$BASE_PATH:/usr/X11R6/bin" + MANPATH="$MANPATH:/usr/X11R6/man" +fi + +# Needs to be turned on for some of the globs below to work +setopt extended_glob + +# Hackish... +zdotdir=$HOME +export zdotdir + +# Set up the function path and autoload all the functions in +# there. (Basically cribbed from adam, but not quite the same.. Probably +# soom room for improvement). +fpath=( + $fpath + $zdotdir/{lib/zsh,.zsh}/{functions,scripts}(N) + ) +typeset -U fpath + +# Autoload shell functions from all directories in $fpath. Restrict +# functions from $zdotdir/.zsh to ones that have the executable bit +# on. (The executable bit is not necessary, but gives you an easy way +# to stop the autoloading of a particular shell function). +# +# The ':t' is a history modifier to produce the tail of the file only, +# i.e. dropping the directory path. The 'x' glob qualifier means +# executable by the owner (which might not be the same as the current +# user). +# +# (remove the aforementioned "x", because that means it doesn't work +# on cygwin, which doesn't support an executable flag for scripts) +for dirname in $fpath; do + case "$dirname" in + $zdotdir/.zsh*) fns=( $dirname/*~*~(N.:t) ) ;; + *) fns=( $dirname/*~*~(N.:t) ) ;; + esac + (( $#fns )) && autoload "$fns[@]" +done + +# This works no matter what the platform, but it's turned off for the moment. +# +#for file in $HOME/.zsh/functions/*; do +# [ -r $file ] && autoload ${file:t} +#done + +## Common hostnames +hosts=( + dahmer.vistech.net + + # Home + 81.5.166.232 + {,www.}markhj.com + + # frottage + {ipx,ipy,newipy,ipz}.frottage.org +) + +# Sometimes emacs isn't there, so set it as EDITOR conditionally, +# falling back on vim, which also isn't there sometimes. Also, we +# want to do this AFTER the local .zshenv has been run, so that it's +# possible for emacs/vim to be added to the PATH locally somewhere +# before looking for it. +if which emacs >&/dev/null; then + EDITOR="emacs" +elif which vim >&/dev/null; then + EDITOR="vim" + alias emacs='vim' +else + EDITOR="vi" + alias emacs='vi' +fi + +# Conditionally +# Bit of a foul hack this... +if [[ "$EDITOR" = "emacs" ]]; then + VISUAL="$EDITOR -nw" +else + VISUAL="$EDITOR" +fi + +## Set a var when screen is being run +case "$TERM" in + screen*) IN_SCREEN=yes; export IN_SCREEN ;; +esac + +# Site-specific PATH bits can be included here +localenv=$HOME/.zshenv.local +if [[ -r $localenv ]]; then + . $localenv +fi + +localenv=$HOME/.zshenv.${HOST%%.*} +if [[ -r $localenv ]]; then + . $localenv +fi + +# Tune completion *after* local env file is read, so local hosts can +# be added. +zstyle ':completion:*' hosts $hosts + +# Re-export these, as they may have been alterred in the local config +export hosts LANG +export EDITOR VISUAL +export PATH=$BASE_PATH:$LOCAL_PATH +export MANPATH diff --git a/.zshrc b/.zshrc new file mode 100755 index 0000000..c684b97 --- /dev/null +++ b/.zshrc @@ -0,0 +1,586 @@ +#!/bin/zsh +# +# .zshrc +# for zsh 3.1.6 and newer (may work OK with earlier versions) +# +# by Adam Spiers <[email protected]> +# Edited pretty heavily by Mark Hulme-Jones <[email protected]> +# +# $Id: .zshrc,v 1.32 2005/12/01 10:03:31 mark Exp $ +# + +zshrc_load_status () { + if [[ "$TERM" != "dumb" ]]; then + echo -n "\r.zshrc load: $* ... \e[0K" + fi +} + +## What version are we running? +zshrc_load_status 'checking version' + +if [[ $ZSH_VERSION == 3.0.<->* ]]; then ZSH_STABLE_VERSION=yes; fi +if [[ $ZSH_VERSION == 3.1.<->* ]]; then ZSH_DEVEL_VERSION=yes; fi + +ZSH_VERSION_TYPE=old +if [[ $ZSH_VERSION == 3.1.<6->* || + $ZSH_VERSION == 3.2.<->* || + $ZSH_VERSION == 4.<->* ]] +then + ZSH_VERSION_TYPE=new +fi + +## Options +zshrc_load_status 'setting options' + +setopt \ + NO_all_export \ + always_last_prompt \ + NO_always_to_end \ + append_history \ + NO_auto_cd \ + auto_list \ + auto_menu \ + NO_auto_name_dirs \ + auto_param_keys \ + auto_param_slash \ + auto_pushd \ + auto_remove_slash \ + NO_auto_resume \ + bad_pattern \ + bang_hist \ + NO_beep \ + brace_ccl \ + NO_bsd_echo \ + cdable_vars \ + NO_chase_links \ + NO_clobber \ + complete_aliases \ + complete_in_word \ + csh_junkie_history \ + NO_csh_junkie_loops \ + NO_csh_junkie_quotes \ + NO_csh_null_glob \ + equals \ + extended_glob \ + extended_history \ + function_argzero \ + glob \ + NO_glob_assign \ + NO_glob_complete \ + glob_dots \ + NO_glob_subst \ + hash_cmds \ + hash_dirs \ + hash_list_all \ + hist_allow_clobber \ + hist_beep \ + hist_ignore_dups \ + hist_ignore_space \ + NO_hist_no_store \ + NO_hist_save_no_dups \ + NO_hist_verify \ + NO_hup \ + NO_ignore_braces \ + NO_ignore_eof \ + interactive_comments \ + NO_list_ambiguous \ + NO_list_beep \ + list_types \ + long_list_jobs \ + magic_equal_subst \ + NO_mail_warning \ + NO_mark_dirs \ + NO_menu_complete \ + multios \ + nomatch \ + notify \ + NO_null_glob \ + numeric_glob_sort \ + NO_overstrike \ + path_dirs \ + posix_builtins \ + NO_print_exit_value \ + NO_prompt_cr \ + prompt_subst \ + pushd_ignore_dups \ + NO_pushd_minus \ + NO_pushd_silent \ + pushd_to_home \ + rc_expand_param \ + NO_rc_quotes \ + NO_rm_star_silent \ + NO_sh_file_expansion \ + sh_option_letters \ + short_loops \ + NO_sh_word_split \ + NO_single_line_zle \ + NO_sun_keyboard_hack \ + unset \ + NO_verbose \ + zle + #NO_xtrace \ + +# Don't want auto-correction to happen when we're running under emacs tramp. +if [[ "$TERM" != "dumb" ]]; then + setopt \ + NO_correct \ + correct_all +fi + +if [[ $ZSH_VERSION_TYPE == 'new' ]]; then + setopt \ + hist_expire_dups_first \ + hist_ignore_all_dups \ + NO_hist_no_functions \ + NO_hist_save_no_dups \ + inc_append_history \ + list_packed \ + NO_rm_star_wait +fi + +if [[ $ZSH_VERSION == 3.0.<6->* || $ZSH_VERSION_TYPE == 'new' ]]; then + setopt \ + hist_reduce_blanks +fi + +## Environment +zshrc_load_status 'setting environment' + +## Some programs might find this handy. Shouldn't do any harm. +export COLUMNS + +## Variables used by zsh +## Function path + +## Choose word delimiter characters in line editor +WORDCHARS='' + +## Save a large history +HISTFILE=~/.zshhistory +HISTSIZE=5000 +SAVEHIST=5000 + +## Maximum size of completion listing +## Only ask if line would scroll off screen +LISTMAX=0 + +## Watching for other users +LOGCHECK=60 +WATCHFMT="%n has %a %l from %M" + +## Prompts + +#local _find_promptinit +#_find_promptinit=( $^fpath/promptinit(N) ) +#if (( $#_find_promptinit == 1 )) && [[ -r $_find_promptinit[1] ]]; then +# zshrc_load_status 'prompt system' +# +# autoload -U promptinit +# promptinit +# +# PS4="trace %N:%i> " +# #RPS1="$bold_colour$bg_red $reset_colour" +# +# # Default prompt style +# if [[ -r /proc/$PPID/cmdline ]] && egrep -q 'Eterm|nexus|vga' /proc/$PPID/cmdline; then +# # probably OK for fancy graphic prompt +# prompt adam2 +# else +# prompt adam2 plain +# fi +#else +# PS1='%n@%m %B%3~%b %# ' +#fi +# + +## Load the prompt stuff +if [[ "$TERM" != "dumb" ]]; then + autoload -U promptinit + promptinit + prompt adam2 +fi + +export PS1="[%n@%m %~/]\$ " + +## Completions +zshrc_load_status 'completion system' + +## New advanced completion system things + +# Reset keybindings to emacs defaults +bindkey -e + +if [[ "$ZSH_VERSION_TYPE" == 'new' ]]; then + autoload -U compinit + compinit -u # don't perform security check +else + print "No advanced completion stuff" + function zstyle { } + function compdef { } + + # an antiquated, barebones completion system is better than nowt + zmodload zsh/compctl +fi + +## Enable the way cool bells and whistles. + +## General completion technique +zstyle ':completion:*' completer _complete _prefix +zstyle ':completion::prefix-1:*' completer _complete +zstyle ':completion:incremental:*' completer _complete _correct +zstyle ':completion:predict:*' completer _complete + +# Completion caching +zstyle ':completion::complete:*' use-cache 1 +zstyle ':completion::complete:*' cache-path ~/.zsh/cache/$HOST + +## Expand partial paths +zstyle ':completion:*' expand 'yes' +zstyle ':completion:*' squeeze-slashes 'yes' + +# Include non-hidden directories in globbed file completions +# for certain commands +#zstyle ':completion::complete:*' \ +# tag-order 'globbed-files directories' all-files +#zstyle ':completion::complete:*:tar:directories' file-patterns '*~.*(-/)' +# Separate matches into groups +zstyle ':completion:*:matches' group 'yes' + +## Describe each match group. +zstyle ':completion:*:descriptions' format "%B---- %d%b" + +## Messages/warnings format +zstyle ':completion:*:messages' format '%B%U---- %d%u%b' +zstyle ':completion:*:warnings' format '%B%U---- no match for: %d%u%b' + +## Describe options in full +zstyle ':completion:*:options' description 'yes' +zstyle ':completion:*:options' auto-description '%d' + +## Simulate my old dabbrev-expand 3.0.5 patch +zstyle ':completion:*:history-words' stop verbose +zstyle ':completion:*:history-words' remove-all-dups yes + +## Common usernames +# users=( tom dick harry ) + +my_accounts=( +) + + +zshrc_load_status 'aliases and functions' + +bash () { + NO_ZSH="yes" command bash "$@" +} + +restart () { + exec $SHELL "$@" +} + +## Reloading .zshrc or functions +reload () { + if [[ "$#*" -eq 0 ]]; then + . ~/.zshrc + else + local fn + for fn in "$@"; do + unfunction $fn + autoload -U $fn + done + fi +} +compdef _functions reload + +# Miscellaneous aliases +alias du1='du --max-depth=1' +alias dsn='du | sort -n' +alias dh='df -h' +alias clean='rm *~(N) >&/dev/null' +alias more='less' +alias lock='xscreensaver-command -lock' +alias nskill='killall -9 netscape-communicator' +alias mpage='mpage -bA4' +alias pss="ps aux | more" +alias psw="ps auxw | more" +alias enw="emacs -nw" +alias bash="NO_SWITCH=t /bin/bash" +alias k9='kill -9' +alias igrep='grep -i' + +# Global Aliases that I use a lot. +alias -g L="| less" +alias -g SN="| sort -n" +alias -g SU="| sort | uniq" +alias -g WC="| wc -l" +alias -g G="| grep " +alias -g GV="| grep -v" + +# Use my version of the ctags command if available. +[[ -f $HOME/usr/bin/ctags ]] && alias ctags="$HOME/usr/bin/ctags" + +if which gnuclient >&/dev/null; then + alias ec='gnuclient' +elif which emacsclient >&/dev/null; then + alias ec='emacsclient' +else + alias ec='emacs' +fi + +which vim >&/dev/null && alias vi='vim' +which vim >&/dev/null || alias vim='vi' +alias bcd='byte_compile_directory' + +## CVS-related aliases +alias up='cvs update' + +# Huh?? +#which cx >&/dev/null || cx () { } +if [[ "$TERM" == xterm* ]]; then + # Could also look at /proc/$PPID/cmdline ... + cx +fi + +# Bc annoyingly doesn't load an rc file by default, and +# I want to do things like set the scale. +[[ -f $HOME/.bcrc ]] && alias bc='bc -l $HOME/.bcrc' + +# Function for auto-adding my ssh keys to the ssh-agent +addkeys() { + [ -f $HOME/.ssh/id_rsa ] && ssh-add $HOME/.ssh/id_rsa + [ -f $HOME/.ssh/id_dsa ] && ssh-add $HOME/.ssh/id_dsa +} + +## ls aliases +alias ls='ls --color=tty -F' +alias l='ls -l' +alias ll='ls -la' +alias lh='ls -lh' +alias lt='ls -lt' +alias ltr='ls -ltr' +alias lth='ls -ltrh' +alias lll='ls -la | less' +alias lsa='ls -a' +alias lsd='ls -ld' +alias lss='ls -lr --sort=size' +alias lsh='ls -lrh --sort=size' +alias lr='ls -lr' +alias lsr='ls -lR' + +## File management +alias dirs='dirs -v' +alias d=dirs +alias pu=pushd +alias po=popd +alias pwd='pwd -r' + +# Run a find, then carry out some action on the first result found. +find_action() { + local action=$1 + local file=$2 + local is_dir_action=$3 + + if [[ -z "$file" ]]; then + echo "Usage: $0 filename" + return -1 + fi + + for found_file in $(find . -name $file -print); do + echo $found_file + if [[ -f "$found_file" && -n "$is_dir_action" ]]; then + eval "$action $(dirname $found_file)" + else + eval "$action $found_file" + fi + return 0 + done + + echo "File not found: $file" +} + +fcd() { find_action cd $1 yes } +fless() { find_action less $1 } + +# Wait until the given text is found in named file, occasionally +# echoing "waiting" until that time. +# FIXME - Might be nifty to add a timeout +waitfile () { + if [[ $# < 2 ]]; then + echo "Usage: $0 expression file" >&2 + return -1 + elif [[ ! -r $2 ]]; then + echo "Error: file does not exist $2" >&2 + return -1 + fi + + until grep $1 $2; do + sleep 2 + echo "Waiting..." + done +} + +# CVS related - This is pretty horrible for now, but it's a start +quickstat () { + if [[ -n "$1" && "-m" = "$1" ]]; then + cvs status 2>|/dev/null | grep '^File' | grep 'Modified' + elif [[ -n "$1" && "-u" = "$1" ]]; then + cvs status 2>|/dev/null | grep '^File' | grep -v "Up-to-date" + else + cvs status 2>|/dev/null | grep '^File' + fi +} + +# Tomcat-related functions +check_tomcat_home () { + if [[ -z "$TOMCAT_HOME" ]]; then + echo "You must set the TOMCAT_HOME environment variable" >&2 + return -1 + fi + + return 0 +} + +shutdown_tomcat () { + check_tomcat_home || return -1 + cd $TOMCAT_HOME + bin/shutdown.sh + cd - +} + +startup_tomcat () { + check_tomcat_home || return -1 + cd $TOMCAT_HOME + bin/startup.sh + cd - +} + +restart_tomcat () { + check_tomcat_home || return -1 + shutdown_tomcat + sleep 2 + startup_tomcat +} + +alias rt=restart_tomcat +alias st=shutdown_tomcat +alias ut=startup_tomcat + + +# Some simple functions +psg () { + ps aux | grep $1 | more +} + +## Remove the run-help alias +alias run-help='' >&/dev/null && unalias run-help +autoload run-help + +## fbig +fbig () { + ls -alFR $* | sort -rn -k5 | less -r +} + +# fbigrpms (no idea what this does!) +alias fbigrpms='rpm --qf "%{SIZE}\t%{NAME}\n" -qa | sort -n | less' + +## Job/process control +alias j='jobs -l' +alias mps='ps -o user,pcpu,command' +pst () { + pstree -p $* | less -S +} +alias gps='gitps -p afx; cx' +alias ra='ps auxww | grep -vE "(^($USER|nobody|root|bin))|login"' +rj () { + ps auxww | grep -E "($*|^USER)" +} +ru () { + ps auxww | grep -E "^($*|USER)" | grep -vE "^$USER|login" +} +compdef _users ru + +## Changing terminal type +alias v1='export TERM=vt100' +alias v2='export TERM=vt220' +alias vx='export TERM=xterm-color' + + +alias f=finger + +# su to root and change window title +alias root='echo -n "\e]0;root@${HOST}\a"; su -; cx' + +# No spelling correction for the man command +alias man='nocorrect man' + +# Make sure to run ocaml with rlwrap +if which rlwrap >&/dev/null; then + alias ocaml='rlwrap ocaml' + alias scala='rlwrap scala' +fi + +## Set up the appropriate ftp program +if which lftp >&/dev/null; then + alias ftp=lftp +elif which ncftp >&/dev/null; then + alias ftp=ncftp +fi + +## Key bindings +zshrc_load_status 'key bindings' +bindkey -s '^X^Z' '%-^M' +bindkey '^[e' expand-cmd-path +bindkey -s '^X?' '\eb=\ef\C-x*' +bindkey '^[^I' reverse-menu-complete +bindkey '^X^N' accept-and-infer-next-history +bindkey '^[p' history-beginning-search-backward +bindkey '^[n' history-beginning-search-forward +bindkey '^[P' history-beginning-search-backward +bindkey '^[N' history-beginning-search-forward +bindkey '^[b' emacs-backward-word +bindkey '^[f' emacs-forward-word + +## Fix weird sequence that rxvt produces +bindkey -s '^[[Z' '\t' + +## Miscellaneous + +zshrc_load_status 'miscellaneous' + +## Hash named directories +hash -d I3=/usr/src/redhat/RPMS/i386 +hash -d I6=/usr/src/redhat/RPMS/i686 +hash -d SR=/usr/src/redhat/SRPMS +hash -d SP=/usr/src/redhat/SPECS +hash -d SO=/usr/src/redhat/SOURCES +hash -d BU=/usr/src/redhat/BUILD + +## ls colours + +if [[ $ZSH_VERSION > 3.1.5 ]]; then + zmodload -i zsh/complist + + zstyle ':completion:*' list-colors '' + zstyle ':completion:*:*:kill:*:processes' list-colors \ + '=(#b) #([0-9]#)*=0=01;31' + + ZLS_COLOURS=${LS_COLORS-${LS_COLOURS-''}} +fi + +## Specific to hosts +if [[ -r ~/.zshrc.local ]]; then + zshrc_load_status '.zshrc.local' + . ~/.zshrc.local +fi + +# Run host-specific .zshrc files +if [[ -r ~/.zshrc.${HOST%%.*} ]]; then + zshrc_load_status ".zshrc.${HOST%%.*}" + . ~/.zshrc.${HOST%%.*} +fi + +## Ensure that we're using sensible shell key bindings +bindkey -e + +## Clear up after status display +echo -n "\r" diff --git a/README~ b/README~ new file mode 100644 index 0000000..e69de29
wil/gtornado
4774fd4bdcef05e0490f8940092e03b91e98948c
link to gevent
diff --git a/README.rst b/README.rst index 3b2e6dd..da7b96e 100644 --- a/README.rst +++ b/README.rst @@ -1,54 +1,55 @@ gtornado = gevent + Tornado =========================== Introduction ------------ Tornado_ is a high performance web server and framework. It operates in a non-blocking fashion, utilizing Linux's epoll_ facility when available. It also comes bundled with several niceties such as authentication via OpenID, OAuth, secure cookies, templates, CSRF protection and UI modules. Unfortunately, some of its features ties the developer into its own asynchronous API implementation. -This module is an experiment to monkey patch it just enough to make it run under gevent. +This module is an experiment to monkey patch it just enough to make it run under gevent_. One advantage of doing so is that one can use a coroutine-style and code in a blocking fashion while being able to use the tornado framework. For example, one could use Tornado's OpenID mixins, together with other libraries (perhaps AMQP or XMPP clients?) that may not otherwise be written to Tornado's asynchronous API and therefore would block the entire process. .. _Tornado: http://www.tornadoweb.org/ .. _epoll: http://www.kernel.org/doc/man-pages/online/pages/man4/epoll.4.html +.. _gevent: http://www.gevent.org/ Monkey Patching --------------- gtornado currently includes patches to two different Tornado modules: ``ioloop`` and ``httpserver``. The ``ioloop`` patch uses gevent's internal pyevent implementation, mapping ``ioloop``'s concepts into libevent's. The ``httpserver`` patch uses gevent's libevent_http wrapper, which *should* be blazing fast. However, due to the way tornado's httpserver is structured, the monkey patching code has to do some, well, monkeying around (parsing the headers from tornado and translating them into libevent_http calls.) It tries to be fairly efficient, but if your application is doesn't do much (most benchmarks), the parsing overhead can be a significant chunk of your CPU time. There are two ways to monkey patch your tornado application: - by importing the ``gtornado.monkey`` module and calling the ``patch_*`` functions in your tornado application source before importing any tornado modules. :: from gtornado.monkey import patch_all; patch_all() # now import your usual stuff from tornado import ioloop - by running the gtornado.monkey module as a script, to let it patch tornado before running your tornado application. :: $ python -m gtornado.monkey my_tornado_app.py
wil/gtornado
132191b2895a84d09ad54b514d3da48d5df7d7d1
monkey patching instructions
diff --git a/README.rst b/README.rst index c2b1b6f..3b2e6dd 100644 --- a/README.rst +++ b/README.rst @@ -1,19 +1,54 @@ gtornado = gevent + Tornado =========================== Introduction ------------ Tornado_ is a high performance web server and framework. It operates in a non-blocking fashion, utilizing Linux's epoll_ facility when available. It also comes bundled with several niceties such as authentication via OpenID, OAuth, secure cookies, templates, CSRF protection and UI modules. Unfortunately, some of its features ties the developer into its own asynchronous API implementation. This module is an experiment to monkey patch it just enough to make it run under gevent. One advantage of doing so is that one can use a coroutine-style and code in a blocking fashion -while being able to use the tornado framework. +while being able to use the tornado framework. For example, one could use Tornado's OpenID mixins, together with +other libraries (perhaps AMQP or XMPP clients?) that may not otherwise be written to Tornado's asynchronous API and therefore would block the entire process. .. _Tornado: http://www.tornadoweb.org/ .. _epoll: http://www.kernel.org/doc/man-pages/online/pages/man4/epoll.4.html + + +Monkey Patching +--------------- + +gtornado currently includes patches to two different Tornado modules: ``ioloop`` and ``httpserver``. + +The ``ioloop`` patch uses gevent's internal pyevent implementation, mapping ``ioloop``'s concepts +into libevent's. + +The ``httpserver`` patch uses gevent's libevent_http wrapper, which *should* be blazing fast. +However, due to the way tornado's httpserver is structured, the monkey patching code has to do some, +well, monkeying around (parsing the headers from tornado and translating them into libevent_http calls.) +It tries to be fairly efficient, but if your application is doesn't do much (most benchmarks), +the parsing overhead can be a significant chunk of your CPU time. + +There are two ways to monkey patch your tornado application: + +- by importing the ``gtornado.monkey`` module and calling the ``patch_*`` functions in your tornado application source before importing any tornado modules. + +:: + + from gtornado.monkey import patch_all; patch_all() + # now import your usual stuff + from tornado import ioloop + +- by running the gtornado.monkey module as a script, to let it patch tornado before running your tornado application. + +:: + + $ python -m gtornado.monkey my_tornado_app.py + + +
wil/gtornado
89f2df13d003c63d32f8ca669a565e5cefb69a81
example programs
diff --git a/src/thelloworld.py b/src/thelloworld.py new file mode 100755 index 0000000..0f1ed61 --- /dev/null +++ b/src/thelloworld.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python +# +# Copyright 2009 Facebook +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import tornado.httpserver +import tornado.ioloop +import tornado.options +import tornado.web + +from tornado.options import define, options + +define("port", default=8888, help="run on the given port", type=int) + + +class MainHandler(tornado.web.RequestHandler): + def get(self): + self.write("Hello, world") + + +def main(): + tornado.options.parse_command_line() + application = tornado.web.Application([ + (r"/", MainHandler), + ]) + http_server = tornado.httpserver.HTTPServer(application) + http_server.listen(options.port) + tornado.ioloop.IOLoop.instance().start() + + +if __name__ == "__main__": + main() diff --git a/src/tsockhttp.py b/src/tsockhttp.py new file mode 100644 index 0000000..50f95e3 --- /dev/null +++ b/src/tsockhttp.py @@ -0,0 +1,35 @@ +# taken from http://nichol.as/asynchronous-servers-in-python + +import errno +import functools +import socket +from tornado import ioloop, iostream + + +def connection_ready(sock, fd, events): + while True: + try: + connection, address = sock.accept() + except socket.error, e: + if e[0] not in (errno.EWOULDBLOCK, errno.EAGAIN): + raise + return + connection.setblocking(0) + stream = iostream.IOStream(connection) + stream.write("HTTP/1.0 200 OK\r\nContent-Length: 5\r\n\r\nPong!\r\n", stream.close) + +if __name__ == '__main__': + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.setblocking(0) + sock.bind(("", 8010)) + sock.listen(5000) + + io_loop = ioloop.IOLoop.instance() + callback = functools.partial(connection_ready, sock) + io_loop.add_handler(sock.fileno(), callback, io_loop.READ) + try: + io_loop.start() + except KeyboardInterrupt: + io_loop.stop() + print "exited cleanly"
wil/gtornado
bb88f274d59b0f47bbcff063115c37b14ace1909
make monkey runnable
diff --git a/src/gtornado/monkey.py b/src/gtornado/monkey.py index 6652e73..838f7ea 100644 --- a/src/gtornado/monkey.py +++ b/src/gtornado/monkey.py @@ -1,261 +1,316 @@ import time import cgi import gevent import gevent.hub import gevent.http -def patch_tornado_ioloop(): +def patch_ioloop(): _tornado_iol = __import__('tornado.ioloop', fromlist=['fromlist_has_to_be_non_empty']) _IOLoop = _tornado_iol.IOLoop class IOLoop: READ = _IOLoop.READ WRITE = _IOLoop.WRITE ERROR = _IOLoop.ERROR def __init__(self): self._handlers = {} # by fd self._events = {} # by fd def start(self): gevent.hub.get_hub().switch() def stop(self): for e,fd in list(self._events.iteritems()): self.remove_handler(e) gevent.hub.shutdown() def remove_handler(self, fd): self._handlers.pop(fd, None) ev = self._events.pop(fd, None) ev.cancel() def update_handler(self, fd, events): handler = self._handlers.pop(fd, None) self.remove_handler(fd) self.add_handler(fd, handler, events) def add_handler(self, fd, handler, events): type = gevent.core.EV_PERSIST if events & _IOLoop.READ: type = type | gevent.core.EV_READ if events & _IOLoop.WRITE: type = type | gevent.core.EV_WRITE if events & _IOLoop.ERROR: type = type | gevent.core.EV_READ def callback(ev, type): #print "ev=%r type=%r firing" % (ev, type) tornado_events = 0 if type & gevent.core.EV_READ: tornado_events |= _IOLoop.READ if type & gevent.core.EV_WRITE: tornado_events |= _IOLoop.WRITE if type & gevent.core.EV_SIGNAL: tornado_events |= _IOLoop.ERROR return handler(ev.fd, tornado_events) #print "add_handler(fd=%r, handler=%r, events=%r)" % (fd, handler, events) #print "type => %r" % type e = gevent.core.event(type, fd, callback) e.add() self._events[fd] = e self._handlers[fd] = handler def add_callback(self, callback): print "adding callback" gevent.spawn(callback) def add_timeout(self, deadline, callback): print "adding callback" gevent.spawn_later(int(deadline - time.time()), callback) @classmethod def instance(cls): if not hasattr(cls, "_instance"): print "new instance?" cls._instance = cls() return cls._instance #print "orig ioloop = ", dir(_tornado_iol) _tornado_iol.IOLoop = IOLoop #print "iol = ", id(_tornado_iol.IOLoop) -def patch_tornado_httpserver(): +def patch_httpserver(): from tornado.httpserver import HTTPRequest def parse_t_http_output(buf): headers, body = buf.split("\r\n\r\n", 1) headers = headers.split("\r\n") ver, code, msg = headers[0].split(" ", 2) code = int(code) chunked = False headers_out = [] for h in headers[1:]: k, v = h.split(":", 1) if k == "Transfer-Encoding" and v == "chunked": chunked = True headers_out.append((k, v.lstrip())) return code, msg, headers_out, body, chunked def parse_post_body(req, body): content_type = req.headers.get("Content-Type", "") if req.method == "POST": if content_type.startswith("application/x-www-form-urlencoded"): arguments = cgi.parse_qs(req.body) for name, values in arguments.iteritems(): values = [v for v in values if v] if values: req.arguments.setdefault(name, []).extend(values) elif content_type.startswith("multipart/form-data"): boundary = content_type[30:] if boundary: self._parse_mime_body(boundary, data) # from HTTPConnection._parse_mime_body if data.endswith("\r\n"): footer_length = len(boundary) + 6 else: footer_length = len(boundary) + 4 parts = data[:-footer_length].split("--" + boundary + "\r\n") for part in parts: if not part: continue eoh = part.find("\r\n\r\n") if eoh == -1: logging.warning("multipart/form-data missing headers") continue headers = HTTPHeaders.parse(part[:eoh]) name_header = headers.get("Content-Disposition", "") if not name_header.startswith("form-data;") or \ not part.endswith("\r\n"): logging.warning("Invalid multipart/form-data") continue value = part[eoh + 4:-2] name_values = {} for name_part in name_header[10:].split(";"): name, name_value = name_part.strip().split("=", 1) name_values[name] = name_value.strip('"').decode("utf-8") if not name_values.get("name"): logging.warning("multipart/form-data value missing name") continue name = name_values["name"] if name_values.get("filename"): ctype = headers.get("Content-Type", "application/unknown") req.files.setdefault(name, []).append(dict( filename=name_values["filename"], body=value, content_type=ctype)) else: req.arguments.setdefault(name, []).append(value) class FakeStream(): def __init__(self): self._closed = False def closed(self): print "stream closed = ", self._closed return self._closed class FakeConnection(): def __init__(self, r): self._r = r self.xheaders = False self.reply_started = False self.stream = FakeStream() #r.connection.set_closecb(self) def _cb_connection_close(self, conn): print "connection %r closed!!!!" % (conn,) print "stream = %r" % self.stream self.stream._closed = True print "flagged stream as closed" def write(self, chunk): if not self.reply_started: #print "starting reply..." # need to parse the first line as RequestHandler actually writes the response line code, msg, headers, body, chunked = parse_t_http_output(chunk) for k, v in headers: #print "header[%s] = %s" % (k, v) self._r.add_output_header(k, v) if chunked: self._r.send_reply_start(code, msg) self._r.send_reply_chunk(body) else: self._r.send_reply(code, msg, body) self.reply_started = True else: print "writing %s" % chunk self._r.send_reply_chunk(chunk) def finish(self): - print "finishing..." self._r.send_reply_end() - print "finished" class GHttpServer: def __init__(self, t_app): def debug_http_cb(r): print "http request = ", r for m in dir(r): o = eval("r." + m) if type(o) in (str, list, int, tuple): print "r.%s = %r" % (m, o) r.add_output_header("X-Awesomeness", "100%") r.send_reply(200, "OK", '<b>hello</b>') def http_cb(r): body = r.input_buffer.read() treq = HTTPRequest( r.typestr, # method r.uri, # uri headers=dict(r.get_input_headers()), # need to transform from list of tuples to dict body=body, remote_ip=r.remote_host, protocol="http", # or https host=None, # 127.0.0.1? files=None, # ?? connection=FakeConnection(r)) parse_post_body(treq, body) """ print "http request = ", r for m in dir(r): o = eval("r." + m) if type(o) in (str, list, int, tuple): print "r.%s = %r" % (m, o) """ t_app(treq) self._httpserver = gevent.http.HTTPServer(http_cb) def listen(self, port): self._httpserver.serve_forever(('0.0.0.0', port), backlog=128) @classmethod def instance(cls): - print "new instance?" if not hasattr(cls, "_instance"): cls._instance = cls() return cls._instance _httpserver = __import__('tornado.httpserver', fromlist=['fromlist_has_to_be_non_empty']) _httpserver.HTTPServer = GHttpServer -def patch_tornado(): - patch_tornado_ioloop() - patch_tornado_httpserver() +def patch_all(ioloop=True, httpserver=True): + if ioloop: + print "Patching ioloop" + patch_ioloop() + + if httpserver: + print "Patching httpserver" + patch_httpserver() + + +# code below shamelessly stolen from gevent.monkey +if __name__=='__main__': + import sys + modules = [x.replace('patch_', '') for x in globals().keys() if x.startswith('patch_') and x!='patch_all'] + script_help = """gtornado.monkey - monkey patch the tornado modules to use gevent. + +USAGE: python -m gtornado.monkey [MONKEY OPTIONS] script [SCRIPT OPTIONS] + +If no OPTIONS present, monkey patches all the modules it can patch. +You can exclude a module with --no-module, e.g. --no-thread. You can +specify a module to patch with --module, e.g. --socket. In the latter +case only the modules specified on the command line will be patched. + +MONKEY OPTIONS: --verbose %s""" % ', '.join('--[no-]%s' % m for m in modules) + args = {} + argv = sys.argv[1:] + verbose = False + default_yesno = True + while argv and argv[0].startswith('--'): + option = argv[0][2:] + if option == 'verbose': + verbose = True + elif option.startswith('no-') and option.replace('no-', '') in modules: + args[option[3:]] = False + elif option in modules: + args[option] = True + default_yesno = False + else: + sys.exit(script_help + '\n\n' + 'Cannot patch %r' % option) + del argv[0] + + for m in modules: + if args and m not in args: + args[m] = default_yesno + + if verbose: + import pprint, os + print 'gtornado.monkey.patch_all(%s)' % ', '.join('%s=%s' % item for item in args.items()) + print 'sys.version=%s' % (sys.version.strip().replace('\n', ' '), ) + print 'sys.path=%s' % pprint.pformat(sys.path) + print 'sys.modules=%s' % pprint.pformat(sorted(sys.modules.keys())) + print 'cwd=%s' % os.getcwd() + + patch_all(**args) + if argv: + sys.argv = argv + __package__ = None + execfile(sys.argv[0]) + else: + print script_help +
wil/gtornado
7e8efb1eee69601b2a5a6d20aa0bc2dabc7ba9e0
ignore .pyc
diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 0000000..c9b568f --- /dev/null +++ b/src/.gitignore @@ -0,0 +1,2 @@ +*.pyc +*.swp diff --git a/src/gt/__init__.pyc b/src/gt/__init__.pyc deleted file mode 100644 index b6f9255..0000000 Binary files a/src/gt/__init__.pyc and /dev/null differ diff --git a/src/gt/monkey.pyc b/src/gt/monkey.pyc deleted file mode 100644 index e4497e9..0000000 Binary files a/src/gt/monkey.pyc and /dev/null differ
wil/gtornado
578f50d2c37f17f39f4ed5d0f2e0c9a793b3600a
IOLoop fixes
diff --git a/src/gt/monkey.py b/src/gt/monkey.py index cb30e8b..6652e73 100644 --- a/src/gt/monkey.py +++ b/src/gt/monkey.py @@ -1,247 +1,261 @@ import time import cgi import gevent import gevent.hub import gevent.http def patch_tornado_ioloop(): _tornado_iol = __import__('tornado.ioloop', fromlist=['fromlist_has_to_be_non_empty']) _IOLoop = _tornado_iol.IOLoop class IOLoop: + READ = _IOLoop.READ + WRITE = _IOLoop.WRITE + ERROR = _IOLoop.ERROR + def __init__(self): self._handlers = {} # by fd self._events = {} # by fd def start(self): gevent.hub.get_hub().switch() + def stop(self): + for e,fd in list(self._events.iteritems()): + self.remove_handler(e) + + gevent.hub.shutdown() + def remove_handler(self, fd): self._handlers.pop(fd, None) ev = self._events.pop(fd, None) ev.cancel() def update_handler(self, fd, events): handler = self._handlers.pop(fd, None) - ev = self._events[fd] self.remove_handler(fd) self.add_handler(fd, handler, events) def add_handler(self, fd, handler, events): - type = 0 + type = gevent.core.EV_PERSIST if events & _IOLoop.READ: type = type | gevent.core.EV_READ if events & _IOLoop.WRITE: type = type | gevent.core.EV_WRITE if events & _IOLoop.ERROR: - type = type | gevent.core.EV_SIGNAL + type = type | gevent.core.EV_READ def callback(ev, type): + #print "ev=%r type=%r firing" % (ev, type) tornado_events = 0 if type & gevent.core.EV_READ: tornado_events |= _IOLoop.READ if type & gevent.core.EV_WRITE: tornado_events |= _IOLoop.WRITE if type & gevent.core.EV_SIGNAL: tornado_events |= _IOLoop.ERROR return handler(ev.fd, tornado_events) - self._events[fd] = gevent.core.event(type, fd, callback) + #print "add_handler(fd=%r, handler=%r, events=%r)" % (fd, handler, events) + #print "type => %r" % type + e = gevent.core.event(type, fd, callback) + e.add() + self._events[fd] = e self._handlers[fd] = handler def add_callback(self, callback): print "adding callback" gevent.spawn(callback) def add_timeout(self, deadline, callback): print "adding callback" gevent.spawn_later(int(deadline - time.time()), callback) @classmethod def instance(cls): - print "new instance?" if not hasattr(cls, "_instance"): + print "new instance?" cls._instance = cls() return cls._instance #print "orig ioloop = ", dir(_tornado_iol) _tornado_iol.IOLoop = IOLoop #print "iol = ", id(_tornado_iol.IOLoop) def patch_tornado_httpserver(): from tornado.httpserver import HTTPRequest def parse_t_http_output(buf): headers, body = buf.split("\r\n\r\n", 1) headers = headers.split("\r\n") ver, code, msg = headers[0].split(" ", 2) code = int(code) chunked = False headers_out = [] for h in headers[1:]: k, v = h.split(":", 1) if k == "Transfer-Encoding" and v == "chunked": chunked = True headers_out.append((k, v.lstrip())) return code, msg, headers_out, body, chunked def parse_post_body(req, body): content_type = req.headers.get("Content-Type", "") if req.method == "POST": if content_type.startswith("application/x-www-form-urlencoded"): arguments = cgi.parse_qs(req.body) for name, values in arguments.iteritems(): values = [v for v in values if v] if values: req.arguments.setdefault(name, []).extend(values) elif content_type.startswith("multipart/form-data"): boundary = content_type[30:] if boundary: self._parse_mime_body(boundary, data) # from HTTPConnection._parse_mime_body if data.endswith("\r\n"): footer_length = len(boundary) + 6 else: footer_length = len(boundary) + 4 parts = data[:-footer_length].split("--" + boundary + "\r\n") for part in parts: if not part: continue eoh = part.find("\r\n\r\n") if eoh == -1: logging.warning("multipart/form-data missing headers") continue headers = HTTPHeaders.parse(part[:eoh]) name_header = headers.get("Content-Disposition", "") if not name_header.startswith("form-data;") or \ not part.endswith("\r\n"): logging.warning("Invalid multipart/form-data") continue value = part[eoh + 4:-2] name_values = {} for name_part in name_header[10:].split(";"): name, name_value = name_part.strip().split("=", 1) name_values[name] = name_value.strip('"').decode("utf-8") if not name_values.get("name"): logging.warning("multipart/form-data value missing name") continue name = name_values["name"] if name_values.get("filename"): ctype = headers.get("Content-Type", "application/unknown") req.files.setdefault(name, []).append(dict( filename=name_values["filename"], body=value, content_type=ctype)) else: req.arguments.setdefault(name, []).append(value) class FakeStream(): def __init__(self): self._closed = False def closed(self): print "stream closed = ", self._closed return self._closed class FakeConnection(): def __init__(self, r): self._r = r self.xheaders = False self.reply_started = False self.stream = FakeStream() #r.connection.set_closecb(self) def _cb_connection_close(self, conn): print "connection %r closed!!!!" % (conn,) print "stream = %r" % self.stream self.stream._closed = True print "flagged stream as closed" def write(self, chunk): if not self.reply_started: #print "starting reply..." # need to parse the first line as RequestHandler actually writes the response line code, msg, headers, body, chunked = parse_t_http_output(chunk) for k, v in headers: #print "header[%s] = %s" % (k, v) self._r.add_output_header(k, v) if chunked: self._r.send_reply_start(code, msg) self._r.send_reply_chunk(body) else: self._r.send_reply(code, msg, body) self.reply_started = True else: print "writing %s" % chunk self._r.send_reply_chunk(chunk) def finish(self): print "finishing..." self._r.send_reply_end() print "finished" class GHttpServer: def __init__(self, t_app): def debug_http_cb(r): print "http request = ", r for m in dir(r): o = eval("r." + m) if type(o) in (str, list, int, tuple): print "r.%s = %r" % (m, o) r.add_output_header("X-Awesomeness", "100%") r.send_reply(200, "OK", '<b>hello</b>') def http_cb(r): body = r.input_buffer.read() treq = HTTPRequest( r.typestr, # method r.uri, # uri headers=dict(r.get_input_headers()), # need to transform from list of tuples to dict body=body, remote_ip=r.remote_host, protocol="http", # or https host=None, # 127.0.0.1? files=None, # ?? connection=FakeConnection(r)) parse_post_body(treq, body) """ print "http request = ", r for m in dir(r): o = eval("r." + m) if type(o) in (str, list, int, tuple): print "r.%s = %r" % (m, o) """ t_app(treq) self._httpserver = gevent.http.HTTPServer(http_cb) def listen(self, port): self._httpserver.serve_forever(('0.0.0.0', port), backlog=128) @classmethod def instance(cls): print "new instance?" if not hasattr(cls, "_instance"): cls._instance = cls() return cls._instance _httpserver = __import__('tornado.httpserver', fromlist=['fromlist_has_to_be_non_empty']) _httpserver.HTTPServer = GHttpServer def patch_tornado(): patch_tornado_ioloop() patch_tornado_httpserver()
wil/gtornado
614e5e0783a9504c5b5a33d8d7909be1da3af72e
reverse the components :)
diff --git a/README.rst b/README.rst index 169db54..c2b1b6f 100644 --- a/README.rst +++ b/README.rst @@ -1,19 +1,19 @@ -gtornado = Tornado + gevent +gtornado = gevent + Tornado =========================== Introduction ------------ Tornado_ is a high performance web server and framework. It operates in a non-blocking fashion, utilizing Linux's epoll_ facility when available. It also comes bundled with several niceties such as authentication via OpenID, OAuth, secure cookies, templates, CSRF protection and UI modules. Unfortunately, some of its features ties the developer into its own asynchronous API implementation. This module is an experiment to monkey patch it just enough to make it run under gevent. One advantage of doing so is that one can use a coroutine-style and code in a blocking fashion while being able to use the tornado framework. .. _Tornado: http://www.tornadoweb.org/ .. _epoll: http://www.kernel.org/doc/man-pages/online/pages/man4/epoll.4.html
wil/gtornado
fa29c796c90e22d8c0a335d99fa21a50417400fb
move README.rst to top level
diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..4b3e4eb --- /dev/null +++ b/README.rst @@ -0,0 +1,22 @@ +gtornado = Tornado + gevent +=========================== + +:Author: Wil Tan +:Version: $Revision: + + +Introduction +------------ + +Tornado_ is a high performance web server and framework. It operates in a non-blocking fashion, +utilizing Linux's epoll_ facility when available. It also comes bundled with several niceties +such as authentication via OpenID, OAuth, secure cookies, templates, CSRF protection and UI modules. + +Unfortunately, some of its features ties the developer into its own asynchronous API implementation. + +This module is an experiment to monkey patch it just enough to make it run under gevent. +One advantage of doing so is that one can use a coroutine-style and code in a blocking fashion +while being able to use the tornado framework. + +.. _Tornado: http://www.tornadoweb.org/ +.. _epoll: http://www.kernel.org/doc/man-pages/online/pages/man4/epoll.4.html
ctb/lamprey-est-map
efe7bd53e2d9fbf55899d2a128bbeddd0294d30f
added option to not parse attributes
diff --git a/gff_parser.py b/gff_parser.py index ffbf1a7..75470e6 100644 --- a/gff_parser.py +++ b/gff_parser.py @@ -1,118 +1,122 @@ """GFF parser. See http://www.sequenceontology.org/gff3.shtml. Note, for gap format, see http://may2005.archive.ensembl.org/Docs/wiki/html/EnsemblDocs/CigarFormat.html read(fp) is the main function provided by this module. """ import csv import urllib DELIMITER='\t' FIELDNAMES = ['seqid', 'source', 'type', 'start', 'end', 'score', 'strand', 'phase', 'attributes' ] class Bag(dict): """dict-like class that supports attribute access as well as getitem. >>> x = Bag() >>> x['foo'] = 'bar' >>> x.foo 'bar' """ def __init__(self, *args, **kw): dict.__init__(self, *args, **kw) for k in self.keys(): self.__dict__[k] = self.__getitem__(k) def __setitem__(self, k, v): dict.__setitem__(self, k, v) self.__dict__[k] = v -def read(fp): +def read(fp, parse_attributes=True): """Parse the given fp as GFF3, yielding Bag objects containing row info. """ reader = csv.DictReader(fp, delimiter=DELIMITER, fieldnames=FIELDNAMES) for row in reader: if row['seqid'].startswith('#'): continue - # pick out the attributes and deal with them specially: - # - only unquote after splitting on ; - # - make them into a dictionary - - attr = row['attributes'] - attr = attr.split(';') - attr_d = Bag() - for kv in attr: - k, v = kv.split('=', 1) - k, v = urllib.unquote(k), urllib.unquote(v) - attr_d[k] = v - # unquote all of the other values & store them in a new dict row_d = Bag([ (k, urllib.unquote(v)) for (k, v) in row.items() \ if k != 'attributes' ]) # convert int coords row_d['start'] = int(row_d['start']) row_d['end'] = int(row_d['end']) - # save attributes back into it - row_d['attributes'] = attr_d + if parse_attributes: + # pick out the attributes and deal with them specially: + # - only unquote after splitting on ; + # - make them into a dictionary + + attr = row['attributes'] + attr = attr.split(';') + attr_d = Bag() + for kv in attr: + k, v = kv.split('=', 1) + k, v = urllib.unquote(k), urllib.unquote(v) + attr_d[k] = v + + # save attributes back into it + row_d['attributes'] = attr_d + else: + # we don't want to unquote them if we're not parsing. + row_d['attributes'] = row['attributes'] # done! yield row_d parent_collector_fn = lambda x: x.attributes.Parent def read_groups(fp, collector_fn=None): """Read collections, grouping by provided criterion. Default is Parent. 'collector_fn' is an optional callable that returns a cookie; this cookie is used to decide whether or not to start a new collection. It should return something with reasonable '==' behavior (e.g. a string!) and should never return None. Note, groupings must be contiguous within file. Returns lists of Bag objects representing each row. """ if collector_fn is None: collector_fn = parent_collector_fn parent = None collect = [] for row in read(fp): if parent != collector_fn(row): if collect: yield collect collect = [] parent = collector_fn(row) collect.append(row) if collect: yield collect def parse_target(row): """Extract Target attr information from the given row.""" target = row.attributes.Target.split(' ') name, start, stop = target[:3] ori = '+' if len(target) == 4: ori = target[3] return name, int(start), int(stop), ori if __name__ == '__main__': import doctest doctest.testmod()
ctb/lamprey-est-map
46c84aec690fe8d9cbc8cec9644a80867a9f1164
drawing code
diff --git a/draw.py b/draw.py new file mode 100644 index 0000000..2e1112b --- /dev/null +++ b/draw.py @@ -0,0 +1,35 @@ +from pygr import seqdb, cnestedlist +import pygr_draw +from pygr_draw.annotation import SequenceWrapperFactory, SequenceWrapper + +# load in the NLMSAs +est_map = '/u/t/dev/lamprey-est-map/data/52/aln-52' +al1 = cnestedlist.NLMSA(est_map) + +# plot the ESTs with names == sequence.id, color == 'red' +wrapper_est = SequenceWrapperFactory(color='red') + +reads_filename = '/u/t/dev/lamprey-est-map/data/brain-rnaseq/lamprey30M2H/s_1_al-trim3-20' +al2 = cnestedlist.NLMSA(reads_filename) +wrapper_read = SequenceWrapperFactory(name='') + +# because we're not using pygr.Data, the NLMSAs have different seqdbs +# for the supercontigs. We have to munge them to make them the same +# so that we can do a single draw. EVIL. Ignore Me. +sc = al1.seqDict.prefixDict['supercontigs'] +al2.seqDict.prefixDict['supercontigs'] = al1.seqDict.prefixDict['supercontigs'] +al2.seqDict.dicts[sc] = 'supercontigs' + +# choose the sequence to plot +contig1 = al1.seqDict['supercontigs.Contig0'][:5000] + +# build a png +picture_class = pygr_draw.BitmapSequencePicture +p = pygr_draw.draw_annotation_maps(contig1, (al1, al2), + picture_class=picture_class, + wrappers=(wrapper_est, wrapper_read)) + +# write out +image = p.finalize() +filename = 'draw.png' +open(filename, 'w').write(image)
ctb/lamprey-est-map
0493a9ba7b82bfaf6051557c1860e24d8ed132d1
bowtie parsing & some pygr-draw interface code
diff --git a/bowtie-to-nlmsa.py b/bowtie-to-nlmsa.py new file mode 100644 index 0000000..c132b40 --- /dev/null +++ b/bowtie-to-nlmsa.py @@ -0,0 +1,18 @@ +import sys +import bowtie_parser +import bowtie_pygr +from pygr import seqdb, cnestedlist + +genome_db = seqdb.SequenceFileDB('/scratch/titus/lamprey/supercontigs.fa') +reads_db = seqdb.SequenceFileDB('/scratch/titus/lamprey/brain-rnaseq/lamprey30M2H/s_1_sequence.fasta') + +def counter(g, when): + for n, x in enumerate(g): + if n % when == 0: + print '...', n + yield x + +al = cnestedlist.NLMSA(sys.argv[1], mode='w', pairwiseMode=True) +fp = open(sys.argv[2]) +bowtie_pygr.build_alignment(al, counter(fp, 1000), genome_db, reads_db) +al.build(saveSeqDict=True) diff --git a/bowtie_parser.py b/bowtie_parser.py new file mode 100644 index 0000000..606a34d --- /dev/null +++ b/bowtie_parser.py @@ -0,0 +1,51 @@ +"""Bowtie parser. + +See http://bowtie-bio.sourceforge.net/manual.shtml#algn_out + +read(fp) is the main function provided by this module. +""" + +import csv +import urllib + +DELIMITER='\t' +FIELDNAMES = ['readname', 'strand', 'seqid', 'start', 'read', 'readqual', '_', + 'mismatches'] + +class Bag(dict): + """dict-like class that supports attribute access as well as getitem. + + >>> x = Bag() + >>> x['foo'] = 'bar' + >>> x.foo + 'bar' + + """ + def __init__(self, *args, **kw): + dict.__init__(self, *args, **kw) + for k in self.keys(): + self.__dict__[k] = self.__getitem__(k) + + def __setitem__(self, k, v): + dict.__setitem__(self, k, v) + self.__dict__[k] = v + +def read(fp): + """Parse the given fp as Bowtie output, yielding Bag objects. + """ + + reader = csv.DictReader(fp, delimiter=DELIMITER, fieldnames=FIELDNAMES) + + for row in reader: + # store values in a Bag instead of a dict + row_d = Bag(row) + + # convert start to int + row_d['start'] = int(row_d['start']) + + # done! + yield row_d + +if __name__ == '__main__': + import doctest + doctest.testmod() diff --git a/bowtie_pygr.py b/bowtie_pygr.py new file mode 100644 index 0000000..da2dc63 --- /dev/null +++ b/bowtie_pygr.py @@ -0,0 +1,25 @@ +import bowtie_parser + +def get_src_sequence(db, row): + seq = db[row.seqid] + start = row.start + stop = start + len(row.read) + return seq[start:stop] + +def get_read_sequence(db, row): + seq = db[row.readname] + if row.strand == '-': + seq = -seq + + return seq + +def build_ivals(fp, genome_db, reads_db): + for row in bowtie_parser.read(fp): + src_seq = get_src_sequence(genome_db, row) + read_seq = get_read_sequence(reads_db, row) + + yield src_seq, read_seq + +def build_alignment(al, fp, genome_db, ests_db): + """Build an NLMSA out of the bowtie mapping in fp.""" + al.add_aligned_intervals(build_ivals(fp, genome_db, ests_db)) diff --git a/gmap_pygr.py b/gmap_pygr.py index 1912eac..d069174 100644 --- a/gmap_pygr.py +++ b/gmap_pygr.py @@ -1,80 +1,80 @@ """ Parse GFF3 output from GMAP, and build pygr NLMSAs with it. For GMAP, see: http://www.gene.com/share/gmap/ http://www.gene.com/share/gmap/src/README http://bioinformatics.oxfordjournals.org/cgi/content/full/21/9/1859 For pygr, see: http://code.google.com/p/pygr/ Author: C. Titus Brown, <[email protected]> """ import gff_parser def get_src_sequence(db, row): """Extract the source sequence from the given GFF row and seqdb.""" seq = db[row.seqid][row.start - 1:row.end] if row.strand == '-': seq = -seq return seq def get_dest_sequence(db, row): """Parse the Target attribute and extract the associated sequence.""" name, start, stop, ori = gff_parser.parse_target(row) seq = db[name][start - 1:stop] if ori == '-': seq = -seq return seq def gaps(row): """Parse the gmap 'Tags' attribute.""" g = row.attributes.Gap g = g.split(' ') for x in g: typ, n = x[0], int(x[1:]) yield typ, n def build_ivals(fp, genome_db, ests_db): """Generate aligned intervals based on the GMAP/GFF3 data in 'fp'. Yields (pathname, ivals) where ivals is a list of interval pairs. """ - for n, row in enumerate(gff_parser.read(fp)): + for row in gff_parser.read(fp): ivals = [] src_seq = get_src_sequence(genome_db, row) dest_seq = get_dest_sequence(ests_db, row) src_i = 0 dst_i = 0 for typ, m in gaps(row): if typ == 'M': # full match src_ival = src_seq[src_i:src_i + m] dst_ival = dest_seq[dst_i:dst_i + m] ivals.append((src_ival, dst_ival)) src_i += m dst_i += m elif typ == 'I': # insertion on dest seq dst_i += m elif typ == 'D': # insertion on src seq src_i += m else: raise Exception, "unknown char in Gap attr: %s%d" % (typ, m) yield row.attributes.ID, ivals def build_alignment(al, fp, genome_db, ests_db): """Build an NLMSA out of the GMAP alignment in fp.""" for path, ivals in build_ivals(fp, genome_db, ests_db): al.add_aligned_intervals(ivals) if __name__ == '__main__': pass diff --git a/test.py b/test.py index 133e244..c132b40 100644 --- a/test.py +++ b/test.py @@ -1,9 +1,18 @@ import sys -import gff_parser +import bowtie_parser +import bowtie_pygr +from pygr import seqdb, cnestedlist -fp = open(sys.argv[1]) +genome_db = seqdb.SequenceFileDB('/scratch/titus/lamprey/supercontigs.fa') +reads_db = seqdb.SequenceFileDB('/scratch/titus/lamprey/brain-rnaseq/lamprey30M2H/s_1_sequence.fasta') -for n, row in enumerate(gff_parser.read(fp)): - print row.attributes.Gap - if n > 100: - break +def counter(g, when): + for n, x in enumerate(g): + if n % when == 0: + print '...', n + yield x + +al = cnestedlist.NLMSA(sys.argv[1], mode='w', pairwiseMode=True) +fp = open(sys.argv[2]) +bowtie_pygr.build_alignment(al, counter(fp, 1000), genome_db, reads_db) +al.build(saveSeqDict=True) diff --git a/test2.py b/test2.py index d1f216d..9cb6c49 100644 --- a/test2.py +++ b/test2.py @@ -1,10 +1,10 @@ import sys from pygr import seqdb, cnestedlist al = cnestedlist.NLMSA(sys.argv[1]) -contig1 = al.seqDict['supercontigs.Contig1'] +contig1 = al.seqDict['supercontigs.Contig0'] slice = al[contig1] for (src, dest, edge) in slice.edges(): print repr(src), repr(dest), edge.pIdentity()
ctb/lamprey-est-map
3dc89fa5c8b130fdda6f7256d242836c1174c7a5
finished NLMSA building code
diff --git a/gmap-to-nlmsa.py b/gmap-to-nlmsa.py new file mode 100644 index 0000000..c32ad23 --- /dev/null +++ b/gmap-to-nlmsa.py @@ -0,0 +1,25 @@ +import sys +import gff_parser +import gmap_pygr +import pprint +from pygr import seqdb, cnestedlist +from itertools import izip + +genome = '/scratch/titus/lamprey/supercontigs.fa' +ests = '/scratch/titus/lamprey/Pma200805_collapsed_ESTs.fasta' + +genome_db = seqdb.SequenceFileDB(genome) +ests_db = seqdb.SequenceFileDB(ests) + +def counter(g, when): + for n, x in enumerate(g): + if n % when == 0: + print '...', n + yield x + +gmap_fp = open(sys.argv[1]) +al_name = sys.argv[2] + +al = cnestedlist.NLMSA(al_name, 'w', pairwiseMode=True) +gmap_pygr.build_alignment(al, counter(gmap_fp, 1000), genome_db, ests_db) +al.build(saveSeqDict=True) diff --git a/gmap_pygr.py b/gmap_pygr.py index a2385c4..1912eac 100644 --- a/gmap_pygr.py +++ b/gmap_pygr.py @@ -1,75 +1,80 @@ """ Parse GFF3 output from GMAP, and build pygr NLMSAs with it. For GMAP, see: http://www.gene.com/share/gmap/ http://www.gene.com/share/gmap/src/README http://bioinformatics.oxfordjournals.org/cgi/content/full/21/9/1859 For pygr, see: http://code.google.com/p/pygr/ Author: C. Titus Brown, <[email protected]> """ import gff_parser def get_src_sequence(db, row): """Extract the source sequence from the given GFF row and seqdb.""" seq = db[row.seqid][row.start - 1:row.end] if row.strand == '-': seq = -seq return seq def get_dest_sequence(db, row): """Parse the Target attribute and extract the associated sequence.""" name, start, stop, ori = gff_parser.parse_target(row) seq = db[name][start - 1:stop] if ori == '-': seq = -seq return seq def gaps(row): """Parse the gmap 'Tags' attribute.""" g = row.attributes.Gap g = g.split(' ') for x in g: typ, n = x[0], int(x[1:]) yield typ, n def build_ivals(fp, genome_db, ests_db): """Generate aligned intervals based on the GMAP/GFF3 data in 'fp'. Yields (pathname, ivals) where ivals is a list of interval pairs. """ for n, row in enumerate(gff_parser.read(fp)): ivals = [] src_seq = get_src_sequence(genome_db, row) dest_seq = get_dest_sequence(ests_db, row) src_i = 0 dst_i = 0 for typ, m in gaps(row): if typ == 'M': # full match src_ival = src_seq[src_i:src_i + m] dst_ival = dest_seq[dst_i:dst_i + m] ivals.append((src_ival, dst_ival)) src_i += m dst_i += m elif typ == 'I': # insertion on dest seq dst_i += m elif typ == 'D': # insertion on src seq src_i += m else: raise Exception, "unknown char in Gap attr: %s%d" % (typ, m) yield row.attributes.ID, ivals +def build_alignment(al, fp, genome_db, ests_db): + """Build an NLMSA out of the GMAP alignment in fp.""" + for path, ivals in build_ivals(fp, genome_db, ests_db): + al.add_aligned_intervals(ivals) + if __name__ == '__main__': pass diff --git a/test2.py b/test2.py index 58a3699..d1f216d 100644 --- a/test2.py +++ b/test2.py @@ -1,23 +1,10 @@ import sys -import gff_parser -import gmap_pygr -import pprint from pygr import seqdb, cnestedlist -from itertools import izip -genome = '/scratch/titus/lamprey/supercontigs.fa' -ests = '/scratch/titus/lamprey/Pma200805_collapsed_ESTs.fasta' +al = cnestedlist.NLMSA(sys.argv[1]) -genome_db = seqdb.SequenceFileDB(genome) -ests_db = seqdb.SequenceFileDB(ests) +contig1 = al.seqDict['supercontigs.Contig1'] +slice = al[contig1] -fp = open(sys.argv[1]) -paths = gmap_pygr.build_ivals(fp, genome_db, ests_db) - -al = cnestedlist.NLMSA('foo', 'memory', pairwiseMode=True) -for n, (path, ivals) in enumerate(paths): - if n > 100: - break - al.add_aligned_intervals(ivals) - -al.build() +for (src, dest, edge) in slice.edges(): + print repr(src), repr(dest), edge.pIdentity()
ctb/lamprey-est-map
33baf64a0e3eaf23a84547ce34af300c5af8cb23
added *~ to ignore
diff --git a/.gitignore b/.gitignore index 0d20b64..f3d74a9 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ *.pyc +*~
ctb/lamprey-est-map
77372ad35642fe2c937c77a5e551d217ae49766d
build an alignment
diff --git a/test2.py b/test2.py index 2cf1276..58a3699 100644 --- a/test2.py +++ b/test2.py @@ -1,19 +1,23 @@ import sys import gff_parser import gmap_pygr import pprint -from pygr import seqdb +from pygr import seqdb, cnestedlist from itertools import izip genome = '/scratch/titus/lamprey/supercontigs.fa' ests = '/scratch/titus/lamprey/Pma200805_collapsed_ESTs.fasta' genome_db = seqdb.SequenceFileDB(genome) ests_db = seqdb.SequenceFileDB(ests) fp = open(sys.argv[1]) -ivals = gmap_pygr.build_ivals(fp, genome_db, ests_db) +paths = gmap_pygr.build_ivals(fp, genome_db, ests_db) -first100 = list(izip(range(100), ivals)) +al = cnestedlist.NLMSA('foo', 'memory', pairwiseMode=True) +for n, (path, ivals) in enumerate(paths): + if n > 100: + break + al.add_aligned_intervals(ivals) -pprint.pprint(first100) +al.build()
ctb/lamprey-est-map
857ea5a318735ec2d90495ff81a1a843549cc834
added gmap ival parser, docs.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0d20b64 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.pyc diff --git a/gff_parser.py b/gff_parser.py index 600f02f..ffbf1a7 100644 --- a/gff_parser.py +++ b/gff_parser.py @@ -1,113 +1,118 @@ -"""See http://www.sequenceontology.org/gff3.shtml. +"""GFF parser. -Note, for gaps, see +See http://www.sequenceontology.org/gff3.shtml. + +Note, for gap format, see http://may2005.archive.ensembl.org/Docs/wiki/html/EnsemblDocs/CigarFormat.html + +read(fp) is the main function provided by this module. """ import csv import urllib DELIMITER='\t' FIELDNAMES = ['seqid', 'source', 'type', 'start', 'end', 'score', 'strand', 'phase', 'attributes' ] class Bag(dict): """dict-like class that supports attribute access as well as getitem. >>> x = Bag() >>> x['foo'] = 'bar' >>> x.foo 'bar' """ def __init__(self, *args, **kw): dict.__init__(self, *args, **kw) for k in self.keys(): self.__dict__[k] = self.__getitem__(k) def __setitem__(self, k, v): dict.__setitem__(self, k, v) self.__dict__[k] = v def read(fp): """Parse the given fp as GFF3, yielding Bag objects containing row info. """ reader = csv.DictReader(fp, delimiter=DELIMITER, fieldnames=FIELDNAMES) for row in reader: if row['seqid'].startswith('#'): continue # pick out the attributes and deal with them specially: # - only unquote after splitting on ; # - make them into a dictionary attr = row['attributes'] attr = attr.split(';') attr_d = Bag() for kv in attr: k, v = kv.split('=', 1) k, v = urllib.unquote(k), urllib.unquote(v) attr_d[k] = v # unquote all of the other values & store them in a new dict row_d = Bag([ (k, urllib.unquote(v)) for (k, v) in row.items() \ if k != 'attributes' ]) # convert int coords row_d['start'] = int(row_d['start']) row_d['end'] = int(row_d['end']) # save attributes back into it row_d['attributes'] = attr_d # done! yield row_d parent_collector_fn = lambda x: x.attributes.Parent def read_groups(fp, collector_fn=None): """Read collections, grouping by provided criterion. Default is Parent. 'collector_fn' is an optional callable that returns a cookie; this cookie is used to decide whether or not to start a new collection. It should return something with reasonable '==' behavior (e.g. a string!) and should never return None. Note, groupings must be contiguous within file. Returns lists of Bag objects representing each row. """ if collector_fn is None: collector_fn = parent_collector_fn parent = None collect = [] for row in read(fp): if parent != collector_fn(row): if collect: yield collect collect = [] parent = collector_fn(row) collect.append(row) if collect: yield collect -def parse_target(s): - target = s.split(' ') +def parse_target(row): + """Extract Target attr information from the given row.""" + target = row.attributes.Target.split(' ') name, start, stop = target[:3] ori = '+' if len(target) == 4: ori = target[3] return name, int(start), int(stop), ori if __name__ == '__main__': import doctest doctest.testmod() diff --git a/gmap_pygr.py b/gmap_pygr.py new file mode 100644 index 0000000..a2385c4 --- /dev/null +++ b/gmap_pygr.py @@ -0,0 +1,75 @@ +""" +Parse GFF3 output from GMAP, and build pygr NLMSAs with it. + +For GMAP, see: + + http://www.gene.com/share/gmap/ + http://www.gene.com/share/gmap/src/README + http://bioinformatics.oxfordjournals.org/cgi/content/full/21/9/1859 + +For pygr, see: + http://code.google.com/p/pygr/ + +Author: C. Titus Brown, <[email protected]> +""" + +import gff_parser + +def get_src_sequence(db, row): + """Extract the source sequence from the given GFF row and seqdb.""" + seq = db[row.seqid][row.start - 1:row.end] + if row.strand == '-': + seq = -seq + + return seq + +def get_dest_sequence(db, row): + """Parse the Target attribute and extract the associated sequence.""" + name, start, stop, ori = gff_parser.parse_target(row) + + seq = db[name][start - 1:stop] + if ori == '-': + seq = -seq + + return seq + +def gaps(row): + """Parse the gmap 'Tags' attribute.""" + g = row.attributes.Gap + g = g.split(' ') + for x in g: + typ, n = x[0], int(x[1:]) + yield typ, n + +def build_ivals(fp, genome_db, ests_db): + """Generate aligned intervals based on the GMAP/GFF3 data in 'fp'. + + Yields (pathname, ivals) where ivals is a list of interval pairs. + """ + + for n, row in enumerate(gff_parser.read(fp)): + ivals = [] + src_seq = get_src_sequence(genome_db, row) + dest_seq = get_dest_sequence(ests_db, row) + + src_i = 0 + dst_i = 0 + for typ, m in gaps(row): + if typ == 'M': # full match + src_ival = src_seq[src_i:src_i + m] + dst_ival = dest_seq[dst_i:dst_i + m] + ivals.append((src_ival, dst_ival)) + + src_i += m + dst_i += m + elif typ == 'I': # insertion on dest seq + dst_i += m + elif typ == 'D': # insertion on src seq + src_i += m + else: + raise Exception, "unknown char in Gap attr: %s%d" % (typ, m) + + yield row.attributes.ID, ivals + +if __name__ == '__main__': + pass diff --git a/test2.py b/test2.py index 35b5940..2cf1276 100644 --- a/test2.py +++ b/test2.py @@ -1,71 +1,19 @@ import sys import gff_parser +import gmap_pygr +import pprint from pygr import seqdb +from itertools import izip genome = '/scratch/titus/lamprey/supercontigs.fa' ests = '/scratch/titus/lamprey/Pma200805_collapsed_ESTs.fasta' genome_db = seqdb.SequenceFileDB(genome) ests_db = seqdb.SequenceFileDB(ests) fp = open(sys.argv[1]) +ivals = gmap_pygr.build_ivals(fp, genome_db, ests_db) -for n, row in enumerate(gff_parser.read(fp)): - src_seq = genome_db[row.seqid][row.start - 1:row.end] - if row.strand == '-': - src_seq = -src_seq +first100 = list(izip(range(100), ivals)) - ## - - target_name, target_start, target_stop, target_ori = \ - gff_parser.parse_target(row.attributes.Target) - - target_seq = ests_db[target_name][target_start - 1:target_stop] - if target_ori == '-': - target_seq = -target_seq - - ## - - ivals = [] - gaps = row.attributes.Gap.split(' ') - - src_i = 0 - dst_i = 0 - for x in gaps: - typ, m = x[0], int(x[1:]) - - if typ == 'M': - src_ival = src_seq[src_i:src_i + m] - dst_ival = target_seq[dst_i:dst_i + m] - ivals.append((src_ival, dst_ival)) - - src_i += m - dst_i += m - elif typ == 'I': - dst_i += m - elif typ == 'D': - src_i += m - else: - raise Exception, "unknown char in Gap attr: %s%d" % (typ, m) - - for (src, dst) in ivals: - print row.seqid, row.start, row.end, ' == ', row.attributes.Target - print src - print dst - - s = str(src) - d = str(dst) - ident = 0 - for i in range(len(s)): - if s[i] == d[i]: - ident += 1 - - print row.score, int(ident / float(len(s)) * 100) - print row.strand, row.attributes.Target - print '' - - print '*' * 20 - - - if n > 100: - break +pprint.pprint(first100)
ctb/lamprey-est-map
01d5d7b112bd169194e5c05fc19cce6fac8c4e56
alignment building
diff --git a/gff_parser.py b/gff_parser.py index 542fd73..600f02f 100644 --- a/gff_parser.py +++ b/gff_parser.py @@ -1,99 +1,113 @@ """See http://www.sequenceontology.org/gff3.shtml. Note, for gaps, see http://may2005.archive.ensembl.org/Docs/wiki/html/EnsemblDocs/CigarFormat.html """ import csv import urllib DELIMITER='\t' FIELDNAMES = ['seqid', 'source', 'type', 'start', 'end', 'score', 'strand', 'phase', 'attributes' ] class Bag(dict): """dict-like class that supports attribute access as well as getitem. >>> x = Bag() >>> x['foo'] = 'bar' >>> x.foo 'bar' """ def __init__(self, *args, **kw): dict.__init__(self, *args, **kw) for k in self.keys(): self.__dict__[k] = self.__getitem__(k) def __setitem__(self, k, v): dict.__setitem__(self, k, v) self.__dict__[k] = v def read(fp): """Parse the given fp as GFF3, yielding Bag objects containing row info. """ reader = csv.DictReader(fp, delimiter=DELIMITER, fieldnames=FIELDNAMES) for row in reader: if row['seqid'].startswith('#'): continue # pick out the attributes and deal with them specially: # - only unquote after splitting on ; # - make them into a dictionary attr = row['attributes'] attr = attr.split(';') attr_d = Bag() for kv in attr: k, v = kv.split('=', 1) k, v = urllib.unquote(k), urllib.unquote(v) attr_d[k] = v # unquote all of the other values & store them in a new dict row_d = Bag([ (k, urllib.unquote(v)) for (k, v) in row.items() \ if k != 'attributes' ]) - + + # convert int coords + row_d['start'] = int(row_d['start']) + row_d['end'] = int(row_d['end']) + # save attributes back into it row_d['attributes'] = attr_d # done! yield row_d parent_collector_fn = lambda x: x.attributes.Parent def read_groups(fp, collector_fn=None): """Read collections, grouping by provided criterion. Default is Parent. 'collector_fn' is an optional callable that returns a cookie; this cookie is used to decide whether or not to start a new collection. It should return something with reasonable '==' behavior (e.g. a string!) and should never return None. Note, groupings must be contiguous within file. Returns lists of Bag objects representing each row. """ if collector_fn is None: collector_fn = parent_collector_fn parent = None collect = [] for row in read(fp): if parent != collector_fn(row): if collect: yield collect collect = [] parent = collector_fn(row) collect.append(row) if collect: yield collect +def parse_target(s): + target = s.split(' ') + name, start, stop = target[:3] + ori = '+' + if len(target) == 4: + ori = target[3] + + return name, int(start), int(stop), ori + if __name__ == '__main__': import doctest doctest.testmod() + diff --git a/test.py b/test.py index 96dbeb7..133e244 100644 --- a/test.py +++ b/test.py @@ -1,13 +1,9 @@ import sys import gff_parser -target_collector_fn = lambda row: row.attributes.Name - fp = open(sys.argv[1]) -n = 0 -for collect in gff_parser.read_groups(fp, target_collector_fn): - n += 1 - print set([ c.attributes.Name for c in collect ]) +for n, row in enumerate(gff_parser.read(fp)): + print row.attributes.Gap if n > 100: break diff --git a/test2.py b/test2.py new file mode 100644 index 0000000..35b5940 --- /dev/null +++ b/test2.py @@ -0,0 +1,71 @@ +import sys +import gff_parser +from pygr import seqdb + +genome = '/scratch/titus/lamprey/supercontigs.fa' +ests = '/scratch/titus/lamprey/Pma200805_collapsed_ESTs.fasta' + +genome_db = seqdb.SequenceFileDB(genome) +ests_db = seqdb.SequenceFileDB(ests) + +fp = open(sys.argv[1]) + +for n, row in enumerate(gff_parser.read(fp)): + src_seq = genome_db[row.seqid][row.start - 1:row.end] + if row.strand == '-': + src_seq = -src_seq + + ## + + target_name, target_start, target_stop, target_ori = \ + gff_parser.parse_target(row.attributes.Target) + + target_seq = ests_db[target_name][target_start - 1:target_stop] + if target_ori == '-': + target_seq = -target_seq + + ## + + ivals = [] + gaps = row.attributes.Gap.split(' ') + + src_i = 0 + dst_i = 0 + for x in gaps: + typ, m = x[0], int(x[1:]) + + if typ == 'M': + src_ival = src_seq[src_i:src_i + m] + dst_ival = target_seq[dst_i:dst_i + m] + ivals.append((src_ival, dst_ival)) + + src_i += m + dst_i += m + elif typ == 'I': + dst_i += m + elif typ == 'D': + src_i += m + else: + raise Exception, "unknown char in Gap attr: %s%d" % (typ, m) + + for (src, dst) in ivals: + print row.seqid, row.start, row.end, ' == ', row.attributes.Target + print src + print dst + + s = str(src) + d = str(dst) + ident = 0 + for i in range(len(s)): + if s[i] == d[i]: + ident += 1 + + print row.score, int(ident / float(len(s)) * 100) + print row.strand, row.attributes.Target + print '' + + print '*' * 20 + + + if n > 100: + break
mortenberg80/minimal_ircbot
b3c724cce68ab573e615bfd252433119fad6882c
added debug information
diff --git a/minimal_bot.py b/minimal_bot.py index 332e2d2..2d7181a 100644 --- a/minimal_bot.py +++ b/minimal_bot.py @@ -1,45 +1,48 @@ # -*- coding: utf-8 -*- # Based on the O'Reilly example at http://oreilly.com/pub/h/1968 import sys import socket import subprocess import config print 'Trying to connect to %s:%s%s' % (config.HOST, config.PORT, config.CHANNEL) +print 'Trying to create socket...' s=socket.socket() +print 'Socket created, trying to connect...' s.connect((config.HOST, config.PORT)) +print 'Connected, setting nick and joining channel...' s.send("NICK %s\r\n" % config.NICK) s.send("USER %s %s bla :%s\r\n" % (config.IDENT, config.HOST, config.REALNAME)) s.send("JOIN %s\r\n" % config.CHANNEL) def parse(input): p = subprocess.Popen(config.PARSE_COMMAND, shell=True, bufsize=1024, stdin=subprocess.PIPE, stdout=subprocess.PIPE) return p.communicate(input=input)[0].split('\n')[:-1] readbuffer='' while 1: readbuffer = readbuffer + s.recv(1024) temp = readbuffer.split("\n") readbuffer = temp.pop() for line in temp: line = line.strip() tokens = line.split() if tokens[0] == ':%s' % config.HOST: print ' '.join(tokens[3:]) if tokens[1] == "PRIVMSG" and tokens[2] == config.CHANNEL: messages = parse(line) for message in messages: s.send("PRIVMSG %s :%s\r\n" % (config.CHANNEL, message)) if tokens[0] == "PING": s.send("PONG %s\r\n" % tokens[1])
mortenberg80/minimal_ircbot
044d3b0218af1bae8be6b8c954425724f0bf79dc
added better output on ping result
diff --git a/minimal_parser.py b/minimal_parser.py index b6c7e6e..ab4ab9f 100644 --- a/minimal_parser.py +++ b/minimal_parser.py @@ -1,88 +1,88 @@ # -*- coding: utf-8 -*- import datetime as dt import re import subprocess import sys import config class Parser(object): def __init__(self, input): self.input = input self.input_tokens = input.split() self.tokens = self.input_tokens[3:] self.tokens[0] = self.tokens[0][1:] def parse(self): message = ' '.join(self.tokens) output = [] if self.tokens[0] == '%s:' % config.NICK: self.tokens.pop(0) handler_name = self.find_handler(prefix = 'handle_personal') else: handler_name = self.find_handler(prefix = 'handle') try: output = apply(self.__getattribute__(handler_name)) except AttributeError: pass if type(output) == str: output = output.strip().split('\n') return output def find_handler(self, parser=None, prefix = 'handle', default = 'default'): if parser is None: parser = self handler_name = prefix while len(self.tokens) > 0: token = self.tokens.pop(0) search = ''.join(re.findall('\w', token.lower())) handler_name += '_%s' % search if hasattr(parser, handler_name): return handler_name return '%s_%s' % (prefix, default) def handle_ping(self): return 'pong' def handle_time(self): return dt.datetime.now().strftime("%Y-%m-%d %H:%M") def handle_personal_default(self): output = ["Beklager... Jeg har ikke lært meg ditt språk ennå."] output += ["Prøv %s: how are you?" % config.NICK] return output def handle_personal_how_are_you(self): return 'I am bad to the bone!' def handle_personal_echo(self): return ' '.join(self.tokens) def handle_personal_ping(self): host = self.tokens.pop(0) try: re.match('^\w[\w\.]+\w$', host).group(0) p = subprocess.Popen(["ping", "-c 1", host], stderr=subprocess.PIPE, stdout=subprocess.PIPE) error = p.stderr.readline() if len(error) > 0: return error else: - return p.stdout.readlines()[1] + return "ping %s: %s" % (host, p.stdout.readlines()[1]) except AttributeError: return "Example usage: %s: ping vg.no" % config.NICK p = Parser(sys.stdin.readline()) output = p.parse() for output_line in output: print output_line
mortenberg80/minimal_ircbot
cd329e0a9298010ce7d9ca496094669d7473bfbb
added error output on ping command
diff --git a/minimal_parser.py b/minimal_parser.py index 88ec7bf..b6c7e6e 100644 --- a/minimal_parser.py +++ b/minimal_parser.py @@ -1,84 +1,88 @@ # -*- coding: utf-8 -*- import datetime as dt import re import subprocess import sys import config class Parser(object): def __init__(self, input): self.input = input self.input_tokens = input.split() self.tokens = self.input_tokens[3:] self.tokens[0] = self.tokens[0][1:] def parse(self): message = ' '.join(self.tokens) output = [] if self.tokens[0] == '%s:' % config.NICK: self.tokens.pop(0) handler_name = self.find_handler(prefix = 'handle_personal') else: handler_name = self.find_handler(prefix = 'handle') try: output = apply(self.__getattribute__(handler_name)) except AttributeError: pass if type(output) == str: output = output.strip().split('\n') return output def find_handler(self, parser=None, prefix = 'handle', default = 'default'): if parser is None: parser = self handler_name = prefix while len(self.tokens) > 0: token = self.tokens.pop(0) search = ''.join(re.findall('\w', token.lower())) handler_name += '_%s' % search if hasattr(parser, handler_name): return handler_name return '%s_%s' % (prefix, default) def handle_ping(self): return 'pong' def handle_time(self): return dt.datetime.now().strftime("%Y-%m-%d %H:%M") def handle_personal_default(self): output = ["Beklager... Jeg har ikke lært meg ditt språk ennå."] output += ["Prøv %s: how are you?" % config.NICK] return output def handle_personal_how_are_you(self): return 'I am bad to the bone!' def handle_personal_echo(self): return ' '.join(self.tokens) def handle_personal_ping(self): host = self.tokens.pop(0) try: re.match('^\w[\w\.]+\w$', host).group(0) p = subprocess.Popen(["ping", "-c 1", host], - stdout=subprocess.PIPE).stdout - output = p.readlines()[1] - return output + stderr=subprocess.PIPE, + stdout=subprocess.PIPE) + error = p.stderr.readline() + if len(error) > 0: + return error + else: + return p.stdout.readlines()[1] except AttributeError: return "Example usage: %s: ping vg.no" % config.NICK p = Parser(sys.stdin.readline()) output = p.parse() for output_line in output: print output_line
mortenberg80/minimal_ircbot
d6af9a723ba81bc175890f2637f4857b1fc76b94
Added ping host handler as an example
diff --git a/minimal_parser.py b/minimal_parser.py index e0522d6..88ec7bf 100644 --- a/minimal_parser.py +++ b/minimal_parser.py @@ -1,72 +1,84 @@ # -*- coding: utf-8 -*- import datetime as dt import re +import subprocess import sys import config class Parser(object): def __init__(self, input): self.input = input self.input_tokens = input.split() self.tokens = self.input_tokens[3:] self.tokens[0] = self.tokens[0][1:] def parse(self): message = ' '.join(self.tokens) output = [] if self.tokens[0] == '%s:' % config.NICK: self.tokens.pop(0) handler_name = self.find_handler(prefix = 'handle_personal') else: handler_name = self.find_handler(prefix = 'handle') try: output = apply(self.__getattribute__(handler_name)) except AttributeError: pass if type(output) == str: - output = output.split('\n') + output = output.strip().split('\n') return output def find_handler(self, parser=None, prefix = 'handle', default = 'default'): if parser is None: parser = self handler_name = prefix while len(self.tokens) > 0: token = self.tokens.pop(0) search = ''.join(re.findall('\w', token.lower())) handler_name += '_%s' % search if hasattr(parser, handler_name): return handler_name return '%s_%s' % (prefix, default) + def handle_ping(self): + return 'pong' + + def handle_time(self): + return dt.datetime.now().strftime("%Y-%m-%d %H:%M") + def handle_personal_default(self): output = ["Beklager... Jeg har ikke lært meg ditt språk ennå."] output += ["Prøv %s: how are you?" % config.NICK] return output def handle_personal_how_are_you(self): return 'I am bad to the bone!' def handle_personal_echo(self): return ' '.join(self.tokens) - def handle_ping(self): - return 'pong' - - def handle_time(self): - return dt.datetime.now().strftime("%Y-%m-%d %H:%M") + def handle_personal_ping(self): + host = self.tokens.pop(0) + try: + re.match('^\w[\w\.]+\w$', host).group(0) + p = subprocess.Popen(["ping", "-c 1", host], + stdout=subprocess.PIPE).stdout + output = p.readlines()[1] + return output + except AttributeError: + return "Example usage: %s: ping vg.no" % config.NICK p = Parser(sys.stdin.readline()) output = p.parse() for output_line in output: print output_line
mortenberg80/minimal_ircbot
6665117efbc84fc808f2a39bbb5e76f7d4fe42cb
Eliminated the need for if-elses in parser.
diff --git a/minimal_parser.py b/minimal_parser.py index 1a1c66e..e0522d6 100644 --- a/minimal_parser.py +++ b/minimal_parser.py @@ -1,55 +1,72 @@ # -*- coding: utf-8 -*- -import sys import datetime as dt +import re +import sys import config -class parser: +class Parser(object): def __init__(self, input): self.input = input - self.tokens = input.split() - self.message_tokens = self.tokens[3:] - self.message_tokens[0] = self.message_tokens[0][1:] + self.input_tokens = input.split() + self.tokens = self.input_tokens[3:] + self.tokens[0] = self.tokens[0][1:] def parse(self): - message = ' '.join(self.message_tokens) + message = ' '.join(self.tokens) output = [] - if message.lower() == "ping": - output = self.handle_ping() - - elif message.lower() == "time": - output = self.handle_time() + if self.tokens[0] == '%s:' % config.NICK: + self.tokens.pop(0) + handler_name = self.find_handler(prefix = 'handle_personal') + else: + handler_name = self.find_handler(prefix = 'handle') - elif self.message_tokens.pop(0) == '%s:' % config.NICK: - output = self.parse_personal_message() + try: + output = apply(self.__getattribute__(handler_name)) + except AttributeError: + pass if type(output) == str: output = output.split('\n') return output - def parse_personal_message(self): - self.message = ' '.join(self.message_tokens) + def find_handler(self, parser=None, prefix = 'handle', default = 'default'): + if parser is None: + parser = self - if self.message.lower() == 'how are you?': - return self.handle_personal_how_are_you() - else: - output = ["Beklager... Jeg har ikke lært meg ditt språk ennå."] - output += ["Prøv %s: how are you?" % config.NICK] - return output + handler_name = prefix + while len(self.tokens) > 0: + token = self.tokens.pop(0) + + search = ''.join(re.findall('\w', token.lower())) + handler_name += '_%s' % search + + if hasattr(parser, handler_name): + return handler_name + + return '%s_%s' % (prefix, default) + + def handle_personal_default(self): + output = ["Beklager... Jeg har ikke lært meg ditt språk ennå."] + output += ["Prøv %s: how are you?" % config.NICK] + return output def handle_personal_how_are_you(self): return 'I am bad to the bone!' + def handle_personal_echo(self): + return ' '.join(self.tokens) + def handle_ping(self): return 'pong' def handle_time(self): return dt.datetime.now().strftime("%Y-%m-%d %H:%M") -p = parser(sys.stdin.readline()) +p = Parser(sys.stdin.readline()) output = p.parse() for output_line in output: print output_line
mortenberg80/minimal_ircbot
ba927f2afa5f7e48ba2eeb1d37087bdf1f16fc51
No longer tries to send an empty message when having no parse result
diff --git a/minimal_bot.py b/minimal_bot.py index f23f0ec..332e2d2 100644 --- a/minimal_bot.py +++ b/minimal_bot.py @@ -1,45 +1,45 @@ # -*- coding: utf-8 -*- # Based on the O'Reilly example at http://oreilly.com/pub/h/1968 import sys import socket import subprocess import config print 'Trying to connect to %s:%s%s' % (config.HOST, config.PORT, config.CHANNEL) s=socket.socket() s.connect((config.HOST, config.PORT)) s.send("NICK %s\r\n" % config.NICK) s.send("USER %s %s bla :%s\r\n" % (config.IDENT, config.HOST, config.REALNAME)) s.send("JOIN %s\r\n" % config.CHANNEL) def parse(input): p = subprocess.Popen(config.PARSE_COMMAND, shell=True, bufsize=1024, stdin=subprocess.PIPE, stdout=subprocess.PIPE) - return p.communicate(input=input)[0].strip().split('\n') + return p.communicate(input=input)[0].split('\n')[:-1] readbuffer='' while 1: readbuffer = readbuffer + s.recv(1024) temp = readbuffer.split("\n") readbuffer = temp.pop() for line in temp: line = line.strip() tokens = line.split() if tokens[0] == ':%s' % config.HOST: print ' '.join(tokens[3:]) if tokens[1] == "PRIVMSG" and tokens[2] == config.CHANNEL: messages = parse(line) for message in messages: s.send("PRIVMSG %s :%s\r\n" % (config.CHANNEL, message)) if tokens[0] == "PING": s.send("PONG %s\r\n" % tokens[1])
mortenberg80/minimal_ircbot
9690a1d995d5aeb71dab096b094bf4229c3d1725
Added printing of server messages
diff --git a/minimal_bot.py b/minimal_bot.py index bc160b5..f23f0ec 100644 --- a/minimal_bot.py +++ b/minimal_bot.py @@ -1,43 +1,45 @@ # -*- coding: utf-8 -*- # Based on the O'Reilly example at http://oreilly.com/pub/h/1968 import sys import socket import subprocess import config -readbuffer='' +print 'Trying to connect to %s:%s%s' % (config.HOST, config.PORT, config.CHANNEL) s=socket.socket() s.connect((config.HOST, config.PORT)) s.send("NICK %s\r\n" % config.NICK) s.send("USER %s %s bla :%s\r\n" % (config.IDENT, config.HOST, config.REALNAME)) s.send("JOIN %s\r\n" % config.CHANNEL) -print 'Connected to %s:%s%s' % (config.HOST, config.PORT, config.CHANNEL) - def parse(input): p = subprocess.Popen(config.PARSE_COMMAND, shell=True, bufsize=1024, stdin=subprocess.PIPE, stdout=subprocess.PIPE) return p.communicate(input=input)[0].strip().split('\n') +readbuffer='' while 1: readbuffer = readbuffer + s.recv(1024) temp = readbuffer.split("\n") readbuffer = temp.pop() for line in temp: line = line.strip() tokens = line.split() + if tokens[0] == ':%s' % config.HOST: + print ' '.join(tokens[3:]) + if tokens[1] == "PRIVMSG" and tokens[2] == config.CHANNEL: messages = parse(line) for message in messages: s.send("PRIVMSG %s :%s\r\n" % (config.CHANNEL, message)) if tokens[0] == "PING": s.send("PONG %s\r\n" % tokens[1])
mortenberg80/minimal_ircbot
a391b44df4937cb6aa7feaf680fd8e6905e5f041
Show host, port and channel server is connected to upon startup
diff --git a/minimal_bot.py b/minimal_bot.py index 45d8b1c..bc160b5 100644 --- a/minimal_bot.py +++ b/minimal_bot.py @@ -1,43 +1,43 @@ # -*- coding: utf-8 -*- # Based on the O'Reilly example at http://oreilly.com/pub/h/1968 import sys import socket import subprocess import config readbuffer='' s=socket.socket() s.connect((config.HOST, config.PORT)) s.send("NICK %s\r\n" % config.NICK) s.send("USER %s %s bla :%s\r\n" % (config.IDENT, config.HOST, config.REALNAME)) s.send("JOIN %s\r\n" % config.CHANNEL) -print 'Running' +print 'Connected to %s:%s%s' % (config.HOST, config.PORT, config.CHANNEL) def parse(input): p = subprocess.Popen(config.PARSE_COMMAND, shell=True, bufsize=1024, stdin=subprocess.PIPE, stdout=subprocess.PIPE) return p.communicate(input=input)[0].strip().split('\n') while 1: readbuffer = readbuffer + s.recv(1024) temp = readbuffer.split("\n") readbuffer = temp.pop() for line in temp: line = line.strip() tokens = line.split() if tokens[1] == "PRIVMSG" and tokens[2] == config.CHANNEL: messages = parse(line) for message in messages: s.send("PRIVMSG %s :%s\r\n" % (config.CHANNEL, message)) if tokens[0] == "PING": s.send("PONG %s\r\n" % tokens[1])
mortenberg80/minimal_ircbot
b2364cc3564fdbca3ecab8ca8d55207b45929b42
Fixed bug, which caused the bot to never reply to server pings
diff --git a/minimal_bot.py b/minimal_bot.py index 0aada93..45d8b1c 100644 --- a/minimal_bot.py +++ b/minimal_bot.py @@ -1,43 +1,43 @@ # -*- coding: utf-8 -*- # Based on the O'Reilly example at http://oreilly.com/pub/h/1968 import sys import socket import subprocess import config readbuffer='' s=socket.socket() s.connect((config.HOST, config.PORT)) s.send("NICK %s\r\n" % config.NICK) s.send("USER %s %s bla :%s\r\n" % (config.IDENT, config.HOST, config.REALNAME)) s.send("JOIN %s\r\n" % config.CHANNEL) print 'Running' def parse(input): p = subprocess.Popen(config.PARSE_COMMAND, shell=True, bufsize=1024, stdin=subprocess.PIPE, stdout=subprocess.PIPE) return p.communicate(input=input)[0].strip().split('\n') while 1: readbuffer = readbuffer + s.recv(1024) temp = readbuffer.split("\n") readbuffer = temp.pop() for line in temp: line = line.strip() tokens = line.split() if tokens[1] == "PRIVMSG" and tokens[2] == config.CHANNEL: messages = parse(line) for message in messages: s.send("PRIVMSG %s :%s\r\n" % (config.CHANNEL, message)) - if line[0] == "PING": + if tokens[0] == "PING": s.send("PONG %s\r\n" % tokens[1])
mortenberg80/minimal_ircbot
3cb2de83eadb1e021cacf4de1d4d3cfcf5227bbe
Extracted script command as a configurable option
diff --git a/config.py b/config.py index 859b9b1..4bed88b 100644 --- a/config.py +++ b/config.py @@ -1,11 +1,12 @@ HOST = 'irc.homelien.no' PORT = 6667 NICK = 'mynick' IDENT = 'pybot' REALNAME = 'I am' CHANNEL = '#mychannel' +PARSE_COMMAND = 'python ./minimal_parser.py' try: from local_config import * except ImportError: pass diff --git a/minimal_bot.py b/minimal_bot.py index d8d6c6b..0aada93 100644 --- a/minimal_bot.py +++ b/minimal_bot.py @@ -1,43 +1,43 @@ # -*- coding: utf-8 -*- # Based on the O'Reilly example at http://oreilly.com/pub/h/1968 import sys import socket import subprocess import config readbuffer='' s=socket.socket() s.connect((config.HOST, config.PORT)) s.send("NICK %s\r\n" % config.NICK) s.send("USER %s %s bla :%s\r\n" % (config.IDENT, config.HOST, config.REALNAME)) s.send("JOIN %s\r\n" % config.CHANNEL) print 'Running' def parse(input): - p = subprocess.Popen('python %s' % 'minimal_parser.py', + p = subprocess.Popen(config.PARSE_COMMAND, shell=True, bufsize=1024, stdin=subprocess.PIPE, stdout=subprocess.PIPE) return p.communicate(input=input)[0].strip().split('\n') while 1: readbuffer = readbuffer + s.recv(1024) temp = readbuffer.split("\n") readbuffer = temp.pop() for line in temp: line = line.strip() tokens = line.split() if tokens[1] == "PRIVMSG" and tokens[2] == config.CHANNEL: messages = parse(line) for message in messages: s.send("PRIVMSG %s :%s\r\n" % (config.CHANNEL, message)) if line[0] == "PING": s.send("PONG %s\r\n" % tokens[1])