repo
string
commit
string
message
string
diff
string
padhi/golf
528b75bfbd612afccdc0952ca7ac73a717e35014
Added bt Ayuta
diff --git a/README b/README index 93efe29..0c35780 100644 --- a/README +++ b/README @@ -1,259 +1,261 @@ +This is added by ayuta + == Welcome to Rails Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern. This pattern splits the view (also called the presentation) into "dumb" templates that are primarily responsible for inserting pre-built data in between HTML tags. The model contains the "smart" domain objects (such as Account, Product, Person, Post) that holds all the business logic and knows how to persist themselves to a database. The controller handles the incoming requests (such as Save New Account, Update Product, Show Post) by manipulating the model and directing data to the view. In Rails, the model is handled by what's called an object-relational mapping layer entitled Active Record. This layer allows you to present the data from database rows as objects and embellish these data objects with business logic methods. You can read more about Active Record in link:files/vendor/rails/activerecord/README.html. The controller and view are handled by the Action Pack, which handles both layers by its two parts: Action View and Action Controller. These two layers are bundled in a single package due to their heavy interdependence. This is unlike the relationship between the Active Record and Action Pack that is much more separate. Each of these packages can be used independently outside of Rails. You can read more about Action Pack in link:files/vendor/rails/actionpack/README.html. == Getting Started 1. At the command prompt, start a new Rails application using the <tt>rails</tt> command and your application name. Ex: rails myapp 2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options) 3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!" 4. Follow the guidelines to start developing your application == Web Servers By default, Rails will try to use Mongrel and lighttpd if they are installed, otherwise Rails will use WEBrick, the webserver that ships with Ruby. When you run script/server, Rails will check if Mongrel exists, then lighttpd and finally fall back to WEBrick. This ensures that you can always get up and running quickly. Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is suitable for development and deployment of Rails applications. If you have Ruby Gems installed, getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>. More info at: http://mongrel.rubyforge.org If Mongrel is not installed, Rails will look for lighttpd. It's considerably faster than Mongrel and WEBrick and also suited for production use, but requires additional installation and currently only works well on OS X/Unix (Windows users are encouraged to start with Mongrel). We recommend version 1.4.11 and higher. You can download it from http://www.lighttpd.net. And finally, if neither Mongrel or lighttpd are installed, Rails will use the built-in Ruby web server, WEBrick. WEBrick is a small Ruby web server suitable for development, but not for production. But of course its also possible to run Rails on any platform that supports FCGI. Apache, LiteSpeed, IIS are just a few. For more information on FCGI, please visit: http://wiki.rubyonrails.com/rails/pages/FastCGI == Apache .htaccess example # General Apache options AddHandler fastcgi-script .fcgi AddHandler cgi-script .cgi Options +FollowSymLinks +ExecCGI # If you don't want Rails to look in certain directories, # use the following rewrite rules so that Apache won't rewrite certain requests # # Example: # RewriteCond %{REQUEST_URI} ^/notrails.* # RewriteRule .* - [L] # Redirect all requests not available on the filesystem to Rails # By default the cgi dispatcher is used which is very slow # # For better performance replace the dispatcher with the fastcgi one # # Example: # RewriteRule ^(.*)$ dispatch.fcgi [QSA,L] RewriteEngine On # If your Rails application is accessed via an Alias directive, # then you MUST also set the RewriteBase in this htaccess file. # # Example: # Alias /myrailsapp /path/to/myrailsapp/public # RewriteBase /myrailsapp RewriteRule ^$ index.html [QSA] RewriteRule ^([^.]+)$ $1.html [QSA] RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ dispatch.cgi [QSA,L] # In case Rails experiences terminal errors # Instead of displaying this message you can supply a file here which will be rendered instead # # Example: # ErrorDocument 500 /500.html ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly" == Debugging Rails Sometimes your application goes wrong. Fortunately there are a lot of tools that will help you debug it and get it back on the rails. First area to check is the application log files. Have "tail -f" commands running on the server.log and development.log. Rails will automatically display debugging and runtime information to these files. Debugging info will also be shown in the browser on requests from 127.0.0.1. You can also log your own messages directly into the log file from your code using the Ruby logger class from inside your controllers. Example: class WeblogController < ActionController::Base def destroy @weblog = Weblog.find(params[:id]) @weblog.destroy logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") end end The result will be a message in your log file along the lines of: Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1 More information on how to use the logger is at http://www.ruby-doc.org/core/ Also, Ruby documentation can be found at http://www.ruby-lang.org/ including: * The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/ * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) These two online (and free) books will bring you up to speed on the Ruby language and also on programming in general. == Debugger Debugger support is available through the debugger command when you start your Mongrel or Webrick server with --debugger. This means that you can break out of execution at any point in the code, investigate and change the model, AND then resume execution! You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug' Example: class WeblogController < ActionController::Base def index @posts = Post.find(:all) debugger end end So the controller will accept the action, run the first line, then present you with a IRB prompt in the server window. Here you can do things like: >> @posts.inspect => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>, #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]" >> @posts.first.title = "hello from a debugger" => "hello from a debugger" ...and even better is that you can examine how your runtime objects actually work: >> f = @posts.first => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}> >> f. Display all 152 possibilities? (y or n) Finally, when you're ready to resume execution, you enter "cont" == Console You can interact with the domain model by starting the console through <tt>script/console</tt>. Here you'll have all parts of the application configured, just like it is when the application is running. You can inspect domain models, change values, and save to the database. Starting the script without arguments will launch it in the development environment. Passing an argument will specify a different environment, like <tt>script/console production</tt>. To reload your controllers and models after launching the console run <tt>reload!</tt> == dbconsole You can go to the command line of your database directly through <tt>script/dbconsole</tt>. You would be connected to the database with the credentials defined in database.yml. Starting the script without arguments will connect you to the development database. Passing an argument will connect you to a different database, like <tt>script/dbconsole production</tt>. Currently works for mysql, postgresql and sqlite. == Description of Contents app Holds all the code that's specific to this particular application. app/controllers Holds controllers that should be named like weblogs_controller.rb for automated URL mapping. All controllers should descend from ApplicationController which itself descends from ActionController::Base. app/models Holds models that should be named like post.rb. Most models will descend from ActiveRecord::Base. app/views Holds the template files for the view that should be named like weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby syntax. app/views/layouts Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout. app/helpers Holds view helpers that should be named like weblogs_helper.rb. These are generated for you automatically when using script/generate for controllers. Helpers can be used to wrap functionality for your views into methods. config Configuration files for the Rails environment, the routing map, the database, and other dependencies. db Contains the database schema in schema.rb. db/migrate contains all the sequence of Migrations for your schema. doc This directory is where your application documentation will be stored when generated using <tt>rake doc:app</tt> lib Application specific libraries. Basically, any kind of custom code that doesn't belong under controllers, models, or helpers. This directory is in the load path. public The directory available for the web server. Contains subdirectories for images, stylesheets, and javascripts. Also contains the dispatchers and the default HTML files. This should be set as the DOCUMENT_ROOT of your web server. script Helper scripts for automation and generation. test Unit and functional tests along with fixtures. When using the script/generate scripts, template test files will be generated for you and placed in this directory. vendor External libraries that the application depends on. Also includes the plugins subdirectory. If the app has frozen rails, those gems also go here, under vendor/rails/. This directory is in the load path. -- Hani( alias helabed ) was added as a collaborator
padhi/golf
a30e553c28212a806f03e9833d4ab22643dfffcc
added Hani as collaborator
diff --git a/README b/README index 2af0fb1..93efe29 100644 --- a/README +++ b/README @@ -1,256 +1,259 @@ == Welcome to Rails Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern. This pattern splits the view (also called the presentation) into "dumb" templates that are primarily responsible for inserting pre-built data in between HTML tags. The model contains the "smart" domain objects (such as Account, Product, Person, Post) that holds all the business logic and knows how to persist themselves to a database. The controller handles the incoming requests (such as Save New Account, Update Product, Show Post) by manipulating the model and directing data to the view. In Rails, the model is handled by what's called an object-relational mapping layer entitled Active Record. This layer allows you to present the data from database rows as objects and embellish these data objects with business logic methods. You can read more about Active Record in link:files/vendor/rails/activerecord/README.html. The controller and view are handled by the Action Pack, which handles both layers by its two parts: Action View and Action Controller. These two layers are bundled in a single package due to their heavy interdependence. This is unlike the relationship between the Active Record and Action Pack that is much more separate. Each of these packages can be used independently outside of Rails. You can read more about Action Pack in link:files/vendor/rails/actionpack/README.html. == Getting Started 1. At the command prompt, start a new Rails application using the <tt>rails</tt> command and your application name. Ex: rails myapp 2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options) 3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!" 4. Follow the guidelines to start developing your application == Web Servers By default, Rails will try to use Mongrel and lighttpd if they are installed, otherwise Rails will use WEBrick, the webserver that ships with Ruby. When you run script/server, Rails will check if Mongrel exists, then lighttpd and finally fall back to WEBrick. This ensures that you can always get up and running quickly. Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is suitable for development and deployment of Rails applications. If you have Ruby Gems installed, getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>. More info at: http://mongrel.rubyforge.org If Mongrel is not installed, Rails will look for lighttpd. It's considerably faster than Mongrel and WEBrick and also suited for production use, but requires additional installation and currently only works well on OS X/Unix (Windows users are encouraged to start with Mongrel). We recommend version 1.4.11 and higher. You can download it from http://www.lighttpd.net. And finally, if neither Mongrel or lighttpd are installed, Rails will use the built-in Ruby web server, WEBrick. WEBrick is a small Ruby web server suitable for development, but not for production. But of course its also possible to run Rails on any platform that supports FCGI. Apache, LiteSpeed, IIS are just a few. For more information on FCGI, please visit: http://wiki.rubyonrails.com/rails/pages/FastCGI == Apache .htaccess example # General Apache options AddHandler fastcgi-script .fcgi AddHandler cgi-script .cgi Options +FollowSymLinks +ExecCGI # If you don't want Rails to look in certain directories, # use the following rewrite rules so that Apache won't rewrite certain requests # # Example: # RewriteCond %{REQUEST_URI} ^/notrails.* # RewriteRule .* - [L] # Redirect all requests not available on the filesystem to Rails # By default the cgi dispatcher is used which is very slow # # For better performance replace the dispatcher with the fastcgi one # # Example: # RewriteRule ^(.*)$ dispatch.fcgi [QSA,L] RewriteEngine On # If your Rails application is accessed via an Alias directive, # then you MUST also set the RewriteBase in this htaccess file. # # Example: # Alias /myrailsapp /path/to/myrailsapp/public # RewriteBase /myrailsapp RewriteRule ^$ index.html [QSA] RewriteRule ^([^.]+)$ $1.html [QSA] RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ dispatch.cgi [QSA,L] # In case Rails experiences terminal errors # Instead of displaying this message you can supply a file here which will be rendered instead # # Example: # ErrorDocument 500 /500.html ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly" == Debugging Rails Sometimes your application goes wrong. Fortunately there are a lot of tools that will help you debug it and get it back on the rails. First area to check is the application log files. Have "tail -f" commands running on the server.log and development.log. Rails will automatically display debugging and runtime information to these files. Debugging info will also be shown in the browser on requests from 127.0.0.1. You can also log your own messages directly into the log file from your code using the Ruby logger class from inside your controllers. Example: class WeblogController < ActionController::Base def destroy @weblog = Weblog.find(params[:id]) @weblog.destroy logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") end end The result will be a message in your log file along the lines of: Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1 More information on how to use the logger is at http://www.ruby-doc.org/core/ Also, Ruby documentation can be found at http://www.ruby-lang.org/ including: * The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/ * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) These two online (and free) books will bring you up to speed on the Ruby language and also on programming in general. == Debugger Debugger support is available through the debugger command when you start your Mongrel or Webrick server with --debugger. This means that you can break out of execution at any point in the code, investigate and change the model, AND then resume execution! You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug' Example: class WeblogController < ActionController::Base def index @posts = Post.find(:all) debugger end end So the controller will accept the action, run the first line, then present you with a IRB prompt in the server window. Here you can do things like: >> @posts.inspect => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>, #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]" >> @posts.first.title = "hello from a debugger" => "hello from a debugger" ...and even better is that you can examine how your runtime objects actually work: >> f = @posts.first => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}> >> f. Display all 152 possibilities? (y or n) Finally, when you're ready to resume execution, you enter "cont" == Console You can interact with the domain model by starting the console through <tt>script/console</tt>. Here you'll have all parts of the application configured, just like it is when the application is running. You can inspect domain models, change values, and save to the database. Starting the script without arguments will launch it in the development environment. Passing an argument will specify a different environment, like <tt>script/console production</tt>. To reload your controllers and models after launching the console run <tt>reload!</tt> == dbconsole You can go to the command line of your database directly through <tt>script/dbconsole</tt>. You would be connected to the database with the credentials defined in database.yml. Starting the script without arguments will connect you to the development database. Passing an argument will connect you to a different database, like <tt>script/dbconsole production</tt>. Currently works for mysql, postgresql and sqlite. == Description of Contents app Holds all the code that's specific to this particular application. app/controllers Holds controllers that should be named like weblogs_controller.rb for automated URL mapping. All controllers should descend from ApplicationController which itself descends from ActionController::Base. app/models Holds models that should be named like post.rb. Most models will descend from ActiveRecord::Base. app/views Holds the template files for the view that should be named like weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby syntax. app/views/layouts Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout. app/helpers Holds view helpers that should be named like weblogs_helper.rb. These are generated for you automatically when using script/generate for controllers. Helpers can be used to wrap functionality for your views into methods. config Configuration files for the Rails environment, the routing map, the database, and other dependencies. db Contains the database schema in schema.rb. db/migrate contains all the sequence of Migrations for your schema. doc This directory is where your application documentation will be stored when generated using <tt>rake doc:app</tt> lib Application specific libraries. Basically, any kind of custom code that doesn't belong under controllers, models, or helpers. This directory is in the load path. public The directory available for the web server. Contains subdirectories for images, stylesheets, and javascripts. Also contains the dispatchers and the default HTML files. This should be set as the DOCUMENT_ROOT of your web server. script Helper scripts for automation and generation. test Unit and functional tests along with fixtures. When using the script/generate scripts, template test files will be generated for you and placed in this directory. vendor External libraries that the application depends on. Also includes the plugins subdirectory. If the app has frozen rails, those gems also go here, under vendor/rails/. This directory is in the load path. + +-- +Hani( alias helabed ) was added as a collaborator
padhi/golf
a7424295e5a0af95fb2bf513209ab63a014a286b
started db and removed index.html
diff --git a/db/development.sqlite3 b/db/development.sqlite3 new file mode 100644 index 0000000..8fc7137 Binary files /dev/null and b/db/development.sqlite3 differ diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000..62e21f5 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,21 @@ +# 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 => 20080929233921) do + + create_table "golfers", :force => true do |t| + t.string "name" + t.integer "earnings" + t.datetime "created_at" + t.datetime "updated_at" + end + +end diff --git a/public/index.html b/public/index.html deleted file mode 100644 index e84c359..0000000 --- a/public/index.html +++ /dev/null @@ -1,274 +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> - </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
padhi/golf
3737bba903c99c97f6dd1131d05931b42d5f8d3f
script/generate rspec_scaffold golfer...
diff --git a/app/controllers/golfers_controller.rb b/app/controllers/golfers_controller.rb new file mode 100644 index 0000000..3d00a1a --- /dev/null +++ b/app/controllers/golfers_controller.rb @@ -0,0 +1,85 @@ +class GolfersController < ApplicationController + # GET /golfers + # GET /golfers.xml + def index + @golfers = Golfer.find(:all) + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @golfers } + end + end + + # GET /golfers/1 + # GET /golfers/1.xml + def show + @golfer = Golfer.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @golfer } + end + end + + # GET /golfers/new + # GET /golfers/new.xml + def new + @golfer = Golfer.new + + respond_to do |format| + format.html # new.html.erb + format.xml { render :xml => @golfer } + end + end + + # GET /golfers/1/edit + def edit + @golfer = Golfer.find(params[:id]) + end + + # POST /golfers + # POST /golfers.xml + def create + @golfer = Golfer.new(params[:golfer]) + + respond_to do |format| + if @golfer.save + flash[:notice] = 'Golfer was successfully created.' + format.html { redirect_to(@golfer) } + format.xml { render :xml => @golfer, :status => :created, :location => @golfer } + else + format.html { render :action => "new" } + format.xml { render :xml => @golfer.errors, :status => :unprocessable_entity } + end + end + end + + # PUT /golfers/1 + # PUT /golfers/1.xml + def update + @golfer = Golfer.find(params[:id]) + + respond_to do |format| + if @golfer.update_attributes(params[:golfer]) + flash[:notice] = 'Golfer was successfully updated.' + format.html { redirect_to(@golfer) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @golfer.errors, :status => :unprocessable_entity } + end + end + end + + # DELETE /golfers/1 + # DELETE /golfers/1.xml + def destroy + @golfer = Golfer.find(params[:id]) + @golfer.destroy + + respond_to do |format| + format.html { redirect_to(golfers_url) } + format.xml { head :ok } + end + end +end diff --git a/app/helpers/golfers_helper.rb b/app/helpers/golfers_helper.rb new file mode 100644 index 0000000..a7a47f3 --- /dev/null +++ b/app/helpers/golfers_helper.rb @@ -0,0 +1,2 @@ +module GolfersHelper +end diff --git a/app/models/golfer.rb b/app/models/golfer.rb new file mode 100644 index 0000000..70e028d --- /dev/null +++ b/app/models/golfer.rb @@ -0,0 +1,2 @@ +class Golfer < ActiveRecord::Base +end diff --git a/app/views/golfers/edit.html.erb b/app/views/golfers/edit.html.erb new file mode 100644 index 0000000..6c288b8 --- /dev/null +++ b/app/views/golfers/edit.html.erb @@ -0,0 +1,20 @@ +<h1>Editing golfer</h1> + +<% form_for(@golfer) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :name %><br /> + <%= f.text_field :name %> + </p> + <p> + <%= f.label :earnings %><br /> + <%= f.text_field :earnings %> + </p> + <p> + <%= f.submit "Update" %> + </p> +<% end %> + +<%= link_to 'Show', @golfer %> | +<%= link_to 'Back', golfers_path %> diff --git a/app/views/golfers/index.html.erb b/app/views/golfers/index.html.erb new file mode 100644 index 0000000..66319d3 --- /dev/null +++ b/app/views/golfers/index.html.erb @@ -0,0 +1,22 @@ +<h1>Listing golfers</h1> + +<table> + <tr> + <th>Name</th> + <th>Earnings</th> + </tr> + +<% for golfer in @golfers %> + <tr> + <td><%=h golfer.name %></td> + <td><%=h golfer.earnings %></td> + <td><%= link_to 'Show', golfer %></td> + <td><%= link_to 'Edit', edit_golfer_path(golfer) %></td> + <td><%= link_to 'Destroy', golfer, :confirm => 'Are you sure?', :method => :delete %></td> + </tr> +<% end %> +</table> + +<br /> + +<%= link_to 'New golfer', new_golfer_path %> diff --git a/app/views/golfers/new.html.erb b/app/views/golfers/new.html.erb new file mode 100644 index 0000000..1dded42 --- /dev/null +++ b/app/views/golfers/new.html.erb @@ -0,0 +1,19 @@ +<h1>New golfer</h1> + +<% form_for(@golfer) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :name %><br /> + <%= f.text_field :name %> + </p> + <p> + <%= f.label :earnings %><br /> + <%= f.text_field :earnings %> + </p> + <p> + <%= f.submit "Create" %> + </p> +<% end %> + +<%= link_to 'Back', golfers_path %> diff --git a/app/views/golfers/show.html.erb b/app/views/golfers/show.html.erb new file mode 100644 index 0000000..35bd49a --- /dev/null +++ b/app/views/golfers/show.html.erb @@ -0,0 +1,13 @@ +<p> + <b>Name:</b> + <%=h @golfer.name %> +</p> + +<p> + <b>Earnings:</b> + <%=h @golfer.earnings %> +</p> + + +<%= link_to 'Edit', edit_golfer_path(@golfer) %> | +<%= link_to 'Back', golfers_path %> diff --git a/config/routes.rb b/config/routes.rb index 4f3d9d2..f5ddf48 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,43 +1,45 @@ ActionController::Routing::Routes.draw do |map| + map.resources :golfers + # 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/20080929233921_create_golfers.rb b/db/migrate/20080929233921_create_golfers.rb new file mode 100644 index 0000000..b2e2f0a --- /dev/null +++ b/db/migrate/20080929233921_create_golfers.rb @@ -0,0 +1,14 @@ +class CreateGolfers < ActiveRecord::Migration + def self.up + create_table :golfers do |t| + t.string :name + t.integer :earnings + + t.timestamps + end + end + + def self.down + drop_table :golfers + end +end diff --git a/spec/controllers/golfers_controller_spec.rb b/spec/controllers/golfers_controller_spec.rb new file mode 100644 index 0000000..4bcae2b --- /dev/null +++ b/spec/controllers/golfers_controller_spec.rb @@ -0,0 +1,173 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe GolfersController do + + def mock_golfer(stubs={}) + @mock_golfer ||= mock_model(Golfer, stubs) + end + + describe "responding to GET index" do + + it "should expose all golfers as @golfers" do + Golfer.should_receive(:find).with(:all).and_return([mock_golfer]) + get :index + assigns[:golfers].should == [mock_golfer] + end + + describe "with mime type of xml" do + + it "should render all golfers as xml" do + request.env["HTTP_ACCEPT"] = "application/xml" + Golfer.should_receive(:find).with(:all).and_return(golfers = mock("Array of Golfers")) + golfers.should_receive(:to_xml).and_return("generated XML") + get :index + response.body.should == "generated XML" + end + + end + + end + + describe "responding to GET show" do + + it "should expose the requested golfer as @golfer" do + Golfer.should_receive(:find).with("37").and_return(mock_golfer) + get :show, :id => "37" + assigns[:golfer].should equal(mock_golfer) + end + + describe "with mime type of xml" do + + it "should render the requested golfer as xml" do + request.env["HTTP_ACCEPT"] = "application/xml" + Golfer.should_receive(:find).with("37").and_return(mock_golfer) + mock_golfer.should_receive(:to_xml).and_return("generated XML") + get :show, :id => "37" + response.body.should == "generated XML" + end + + end + + end + + describe "responding to GET new" do + + it "should expose a new golfer as @golfer" do + Golfer.should_receive(:new).and_return(mock_golfer) + get :new + assigns[:golfer].should equal(mock_golfer) + end + + end + + describe "responding to GET edit" do + + it "should expose the requested golfer as @golfer" do + Golfer.should_receive(:find).with("37").and_return(mock_golfer) + get :edit, :id => "37" + assigns[:golfer].should equal(mock_golfer) + end + + end + + describe "responding to POST create" do + + describe "with valid params" do + + it "should expose a newly created golfer as @golfer" do + Golfer.should_receive(:new).with({'these' => 'params'}).and_return(mock_golfer(:save => true)) + post :create, :golfer => {:these => 'params'} + assigns(:golfer).should equal(mock_golfer) + end + + it "should redirect to the created golfer" do + Golfer.stub!(:new).and_return(mock_golfer(:save => true)) + post :create, :golfer => {} + response.should redirect_to(golfer_url(mock_golfer)) + end + + end + + describe "with invalid params" do + + it "should expose a newly created but unsaved golfer as @golfer" do + Golfer.stub!(:new).with({'these' => 'params'}).and_return(mock_golfer(:save => false)) + post :create, :golfer => {:these => 'params'} + assigns(:golfer).should equal(mock_golfer) + end + + it "should re-render the 'new' template" do + Golfer.stub!(:new).and_return(mock_golfer(:save => false)) + post :create, :golfer => {} + response.should render_template('new') + end + + end + + end + + describe "responding to PUT udpate" do + + describe "with valid params" do + + it "should update the requested golfer" do + Golfer.should_receive(:find).with("37").and_return(mock_golfer) + mock_golfer.should_receive(:update_attributes).with({'these' => 'params'}) + put :update, :id => "37", :golfer => {:these => 'params'} + end + + it "should expose the requested golfer as @golfer" do + Golfer.stub!(:find).and_return(mock_golfer(:update_attributes => true)) + put :update, :id => "1" + assigns(:golfer).should equal(mock_golfer) + end + + it "should redirect to the golfer" do + Golfer.stub!(:find).and_return(mock_golfer(:update_attributes => true)) + put :update, :id => "1" + response.should redirect_to(golfer_url(mock_golfer)) + end + + end + + describe "with invalid params" do + + it "should update the requested golfer" do + Golfer.should_receive(:find).with("37").and_return(mock_golfer) + mock_golfer.should_receive(:update_attributes).with({'these' => 'params'}) + put :update, :id => "37", :golfer => {:these => 'params'} + end + + it "should expose the golfer as @golfer" do + Golfer.stub!(:find).and_return(mock_golfer(:update_attributes => false)) + put :update, :id => "1" + assigns(:golfer).should equal(mock_golfer) + end + + it "should re-render the 'edit' template" do + Golfer.stub!(:find).and_return(mock_golfer(:update_attributes => false)) + put :update, :id => "1" + response.should render_template('edit') + end + + end + + end + + describe "responding to DELETE destroy" do + + it "should destroy the requested golfer" do + Golfer.should_receive(:find).with("37").and_return(mock_golfer) + mock_golfer.should_receive(:destroy) + delete :destroy, :id => "37" + end + + it "should redirect to the golfers list" do + Golfer.stub!(:find).and_return(mock_golfer(:destroy => true)) + delete :destroy, :id => "1" + response.should redirect_to(golfers_url) + end + + end + +end diff --git a/spec/controllers/golfers_routing_spec.rb b/spec/controllers/golfers_routing_spec.rb new file mode 100644 index 0000000..7f5d454 --- /dev/null +++ b/spec/controllers/golfers_routing_spec.rb @@ -0,0 +1,59 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe GolfersController do + describe "route generation" do + it "should map #index" do + route_for(:controller => "golfers", :action => "index").should == "/golfers" + end + + it "should map #new" do + route_for(:controller => "golfers", :action => "new").should == "/golfers/new" + end + + it "should map #show" do + route_for(:controller => "golfers", :action => "show", :id => 1).should == "/golfers/1" + end + + it "should map #edit" do + route_for(:controller => "golfers", :action => "edit", :id => 1).should == "/golfers/1/edit" + end + + it "should map #update" do + route_for(:controller => "golfers", :action => "update", :id => 1).should == "/golfers/1" + end + + it "should map #destroy" do + route_for(:controller => "golfers", :action => "destroy", :id => 1).should == "/golfers/1" + end + end + + describe "route recognition" do + it "should generate params for #index" do + params_from(:get, "/golfers").should == {:controller => "golfers", :action => "index"} + end + + it "should generate params for #new" do + params_from(:get, "/golfers/new").should == {:controller => "golfers", :action => "new"} + end + + it "should generate params for #create" do + params_from(:post, "/golfers").should == {:controller => "golfers", :action => "create"} + end + + it "should generate params for #show" do + params_from(:get, "/golfers/1").should == {:controller => "golfers", :action => "show", :id => "1"} + end + + it "should generate params for #edit" do + params_from(:get, "/golfers/1/edit").should == {:controller => "golfers", :action => "edit", :id => "1"} + end + + it "should generate params for #update" do + params_from(:put, "/golfers/1").should == {:controller => "golfers", :action => "update", :id => "1"} + end + + it "should generate params for #destroy" do + params_from(:delete, "/golfers/1").should == {:controller => "golfers", :action => "destroy", :id => "1"} + end + end +end diff --git a/spec/fixtures/golfers.yml b/spec/fixtures/golfers.yml new file mode 100644 index 0000000..9a0f228 --- /dev/null +++ b/spec/fixtures/golfers.yml @@ -0,0 +1,9 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +one: + name: MyString + earnings: 1 + +two: + name: MyString + earnings: 1 diff --git a/spec/helpers/golfers_helper_spec.rb b/spec/helpers/golfers_helper_spec.rb new file mode 100644 index 0000000..a69d11b --- /dev/null +++ b/spec/helpers/golfers_helper_spec.rb @@ -0,0 +1,11 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe GolfersHelper do + + #Delete this example and add some real ones or delete this file + it "should be included in the object returned by #helper" do + included_modules = (class << helper; self; end).send :included_modules + included_modules.should include(GolfersHelper) + end + +end diff --git a/spec/models/golfer_spec.rb b/spec/models/golfer_spec.rb new file mode 100644 index 0000000..9a780f4 --- /dev/null +++ b/spec/models/golfer_spec.rb @@ -0,0 +1,14 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe Golfer do + before(:each) do + @valid_attributes = { + :name => "value for name", + :earnings => "1" + } + end + + it "should create a new instance given valid attributes" do + Golfer.create!(@valid_attributes) + end +end diff --git a/spec/views/golfers/edit.html.erb_spec.rb b/spec/views/golfers/edit.html.erb_spec.rb new file mode 100644 index 0000000..a6fc738 --- /dev/null +++ b/spec/views/golfers/edit.html.erb_spec.rb @@ -0,0 +1,24 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/golfers/edit.html.erb" do + include GolfersHelper + + before(:each) do + assigns[:golfer] = @golfer = stub_model(Golfer, + :new_record? => false, + :name => "value for name", + :earnings => "1" + ) + end + + it "should render edit form" do + render "/golfers/edit.html.erb" + + response.should have_tag("form[action=#{golfer_path(@golfer)}][method=post]") do + with_tag('input#golfer_name[name=?]', "golfer[name]") + with_tag('input#golfer_earnings[name=?]', "golfer[earnings]") + end + end +end + + diff --git a/spec/views/golfers/index.html.erb_spec.rb b/spec/views/golfers/index.html.erb_spec.rb new file mode 100644 index 0000000..5e74076 --- /dev/null +++ b/spec/views/golfers/index.html.erb_spec.rb @@ -0,0 +1,25 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/golfers/index.html.erb" do + include GolfersHelper + + before(:each) do + assigns[:golfers] = [ + stub_model(Golfer, + :name => "value for name", + :earnings => "1" + ), + stub_model(Golfer, + :name => "value for name", + :earnings => "1" + ) + ] + end + + it "should render list of golfers" do + render "/golfers/index.html.erb" + response.should have_tag("tr>td", "value for name", 2) + response.should have_tag("tr>td", "1", 2) + end +end + diff --git a/spec/views/golfers/new.html.erb_spec.rb b/spec/views/golfers/new.html.erb_spec.rb new file mode 100644 index 0000000..5e349e2 --- /dev/null +++ b/spec/views/golfers/new.html.erb_spec.rb @@ -0,0 +1,24 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/golfers/new.html.erb" do + include GolfersHelper + + before(:each) do + assigns[:golfer] = stub_model(Golfer, + :new_record? => true, + :name => "value for name", + :earnings => "1" + ) + end + + it "should render new form" do + render "/golfers/new.html.erb" + + response.should have_tag("form[action=?][method=post]", golfers_path) do + with_tag("input#golfer_name[name=?]", "golfer[name]") + with_tag("input#golfer_earnings[name=?]", "golfer[earnings]") + end + end +end + + diff --git a/spec/views/golfers/show.html.erb_spec.rb b/spec/views/golfers/show.html.erb_spec.rb new file mode 100644 index 0000000..c16711b --- /dev/null +++ b/spec/views/golfers/show.html.erb_spec.rb @@ -0,0 +1,19 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/golfers/show.html.erb" do + include GolfersHelper + + before(:each) do + assigns[:golfer] = @golfer = stub_model(Golfer, + :name => "value for name", + :earnings => "1" + ) + end + + it "should render attributes in <p>" do + render "/golfers/show.html.erb" + response.should have_text(/value\ for\ name/) + response.should have_text(/1/) + end +end +
padhi/golf
fdae070101788390c97cbdbba6ec0187decf84bb
added haml
diff --git a/vendor/plugins/haml/init.rb b/vendor/plugins/haml/init.rb new file mode 100644 index 0000000..c704100 --- /dev/null +++ b/vendor/plugins/haml/init.rb @@ -0,0 +1,8 @@ +require 'rubygems' +begin + require File.join(File.dirname(__FILE__), 'lib', 'haml') # From here +rescue LoadError + require 'haml' # From gem +end + +Haml.init_rails(binding)
hariseldon78/hariseldon78.github.com
4e6ee600f32ee37dbac3ff34ddc4192fe136d3be
added index
diff --git a/index.html b/index.html new file mode 100644 index 0000000..6b5db06 --- /dev/null +++ b/index.html @@ -0,0 +1,21 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> +<html> +<head> +<title>hariseldon78_github_page</title> +<meta name="generator" content="Bluefish 1.0.7"> +<meta name="author" content="Unknown"> +<meta name="date" content="2009-12-29T01:59:33+0100"> +<meta name="copyright" content=""> +<meta name="keywords" content=""> +<meta name="description" content=""> +<meta name="ROBOTS" content="NOINDEX, NOFOLLOW"> +<meta http-equiv="content-type" content="text/html; charset=UTF-8"> +<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8"> +<meta http-equiv="content-style-type" content="text/css"> +<meta http-equiv="expires" content="0"> +<meta http-equiv="refresh" content="5; URL=http://"> +</head> +<body> +<a href="http://hariseldon78.github.com/pidgin-share-desktop">Pidgin share desktop</a> +</body> +</html> \ No newline at end of file
unlight/DtCss
bcd03121897df97b4bc3b1f0f3e38a1a4962e3b2
emptycache script
diff --git a/.gitignore b/.gitignore index e08ea61..6d73517 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ http://github.com/search?q=DtCss&type=Repositories -emptycache.php cmd.lnk __* \ No newline at end of file diff --git a/emptycache.php b/emptycache.php new file mode 100644 index 0000000..067c35c --- /dev/null +++ b/emptycache.php @@ -0,0 +1,4 @@ +<?php +require_once implode('/', array(dirname(__FILE__), '..', '..', 'plugins', 'UsefulFunctions', 'bootstrap.console.php')); + +DtCssPlugin::_EmptyCache(); \ No newline at end of file
unlight/DtCss
57f616ea372a5ee713f03f926b1295980aff5d95
Disabled auto clean cache, icon, .gitignore updated
diff --git a/.gitignore b/.gitignore index 04bbaf4..e08ea61 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -log.php http://github.com/search?q=DtCss&type=Repositories emptycache.php -cmd.lnk \ No newline at end of file +cmd.lnk +__* \ No newline at end of file diff --git a/dtcss.plugin.php b/dtcss.plugin.php index 8b7ca9d..c4dc57b 100644 --- a/dtcss.plugin.php +++ b/dtcss.plugin.php @@ -1,127 +1,131 @@ <?php if (!defined('APPLICATION')) die(); $PluginInfo['DtCss'] = array( 'Name' => 'DtCss', - 'Description' => 'Adapts DtCSS to work with Garden.', - 'Version' => '1.2.5', + 'Description' => 'Adapts DtCSS to work with Garden. DtCSS is a PHP script that preprocesses your CSS file. It speeds up CSS coding by extending the features to CSS. Such as nested selectors, color mixing and more. DtCSS reads the CSS file with special syntax written for DtCSS, and outputs the standard CSS. <a href="http://code.google.com/p/dtcss/">DtCSS project home page</a>', + 'Version' => '1.3f', 'Author' => 'DtCss', - 'AuthorUrl' => 'http://code.google.com/p/dtcss/', + 'Date' => 'Summer 2011', + 'AuthorUrl' => 'http://github.com/search?q=DtCss&type=Repositories', 'RequiredApplications' => False, 'RequiredTheme' => False, 'RequiredPlugins' => False, 'RegisterPermissions' => False, - 'SettingsPermission' => False + 'SettingsPermission' => False, + 'License' => 'X.Net License' ); /* TODO: - enable expressions - parse error handling */ class DtCssPlugin extends Gdn_Plugin { - public function Tick_Every_20_Days_Handler() { +/* public function Tick_Every_20_Days_Handler() { self::_EmptyCache(); } public function SettingsController_AfterEnablePlugin_Handler() { self::_EmptyCache(); } public function SettingsController_AfterDisablePlugin_Handler() { - self::_EmptyCache(); - } + self::_EmptyCache(); + }*/ - private static function _EmptyCache() { + public static function _EmptyCache() { $DirectoryAry = array(PATH_APPLICATIONS, PATH_PLUGINS, PATH_THEMES); foreach($DirectoryAry as $DirectoryPath) { $Directory = new RecursiveDirectoryIterator($DirectoryPath); foreach(new RecursiveIteratorIterator($Directory) as $File){ $Basename = $File->GetBasename(); $Extension = pathinfo($Basename, 4); $Filename = pathinfo($Basename, 8); if ($Extension != 'css') continue; - if (!preg_match('/^[\.\w]+\-c\-[a-z0-9]{6}$/', $Filename)) continue; + if (!preg_match('/^[\.\w\-]+\-c\-[a-z0-9]{5,7}$/', $Filename)) continue; $CachedFile = $File->GetRealPath(); unlink($CachedFile); } } } public function PluginController_DtCssDemo_Create($Sender) { $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); $Sender->View = $this->GetView('demo.php'); $Sender->Render(); } - public static function GetHash($S) { + protected static function GetHash($S) { $Crc = sprintf('%u', crc32($S)); $Hash = base_convert($Crc, 10, 36); $Hash = sprintf("%06s", substr($Hash, -6)); // zero-padding for string length < 6 return $Hash; } public static function MakeCssFile($CssPath, $CachedCssFile) { - if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; + if (!function_exists('DtCSS')) require dirname(__FILE__) . '/DtCSS-R27f/libdtcss.php'; $Filedata = file_get_contents($CssPath); // $CssPath need for #include directives, will use dirname($CssPath)/other.css $Data = DtCSS($CssPath, $Filedata); file_put_contents($CachedCssFile, $Data); } public function Base_BeforeAddCss_Handler($Sender) { if ($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; $CssFiles =& $Sender->EventArguments['CssFiles']; foreach ($CssFiles as $Index => $CssInfo) { $CssFile = $CssInfo['FileName']; if (substr($CssFile, -7) != '.dt.css') continue; $AppFolder = $CssInfo['AppFolder']; if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; $CssPaths = array(); if(strpos($CssFile, '/') !== False) { $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); } else { if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; } $CssPath = False; foreach($CssPaths as $Glob) { $Paths = SafeGlob($Glob); if(count($Paths) > 0) { $CssPath = $Paths[0]; break; } } if($CssPath == False) continue; // not found - + $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css $Hash = self::GetHash($CssPath . filemtime($CssPath)); - $CacheFileName = sprintf('.%s-c-%s.css', $Basename, $Hash); + $CacheFileName = sprintf('__%s-c-%s.css', $Basename, $Hash); $CachedCssFile = dirname($CssPath).DS.$CacheFileName; if (!file_exists($CachedCssFile)){ self::MakeCssFile($CssPath, $CachedCssFile, True); } + + // TODO: use AbsoluteSource() from 2.0.18 // ... and replace preprocessored dt.css file by css $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) } } public function Setup() { // Nothing to do } } diff --git a/icon.png b/icon.png new file mode 100644 index 0000000..e44087e Binary files /dev/null and b/icon.png differ
unlight/DtCss
2f4352067524b86e0c0737732b703df79cb56077
Now result css file starting with dot, added some demo
diff --git a/css/demo.dt.css b/css/demo.dt.css index 0e88e36..dceed26 100644 --- a/css/demo.dt.css +++ b/css/demo.dt.css @@ -1,39 +1,57 @@ #define TEXT_COLOR red #define LINK_COLOR blue +#define BodyWidth 97 +#define PanelWidth 20 + +#PanelB { width: <# PanelWidth #>%; } +#ContentB { width: <# (BodyWidth - PanelWidth) #>%; } + +/* CSS3 */ + +div.DtCssDemo { + a { + text-shadow: black 1px 1px 2px, red 0 0 1em, white 1px 3px 1px; + } + h1 { + text-shadow: black 1px 1px 2px, red 0 0 1em; + } +} + + %Rounded{ -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; } div.DtCssDemo{ background:CadetBlue; h1{ font-size:12px; } h2{ font-style:italic; } self .SomeText span{ border:1px solid black; use:Rounded; } } body { color: TEXT_COLOR; } a { self:link, self:visited { color: LINK_COLOR; } self:hover { color: lighter(LINK_COLOR); } } \ No newline at end of file diff --git a/dtcss.plugin.php b/dtcss.plugin.php index e907cd7..8b7ca9d 100644 --- a/dtcss.plugin.php +++ b/dtcss.plugin.php @@ -1,126 +1,127 @@ <?php if (!defined('APPLICATION')) die(); $PluginInfo['DtCss'] = array( 'Name' => 'DtCss', 'Description' => 'Adapts DtCSS to work with Garden.', - 'Version' => '1.2.4', + 'Version' => '1.2.5', + 'Author' => 'DtCss', 'AuthorUrl' => 'http://code.google.com/p/dtcss/', 'RequiredApplications' => False, - 'RequiredTheme' => False, + 'RequiredTheme' => False, 'RequiredPlugins' => False, 'RegisterPermissions' => False, 'SettingsPermission' => False ); /* TODO: - enable expressions - parse error handling */ class DtCssPlugin extends Gdn_Plugin { public function Tick_Every_20_Days_Handler() { self::_EmptyCache(); } public function SettingsController_AfterEnablePlugin_Handler() { self::_EmptyCache(); } public function SettingsController_AfterDisablePlugin_Handler() { self::_EmptyCache(); } private static function _EmptyCache() { $DirectoryAry = array(PATH_APPLICATIONS, PATH_PLUGINS, PATH_THEMES); foreach($DirectoryAry as $DirectoryPath) { $Directory = new RecursiveDirectoryIterator($DirectoryPath); foreach(new RecursiveIteratorIterator($Directory) as $File){ $Basename = $File->GetBasename(); $Extension = pathinfo($Basename, 4); $Filename = pathinfo($Basename, 8); if ($Extension != 'css') continue; - if (!preg_match('/^\w+\-c\-[a-z0-9]{6}$/', $Filename)) continue; + if (!preg_match('/^[\.\w]+\-c\-[a-z0-9]{6}$/', $Filename)) continue; $CachedFile = $File->GetRealPath(); unlink($CachedFile); } } } public function PluginController_DtCssDemo_Create($Sender) { $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); $Sender->View = $this->GetView('demo.php'); $Sender->Render(); } public static function GetHash($S) { $Crc = sprintf('%u', crc32($S)); $Hash = base_convert($Crc, 10, 36); $Hash = sprintf("%06s", substr($Hash, -6)); // zero-padding for string length < 6 return $Hash; } public static function MakeCssFile($CssPath, $CachedCssFile) { if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; $Filedata = file_get_contents($CssPath); // $CssPath need for #include directives, will use dirname($CssPath)/other.css $Data = DtCSS($CssPath, $Filedata); file_put_contents($CachedCssFile, $Data); } public function Base_BeforeAddCss_Handler($Sender) { - if($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; + if ($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; $CssFiles =& $Sender->EventArguments['CssFiles']; foreach ($CssFiles as $Index => $CssInfo) { $CssFile = $CssInfo['FileName']; if (substr($CssFile, -7) != '.dt.css') continue; $AppFolder = $CssInfo['AppFolder']; if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; $CssPaths = array(); if(strpos($CssFile, '/') !== False) { $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); } else { if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; } $CssPath = False; foreach($CssPaths as $Glob) { $Paths = SafeGlob($Glob); if(count($Paths) > 0) { $CssPath = $Paths[0]; break; } } if($CssPath == False) continue; // not found $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css $Hash = self::GetHash($CssPath . filemtime($CssPath)); - $CacheFileName = sprintf('%s-c-%s.css', $Basename, $Hash); + $CacheFileName = sprintf('.%s-c-%s.css', $Basename, $Hash); $CachedCssFile = dirname($CssPath).DS.$CacheFileName; if (!file_exists($CachedCssFile)){ self::MakeCssFile($CssPath, $CachedCssFile, True); } // ... and replace preprocessored dt.css file by css $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) } } public function Setup() { // Nothing to do } }
unlight/DtCss
86be676d4d2114f05768362718a202c9b0d1dc51
Changed clear cache to 20 days interval
diff --git a/dtcss.plugin.php b/dtcss.plugin.php index 50bfc0f..e907cd7 100644 --- a/dtcss.plugin.php +++ b/dtcss.plugin.php @@ -1,126 +1,126 @@ <?php if (!defined('APPLICATION')) die(); $PluginInfo['DtCss'] = array( 'Name' => 'DtCss', 'Description' => 'Adapts DtCSS to work with Garden.', - 'Version' => '1.2.3', + 'Version' => '1.2.4', 'AuthorUrl' => 'http://code.google.com/p/dtcss/', 'RequiredApplications' => False, 'RequiredTheme' => False, 'RequiredPlugins' => False, 'RegisterPermissions' => False, 'SettingsPermission' => False ); /* TODO: - enable expressions - parse error handling */ class DtCssPlugin extends Gdn_Plugin { - public function Tick_Every_10_Days_Handler() { + public function Tick_Every_20_Days_Handler() { self::_EmptyCache(); } public function SettingsController_AfterEnablePlugin_Handler() { self::_EmptyCache(); } public function SettingsController_AfterDisablePlugin_Handler() { self::_EmptyCache(); } private static function _EmptyCache() { $DirectoryAry = array(PATH_APPLICATIONS, PATH_PLUGINS, PATH_THEMES); foreach($DirectoryAry as $DirectoryPath) { $Directory = new RecursiveDirectoryIterator($DirectoryPath); foreach(new RecursiveIteratorIterator($Directory) as $File){ $Basename = $File->GetBasename(); $Extension = pathinfo($Basename, 4); $Filename = pathinfo($Basename, 8); if ($Extension != 'css') continue; if (!preg_match('/^\w+\-c\-[a-z0-9]{6}$/', $Filename)) continue; $CachedFile = $File->GetRealPath(); unlink($CachedFile); } } } public function PluginController_DtCssDemo_Create($Sender) { $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); $Sender->View = $this->GetView('demo.php'); $Sender->Render(); } public static function GetHash($S) { $Crc = sprintf('%u', crc32($S)); $Hash = base_convert($Crc, 10, 36); $Hash = sprintf("%06s", substr($Hash, -6)); // zero-padding for string length < 6 return $Hash; } public static function MakeCssFile($CssPath, $CachedCssFile) { if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; $Filedata = file_get_contents($CssPath); // $CssPath need for #include directives, will use dirname($CssPath)/other.css $Data = DtCSS($CssPath, $Filedata); file_put_contents($CachedCssFile, $Data); } public function Base_BeforeAddCss_Handler($Sender) { if($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; $CssFiles =& $Sender->EventArguments['CssFiles']; foreach ($CssFiles as $Index => $CssInfo) { $CssFile = $CssInfo['FileName']; if (substr($CssFile, -7) != '.dt.css') continue; $AppFolder = $CssInfo['AppFolder']; if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; $CssPaths = array(); if(strpos($CssFile, '/') !== False) { $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); } else { if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; } $CssPath = False; foreach($CssPaths as $Glob) { $Paths = SafeGlob($Glob); if(count($Paths) > 0) { $CssPath = $Paths[0]; break; } } if($CssPath == False) continue; // not found $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css $Hash = self::GetHash($CssPath . filemtime($CssPath)); $CacheFileName = sprintf('%s-c-%s.css', $Basename, $Hash); $CachedCssFile = dirname($CssPath).DS.$CacheFileName; if (!file_exists($CachedCssFile)){ self::MakeCssFile($CssPath, $CachedCssFile, True); } // ... and replace preprocessored dt.css file by css $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) } } public function Setup() { // Nothing to do } }
unlight/DtCss
87a747bba9e0798613edab83124090d2f4fd29f1
Added cron job: remove cached files
diff --git a/dtcss.plugin.php b/dtcss.plugin.php index 7c85358..50bfc0f 100644 --- a/dtcss.plugin.php +++ b/dtcss.plugin.php @@ -1,133 +1,126 @@ <?php if (!defined('APPLICATION')) die(); $PluginInfo['DtCss'] = array( 'Name' => 'DtCss', 'Description' => 'Adapts DtCSS to work with Garden.', 'Version' => '1.2.3', 'AuthorUrl' => 'http://code.google.com/p/dtcss/', 'RequiredApplications' => False, 'RequiredTheme' => False, 'RequiredPlugins' => False, 'RegisterPermissions' => False, 'SettingsPermission' => False ); /* TODO: - enable expressions - parse error handling */ -/* -CHANGELOG -04 Sep 2010 / 1.2 -- delete all cached files when enabling/disabling plugin -22 Aug 2010 / 1.1 -21 Aug 2010 / 1.0 -- save cached css file to same directory where .dt.css file -20 Aug 2010 / 0.9 -- first release -*/ - class DtCssPlugin extends Gdn_Plugin { + public function Tick_Every_10_Days_Handler() { + self::_EmptyCache(); + } + public function SettingsController_AfterEnablePlugin_Handler() { - self::_EmptyCache(); + self::_EmptyCache(); } public function SettingsController_AfterDisablePlugin_Handler() { self::_EmptyCache(); } private static function _EmptyCache() { $DirectoryAry = array(PATH_APPLICATIONS, PATH_PLUGINS, PATH_THEMES); foreach($DirectoryAry as $DirectoryPath) { $Directory = new RecursiveDirectoryIterator($DirectoryPath); foreach(new RecursiveIteratorIterator($Directory) as $File){ $Basename = $File->GetBasename(); $Extension = pathinfo($Basename, 4); $Filename = pathinfo($Basename, 8); if ($Extension != 'css') continue; if (!preg_match('/^\w+\-c\-[a-z0-9]{6}$/', $Filename)) continue; $CachedFile = $File->GetRealPath(); unlink($CachedFile); } } } public function PluginController_DtCssDemo_Create($Sender) { $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); $Sender->View = $this->GetView('demo.php'); $Sender->Render(); } public static function GetHash($S) { $Crc = sprintf('%u', crc32($S)); $Hash = base_convert($Crc, 10, 36); $Hash = sprintf("%06s", substr($Hash, -6)); // zero-padding for string length < 6 return $Hash; } public static function MakeCssFile($CssPath, $CachedCssFile) { if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; $Filedata = file_get_contents($CssPath); // $CssPath need for #include directives, will use dirname($CssPath)/other.css $Data = DtCSS($CssPath, $Filedata); file_put_contents($CachedCssFile, $Data); } public function Base_BeforeAddCss_Handler($Sender) { if($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; $CssFiles =& $Sender->EventArguments['CssFiles']; foreach ($CssFiles as $Index => $CssInfo) { $CssFile = $CssInfo['FileName']; if (substr($CssFile, -7) != '.dt.css') continue; $AppFolder = $CssInfo['AppFolder']; if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; $CssPaths = array(); if(strpos($CssFile, '/') !== False) { $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); } else { if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; } $CssPath = False; foreach($CssPaths as $Glob) { $Paths = SafeGlob($Glob); if(count($Paths) > 0) { $CssPath = $Paths[0]; break; } } if($CssPath == False) continue; // not found $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css $Hash = self::GetHash($CssPath . filemtime($CssPath)); $CacheFileName = sprintf('%s-c-%s.css', $Basename, $Hash); $CachedCssFile = dirname($CssPath).DS.$CacheFileName; if (!file_exists($CachedCssFile)){ self::MakeCssFile($CssPath, $CachedCssFile, True); } // ... and replace preprocessored dt.css file by css $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) } } public function Setup() { // Nothing to do } }
unlight/DtCss
f10923fc1e3914e378b02cc5daa2903b367ea268
Removed SaveLog() Dashboard_Handler() method. Now cached files removes only when enabled/disabling plugin.
diff --git a/dtcss.plugin.php b/dtcss.plugin.php index a5d0ae1..7c85358 100644 --- a/dtcss.plugin.php +++ b/dtcss.plugin.php @@ -1,164 +1,133 @@ <?php if (!defined('APPLICATION')) die(); $PluginInfo['DtCss'] = array( 'Name' => 'DtCss', 'Description' => 'Adapts DtCSS to work with Garden.', 'Version' => '1.2.3', 'AuthorUrl' => 'http://code.google.com/p/dtcss/', 'RequiredApplications' => False, 'RequiredTheme' => False, 'RequiredPlugins' => False, 'RegisterPermissions' => False, 'SettingsPermission' => False ); /* TODO: - enable expressions - parse error handling */ /* CHANGELOG 04 Sep 2010 / 1.2 - delete all cached files when enabling/disabling plugin 22 Aug 2010 / 1.1 21 Aug 2010 / 1.0 - save cached css file to same directory where .dt.css file 20 Aug 2010 / 0.9 - first release */ class DtCssPlugin extends Gdn_Plugin { public function SettingsController_AfterEnablePlugin_Handler() { self::_EmptyCache(); } public function SettingsController_AfterDisablePlugin_Handler() { self::_EmptyCache(); } private static function _EmptyCache() { $DirectoryAry = array(PATH_APPLICATIONS, PATH_PLUGINS, PATH_THEMES); foreach($DirectoryAry as $DirectoryPath) { $Directory = new RecursiveDirectoryIterator($DirectoryPath); foreach(new RecursiveIteratorIterator($Directory) as $File){ $Basename = $File->GetBasename(); $Extension = pathinfo($Basename, 4); $Filename = pathinfo($Basename, 8); if ($Extension != 'css') continue; if (!preg_match('/^\w+\-c\-[a-z0-9]{6}$/', $Filename)) continue; $CachedFile = $File->GetRealPath(); unlink($CachedFile); } } } - public function SettingsController_DashboardData_Handler() { - self::_CleanUp(); - } - - // remove cached files - private static function _CleanUp(){ - static $bWait; - if($bWait === True) return; - $bWait = True; - $LogFile = dirname(__FILE__).DS.'log.php'; - if(!file_exists($LogFile)) return; - $UntouchedTime = time() - filemtime($LogFile); - $DeleteTime = strtotime('+5 days', 0); - if($UntouchedTime < $DeleteTime) return; - $LoggedData = array_map('trim', file($LogFile)); - for($Count = count($LoggedData), $i = 1; $i < $Count; $i++){ - $File = $LoggedData[$i]; - if(file_exists($File)) unlink($File); - } - unlink($LogFile); - } - - private static function SaveLog($CachedCssFile) { - static $LogFile; - if (is_null($LogFile)){ - $LogFile = dirname(__FILE__).DS.'log.php'; - if(!file_exists($LogFile)) Gdn_FileSystem::SaveFile($LogFile, "<?php exit();\n"); - } - file_put_contents($LogFile, $CachedCssFile."\n", FILE_APPEND); - } - public function PluginController_DtCssDemo_Create($Sender) { $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); $Sender->View = $this->GetView('demo.php'); $Sender->Render(); } public static function GetHash($S) { $Crc = sprintf('%u', crc32($S)); $Hash = base_convert($Crc, 10, 36); $Hash = sprintf("%06s", substr($Hash, -6)); // zero-padding for string length < 6 return $Hash; } public static function MakeCssFile($CssPath, $CachedCssFile) { if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; $Filedata = file_get_contents($CssPath); // $CssPath need for #include directives, will use dirname($CssPath)/other.css $Data = DtCSS($CssPath, $Filedata); file_put_contents($CachedCssFile, $Data); } public function Base_BeforeAddCss_Handler($Sender) { if($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; $CssFiles =& $Sender->EventArguments['CssFiles']; foreach ($CssFiles as $Index => $CssInfo) { $CssFile = $CssInfo['FileName']; if (substr($CssFile, -7) != '.dt.css') continue; $AppFolder = $CssInfo['AppFolder']; if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; $CssPaths = array(); if(strpos($CssFile, '/') !== False) { $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); } else { if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; } $CssPath = False; foreach($CssPaths as $Glob) { $Paths = SafeGlob($Glob); if(count($Paths) > 0) { $CssPath = $Paths[0]; break; } } if($CssPath == False) continue; // not found $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css $Hash = self::GetHash($CssPath . filemtime($CssPath)); $CacheFileName = sprintf('%s-c-%s.css', $Basename, $Hash); $CachedCssFile = dirname($CssPath).DS.$CacheFileName; if (!file_exists($CachedCssFile)){ - self::SaveLog($CachedCssFile); // for deleting self::MakeCssFile($CssPath, $CachedCssFile, True); } // ... and replace preprocessored dt.css file by css $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) } } public function Setup() { + // Nothing to do } }
unlight/DtCss
224a9213230f2f40e677580ee6e11f3c31c015d8
Fixed removing cached files for plugins
diff --git a/dtcss.plugin.php b/dtcss.plugin.php index e181f30..a5d0ae1 100644 --- a/dtcss.plugin.php +++ b/dtcss.plugin.php @@ -1,165 +1,164 @@ <?php if (!defined('APPLICATION')) die(); $PluginInfo['DtCss'] = array( 'Name' => 'DtCss', 'Description' => 'Adapts DtCSS to work with Garden.', 'Version' => '1.2.3', 'AuthorUrl' => 'http://code.google.com/p/dtcss/', 'RequiredApplications' => False, 'RequiredTheme' => False, 'RequiredPlugins' => False, 'RegisterPermissions' => False, 'SettingsPermission' => False ); /* TODO: - enable expressions - parse error handling */ /* CHANGELOG 04 Sep 2010 / 1.2 - delete all cached files when enabling/disabling plugin 22 Aug 2010 / 1.1 21 Aug 2010 / 1.0 - save cached css file to same directory where .dt.css file 20 Aug 2010 / 0.9 - first release */ class DtCssPlugin extends Gdn_Plugin { public function SettingsController_AfterEnablePlugin_Handler() { self::_EmptyCache(); } public function SettingsController_AfterDisablePlugin_Handler() { self::_EmptyCache(); } private static function _EmptyCache() { $DirectoryAry = array(PATH_APPLICATIONS, PATH_PLUGINS, PATH_THEMES); foreach($DirectoryAry as $DirectoryPath) { - $Directory = new RecursiveDirectoryIterator(PATH_APPLICATIONS); + $Directory = new RecursiveDirectoryIterator($DirectoryPath); foreach(new RecursiveIteratorIterator($Directory) as $File){ $Basename = $File->GetBasename(); $Extension = pathinfo($Basename, 4); $Filename = pathinfo($Basename, 8); if ($Extension != 'css') continue; if (!preg_match('/^\w+\-c\-[a-z0-9]{6}$/', $Filename)) continue; - //d(@$Extension, $File->GetRealPath(), @$Filename, $File, get_class_methods($File), $File->GetBasename()); $CachedFile = $File->GetRealPath(); unlink($CachedFile); } } } public function SettingsController_DashboardData_Handler() { self::_CleanUp(); } // remove cached files private static function _CleanUp(){ static $bWait; if($bWait === True) return; $bWait = True; $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) return; $UntouchedTime = time() - filemtime($LogFile); $DeleteTime = strtotime('+5 days', 0); if($UntouchedTime < $DeleteTime) return; $LoggedData = array_map('trim', file($LogFile)); for($Count = count($LoggedData), $i = 1; $i < $Count; $i++){ $File = $LoggedData[$i]; if(file_exists($File)) unlink($File); } unlink($LogFile); } private static function SaveLog($CachedCssFile) { static $LogFile; if (is_null($LogFile)){ $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) Gdn_FileSystem::SaveFile($LogFile, "<?php exit();\n"); } file_put_contents($LogFile, $CachedCssFile."\n", FILE_APPEND); } public function PluginController_DtCssDemo_Create($Sender) { $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); $Sender->View = $this->GetView('demo.php'); $Sender->Render(); } public static function GetHash($S) { $Crc = sprintf('%u', crc32($S)); $Hash = base_convert($Crc, 10, 36); $Hash = sprintf("%06s", substr($Hash, -6)); // zero-padding for string length < 6 return $Hash; } public static function MakeCssFile($CssPath, $CachedCssFile) { if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; $Filedata = file_get_contents($CssPath); // $CssPath need for #include directives, will use dirname($CssPath)/other.css $Data = DtCSS($CssPath, $Filedata); file_put_contents($CachedCssFile, $Data); } public function Base_BeforeAddCss_Handler($Sender) { if($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; $CssFiles =& $Sender->EventArguments['CssFiles']; foreach ($CssFiles as $Index => $CssInfo) { $CssFile = $CssInfo['FileName']; if (substr($CssFile, -7) != '.dt.css') continue; $AppFolder = $CssInfo['AppFolder']; if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; $CssPaths = array(); if(strpos($CssFile, '/') !== False) { $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); } else { if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; } $CssPath = False; foreach($CssPaths as $Glob) { $Paths = SafeGlob($Glob); if(count($Paths) > 0) { $CssPath = $Paths[0]; break; } } if($CssPath == False) continue; // not found $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css $Hash = self::GetHash($CssPath . filemtime($CssPath)); $CacheFileName = sprintf('%s-c-%s.css', $Basename, $Hash); $CachedCssFile = dirname($CssPath).DS.$CacheFileName; if (!file_exists($CachedCssFile)){ self::SaveLog($CachedCssFile); // for deleting self::MakeCssFile($CssPath, $CachedCssFile, True); } // ... and replace preprocessored dt.css file by css $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) } } public function Setup() { } }
unlight/DtCss
a457d5ee62a95eb08ddb9fcc1bf7dffc141b9865
Fixed incorrect function name
diff --git a/dtcss.plugin.php b/dtcss.plugin.php index d80702b..596ff95 100644 --- a/dtcss.plugin.php +++ b/dtcss.plugin.php @@ -1,165 +1,165 @@ <?php if (!defined('APPLICATION')) die(); $PluginInfo['DtCss'] = array( 'Name' => 'DtCss', 'Description' => 'Adapts DtCSS to work with Garden.', 'Version' => '1.2.2', 'AuthorUrl' => 'http://code.google.com/p/dtcss/', 'RequiredApplications' => False, 'RequiredTheme' => False, 'RequiredPlugins' => False, 'RegisterPermissions' => False, 'SettingsPermission' => False ); /* TODO: - enable expressions - parse error handling */ /* CHANGELOG 04 Sep 2010 / 1.2 - delete all cached files when enabling/disabling plugin 22 Aug 2010 / 1.1 21 Aug 2010 / 1.0 - save cached css file to same directory where .dt.css file 20 Aug 2010 / 0.9 - first release */ class DtCssPlugin extends Gdn_Plugin { public function SettingsController_AfterEnablePlugin_Handler() { self::_EmptyCache(); } public function SettingsController_AfterDisablePlugin_Handler() { - self::EmptyCache(); + self::_EmptyCache(); } private static function _EmptyCache() { $DirectoryAry = array(PATH_APPLICATIONS, PATH_PLUGINS, PATH_THEMES); foreach($DirectoryAry as $DirectoryPath) { $Directory = new RecursiveDirectoryIterator(PATH_APPLICATIONS); foreach(new RecursiveIteratorIterator($Directory) as $File){ $Basename = $File->GetBasename(); $Extension = pathinfo($Basename, 4); $Filename = pathinfo($Basename, 8); if ($Extension != 'css') continue; if (!preg_match('/^\w+\-c\-[a-z0-9]{6}$/', $Filename)) continue; //d(@$Extension, $File->GetRealPath(), @$Filename, $File, get_class_methods($File), $File->GetBasename()); $CachedFile = $File->GetRealPath(); unlink($CachedFile); } } } public function SettingsController_DashboardData_Handler() { self::_CleanUp(); } // remove cached files private static function _CleanUp(){ static $bWait; if($bWait === True) return; $bWait = True; $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) return; $UntouchedTime = time() - filemtime($LogFile); $DeleteTime = strtotime('+5 days', 0); if($UntouchedTime < $DeleteTime) return; $LoggedData = array_map('trim', file($LogFile)); for($Count = count($LoggedData), $i = 1; $i < $Count; $i++){ $File = $LoggedData[$i]; if(file_exists($File)) unlink($File); } unlink($LogFile); } private static function SaveLog($CachedCssFile) { static $LogFile; if (is_null($LogFile)){ $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) Gdn_FileSystem::SaveFile($LogFile, "<?php exit();\n"); } file_put_contents($LogFile, $CachedCssFile."\n", FILE_APPEND); } public function PluginController_DtCssDemo_Create($Sender) { $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); $Sender->View = $this->GetView('demo.php'); $Sender->Render(); } public static function GetHash($S) { $Crc = sprintf('%u', crc32($S)); $Hash = base_convert($Crc, 10, 36); $Hash = sprintf("%06s", substr($Hash, -6)); // zero-padding for string length < 6 return $Hash; } public static function MakeCssFile($CssPath, $CachedCssFile) { if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; $Filedata = file_get_contents($CssPath); // $CssPath need for #include directives, will use dirname($CssPath)/other.css $Data = DtCSS($CssPath, $Filedata); file_put_contents($CachedCssFile, $Data); } public function Base_BeforeAddCss_Handler($Sender) { if($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; $CssFiles =& $Sender->EventArguments['CssFiles']; foreach ($CssFiles as $Index => $CssInfo) { $CssFile = $CssInfo['FileName']; if (substr($CssFile, -7) != '.dt.css') continue; $AppFolder = $CssInfo['AppFolder']; if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; $CssPaths = array(); if(strpos($CssFile, '/') !== False) { $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); } else { if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; } $CssPath = False; foreach($CssPaths as $Glob) { $Paths = SafeGlob($Glob); if(count($Paths) > 0) { $CssPath = $Paths[0]; break; } } if($CssPath == False) continue; // not found $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css $Hash = self::GetHash($CssPath . filemtime($CssPath)); $CacheFileName = sprintf('%s-c-%s.css', $Basename, $Hash); $CachedCssFile = dirname($CssPath).DS.$CacheFileName; if (!file_exists($CachedCssFile)){ self::SaveLog($CachedCssFile); // for deleting self::MakeCssFile($CssPath, $CachedCssFile, True); } // ... and replace preprocessored dt.css file by css $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) } } public function Setup() { } }
unlight/DtCss
094e92ebddea85eb89116b47de43567c693d3460
Fixed _EmptyCache()
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..04bbaf4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +log.php +http://github.com/search?q=DtCss&type=Repositories +emptycache.php +cmd.lnk \ No newline at end of file diff --git a/dtcss.plugin.php b/dtcss.plugin.php index 36a094f..3a2ea8f 100644 --- a/dtcss.plugin.php +++ b/dtcss.plugin.php @@ -1,164 +1,165 @@ <?php if (!defined('APPLICATION')) die(); $PluginInfo['DtCss'] = array( 'Name' => 'DtCss', 'Description' => 'Adapts DtCSS to work with Garden.', 'Version' => '1.2.1', 'AuthorUrl' => 'http://code.google.com/p/dtcss/', 'RequiredApplications' => False, 'RequiredTheme' => False, 'RequiredPlugins' => False, 'RegisterPermissions' => False, 'SettingsPermission' => False ); /* TODO: - enable expressions - parse error handling */ /* CHANGELOG 04 Sep 2010 / 1.2 - delete all cached files when enabling/disabling plugin 22 Aug 2010 / 1.1 21 Aug 2010 / 1.0 - save cached css file to same directory where .dt.css file 20 Aug 2010 / 0.9 - first release */ class DtCssPlugin extends Gdn_Plugin { public function SettingsController_AfterEnablePlugin_Handler() { self::_EmptyCache(); } public function SettingsController_AfterDisablePlugin_Handler() { self::EmptyCache(); } private static function _EmptyCache() { $DirectoryAry = array(PATH_APPLICATIONS, PATH_PLUGINS, PATH_THEMES); foreach($DirectoryAry as $DirectoryPath) { $Directory = new RecursiveDirectoryIterator(PATH_APPLICATIONS); foreach(new RecursiveIteratorIterator($Directory) as $File){ $Basename = $File->GetBasename(); $Extension = pathinfo($Basename, 4); $Filename = pathinfo($Basename, 8); - if ($Extension != 'css' || empty($Filename[11]) || !preg_match('/^\w+\-c\-[a-z0-9]{6}$/', $Filename)) continue; - //d(@$Extension, @$Filename, $File, get_class_methods($File), $File->GetBasename()); + if ($Extension != 'css') continue; + if (!preg_match('/^\w+\-c\-[a-z0-9]{6}$/', $Filename)) continue; + //d(@$Extension, $File->GetRealPath(), @$Filename, $File, get_class_methods($File), $File->GetBasename()); $CachedFile = $File->GetRealPath(); unlink($CachedFile); } } } public function SettingsController_DashboardData_Handler() { self::_CleanUp(); } // remove cached files private static function _CleanUp(){ static $bWait; if($bWait === True) return; $bWait = True; $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) return; $UntouchedTime = time() - filemtime($LogFile); $DeleteTime = strtotime('+5 days', 0); if($UntouchedTime < $DeleteTime) return; $LoggedData = array_map('trim', file($LogFile)); for($Count = count($LoggedData), $i = 1; $i < $Count; $i++){ $File = $LoggedData[$i]; if(file_exists($File)) unlink($File); } unlink($LogFile); } private static function SaveLog($CachedCssFile) { static $LogFile; if (is_null($LogFile)){ $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) Gdn_FileSystem::SaveFile($LogFile, "<?php exit();\n"); } file_put_contents($LogFile, $CachedCssFile."\n", FILE_APPEND); } public function PluginController_DtCssDemo_Create($Sender) { $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); $Sender->View = $this->GetView('demo.php'); $Sender->Render(); } public static function GetHash($S) { $Crc = sprintf('%u', crc32($S)); $Hash = base_convert($Crc, 10, 36); $Hash = sprintf("%06s", substr($Hash, -6)); // zero-padding for string length < 6 return $Hash; } public static function MakeCssFile($CssPath, $CachedCssFile) { if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; $Filedata = file_get_contents($CssPath); // $CssPath need for #include directives, will use dirname($CssPath)/other.css $Data = DtCSS($CssPath, $Filedata); file_put_contents($CachedCssFile, $Data); } public function Base_BeforeAddCss_Handler($Sender) { if($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; $CssFiles =& $Sender->EventArguments['CssFiles']; foreach ($CssFiles as $Index => $CssInfo) { $CssFile = $CssInfo['FileName']; if (substr($CssFile, -7) != '.dt.css') continue; $AppFolder = $CssInfo['AppFolder']; if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; $CssPaths = array(); if(strpos($CssFile, '/') !== False) { $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); } else { if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; } $CssPath = False; foreach($CssPaths as $Glob) { $Paths = SafeGlob($Glob); if(count($Paths) > 0) { $CssPath = $Paths[0]; break; } } if($CssPath == False) continue; // not found $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css $Hash = self::GetHash($CssPath . filemtime($CssPath)); $CacheFileName = sprintf('%s-c-%s.css', $Basename, $Hash); $CachedCssFile = dirname($CssPath).DS.$CacheFileName; if (!file_exists($CachedCssFile)){ self::SaveLog($CachedCssFile); // for deleting self::MakeCssFile($CssPath, $CachedCssFile, True); } // ... and replace preprocessored dt.css file by css $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) } } public function Setup() { } }
unlight/DtCss
f0c43e2fa6ee0fc86ff2e11f6a80534d64520923
v. 1.2.1
diff --git a/dtcss.plugin.php b/dtcss.plugin.php index 515eb2f..36a094f 100644 --- a/dtcss.plugin.php +++ b/dtcss.plugin.php @@ -1,164 +1,164 @@ <?php if (!defined('APPLICATION')) die(); $PluginInfo['DtCss'] = array( 'Name' => 'DtCss', 'Description' => 'Adapts DtCSS to work with Garden.', - 'Version' => '1.2', + 'Version' => '1.2.1', 'AuthorUrl' => 'http://code.google.com/p/dtcss/', 'RequiredApplications' => False, 'RequiredTheme' => False, 'RequiredPlugins' => False, 'RegisterPermissions' => False, 'SettingsPermission' => False ); /* TODO: - enable expressions - parse error handling */ /* CHANGELOG 04 Sep 2010 / 1.2 - delete all cached files when enabling/disabling plugin 22 Aug 2010 / 1.1 21 Aug 2010 / 1.0 - save cached css file to same directory where .dt.css file 20 Aug 2010 / 0.9 - first release */ class DtCssPlugin extends Gdn_Plugin { public function SettingsController_AfterEnablePlugin_Handler() { self::_EmptyCache(); } public function SettingsController_AfterDisablePlugin_Handler() { self::EmptyCache(); } private static function _EmptyCache() { $DirectoryAry = array(PATH_APPLICATIONS, PATH_PLUGINS, PATH_THEMES); foreach($DirectoryAry as $DirectoryPath) { $Directory = new RecursiveDirectoryIterator(PATH_APPLICATIONS); foreach(new RecursiveIteratorIterator($Directory) as $File){ $Basename = $File->GetBasename(); $Extension = pathinfo($Basename, 4); $Filename = pathinfo($Basename, 8); if ($Extension != 'css' || empty($Filename[11]) || !preg_match('/^\w+\-c\-[a-z0-9]{6}$/', $Filename)) continue; //d(@$Extension, @$Filename, $File, get_class_methods($File), $File->GetBasename()); $CachedFile = $File->GetRealPath(); unlink($CachedFile); } } } public function SettingsController_DashboardData_Handler() { self::_CleanUp(); } // remove cached files private static function _CleanUp(){ static $bWait; if($bWait === True) return; $bWait = True; $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) return; $UntouchedTime = time() - filemtime($LogFile); $DeleteTime = strtotime('+5 days', 0); if($UntouchedTime < $DeleteTime) return; $LoggedData = array_map('trim', file($LogFile)); for($Count = count($LoggedData), $i = 1; $i < $Count; $i++){ $File = $LoggedData[$i]; if(file_exists($File)) unlink($File); } unlink($LogFile); } private static function SaveLog($CachedCssFile) { static $LogFile; if (is_null($LogFile)){ $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) Gdn_FileSystem::SaveFile($LogFile, "<?php exit();\n"); } file_put_contents($LogFile, $CachedCssFile."\n", FILE_APPEND); } public function PluginController_DtCssDemo_Create($Sender) { $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); $Sender->View = $this->GetView('demo.php'); $Sender->Render(); } public static function GetHash($S) { $Crc = sprintf('%u', crc32($S)); $Hash = base_convert($Crc, 10, 36); $Hash = sprintf("%06s", substr($Hash, -6)); // zero-padding for string length < 6 return $Hash; } public static function MakeCssFile($CssPath, $CachedCssFile) { if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; $Filedata = file_get_contents($CssPath); // $CssPath need for #include directives, will use dirname($CssPath)/other.css $Data = DtCSS($CssPath, $Filedata); file_put_contents($CachedCssFile, $Data); } public function Base_BeforeAddCss_Handler($Sender) { if($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; $CssFiles =& $Sender->EventArguments['CssFiles']; foreach ($CssFiles as $Index => $CssInfo) { $CssFile = $CssInfo['FileName']; if (substr($CssFile, -7) != '.dt.css') continue; $AppFolder = $CssInfo['AppFolder']; if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; $CssPaths = array(); if(strpos($CssFile, '/') !== False) { $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); } else { if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; } $CssPath = False; foreach($CssPaths as $Glob) { $Paths = SafeGlob($Glob); if(count($Paths) > 0) { $CssPath = $Paths[0]; break; } } if($CssPath == False) continue; // not found $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css $Hash = self::GetHash($CssPath . filemtime($CssPath)); $CacheFileName = sprintf('%s-c-%s.css', $Basename, $Hash); $CachedCssFile = dirname($CssPath).DS.$CacheFileName; if (!file_exists($CachedCssFile)){ self::SaveLog($CachedCssFile); // for deleting self::MakeCssFile($CssPath, $CachedCssFile, True); } // ... and replace preprocessored dt.css file by css $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) } } public function Setup() { } }
unlight/DtCss
928490e398be15b9aec74f2aa05cdf0800be6b40
zero-padding for string length < 6
diff --git a/dtcss.plugin.php b/dtcss.plugin.php index eed1d75..515eb2f 100644 --- a/dtcss.plugin.php +++ b/dtcss.plugin.php @@ -1,164 +1,164 @@ <?php if (!defined('APPLICATION')) die(); $PluginInfo['DtCss'] = array( 'Name' => 'DtCss', 'Description' => 'Adapts DtCSS to work with Garden.', 'Version' => '1.2', 'AuthorUrl' => 'http://code.google.com/p/dtcss/', 'RequiredApplications' => False, 'RequiredTheme' => False, 'RequiredPlugins' => False, 'RegisterPermissions' => False, 'SettingsPermission' => False ); /* TODO: - enable expressions - parse error handling */ /* CHANGELOG 04 Sep 2010 / 1.2 - delete all cached files when enabling/disabling plugin 22 Aug 2010 / 1.1 21 Aug 2010 / 1.0 - save cached css file to same directory where .dt.css file 20 Aug 2010 / 0.9 - first release */ class DtCssPlugin extends Gdn_Plugin { public function SettingsController_AfterEnablePlugin_Handler() { self::_EmptyCache(); } public function SettingsController_AfterDisablePlugin_Handler() { self::EmptyCache(); } private static function _EmptyCache() { $DirectoryAry = array(PATH_APPLICATIONS, PATH_PLUGINS, PATH_THEMES); foreach($DirectoryAry as $DirectoryPath) { $Directory = new RecursiveDirectoryIterator(PATH_APPLICATIONS); foreach(new RecursiveIteratorIterator($Directory) as $File){ $Basename = $File->GetBasename(); $Extension = pathinfo($Basename, 4); $Filename = pathinfo($Basename, 8); if ($Extension != 'css' || empty($Filename[11]) || !preg_match('/^\w+\-c\-[a-z0-9]{6}$/', $Filename)) continue; //d(@$Extension, @$Filename, $File, get_class_methods($File), $File->GetBasename()); $CachedFile = $File->GetRealPath(); unlink($CachedFile); } } } public function SettingsController_DashboardData_Handler() { self::_CleanUp(); } // remove cached files private static function _CleanUp(){ static $bWait; if($bWait === True) return; $bWait = True; $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) return; $UntouchedTime = time() - filemtime($LogFile); $DeleteTime = strtotime('+5 days', 0); if($UntouchedTime < $DeleteTime) return; $LoggedData = array_map('trim', file($LogFile)); for($Count = count($LoggedData), $i = 1; $i < $Count; $i++){ $File = $LoggedData[$i]; if(file_exists($File)) unlink($File); } unlink($LogFile); } private static function SaveLog($CachedCssFile) { static $LogFile; if (is_null($LogFile)){ $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) Gdn_FileSystem::SaveFile($LogFile, "<?php exit();\n"); } file_put_contents($LogFile, $CachedCssFile."\n", FILE_APPEND); } public function PluginController_DtCssDemo_Create($Sender) { $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); $Sender->View = $this->GetView('demo.php'); $Sender->Render(); } public static function GetHash($S) { $Crc = sprintf('%u', crc32($S)); $Hash = base_convert($Crc, 10, 36); - $Hash = substr($Hash, -6); + $Hash = sprintf("%06s", substr($Hash, -6)); // zero-padding for string length < 6 return $Hash; } public static function MakeCssFile($CssPath, $CachedCssFile) { if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; $Filedata = file_get_contents($CssPath); // $CssPath need for #include directives, will use dirname($CssPath)/other.css $Data = DtCSS($CssPath, $Filedata); file_put_contents($CachedCssFile, $Data); } public function Base_BeforeAddCss_Handler($Sender) { if($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; $CssFiles =& $Sender->EventArguments['CssFiles']; foreach ($CssFiles as $Index => $CssInfo) { $CssFile = $CssInfo['FileName']; if (substr($CssFile, -7) != '.dt.css') continue; $AppFolder = $CssInfo['AppFolder']; if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; $CssPaths = array(); if(strpos($CssFile, '/') !== False) { $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); } else { if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; } $CssPath = False; foreach($CssPaths as $Glob) { $Paths = SafeGlob($Glob); if(count($Paths) > 0) { $CssPath = $Paths[0]; break; } } if($CssPath == False) continue; // not found $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css $Hash = self::GetHash($CssPath . filemtime($CssPath)); $CacheFileName = sprintf('%s-c-%s.css', $Basename, $Hash); $CachedCssFile = dirname($CssPath).DS.$CacheFileName; if (!file_exists($CachedCssFile)){ self::SaveLog($CachedCssFile); // for deleting self::MakeCssFile($CssPath, $CachedCssFile, True); } // ... and replace preprocessored dt.css file by css $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) } } public function Setup() { } }
unlight/DtCss
55316b8c0f45264b4e72014c2659e0acbfd25e6c
New Version. Delete all cached files when enabling/disabling plugin.
diff --git a/dtcss.plugin.php b/dtcss.plugin.php index 6a71e80..eed1d75 100644 --- a/dtcss.plugin.php +++ b/dtcss.plugin.php @@ -1,142 +1,164 @@ <?php if (!defined('APPLICATION')) die(); $PluginInfo['DtCss'] = array( 'Name' => 'DtCss', 'Description' => 'Adapts DtCSS to work with Garden.', - 'Version' => '1.1', - 'Date' => '22 Aug 2010', + 'Version' => '1.2', 'AuthorUrl' => 'http://code.google.com/p/dtcss/', 'RequiredApplications' => False, 'RequiredTheme' => False, 'RequiredPlugins' => False, 'RegisterPermissions' => False, 'SettingsPermission' => False ); /* TODO: - enable expressions - parse error handling -- empty cache while enabling/disabling plugin */ /* CHANGELOG -1.1 / 22 Aug 2010 - -1.0 / 21 Aug 2010 +04 Sep 2010 / 1.2 +- delete all cached files when enabling/disabling plugin +22 Aug 2010 / 1.1 +21 Aug 2010 / 1.0 - save cached css file to same directory where .dt.css file - -0.9 / 20 Aug 2010 +20 Aug 2010 / 0.9 - first release - */ class DtCssPlugin extends Gdn_Plugin { + public function SettingsController_AfterEnablePlugin_Handler() { + self::_EmptyCache(); + } + + public function SettingsController_AfterDisablePlugin_Handler() { + self::EmptyCache(); + } + + private static function _EmptyCache() { + $DirectoryAry = array(PATH_APPLICATIONS, PATH_PLUGINS, PATH_THEMES); + foreach($DirectoryAry as $DirectoryPath) { + $Directory = new RecursiveDirectoryIterator(PATH_APPLICATIONS); + foreach(new RecursiveIteratorIterator($Directory) as $File){ + $Basename = $File->GetBasename(); + $Extension = pathinfo($Basename, 4); + $Filename = pathinfo($Basename, 8); + if ($Extension != 'css' || empty($Filename[11]) || !preg_match('/^\w+\-c\-[a-z0-9]{6}$/', $Filename)) continue; + //d(@$Extension, @$Filename, $File, get_class_methods($File), $File->GetBasename()); + $CachedFile = $File->GetRealPath(); + unlink($CachedFile); + } + } + } + public function SettingsController_DashboardData_Handler() { self::_CleanUp(); } // remove cached files private static function _CleanUp(){ static $bWait; if($bWait === True) return; $bWait = True; $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) return; $UntouchedTime = time() - filemtime($LogFile); $DeleteTime = strtotime('+5 days', 0); if($UntouchedTime < $DeleteTime) return; $LoggedData = array_map('trim', file($LogFile)); for($Count = count($LoggedData), $i = 1; $i < $Count; $i++){ $File = $LoggedData[$i]; if(file_exists($File)) unlink($File); } unlink($LogFile); } private static function SaveLog($CachedCssFile) { static $LogFile; if (is_null($LogFile)){ $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) Gdn_FileSystem::SaveFile($LogFile, "<?php exit();\n"); } file_put_contents($LogFile, $CachedCssFile."\n", FILE_APPEND); } public function PluginController_DtCssDemo_Create($Sender) { $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); $Sender->View = $this->GetView('demo.php'); $Sender->Render(); } public static function GetHash($S) { $Crc = sprintf('%u', crc32($S)); $Hash = base_convert($Crc, 10, 36); $Hash = substr($Hash, -6); return $Hash; } public static function MakeCssFile($CssPath, $CachedCssFile) { if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; $Filedata = file_get_contents($CssPath); // $CssPath need for #include directives, will use dirname($CssPath)/other.css $Data = DtCSS($CssPath, $Filedata); file_put_contents($CachedCssFile, $Data); } public function Base_BeforeAddCss_Handler($Sender) { if($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; $CssFiles =& $Sender->EventArguments['CssFiles']; foreach ($CssFiles as $Index => $CssInfo) { $CssFile = $CssInfo['FileName']; if (substr($CssFile, -7) != '.dt.css') continue; $AppFolder = $CssInfo['AppFolder']; if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; $CssPaths = array(); if(strpos($CssFile, '/') !== False) { $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); } else { if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; } $CssPath = False; foreach($CssPaths as $Glob) { $Paths = SafeGlob($Glob); if(count($Paths) > 0) { $CssPath = $Paths[0]; break; } } if($CssPath == False) continue; // not found $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css $Hash = self::GetHash($CssPath . filemtime($CssPath)); $CacheFileName = sprintf('%s-c-%s.css', $Basename, $Hash); $CachedCssFile = dirname($CssPath).DS.$CacheFileName; if (!file_exists($CachedCssFile)){ self::SaveLog($CachedCssFile); // for deleting self::MakeCssFile($CssPath, $CachedCssFile, True); } // ... and replace preprocessored dt.css file by css $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) } } public function Setup() { } } +
unlight/DtCss
72951c14dadc602d5abf4da8cad4ff79ae351ba7
Auto cleanup cached files
diff --git a/dtcss.plugin.php b/dtcss.plugin.php index bbf3bfa..6a71e80 100644 --- a/dtcss.plugin.php +++ b/dtcss.plugin.php @@ -1,136 +1,142 @@ <?php if (!defined('APPLICATION')) die(); $PluginInfo['DtCss'] = array( 'Name' => 'DtCss', 'Description' => 'Adapts DtCSS to work with Garden.', 'Version' => '1.1', 'Date' => '22 Aug 2010', 'AuthorUrl' => 'http://code.google.com/p/dtcss/', 'RequiredApplications' => False, 'RequiredTheme' => False, 'RequiredPlugins' => False, 'RegisterPermissions' => False, 'SettingsPermission' => False ); /* TODO: - enable expressions - parse error handling - empty cache while enabling/disabling plugin */ /* CHANGELOG 1.1 / 22 Aug 2010 1.0 / 21 Aug 2010 - save cached css file to same directory where .dt.css file 0.9 / 20 Aug 2010 - first release */ class DtCssPlugin extends Gdn_Plugin { -/* public function SettingsController_DashboardData_Handler() { - static $bWait = False; - // remove cached files + public function SettingsController_DashboardData_Handler() { + self::_CleanUp(); + } + + // remove cached files + private static function _CleanUp(){ + static $bWait; + if($bWait === True) return; + $bWait = True; $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) return; $UntouchedTime = time() - filemtime($LogFile); $DeleteTime = strtotime('+5 days', 0); if($UntouchedTime < $DeleteTime) return; $LoggedData = array_map('trim', file($LogFile)); for($Count = count($LoggedData), $i = 1; $i < $Count; $i++){ $File = $LoggedData[$i]; if(file_exists($File)) unlink($File); } unlink($LogFile); - }*/ + } - public static function SaveLog($CachedCssFile) { + private static function SaveLog($CachedCssFile) { static $LogFile; if (is_null($LogFile)){ $LogFile = dirname(__FILE__).DS.'log.php'; if(!file_exists($LogFile)) Gdn_FileSystem::SaveFile($LogFile, "<?php exit();\n"); } file_put_contents($LogFile, $CachedCssFile."\n", FILE_APPEND); } public function PluginController_DtCssDemo_Create($Sender) { $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); $Sender->View = $this->GetView('demo.php'); $Sender->Render(); } public static function GetHash($S) { $Crc = sprintf('%u', crc32($S)); $Hash = base_convert($Crc, 10, 36); $Hash = substr($Hash, -6); return $Hash; } public static function MakeCssFile($CssPath, $CachedCssFile) { if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; $Filedata = file_get_contents($CssPath); // $CssPath need for #include directives, will use dirname($CssPath)/other.css $Data = DtCSS($CssPath, $Filedata); file_put_contents($CachedCssFile, $Data); } public function Base_BeforeAddCss_Handler($Sender) { if($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; $CssFiles =& $Sender->EventArguments['CssFiles']; foreach ($CssFiles as $Index => $CssInfo) { $CssFile = $CssInfo['FileName']; if (substr($CssFile, -7) != '.dt.css') continue; $AppFolder = $CssInfo['AppFolder']; if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; $CssPaths = array(); if(strpos($CssFile, '/') !== False) { $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); } else { if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; } $CssPath = False; foreach($CssPaths as $Glob) { $Paths = SafeGlob($Glob); if(count($Paths) > 0) { $CssPath = $Paths[0]; break; } } if($CssPath == False) continue; // not found $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css $Hash = self::GetHash($CssPath . filemtime($CssPath)); $CacheFileName = sprintf('%s-c-%s.css', $Basename, $Hash); $CachedCssFile = dirname($CssPath).DS.$CacheFileName; if (!file_exists($CachedCssFile)){ self::SaveLog($CachedCssFile); // for deleting self::MakeCssFile($CssPath, $CachedCssFile, True); } // ... and replace preprocessored dt.css file by css $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) } } public function Setup() { } }
unlight/DtCss
e7392db94817b60b533569d92524b55db4b74cc8
Log for future empty cache.
diff --git a/dtcss.plugin.php b/dtcss.plugin.php index 5079ac8..bbf3bfa 100644 --- a/dtcss.plugin.php +++ b/dtcss.plugin.php @@ -1,109 +1,136 @@ <?php if (!defined('APPLICATION')) die(); $PluginInfo['DtCss'] = array( 'Name' => 'DtCss', 'Description' => 'Adapts DtCSS to work with Garden.', 'Version' => '1.1', 'Date' => '22 Aug 2010', 'AuthorUrl' => 'http://code.google.com/p/dtcss/', 'RequiredApplications' => False, 'RequiredTheme' => False, 'RequiredPlugins' => False, 'RegisterPermissions' => False, 'SettingsPermission' => False ); /* TODO: - enable expressions - parse error handling - empty cache while enabling/disabling plugin */ /* CHANGELOG 1.1 / 22 Aug 2010 1.0 / 21 Aug 2010 - save cached css file to same directory where .dt.css file 0.9 / 20 Aug 2010 - first release */ class DtCssPlugin extends Gdn_Plugin { +/* public function SettingsController_DashboardData_Handler() { + static $bWait = False; + // remove cached files + $LogFile = dirname(__FILE__).DS.'log.php'; + if(!file_exists($LogFile)) return; + $UntouchedTime = time() - filemtime($LogFile); + $DeleteTime = strtotime('+5 days', 0); + if($UntouchedTime < $DeleteTime) return; + $LoggedData = array_map('trim', file($LogFile)); + for($Count = count($LoggedData), $i = 1; $i < $Count; $i++){ + $File = $LoggedData[$i]; + if(file_exists($File)) unlink($File); + } + unlink($LogFile); + }*/ + + public static function SaveLog($CachedCssFile) { + static $LogFile; + if (is_null($LogFile)){ + $LogFile = dirname(__FILE__).DS.'log.php'; + if(!file_exists($LogFile)) Gdn_FileSystem::SaveFile($LogFile, "<?php exit();\n"); + } + file_put_contents($LogFile, $CachedCssFile."\n", FILE_APPEND); + } + public function PluginController_DtCssDemo_Create($Sender) { $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); $Sender->View = $this->GetView('demo.php'); $Sender->Render(); } public static function GetHash($S) { $Crc = sprintf('%u', crc32($S)); $Hash = base_convert($Crc, 10, 36); $Hash = substr($Hash, -6); return $Hash; } public static function MakeCssFile($CssPath, $CachedCssFile) { if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; $Filedata = file_get_contents($CssPath); // $CssPath need for #include directives, will use dirname($CssPath)/other.css $Data = DtCSS($CssPath, $Filedata); file_put_contents($CachedCssFile, $Data); } public function Base_BeforeAddCss_Handler($Sender) { if($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; $CssFiles =& $Sender->EventArguments['CssFiles']; foreach ($CssFiles as $Index => $CssInfo) { $CssFile = $CssInfo['FileName']; if (substr($CssFile, -7) != '.dt.css') continue; $AppFolder = $CssInfo['AppFolder']; if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; $CssPaths = array(); if(strpos($CssFile, '/') !== False) { $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); } else { if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; } $CssPath = False; foreach($CssPaths as $Glob) { $Paths = SafeGlob($Glob); if(count($Paths) > 0) { $CssPath = $Paths[0]; break; } } if($CssPath == False) continue; // not found $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css $Hash = self::GetHash($CssPath . filemtime($CssPath)); $CacheFileName = sprintf('%s-c-%s.css', $Basename, $Hash); $CachedCssFile = dirname($CssPath).DS.$CacheFileName; - if (!file_exists($CachedCssFile)) self::MakeCssFile($CssPath, $CachedCssFile); + if (!file_exists($CachedCssFile)){ + self::SaveLog($CachedCssFile); // for deleting + self::MakeCssFile($CssPath, $CachedCssFile, True); + } // ... and replace preprocessored dt.css file by css $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) } } - public function Setup() { } -} \ No newline at end of file +}
unlight/DtCss
e55b7f0ea58095e43a15ea2b3cb6931c8a650ff5
Real first commit
diff --git a/DtCSS-R27f/DtCSS__colorlist.txt b/DtCSS-R27f/DtCSS__colorlist.txt new file mode 100644 index 0000000..f51e6ae --- /dev/null +++ b/DtCSS-R27f/DtCSS__colorlist.txt @@ -0,0 +1,142 @@ +# The data above is from http://en.wikipedia.org/wiki/X11_color_names +AliceBlue 240 248 255 +AntiqueWhite 250 235 215 +Aqua 0 255 255 +Aquamarine 127 255 212 +Azure 240 255 255 +Beige 245 245 220 +Bisque 255 228 196 +Black 0 0 0 +BlanchedAlmond 255 235 205 +Blue 0 0 255 +BlueViolet 138 43 226 +Brown 165 42 42 +BurgessWood 222 184 135 +CadetBlue 95 158 160 +Chartreuse 127 255 0 +Chocolate 210 105 30 +Coral 255 127 80 +CornflowerBlue 100 149 237 +Cornsilk 255 248 220 +Crimson 220 20 60 +Cyan 0 255 255 +DarkBlue 0 0 139 +DarkCyan 0 139 139 +DarkGoldenrod 184 134 11 +DarkGray 169 169 169 +DarkGreen 0 100 0 +DarkKhaki 189 183 107 +DarkMagenta 139 0 139 +DarkOliveGreen 85 107 47 +DarkOrange 255 140 0 +DarkOrchid 153 50 204 +DarkRed 139 0 0 +DarkSalmon 233 150 122 +DarkSeaGreen 143 188 143 +DarkSlateBlue 72 61 139 +DarkSlateGray 47 79 79 +DarkTurquoise 0 206 209 +DarkViolet 148 0 211 +DeepPink 255 20 147 +DeepSkyBlue 0 191 255 +DimGray 105 105 105 +DodgerBlue 30 144 255 +FireBrick 178 34 34 +FloralWhite 255 250 240 +ForestGreen 34 139 34 +Fuchsia 255 0 255 +Gainsboro 220 220 220 +GhostWhite 248 248 255 +Gold 255 215 0 +Goldenrod 218 165 32 +GreenYellow 173 255 47 +Honeydew 240 255 240 +HotPink 255 105 180 +IndianRed 205 92 92 +Indigo 75 0 130 +Ivory 255 255 240 +Khaki 240 230 140 +Lavender 230 230 250 +LavenderBlush 255 240 245 +LawnGreen 124 252 0 +LemonChiffon 255 250 205 +LightBlue 173 216 230 +LightCoral 240 128 128 +LightCyan 224 255 255 +LightGoldenrodYellow 250 250 210 +LightGreen 144 238 144 +LightGrey 211 211 211 +LightPink 255 182 193 +LightSalmon 255 160 122 +LightSeaGreen 32 178 170 +LightSkyBlue 135 206 250 +LightSlateGray 119 136 153 +LightSteelBlue 176 196 222 +LightYellow 255 255 224 +Lime 0 255 0 +LimeGreen 50 205 50 +Linen 250 240 230 +Magenta 255 0 255 +MediumAquamarine 102 205 170 +MediumBlue 0 0 205 +MediumOrchid 186 85 211 +MediumPurple 147 112 219 +MediumSeaGreen 60 179 113 +MediumSlateBlue 123 104 238 +MediumSpringGreen 0 250 154 +MediumTurquoise 72 209 204 +MediumVioletRed 199 21 133 +MidnightBlue 25 25 112 +MintCream 245 255 250 +MistyRose 255 228 225 +Moccasin 255 228 181 +NavajoWhite 255 222 173 +Navy 0 0 128 +OldLace 253 245 230 +Olive 128 128 0 +OliveDrab 107 142 35 +Orange 255 165 0 +OrangeRed 255 69 0 +Orchid 218 112 214 +PaleGoldenrod 238 232 170 +PaleGreen 152 251 152 +PaleTurquoise 175 238 238 +PaleVioletRed 219 112 147 +PapayaWhip 255 239 213 +PeachPuff 255 218 185 +Peru 205 133 63 +Pink 255 192 203 +Plum 221 160 221 +PowderBlue 176 224 230 +PurwaBlue 155 225 255 +Red 255 0 0 +RosyBrown 188 143 143 +RoyalBlue 65 105 225 +SaddleBrown 139 69 19 +Salmon 250 128 114 +SandyBrown 244 164 96 +SeaGreen 46 139 87 +Seashell 255 245 238 +Sienna 160 82 45 +Silver 192 192 192 +SkyBlue 135 206 235 +SlateBlue 106 90 205 +SlateGray 112 128 144 +Snow 255 250 250 +SpringGreen 0 255 127 +SteelBlue 70 130 180 +Tan 210 180 140 +Teal 0 128 128 +Thistle 216 191 216 +Tomato 255 99 71 +Turquoise 64 224 208 +Violet 238 130 238 +Wheat 245 222 179 +White 255 255 255 +WhiteSmoke 245 245 245 +Yellow 255 255 0 +YellowGreen 154 205 50 +Gray 128 128 128 +Green 0 128 0 +Maroon 128 0 0 +Purple 128 0 128 diff --git a/DtCSS-R27f/libdtcss.php b/DtCSS-R27f/libdtcss.php new file mode 100644 index 0000000..ace85ed --- /dev/null +++ b/DtCSS-R27f/libdtcss.php @@ -0,0 +1,782 @@ +<?php + +/* + DtCSS - the DtTvB's CSS Macro + Copyright (C) 2008 Thai Pangsakulyanont + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * DtCSS - the DtTvB's CSS Macro + * This is a library file. + * This file is need by the main file. + * That means, without me, + * the main file won't work. + * And the main file won't work without me. + * You know. SVN version. + */ + +/* This is a comment. */ +/* What are the comments doing here? */ +/* Well... I need to document the code so that when I come back to read the code, + I don't forget everything. */ +/* I don't use classes so much. No classes are created in this file. */ + +/* This is a regular expression to tokenize CSS syntaxes. */ +define ('DTCSS_MATCH', '~ + "(?:\\\\.|[^"])*" # double quotes + | \'(?:\\\\.|[^\'])*\' # single quotes + | /\\*([\\s\\S]*?)\\*/ # comments + | <\\#(?:[\s\S]+?)\\#> + | (?:mix|shade|lighter|darker|variant)\\s* + \\( + | \\([^\\)]*\\) # match parens + | //.* + | \\w+ # words + | [^{},;:"\'\\[\\]\\s\\(\\)/]+ # string + | [\\s\\S] + ~x'); + +include dirname(__FILE__) . '/libdtexpression.php'; + +/* This global variable holds the list of available HTML colors */ +$DtCSS__colors = array(); + +/* Call this function to use DtCSS + Pass the following argument: + + file --> the file name of the css file you want to preprocess + | if you don't want one just use the __FILE__ magic constant. + + css --> the css source code you want to preprocess + + macros --> an associative array of predefined macros +*/ +function DtCSS($file, $css, $macros = array()) { + + /* First process the macros */ + $css = DtCSS__preprocess($file, $css, $macros); + + /* Tokenize the processed CSS */ + if (!preg_match_all(DTCSS_MATCH, $css, $tokens, PREG_PATTERN_ORDER)) { + return ''; + } + + /* Tokens -> Structures */ + $next = DtCSS__firstpass($tokens[0]); + + /* Structures -> Rules */ + $list = array(); + DtCSS__secondpass ($next, '', $list, $macros); + + /* Ok now we have the rules. + Let's output it nicely. */ + $copies = array(); + $out = ''; + + /* For each rules... Why should I type this? */ + foreach ($list as $v) { + + /* What is this? */ + if (empty($v)) continue; + $out .= "\n"; + if (count($v) > 0) { + + /* Get the selector. See if it is a template. */ + $selector = trim(substr($v[0], 0, -1)); + $current = ''; + $is_copy = 0; + $cname = ''; + + /* Now we have the templates! */ + if (substr($selector, 0, 1) == '%') { + $cname = trim(substr($selector, 1)); + $current = '/* % ' . $cname . ' */'; + $is_copy = 1; + } + + /* Now go through each declarations. */ + foreach ($v as $w) { + + $c = trim($w); + + /* If it is not an opening or closing brace then indent it a bit. */ + if (substr($c, -1, 1) != '{' && $c != '}') { + $current .= "\n"; + $current .= ' '; + + /* I don't want braces in templates. */ + } else if ($is_copy) { + continue; + + /* But we are not in a template. */ + } else { + $current .= "\n"; + } + + /* We are using a template. */ + if (preg_match('~^use\\s*:\\s*(.*);$~', trim($w), $m)) { + $cpname = $m[1]; + if (isset($copies[$cpname])) { + $current .= trim($copies[$cpname]); + } else { + $current .= '/* ' . $m[0] . ' -- not found */'; + } + + /* Wait, we are not. */ + } else { + + /* Let's see if we can make more rules out of it. */ + if (preg_match('~^([a-z0-9\\-\\s,]+):([\\s\\S]+;)~i', $c, $m)) { + + $properties = DtCSS__splitproperties($m[1]); + $shall_pad = 0; + foreach ($properties as $vv) { + $current .= ($shall_pad ? "\n " : '') . $vv . ':' . $m[2]; + $shall_pad = 1; + } + + } else { + $current .= $c; + } + + } + + } + + /* Output them or add to template. */ + if ($is_copy) { + $copies[$cname] = $current . "\n /* $cname % */"; + } else { + $out .= $current; + } + + } + } + + return $out; + +} + +/* Make writing properties easier */ +function DtCSS__splitproperties($x) { + + /* Split CSS */ + + /* First pass split with comma. */ + $o = array(); + $t = explode(',', $x); + foreach ($t as $v) { + + /* top left right bottom can be grouped together. */ + $v = trim($v); + if (preg_match('~(?:(?:(?:^|\\-)(?:left|top|right|bottom)){2,4})~i', $v, $m, PREG_OFFSET_CAPTURE)) { + $string = $m[0][0]; + $offset = $m[0][1]; + if (substr($string, 0, 1) == '-') { + $string = substr($string, 1); + $offset += 1; + } + $splitter = explode('-', $string); + foreach ($splitter as $w) { + $o[] = substr($v, 0, $offset) . $w . substr($v, $offset + strlen($string)); + } + } else { + $o[] = $v; + } + + } + + return $o; + +} + +/* This functions loads the color list from */ +function DtCSS__loadcolors() { + + global $DtCSS__colors; + $fp = fopen(dirname(__FILE__) . '/DtCSS__colorlist.txt', 'r'); + while (!feof($fp)) { + $l = trim(fgets($fp)); + if (substr($l, 0, 1) == '#' || trim($l) == '') { + continue; + } + $d = preg_split('~\\s+~', $l); + $DtCSS__colors[strtolower($d[0])] = array($d[1] / 255, $d[2] / 255, $d[3] / 255); + } + +} + +/* Ok. Let's do it now. I made this function because + I don't want to screw any other global variables.. */ +DtCSS__loadcolors (); + +/* Some color related function. + This function converts the color in RGB and returns the same color in HLS. + This function was taken from GTK+'s gtkstyle.c + Pass these: + - R [0.0 - 1.0] + - G [0.0 - 1.0] + - B [0.0 - 1.0] + Outputs array: + - H [0.0 - 359.99999999999999999999999999999999999999999999999999999....] + - L [0.0 - 1.0] + - S [0.0 - 1.0] + */ +function DtCSS__rgb_to_hls($r, $g, $b) { + + $max = max($r, $g, $b); + $min = min($r, $g, $b); + + $l = ($max + $min) / 2; + $s = $h = 0; + + if ($max != $min) { + if ($l < 0.5) + $s = ($max - $min) / ($max + $min); + else + $s = ($max - $min) / (2 - $max - $min); + $d = $max - $min; + if ($r == $max) + $h = ($g - $b) / $d; + else if ($g == $max) + $h = 2 + ($b - $r) / $d; + else if ($b == $max) + $h = 4 + ($r - $g) / $d; + $h *= 60; + if ($h < 0) $h += 360; + } + + return array($h, $l, $s); + +} + +/* Some color related function. + This function converts the color in RGB and returns the same color in HLS. + This function was taken from GTK+'s gtkstyle.c + Pass these: + - H [0.0 - 359.99999999999999999999999999999999999999999999999999999....] + - L [0.0 - 1.0] + - S [0.0 - 1.0] + Outputs array: + - R [0.0 - 1.0] + - G [0.0 - 1.0] + - B [0.0 - 1.0] + */ +function DtCSS__hls_to_rgb($h, $l, $s) { + if ($l < 0.5) + $n = $l * (1 + $s); + else + $n = $l + $s - $l * $s; + $m = 2 * $l - $n; + if ($s == 0) { + return array($l, $l, $l); + } + $hue = $h + 120; + while ($hue > 360) $hue -= 360; + while ($hue < 0) $hue += 360; + if ($hue < 60) + $r = $m + ($n - $m) * $hue / 60; + else if ($hue < 180) + $r = $n; + else if ($hue < 240) + $r = $m + ($n - $m) * (240 - $hue) / 60; + else + $r = $m; + $hue = $h; + while ($hue > 360) $hue -= 360; + while ($hue < 0) $hue += 360; + if ($hue < 60) + $g = $m + ($n - $m) * $hue / 60; + else if ($hue < 180) + $g = $n; + else if ($hue < 240) + $g = $m + ($n - $m) * (240 - $hue) / 60; + else + $g = $m; + $hue = $h - 120; + while ($hue > 360) $hue -= 360; + while ($hue < 0) $hue += 360; + if ($hue < 60) + $b = $m + ($n - $m) * $hue / 60; + else if ($hue < 180) + $b = $n; + else if ($hue < 240) + $b = $m + ($n - $m) * (240 - $hue) / 60; + else + $b = $m; + return array($r, $g, $b); +} + +/* This function replaces the macro. Text in strings will not be processed. */ +function DtCSS__replacemacros($v, &$macro) { + if (preg_match_all(DTCSS_MATCH, $v, $tokens, PREG_PATTERN_ORDER)) { + $n = ''; + foreach ($tokens[0] as $w) { + if (isset($macro[$w])) { + $n .= $macro[$w]; + } else { + $n .= $w; + } + } + $v = $n; + } + return $v; +} + +/* The preprocess function. + Takes the arguments like the same as DtCSS. */ +function DtCSS__preprocess($file, $text, &$macro) { + + /* Split it into lines first. */ + $x = explode("\n", $text); + $o = array(); + $level = 0; + + foreach ($x as $v) { + + /* ifdef, ifndef, and endif + supports nested */ + if (strtolower(trim($v)) == '#endif') { + if ($level > 0) { + $level --; + } + continue; + } else if (strtolower(trim($v)) == '#else') { + if ($level == 1) { + $level --; + } else if ($level <= 0) { + $level ++; + } + continue; + } else if (preg_match('~^[#]if(n?)expr\\s+(.*)$~is', trim($v), $m)) { + if ($level > 0) { + $level ++; + } else { + $isset = DtCSS__DtExpression($m[2], $macro); + $negate = strtolower($m[1]) == 'n'; + if ($negate) $isset = !$isset; + if (!$isset) { + $level ++; + } + } + continue; + } else if (preg_match('~^[#]if(n?)def\\s+(\\w+)$~is', trim($v), $m)) { + if ($level > 0) { + $level ++; + } else { + $isset = isset($macro[$m[2]]); + $negate = strtolower($m[1]) == 'n'; + if ($negate) $isset = !$isset; + if (!$isset) { + $level ++; + } + } + continue; + } + if ($level > 0) continue; + + /* Define a macro. Allows an earlier defined macros to be used in the content. + The name won't be processed. */ + if (preg_match('~^[#]define\\s+(\\w+)\\s+(.*)$~is', ltrim($v), $m)) { + $macro[$m[1]] = DtCSS__replacemacros($m[2], $macro); + + /* Include that file. But before that the file must be processed first. */ + } else if (preg_match('~^[#]include\\s*"([^"]+)"$~is', trim($v), $m)) { + $fn = dirname($file) . '/' . $m[1]; + if (file_exists($fn)) { + /* Fcking recursive call. */ + /* I think this can lead to endless loop. */ + $o[] = DtCSS__preprocess($fn, file_get_contents($fn), $macro); + } else { + $o[] = '/* Warning: #include "' . $m[1] . '" -- not found */'; + } + + /* Nothing. */ + } else { + $o[] = DtCSS__replacemacros($v, $macro); + } + } + return implode("\n", $o); +} + +/* Tokenize and split the selector using ',' */ +function DtCSS__splitselector($sel) { + + /* Ok? */ + if (!preg_match_all(DTCSS_MATCH, $sel, $tokens, PREG_PATTERN_ORDER)) { + return array(); + } + + /* Split it!!!! */ + $o = array(); + $b = ''; + foreach ($tokens[0] as $v) { + if ($v == ',') { + $o[] = trim($b); + $b = ''; + } else { + $b .= $v; + } + } + + /* Any craps left? */ + if (trim($b) != '') + $o[] = trim($b); + + /* Work done. */ + return $o; + +} + +/* Combines a single selector "a" with "b" */ +function DtCSS__combinesingle($a, $b) { + + // fixed by S + if (strtolower(substr($b, 0, 4)) == 'self') return $a . substr($b, 4); + elseif (strtolower(substr($b, 0, 8)) == '__self__') return $a . substr($b, 8); + + if (trim($a) == '') return $b; + return $a . ' ' . $b; + +} + +/* Combines selectors in "a" with "b" + Multiple selectors maybe. */ +function DtCSS__combineselector($a, $b) { + if (trim($a) == '') return DtCSS__combinesingle('', $b); + $ta = DtCSS__splitselector($a); + $tb = DtCSS__splitselector($b); + $tc = array(); + $la = count($ta); + $lb = count($tb); + for ($i = 0; $i < $la; $i ++) { + for ($j = 0; $j < $lb; $j ++) { + $tc[] = DtCSS__combinesingle($ta[$i], $tb[$j]); + } + } + return implode(', ', $tc); +} + +/* Parse the color and output as an RGB array. */ +function DtCSS__parsecolor($c) { + $c = preg_replace('~\\s~', '', strtolower(trim($c))); + if (preg_match('~^#([a-f0-9])([a-f0-9])([a-f0-9])$~', $c, $m)) { + return array( + (hexdec($m[1]) * 17) / 255, + (hexdec($m[2]) * 17) / 255, + (hexdec($m[3]) * 17) / 255 + ); + } + if (preg_match('~^#([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])$~', $c, $m)) { + return array( + (hexdec($m[1])) / 255, + (hexdec($m[2])) / 255, + (hexdec($m[3])) / 255 + ); + } + if (preg_match('~rgb\\((\\d+),(\\d+),(\\d+)\\)~', $c, $m)) { + return array( + ($m[1] / 255), + ($m[2] / 255), + ($m[3] / 255) + ); + } + if (preg_match('~rgb\\((\\d+)[%],(\\d+)[%],(\\d+)[%]\\)~', $c, $m)) { + return array( + ($m[1] / 100), + ($m[2] / 100), + ($m[3] / 100) + ); + } + global $DtCSS__colors; + if (isset($DtCSS__colors[$c])) + return $DtCSS__colors[$c]; + return array(0, 0, 0); +} + +/* The shade function from GTK+ */ +function DtCSS__shade($factor, $color) { + $hls = DtCSS__rgb_to_hls($color[0], $color[1], $color[2]); + $hls[1] = min(1, max(0, $hls[1] * $factor)); + $hls[2] = min(1, max(0, $hls[2] * $factor)); + return DtCSS__hls_to_rgb($hls[0], $hls[1], $hls[2]); +} + +/* Into 0 or 1 + Factor = 0 returns old. + Factor < 0 goes towards 0. + Factor > 0 goes towards 1. */ +function DtCSS__into($factor, $old) { + if ($factor > 1) $factor = 1; + if ($factor < -1) $factor = -1; + if ($factor > 0) { + return $old + ((1 - $old) * $factor); + } + if ($factor < 0) { + return $old + ((0 - $old) * abs($factor)); + } + return $old; +} + +/* Expression parsing. Returns color in RGB. + Fun time. */ +function DtCSS__expression($text) { + + /* This is an expression! Tokenize it. */ + if (preg_match('~^(mix|shade|lighter|darker|variant)\\(([\\s\\S]*)\\)$~', $text, $m)) { + if (!preg_match_all(DTCSS_MATCH, $m[2], $tokens, PREG_PATTERN_ORDER)) { + return array(0, 0, 0); + } + + /* Find out the + (i) Function name + (ii) List of arguments. Maybe nested. */ + $buffer = ''; + $list = array(); + $level = 0; + $buf = ''; + foreach ($tokens[0] as $v) { + if (preg_match('~^(lighter|darker|shade|mix|variant)\\s*\\($~s', $v)) { + if ($level == 0) { + $buf = $v; + } else { + $buf .= $v; + } + $level ++; + continue; + } else if ($v == ')') { + $buf .= $v; + $level --; + if ($level == 0) { + $buffer .= $buf; + $buf = ''; + } + continue; + } else if ($level > 0) { + $buf .= $v; + continue; + } + if ($v == ',') { + $list[] = $buffer; + $buffer = ''; + } else { + $buffer .= $v; + } + } + if ($buffer != '') $list[] = $buffer; + + /* Now for each function... */ + if ($m[1] == 'mix') { + $color1 = DtCSS__expression($list[1]); + $color2 = DtCSS__expression($list[2]); + return array( + $color2[0] + (($color1[0] - $color2[0]) * $list[0]), + $color2[1] + (($color1[1] - $color2[1]) * $list[0]), + $color2[2] + (($color1[2] - $color2[2]) * $list[0]) + ); + } + if ($m[1] == 'lighter') { + return DtCSS__shade(1.3, DtCSS__expression($list[0])); + } + if ($m[1] == 'darker') { + return DtCSS__shade(0.7, DtCSS__expression($list[0])); + } + if ($m[1] == 'shade') { + return DtCSS__shade($list[0], DtCSS__expression($list[1])); + } + if ($m[1] == 'variant') { + $color = DtCSS__expression($list[3]); + $hls = DtCSS__rgb_to_hls($color[0], $color[1], $color[2]); + $my_h = ($list[0]) - 0; + $my_s = ($list[1]) / 100; + $my_l = ($list[2]) / 100; + $hls[0] += $my_h; + while ($hls[0] > 360) $hls[0] -= 360; + while ($hls[0] < 0) $hls[0] += 360; + $hls[1] = DtCSS__into($my_l, $hls[1]); + $hls[2] = DtCSS__into($my_s, $hls[2]); + return DtCSS__hls_to_rgb($hls[0], $hls[1], $hls[2]); + } + } + return DtCSS__parsecolor($text); +} + +/* Changes the value from 0.0 - 1.0 to 00 - ff */ +function DtCSS__hexcolor($x) { + $v = dechex(floor($x * 255)); + if (strlen($v) < 2) return '0' . $v; + return $v; +} + +/* Make HTML color code from array of 0.0 - 1.0. */ +function DtCSS__makecolor($a) { + return '#' . DtCSS__hexcolor($a[0]) . DtCSS__hexcolor($a[1]) . DtCSS__hexcolor($a[2]); +} + +/* This thing evaluates an expression and returns the result. + It also process macros. Really powerful! + It uses libdtexpression.php that comes with this package. */ +function DtCSS__DtExpression($expr, &$macros) { + $d = ''; + $dtexsub = $expr; + if (preg_match_all(DTEXPR_MATCH, $dtexsub, $dtextokens, PREG_SET_ORDER)) { + $dtexcode = ''; + foreach ($dtextokens as $dtexv) { + if (isset($macros[$dtexv[0]])) { + $mct = $macros[$dtexv[0]]; + if (!is_numeric($mct)) { + $mct = DtExpression__quotestring($mct); + } + $dtexcode .= $mct; + } else { + $dtexcode .= $dtexv[0]; + } + $dtexcode .= ' '; + } + //$d = $dtexcode; + $d = DtExpression($dtexcode); + } + return $d; + +} + +/* This function parses the nested CSS structures and explode it. */ +function DtCSS__secondpass($tokens, $old_selector, &$output, &$macros) { + $my_sel = array(); + $output[] = &$my_sel; + $selector = ''; + $level = 0; + $buffer = ''; + + /* We are not in the top. We have a rule. Add it. */ + if ($old_selector != '') + $my_sel[] = $old_selector . ' {'; + + /* Go through the tokens */ + foreach ($tokens as $v) { + if (is_array($v)) { + + /* If it's an array it means it's a structure. + Combine the selectors and put in the rules. */ + $sel = trim($selector); + $sel = DtCSS__combineselector($old_selector, $sel); + DtCSS__secondpass ($v, $sel, $output, $macros); + $selector = ''; + + } else if (substr($v, 0, 2) == '//') { + + /* Line comments. Change them to multiline comments. */ + $my_sel[] = '/* ' . trim(substr(($v), 2)) . ' */'; + + } else if (substr($v, 0, 2) == '/*') { + + /* Comments */ + $my_sel[] = $v; + + } else if (substr($v, 0, 2) == '<#') { + + $selector .= DtCSS__DtExpression(substr(substr($v, 2), 0, -2), $macros); + + } else if ($v == ';') { + + /* We have it. */ + $my_sel[] = $selector . ';'; + $selector = ''; + + } else if (preg_match('~^(lighter|darker|shade|mix|variant)\\s*\\($~s', $v)) { + + /* We found the function. Find its closing. */ + if ($level > 0) { + $buffer .= $v; + $level ++; + } else { + $buffer = $v; + $level ++; + } + + } else if ($level > 0 && $v == ')') { + + /* Almost */ + $level --; + $buffer .= $v; + if ($level == 0) { + /* I found that stupid closing brace! + It's perfectly nested! + So now I can parse the expression!!! HAHA! */ + $selector .= DtCSS__makecolor(DtCSS__expression(preg_replace('~\\s~', '', $buffer))); + } + + } else { + + /* Normal syntax */ + if ($level > 0) { + $buffer .= $v; + } else { + $selector .= $v; + } + + } + } + + /* Need more? */ + if (trim($selector) != '') { + $my_sel[] = trim($selector) . ';'; + } + + /* A root level does not need a closing brace. */ + if ($old_selector != '') + $my_sel[] = '}'; + +} + +/* Parses nested structures into ... + yeah + something like nested array. + + Right it's nested array. */ +function DtCSS__firstpass(&$tokens) { + + $cnt = count($tokens); + $buffer = array(); + $level = 0; + for ($i = 0; $i < $cnt; $i ++) { + $c = $tokens[$i]; + if ($c == '{') { + if ($level > 0) { + $level ++; + $add[] = $c; + } else { + $level ++; + $add = array(); + } + } else if ($c == '}' && $level > 0) { + $level --; + if ($level > 0) { + $add[] = $c; + } else { + $buffer[] = DtCSS__firstpass($add); + } + } else { + if ($level > 0) { + $add[] = $c; + } else { + $buffer[] = $c; + } + } + } + + return $buffer; + +} + +?> diff --git a/DtCSS-R27f/libdtexpression.php b/DtCSS-R27f/libdtexpression.php new file mode 100644 index 0000000..e0123dc --- /dev/null +++ b/DtCSS-R27f/libdtexpression.php @@ -0,0 +1,306 @@ +<?php + +/* + DtExpression - the DtTvB's Expression Evaluator + Copyright (C) 2008 Thai Pangsakulyanont + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/* The code is undocumented. + Have fun! */ + +define ('DTEXPR_MATCH', '~ + ("(?:\\\\.|[^"])*" + | \'(?:\\\\.|[^\'])*\') # 1 string + | (\\-?(?:[0-9]+)(?:\\.(?:[0-9]+))? + | (?:0x[0-9a-fA-F]+)) # 2 number + | (\\w+) # 3 words + | ([\\-' . preg_quote('()+*/%>,<?:', '~') . '] + |>>|<<|>=|<=|==|!=|&&|\\|\\||!|\\.) # 4 operators + ~sxi'); + +define ('DTEXPR_UNKNOWN', 0); +define ('DTEXPR_STRING', 1); +define ('DTEXPR_NUMBER', 2); +define ('DTEXPR_WORD', 3); +define ('DTEXPR_OPERATOR', 4); +define ('DTEXPR_STRUCT', 5); + +$DtExpr__FunctionMap = array( + 'abs' => 'abs', + 'acos' => 'acos', + 'acosh' => 'acosh', + 'asin' => 'asin', + 'asinh' => 'asinh', + 'atan2' => 'atan2', + 'atan' => 'atan', + 'atanh' => 'atanh', + 'base_convert' => 'base_convert', + 'bindec' => 'bindec', + 'ceil' => 'ceil', + 'cos' => 'cos', + 'cosh' => 'cosh', + 'decbin' => 'decbin', + 'dechex' => 'dechex', + 'decoct' => 'decoct', + 'deg2rad' => 'deg2rad', + 'exp' => 'exp', + 'expm1' => 'expm1', + 'floor' => 'floor', + 'fmod' => 'fmod', + 'getrandmax' => 'getrandmax', + 'hexdec' => 'hexdec', + 'hypot' => 'hypot', + 'is_finite' => 'is_finite', + 'is_infinite' => 'is_infinite', + 'is_nan' => 'is_nan', + 'lcg_value' => 'lcg_value', + 'log10' => 'log10', + 'log1p' => 'log1p', + 'log' => 'log', + 'max' => 'max', + 'min' => 'min', + 'mt_getrandmax' => 'mt_getrandmax', + 'mt_rand' => 'mt_rand', + 'mt_srand' => 'mt_srand', + 'octdec' => 'octdec', + 'pi' => 'pi', + 'pow' => 'pow', + 'rad2deg' => 'rad2deg', + 'rand' => 'rand', + 'round' => 'round', + 'sin' => 'sin', + 'sinh' => 'sinh', + 'sqrt' => 'sqrt', + 'srand' => 'srand', + 'tan' => 'tan', + 'tanh' => 'tanh', + 'crc32' => 'crc32', + 'chr' => 'chr', + 'levenshtein' => 'levenshtein', + 'ltrim' => 'ltrim', + 'md5' => 'md5', + 'metaphone' => 'metaphone', + 'money_format' => 'money_format', + 'nl2br' => 'nl2br', + 'number_format' => 'number_format', + 'ord' => 'ord', + 'printf' => 'sprintf', + 'sprintf' => 'sprintf', + 'rtrim' => 'rtrim', + 'sha1' => 'sha1', + 'similar_text' => 'similar_text', + 'soundex' => 'soundex', + 'str_pad' => 'str_pad', + 'pad' => 'str_pad', + 'str_repeat' => 'str_repeat', + 'repeat' => 'str_repeat', + 'str_replace' => 'str_replace', + 'replace' => 'str_replace', + 'str_rot13' => 'str_rot13', + 'rot13' => 'str_rot13', + 'str_shuffle' => 'str_shuffle', + 'shuffle' => 'str_shuffle', + 'strcasecmp' => 'strcasecmp', + 'casecmp' => 'strcasecmp', + 'strchr' => 'strchr', + 'strcmp' => 'strcmp', + 'cmp' => 'strcmp', + 'strip_tags' => 'strip_tags', + 'stristr' => 'stristr', + 'strnatcasecmp' => 'strnatcasecmp', + 'natcasecmp' => 'strnatcasecmp', + 'strnatcmp' => 'strnatcmp', + 'natcmp' => 'strnatcmp', + 'strrev' => 'strrev', + 'rev' => 'strrev', + 'reverse' => 'strrev', + 'strrchr' => 'strrchr', + 'strstr' => 'strstr', + 'substr_replace' => 'substr_replace', + 'substr' => 'substr', + 'mid' => 'substr', + 'trim' => 'trim', + 'ucfirst' => 'ucfirst', + 'ucwords' => 'ucwords', + 'date' => 'date', + 'gmdate' => 'gmdate', + 'mktime' => 'mktime', + 'gmmktime' => 'gmmktime', + 'strftime' => 'strftime', + 'gmstrftime' => 'gmstrftime', + 'time' => 'time', + 'strtotime' => 'strtotime', + 'strtolower' => 'strtolower', + 'tolower' => 'strtolower', + 'lower' => 'strtolower', + 'strtoupper' => 'strtoupper', + 'toupper' => 'strtoupper', + 'upper' => 'strtoupper', + 'str' => 'strval', + 'strval' => 'strval', + 'int' => 'intval', + 'intval' => 'intval', + 'float' => 'floatval', + 'floatval' => 'floatval', + 'escape' => 'DtExpression__quotestring', +); + +function DtExpression($data) { + $tokens = DtExpression__Tokenize($data); + $struct = DtExpression__MakeStruct($tokens); + $code = DtExpression__GenerateCode($struct); + return @eval('return ' . $code . ';'); +} + +function DtExpression__quotestring($text) { + return '\'' . strtr($text, array( + '\\' => '\\\\', + '\'' => '\\\'' + )) . '\''; +} + +function DtExpression__GenerateCode($struct) { + $final = array(); + $last = false; + $inlist = false; + $afterword = false; + foreach ($struct as $v) { + $current = $v; + if ($inlist == true) { + if ($current[0] == DTEXPR_OPERATOR && $current[1] == ',') { + $final[] = $current; + $last = $v; + continue; + } else if ($last[0] == DTEXPR_OPERATOR && $last[1] == ',') { + $final[] = $current; + $last = $v; + continue; + } else { + $final[] = ')'; + $afterword = false; + $inlist = false; + } + } + if ($v[0] == DTEXPR_STRUCT) { + if ($last[0] == DTEXPR_WORD) { + array_pop ($v[1]); + array_shift ($v[1]); + } + $current[1] = DtExpression__GenerateCode($v[1]); + } + if ($v[0] == DTEXPR_WORD) { + if (isset($GLOBALS['DtExpr__FunctionMap'][$current[1]])) { + $current[1] = $GLOBALS['DtExpr__FunctionMap'][$current[1]]; + $afterword = true; + } else { + continue; + } + } + if ($last !== false && $current[0] != DTEXPR_OPERATOR && $last[0] != DTEXPR_OPERATOR) { + if ($last[0] == DTEXPR_WORD) { + $final[] = '('; + $final[] = $current; + $inlist = true; + } else if ($current[0] == DTEXPR_STRING || $last[0] == DTEXPR_STRING) { + $final[] .= '.'; + $final[] = $current; + } else { + $final[] .= '*'; + $final[] = $current; + } + } else { + $final[] = $current; + } + $last = $v; + } + if ($inlist) { + $final[] = ')'; + $afterword = false; + } + if ($afterword) { + $final[] = '()'; + } + $out = array(); + foreach ($final as $v) { + if (is_array($v)) { + $out[] = $v[1]; + } else { + $out[] = $v; + } + } + return implode(' ', $out); +} + +function DtExpression__MakeStruct($tokens) { + $final = array(); + $buffer = array(); + $level = 0; + foreach ($tokens as $k => $v) { + if ($v[0] == DTEXPR_OPERATOR && $v[1] == '(' && $k != 0) { + if ($level == 0) { + $buffer = array(DTEXPR_STRUCT, array()); + } + $level ++; + } + if ($level > 0) { + $buffer[1][] = $v; + } else { + $final[] = $v; + } + if ($v[0] == DTEXPR_OPERATOR && $v[1] == ')' && $level > 0) { + $level --; + if ($level == 0) { + $buffer[1] = DtExpression__MakeStruct($buffer[1]); + $final[] = $buffer; + } + } + } + return $final; +} + +function DtExpression__Tokenize($data) { + preg_match_all (DTEXPR_MATCH, $data, $tokens, PREG_SET_ORDER); + $final = array(); + foreach ($tokens as $match) { + $raw = $match[0]; + $type = DTEXPR_UNKNOWN; + if (isset($match[1]) && $match[1] !== '') $type = DTEXPR_STRING; + if (isset($match[2]) && $match[2] !== '') $type = DTEXPR_NUMBER; + if (isset($match[3]) && $match[3] !== '') $type = DTEXPR_WORD; + if (isset($match[4]) && $match[4] !== '') $type = DTEXPR_OPERATOR; + if ($type == DTEXPR_STRING && $raw[0] == '"') { + $new = ''; + $len = strlen($raw); + for ($i = 0; $i <= $len; $i ++) { + if ($raw[$i] == '\\') { + $new .= $raw[$i] . $raw[$i + 1]; + $i ++; + } else { + if ($raw[$i] == '$') { + $new .= '\\$'; + } else { + $new .= $raw[$i]; + } + } + } + $raw = $new; + } + $final[] = array($type, $raw); + } + return $final; +} + +?> diff --git a/DtCSS-R27f/rewrite_css.php b/DtCSS-R27f/rewrite_css.php new file mode 100644 index 0000000..f28d758 --- /dev/null +++ b/DtCSS-R27f/rewrite_css.php @@ -0,0 +1,67 @@ +<?php + +/* + DtCSS - the DtTvB's CSS Macro + Copyright (C) 2008 Thai Pangsakulyanont + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +header ('Content-Type: text/css'); +include 'libdtcss.php'; + +if (!isset($_GET['f'])) { + die ('/* No ! */'); +} + +$filename = $_SERVER['DOCUMENT_ROOT'] . '/' . $_GET['f']; + +if (file_exists($filename) && is_file($filename) + && strpos('/' . $filename . '/', '/../') === false) { + $j = array(); + foreach ($_GET as $k => $v) { + if ($k == 'PHPSESSID') continue; + if ($k == 'f') continue; + $k = trim(preg_replace('~[^A-Z0-9_]~', '_', strtoupper($k)), '_'); + if ($k == '') continue; + $j[$k] = $v; + } + $fnhash = md5($filename) . md5(serialize($j)); + $hash = $fnhash . '-' . filemtime($filename); + $cachebase = './cache/'; + $cachefile = $cachebase . $hash . '.cssc'; + $filedata = file_get_contents($filename); + if (strpos($filedata, '<#') === false && strpos($filedata, '#ifexpr') === false && file_exists($cachefile)) { + echo '/* cached */ + +'; + readfile ($cachefile); + } else { + $data = DtCSS($filename, $filedata, $j); + $dir = opendir($cachebase); + while ($entry = readdir($dir)) { + if (substr($entry, 0, strlen($fnhash)) == $fnhash) { + unlink ($cachebase . $entry); + } + } + $fp = fopen($cachefile, 'w'); + fwrite ($fp, $data); fclose ($fp); + echo $data; + } +} else { + echo '/* File not found */'; +} + + +?> diff --git a/css/demo.dt.css b/css/demo.dt.css new file mode 100644 index 0000000..0e88e36 --- /dev/null +++ b/css/demo.dt.css @@ -0,0 +1,39 @@ +#define TEXT_COLOR red +#define LINK_COLOR blue + +%Rounded{ + -webkit-border-radius: 2px; + -moz-border-radius: 2px; + border-radius: 2px; +} + + +div.DtCssDemo{ + + background:CadetBlue; + + h1{ + font-size:12px; + } + h2{ + font-style:italic; + } + self .SomeText span{ + border:1px solid black; + use:Rounded; + } +} + + +body { + color: TEXT_COLOR; +} +a { + self:link, + self:visited { + color: LINK_COLOR; + } + self:hover { + color: lighter(LINK_COLOR); + } +} \ No newline at end of file diff --git a/dtcss.plugin.php b/dtcss.plugin.php new file mode 100644 index 0000000..5079ac8 --- /dev/null +++ b/dtcss.plugin.php @@ -0,0 +1,109 @@ +<?php if (!defined('APPLICATION')) die(); + +$PluginInfo['DtCss'] = array( + 'Name' => 'DtCss', + 'Description' => 'Adapts DtCSS to work with Garden.', + 'Version' => '1.1', + 'Date' => '22 Aug 2010', + 'AuthorUrl' => 'http://code.google.com/p/dtcss/', + 'RequiredApplications' => False, + 'RequiredTheme' => False, + 'RequiredPlugins' => False, + 'RegisterPermissions' => False, + 'SettingsPermission' => False +); + +/* +TODO: +- enable expressions +- parse error handling +- empty cache while enabling/disabling plugin +*/ + +/* +CHANGELOG +1.1 / 22 Aug 2010 + +1.0 / 21 Aug 2010 +- save cached css file to same directory where .dt.css file + +0.9 / 20 Aug 2010 +- first release + +*/ + +class DtCssPlugin extends Gdn_Plugin { + + public function PluginController_DtCssDemo_Create($Sender) { + $Sender->AddCssFile( $this->GetWebResource('css/demo.dt.css') ); + $Sender->View = $this->GetView('demo.php'); + $Sender->Render(); + } + + + public static function GetHash($S) { + $Crc = sprintf('%u', crc32($S)); + $Hash = base_convert($Crc, 10, 36); + $Hash = substr($Hash, -6); + return $Hash; + } + + public static function MakeCssFile($CssPath, $CachedCssFile) { + if (!function_exists('DtCSS')) require dirname(__FILE__).DS.'DtCSS-R27f'.DS.'libdtcss.php'; + $Filedata = file_get_contents($CssPath); + // $CssPath need for #include directives, will use dirname($CssPath)/other.css + $Data = DtCSS($CssPath, $Filedata); + file_put_contents($CachedCssFile, $Data); + } + + public function Base_BeforeAddCss_Handler($Sender) { + if($Sender->DeliveryType() != DELIVERY_TYPE_ALL) return; + $CssFiles =& $Sender->EventArguments['CssFiles']; + foreach ($CssFiles as $Index => $CssInfo) { + $CssFile = $CssInfo['FileName']; + if (substr($CssFile, -7) != '.dt.css') continue; + $AppFolder = $CssInfo['AppFolder']; + if ($AppFolder == '') $AppFolder = $Sender->ApplicationFolder; + $CssPaths = array(); + if(strpos($CssFile, '/') !== False) { + $CssPaths[] = CombinePaths(array(PATH_ROOT, $CssFile)); + } else { + if ($Sender->Theme) $CssPaths[] = PATH_THEMES . DS . $Sender->Theme . DS . 'design' . DS . $CssFile; + $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile; + $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile; + } + + $CssPath = False; + foreach($CssPaths as $Glob) { + $Paths = SafeGlob($Glob); + if(count($Paths) > 0) { + $CssPath = $Paths[0]; + break; + } + } + + if($CssPath == False) continue; // not found + + $Basename = pathinfo(pathinfo($CssPath, 8), 8); // without .dt.css + $Hash = self::GetHash($CssPath . filemtime($CssPath)); + + $CacheFileName = sprintf('%s-c-%s.css', $Basename, $Hash); + $CachedCssFile = dirname($CssPath).DS.$CacheFileName; + if (!file_exists($CachedCssFile)) self::MakeCssFile($CssPath, $CachedCssFile); + + // ... and replace preprocessored dt.css file by css + $CssInfo['FileName'] = substr($CachedCssFile, strlen(PATH_ROOT)); + $CssFiles[$Index] = $CssInfo; // AppFolder nevermind (will be ignored) + + } + + + } + + + public function Setup() { + } + + + +} \ No newline at end of file diff --git a/views/demo.php b/views/demo.php new file mode 100644 index 0000000..8773025 --- /dev/null +++ b/views/demo.php @@ -0,0 +1,20 @@ +<?php if (!defined('APPLICATION')) exit(); ?> + + +<p class="Info"> +<code>See plugins/DtCss/css/demo.dt.css</code> and <code>plugins/DtCss/views/demo.php</code> +</p> + +<div class="DtCssDemo"> + +<h1>Lorem ipsum dolor sit amet</h1> + +<div class="SomeText"> +Lorem <span>ipsum dolor sit amet</span> , consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. +</div> +<h2>Epsum</h2> +Epsum factorial non deposit quid pro quo hic escorol. Olypian quarrels et gorilla congolium sic ad nauseum. Souvlaki ignitus carborundum e pluribus unum. Defacto lingo est igpay atinlay. Marquee selectus non provisio incongruous feline nolo contendre. Gratuitous octopus niacin, sodium glutimate. Quote meon an estimate et non interruptus stadium. Sic tempus fugit esperanto hiccup estrogen. Glorious baklava ex librus hup hey ad infinitum. Non sequitur condominium facile et geranium incognito. Epsum factorial non deposit quid pro quo hic escorol. Marquee selectus non provisio incongruous feline nolo contendre Olypian quarrels et gorilla congolium sic ad nauseum. Souvlaki ignitus carborundum e pluribus unum. +Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc., li tot Europa usa li sam vocabularium. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilita de un nov lingua franca: on refusa continuar payar custosi traductores. It solmen va esser necessi far uniform grammatica, pronunciation e plu sommun paroles. +Ma quande lingues coalesce, li grammatica del resultant lingue es plu simplic e regulari quam ti del coalescent lingues. Li nov lingua franca va esser plu simplic e regulari quam li existent Europan lingues. It va esser tam simplic quam Occidental: in fact, it va esser Occidental. A un Angleso it va semblar un simplificat Angles, quam un skeptic Cambridge amico dit me que Occidental es. + +</div> \ No newline at end of file
signup-disabled/small
880fd34d55e993e5923cde787e69388c1abb5557
THE TURKS DID IT (take 3)
diff --git a/README.mkdn b/README.mkdn index b246747..ff28e37 100644 --- a/README.mkdn +++ b/README.mkdn @@ -1,10 +1,10 @@ THE TURKS DID IT! ================= No, really. They did. I lie not! Anyway, this is bugged. You can probably reach the ACTUAL signup page here: -<http://github.com/signup/free/tree> +<http://github.com/signup/<the_size_you_want/tree> (Don't ask *me* why, I have somewhere between 0 and 0 idea why...) \ No newline at end of file
signup-disabled/small
19cae62b6c7e060b17f22e339deedcfd6c762612
OMG TURKS (take 2)
diff --git a/README.mkdn b/README.mkdn index 7cefea3..b246747 100644 --- a/README.mkdn +++ b/README.mkdn @@ -1,4 +1,10 @@ THE TURKS DID IT! ================= -No, really. They did. I lie not! \ No newline at end of file +No, really. They did. I lie not! + +Anyway, this is bugged. You can probably reach the ACTUAL signup page here: + +<http://github.com/signup/free/tree> + +(Don't ask *me* why, I have somewhere between 0 and 0 idea why...) \ No newline at end of file
signup-disabled/small
22793117b4ddf510393e3f722e8f226504b0fc65
OMG TURKS
diff --git a/README.mkdn b/README.mkdn new file mode 100644 index 0000000..7cefea3 --- /dev/null +++ b/README.mkdn @@ -0,0 +1,4 @@ +THE TURKS DID IT! +================= + +No, really. They did. I lie not! \ No newline at end of file
abchernin/Scribd_net-Practice
cf5ff6c58a152a715432e8bcbf436cc5621d1bf5
Basic README added.
diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..afb9774 --- /dev/null +++ b/README.txt @@ -0,0 +1,3 @@ +This is a simple program I design while learning to work with Scribd API through Scribd.Net library by, well, poking it with a stick. + +Scribd.Net library reference is required in order for it to function properly. See wiki. \ No newline at end of file
robn/MooseX-ProtectedAttribute
73409ff5fb458c741418b1961a4d161da4019651
use isa to avoid wrapped methods when finding the caller
diff --git a/lib/MooseX/Meta/Attribute/Trait/Protected.pm b/lib/MooseX/Meta/Attribute/Trait/Protected.pm index 33d2852..e5025ea 100644 --- a/lib/MooseX/Meta/Attribute/Trait/Protected.pm +++ b/lib/MooseX/Meta/Attribute/Trait/Protected.pm @@ -1,99 +1,99 @@ package MooseX::Meta::Attribute::Trait::Protected; use Moose::Role; use Moose::Util qw(meta_attribute_alias); use MooseX::Types::Moose qw(Str HashRef); use MooseX::Types::Structured qw(Dict Optional); use MooseX::Types -declare => [qw(ProtectionTable)]; my @types = qw(accessor reader writer predicate clearer); has "protection" => ( is => "rw", isa => ProtectionTable, default => sub { return { map { $_ => "private" } @types }; }, coerce => 1, ); subtype ProtectionTable, as Dict[ accessor => Optional[Str], reader => Optional[Str], writer => Optional[Str], predicate => Optional[Str], clearer => Optional[Str], ]; coerce ProtectionTable, from Str, via { my $p = $_; +{ map { $_ => $p } qw(accessor reader writer predicate clearer) }; }; around "_process_accessors" => sub { my $orig = shift; my $self = shift; my $type = $_[0]; my $name = $self->name; my $class = $self->associated_class->name; my $protection = $self->protection; map { $protection->{$_} ||= "private" } @types; return $self->$orig(@_) if $protection->{$type} eq "public"; my ($method, $code) = $self->$orig(@_); my $wrap = Class::MOP::Method::Wrapped->wrap($code); # private. the caller must be in the same class that the object is blessed into if ($protection->{$type} eq "private") { $wrap->add_around_modifier(sub { my $orig = shift; my ($self) = @_; my $n = 0; my $caller; - while (($caller = caller($n++)) eq "Class::MOP::Method::Wrapped") { } + while (($caller = caller($n++))->isa("Class::MOP::Method::Wrapped")) { } if ($caller ne blessed $self) { confess "Method '$method' in class '$class' is private"; } goto $orig; }); } # protected. the caller must be in the same class or one of of the # subclasses of that which the object is blessed into elsif ($protection->{$type} eq "protected") { $wrap->add_around_modifier(sub { my $orig = shift; my ($self) = @_; my $n = 0; my $caller; - while (($caller = caller($n++)) eq "Class::MOP::Method::Wrapped") { } + while (($caller = caller($n++))->isa("Class::MOP::Method::Wrapped")) { } if (!($caller eq blessed $self || $self->isa($caller))) { confess "Method '$method' in class '$class' is protected"; } goto $orig; }); } return ($method, $wrap); }; meta_attribute_alias("Protected"); no Moose::Role; 1;
robn/MooseX-ProtectedAttribute
3b50f88b601a005531a277d33f7b9bb419839d1c
use blessed instead of ref
diff --git a/lib/MooseX/Meta/Attribute/Trait/Protected.pm b/lib/MooseX/Meta/Attribute/Trait/Protected.pm index 778833c..33d2852 100644 --- a/lib/MooseX/Meta/Attribute/Trait/Protected.pm +++ b/lib/MooseX/Meta/Attribute/Trait/Protected.pm @@ -1,99 +1,99 @@ package MooseX::Meta::Attribute::Trait::Protected; use Moose::Role; use Moose::Util qw(meta_attribute_alias); use MooseX::Types::Moose qw(Str HashRef); use MooseX::Types::Structured qw(Dict Optional); use MooseX::Types -declare => [qw(ProtectionTable)]; my @types = qw(accessor reader writer predicate clearer); has "protection" => ( is => "rw", isa => ProtectionTable, default => sub { return { map { $_ => "private" } @types }; }, coerce => 1, ); subtype ProtectionTable, as Dict[ accessor => Optional[Str], reader => Optional[Str], writer => Optional[Str], predicate => Optional[Str], clearer => Optional[Str], ]; coerce ProtectionTable, from Str, via { my $p = $_; +{ map { $_ => $p } qw(accessor reader writer predicate clearer) }; }; around "_process_accessors" => sub { my $orig = shift; my $self = shift; my $type = $_[0]; my $name = $self->name; my $class = $self->associated_class->name; my $protection = $self->protection; map { $protection->{$_} ||= "private" } @types; return $self->$orig(@_) if $protection->{$type} eq "public"; my ($method, $code) = $self->$orig(@_); my $wrap = Class::MOP::Method::Wrapped->wrap($code); # private. the caller must be in the same class that the object is blessed into if ($protection->{$type} eq "private") { $wrap->add_around_modifier(sub { my $orig = shift; my ($self) = @_; my $n = 0; my $caller; while (($caller = caller($n++)) eq "Class::MOP::Method::Wrapped") { } - if ($caller ne ref $self) { + if ($caller ne blessed $self) { confess "Method '$method' in class '$class' is private"; } goto $orig; }); } # protected. the caller must be in the same class or one of of the # subclasses of that which the object is blessed into elsif ($protection->{$type} eq "protected") { $wrap->add_around_modifier(sub { my $orig = shift; my ($self) = @_; my $n = 0; my $caller; while (($caller = caller($n++)) eq "Class::MOP::Method::Wrapped") { } - if (!($caller eq ref $self || $self->isa($caller))) { + if (!($caller eq blessed $self || $self->isa($caller))) { confess "Method '$method' in class '$class' is protected"; } goto $orig; }); } return ($method, $wrap); }; meta_attribute_alias("Protected"); no Moose::Role; 1;
robn/MooseX-ProtectedAttribute
d9a25a642c2072e2c32b5c92fab4e2d275e76242
use Moose::Util::meta_attribute_alias to register the trait
diff --git a/lib/MooseX/Meta/Attribute/Trait/Protected.pm b/lib/MooseX/Meta/Attribute/Trait/Protected.pm index 20b9b04..778833c 100644 --- a/lib/MooseX/Meta/Attribute/Trait/Protected.pm +++ b/lib/MooseX/Meta/Attribute/Trait/Protected.pm @@ -1,100 +1,99 @@ package MooseX::Meta::Attribute::Trait::Protected; use Moose::Role; +use Moose::Util qw(meta_attribute_alias); + use MooseX::Types::Moose qw(Str HashRef); use MooseX::Types::Structured qw(Dict Optional); use MooseX::Types -declare => [qw(ProtectionTable)]; my @types = qw(accessor reader writer predicate clearer); has "protection" => ( is => "rw", isa => ProtectionTable, default => sub { return { map { $_ => "private" } @types }; }, coerce => 1, ); subtype ProtectionTable, as Dict[ accessor => Optional[Str], reader => Optional[Str], writer => Optional[Str], predicate => Optional[Str], clearer => Optional[Str], ]; coerce ProtectionTable, from Str, via { my $p = $_; +{ map { $_ => $p } qw(accessor reader writer predicate clearer) }; }; around "_process_accessors" => sub { my $orig = shift; my $self = shift; my $type = $_[0]; my $name = $self->name; my $class = $self->associated_class->name; my $protection = $self->protection; map { $protection->{$_} ||= "private" } @types; return $self->$orig(@_) if $protection->{$type} eq "public"; my ($method, $code) = $self->$orig(@_); my $wrap = Class::MOP::Method::Wrapped->wrap($code); # private. the caller must be in the same class that the object is blessed into if ($protection->{$type} eq "private") { $wrap->add_around_modifier(sub { my $orig = shift; my ($self) = @_; my $n = 0; my $caller; while (($caller = caller($n++)) eq "Class::MOP::Method::Wrapped") { } if ($caller ne ref $self) { confess "Method '$method' in class '$class' is private"; } goto $orig; }); } # protected. the caller must be in the same class or one of of the # subclasses of that which the object is blessed into elsif ($protection->{$type} eq "protected") { $wrap->add_around_modifier(sub { my $orig = shift; my ($self) = @_; my $n = 0; my $caller; while (($caller = caller($n++)) eq "Class::MOP::Method::Wrapped") { } if (!($caller eq ref $self || $self->isa($caller))) { confess "Method '$method' in class '$class' is protected"; } goto $orig; }); } return ($method, $wrap); }; -no Moose::Role; - -package # hide from PAUSE - Moose::Meta::Attribute::Custom::Trait::Protected; +meta_attribute_alias("Protected"); -sub register_implementation { "MooseX::Meta::Attribute::Trait::Protected" } +no Moose::Role; 1;
robn/MooseX-ProtectedAttribute
353f7bd79f5bfd55bd851485fd46ccefd51a4fe6
documentation stubs
diff --git a/lib/MooseX/ProtectedAttribute.pm b/lib/MooseX/ProtectedAttribute.pm index 527d1c6..c054b75 100644 --- a/lib/MooseX/ProtectedAttribute.pm +++ b/lib/MooseX/ProtectedAttribute.pm @@ -1,38 +1,101 @@ package MooseX::ProtectedAttribute; use strict; use warnings; use Moose (); use Moose::Exporter (); use MooseX::Meta::Attribute::Trait::Protected; our $VERSION = '0.01'; Moose::Exporter->setup_import_methods( with_caller => [qw(has_protected has_private)], also => "Moose", ); sub has_protected { my $caller = shift; my $name = shift; my %options = @_; $options{traits} ||= []; unshift @{$options{traits}}, 'Protected'; $options{protection} ||= "protected"; Class::MOP::Class->initialize($caller)->add_attribute($name, %options); } sub has_private { my $caller = shift; my $name = shift; my %options = @_; $options{traits} ||= []; unshift @{$options{traits}}, 'Protected'; $options{protection} ||= "private"; Class::MOP::Class->initialize($caller)->add_attribute($name, %options); } 1; + +__END__ + +=pod + +=head1 NAME + +MooseX::ProtectedAttribute - hide your attributes from prying eyes + +=head1 SYNOPSIS + + use Moose; + use MooseX::ProtectedAttribute; + + has_private "thing" => { + is => "rw", + isa => "Str", + }; + + has_protected "whatever" => { + is => "ro", + isa => "Int", + }; + +=head1 DESCRIPTION + +MooseX::ProtectedAttribute allows you to restrict access to attribute accessor +methods. It allows you to created "private" and "protected" attributes than +can only be accessed from within the class they were declared in (private) or +its subclasses (protected). These are much like similarly named mechanisms +from other languages. + +Note that due to limitations in Perl, the attributes created with this module +are not truly off-limits. See L<"CAVEATS"> for details. + +=head1 EXPORTS + +=head2 has_private + +=head2 has_protected + +=head1 CAVEATS + +=head1 FEEDBACK + +If you find this module useful, please consider rating it on the CPAN Ratings +service at +L<http://cpanratings.perl.org/rate?distribution=MooseX-ProtectedAttribute> + +Please report bugs via the CPAN Request Tracker at +L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=MooseX-ProtectedAttribute> + +If you like (or hate) this module, please tell the author! Send mail to +E<lt>[email protected]<gt>. + +=head1 AUTHOR + +Copyright 2009 Robert Norris E<lt>[email protected]<gt>. + +=head1 LICENSE + +This module is free software, you can redistribute it and/or modify it under +the same terms as Perl itself.
robn/MooseX-ProtectedAttribute
ee3ee90a9e4e9a49cbdb8b6b5c9e41fcc1327bd4
try to walk up the caller tree to figure out if access is allowed, probably wrong
diff --git a/lib/MooseX/Meta/Attribute/Trait/Protected.pm b/lib/MooseX/Meta/Attribute/Trait/Protected.pm index efa38a6..20b9b04 100644 --- a/lib/MooseX/Meta/Attribute/Trait/Protected.pm +++ b/lib/MooseX/Meta/Attribute/Trait/Protected.pm @@ -1,92 +1,100 @@ package MooseX::Meta::Attribute::Trait::Protected; use Moose::Role; use MooseX::Types::Moose qw(Str HashRef); use MooseX::Types::Structured qw(Dict Optional); use MooseX::Types -declare => [qw(ProtectionTable)]; my @types = qw(accessor reader writer predicate clearer); has "protection" => ( is => "rw", isa => ProtectionTable, default => sub { return { map { $_ => "private" } @types }; }, coerce => 1, ); subtype ProtectionTable, as Dict[ accessor => Optional[Str], reader => Optional[Str], writer => Optional[Str], predicate => Optional[Str], clearer => Optional[Str], ]; coerce ProtectionTable, from Str, via { my $p = $_; +{ map { $_ => $p } qw(accessor reader writer predicate clearer) }; }; around "_process_accessors" => sub { my $orig = shift; my $self = shift; my $type = $_[0]; my $name = $self->name; my $class = $self->associated_class->name; my $protection = $self->protection; map { $protection->{$_} ||= "private" } @types; return $self->$orig(@_) if $protection->{$type} eq "public"; my ($method, $code) = $self->$orig(@_); my $wrap = Class::MOP::Method::Wrapped->wrap($code); # private. the caller must be in the same class that the object is blessed into if ($protection->{$type} eq "private") { $wrap->add_around_modifier(sub { my $orig = shift; my ($self) = @_; - if (caller ne ref $self) { + my $n = 0; + my $caller; + while (($caller = caller($n++)) eq "Class::MOP::Method::Wrapped") { } + + if ($caller ne ref $self) { confess "Method '$method' in class '$class' is private"; } goto $orig; }); } # protected. the caller must be in the same class or one of of the # subclasses of that which the object is blessed into elsif ($protection->{$type} eq "protected") { $wrap->add_around_modifier(sub { my $orig = shift; my ($self) = @_; - if (!(caller eq ref $self || $self->isa(caller))) { + my $n = 0; + my $caller; + while (($caller = caller($n++)) eq "Class::MOP::Method::Wrapped") { } + + if (!($caller eq ref $self || $self->isa($caller))) { confess "Method '$method' in class '$class' is protected"; } goto $orig; }); } return ($method, $wrap); }; no Moose::Role; package # hide from PAUSE Moose::Meta::Attribute::Custom::Trait::Protected; sub register_implementation { "MooseX::Meta::Attribute::Trait::Protected" } 1;
robn/MooseX-ProtectedAttribute
4824eabb42e19ba110c36e014c25580d111156fb
seperate protection settings for each method
diff --git a/lib/MooseX/Meta/Attribute/Trait/Protected.pm b/lib/MooseX/Meta/Attribute/Trait/Protected.pm index 50c5c1b..efa38a6 100644 --- a/lib/MooseX/Meta/Attribute/Trait/Protected.pm +++ b/lib/MooseX/Meta/Attribute/Trait/Protected.pm @@ -1,74 +1,92 @@ package MooseX::Meta::Attribute::Trait::Protected; use Moose::Role; +use MooseX::Types::Moose qw(Str HashRef); +use MooseX::Types::Structured qw(Dict Optional); +use MooseX::Types -declare => [qw(ProtectionTable)]; + +my @types = qw(accessor reader writer predicate clearer); has "protection" => ( is => "rw", - isa => "Str", - default => "private", + isa => ProtectionTable, + default => sub { + return { map { $_ => "private" } @types }; + }, + coerce => 1, ); +subtype ProtectionTable, + as Dict[ + accessor => Optional[Str], + reader => Optional[Str], + writer => Optional[Str], + predicate => Optional[Str], + clearer => Optional[Str], + ]; + +coerce ProtectionTable, + from Str, + via { + my $p = $_; + +{ map { $_ => $p } qw(accessor reader writer predicate clearer) }; + }; + around "_process_accessors" => sub { my $orig = shift; my $self = shift; - return $self->$orig(@_) if $_[0] ne "accessor"; + my $type = $_[0]; my $name = $self->name; my $class = $self->associated_class->name; - my $protection = $self->protection; - if (! grep { $protection eq $_ } qw(private protected public)) { - confess "Unknown value '$protection' for option 'protection' on attribute '$name'"; - } + my $protection = $self->protection; + map { $protection->{$_} ||= "private" } @types; - return $self->$orig(@_) if $protection eq "public"; + return $self->$orig(@_) if $protection->{$type} eq "public"; my ($method, $code) = $self->$orig(@_); my $wrap = Class::MOP::Method::Wrapped->wrap($code); # private. the caller must be in the same class that the object is blessed into - if ($protection eq "private") { + if ($protection->{$type} eq "private") { $wrap->add_around_modifier(sub { my $orig = shift; my ($self) = @_; if (caller ne ref $self) { confess "Method '$method' in class '$class' is private"; } goto $orig; }); } # protected. the caller must be in the same class or one of of the # subclasses of that which the object is blessed into - elsif ($protection eq "protected") { + elsif ($protection->{$type} eq "protected") { $wrap->add_around_modifier(sub { my $orig = shift; my ($self) = @_; if (!(caller eq ref $self || $self->isa(caller))) { confess "Method '$method' in class '$class' is protected"; } goto $orig; }); } - else { - confess "Unknown protection type '$protection'. This is a bug in MooseX::ProtectedAttribute. Report it!"; - } - return ($method, $wrap); }; no Moose::Role; package # hide from PAUSE Moose::Meta::Attribute::Custom::Trait::Protected; sub register_implementation { "MooseX::Meta::Attribute::Trait::Protected" } 1;
robn/MooseX-ProtectedAttribute
d7a259178bb7ed37a252ff58aa35cb6040919d88
remove debug
diff --git a/lib/MooseX/Meta/Attribute/Trait/Protected.pm b/lib/MooseX/Meta/Attribute/Trait/Protected.pm index 09051f9..50c5c1b 100644 --- a/lib/MooseX/Meta/Attribute/Trait/Protected.pm +++ b/lib/MooseX/Meta/Attribute/Trait/Protected.pm @@ -1,77 +1,74 @@ package MooseX::Meta::Attribute::Trait::Protected; use Moose::Role; has "protection" => ( is => "rw", isa => "Str", default => "private", ); around "_process_accessors" => sub { my $orig = shift; my $self = shift; return $self->$orig(@_) if $_[0] ne "accessor"; my $name = $self->name; my $class = $self->associated_class->name; my $protection = $self->protection; if (! grep { $protection eq $_ } qw(private protected public)) { confess "Unknown value '$protection' for option 'protection' on attribute '$name'"; } return $self->$orig(@_) if $protection eq "public"; my ($method, $code) = $self->$orig(@_); my $wrap = Class::MOP::Method::Wrapped->wrap($code); # private. the caller must be in the same class that the object is blessed into if ($protection eq "private") { $wrap->add_around_modifier(sub { my $orig = shift; my ($self) = @_; - printf "caller: %s\n", scalar caller; - printf " self: %s\n", ref $self; - if (caller ne ref $self) { confess "Method '$method' in class '$class' is private"; } goto $orig; }); } # protected. the caller must be in the same class or one of of the # subclasses of that which the object is blessed into elsif ($protection eq "protected") { $wrap->add_around_modifier(sub { my $orig = shift; my ($self) = @_; if (!(caller eq ref $self || $self->isa(caller))) { confess "Method '$method' in class '$class' is protected"; } goto $orig; }); } else { confess "Unknown protection type '$protection'. This is a bug in MooseX::ProtectedAttribute. Report it!"; } return ($method, $wrap); }; no Moose::Role; package # hide from PAUSE Moose::Meta::Attribute::Custom::Trait::Protected; sub register_implementation { "MooseX::Meta::Attribute::Trait::Protected" } 1;
robn/MooseX-ProtectedAttribute
3f25b7370cac7ceb022b4ab19ffa4f5fab664f8a
first implementation, works for privates at least!
diff --git a/lib/MooseX/Meta/Attribute/Trait/Protected.pm b/lib/MooseX/Meta/Attribute/Trait/Protected.pm index 6773d42..09051f9 100644 --- a/lib/MooseX/Meta/Attribute/Trait/Protected.pm +++ b/lib/MooseX/Meta/Attribute/Trait/Protected.pm @@ -1,46 +1,77 @@ package MooseX::Meta::Attribute::Trait::Protected; use Moose::Role; has "protection" => ( is => "rw", isa => "Str", default => "private", ); around "_process_accessors" => sub { my $orig = shift; my $self = shift; - print "PA: _process_accessors\n"; + return $self->$orig(@_) if $_[0] ne "accessor"; - print " orig: $orig\n"; - print " self: $self\n"; + my $name = $self->name; + my $class = $self->associated_class->name; + my $protection = $self->protection; - if (@_) { - print " args:\n"; - print " $_\n" for map { defined $_ ? $_ : "[undef]" } @_; + if (! grep { $protection eq $_ } qw(private protected public)) { + confess "Unknown value '$protection' for option 'protection' on attribute '$name'"; } - my ($name, $method) = $self->$orig(@_); + return $self->$orig(@_) if $protection eq "public"; - my $wrap = Class::MOP::Method::Wrapped->wrap($method); - $wrap->add_around_modifier(sub { - my $orig = shift; + my ($method, $code) = $self->$orig(@_); - print ">>> I'm around $name\n"; + my $wrap = Class::MOP::Method::Wrapped->wrap($code); - goto $orig; - }); + # private. the caller must be in the same class that the object is blessed into + if ($protection eq "private") { + $wrap->add_around_modifier(sub { + my $orig = shift; + my ($self) = @_; - return ($name, $wrap); + printf "caller: %s\n", scalar caller; + printf " self: %s\n", ref $self; + + if (caller ne ref $self) { + confess "Method '$method' in class '$class' is private"; + } + + goto $orig; + }); + } + + # protected. the caller must be in the same class or one of of the + # subclasses of that which the object is blessed into + elsif ($protection eq "protected") { + $wrap->add_around_modifier(sub { + my $orig = shift; + my ($self) = @_; + + if (!(caller eq ref $self || $self->isa(caller))) { + confess "Method '$method' in class '$class' is protected"; + } + + goto $orig; + }); + } + + else { + confess "Unknown protection type '$protection'. This is a bug in MooseX::ProtectedAttribute. Report it!"; + } + + return ($method, $wrap); }; no Moose::Role; package # hide from PAUSE Moose::Meta::Attribute::Custom::Trait::Protected; sub register_implementation { "MooseX::Meta::Attribute::Trait::Protected" } 1;
robn/MooseX-ProtectedAttribute
9cb4846f77031d47b82a4f31d2f12505258cf13f
_process_accessors wrapper from the prototype
diff --git a/lib/MooseX/Meta/Attribute/Trait/Protected.pm b/lib/MooseX/Meta/Attribute/Trait/Protected.pm index dba8a18..6773d42 100644 --- a/lib/MooseX/Meta/Attribute/Trait/Protected.pm +++ b/lib/MooseX/Meta/Attribute/Trait/Protected.pm @@ -1,18 +1,46 @@ package MooseX::Meta::Attribute::Trait::Protected; use Moose::Role; has "protection" => ( is => "rw", isa => "Str", default => "private", ); +around "_process_accessors" => sub { + my $orig = shift; + my $self = shift; + + print "PA: _process_accessors\n"; + + print " orig: $orig\n"; + print " self: $self\n"; + + if (@_) { + print " args:\n"; + print " $_\n" for map { defined $_ ? $_ : "[undef]" } @_; + } + + my ($name, $method) = $self->$orig(@_); + + my $wrap = Class::MOP::Method::Wrapped->wrap($method); + $wrap->add_around_modifier(sub { + my $orig = shift; + + print ">>> I'm around $name\n"; + + goto $orig; + }); + + return ($name, $wrap); +}; + no Moose::Role; package # hide from PAUSE Moose::Meta::Attribute::Custom::Trait::Protected; sub register_implementation { "MooseX::Meta::Attribute::Trait::Protected" } 1;
robn/MooseX-ProtectedAttribute
0ee1b218db1d435f28e40dd279f402b5ad463ee5
remove pirates
diff --git a/lib/MooseX/ProtectedAttribute.pm b/lib/MooseX/ProtectedAttribute.pm index ebcc367..527d1c6 100644 --- a/lib/MooseX/ProtectedAttribute.pm +++ b/lib/MooseX/ProtectedAttribute.pm @@ -1,38 +1,38 @@ package MooseX::ProtectedAttribute; use strict; use warnings; use Moose (); use Moose::Exporter (); use MooseX::Meta::Attribute::Trait::Protected; our $VERSION = '0.01'; Moose::Exporter->setup_import_methods( with_caller => [qw(has_protected has_private)], also => "Moose", ); sub has_protected { my $caller = shift; my $name = shift; my %options = @_; $options{traits} ||= []; unshift @{$options{traits}}, 'Protected'; $options{protection} ||= "protected"; - Class::MOP::Class->initialize($callar)->add_attribute($name, %options); + Class::MOP::Class->initialize($caller)->add_attribute($name, %options); } sub has_private { my $caller = shift; my $name = shift; my %options = @_; $options{traits} ||= []; unshift @{$options{traits}}, 'Protected'; $options{protection} ||= "private"; - Class::MOP::Class->initialize($callar)->add_attribute($name, %options); + Class::MOP::Class->initialize($caller)->add_attribute($name, %options); } 1;
robn/MooseX-ProtectedAttribute
b86cd731d3bf4073d3e3d6576af4c529f3ea846f
trait registration
diff --git a/lib/MooseX/Meta/Attribute/Trait/Protected.pm b/lib/MooseX/Meta/Attribute/Trait/Protected.pm index 355b9b3..dba8a18 100644 --- a/lib/MooseX/Meta/Attribute/Trait/Protected.pm +++ b/lib/MooseX/Meta/Attribute/Trait/Protected.pm @@ -1,11 +1,18 @@ package MooseX::Meta::Attribute::Trait::Protected; use Moose::Role; has "protection" => ( is => "rw", isa => "Str", default => "private", ); +no Moose::Role; + +package # hide from PAUSE + Moose::Meta::Attribute::Custom::Trait::Protected; + +sub register_implementation { "MooseX::Meta::Attribute::Trait::Protected" } + 1;
robn/MooseX-ProtectedAttribute
f6f29b08b3804fb4a6867ac1f26267f7605a08b8
code stubs
diff --git a/lib/MooseX/Meta/Attribute/Trait/Protected.pm b/lib/MooseX/Meta/Attribute/Trait/Protected.pm index 5b0e656..355b9b3 100644 --- a/lib/MooseX/Meta/Attribute/Trait/Protected.pm +++ b/lib/MooseX/Meta/Attribute/Trait/Protected.pm @@ -1,3 +1,11 @@ package MooseX::Meta::Attribute::Trait::Protected; +use Moose::Role; + +has "protection" => ( + is => "rw", + isa => "Str", + default => "private", +); + 1; diff --git a/lib/MooseX/ProtectedAttribute.pm b/lib/MooseX/ProtectedAttribute.pm index ae36c10..9fb1ace 100644 --- a/lib/MooseX/ProtectedAttribute.pm +++ b/lib/MooseX/ProtectedAttribute.pm @@ -1,3 +1,24 @@ package MooseX::ProtectedAttribute; +use strict; +use warnings; + +use Moose (); +use Moose::Exporter (); + +use MooseX::Meta::Attribute::Trait::Protected; + +our $VERSION = '0.01'; + +Moose::Exporter->setup_import_methods( + with_caller => [qw(has_protected has_private)], + also => "Moose", +); + +sub has_protected { +} + +sub has_private { +} + 1;
robn/MooseX-ProtectedAttribute
efc634076992df3ffcae091895e707ba4e959838
module stub
diff --git a/lib/MooseX/Meta/Attribute/Trait/Protected.pm b/lib/MooseX/Meta/Attribute/Trait/Protected.pm new file mode 100644 index 0000000..5b0e656 --- /dev/null +++ b/lib/MooseX/Meta/Attribute/Trait/Protected.pm @@ -0,0 +1,3 @@ +package MooseX::Meta::Attribute::Trait::Protected; + +1; diff --git a/lib/MooseX/ProtectedAttribute.pm b/lib/MooseX/ProtectedAttribute.pm index 4471c2e..ae36c10 100644 --- a/lib/MooseX/ProtectedAttribute.pm +++ b/lib/MooseX/ProtectedAttribute.pm @@ -1,110 +1,3 @@ package MooseX::ProtectedAttribute; -use warnings; -use strict; - -=head1 NAME - -MooseX::ProtectedAttribute - The great new MooseX::ProtectedAttribute! - -=head1 VERSION - -Version 0.01 - -=cut - -our $VERSION = '0.01'; - - -=head1 SYNOPSIS - -Quick summary of what the module does. - -Perhaps a little code snippet. - - use MooseX::ProtectedAttribute; - - my $foo = MooseX::ProtectedAttribute->new(); - ... - -=head1 EXPORT - -A list of functions that can be exported. You can delete this section -if you don't export anything, such as for a purely object-oriented module. - -=head1 SUBROUTINES/METHODS - -=head2 function1 - -=cut - -sub function1 { -} - -=head2 function2 - -=cut - -sub function2 { -} - -=head1 AUTHOR - -Robert Norris, C<< <rob at cataclysm.cx> >> - -=head1 BUGS - -Please report any bugs or feature requests to C<bug-moosex-protectedattribute at rt.cpan.org>, or through -the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=MooseX-ProtectedAttribute>. I will be notified, and then you'll -automatically be notified of progress on your bug as I make changes. - - - - -=head1 SUPPORT - -You can find documentation for this module with the perldoc command. - - perldoc MooseX::ProtectedAttribute - - -You can also look for information at: - -=over 4 - -=item * RT: CPAN's request tracker - -L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=MooseX-ProtectedAttribute> - -=item * AnnoCPAN: Annotated CPAN documentation - -L<http://annocpan.org/dist/MooseX-ProtectedAttribute> - -=item * CPAN Ratings - -L<http://cpanratings.perl.org/d/MooseX-ProtectedAttribute> - -=item * Search CPAN - -L<http://search.cpan.org/dist/MooseX-ProtectedAttribute/> - -=back - - -=head1 ACKNOWLEDGEMENTS - - -=head1 LICENSE AND COPYRIGHT - -Copyright 2009 Robert Norris. - -This program is free software; you can redistribute it and/or modify it -under the terms of either: the GNU General Public License as published -by the Free Software Foundation; or the Artistic License. - -See http://dev.perl.org/licenses/ for more information. - - -=cut - -1; # End of MooseX::ProtectedAttribute +1;
robn/MooseX-ProtectedAttribute
78d6bcb2c5b4b8f89b3f22a0d99186be0dc07cf6
bootstrapped by module-starter
diff --git a/Changes b/Changes new file mode 100644 index 0000000..0b66214 --- /dev/null +++ b/Changes @@ -0,0 +1,5 @@ +Revision history for MooseX-ProtectedAttribute + +0.01 Date/time + First version, released on an unsuspecting world. + diff --git a/MANIFEST b/MANIFEST new file mode 100644 index 0000000..b113561 --- /dev/null +++ b/MANIFEST @@ -0,0 +1,9 @@ +Changes +MANIFEST +Makefile.PL +README +lib/MooseX/ProtectedAttribute.pm +t/00-load.t +t/manifest.t +t/pod-coverage.t +t/pod.t diff --git a/Makefile.PL b/Makefile.PL new file mode 100644 index 0000000..f620a71 --- /dev/null +++ b/Makefile.PL @@ -0,0 +1,19 @@ +use strict; +use warnings; +use ExtUtils::MakeMaker; + +WriteMakefile( + NAME => 'MooseX::ProtectedAttribute', + AUTHOR => q{Robert Norris <[email protected]>}, + VERSION_FROM => 'lib/MooseX/ProtectedAttribute.pm', + ABSTRACT_FROM => 'lib/MooseX/ProtectedAttribute.pm', + ($ExtUtils::MakeMaker::VERSION >= 6.3002 + ? ('LICENSE'=> 'perl') + : ()), + PL_FILES => {}, + PREREQ_PM => { + 'Test::More' => 0, + }, + dist => { COMPRESS => 'gzip -9f', SUFFIX => 'gz', }, + clean => { FILES => 'MooseX-ProtectedAttribute-*' }, +); diff --git a/README b/README new file mode 100644 index 0000000..bfe7dbf --- /dev/null +++ b/README @@ -0,0 +1,55 @@ +MooseX-ProtectedAttribute + +The README is used to introduce the module and provide instructions on +how to install the module, any machine dependencies it may have (for +example C compilers and installed libraries) and any other information +that should be provided before the module is installed. + +A README file is required for CPAN modules since CPAN extracts the README +file from a module distribution so that people browsing the archive +can use it to get an idea of the module's uses. It is usually a good idea +to provide version information here so that people can decide whether +fixes for the module are worth downloading. + + +INSTALLATION + +To install this module, run the following commands: + + perl Makefile.PL + make + make test + make install + +SUPPORT AND DOCUMENTATION + +After installing, you can find documentation for this module with the +perldoc command. + + perldoc MooseX::ProtectedAttribute + +You can also look for information at: + + RT, CPAN's request tracker + http://rt.cpan.org/NoAuth/Bugs.html?Dist=MooseX-ProtectedAttribute + + AnnoCPAN, Annotated CPAN documentation + http://annocpan.org/dist/MooseX-ProtectedAttribute + + CPAN Ratings + http://cpanratings.perl.org/d/MooseX-ProtectedAttribute + + Search CPAN + http://search.cpan.org/dist/MooseX-ProtectedAttribute/ + + +LICENSE AND COPYRIGHT + +Copyright (C) 2009 Robert Norris + +This program is free software; you can redistribute it and/or modify it +under the terms of either: the GNU General Public License as published +by the Free Software Foundation; or the Artistic License. + +See http://dev.perl.org/licenses/ for more information. + diff --git a/ignore.txt b/ignore.txt new file mode 100644 index 0000000..57d868c --- /dev/null +++ b/ignore.txt @@ -0,0 +1,12 @@ +blib* +Makefile +Makefile.old +Build +Build.bat +_build* +pm_to_blib* +*.tar.gz +.lwpcookies +cover_db +pod2htm*.tmp +MooseX-ProtectedAttribute-* diff --git a/lib/MooseX/ProtectedAttribute.pm b/lib/MooseX/ProtectedAttribute.pm new file mode 100644 index 0000000..4471c2e --- /dev/null +++ b/lib/MooseX/ProtectedAttribute.pm @@ -0,0 +1,110 @@ +package MooseX::ProtectedAttribute; + +use warnings; +use strict; + +=head1 NAME + +MooseX::ProtectedAttribute - The great new MooseX::ProtectedAttribute! + +=head1 VERSION + +Version 0.01 + +=cut + +our $VERSION = '0.01'; + + +=head1 SYNOPSIS + +Quick summary of what the module does. + +Perhaps a little code snippet. + + use MooseX::ProtectedAttribute; + + my $foo = MooseX::ProtectedAttribute->new(); + ... + +=head1 EXPORT + +A list of functions that can be exported. You can delete this section +if you don't export anything, such as for a purely object-oriented module. + +=head1 SUBROUTINES/METHODS + +=head2 function1 + +=cut + +sub function1 { +} + +=head2 function2 + +=cut + +sub function2 { +} + +=head1 AUTHOR + +Robert Norris, C<< <rob at cataclysm.cx> >> + +=head1 BUGS + +Please report any bugs or feature requests to C<bug-moosex-protectedattribute at rt.cpan.org>, or through +the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=MooseX-ProtectedAttribute>. I will be notified, and then you'll +automatically be notified of progress on your bug as I make changes. + + + + +=head1 SUPPORT + +You can find documentation for this module with the perldoc command. + + perldoc MooseX::ProtectedAttribute + + +You can also look for information at: + +=over 4 + +=item * RT: CPAN's request tracker + +L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=MooseX-ProtectedAttribute> + +=item * AnnoCPAN: Annotated CPAN documentation + +L<http://annocpan.org/dist/MooseX-ProtectedAttribute> + +=item * CPAN Ratings + +L<http://cpanratings.perl.org/d/MooseX-ProtectedAttribute> + +=item * Search CPAN + +L<http://search.cpan.org/dist/MooseX-ProtectedAttribute/> + +=back + + +=head1 ACKNOWLEDGEMENTS + + +=head1 LICENSE AND COPYRIGHT + +Copyright 2009 Robert Norris. + +This program is free software; you can redistribute it and/or modify it +under the terms of either: the GNU General Public License as published +by the Free Software Foundation; or the Artistic License. + +See http://dev.perl.org/licenses/ for more information. + + +=cut + +1; # End of MooseX::ProtectedAttribute diff --git a/t/00-load.t b/t/00-load.t new file mode 100644 index 0000000..40cfd50 --- /dev/null +++ b/t/00-load.t @@ -0,0 +1,10 @@ +#!perl -T + +use Test::More tests => 1; + +BEGIN { + use_ok( 'MooseX::ProtectedAttribute' ) || print "Bail out! +"; +} + +diag( "Testing MooseX::ProtectedAttribute $MooseX::ProtectedAttribute::VERSION, Perl $], $^X" ); diff --git a/t/boilerplate.t b/t/boilerplate.t new file mode 100644 index 0000000..874f0f2 --- /dev/null +++ b/t/boilerplate.t @@ -0,0 +1,55 @@ +#!perl -T + +use strict; +use warnings; +use Test::More tests => 3; + +sub not_in_file_ok { + my ($filename, %regex) = @_; + open( my $fh, '<', $filename ) + or die "couldn't open $filename for reading: $!"; + + my %violated; + + while (my $line = <$fh>) { + while (my ($desc, $regex) = each %regex) { + if ($line =~ $regex) { + push @{$violated{$desc}||=[]}, $.; + } + } + } + + if (%violated) { + fail("$filename contains boilerplate text"); + diag "$_ appears on lines @{$violated{$_}}" for keys %violated; + } else { + pass("$filename contains no boilerplate text"); + } +} + +sub module_boilerplate_ok { + my ($module) = @_; + not_in_file_ok($module => + 'the great new $MODULENAME' => qr/ - The great new /, + 'boilerplate description' => qr/Quick summary of what the module/, + 'stub function definition' => qr/function[12]/, + ); +} + +TODO: { + local $TODO = "Need to replace the boilerplate text"; + + not_in_file_ok(README => + "The README is used..." => qr/The README is used/, + "'version information here'" => qr/to provide version information/, + ); + + not_in_file_ok(Changes => + "placeholder date/time" => qr(Date/time) + ); + + module_boilerplate_ok('lib/MooseX/ProtectedAttribute.pm'); + + +} + diff --git a/t/manifest.t b/t/manifest.t new file mode 100644 index 0000000..45eb83f --- /dev/null +++ b/t/manifest.t @@ -0,0 +1,13 @@ +#!perl -T + +use strict; +use warnings; +use Test::More; + +unless ( $ENV{RELEASE_TESTING} ) { + plan( skip_all => "Author tests not required for installation" ); +} + +eval "use Test::CheckManifest 0.9"; +plan skip_all => "Test::CheckManifest 0.9 required" if $@; +ok_manifest(); diff --git a/t/pod-coverage.t b/t/pod-coverage.t new file mode 100644 index 0000000..fc40a57 --- /dev/null +++ b/t/pod-coverage.t @@ -0,0 +1,18 @@ +use strict; +use warnings; +use Test::More; + +# Ensure a recent version of Test::Pod::Coverage +my $min_tpc = 1.08; +eval "use Test::Pod::Coverage $min_tpc"; +plan skip_all => "Test::Pod::Coverage $min_tpc required for testing POD coverage" + if $@; + +# Test::Pod::Coverage doesn't require a minimum Pod::Coverage version, +# but older versions don't recognize some common documentation styles +my $min_pc = 0.18; +eval "use Pod::Coverage $min_pc"; +plan skip_all => "Pod::Coverage $min_pc required for testing POD coverage" + if $@; + +all_pod_coverage_ok(); diff --git a/t/pod.t b/t/pod.t new file mode 100644 index 0000000..ee8b18a --- /dev/null +++ b/t/pod.t @@ -0,0 +1,12 @@ +#!perl -T + +use strict; +use warnings; +use Test::More; + +# Ensure a recent version of Test::Pod +my $min_tp = 1.22; +eval "use Test::Pod $min_tp"; +plan skip_all => "Test::Pod $min_tp required for testing POD" if $@; + +all_pod_files_ok();
dap/App-FoxyProxy-Control
a682dcdf3a2721efa5b6682951c75235f8eea522
Convert to Perl module layout
diff --git a/Build.PL b/Build.PL new file mode 100644 index 0000000..c185587 --- /dev/null +++ b/Build.PL @@ -0,0 +1,14 @@ +use Module::Build; +my $build = Module::Build->new( + module_name => 'App::FoxyProxy::Control', + dist_version_from => 'bin/fpc.pl', + license => 'perl', + requires => { + 'perl' => '>= 5.10.0', + 'Modern::Perl' => '>= 1.03', + 'XML::Simple' => '>= 2.18', + 'Proc::ProcessTable' => '>= 0.42', + }, +); +$build->create_build_script(); + diff --git a/MANIFEST b/MANIFEST new file mode 100644 index 0000000..5052101 --- /dev/null +++ b/MANIFEST @@ -0,0 +1,5 @@ +bin/fpc.pl +Build.PL +MANIFEST This list of files +MANIFEST.SKIP +README diff --git a/MANIFEST.SKIP b/MANIFEST.SKIP new file mode 100644 index 0000000..4e3010a --- /dev/null +++ b/MANIFEST.SKIP @@ -0,0 +1,15 @@ +#!include_default +# Avoid configuration metadata file +^MYMETA\. + +# Avoid Module::Build generated and utility files. +\bBuild$ +\bBuild.bat$ +\b_build +\bBuild.COM$ +\bBUILD.COM$ +\bbuild.com$ +^MANIFEST\.SKIP + +# Avoid archives of this distribution +\bApp-FoxyProxy-Control-[\d\.\_]+ diff --git a/bin/fpc.pl b/bin/fpc.pl index a2c5c4c..e41ebdf 100755 --- a/bin/fpc.pl +++ b/bin/fpc.pl @@ -1,281 +1,285 @@ #!/usr/bin/perl =head1 NAME fpc.pl - Utility to start/stop tunnels parsed from FoxyProxy config =head1 SYNOPSIS # List available proxies $ fpc.pl list # Start a given proxy $ fpc.pl start footun # Restart a given proxy $ fpc.pl restart footun # Stop a given proxy $ fpc.pl stop footun # Show status of a given proxy $ fpc.pl status footun # Show usage assistance $ fpc.pl help =head1 DESCRIPTION WARNING: this program contains a bunch of stuff that I once thought was really cool and interesting, but now I mostly just find hard to understand and maintain. This will be addressed after I complete the test suite. =cut +package App::FoxyProxy::Control; + use Modern::Perl; use XML::Simple; use Proc::ProcessTable; +our $VERSION = '1.00'; + my $conf_path = $ENV{'FPC_CONF_PATH'}; my $command_re = qr/^(ssh.*)/; my %commands = ( 'help' => sub { usage() }, 'start' => sub { # Check that params were passed, or exit with usage message params_or_usage(); # Start proxies my @unprocessed_params = proxy_do(sub { my ($p, $x) = @_; if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { say "Starting [$p]: $x"; system(split /\s/, $x); return 1; } return 0; }); say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) if @unprocessed_params; }, 'stop' => sub { params_or_usage(); my $pt = (new Proc::ProcessTable)->table(); # Find proxies in process table and stop them my @unprocessed_params = proxy_do(sub { my ($p, $x) = @_; if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { foreach my $proc ( @{$pt} ) { if ( $proc->cmndline =~ m/^$x\s*$/ ) { say "Stopping [$p]: $x"; $proc->kill('TERM'); } } return 1; } return 0; }); say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) if @unprocessed_params; }, 'restart_broken' => sub { params_or_usage(); my $pt = (new Proc::ProcessTable)->table(); # Find proxies in process table and stop them my @unprocessed_params = proxy_do(sub { my ($p, $x) = @_; if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { foreach my $proc ( @{$pt} ) { if ( $proc->cmndline =~ m/^$x\s*$/ ) { say "Stopping [$p]: $x"; $proc->kill('TERM'); say "Starting [$p]: $x"; system(split /\s/, $x); } } return 1; } return 0; }); say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) if @unprocessed_params; }, 'restart' => sub { # handled elsewhere, but here for inclusion in usage() }, 'list' => sub { say "Configured Proxies:"; proxy_do(sub { say "\t$_[0]"; }); }, 'status' => sub { params_or_usage(); my $pt = (new Proc::ProcessTable)->table(); say "Proxy Status:"; # Find proxies in process table and stop them my @unprocessed_params = proxy_do(sub { my ($p, $x) = @_; my $p_found = 0; if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { PROC: foreach my $proc ( @{$pt} ) { if ( $proc->cmndline =~ m/^$x\s*$/ ) { $p_found = 1; last PROC; } } say "\t${p} ", $p_found ? 'UP' : 'DOWN'; return 1; } return 0; }); say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) if @unprocessed_params; }, ); =begin private =head1 PRIVATE METHODS =head2 proxy_do my @unprocessed_params = proxy_do(sub { my ($proxy, $cmd) = @_; say "$proxy, $cmd"; }); Invokes the supplied method, passing in the name of the proxy and the command as parsed from the FoxyProxy configuration. =cut sub proxy_do { my $func = shift; my $fp = get_fp_cfg(); my @processed; foreach my $p ( keys( %{$fp->{'proxies'}{'proxy'}} ) ) { if ( $fp->{'proxies'}{'proxy'}{$p}{'notes'} =~ $command_re ) { push @processed, $p if $func->($p, $1); } } # From http://www.perlmonks.org/?node_id=153402 # TODO: relearn what this does and document it my @unknown; OUTER: for ( @ARGV ) { last OUTER if $_ eq 'all'; for my $p ( @processed ) { if ( $p eq $_ ) { next OUTER; } } push @unknown, $_; } return @unknown; } =head2 get_fp_cfg my $fp = get_fp_cfg(); Reads and parses FoxyProxy config, returning hashref. =cut sub get_fp_cfg { my $fp; # TODO I don't know why the fuck I did this; seems kind of showy ( sub { $fp ? $fp : $fp = XMLin($conf_path); } )->(); } # From Garick # TODO add this to notes as example of removing element from array by value #sub remove_param { # my $p = shift; # for my $i ( 0..$#ARGV ) { # next unless $ARGV[$i] eq $p; # splice @ARGV, $i, 1, (); # last; # } #} =head2 params_or_usage params_or_usage(); Checks that proxies have been specified in addition to a command, or dies displaying a usage message to stdout. =cut sub params_or_usage { # Remove command name shift @ARGV; # Error if no proxies specified usage() if !@ARGV; } =head3 usage usage(); Displays program usage information to stdout. =cut sub usage { say "Usage: $0 {", ( join '|', keys(%commands) ), '} [all|[proxy_name|proxy_name|...]]'; exit; } =head2 main main(); Invokes main program logic. =cut sub main { usage() unless ( $ARGV[0] && grep {$_ eq $ARGV[0]} keys(%commands) ); # restart is the only command handled # outside of the %commands hash if ( $ARGV[0] eq 'restart' ) { $commands{'stop'}->(); unshift(@ARGV, 'start'); $commands{'start'}->(); } else { $commands{$ARGV[0]}->(); } } main() if $0 eq __FILE__; =end private =cut
dap/App-FoxyProxy-Control
4a5d07835a0203d5351cef3a7d594e86e1514a95
Modern::Perl instead of strict/warnings/Perl6::Say
diff --git a/bin/fpc.pl b/bin/fpc.pl index 4b47d35..a2c5c4c 100755 --- a/bin/fpc.pl +++ b/bin/fpc.pl @@ -1,283 +1,281 @@ #!/usr/bin/perl =head1 NAME fpc.pl - Utility to start/stop tunnels parsed from FoxyProxy config =head1 SYNOPSIS # List available proxies $ fpc.pl list # Start a given proxy $ fpc.pl start footun # Restart a given proxy $ fpc.pl restart footun # Stop a given proxy $ fpc.pl stop footun # Show status of a given proxy $ fpc.pl status footun # Show usage assistance $ fpc.pl help =head1 DESCRIPTION WARNING: this program contains a bunch of stuff that I once thought was really cool and interesting, but now I mostly just find hard to understand and maintain. This will be addressed after I complete the test suite. =cut -use strict; -use warnings; +use Modern::Perl; use XML::Simple; -use Perl6::Say; use Proc::ProcessTable; my $conf_path = $ENV{'FPC_CONF_PATH'}; my $command_re = qr/^(ssh.*)/; my %commands = ( 'help' => sub { usage() }, 'start' => sub { # Check that params were passed, or exit with usage message params_or_usage(); # Start proxies my @unprocessed_params = proxy_do(sub { my ($p, $x) = @_; if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { say "Starting [$p]: $x"; system(split /\s/, $x); return 1; } return 0; }); say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) if @unprocessed_params; }, 'stop' => sub { params_or_usage(); my $pt = (new Proc::ProcessTable)->table(); # Find proxies in process table and stop them my @unprocessed_params = proxy_do(sub { my ($p, $x) = @_; if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { foreach my $proc ( @{$pt} ) { if ( $proc->cmndline =~ m/^$x\s*$/ ) { say "Stopping [$p]: $x"; $proc->kill('TERM'); } } return 1; } return 0; }); say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) if @unprocessed_params; }, 'restart_broken' => sub { params_or_usage(); my $pt = (new Proc::ProcessTable)->table(); # Find proxies in process table and stop them my @unprocessed_params = proxy_do(sub { my ($p, $x) = @_; if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { foreach my $proc ( @{$pt} ) { if ( $proc->cmndline =~ m/^$x\s*$/ ) { say "Stopping [$p]: $x"; $proc->kill('TERM'); say "Starting [$p]: $x"; system(split /\s/, $x); } } return 1; } return 0; }); say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) if @unprocessed_params; }, 'restart' => sub { # handled elsewhere, but here for inclusion in usage() }, 'list' => sub { say "Configured Proxies:"; proxy_do(sub { say "\t$_[0]"; }); }, 'status' => sub { params_or_usage(); my $pt = (new Proc::ProcessTable)->table(); say "Proxy Status:"; # Find proxies in process table and stop them my @unprocessed_params = proxy_do(sub { my ($p, $x) = @_; my $p_found = 0; if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { PROC: foreach my $proc ( @{$pt} ) { if ( $proc->cmndline =~ m/^$x\s*$/ ) { $p_found = 1; last PROC; } } say "\t${p} ", $p_found ? 'UP' : 'DOWN'; return 1; } return 0; }); say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) if @unprocessed_params; }, ); =begin private =head1 PRIVATE METHODS =head2 proxy_do my @unprocessed_params = proxy_do(sub { my ($proxy, $cmd) = @_; say "$proxy, $cmd"; }); Invokes the supplied method, passing in the name of the proxy and the command as parsed from the FoxyProxy configuration. =cut sub proxy_do { my $func = shift; my $fp = get_fp_cfg(); my @processed; foreach my $p ( keys( %{$fp->{'proxies'}{'proxy'}} ) ) { if ( $fp->{'proxies'}{'proxy'}{$p}{'notes'} =~ $command_re ) { push @processed, $p if $func->($p, $1); } } # From http://www.perlmonks.org/?node_id=153402 # TODO: relearn what this does and document it my @unknown; OUTER: for ( @ARGV ) { last OUTER if $_ eq 'all'; for my $p ( @processed ) { if ( $p eq $_ ) { next OUTER; } } push @unknown, $_; } return @unknown; } =head2 get_fp_cfg my $fp = get_fp_cfg(); Reads and parses FoxyProxy config, returning hashref. =cut sub get_fp_cfg { my $fp; # TODO I don't know why the fuck I did this; seems kind of showy ( sub { $fp ? $fp : $fp = XMLin($conf_path); } )->(); } # From Garick # TODO add this to notes as example of removing element from array by value #sub remove_param { # my $p = shift; # for my $i ( 0..$#ARGV ) { # next unless $ARGV[$i] eq $p; # splice @ARGV, $i, 1, (); # last; # } #} =head2 params_or_usage params_or_usage(); Checks that proxies have been specified in addition to a command, or dies displaying a usage message to stdout. =cut sub params_or_usage { # Remove command name shift @ARGV; # Error if no proxies specified usage() if !@ARGV; } =head3 usage usage(); Displays program usage information to stdout. =cut sub usage { say "Usage: $0 {", ( join '|', keys(%commands) ), '} [all|[proxy_name|proxy_name|...]]'; exit; } =head2 main main(); Invokes main program logic. =cut sub main { usage() unless ( $ARGV[0] && grep {$_ eq $ARGV[0]} keys(%commands) ); # restart is the only command handled # outside of the %commands hash if ( $ARGV[0] eq 'restart' ) { $commands{'stop'}->(); unshift(@ARGV, 'start'); $commands{'start'}->(); } else { $commands{$ARGV[0]}->(); } } main() if $0 eq __FILE__; =end private =cut
dap/App-FoxyProxy-Control
4aabe182a3ac25c9172f102214930aa08eadb5a8
Major refactoring; added POD for private methods and command invocation
diff --git a/bin/fpc.pl b/bin/fpc.pl index acbf4e5..4b47d35 100755 --- a/bin/fpc.pl +++ b/bin/fpc.pl @@ -1,203 +1,283 @@ #!/usr/bin/perl +=head1 NAME + +fpc.pl - Utility to start/stop tunnels parsed from FoxyProxy config + +=head1 SYNOPSIS + + # List available proxies + $ fpc.pl list + + # Start a given proxy + $ fpc.pl start footun + + # Restart a given proxy + $ fpc.pl restart footun + + # Stop a given proxy + $ fpc.pl stop footun + + # Show status of a given proxy + $ fpc.pl status footun + + # Show usage assistance + $ fpc.pl help + +=head1 DESCRIPTION + +WARNING: this program contains a bunch of stuff that I once thought + was really cool and interesting, but now I mostly just find + hard to understand and maintain. This will be addressed + after I complete the test suite. +=cut + use strict; use warnings; use XML::Simple; use Perl6::Say; use Proc::ProcessTable; my $conf_path - = $ENV{'FP_CONF_PATH'}; + = $ENV{'FPC_CONF_PATH'}; my $command_re = qr/^(ssh.*)/; my %commands = ( - 'help' => sub { usage() }, - 'start' => sub { + 'help' => sub { + usage() + }, + 'start' => sub { # Check that params were passed, or exit with usage message params_or_usage(); # Start proxies my @unprocessed_params = proxy_do(sub { my ($p, $x) = @_; if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { say "Starting [$p]: $x"; system(split /\s/, $x); return 1; } return 0; }); say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) if @unprocessed_params; }, - 'stop' => sub { + 'stop' => sub { params_or_usage(); my $pt = (new Proc::ProcessTable)->table(); # Find proxies in process table and stop them my @unprocessed_params = proxy_do(sub { my ($p, $x) = @_; if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { foreach my $proc ( @{$pt} ) { if ( $proc->cmndline =~ m/^$x\s*$/ ) { say "Stopping [$p]: $x"; $proc->kill('TERM'); } } return 1; } return 0; }); say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) if @unprocessed_params; }, 'restart_broken' => sub { params_or_usage(); my $pt = (new Proc::ProcessTable)->table(); # Find proxies in process table and stop them my @unprocessed_params = proxy_do(sub { my ($p, $x) = @_; if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { foreach my $proc ( @{$pt} ) { if ( $proc->cmndline =~ m/^$x\s*$/ ) { say "Stopping [$p]: $x"; $proc->kill('TERM'); say "Starting [$p]: $x"; system(split /\s/, $x); } } return 1; } return 0; }); say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) if @unprocessed_params; }, - 'restart' => sub { # handled elsewhere + 'restart' => sub { # handled elsewhere, but here for inclusion in usage() }, - 'list' => sub { + 'list' => sub { say "Configured Proxies:"; proxy_do(sub { say "\t$_[0]"; }); }, 'status' => sub { params_or_usage(); my $pt = (new Proc::ProcessTable)->table(); say "Proxy Status:"; # Find proxies in process table and stop them my @unprocessed_params = proxy_do(sub { my ($p, $x) = @_; my $p_found = 0; if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { PROC: foreach my $proc ( @{$pt} ) { if ( $proc->cmndline =~ m/^$x\s*$/ ) { $p_found = 1; last PROC; } } say "\t${p} ", $p_found ? 'UP' : 'DOWN'; return 1; } return 0; }); say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) if @unprocessed_params; }, ); -usage() - unless ( $ARGV[0] && grep {$_ eq $ARGV[0]} keys(%commands) ); +=begin private +=head1 PRIVATE METHODS -if ( $ARGV[0] eq 'restart' ) { - $commands{'stop'}->(); - unshift(@ARGV, 'start'); - $commands{'start'}->(); -} -else -{ - $commands{$ARGV[0]}->(); -} +=head2 proxy_do + my @unprocessed_params = proxy_do(sub { + my ($proxy, $cmd) = @_; + say "$proxy, $cmd"; + }); + +Invokes the supplied method, passing in the name of the proxy and the +command as parsed from the FoxyProxy configuration. +=cut sub proxy_do { my $func = shift; my $fp = get_fp_cfg(); my @processed; foreach my $p ( keys( %{$fp->{'proxies'}{'proxy'}} ) ) { if ( $fp->{'proxies'}{'proxy'}{$p}{'notes'} =~ $command_re ) { push @processed, $p if $func->($p, $1); } } # From http://www.perlmonks.org/?node_id=153402 + # TODO: relearn what this does and document it my @unknown; OUTER: for ( @ARGV ) { last OUTER if $_ eq 'all'; for my $p ( @processed ) { if ( $p eq $_ ) { next OUTER; } } push @unknown, $_; } return @unknown; } +=head2 get_fp_cfg + + my $fp = get_fp_cfg(); + +Reads and parses FoxyProxy config, returning hashref. +=cut sub get_fp_cfg { my $fp; + # TODO I don't know why the fuck I did this; seems kind of showy ( sub { $fp ? $fp : $fp = XMLin($conf_path); } )->(); } -sub params_or_usage { - # Remove command name - shift @ARGV; - - # Error if no proxies specified - usage() - if !@ARGV; -} - # From Garick # TODO add this to notes as example of removing element from array by value #sub remove_param { # my $p = shift; # for my $i ( 0..$#ARGV ) { # next unless $ARGV[$i] eq $p; # splice @ARGV, $i, 1, (); # last; # } #} +=head2 params_or_usage + + params_or_usage(); + +Checks that proxies have been specified in addition to a command, or dies +displaying a usage message to stdout. +=cut +sub params_or_usage { + # Remove command name + shift @ARGV; + + # Error if no proxies specified + usage() if !@ARGV; +} + +=head3 usage + + usage(); + +Displays program usage information to stdout. +=cut sub usage { say "Usage: $0 {", ( join '|', keys(%commands) ), '} [all|[proxy_name|proxy_name|...]]'; exit; } +=head2 main + + main(); + +Invokes main program logic. +=cut +sub main { + usage() + unless ( $ARGV[0] && grep {$_ eq $ARGV[0]} keys(%commands) ); + + # restart is the only command handled + # outside of the %commands hash + if ( $ARGV[0] eq 'restart' ) { + $commands{'stop'}->(); + unshift(@ARGV, 'start'); + $commands{'start'}->(); + } + else { + $commands{$ARGV[0]}->(); + } +} + +main() if $0 eq __FILE__; + +=end private +=cut
dap/App-FoxyProxy-Control
6614c857b38ef20e523c8587999f64d0401fe48f
Added existing fpc.pl
diff --git a/bin/fpc.pl b/bin/fpc.pl new file mode 100755 index 0000000..acbf4e5 --- /dev/null +++ b/bin/fpc.pl @@ -0,0 +1,203 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +use XML::Simple; +use Perl6::Say; +use Proc::ProcessTable; + +my $conf_path + = $ENV{'FP_CONF_PATH'}; +my $command_re + = qr/^(ssh.*)/; + +my %commands = ( + 'help' => sub { usage() }, + 'start' => sub { + # Check that params were passed, or exit with usage message + params_or_usage(); + + # Start proxies + my @unprocessed_params = proxy_do(sub { + my ($p, $x) = @_; + + if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { + say "Starting [$p]: $x"; + system(split /\s/, $x); + return 1; + } + + return 0; + }); + + say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) + if @unprocessed_params; + }, + 'stop' => sub { + params_or_usage(); + + my $pt = (new Proc::ProcessTable)->table(); + + # Find proxies in process table and stop them + my @unprocessed_params = proxy_do(sub { + my ($p, $x) = @_; + + if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { + foreach my $proc ( @{$pt} ) { + if ( $proc->cmndline =~ m/^$x\s*$/ ) { + say "Stopping [$p]: $x"; + $proc->kill('TERM'); + } + } + return 1; + } + + return 0; + }); + + say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) + if @unprocessed_params; + }, + 'restart_broken' => sub { + params_or_usage(); + + my $pt = (new Proc::ProcessTable)->table(); + + # Find proxies in process table and stop them + my @unprocessed_params = proxy_do(sub { + my ($p, $x) = @_; + + if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { + foreach my $proc ( @{$pt} ) { + if ( $proc->cmndline =~ m/^$x\s*$/ ) { + say "Stopping [$p]: $x"; + $proc->kill('TERM'); + say "Starting [$p]: $x"; + system(split /\s/, $x); + } + } + return 1; + } + + return 0; + }); + + say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) + if @unprocessed_params; + }, + 'restart' => sub { # handled elsewhere + }, + 'list' => sub { + say "Configured Proxies:"; + + proxy_do(sub { + say "\t$_[0]"; + }); + }, + 'status' => sub { + params_or_usage(); + + my $pt = (new Proc::ProcessTable)->table(); + + say "Proxy Status:"; + + # Find proxies in process table and stop them + my @unprocessed_params = proxy_do(sub { + my ($p, $x) = @_; + + my $p_found = 0; + + if ( $ARGV[0] eq 'all' || grep {$_ eq $p} @ARGV ) { + PROC: foreach my $proc ( @{$pt} ) { + if ( $proc->cmndline =~ m/^$x\s*$/ ) { + $p_found = 1; + last PROC; + } + } + say "\t${p} ", $p_found ? 'UP' : 'DOWN'; + return 1; + } + + return 0; + }); + + say 'Warning: No proxy definition found for ', join(' ', @unprocessed_params) + if @unprocessed_params; + }, +); + +usage() + unless ( $ARGV[0] && grep {$_ eq $ARGV[0]} keys(%commands) ); + +if ( $ARGV[0] eq 'restart' ) { + $commands{'stop'}->(); + unshift(@ARGV, 'start'); + $commands{'start'}->(); +} +else +{ + $commands{$ARGV[0]}->(); +} + +sub proxy_do { + my $func = shift; + my $fp = get_fp_cfg(); + my @processed; + + foreach my $p ( keys( %{$fp->{'proxies'}{'proxy'}} ) ) { + if ( $fp->{'proxies'}{'proxy'}{$p}{'notes'} =~ $command_re ) { + push @processed, $p + if $func->($p, $1); + } + } + + # From http://www.perlmonks.org/?node_id=153402 + my @unknown; + OUTER: + for ( @ARGV ) { + last OUTER + if $_ eq 'all'; + for my $p ( @processed ) { + if ( $p eq $_ ) { + next OUTER; + } + } + push @unknown, $_; + } + + return @unknown; +} + +sub get_fp_cfg { + my $fp; + ( sub { $fp ? $fp : $fp = XMLin($conf_path); } )->(); +} + +sub params_or_usage { + # Remove command name + shift @ARGV; + + # Error if no proxies specified + usage() + if !@ARGV; +} + +# From Garick +# TODO add this to notes as example of removing element from array by value +#sub remove_param { +# my $p = shift; +# for my $i ( 0..$#ARGV ) { +# next unless $ARGV[$i] eq $p; +# splice @ARGV, $i, 1, (); +# last; +# } +#} + +sub usage { + say "Usage: $0 {", + ( join '|', keys(%commands) ), + '} [all|[proxy_name|proxy_name|...]]'; + exit; +} +
mleung/Sex
c3b741325d9fbfb3a973e0ff5f356999d27b420c
Used gsub! in strip_markup! instead of gsub
diff --git a/lib/sex/string_pattern_extensions.rb b/lib/sex/string_pattern_extensions.rb index fd0b54d..f5021ae 100644 --- a/lib/sex/string_pattern_extensions.rb +++ b/lib/sex/string_pattern_extensions.rb @@ -1,38 +1,38 @@ module Sex module StringPatternExtensions String.class_eval do include Sex::Expressions def starts_with?(what) matches?(starts_with_exp(what)) end def ends_with?(what) matches?(ends_with_exp(what)) end def contains?(what, case_sensitive = false) matches?(contains_exp(what, case_sensitive)) end def contains_a_number? matches?(/\d/) end def extract_grouped_numbers scan(/\d+/) end def strip_markup! - gsub(/<\/?[^>]*>/, "") + gsub!(/<\/?[^>]*>/, "") end private def matches?(pattern) !match(pattern).nil? end end end end \ No newline at end of file
mleung/Sex
9ffd3efa61bf4917a9e31c12c722ffbbc0458e8f
Changed remove_markup to strip_markup!
diff --git a/lib/sex/string_pattern_extensions.rb b/lib/sex/string_pattern_extensions.rb index d9e781b..fd0b54d 100644 --- a/lib/sex/string_pattern_extensions.rb +++ b/lib/sex/string_pattern_extensions.rb @@ -1,38 +1,38 @@ module Sex module StringPatternExtensions String.class_eval do include Sex::Expressions def starts_with?(what) matches?(starts_with_exp(what)) end def ends_with?(what) matches?(ends_with_exp(what)) end def contains?(what, case_sensitive = false) matches?(contains_exp(what, case_sensitive)) end def contains_a_number? matches?(/\d/) end def extract_grouped_numbers scan(/\d+/) end - def remove_markup + def strip_markup! gsub(/<\/?[^>]*>/, "") end private def matches?(pattern) !match(pattern).nil? end end end end \ No newline at end of file diff --git a/spec/sex/string_pattern_extensions_spec.rb b/spec/sex/string_pattern_extensions_spec.rb index c91b0e2..16b1d1c 100644 --- a/spec/sex/string_pattern_extensions_spec.rb +++ b/spec/sex/string_pattern_extensions_spec.rb @@ -1,100 +1,100 @@ require File.dirname(__FILE__) + '/../spec_helper' describe Sex::StringPatternExtensions, "starts_with?" do before(:all) do @url = "http://www.sex.com" end it "should return true for a valid condition" do @url.starts_with?("http://").should eql(true) end it "should return false for an invalid condition" do @url.starts_with?("sex").should eql(false) end end describe Sex::StringPatternExtensions, "ends_with?" do before(:all) do @url = "http://www.sex.com" end it "should return true for a valid condition" do @url.ends_with?(".com").should eql(true) end it "should return false for an invalid condition" do @url.ends_with?(".tv").should eql(false) end end describe Sex::StringPatternExtensions, "contains?" do before(:all) do @phrase = "sex is hot" end it "should return true for a valid condition" do @phrase.contains?('hot').should eql(true) end it "should return false for an invalid condition" do @phrase.contains?('pumpernickel').should eql(false) end it "should return false if case is set, and the case does not match" do @phrase.contains?('HOT', true).should eql(false) end end describe Sex::StringPatternExtensions, "contains_a_number?" do it "should return true if a number is present" do "ABC123".contains_a_number?.should eql(true) end it "should return false if it's a purely alpha sequence" do "this does not have a number".contains_a_number?.should eql(false) end end describe Sex::StringPatternExtensions, "extract_grouped_numbers" do it "should return an array of numbers" do "123 comes before 456".extract_grouped_numbers.should eql(["123", "456"]) end it "should return an empty array for strings with no numbers" do "this is alpha only, isn't it?".extract_grouped_numbers.should eql([]) end end describe Sex::StringPatternExtensions, "number_of_alpha_characters" do it "should return the proper number of characters" do pending do "abcdefghijklmnopqrstuvwxyz1".number_of_alpha_characters.should eql(26) end end end describe Sex::StringPatternExtensions, "number_of_numeric_characters" do it "should return the proper amount of numbers" end -describe Sex::StringPatternExtensions, "remove_markup" do +describe Sex::StringPatternExtensions, "strip_markup!" do it "should totally remove any markup tags" do - "<bold>Text</bold>".remove_markup.should eql("Text") + "<bold>Text</bold>".strip_markup!.should eql("Text") end end
mleung/Sex
8ae84bc5937a11b1100fbd1a53d00ed454067193
Put in the remove_markup method to gsub out any html or xml tags from a string instance
diff --git a/lib/sex/string_pattern_extensions.rb b/lib/sex/string_pattern_extensions.rb index 2b2947f..d9e781b 100644 --- a/lib/sex/string_pattern_extensions.rb +++ b/lib/sex/string_pattern_extensions.rb @@ -1,34 +1,38 @@ module Sex module StringPatternExtensions String.class_eval do include Sex::Expressions def starts_with?(what) matches?(starts_with_exp(what)) end def ends_with?(what) matches?(ends_with_exp(what)) end def contains?(what, case_sensitive = false) matches?(contains_exp(what, case_sensitive)) end def contains_a_number? matches?(/\d/) end def extract_grouped_numbers scan(/\d+/) end + def remove_markup + gsub(/<\/?[^>]*>/, "") + end + private def matches?(pattern) !match(pattern).nil? end end end end \ No newline at end of file diff --git a/spec/sex/string_pattern_extensions_spec.rb b/spec/sex/string_pattern_extensions_spec.rb index 2e6d53a..c91b0e2 100644 --- a/spec/sex/string_pattern_extensions_spec.rb +++ b/spec/sex/string_pattern_extensions_spec.rb @@ -1,92 +1,100 @@ require File.dirname(__FILE__) + '/../spec_helper' describe Sex::StringPatternExtensions, "starts_with?" do before(:all) do @url = "http://www.sex.com" end it "should return true for a valid condition" do @url.starts_with?("http://").should eql(true) end it "should return false for an invalid condition" do @url.starts_with?("sex").should eql(false) end end describe Sex::StringPatternExtensions, "ends_with?" do before(:all) do @url = "http://www.sex.com" end it "should return true for a valid condition" do @url.ends_with?(".com").should eql(true) end it "should return false for an invalid condition" do @url.ends_with?(".tv").should eql(false) end end describe Sex::StringPatternExtensions, "contains?" do before(:all) do @phrase = "sex is hot" end it "should return true for a valid condition" do @phrase.contains?('hot').should eql(true) end it "should return false for an invalid condition" do @phrase.contains?('pumpernickel').should eql(false) end it "should return false if case is set, and the case does not match" do @phrase.contains?('HOT', true).should eql(false) end end describe Sex::StringPatternExtensions, "contains_a_number?" do it "should return true if a number is present" do "ABC123".contains_a_number?.should eql(true) end it "should return false if it's a purely alpha sequence" do "this does not have a number".contains_a_number?.should eql(false) end end describe Sex::StringPatternExtensions, "extract_grouped_numbers" do it "should return an array of numbers" do "123 comes before 456".extract_grouped_numbers.should eql(["123", "456"]) end it "should return an empty array for strings with no numbers" do "this is alpha only, isn't it?".extract_grouped_numbers.should eql([]) end end describe Sex::StringPatternExtensions, "number_of_alpha_characters" do it "should return the proper number of characters" do pending do "abcdefghijklmnopqrstuvwxyz1".number_of_alpha_characters.should eql(26) end end end describe Sex::StringPatternExtensions, "number_of_numeric_characters" do it "should return the proper amount of numbers" end + +describe Sex::StringPatternExtensions, "remove_markup" do + + it "should totally remove any markup tags" do + "<bold>Text</bold>".remove_markup.should eql("Text") + end + +end
mleung/Sex
e2aca633c9154d71d74266d6d04ec3ab24e11851
Quick rename of test name
diff --git a/test/sex/expressions_test.rb b/test/sex/expressions_test.rb index 25006ea..3d642d9 100644 --- a/test/sex/expressions_test.rb +++ b/test/sex/expressions_test.rb @@ -1,13 +1,13 @@ require File.dirname(__FILE__) + '/../test_helper' class ExpressionsTest < Test::Unit::TestCase context "Starts with Expression" do - should "Be the correct Regexp" do + should "be the correct regexp" do assert_equal starts_with_exp("http://"), Regexp.new("^http:\/\/") end end end
mleung/Sex
f837d05f8162602394250842b809dd236d804be1
Starting to convert rspecs to shoulda
diff --git a/Rakefile b/Rakefile index 5404dd6..398c2f4 100644 --- a/Rakefile +++ b/Rakefile @@ -1,20 +1,20 @@ spec = Gem::Specification.new do |s| s.name = "Sex" s.version = "0.0.1" s.author = "Michael Leung" s.email = "[email protected]" s.homepage = "" s.platform = Gem::Platform::RUBY s.summary = "Sex is a ruby library created to replace Regexp with a rubyish syntax." s.files = FileList["{bin,lib}/**/*"].to_a s.require_path = "lib" s.autorequire = "name" s.test_files = FileList["{test}/**/*test.rb"].to_a s.has_rdoc = true s.extra_rdoc_files = ["README"] - s.add_dependency("dependency", ">= 0.x.x") + # s.add_dependency("dependency", ">= 0.x.x") end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_tar = true end \ No newline at end of file diff --git a/spec/sex/expressions_spec.rb b/spec_obsolete/sex/expressions_spec.rb similarity index 100% rename from spec/sex/expressions_spec.rb rename to spec_obsolete/sex/expressions_spec.rb diff --git a/spec/sex/string_pattern_extensions_spec.rb b/spec_obsolete/sex/string_pattern_extensions_spec.rb similarity index 100% rename from spec/sex/string_pattern_extensions_spec.rb rename to spec_obsolete/sex/string_pattern_extensions_spec.rb diff --git a/spec/spec_helper.rb b/spec_obsolete/spec_helper.rb similarity index 100% rename from spec/spec_helper.rb rename to spec_obsolete/spec_helper.rb diff --git a/test/sex/expressions_test.rb b/test/sex/expressions_test.rb new file mode 100644 index 0000000..25006ea --- /dev/null +++ b/test/sex/expressions_test.rb @@ -0,0 +1,13 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class ExpressionsTest < Test::Unit::TestCase + + context "Starts with Expression" do + + should "Be the correct Regexp" do + assert_equal starts_with_exp("http://"), Regexp.new("^http:\/\/") + end + + end + +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..af1faa8 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,6 @@ +$:.push File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) + +require 'rubygems' +require 'sex' +require 'test/unit' +require 'shoulda'
kernow/javascript_auto_include
51fc7b187fd9986349c08a1890a0a4c035b6fb16
removed out of date svn link
diff --git a/README b/README index f645fa1..0b77996 100644 --- a/README +++ b/README @@ -1,57 +1,54 @@ JavascriptAutoInclude ===================== == Resources Install - * Run the following command: - script/plugin install http://kernowsoul.com/svn/plugins/javascript_auto_include - - * On rails 2.1 and above you can run + * On rails 2.1 and above run script/plugin install git://github.com/kernow/javascript_auto_include.git == Usage Add the following to the head of your template file <%= javascript_auto_include_tags %> Now each time the template is loaded javascript files in the public/javascripts/views folder that correspond to the name of the current controller or view will be auto loaded. It's also possible for the same javascript file to be loaded by multiple views by adding the name of each view to the filename separated by the "-" character, e.g. to load a javascript file in the new and edit views create a file named new-edit.js. Any number of views can be strung together using this naming convention. For example: /public /javascripts /views users.js /users edit.js roles.js /accounts show-new-edit-create.js show.js Assuming the above file structure loading each of the following urls would include: mydomain.com/users # includes users.js mydomain.com/users/edit/1 # includes users.js and edit.js mydomain.com/users/show/1 # includes users.js mydomain.com/roles # includes roles.js mydomain.com/accounts # no files included mydomain.com/accounts/show/1 # includes show.js and show-new-edit-create.js mydomain.com/accounts/new # includes show-new-edit-create.js mydomain.com/accounts/edit/1 # includes show-new-edit-create.js mydomain.com/accounts/create # includes show-new-edit-create.js == More http://kernowsoul.com/page/javascript_auto_include == Acknowledgements Thanks to geoffgarside http://github.com/geoffgarside for also creating a version that can include the same file in multiple views. Some of the code comments are from his version as they are more concise than mine. \ No newline at end of file
kernow/javascript_auto_include
ab4191fbcb1080ce2daa2ddcef42cef284b4161e
Allow use of namespaced controllers - e.g. javascripts/views/admin/items/index.js
diff --git a/lib/javascript_auto_include.rb b/lib/javascript_auto_include.rb index 1c6d0a0..bd79505 100644 --- a/lib/javascript_auto_include.rb +++ b/lib/javascript_auto_include.rb @@ -1,52 +1,52 @@ module ActionView module Helpers module AssetTagHelper # Checks for the existence of view related javaScripts and # includes them based on current controller and action name. # # Supports the following include options # Given: controller_name => "users", action_name => "new" # # The following files will be checked for # 1. public/javascripts/views/users.js # 2. public/javascripts/views/users/new.js # 3. public/javascripts/views/users/new-*.js # 4. public/javascripts/views/users/*-new.js # 5. public/javascripts/views/users/*-new-*.js # # This allows javascript files to be shared between multiple views # an unlimited number of views can be stringed together e.g. # new-edit-index.js would be included in the new, edit, and index views @@jsai_path = "#{RAILS_ROOT}/public/javascripts/views" @@jsai_ext = '.js' @@jsai_url = 'views' @@jsai_delimiter = '-' @@jsai_paths = [] def javascript_auto_include_tags @@jsai_paths = [] return unless File.directory? @@jsai_path if File.exists?(File.join(@@jsai_path, controller.controller_name + @@jsai_ext)) @@jsai_paths.push(File.join(@@jsai_url, controller.controller_name)) end - search_dir(controller.controller_name, controller.action_name) + search_dir(controller.controller_path, controller.action_name) javascript_include_tag *@@jsai_paths end private def search_dir(cont, action) dir = File.join(@@jsai_path, cont) return unless File.directory? dir Dir.new(dir).each do |file| if File.extname(file) == @@jsai_ext file.split(@@jsai_delimiter).collect do |part| @@jsai_paths.push(File.join(@@jsai_url, cont, file)) if File.basename(part, @@jsai_ext) == action end end end end end end end \ No newline at end of file
kernow/javascript_auto_include
d4f0418efffb698539c4ec46921ae39408290c83
Added splat operator for rails 2.x compatibility, submitted by davidsch
diff --git a/lib/javascript_auto_include.rb b/lib/javascript_auto_include.rb index ea29a21..1c6d0a0 100644 --- a/lib/javascript_auto_include.rb +++ b/lib/javascript_auto_include.rb @@ -1,52 +1,52 @@ module ActionView module Helpers module AssetTagHelper # Checks for the existence of view related javaScripts and # includes them based on current controller and action name. # # Supports the following include options # Given: controller_name => "users", action_name => "new" # # The following files will be checked for # 1. public/javascripts/views/users.js # 2. public/javascripts/views/users/new.js # 3. public/javascripts/views/users/new-*.js # 4. public/javascripts/views/users/*-new.js # 5. public/javascripts/views/users/*-new-*.js # # This allows javascript files to be shared between multiple views # an unlimited number of views can be stringed together e.g. # new-edit-index.js would be included in the new, edit, and index views @@jsai_path = "#{RAILS_ROOT}/public/javascripts/views" @@jsai_ext = '.js' @@jsai_url = 'views' @@jsai_delimiter = '-' @@jsai_paths = [] def javascript_auto_include_tags @@jsai_paths = [] return unless File.directory? @@jsai_path if File.exists?(File.join(@@jsai_path, controller.controller_name + @@jsai_ext)) @@jsai_paths.push(File.join(@@jsai_url, controller.controller_name)) end search_dir(controller.controller_name, controller.action_name) - javascript_include_tag @@jsai_paths + javascript_include_tag *@@jsai_paths end private def search_dir(cont, action) dir = File.join(@@jsai_path, cont) return unless File.directory? dir Dir.new(dir).each do |file| if File.extname(file) == @@jsai_ext file.split(@@jsai_delimiter).collect do |part| @@jsai_paths.push(File.join(@@jsai_url, cont, file)) if File.basename(part, @@jsai_ext) == action end end end end end end end \ No newline at end of file
kernow/javascript_auto_include
d8ab2275687d29343be42e0180d6261a5221fad7
Changed plugin to work better with different namespaces
diff --git a/lib/javascript_auto_include.rb b/lib/javascript_auto_include.rb index ea29a21..5c9fe92 100644 --- a/lib/javascript_auto_include.rb +++ b/lib/javascript_auto_include.rb @@ -1,52 +1,52 @@ module ActionView module Helpers module AssetTagHelper # Checks for the existence of view related javaScripts and # includes them based on current controller and action name. # # Supports the following include options # Given: controller_name => "users", action_name => "new" # # The following files will be checked for # 1. public/javascripts/views/users.js # 2. public/javascripts/views/users/new.js # 3. public/javascripts/views/users/new-*.js # 4. public/javascripts/views/users/*-new.js # 5. public/javascripts/views/users/*-new-*.js # # This allows javascript files to be shared between multiple views # an unlimited number of views can be stringed together e.g. # new-edit-index.js would be included in the new, edit, and index views @@jsai_path = "#{RAILS_ROOT}/public/javascripts/views" @@jsai_ext = '.js' @@jsai_url = 'views' @@jsai_delimiter = '-' @@jsai_paths = [] def javascript_auto_include_tags @@jsai_paths = [] return unless File.directory? @@jsai_path - if File.exists?(File.join(@@jsai_path, controller.controller_name + @@jsai_ext)) - @@jsai_paths.push(File.join(@@jsai_url, controller.controller_name)) + if File.exists?(File.join(@@jsai_path, controller.controller_path + @@jsai_ext)) + @@jsai_paths.push(File.join(@@jsai_url, controller.controller_path)) end search_dir(controller.controller_name, controller.action_name) javascript_include_tag @@jsai_paths end private def search_dir(cont, action) dir = File.join(@@jsai_path, cont) return unless File.directory? dir Dir.new(dir).each do |file| if File.extname(file) == @@jsai_ext file.split(@@jsai_delimiter).collect do |part| @@jsai_paths.push(File.join(@@jsai_url, cont, file)) if File.basename(part, @@jsai_ext) == action end end end end end end end \ No newline at end of file
kernow/javascript_auto_include
7da57f4542ee1e9d04f950e6463dd136d12fe090
re-factored code
diff --git a/lib/javascript_auto_include.rb b/lib/javascript_auto_include.rb index 0d4c256..ea29a21 100644 --- a/lib/javascript_auto_include.rb +++ b/lib/javascript_auto_include.rb @@ -1,53 +1,52 @@ module ActionView module Helpers module AssetTagHelper # Checks for the existence of view related javaScripts and # includes them based on current controller and action name. # # Supports the following include options # Given: controller_name => "users", action_name => "new" # # The following files will be checked for # 1. public/javascripts/views/users.js # 2. public/javascripts/views/users/new.js # 3. public/javascripts/views/users/new-*.js # 4. public/javascripts/views/users/*-new.js # 5. public/javascripts/views/users/*-new-*.js # # This allows javascript files to be shared between multiple views # an unlimited number of views can be stringed together e.g. # new-edit-index.js would be included in the new, edit, and index views @@jsai_path = "#{RAILS_ROOT}/public/javascripts/views" @@jsai_ext = '.js' @@jsai_url = 'views' @@jsai_delimiter = '-' + @@jsai_paths = [] def javascript_auto_include_tags + @@jsai_paths = [] return unless File.directory? @@jsai_path - paths = [] if File.exists?(File.join(@@jsai_path, controller.controller_name + @@jsai_ext)) - paths.push(File.join(@@jsai_url, controller.controller_name)) + @@jsai_paths.push(File.join(@@jsai_url, controller.controller_name)) end - paths.push(search_dir(controller.controller_name, controller.action_name)) - javascript_include_tag paths + search_dir(controller.controller_name, controller.action_name) + javascript_include_tag @@jsai_paths end private - def search_dir(controller, action) - dir = File.join(@@jsai_path, controller) + def search_dir(cont, action) + dir = File.join(@@jsai_path, cont) return unless File.directory? dir - paths = [] Dir.new(dir).each do |file| if File.extname(file) == @@jsai_ext file.split(@@jsai_delimiter).collect do |part| - paths.push(File.join(@@jsai_url, controller, file)) if File.basename(part, @@jsai_ext) == action + @@jsai_paths.push(File.join(@@jsai_url, cont, file)) if File.basename(part, @@jsai_ext) == action end end end - return paths end end end end \ No newline at end of file
kernow/javascript_auto_include
3f1f8ad3df87f0759375d1ee7cadf8b87481c27c
changed variables to avoid naming conflicts
diff --git a/lib/javascript_auto_include.rb b/lib/javascript_auto_include.rb index cc4f1a8..0d4c256 100644 --- a/lib/javascript_auto_include.rb +++ b/lib/javascript_auto_include.rb @@ -1,53 +1,53 @@ module ActionView module Helpers module AssetTagHelper # Checks for the existence of view related javaScripts and # includes them based on current controller and action name. # # Supports the following include options # Given: controller_name => "users", action_name => "new" # # The following files will be checked for # 1. public/javascripts/views/users.js # 2. public/javascripts/views/users/new.js # 3. public/javascripts/views/users/new-*.js # 4. public/javascripts/views/users/*-new.js # 5. public/javascripts/views/users/*-new-*.js # # This allows javascript files to be shared between multiple views # an unlimited number of views can be stringed together e.g. # new-edit-index.js would be included in the new, edit, and index views - @@js_path = "#{RAILS_ROOT}/public/javascripts/views" - @@js_ext = '.js' - @@js_url = 'views' - @@delimiter = '-' + @@jsai_path = "#{RAILS_ROOT}/public/javascripts/views" + @@jsai_ext = '.js' + @@jsai_url = 'views' + @@jsai_delimiter = '-' def javascript_auto_include_tags - return unless File.directory? @@js_path + return unless File.directory? @@jsai_path paths = [] - if File.exists?(File.join(@@js_path, controller.controller_name + @@js_ext)) - paths.push(File.join(@@js_url, controller.controller_name)) + if File.exists?(File.join(@@jsai_path, controller.controller_name + @@jsai_ext)) + paths.push(File.join(@@jsai_url, controller.controller_name)) end paths.push(search_dir(controller.controller_name, controller.action_name)) javascript_include_tag paths end private def search_dir(controller, action) - dir = File.join(@@js_path, controller) + dir = File.join(@@jsai_path, controller) return unless File.directory? dir paths = [] Dir.new(dir).each do |file| - if File.extname(file) == @@js_ext - file.split(@@delimiter).collect do |part| - paths.push(File.join(@@js_url, controller, file)) if File.basename(part, @@js_ext) == action + if File.extname(file) == @@jsai_ext + file.split(@@jsai_delimiter).collect do |part| + paths.push(File.join(@@jsai_url, controller, file)) if File.basename(part, @@jsai_ext) == action end end end return paths end end end end \ No newline at end of file
kernow/javascript_auto_include
efd069f7e2f71512ec269f813974eb95d15516a6
added functionality to include js files in multiple views
diff --git a/lib/javascript_auto_include.rb b/lib/javascript_auto_include.rb index 9dfa770..cc4f1a8 100644 --- a/lib/javascript_auto_include.rb +++ b/lib/javascript_auto_include.rb @@ -1,13 +1,53 @@ module ActionView module Helpers module AssetTagHelper + # Checks for the existence of view related javaScripts and + # includes them based on current controller and action name. + # + # Supports the following include options + # Given: controller_name => "users", action_name => "new" + # + # The following files will be checked for + # 1. public/javascripts/views/users.js + # 2. public/javascripts/views/users/new.js + # 3. public/javascripts/views/users/new-*.js + # 4. public/javascripts/views/users/*-new.js + # 5. public/javascripts/views/users/*-new-*.js + # + # This allows javascript files to be shared between multiple views + # an unlimited number of views can be stringed together e.g. + # new-edit-index.js would be included in the new, edit, and index views + + @@js_path = "#{RAILS_ROOT}/public/javascripts/views" + @@js_ext = '.js' + @@js_url = 'views' + @@delimiter = '-' + def javascript_auto_include_tags - js_path = "#{RAILS_ROOT}/public/javascripts/views" - if File.directory? js_path - paths = [controller.controller_name, File.join(controller.controller_name, controller.action_name)] - paths.collect { |source| javascript_include_tag("views/#{source}") if File.exist?(File.join(js_path, "#{source}.js")) }.join("\n") + return unless File.directory? @@js_path + paths = [] + if File.exists?(File.join(@@js_path, controller.controller_name + @@js_ext)) + paths.push(File.join(@@js_url, controller.controller_name)) end + paths.push(search_dir(controller.controller_name, controller.action_name)) + javascript_include_tag paths end + + private + def search_dir(controller, action) + dir = File.join(@@js_path, controller) + return unless File.directory? dir + paths = [] + Dir.new(dir).each do |file| + if File.extname(file) == @@js_ext + file.split(@@delimiter).collect do |part| + paths.push(File.join(@@js_url, controller, file)) if File.basename(part, @@js_ext) == action + end + end + end + return paths + end + end end end \ No newline at end of file
kernow/javascript_auto_include
ace1b59b2ec4da9137bdd548f48c4acc0813244e
Changed README to include git install
diff --git a/README b/README index f3670a3..9aebef3 100644 --- a/README +++ b/README @@ -1,41 +1,44 @@ JavascriptAutoInclude ===================== == Resources Install * Run the following command: script/plugin install http://kernowsoul.com/svn/plugins/javascript_auto_include + + * On EDGE rails you can run + script/plugin install git://github.com/kernow/javascript_auto_include.git == Usage Add the following to the head of your template file <%= javascript_auto_include_tags %> Now each time the template is loaded javascript files in the public/javascripts/views folder that correspond to the name of the current controller or view will be auto loaded. For example: /public /javascripts /views users.js /users edit.js roles.js /accounts show.js Assuming the above file structure loading each of the following urls would load: mydomain.com/users # loads users.js mydomain.com/users/edit/1 # loads users.js and edit.js mydomain.com/users/show/1 # loads users.js mydomain.com/roles # loads roles.js mydomain.com/accounts # no js files loaded mydomain.com/accounts/show/1 # loads show.js == More http://hosting.media72.co.uk/blog/ \ No newline at end of file
kernow/javascript_auto_include
666c3846548722b6ee20dd5b1e9c9299689d7840
put file back
diff --git a/tasks/javascript_auto_include_tasks.rake b/tasks/javascript_auto_include_tasks.rake new file mode 100644 index 0000000..a19a38b --- /dev/null +++ b/tasks/javascript_auto_include_tasks.rake @@ -0,0 +1,4 @@ +# desc "Explaining what the task does" +# task :javascript_auto_include do +# # Task goes here +# end \ No newline at end of file
kernow/javascript_auto_include
1821253b503d2276eb71775fc62edc7411ea1781
fixed javascript file path in install.rb
diff --git a/install.rb b/install.rb index d9234c8..4c67228 100644 --- a/install.rb +++ b/install.rb @@ -1,3 +1,3 @@ require 'fileutils' -FileUtils.mkdir File.dirname(__FILE__) + '/../../../public/views' \ No newline at end of file +FileUtils.mkdir File.dirname(__FILE__) + '/../../../public/javascripts/views' \ No newline at end of file
kernow/javascript_auto_include
d121504a8689331cb1bb0290177f47831840c41d
git-svn-id: http://kernowsoul.com/svn/plugins/javascript_auto_include@1 581f9dff-63f6-4202-9a23-85763b9ce6d8
diff --git a/README b/README new file mode 100644 index 0000000..f3670a3 --- /dev/null +++ b/README @@ -0,0 +1,41 @@ +JavascriptAutoInclude +===================== + +== Resources + +Install + * Run the following command: + script/plugin install http://kernowsoul.com/svn/plugins/javascript_auto_include + +== Usage + + Add the following to the head of your template file + + <%= javascript_auto_include_tags %> + + Now each time the template is loaded javascript files in the public/javascripts/views + folder that correspond to the name of the current controller or view will be auto + loaded. For example: + + /public + /javascripts + /views + users.js + /users + edit.js + roles.js + /accounts + show.js + + Assuming the above file structure loading each of the following urls would load: + + mydomain.com/users # loads users.js + mydomain.com/users/edit/1 # loads users.js and edit.js + mydomain.com/users/show/1 # loads users.js + mydomain.com/roles # loads roles.js + mydomain.com/accounts # no js files loaded + mydomain.com/accounts/show/1 # loads show.js + +== More + +http://hosting.media72.co.uk/blog/ \ No newline at end of file diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..30ba23c --- /dev/null +++ b/Rakefile @@ -0,0 +1,22 @@ +require 'rake' +require 'rake/testtask' +require 'rake/rdoctask' + +desc 'Default: run unit tests.' +task :default => :test + +desc 'Test the javascript_auto_include plugin.' +Rake::TestTask.new(:test) do |t| + t.libs << 'lib' + t.pattern = 'test/**/*_test.rb' + t.verbose = true +end + +desc 'Generate documentation for the javascript_auto_include plugin.' +Rake::RDocTask.new(:rdoc) do |rdoc| + rdoc.rdoc_dir = 'rdoc' + rdoc.title = 'JavascriptAutoInclude' + 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..52c2949 --- /dev/null +++ b/init.rb @@ -0,0 +1 @@ +require 'javascript_auto_include' \ No newline at end of file diff --git a/install.rb b/install.rb new file mode 100644 index 0000000..d9234c8 --- /dev/null +++ b/install.rb @@ -0,0 +1,3 @@ +require 'fileutils' + +FileUtils.mkdir File.dirname(__FILE__) + '/../../../public/views' \ No newline at end of file diff --git a/lib/javascript_auto_include.rb b/lib/javascript_auto_include.rb new file mode 100644 index 0000000..9dfa770 --- /dev/null +++ b/lib/javascript_auto_include.rb @@ -0,0 +1,13 @@ +module ActionView + module Helpers + module AssetTagHelper + def javascript_auto_include_tags + js_path = "#{RAILS_ROOT}/public/javascripts/views" + if File.directory? js_path + paths = [controller.controller_name, File.join(controller.controller_name, controller.action_name)] + paths.collect { |source| javascript_include_tag("views/#{source}") if File.exist?(File.join(js_path, "#{source}.js")) }.join("\n") + end + end + end + end +end \ No newline at end of file diff --git a/tasks/javascript_auto_include_tasks.rake b/tasks/javascript_auto_include_tasks.rake new file mode 100644 index 0000000..a19a38b --- /dev/null +++ b/tasks/javascript_auto_include_tasks.rake @@ -0,0 +1,4 @@ +# desc "Explaining what the task does" +# task :javascript_auto_include do +# # Task goes here +# end \ No newline at end of file diff --git a/test/javascript_auto_include_test.rb b/test/javascript_auto_include_test.rb new file mode 100644 index 0000000..331c472 --- /dev/null +++ b/test/javascript_auto_include_test.rb @@ -0,0 +1,8 @@ +require 'test/unit' + +class JavascriptAutoIncludeTest < Test::Unit::TestCase + # Replace this with your real tests. + def test_this_plugin + flunk + end +end 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
mminer/silverscreen
8efe8a82db6d75843a3b06a26e29440257370c54
Add note about other options in the Asset Store.
diff --git a/README.md b/README.md index f5c40ec..bc2448c 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,42 @@ Silver Screen ============= Editor tools for creating cinematics using the Unity game engine. +I haven't updated this in ages. If you're looking for a cutscene editor, there +are numerous good options on the Asset Store that are more likely to work well +with the latest version of Unity. + Release History --------------- - 0.1 - Initial release - Compatible with Unity 2.6 License ------- All code is released under the MIT license. > Copyright (c) 2010 Matthew Miner > > 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.
mminer/silverscreen
dd82ea6a2ff9b3c7fae0476e73af75328dc4cd6e
Remove hotkey for opening editor window.
diff --git a/Cutscene Ed/Editor/CutsceneEditor.cs b/Cutscene Ed/Editor/CutsceneEditor.cs index 1692f88..78985a3 100755 --- a/Cutscene Ed/Editor/CutsceneEditor.cs +++ b/Cutscene Ed/Editor/CutsceneEditor.cs @@ -1,537 +1,537 @@ /** * Copyright (c) 2010 Matthew Miner - * + * * 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. */ using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// The Cutscene Editor, where tracks and clips can be managed in a fashion similar to non-linear video editors. /// </summary> public class CutsceneEditor : EditorWindow { public static readonly System.Version version = new System.Version(0, 2); public Cutscene scene { get { Object[] scenes = Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel); - + if (scenes.Length == 0) { return null; } - + return scenes[0] as Cutscene; } } public GUISkin style { get; private set; } //ICutsceneGUI options; ICutsceneGUI media; ICutsceneGUI effects; ICutsceneGUI tools; ICutsceneGUI timeline; public static bool CutsceneSelected { get { return Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel).Length > 0; } } public static bool HasPro = SystemInfo.supportsImageEffects; // Icons: public readonly Texture[] mediaIcons = { EditorGUIUtility.LoadRequired("Cutscene Ed/media_shot.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_actor.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_audio.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_subtitle.png") as Texture }; // Timeline: - + public Tool currentTool = Tool.MoveResize; - + public Vector2 timelineScrollPos; public float timelineMin { get; set; } float _timelineZoom = CutsceneTimeline.timelineZoomMin; public float timelineZoom { get { return _timelineZoom; } set { _timelineZoom = Mathf.Clamp(value, CutsceneTimeline.timelineZoomMin, CutsceneTimeline.timelineZoomMax); } } - + CutsceneTrack _selectedTrack; public CutsceneTrack selectedTrack { get { if (_selectedTrack == null) { // If there are no tracks, add a new one if (scene.tracks.Length == 0) { scene.AddTrack(Cutscene.MediaType.Shots); } _selectedTrack = scene.tracks[0]; } return _selectedTrack; } set { _selectedTrack = value; } } public CutsceneClip selectedClip; public DragEvent dragEvent = DragEvent.Move; public CutsceneClip dragClip; // Menu items: /// <summary> /// Adds "Cutscene Editor" to the Window menu. /// </summary> - [MenuItem("Window/Cutscene Editor %9")] + [MenuItem("Window/Cutscene Editor")] public static void OpenEditor () { // Get existing open window or if none, make a new one GetWindow<CutsceneEditor>(false, "Cutscene Editor").Show(); } /// <summary> /// Validates the Cutscene Editor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> - [MenuItem("Window/Cutscene Editor %9", true)] + [MenuItem("Window/Cutscene Editor", true)] static bool ValidateOpenEditor () { return CutsceneSelected; } /// <summary> /// Adds the option to create a cutscene from the GameObject > Create Other menu. /// </summary> /// <returns>The new cutscene.</returns> [MenuItem("GameObject/Create Other/Cutscene")] static void CreateCutscene () { // Create the new cutscene game object GameObject newSceneGO = new GameObject("Cutscene", typeof(Cutscene)); Cutscene newScene = newSceneGO.GetComponent<Cutscene>(); - + // Add some tracks to get the user started newScene.AddTrack(Cutscene.MediaType.Shots); newScene.AddTrack(Cutscene.MediaType.Actors); newScene.AddTrack(Cutscene.MediaType.Audio); newScene.AddTrack(Cutscene.MediaType.Subtitles); // Create the cutscene's media game objects GameObject shots = new GameObject("Shots"); GameObject actors = new GameObject("Actors"); GameObject audio = new GameObject("Audio"); GameObject subtitles = new GameObject("Subtitles"); // Make the media game objects a child of the cutscene shots.transform.parent = newScene.transform; actors.transform.parent = newScene.transform; audio.transform.parent = newScene.transform; subtitles.transform.parent = newScene.transform; // Create the master animation clip AnimationClip masterClip = new AnimationClip(); newScene.masterClip = masterClip; newScene.animation.AddClip(masterClip, "master"); newScene.animation.playAutomatically = false; newScene.animation.wrapMode = WrapMode.Once; EDebug.Log("Cutscene Editor: created a new cutscene"); } /// <summary> /// Adds the option to create a cutscene trigger to the GameObject > Create Other menu. /// </summary> /// <returns>The trigger's collider.</returns> [MenuItem("GameObject/Create Other/Cutscene Trigger")] static Collider CreateCutsceneTrigger () { // Create the new cutscene trigger game object GameObject triggerGO = new GameObject("Cutscene Trigger", typeof(BoxCollider), typeof(CutsceneTrigger)); triggerGO.collider.isTrigger = true; return triggerGO.collider; } /// <summary> /// Adds the option to create a new shot track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Shot")] static void CreateShotTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Shots); } /// <summary> /// Validates the Shot menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Shot", true)] static bool ValidateCreateShotTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new actor track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Actor")] static void CreateActorTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Actors); } /// <summary> /// Validates the Actor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Actor", true)] static bool ValidateCreateActorTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new audio track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Audio")] static void CreateAudioTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Audio); } /// <summary> /// Validates the Audio menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Audio", true)] static bool ValidateCreateAudioTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new subtitle track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Subtitle")] static void CreateSubtitleTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Subtitles); } /// <summary> /// Validates the Subtitle menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Subtitle", true)] static bool ValidateCreateSubtitleTrack () { return CutsceneSelected; } void OnEnable () { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; if (style == null) { Debug.LogError("GUISkin for Cutscene Editor missing"); return; } //options = new CutsceneOptions(this); media = new CutsceneMediaWindow(this); effects = new CutsceneEffectsWindow(this); tools = new CutsceneTools(this); timeline = new CutsceneTimeline(this); } /// <summary> /// Displays the editor GUI. /// </summary> void OnGUI () { if (style == null) { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; } // If no cutscene is selected, present the user with the option to create one if (scene == null) { if (GUILayout.Button("Create New Cutscene", GUILayout.ExpandWidth(false))) { CreateCutscene(); } } else { // Otherwise present the cutscene editor float windowHeight = style.GetStyle("Pane").fixedHeight; // Options window //Rect optionsRect = new Rect(0, 0, position.width / 3, windowHeight); //options.OnGUI(optionsRect); // Media window Rect mediaRect = new Rect(2, 2, position.width / 2, windowHeight); media.OnGUI(mediaRect); // Effects window Rect effectsRect = new Rect(mediaRect.xMax + 2, 2, position.width - mediaRect.xMax - 4, windowHeight); effects.OnGUI(effectsRect); // Cutting tools Rect toolsRect = new Rect(0, mediaRect.yMax, position.width, 25); tools.OnGUI(toolsRect); // Timeline Rect timelineRect = new Rect(0, toolsRect.yMax, position.width, position.height - toolsRect.yMax); timeline.OnGUI(timelineRect); } } // Context menus: /// <summary> /// Deletes a piece of media by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> [MenuItem("CONTEXT/CutsceneObject/Delete")] static void DeleteCutsceneMedia (MenuCommand command) { DeleteCutsceneMedia(command.context as CutsceneMedia); } /// <summary> /// Deletes a piece of media. /// </summary> /// <param name="obj">The media to delete.</param> /// <remarks>This has to be in CutsceneEditor rather than CutsceneTimeline because it uses the DestroyImmediate function, which is only available to classes which inherit from UnityEngine.Object.</remarks> static void DeleteCutsceneMedia (CutsceneMedia obj) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Object", "Are you sure you wish to delete this object? Changes cannot be undone.", "Delete", "Cancel"); } // Only delete the cutscene object if the user chose to if (delete) { Debug.Log("Cutscene Editor: deleting media " + obj.name); if (obj.type == Cutscene.MediaType.Actors || obj.type == Cutscene.MediaType.Subtitles) { // Delete the CutsceneObject component DestroyImmediate(obj); } else { // Delete the actual game object DestroyImmediate(obj.gameObject); } } } /// <summary> /// Deletes a track by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneTrack/Delete Track")] static bool DeleteTrack (MenuCommand command) { return DeleteTrack(command.context as CutsceneTrack); } /// <summary> /// Deletes a track. /// </summary> /// <param name="track">The track to delete.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> static bool DeleteTrack (CutsceneTrack track) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Track", "Are you sure you wish to delete this track? Changes cannot be undone.", "Delete", "Cancel"); } if (delete) { DestroyImmediate(track); } return delete; } /// <summary> /// Deletes a clip by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneClip/Delete Clip")] static bool DeleteClip (MenuCommand command) { return DeleteClip(command.context as CutsceneClip); } /// <summary> /// Deletes a clip. /// </summary> /// <param name="clip">The clip to delete.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> static bool DeleteClip (CutsceneClip clip) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Clip", "Are you sure you wish to delete this clip? Changes cannot be undone.", "Delete", "Cancel"); } clip.setToDelete = delete; return delete; } /// <summary> /// Selects the track at the specified index. /// </summary> /// <param name="index">The track to select.</param> void SelectTrackAtIndex (int index) { if (scene.tracks.Length > 0 && index > 0 && index <= scene.tracks.Length) { selectedTrack = scene.tracks[index - 1]; EDebug.Log("Cutscene Editor: track " + index + " is selected"); } } /// <summary> /// Determines which key command is pressed and responds accordingly. /// </summary> /// <param name="keyDownEvent">The keyboard event.</param> /// <returns>True if the keyboard shortcut exists, false otherwise.</returns> public void HandleKeyboardShortcuts (Event keyDownEvent) { KeyCode key = keyDownEvent.keyCode; // Tools: - + // Move/resize if (key == CutsceneHotkeys.MoveResizeTool.key) { currentTool = Tool.MoveResize; EDebug.Log("Cutscene Editor: switching to Move/Resize tool"); // Scissors } else if (key == CutsceneHotkeys.ScissorsTool.key) { currentTool = Tool.Scissors; EDebug.Log("Cutscene Editor: switching to Scissors tool"); // Zoom } else if (key == CutsceneHotkeys.ZoomTool.key) { currentTool = Tool.Zoom; EDebug.Log("Cutscene Editor: switching to Zoom tool"); } // Timeline navigation: - + // Set in point else if (key == CutsceneHotkeys.SetInPont.key) { scene.inPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting in point"); // Set out point } else if (key == CutsceneHotkeys.SetOutPoint.key) { scene.outPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting out point"); // Scrub left } else if (keyDownEvent.Equals(Event.KeyboardEvent("left"))) { scene.playhead -= CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead left"); // Scrub left large } else if (keyDownEvent.Equals(Event.KeyboardEvent("#left"))) { scene.playhead -= CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead left"); // Scrub right } else if (keyDownEvent.Equals(Event.KeyboardEvent("right"))) { scene.playhead += CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead right"); // Scrub right large } else if (keyDownEvent.Equals(Event.KeyboardEvent("#right"))) { scene.playhead += CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead right"); // Go to previous split point } else if (keyDownEvent.Equals(Event.KeyboardEvent("up"))) { scene.playhead = selectedTrack.GetTimeOfNextSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to previous split point"); // Go to next split point } else if (keyDownEvent.Equals(Event.KeyboardEvent("down"))) { scene.playhead = selectedTrack.GetTimeOfPreviousSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to next split point"); // Go to in point } else if (keyDownEvent.Equals(Event.KeyboardEvent("#up"))) { scene.playhead = scene.inPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); // Go to out point } else if (keyDownEvent.Equals(Event.KeyboardEvent("#down"))) { scene.playhead = scene.outPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); } // Track selection: - + // Select track 1 else if (key == CutsceneHotkeys.SelectTrack1.key) { SelectTrackAtIndex(1); // Select track 2 } else if (key == CutsceneHotkeys.SelectTrack2.key) { SelectTrackAtIndex(2); // Select track 3 } else if (key == CutsceneHotkeys.SelectTrack3.key) { SelectTrackAtIndex(3); // Select track 4 } else if (key == CutsceneHotkeys.SelectTrack4.key) { SelectTrackAtIndex(4); // Select track 5 } else if (key == CutsceneHotkeys.SelectTrack5.key) { SelectTrackAtIndex(5); // Select track 6 } else if (key == CutsceneHotkeys.SelectTrack6.key) { SelectTrackAtIndex(6); // Select track 7 } else if (key == CutsceneHotkeys.SelectTrack7.key) { SelectTrackAtIndex(7); // Select track 8 } else if (key == CutsceneHotkeys.SelectTrack8.key) { SelectTrackAtIndex(8); // Select track 9 } else if (key == CutsceneHotkeys.SelectTrack9.key) { SelectTrackAtIndex(9); } - + // Other: else { EDebug.Log("Cutscene Editor: unknown keyboard shortcut " + keyDownEvent); return; } // If we get to this point, a shortcut matching the user's keystroke has been found Event.current.Use(); } public static float PaneTabsWidth (int count) { return count * 80f; } -} \ No newline at end of file +}
mminer/silverscreen
09a2f05a1da3051423dbc17da277619b99611937
Add ancient uncommitted changes.
diff --git a/Cutscene Ed/Editor/CutsceneAddAudio.cs b/Cutscene Ed/Editor/CutsceneAddAudio.cs index ca5284c..ad4a39e 100755 --- a/Cutscene Ed/Editor/CutsceneAddAudio.cs +++ b/Cutscene Ed/Editor/CutsceneAddAudio.cs @@ -1,115 +1,115 @@ /** * Copyright (c) 2010 Matthew Miner - * + * * 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. */ using UnityEngine; using UnityEditor; class CutsceneAddAudio : ScriptableWizard { //GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; AudioClip[] audioClips; AudioClip selected; /// <summary> /// Creates a wizard for adding a new audio clip. /// </summary> [MenuItem("Component/Cutscene/Add Media/Audio")] public static void CreateWizard () { DisplayWizard<CutsceneAddAudio>("Add Audio", "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Audio", true)] static bool ValidateCreateWizard () { return CutsceneEditor.CutsceneSelected; } void OnGUI () { OnWizardUpdate(); // Display temporary workaround info GUILayout.Label("To add an audio clip from the Project view, drag and drop it to the audio pane. This is a temporary workaround and will hopefully be fixed soon."); // TODO Make LoadAllAssetsAtPath work /* audioClips = (AudioClip[])AssetDatabase.LoadAllAssetsAtPath("Assets"); Debug.Log("Objects length: " + audioClips.Length); EditorGUILayout.BeginVertical(style.GetStyle("List Container")); foreach (AudioClip aud in audioClips) { GUIStyle itemStyle = aud == selected ? style.GetStyle("Selected List Item") : GUIStyle.none; Rect rect = EditorGUILayout.BeginHorizontal(itemStyle); GUIContent itemLabel = new GUIContent(aud.name, EditorGUIUtility.ObjectContent(null, typeof(AudioClip)).image); GUILayout.Label(itemLabel); - + EditorGUILayout.EndHorizontal(); // Select when clicked if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { selected = aud; EditorGUIUtility.PingObject(aud); Event.current.Use(); } } EditorGUILayout.EndVertical(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true;*/ } void OnWizardUpdate () { helpString = "Choose an audio clip to add."; // Only valid if an audio clip has been selected isValid = selected != null; } /// <summary> /// Adds a new audio clip to the cutscene. /// </summary> void OnWizardCreate () { Selection.activeGameObject.GetComponent<Cutscene>().NewAudio(selected); } -} \ No newline at end of file +} diff --git a/Cutscene Ed/Editor/CutsceneEditorGUILayout.cs b/Cutscene Ed/Editor/CutsceneEditorGUILayout.cs new file mode 100644 index 0000000..e329522 --- /dev/null +++ b/Cutscene Ed/Editor/CutsceneEditorGUILayout.cs @@ -0,0 +1,35 @@ +using UnityEditor; +using UnityEngine; + +public delegate void GUIContents (); + +public static class CutsceneEditorGUILayout +{ + public static Rect Horizontal (GUIContents contents, params GUILayoutOption[] options) + { + Rect rect = EditorGUILayout.BeginHorizontal(options); + contents(); + EditorGUILayout.EndHorizontal(); + + return rect; + } + + public static Rect Horizontal (GUIContents contents, GUIStyle style, params GUILayoutOption[] options) + { + Rect rect = EditorGUILayout.BeginHorizontal(style, options); + contents(); + EditorGUILayout.EndHorizontal(); + + return rect; + } +} + +public static class CutsceneGUILayout +{ + public static void Area (GUIContents contents, Rect screenRect) + { + GUILayout.BeginArea(screenRect); + contents(); + GUILayout.EndArea(); + } +} \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTimeline.cs b/Cutscene Ed/Editor/CutsceneTimeline.cs index 7ec7433..71131de 100755 --- a/Cutscene Ed/Editor/CutsceneTimeline.cs +++ b/Cutscene Ed/Editor/CutsceneTimeline.cs @@ -1,139 +1,139 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; public enum DragEvent { Move, ResizeLeft, ResizeRight } class CutsceneTimeline : ICutsceneGUI { readonly CutsceneEditor ed; public const int scrubLargeJump = 10; public const int scrubSmallJump = 1; readonly ICutsceneGUI navigation; readonly ICutsceneGUI tracksView; readonly ICutsceneGUI trackControls; readonly ICutsceneGUI trackInfo; public const float timelineZoomMin = 1f; public const float timelineZoomMax = 100f; public const float trackInfoWidth = 160f; public CutsceneTimeline (CutsceneEditor ed) { this.ed = ed; navigation = new CutsceneNavigation(ed); tracksView = new CutsceneTracksView(ed); trackControls = new CutsceneTrackControls(ed); trackInfo = new CutsceneTrackInfo(ed); } /// <summary> /// Displays the timeline's GUI. /// </summary> /// <param name="rect">The timeline's Rect.</param> public void OnGUI (Rect rect) { - GUILayout.BeginArea(rect); - - float rightColWidth = GUI.skin.verticalScrollbar.fixedWidth; - float middleColWidth = rect.width - CutsceneTimeline.trackInfoWidth - rightColWidth; - - ed.timelineMin = CutsceneTimeline.timelineZoomMin * (middleColWidth / ed.scene.duration); - ed.timelineZoom = Mathf.Clamp(ed.timelineZoom, ed.timelineMin, CutsceneTimeline.timelineZoomMax); - - // Navigation bar - Rect navigationRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.toolbar, GUILayout.Width(rect.width)); - navigation.OnGUI(navigationRect); - - // Begin Tracks - EditorGUILayout.BeginHorizontal(GUILayout.Width(rect.width), GUILayout.ExpandHeight(true)); - - // Track info - //Rect trackInfoRect = GUILayoutUtility.GetRect(trackInfoWidth, rect.height - navigationRect.yMax - GUI.skin.horizontalScrollbar.fixedHeight); - Rect trackInfoRect = new Rect(0, 0, CutsceneTimeline.trackInfoWidth, 9999); - trackInfo.OnGUI(trackInfoRect); - - // Track controls - float trackControlsHeight = GUI.skin.horizontalScrollbar.fixedHeight; - Rect trackControlsRect = new Rect(0, rect.height - trackControlsHeight, CutsceneTimeline.trackInfoWidth, trackControlsHeight); - trackControls.OnGUI(trackControlsRect); - - // Tracks - Rect tracksRect = new Rect(trackInfoRect.xMax, navigationRect.yMax, middleColWidth + rightColWidth, rect.height - navigationRect.yMax); - tracksView.OnGUI(tracksRect); - - EditorGUILayout.EndHorizontal(); - - if (Event.current.type == EventType.KeyDown) { // Key presses - ed.HandleKeyboardShortcuts(Event.current); - } - - GUILayout.EndArea(); + CutsceneGUILayout.Area(delegate { + + float rightColWidth = GUI.skin.verticalScrollbar.fixedWidth; + float middleColWidth = rect.width - CutsceneTimeline.trackInfoWidth - rightColWidth; + + ed.timelineMin = CutsceneTimeline.timelineZoomMin * (middleColWidth / ed.scene.duration); + ed.timelineZoom = Mathf.Clamp(ed.timelineZoom, ed.timelineMin, CutsceneTimeline.timelineZoomMax); + + // Navigation bar + Rect navigationRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.toolbar, GUILayout.Width(rect.width)); + navigation.OnGUI(navigationRect); + + // Begin Tracks + CutsceneEditorGUILayout.Horizontal(delegate { + + // Track info + //Rect trackInfoRect = GUILayoutUtility.GetRect(trackInfoWidth, rect.height - navigationRect.yMax - GUI.skin.horizontalScrollbar.fixedHeight); + Rect trackInfoRect = new Rect(0, 0, CutsceneTimeline.trackInfoWidth, 9999); + trackInfo.OnGUI(trackInfoRect); + + // Track controls + float trackControlsHeight = GUI.skin.horizontalScrollbar.fixedHeight; + Rect trackControlsRect = new Rect(0, rect.height - trackControlsHeight, CutsceneTimeline.trackInfoWidth, trackControlsHeight); + trackControls.OnGUI(trackControlsRect); + + // Tracks + Rect tracksRect = new Rect(trackInfoRect.xMax, navigationRect.yMax, middleColWidth + rightColWidth, rect.height - navigationRect.yMax); + tracksView.OnGUI(tracksRect); + + }, GUILayout.Width(rect.width), GUILayout.ExpandHeight(true)); + + if (Event.current.type == EventType.KeyDown) { // Key presses + ed.HandleKeyboardShortcuts(Event.current); + } + + }, rect); } /// <summary> /// Moves the playhead. /// </summary> /// <param name="playheadPos">The position to move the playhead to.</param> void MovePlayheadToPosition (float playheadPos) { ed.scene.playhead = playheadPos / ed.timelineZoom; } /// <summary> /// Splits a clip into two separate ones at the specified time. /// </summary> /// <param name="splitPoint">The time at which to split the clip.</param> /// <param name="track">The track the clip is sitting on.</param> /// <param name="clip">The clip to split.</param> /// <returns>The new clip.</returns> public static CutsceneClip SplitClipAtTime (float splitPoint, CutsceneTrack track, CutsceneClip clip) { CutsceneClip newClip = clip.GetCopy(); // Make sure the clip actually spans over the split point if (splitPoint < clip.timelineStart || splitPoint > clip.timelineStart + clip.duration) { EDebug.Log("Cutscene Editor: cannot split clip; clip does not contain the split point"); return null; } clip.SetOutPoint(clip.inPoint + (splitPoint - clip.timelineStart)); newClip.SetInPoint(clip.outPoint); newClip.SetTimelineStart(splitPoint); track.clips.Add(newClip); Event.current.Use(); EDebug.Log("Cutscene Editor: splitting clip at time " + splitPoint); return newClip; } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTools.cs b/Cutscene Ed/Editor/CutsceneTools.cs index 0014093..02fe361 100755 --- a/Cutscene Ed/Editor/CutsceneTools.cs +++ b/Cutscene Ed/Editor/CutsceneTools.cs @@ -1,60 +1,58 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; public enum Tool { MoveResize, Scissors, Zoom } class CutsceneTools : ICutsceneGUI { readonly CutsceneEditor ed; readonly GUIContent[] tools = { new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_move.png") as Texture, "Move/Resize"), new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_scissors.png") as Texture, "Scissors"), new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_zoom.png") as Texture, "Zoom") }; public CutsceneTools (CutsceneEditor ed) { this.ed = ed; } public void OnGUI (Rect rect) { - GUILayout.BeginArea(rect); - - EditorGUILayout.BeginHorizontal(ed.style.GetStyle("Tools Bar"), GUILayout.Width(rect.width)); - - GUILayout.FlexibleSpace(); - ed.currentTool = (Tool)GUILayout.Toolbar((int)ed.currentTool, tools); - - EditorGUILayout.EndHorizontal(); - - GUILayout.EndArea(); + CutsceneGUILayout.Area(delegate { + CutsceneEditorGUILayout.Horizontal(delegate { + + GUILayout.FlexibleSpace(); + ed.currentTool = (Tool)GUILayout.Toolbar((int)ed.currentTool, tools); + + }, ed.style.GetStyle("Tools Bar"), GUILayout.Width(rect.width)); + }, rect); } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/EDebug.cs b/Cutscene Ed/Scripts/EDebug.cs index 6ac7d98..cab48b5 100755 --- a/Cutscene Ed/Scripts/EDebug.cs +++ b/Cutscene Ed/Scripts/EDebug.cs @@ -1,66 +1,66 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; /// <summary> /// A simple class for toggle-able debug messages. Debug messages for editor tools are useful when developing the tool itself, but annoying for end users. /// </summary> public class EDebug { static bool debug = false; public static void Break () { if (debug) Debug.Break(); } public static void Log (object message) { if (debug) Debug.Log(message); } - public static void Log (object message, UnityEngine.Object context) + public static void Log (object message, Object context) { if (debug) Debug.Log(message, context); } public static void LogError (object message) { if (debug) Debug.LogError(message); } - public static void LogError (object message, UnityEngine.Object context) + public static void LogError (object message, Object context) { if (debug) Debug.LogError(message, context); } public static void LogWarning (object message) { if (debug) Debug.LogWarning(message); } - public static void LogWarning (object message, UnityEngine.Object context) + public static void LogWarning (object message, Object context) { if (debug) Debug.LogWarning(message, context); } } \ No newline at end of file
mminer/silverscreen
cbcc182c7627ebfd809fe78ab5f2fed6b10b9f0d
Replace obsolete property with new function call.
diff --git a/Cutscene Ed/Scripts/Cutscene.cs b/Cutscene Ed/Scripts/Cutscene.cs index a6c26e2..4380498 100755 --- a/Cutscene Ed/Scripts/Cutscene.cs +++ b/Cutscene Ed/Scripts/Cutscene.cs @@ -1,462 +1,462 @@ /** * Copyright (c) 2010 Matthew Miner - * + * * 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. */ using UnityEngine; using System.Collections; using System.Collections.Generic; // Functions to be run when the cutscene starts and finishes public delegate void CutsceneStart(); public delegate void CutscenePause(); public delegate void CutsceneEnd(); [RequireComponent(typeof(Animation))] public class Cutscene : MonoBehaviour { public float duration = 30f; public float inPoint = 0f; public float outPoint = 30f; public bool stopPlayer = true; public GameObject player; public GUIStyle subtitleStyle; public Rect subtitlePosition = new Rect(0, 0, 400, 200); - + public CutsceneStart startFunction { get; set; } public CutscenePause pauseFunction { get; set; } public CutsceneEnd endFunction { get; set; } public enum MediaType { Shots, Actors, Audio, Subtitles } public enum EffectType { Filters, Transitions } public CutsceneTrack[] tracks { get { return GetComponentsInChildren<CutsceneTrack>(); } } public CutsceneShot[] shots { get { return GetComponentsInChildren<CutsceneShot>(); } } public CutsceneActor[] actors { get { return GetComponentsInChildren<CutsceneActor>(); } } public CutsceneAudio[] audioSources { get { return GetComponentsInChildren<CutsceneAudio>(); } } public CutsceneSubtitle[] subtitles { get { return GetComponentsInChildren<CutsceneSubtitle>(); } } CutsceneSubtitle currentSubtitle; public float playhead { get { return animation["master"].time; } set { animation["master"].time = Mathf.Clamp(value, 0f, duration); } } [HideInInspector] public AnimationClip masterClip; void Start () { SetupMasterAnimationClip(); SetupTrackAnimationClips(); - + DisableCameras(); DisableAudio(); } - + void OnGUI () { /// Displays the current subtitle if there is one if (currentSubtitle == null) { return; } - + GUI.BeginGroup(subtitlePosition, subtitleStyle); - + GUILayout.Label(currentSubtitle.dialog, subtitleStyle); GUI.EndGroup(); } - + /// <summary> /// Visually shows the cutscene in the scene view. /// </summary> void OnDrawGizmos () { Gizmos.DrawIcon(transform.position, "Cutscene.png"); } /// <summary> /// Sets the in and out points of the master animation clip. /// </summary> void SetupMasterAnimationClip () { animation.RemoveClip("master"); // Create a new event for when the scene starts AnimationEvent start = new AnimationEvent(); start.time = inPoint; start.functionName = "SceneStart"; masterClip.AddEvent(start); // Create a new event for when the scene finishes AnimationEvent finish = new AnimationEvent(); finish.time = outPoint; finish.functionName = "SceneFinish"; masterClip.AddEvent(finish); - + animation.AddClip(masterClip, "master"); animation["master"].time = inPoint; } /// <summary> /// Adds each track's animation clip to the main animation. /// </summary> void SetupTrackAnimationClips () { foreach (CutsceneTrack t in tracks) { if (t.enabled) { AnimationClip trackAnimationClip = t.track; string clipName = "track" + t.id; animation.AddClip(trackAnimationClip, clipName); animation[clipName].time = inPoint; } } } - + /// <summary> /// Turns off all child cameras so that they don't display before the cutscene starts. /// </summary> void DisableCameras () { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { cam.enabled = false; } } - + /// <summary> /// Turns off all child cameras except for the one specified. /// </summary> /// <param name="exemptCam">The camera to stay enabled.</param> void DisableOtherCameras (Camera exemptCam) { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { if (cam != exemptCam) { cam.enabled = false; } } } - + /// <summary> /// Keeps all child audio sources from playing once the game starts. /// </summary> void DisableAudio () { AudioSource[] childAudio = GetComponentsInChildren<AudioSource>(); foreach (AudioSource audio in childAudio) { audio.playOnAwake = false; } } /// <summary> /// Starts playing the cutscene. /// </summary> public void PlayCutscene () { // Set up and play the master animation animation["master"].layer = 0; animation.Play("master"); // Set up and play each individual track for (int i = 0; i < tracks.Length; i++) { if (tracks[i].enabled) { animation["track" + tracks[i].id].layer = i + 1; animation.Play("track" + tracks[i].id); } } } - + /// <summary> /// Pauses the cutscene. /// </summary> public void PauseCutscene () { pauseFunction(); // TODO actually pause the cutscene } /// <summary> /// Called when the scene starts. /// </summary> void SceneStart () { if (startFunction != null) { startFunction(); } // Stop the player from being able to move if (player != null && stopPlayer) { EDebug.Log("Cutscene: deactivating player"); - player.active = false; + player.SetActive(false); } - + DisableCameras(); currentSubtitle = null; EDebug.Log("Cutscene: scene started at " + animation["master"].time); } - + /// <summary> /// Called when the scene ends. /// </summary> void SceneFinish () { if (endFunction != null) { endFunction(); } // Allow the player to move again if (player != null) { EDebug.Log("Cutscene: activating player"); - player.active = true; + player.SetActive(true); } - + EDebug.Log("Cutscene: scene finished at " + animation["master"].time); } - + /// <summary> /// Shows the specified shot. /// </summary> /// <param name="clip">The shot to show.</summary> void PlayShot (CutsceneClip clip) { Camera cam = ((CutsceneShot)clip.master).camera; cam.enabled = true; - + StartCoroutine(StopShot(cam, clip.duration)); EDebug.Log("Cutscene: showing camera " + clip.name + " at " + animation["master"].time); } - + /// <summary> /// Stops the shot from playing at its out point. /// </summary> /// <param name="shot">The shot to stop.</param> /// <param name="duration">The time at which to stop the shot.</param> IEnumerator StopShot (Camera cam, float duration) { yield return new WaitForSeconds(duration); cam.enabled = false; EDebug.Log("Cutscene: stopping shot at " + animation["master"].time); } - + /// <summary> /// Plays the specified actor. /// </summary> /// <param name="clip">The actor to play.</summary> void PlayActor (CutsceneClip clip) { CutsceneActor actor = ((CutsceneActor)clip.master); AnimationClip anim = actor.anim; GameObject go = ((CutsceneActor)clip.master).go; - + go.animation[anim.name].time = clip.inPoint; go.animation.Play(anim.name); StartCoroutine(StopActor(actor, clip.duration)); - + EDebug.Log("Cutscene: showing actor " + clip.name + " at " + animation["master"].time); } - + /// <summary> /// Stops the actor from playing at its out point. /// </summary> /// <param name="actor">The actor to stop.</param> /// <param name="duration">The time at which to stop the actor.</param> IEnumerator StopActor (CutsceneActor actor, float duration) { yield return new WaitForSeconds(duration); actor.go.animation.Stop(actor.anim.name); EDebug.Log("Cutscene: stopping actor at " + animation["master"].time); } - + /// <summary> /// Plays the specified audio. /// </summary> /// <param name="clip">The audio to play.</summary> void PlayAudio (CutsceneClip clip) { AudioSource aud = ((CutsceneAudio)clip.master).audio; aud.Play(); aud.time = clip.inPoint; // Set the point at which the clip plays StartCoroutine(StopAudio(aud, clip.duration)); // Set the point at which the clip stops EDebug.Log("Playing audio " + clip.name + " at " + animation["master"].time); } - + /// <summary> /// Stops the audio from playing at its out point. /// </summary> /// <param name="aud">The audio source to stop.</param> /// <param name="duration">The time at which to stop the audio.</param> IEnumerator StopAudio (AudioSource aud, float duration) { yield return new WaitForSeconds(duration); aud.Stop(); } - + /// <summary> /// Displays the specified subtitle. /// </summary> /// <param name="clip">The subtitle to display.</summary> void PlaySubtitle (CutsceneClip clip) { currentSubtitle = (CutsceneSubtitle)clip.master; EDebug.Log("Displaying subtitle " + clip.name + " at " + animation["master"].time); - + StartCoroutine(StopSubtitle(clip.duration)); } - + /// <summary> /// Stops the subtitle from displaying at its out point. /// </summary> /// <param name="duration">The time at which to stop the audio.</param> IEnumerator StopSubtitle (float duration) { yield return new WaitForSeconds(duration); currentSubtitle = null; } - + /// <summary> /// Stops all subtitles from displaying by setting the current subtitle to null. /// </summary> void StopSubtitle () { currentSubtitle = null; } - + /// <summary> /// Called when the clip type is unknown. /// </summary> /// <remarks>For debugging only; ideally this will never be called.</remarks> void UnknownFunction (CutsceneClip clip) { EDebug.Log("Cutscene: unknown function call from clip " + clip.name); } /// <summary> /// Creates a new CutsceneShot object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneShot object.</returns> public CutsceneShot NewShot () { GameObject shot = new GameObject("Camera", typeof(Camera), typeof(CutsceneShot)); // Keep the camera from displaying before it's placed on the timeline shot.camera.enabled = false; // Set the parent of the new shot to the Shots object shot.transform.parent = transform.Find("Shots"); EDebug.Log("Cutscene Editor: added new shot"); return shot.GetComponent<CutsceneShot>(); } /// <summary> /// Creates a new CutsceneActor object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneActor object.</returns> public CutsceneActor NewActor (AnimationClip anim, GameObject go) { CutsceneActor actor = GameObject.Find("Actors").AddComponent<CutsceneActor>(); actor.name = anim.name; actor.anim = anim; actor.go = go; EDebug.Log("Cutscene Editor: adding new actor"); return actor; } /// <summary> /// Creates a new CutsceneAudio object and attaches it to a new game object as a child of the Audio game object. /// </summary> /// <param name="clip">The audio clip to be attached the CutsceneAudio object.</param> /// <returns>The new CutsceneAudio object.</returns> public CutsceneAudio NewAudio (AudioClip clip) { GameObject aud = new GameObject(clip.name, typeof(AudioSource), typeof(CutsceneAudio)); aud.audio.clip = clip; // Keep the audio from playing when the game starts aud.audio.playOnAwake = false; // Set the parent of the new audio to the "Audio" object aud.transform.parent = transform.Find("Audio"); EDebug.Log("Cutscene Editor: added new audio"); return aud.GetComponent<CutsceneAudio>(); } /// <summary> /// Creates a new CutsceneSubtitle object and attaches it to the Subtitles game object. /// </summary> /// <param name="dialog">The dialog to be displayed.</param> /// <returns>The new CutsceneSubtitle object.</returns> public CutsceneSubtitle NewSubtitle (string dialog) { CutsceneSubtitle subtitle = GameObject.Find("Subtitles").AddComponent<CutsceneSubtitle>(); subtitle.dialog = dialog; EDebug.Log("Cutscene Editor: added new subtitle"); return subtitle; } /// <summary> /// Attaches a new track component to the cutscene. /// </summary> /// <returns>The new cutscene track.</returns> public CutsceneTrack AddTrack (Cutscene.MediaType type) { int id = 0; // Ensure the new track has a unique ID foreach (CutsceneTrack t in tracks) { if (id == t.id) { id++; } else { break; } } - + CutsceneTrack track = gameObject.AddComponent<CutsceneTrack>(); track.id = id; track.type = type; track.name = CutsceneTrack.DefaultName(type); - + EDebug.Log("Cutscene Editor: added new track of type " + type); return track; } -} \ No newline at end of file +}
mminer/silverscreen
e313c24c8e272f2b49575e2315c9b5abfaf2f558
Moved braces after classes / methods to new line.
diff --git a/Cutscene Ed/Editor/BugReporter.cs b/Cutscene Ed/Editor/BugReporter.cs index ef3b461..a7ca636 100755 --- a/Cutscene Ed/Editor/BugReporter.cs +++ b/Cutscene Ed/Editor/BugReporter.cs @@ -1,64 +1,67 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; -public class BugReporter : EditorWindow { +public class BugReporter : EditorWindow +{ string email = ""; string details = ""; readonly GUIContent emailLabel = new GUIContent("Your Email", "If we require additional information, we'll contact you at the supplied address (optional)."); readonly GUIContent submitLabel = new GUIContent("Submit", "Send this bug report."); /// <summary> /// Adds "Bug Reporter" to the Window menu. /// </summary> [MenuItem("Window/Bug Reporter")] - public static void OpenEditor () { + public static void OpenEditor () + { // Get existing open window or if none, make a new one GetWindow<BugReporter>(true, "Bug Reporter").Show(); } - void OnGUI () { + void OnGUI () + { GUILayout.Label("Please take a minute to tell us what happened in as much detail as possible. This makes it possible for us to fix the problem."); EditorGUILayout.Separator(); email = EditorGUILayout.TextField(emailLabel, email); EditorGUILayout.Separator(); GUILayout.Label("Problem Details:"); details = EditorGUILayout.TextArea(details); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(submitLabel, GUILayout.ExpandWidth(false))) { // TODO Send bug report Debug.Log("Bug report sent."); } EditorGUILayout.EndHorizontal(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneAddActor.cs b/Cutscene Ed/Editor/CutsceneAddActor.cs index 31f3925..9c0885e 100755 --- a/Cutscene Ed/Editor/CutsceneAddActor.cs +++ b/Cutscene Ed/Editor/CutsceneAddActor.cs @@ -1,112 +1,116 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; -class CutsceneAddActor : ScriptableWizard { +class CutsceneAddActor : ScriptableWizard +{ GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; AnimationClip selected; GameObject selectedGO; /// <summary> /// Creates a wizard for adding a new actor. /// </summary> [MenuItem("Component/Cutscene/Add Media/Actor")] public static void CreateWizard () { DisplayWizard<CutsceneAddActor>("Add Actor", "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Actor", true)] static bool ValidateCreateWizard () { return CutsceneEditor.CutsceneSelected; } - void OnGUI () { + void OnGUI () + { OnWizardUpdate(); - - Animation[] animations = (Animation[])FindObjectsOfType(typeof(Animation)); + + Object[] animations = FindObjectsOfType(typeof(Animation)); EditorGUILayout.BeginVertical(style.GetStyle("List Container")); foreach (Animation anim in animations) { GUILayout.Label(anim.gameObject.name, EditorStyles.largeLabel); foreach (AnimationClip clip in AnimationUtility.GetAnimationClips(anim)) { GUIStyle itemStyle = GUIStyle.none; if (clip == selected) { itemStyle = style.GetStyle("Selected List Item"); } Rect rect = EditorGUILayout.BeginHorizontal(itemStyle); GUIContent itemLabel = new GUIContent(clip.name, EditorGUIUtility.ObjectContent(null, typeof(Animation)).image); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); // Select when clicked if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { selected = clip; selectedGO = anim.gameObject; EditorGUIUtility.PingObject(anim); Event.current.Use(); Repaint(); } } } EditorGUILayout.EndVertical(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true; } - void OnWizardUpdate () { + void OnWizardUpdate () + { helpString = "Choose an animation to add."; // Only valid if an animation has been selected isValid = selected != null; } /// <summary> /// Adds the new actor to the cutscene. /// </summary> - void OnWizardCreate () { + void OnWizardCreate () + { Selection.activeGameObject.GetComponent<Cutscene>().NewActor(selected, selectedGO); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneAddAudio.cs b/Cutscene Ed/Editor/CutsceneAddAudio.cs index 19aa13f..ca5284c 100755 --- a/Cutscene Ed/Editor/CutsceneAddAudio.cs +++ b/Cutscene Ed/Editor/CutsceneAddAudio.cs @@ -1,109 +1,115 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; using UnityEditor; -class CutsceneAddAudio : ScriptableWizard { +class CutsceneAddAudio : ScriptableWizard +{ //GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; AudioClip[] audioClips; AudioClip selected; /// <summary> /// Creates a wizard for adding a new audio clip. /// </summary> [MenuItem("Component/Cutscene/Add Media/Audio")] - public static void CreateWizard () { + public static void CreateWizard () + { DisplayWizard<CutsceneAddAudio>("Add Audio", "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Audio", true)] - static bool ValidateCreateWizard () { + static bool ValidateCreateWizard () + { return CutsceneEditor.CutsceneSelected; } - void OnGUI () { + void OnGUI () + { OnWizardUpdate(); // Display temporary workaround info GUILayout.Label("To add an audio clip from the Project view, drag and drop it to the audio pane. This is a temporary workaround and will hopefully be fixed soon."); // TODO Make LoadAllAssetsAtPath work /* audioClips = (AudioClip[])AssetDatabase.LoadAllAssetsAtPath("Assets"); Debug.Log("Objects length: " + audioClips.Length); EditorGUILayout.BeginVertical(style.GetStyle("List Container")); foreach (AudioClip aud in audioClips) { GUIStyle itemStyle = aud == selected ? style.GetStyle("Selected List Item") : GUIStyle.none; Rect rect = EditorGUILayout.BeginHorizontal(itemStyle); GUIContent itemLabel = new GUIContent(aud.name, EditorGUIUtility.ObjectContent(null, typeof(AudioClip)).image); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); // Select when clicked if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { selected = aud; EditorGUIUtility.PingObject(aud); Event.current.Use(); } } EditorGUILayout.EndVertical(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true;*/ } - void OnWizardUpdate () { + void OnWizardUpdate () + { helpString = "Choose an audio clip to add."; // Only valid if an audio clip has been selected isValid = selected != null; } /// <summary> /// Adds a new audio clip to the cutscene. /// </summary> - void OnWizardCreate () { + void OnWizardCreate () + { Selection.activeGameObject.GetComponent<Cutscene>().NewAudio(selected); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneAddSubtitle.cs b/Cutscene Ed/Editor/CutsceneAddSubtitle.cs index c108c6f..6c88b61 100755 --- a/Cutscene Ed/Editor/CutsceneAddSubtitle.cs +++ b/Cutscene Ed/Editor/CutsceneAddSubtitle.cs @@ -1,83 +1,88 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; using UnityEditor; public class CutsceneAddSubtitle : ScriptableWizard { string dialog = ""; /// <summary> /// Creates a wizard for adding a new subtitle. /// </summary> [MenuItem("Component/Cutscene/Add Media/Subtitle")] - public static void CreateWizard () { + public static void CreateWizard () + { DisplayWizard<CutsceneAddSubtitle>("Add Subtitle", "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Subtitle", true)] - static bool ValidateCreateWizard () { + static bool ValidateCreateWizard () + { return CutsceneEditor.CutsceneSelected; } - void OnGUI () { + void OnGUI () + { OnWizardUpdate(); EditorGUILayout.BeginHorizontal(); GUIContent itemLabel = new GUIContent("Dialog", EditorGUIUtility.ObjectContent(null, typeof(TextAsset)).image); GUILayout.Label(itemLabel, GUILayout.ExpandWidth(false)); dialog = EditorGUILayout.TextArea(dialog); EditorGUILayout.EndHorizontal(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true; } - void OnWizardUpdate () { + void OnWizardUpdate () + { helpString = "Type in some dialog to add."; // Only valid if some text has been entered in the text field isValid = dialog != ""; } /// <summary> /// Adds the new subtitle to the cutscene. /// </summary> - void OnWizardCreate () { + void OnWizardCreate () + { Selection.activeGameObject.GetComponent<Cutscene>().NewSubtitle(dialog); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneEditor.cs b/Cutscene Ed/Editor/CutsceneEditor.cs index 8a2a09c..1692f88 100755 --- a/Cutscene Ed/Editor/CutsceneEditor.cs +++ b/Cutscene Ed/Editor/CutsceneEditor.cs @@ -1,513 +1,537 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// The Cutscene Editor, where tracks and clips can be managed in a fashion similar to non-linear video editors. /// </summary> -public class CutsceneEditor : EditorWindow { +public class CutsceneEditor : EditorWindow +{ public static readonly System.Version version = new System.Version(0, 2); public Cutscene scene { get { Object[] scenes = Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel); if (scenes.Length == 0) { return null; } return scenes[0] as Cutscene; } } public GUISkin style { get; private set; } //ICutsceneGUI options; ICutsceneGUI media; ICutsceneGUI effects; ICutsceneGUI tools; ICutsceneGUI timeline; public static bool CutsceneSelected { get { return Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel).Length > 0; } } public static bool HasPro = SystemInfo.supportsImageEffects; // Icons: public readonly Texture[] mediaIcons = { EditorGUIUtility.LoadRequired("Cutscene Ed/media_shot.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_actor.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_audio.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_subtitle.png") as Texture }; // Timeline: public Tool currentTool = Tool.MoveResize; public Vector2 timelineScrollPos; public float timelineMin { get; set; } float _timelineZoom = CutsceneTimeline.timelineZoomMin; public float timelineZoom { get { return _timelineZoom; } set { _timelineZoom = Mathf.Clamp(value, CutsceneTimeline.timelineZoomMin, CutsceneTimeline.timelineZoomMax); } } CutsceneTrack _selectedTrack; public CutsceneTrack selectedTrack { get { if (_selectedTrack == null) { // If there are no tracks, add a new one if (scene.tracks.Length == 0) { scene.AddTrack(Cutscene.MediaType.Shots); } _selectedTrack = scene.tracks[0]; } return _selectedTrack; } set { _selectedTrack = value; } } public CutsceneClip selectedClip; public DragEvent dragEvent = DragEvent.Move; public CutsceneClip dragClip; // Menu items: /// <summary> /// Adds "Cutscene Editor" to the Window menu. /// </summary> [MenuItem("Window/Cutscene Editor %9")] - public static void OpenEditor () { + public static void OpenEditor () + { // Get existing open window or if none, make a new one GetWindow<CutsceneEditor>(false, "Cutscene Editor").Show(); } /// <summary> /// Validates the Cutscene Editor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Window/Cutscene Editor %9", true)] - static bool ValidateOpenEditor () { + static bool ValidateOpenEditor () + { return CutsceneSelected; } /// <summary> /// Adds the option to create a cutscene from the GameObject > Create Other menu. /// </summary> /// <returns>The new cutscene.</returns> [MenuItem("GameObject/Create Other/Cutscene")] - static void CreateCutscene () { + static void CreateCutscene () + { // Create the new cutscene game object GameObject newSceneGO = new GameObject("Cutscene", typeof(Cutscene)); Cutscene newScene = newSceneGO.GetComponent<Cutscene>(); // Add some tracks to get the user started newScene.AddTrack(Cutscene.MediaType.Shots); newScene.AddTrack(Cutscene.MediaType.Actors); newScene.AddTrack(Cutscene.MediaType.Audio); newScene.AddTrack(Cutscene.MediaType.Subtitles); // Create the cutscene's media game objects GameObject shots = new GameObject("Shots"); GameObject actors = new GameObject("Actors"); GameObject audio = new GameObject("Audio"); GameObject subtitles = new GameObject("Subtitles"); // Make the media game objects a child of the cutscene shots.transform.parent = newScene.transform; actors.transform.parent = newScene.transform; audio.transform.parent = newScene.transform; subtitles.transform.parent = newScene.transform; // Create the master animation clip AnimationClip masterClip = new AnimationClip(); newScene.masterClip = masterClip; newScene.animation.AddClip(masterClip, "master"); newScene.animation.playAutomatically = false; newScene.animation.wrapMode = WrapMode.Once; EDebug.Log("Cutscene Editor: created a new cutscene"); } /// <summary> /// Adds the option to create a cutscene trigger to the GameObject > Create Other menu. /// </summary> /// <returns>The trigger's collider.</returns> [MenuItem("GameObject/Create Other/Cutscene Trigger")] - static Collider CreateCutsceneTrigger () { + static Collider CreateCutsceneTrigger () + { // Create the new cutscene trigger game object GameObject triggerGO = new GameObject("Cutscene Trigger", typeof(BoxCollider), typeof(CutsceneTrigger)); triggerGO.collider.isTrigger = true; return triggerGO.collider; } /// <summary> /// Adds the option to create a new shot track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Shot")] - static void CreateShotTrack () { + static void CreateShotTrack () + { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Shots); } /// <summary> /// Validates the Shot menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Shot", true)] - static bool ValidateCreateShotTrack () { + static bool ValidateCreateShotTrack () + { return CutsceneSelected; } /// <summary> /// Adds the option to create a new actor track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Actor")] - static void CreateActorTrack () { + static void CreateActorTrack () + { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Actors); } /// <summary> /// Validates the Actor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Actor", true)] - static bool ValidateCreateActorTrack () { + static bool ValidateCreateActorTrack () + { return CutsceneSelected; } /// <summary> /// Adds the option to create a new audio track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Audio")] - static void CreateAudioTrack () { + static void CreateAudioTrack () + { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Audio); } /// <summary> /// Validates the Audio menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Audio", true)] - static bool ValidateCreateAudioTrack () { + static bool ValidateCreateAudioTrack () + { return CutsceneSelected; } /// <summary> /// Adds the option to create a new subtitle track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Subtitle")] - static void CreateSubtitleTrack () { + static void CreateSubtitleTrack () + { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Subtitles); } /// <summary> /// Validates the Subtitle menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Subtitle", true)] - static bool ValidateCreateSubtitleTrack () { + static bool ValidateCreateSubtitleTrack () + { return CutsceneSelected; } - void OnEnable () { + void OnEnable () + { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; if (style == null) { Debug.LogError("GUISkin for Cutscene Editor missing"); return; } //options = new CutsceneOptions(this); media = new CutsceneMediaWindow(this); effects = new CutsceneEffectsWindow(this); tools = new CutsceneTools(this); timeline = new CutsceneTimeline(this); } /// <summary> /// Displays the editor GUI. /// </summary> - void OnGUI () { + void OnGUI () + { if (style == null) { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; } // If no cutscene is selected, present the user with the option to create one if (scene == null) { if (GUILayout.Button("Create New Cutscene", GUILayout.ExpandWidth(false))) { CreateCutscene(); } } else { // Otherwise present the cutscene editor float windowHeight = style.GetStyle("Pane").fixedHeight; // Options window //Rect optionsRect = new Rect(0, 0, position.width / 3, windowHeight); //options.OnGUI(optionsRect); // Media window Rect mediaRect = new Rect(2, 2, position.width / 2, windowHeight); media.OnGUI(mediaRect); // Effects window Rect effectsRect = new Rect(mediaRect.xMax + 2, 2, position.width - mediaRect.xMax - 4, windowHeight); effects.OnGUI(effectsRect); // Cutting tools Rect toolsRect = new Rect(0, mediaRect.yMax, position.width, 25); tools.OnGUI(toolsRect); // Timeline Rect timelineRect = new Rect(0, toolsRect.yMax, position.width, position.height - toolsRect.yMax); timeline.OnGUI(timelineRect); } } // Context menus: /// <summary> /// Deletes a piece of media by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> [MenuItem("CONTEXT/CutsceneObject/Delete")] - static void DeleteCutsceneMedia (MenuCommand command) { + static void DeleteCutsceneMedia (MenuCommand command) + { DeleteCutsceneMedia(command.context as CutsceneMedia); } /// <summary> /// Deletes a piece of media. /// </summary> /// <param name="obj">The media to delete.</param> /// <remarks>This has to be in CutsceneEditor rather than CutsceneTimeline because it uses the DestroyImmediate function, which is only available to classes which inherit from UnityEngine.Object.</remarks> - static void DeleteCutsceneMedia (CutsceneMedia obj) { + static void DeleteCutsceneMedia (CutsceneMedia obj) + { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Object", "Are you sure you wish to delete this object? Changes cannot be undone.", "Delete", "Cancel"); } // Only delete the cutscene object if the user chose to if (delete) { Debug.Log("Cutscene Editor: deleting media " + obj.name); if (obj.type == Cutscene.MediaType.Actors || obj.type == Cutscene.MediaType.Subtitles) { // Delete the CutsceneObject component DestroyImmediate(obj); } else { // Delete the actual game object DestroyImmediate(obj.gameObject); } } } /// <summary> /// Deletes a track by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneTrack/Delete Track")] - static bool DeleteTrack (MenuCommand command) { + static bool DeleteTrack (MenuCommand command) + { return DeleteTrack(command.context as CutsceneTrack); } /// <summary> /// Deletes a track. /// </summary> /// <param name="track">The track to delete.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> - static bool DeleteTrack (CutsceneTrack track) { + static bool DeleteTrack (CutsceneTrack track) + { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Track", "Are you sure you wish to delete this track? Changes cannot be undone.", "Delete", "Cancel"); } if (delete) { DestroyImmediate(track); } return delete; } /// <summary> /// Deletes a clip by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneClip/Delete Clip")] - static bool DeleteClip (MenuCommand command) { + static bool DeleteClip (MenuCommand command) + { return DeleteClip(command.context as CutsceneClip); } /// <summary> /// Deletes a clip. /// </summary> /// <param name="clip">The clip to delete.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> - static bool DeleteClip (CutsceneClip clip) { + static bool DeleteClip (CutsceneClip clip) + { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Clip", "Are you sure you wish to delete this clip? Changes cannot be undone.", "Delete", "Cancel"); } clip.setToDelete = delete; return delete; } /// <summary> /// Selects the track at the specified index. /// </summary> /// <param name="index">The track to select.</param> - void SelectTrackAtIndex (int index) { + void SelectTrackAtIndex (int index) + { if (scene.tracks.Length > 0 && index > 0 && index <= scene.tracks.Length) { selectedTrack = scene.tracks[index - 1]; EDebug.Log("Cutscene Editor: track " + index + " is selected"); } } /// <summary> /// Determines which key command is pressed and responds accordingly. /// </summary> /// <param name="keyDownEvent">The keyboard event.</param> /// <returns>True if the keyboard shortcut exists, false otherwise.</returns> - public void HandleKeyboardShortcuts (Event keyDownEvent) { + public void HandleKeyboardShortcuts (Event keyDownEvent) + { KeyCode key = keyDownEvent.keyCode; // Tools: // Move/resize if (key == CutsceneHotkeys.MoveResizeTool.key) { currentTool = Tool.MoveResize; EDebug.Log("Cutscene Editor: switching to Move/Resize tool"); // Scissors } else if (key == CutsceneHotkeys.ScissorsTool.key) { currentTool = Tool.Scissors; EDebug.Log("Cutscene Editor: switching to Scissors tool"); // Zoom } else if (key == CutsceneHotkeys.ZoomTool.key) { currentTool = Tool.Zoom; EDebug.Log("Cutscene Editor: switching to Zoom tool"); } // Timeline navigation: // Set in point else if (key == CutsceneHotkeys.SetInPont.key) { scene.inPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting in point"); // Set out point } else if (key == CutsceneHotkeys.SetOutPoint.key) { scene.outPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting out point"); // Scrub left } else if (keyDownEvent.Equals(Event.KeyboardEvent("left"))) { scene.playhead -= CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead left"); // Scrub left large } else if (keyDownEvent.Equals(Event.KeyboardEvent("#left"))) { scene.playhead -= CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead left"); // Scrub right } else if (keyDownEvent.Equals(Event.KeyboardEvent("right"))) { scene.playhead += CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead right"); // Scrub right large } else if (keyDownEvent.Equals(Event.KeyboardEvent("#right"))) { scene.playhead += CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead right"); // Go to previous split point } else if (keyDownEvent.Equals(Event.KeyboardEvent("up"))) { scene.playhead = selectedTrack.GetTimeOfNextSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to previous split point"); // Go to next split point } else if (keyDownEvent.Equals(Event.KeyboardEvent("down"))) { scene.playhead = selectedTrack.GetTimeOfPreviousSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to next split point"); // Go to in point } else if (keyDownEvent.Equals(Event.KeyboardEvent("#up"))) { scene.playhead = scene.inPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); // Go to out point } else if (keyDownEvent.Equals(Event.KeyboardEvent("#down"))) { scene.playhead = scene.outPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); } // Track selection: // Select track 1 else if (key == CutsceneHotkeys.SelectTrack1.key) { SelectTrackAtIndex(1); // Select track 2 } else if (key == CutsceneHotkeys.SelectTrack2.key) { SelectTrackAtIndex(2); // Select track 3 } else if (key == CutsceneHotkeys.SelectTrack3.key) { SelectTrackAtIndex(3); // Select track 4 } else if (key == CutsceneHotkeys.SelectTrack4.key) { SelectTrackAtIndex(4); // Select track 5 } else if (key == CutsceneHotkeys.SelectTrack5.key) { SelectTrackAtIndex(5); // Select track 6 } else if (key == CutsceneHotkeys.SelectTrack6.key) { SelectTrackAtIndex(6); // Select track 7 } else if (key == CutsceneHotkeys.SelectTrack7.key) { SelectTrackAtIndex(7); // Select track 8 } else if (key == CutsceneHotkeys.SelectTrack8.key) { SelectTrackAtIndex(8); // Select track 9 } else if (key == CutsceneHotkeys.SelectTrack9.key) { SelectTrackAtIndex(9); } // Other: else { EDebug.Log("Cutscene Editor: unknown keyboard shortcut " + keyDownEvent); return; } // If we get to this point, a shortcut matching the user's keystroke has been found Event.current.Use(); } - public static float PaneTabsWidth (int count) { + public static float PaneTabsWidth (int count) + { return count * 80f; } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneEffectsWindow.cs b/Cutscene Ed/Editor/CutsceneEffectsWindow.cs index d1207f7..906d9e4 100755 --- a/Cutscene Ed/Editor/CutsceneEffectsWindow.cs +++ b/Cutscene Ed/Editor/CutsceneEffectsWindow.cs @@ -1,128 +1,131 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; using System; using System.Collections.Generic; -class CutsceneEffectsWindow : ICutsceneGUI { +class CutsceneEffectsWindow : ICutsceneGUI +{ readonly CutsceneEditor ed; static Dictionary<string, Type> filters = new Dictionary<string, Type> { { CutsceneBlurFilter.name, typeof(CutsceneBlurFilter) }, { CutsceneInvertFilter.name, typeof(CutsceneInvertFilter) } }; static Dictionary<string, Type> transitions = new Dictionary<string, Type> {}; static readonly GUIContent filtersLabel = new GUIContent("Filters", "Full screen filters."); static readonly GUIContent transitionsLabel = new GUIContent("Transitions", "Camera transitions."); readonly GUIContent[] effectsTabs = CutsceneEditor.HasPro ? new GUIContent[] { filtersLabel, transitionsLabel } : new GUIContent[] { transitionsLabel }; Cutscene.EffectType currentEffectsTab = Cutscene.EffectType.Filters; Type selectedEffect; readonly Texture[] effectsIcons = { EditorGUIUtility.LoadRequired("Cutscene Ed/effects_filter.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/effects_transition.png") as Texture }; - public CutsceneEffectsWindow (CutsceneEditor ed) { + public CutsceneEffectsWindow (CutsceneEditor ed) + { this.ed = ed; } /// <summary> /// Displays the effects pane's GUI. /// </summary> /// <param name="rect">The effects pane's Rect.</param> - public void OnGUI (Rect rect) { + public void OnGUI (Rect rect) + { GUILayout.BeginArea(rect, ed.style.GetStyle("Pane")); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); currentEffectsTab = (Cutscene.EffectType)GUILayout.Toolbar((int)currentEffectsTab, effectsTabs, GUILayout.Width(CutsceneEditor.PaneTabsWidth(effectsTabs.Length))); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); GUI.enabled = ed.selectedClip != null && ed.selectedClip.type == Cutscene.MediaType.Shots && selectedEffect != null; GUIContent applyLabel = new GUIContent("Apply", "Apply the selected effect to the selected clip."); if (GUILayout.Button(applyLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { if (ed.selectedClip != null) { ed.selectedClip.ApplyEffect(selectedEffect); } } GUI.enabled = true; EditorGUILayout.EndHorizontal(); switch (currentEffectsTab) { case Cutscene.EffectType.Filters: foreach (KeyValuePair<string, Type> item in filters) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedEffect == item.Value ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent filterLabel = new GUIContent(item.Key, effectsIcons[(int)Cutscene.EffectType.Filters]); GUILayout.Label(filterLabel); EditorGUILayout.EndHorizontal(); // Handle clicks if (Event.current.type == EventType.MouseDown && itemRect.Contains(Event.current.mousePosition)) { selectedEffect = item.Value; Event.current.Use(); } } break; case Cutscene.EffectType.Transitions: foreach (KeyValuePair<string, Type> item in transitions) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedEffect == item.Value ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent transitionLabel = new GUIContent(item.Key, effectsIcons[(int)Cutscene.EffectType.Transitions]); GUILayout.Label(transitionLabel); EditorGUILayout.EndHorizontal(); // Handle clicks if (Event.current.type == EventType.MouseDown && itemRect.Contains(Event.current.mousePosition)) { selectedEffect = item.Value; Event.current.Use(); } } break; default: break; } GUILayout.EndArea(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneHotkeys.cs b/Cutscene Ed/Editor/CutsceneHotkeys.cs index 5def824..34f98ea 100755 --- a/Cutscene Ed/Editor/CutsceneHotkeys.cs +++ b/Cutscene Ed/Editor/CutsceneHotkeys.cs @@ -1,102 +1,107 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; -struct Hotkey { +struct Hotkey +{ const string prefPrefix = "Cutscene Editor Hotkey "; string id; KeyCode defaultKey; bool assignable; public KeyCode key { get { if (assignable && EditorPrefs.HasKey(prefPrefix + id)) { return (KeyCode)EditorPrefs.GetInt(prefPrefix + id, (int)defaultKey); } else { return defaultKey; } } set { if (assignable) { EditorPrefs.SetInt(prefPrefix + id, (int)value); } else { EDebug.LogWarning("Cutscene Editor: Hotkey " + id + " cannot be reassigned"); } } } - public Hotkey (string id, KeyCode defaultKey, bool assignable) { + public Hotkey (string id, KeyCode defaultKey, bool assignable) + { this.id = id; this.defaultKey = defaultKey; this.assignable = assignable; } /// <summary> /// Resets the key to its default value. /// </summary> - public void Reset () { + public void Reset () + { if (assignable) { key = defaultKey; } EDebug.Log("Cutscene Editor: Hotkey " + id + " reset to its default " + defaultKey); } } -static class CutsceneHotkeys { +static class CutsceneHotkeys +{ // Assignable: public static Hotkey MoveResizeTool = new Hotkey("moveResizeTool", KeyCode.M, true); public static Hotkey ScissorsTool = new Hotkey("scissorsTool", KeyCode.S, true); public static Hotkey ZoomTool = new Hotkey("zoomTool", KeyCode.Z, true); public static Hotkey SetInPont = new Hotkey("setInPoint", KeyCode.I, true); public static Hotkey SetOutPoint = new Hotkey("setOutPoint", KeyCode.O, true); // Unassignable: public static readonly Hotkey SelectTrack1 = new Hotkey("selectTrack1", KeyCode.Alpha1, true); public static readonly Hotkey SelectTrack2 = new Hotkey("selectTrack2", KeyCode.Alpha2, true); public static readonly Hotkey SelectTrack3 = new Hotkey("selectTrack3", KeyCode.Alpha3, true); public static readonly Hotkey SelectTrack4 = new Hotkey("selectTrack4", KeyCode.Alpha4, true); public static readonly Hotkey SelectTrack5 = new Hotkey("selectTrack5", KeyCode.Alpha5, true); public static readonly Hotkey SelectTrack6 = new Hotkey("selectTrack6", KeyCode.Alpha6, true); public static readonly Hotkey SelectTrack7 = new Hotkey("selectTrack7", KeyCode.Alpha7, true); public static readonly Hotkey SelectTrack8 = new Hotkey("selectTrack8", KeyCode.Alpha8, true); public static readonly Hotkey SelectTrack9 = new Hotkey("selectTrack9", KeyCode.Alpha9, true); public static Hotkey[] assignable = new Hotkey[] { MoveResizeTool, ScissorsTool, ZoomTool, SetInPont, SetOutPoint }; /// <summary> /// Resets all the assignable hotkeys to their default values. /// </summary> - public static void ResetAll () { + public static void ResetAll () + { foreach (Hotkey key in assignable) { key.Reset(); } } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneInspector.cs b/Cutscene Ed/Editor/CutsceneInspector.cs index 28ef2a0..e4d241f 100755 --- a/Cutscene Ed/Editor/CutsceneInspector.cs +++ b/Cutscene Ed/Editor/CutsceneInspector.cs @@ -1,111 +1,115 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; /// <summary> /// A custom inspector for a cutscene. /// </summary> [CustomEditor(typeof(Cutscene))] -public class CutsceneInspector : Editor { +public class CutsceneInspector : Editor +{ Cutscene scene { get { return target as Cutscene; } } - public override void OnInspectorGUI () { + public override void OnInspectorGUI () + { /* GUILayout.Label("Timing", EditorStyles.boldLabel); GUIContent durationLabel = new GUIContent("Duration", "The entire length of the cutscene."); scene.duration = EditorGUILayout.FloatField(durationLabel, scene.duration); // Instead of trying to clamp the values of the in and out points by slider leftValue and rightValue of the slider, we leave it to the Cutscene class GUIContent inPointLabel = new GUIContent("In", "The point at which the cutscene starts."); scene.inPoint = EditorGUILayout.Slider(inPointLabel, scene.inPoint, 0f, scene.duration); GUIContent outPointLabel = new GUIContent("Out", "The point at which the cutscene ends."); scene.outPoint = EditorGUILayout.Slider(outPointLabel, scene.outPoint, 0f, scene.duration); GUILayout.Label("Options", EditorStyles.boldLabel); GUIContent stopPlayerLabel = new GUIContent("Stop Player", "Deactivate the player when the scene starts."); scene.stopPlayer = EditorGUILayout.Toggle(stopPlayerLabel, scene.stopPlayer); // Disable the player reference box if the stop player toggle in unchecked GUI.enabled = scene.stopPlayer ? true : false; GUIContent playerLabel = new GUIContent("Player", "The player to deactivate."); scene.player = EditorGUILayout.ObjectField(playerLabel, scene.player, typeof(GameObject)) as GameObject; GUI.enabled = true; EditorGUILayout.Separator();*/ DrawDefaultInspector(); if (GUILayout.Button("Edit")) { CutsceneEditor.OpenEditor(); } if (GUI.changed) { EditorUtility.SetDirty(target); } } - public void OnSceneGUI () { + public void OnSceneGUI () + { Handles.BeginGUI(); GUI.Box(new Rect(0, Screen.height - 300, 200, 30), "Cutscene Preview"); //Rect camRect = GUILayoutUtility.GetRect(100, 100); if (scene != null) { Camera cam = null; foreach (CutsceneTrack track in scene.tracks) { if (track.type == Cutscene.MediaType.Shots) { CutsceneClip clip = track.ContainsClipAtTime(scene.playhead); if (clip != null) { cam = ((CutsceneShot)clip.master).camera; break; } } } if (cam != null) { DrawCamera(new Rect(0, 0, 200, 200), cam); } } Handles.EndGUI(); } - void DrawCamera (Rect previewRect, Camera camera) { + void DrawCamera (Rect previewRect, Camera camera) + { if (Event.current.type == EventType.Repaint) { Rect cameraOriginalRect = camera.pixelRect; camera.pixelRect = previewRect; camera.Render(); camera.pixelRect = cameraOriginalRect; } } } diff --git a/Cutscene Ed/Editor/CutsceneMediaWindow.cs b/Cutscene Ed/Editor/CutsceneMediaWindow.cs index f44f0ae..5b958cb 100755 --- a/Cutscene Ed/Editor/CutsceneMediaWindow.cs +++ b/Cutscene Ed/Editor/CutsceneMediaWindow.cs @@ -1,308 +1,314 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; -class CutsceneMediaWindow : ICutsceneGUI { +class CutsceneMediaWindow : ICutsceneGUI +{ readonly CutsceneEditor ed; readonly GUIContent[] mediaTabs = { new GUIContent("Shots", "Camera views."), new GUIContent("Actors", "Animated game objects."), new GUIContent("Audio", "Dialog, background music and sound effects."), new GUIContent("Subtitles", "Textual versions of dialog.") }; Cutscene.MediaType currentMediaTab = Cutscene.MediaType.Shots; Vector2[] mediaScrollPos = new Vector2[4]; CutsceneMedia selectedMediaItem; readonly GUIContent newMediaLabel = new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/icon_add.png") as Texture, "Add new media."); readonly GUIContent insertMediaLabel = new GUIContent("Insert", "Insert the selected shot onto the timeline."); - public CutsceneMediaWindow (CutsceneEditor ed) { + public CutsceneMediaWindow (CutsceneEditor ed) + { this.ed = ed; } /// <summary> /// Displays the media pane's GUI. /// </summary> /// <param name="rect">The media pane's Rect.</param> - public void OnGUI (Rect rect) { + public void OnGUI (Rect rect) + { GUILayout.BeginArea(rect, ed.style.GetStyle("Pane")); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); currentMediaTab = (Cutscene.MediaType)GUILayout.Toolbar((int)currentMediaTab, mediaTabs, GUILayout.Width(CutsceneEditor.PaneTabsWidth(mediaTabs.Length))); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); switch (currentMediaTab) { case Cutscene.MediaType.Shots: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { ed.scene.NewShot(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneShot shot in ed.scene.shots) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == shot ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(shot.name, ed.mediaIcons[(int)Cutscene.MediaType.Shots]); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(shot, itemRect); } EditorGUILayout.EndScrollView(); break; case Cutscene.MediaType.Actors: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { CutsceneAddActor.CreateWizard(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneActor actor in ed.scene.actors) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == actor ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(actor.anim.name, ed.mediaIcons[(int)Cutscene.MediaType.Actors]); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(actor, itemRect); } EditorGUILayout.EndScrollView(); break; case Cutscene.MediaType.Audio: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { // Show a wizard that will take care of adding audio CutsceneAddAudio.CreateWizard(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneAudio aud in ed.scene.audioSources) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == aud ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(aud.name, ed.mediaIcons[(int)Cutscene.MediaType.Audio]); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(aud, itemRect); } EditorGUILayout.EndScrollView(); break; case Cutscene.MediaType.Subtitles: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { // Show a wizard that will take care of adding audio CutsceneAddSubtitle.CreateWizard(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneSubtitle subtitle in ed.scene.subtitles) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == subtitle ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(ed.mediaIcons[(int)Cutscene.MediaType.Subtitles]); GUILayout.Label(itemLabel, GUILayout.ExpandWidth(false)); subtitle.dialog = EditorGUILayout.TextField(subtitle.dialog); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(subtitle, itemRect); } EditorGUILayout.EndScrollView(); break; default: break; } GUILayout.EndArea(); // Handle drag and drop events if (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform) { // Show a copy icon on the drag DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (Event.current.type == EventType.DragPerform && rect.Contains(Event.current.mousePosition)) { DragAndDrop.AcceptDrag(); Object[] draggedObjects = DragAndDrop.objectReferences; // Create the appropriate cutscene objects for each dragged object foreach (Object obj in draggedObjects) { if (obj is AudioClip) { ed.scene.NewAudio((AudioClip)obj); } else if (obj is GameObject && ((GameObject)obj).animation != null) { GameObject go = obj as GameObject; foreach (AnimationClip anim in AnimationUtility.GetAnimationClips(go.animation)) { ed.scene.NewActor(anim, go); } } EDebug.Log("Cutscene Editor: dropping " + obj.GetType()); } } Event.current.Use(); } } /// <summary> /// Handles left and right mouse clicks of media items. /// </summary> /// <param name="item">The item clicked on.</param> /// <param name="rect">The item's Rect.</param> - void HandleMediaItemClicks (CutsceneMedia item, Rect rect) { + void HandleMediaItemClicks (CutsceneMedia item, Rect rect) + { Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && rect.Contains(mousePos)) { switch (Event.current.button) { case 0: // Left click selectedMediaItem = item; EditorGUIUtility.PingObject(item); break; case 1: // Right click EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneObject/", new MenuCommand(item)); break; default: break; } Event.current.Use(); } } /// <summary> /// Determines whether or not the currently selected cutscene object can be inserted into the selected timeline. /// </summary> /// <returns>True if the selected clip and the selected track are the same, false otherwise.</returns> - bool IsMediaInsertable () { + bool IsMediaInsertable () + { return selectedMediaItem != null && selectedMediaItem.type == ed.selectedTrack.type; } /// <summary> /// Inserts the given cutscene object into the timeline. /// </summary> /// <param name="obj">The cutscene object to insert.</param> - void Insert (CutsceneMedia obj) { + void Insert (CutsceneMedia obj) + { CutsceneClip newClip = new CutsceneClip(obj); newClip.timelineStart = ed.scene.playhead; // If there are no existing tracks, add a new one if (ed.scene.tracks.Length == 0) { ed.scene.AddTrack(newClip.type); } // Manage overlap with other clips CutsceneClip existingClip = ed.selectedTrack.ContainsClipAtTime(ed.scene.playhead); if (existingClip != null) { CutsceneClip middleOfSplit = CutsceneTimeline.SplitClipAtTime(ed.scene.playhead, ed.selectedTrack, existingClip); CutsceneTimeline.SplitClipAtTime(ed.scene.playhead + newClip.duration, ed.selectedTrack, middleOfSplit); ed.selectedTrack.clips.Remove(middleOfSplit); } ed.selectedTrack.clips.Add(newClip); EDebug.Log("Cutscene Editor: inserting " + newClip.name + " into timeline " + ed.selectedTrack + " at " + ed.scene.playhead); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneNavigation.cs b/Cutscene Ed/Editor/CutsceneNavigation.cs index 2e273e3..ff9154c 100755 --- a/Cutscene Ed/Editor/CutsceneNavigation.cs +++ b/Cutscene Ed/Editor/CutsceneNavigation.cs @@ -1,63 +1,66 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; -class CutsceneNavigation : ICutsceneGUI { +class CutsceneNavigation : ICutsceneGUI +{ readonly CutsceneEditor ed; readonly ICutsceneGUI playbackControls; readonly ICutsceneGUI timecodeBar; readonly GUIContent zoomButton = new GUIContent("", "Zoom timeline to entire scene."); - public CutsceneNavigation (CutsceneEditor ed) { + public CutsceneNavigation (CutsceneEditor ed) + { this.ed = ed; playbackControls = new CutscenePlaybackControls(ed); timecodeBar = new CutsceneTimecodeBar(ed); } - public void OnGUI (Rect rect) { + public void OnGUI (Rect rect) + { GUI.BeginGroup(rect); float zoomButtonWidth = GUI.skin.verticalScrollbar.fixedWidth; float timecodeBarWidth = ed.position.width - CutsceneTimeline.trackInfoWidth - zoomButtonWidth; // Playback controls Rect playbackControlsRect = new Rect(0, 0, CutsceneTimeline.trackInfoWidth, rect.height); playbackControls.OnGUI(playbackControlsRect); // Timecode bar Rect timecodeBarRect = new Rect(playbackControlsRect.xMax, 0, timecodeBarWidth, rect.height); timecodeBar.OnGUI(timecodeBarRect); // Zoom to view entire project Rect zoomButtonRect = new Rect(timecodeBarRect.xMax, 0, zoomButtonWidth, rect.height); if (GUI.Button(zoomButtonRect, zoomButton, EditorStyles.toolbarButton)) { ed.timelineZoom = ed.timelineMin; EDebug.Log("Cutscene Editor: zoomed timeline to entire scene"); } GUI.EndGroup(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneOptions.cs b/Cutscene Ed/Editor/CutsceneOptions.cs index 1a4d995..8004fc9 100755 --- a/Cutscene Ed/Editor/CutsceneOptions.cs +++ b/Cutscene Ed/Editor/CutsceneOptions.cs @@ -1,44 +1,47 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; -class CutsceneOptions : ICutsceneGUI { +class CutsceneOptions : ICutsceneGUI +{ readonly CutsceneEditor ed; - public CutsceneOptions (CutsceneEditor ed) { + public CutsceneOptions (CutsceneEditor ed) + { this.ed = ed; } /// <summary> /// Displays the options window. /// </summary> /// <param name="rect">The options window's Rect.</param> - public void OnGUI (Rect rect) { + public void OnGUI (Rect rect) + { GUILayout.BeginArea(rect); ed.scene.inPoint = GUILayout.HorizontalSlider(ed.scene.inPoint, 0, 100); GUILayout.EndArea(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutscenePlaybackControls.cs b/Cutscene Ed/Editor/CutscenePlaybackControls.cs index 7f93c81..622223e 100755 --- a/Cutscene Ed/Editor/CutscenePlaybackControls.cs +++ b/Cutscene Ed/Editor/CutscenePlaybackControls.cs @@ -1,97 +1,100 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; -class CutscenePlaybackControls : ICutsceneGUI { +class CutscenePlaybackControls : ICutsceneGUI +{ readonly CutsceneEditor ed; const int buttonWidth = 18; readonly GUIContent inPointLabel = new GUIContent( EditorGUIUtility.LoadRequired("Cutscene Ed/playback_in.png") as Texture, "Go to in point." ); readonly GUIContent backLabel = new GUIContent( EditorGUIUtility.LoadRequired("Cutscene Ed/playback_back.png") as Texture, "Go back a second." ); /* readonly GUIContent playLabel = new GUIContent( EditorGUIUtility.LoadRequired("Cutscene Ed/playback_play.png") as Texture, "Play." ); */ readonly GUIContent forwardLabel = new GUIContent( EditorGUIUtility.LoadRequired("Cutscene Ed/playback_forward.png") as Texture, "Go forward a second." ); readonly GUIContent outPointLabel = new GUIContent( EditorGUIUtility.LoadRequired("Cutscene Ed/playback_out.png") as Texture, "Go to out point." ); - public CutscenePlaybackControls (CutsceneEditor ed) { + public CutscenePlaybackControls (CutsceneEditor ed) + { this.ed = ed; } /// <summary> /// Displays playback controls. /// </summary> /// <param name="rect">The playback controls' Rect.</param> - public void OnGUI (Rect rect) { + public void OnGUI (Rect rect) + { GUI.BeginGroup(rect, EditorStyles.toolbar); // In point Rect inPointRect = new Rect(6, 0, buttonWidth, rect.height); if (GUI.Button(inPointRect, inPointLabel, EditorStyles.toolbarButton)) { ed.scene.playhead = ed.scene.inPoint; } // Back Rect backRect = new Rect(inPointRect.xMax, 0, buttonWidth, rect.height); if (GUI.Button(backRect, backLabel, EditorStyles.toolbarButton)) { ed.scene.playhead -= CutsceneTimeline.scrubSmallJump; } /* Feature not implemented yet: // Play Rect playRect = new Rect(backRect.xMax, 0, buttonWidth, rect.height); if (GUI.Button(playRect, playLabel, EditorStyles.toolbarButton)) { EDebug.Log("Cutscene Editor: previewing scene (feature not implemented)"); };*/ // Forward Rect forwardRect = new Rect(backRect.xMax, 0, buttonWidth, rect.height); if (GUI.Button(forwardRect, forwardLabel, EditorStyles.toolbarButton)) { ed.scene.playhead += CutsceneTimeline.scrubSmallJump; } // Out point Rect outPointRect = new Rect(forwardRect.xMax, 0, buttonWidth, rect.height); if (GUI.Button(outPointRect, outPointLabel, EditorStyles.toolbarButton)) { ed.scene.playhead = ed.scene.outPoint; } Rect floatRect = new Rect(outPointRect.xMax + 4, 2, 50, rect.height); ed.scene.playhead = EditorGUI.FloatField(floatRect, ed.scene.playhead, EditorStyles.toolbarTextField); GUI.EndGroup(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutscenePreview.cs b/Cutscene Ed/Editor/CutscenePreview.cs index 8f01fab..3447f60 100755 --- a/Cutscene Ed/Editor/CutscenePreview.cs +++ b/Cutscene Ed/Editor/CutscenePreview.cs @@ -1,70 +1,73 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; using UnityEditor; -class CutscenePreview : ICutsceneGUI { +class CutscenePreview : ICutsceneGUI +{ //readonly CutsceneEditor ed; - public CutscenePreview (CutsceneEditor ed) { + public CutscenePreview (CutsceneEditor ed) + { //this.ed = ed; } - public void OnGUI (Rect rect) { + public void OnGUI (Rect rect) + { //GUI.DrawTexture(rect, ); Camera cam = GameObject.Find("Some Cam").GetComponent<Camera>(); EDebug.Log(cam.name); cam.targetTexture = new RenderTexture(128, 128, 32); cam.targetTexture.isPowerOfTwo = true; cam.targetTexture.Create(); GUI.DrawTexture(rect, cam.targetTexture); cam.targetTexture.Release(); cam.targetTexture = null; /*if (Event.current.type == EventType.repaint) { MovieTexture target = base.target as MovieTexture; float num = Mathf.Min(Mathf.Min((float)(r.width / ((float)target.width)), (float)(r.height / ((float)target.height))), 1f); Rect viewRect = new Rect(r.x, r.y, target.width * num, target.height * num); PreviewGUI.BeginScrollView(r, this.m_Pos, viewRect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb"); GUI.DrawTexture(viewRect, target, ScaleMode.StretchToFill, false); this.m_Pos = PreviewGUI.EndScrollView(); if (target.isPlaying) { GUIView.current.Repaint(); } if (Application.isPlaying) { if (target.isPlaying) { Rect position = new Rect(r.x, r.y + 10f, r.width, 20f); EditorGUI.DropShadowLabel(position, "Can't pause preview when in play mode"); } else { Rect rect3 = new Rect(r.x, r.y + 10f, r.width, 20f); EditorGUI.DropShadowLabel(rect3, "Can't start preview when in play mode"); } } }*/ } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneSubtitleInspector.cs b/Cutscene Ed/Editor/CutsceneSubtitleInspector.cs index 51b96a1..a4f875b 100644 --- a/Cutscene Ed/Editor/CutsceneSubtitleInspector.cs +++ b/Cutscene Ed/Editor/CutsceneSubtitleInspector.cs @@ -1,47 +1,49 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; /// <summary> /// A custom inspector for a subtitle. /// </summary> [CustomEditor (typeof(CutsceneSubtitle))] -public class CutsceneSubtitleInspector : Editor { +public class CutsceneSubtitleInspector : Editor +{ CutsceneSubtitle subtitle { get { return target as CutsceneSubtitle; } } - public override void OnInspectorGUI () { + public override void OnInspectorGUI () + { EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Dialog"); subtitle.dialog = EditorGUILayout.TextArea(subtitle.dialog); EditorGUILayout.EndHorizontal(); if (GUI.changed) { EditorUtility.SetDirty(subtitle); } } } diff --git a/Cutscene Ed/Editor/CutsceneTimecodeBar.cs b/Cutscene Ed/Editor/CutsceneTimecodeBar.cs index 328d11b..bafb6a4 100755 --- a/Cutscene Ed/Editor/CutsceneTimecodeBar.cs +++ b/Cutscene Ed/Editor/CutsceneTimecodeBar.cs @@ -1,183 +1,192 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; using UnityEditor; -class CutsceneTimecodeBar : ICutsceneGUI { +class CutsceneTimecodeBar : ICutsceneGUI +{ readonly CutsceneEditor ed; const int shortTickHeight = 3; const int tallTickHeight = 6; readonly Color tickColor = Color.gray; readonly Color playheadBlockColor = Color.black; readonly Color inOutPointColour = Color.cyan; readonly Texture positionIndicatorIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/position_indicator.png") as Texture; readonly Texture inPointIndicatorIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/inpoint_indicator.png") as Texture; readonly Texture outPointIndicatorIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/outpoint_indicator.png") as Texture; readonly GUIContent inTooltip = new GUIContent("", "In point."); readonly GUIContent outTooltip = new GUIContent("", "Out point."); - public CutsceneTimecodeBar (CutsceneEditor ed) { + public CutsceneTimecodeBar (CutsceneEditor ed) + { this.ed = ed; } /// <summary> /// Displays the timecode bar with vertical lines indicating the time and the playhead. /// </summary> /// <param name="rect">The timecode bar's Rect.</param> - public void OnGUI (Rect rect) { + public void OnGUI (Rect rect) + { GUI.BeginGroup(rect); // Create a button that looks like a toolbar if (GUI.RepeatButton(new Rect(0, 0, rect.width, rect.height), GUIContent.none, EditorStyles.toolbar)) { float position = Event.current.mousePosition.x + ed.timelineScrollPos.x; ed.scene.playhead = position / ed.timelineZoom; // Show a visual notification of the position GUIContent notification = new GUIContent("Playhead " + ed.scene.playhead.ToString("N2")); ed.ShowNotification(notification); ed.Repaint(); //SceneView.RepaintAll(); } else { // TODO Investigate if attempting to remove the notification every frame like this is wasteful ed.RemoveNotification(); } DrawTicks(); DrawLabels(); DrawPlayhead(); DrawInOutPoints(); GUI.EndGroup(); } /// <summary> /// Draws vertical lines representing time increments. /// </summary> - void DrawTicks () { + void DrawTicks () + { Handles.color = tickColor; // Draw short ticks every second for (float i = 0; i < ed.scene.duration * ed.timelineZoom; i += ed.timelineZoom) { float xPos = i - ed.timelineScrollPos.x; Handles.DrawLine(new Vector3(xPos, 0, 0), new Vector3(xPos, shortTickHeight)); } // Draw tall ticks every ten seconds for (float i = 0; i < ed.scene.duration * ed.timelineZoom; i += ed.timelineZoom * 10) { float xPos = i - ed.timelineScrollPos.x; Handles.DrawLine(new Vector3(xPos, 0, 0), new Vector3(xPos, tallTickHeight)); } } /// <summary> /// Draws labels indicating the time. /// </summary> - void DrawLabels () { + void DrawLabels () + { for (float i = 0; i < 1000; i += 10) { float xPos = (i * ed.timelineZoom) - ed.timelineScrollPos.x; GUIContent label = new GUIContent(i + ""); Vector2 dimensions = EditorStyles.miniLabel.CalcSize(label); Rect labelRect = new Rect(xPos - (dimensions.x / 2), 2, dimensions.x, dimensions.y); GUI.Label(labelRect, label, EditorStyles.miniLabel); } } /// <summary> /// Draws the playhead. /// </summary> - void DrawPlayhead () { + void DrawPlayhead () + { // Draw position indicator float pos = (ed.scene.playhead * ed.timelineZoom) - ed.timelineScrollPos.x; GUI.DrawTexture(new Rect(pos - 4, 0, 8, 8), positionIndicatorIcon); Handles.color = Color.black; // Vertical line Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, EditorStyles.toolbar.fixedHeight); Handles.DrawLine(top, bottom); // Zoom indicator block Handles.color = playheadBlockColor; for (int i = 1; i <= ed.timelineZoom; i++) { float xPos = pos + i; top = new Vector3(xPos, 4); bottom = new Vector3(xPos, EditorStyles.toolbar.fixedHeight - 1); Handles.DrawLine(top, bottom); } } /// <summary> /// Draws the in and out points. /// </summary> - void DrawInOutPoints () { + void DrawInOutPoints () + { Handles.color = inOutPointColour; DrawInPoint(); DrawOutPoint(); } /// <summary> /// Draws the in point. /// </summary> - void DrawInPoint () { + void DrawInPoint () + { float pos = (ed.scene.inPoint * ed.timelineZoom) - ed.timelineScrollPos.x; // Icon Rect indicatorRect = new Rect(pos, 0, 4, 8); GUI.DrawTexture(indicatorRect, inPointIndicatorIcon); // Tooltip GUI.Label(indicatorRect, inTooltip); // Vertical line Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, EditorStyles.toolbar.fixedHeight); Handles.DrawLine(top, bottom); } /// <summary> /// Draws the out point. /// </summary> - void DrawOutPoint () { + void DrawOutPoint () + { float pos = (ed.scene.outPoint * ed.timelineZoom) - ed.timelineScrollPos.x; // Icon Rect indicatorRect = new Rect(pos - 4, 0, 4, 8); GUI.DrawTexture(indicatorRect, outPointIndicatorIcon); // Tooltip GUI.Label(indicatorRect, outTooltip); // Vertical line Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, EditorStyles.toolbar.fixedHeight); Handles.DrawLine(top, bottom); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTimeline.cs b/Cutscene Ed/Editor/CutsceneTimeline.cs index 8b7db67..7ec7433 100755 --- a/Cutscene Ed/Editor/CutsceneTimeline.cs +++ b/Cutscene Ed/Editor/CutsceneTimeline.cs @@ -1,134 +1,139 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; public enum DragEvent { Move, ResizeLeft, ResizeRight } -class CutsceneTimeline : ICutsceneGUI { +class CutsceneTimeline : ICutsceneGUI +{ readonly CutsceneEditor ed; public const int scrubLargeJump = 10; public const int scrubSmallJump = 1; readonly ICutsceneGUI navigation; readonly ICutsceneGUI tracksView; readonly ICutsceneGUI trackControls; readonly ICutsceneGUI trackInfo; public const float timelineZoomMin = 1f; public const float timelineZoomMax = 100f; public const float trackInfoWidth = 160f; - public CutsceneTimeline (CutsceneEditor ed) { + public CutsceneTimeline (CutsceneEditor ed) + { this.ed = ed; navigation = new CutsceneNavigation(ed); tracksView = new CutsceneTracksView(ed); trackControls = new CutsceneTrackControls(ed); trackInfo = new CutsceneTrackInfo(ed); } /// <summary> /// Displays the timeline's GUI. /// </summary> /// <param name="rect">The timeline's Rect.</param> - public void OnGUI (Rect rect) { + public void OnGUI (Rect rect) + { GUILayout.BeginArea(rect); float rightColWidth = GUI.skin.verticalScrollbar.fixedWidth; float middleColWidth = rect.width - CutsceneTimeline.trackInfoWidth - rightColWidth; ed.timelineMin = CutsceneTimeline.timelineZoomMin * (middleColWidth / ed.scene.duration); ed.timelineZoom = Mathf.Clamp(ed.timelineZoom, ed.timelineMin, CutsceneTimeline.timelineZoomMax); // Navigation bar Rect navigationRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.toolbar, GUILayout.Width(rect.width)); navigation.OnGUI(navigationRect); // Begin Tracks EditorGUILayout.BeginHorizontal(GUILayout.Width(rect.width), GUILayout.ExpandHeight(true)); // Track info //Rect trackInfoRect = GUILayoutUtility.GetRect(trackInfoWidth, rect.height - navigationRect.yMax - GUI.skin.horizontalScrollbar.fixedHeight); Rect trackInfoRect = new Rect(0, 0, CutsceneTimeline.trackInfoWidth, 9999); trackInfo.OnGUI(trackInfoRect); // Track controls float trackControlsHeight = GUI.skin.horizontalScrollbar.fixedHeight; Rect trackControlsRect = new Rect(0, rect.height - trackControlsHeight, CutsceneTimeline.trackInfoWidth, trackControlsHeight); trackControls.OnGUI(trackControlsRect); // Tracks Rect tracksRect = new Rect(trackInfoRect.xMax, navigationRect.yMax, middleColWidth + rightColWidth, rect.height - navigationRect.yMax); tracksView.OnGUI(tracksRect); EditorGUILayout.EndHorizontal(); if (Event.current.type == EventType.KeyDown) { // Key presses ed.HandleKeyboardShortcuts(Event.current); } GUILayout.EndArea(); } /// <summary> /// Moves the playhead. /// </summary> /// <param name="playheadPos">The position to move the playhead to.</param> - void MovePlayheadToPosition (float playheadPos) { + void MovePlayheadToPosition (float playheadPos) + { ed.scene.playhead = playheadPos / ed.timelineZoom; } /// <summary> /// Splits a clip into two separate ones at the specified time. /// </summary> /// <param name="splitPoint">The time at which to split the clip.</param> /// <param name="track">The track the clip is sitting on.</param> /// <param name="clip">The clip to split.</param> /// <returns>The new clip.</returns> - public static CutsceneClip SplitClipAtTime (float splitPoint, CutsceneTrack track, CutsceneClip clip) { + public static CutsceneClip SplitClipAtTime (float splitPoint, CutsceneTrack track, CutsceneClip clip) + { CutsceneClip newClip = clip.GetCopy(); // Make sure the clip actually spans over the split point if (splitPoint < clip.timelineStart || splitPoint > clip.timelineStart + clip.duration) { EDebug.Log("Cutscene Editor: cannot split clip; clip does not contain the split point"); return null; } clip.SetOutPoint(clip.inPoint + (splitPoint - clip.timelineStart)); newClip.SetInPoint(clip.outPoint); newClip.SetTimelineStart(splitPoint); track.clips.Add(newClip); Event.current.Use(); EDebug.Log("Cutscene Editor: splitting clip at time " + splitPoint); return newClip; } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTools.cs b/Cutscene Ed/Editor/CutsceneTools.cs index eed5241..0014093 100755 --- a/Cutscene Ed/Editor/CutsceneTools.cs +++ b/Cutscene Ed/Editor/CutsceneTools.cs @@ -1,57 +1,60 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEditor; using UnityEngine; public enum Tool { MoveResize, Scissors, Zoom } -class CutsceneTools : ICutsceneGUI { +class CutsceneTools : ICutsceneGUI +{ readonly CutsceneEditor ed; readonly GUIContent[] tools = { new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_move.png") as Texture, "Move/Resize"), new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_scissors.png") as Texture, "Scissors"), new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_zoom.png") as Texture, "Zoom") }; - public CutsceneTools (CutsceneEditor ed) { + public CutsceneTools (CutsceneEditor ed) + { this.ed = ed; } - public void OnGUI (Rect rect) { + public void OnGUI (Rect rect) + { GUILayout.BeginArea(rect); EditorGUILayout.BeginHorizontal(ed.style.GetStyle("Tools Bar"), GUILayout.Width(rect.width)); GUILayout.FlexibleSpace(); ed.currentTool = (Tool)GUILayout.Toolbar((int)ed.currentTool, tools); EditorGUILayout.EndHorizontal(); GUILayout.EndArea(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTrackControls.cs b/Cutscene Ed/Editor/CutsceneTrackControls.cs index b34549a..6cd9041 100755 --- a/Cutscene Ed/Editor/CutsceneTrackControls.cs +++ b/Cutscene Ed/Editor/CutsceneTrackControls.cs @@ -1,61 +1,64 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; using UnityEditor; -class CutsceneTrackControls : ICutsceneGUI { +class CutsceneTrackControls : ICutsceneGUI +{ readonly CutsceneEditor ed; readonly GUIContent newTrackLabel = new GUIContent( EditorGUIUtility.LoadRequired("Cutscene Ed/icon_addtrack.png") as Texture, "Add a new track." ); - public CutsceneTrackControls (CutsceneEditor ed) { + public CutsceneTrackControls (CutsceneEditor ed) + { this.ed = ed; } - public void OnGUI (Rect rect) { + public void OnGUI (Rect rect) + { // TODO Make this a style in the cutscene editor's GUISkin GUIStyle popupStyle = "MiniToolbarButton"; popupStyle.padding = new RectOffset(0, 0, 2, 1); // Left, right, top, bottom GUI.BeginGroup(rect, GUI.skin.GetStyle("MiniToolbarButtonLeft")); // New track popdown Rect newTrackRect = new Rect(0, 0, 33, rect.height); GUI.Label(newTrackRect, newTrackLabel, popupStyle); if (Event.current.type == EventType.MouseDown && newTrackRect.Contains(Event.current.mousePosition)) { GUIUtility.hotControl = 0; EditorUtility.DisplayPopupMenu(newTrackRect, "Component/Cutscene/Track", null); Event.current.Use(); } // Timeline zoom slider Rect timelineZoomRect = new Rect(newTrackRect.xMax + GUI.skin.horizontalSlider.margin.left, -1, rect.width - newTrackRect.xMax - GUI.skin.horizontalSlider.margin.horizontal, rect.height); ed.timelineZoom = GUI.HorizontalSlider(timelineZoomRect, ed.timelineZoom, ed.timelineMin, CutsceneTimeline.timelineZoomMax); GUI.EndGroup(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTrackInfo.cs b/Cutscene Ed/Editor/CutsceneTrackInfo.cs index 10edba9..f9e04f0 100755 --- a/Cutscene Ed/Editor/CutsceneTrackInfo.cs +++ b/Cutscene Ed/Editor/CutsceneTrackInfo.cs @@ -1,109 +1,111 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; using UnityEditor; -class CutsceneTrackInfo : ICutsceneGUI { +class CutsceneTrackInfo : ICutsceneGUI +{ readonly CutsceneEditor ed; readonly GUIContent visibilityIcon = new GUIContent("", EditorGUIUtility.LoadRequired("Cutscene Ed/icon_eye.png") as Texture, "Toggle visibility." ); readonly GUIContent lockIcon = new GUIContent("", EditorGUIUtility.LoadRequired("Cutscene Ed/icon_lock.png") as Texture, "Toggle track lock." ); public CutsceneTrackInfo (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the track info GUI. /// </summary> /// <param name="rect">The track info's Rect.</param> - public void OnGUI (Rect rect) { + public void OnGUI (Rect rect) + { ed.timelineScrollPos.y = EditorGUILayout.BeginScrollView( new Vector2(0, ed.timelineScrollPos.y), false, false, ed.style.horizontalScrollbar, ed.style.verticalScrollbar, GUIStyle.none, GUILayout.Width(CutsceneTimeline.trackInfoWidth), GUILayout.ExpandHeight(true)).y; foreach (CutsceneTrack track in ed.scene.tracks) { if (track == ed.selectedTrack) { GUI.SetNextControlName("track"); } Rect infoRect = EditorGUILayout.BeginHorizontal(ed.style.GetStyle("Track Info")); track.enabled = GUILayout.Toggle(track.enabled, visibilityIcon, EditorStyles.miniButtonLeft, GUILayout.ExpandWidth(false)); track.locked = GUILayout.Toggle(track.locked, lockIcon, EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false)); GUILayout.Space(10); GUI.enabled = track.enabled; // Track name and icon GUIContent trackIcon = new GUIContent(ed.mediaIcons[(int)track.type]); GUILayout.Label(trackIcon, GUILayout.ExpandWidth(false)); // Set a minimum width to keep the label from becoming uneditable Rect trackNameRect = GUILayoutUtility.GetRect(new GUIContent(track.name), EditorStyles.miniLabel, GUILayout.ExpandWidth(false), GUILayout.MinWidth(20)); track.name = EditorGUI.TextField(trackNameRect, track.name, EditorStyles.miniLabel); GUI.enabled = true; EditorGUILayout.EndHorizontal(); if (track == ed.selectedTrack) { GUI.FocusControl("track"); } // Handle clicks Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && infoRect.Contains(mousePos)) { switch (Event.current.button) { case 0: // Left mouse button ed.selectedTrack = track; break; case 1: // Right mouse button EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneTrack/", new MenuCommand(track)); break; default: break; } Event.current.Use(); } } // Divider line Handles.color = Color.grey; Handles.DrawLine(new Vector3(67, 0), new Vector3(67, rect.yMax)); EditorGUILayout.EndScrollView(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTracksView.cs b/Cutscene Ed/Editor/CutsceneTracksView.cs index 7a09858..2725491 100755 --- a/Cutscene Ed/Editor/CutsceneTracksView.cs +++ b/Cutscene Ed/Editor/CutsceneTracksView.cs @@ -1,364 +1,374 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; using UnityEditor; -class CutsceneTracksView : ICutsceneGUI { +class CutsceneTracksView : ICutsceneGUI +{ readonly CutsceneEditor ed; readonly Texture overlay = EditorGUIUtility.LoadRequired("Cutscene Ed/overlay.png") as Texture; readonly Color inOutPointColour = Color.cyan; - public CutsceneTracksView (CutsceneEditor ed) { + public CutsceneTracksView (CutsceneEditor ed) + { this.ed = ed; } /// <summary> /// Displays the tracks GUI. /// </summary> /// <param name="rect">The tracks' Rect.</param> - public void OnGUI (Rect rect) { + public void OnGUI (Rect rect) + { // Display background Rect background = new Rect(rect.x, rect.y, rect.width - GUI.skin.verticalScrollbar.fixedWidth, rect.height - GUI.skin.horizontalScrollbar.fixedHeight); GUI.BeginGroup(background, GUI.skin.GetStyle("AnimationCurveEditorBackground")); GUI.EndGroup(); float trackHeight = ed.style.GetStyle("Track").fixedHeight + ed.style.GetStyle("Track").margin.vertical; // TODO Make the track width take into account clips that are beyond the out point float tracksWidth = (ed.scene.outPoint + 10) * ed.timelineZoom; float tracksHeight = trackHeight * ed.scene.tracks.Length; Rect view = new Rect(0, 0, Mathf.Max(background.width + 1, tracksWidth), Mathf.Max(background.height + 1, tracksHeight)); ed.timelineScrollPos = GUI.BeginScrollView(rect, ed.timelineScrollPos, view, true, true); // Zoom clicks if (ed.currentTool == Tool.Zoom && Event.current.type == EventType.MouseDown) { if (Event.current.alt && Event.current.shift) { // Zoom out all the way ed.timelineZoom = CutsceneTimeline.timelineZoomMin; } else if (Event.current.shift) { // Zoom in all the way ed.timelineZoom = CutsceneTimeline.timelineZoomMax; } else if (Event.current.alt) { // Zoom out ed.timelineZoom -= 10; } else { // Zoom in ed.timelineZoom += 10; } Event.current.Use(); } // Draw track divider lines Handles.color = Color.grey; for (int i = 0; i < ed.scene.tracks.Length; i++) { Rect trackRect = new Rect(0, trackHeight * i, view.width, trackHeight); DisplayTrack(trackRect, ed.scene.tracks[i]); float yPos = (i + 1) * trackHeight - 1; Handles.DrawLine(new Vector3(0, yPos), new Vector3(view.width, yPos)); } // Draw overlay over in area Rect inOverlay = new Rect(0, 0, ed.scene.inPoint * ed.timelineZoom, view.height); GUI.DrawTexture(inOverlay, overlay); // Draw overlay over out area Rect outOverlay = new Rect(ed.scene.outPoint * ed.timelineZoom, 0, 0, view.height); outOverlay.width = view.width - outOverlay.x; GUI.DrawTexture(outOverlay, overlay); DrawLines(view); GUI.EndScrollView(); } /// <summary> /// Displays visual tracks upon which clips sit. /// </summary> - void DisplayTrack (Rect rect, CutsceneTrack track) { + void DisplayTrack (Rect rect, CutsceneTrack track) + { GUI.enabled = track.enabled; for (int i = track.clips.Count - 1; i >= 0; i--) { DisplayClip(rect, track, track.clips[i]); } GUI.enabled = true; // Handle clicks Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && rect.Contains(mousePos)) { switch (Event.current.button) { case 0: // Left mouse button ed.selectedTrack = track; ed.selectedClip = null; break; case 1: // Right mouse button EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneTrack/", new MenuCommand(track)); Event.current.Use(); break; default: break; } Event.current.Use(); } } /// <summary> /// Displays a clip. /// </summary> /// <param name="trackRect">The Rect of the track the clip sits on.</param> /// <param name="track">The track the clip sits on.</param> /// <param name="clip">The clip to display.</param> - void DisplayClip (Rect trackRect, CutsceneTrack track, CutsceneClip clip) { + void DisplayClip (Rect trackRect, CutsceneTrack track, CutsceneClip clip) + { const float trimWidth = 5f; GUIStyle clipStyle = ed.style.GetStyle("Selected Clip"); // Set the clip style if this isn't the selected clip (selected clips all share the same style) if (clip != ed.selectedClip) { switch (clip.type) { case Cutscene.MediaType.Shots: clipStyle = ed.style.GetStyle("Shot Clip"); break; case Cutscene.MediaType.Actors: clipStyle = ed.style.GetStyle("Actor Clip"); break; case Cutscene.MediaType.Audio: clipStyle = ed.style.GetStyle("Audio Clip"); break; default: // Cutscene.MediaType.Subtitles clipStyle = ed.style.GetStyle("Subtitle Clip"); break; } } Rect rect = new Rect((trackRect.x + clip.timelineStart) * ed.timelineZoom, trackRect.y + 1, clip.duration * ed.timelineZoom, clipStyle.fixedHeight); GUI.BeginGroup(rect, clipStyle); GUIContent clipLabel = new GUIContent(clip.name, "Clip: " + clip.name + "\nDuration: " + clip.duration + "\nTimeline start: " + clip.timelineStart + "\nTimeline end: " + (clip.timelineStart + clip.duration)); Rect clipLabelRect = new Rect(clipStyle.contentOffset.x, 0, rect.width - clipStyle.contentOffset.x, rect.height); GUI.Label(clipLabelRect, clipLabel); GUI.EndGroup(); // Handle mouse clicks Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { switch (Event.current.button) { case 0: // Left mouse button ed.selectedClip = clip; ed.selectedTrack = track; break; case 1: // Right mouse button EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneClip/", new MenuCommand(clip)); Event.current.Use(); break; default: break; } } if (clip.setToDelete) { ed.selectedTrack.clips.Remove(clip); return; } // Don't allow actions to be performed on the clip if the track is disabled or locked if (!track.enabled || track.locked) { return; } switch (ed.currentTool) { case Tool.MoveResize: // Define edit areas, adding custom cursors when hovered over // Move Rect move = new Rect(rect.x + trimWidth, rect.y, rect.width - (2 * trimWidth), rect.height); EditorGUIUtility.AddCursorRect(move, MouseCursor.SlideArrow); // Resize left Rect resizeLeft = new Rect(rect.x, rect.y, trimWidth, rect.height); EditorGUIUtility.AddCursorRect(resizeLeft, MouseCursor.ResizeHorizontal); // Resize right Rect resizeRight = new Rect(rect.xMax - trimWidth, rect.y, trimWidth, rect.height); EditorGUIUtility.AddCursorRect(resizeRight, MouseCursor.ResizeHorizontal); if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { ed.dragClip = clip; // Move if (move.Contains(Event.current.mousePosition)) { ed.dragEvent = DragEvent.Move; EDebug.Log("Cutscene Editor: starting clip move"); // Resize left } else if (resizeLeft.Contains(Event.current.mousePosition)) { ed.dragEvent = DragEvent.ResizeLeft; EDebug.Log("Cutscene Editor: starting clip resize left"); // Resize right } else if (resizeRight.Contains(Event.current.mousePosition)) { ed.dragEvent = DragEvent.ResizeRight; EDebug.Log("Cutscene Editor: starting clip resize right"); } Event.current.Use(); } else if (Event.current.type == EventType.MouseDrag && ed.dragClip == clip) { float shift = Event.current.delta.x / ed.timelineZoom; switch (ed.dragEvent) { case DragEvent.Move: float newPos = clip.timelineStart + shift; // Left collisions CutsceneClip leftCollision = track.ContainsClipAtTime(newPos, clip); if (leftCollision != null) { newPos = leftCollision.timelineStart + leftCollision.duration; } // Right collisions CutsceneClip rightCollision = track.ContainsClipAtTime(newPos + clip.duration, clip); if (rightCollision != null) { newPos = rightCollision.timelineStart - clip.duration; } if (newPos + clip.duration > ed.scene.duration) { newPos = ed.scene.duration - clip.duration; } clip.SetTimelineStart(newPos); break; case DragEvent.ResizeLeft: clip.SetTimelineStart(clip.timelineStart + shift); clip.SetInPoint(clip.inPoint + shift); // TODO Improve collision behaviour CutsceneClip leftResizeCollision = track.ContainsClipAtTime(clip.timelineStart, clip); if (leftResizeCollision != null) { clip.SetTimelineStart(leftResizeCollision.timelineStart + leftResizeCollision.duration); } break; case DragEvent.ResizeRight: float newOut = clip.outPoint + shift; // Right collisions CutsceneClip rightResizeCollision = track.ContainsClipAtTime(clip.timelineStart + clip.duration + shift, clip); if (rightResizeCollision != null) { newOut = rightResizeCollision.timelineStart - clip.timelineStart + clip.inPoint; } clip.SetOutPoint(newOut); break; default: break; } Event.current.Use(); } else if (Event.current.type == EventType.MouseUp) { ed.dragClip = null; Event.current.Use(); } break; case Tool.Scissors: // TODO Switch to something better than the text cursor, if possible EditorGUIUtility.AddCursorRect(rect, MouseCursor.Text); if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { SplitClip(track, clip, Event.current.mousePosition); Event.current.Use(); } break; default: break; } } /// <summary> /// Splits a clip into two separate ones. /// </summary> /// <param name="track">The track the clip is sitting on.</param> /// <param name="clip">The clip to split.</param> /// <param name="mousePosition">The position of the mouse when the split operation occurred.</param> /// <returns>The new clip.</returns> - CutsceneClip SplitClip (CutsceneTrack track, CutsceneClip clip, Vector2 mousePosition) { + CutsceneClip SplitClip (CutsceneTrack track, CutsceneClip clip, Vector2 mousePosition) + { float splitPoint = mousePosition.x / ed.timelineZoom; return CutsceneTimeline.SplitClipAtTime(splitPoint, track, clip); } /// <summary> /// Draws the in, out, and playhead lines. /// </summary> /// <param name="rect">The timeline's Rect.</param> - void DrawLines (Rect rect) { + void DrawLines (Rect rect) + { DrawPlayhead(rect); Handles.color = inOutPointColour; DrawInLine(rect); DrawOutLine(rect); } /// <summary> /// Draws the playhead over the timeline. /// </summary> /// <param name="rect">The timeline's Rect.</param> - void DrawPlayhead (Rect rect) { + void DrawPlayhead (Rect rect) + { Handles.color = Color.black; float pos = ed.scene.playhead * ed.timelineZoom; Vector3 timelineTop = new Vector3(pos, 0); Vector3 timelineBottom = new Vector3(pos, rect.yMax); Handles.DrawLine(timelineTop, timelineBottom); } /// <summary> /// Draws the in point line over the timeline. /// </summary> /// <param name="rect">The timeline's Rect.</param> - void DrawInLine (Rect rect) { + void DrawInLine (Rect rect) + { float pos = ed.scene.inPoint * ed.timelineZoom; Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, rect.yMax); Handles.DrawLine(top, bottom); } /// <summary> /// Draws the out point line over the timeline. /// </summary> /// <param name="rect">The timeline's Rect.</param> - void DrawOutLine (Rect rect) { + void DrawOutLine (Rect rect) + { float pos = ed.scene.outPoint * ed.timelineZoom; Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, rect.yMax); Handles.DrawLine(top, bottom); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/ICutsceneGUI.cs b/Cutscene Ed/Editor/ICutsceneGUI.cs index 0c288ca..38ca89f 100755 --- a/Cutscene Ed/Editor/ICutsceneGUI.cs +++ b/Cutscene Ed/Editor/ICutsceneGUI.cs @@ -1,31 +1,32 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; -interface ICutsceneGUI { +interface ICutsceneGUI +{ /// <summary> /// Displays the GUI for this element. /// </summary> /// <param name="rect">The bounding box this element is contained in.</param> void OnGUI (Rect rect); } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/Cutscene.cs b/Cutscene Ed/Scripts/Cutscene.cs index 2bf6c48..a6c26e2 100755 --- a/Cutscene Ed/Scripts/Cutscene.cs +++ b/Cutscene Ed/Scripts/Cutscene.cs @@ -1,434 +1,462 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; using System.Collections; using System.Collections.Generic; // Functions to be run when the cutscene starts and finishes public delegate void CutsceneStart(); public delegate void CutscenePause(); public delegate void CutsceneEnd(); [RequireComponent(typeof(Animation))] -public class Cutscene : MonoBehaviour { +public class Cutscene : MonoBehaviour +{ public float duration = 30f; public float inPoint = 0f; public float outPoint = 30f; public bool stopPlayer = true; public GameObject player; public GUIStyle subtitleStyle; public Rect subtitlePosition = new Rect(0, 0, 400, 200); public CutsceneStart startFunction { get; set; } public CutscenePause pauseFunction { get; set; } public CutsceneEnd endFunction { get; set; } public enum MediaType { Shots, Actors, Audio, Subtitles } public enum EffectType { Filters, Transitions } public CutsceneTrack[] tracks { get { return GetComponentsInChildren<CutsceneTrack>(); } } public CutsceneShot[] shots { get { return GetComponentsInChildren<CutsceneShot>(); } } public CutsceneActor[] actors { get { return GetComponentsInChildren<CutsceneActor>(); } } public CutsceneAudio[] audioSources { get { return GetComponentsInChildren<CutsceneAudio>(); } } public CutsceneSubtitle[] subtitles { get { return GetComponentsInChildren<CutsceneSubtitle>(); } } CutsceneSubtitle currentSubtitle; public float playhead { get { return animation["master"].time; } set { animation["master"].time = Mathf.Clamp(value, 0f, duration); } } [HideInInspector] public AnimationClip masterClip; - void Start () { + void Start () + { SetupMasterAnimationClip(); SetupTrackAnimationClips(); DisableCameras(); DisableAudio(); } - void OnGUI () { + void OnGUI () + { /// Displays the current subtitle if there is one if (currentSubtitle == null) { return; } GUI.BeginGroup(subtitlePosition, subtitleStyle); GUILayout.Label(currentSubtitle.dialog, subtitleStyle); GUI.EndGroup(); } /// <summary> /// Visually shows the cutscene in the scene view. /// </summary> - void OnDrawGizmos () { + void OnDrawGizmos () + { Gizmos.DrawIcon(transform.position, "Cutscene.png"); } /// <summary> /// Sets the in and out points of the master animation clip. /// </summary> - void SetupMasterAnimationClip () { + void SetupMasterAnimationClip () + { animation.RemoveClip("master"); // Create a new event for when the scene starts AnimationEvent start = new AnimationEvent(); start.time = inPoint; start.functionName = "SceneStart"; masterClip.AddEvent(start); // Create a new event for when the scene finishes AnimationEvent finish = new AnimationEvent(); finish.time = outPoint; finish.functionName = "SceneFinish"; masterClip.AddEvent(finish); animation.AddClip(masterClip, "master"); animation["master"].time = inPoint; } /// <summary> /// Adds each track's animation clip to the main animation. /// </summary> - void SetupTrackAnimationClips () { + void SetupTrackAnimationClips () + { foreach (CutsceneTrack t in tracks) { if (t.enabled) { AnimationClip trackAnimationClip = t.track; string clipName = "track" + t.id; animation.AddClip(trackAnimationClip, clipName); animation[clipName].time = inPoint; } } } /// <summary> /// Turns off all child cameras so that they don't display before the cutscene starts. /// </summary> - void DisableCameras () { + void DisableCameras () + { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { cam.enabled = false; } } /// <summary> /// Turns off all child cameras except for the one specified. /// </summary> /// <param name="exemptCam">The camera to stay enabled.</param> - void DisableOtherCameras (Camera exemptCam) { + void DisableOtherCameras (Camera exemptCam) + { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { if (cam != exemptCam) { cam.enabled = false; } } } /// <summary> /// Keeps all child audio sources from playing once the game starts. /// </summary> - void DisableAudio () { + void DisableAudio () + { AudioSource[] childAudio = GetComponentsInChildren<AudioSource>(); foreach (AudioSource audio in childAudio) { audio.playOnAwake = false; } } /// <summary> /// Starts playing the cutscene. /// </summary> - public void PlayCutscene () { + public void PlayCutscene () + { // Set up and play the master animation animation["master"].layer = 0; animation.Play("master"); // Set up and play each individual track for (int i = 0; i < tracks.Length; i++) { if (tracks[i].enabled) { animation["track" + tracks[i].id].layer = i + 1; animation.Play("track" + tracks[i].id); } } } /// <summary> /// Pauses the cutscene. /// </summary> - public void PauseCutscene () { + public void PauseCutscene () + { pauseFunction(); // TODO actually pause the cutscene } /// <summary> /// Called when the scene starts. /// </summary> - void SceneStart () { + void SceneStart () + { if (startFunction != null) { startFunction(); } // Stop the player from being able to move if (player != null && stopPlayer) { EDebug.Log("Cutscene: deactivating player"); player.active = false; } DisableCameras(); currentSubtitle = null; EDebug.Log("Cutscene: scene started at " + animation["master"].time); } /// <summary> /// Called when the scene ends. /// </summary> - void SceneFinish () { + void SceneFinish () + { if (endFunction != null) { endFunction(); } // Allow the player to move again if (player != null) { EDebug.Log("Cutscene: activating player"); player.active = true; } EDebug.Log("Cutscene: scene finished at " + animation["master"].time); } /// <summary> /// Shows the specified shot. /// </summary> /// <param name="clip">The shot to show.</summary> - void PlayShot (CutsceneClip clip) { + void PlayShot (CutsceneClip clip) + { Camera cam = ((CutsceneShot)clip.master).camera; cam.enabled = true; StartCoroutine(StopShot(cam, clip.duration)); EDebug.Log("Cutscene: showing camera " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the shot from playing at its out point. /// </summary> /// <param name="shot">The shot to stop.</param> /// <param name="duration">The time at which to stop the shot.</param> - IEnumerator StopShot (Camera cam, float duration) { + IEnumerator StopShot (Camera cam, float duration) + { yield return new WaitForSeconds(duration); cam.enabled = false; EDebug.Log("Cutscene: stopping shot at " + animation["master"].time); } /// <summary> /// Plays the specified actor. /// </summary> /// <param name="clip">The actor to play.</summary> - void PlayActor (CutsceneClip clip) { + void PlayActor (CutsceneClip clip) + { CutsceneActor actor = ((CutsceneActor)clip.master); AnimationClip anim = actor.anim; GameObject go = ((CutsceneActor)clip.master).go; go.animation[anim.name].time = clip.inPoint; go.animation.Play(anim.name); StartCoroutine(StopActor(actor, clip.duration)); EDebug.Log("Cutscene: showing actor " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the actor from playing at its out point. /// </summary> /// <param name="actor">The actor to stop.</param> /// <param name="duration">The time at which to stop the actor.</param> - IEnumerator StopActor (CutsceneActor actor, float duration) { + IEnumerator StopActor (CutsceneActor actor, float duration) + { yield return new WaitForSeconds(duration); actor.go.animation.Stop(actor.anim.name); EDebug.Log("Cutscene: stopping actor at " + animation["master"].time); } /// <summary> /// Plays the specified audio. /// </summary> /// <param name="clip">The audio to play.</summary> - void PlayAudio (CutsceneClip clip) { + void PlayAudio (CutsceneClip clip) + { AudioSource aud = ((CutsceneAudio)clip.master).audio; aud.Play(); aud.time = clip.inPoint; // Set the point at which the clip plays StartCoroutine(StopAudio(aud, clip.duration)); // Set the point at which the clip stops EDebug.Log("Playing audio " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the audio from playing at its out point. /// </summary> /// <param name="aud">The audio source to stop.</param> /// <param name="duration">The time at which to stop the audio.</param> - IEnumerator StopAudio (AudioSource aud, float duration) { + IEnumerator StopAudio (AudioSource aud, float duration) + { yield return new WaitForSeconds(duration); aud.Stop(); } /// <summary> /// Displays the specified subtitle. /// </summary> /// <param name="clip">The subtitle to display.</summary> - void PlaySubtitle (CutsceneClip clip) { + void PlaySubtitle (CutsceneClip clip) + { currentSubtitle = (CutsceneSubtitle)clip.master; EDebug.Log("Displaying subtitle " + clip.name + " at " + animation["master"].time); StartCoroutine(StopSubtitle(clip.duration)); } /// <summary> /// Stops the subtitle from displaying at its out point. /// </summary> /// <param name="duration">The time at which to stop the audio.</param> - IEnumerator StopSubtitle (float duration) { + IEnumerator StopSubtitle (float duration) + { yield return new WaitForSeconds(duration); currentSubtitle = null; } /// <summary> /// Stops all subtitles from displaying by setting the current subtitle to null. /// </summary> - void StopSubtitle () { + void StopSubtitle () + { currentSubtitle = null; } /// <summary> /// Called when the clip type is unknown. /// </summary> /// <remarks>For debugging only; ideally this will never be called.</remarks> - void UnknownFunction (CutsceneClip clip) { + void UnknownFunction (CutsceneClip clip) + { EDebug.Log("Cutscene: unknown function call from clip " + clip.name); } /// <summary> /// Creates a new CutsceneShot object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneShot object.</returns> - public CutsceneShot NewShot () { + public CutsceneShot NewShot () + { GameObject shot = new GameObject("Camera", typeof(Camera), typeof(CutsceneShot)); // Keep the camera from displaying before it's placed on the timeline shot.camera.enabled = false; // Set the parent of the new shot to the Shots object shot.transform.parent = transform.Find("Shots"); EDebug.Log("Cutscene Editor: added new shot"); return shot.GetComponent<CutsceneShot>(); } /// <summary> /// Creates a new CutsceneActor object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneActor object.</returns> - public CutsceneActor NewActor (AnimationClip anim, GameObject go) { + public CutsceneActor NewActor (AnimationClip anim, GameObject go) + { CutsceneActor actor = GameObject.Find("Actors").AddComponent<CutsceneActor>(); actor.name = anim.name; actor.anim = anim; actor.go = go; EDebug.Log("Cutscene Editor: adding new actor"); return actor; } /// <summary> /// Creates a new CutsceneAudio object and attaches it to a new game object as a child of the Audio game object. /// </summary> /// <param name="clip">The audio clip to be attached the CutsceneAudio object.</param> /// <returns>The new CutsceneAudio object.</returns> - public CutsceneAudio NewAudio (AudioClip clip) { + public CutsceneAudio NewAudio (AudioClip clip) + { GameObject aud = new GameObject(clip.name, typeof(AudioSource), typeof(CutsceneAudio)); aud.audio.clip = clip; // Keep the audio from playing when the game starts aud.audio.playOnAwake = false; // Set the parent of the new audio to the "Audio" object aud.transform.parent = transform.Find("Audio"); EDebug.Log("Cutscene Editor: added new audio"); return aud.GetComponent<CutsceneAudio>(); } /// <summary> /// Creates a new CutsceneSubtitle object and attaches it to the Subtitles game object. /// </summary> /// <param name="dialog">The dialog to be displayed.</param> /// <returns>The new CutsceneSubtitle object.</returns> - public CutsceneSubtitle NewSubtitle (string dialog) { + public CutsceneSubtitle NewSubtitle (string dialog) + { CutsceneSubtitle subtitle = GameObject.Find("Subtitles").AddComponent<CutsceneSubtitle>(); subtitle.dialog = dialog; EDebug.Log("Cutscene Editor: added new subtitle"); return subtitle; } /// <summary> /// Attaches a new track component to the cutscene. /// </summary> /// <returns>The new cutscene track.</returns> - public CutsceneTrack AddTrack (Cutscene.MediaType type) { + public CutsceneTrack AddTrack (Cutscene.MediaType type) + { int id = 0; // Ensure the new track has a unique ID foreach (CutsceneTrack t in tracks) { if (id == t.id) { id++; } else { break; } } CutsceneTrack track = gameObject.AddComponent<CutsceneTrack>(); track.id = id; track.type = type; track.name = CutsceneTrack.DefaultName(type); EDebug.Log("Cutscene Editor: added new track of type " + type); return track; } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneActor.cs b/Cutscene Ed/Scripts/CutsceneActor.cs index ce23924..953433e 100644 --- a/Cutscene Ed/Scripts/CutsceneActor.cs +++ b/Cutscene Ed/Scripts/CutsceneActor.cs @@ -1,28 +1,29 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; -public class CutsceneActor : CutsceneMedia { +public class CutsceneActor : CutsceneMedia +{ public AnimationClip anim; public GameObject go; } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneClip.cs b/Cutscene Ed/Scripts/CutsceneClip.cs index bbcbfee..16b2f43 100644 --- a/Cutscene Ed/Scripts/CutsceneClip.cs +++ b/Cutscene Ed/Scripts/CutsceneClip.cs @@ -1,136 +1,143 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; using System; -public class CutsceneClip : ScriptableObject { +public class CutsceneClip : ScriptableObject +{ public CutsceneMedia master; public float timelineStart = 0f; public float inPoint = 0f; public float outPoint = 5f; // Default 5 seconds public float timelineEnd { get { return timelineStart + duration; } } float maxOutPoint { get { float max = Mathf.Infinity; if (master is CutsceneActor) { max = ((CutsceneActor)master).anim.length; } else if (master is CutsceneAudio) { max = ((CutsceneAudio)master).gameObject.audio.clip.length; } return max; } } - public void SetTimelineStart (float value) { + public void SetTimelineStart (float value) + { timelineStart = Mathf.Clamp(value, 0f, Mathf.Infinity); } - public void SetInPoint (float value) { + public void SetInPoint (float value) + { inPoint = Mathf.Clamp(value, 0f, outPoint); } - public void SetOutPoint (float value) { + public void SetOutPoint (float value) + { outPoint = Mathf.Clamp(value, inPoint, maxOutPoint); } [HideInInspector] public bool setToDelete = false; // An ugly workaround used for deleting clips // Read only public float duration { get { return outPoint - inPoint; } } public string startFunction { get { // Determine which function to call based on the master object type if (master is CutsceneShot) { return "PlayShot"; } else if (master is CutsceneActor) { return "PlayActor"; } else if (master is CutsceneAudio) { return "PlayAudio"; } else if (master is CutsceneSubtitle) { return "PlaySubtitle"; } else { return "UnknownFunction"; } } } public Cutscene.MediaType type { get { if (master is CutsceneShot) { return Cutscene.MediaType.Shots; } else if (master is CutsceneActor) { return Cutscene.MediaType.Actors; } else if (master is CutsceneAudio) { return Cutscene.MediaType.Audio; } else { // master is CutsceneSubtitles return Cutscene.MediaType.Subtitles; } } } - public CutsceneClip (CutsceneMedia master) { + public CutsceneClip (CutsceneMedia master) + { this.master = master; if (master is CutsceneSubtitle) { name = ((CutsceneSubtitle)master).dialog; } else { name = master.name; } if (maxOutPoint != Mathf.Infinity) { outPoint = maxOutPoint; } } /// <summary> /// Gets a clone of the current clip. /// </summary> /// <returns>The clip copy.</returns> - public CutsceneClip GetCopy () { + public CutsceneClip GetCopy () + { CutsceneClip copy = new CutsceneClip(master); copy.timelineStart = timelineStart; copy.SetInPoint(inPoint); copy.outPoint = outPoint; return copy; } /// <summary> /// Adds an effect to the clip. /// </summary> /// <param name="effect">The transitions or filter.</param> - public void ApplyEffect (Type effect) { + public void ApplyEffect (Type effect) + { // Only add the effect if the master object is a camera shot if (master is CutsceneShot) { master.gameObject.AddComponent(effect); } } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneMedia.cs b/Cutscene Ed/Scripts/CutsceneMedia.cs index a182b52..126b288 100644 --- a/Cutscene Ed/Scripts/CutsceneMedia.cs +++ b/Cutscene Ed/Scripts/CutsceneMedia.cs @@ -1,39 +1,40 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; -public abstract class CutsceneMedia : MonoBehaviour { +public abstract class CutsceneMedia : MonoBehaviour +{ public Cutscene.MediaType type { get { if (this.GetType() == typeof(CutsceneShot)) { return Cutscene.MediaType.Shots; } else if (this.GetType() == typeof(CutsceneActor)) { return Cutscene.MediaType.Actors; } else if (this.GetType() == typeof(CutsceneAudio)) { return Cutscene.MediaType.Audio; } else { // obj.GetType() == typeof(CutsceneSubtitle) return Cutscene.MediaType.Subtitles; } } } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneSubtitle.cs b/Cutscene Ed/Scripts/CutsceneSubtitle.cs index d5e80d4..78d4238 100644 --- a/Cutscene Ed/Scripts/CutsceneSubtitle.cs +++ b/Cutscene Ed/Scripts/CutsceneSubtitle.cs @@ -1,38 +1,39 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; -public class CutsceneSubtitle : CutsceneMedia { +public class CutsceneSubtitle : CutsceneMedia +{ public string dialog; public new string name { get { int maxTitleLength = 25; string _name = dialog; if (_name.Length > maxTitleLength) { _name = _name.Substring(0, maxTitleLength) + " ..."; } return _name; } } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneTrack.cs b/Cutscene Ed/Scripts/CutsceneTrack.cs index b49ae1c..200ca24 100644 --- a/Cutscene Ed/Scripts/CutsceneTrack.cs +++ b/Cutscene Ed/Scripts/CutsceneTrack.cs @@ -1,125 +1,131 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; using System.Collections.Generic; using System; -public class CutsceneTrack : MonoBehaviour { +public class CutsceneTrack : MonoBehaviour +{ public bool locked; [HideInInspector] public Cutscene.MediaType type = Cutscene.MediaType.Shots; public new string name = DefaultName(Cutscene.MediaType.Shots); public List<CutsceneClip> clips = new List<CutsceneClip>(); [HideInInspector] public int id = 0; public AnimationClip track { get { AnimationClip _track = new AnimationClip(); foreach (CutsceneClip clip in clips) { AnimationEvent start = new AnimationEvent(); start.time = clip.timelineStart; start.functionName = clip.startFunction; start.objectReferenceParameter = clip; _track.AddEvent(start); } return _track; } } - public static string DefaultName (Cutscene.MediaType type) { + public static string DefaultName (Cutscene.MediaType type) + { switch (type) { case Cutscene.MediaType.Shots: return "Shots"; case Cutscene.MediaType.Actors: return "Actors"; case Cutscene.MediaType.Audio: return "Audio"; default: // Cutscene.MediaType.Subtitles return "Subtitles"; } } /// <summary> /// Checks to see if there's a clip at the given time, ignoring the given clip. /// </summary> /// <param name="time">The time to check for.</param> /// <returns>The CutsceneClip that is at the given time.</returns> - public CutsceneClip ContainsClipAtTime (float time, CutsceneClip ignoreClip) { + public CutsceneClip ContainsClipAtTime (float time, CutsceneClip ignoreClip) + { CutsceneClip contains = ContainsClipAtTime(time); if (contains != null && contains != ignoreClip) { return contains; } else { return null; } } /// <summary> /// Checks to see if there's a clip at the given time. /// </summary> /// <param name="time">The time to check for.</param> /// <returns>The CutsceneClip that is at the given time.</returns> - public CutsceneClip ContainsClipAtTime (float time) { + public CutsceneClip ContainsClipAtTime (float time) + { foreach (CutsceneClip clip in clips) { if (time >= clip.timelineStart && time <= clip.timelineStart + clip.duration) { return clip; } } // The timeline doesn't contain a clip at the specified time return null; } - public float GetTimeOfPreviousSplit (float time) { + public float GetTimeOfPreviousSplit (float time) + { float splitTime = -1f; foreach (CutsceneClip clip in clips) { if (clip.timelineEnd < time && clip.timelineEnd > splitTime) { splitTime = clip.timelineEnd; } else if (clip.timelineStart < time && clip.timelineStart > splitTime) { splitTime = clip.timelineStart; } } // If splitTime is still -1, just return the original time return splitTime == -1f ? time : splitTime; } - public float GetTimeOfNextSplit (float time) { + public float GetTimeOfNextSplit (float time) + { float splitTime = Mathf.Infinity; foreach (CutsceneClip clip in clips) { if (clip.timelineStart > time && clip.timelineStart < splitTime) { splitTime = clip.timelineStart; } else if (clip.timelineEnd > time && clip.timelineEnd < splitTime) { splitTime = clip.timelineEnd; } } // If splitTime is still infinity, just return the original time return splitTime == Mathf.Infinity ? time : splitTime; } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneTrigger.cs b/Cutscene Ed/Scripts/CutsceneTrigger.cs index 10b9aef..812e403 100644 --- a/Cutscene Ed/Scripts/CutsceneTrigger.cs +++ b/Cutscene Ed/Scripts/CutsceneTrigger.cs @@ -1,39 +1,42 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; using System.Collections; -public class CutsceneTrigger : MonoBehaviour { +public class CutsceneTrigger : MonoBehaviour +{ public Cutscene scene; - void Update () { + void Update () + { //TEMP if (Input.GetKey("p")) { scene.PlayCutscene(); } } - void OnTriggerEnter (Collider collider) { + void OnTriggerEnter (Collider collider) + { scene.PlayCutscene(); } } diff --git a/Cutscene Ed/Scripts/EDebug.cs b/Cutscene Ed/Scripts/EDebug.cs index ef2489b..6ac7d98 100755 --- a/Cutscene Ed/Scripts/EDebug.cs +++ b/Cutscene Ed/Scripts/EDebug.cs @@ -1,58 +1,66 @@ /** * Copyright (c) 2010 Matthew Miner * * 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. */ using UnityEngine; /// <summary> /// A simple class for toggle-able debug messages. Debug messages for editor tools are useful when developing the tool itself, but annoying for end users. /// </summary> -public class EDebug { +public class EDebug +{ static bool debug = false; - public static void Break () { + public static void Break () + { if (debug) Debug.Break(); } - public static void Log (object message) { + public static void Log (object message) + { if (debug) Debug.Log(message); } - public static void Log (object message, UnityEngine.Object context) { + public static void Log (object message, UnityEngine.Object context) + { if (debug) Debug.Log(message, context); } - public static void LogError (object message) { + public static void LogError (object message) + { if (debug) Debug.LogError(message); } - public static void LogError (object message, UnityEngine.Object context) { + public static void LogError (object message, UnityEngine.Object context) + { if (debug) Debug.LogError(message, context); } - public static void LogWarning (object message) { + public static void LogWarning (object message) + { if (debug) Debug.LogWarning(message); } - public static void LogWarning (object message, UnityEngine.Object context) { + public static void LogWarning (object message, UnityEngine.Object context) + { if (debug) Debug.LogWarning(message, context); } } \ No newline at end of file
mminer/silverscreen
5276d3b40751b22b4fca958ea7a110c6afa3ad1a
Added license notice to top of scripts.
diff --git a/Cutscene Ed/Editor/BugReporter.cs b/Cutscene Ed/Editor/BugReporter.cs index 8a04202..ef3b461 100755 --- a/Cutscene Ed/Editor/BugReporter.cs +++ b/Cutscene Ed/Editor/BugReporter.cs @@ -1,42 +1,64 @@ -using UnityEditor; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEditor; using UnityEngine; public class BugReporter : EditorWindow { string email = ""; string details = ""; readonly GUIContent emailLabel = new GUIContent("Your Email", "If we require additional information, we'll contact you at the supplied address (optional)."); readonly GUIContent submitLabel = new GUIContent("Submit", "Send this bug report."); /// <summary> /// Adds "Bug Reporter" to the Window menu. /// </summary> [MenuItem("Window/Bug Reporter")] public static void OpenEditor () { // Get existing open window or if none, make a new one GetWindow<BugReporter>(true, "Bug Reporter").Show(); } void OnGUI () { GUILayout.Label("Please take a minute to tell us what happened in as much detail as possible. This makes it possible for us to fix the problem."); EditorGUILayout.Separator(); email = EditorGUILayout.TextField(emailLabel, email); EditorGUILayout.Separator(); GUILayout.Label("Problem Details:"); details = EditorGUILayout.TextArea(details); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(submitLabel, GUILayout.ExpandWidth(false))) { // TODO Send bug report Debug.Log("Bug report sent."); } EditorGUILayout.EndHorizontal(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneAddActor.cs b/Cutscene Ed/Editor/CutsceneAddActor.cs index 70f46d8..31f3925 100755 --- a/Cutscene Ed/Editor/CutsceneAddActor.cs +++ b/Cutscene Ed/Editor/CutsceneAddActor.cs @@ -1,90 +1,112 @@ -using UnityEngine; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; class CutsceneAddActor : ScriptableWizard { GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; AnimationClip selected; GameObject selectedGO; /// <summary> /// Creates a wizard for adding a new actor. /// </summary> [MenuItem("Component/Cutscene/Add Media/Actor")] public static void CreateWizard () { DisplayWizard<CutsceneAddActor>("Add Actor", "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Actor", true)] static bool ValidateCreateWizard () { return CutsceneEditor.CutsceneSelected; } void OnGUI () { OnWizardUpdate(); Animation[] animations = (Animation[])FindObjectsOfType(typeof(Animation)); EditorGUILayout.BeginVertical(style.GetStyle("List Container")); foreach (Animation anim in animations) { GUILayout.Label(anim.gameObject.name, EditorStyles.largeLabel); foreach (AnimationClip clip in AnimationUtility.GetAnimationClips(anim)) { GUIStyle itemStyle = GUIStyle.none; if (clip == selected) { itemStyle = style.GetStyle("Selected List Item"); } Rect rect = EditorGUILayout.BeginHorizontal(itemStyle); GUIContent itemLabel = new GUIContent(clip.name, EditorGUIUtility.ObjectContent(null, typeof(Animation)).image); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); // Select when clicked if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { selected = clip; selectedGO = anim.gameObject; EditorGUIUtility.PingObject(anim); Event.current.Use(); Repaint(); } } } EditorGUILayout.EndVertical(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true; } void OnWizardUpdate () { helpString = "Choose an animation to add."; // Only valid if an animation has been selected isValid = selected != null; } /// <summary> /// Adds the new actor to the cutscene. /// </summary> void OnWizardCreate () { Selection.activeGameObject.GetComponent<Cutscene>().NewActor(selected, selectedGO); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneAddAudio.cs b/Cutscene Ed/Editor/CutsceneAddAudio.cs index ba7ffa9..19aa13f 100755 --- a/Cutscene Ed/Editor/CutsceneAddAudio.cs +++ b/Cutscene Ed/Editor/CutsceneAddAudio.cs @@ -1,87 +1,109 @@ -using UnityEngine; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEngine; using UnityEditor; class CutsceneAddAudio : ScriptableWizard { //GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; AudioClip[] audioClips; AudioClip selected; /// <summary> /// Creates a wizard for adding a new audio clip. /// </summary> [MenuItem("Component/Cutscene/Add Media/Audio")] public static void CreateWizard () { DisplayWizard<CutsceneAddAudio>("Add Audio", "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Audio", true)] static bool ValidateCreateWizard () { return CutsceneEditor.CutsceneSelected; } void OnGUI () { OnWizardUpdate(); // Display temporary workaround info GUILayout.Label("To add an audio clip from the Project view, drag and drop it to the audio pane. This is a temporary workaround and will hopefully be fixed soon."); // TODO Make LoadAllAssetsAtPath work /* audioClips = (AudioClip[])AssetDatabase.LoadAllAssetsAtPath("Assets"); Debug.Log("Objects length: " + audioClips.Length); EditorGUILayout.BeginVertical(style.GetStyle("List Container")); foreach (AudioClip aud in audioClips) { GUIStyle itemStyle = aud == selected ? style.GetStyle("Selected List Item") : GUIStyle.none; Rect rect = EditorGUILayout.BeginHorizontal(itemStyle); GUIContent itemLabel = new GUIContent(aud.name, EditorGUIUtility.ObjectContent(null, typeof(AudioClip)).image); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); // Select when clicked if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { selected = aud; EditorGUIUtility.PingObject(aud); Event.current.Use(); } } EditorGUILayout.EndVertical(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true;*/ } void OnWizardUpdate () { helpString = "Choose an audio clip to add."; // Only valid if an audio clip has been selected isValid = selected != null; } /// <summary> /// Adds a new audio clip to the cutscene. /// </summary> void OnWizardCreate () { Selection.activeGameObject.GetComponent<Cutscene>().NewAudio(selected); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneAddSubtitle.cs b/Cutscene Ed/Editor/CutsceneAddSubtitle.cs index 537bd0e..c108c6f 100755 --- a/Cutscene Ed/Editor/CutsceneAddSubtitle.cs +++ b/Cutscene Ed/Editor/CutsceneAddSubtitle.cs @@ -1,61 +1,83 @@ -using UnityEngine; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEngine; using UnityEditor; public class CutsceneAddSubtitle : ScriptableWizard { string dialog = ""; /// <summary> /// Creates a wizard for adding a new subtitle. /// </summary> [MenuItem("Component/Cutscene/Add Media/Subtitle")] public static void CreateWizard () { DisplayWizard<CutsceneAddSubtitle>("Add Subtitle", "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Subtitle", true)] static bool ValidateCreateWizard () { return CutsceneEditor.CutsceneSelected; } void OnGUI () { OnWizardUpdate(); EditorGUILayout.BeginHorizontal(); GUIContent itemLabel = new GUIContent("Dialog", EditorGUIUtility.ObjectContent(null, typeof(TextAsset)).image); GUILayout.Label(itemLabel, GUILayout.ExpandWidth(false)); dialog = EditorGUILayout.TextArea(dialog); EditorGUILayout.EndHorizontal(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true; } void OnWizardUpdate () { helpString = "Type in some dialog to add."; // Only valid if some text has been entered in the text field isValid = dialog != ""; } /// <summary> /// Adds the new subtitle to the cutscene. /// </summary> void OnWizardCreate () { Selection.activeGameObject.GetComponent<Cutscene>().NewSubtitle(dialog); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneEditor.cs b/Cutscene Ed/Editor/CutsceneEditor.cs index 6990fd8..8a2a09c 100755 --- a/Cutscene Ed/Editor/CutsceneEditor.cs +++ b/Cutscene Ed/Editor/CutsceneEditor.cs @@ -1,491 +1,513 @@ +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// The Cutscene Editor, where tracks and clips can be managed in a fashion similar to non-linear video editors. /// </summary> public class CutsceneEditor : EditorWindow { public static readonly System.Version version = new System.Version(0, 2); public Cutscene scene { get { Object[] scenes = Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel); if (scenes.Length == 0) { return null; } return scenes[0] as Cutscene; } } public GUISkin style { get; private set; } //ICutsceneGUI options; ICutsceneGUI media; ICutsceneGUI effects; ICutsceneGUI tools; ICutsceneGUI timeline; public static bool CutsceneSelected { get { return Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel).Length > 0; } } public static bool HasPro = SystemInfo.supportsImageEffects; // Icons: public readonly Texture[] mediaIcons = { EditorGUIUtility.LoadRequired("Cutscene Ed/media_shot.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_actor.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_audio.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_subtitle.png") as Texture }; // Timeline: public Tool currentTool = Tool.MoveResize; public Vector2 timelineScrollPos; public float timelineMin { get; set; } float _timelineZoom = CutsceneTimeline.timelineZoomMin; public float timelineZoom { get { return _timelineZoom; } set { _timelineZoom = Mathf.Clamp(value, CutsceneTimeline.timelineZoomMin, CutsceneTimeline.timelineZoomMax); } } CutsceneTrack _selectedTrack; public CutsceneTrack selectedTrack { get { if (_selectedTrack == null) { // If there are no tracks, add a new one if (scene.tracks.Length == 0) { scene.AddTrack(Cutscene.MediaType.Shots); } _selectedTrack = scene.tracks[0]; } return _selectedTrack; } set { _selectedTrack = value; } } public CutsceneClip selectedClip; public DragEvent dragEvent = DragEvent.Move; public CutsceneClip dragClip; // Menu items: /// <summary> /// Adds "Cutscene Editor" to the Window menu. /// </summary> [MenuItem("Window/Cutscene Editor %9")] public static void OpenEditor () { // Get existing open window or if none, make a new one GetWindow<CutsceneEditor>(false, "Cutscene Editor").Show(); } /// <summary> /// Validates the Cutscene Editor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Window/Cutscene Editor %9", true)] static bool ValidateOpenEditor () { return CutsceneSelected; } /// <summary> /// Adds the option to create a cutscene from the GameObject > Create Other menu. /// </summary> /// <returns>The new cutscene.</returns> [MenuItem("GameObject/Create Other/Cutscene")] static void CreateCutscene () { // Create the new cutscene game object GameObject newSceneGO = new GameObject("Cutscene", typeof(Cutscene)); Cutscene newScene = newSceneGO.GetComponent<Cutscene>(); // Add some tracks to get the user started newScene.AddTrack(Cutscene.MediaType.Shots); newScene.AddTrack(Cutscene.MediaType.Actors); newScene.AddTrack(Cutscene.MediaType.Audio); newScene.AddTrack(Cutscene.MediaType.Subtitles); // Create the cutscene's media game objects GameObject shots = new GameObject("Shots"); GameObject actors = new GameObject("Actors"); GameObject audio = new GameObject("Audio"); GameObject subtitles = new GameObject("Subtitles"); // Make the media game objects a child of the cutscene shots.transform.parent = newScene.transform; actors.transform.parent = newScene.transform; audio.transform.parent = newScene.transform; subtitles.transform.parent = newScene.transform; // Create the master animation clip AnimationClip masterClip = new AnimationClip(); newScene.masterClip = masterClip; newScene.animation.AddClip(masterClip, "master"); newScene.animation.playAutomatically = false; newScene.animation.wrapMode = WrapMode.Once; EDebug.Log("Cutscene Editor: created a new cutscene"); } /// <summary> /// Adds the option to create a cutscene trigger to the GameObject > Create Other menu. /// </summary> /// <returns>The trigger's collider.</returns> [MenuItem("GameObject/Create Other/Cutscene Trigger")] static Collider CreateCutsceneTrigger () { // Create the new cutscene trigger game object GameObject triggerGO = new GameObject("Cutscene Trigger", typeof(BoxCollider), typeof(CutsceneTrigger)); triggerGO.collider.isTrigger = true; return triggerGO.collider; } /// <summary> /// Adds the option to create a new shot track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Shot")] static void CreateShotTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Shots); } /// <summary> /// Validates the Shot menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Shot", true)] static bool ValidateCreateShotTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new actor track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Actor")] static void CreateActorTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Actors); } /// <summary> /// Validates the Actor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Actor", true)] static bool ValidateCreateActorTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new audio track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Audio")] static void CreateAudioTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Audio); } /// <summary> /// Validates the Audio menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Audio", true)] static bool ValidateCreateAudioTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new subtitle track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Subtitle")] static void CreateSubtitleTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Subtitles); } /// <summary> /// Validates the Subtitle menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Subtitle", true)] static bool ValidateCreateSubtitleTrack () { return CutsceneSelected; } void OnEnable () { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; if (style == null) { Debug.LogError("GUISkin for Cutscene Editor missing"); return; } //options = new CutsceneOptions(this); media = new CutsceneMediaWindow(this); effects = new CutsceneEffectsWindow(this); tools = new CutsceneTools(this); timeline = new CutsceneTimeline(this); } /// <summary> /// Displays the editor GUI. /// </summary> void OnGUI () { if (style == null) { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; } // If no cutscene is selected, present the user with the option to create one if (scene == null) { if (GUILayout.Button("Create New Cutscene", GUILayout.ExpandWidth(false))) { CreateCutscene(); } } else { // Otherwise present the cutscene editor float windowHeight = style.GetStyle("Pane").fixedHeight; // Options window //Rect optionsRect = new Rect(0, 0, position.width / 3, windowHeight); //options.OnGUI(optionsRect); // Media window Rect mediaRect = new Rect(2, 2, position.width / 2, windowHeight); media.OnGUI(mediaRect); // Effects window Rect effectsRect = new Rect(mediaRect.xMax + 2, 2, position.width - mediaRect.xMax - 4, windowHeight); effects.OnGUI(effectsRect); // Cutting tools Rect toolsRect = new Rect(0, mediaRect.yMax, position.width, 25); tools.OnGUI(toolsRect); // Timeline Rect timelineRect = new Rect(0, toolsRect.yMax, position.width, position.height - toolsRect.yMax); timeline.OnGUI(timelineRect); } } // Context menus: /// <summary> /// Deletes a piece of media by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> [MenuItem("CONTEXT/CutsceneObject/Delete")] static void DeleteCutsceneMedia (MenuCommand command) { DeleteCutsceneMedia(command.context as CutsceneMedia); } /// <summary> /// Deletes a piece of media. /// </summary> /// <param name="obj">The media to delete.</param> /// <remarks>This has to be in CutsceneEditor rather than CutsceneTimeline because it uses the DestroyImmediate function, which is only available to classes which inherit from UnityEngine.Object.</remarks> static void DeleteCutsceneMedia (CutsceneMedia obj) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Object", "Are you sure you wish to delete this object? Changes cannot be undone.", "Delete", "Cancel"); } // Only delete the cutscene object if the user chose to if (delete) { Debug.Log("Cutscene Editor: deleting media " + obj.name); if (obj.type == Cutscene.MediaType.Actors || obj.type == Cutscene.MediaType.Subtitles) { // Delete the CutsceneObject component DestroyImmediate(obj); } else { // Delete the actual game object DestroyImmediate(obj.gameObject); } } } /// <summary> /// Deletes a track by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneTrack/Delete Track")] static bool DeleteTrack (MenuCommand command) { return DeleteTrack(command.context as CutsceneTrack); } /// <summary> /// Deletes a track. /// </summary> /// <param name="track">The track to delete.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> static bool DeleteTrack (CutsceneTrack track) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Track", "Are you sure you wish to delete this track? Changes cannot be undone.", "Delete", "Cancel"); } if (delete) { DestroyImmediate(track); } return delete; } /// <summary> /// Deletes a clip by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneClip/Delete Clip")] static bool DeleteClip (MenuCommand command) { return DeleteClip(command.context as CutsceneClip); } /// <summary> /// Deletes a clip. /// </summary> /// <param name="clip">The clip to delete.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> static bool DeleteClip (CutsceneClip clip) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Clip", "Are you sure you wish to delete this clip? Changes cannot be undone.", "Delete", "Cancel"); } clip.setToDelete = delete; return delete; } /// <summary> /// Selects the track at the specified index. /// </summary> /// <param name="index">The track to select.</param> void SelectTrackAtIndex (int index) { if (scene.tracks.Length > 0 && index > 0 && index <= scene.tracks.Length) { selectedTrack = scene.tracks[index - 1]; EDebug.Log("Cutscene Editor: track " + index + " is selected"); } } /// <summary> /// Determines which key command is pressed and responds accordingly. /// </summary> /// <param name="keyDownEvent">The keyboard event.</param> /// <returns>True if the keyboard shortcut exists, false otherwise.</returns> public void HandleKeyboardShortcuts (Event keyDownEvent) { KeyCode key = keyDownEvent.keyCode; // Tools: // Move/resize if (key == CutsceneHotkeys.MoveResizeTool.key) { currentTool = Tool.MoveResize; EDebug.Log("Cutscene Editor: switching to Move/Resize tool"); // Scissors } else if (key == CutsceneHotkeys.ScissorsTool.key) { currentTool = Tool.Scissors; EDebug.Log("Cutscene Editor: switching to Scissors tool"); // Zoom } else if (key == CutsceneHotkeys.ZoomTool.key) { currentTool = Tool.Zoom; EDebug.Log("Cutscene Editor: switching to Zoom tool"); } // Timeline navigation: // Set in point else if (key == CutsceneHotkeys.SetInPont.key) { scene.inPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting in point"); // Set out point } else if (key == CutsceneHotkeys.SetOutPoint.key) { scene.outPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting out point"); // Scrub left } else if (keyDownEvent.Equals(Event.KeyboardEvent("left"))) { scene.playhead -= CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead left"); // Scrub left large } else if (keyDownEvent.Equals(Event.KeyboardEvent("#left"))) { scene.playhead -= CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead left"); // Scrub right } else if (keyDownEvent.Equals(Event.KeyboardEvent("right"))) { scene.playhead += CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead right"); // Scrub right large } else if (keyDownEvent.Equals(Event.KeyboardEvent("#right"))) { scene.playhead += CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead right"); // Go to previous split point } else if (keyDownEvent.Equals(Event.KeyboardEvent("up"))) { scene.playhead = selectedTrack.GetTimeOfNextSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to previous split point"); // Go to next split point } else if (keyDownEvent.Equals(Event.KeyboardEvent("down"))) { scene.playhead = selectedTrack.GetTimeOfPreviousSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to next split point"); // Go to in point } else if (keyDownEvent.Equals(Event.KeyboardEvent("#up"))) { scene.playhead = scene.inPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); // Go to out point } else if (keyDownEvent.Equals(Event.KeyboardEvent("#down"))) { scene.playhead = scene.outPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); } // Track selection: // Select track 1 else if (key == CutsceneHotkeys.SelectTrack1.key) { SelectTrackAtIndex(1); // Select track 2 } else if (key == CutsceneHotkeys.SelectTrack2.key) { SelectTrackAtIndex(2); // Select track 3 } else if (key == CutsceneHotkeys.SelectTrack3.key) { SelectTrackAtIndex(3); // Select track 4 } else if (key == CutsceneHotkeys.SelectTrack4.key) { SelectTrackAtIndex(4); // Select track 5 } else if (key == CutsceneHotkeys.SelectTrack5.key) { SelectTrackAtIndex(5); // Select track 6 } else if (key == CutsceneHotkeys.SelectTrack6.key) { SelectTrackAtIndex(6); // Select track 7 } else if (key == CutsceneHotkeys.SelectTrack7.key) { SelectTrackAtIndex(7); // Select track 8 } else if (key == CutsceneHotkeys.SelectTrack8.key) { SelectTrackAtIndex(8); // Select track 9 } else if (key == CutsceneHotkeys.SelectTrack9.key) { SelectTrackAtIndex(9); } // Other: else { EDebug.Log("Cutscene Editor: unknown keyboard shortcut " + keyDownEvent); return; } // If we get to this point, a shortcut matching the user's keystroke has been found Event.current.Use(); } public static float PaneTabsWidth (int count) { return count * 80f; } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneEffectsWindow.cs b/Cutscene Ed/Editor/CutsceneEffectsWindow.cs index 33227fc..d1207f7 100755 --- a/Cutscene Ed/Editor/CutsceneEffectsWindow.cs +++ b/Cutscene Ed/Editor/CutsceneEffectsWindow.cs @@ -1,106 +1,128 @@ -using UnityEditor; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEditor; using UnityEngine; using System; using System.Collections.Generic; class CutsceneEffectsWindow : ICutsceneGUI { readonly CutsceneEditor ed; static Dictionary<string, Type> filters = new Dictionary<string, Type> { { CutsceneBlurFilter.name, typeof(CutsceneBlurFilter) }, { CutsceneInvertFilter.name, typeof(CutsceneInvertFilter) } }; static Dictionary<string, Type> transitions = new Dictionary<string, Type> {}; static readonly GUIContent filtersLabel = new GUIContent("Filters", "Full screen filters."); static readonly GUIContent transitionsLabel = new GUIContent("Transitions", "Camera transitions."); readonly GUIContent[] effectsTabs = CutsceneEditor.HasPro ? new GUIContent[] { filtersLabel, transitionsLabel } : new GUIContent[] { transitionsLabel }; Cutscene.EffectType currentEffectsTab = Cutscene.EffectType.Filters; Type selectedEffect; readonly Texture[] effectsIcons = { EditorGUIUtility.LoadRequired("Cutscene Ed/effects_filter.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/effects_transition.png") as Texture }; public CutsceneEffectsWindow (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the effects pane's GUI. /// </summary> /// <param name="rect">The effects pane's Rect.</param> public void OnGUI (Rect rect) { GUILayout.BeginArea(rect, ed.style.GetStyle("Pane")); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); currentEffectsTab = (Cutscene.EffectType)GUILayout.Toolbar((int)currentEffectsTab, effectsTabs, GUILayout.Width(CutsceneEditor.PaneTabsWidth(effectsTabs.Length))); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); GUI.enabled = ed.selectedClip != null && ed.selectedClip.type == Cutscene.MediaType.Shots && selectedEffect != null; GUIContent applyLabel = new GUIContent("Apply", "Apply the selected effect to the selected clip."); if (GUILayout.Button(applyLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { if (ed.selectedClip != null) { ed.selectedClip.ApplyEffect(selectedEffect); } } GUI.enabled = true; EditorGUILayout.EndHorizontal(); switch (currentEffectsTab) { case Cutscene.EffectType.Filters: foreach (KeyValuePair<string, Type> item in filters) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedEffect == item.Value ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent filterLabel = new GUIContent(item.Key, effectsIcons[(int)Cutscene.EffectType.Filters]); GUILayout.Label(filterLabel); EditorGUILayout.EndHorizontal(); // Handle clicks if (Event.current.type == EventType.MouseDown && itemRect.Contains(Event.current.mousePosition)) { selectedEffect = item.Value; Event.current.Use(); } } break; case Cutscene.EffectType.Transitions: foreach (KeyValuePair<string, Type> item in transitions) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedEffect == item.Value ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent transitionLabel = new GUIContent(item.Key, effectsIcons[(int)Cutscene.EffectType.Transitions]); GUILayout.Label(transitionLabel); EditorGUILayout.EndHorizontal(); // Handle clicks if (Event.current.type == EventType.MouseDown && itemRect.Contains(Event.current.mousePosition)) { selectedEffect = item.Value; Event.current.Use(); } } break; default: break; } GUILayout.EndArea(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneHotkeys.cs b/Cutscene Ed/Editor/CutsceneHotkeys.cs index af70f17..5def824 100755 --- a/Cutscene Ed/Editor/CutsceneHotkeys.cs +++ b/Cutscene Ed/Editor/CutsceneHotkeys.cs @@ -1,80 +1,102 @@ -using UnityEditor; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEditor; using UnityEngine; struct Hotkey { const string prefPrefix = "Cutscene Editor Hotkey "; string id; KeyCode defaultKey; bool assignable; public KeyCode key { get { if (assignable && EditorPrefs.HasKey(prefPrefix + id)) { return (KeyCode)EditorPrefs.GetInt(prefPrefix + id, (int)defaultKey); } else { return defaultKey; } } set { if (assignable) { EditorPrefs.SetInt(prefPrefix + id, (int)value); } else { EDebug.LogWarning("Cutscene Editor: Hotkey " + id + " cannot be reassigned"); } } } public Hotkey (string id, KeyCode defaultKey, bool assignable) { this.id = id; this.defaultKey = defaultKey; this.assignable = assignable; } /// <summary> /// Resets the key to its default value. /// </summary> public void Reset () { if (assignable) { key = defaultKey; } EDebug.Log("Cutscene Editor: Hotkey " + id + " reset to its default " + defaultKey); } } static class CutsceneHotkeys { // Assignable: public static Hotkey MoveResizeTool = new Hotkey("moveResizeTool", KeyCode.M, true); public static Hotkey ScissorsTool = new Hotkey("scissorsTool", KeyCode.S, true); public static Hotkey ZoomTool = new Hotkey("zoomTool", KeyCode.Z, true); public static Hotkey SetInPont = new Hotkey("setInPoint", KeyCode.I, true); public static Hotkey SetOutPoint = new Hotkey("setOutPoint", KeyCode.O, true); // Unassignable: public static readonly Hotkey SelectTrack1 = new Hotkey("selectTrack1", KeyCode.Alpha1, true); public static readonly Hotkey SelectTrack2 = new Hotkey("selectTrack2", KeyCode.Alpha2, true); public static readonly Hotkey SelectTrack3 = new Hotkey("selectTrack3", KeyCode.Alpha3, true); public static readonly Hotkey SelectTrack4 = new Hotkey("selectTrack4", KeyCode.Alpha4, true); public static readonly Hotkey SelectTrack5 = new Hotkey("selectTrack5", KeyCode.Alpha5, true); public static readonly Hotkey SelectTrack6 = new Hotkey("selectTrack6", KeyCode.Alpha6, true); public static readonly Hotkey SelectTrack7 = new Hotkey("selectTrack7", KeyCode.Alpha7, true); public static readonly Hotkey SelectTrack8 = new Hotkey("selectTrack8", KeyCode.Alpha8, true); public static readonly Hotkey SelectTrack9 = new Hotkey("selectTrack9", KeyCode.Alpha9, true); public static Hotkey[] assignable = new Hotkey[] { MoveResizeTool, ScissorsTool, ZoomTool, SetInPont, SetOutPoint }; /// <summary> /// Resets all the assignable hotkeys to their default values. /// </summary> public static void ResetAll () { foreach (Hotkey key in assignable) { key.Reset(); } } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneInspector.cs b/Cutscene Ed/Editor/CutsceneInspector.cs index 55671ae..28ef2a0 100755 --- a/Cutscene Ed/Editor/CutsceneInspector.cs +++ b/Cutscene Ed/Editor/CutsceneInspector.cs @@ -1,89 +1,111 @@ -using UnityEditor; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEditor; using UnityEngine; /// <summary> /// A custom inspector for a cutscene. /// </summary> [CustomEditor(typeof(Cutscene))] public class CutsceneInspector : Editor { Cutscene scene { get { return target as Cutscene; } } public override void OnInspectorGUI () { /* GUILayout.Label("Timing", EditorStyles.boldLabel); GUIContent durationLabel = new GUIContent("Duration", "The entire length of the cutscene."); scene.duration = EditorGUILayout.FloatField(durationLabel, scene.duration); // Instead of trying to clamp the values of the in and out points by slider leftValue and rightValue of the slider, we leave it to the Cutscene class GUIContent inPointLabel = new GUIContent("In", "The point at which the cutscene starts."); scene.inPoint = EditorGUILayout.Slider(inPointLabel, scene.inPoint, 0f, scene.duration); GUIContent outPointLabel = new GUIContent("Out", "The point at which the cutscene ends."); scene.outPoint = EditorGUILayout.Slider(outPointLabel, scene.outPoint, 0f, scene.duration); GUILayout.Label("Options", EditorStyles.boldLabel); GUIContent stopPlayerLabel = new GUIContent("Stop Player", "Deactivate the player when the scene starts."); scene.stopPlayer = EditorGUILayout.Toggle(stopPlayerLabel, scene.stopPlayer); // Disable the player reference box if the stop player toggle in unchecked GUI.enabled = scene.stopPlayer ? true : false; GUIContent playerLabel = new GUIContent("Player", "The player to deactivate."); scene.player = EditorGUILayout.ObjectField(playerLabel, scene.player, typeof(GameObject)) as GameObject; GUI.enabled = true; EditorGUILayout.Separator();*/ DrawDefaultInspector(); if (GUILayout.Button("Edit")) { CutsceneEditor.OpenEditor(); } if (GUI.changed) { EditorUtility.SetDirty(target); } } public void OnSceneGUI () { Handles.BeginGUI(); GUI.Box(new Rect(0, Screen.height - 300, 200, 30), "Cutscene Preview"); //Rect camRect = GUILayoutUtility.GetRect(100, 100); if (scene != null) { Camera cam = null; foreach (CutsceneTrack track in scene.tracks) { if (track.type == Cutscene.MediaType.Shots) { CutsceneClip clip = track.ContainsClipAtTime(scene.playhead); if (clip != null) { cam = ((CutsceneShot)clip.master).camera; break; } } } if (cam != null) { DrawCamera(new Rect(0, 0, 200, 200), cam); } } Handles.EndGUI(); } void DrawCamera (Rect previewRect, Camera camera) { if (Event.current.type == EventType.Repaint) { Rect cameraOriginalRect = camera.pixelRect; camera.pixelRect = previewRect; camera.Render(); camera.pixelRect = cameraOriginalRect; } } } diff --git a/Cutscene Ed/Editor/CutsceneMediaWindow.cs b/Cutscene Ed/Editor/CutsceneMediaWindow.cs index 7fd9972..f44f0ae 100755 --- a/Cutscene Ed/Editor/CutsceneMediaWindow.cs +++ b/Cutscene Ed/Editor/CutsceneMediaWindow.cs @@ -1,286 +1,308 @@ -using UnityEditor; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEditor; using UnityEngine; class CutsceneMediaWindow : ICutsceneGUI { readonly CutsceneEditor ed; readonly GUIContent[] mediaTabs = { new GUIContent("Shots", "Camera views."), new GUIContent("Actors", "Animated game objects."), new GUIContent("Audio", "Dialog, background music and sound effects."), new GUIContent("Subtitles", "Textual versions of dialog.") }; Cutscene.MediaType currentMediaTab = Cutscene.MediaType.Shots; - Vector2[] mediaScrollPos = { Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero }; + Vector2[] mediaScrollPos = new Vector2[4]; CutsceneMedia selectedMediaItem; readonly GUIContent newMediaLabel = new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/icon_add.png") as Texture, "Add new media."); readonly GUIContent insertMediaLabel = new GUIContent("Insert", "Insert the selected shot onto the timeline."); public CutsceneMediaWindow (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the media pane's GUI. /// </summary> /// <param name="rect">The media pane's Rect.</param> public void OnGUI (Rect rect) { GUILayout.BeginArea(rect, ed.style.GetStyle("Pane")); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); currentMediaTab = (Cutscene.MediaType)GUILayout.Toolbar((int)currentMediaTab, mediaTabs, GUILayout.Width(CutsceneEditor.PaneTabsWidth(mediaTabs.Length))); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); switch (currentMediaTab) { case Cutscene.MediaType.Shots: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { ed.scene.NewShot(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneShot shot in ed.scene.shots) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == shot ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(shot.name, ed.mediaIcons[(int)Cutscene.MediaType.Shots]); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(shot, itemRect); } EditorGUILayout.EndScrollView(); break; case Cutscene.MediaType.Actors: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { CutsceneAddActor.CreateWizard(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneActor actor in ed.scene.actors) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == actor ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(actor.anim.name, ed.mediaIcons[(int)Cutscene.MediaType.Actors]); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(actor, itemRect); } EditorGUILayout.EndScrollView(); break; case Cutscene.MediaType.Audio: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { // Show a wizard that will take care of adding audio CutsceneAddAudio.CreateWizard(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneAudio aud in ed.scene.audioSources) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == aud ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(aud.name, ed.mediaIcons[(int)Cutscene.MediaType.Audio]); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(aud, itemRect); } EditorGUILayout.EndScrollView(); break; case Cutscene.MediaType.Subtitles: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { // Show a wizard that will take care of adding audio CutsceneAddSubtitle.CreateWizard(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneSubtitle subtitle in ed.scene.subtitles) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == subtitle ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(ed.mediaIcons[(int)Cutscene.MediaType.Subtitles]); GUILayout.Label(itemLabel, GUILayout.ExpandWidth(false)); subtitle.dialog = EditorGUILayout.TextField(subtitle.dialog); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(subtitle, itemRect); } EditorGUILayout.EndScrollView(); break; default: break; } GUILayout.EndArea(); // Handle drag and drop events if (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform) { // Show a copy icon on the drag DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (Event.current.type == EventType.DragPerform && rect.Contains(Event.current.mousePosition)) { DragAndDrop.AcceptDrag(); Object[] draggedObjects = DragAndDrop.objectReferences; // Create the appropriate cutscene objects for each dragged object foreach (Object obj in draggedObjects) { if (obj is AudioClip) { ed.scene.NewAudio((AudioClip)obj); } else if (obj is GameObject && ((GameObject)obj).animation != null) { GameObject go = obj as GameObject; foreach (AnimationClip anim in AnimationUtility.GetAnimationClips(go.animation)) { ed.scene.NewActor(anim, go); } } EDebug.Log("Cutscene Editor: dropping " + obj.GetType()); } } Event.current.Use(); } } /// <summary> /// Handles left and right mouse clicks of media items. /// </summary> /// <param name="item">The item clicked on.</param> /// <param name="rect">The item's Rect.</param> void HandleMediaItemClicks (CutsceneMedia item, Rect rect) { Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && rect.Contains(mousePos)) { switch (Event.current.button) { case 0: // Left click selectedMediaItem = item; EditorGUIUtility.PingObject(item); break; case 1: // Right click EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneObject/", new MenuCommand(item)); break; default: break; } Event.current.Use(); } } /// <summary> /// Determines whether or not the currently selected cutscene object can be inserted into the selected timeline. /// </summary> /// <returns>True if the selected clip and the selected track are the same, false otherwise.</returns> bool IsMediaInsertable () { return selectedMediaItem != null && selectedMediaItem.type == ed.selectedTrack.type; } /// <summary> /// Inserts the given cutscene object into the timeline. /// </summary> /// <param name="obj">The cutscene object to insert.</param> void Insert (CutsceneMedia obj) { CutsceneClip newClip = new CutsceneClip(obj); newClip.timelineStart = ed.scene.playhead; // If there are no existing tracks, add a new one if (ed.scene.tracks.Length == 0) { ed.scene.AddTrack(newClip.type); } // Manage overlap with other clips CutsceneClip existingClip = ed.selectedTrack.ContainsClipAtTime(ed.scene.playhead); if (existingClip != null) { CutsceneClip middleOfSplit = CutsceneTimeline.SplitClipAtTime(ed.scene.playhead, ed.selectedTrack, existingClip); CutsceneTimeline.SplitClipAtTime(ed.scene.playhead + newClip.duration, ed.selectedTrack, middleOfSplit); ed.selectedTrack.clips.Remove(middleOfSplit); } ed.selectedTrack.clips.Add(newClip); EDebug.Log("Cutscene Editor: inserting " + newClip.name + " into timeline " + ed.selectedTrack + " at " + ed.scene.playhead); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneNavigation.cs b/Cutscene Ed/Editor/CutsceneNavigation.cs index 69e58aa..2e273e3 100755 --- a/Cutscene Ed/Editor/CutsceneNavigation.cs +++ b/Cutscene Ed/Editor/CutsceneNavigation.cs @@ -1,41 +1,63 @@ -using UnityEditor; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEditor; using UnityEngine; class CutsceneNavigation : ICutsceneGUI { readonly CutsceneEditor ed; readonly ICutsceneGUI playbackControls; readonly ICutsceneGUI timecodeBar; readonly GUIContent zoomButton = new GUIContent("", "Zoom timeline to entire scene."); public CutsceneNavigation (CutsceneEditor ed) { this.ed = ed; playbackControls = new CutscenePlaybackControls(ed); timecodeBar = new CutsceneTimecodeBar(ed); } public void OnGUI (Rect rect) { GUI.BeginGroup(rect); float zoomButtonWidth = GUI.skin.verticalScrollbar.fixedWidth; float timecodeBarWidth = ed.position.width - CutsceneTimeline.trackInfoWidth - zoomButtonWidth; // Playback controls Rect playbackControlsRect = new Rect(0, 0, CutsceneTimeline.trackInfoWidth, rect.height); playbackControls.OnGUI(playbackControlsRect); // Timecode bar Rect timecodeBarRect = new Rect(playbackControlsRect.xMax, 0, timecodeBarWidth, rect.height); timecodeBar.OnGUI(timecodeBarRect); // Zoom to view entire project Rect zoomButtonRect = new Rect(timecodeBarRect.xMax, 0, zoomButtonWidth, rect.height); if (GUI.Button(zoomButtonRect, zoomButton, EditorStyles.toolbarButton)) { ed.timelineZoom = ed.timelineMin; EDebug.Log("Cutscene Editor: zoomed timeline to entire scene"); } GUI.EndGroup(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneOptions.cs b/Cutscene Ed/Editor/CutsceneOptions.cs index 6a07181..1a4d995 100755 --- a/Cutscene Ed/Editor/CutsceneOptions.cs +++ b/Cutscene Ed/Editor/CutsceneOptions.cs @@ -1,22 +1,44 @@ -using UnityEditor; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEditor; using UnityEngine; class CutsceneOptions : ICutsceneGUI { readonly CutsceneEditor ed; public CutsceneOptions (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the options window. /// </summary> /// <param name="rect">The options window's Rect.</param> public void OnGUI (Rect rect) { GUILayout.BeginArea(rect); ed.scene.inPoint = GUILayout.HorizontalSlider(ed.scene.inPoint, 0, 100); GUILayout.EndArea(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutscenePlaybackControls.cs b/Cutscene Ed/Editor/CutscenePlaybackControls.cs index daa69bf..7f93c81 100755 --- a/Cutscene Ed/Editor/CutscenePlaybackControls.cs +++ b/Cutscene Ed/Editor/CutscenePlaybackControls.cs @@ -1,75 +1,97 @@ -using UnityEditor; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEditor; using UnityEngine; class CutscenePlaybackControls : ICutsceneGUI { readonly CutsceneEditor ed; const int buttonWidth = 18; readonly GUIContent inPointLabel = new GUIContent( EditorGUIUtility.LoadRequired("Cutscene Ed/playback_in.png") as Texture, "Go to in point." ); readonly GUIContent backLabel = new GUIContent( EditorGUIUtility.LoadRequired("Cutscene Ed/playback_back.png") as Texture, "Go back a second." ); /* readonly GUIContent playLabel = new GUIContent( EditorGUIUtility.LoadRequired("Cutscene Ed/playback_play.png") as Texture, "Play." ); */ readonly GUIContent forwardLabel = new GUIContent( EditorGUIUtility.LoadRequired("Cutscene Ed/playback_forward.png") as Texture, "Go forward a second." ); readonly GUIContent outPointLabel = new GUIContent( EditorGUIUtility.LoadRequired("Cutscene Ed/playback_out.png") as Texture, "Go to out point." ); public CutscenePlaybackControls (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays playback controls. /// </summary> /// <param name="rect">The playback controls' Rect.</param> public void OnGUI (Rect rect) { GUI.BeginGroup(rect, EditorStyles.toolbar); // In point Rect inPointRect = new Rect(6, 0, buttonWidth, rect.height); if (GUI.Button(inPointRect, inPointLabel, EditorStyles.toolbarButton)) { ed.scene.playhead = ed.scene.inPoint; } // Back Rect backRect = new Rect(inPointRect.xMax, 0, buttonWidth, rect.height); if (GUI.Button(backRect, backLabel, EditorStyles.toolbarButton)) { ed.scene.playhead -= CutsceneTimeline.scrubSmallJump; } /* Feature not implemented yet: // Play Rect playRect = new Rect(backRect.xMax, 0, buttonWidth, rect.height); if (GUI.Button(playRect, playLabel, EditorStyles.toolbarButton)) { EDebug.Log("Cutscene Editor: previewing scene (feature not implemented)"); };*/ // Forward Rect forwardRect = new Rect(backRect.xMax, 0, buttonWidth, rect.height); if (GUI.Button(forwardRect, forwardLabel, EditorStyles.toolbarButton)) { ed.scene.playhead += CutsceneTimeline.scrubSmallJump; } // Out point Rect outPointRect = new Rect(forwardRect.xMax, 0, buttonWidth, rect.height); if (GUI.Button(outPointRect, outPointLabel, EditorStyles.toolbarButton)) { ed.scene.playhead = ed.scene.outPoint; } Rect floatRect = new Rect(outPointRect.xMax + 4, 2, 50, rect.height); ed.scene.playhead = EditorGUI.FloatField(floatRect, ed.scene.playhead, EditorStyles.toolbarTextField); GUI.EndGroup(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutscenePreview.cs b/Cutscene Ed/Editor/CutscenePreview.cs index c54c0c7..8f01fab 100755 --- a/Cutscene Ed/Editor/CutscenePreview.cs +++ b/Cutscene Ed/Editor/CutscenePreview.cs @@ -1,48 +1,70 @@ -using UnityEngine; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEngine; using UnityEditor; class CutscenePreview : ICutsceneGUI { //readonly CutsceneEditor ed; public CutscenePreview (CutsceneEditor ed) { //this.ed = ed; } public void OnGUI (Rect rect) { //GUI.DrawTexture(rect, ); Camera cam = GameObject.Find("Some Cam").GetComponent<Camera>(); EDebug.Log(cam.name); cam.targetTexture = new RenderTexture(128, 128, 32); cam.targetTexture.isPowerOfTwo = true; cam.targetTexture.Create(); GUI.DrawTexture(rect, cam.targetTexture); cam.targetTexture.Release(); cam.targetTexture = null; /*if (Event.current.type == EventType.repaint) { MovieTexture target = base.target as MovieTexture; float num = Mathf.Min(Mathf.Min((float)(r.width / ((float)target.width)), (float)(r.height / ((float)target.height))), 1f); Rect viewRect = new Rect(r.x, r.y, target.width * num, target.height * num); PreviewGUI.BeginScrollView(r, this.m_Pos, viewRect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb"); GUI.DrawTexture(viewRect, target, ScaleMode.StretchToFill, false); this.m_Pos = PreviewGUI.EndScrollView(); if (target.isPlaying) { GUIView.current.Repaint(); } if (Application.isPlaying) { if (target.isPlaying) { Rect position = new Rect(r.x, r.y + 10f, r.width, 20f); EditorGUI.DropShadowLabel(position, "Can't pause preview when in play mode"); } else { Rect rect3 = new Rect(r.x, r.y + 10f, r.width, 20f); EditorGUI.DropShadowLabel(rect3, "Can't start preview when in play mode"); } } }*/ } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneSubtitleInspector.cs b/Cutscene Ed/Editor/CutsceneSubtitleInspector.cs index 5b64470..51b96a1 100644 --- a/Cutscene Ed/Editor/CutsceneSubtitleInspector.cs +++ b/Cutscene Ed/Editor/CutsceneSubtitleInspector.cs @@ -1,25 +1,47 @@ +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + using UnityEditor; using UnityEngine; /// <summary> /// A custom inspector for a subtitle. /// </summary> [CustomEditor (typeof(CutsceneSubtitle))] public class CutsceneSubtitleInspector : Editor { CutsceneSubtitle subtitle { get { return target as CutsceneSubtitle; } } public override void OnInspectorGUI () { EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Dialog"); subtitle.dialog = EditorGUILayout.TextArea(subtitle.dialog); EditorGUILayout.EndHorizontal(); if (GUI.changed) { EditorUtility.SetDirty(subtitle); } } } diff --git a/Cutscene Ed/Editor/CutsceneTimecodeBar.cs b/Cutscene Ed/Editor/CutsceneTimecodeBar.cs index 0dd3f00..328d11b 100755 --- a/Cutscene Ed/Editor/CutsceneTimecodeBar.cs +++ b/Cutscene Ed/Editor/CutsceneTimecodeBar.cs @@ -1,161 +1,183 @@ -using UnityEngine; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEngine; using UnityEditor; class CutsceneTimecodeBar : ICutsceneGUI { readonly CutsceneEditor ed; const int shortTickHeight = 3; const int tallTickHeight = 6; readonly Color tickColor = Color.gray; readonly Color playheadBlockColor = Color.black; readonly Color inOutPointColour = Color.cyan; readonly Texture positionIndicatorIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/position_indicator.png") as Texture; readonly Texture inPointIndicatorIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/inpoint_indicator.png") as Texture; readonly Texture outPointIndicatorIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/outpoint_indicator.png") as Texture; readonly GUIContent inTooltip = new GUIContent("", "In point."); readonly GUIContent outTooltip = new GUIContent("", "Out point."); public CutsceneTimecodeBar (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the timecode bar with vertical lines indicating the time and the playhead. /// </summary> /// <param name="rect">The timecode bar's Rect.</param> public void OnGUI (Rect rect) { GUI.BeginGroup(rect); // Create a button that looks like a toolbar if (GUI.RepeatButton(new Rect(0, 0, rect.width, rect.height), GUIContent.none, EditorStyles.toolbar)) { float position = Event.current.mousePosition.x + ed.timelineScrollPos.x; ed.scene.playhead = position / ed.timelineZoom; // Show a visual notification of the position GUIContent notification = new GUIContent("Playhead " + ed.scene.playhead.ToString("N2")); ed.ShowNotification(notification); ed.Repaint(); //SceneView.RepaintAll(); } else { // TODO Investigate if attempting to remove the notification every frame like this is wasteful ed.RemoveNotification(); } DrawTicks(); DrawLabels(); DrawPlayhead(); DrawInOutPoints(); GUI.EndGroup(); } /// <summary> /// Draws vertical lines representing time increments. /// </summary> void DrawTicks () { Handles.color = tickColor; // Draw short ticks every second for (float i = 0; i < ed.scene.duration * ed.timelineZoom; i += ed.timelineZoom) { float xPos = i - ed.timelineScrollPos.x; Handles.DrawLine(new Vector3(xPos, 0, 0), new Vector3(xPos, shortTickHeight)); } // Draw tall ticks every ten seconds for (float i = 0; i < ed.scene.duration * ed.timelineZoom; i += ed.timelineZoom * 10) { float xPos = i - ed.timelineScrollPos.x; Handles.DrawLine(new Vector3(xPos, 0, 0), new Vector3(xPos, tallTickHeight)); } } /// <summary> /// Draws labels indicating the time. /// </summary> void DrawLabels () { for (float i = 0; i < 1000; i += 10) { float xPos = (i * ed.timelineZoom) - ed.timelineScrollPos.x; GUIContent label = new GUIContent(i + ""); Vector2 dimensions = EditorStyles.miniLabel.CalcSize(label); Rect labelRect = new Rect(xPos - (dimensions.x / 2), 2, dimensions.x, dimensions.y); GUI.Label(labelRect, label, EditorStyles.miniLabel); } } /// <summary> /// Draws the playhead. /// </summary> void DrawPlayhead () { // Draw position indicator float pos = (ed.scene.playhead * ed.timelineZoom) - ed.timelineScrollPos.x; GUI.DrawTexture(new Rect(pos - 4, 0, 8, 8), positionIndicatorIcon); Handles.color = Color.black; // Vertical line Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, EditorStyles.toolbar.fixedHeight); Handles.DrawLine(top, bottom); // Zoom indicator block Handles.color = playheadBlockColor; for (int i = 1; i <= ed.timelineZoom; i++) { float xPos = pos + i; top = new Vector3(xPos, 4); bottom = new Vector3(xPos, EditorStyles.toolbar.fixedHeight - 1); Handles.DrawLine(top, bottom); } } /// <summary> /// Draws the in and out points. /// </summary> void DrawInOutPoints () { Handles.color = inOutPointColour; DrawInPoint(); DrawOutPoint(); } /// <summary> /// Draws the in point. /// </summary> void DrawInPoint () { float pos = (ed.scene.inPoint * ed.timelineZoom) - ed.timelineScrollPos.x; // Icon Rect indicatorRect = new Rect(pos, 0, 4, 8); GUI.DrawTexture(indicatorRect, inPointIndicatorIcon); // Tooltip GUI.Label(indicatorRect, inTooltip); // Vertical line Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, EditorStyles.toolbar.fixedHeight); Handles.DrawLine(top, bottom); } /// <summary> /// Draws the out point. /// </summary> void DrawOutPoint () { float pos = (ed.scene.outPoint * ed.timelineZoom) - ed.timelineScrollPos.x; // Icon Rect indicatorRect = new Rect(pos - 4, 0, 4, 8); GUI.DrawTexture(indicatorRect, outPointIndicatorIcon); // Tooltip GUI.Label(indicatorRect, outTooltip); // Vertical line Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, EditorStyles.toolbar.fixedHeight); Handles.DrawLine(top, bottom); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTimeline.cs b/Cutscene Ed/Editor/CutsceneTimeline.cs index 6a3b523..8b7db67 100755 --- a/Cutscene Ed/Editor/CutsceneTimeline.cs +++ b/Cutscene Ed/Editor/CutsceneTimeline.cs @@ -1,112 +1,134 @@ -using UnityEditor; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEditor; using UnityEngine; public enum DragEvent { Move, ResizeLeft, ResizeRight } class CutsceneTimeline : ICutsceneGUI { readonly CutsceneEditor ed; public const int scrubLargeJump = 10; public const int scrubSmallJump = 1; readonly ICutsceneGUI navigation; readonly ICutsceneGUI tracksView; readonly ICutsceneGUI trackControls; readonly ICutsceneGUI trackInfo; public const float timelineZoomMin = 1f; public const float timelineZoomMax = 100f; public const float trackInfoWidth = 160f; public CutsceneTimeline (CutsceneEditor ed) { this.ed = ed; navigation = new CutsceneNavigation(ed); tracksView = new CutsceneTracksView(ed); trackControls = new CutsceneTrackControls(ed); trackInfo = new CutsceneTrackInfo(ed); } /// <summary> /// Displays the timeline's GUI. /// </summary> /// <param name="rect">The timeline's Rect.</param> public void OnGUI (Rect rect) { GUILayout.BeginArea(rect); float rightColWidth = GUI.skin.verticalScrollbar.fixedWidth; float middleColWidth = rect.width - CutsceneTimeline.trackInfoWidth - rightColWidth; ed.timelineMin = CutsceneTimeline.timelineZoomMin * (middleColWidth / ed.scene.duration); ed.timelineZoom = Mathf.Clamp(ed.timelineZoom, ed.timelineMin, CutsceneTimeline.timelineZoomMax); // Navigation bar Rect navigationRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.toolbar, GUILayout.Width(rect.width)); navigation.OnGUI(navigationRect); // Begin Tracks EditorGUILayout.BeginHorizontal(GUILayout.Width(rect.width), GUILayout.ExpandHeight(true)); // Track info //Rect trackInfoRect = GUILayoutUtility.GetRect(trackInfoWidth, rect.height - navigationRect.yMax - GUI.skin.horizontalScrollbar.fixedHeight); Rect trackInfoRect = new Rect(0, 0, CutsceneTimeline.trackInfoWidth, 9999); trackInfo.OnGUI(trackInfoRect); // Track controls float trackControlsHeight = GUI.skin.horizontalScrollbar.fixedHeight; Rect trackControlsRect = new Rect(0, rect.height - trackControlsHeight, CutsceneTimeline.trackInfoWidth, trackControlsHeight); trackControls.OnGUI(trackControlsRect); // Tracks Rect tracksRect = new Rect(trackInfoRect.xMax, navigationRect.yMax, middleColWidth + rightColWidth, rect.height - navigationRect.yMax); tracksView.OnGUI(tracksRect); EditorGUILayout.EndHorizontal(); if (Event.current.type == EventType.KeyDown) { // Key presses ed.HandleKeyboardShortcuts(Event.current); } GUILayout.EndArea(); } /// <summary> /// Moves the playhead. /// </summary> /// <param name="playheadPos">The position to move the playhead to.</param> void MovePlayheadToPosition (float playheadPos) { ed.scene.playhead = playheadPos / ed.timelineZoom; } /// <summary> /// Splits a clip into two separate ones at the specified time. /// </summary> /// <param name="splitPoint">The time at which to split the clip.</param> /// <param name="track">The track the clip is sitting on.</param> /// <param name="clip">The clip to split.</param> /// <returns>The new clip.</returns> public static CutsceneClip SplitClipAtTime (float splitPoint, CutsceneTrack track, CutsceneClip clip) { CutsceneClip newClip = clip.GetCopy(); // Make sure the clip actually spans over the split point if (splitPoint < clip.timelineStart || splitPoint > clip.timelineStart + clip.duration) { EDebug.Log("Cutscene Editor: cannot split clip; clip does not contain the split point"); return null; } clip.SetOutPoint(clip.inPoint + (splitPoint - clip.timelineStart)); newClip.SetInPoint(clip.outPoint); newClip.SetTimelineStart(splitPoint); track.clips.Add(newClip); Event.current.Use(); EDebug.Log("Cutscene Editor: splitting clip at time " + splitPoint); return newClip; } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTools.cs b/Cutscene Ed/Editor/CutsceneTools.cs index cef6577..eed5241 100755 --- a/Cutscene Ed/Editor/CutsceneTools.cs +++ b/Cutscene Ed/Editor/CutsceneTools.cs @@ -1,35 +1,57 @@ -using UnityEditor; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEditor; using UnityEngine; public enum Tool { MoveResize, Scissors, Zoom } class CutsceneTools : ICutsceneGUI { readonly CutsceneEditor ed; readonly GUIContent[] tools = { new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_move.png") as Texture, "Move/Resize"), new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_scissors.png") as Texture, "Scissors"), new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_zoom.png") as Texture, "Zoom") }; public CutsceneTools (CutsceneEditor ed) { this.ed = ed; } public void OnGUI (Rect rect) { GUILayout.BeginArea(rect); EditorGUILayout.BeginHorizontal(ed.style.GetStyle("Tools Bar"), GUILayout.Width(rect.width)); GUILayout.FlexibleSpace(); ed.currentTool = (Tool)GUILayout.Toolbar((int)ed.currentTool, tools); EditorGUILayout.EndHorizontal(); GUILayout.EndArea(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTrackControls.cs b/Cutscene Ed/Editor/CutsceneTrackControls.cs index 2975f7a..b34549a 100755 --- a/Cutscene Ed/Editor/CutsceneTrackControls.cs +++ b/Cutscene Ed/Editor/CutsceneTrackControls.cs @@ -1,39 +1,61 @@ -using UnityEngine; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEngine; using UnityEditor; class CutsceneTrackControls : ICutsceneGUI { readonly CutsceneEditor ed; readonly GUIContent newTrackLabel = new GUIContent( EditorGUIUtility.LoadRequired("Cutscene Ed/icon_addtrack.png") as Texture, "Add a new track." ); public CutsceneTrackControls (CutsceneEditor ed) { this.ed = ed; } public void OnGUI (Rect rect) { // TODO Make this a style in the cutscene editor's GUISkin GUIStyle popupStyle = "MiniToolbarButton"; popupStyle.padding = new RectOffset(0, 0, 2, 1); // Left, right, top, bottom GUI.BeginGroup(rect, GUI.skin.GetStyle("MiniToolbarButtonLeft")); // New track popdown Rect newTrackRect = new Rect(0, 0, 33, rect.height); GUI.Label(newTrackRect, newTrackLabel, popupStyle); if (Event.current.type == EventType.MouseDown && newTrackRect.Contains(Event.current.mousePosition)) { GUIUtility.hotControl = 0; EditorUtility.DisplayPopupMenu(newTrackRect, "Component/Cutscene/Track", null); Event.current.Use(); } // Timeline zoom slider Rect timelineZoomRect = new Rect(newTrackRect.xMax + GUI.skin.horizontalSlider.margin.left, -1, rect.width - newTrackRect.xMax - GUI.skin.horizontalSlider.margin.horizontal, rect.height); ed.timelineZoom = GUI.HorizontalSlider(timelineZoomRect, ed.timelineZoom, ed.timelineMin, CutsceneTimeline.timelineZoomMax); GUI.EndGroup(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTrackInfo.cs b/Cutscene Ed/Editor/CutsceneTrackInfo.cs index dffcafd..10edba9 100755 --- a/Cutscene Ed/Editor/CutsceneTrackInfo.cs +++ b/Cutscene Ed/Editor/CutsceneTrackInfo.cs @@ -1,87 +1,109 @@ -using UnityEngine; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEngine; using UnityEditor; class CutsceneTrackInfo : ICutsceneGUI { readonly CutsceneEditor ed; readonly GUIContent visibilityIcon = new GUIContent("", EditorGUIUtility.LoadRequired("Cutscene Ed/icon_eye.png") as Texture, "Toggle visibility." ); readonly GUIContent lockIcon = new GUIContent("", EditorGUIUtility.LoadRequired("Cutscene Ed/icon_lock.png") as Texture, "Toggle track lock." ); public CutsceneTrackInfo (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the track info GUI. /// </summary> /// <param name="rect">The track info's Rect.</param> public void OnGUI (Rect rect) { ed.timelineScrollPos.y = EditorGUILayout.BeginScrollView( new Vector2(0, ed.timelineScrollPos.y), false, false, ed.style.horizontalScrollbar, ed.style.verticalScrollbar, GUIStyle.none, GUILayout.Width(CutsceneTimeline.trackInfoWidth), GUILayout.ExpandHeight(true)).y; foreach (CutsceneTrack track in ed.scene.tracks) { if (track == ed.selectedTrack) { GUI.SetNextControlName("track"); } Rect infoRect = EditorGUILayout.BeginHorizontal(ed.style.GetStyle("Track Info")); track.enabled = GUILayout.Toggle(track.enabled, visibilityIcon, EditorStyles.miniButtonLeft, GUILayout.ExpandWidth(false)); track.locked = GUILayout.Toggle(track.locked, lockIcon, EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false)); GUILayout.Space(10); GUI.enabled = track.enabled; // Track name and icon GUIContent trackIcon = new GUIContent(ed.mediaIcons[(int)track.type]); GUILayout.Label(trackIcon, GUILayout.ExpandWidth(false)); // Set a minimum width to keep the label from becoming uneditable Rect trackNameRect = GUILayoutUtility.GetRect(new GUIContent(track.name), EditorStyles.miniLabel, GUILayout.ExpandWidth(false), GUILayout.MinWidth(20)); track.name = EditorGUI.TextField(trackNameRect, track.name, EditorStyles.miniLabel); GUI.enabled = true; EditorGUILayout.EndHorizontal(); if (track == ed.selectedTrack) { GUI.FocusControl("track"); } // Handle clicks Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && infoRect.Contains(mousePos)) { switch (Event.current.button) { case 0: // Left mouse button ed.selectedTrack = track; break; case 1: // Right mouse button EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneTrack/", new MenuCommand(track)); break; default: break; } Event.current.Use(); } } // Divider line Handles.color = Color.grey; Handles.DrawLine(new Vector3(67, 0), new Vector3(67, rect.yMax)); EditorGUILayout.EndScrollView(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTracksView.cs b/Cutscene Ed/Editor/CutsceneTracksView.cs index 57e3de9..7a09858 100755 --- a/Cutscene Ed/Editor/CutsceneTracksView.cs +++ b/Cutscene Ed/Editor/CutsceneTracksView.cs @@ -1,342 +1,364 @@ -using UnityEngine; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEngine; using UnityEditor; class CutsceneTracksView : ICutsceneGUI { readonly CutsceneEditor ed; readonly Texture overlay = EditorGUIUtility.LoadRequired("Cutscene Ed/overlay.png") as Texture; readonly Color inOutPointColour = Color.cyan; public CutsceneTracksView (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the tracks GUI. /// </summary> /// <param name="rect">The tracks' Rect.</param> public void OnGUI (Rect rect) { // Display background Rect background = new Rect(rect.x, rect.y, rect.width - GUI.skin.verticalScrollbar.fixedWidth, rect.height - GUI.skin.horizontalScrollbar.fixedHeight); GUI.BeginGroup(background, GUI.skin.GetStyle("AnimationCurveEditorBackground")); GUI.EndGroup(); float trackHeight = ed.style.GetStyle("Track").fixedHeight + ed.style.GetStyle("Track").margin.vertical; // TODO Make the track width take into account clips that are beyond the out point float tracksWidth = (ed.scene.outPoint + 10) * ed.timelineZoom; float tracksHeight = trackHeight * ed.scene.tracks.Length; Rect view = new Rect(0, 0, Mathf.Max(background.width + 1, tracksWidth), Mathf.Max(background.height + 1, tracksHeight)); ed.timelineScrollPos = GUI.BeginScrollView(rect, ed.timelineScrollPos, view, true, true); // Zoom clicks if (ed.currentTool == Tool.Zoom && Event.current.type == EventType.MouseDown) { if (Event.current.alt && Event.current.shift) { // Zoom out all the way ed.timelineZoom = CutsceneTimeline.timelineZoomMin; } else if (Event.current.shift) { // Zoom in all the way ed.timelineZoom = CutsceneTimeline.timelineZoomMax; } else if (Event.current.alt) { // Zoom out ed.timelineZoom -= 10; } else { // Zoom in ed.timelineZoom += 10; } Event.current.Use(); } // Draw track divider lines Handles.color = Color.grey; for (int i = 0; i < ed.scene.tracks.Length; i++) { Rect trackRect = new Rect(0, trackHeight * i, view.width, trackHeight); DisplayTrack(trackRect, ed.scene.tracks[i]); float yPos = (i + 1) * trackHeight - 1; Handles.DrawLine(new Vector3(0, yPos), new Vector3(view.width, yPos)); } // Draw overlay over in area Rect inOverlay = new Rect(0, 0, ed.scene.inPoint * ed.timelineZoom, view.height); GUI.DrawTexture(inOverlay, overlay); // Draw overlay over out area Rect outOverlay = new Rect(ed.scene.outPoint * ed.timelineZoom, 0, 0, view.height); outOverlay.width = view.width - outOverlay.x; GUI.DrawTexture(outOverlay, overlay); DrawLines(view); GUI.EndScrollView(); } /// <summary> /// Displays visual tracks upon which clips sit. /// </summary> void DisplayTrack (Rect rect, CutsceneTrack track) { GUI.enabled = track.enabled; for (int i = track.clips.Count - 1; i >= 0; i--) { DisplayClip(rect, track, track.clips[i]); } GUI.enabled = true; // Handle clicks Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && rect.Contains(mousePos)) { switch (Event.current.button) { case 0: // Left mouse button ed.selectedTrack = track; ed.selectedClip = null; break; case 1: // Right mouse button EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneTrack/", new MenuCommand(track)); Event.current.Use(); break; default: break; } Event.current.Use(); } } /// <summary> /// Displays a clip. /// </summary> /// <param name="trackRect">The Rect of the track the clip sits on.</param> /// <param name="track">The track the clip sits on.</param> /// <param name="clip">The clip to display.</param> void DisplayClip (Rect trackRect, CutsceneTrack track, CutsceneClip clip) { const float trimWidth = 5f; GUIStyle clipStyle = ed.style.GetStyle("Selected Clip"); // Set the clip style if this isn't the selected clip (selected clips all share the same style) if (clip != ed.selectedClip) { switch (clip.type) { case Cutscene.MediaType.Shots: clipStyle = ed.style.GetStyle("Shot Clip"); break; case Cutscene.MediaType.Actors: clipStyle = ed.style.GetStyle("Actor Clip"); break; case Cutscene.MediaType.Audio: clipStyle = ed.style.GetStyle("Audio Clip"); break; default: // Cutscene.MediaType.Subtitles clipStyle = ed.style.GetStyle("Subtitle Clip"); break; } } Rect rect = new Rect((trackRect.x + clip.timelineStart) * ed.timelineZoom, trackRect.y + 1, clip.duration * ed.timelineZoom, clipStyle.fixedHeight); GUI.BeginGroup(rect, clipStyle); GUIContent clipLabel = new GUIContent(clip.name, "Clip: " + clip.name + "\nDuration: " + clip.duration + "\nTimeline start: " + clip.timelineStart + "\nTimeline end: " + (clip.timelineStart + clip.duration)); Rect clipLabelRect = new Rect(clipStyle.contentOffset.x, 0, rect.width - clipStyle.contentOffset.x, rect.height); GUI.Label(clipLabelRect, clipLabel); GUI.EndGroup(); // Handle mouse clicks Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { switch (Event.current.button) { case 0: // Left mouse button ed.selectedClip = clip; ed.selectedTrack = track; break; case 1: // Right mouse button EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneClip/", new MenuCommand(clip)); Event.current.Use(); break; default: break; } } if (clip.setToDelete) { ed.selectedTrack.clips.Remove(clip); return; } // Don't allow actions to be performed on the clip if the track is disabled or locked if (!track.enabled || track.locked) { return; } switch (ed.currentTool) { case Tool.MoveResize: // Define edit areas, adding custom cursors when hovered over // Move Rect move = new Rect(rect.x + trimWidth, rect.y, rect.width - (2 * trimWidth), rect.height); EditorGUIUtility.AddCursorRect(move, MouseCursor.SlideArrow); // Resize left Rect resizeLeft = new Rect(rect.x, rect.y, trimWidth, rect.height); EditorGUIUtility.AddCursorRect(resizeLeft, MouseCursor.ResizeHorizontal); // Resize right Rect resizeRight = new Rect(rect.xMax - trimWidth, rect.y, trimWidth, rect.height); EditorGUIUtility.AddCursorRect(resizeRight, MouseCursor.ResizeHorizontal); if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { ed.dragClip = clip; // Move if (move.Contains(Event.current.mousePosition)) { ed.dragEvent = DragEvent.Move; EDebug.Log("Cutscene Editor: starting clip move"); // Resize left } else if (resizeLeft.Contains(Event.current.mousePosition)) { ed.dragEvent = DragEvent.ResizeLeft; EDebug.Log("Cutscene Editor: starting clip resize left"); // Resize right } else if (resizeRight.Contains(Event.current.mousePosition)) { ed.dragEvent = DragEvent.ResizeRight; EDebug.Log("Cutscene Editor: starting clip resize right"); } Event.current.Use(); } else if (Event.current.type == EventType.MouseDrag && ed.dragClip == clip) { float shift = Event.current.delta.x / ed.timelineZoom; switch (ed.dragEvent) { case DragEvent.Move: float newPos = clip.timelineStart + shift; // Left collisions CutsceneClip leftCollision = track.ContainsClipAtTime(newPos, clip); if (leftCollision != null) { newPos = leftCollision.timelineStart + leftCollision.duration; } // Right collisions CutsceneClip rightCollision = track.ContainsClipAtTime(newPos + clip.duration, clip); if (rightCollision != null) { newPos = rightCollision.timelineStart - clip.duration; } if (newPos + clip.duration > ed.scene.duration) { newPos = ed.scene.duration - clip.duration; } clip.SetTimelineStart(newPos); break; case DragEvent.ResizeLeft: clip.SetTimelineStart(clip.timelineStart + shift); clip.SetInPoint(clip.inPoint + shift); // TODO Improve collision behaviour CutsceneClip leftResizeCollision = track.ContainsClipAtTime(clip.timelineStart, clip); if (leftResizeCollision != null) { clip.SetTimelineStart(leftResizeCollision.timelineStart + leftResizeCollision.duration); } break; case DragEvent.ResizeRight: float newOut = clip.outPoint + shift; // Right collisions CutsceneClip rightResizeCollision = track.ContainsClipAtTime(clip.timelineStart + clip.duration + shift, clip); if (rightResizeCollision != null) { newOut = rightResizeCollision.timelineStart - clip.timelineStart + clip.inPoint; } clip.SetOutPoint(newOut); break; default: break; } Event.current.Use(); } else if (Event.current.type == EventType.MouseUp) { ed.dragClip = null; Event.current.Use(); } break; case Tool.Scissors: // TODO Switch to something better than the text cursor, if possible EditorGUIUtility.AddCursorRect(rect, MouseCursor.Text); if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { SplitClip(track, clip, Event.current.mousePosition); Event.current.Use(); } break; default: break; } } /// <summary> /// Splits a clip into two separate ones. /// </summary> /// <param name="track">The track the clip is sitting on.</param> /// <param name="clip">The clip to split.</param> /// <param name="mousePosition">The position of the mouse when the split operation occurred.</param> /// <returns>The new clip.</returns> CutsceneClip SplitClip (CutsceneTrack track, CutsceneClip clip, Vector2 mousePosition) { float splitPoint = mousePosition.x / ed.timelineZoom; return CutsceneTimeline.SplitClipAtTime(splitPoint, track, clip); } /// <summary> /// Draws the in, out, and playhead lines. /// </summary> /// <param name="rect">The timeline's Rect.</param> void DrawLines (Rect rect) { DrawPlayhead(rect); Handles.color = inOutPointColour; DrawInLine(rect); DrawOutLine(rect); } /// <summary> /// Draws the playhead over the timeline. /// </summary> /// <param name="rect">The timeline's Rect.</param> void DrawPlayhead (Rect rect) { Handles.color = Color.black; float pos = ed.scene.playhead * ed.timelineZoom; Vector3 timelineTop = new Vector3(pos, 0); Vector3 timelineBottom = new Vector3(pos, rect.yMax); Handles.DrawLine(timelineTop, timelineBottom); } /// <summary> /// Draws the in point line over the timeline. /// </summary> /// <param name="rect">The timeline's Rect.</param> void DrawInLine (Rect rect) { float pos = ed.scene.inPoint * ed.timelineZoom; Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, rect.yMax); Handles.DrawLine(top, bottom); } /// <summary> /// Draws the out point line over the timeline. /// </summary> /// <param name="rect">The timeline's Rect.</param> void DrawOutLine (Rect rect) { float pos = ed.scene.outPoint * ed.timelineZoom; Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, rect.yMax); Handles.DrawLine(top, bottom); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/ICutsceneGUI.cs b/Cutscene Ed/Editor/ICutsceneGUI.cs index f540290..0c288ca 100755 --- a/Cutscene Ed/Editor/ICutsceneGUI.cs +++ b/Cutscene Ed/Editor/ICutsceneGUI.cs @@ -1,9 +1,31 @@ -using UnityEngine; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEngine; interface ICutsceneGUI { /// <summary> /// Displays the GUI for this element. /// </summary> /// <param name="rect">The bounding box this element is contained in.</param> void OnGUI (Rect rect); } \ No newline at end of file diff --git a/Cutscene Ed/Effects/CutsceneEffect.cs b/Cutscene Ed/Effects/CutsceneEffect.cs index 33383a0..15ff4cf 100755 --- a/Cutscene Ed/Effects/CutsceneEffect.cs +++ b/Cutscene Ed/Effects/CutsceneEffect.cs @@ -1,8 +1,30 @@ -using UnityEngine; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEngine; /// <summary> /// Base class for all cutscene effects. /// </summary> [ExecuteInEditMode] [RequireComponent(typeof(CutsceneShot))] public class CutsceneEffect : MonoBehaviour {} \ No newline at end of file diff --git a/Cutscene Ed/Effects/ImageEffects.cs b/Cutscene Ed/Effects/ImageEffects.cs index e877fa6..21d0237 100644 --- a/Cutscene Ed/Effects/ImageEffects.cs +++ b/Cutscene Ed/Effects/ImageEffects.cs @@ -1,175 +1,175 @@ using UnityEngine; /// Blending modes use by the ImageEffects.Blit functions. public enum BlendMode { Copy, Multiply, MultiplyDouble, Add, AddSmoooth, Blend } /// A Utility class for performing various image based rendering tasks. [AddComponentMenu("")] public class ImageEffects { - static Material[] m_BlitMaterials = {null, null, null, null, null, null}; + static Material[] m_BlitMaterials = new Material[6]; static public Material GetBlitMaterial (BlendMode mode) { int index = (int)mode; if (m_BlitMaterials[index] != null) return m_BlitMaterials[index]; // Blit Copy Material m_BlitMaterials[0] = new Material ( "Shader \"BlitCopy\" {\n" + " SubShader { Pass {\n" + " ZTest Always Cull Off ZWrite Off Fog { Mode Off }\n" + " SetTexture [__RenderTex] { combine texture}" + " }}\n" + "Fallback Off }" ); // Blit Multiply m_BlitMaterials[1] = new Material ( "Shader \"BlitMultiply\" {\n" + " SubShader { Pass {\n" + " Blend DstColor Zero\n" + " ZTest Always Cull Off ZWrite Off Fog { Mode Off }\n" + " SetTexture [__RenderTex] { combine texture }" + " }}\n" + "Fallback Off }" ); // Blit Multiply 2X m_BlitMaterials[2] = new Material ( "Shader \"BlitMultiplyDouble\" {\n" + " SubShader { Pass {\n" + " Blend DstColor SrcColor\n" + " ZTest Always Cull Off ZWrite Off Fog { Mode Off }\n" + " SetTexture [__RenderTex] { combine texture }" + " }}\n" + "Fallback Off }" ); // Blit Add m_BlitMaterials[3] = new Material ( "Shader \"BlitAdd\" {\n" + " SubShader { Pass {\n" + " Blend One One\n" + " ZTest Always Cull Off ZWrite Off Fog { Mode Off }\n" + " SetTexture [__RenderTex] { combine texture }" + " }}\n" + "Fallback Off }" ); // Blit AddSmooth m_BlitMaterials[4] = new Material ( "Shader \"BlitAddSmooth\" {\n" + " SubShader { Pass {\n" + " Blend OneMinusDstColor One\n" + " ZTest Always Cull Off ZWrite Off Fog { Mode Off }\n" + " SetTexture [__RenderTex] { combine texture }" + " }}\n" + "Fallback Off }" ); // Blit Blend m_BlitMaterials[5] = new Material ( "Shader \"BlitBlend\" {\n" + " SubShader { Pass {\n" + " Blend SrcAlpha OneMinusSrcAlpha\n" + " ZTest Always Cull Off ZWrite Off Fog { Mode Off }\n" + " SetTexture [__RenderTex] { combine texture }" + " }}\n" + "Fallback Off }" ); for( int i = 0; i < m_BlitMaterials.Length; ++i ) { m_BlitMaterials[i].hideFlags = HideFlags.HideAndDontSave; m_BlitMaterials[i].shader.hideFlags = HideFlags.HideAndDontSave; } return m_BlitMaterials[index]; } /// Copies one render texture onto another. /// This function copies /source/ onto /dest/, optionally using a custom blend mode. /// If /blendMode/ is left out, the default operation is simply to copy one texture on to another. /// This function will copy the whole source texture on to the whole destination texture. If the sizes differ, /// the image in the source texture will get stretched to fit. /// The source and destination textures cannot be the same. public static void Blit (RenderTexture source, RenderTexture dest, BlendMode blendMode) { Blit (source, new Rect (0,0,1,1), dest, new Rect (0,0,1,1), blendMode); } public static void Blit (RenderTexture source, RenderTexture dest) { Blit (source, dest, BlendMode.Copy); } /// Copies one render texture onto another. public static void Blit (RenderTexture source, Rect sourceRect, RenderTexture dest, Rect destRect, BlendMode blendMode) { // Make the destination texture the target for all rendering RenderTexture.active = dest; // Assign the source texture to a property from a shader source.SetGlobalShaderProperty ("__RenderTex"); // Set up the simple Matrix GL.PushMatrix (); GL.LoadOrtho (); Material blitMaterial = GetBlitMaterial(blendMode); for (int i = 0; i < blitMaterial.passCount; i++) { blitMaterial.SetPass (i); DrawQuad(); } GL.PopMatrix (); } public static void BlitWithMaterial (Material material, RenderTexture source, RenderTexture destination) { RenderTexture.active = destination; material.SetTexture("_MainTex", source); GL.PushMatrix (); GL.LoadOrtho (); for (int i = 0; i < material.passCount; i++) { material.SetPass (i); ImageEffects.DrawQuad(); } GL.PopMatrix (); } public static void RenderDistortion (Material material, RenderTexture source, RenderTexture destination, float angle, Vector2 center, Vector2 radius) { Matrix4x4 rotationMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, angle), Vector3.one); material.SetMatrix("_RotationMatrix", rotationMatrix); material.SetVector("_CenterRadius", new Vector4(center.x,center.y,radius.x,radius.y) ); material.SetFloat("_Angle", angle * Mathf.Deg2Rad); ImageEffects.BlitWithMaterial( material, source, destination ); } public static void DrawQuad() { GL.Begin (GL.QUADS); GL.TexCoord2( 0.0f, 0.0f ); GL.Vertex3( 0.0f, 0.0f, 0.1f ); GL.TexCoord2( 1.0f, 0.0f ); GL.Vertex3( 1.0f, 0.0f, 0.1f ); GL.TexCoord2( 1.0f, 1.0f ); GL.Vertex3( 1.0f, 1.0f, 0.1f ); GL.TexCoord2( 0.0f, 1.0f ); GL.Vertex3( 0.0f, 1.0f, 0.1f ); GL.End(); } public static void DrawGrid (int xSize, int ySize) { GL.Begin (GL.QUADS); float xDelta = 1.0F / xSize; float yDelta = 1.0F / ySize; for (int y=0;y<xSize;y++) { for (int x=0;x<ySize;x++) { GL.TexCoord2 ((x+0) * xDelta, (y+0) * yDelta); GL.Vertex3 ((x+0) * xDelta, (y+0) * yDelta, 0.1f); GL.TexCoord2 ((x+1) * xDelta, (y+0) * yDelta); GL.Vertex3 ((x+1) * xDelta, (y+0) * yDelta, 0.1f); GL.TexCoord2 ((x+1) * xDelta, (y+1) * yDelta); GL.Vertex3 ((x+1) * xDelta, (y+1) * yDelta, 0.1f); GL.TexCoord2 ((x+0) * xDelta, (y+1) * yDelta); GL.Vertex3 ((x+0) * xDelta, (y+1) * yDelta, 0.1f); } } GL.End(); } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/Cutscene.cs b/Cutscene Ed/Scripts/Cutscene.cs index 4cf9133..2bf6c48 100755 --- a/Cutscene Ed/Scripts/Cutscene.cs +++ b/Cutscene Ed/Scripts/Cutscene.cs @@ -1,412 +1,434 @@ +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + using UnityEngine; using System.Collections; using System.Collections.Generic; // Functions to be run when the cutscene starts and finishes public delegate void CutsceneStart(); public delegate void CutscenePause(); public delegate void CutsceneEnd(); [RequireComponent(typeof(Animation))] public class Cutscene : MonoBehaviour { public float duration = 30f; public float inPoint = 0f; public float outPoint = 30f; public bool stopPlayer = true; public GameObject player; public GUIStyle subtitleStyle; public Rect subtitlePosition = new Rect(0, 0, 400, 200); public CutsceneStart startFunction { get; set; } public CutscenePause pauseFunction { get; set; } public CutsceneEnd endFunction { get; set; } public enum MediaType { Shots, Actors, Audio, Subtitles } public enum EffectType { Filters, Transitions } public CutsceneTrack[] tracks { get { return GetComponentsInChildren<CutsceneTrack>(); } } public CutsceneShot[] shots { get { return GetComponentsInChildren<CutsceneShot>(); } } public CutsceneActor[] actors { get { return GetComponentsInChildren<CutsceneActor>(); } } public CutsceneAudio[] audioSources { get { return GetComponentsInChildren<CutsceneAudio>(); } } public CutsceneSubtitle[] subtitles { get { return GetComponentsInChildren<CutsceneSubtitle>(); } } CutsceneSubtitle currentSubtitle; public float playhead { get { return animation["master"].time; } set { animation["master"].time = Mathf.Clamp(value, 0f, duration); } } [HideInInspector] public AnimationClip masterClip; void Start () { SetupMasterAnimationClip(); SetupTrackAnimationClips(); DisableCameras(); DisableAudio(); } void OnGUI () { /// Displays the current subtitle if there is one if (currentSubtitle == null) { return; } GUI.BeginGroup(subtitlePosition, subtitleStyle); GUILayout.Label(currentSubtitle.dialog, subtitleStyle); GUI.EndGroup(); } /// <summary> /// Visually shows the cutscene in the scene view. /// </summary> void OnDrawGizmos () { Gizmos.DrawIcon(transform.position, "Cutscene.png"); } /// <summary> /// Sets the in and out points of the master animation clip. /// </summary> void SetupMasterAnimationClip () { animation.RemoveClip("master"); // Create a new event for when the scene starts AnimationEvent start = new AnimationEvent(); start.time = inPoint; start.functionName = "SceneStart"; masterClip.AddEvent(start); // Create a new event for when the scene finishes AnimationEvent finish = new AnimationEvent(); finish.time = outPoint; finish.functionName = "SceneFinish"; masterClip.AddEvent(finish); animation.AddClip(masterClip, "master"); animation["master"].time = inPoint; } /// <summary> /// Adds each track's animation clip to the main animation. /// </summary> void SetupTrackAnimationClips () { foreach (CutsceneTrack t in tracks) { if (t.enabled) { AnimationClip trackAnimationClip = t.track; string clipName = "track" + t.id; animation.AddClip(trackAnimationClip, clipName); animation[clipName].time = inPoint; } } } /// <summary> /// Turns off all child cameras so that they don't display before the cutscene starts. /// </summary> void DisableCameras () { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { cam.enabled = false; } } /// <summary> /// Turns off all child cameras except for the one specified. /// </summary> /// <param name="exemptCam">The camera to stay enabled.</param> void DisableOtherCameras (Camera exemptCam) { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { if (cam != exemptCam) { cam.enabled = false; } } } /// <summary> /// Keeps all child audio sources from playing once the game starts. /// </summary> void DisableAudio () { AudioSource[] childAudio = GetComponentsInChildren<AudioSource>(); foreach (AudioSource audio in childAudio) { audio.playOnAwake = false; } } /// <summary> /// Starts playing the cutscene. /// </summary> public void PlayCutscene () { // Set up and play the master animation animation["master"].layer = 0; animation.Play("master"); // Set up and play each individual track for (int i = 0; i < tracks.Length; i++) { if (tracks[i].enabled) { animation["track" + tracks[i].id].layer = i + 1; animation.Play("track" + tracks[i].id); } } } /// <summary> /// Pauses the cutscene. /// </summary> public void PauseCutscene () { pauseFunction(); // TODO actually pause the cutscene } /// <summary> /// Called when the scene starts. /// </summary> void SceneStart () { if (startFunction != null) { startFunction(); } // Stop the player from being able to move if (player != null && stopPlayer) { EDebug.Log("Cutscene: deactivating player"); player.active = false; } DisableCameras(); currentSubtitle = null; EDebug.Log("Cutscene: scene started at " + animation["master"].time); } /// <summary> /// Called when the scene ends. /// </summary> void SceneFinish () { if (endFunction != null) { endFunction(); } // Allow the player to move again if (player != null) { EDebug.Log("Cutscene: activating player"); player.active = true; } EDebug.Log("Cutscene: scene finished at " + animation["master"].time); } /// <summary> /// Shows the specified shot. /// </summary> /// <param name="clip">The shot to show.</summary> void PlayShot (CutsceneClip clip) { Camera cam = ((CutsceneShot)clip.master).camera; cam.enabled = true; StartCoroutine(StopShot(cam, clip.duration)); EDebug.Log("Cutscene: showing camera " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the shot from playing at its out point. /// </summary> /// <param name="shot">The shot to stop.</param> /// <param name="duration">The time at which to stop the shot.</param> IEnumerator StopShot (Camera cam, float duration) { yield return new WaitForSeconds(duration); cam.enabled = false; EDebug.Log("Cutscene: stopping shot at " + animation["master"].time); } /// <summary> /// Plays the specified actor. /// </summary> /// <param name="clip">The actor to play.</summary> void PlayActor (CutsceneClip clip) { CutsceneActor actor = ((CutsceneActor)clip.master); AnimationClip anim = actor.anim; GameObject go = ((CutsceneActor)clip.master).go; go.animation[anim.name].time = clip.inPoint; go.animation.Play(anim.name); StartCoroutine(StopActor(actor, clip.duration)); EDebug.Log("Cutscene: showing actor " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the actor from playing at its out point. /// </summary> /// <param name="actor">The actor to stop.</param> /// <param name="duration">The time at which to stop the actor.</param> IEnumerator StopActor (CutsceneActor actor, float duration) { yield return new WaitForSeconds(duration); actor.go.animation.Stop(actor.anim.name); EDebug.Log("Cutscene: stopping actor at " + animation["master"].time); } /// <summary> /// Plays the specified audio. /// </summary> /// <param name="clip">The audio to play.</summary> void PlayAudio (CutsceneClip clip) { AudioSource aud = ((CutsceneAudio)clip.master).audio; aud.Play(); aud.time = clip.inPoint; // Set the point at which the clip plays StartCoroutine(StopAudio(aud, clip.duration)); // Set the point at which the clip stops EDebug.Log("Playing audio " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the audio from playing at its out point. /// </summary> /// <param name="aud">The audio source to stop.</param> /// <param name="duration">The time at which to stop the audio.</param> IEnumerator StopAudio (AudioSource aud, float duration) { yield return new WaitForSeconds(duration); aud.Stop(); } /// <summary> /// Displays the specified subtitle. /// </summary> /// <param name="clip">The subtitle to display.</summary> void PlaySubtitle (CutsceneClip clip) { currentSubtitle = (CutsceneSubtitle)clip.master; EDebug.Log("Displaying subtitle " + clip.name + " at " + animation["master"].time); StartCoroutine(StopSubtitle(clip.duration)); } /// <summary> /// Stops the subtitle from displaying at its out point. /// </summary> /// <param name="duration">The time at which to stop the audio.</param> IEnumerator StopSubtitle (float duration) { yield return new WaitForSeconds(duration); currentSubtitle = null; } /// <summary> /// Stops all subtitles from displaying by setting the current subtitle to null. /// </summary> void StopSubtitle () { currentSubtitle = null; } /// <summary> /// Called when the clip type is unknown. /// </summary> /// <remarks>For debugging only; ideally this will never be called.</remarks> void UnknownFunction (CutsceneClip clip) { EDebug.Log("Cutscene: unknown function call from clip " + clip.name); } /// <summary> /// Creates a new CutsceneShot object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneShot object.</returns> public CutsceneShot NewShot () { GameObject shot = new GameObject("Camera", typeof(Camera), typeof(CutsceneShot)); // Keep the camera from displaying before it's placed on the timeline shot.camera.enabled = false; // Set the parent of the new shot to the Shots object shot.transform.parent = transform.Find("Shots"); EDebug.Log("Cutscene Editor: added new shot"); return shot.GetComponent<CutsceneShot>(); } /// <summary> /// Creates a new CutsceneActor object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneActor object.</returns> public CutsceneActor NewActor (AnimationClip anim, GameObject go) { CutsceneActor actor = GameObject.Find("Actors").AddComponent<CutsceneActor>(); actor.name = anim.name; actor.anim = anim; actor.go = go; EDebug.Log("Cutscene Editor: adding new actor"); return actor; } /// <summary> /// Creates a new CutsceneAudio object and attaches it to a new game object as a child of the Audio game object. /// </summary> /// <param name="clip">The audio clip to be attached the CutsceneAudio object.</param> /// <returns>The new CutsceneAudio object.</returns> public CutsceneAudio NewAudio (AudioClip clip) { GameObject aud = new GameObject(clip.name, typeof(AudioSource), typeof(CutsceneAudio)); aud.audio.clip = clip; // Keep the audio from playing when the game starts aud.audio.playOnAwake = false; // Set the parent of the new audio to the "Audio" object aud.transform.parent = transform.Find("Audio"); EDebug.Log("Cutscene Editor: added new audio"); return aud.GetComponent<CutsceneAudio>(); } /// <summary> /// Creates a new CutsceneSubtitle object and attaches it to the Subtitles game object. /// </summary> /// <param name="dialog">The dialog to be displayed.</param> /// <returns>The new CutsceneSubtitle object.</returns> public CutsceneSubtitle NewSubtitle (string dialog) { CutsceneSubtitle subtitle = GameObject.Find("Subtitles").AddComponent<CutsceneSubtitle>(); subtitle.dialog = dialog; EDebug.Log("Cutscene Editor: added new subtitle"); return subtitle; } /// <summary> /// Attaches a new track component to the cutscene. /// </summary> /// <returns>The new cutscene track.</returns> public CutsceneTrack AddTrack (Cutscene.MediaType type) { int id = 0; // Ensure the new track has a unique ID foreach (CutsceneTrack t in tracks) { if (id == t.id) { id++; } else { break; } } CutsceneTrack track = gameObject.AddComponent<CutsceneTrack>(); track.id = id; track.type = type; track.name = CutsceneTrack.DefaultName(type); EDebug.Log("Cutscene Editor: added new track of type " + type); return track; } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneActor.cs b/Cutscene Ed/Scripts/CutsceneActor.cs index cf0362c..ce23924 100644 --- a/Cutscene Ed/Scripts/CutsceneActor.cs +++ b/Cutscene Ed/Scripts/CutsceneActor.cs @@ -1,6 +1,28 @@ +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + using UnityEngine; public class CutsceneActor : CutsceneMedia { public AnimationClip anim; public GameObject go; } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneAudio.cs b/Cutscene Ed/Scripts/CutsceneAudio.cs index 5a5553d..03d0617 100644 --- a/Cutscene Ed/Scripts/CutsceneAudio.cs +++ b/Cutscene Ed/Scripts/CutsceneAudio.cs @@ -1,4 +1,26 @@ +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + using UnityEngine; [RequireComponent(typeof(AudioSource))] public class CutsceneAudio : CutsceneMedia {} \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneClip.cs b/Cutscene Ed/Scripts/CutsceneClip.cs index 8d3959c..bbcbfee 100644 --- a/Cutscene Ed/Scripts/CutsceneClip.cs +++ b/Cutscene Ed/Scripts/CutsceneClip.cs @@ -1,114 +1,136 @@ +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + using UnityEngine; using System; public class CutsceneClip : ScriptableObject { public CutsceneMedia master; public float timelineStart = 0f; public float inPoint = 0f; public float outPoint = 5f; // Default 5 seconds public float timelineEnd { get { return timelineStart + duration; } } float maxOutPoint { get { float max = Mathf.Infinity; if (master is CutsceneActor) { max = ((CutsceneActor)master).anim.length; } else if (master is CutsceneAudio) { max = ((CutsceneAudio)master).gameObject.audio.clip.length; } return max; } } public void SetTimelineStart (float value) { timelineStart = Mathf.Clamp(value, 0f, Mathf.Infinity); } public void SetInPoint (float value) { inPoint = Mathf.Clamp(value, 0f, outPoint); } public void SetOutPoint (float value) { outPoint = Mathf.Clamp(value, inPoint, maxOutPoint); } [HideInInspector] public bool setToDelete = false; // An ugly workaround used for deleting clips // Read only public float duration { get { return outPoint - inPoint; } } public string startFunction { get { // Determine which function to call based on the master object type if (master is CutsceneShot) { return "PlayShot"; } else if (master is CutsceneActor) { return "PlayActor"; } else if (master is CutsceneAudio) { return "PlayAudio"; } else if (master is CutsceneSubtitle) { return "PlaySubtitle"; } else { return "UnknownFunction"; } } } public Cutscene.MediaType type { get { if (master is CutsceneShot) { return Cutscene.MediaType.Shots; } else if (master is CutsceneActor) { return Cutscene.MediaType.Actors; } else if (master is CutsceneAudio) { return Cutscene.MediaType.Audio; } else { // master is CutsceneSubtitles return Cutscene.MediaType.Subtitles; } } } public CutsceneClip (CutsceneMedia master) { this.master = master; if (master is CutsceneSubtitle) { name = ((CutsceneSubtitle)master).dialog; } else { name = master.name; } if (maxOutPoint != Mathf.Infinity) { outPoint = maxOutPoint; } } /// <summary> /// Gets a clone of the current clip. /// </summary> /// <returns>The clip copy.</returns> public CutsceneClip GetCopy () { CutsceneClip copy = new CutsceneClip(master); copy.timelineStart = timelineStart; copy.SetInPoint(inPoint); copy.outPoint = outPoint; return copy; } /// <summary> /// Adds an effect to the clip. /// </summary> /// <param name="effect">The transitions or filter.</param> public void ApplyEffect (Type effect) { // Only add the effect if the master object is a camera shot if (master is CutsceneShot) { master.gameObject.AddComponent(effect); } } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneMedia.cs b/Cutscene Ed/Scripts/CutsceneMedia.cs index c64ca7e..a182b52 100644 --- a/Cutscene Ed/Scripts/CutsceneMedia.cs +++ b/Cutscene Ed/Scripts/CutsceneMedia.cs @@ -1,17 +1,39 @@ +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + using UnityEngine; public abstract class CutsceneMedia : MonoBehaviour { public Cutscene.MediaType type { get { if (this.GetType() == typeof(CutsceneShot)) { return Cutscene.MediaType.Shots; } else if (this.GetType() == typeof(CutsceneActor)) { return Cutscene.MediaType.Actors; } else if (this.GetType() == typeof(CutsceneAudio)) { return Cutscene.MediaType.Audio; } else { // obj.GetType() == typeof(CutsceneSubtitle) return Cutscene.MediaType.Subtitles; } } } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneShot.cs b/Cutscene Ed/Scripts/CutsceneShot.cs index 1490ccd..0af06ec 100644 --- a/Cutscene Ed/Scripts/CutsceneShot.cs +++ b/Cutscene Ed/Scripts/CutsceneShot.cs @@ -1,4 +1,26 @@ +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + using UnityEngine; [RequireComponent(typeof(Camera))] public class CutsceneShot : CutsceneMedia {} \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneSubtitle.cs b/Cutscene Ed/Scripts/CutsceneSubtitle.cs index 108c04b..d5e80d4 100644 --- a/Cutscene Ed/Scripts/CutsceneSubtitle.cs +++ b/Cutscene Ed/Scripts/CutsceneSubtitle.cs @@ -1,16 +1,38 @@ +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + using UnityEngine; public class CutsceneSubtitle : CutsceneMedia { public string dialog; public new string name { get { int maxTitleLength = 25; string _name = dialog; if (_name.Length > maxTitleLength) { _name = _name.Substring(0, maxTitleLength) + " ..."; } return _name; } } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneTrack.cs b/Cutscene Ed/Scripts/CutsceneTrack.cs index 54c70da..b49ae1c 100644 --- a/Cutscene Ed/Scripts/CutsceneTrack.cs +++ b/Cutscene Ed/Scripts/CutsceneTrack.cs @@ -1,103 +1,125 @@ +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + using UnityEngine; using System.Collections.Generic; using System; public class CutsceneTrack : MonoBehaviour { public bool locked; [HideInInspector] public Cutscene.MediaType type = Cutscene.MediaType.Shots; public new string name = DefaultName(Cutscene.MediaType.Shots); public List<CutsceneClip> clips = new List<CutsceneClip>(); [HideInInspector] public int id = 0; public AnimationClip track { get { AnimationClip _track = new AnimationClip(); foreach (CutsceneClip clip in clips) { AnimationEvent start = new AnimationEvent(); start.time = clip.timelineStart; start.functionName = clip.startFunction; start.objectReferenceParameter = clip; _track.AddEvent(start); } return _track; } } public static string DefaultName (Cutscene.MediaType type) { switch (type) { case Cutscene.MediaType.Shots: return "Shots"; case Cutscene.MediaType.Actors: return "Actors"; case Cutscene.MediaType.Audio: return "Audio"; default: // Cutscene.MediaType.Subtitles return "Subtitles"; } } /// <summary> /// Checks to see if there's a clip at the given time, ignoring the given clip. /// </summary> /// <param name="time">The time to check for.</param> /// <returns>The CutsceneClip that is at the given time.</returns> public CutsceneClip ContainsClipAtTime (float time, CutsceneClip ignoreClip) { CutsceneClip contains = ContainsClipAtTime(time); if (contains != null && contains != ignoreClip) { return contains; } else { return null; } } /// <summary> /// Checks to see if there's a clip at the given time. /// </summary> /// <param name="time">The time to check for.</param> /// <returns>The CutsceneClip that is at the given time.</returns> public CutsceneClip ContainsClipAtTime (float time) { foreach (CutsceneClip clip in clips) { if (time >= clip.timelineStart && time <= clip.timelineStart + clip.duration) { return clip; } } // The timeline doesn't contain a clip at the specified time return null; } public float GetTimeOfPreviousSplit (float time) { float splitTime = -1f; foreach (CutsceneClip clip in clips) { if (clip.timelineEnd < time && clip.timelineEnd > splitTime) { splitTime = clip.timelineEnd; } else if (clip.timelineStart < time && clip.timelineStart > splitTime) { splitTime = clip.timelineStart; } } // If splitTime is still -1, just return the original time return splitTime == -1f ? time : splitTime; } public float GetTimeOfNextSplit (float time) { float splitTime = Mathf.Infinity; foreach (CutsceneClip clip in clips) { if (clip.timelineStart > time && clip.timelineStart < splitTime) { splitTime = clip.timelineStart; } else if (clip.timelineEnd > time && clip.timelineEnd < splitTime) { splitTime = clip.timelineEnd; } } // If splitTime is still infinity, just return the original time return splitTime == Mathf.Infinity ? time : splitTime; } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneTrigger.cs b/Cutscene Ed/Scripts/CutsceneTrigger.cs index a9c42d1..10b9aef 100644 --- a/Cutscene Ed/Scripts/CutsceneTrigger.cs +++ b/Cutscene Ed/Scripts/CutsceneTrigger.cs @@ -1,17 +1,39 @@ +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + using UnityEngine; using System.Collections; public class CutsceneTrigger : MonoBehaviour { public Cutscene scene; void Update () { //TEMP if (Input.GetKey("p")) { scene.PlayCutscene(); } } void OnTriggerEnter (Collider collider) { scene.PlayCutscene(); } } diff --git a/Cutscene Ed/Scripts/EDebug.cs b/Cutscene Ed/Scripts/EDebug.cs index d59e61e..ef2489b 100755 --- a/Cutscene Ed/Scripts/EDebug.cs +++ b/Cutscene Ed/Scripts/EDebug.cs @@ -1,36 +1,58 @@ -using UnityEngine; +/** + * Copyright (c) 2010 Matthew Miner + * + * 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. + */ + +using UnityEngine; /// <summary> /// A simple class for toggle-able debug messages. Debug messages for editor tools are useful when developing the tool itself, but annoying for end users. /// </summary> public class EDebug { static bool debug = false; public static void Break () { if (debug) Debug.Break(); } public static void Log (object message) { if (debug) Debug.Log(message); } public static void Log (object message, UnityEngine.Object context) { if (debug) Debug.Log(message, context); } public static void LogError (object message) { if (debug) Debug.LogError(message); } public static void LogError (object message, UnityEngine.Object context) { if (debug) Debug.LogError(message, context); } public static void LogWarning (object message) { if (debug) Debug.LogWarning(message); } public static void LogWarning (object message, UnityEngine.Object context) { if (debug) Debug.LogWarning(message, context); } } \ No newline at end of file
mminer/silverscreen
05a93ea3f9c3b8bdb5430c299498d2841cbabaf1
Tweaked readme for better readability.
diff --git a/README.markdown b/README.markdown index acb5def..ca9915c 100644 --- a/README.markdown +++ b/README.markdown @@ -1,31 +1,39 @@ -## Release History +Silver Screen +============= -### 0.1 +A suite of editor tools for the creation of cinematics using the Unity game +engine. -* Initial release -* Compatible with Unity 2.6 +Release History +--------------- -## License +- 0.1 + - Initial release + - Compatible with Unity 2.6 + + +License +------- All code is released under the MIT license. > Copyright (c) 2010 Matthew Miner > > 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
mminer/silverscreen
ea6b3390b6a6a1fb6e67a2200d5a477a45561459
Added release history and license info to readme.
diff --git a/README.markdown b/README.markdown index 50816a5..acb5def 100644 --- a/README.markdown +++ b/README.markdown @@ -1 +1,31 @@ -Silver Screen has been tested to work in Unity 2.6. \ No newline at end of file +## Release History + +### 0.1 + +* Initial release +* Compatible with Unity 2.6 + + +## License + +All code is released under the MIT license. + +> Copyright (c) 2010 Matthew Miner +> +> 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
mminer/silverscreen
de5d7bf61aead7fb73fdd67c4b6ff4ec2d8fdfd9
Commented out line that was erronously uncommented last commit.
diff --git a/Cutscene Ed/Editor/CutsceneEditor.cs b/Cutscene Ed/Editor/CutsceneEditor.cs index bb80853..6990fd8 100755 --- a/Cutscene Ed/Editor/CutsceneEditor.cs +++ b/Cutscene Ed/Editor/CutsceneEditor.cs @@ -1,491 +1,491 @@ using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// The Cutscene Editor, where tracks and clips can be managed in a fashion similar to non-linear video editors. /// </summary> public class CutsceneEditor : EditorWindow { public static readonly System.Version version = new System.Version(0, 2); public Cutscene scene { get { Object[] scenes = Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel); if (scenes.Length == 0) { return null; } return scenes[0] as Cutscene; } } public GUISkin style { get; private set; } //ICutsceneGUI options; ICutsceneGUI media; ICutsceneGUI effects; ICutsceneGUI tools; ICutsceneGUI timeline; public static bool CutsceneSelected { get { return Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel).Length > 0; } } public static bool HasPro = SystemInfo.supportsImageEffects; // Icons: public readonly Texture[] mediaIcons = { EditorGUIUtility.LoadRequired("Cutscene Ed/media_shot.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_actor.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_audio.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_subtitle.png") as Texture }; // Timeline: public Tool currentTool = Tool.MoveResize; public Vector2 timelineScrollPos; public float timelineMin { get; set; } float _timelineZoom = CutsceneTimeline.timelineZoomMin; public float timelineZoom { get { return _timelineZoom; } set { _timelineZoom = Mathf.Clamp(value, CutsceneTimeline.timelineZoomMin, CutsceneTimeline.timelineZoomMax); } } CutsceneTrack _selectedTrack; public CutsceneTrack selectedTrack { get { if (_selectedTrack == null) { // If there are no tracks, add a new one if (scene.tracks.Length == 0) { scene.AddTrack(Cutscene.MediaType.Shots); } _selectedTrack = scene.tracks[0]; } return _selectedTrack; } set { _selectedTrack = value; } } public CutsceneClip selectedClip; public DragEvent dragEvent = DragEvent.Move; public CutsceneClip dragClip; // Menu items: /// <summary> /// Adds "Cutscene Editor" to the Window menu. /// </summary> [MenuItem("Window/Cutscene Editor %9")] public static void OpenEditor () { // Get existing open window or if none, make a new one GetWindow<CutsceneEditor>(false, "Cutscene Editor").Show(); } /// <summary> /// Validates the Cutscene Editor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Window/Cutscene Editor %9", true)] static bool ValidateOpenEditor () { return CutsceneSelected; } /// <summary> /// Adds the option to create a cutscene from the GameObject > Create Other menu. /// </summary> /// <returns>The new cutscene.</returns> [MenuItem("GameObject/Create Other/Cutscene")] static void CreateCutscene () { // Create the new cutscene game object GameObject newSceneGO = new GameObject("Cutscene", typeof(Cutscene)); Cutscene newScene = newSceneGO.GetComponent<Cutscene>(); // Add some tracks to get the user started newScene.AddTrack(Cutscene.MediaType.Shots); newScene.AddTrack(Cutscene.MediaType.Actors); newScene.AddTrack(Cutscene.MediaType.Audio); newScene.AddTrack(Cutscene.MediaType.Subtitles); // Create the cutscene's media game objects GameObject shots = new GameObject("Shots"); GameObject actors = new GameObject("Actors"); GameObject audio = new GameObject("Audio"); GameObject subtitles = new GameObject("Subtitles"); // Make the media game objects a child of the cutscene shots.transform.parent = newScene.transform; actors.transform.parent = newScene.transform; audio.transform.parent = newScene.transform; subtitles.transform.parent = newScene.transform; // Create the master animation clip AnimationClip masterClip = new AnimationClip(); newScene.masterClip = masterClip; newScene.animation.AddClip(masterClip, "master"); newScene.animation.playAutomatically = false; newScene.animation.wrapMode = WrapMode.Once; EDebug.Log("Cutscene Editor: created a new cutscene"); } /// <summary> /// Adds the option to create a cutscene trigger to the GameObject > Create Other menu. /// </summary> /// <returns>The trigger's collider.</returns> [MenuItem("GameObject/Create Other/Cutscene Trigger")] static Collider CreateCutsceneTrigger () { // Create the new cutscene trigger game object GameObject triggerGO = new GameObject("Cutscene Trigger", typeof(BoxCollider), typeof(CutsceneTrigger)); triggerGO.collider.isTrigger = true; return triggerGO.collider; } /// <summary> /// Adds the option to create a new shot track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Shot")] static void CreateShotTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Shots); } /// <summary> /// Validates the Shot menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Shot", true)] static bool ValidateCreateShotTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new actor track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Actor")] static void CreateActorTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Actors); } /// <summary> /// Validates the Actor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Actor", true)] static bool ValidateCreateActorTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new audio track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Audio")] static void CreateAudioTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Audio); } /// <summary> /// Validates the Audio menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Audio", true)] static bool ValidateCreateAudioTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new subtitle track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Subtitle")] static void CreateSubtitleTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Subtitles); } /// <summary> /// Validates the Subtitle menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Subtitle", true)] static bool ValidateCreateSubtitleTrack () { return CutsceneSelected; } void OnEnable () { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; if (style == null) { Debug.LogError("GUISkin for Cutscene Editor missing"); return; } - options = new CutsceneOptions(this); + //options = new CutsceneOptions(this); media = new CutsceneMediaWindow(this); effects = new CutsceneEffectsWindow(this); tools = new CutsceneTools(this); timeline = new CutsceneTimeline(this); } /// <summary> /// Displays the editor GUI. /// </summary> void OnGUI () { if (style == null) { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; } // If no cutscene is selected, present the user with the option to create one if (scene == null) { if (GUILayout.Button("Create New Cutscene", GUILayout.ExpandWidth(false))) { CreateCutscene(); } } else { // Otherwise present the cutscene editor float windowHeight = style.GetStyle("Pane").fixedHeight; // Options window //Rect optionsRect = new Rect(0, 0, position.width / 3, windowHeight); //options.OnGUI(optionsRect); // Media window Rect mediaRect = new Rect(2, 2, position.width / 2, windowHeight); media.OnGUI(mediaRect); // Effects window Rect effectsRect = new Rect(mediaRect.xMax + 2, 2, position.width - mediaRect.xMax - 4, windowHeight); effects.OnGUI(effectsRect); // Cutting tools Rect toolsRect = new Rect(0, mediaRect.yMax, position.width, 25); tools.OnGUI(toolsRect); // Timeline Rect timelineRect = new Rect(0, toolsRect.yMax, position.width, position.height - toolsRect.yMax); timeline.OnGUI(timelineRect); } } // Context menus: /// <summary> /// Deletes a piece of media by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> [MenuItem("CONTEXT/CutsceneObject/Delete")] static void DeleteCutsceneMedia (MenuCommand command) { DeleteCutsceneMedia(command.context as CutsceneMedia); } /// <summary> /// Deletes a piece of media. /// </summary> /// <param name="obj">The media to delete.</param> /// <remarks>This has to be in CutsceneEditor rather than CutsceneTimeline because it uses the DestroyImmediate function, which is only available to classes which inherit from UnityEngine.Object.</remarks> static void DeleteCutsceneMedia (CutsceneMedia obj) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Object", "Are you sure you wish to delete this object? Changes cannot be undone.", "Delete", "Cancel"); } // Only delete the cutscene object if the user chose to if (delete) { Debug.Log("Cutscene Editor: deleting media " + obj.name); if (obj.type == Cutscene.MediaType.Actors || obj.type == Cutscene.MediaType.Subtitles) { // Delete the CutsceneObject component DestroyImmediate(obj); } else { // Delete the actual game object DestroyImmediate(obj.gameObject); } } } /// <summary> /// Deletes a track by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneTrack/Delete Track")] static bool DeleteTrack (MenuCommand command) { return DeleteTrack(command.context as CutsceneTrack); } /// <summary> /// Deletes a track. /// </summary> /// <param name="track">The track to delete.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> static bool DeleteTrack (CutsceneTrack track) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Track", "Are you sure you wish to delete this track? Changes cannot be undone.", "Delete", "Cancel"); } if (delete) { DestroyImmediate(track); } return delete; } /// <summary> /// Deletes a clip by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneClip/Delete Clip")] static bool DeleteClip (MenuCommand command) { return DeleteClip(command.context as CutsceneClip); } /// <summary> /// Deletes a clip. /// </summary> /// <param name="clip">The clip to delete.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> static bool DeleteClip (CutsceneClip clip) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Clip", "Are you sure you wish to delete this clip? Changes cannot be undone.", "Delete", "Cancel"); } clip.setToDelete = delete; return delete; } /// <summary> /// Selects the track at the specified index. /// </summary> /// <param name="index">The track to select.</param> void SelectTrackAtIndex (int index) { if (scene.tracks.Length > 0 && index > 0 && index <= scene.tracks.Length) { selectedTrack = scene.tracks[index - 1]; EDebug.Log("Cutscene Editor: track " + index + " is selected"); } } /// <summary> /// Determines which key command is pressed and responds accordingly. /// </summary> /// <param name="keyDownEvent">The keyboard event.</param> /// <returns>True if the keyboard shortcut exists, false otherwise.</returns> public void HandleKeyboardShortcuts (Event keyDownEvent) { KeyCode key = keyDownEvent.keyCode; // Tools: // Move/resize if (key == CutsceneHotkeys.MoveResizeTool.key) { currentTool = Tool.MoveResize; EDebug.Log("Cutscene Editor: switching to Move/Resize tool"); // Scissors } else if (key == CutsceneHotkeys.ScissorsTool.key) { currentTool = Tool.Scissors; EDebug.Log("Cutscene Editor: switching to Scissors tool"); // Zoom } else if (key == CutsceneHotkeys.ZoomTool.key) { currentTool = Tool.Zoom; EDebug.Log("Cutscene Editor: switching to Zoom tool"); } // Timeline navigation: // Set in point else if (key == CutsceneHotkeys.SetInPont.key) { scene.inPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting in point"); // Set out point } else if (key == CutsceneHotkeys.SetOutPoint.key) { scene.outPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting out point"); // Scrub left } else if (keyDownEvent.Equals(Event.KeyboardEvent("left"))) { scene.playhead -= CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead left"); // Scrub left large } else if (keyDownEvent.Equals(Event.KeyboardEvent("#left"))) { scene.playhead -= CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead left"); // Scrub right } else if (keyDownEvent.Equals(Event.KeyboardEvent("right"))) { scene.playhead += CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead right"); // Scrub right large } else if (keyDownEvent.Equals(Event.KeyboardEvent("#right"))) { scene.playhead += CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead right"); // Go to previous split point } else if (keyDownEvent.Equals(Event.KeyboardEvent("up"))) { scene.playhead = selectedTrack.GetTimeOfNextSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to previous split point"); // Go to next split point } else if (keyDownEvent.Equals(Event.KeyboardEvent("down"))) { scene.playhead = selectedTrack.GetTimeOfPreviousSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to next split point"); // Go to in point } else if (keyDownEvent.Equals(Event.KeyboardEvent("#up"))) { scene.playhead = scene.inPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); // Go to out point } else if (keyDownEvent.Equals(Event.KeyboardEvent("#down"))) { scene.playhead = scene.outPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); } // Track selection: // Select track 1 else if (key == CutsceneHotkeys.SelectTrack1.key) { SelectTrackAtIndex(1); // Select track 2 } else if (key == CutsceneHotkeys.SelectTrack2.key) { SelectTrackAtIndex(2); // Select track 3 } else if (key == CutsceneHotkeys.SelectTrack3.key) { SelectTrackAtIndex(3); // Select track 4 } else if (key == CutsceneHotkeys.SelectTrack4.key) { SelectTrackAtIndex(4); // Select track 5 } else if (key == CutsceneHotkeys.SelectTrack5.key) { SelectTrackAtIndex(5); // Select track 6 } else if (key == CutsceneHotkeys.SelectTrack6.key) { SelectTrackAtIndex(6); // Select track 7 } else if (key == CutsceneHotkeys.SelectTrack7.key) { SelectTrackAtIndex(7); // Select track 8 } else if (key == CutsceneHotkeys.SelectTrack8.key) { SelectTrackAtIndex(8); // Select track 9 } else if (key == CutsceneHotkeys.SelectTrack9.key) { SelectTrackAtIndex(9); } // Other: else { EDebug.Log("Cutscene Editor: unknown keyboard shortcut " + keyDownEvent); return; } // If we get to this point, a shortcut matching the user's keystroke has been found Event.current.Use(); } public static float PaneTabsWidth (int count) { return count * 80f; } } \ No newline at end of file
mminer/silverscreen
4c08d1083d8341c4caa6653fbeb9f8667a40e658
Minor whitespace alignment changes in code.
diff --git a/Cutscene Ed/Editor/BugReporter.cs b/Cutscene Ed/Editor/BugReporter.cs index 77c9cde..8a04202 100755 --- a/Cutscene Ed/Editor/BugReporter.cs +++ b/Cutscene Ed/Editor/BugReporter.cs @@ -1,42 +1,42 @@ using UnityEditor; using UnityEngine; public class BugReporter : EditorWindow { - string email = ""; - string details = ""; + string email = ""; + string details = ""; - readonly GUIContent emailLabel = new GUIContent("Your Email", "If we require additional information, we'll contact you at the supplied address (optional)."); - readonly GUIContent submitLabel = new GUIContent("Submit", "Send this bug report."); + readonly GUIContent emailLabel = new GUIContent("Your Email", "If we require additional information, we'll contact you at the supplied address (optional)."); + readonly GUIContent submitLabel = new GUIContent("Submit", "Send this bug report."); /// <summary> /// Adds "Bug Reporter" to the Window menu. /// </summary> [MenuItem("Window/Bug Reporter")] public static void OpenEditor () { // Get existing open window or if none, make a new one GetWindow<BugReporter>(true, "Bug Reporter").Show(); } void OnGUI () { GUILayout.Label("Please take a minute to tell us what happened in as much detail as possible. This makes it possible for us to fix the problem."); EditorGUILayout.Separator(); email = EditorGUILayout.TextField(emailLabel, email); EditorGUILayout.Separator(); GUILayout.Label("Problem Details:"); details = EditorGUILayout.TextArea(details); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(submitLabel, GUILayout.ExpandWidth(false))) { // TODO Send bug report Debug.Log("Bug report sent."); } EditorGUILayout.EndHorizontal(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneAddActor.cs b/Cutscene Ed/Editor/CutsceneAddActor.cs index 67263ed..70f46d8 100755 --- a/Cutscene Ed/Editor/CutsceneAddActor.cs +++ b/Cutscene Ed/Editor/CutsceneAddActor.cs @@ -1,90 +1,90 @@ using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; class CutsceneAddActor : ScriptableWizard { - GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; - AnimationClip selected; - GameObject selectedGO; + GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; + AnimationClip selected; + GameObject selectedGO; /// <summary> /// Creates a wizard for adding a new actor. /// </summary> [MenuItem("Component/Cutscene/Add Media/Actor")] public static void CreateWizard () { DisplayWizard<CutsceneAddActor>("Add Actor", "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Actor", true)] static bool ValidateCreateWizard () { return CutsceneEditor.CutsceneSelected; } void OnGUI () { OnWizardUpdate(); Animation[] animations = (Animation[])FindObjectsOfType(typeof(Animation)); EditorGUILayout.BeginVertical(style.GetStyle("List Container")); foreach (Animation anim in animations) { GUILayout.Label(anim.gameObject.name, EditorStyles.largeLabel); foreach (AnimationClip clip in AnimationUtility.GetAnimationClips(anim)) { GUIStyle itemStyle = GUIStyle.none; if (clip == selected) { itemStyle = style.GetStyle("Selected List Item"); } Rect rect = EditorGUILayout.BeginHorizontal(itemStyle); GUIContent itemLabel = new GUIContent(clip.name, EditorGUIUtility.ObjectContent(null, typeof(Animation)).image); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); // Select when clicked if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { selected = clip; selectedGO = anim.gameObject; EditorGUIUtility.PingObject(anim); Event.current.Use(); Repaint(); } } } EditorGUILayout.EndVertical(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true; } void OnWizardUpdate () { helpString = "Choose an animation to add."; // Only valid if an animation has been selected isValid = selected != null; } /// <summary> /// Adds the new actor to the cutscene. /// </summary> void OnWizardCreate () { Selection.activeGameObject.GetComponent<Cutscene>().NewActor(selected, selectedGO); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneAddAudio.cs b/Cutscene Ed/Editor/CutsceneAddAudio.cs index 9af804a..ba7ffa9 100755 --- a/Cutscene Ed/Editor/CutsceneAddAudio.cs +++ b/Cutscene Ed/Editor/CutsceneAddAudio.cs @@ -1,87 +1,87 @@ using UnityEngine; using UnityEditor; class CutsceneAddAudio : ScriptableWizard { - //GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; + //GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; - AudioClip[] audioClips; - AudioClip selected; + AudioClip[] audioClips; + AudioClip selected; /// <summary> /// Creates a wizard for adding a new audio clip. /// </summary> [MenuItem("Component/Cutscene/Add Media/Audio")] public static void CreateWizard () { DisplayWizard<CutsceneAddAudio>("Add Audio", "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Audio", true)] static bool ValidateCreateWizard () { return CutsceneEditor.CutsceneSelected; } void OnGUI () { OnWizardUpdate(); // Display temporary workaround info GUILayout.Label("To add an audio clip from the Project view, drag and drop it to the audio pane. This is a temporary workaround and will hopefully be fixed soon."); // TODO Make LoadAllAssetsAtPath work /* audioClips = (AudioClip[])AssetDatabase.LoadAllAssetsAtPath("Assets"); Debug.Log("Objects length: " + audioClips.Length); EditorGUILayout.BeginVertical(style.GetStyle("List Container")); foreach (AudioClip aud in audioClips) { GUIStyle itemStyle = aud == selected ? style.GetStyle("Selected List Item") : GUIStyle.none; Rect rect = EditorGUILayout.BeginHorizontal(itemStyle); GUIContent itemLabel = new GUIContent(aud.name, EditorGUIUtility.ObjectContent(null, typeof(AudioClip)).image); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); // Select when clicked if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { selected = aud; EditorGUIUtility.PingObject(aud); Event.current.Use(); } } EditorGUILayout.EndVertical(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true;*/ } void OnWizardUpdate () { helpString = "Choose an audio clip to add."; // Only valid if an audio clip has been selected isValid = selected != null; } /// <summary> /// Adds a new audio clip to the cutscene. /// </summary> void OnWizardCreate () { Selection.activeGameObject.GetComponent<Cutscene>().NewAudio(selected); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneEditor.cs b/Cutscene Ed/Editor/CutsceneEditor.cs index eba8e29..bb80853 100755 --- a/Cutscene Ed/Editor/CutsceneEditor.cs +++ b/Cutscene Ed/Editor/CutsceneEditor.cs @@ -1,491 +1,491 @@ using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// The Cutscene Editor, where tracks and clips can be managed in a fashion similar to non-linear video editors. /// </summary> public class CutsceneEditor : EditorWindow { public static readonly System.Version version = new System.Version(0, 2); public Cutscene scene { get { Object[] scenes = Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel); if (scenes.Length == 0) { return null; } return scenes[0] as Cutscene; } } public GUISkin style { get; private set; } //ICutsceneGUI options; ICutsceneGUI media; ICutsceneGUI effects; ICutsceneGUI tools; ICutsceneGUI timeline; public static bool CutsceneSelected { get { return Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel).Length > 0; } } public static bool HasPro = SystemInfo.supportsImageEffects; // Icons: public readonly Texture[] mediaIcons = { - EditorGUIUtility.LoadRequired("Cutscene Ed/media_shot.png") as Texture, - EditorGUIUtility.LoadRequired("Cutscene Ed/media_actor.png") as Texture, - EditorGUIUtility.LoadRequired("Cutscene Ed/media_audio.png") as Texture, - EditorGUIUtility.LoadRequired("Cutscene Ed/media_subtitle.png") as Texture + EditorGUIUtility.LoadRequired("Cutscene Ed/media_shot.png") as Texture, + EditorGUIUtility.LoadRequired("Cutscene Ed/media_actor.png") as Texture, + EditorGUIUtility.LoadRequired("Cutscene Ed/media_audio.png") as Texture, + EditorGUIUtility.LoadRequired("Cutscene Ed/media_subtitle.png") as Texture }; // Timeline: public Tool currentTool = Tool.MoveResize; public Vector2 timelineScrollPos; public float timelineMin { get; set; } float _timelineZoom = CutsceneTimeline.timelineZoomMin; public float timelineZoom { get { return _timelineZoom; } set { _timelineZoom = Mathf.Clamp(value, CutsceneTimeline.timelineZoomMin, CutsceneTimeline.timelineZoomMax); } } CutsceneTrack _selectedTrack; public CutsceneTrack selectedTrack { get { if (_selectedTrack == null) { // If there are no tracks, add a new one if (scene.tracks.Length == 0) { scene.AddTrack(Cutscene.MediaType.Shots); } _selectedTrack = scene.tracks[0]; } return _selectedTrack; } set { _selectedTrack = value; } } public CutsceneClip selectedClip; public DragEvent dragEvent = DragEvent.Move; public CutsceneClip dragClip; // Menu items: /// <summary> /// Adds "Cutscene Editor" to the Window menu. /// </summary> [MenuItem("Window/Cutscene Editor %9")] public static void OpenEditor () { // Get existing open window or if none, make a new one GetWindow<CutsceneEditor>(false, "Cutscene Editor").Show(); } /// <summary> /// Validates the Cutscene Editor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Window/Cutscene Editor %9", true)] static bool ValidateOpenEditor () { return CutsceneSelected; } /// <summary> /// Adds the option to create a cutscene from the GameObject > Create Other menu. /// </summary> /// <returns>The new cutscene.</returns> [MenuItem("GameObject/Create Other/Cutscene")] static void CreateCutscene () { // Create the new cutscene game object GameObject newSceneGO = new GameObject("Cutscene", typeof(Cutscene)); Cutscene newScene = newSceneGO.GetComponent<Cutscene>(); // Add some tracks to get the user started newScene.AddTrack(Cutscene.MediaType.Shots); newScene.AddTrack(Cutscene.MediaType.Actors); newScene.AddTrack(Cutscene.MediaType.Audio); newScene.AddTrack(Cutscene.MediaType.Subtitles); // Create the cutscene's media game objects - GameObject shots = new GameObject("Shots"); - GameObject actors = new GameObject("Actors"); - GameObject audio = new GameObject("Audio"); - GameObject subtitles = new GameObject("Subtitles"); + GameObject shots = new GameObject("Shots"); + GameObject actors = new GameObject("Actors"); + GameObject audio = new GameObject("Audio"); + GameObject subtitles = new GameObject("Subtitles"); // Make the media game objects a child of the cutscene - shots.transform.parent = newScene.transform; - actors.transform.parent = newScene.transform; - audio.transform.parent = newScene.transform; - subtitles.transform.parent = newScene.transform; + shots.transform.parent = newScene.transform; + actors.transform.parent = newScene.transform; + audio.transform.parent = newScene.transform; + subtitles.transform.parent = newScene.transform; // Create the master animation clip AnimationClip masterClip = new AnimationClip(); newScene.masterClip = masterClip; newScene.animation.AddClip(masterClip, "master"); newScene.animation.playAutomatically = false; newScene.animation.wrapMode = WrapMode.Once; EDebug.Log("Cutscene Editor: created a new cutscene"); } /// <summary> /// Adds the option to create a cutscene trigger to the GameObject > Create Other menu. /// </summary> /// <returns>The trigger's collider.</returns> [MenuItem("GameObject/Create Other/Cutscene Trigger")] static Collider CreateCutsceneTrigger () { // Create the new cutscene trigger game object GameObject triggerGO = new GameObject("Cutscene Trigger", typeof(BoxCollider), typeof(CutsceneTrigger)); triggerGO.collider.isTrigger = true; return triggerGO.collider; } /// <summary> /// Adds the option to create a new shot track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Shot")] static void CreateShotTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Shots); } /// <summary> /// Validates the Shot menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Shot", true)] static bool ValidateCreateShotTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new actor track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Actor")] static void CreateActorTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Actors); } /// <summary> /// Validates the Actor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Actor", true)] static bool ValidateCreateActorTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new audio track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Audio")] static void CreateAudioTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Audio); } /// <summary> /// Validates the Audio menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Audio", true)] static bool ValidateCreateAudioTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new subtitle track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Subtitle")] static void CreateSubtitleTrack () { Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Subtitles); } /// <summary> /// Validates the Subtitle menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Subtitle", true)] static bool ValidateCreateSubtitleTrack () { return CutsceneSelected; } void OnEnable () { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; if (style == null) { Debug.LogError("GUISkin for Cutscene Editor missing"); return; } - //options = new CutsceneOptions(this); - media = new CutsceneMediaWindow(this); - effects = new CutsceneEffectsWindow(this); - tools = new CutsceneTools(this); - timeline = new CutsceneTimeline(this); + options = new CutsceneOptions(this); + media = new CutsceneMediaWindow(this); + effects = new CutsceneEffectsWindow(this); + tools = new CutsceneTools(this); + timeline = new CutsceneTimeline(this); } /// <summary> /// Displays the editor GUI. /// </summary> void OnGUI () { if (style == null) { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; } // If no cutscene is selected, present the user with the option to create one if (scene == null) { if (GUILayout.Button("Create New Cutscene", GUILayout.ExpandWidth(false))) { CreateCutscene(); } } else { // Otherwise present the cutscene editor float windowHeight = style.GetStyle("Pane").fixedHeight; // Options window //Rect optionsRect = new Rect(0, 0, position.width / 3, windowHeight); //options.OnGUI(optionsRect); // Media window Rect mediaRect = new Rect(2, 2, position.width / 2, windowHeight); media.OnGUI(mediaRect); // Effects window Rect effectsRect = new Rect(mediaRect.xMax + 2, 2, position.width - mediaRect.xMax - 4, windowHeight); effects.OnGUI(effectsRect); // Cutting tools Rect toolsRect = new Rect(0, mediaRect.yMax, position.width, 25); tools.OnGUI(toolsRect); // Timeline Rect timelineRect = new Rect(0, toolsRect.yMax, position.width, position.height - toolsRect.yMax); timeline.OnGUI(timelineRect); } } // Context menus: /// <summary> /// Deletes a piece of media by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> [MenuItem("CONTEXT/CutsceneObject/Delete")] static void DeleteCutsceneMedia (MenuCommand command) { DeleteCutsceneMedia(command.context as CutsceneMedia); } /// <summary> /// Deletes a piece of media. /// </summary> /// <param name="obj">The media to delete.</param> /// <remarks>This has to be in CutsceneEditor rather than CutsceneTimeline because it uses the DestroyImmediate function, which is only available to classes which inherit from UnityEngine.Object.</remarks> static void DeleteCutsceneMedia (CutsceneMedia obj) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Object", "Are you sure you wish to delete this object? Changes cannot be undone.", "Delete", "Cancel"); } // Only delete the cutscene object if the user chose to if (delete) { Debug.Log("Cutscene Editor: deleting media " + obj.name); if (obj.type == Cutscene.MediaType.Actors || obj.type == Cutscene.MediaType.Subtitles) { // Delete the CutsceneObject component DestroyImmediate(obj); } else { // Delete the actual game object DestroyImmediate(obj.gameObject); } } } /// <summary> /// Deletes a track by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneTrack/Delete Track")] static bool DeleteTrack (MenuCommand command) { return DeleteTrack(command.context as CutsceneTrack); } /// <summary> /// Deletes a track. /// </summary> /// <param name="track">The track to delete.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> static bool DeleteTrack (CutsceneTrack track) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Track", "Are you sure you wish to delete this track? Changes cannot be undone.", "Delete", "Cancel"); } if (delete) { DestroyImmediate(track); } return delete; } /// <summary> /// Deletes a clip by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneClip/Delete Clip")] static bool DeleteClip (MenuCommand command) { return DeleteClip(command.context as CutsceneClip); } /// <summary> /// Deletes a clip. /// </summary> /// <param name="clip">The clip to delete.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> static bool DeleteClip (CutsceneClip clip) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Clip", "Are you sure you wish to delete this clip? Changes cannot be undone.", "Delete", "Cancel"); } clip.setToDelete = delete; return delete; } /// <summary> /// Selects the track at the specified index. /// </summary> /// <param name="index">The track to select.</param> void SelectTrackAtIndex (int index) { if (scene.tracks.Length > 0 && index > 0 && index <= scene.tracks.Length) { selectedTrack = scene.tracks[index - 1]; EDebug.Log("Cutscene Editor: track " + index + " is selected"); } } /// <summary> /// Determines which key command is pressed and responds accordingly. /// </summary> /// <param name="keyDownEvent">The keyboard event.</param> /// <returns>True if the keyboard shortcut exists, false otherwise.</returns> public void HandleKeyboardShortcuts (Event keyDownEvent) { KeyCode key = keyDownEvent.keyCode; // Tools: // Move/resize if (key == CutsceneHotkeys.MoveResizeTool.key) { currentTool = Tool.MoveResize; EDebug.Log("Cutscene Editor: switching to Move/Resize tool"); // Scissors } else if (key == CutsceneHotkeys.ScissorsTool.key) { currentTool = Tool.Scissors; EDebug.Log("Cutscene Editor: switching to Scissors tool"); // Zoom } else if (key == CutsceneHotkeys.ZoomTool.key) { currentTool = Tool.Zoom; EDebug.Log("Cutscene Editor: switching to Zoom tool"); } // Timeline navigation: // Set in point else if (key == CutsceneHotkeys.SetInPont.key) { scene.inPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting in point"); // Set out point } else if (key == CutsceneHotkeys.SetOutPoint.key) { scene.outPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting out point"); // Scrub left } else if (keyDownEvent.Equals(Event.KeyboardEvent("left"))) { scene.playhead -= CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead left"); // Scrub left large } else if (keyDownEvent.Equals(Event.KeyboardEvent("#left"))) { scene.playhead -= CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead left"); // Scrub right } else if (keyDownEvent.Equals(Event.KeyboardEvent("right"))) { scene.playhead += CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead right"); // Scrub right large } else if (keyDownEvent.Equals(Event.KeyboardEvent("#right"))) { scene.playhead += CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead right"); // Go to previous split point } else if (keyDownEvent.Equals(Event.KeyboardEvent("up"))) { scene.playhead = selectedTrack.GetTimeOfNextSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to previous split point"); // Go to next split point } else if (keyDownEvent.Equals(Event.KeyboardEvent("down"))) { scene.playhead = selectedTrack.GetTimeOfPreviousSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to next split point"); // Go to in point } else if (keyDownEvent.Equals(Event.KeyboardEvent("#up"))) { scene.playhead = scene.inPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); // Go to out point } else if (keyDownEvent.Equals(Event.KeyboardEvent("#down"))) { scene.playhead = scene.outPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); } // Track selection: // Select track 1 else if (key == CutsceneHotkeys.SelectTrack1.key) { SelectTrackAtIndex(1); // Select track 2 } else if (key == CutsceneHotkeys.SelectTrack2.key) { SelectTrackAtIndex(2); // Select track 3 } else if (key == CutsceneHotkeys.SelectTrack3.key) { SelectTrackAtIndex(3); // Select track 4 } else if (key == CutsceneHotkeys.SelectTrack4.key) { SelectTrackAtIndex(4); // Select track 5 } else if (key == CutsceneHotkeys.SelectTrack5.key) { SelectTrackAtIndex(5); // Select track 6 } else if (key == CutsceneHotkeys.SelectTrack6.key) { SelectTrackAtIndex(6); // Select track 7 } else if (key == CutsceneHotkeys.SelectTrack7.key) { SelectTrackAtIndex(7); // Select track 8 } else if (key == CutsceneHotkeys.SelectTrack8.key) { SelectTrackAtIndex(8); // Select track 9 } else if (key == CutsceneHotkeys.SelectTrack9.key) { SelectTrackAtIndex(9); } // Other: else { EDebug.Log("Cutscene Editor: unknown keyboard shortcut " + keyDownEvent); return; } // If we get to this point, a shortcut matching the user's keystroke has been found Event.current.Use(); } public static float PaneTabsWidth (int count) { return count * 80f; } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneEffectsWindow.cs b/Cutscene Ed/Editor/CutsceneEffectsWindow.cs index 22244ab..33227fc 100755 --- a/Cutscene Ed/Editor/CutsceneEffectsWindow.cs +++ b/Cutscene Ed/Editor/CutsceneEffectsWindow.cs @@ -1,106 +1,106 @@ using UnityEditor; using UnityEngine; using System; using System.Collections.Generic; class CutsceneEffectsWindow : ICutsceneGUI { readonly CutsceneEditor ed; static Dictionary<string, Type> filters = new Dictionary<string, Type> { - { CutsceneBlurFilter.name, typeof(CutsceneBlurFilter) }, - { CutsceneInvertFilter.name, typeof(CutsceneInvertFilter) } + { CutsceneBlurFilter.name, typeof(CutsceneBlurFilter) }, + { CutsceneInvertFilter.name, typeof(CutsceneInvertFilter) } }; static Dictionary<string, Type> transitions = new Dictionary<string, Type> {}; - static readonly GUIContent filtersLabel = new GUIContent("Filters", "Full screen filters."); - static readonly GUIContent transitionsLabel = new GUIContent("Transitions", "Camera transitions."); + static readonly GUIContent filtersLabel = new GUIContent("Filters", "Full screen filters."); + static readonly GUIContent transitionsLabel = new GUIContent("Transitions", "Camera transitions."); readonly GUIContent[] effectsTabs = CutsceneEditor.HasPro ? new GUIContent[] { filtersLabel, transitionsLabel } : new GUIContent[] { transitionsLabel }; Cutscene.EffectType currentEffectsTab = Cutscene.EffectType.Filters; Type selectedEffect; readonly Texture[] effectsIcons = { - EditorGUIUtility.LoadRequired("Cutscene Ed/effects_filter.png") as Texture, - EditorGUIUtility.LoadRequired("Cutscene Ed/effects_transition.png") as Texture + EditorGUIUtility.LoadRequired("Cutscene Ed/effects_filter.png") as Texture, + EditorGUIUtility.LoadRequired("Cutscene Ed/effects_transition.png") as Texture }; public CutsceneEffectsWindow (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the effects pane's GUI. /// </summary> /// <param name="rect">The effects pane's Rect.</param> public void OnGUI (Rect rect) { GUILayout.BeginArea(rect, ed.style.GetStyle("Pane")); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); currentEffectsTab = (Cutscene.EffectType)GUILayout.Toolbar((int)currentEffectsTab, effectsTabs, GUILayout.Width(CutsceneEditor.PaneTabsWidth(effectsTabs.Length))); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); GUI.enabled = ed.selectedClip != null && ed.selectedClip.type == Cutscene.MediaType.Shots && selectedEffect != null; GUIContent applyLabel = new GUIContent("Apply", "Apply the selected effect to the selected clip."); if (GUILayout.Button(applyLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { if (ed.selectedClip != null) { ed.selectedClip.ApplyEffect(selectedEffect); } } GUI.enabled = true; EditorGUILayout.EndHorizontal(); switch (currentEffectsTab) { case Cutscene.EffectType.Filters: foreach (KeyValuePair<string, Type> item in filters) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedEffect == item.Value ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent filterLabel = new GUIContent(item.Key, effectsIcons[(int)Cutscene.EffectType.Filters]); GUILayout.Label(filterLabel); EditorGUILayout.EndHorizontal(); // Handle clicks if (Event.current.type == EventType.MouseDown && itemRect.Contains(Event.current.mousePosition)) { selectedEffect = item.Value; Event.current.Use(); } } break; case Cutscene.EffectType.Transitions: foreach (KeyValuePair<string, Type> item in transitions) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedEffect == item.Value ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent transitionLabel = new GUIContent(item.Key, effectsIcons[(int)Cutscene.EffectType.Transitions]); GUILayout.Label(transitionLabel); EditorGUILayout.EndHorizontal(); // Handle clicks if (Event.current.type == EventType.MouseDown && itemRect.Contains(Event.current.mousePosition)) { selectedEffect = item.Value; Event.current.Use(); } } break; default: break; } GUILayout.EndArea(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneHotkeys.cs b/Cutscene Ed/Editor/CutsceneHotkeys.cs index a8df31d..af70f17 100755 --- a/Cutscene Ed/Editor/CutsceneHotkeys.cs +++ b/Cutscene Ed/Editor/CutsceneHotkeys.cs @@ -1,80 +1,80 @@ using UnityEditor; using UnityEngine; struct Hotkey { const string prefPrefix = "Cutscene Editor Hotkey "; - string id; - KeyCode defaultKey; - bool assignable; + string id; + KeyCode defaultKey; + bool assignable; public KeyCode key { get { if (assignable && EditorPrefs.HasKey(prefPrefix + id)) { return (KeyCode)EditorPrefs.GetInt(prefPrefix + id, (int)defaultKey); } else { return defaultKey; } } set { if (assignable) { EditorPrefs.SetInt(prefPrefix + id, (int)value); } else { EDebug.LogWarning("Cutscene Editor: Hotkey " + id + " cannot be reassigned"); } } } public Hotkey (string id, KeyCode defaultKey, bool assignable) { - this.id = id; + this.id = id; this.defaultKey = defaultKey; this.assignable = assignable; } /// <summary> /// Resets the key to its default value. /// </summary> public void Reset () { if (assignable) { key = defaultKey; } EDebug.Log("Cutscene Editor: Hotkey " + id + " reset to its default " + defaultKey); } } static class CutsceneHotkeys { // Assignable: - public static Hotkey MoveResizeTool = new Hotkey("moveResizeTool", KeyCode.M, true); - public static Hotkey ScissorsTool = new Hotkey("scissorsTool", KeyCode.S, true); - public static Hotkey ZoomTool = new Hotkey("zoomTool", KeyCode.Z, true); - public static Hotkey SetInPont = new Hotkey("setInPoint", KeyCode.I, true); - public static Hotkey SetOutPoint = new Hotkey("setOutPoint", KeyCode.O, true); + public static Hotkey MoveResizeTool = new Hotkey("moveResizeTool", KeyCode.M, true); + public static Hotkey ScissorsTool = new Hotkey("scissorsTool", KeyCode.S, true); + public static Hotkey ZoomTool = new Hotkey("zoomTool", KeyCode.Z, true); + public static Hotkey SetInPont = new Hotkey("setInPoint", KeyCode.I, true); + public static Hotkey SetOutPoint = new Hotkey("setOutPoint", KeyCode.O, true); // Unassignable: public static readonly Hotkey SelectTrack1 = new Hotkey("selectTrack1", KeyCode.Alpha1, true); public static readonly Hotkey SelectTrack2 = new Hotkey("selectTrack2", KeyCode.Alpha2, true); public static readonly Hotkey SelectTrack3 = new Hotkey("selectTrack3", KeyCode.Alpha3, true); public static readonly Hotkey SelectTrack4 = new Hotkey("selectTrack4", KeyCode.Alpha4, true); public static readonly Hotkey SelectTrack5 = new Hotkey("selectTrack5", KeyCode.Alpha5, true); public static readonly Hotkey SelectTrack6 = new Hotkey("selectTrack6", KeyCode.Alpha6, true); public static readonly Hotkey SelectTrack7 = new Hotkey("selectTrack7", KeyCode.Alpha7, true); public static readonly Hotkey SelectTrack8 = new Hotkey("selectTrack8", KeyCode.Alpha8, true); public static readonly Hotkey SelectTrack9 = new Hotkey("selectTrack9", KeyCode.Alpha9, true); public static Hotkey[] assignable = new Hotkey[] { MoveResizeTool, ScissorsTool, ZoomTool, SetInPont, SetOutPoint }; /// <summary> /// Resets all the assignable hotkeys to their default values. /// </summary> public static void ResetAll () { foreach (Hotkey key in assignable) { key.Reset(); } } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneMediaWindow.cs b/Cutscene Ed/Editor/CutsceneMediaWindow.cs index 9514dc1..7fd9972 100755 --- a/Cutscene Ed/Editor/CutsceneMediaWindow.cs +++ b/Cutscene Ed/Editor/CutsceneMediaWindow.cs @@ -1,286 +1,286 @@ using UnityEditor; using UnityEngine; class CutsceneMediaWindow : ICutsceneGUI { readonly CutsceneEditor ed; readonly GUIContent[] mediaTabs = { - new GUIContent("Shots", "Camera views."), - new GUIContent("Actors", "Animated game objects."), - new GUIContent("Audio", "Dialog, background music and sound effects."), + new GUIContent("Shots", "Camera views."), + new GUIContent("Actors", "Animated game objects."), + new GUIContent("Audio", "Dialog, background music and sound effects."), new GUIContent("Subtitles", "Textual versions of dialog.") }; Cutscene.MediaType currentMediaTab = Cutscene.MediaType.Shots; Vector2[] mediaScrollPos = { Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero }; CutsceneMedia selectedMediaItem; - readonly GUIContent newMediaLabel = new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/icon_add.png") as Texture, "Add new media."); - readonly GUIContent insertMediaLabel = new GUIContent("Insert", "Insert the selected shot onto the timeline."); + readonly GUIContent newMediaLabel = new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/icon_add.png") as Texture, "Add new media."); + readonly GUIContent insertMediaLabel = new GUIContent("Insert", "Insert the selected shot onto the timeline."); public CutsceneMediaWindow (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the media pane's GUI. /// </summary> /// <param name="rect">The media pane's Rect.</param> public void OnGUI (Rect rect) { GUILayout.BeginArea(rect, ed.style.GetStyle("Pane")); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); currentMediaTab = (Cutscene.MediaType)GUILayout.Toolbar((int)currentMediaTab, mediaTabs, GUILayout.Width(CutsceneEditor.PaneTabsWidth(mediaTabs.Length))); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); switch (currentMediaTab) { case Cutscene.MediaType.Shots: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { ed.scene.NewShot(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneShot shot in ed.scene.shots) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == shot ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(shot.name, ed.mediaIcons[(int)Cutscene.MediaType.Shots]); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(shot, itemRect); } EditorGUILayout.EndScrollView(); break; case Cutscene.MediaType.Actors: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { CutsceneAddActor.CreateWizard(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneActor actor in ed.scene.actors) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == actor ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(actor.anim.name, ed.mediaIcons[(int)Cutscene.MediaType.Actors]); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(actor, itemRect); } EditorGUILayout.EndScrollView(); break; case Cutscene.MediaType.Audio: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { // Show a wizard that will take care of adding audio CutsceneAddAudio.CreateWizard(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneAudio aud in ed.scene.audioSources) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == aud ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(aud.name, ed.mediaIcons[(int)Cutscene.MediaType.Audio]); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(aud, itemRect); } EditorGUILayout.EndScrollView(); break; case Cutscene.MediaType.Subtitles: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { // Show a wizard that will take care of adding audio CutsceneAddSubtitle.CreateWizard(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneSubtitle subtitle in ed.scene.subtitles) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == subtitle ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(ed.mediaIcons[(int)Cutscene.MediaType.Subtitles]); GUILayout.Label(itemLabel, GUILayout.ExpandWidth(false)); subtitle.dialog = EditorGUILayout.TextField(subtitle.dialog); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(subtitle, itemRect); } EditorGUILayout.EndScrollView(); break; default: break; } GUILayout.EndArea(); // Handle drag and drop events if (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform) { // Show a copy icon on the drag DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (Event.current.type == EventType.DragPerform && rect.Contains(Event.current.mousePosition)) { DragAndDrop.AcceptDrag(); Object[] draggedObjects = DragAndDrop.objectReferences; // Create the appropriate cutscene objects for each dragged object foreach (Object obj in draggedObjects) { if (obj is AudioClip) { ed.scene.NewAudio((AudioClip)obj); } else if (obj is GameObject && ((GameObject)obj).animation != null) { GameObject go = obj as GameObject; foreach (AnimationClip anim in AnimationUtility.GetAnimationClips(go.animation)) { ed.scene.NewActor(anim, go); } } EDebug.Log("Cutscene Editor: dropping " + obj.GetType()); } } Event.current.Use(); } } /// <summary> /// Handles left and right mouse clicks of media items. /// </summary> /// <param name="item">The item clicked on.</param> /// <param name="rect">The item's Rect.</param> void HandleMediaItemClicks (CutsceneMedia item, Rect rect) { Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && rect.Contains(mousePos)) { switch (Event.current.button) { case 0: // Left click selectedMediaItem = item; EditorGUIUtility.PingObject(item); break; case 1: // Right click EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneObject/", new MenuCommand(item)); break; default: break; } Event.current.Use(); } } /// <summary> /// Determines whether or not the currently selected cutscene object can be inserted into the selected timeline. /// </summary> /// <returns>True if the selected clip and the selected track are the same, false otherwise.</returns> bool IsMediaInsertable () { return selectedMediaItem != null && selectedMediaItem.type == ed.selectedTrack.type; } /// <summary> /// Inserts the given cutscene object into the timeline. /// </summary> /// <param name="obj">The cutscene object to insert.</param> void Insert (CutsceneMedia obj) { CutsceneClip newClip = new CutsceneClip(obj); newClip.timelineStart = ed.scene.playhead; // If there are no existing tracks, add a new one if (ed.scene.tracks.Length == 0) { ed.scene.AddTrack(newClip.type); } // Manage overlap with other clips CutsceneClip existingClip = ed.selectedTrack.ContainsClipAtTime(ed.scene.playhead); if (existingClip != null) { CutsceneClip middleOfSplit = CutsceneTimeline.SplitClipAtTime(ed.scene.playhead, ed.selectedTrack, existingClip); CutsceneTimeline.SplitClipAtTime(ed.scene.playhead + newClip.duration, ed.selectedTrack, middleOfSplit); ed.selectedTrack.clips.Remove(middleOfSplit); } ed.selectedTrack.clips.Add(newClip); EDebug.Log("Cutscene Editor: inserting " + newClip.name + " into timeline " + ed.selectedTrack + " at " + ed.scene.playhead); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneNavigation.cs b/Cutscene Ed/Editor/CutsceneNavigation.cs index 5d79eb2..69e58aa 100755 --- a/Cutscene Ed/Editor/CutsceneNavigation.cs +++ b/Cutscene Ed/Editor/CutsceneNavigation.cs @@ -1,41 +1,41 @@ using UnityEditor; using UnityEngine; class CutsceneNavigation : ICutsceneGUI { readonly CutsceneEditor ed; readonly ICutsceneGUI playbackControls; readonly ICutsceneGUI timecodeBar; readonly GUIContent zoomButton = new GUIContent("", "Zoom timeline to entire scene."); public CutsceneNavigation (CutsceneEditor ed) { this.ed = ed; - playbackControls = new CutscenePlaybackControls(ed); - timecodeBar = new CutsceneTimecodeBar(ed); + playbackControls = new CutscenePlaybackControls(ed); + timecodeBar = new CutsceneTimecodeBar(ed); } public void OnGUI (Rect rect) { GUI.BeginGroup(rect); float zoomButtonWidth = GUI.skin.verticalScrollbar.fixedWidth; float timecodeBarWidth = ed.position.width - CutsceneTimeline.trackInfoWidth - zoomButtonWidth; // Playback controls Rect playbackControlsRect = new Rect(0, 0, CutsceneTimeline.trackInfoWidth, rect.height); playbackControls.OnGUI(playbackControlsRect); // Timecode bar Rect timecodeBarRect = new Rect(playbackControlsRect.xMax, 0, timecodeBarWidth, rect.height); timecodeBar.OnGUI(timecodeBarRect); // Zoom to view entire project Rect zoomButtonRect = new Rect(timecodeBarRect.xMax, 0, zoomButtonWidth, rect.height); if (GUI.Button(zoomButtonRect, zoomButton, EditorStyles.toolbarButton)) { ed.timelineZoom = ed.timelineMin; EDebug.Log("Cutscene Editor: zoomed timeline to entire scene"); } GUI.EndGroup(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTimecodeBar.cs b/Cutscene Ed/Editor/CutsceneTimecodeBar.cs index e096070..0dd3f00 100755 --- a/Cutscene Ed/Editor/CutsceneTimecodeBar.cs +++ b/Cutscene Ed/Editor/CutsceneTimecodeBar.cs @@ -1,161 +1,161 @@ using UnityEngine; using UnityEditor; class CutsceneTimecodeBar : ICutsceneGUI { readonly CutsceneEditor ed; - const int shortTickHeight = 3; - const int tallTickHeight = 6; + const int shortTickHeight = 3; + const int tallTickHeight = 6; - readonly Color tickColor = Color.gray; - readonly Color playheadBlockColor = Color.black; - readonly Color inOutPointColour = Color.cyan; + readonly Color tickColor = Color.gray; + readonly Color playheadBlockColor = Color.black; + readonly Color inOutPointColour = Color.cyan; - readonly Texture positionIndicatorIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/position_indicator.png") as Texture; - readonly Texture inPointIndicatorIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/inpoint_indicator.png") as Texture; - readonly Texture outPointIndicatorIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/outpoint_indicator.png") as Texture; + readonly Texture positionIndicatorIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/position_indicator.png") as Texture; + readonly Texture inPointIndicatorIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/inpoint_indicator.png") as Texture; + readonly Texture outPointIndicatorIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/outpoint_indicator.png") as Texture; - readonly GUIContent inTooltip = new GUIContent("", "In point."); - readonly GUIContent outTooltip = new GUIContent("", "Out point."); + readonly GUIContent inTooltip = new GUIContent("", "In point."); + readonly GUIContent outTooltip = new GUIContent("", "Out point."); public CutsceneTimecodeBar (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the timecode bar with vertical lines indicating the time and the playhead. /// </summary> /// <param name="rect">The timecode bar's Rect.</param> public void OnGUI (Rect rect) { GUI.BeginGroup(rect); // Create a button that looks like a toolbar if (GUI.RepeatButton(new Rect(0, 0, rect.width, rect.height), GUIContent.none, EditorStyles.toolbar)) { float position = Event.current.mousePosition.x + ed.timelineScrollPos.x; ed.scene.playhead = position / ed.timelineZoom; // Show a visual notification of the position GUIContent notification = new GUIContent("Playhead " + ed.scene.playhead.ToString("N2")); ed.ShowNotification(notification); ed.Repaint(); //SceneView.RepaintAll(); } else { // TODO Investigate if attempting to remove the notification every frame like this is wasteful ed.RemoveNotification(); } DrawTicks(); DrawLabels(); DrawPlayhead(); DrawInOutPoints(); GUI.EndGroup(); } /// <summary> /// Draws vertical lines representing time increments. /// </summary> void DrawTicks () { Handles.color = tickColor; // Draw short ticks every second for (float i = 0; i < ed.scene.duration * ed.timelineZoom; i += ed.timelineZoom) { float xPos = i - ed.timelineScrollPos.x; Handles.DrawLine(new Vector3(xPos, 0, 0), new Vector3(xPos, shortTickHeight)); } // Draw tall ticks every ten seconds for (float i = 0; i < ed.scene.duration * ed.timelineZoom; i += ed.timelineZoom * 10) { float xPos = i - ed.timelineScrollPos.x; Handles.DrawLine(new Vector3(xPos, 0, 0), new Vector3(xPos, tallTickHeight)); } } /// <summary> /// Draws labels indicating the time. /// </summary> void DrawLabels () { for (float i = 0; i < 1000; i += 10) { float xPos = (i * ed.timelineZoom) - ed.timelineScrollPos.x; GUIContent label = new GUIContent(i + ""); Vector2 dimensions = EditorStyles.miniLabel.CalcSize(label); Rect labelRect = new Rect(xPos - (dimensions.x / 2), 2, dimensions.x, dimensions.y); GUI.Label(labelRect, label, EditorStyles.miniLabel); } } /// <summary> /// Draws the playhead. /// </summary> void DrawPlayhead () { // Draw position indicator float pos = (ed.scene.playhead * ed.timelineZoom) - ed.timelineScrollPos.x; GUI.DrawTexture(new Rect(pos - 4, 0, 8, 8), positionIndicatorIcon); Handles.color = Color.black; // Vertical line Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, EditorStyles.toolbar.fixedHeight); Handles.DrawLine(top, bottom); // Zoom indicator block Handles.color = playheadBlockColor; for (int i = 1; i <= ed.timelineZoom; i++) { float xPos = pos + i; top = new Vector3(xPos, 4); bottom = new Vector3(xPos, EditorStyles.toolbar.fixedHeight - 1); Handles.DrawLine(top, bottom); } } /// <summary> /// Draws the in and out points. /// </summary> void DrawInOutPoints () { Handles.color = inOutPointColour; DrawInPoint(); DrawOutPoint(); } /// <summary> /// Draws the in point. /// </summary> void DrawInPoint () { float pos = (ed.scene.inPoint * ed.timelineZoom) - ed.timelineScrollPos.x; // Icon Rect indicatorRect = new Rect(pos, 0, 4, 8); GUI.DrawTexture(indicatorRect, inPointIndicatorIcon); // Tooltip GUI.Label(indicatorRect, inTooltip); // Vertical line Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, EditorStyles.toolbar.fixedHeight); Handles.DrawLine(top, bottom); } /// <summary> /// Draws the out point. /// </summary> void DrawOutPoint () { float pos = (ed.scene.outPoint * ed.timelineZoom) - ed.timelineScrollPos.x; // Icon Rect indicatorRect = new Rect(pos - 4, 0, 4, 8); GUI.DrawTexture(indicatorRect, outPointIndicatorIcon); // Tooltip GUI.Label(indicatorRect, outTooltip); // Vertical line Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, EditorStyles.toolbar.fixedHeight); Handles.DrawLine(top, bottom); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTimeline.cs b/Cutscene Ed/Editor/CutsceneTimeline.cs index 9c3228a..6a3b523 100755 --- a/Cutscene Ed/Editor/CutsceneTimeline.cs +++ b/Cutscene Ed/Editor/CutsceneTimeline.cs @@ -1,112 +1,112 @@ using UnityEditor; using UnityEngine; public enum DragEvent { Move, ResizeLeft, ResizeRight } class CutsceneTimeline : ICutsceneGUI { readonly CutsceneEditor ed; public const int scrubLargeJump = 10; public const int scrubSmallJump = 1; readonly ICutsceneGUI navigation; readonly ICutsceneGUI tracksView; readonly ICutsceneGUI trackControls; readonly ICutsceneGUI trackInfo; - public const float timelineZoomMin = 1f; - public const float timelineZoomMax = 100f; - public const float trackInfoWidth = 160f; + public const float timelineZoomMin = 1f; + public const float timelineZoomMax = 100f; + public const float trackInfoWidth = 160f; public CutsceneTimeline (CutsceneEditor ed) { this.ed = ed; - navigation = new CutsceneNavigation(ed); - tracksView = new CutsceneTracksView(ed); - trackControls = new CutsceneTrackControls(ed); - trackInfo = new CutsceneTrackInfo(ed); + navigation = new CutsceneNavigation(ed); + tracksView = new CutsceneTracksView(ed); + trackControls = new CutsceneTrackControls(ed); + trackInfo = new CutsceneTrackInfo(ed); } /// <summary> /// Displays the timeline's GUI. /// </summary> /// <param name="rect">The timeline's Rect.</param> public void OnGUI (Rect rect) { GUILayout.BeginArea(rect); float rightColWidth = GUI.skin.verticalScrollbar.fixedWidth; float middleColWidth = rect.width - CutsceneTimeline.trackInfoWidth - rightColWidth; ed.timelineMin = CutsceneTimeline.timelineZoomMin * (middleColWidth / ed.scene.duration); ed.timelineZoom = Mathf.Clamp(ed.timelineZoom, ed.timelineMin, CutsceneTimeline.timelineZoomMax); // Navigation bar Rect navigationRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.toolbar, GUILayout.Width(rect.width)); navigation.OnGUI(navigationRect); // Begin Tracks EditorGUILayout.BeginHorizontal(GUILayout.Width(rect.width), GUILayout.ExpandHeight(true)); // Track info //Rect trackInfoRect = GUILayoutUtility.GetRect(trackInfoWidth, rect.height - navigationRect.yMax - GUI.skin.horizontalScrollbar.fixedHeight); Rect trackInfoRect = new Rect(0, 0, CutsceneTimeline.trackInfoWidth, 9999); trackInfo.OnGUI(trackInfoRect); // Track controls float trackControlsHeight = GUI.skin.horizontalScrollbar.fixedHeight; Rect trackControlsRect = new Rect(0, rect.height - trackControlsHeight, CutsceneTimeline.trackInfoWidth, trackControlsHeight); trackControls.OnGUI(trackControlsRect); // Tracks Rect tracksRect = new Rect(trackInfoRect.xMax, navigationRect.yMax, middleColWidth + rightColWidth, rect.height - navigationRect.yMax); tracksView.OnGUI(tracksRect); EditorGUILayout.EndHorizontal(); if (Event.current.type == EventType.KeyDown) { // Key presses ed.HandleKeyboardShortcuts(Event.current); } GUILayout.EndArea(); } /// <summary> /// Moves the playhead. /// </summary> /// <param name="playheadPos">The position to move the playhead to.</param> void MovePlayheadToPosition (float playheadPos) { ed.scene.playhead = playheadPos / ed.timelineZoom; } /// <summary> /// Splits a clip into two separate ones at the specified time. /// </summary> /// <param name="splitPoint">The time at which to split the clip.</param> /// <param name="track">The track the clip is sitting on.</param> /// <param name="clip">The clip to split.</param> /// <returns>The new clip.</returns> public static CutsceneClip SplitClipAtTime (float splitPoint, CutsceneTrack track, CutsceneClip clip) { CutsceneClip newClip = clip.GetCopy(); // Make sure the clip actually spans over the split point if (splitPoint < clip.timelineStart || splitPoint > clip.timelineStart + clip.duration) { EDebug.Log("Cutscene Editor: cannot split clip; clip does not contain the split point"); return null; } clip.SetOutPoint(clip.inPoint + (splitPoint - clip.timelineStart)); newClip.SetInPoint(clip.outPoint); newClip.SetTimelineStart(splitPoint); track.clips.Add(newClip); Event.current.Use(); EDebug.Log("Cutscene Editor: splitting clip at time " + splitPoint); return newClip; } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTools.cs b/Cutscene Ed/Editor/CutsceneTools.cs index 5014e8a..cef6577 100755 --- a/Cutscene Ed/Editor/CutsceneTools.cs +++ b/Cutscene Ed/Editor/CutsceneTools.cs @@ -1,35 +1,35 @@ using UnityEditor; using UnityEngine; public enum Tool { MoveResize, Scissors, Zoom } class CutsceneTools : ICutsceneGUI { readonly CutsceneEditor ed; readonly GUIContent[] tools = { - new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_move.png") as Texture, "Move/Resize"), - new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_scissors.png") as Texture, "Scissors"), - new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_zoom.png") as Texture, "Zoom") + new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_move.png") as Texture, "Move/Resize"), + new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_scissors.png") as Texture, "Scissors"), + new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/tool_zoom.png") as Texture, "Zoom") }; public CutsceneTools (CutsceneEditor ed) { this.ed = ed; } public void OnGUI (Rect rect) { GUILayout.BeginArea(rect); EditorGUILayout.BeginHorizontal(ed.style.GetStyle("Tools Bar"), GUILayout.Width(rect.width)); GUILayout.FlexibleSpace(); ed.currentTool = (Tool)GUILayout.Toolbar((int)ed.currentTool, tools); EditorGUILayout.EndHorizontal(); GUILayout.EndArea(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTrackInfo.cs b/Cutscene Ed/Editor/CutsceneTrackInfo.cs index 1f5178f..dffcafd 100755 --- a/Cutscene Ed/Editor/CutsceneTrackInfo.cs +++ b/Cutscene Ed/Editor/CutsceneTrackInfo.cs @@ -1,87 +1,87 @@ using UnityEngine; using UnityEditor; class CutsceneTrackInfo : ICutsceneGUI { readonly CutsceneEditor ed; readonly GUIContent visibilityIcon = new GUIContent("", EditorGUIUtility.LoadRequired("Cutscene Ed/icon_eye.png") as Texture, "Toggle visibility." ); readonly GUIContent lockIcon = new GUIContent("", EditorGUIUtility.LoadRequired("Cutscene Ed/icon_lock.png") as Texture, "Toggle track lock." ); public CutsceneTrackInfo (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the track info GUI. /// </summary> /// <param name="rect">The track info's Rect.</param> public void OnGUI (Rect rect) { ed.timelineScrollPos.y = EditorGUILayout.BeginScrollView( new Vector2(0, ed.timelineScrollPos.y), false, false, ed.style.horizontalScrollbar, ed.style.verticalScrollbar, GUIStyle.none, GUILayout.Width(CutsceneTimeline.trackInfoWidth), GUILayout.ExpandHeight(true)).y; foreach (CutsceneTrack track in ed.scene.tracks) { if (track == ed.selectedTrack) { GUI.SetNextControlName("track"); } Rect infoRect = EditorGUILayout.BeginHorizontal(ed.style.GetStyle("Track Info")); - track.enabled = GUILayout.Toggle(track.enabled, visibilityIcon, EditorStyles.miniButtonLeft, GUILayout.ExpandWidth(false)); - track.locked = GUILayout.Toggle(track.locked, lockIcon, EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false)); + track.enabled = GUILayout.Toggle(track.enabled, visibilityIcon, EditorStyles.miniButtonLeft, GUILayout.ExpandWidth(false)); + track.locked = GUILayout.Toggle(track.locked, lockIcon, EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false)); GUILayout.Space(10); GUI.enabled = track.enabled; // Track name and icon GUIContent trackIcon = new GUIContent(ed.mediaIcons[(int)track.type]); GUILayout.Label(trackIcon, GUILayout.ExpandWidth(false)); // Set a minimum width to keep the label from becoming uneditable Rect trackNameRect = GUILayoutUtility.GetRect(new GUIContent(track.name), EditorStyles.miniLabel, GUILayout.ExpandWidth(false), GUILayout.MinWidth(20)); track.name = EditorGUI.TextField(trackNameRect, track.name, EditorStyles.miniLabel); GUI.enabled = true; EditorGUILayout.EndHorizontal(); if (track == ed.selectedTrack) { GUI.FocusControl("track"); } // Handle clicks Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && infoRect.Contains(mousePos)) { switch (Event.current.button) { case 0: // Left mouse button ed.selectedTrack = track; break; case 1: // Right mouse button EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneTrack/", new MenuCommand(track)); break; default: break; } Event.current.Use(); } } // Divider line Handles.color = Color.grey; Handles.DrawLine(new Vector3(67, 0), new Vector3(67, rect.yMax)); EditorGUILayout.EndScrollView(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTracksView.cs b/Cutscene Ed/Editor/CutsceneTracksView.cs index 6fd6bac..57e3de9 100755 --- a/Cutscene Ed/Editor/CutsceneTracksView.cs +++ b/Cutscene Ed/Editor/CutsceneTracksView.cs @@ -1,339 +1,342 @@ using UnityEngine; using UnityEditor; class CutsceneTracksView : ICutsceneGUI { readonly CutsceneEditor ed; readonly Texture overlay = EditorGUIUtility.LoadRequired("Cutscene Ed/overlay.png") as Texture; readonly Color inOutPointColour = Color.cyan; public CutsceneTracksView (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the tracks GUI. /// </summary> /// <param name="rect">The tracks' Rect.</param> public void OnGUI (Rect rect) { // Display background Rect background = new Rect(rect.x, rect.y, rect.width - GUI.skin.verticalScrollbar.fixedWidth, rect.height - GUI.skin.horizontalScrollbar.fixedHeight); GUI.BeginGroup(background, GUI.skin.GetStyle("AnimationCurveEditorBackground")); GUI.EndGroup(); - float trackHeight = ed.style.GetStyle("Track").fixedHeight + ed.style.GetStyle("Track").margin.vertical; + float trackHeight = ed.style.GetStyle("Track").fixedHeight + ed.style.GetStyle("Track").margin.vertical; // TODO Make the track width take into account clips that are beyond the out point - float tracksWidth = (ed.scene.outPoint + 10) * ed.timelineZoom; - float tracksHeight = trackHeight * ed.scene.tracks.Length; + float tracksWidth = (ed.scene.outPoint + 10) * ed.timelineZoom; + float tracksHeight = trackHeight * ed.scene.tracks.Length; Rect view = new Rect(0, 0, Mathf.Max(background.width + 1, tracksWidth), Mathf.Max(background.height + 1, tracksHeight)); ed.timelineScrollPos = GUI.BeginScrollView(rect, ed.timelineScrollPos, view, true, true); // Zoom clicks if (ed.currentTool == Tool.Zoom && Event.current.type == EventType.MouseDown) { - if (Event.current.alt && Event.current.shift) { // Zoom out all the way + if (Event.current.alt && Event.current.shift) { // Zoom out all the way ed.timelineZoom = CutsceneTimeline.timelineZoomMin; - } else if (Event.current.shift) { // Zoom in all the way + } else if (Event.current.shift) { // Zoom in all the way ed.timelineZoom = CutsceneTimeline.timelineZoomMax; - } else if (Event.current.alt) { // Zoom out + } else if (Event.current.alt) { // Zoom out ed.timelineZoom -= 10; - } else { // Zoom in + } else { // Zoom in ed.timelineZoom += 10; } Event.current.Use(); } // Draw track divider lines Handles.color = Color.grey; for (int i = 0; i < ed.scene.tracks.Length; i++) { Rect trackRect = new Rect(0, trackHeight * i, view.width, trackHeight); DisplayTrack(trackRect, ed.scene.tracks[i]); float yPos = (i + 1) * trackHeight - 1; Handles.DrawLine(new Vector3(0, yPos), new Vector3(view.width, yPos)); } // Draw overlay over in area Rect inOverlay = new Rect(0, 0, ed.scene.inPoint * ed.timelineZoom, view.height); GUI.DrawTexture(inOverlay, overlay); // Draw overlay over out area Rect outOverlay = new Rect(ed.scene.outPoint * ed.timelineZoom, 0, 0, view.height); outOverlay.width = view.width - outOverlay.x; GUI.DrawTexture(outOverlay, overlay); DrawLines(view); GUI.EndScrollView(); } /// <summary> /// Displays visual tracks upon which clips sit. /// </summary> void DisplayTrack (Rect rect, CutsceneTrack track) { GUI.enabled = track.enabled; for (int i = track.clips.Count - 1; i >= 0; i--) { DisplayClip(rect, track, track.clips[i]); } GUI.enabled = true; // Handle clicks Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && rect.Contains(mousePos)) { switch (Event.current.button) { case 0: // Left mouse button ed.selectedTrack = track; ed.selectedClip = null; break; case 1: // Right mouse button EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneTrack/", new MenuCommand(track)); Event.current.Use(); break; default: break; } Event.current.Use(); } } /// <summary> /// Displays a clip. /// </summary> /// <param name="trackRect">The Rect of the track the clip sits on.</param> /// <param name="track">The track the clip sits on.</param> /// <param name="clip">The clip to display.</param> void DisplayClip (Rect trackRect, CutsceneTrack track, CutsceneClip clip) { const float trimWidth = 5f; GUIStyle clipStyle = ed.style.GetStyle("Selected Clip"); // Set the clip style if this isn't the selected clip (selected clips all share the same style) if (clip != ed.selectedClip) { switch (clip.type) { case Cutscene.MediaType.Shots: clipStyle = ed.style.GetStyle("Shot Clip"); break; case Cutscene.MediaType.Actors: clipStyle = ed.style.GetStyle("Actor Clip"); break; case Cutscene.MediaType.Audio: clipStyle = ed.style.GetStyle("Audio Clip"); break; default: // Cutscene.MediaType.Subtitles clipStyle = ed.style.GetStyle("Subtitle Clip"); break; } } Rect rect = new Rect((trackRect.x + clip.timelineStart) * ed.timelineZoom, trackRect.y + 1, clip.duration * ed.timelineZoom, clipStyle.fixedHeight); GUI.BeginGroup(rect, clipStyle); GUIContent clipLabel = new GUIContent(clip.name, "Clip: " + clip.name + "\nDuration: " + clip.duration + "\nTimeline start: " + clip.timelineStart + "\nTimeline end: " + (clip.timelineStart + clip.duration)); Rect clipLabelRect = new Rect(clipStyle.contentOffset.x, 0, rect.width - clipStyle.contentOffset.x, rect.height); GUI.Label(clipLabelRect, clipLabel); GUI.EndGroup(); // Handle mouse clicks Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { switch (Event.current.button) { case 0: // Left mouse button ed.selectedClip = clip; ed.selectedTrack = track; break; case 1: // Right mouse button EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneClip/", new MenuCommand(clip)); Event.current.Use(); break; default: break; } } if (clip.setToDelete) { ed.selectedTrack.clips.Remove(clip); return; } // Don't allow actions to be performed on the clip if the track is disabled or locked if (!track.enabled || track.locked) { return; } switch (ed.currentTool) { case Tool.MoveResize: // Define edit areas, adding custom cursors when hovered over // Move Rect move = new Rect(rect.x + trimWidth, rect.y, rect.width - (2 * trimWidth), rect.height); EditorGUIUtility.AddCursorRect(move, MouseCursor.SlideArrow); // Resize left Rect resizeLeft = new Rect(rect.x, rect.y, trimWidth, rect.height); EditorGUIUtility.AddCursorRect(resizeLeft, MouseCursor.ResizeHorizontal); // Resize right Rect resizeRight = new Rect(rect.xMax - trimWidth, rect.y, trimWidth, rect.height); EditorGUIUtility.AddCursorRect(resizeRight, MouseCursor.ResizeHorizontal); if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { ed.dragClip = clip; - - if (move.Contains(Event.current.mousePosition)) { // Move + + // Move + if (move.Contains(Event.current.mousePosition)) { ed.dragEvent = DragEvent.Move; EDebug.Log("Cutscene Editor: starting clip move"); - } else if (resizeLeft.Contains(Event.current.mousePosition)) { // Resize left + // Resize left + } else if (resizeLeft.Contains(Event.current.mousePosition)) { ed.dragEvent = DragEvent.ResizeLeft; EDebug.Log("Cutscene Editor: starting clip resize left"); - } else if (resizeRight.Contains(Event.current.mousePosition)) { // Resize right + // Resize right + } else if (resizeRight.Contains(Event.current.mousePosition)) { ed.dragEvent = DragEvent.ResizeRight; EDebug.Log("Cutscene Editor: starting clip resize right"); } Event.current.Use(); } else if (Event.current.type == EventType.MouseDrag && ed.dragClip == clip) { float shift = Event.current.delta.x / ed.timelineZoom; switch (ed.dragEvent) { case DragEvent.Move: float newPos = clip.timelineStart + shift; // Left collisions CutsceneClip leftCollision = track.ContainsClipAtTime(newPos, clip); if (leftCollision != null) { newPos = leftCollision.timelineStart + leftCollision.duration; } // Right collisions CutsceneClip rightCollision = track.ContainsClipAtTime(newPos + clip.duration, clip); if (rightCollision != null) { newPos = rightCollision.timelineStart - clip.duration; } if (newPos + clip.duration > ed.scene.duration) { newPos = ed.scene.duration - clip.duration; } clip.SetTimelineStart(newPos); break; case DragEvent.ResizeLeft: clip.SetTimelineStart(clip.timelineStart + shift); clip.SetInPoint(clip.inPoint + shift); // TODO Improve collision behaviour CutsceneClip leftResizeCollision = track.ContainsClipAtTime(clip.timelineStart, clip); if (leftResizeCollision != null) { clip.SetTimelineStart(leftResizeCollision.timelineStart + leftResizeCollision.duration); } break; case DragEvent.ResizeRight: float newOut = clip.outPoint + shift; // Right collisions CutsceneClip rightResizeCollision = track.ContainsClipAtTime(clip.timelineStart + clip.duration + shift, clip); if (rightResizeCollision != null) { newOut = rightResizeCollision.timelineStart - clip.timelineStart + clip.inPoint; } clip.SetOutPoint(newOut); break; default: break; } Event.current.Use(); } else if (Event.current.type == EventType.MouseUp) { ed.dragClip = null; Event.current.Use(); } break; case Tool.Scissors: // TODO Switch to something better than the text cursor, if possible EditorGUIUtility.AddCursorRect(rect, MouseCursor.Text); if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { SplitClip(track, clip, Event.current.mousePosition); Event.current.Use(); } break; default: break; } } /// <summary> /// Splits a clip into two separate ones. /// </summary> /// <param name="track">The track the clip is sitting on.</param> /// <param name="clip">The clip to split.</param> /// <param name="mousePosition">The position of the mouse when the split operation occurred.</param> /// <returns>The new clip.</returns> CutsceneClip SplitClip (CutsceneTrack track, CutsceneClip clip, Vector2 mousePosition) { float splitPoint = mousePosition.x / ed.timelineZoom; return CutsceneTimeline.SplitClipAtTime(splitPoint, track, clip); } /// <summary> /// Draws the in, out, and playhead lines. /// </summary> /// <param name="rect">The timeline's Rect.</param> void DrawLines (Rect rect) { DrawPlayhead(rect); Handles.color = inOutPointColour; DrawInLine(rect); DrawOutLine(rect); } /// <summary> /// Draws the playhead over the timeline. /// </summary> /// <param name="rect">The timeline's Rect.</param> void DrawPlayhead (Rect rect) { Handles.color = Color.black; float pos = ed.scene.playhead * ed.timelineZoom; - Vector3 timelineTop = new Vector3(pos, 0); + Vector3 timelineTop = new Vector3(pos, 0); Vector3 timelineBottom = new Vector3(pos, rect.yMax); Handles.DrawLine(timelineTop, timelineBottom); } /// <summary> /// Draws the in point line over the timeline. /// </summary> /// <param name="rect">The timeline's Rect.</param> void DrawInLine (Rect rect) { float pos = ed.scene.inPoint * ed.timelineZoom; - Vector3 top = new Vector3(pos, 0); + Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, rect.yMax); Handles.DrawLine(top, bottom); } /// <summary> /// Draws the out point line over the timeline. /// </summary> /// <param name="rect">The timeline's Rect.</param> void DrawOutLine (Rect rect) { float pos = ed.scene.outPoint * ed.timelineZoom; - Vector3 top = new Vector3(pos, 0); + Vector3 top = new Vector3(pos, 0); Vector3 bottom = new Vector3(pos, rect.yMax); Handles.DrawLine(top, bottom); } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/Cutscene.cs b/Cutscene Ed/Scripts/Cutscene.cs index 0c8cac5..4cf9133 100755 --- a/Cutscene Ed/Scripts/Cutscene.cs +++ b/Cutscene Ed/Scripts/Cutscene.cs @@ -1,412 +1,412 @@ using UnityEngine; using System.Collections; using System.Collections.Generic; // Functions to be run when the cutscene starts and finishes public delegate void CutsceneStart(); public delegate void CutscenePause(); public delegate void CutsceneEnd(); [RequireComponent(typeof(Animation))] public class Cutscene : MonoBehaviour { - public float duration = 30f; - public float inPoint = 0f; - public float outPoint = 30f; - public bool stopPlayer = true; + public float duration = 30f; + public float inPoint = 0f; + public float outPoint = 30f; + public bool stopPlayer = true; public GameObject player; public GUIStyle subtitleStyle; public Rect subtitlePosition = new Rect(0, 0, 400, 200); - public CutsceneStart startFunction { get; set; } - public CutscenePause pauseFunction { get; set; } - public CutsceneEnd endFunction { get; set; } + public CutsceneStart startFunction { get; set; } + public CutscenePause pauseFunction { get; set; } + public CutsceneEnd endFunction { get; set; } public enum MediaType { Shots, Actors, Audio, Subtitles } public enum EffectType { Filters, Transitions } public CutsceneTrack[] tracks { get { return GetComponentsInChildren<CutsceneTrack>(); } } public CutsceneShot[] shots { get { return GetComponentsInChildren<CutsceneShot>(); } } public CutsceneActor[] actors { get { return GetComponentsInChildren<CutsceneActor>(); } } public CutsceneAudio[] audioSources { get { return GetComponentsInChildren<CutsceneAudio>(); } } public CutsceneSubtitle[] subtitles { get { return GetComponentsInChildren<CutsceneSubtitle>(); } } CutsceneSubtitle currentSubtitle; public float playhead { get { return animation["master"].time; } set { animation["master"].time = Mathf.Clamp(value, 0f, duration); } } [HideInInspector] public AnimationClip masterClip; void Start () { SetupMasterAnimationClip(); SetupTrackAnimationClips(); DisableCameras(); DisableAudio(); } void OnGUI () { /// Displays the current subtitle if there is one if (currentSubtitle == null) { return; } GUI.BeginGroup(subtitlePosition, subtitleStyle); GUILayout.Label(currentSubtitle.dialog, subtitleStyle); GUI.EndGroup(); } /// <summary> /// Visually shows the cutscene in the scene view. /// </summary> void OnDrawGizmos () { Gizmos.DrawIcon(transform.position, "Cutscene.png"); } /// <summary> /// Sets the in and out points of the master animation clip. /// </summary> void SetupMasterAnimationClip () { animation.RemoveClip("master"); // Create a new event for when the scene starts AnimationEvent start = new AnimationEvent(); start.time = inPoint; start.functionName = "SceneStart"; masterClip.AddEvent(start); // Create a new event for when the scene finishes AnimationEvent finish = new AnimationEvent(); finish.time = outPoint; finish.functionName = "SceneFinish"; masterClip.AddEvent(finish); animation.AddClip(masterClip, "master"); animation["master"].time = inPoint; } /// <summary> /// Adds each track's animation clip to the main animation. /// </summary> void SetupTrackAnimationClips () { foreach (CutsceneTrack t in tracks) { if (t.enabled) { AnimationClip trackAnimationClip = t.track; string clipName = "track" + t.id; animation.AddClip(trackAnimationClip, clipName); animation[clipName].time = inPoint; } } } /// <summary> /// Turns off all child cameras so that they don't display before the cutscene starts. /// </summary> void DisableCameras () { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { cam.enabled = false; } } /// <summary> /// Turns off all child cameras except for the one specified. /// </summary> /// <param name="exemptCam">The camera to stay enabled.</param> void DisableOtherCameras (Camera exemptCam) { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { if (cam != exemptCam) { cam.enabled = false; } } } /// <summary> /// Keeps all child audio sources from playing once the game starts. /// </summary> void DisableAudio () { AudioSource[] childAudio = GetComponentsInChildren<AudioSource>(); foreach (AudioSource audio in childAudio) { audio.playOnAwake = false; } } /// <summary> /// Starts playing the cutscene. /// </summary> public void PlayCutscene () { // Set up and play the master animation animation["master"].layer = 0; animation.Play("master"); // Set up and play each individual track for (int i = 0; i < tracks.Length; i++) { if (tracks[i].enabled) { animation["track" + tracks[i].id].layer = i + 1; animation.Play("track" + tracks[i].id); } } } /// <summary> /// Pauses the cutscene. /// </summary> public void PauseCutscene () { pauseFunction(); // TODO actually pause the cutscene } /// <summary> /// Called when the scene starts. /// </summary> void SceneStart () { if (startFunction != null) { startFunction(); } // Stop the player from being able to move if (player != null && stopPlayer) { EDebug.Log("Cutscene: deactivating player"); player.active = false; } DisableCameras(); currentSubtitle = null; EDebug.Log("Cutscene: scene started at " + animation["master"].time); } /// <summary> /// Called when the scene ends. /// </summary> void SceneFinish () { if (endFunction != null) { endFunction(); } // Allow the player to move again if (player != null) { EDebug.Log("Cutscene: activating player"); player.active = true; } EDebug.Log("Cutscene: scene finished at " + animation["master"].time); } /// <summary> /// Shows the specified shot. /// </summary> /// <param name="clip">The shot to show.</summary> void PlayShot (CutsceneClip clip) { Camera cam = ((CutsceneShot)clip.master).camera; cam.enabled = true; StartCoroutine(StopShot(cam, clip.duration)); EDebug.Log("Cutscene: showing camera " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the shot from playing at its out point. /// </summary> /// <param name="shot">The shot to stop.</param> /// <param name="duration">The time at which to stop the shot.</param> IEnumerator StopShot (Camera cam, float duration) { yield return new WaitForSeconds(duration); cam.enabled = false; EDebug.Log("Cutscene: stopping shot at " + animation["master"].time); } /// <summary> /// Plays the specified actor. /// </summary> /// <param name="clip">The actor to play.</summary> void PlayActor (CutsceneClip clip) { CutsceneActor actor = ((CutsceneActor)clip.master); AnimationClip anim = actor.anim; GameObject go = ((CutsceneActor)clip.master).go; go.animation[anim.name].time = clip.inPoint; go.animation.Play(anim.name); StartCoroutine(StopActor(actor, clip.duration)); EDebug.Log("Cutscene: showing actor " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the actor from playing at its out point. /// </summary> /// <param name="actor">The actor to stop.</param> /// <param name="duration">The time at which to stop the actor.</param> IEnumerator StopActor (CutsceneActor actor, float duration) { yield return new WaitForSeconds(duration); actor.go.animation.Stop(actor.anim.name); EDebug.Log("Cutscene: stopping actor at " + animation["master"].time); } /// <summary> /// Plays the specified audio. /// </summary> /// <param name="clip">The audio to play.</summary> void PlayAudio (CutsceneClip clip) { AudioSource aud = ((CutsceneAudio)clip.master).audio; aud.Play(); aud.time = clip.inPoint; // Set the point at which the clip plays StartCoroutine(StopAudio(aud, clip.duration)); // Set the point at which the clip stops EDebug.Log("Playing audio " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the audio from playing at its out point. /// </summary> /// <param name="aud">The audio source to stop.</param> /// <param name="duration">The time at which to stop the audio.</param> IEnumerator StopAudio (AudioSource aud, float duration) { yield return new WaitForSeconds(duration); aud.Stop(); } /// <summary> /// Displays the specified subtitle. /// </summary> /// <param name="clip">The subtitle to display.</summary> void PlaySubtitle (CutsceneClip clip) { currentSubtitle = (CutsceneSubtitle)clip.master; EDebug.Log("Displaying subtitle " + clip.name + " at " + animation["master"].time); StartCoroutine(StopSubtitle(clip.duration)); } /// <summary> /// Stops the subtitle from displaying at its out point. /// </summary> /// <param name="duration">The time at which to stop the audio.</param> IEnumerator StopSubtitle (float duration) { yield return new WaitForSeconds(duration); currentSubtitle = null; } /// <summary> /// Stops all subtitles from displaying by setting the current subtitle to null. /// </summary> void StopSubtitle () { currentSubtitle = null; } /// <summary> /// Called when the clip type is unknown. /// </summary> /// <remarks>For debugging only; ideally this will never be called.</remarks> void UnknownFunction (CutsceneClip clip) { EDebug.Log("Cutscene: unknown function call from clip " + clip.name); } /// <summary> /// Creates a new CutsceneShot object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneShot object.</returns> public CutsceneShot NewShot () { GameObject shot = new GameObject("Camera", typeof(Camera), typeof(CutsceneShot)); // Keep the camera from displaying before it's placed on the timeline shot.camera.enabled = false; // Set the parent of the new shot to the Shots object shot.transform.parent = transform.Find("Shots"); EDebug.Log("Cutscene Editor: added new shot"); return shot.GetComponent<CutsceneShot>(); } /// <summary> /// Creates a new CutsceneActor object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneActor object.</returns> public CutsceneActor NewActor (AnimationClip anim, GameObject go) { CutsceneActor actor = GameObject.Find("Actors").AddComponent<CutsceneActor>(); actor.name = anim.name; actor.anim = anim; actor.go = go; EDebug.Log("Cutscene Editor: adding new actor"); return actor; } /// <summary> /// Creates a new CutsceneAudio object and attaches it to a new game object as a child of the Audio game object. /// </summary> /// <param name="clip">The audio clip to be attached the CutsceneAudio object.</param> /// <returns>The new CutsceneAudio object.</returns> public CutsceneAudio NewAudio (AudioClip clip) { GameObject aud = new GameObject(clip.name, typeof(AudioSource), typeof(CutsceneAudio)); aud.audio.clip = clip; // Keep the audio from playing when the game starts aud.audio.playOnAwake = false; // Set the parent of the new audio to the "Audio" object aud.transform.parent = transform.Find("Audio"); EDebug.Log("Cutscene Editor: added new audio"); return aud.GetComponent<CutsceneAudio>(); } /// <summary> /// Creates a new CutsceneSubtitle object and attaches it to the Subtitles game object. /// </summary> /// <param name="dialog">The dialog to be displayed.</param> /// <returns>The new CutsceneSubtitle object.</returns> public CutsceneSubtitle NewSubtitle (string dialog) { CutsceneSubtitle subtitle = GameObject.Find("Subtitles").AddComponent<CutsceneSubtitle>(); subtitle.dialog = dialog; EDebug.Log("Cutscene Editor: added new subtitle"); return subtitle; } /// <summary> /// Attaches a new track component to the cutscene. /// </summary> /// <returns>The new cutscene track.</returns> public CutsceneTrack AddTrack (Cutscene.MediaType type) { int id = 0; // Ensure the new track has a unique ID foreach (CutsceneTrack t in tracks) { if (id == t.id) { id++; } else { break; } } CutsceneTrack track = gameObject.AddComponent<CutsceneTrack>(); - track.id = id; + track.id = id; track.type = type; track.name = CutsceneTrack.DefaultName(type); EDebug.Log("Cutscene Editor: added new track of type " + type); return track; } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneActor.cs b/Cutscene Ed/Scripts/CutsceneActor.cs index 5da0d14..cf0362c 100644 --- a/Cutscene Ed/Scripts/CutsceneActor.cs +++ b/Cutscene Ed/Scripts/CutsceneActor.cs @@ -1,6 +1,6 @@ using UnityEngine; public class CutsceneActor : CutsceneMedia { public AnimationClip anim; - public GameObject go; + public GameObject go; } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneClip.cs b/Cutscene Ed/Scripts/CutsceneClip.cs index 800d5f5..8d3959c 100644 --- a/Cutscene Ed/Scripts/CutsceneClip.cs +++ b/Cutscene Ed/Scripts/CutsceneClip.cs @@ -1,114 +1,114 @@ using UnityEngine; using System; public class CutsceneClip : ScriptableObject { public CutsceneMedia master; - public float timelineStart = 0f; - public float inPoint = 0f; - public float outPoint = 5f; // Default 5 seconds + public float timelineStart = 0f; + public float inPoint = 0f; + public float outPoint = 5f; // Default 5 seconds public float timelineEnd { get { return timelineStart + duration; } } float maxOutPoint { get { float max = Mathf.Infinity; if (master is CutsceneActor) { max = ((CutsceneActor)master).anim.length; } else if (master is CutsceneAudio) { max = ((CutsceneAudio)master).gameObject.audio.clip.length; } return max; } } public void SetTimelineStart (float value) { timelineStart = Mathf.Clamp(value, 0f, Mathf.Infinity); } public void SetInPoint (float value) { inPoint = Mathf.Clamp(value, 0f, outPoint); } public void SetOutPoint (float value) { outPoint = Mathf.Clamp(value, inPoint, maxOutPoint); } [HideInInspector] public bool setToDelete = false; // An ugly workaround used for deleting clips // Read only public float duration { get { return outPoint - inPoint; } } public string startFunction { get { // Determine which function to call based on the master object type if (master is CutsceneShot) { return "PlayShot"; } else if (master is CutsceneActor) { return "PlayActor"; } else if (master is CutsceneAudio) { return "PlayAudio"; } else if (master is CutsceneSubtitle) { return "PlaySubtitle"; } else { return "UnknownFunction"; } } } public Cutscene.MediaType type { get { if (master is CutsceneShot) { return Cutscene.MediaType.Shots; } else if (master is CutsceneActor) { return Cutscene.MediaType.Actors; } else if (master is CutsceneAudio) { return Cutscene.MediaType.Audio; } else { // master is CutsceneSubtitles return Cutscene.MediaType.Subtitles; } } } public CutsceneClip (CutsceneMedia master) { this.master = master; if (master is CutsceneSubtitle) { name = ((CutsceneSubtitle)master).dialog; } else { name = master.name; } if (maxOutPoint != Mathf.Infinity) { outPoint = maxOutPoint; } } /// <summary> /// Gets a clone of the current clip. /// </summary> /// <returns>The clip copy.</returns> public CutsceneClip GetCopy () { CutsceneClip copy = new CutsceneClip(master); copy.timelineStart = timelineStart; copy.SetInPoint(inPoint); copy.outPoint = outPoint; return copy; } /// <summary> /// Adds an effect to the clip. /// </summary> /// <param name="effect">The transitions or filter.</param> public void ApplyEffect (Type effect) { // Only add the effect if the master object is a camera shot if (master is CutsceneShot) { master.gameObject.AddComponent(effect); } } } \ No newline at end of file
mminer/silverscreen
77ea3cf358e2190c3e3e948e17bdfb920b5e6ece
Fixed issue #15 where actors on timeline are all named "Actors".
diff --git a/Cutscene Ed/Scripts/Cutscene.cs b/Cutscene Ed/Scripts/Cutscene.cs index 4345754..0c8cac5 100755 --- a/Cutscene Ed/Scripts/Cutscene.cs +++ b/Cutscene Ed/Scripts/Cutscene.cs @@ -1,411 +1,412 @@ using UnityEngine; using System.Collections; using System.Collections.Generic; // Functions to be run when the cutscene starts and finishes public delegate void CutsceneStart(); public delegate void CutscenePause(); public delegate void CutsceneEnd(); [RequireComponent(typeof(Animation))] public class Cutscene : MonoBehaviour { public float duration = 30f; public float inPoint = 0f; public float outPoint = 30f; public bool stopPlayer = true; public GameObject player; public GUIStyle subtitleStyle; public Rect subtitlePosition = new Rect(0, 0, 400, 200); public CutsceneStart startFunction { get; set; } public CutscenePause pauseFunction { get; set; } public CutsceneEnd endFunction { get; set; } public enum MediaType { Shots, Actors, Audio, Subtitles } public enum EffectType { Filters, Transitions } public CutsceneTrack[] tracks { get { return GetComponentsInChildren<CutsceneTrack>(); } } public CutsceneShot[] shots { get { return GetComponentsInChildren<CutsceneShot>(); } } public CutsceneActor[] actors { get { return GetComponentsInChildren<CutsceneActor>(); } } public CutsceneAudio[] audioSources { get { return GetComponentsInChildren<CutsceneAudio>(); } } public CutsceneSubtitle[] subtitles { get { return GetComponentsInChildren<CutsceneSubtitle>(); } } CutsceneSubtitle currentSubtitle; public float playhead { get { return animation["master"].time; } set { animation["master"].time = Mathf.Clamp(value, 0f, duration); } } [HideInInspector] public AnimationClip masterClip; void Start () { SetupMasterAnimationClip(); SetupTrackAnimationClips(); DisableCameras(); DisableAudio(); } void OnGUI () { /// Displays the current subtitle if there is one if (currentSubtitle == null) { return; } GUI.BeginGroup(subtitlePosition, subtitleStyle); GUILayout.Label(currentSubtitle.dialog, subtitleStyle); GUI.EndGroup(); } /// <summary> /// Visually shows the cutscene in the scene view. /// </summary> void OnDrawGizmos () { Gizmos.DrawIcon(transform.position, "Cutscene.png"); } /// <summary> /// Sets the in and out points of the master animation clip. /// </summary> void SetupMasterAnimationClip () { animation.RemoveClip("master"); // Create a new event for when the scene starts AnimationEvent start = new AnimationEvent(); start.time = inPoint; start.functionName = "SceneStart"; masterClip.AddEvent(start); // Create a new event for when the scene finishes AnimationEvent finish = new AnimationEvent(); finish.time = outPoint; finish.functionName = "SceneFinish"; masterClip.AddEvent(finish); animation.AddClip(masterClip, "master"); animation["master"].time = inPoint; } /// <summary> /// Adds each track's animation clip to the main animation. /// </summary> void SetupTrackAnimationClips () { foreach (CutsceneTrack t in tracks) { if (t.enabled) { AnimationClip trackAnimationClip = t.track; string clipName = "track" + t.id; animation.AddClip(trackAnimationClip, clipName); animation[clipName].time = inPoint; } } } /// <summary> /// Turns off all child cameras so that they don't display before the cutscene starts. /// </summary> void DisableCameras () { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { cam.enabled = false; } } /// <summary> /// Turns off all child cameras except for the one specified. /// </summary> /// <param name="exemptCam">The camera to stay enabled.</param> void DisableOtherCameras (Camera exemptCam) { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { if (cam != exemptCam) { cam.enabled = false; } } } /// <summary> /// Keeps all child audio sources from playing once the game starts. /// </summary> void DisableAudio () { AudioSource[] childAudio = GetComponentsInChildren<AudioSource>(); foreach (AudioSource audio in childAudio) { audio.playOnAwake = false; } } /// <summary> /// Starts playing the cutscene. /// </summary> public void PlayCutscene () { // Set up and play the master animation animation["master"].layer = 0; animation.Play("master"); // Set up and play each individual track for (int i = 0; i < tracks.Length; i++) { if (tracks[i].enabled) { animation["track" + tracks[i].id].layer = i + 1; animation.Play("track" + tracks[i].id); } } } /// <summary> /// Pauses the cutscene. /// </summary> public void PauseCutscene () { pauseFunction(); // TODO actually pause the cutscene } /// <summary> /// Called when the scene starts. /// </summary> void SceneStart () { if (startFunction != null) { startFunction(); } // Stop the player from being able to move if (player != null && stopPlayer) { EDebug.Log("Cutscene: deactivating player"); player.active = false; } DisableCameras(); currentSubtitle = null; EDebug.Log("Cutscene: scene started at " + animation["master"].time); } /// <summary> /// Called when the scene ends. /// </summary> void SceneFinish () { if (endFunction != null) { endFunction(); } // Allow the player to move again if (player != null) { EDebug.Log("Cutscene: activating player"); player.active = true; } EDebug.Log("Cutscene: scene finished at " + animation["master"].time); } /// <summary> /// Shows the specified shot. /// </summary> /// <param name="clip">The shot to show.</summary> void PlayShot (CutsceneClip clip) { Camera cam = ((CutsceneShot)clip.master).camera; cam.enabled = true; StartCoroutine(StopShot(cam, clip.duration)); EDebug.Log("Cutscene: showing camera " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the shot from playing at its out point. /// </summary> /// <param name="shot">The shot to stop.</param> /// <param name="duration">The time at which to stop the shot.</param> IEnumerator StopShot (Camera cam, float duration) { yield return new WaitForSeconds(duration); cam.enabled = false; EDebug.Log("Cutscene: stopping shot at " + animation["master"].time); } /// <summary> /// Plays the specified actor. /// </summary> /// <param name="clip">The actor to play.</summary> void PlayActor (CutsceneClip clip) { CutsceneActor actor = ((CutsceneActor)clip.master); AnimationClip anim = actor.anim; GameObject go = ((CutsceneActor)clip.master).go; go.animation[anim.name].time = clip.inPoint; go.animation.Play(anim.name); StartCoroutine(StopActor(actor, clip.duration)); EDebug.Log("Cutscene: showing actor " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the actor from playing at its out point. /// </summary> /// <param name="actor">The actor to stop.</param> /// <param name="duration">The time at which to stop the actor.</param> IEnumerator StopActor (CutsceneActor actor, float duration) { yield return new WaitForSeconds(duration); actor.go.animation.Stop(actor.anim.name); EDebug.Log("Cutscene: stopping actor at " + animation["master"].time); } /// <summary> /// Plays the specified audio. /// </summary> /// <param name="clip">The audio to play.</summary> void PlayAudio (CutsceneClip clip) { AudioSource aud = ((CutsceneAudio)clip.master).audio; aud.Play(); aud.time = clip.inPoint; // Set the point at which the clip plays StartCoroutine(StopAudio(aud, clip.duration)); // Set the point at which the clip stops EDebug.Log("Playing audio " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the audio from playing at its out point. /// </summary> /// <param name="aud">The audio source to stop.</param> /// <param name="duration">The time at which to stop the audio.</param> IEnumerator StopAudio (AudioSource aud, float duration) { yield return new WaitForSeconds(duration); aud.Stop(); } /// <summary> /// Displays the specified subtitle. /// </summary> /// <param name="clip">The subtitle to display.</summary> void PlaySubtitle (CutsceneClip clip) { currentSubtitle = (CutsceneSubtitle)clip.master; EDebug.Log("Displaying subtitle " + clip.name + " at " + animation["master"].time); StartCoroutine(StopSubtitle(clip.duration)); } /// <summary> /// Stops the subtitle from displaying at its out point. /// </summary> /// <param name="duration">The time at which to stop the audio.</param> IEnumerator StopSubtitle (float duration) { yield return new WaitForSeconds(duration); currentSubtitle = null; } /// <summary> /// Stops all subtitles from displaying by setting the current subtitle to null. /// </summary> void StopSubtitle () { currentSubtitle = null; } /// <summary> /// Called when the clip type is unknown. /// </summary> /// <remarks>For debugging only; ideally this will never be called.</remarks> void UnknownFunction (CutsceneClip clip) { EDebug.Log("Cutscene: unknown function call from clip " + clip.name); } /// <summary> /// Creates a new CutsceneShot object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneShot object.</returns> public CutsceneShot NewShot () { GameObject shot = new GameObject("Camera", typeof(Camera), typeof(CutsceneShot)); // Keep the camera from displaying before it's placed on the timeline shot.camera.enabled = false; // Set the parent of the new shot to the Shots object shot.transform.parent = transform.Find("Shots"); EDebug.Log("Cutscene Editor: added new shot"); return shot.GetComponent<CutsceneShot>(); } /// <summary> /// Creates a new CutsceneActor object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneActor object.</returns> public CutsceneActor NewActor (AnimationClip anim, GameObject go) { CutsceneActor actor = GameObject.Find("Actors").AddComponent<CutsceneActor>(); + actor.name = anim.name; actor.anim = anim; actor.go = go; EDebug.Log("Cutscene Editor: adding new actor"); return actor; } /// <summary> /// Creates a new CutsceneAudio object and attaches it to a new game object as a child of the Audio game object. /// </summary> /// <param name="clip">The audio clip to be attached the CutsceneAudio object.</param> /// <returns>The new CutsceneAudio object.</returns> public CutsceneAudio NewAudio (AudioClip clip) { GameObject aud = new GameObject(clip.name, typeof(AudioSource), typeof(CutsceneAudio)); aud.audio.clip = clip; // Keep the audio from playing when the game starts aud.audio.playOnAwake = false; // Set the parent of the new audio to the "Audio" object aud.transform.parent = transform.Find("Audio"); EDebug.Log("Cutscene Editor: added new audio"); return aud.GetComponent<CutsceneAudio>(); } /// <summary> /// Creates a new CutsceneSubtitle object and attaches it to the Subtitles game object. /// </summary> /// <param name="dialog">The dialog to be displayed.</param> /// <returns>The new CutsceneSubtitle object.</returns> public CutsceneSubtitle NewSubtitle (string dialog) { CutsceneSubtitle subtitle = GameObject.Find("Subtitles").AddComponent<CutsceneSubtitle>(); subtitle.dialog = dialog; EDebug.Log("Cutscene Editor: added new subtitle"); return subtitle; } /// <summary> /// Attaches a new track component to the cutscene. /// </summary> /// <returns>The new cutscene track.</returns> public CutsceneTrack AddTrack (Cutscene.MediaType type) { int id = 0; // Ensure the new track has a unique ID foreach (CutsceneTrack t in tracks) { if (id == t.id) { id++; } else { break; } } CutsceneTrack track = gameObject.AddComponent<CutsceneTrack>(); track.id = id; track.type = type; track.name = CutsceneTrack.DefaultName(type); EDebug.Log("Cutscene Editor: added new track of type " + type); return track; } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneActor.cs b/Cutscene Ed/Scripts/CutsceneActor.cs index df1fbf4..5da0d14 100644 --- a/Cutscene Ed/Scripts/CutsceneActor.cs +++ b/Cutscene Ed/Scripts/CutsceneActor.cs @@ -1,10 +1,6 @@ using UnityEngine; public class CutsceneActor : CutsceneMedia { public AnimationClip anim; public GameObject go; - - public new string name { - get { return anim.name; } - } } \ No newline at end of file
mminer/silverscreen
8dc54017f2dfa58b97a8a71664655c0d9db02f6c
Simplified code, taking advantage of some C# 3.0 features
diff --git a/Cutscene Ed/Editor/BugReporter.cs b/Cutscene Ed/Editor/BugReporter.cs index 2c790cd..77c9cde 100755 --- a/Cutscene Ed/Editor/BugReporter.cs +++ b/Cutscene Ed/Editor/BugReporter.cs @@ -1,45 +1,42 @@ using UnityEditor; using UnityEngine; public class BugReporter : EditorWindow { string email = ""; string details = ""; readonly GUIContent emailLabel = new GUIContent("Your Email", "If we require additional information, we'll contact you at the supplied address (optional)."); readonly GUIContent submitLabel = new GUIContent("Submit", "Send this bug report."); /// <summary> /// Adds "Bug Reporter" to the Window menu. /// </summary> [MenuItem("Window/Bug Reporter")] public static void OpenEditor () { // Get existing open window or if none, make a new one - BugReporter window = GetWindow(typeof(BugReporter), true, "Bug Reporter") as BugReporter; - if (window != null) { - window.Show(); - } + GetWindow<BugReporter>(true, "Bug Reporter").Show(); } void OnGUI () { GUILayout.Label("Please take a minute to tell us what happened in as much detail as possible. This makes it possible for us to fix the problem."); EditorGUILayout.Separator(); email = EditorGUILayout.TextField(emailLabel, email); EditorGUILayout.Separator(); GUILayout.Label("Problem Details:"); details = EditorGUILayout.TextArea(details); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(submitLabel, GUILayout.ExpandWidth(false))) { - // Do something + // TODO Send bug report Debug.Log("Bug report sent."); } EditorGUILayout.EndHorizontal(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneAddActor.cs b/Cutscene Ed/Editor/CutsceneAddActor.cs index 5deca1f..67263ed 100755 --- a/Cutscene Ed/Editor/CutsceneAddActor.cs +++ b/Cutscene Ed/Editor/CutsceneAddActor.cs @@ -1,92 +1,90 @@ using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; class CutsceneAddActor : ScriptableWizard { GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; AnimationClip selected; GameObject selectedGO; /// <summary> /// Creates a wizard for adding a new actor. /// </summary> [MenuItem("Component/Cutscene/Add Media/Actor")] public static void CreateWizard () { - DisplayWizard("Add Actor", typeof(CutsceneAddActor), "Add"); + DisplayWizard<CutsceneAddActor>("Add Actor", "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Actor", true)] static bool ValidateCreateWizard () { return CutsceneEditor.CutsceneSelected; } void OnGUI () { OnWizardUpdate(); - // The generic version of FindObjectsOfType appears to be broken Animation[] animations = (Animation[])FindObjectsOfType(typeof(Animation)); EditorGUILayout.BeginVertical(style.GetStyle("List Container")); foreach (Animation anim in animations) { GUILayout.Label(anim.gameObject.name, EditorStyles.largeLabel); foreach (AnimationClip clip in AnimationUtility.GetAnimationClips(anim)) { GUIStyle itemStyle = GUIStyle.none; if (clip == selected) { itemStyle = style.GetStyle("Selected List Item"); } - + Rect rect = EditorGUILayout.BeginHorizontal(itemStyle); GUIContent itemLabel = new GUIContent(clip.name, EditorGUIUtility.ObjectContent(null, typeof(Animation)).image); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); // Select when clicked if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { selected = clip; selectedGO = anim.gameObject; EditorGUIUtility.PingObject(anim); Event.current.Use(); Repaint(); } } } EditorGUILayout.EndVertical(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true; } void OnWizardUpdate () { helpString = "Choose an animation to add."; // Only valid if an animation has been selected - isValid = selected == null ? false : true; + isValid = selected != null; } /// <summary> /// Adds the new actor to the cutscene. /// </summary> void OnWizardCreate () { - Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); - scene.NewActor(selected, selectedGO); + Selection.activeGameObject.GetComponent<Cutscene>().NewActor(selected, selectedGO); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneAddAudio.cs b/Cutscene Ed/Editor/CutsceneAddAudio.cs index ca3ba28..9af804a 100755 --- a/Cutscene Ed/Editor/CutsceneAddAudio.cs +++ b/Cutscene Ed/Editor/CutsceneAddAudio.cs @@ -1,88 +1,87 @@ using UnityEngine; using UnityEditor; class CutsceneAddAudio : ScriptableWizard { //GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; AudioClip[] audioClips; AudioClip selected; /// <summary> /// Creates a wizard for adding a new audio clip. /// </summary> [MenuItem("Component/Cutscene/Add Media/Audio")] public static void CreateWizard () { - DisplayWizard("Add Audio", typeof(CutsceneAddAudio), "Add"); + DisplayWizard<CutsceneAddAudio>("Add Audio", "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Audio", true)] static bool ValidateCreateWizard () { return CutsceneEditor.CutsceneSelected; } void OnGUI () { OnWizardUpdate(); // Display temporary workaround info GUILayout.Label("To add an audio clip from the Project view, drag and drop it to the audio pane. This is a temporary workaround and will hopefully be fixed soon."); // TODO Make LoadAllAssetsAtPath work /* audioClips = (AudioClip[])AssetDatabase.LoadAllAssetsAtPath("Assets"); Debug.Log("Objects length: " + audioClips.Length); EditorGUILayout.BeginVertical(style.GetStyle("List Container")); foreach (AudioClip aud in audioClips) { GUIStyle itemStyle = aud == selected ? style.GetStyle("Selected List Item") : GUIStyle.none; Rect rect = EditorGUILayout.BeginHorizontal(itemStyle); GUIContent itemLabel = new GUIContent(aud.name, EditorGUIUtility.ObjectContent(null, typeof(AudioClip)).image); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); // Select when clicked if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { selected = aud; EditorGUIUtility.PingObject(aud); Event.current.Use(); } } EditorGUILayout.EndVertical(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true;*/ } void OnWizardUpdate () { helpString = "Choose an audio clip to add."; // Only valid if an audio clip has been selected - isValid = selected == null ? false : true; + isValid = selected != null; } /// <summary> /// Adds a new audio clip to the cutscene. /// </summary> void OnWizardCreate () { - Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); - scene.NewAudio(selected); + Selection.activeGameObject.GetComponent<Cutscene>().NewAudio(selected); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneAddSubtitle.cs b/Cutscene Ed/Editor/CutsceneAddSubtitle.cs index f8b707c..537bd0e 100755 --- a/Cutscene Ed/Editor/CutsceneAddSubtitle.cs +++ b/Cutscene Ed/Editor/CutsceneAddSubtitle.cs @@ -1,62 +1,61 @@ using UnityEngine; using UnityEditor; public class CutsceneAddSubtitle : ScriptableWizard { string dialog = ""; /// <summary> /// Creates a wizard for adding a new subtitle. /// </summary> [MenuItem("Component/Cutscene/Add Media/Subtitle")] public static void CreateWizard () { - DisplayWizard("Add Subtitle", typeof(CutsceneAddSubtitle), "Add"); + DisplayWizard<CutsceneAddSubtitle>("Add Subtitle", "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Subtitle", true)] static bool ValidateCreateWizard () { return CutsceneEditor.CutsceneSelected; } void OnGUI () { OnWizardUpdate(); EditorGUILayout.BeginHorizontal(); GUIContent itemLabel = new GUIContent("Dialog", EditorGUIUtility.ObjectContent(null, typeof(TextAsset)).image); GUILayout.Label(itemLabel, GUILayout.ExpandWidth(false)); dialog = EditorGUILayout.TextArea(dialog); EditorGUILayout.EndHorizontal(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true; } void OnWizardUpdate () { helpString = "Type in some dialog to add."; // Only valid if some text has been entered in the text field - isValid = dialog == "" ? false : true; + isValid = dialog != ""; } /// <summary> /// Adds the new subtitle to the cutscene. /// </summary> void OnWizardCreate () { - Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); - scene.NewSubtitle(dialog); + Selection.activeGameObject.GetComponent<Cutscene>().NewSubtitle(dialog); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneEditor.cs b/Cutscene Ed/Editor/CutsceneEditor.cs index 243ef58..eba8e29 100755 --- a/Cutscene Ed/Editor/CutsceneEditor.cs +++ b/Cutscene Ed/Editor/CutsceneEditor.cs @@ -1,476 +1,491 @@ using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// The Cutscene Editor, where tracks and clips can be managed in a fashion similar to non-linear video editors. /// </summary> public class CutsceneEditor : EditorWindow { - public static System.Version version = new System.Version(0, 2); + public static readonly System.Version version = new System.Version(0, 2); public Cutscene scene { get { Object[] scenes = Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel); - if (scenes.Length > 0) { - return scenes[0] as Cutscene; - } else { + + if (scenes.Length == 0) { return null; } + + return scenes[0] as Cutscene; } } public GUISkin style { get; private set; } //ICutsceneGUI options; ICutsceneGUI media; ICutsceneGUI effects; ICutsceneGUI tools; ICutsceneGUI timeline; public static bool CutsceneSelected { - // This shouldn't require a getter, but if it's placed on a single line Unity will crash upon hitting Play. get { return Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel).Length > 0; } } public static bool HasPro = SystemInfo.supportsImageEffects; // Icons: public readonly Texture[] mediaIcons = { EditorGUIUtility.LoadRequired("Cutscene Ed/media_shot.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_actor.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_audio.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_subtitle.png") as Texture }; // Timeline: public Tool currentTool = Tool.MoveResize; public Vector2 timelineScrollPos; public float timelineMin { get; set; } float _timelineZoom = CutsceneTimeline.timelineZoomMin; public float timelineZoom { get { return _timelineZoom; } set { _timelineZoom = Mathf.Clamp(value, CutsceneTimeline.timelineZoomMin, CutsceneTimeline.timelineZoomMax); } } CutsceneTrack _selectedTrack; public CutsceneTrack selectedTrack { get { if (_selectedTrack == null) { // If there are no tracks, add a new one if (scene.tracks.Length == 0) { scene.AddTrack(Cutscene.MediaType.Shots); } _selectedTrack = scene.tracks[0]; } return _selectedTrack; } set { _selectedTrack = value; } } public CutsceneClip selectedClip; public DragEvent dragEvent = DragEvent.Move; public CutsceneClip dragClip; // Menu items: /// <summary> /// Adds "Cutscene Editor" to the Window menu. /// </summary> [MenuItem("Window/Cutscene Editor %9")] public static void OpenEditor () { // Get existing open window or if none, make a new one - CutsceneEditor window = GetWindow(typeof(CutsceneEditor), false, "Cutscene Editor") as CutsceneEditor; - if (window != null) { - window.Show(); - } + GetWindow<CutsceneEditor>(false, "Cutscene Editor").Show(); } /// <summary> /// Validates the Cutscene Editor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Window/Cutscene Editor %9", true)] static bool ValidateOpenEditor () { return CutsceneSelected; } /// <summary> /// Adds the option to create a cutscene from the GameObject > Create Other menu. /// </summary> /// <returns>The new cutscene.</returns> [MenuItem("GameObject/Create Other/Cutscene")] static void CreateCutscene () { // Create the new cutscene game object GameObject newSceneGO = new GameObject("Cutscene", typeof(Cutscene)); Cutscene newScene = newSceneGO.GetComponent<Cutscene>(); // Add some tracks to get the user started newScene.AddTrack(Cutscene.MediaType.Shots); newScene.AddTrack(Cutscene.MediaType.Actors); newScene.AddTrack(Cutscene.MediaType.Audio); newScene.AddTrack(Cutscene.MediaType.Subtitles); // Create the cutscene's media game objects GameObject shots = new GameObject("Shots"); GameObject actors = new GameObject("Actors"); GameObject audio = new GameObject("Audio"); GameObject subtitles = new GameObject("Subtitles"); // Make the media game objects a child of the cutscene shots.transform.parent = newScene.transform; actors.transform.parent = newScene.transform; audio.transform.parent = newScene.transform; subtitles.transform.parent = newScene.transform; // Create the master animation clip AnimationClip masterClip = new AnimationClip(); newScene.masterClip = masterClip; newScene.animation.AddClip(masterClip, "master"); newScene.animation.playAutomatically = false; newScene.animation.wrapMode = WrapMode.Once; EDebug.Log("Cutscene Editor: created a new cutscene"); } /// <summary> /// Adds the option to create a cutscene trigger to the GameObject > Create Other menu. /// </summary> /// <returns>The trigger's collider.</returns> [MenuItem("GameObject/Create Other/Cutscene Trigger")] static Collider CreateCutsceneTrigger () { // Create the new cutscene trigger game object GameObject triggerGO = new GameObject("Cutscene Trigger", typeof(BoxCollider), typeof(CutsceneTrigger)); triggerGO.collider.isTrigger = true; return triggerGO.collider; } /// <summary> /// Adds the option to create a new shot track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Shot")] static void CreateShotTrack () { - Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); - scene.AddTrack(Cutscene.MediaType.Shots); + Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Shots); } /// <summary> /// Validates the Shot menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Shot", true)] static bool ValidateCreateShotTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new actor track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Actor")] static void CreateActorTrack () { - Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); - scene.AddTrack(Cutscene.MediaType.Actors); + Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Actors); } /// <summary> /// Validates the Actor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Actor", true)] static bool ValidateCreateActorTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new audio track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Audio")] static void CreateAudioTrack () { - Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); - scene.AddTrack(Cutscene.MediaType.Audio); + Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Audio); } /// <summary> /// Validates the Audio menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Audio", true)] static bool ValidateCreateAudioTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new subtitle track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Subtitle")] static void CreateSubtitleTrack () { - Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); - scene.AddTrack(Cutscene.MediaType.Subtitles); + Selection.activeGameObject.GetComponent<Cutscene>().AddTrack(Cutscene.MediaType.Subtitles); } /// <summary> /// Validates the Subtitle menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Subtitle", true)] static bool ValidateCreateSubtitleTrack () { return CutsceneSelected; } void OnEnable () { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; if (style == null) { Debug.LogError("GUISkin for Cutscene Editor missing"); return; } //options = new CutsceneOptions(this); media = new CutsceneMediaWindow(this); effects = new CutsceneEffectsWindow(this); tools = new CutsceneTools(this); timeline = new CutsceneTimeline(this); } /// <summary> /// Displays the editor GUI. /// </summary> void OnGUI () { if (style == null) { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; } // If no cutscene is selected, present the user with the option to create one if (scene == null) { if (GUILayout.Button("Create New Cutscene", GUILayout.ExpandWidth(false))) { CreateCutscene(); } } else { // Otherwise present the cutscene editor float windowHeight = style.GetStyle("Pane").fixedHeight; // Options window //Rect optionsRect = new Rect(0, 0, position.width / 3, windowHeight); //options.OnGUI(optionsRect); // Media window Rect mediaRect = new Rect(2, 2, position.width / 2, windowHeight); media.OnGUI(mediaRect); // Effects window Rect effectsRect = new Rect(mediaRect.xMax + 2, 2, position.width - mediaRect.xMax - 4, windowHeight); effects.OnGUI(effectsRect); // Cutting tools Rect toolsRect = new Rect(0, mediaRect.yMax, position.width, 25); tools.OnGUI(toolsRect); // Timeline Rect timelineRect = new Rect(0, toolsRect.yMax, position.width, position.height - toolsRect.yMax); timeline.OnGUI(timelineRect); } } // Context menus: /// <summary> /// Deletes a piece of media by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> [MenuItem("CONTEXT/CutsceneObject/Delete")] static void DeleteCutsceneMedia (MenuCommand command) { DeleteCutsceneMedia(command.context as CutsceneMedia); } /// <summary> /// Deletes a piece of media. /// </summary> /// <param name="obj">The media to delete.</param> /// <remarks>This has to be in CutsceneEditor rather than CutsceneTimeline because it uses the DestroyImmediate function, which is only available to classes which inherit from UnityEngine.Object.</remarks> static void DeleteCutsceneMedia (CutsceneMedia obj) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Object", "Are you sure you wish to delete this object? Changes cannot be undone.", "Delete", "Cancel"); } // Only delete the cutscene object if the user chose to if (delete) { Debug.Log("Cutscene Editor: deleting media " + obj.name); if (obj.type == Cutscene.MediaType.Actors || obj.type == Cutscene.MediaType.Subtitles) { // Delete the CutsceneObject component DestroyImmediate(obj); } else { // Delete the actual game object DestroyImmediate(obj.gameObject); } } } /// <summary> /// Deletes a track by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneTrack/Delete Track")] static bool DeleteTrack (MenuCommand command) { return DeleteTrack(command.context as CutsceneTrack); } /// <summary> /// Deletes a track. /// </summary> /// <param name="track">The track to delete.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> static bool DeleteTrack (CutsceneTrack track) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Track", "Are you sure you wish to delete this track? Changes cannot be undone.", "Delete", "Cancel"); } if (delete) { DestroyImmediate(track); } return delete; } /// <summary> /// Deletes a clip by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneClip/Delete Clip")] static bool DeleteClip (MenuCommand command) { return DeleteClip(command.context as CutsceneClip); } /// <summary> /// Deletes a clip. /// </summary> /// <param name="clip">The clip to delete.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> static bool DeleteClip (CutsceneClip clip) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Clip", "Are you sure you wish to delete this clip? Changes cannot be undone.", "Delete", "Cancel"); } clip.setToDelete = delete; return delete; } /// <summary> /// Selects the track at the specified index. /// </summary> /// <param name="index">The track to select.</param> void SelectTrackAtIndex (int index) { if (scene.tracks.Length > 0 && index > 0 && index <= scene.tracks.Length) { selectedTrack = scene.tracks[index - 1]; EDebug.Log("Cutscene Editor: track " + index + " is selected"); } } /// <summary> /// Determines which key command is pressed and responds accordingly. /// </summary> /// <param name="keyDownEvent">The keyboard event.</param> /// <returns>True if the keyboard shortcut exists, false otherwise.</returns> public void HandleKeyboardShortcuts (Event keyDownEvent) { KeyCode key = keyDownEvent.keyCode; // Tools: - - if (key == CutsceneHotkeys.MoveResizeTool.key) { // Move/resize + + // Move/resize + if (key == CutsceneHotkeys.MoveResizeTool.key) { currentTool = Tool.MoveResize; EDebug.Log("Cutscene Editor: switching to Move/Resize tool"); - } else if (key == CutsceneHotkeys.ScissorsTool.key) { // Scissors + // Scissors + } else if (key == CutsceneHotkeys.ScissorsTool.key) { currentTool = Tool.Scissors; EDebug.Log("Cutscene Editor: switching to Scissors tool"); - } else if (key == CutsceneHotkeys.ZoomTool.key) { // Zoom + // Zoom + } else if (key == CutsceneHotkeys.ZoomTool.key) { currentTool = Tool.Zoom; EDebug.Log("Cutscene Editor: switching to Zoom tool"); } // Timeline navigation: - - else if (key == CutsceneHotkeys.SetInPont.key) { // Set in point + + // Set in point + else if (key == CutsceneHotkeys.SetInPont.key) { scene.inPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting in point"); - } else if (key == CutsceneHotkeys.SetOutPoint.key) { // Set out point + // Set out point + } else if (key == CutsceneHotkeys.SetOutPoint.key) { scene.outPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting out point"); - } else if (keyDownEvent.Equals(Event.KeyboardEvent("left"))) { // Scrub left + // Scrub left + } else if (keyDownEvent.Equals(Event.KeyboardEvent("left"))) { scene.playhead -= CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead left"); - } else if (keyDownEvent.Equals(Event.KeyboardEvent("#left"))) { // Scrub left large + // Scrub left large + } else if (keyDownEvent.Equals(Event.KeyboardEvent("#left"))) { scene.playhead -= CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead left"); - } else if (keyDownEvent.Equals(Event.KeyboardEvent("right"))) { // Scrub right + // Scrub right + } else if (keyDownEvent.Equals(Event.KeyboardEvent("right"))) { scene.playhead += CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead right"); - } else if (keyDownEvent.Equals(Event.KeyboardEvent("#right"))) { // Scrub right large + // Scrub right large + } else if (keyDownEvent.Equals(Event.KeyboardEvent("#right"))) { scene.playhead += CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead right"); - } else if (keyDownEvent.Equals(Event.KeyboardEvent("up"))) { // Go to previous split point + // Go to previous split point + } else if (keyDownEvent.Equals(Event.KeyboardEvent("up"))) { scene.playhead = selectedTrack.GetTimeOfNextSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to previous split point"); - } else if (keyDownEvent.Equals(Event.KeyboardEvent("down"))) { // Go to next split point + // Go to next split point + } else if (keyDownEvent.Equals(Event.KeyboardEvent("down"))) { scene.playhead = selectedTrack.GetTimeOfPreviousSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to next split point"); - } else if (keyDownEvent.Equals(Event.KeyboardEvent("#up"))) { // Go to in point + // Go to in point + } else if (keyDownEvent.Equals(Event.KeyboardEvent("#up"))) { scene.playhead = scene.inPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); - } else if (keyDownEvent.Equals(Event.KeyboardEvent("#down"))) { // Go to out point + // Go to out point + } else if (keyDownEvent.Equals(Event.KeyboardEvent("#down"))) { scene.playhead = scene.outPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); } // Track selection: - - else if (key == CutsceneHotkeys.SelectTrack1.key) { // Select track 1 + + // Select track 1 + else if (key == CutsceneHotkeys.SelectTrack1.key) { SelectTrackAtIndex(1); - } else if (key == CutsceneHotkeys.SelectTrack2.key) { // Select track 2 + // Select track 2 + } else if (key == CutsceneHotkeys.SelectTrack2.key) { SelectTrackAtIndex(2); - } else if (key == CutsceneHotkeys.SelectTrack3.key) { // Select track 3 + // Select track 3 + } else if (key == CutsceneHotkeys.SelectTrack3.key) { SelectTrackAtIndex(3); - } else if (key == CutsceneHotkeys.SelectTrack4.key) { // Select track 4 + // Select track 4 + } else if (key == CutsceneHotkeys.SelectTrack4.key) { SelectTrackAtIndex(4); - } else if (key == CutsceneHotkeys.SelectTrack5.key) { // Select track 5 + // Select track 5 + } else if (key == CutsceneHotkeys.SelectTrack5.key) { SelectTrackAtIndex(5); - } else if (key == CutsceneHotkeys.SelectTrack6.key) { // Select track 6 + // Select track 6 + } else if (key == CutsceneHotkeys.SelectTrack6.key) { SelectTrackAtIndex(6); - } else if (key == CutsceneHotkeys.SelectTrack7.key) { // Select track 7 + // Select track 7 + } else if (key == CutsceneHotkeys.SelectTrack7.key) { SelectTrackAtIndex(7); - } else if (key == CutsceneHotkeys.SelectTrack8.key) { // Select track 8 + // Select track 8 + } else if (key == CutsceneHotkeys.SelectTrack8.key) { SelectTrackAtIndex(8); - } else if (key == CutsceneHotkeys.SelectTrack9.key) { // Select track 9 + // Select track 9 + } else if (key == CutsceneHotkeys.SelectTrack9.key) { SelectTrackAtIndex(9); } // Other: else { EDebug.Log("Cutscene Editor: unknown keyboard shortcut " + keyDownEvent); return; } // If we get to this point, a shortcut matching the user's keystroke has been found Event.current.Use(); } public static float PaneTabsWidth (int count) { return count * 80f; } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneEffectsWindow.cs b/Cutscene Ed/Editor/CutsceneEffectsWindow.cs index 471610f..22244ab 100755 --- a/Cutscene Ed/Editor/CutsceneEffectsWindow.cs +++ b/Cutscene Ed/Editor/CutsceneEffectsWindow.cs @@ -1,115 +1,106 @@ using UnityEditor; using UnityEngine; using System; using System.Collections.Generic; class CutsceneEffectsWindow : ICutsceneGUI { readonly CutsceneEditor ed; - static Dictionary<string, Type> filters { - get { - Dictionary<string, Type> _filters = new Dictionary<string, Type>(); - - _filters.Add(CutsceneBlurFilter.name, typeof(CutsceneBlurFilter)); - _filters.Add(CutsceneInvertFilter.name, typeof(CutsceneInvertFilter)); - - return _filters; - } - } + static Dictionary<string, Type> filters = new Dictionary<string, Type> + { + { CutsceneBlurFilter.name, typeof(CutsceneBlurFilter) }, + { CutsceneInvertFilter.name, typeof(CutsceneInvertFilter) } + }; - static Dictionary<string, Type> transitions { - get { - Dictionary<string, Type> _transitions = new Dictionary<string, Type>(); - return _transitions; - } - } + static Dictionary<string, Type> transitions = new Dictionary<string, Type> {}; - static readonly GUIContent filtersLabel = new GUIContent("Filters", "Full screen filters."); - static readonly GUIContent transitionsLabel = new GUIContent("Transitions", "Camera transitions."); + static readonly GUIContent filtersLabel = new GUIContent("Filters", "Full screen filters."); + static readonly GUIContent transitionsLabel = new GUIContent("Transitions", "Camera transitions."); readonly GUIContent[] effectsTabs = CutsceneEditor.HasPro ? new GUIContent[] { filtersLabel, transitionsLabel } : new GUIContent[] { transitionsLabel }; Cutscene.EffectType currentEffectsTab = Cutscene.EffectType.Filters; Type selectedEffect; readonly Texture[] effectsIcons = { EditorGUIUtility.LoadRequired("Cutscene Ed/effects_filter.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/effects_transition.png") as Texture }; public CutsceneEffectsWindow (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the effects pane's GUI. /// </summary> /// <param name="rect">The effects pane's Rect.</param> public void OnGUI (Rect rect) { GUILayout.BeginArea(rect, ed.style.GetStyle("Pane")); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); currentEffectsTab = (Cutscene.EffectType)GUILayout.Toolbar((int)currentEffectsTab, effectsTabs, GUILayout.Width(CutsceneEditor.PaneTabsWidth(effectsTabs.Length))); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); GUI.enabled = ed.selectedClip != null && ed.selectedClip.type == Cutscene.MediaType.Shots && selectedEffect != null; GUIContent applyLabel = new GUIContent("Apply", "Apply the selected effect to the selected clip."); if (GUILayout.Button(applyLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { if (ed.selectedClip != null) { ed.selectedClip.ApplyEffect(selectedEffect); } } GUI.enabled = true; EditorGUILayout.EndHorizontal(); switch (currentEffectsTab) { case Cutscene.EffectType.Filters: - foreach (KeyValuePair<string, Type> item in filters) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedEffect == item.Value ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent filterLabel = new GUIContent(item.Key, effectsIcons[(int)Cutscene.EffectType.Filters]); GUILayout.Label(filterLabel); EditorGUILayout.EndHorizontal(); // Handle clicks if (Event.current.type == EventType.MouseDown && itemRect.Contains(Event.current.mousePosition)) { selectedEffect = item.Value; Event.current.Use(); } } break; + case Cutscene.EffectType.Transitions: foreach (KeyValuePair<string, Type> item in transitions) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedEffect == item.Value ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent transitionLabel = new GUIContent(item.Key, effectsIcons[(int)Cutscene.EffectType.Transitions]); GUILayout.Label(transitionLabel); EditorGUILayout.EndHorizontal(); // Handle clicks if (Event.current.type == EventType.MouseDown && itemRect.Contains(Event.current.mousePosition)) { selectedEffect = item.Value; Event.current.Use(); } } break; + default: break; } GUILayout.EndArea(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneMediaWindow.cs b/Cutscene Ed/Editor/CutsceneMediaWindow.cs index 53a5d07..9514dc1 100755 --- a/Cutscene Ed/Editor/CutsceneMediaWindow.cs +++ b/Cutscene Ed/Editor/CutsceneMediaWindow.cs @@ -1,280 +1,286 @@ using UnityEditor; using UnityEngine; class CutsceneMediaWindow : ICutsceneGUI { readonly CutsceneEditor ed; readonly GUIContent[] mediaTabs = { new GUIContent("Shots", "Camera views."), new GUIContent("Actors", "Animated game objects."), new GUIContent("Audio", "Dialog, background music and sound effects."), new GUIContent("Subtitles", "Textual versions of dialog.") }; Cutscene.MediaType currentMediaTab = Cutscene.MediaType.Shots; Vector2[] mediaScrollPos = { Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero }; CutsceneMedia selectedMediaItem; readonly GUIContent newMediaLabel = new GUIContent(EditorGUIUtility.LoadRequired("Cutscene Ed/icon_add.png") as Texture, "Add new media."); readonly GUIContent insertMediaLabel = new GUIContent("Insert", "Insert the selected shot onto the timeline."); public CutsceneMediaWindow (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the media pane's GUI. /// </summary> /// <param name="rect">The media pane's Rect.</param> public void OnGUI (Rect rect) { GUILayout.BeginArea(rect, ed.style.GetStyle("Pane")); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); currentMediaTab = (Cutscene.MediaType)GUILayout.Toolbar((int)currentMediaTab, mediaTabs, GUILayout.Width(CutsceneEditor.PaneTabsWidth(mediaTabs.Length))); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); switch (currentMediaTab) { case Cutscene.MediaType.Shots: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { ed.scene.NewShot(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneShot shot in ed.scene.shots) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == shot ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(shot.name, ed.mediaIcons[(int)Cutscene.MediaType.Shots]); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(shot, itemRect); } EditorGUILayout.EndScrollView(); break; + case Cutscene.MediaType.Actors: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { CutsceneAddActor.CreateWizard(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneActor actor in ed.scene.actors) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == actor ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(actor.anim.name, ed.mediaIcons[(int)Cutscene.MediaType.Actors]); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(actor, itemRect); } EditorGUILayout.EndScrollView(); break; + case Cutscene.MediaType.Audio: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { // Show a wizard that will take care of adding audio CutsceneAddAudio.CreateWizard(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneAudio aud in ed.scene.audioSources) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == aud ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(aud.name, ed.mediaIcons[(int)Cutscene.MediaType.Audio]); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(aud, itemRect); } EditorGUILayout.EndScrollView(); break; + case Cutscene.MediaType.Subtitles: // If the selected item is in a different tab, set it to null if (selectedMediaItem != null && selectedMediaItem.type != currentMediaTab) { selectedMediaItem = null; } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(newMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { // Show a wizard that will take care of adding audio CutsceneAddSubtitle.CreateWizard(); } GUI.enabled = IsMediaInsertable(); if (GUILayout.Button(insertMediaLabel, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { Insert(selectedMediaItem); } GUI.enabled = true; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); mediaScrollPos[(int)currentMediaTab] = EditorGUILayout.BeginScrollView(mediaScrollPos[(int)currentMediaTab], GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); foreach (CutsceneSubtitle subtitle in ed.scene.subtitles) { Rect itemRect = EditorGUILayout.BeginHorizontal(selectedMediaItem == subtitle ? ed.style.GetStyle("Selected List Item") : GUIStyle.none); GUIContent itemLabel = new GUIContent(ed.mediaIcons[(int)Cutscene.MediaType.Subtitles]); GUILayout.Label(itemLabel, GUILayout.ExpandWidth(false)); subtitle.dialog = EditorGUILayout.TextField(subtitle.dialog); EditorGUILayout.EndHorizontal(); HandleMediaItemClicks(subtitle, itemRect); } EditorGUILayout.EndScrollView(); break; + default: break; } GUILayout.EndArea(); // Handle drag and drop events if (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform) { // Show a copy icon on the drag DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (Event.current.type == EventType.DragPerform && rect.Contains(Event.current.mousePosition)) { DragAndDrop.AcceptDrag(); Object[] draggedObjects = DragAndDrop.objectReferences; // Create the appropriate cutscene objects for each dragged object foreach (Object obj in draggedObjects) { if (obj is AudioClip) { ed.scene.NewAudio((AudioClip)obj); } else if (obj is GameObject && ((GameObject)obj).animation != null) { GameObject go = obj as GameObject; foreach (AnimationClip anim in AnimationUtility.GetAnimationClips(go.animation)) { ed.scene.NewActor(anim, go); } } EDebug.Log("Cutscene Editor: dropping " + obj.GetType()); } } Event.current.Use(); } } /// <summary> /// Handles left and right mouse clicks of media items. /// </summary> /// <param name="item">The item clicked on.</param> /// <param name="rect">The item's Rect.</param> void HandleMediaItemClicks (CutsceneMedia item, Rect rect) { Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && rect.Contains(mousePos)) { switch (Event.current.button) { case 0: // Left click selectedMediaItem = item; EditorGUIUtility.PingObject(item); break; + case 1: // Right click EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneObject/", new MenuCommand(item)); break; + default: break; } Event.current.Use(); } } /// <summary> /// Determines whether or not the currently selected cutscene object can be inserted into the selected timeline. /// </summary> /// <returns>True if the selected clip and the selected track are the same, false otherwise.</returns> bool IsMediaInsertable () { return selectedMediaItem != null && selectedMediaItem.type == ed.selectedTrack.type; } /// <summary> /// Inserts the given cutscene object into the timeline. /// </summary> /// <param name="obj">The cutscene object to insert.</param> void Insert (CutsceneMedia obj) { CutsceneClip newClip = new CutsceneClip(obj); newClip.timelineStart = ed.scene.playhead; // If there are no existing tracks, add a new one if (ed.scene.tracks.Length == 0) { ed.scene.AddTrack(newClip.type); } // Manage overlap with other clips CutsceneClip existingClip = ed.selectedTrack.ContainsClipAtTime(ed.scene.playhead); if (existingClip != null) { CutsceneClip middleOfSplit = CutsceneTimeline.SplitClipAtTime(ed.scene.playhead, ed.selectedTrack, existingClip); CutsceneTimeline.SplitClipAtTime(ed.scene.playhead + newClip.duration, ed.selectedTrack, middleOfSplit); ed.selectedTrack.clips.Remove(middleOfSplit); } ed.selectedTrack.clips.Add(newClip); EDebug.Log("Cutscene Editor: inserting " + newClip.name + " into timeline " + ed.selectedTrack + " at " + ed.scene.playhead); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutscenePlaybackControls.cs b/Cutscene Ed/Editor/CutscenePlaybackControls.cs index 3fee3d5..daa69bf 100755 --- a/Cutscene Ed/Editor/CutscenePlaybackControls.cs +++ b/Cutscene Ed/Editor/CutscenePlaybackControls.cs @@ -1,70 +1,75 @@ using UnityEditor; using UnityEngine; class CutscenePlaybackControls : ICutsceneGUI { readonly CutsceneEditor ed; const int buttonWidth = 18; - readonly Texture inPointIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/playback_in.png") as Texture; - readonly Texture backIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/playback_back.png") as Texture; - //readonly Texture playIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/playback_play.png") as Texture; - readonly Texture forwardIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/playback_forward.png") as Texture; - readonly Texture outPointIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/playback_out.png") as Texture; - - readonly GUIContent inPointLabel; - readonly GUIContent backLabel; - //readonly GUIContent playLabel; - readonly GUIContent forwardLabel; - readonly GUIContent outPointLabel; + readonly GUIContent inPointLabel = new GUIContent( + EditorGUIUtility.LoadRequired("Cutscene Ed/playback_in.png") as Texture, + "Go to in point." + ); + readonly GUIContent backLabel = new GUIContent( + EditorGUIUtility.LoadRequired("Cutscene Ed/playback_back.png") as Texture, + "Go back a second." + ); + /* + readonly GUIContent playLabel = new GUIContent( + EditorGUIUtility.LoadRequired("Cutscene Ed/playback_play.png") as Texture, + "Play." + ); + */ + readonly GUIContent forwardLabel = new GUIContent( + EditorGUIUtility.LoadRequired("Cutscene Ed/playback_forward.png") as Texture, + "Go forward a second." + ); + readonly GUIContent outPointLabel = new GUIContent( + EditorGUIUtility.LoadRequired("Cutscene Ed/playback_out.png") as Texture, + "Go to out point." + ); public CutscenePlaybackControls (CutsceneEditor ed) { this.ed = ed; - - inPointLabel = new GUIContent(inPointIcon, "Go to in point."); - backLabel = new GUIContent(backIcon, "Go back a second."); - //playLabel = new GUIContent(playIcon, "Play."); - forwardLabel = new GUIContent(forwardIcon, "Go forward a second."); - outPointLabel = new GUIContent(outPointIcon, "Go to out point."); } /// <summary> /// Displays playback controls. /// </summary> /// <param name="rect">The playback controls' Rect.</param> public void OnGUI (Rect rect) { GUI.BeginGroup(rect, EditorStyles.toolbar); // In point Rect inPointRect = new Rect(6, 0, buttonWidth, rect.height); if (GUI.Button(inPointRect, inPointLabel, EditorStyles.toolbarButton)) { ed.scene.playhead = ed.scene.inPoint; } // Back Rect backRect = new Rect(inPointRect.xMax, 0, buttonWidth, rect.height); if (GUI.Button(backRect, backLabel, EditorStyles.toolbarButton)) { ed.scene.playhead -= CutsceneTimeline.scrubSmallJump; } /* Feature not implemented yet: // Play Rect playRect = new Rect(backRect.xMax, 0, buttonWidth, rect.height); if (GUI.Button(playRect, playLabel, EditorStyles.toolbarButton)) { EDebug.Log("Cutscene Editor: previewing scene (feature not implemented)"); };*/ // Forward Rect forwardRect = new Rect(backRect.xMax, 0, buttonWidth, rect.height); if (GUI.Button(forwardRect, forwardLabel, EditorStyles.toolbarButton)) { ed.scene.playhead += CutsceneTimeline.scrubSmallJump; } // Out point Rect outPointRect = new Rect(forwardRect.xMax, 0, buttonWidth, rect.height); if (GUI.Button(outPointRect, outPointLabel, EditorStyles.toolbarButton)) { ed.scene.playhead = ed.scene.outPoint; } Rect floatRect = new Rect(outPointRect.xMax + 4, 2, 50, rect.height); ed.scene.playhead = EditorGUI.FloatField(floatRect, ed.scene.playhead, EditorStyles.toolbarTextField); GUI.EndGroup(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTestingWindow.cs b/Cutscene Ed/Editor/CutsceneTestingWindow.cs index 2979805..044f0e0 100644 --- a/Cutscene Ed/Editor/CutsceneTestingWindow.cs +++ b/Cutscene Ed/Editor/CutsceneTestingWindow.cs @@ -1,173 +1,172 @@ using UnityEngine; using UnityEditor; using System.Collections; class CutsceneTestingWindow : EditorWindow { bool allowHorizontal = true; bool allowVertical = false; Rect[] boxes = { new Rect(0, 0, 100, 50), new Rect(100, 0, 100, 50), new Rect(300, 0, 100, 50) }; static Rect noBox = new Rect(0, 0, Mathf.Infinity, Mathf.Infinity); const int NONE = -1; int dragBox = NONE; string dragEvent = ""; public CutsceneTestingWindow () { title = "Testing Window"; } [MenuItem ("Window/Testing Window")] public static void OpenEditor () { - CutsceneTestingWindow window = (CutsceneTestingWindow)EditorWindow.GetWindow(typeof(CutsceneTestingWindow)); - window.Show(); + EditorWindow.GetWindow<CutsceneTestingWindow>().Show(); } - Rect stuff = new Rect(10, 5, 1000, 500); - Rect more = new Rect(10, 10, 100, 100); - Vector2 scrollPos = Vector2.zero; + Rect stuff = new Rect(10, 5, 1000, 500); + Rect more = new Rect(10, 10, 100, 100); + Vector2 scrollPos; public void OnGUI () { /*scrollPos = GUI.BeginScrollView(more, scrollPos, stuff, true, true); GUI.Button(new Rect(0, 0, 100, 20), "Hello"); GUI.EndScrollView();*/ for (int i = 0; i < boxes.Length; i++) { EnforceBoundaries(ref boxes[i]); GUI.Box(boxes[i], "Box " + i); } for (int i = boxes.Length - 1; i >= 0; i--) { Rect dragRect2 = new Rect(boxes[i].x + 5, boxes[i].y, boxes[i].width - 10, boxes[i].height); EditorGUIUtility.AddCursorRect(dragRect2, MouseCursor.SlideArrow); Rect resizeLeftRect2 = new Rect(boxes[i].x, boxes[i].y, 5, boxes[i].height); EditorGUIUtility.AddCursorRect(resizeLeftRect2, MouseCursor.ResizeHorizontal); Rect resizeRightRect2 = new Rect(boxes[i].xMax - 5, boxes[i].y, 5, boxes[i].height); EditorGUIUtility.AddCursorRect(resizeRightRect2, MouseCursor.ResizeHorizontal); } if (Event.current.type == EventType.MouseDown) { // Go in reverse order so that we drag the topmost box for (int i = boxes.Length - 1; i >= 0; i--) { Rect dragRect = new Rect(boxes[i].x + 5, boxes[i].y, boxes[i].width - 10, boxes[i].height); Rect resizeLeftRect = new Rect(boxes[i].x, boxes[i].y, 5, boxes[i].height); Rect resizeRightRect = new Rect(boxes[i].xMax - 5, boxes[i].y, 5, boxes[i].height); if (dragRect.Contains(Event.current.mousePosition)) { dragBox = i; dragEvent = "move"; Debug.Log("Starting drag"); break; } if (resizeLeftRect.Contains(Event.current.mousePosition)) { dragBox = i; dragEvent = "resizeLeft"; Debug.Log("Starting resize left"); break; } if (resizeRightRect.Contains(Event.current.mousePosition)) { dragBox = i; dragEvent = "resizeRight"; Debug.Log("Starting resize right"); break; } } } else if (Event.current.type == EventType.MouseDrag && dragBox != NONE) { if (dragEvent == "resizeLeft") { boxes[dragBox].xMin += Event.current.delta.x; } if (dragEvent == "resizeRight") { //if (!DetectOverlap()) { boxes[dragBox].xMax += Event.current.delta.x; //} } if (allowHorizontal && dragEvent == "move") { boxes[dragBox].x += Event.current.delta.x; } for (int i = 0; i < boxes.Length; i++) { for (int j = 0; j < boxes.Length; j++) { // If first box is pushed into the second one if (boxes[i] != boxes[j] && boxes[j].Contains(new Vector2(boxes[i].xMax, boxes[i].y))) { boxes[j].x = boxes[i].xMax; // If boundaries had to be enforced, move the box back if (EnforceBoundaries(ref boxes[i])) { boxes[i].x = boxes[j].x - boxes[i].width; } } } } if (allowVertical) { boxes[dragBox].y += Event.current.delta.y; } } else if (Event.current.type == EventType.MouseUp) { dragBox = NONE; dragEvent = ""; Debug.Log("Stopping drag"); } Event.current.Use(); } bool EnforceBoundaries (ref Rect box) { if (box.x < 0) { // Left box.x = 0; } else if (box.xMax > position.width) { // Right box.x = position.width - box.width; } else if (box.y < 0) { // Top box.y = 0; } else if (box.yMax > position.height) { // Bottom box.y = position.height - box.height; } else { // No boundaries were hit, so return false; return false; } return true; } bool DetectOverlap () { for (int i = 1; i < boxes.Length; i++) { if (boxes[i] != boxes[dragBox] && boxes[i].x > boxes[i - 1].xMax) { return false; } } /* foreach (Rect box in boxes) { if (box != boxes[dragBox] && box.Contains(Event.current.mousePosition)) { Debug.Log("Overlap detected"); return true; } }*/ // If we get to this point, no overlap has been detected return true; } } diff --git a/Cutscene Ed/Editor/CutsceneTrackControls.cs b/Cutscene Ed/Editor/CutsceneTrackControls.cs index cbf9676..2975f7a 100755 --- a/Cutscene Ed/Editor/CutsceneTrackControls.cs +++ b/Cutscene Ed/Editor/CutsceneTrackControls.cs @@ -1,42 +1,39 @@ using UnityEngine; using UnityEditor; class CutsceneTrackControls : ICutsceneGUI { readonly CutsceneEditor ed; - - readonly Texture newTrackIcon = EditorGUIUtility.LoadRequired("Cutscene Ed/icon_addtrack.png") as Texture; - readonly GUIContent newTrackLabel; + + readonly GUIContent newTrackLabel = new GUIContent( + EditorGUIUtility.LoadRequired("Cutscene Ed/icon_addtrack.png") as Texture, + "Add a new track." + ); public CutsceneTrackControls (CutsceneEditor ed) { this.ed = ed; - - newTrackLabel = new GUIContent(newTrackIcon, "Add a new track."); } public void OnGUI (Rect rect) { // TODO Make this a style in the cutscene editor's GUISkin GUIStyle popupStyle = "MiniToolbarButton"; - popupStyle.padding.top = 2; - popupStyle.padding.right = 0; - popupStyle.padding.bottom = 1; - popupStyle.padding.left = 0; + popupStyle.padding = new RectOffset(0, 0, 2, 1); // Left, right, top, bottom GUI.BeginGroup(rect, GUI.skin.GetStyle("MiniToolbarButtonLeft")); // New track popdown Rect newTrackRect = new Rect(0, 0, 33, rect.height); GUI.Label(newTrackRect, newTrackLabel, popupStyle); if (Event.current.type == EventType.MouseDown && newTrackRect.Contains(Event.current.mousePosition)) { GUIUtility.hotControl = 0; EditorUtility.DisplayPopupMenu(newTrackRect, "Component/Cutscene/Track", null); Event.current.Use(); } // Timeline zoom slider Rect timelineZoomRect = new Rect(newTrackRect.xMax + GUI.skin.horizontalSlider.margin.left, -1, rect.width - newTrackRect.xMax - GUI.skin.horizontalSlider.margin.horizontal, rect.height); ed.timelineZoom = GUI.HorizontalSlider(timelineZoomRect, ed.timelineZoom, ed.timelineMin, CutsceneTimeline.timelineZoomMax); GUI.EndGroup(); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneTrackInfo.cs b/Cutscene Ed/Editor/CutsceneTrackInfo.cs index 5e0547f..1f5178f 100755 --- a/Cutscene Ed/Editor/CutsceneTrackInfo.cs +++ b/Cutscene Ed/Editor/CutsceneTrackInfo.cs @@ -1,84 +1,87 @@ using UnityEngine; using UnityEditor; class CutsceneTrackInfo : ICutsceneGUI { readonly CutsceneEditor ed; - readonly Texture visibilityIconTex = EditorGUIUtility.LoadRequired("Cutscene Ed/icon_eye.png") as Texture; - readonly Texture lockIconTex = EditorGUIUtility.LoadRequired("Cutscene Ed/icon_lock.png") as Texture; + readonly GUIContent visibilityIcon = new GUIContent("", + EditorGUIUtility.LoadRequired("Cutscene Ed/icon_eye.png") as Texture, + "Toggle visibility." + ); + + readonly GUIContent lockIcon = new GUIContent("", + EditorGUIUtility.LoadRequired("Cutscene Ed/icon_lock.png") as Texture, + "Toggle track lock." + ); public CutsceneTrackInfo (CutsceneEditor ed) { this.ed = ed; } /// <summary> /// Displays the track info GUI. /// </summary> /// <param name="rect">The track info's Rect.</param> public void OnGUI (Rect rect) { ed.timelineScrollPos.y = EditorGUILayout.BeginScrollView( new Vector2(0, ed.timelineScrollPos.y), false, false, ed.style.horizontalScrollbar, ed.style.verticalScrollbar, GUIStyle.none, GUILayout.Width(CutsceneTimeline.trackInfoWidth), GUILayout.ExpandHeight(true)).y; foreach (CutsceneTrack track in ed.scene.tracks) { if (track == ed.selectedTrack) { GUI.SetNextControlName("track"); } Rect infoRect = EditorGUILayout.BeginHorizontal(ed.style.GetStyle("Track Info")); - - // Visibility icon - GUIContent visibilityIcon = new GUIContent("", visibilityIconTex, "Toggle visibility."); - track.enabled = GUILayout.Toggle(track.enabled, visibilityIcon, EditorStyles.miniButtonLeft, GUILayout.ExpandWidth(false)); - - // Lock icon - GUIContent lockIcon = new GUIContent("", lockIconTex, "Toggle track lock."); - track.locked = GUILayout.Toggle(track.locked, lockIcon, EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false)); + track.enabled = GUILayout.Toggle(track.enabled, visibilityIcon, EditorStyles.miniButtonLeft, GUILayout.ExpandWidth(false)); + track.locked = GUILayout.Toggle(track.locked, lockIcon, EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false)); GUILayout.Space(10); GUI.enabled = track.enabled; // Track name and icon GUIContent trackIcon = new GUIContent(ed.mediaIcons[(int)track.type]); GUILayout.Label(trackIcon, GUILayout.ExpandWidth(false)); // Set a minimum width to keep the label from becoming uneditable Rect trackNameRect = GUILayoutUtility.GetRect(new GUIContent(track.name), EditorStyles.miniLabel, GUILayout.ExpandWidth(false), GUILayout.MinWidth(20)); track.name = EditorGUI.TextField(trackNameRect, track.name, EditorStyles.miniLabel); GUI.enabled = true; EditorGUILayout.EndHorizontal(); if (track == ed.selectedTrack) { GUI.FocusControl("track"); } // Handle clicks Vector2 mousePos = Event.current.mousePosition; if (Event.current.type == EventType.MouseDown && infoRect.Contains(mousePos)) { switch (Event.current.button) { case 0: // Left mouse button ed.selectedTrack = track; break; + case 1: // Right mouse button EditorUtility.DisplayPopupMenu(new Rect(mousePos.x, mousePos.y, 0, 0), "CONTEXT/CutsceneTrack/", new MenuCommand(track)); break; + default: break; } Event.current.Use(); } } // Divider line Handles.color = Color.grey; Handles.DrawLine(new Vector3(67, 0), new Vector3(67, rect.yMax)); EditorGUILayout.EndScrollView(); } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/Cutscene.cs b/Cutscene Ed/Scripts/Cutscene.cs index f2f0efb..4345754 100755 --- a/Cutscene Ed/Scripts/Cutscene.cs +++ b/Cutscene Ed/Scripts/Cutscene.cs @@ -1,412 +1,411 @@ using UnityEngine; using System.Collections; using System.Collections.Generic; // Functions to be run when the cutscene starts and finishes public delegate void CutsceneStart(); public delegate void CutscenePause(); public delegate void CutsceneEnd(); [RequireComponent(typeof(Animation))] public class Cutscene : MonoBehaviour { public float duration = 30f; public float inPoint = 0f; public float outPoint = 30f; public bool stopPlayer = true; public GameObject player; public GUIStyle subtitleStyle; public Rect subtitlePosition = new Rect(0, 0, 400, 200); public CutsceneStart startFunction { get; set; } public CutscenePause pauseFunction { get; set; } public CutsceneEnd endFunction { get; set; } public enum MediaType { - Shots = 0, - Actors = 1, - Audio = 2, - Subtitles = 3 + Shots, + Actors, + Audio, + Subtitles } public enum EffectType { Filters, Transitions } public CutsceneTrack[] tracks { get { return GetComponentsInChildren<CutsceneTrack>(); } } public CutsceneShot[] shots { get { return GetComponentsInChildren<CutsceneShot>(); } } public CutsceneActor[] actors { get { return GetComponentsInChildren<CutsceneActor>(); } } public CutsceneAudio[] audioSources { get { return GetComponentsInChildren<CutsceneAudio>(); } } public CutsceneSubtitle[] subtitles { get { return GetComponentsInChildren<CutsceneSubtitle>(); } } CutsceneSubtitle currentSubtitle; public float playhead { get { return animation["master"].time; } set { animation["master"].time = Mathf.Clamp(value, 0f, duration); } } [HideInInspector] public AnimationClip masterClip; void Start () { SetupMasterAnimationClip(); SetupTrackAnimationClips(); DisableCameras(); DisableAudio(); } void OnGUI () { /// Displays the current subtitle if there is one - if (currentSubtitle != null) { - GUI.BeginGroup(subtitlePosition, subtitleStyle); - - GUILayout.Label(currentSubtitle.dialog, subtitleStyle); - - GUI.EndGroup(); + if (currentSubtitle == null) { + return; } + + GUI.BeginGroup(subtitlePosition, subtitleStyle); + + GUILayout.Label(currentSubtitle.dialog, subtitleStyle); + + GUI.EndGroup(); } /// <summary> /// Visually shows the cutscene in the scene view. /// </summary> void OnDrawGizmos () { Gizmos.DrawIcon(transform.position, "Cutscene.png"); } /// <summary> /// Sets the in and out points of the master animation clip. /// </summary> void SetupMasterAnimationClip () { animation.RemoveClip("master"); // Create a new event for when the scene starts AnimationEvent start = new AnimationEvent(); start.time = inPoint; start.functionName = "SceneStart"; masterClip.AddEvent(start); // Create a new event for when the scene finishes AnimationEvent finish = new AnimationEvent(); finish.time = outPoint; finish.functionName = "SceneFinish"; masterClip.AddEvent(finish); animation.AddClip(masterClip, "master"); animation["master"].time = inPoint; } /// <summary> /// Adds each track's animation clip to the main animation. /// </summary> void SetupTrackAnimationClips () { foreach (CutsceneTrack t in tracks) { if (t.enabled) { AnimationClip trackAnimationClip = t.track; string clipName = "track" + t.id; animation.AddClip(trackAnimationClip, clipName); animation[clipName].time = inPoint; } } } /// <summary> /// Turns off all child cameras so that they don't display before the cutscene starts. /// </summary> void DisableCameras () { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { cam.enabled = false; } } /// <summary> /// Turns off all child cameras except for the one specified. /// </summary> /// <param name="exemptCam">The camera to stay enabled.</param> void DisableOtherCameras (Camera exemptCam) { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { if (cam != exemptCam) { cam.enabled = false; } } } /// <summary> /// Keeps all child audio sources from playing once the game starts. /// </summary> void DisableAudio () { AudioSource[] childAudio = GetComponentsInChildren<AudioSource>(); foreach (AudioSource audio in childAudio) { audio.playOnAwake = false; } } /// <summary> /// Starts playing the cutscene. /// </summary> public void PlayCutscene () { // Set up and play the master animation animation["master"].layer = 0; animation.Play("master"); // Set up and play each individual track for (int i = 0; i < tracks.Length; i++) { if (tracks[i].enabled) { animation["track" + tracks[i].id].layer = i + 1; animation.Play("track" + tracks[i].id); } } } /// <summary> /// Pauses the cutscene. /// </summary> public void PauseCutscene () { pauseFunction(); // TODO actually pause the cutscene } /// <summary> /// Called when the scene starts. /// </summary> void SceneStart () { if (startFunction != null) { startFunction(); } // Stop the player from being able to move if (player != null && stopPlayer) { EDebug.Log("Cutscene: deactivating player"); player.active = false; } DisableCameras(); currentSubtitle = null; EDebug.Log("Cutscene: scene started at " + animation["master"].time); } /// <summary> /// Called when the scene ends. /// </summary> void SceneFinish () { if (endFunction != null) { endFunction(); } // Allow the player to move again if (player != null) { EDebug.Log("Cutscene: activating player"); player.active = true; } EDebug.Log("Cutscene: scene finished at " + animation["master"].time); } /// <summary> /// Shows the specified shot. /// </summary> /// <param name="clip">The shot to show.</summary> void PlayShot (CutsceneClip clip) { Camera cam = ((CutsceneShot)clip.master).camera; cam.enabled = true; StartCoroutine(StopShot(cam, clip.duration)); EDebug.Log("Cutscene: showing camera " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the shot from playing at its out point. /// </summary> /// <param name="shot">The shot to stop.</param> /// <param name="duration">The time at which to stop the shot.</param> IEnumerator StopShot (Camera cam, float duration) { yield return new WaitForSeconds(duration); cam.enabled = false; EDebug.Log("Cutscene: stopping shot at " + animation["master"].time); } /// <summary> /// Plays the specified actor. /// </summary> /// <param name="clip">The actor to play.</summary> void PlayActor (CutsceneClip clip) { CutsceneActor actor = ((CutsceneActor)clip.master); AnimationClip anim = actor.anim; GameObject go = ((CutsceneActor)clip.master).go; go.animation[anim.name].time = clip.inPoint; go.animation.Play(anim.name); StartCoroutine(StopActor(actor, clip.duration)); EDebug.Log("Cutscene: showing actor " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the actor from playing at its out point. /// </summary> /// <param name="actor">The actor to stop.</param> /// <param name="duration">The time at which to stop the actor.</param> IEnumerator StopActor (CutsceneActor actor, float duration) { yield return new WaitForSeconds(duration); actor.go.animation.Stop(actor.anim.name); EDebug.Log("Cutscene: stopping actor at " + animation["master"].time); } /// <summary> /// Plays the specified audio. /// </summary> /// <param name="clip">The audio to play.</summary> void PlayAudio (CutsceneClip clip) { AudioSource aud = ((CutsceneAudio)clip.master).audio; aud.Play(); aud.time = clip.inPoint; // Set the point at which the clip plays StartCoroutine(StopAudio(aud, clip.duration)); // Set the point at which the clip stops EDebug.Log("Playing audio " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the audio from playing at its out point. /// </summary> /// <param name="aud">The audio source to stop.</param> /// <param name="duration">The time at which to stop the audio.</param> IEnumerator StopAudio (AudioSource aud, float duration) { yield return new WaitForSeconds(duration); aud.Stop(); } /// <summary> /// Displays the specified subtitle. /// </summary> /// <param name="clip">The subtitle to display.</summary> void PlaySubtitle (CutsceneClip clip) { currentSubtitle = (CutsceneSubtitle)clip.master; EDebug.Log("Displaying subtitle " + clip.name + " at " + animation["master"].time); StartCoroutine(StopSubtitle(clip.duration)); } /// <summary> /// Stops the subtitle from displaying at its out point. /// </summary> /// <param name="duration">The time at which to stop the audio.</param> IEnumerator StopSubtitle (float duration) { yield return new WaitForSeconds(duration); currentSubtitle = null; } /// <summary> /// Stops all subtitles from displaying by setting the current subtitle to null. /// </summary> void StopSubtitle () { currentSubtitle = null; } /// <summary> /// Called when the clip type is unknown. /// </summary> /// <remarks>For debugging only; ideally this will never be called.</remarks> void UnknownFunction (CutsceneClip clip) { EDebug.Log("Cutscene: unknown function call from clip " + clip.name); } - /// <summary> /// Creates a new CutsceneShot object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneShot object.</returns> public CutsceneShot NewShot () { GameObject shot = new GameObject("Camera", typeof(Camera), typeof(CutsceneShot)); // Keep the camera from displaying before it's placed on the timeline shot.camera.enabled = false; // Set the parent of the new shot to the Shots object shot.transform.parent = transform.Find("Shots"); EDebug.Log("Cutscene Editor: added new shot"); return shot.GetComponent<CutsceneShot>(); } /// <summary> /// Creates a new CutsceneActor object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneActor object.</returns> public CutsceneActor NewActor (AnimationClip anim, GameObject go) { - GameObject actorsGO = transform.Find("Actors").gameObject; - CutsceneActor actor = actorsGO.AddComponent<CutsceneActor>(); + CutsceneActor actor = GameObject.Find("Actors").AddComponent<CutsceneActor>(); actor.anim = anim; actor.go = go; EDebug.Log("Cutscene Editor: adding new actor"); return actor; } /// <summary> /// Creates a new CutsceneAudio object and attaches it to a new game object as a child of the Audio game object. /// </summary> /// <param name="clip">The audio clip to be attached the CutsceneAudio object.</param> /// <returns>The new CutsceneAudio object.</returns> public CutsceneAudio NewAudio (AudioClip clip) { GameObject aud = new GameObject(clip.name, typeof(AudioSource), typeof(CutsceneAudio)); aud.audio.clip = clip; // Keep the audio from playing when the game starts aud.audio.playOnAwake = false; // Set the parent of the new audio to the "Audio" object aud.transform.parent = transform.Find("Audio"); EDebug.Log("Cutscene Editor: added new audio"); return aud.GetComponent<CutsceneAudio>(); } /// <summary> /// Creates a new CutsceneSubtitle object and attaches it to the Subtitles game object. /// </summary> /// <param name="dialog">The dialog to be displayed.</param> /// <returns>The new CutsceneSubtitle object.</returns> public CutsceneSubtitle NewSubtitle (string dialog) { - GameObject subtitleGO = transform.Find("Subtitles").gameObject; - CutsceneSubtitle subtitle = subtitleGO.AddComponent<CutsceneSubtitle>(); + CutsceneSubtitle subtitle = GameObject.Find("Subtitles").AddComponent<CutsceneSubtitle>(); subtitle.dialog = dialog; EDebug.Log("Cutscene Editor: added new subtitle"); return subtitle; } /// <summary> /// Attaches a new track component to the cutscene. /// </summary> /// <returns>The new cutscene track.</returns> public CutsceneTrack AddTrack (Cutscene.MediaType type) { int id = 0; // Ensure the new track has a unique ID foreach (CutsceneTrack t in tracks) { if (id == t.id) { id++; } else { break; } } CutsceneTrack track = gameObject.AddComponent<CutsceneTrack>(); track.id = id; track.type = type; track.name = CutsceneTrack.DefaultName(type); EDebug.Log("Cutscene Editor: added new track of type " + type); return track; } } \ No newline at end of file
mminer/silverscreen
221b3b659633ea9ceef320e0cf8232080940bb0b
Switched getters/setters to C# 3.0 automatic properties
diff --git a/Cutscene Ed/Editor/CutsceneAddActor.cs b/Cutscene Ed/Editor/CutsceneAddActor.cs index 85fe67a..5deca1f 100755 --- a/Cutscene Ed/Editor/CutsceneAddActor.cs +++ b/Cutscene Ed/Editor/CutsceneAddActor.cs @@ -1,92 +1,92 @@ using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; class CutsceneAddActor : ScriptableWizard { - GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; - AnimationClip selected = null; - GameObject selectedGO = null; + GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; + AnimationClip selected; + GameObject selectedGO; /// <summary> /// Creates a wizard for adding a new actor. /// </summary> [MenuItem("Component/Cutscene/Add Media/Actor")] public static void CreateWizard () { DisplayWizard("Add Actor", typeof(CutsceneAddActor), "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Actor", true)] static bool ValidateCreateWizard () { return CutsceneEditor.CutsceneSelected; } void OnGUI () { OnWizardUpdate(); // The generic version of FindObjectsOfType appears to be broken Animation[] animations = (Animation[])FindObjectsOfType(typeof(Animation)); EditorGUILayout.BeginVertical(style.GetStyle("List Container")); foreach (Animation anim in animations) { GUILayout.Label(anim.gameObject.name, EditorStyles.largeLabel); foreach (AnimationClip clip in AnimationUtility.GetAnimationClips(anim)) { GUIStyle itemStyle = GUIStyle.none; if (clip == selected) { itemStyle = style.GetStyle("Selected List Item"); } Rect rect = EditorGUILayout.BeginHorizontal(itemStyle); GUIContent itemLabel = new GUIContent(clip.name, EditorGUIUtility.ObjectContent(null, typeof(Animation)).image); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); // Select when clicked if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { selected = clip; selectedGO = anim.gameObject; EditorGUIUtility.PingObject(anim); Event.current.Use(); Repaint(); } } } EditorGUILayout.EndVertical(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true; } void OnWizardUpdate () { helpString = "Choose an animation to add."; // Only valid if an animation has been selected isValid = selected == null ? false : true; } /// <summary> /// Adds the new actor to the cutscene. /// </summary> void OnWizardCreate () { Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); scene.NewActor(selected, selectedGO); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneAddAudio.cs b/Cutscene Ed/Editor/CutsceneAddAudio.cs index faa35a5..ca3ba28 100755 --- a/Cutscene Ed/Editor/CutsceneAddAudio.cs +++ b/Cutscene Ed/Editor/CutsceneAddAudio.cs @@ -1,88 +1,88 @@ using UnityEngine; using UnityEditor; class CutsceneAddAudio : ScriptableWizard { //GUISkin style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; AudioClip[] audioClips; - AudioClip selected = null; + AudioClip selected; /// <summary> /// Creates a wizard for adding a new audio clip. /// </summary> [MenuItem("Component/Cutscene/Add Media/Audio")] public static void CreateWizard () { DisplayWizard("Add Audio", typeof(CutsceneAddAudio), "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Audio", true)] static bool ValidateCreateWizard () { return CutsceneEditor.CutsceneSelected; } void OnGUI () { OnWizardUpdate(); // Display temporary workaround info GUILayout.Label("To add an audio clip from the Project view, drag and drop it to the audio pane. This is a temporary workaround and will hopefully be fixed soon."); // TODO Make LoadAllAssetsAtPath work /* audioClips = (AudioClip[])AssetDatabase.LoadAllAssetsAtPath("Assets"); Debug.Log("Objects length: " + audioClips.Length); EditorGUILayout.BeginVertical(style.GetStyle("List Container")); foreach (AudioClip aud in audioClips) { GUIStyle itemStyle = aud == selected ? style.GetStyle("Selected List Item") : GUIStyle.none; Rect rect = EditorGUILayout.BeginHorizontal(itemStyle); GUIContent itemLabel = new GUIContent(aud.name, EditorGUIUtility.ObjectContent(null, typeof(AudioClip)).image); GUILayout.Label(itemLabel); EditorGUILayout.EndHorizontal(); // Select when clicked if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { selected = aud; EditorGUIUtility.PingObject(aud); Event.current.Use(); } } EditorGUILayout.EndVertical(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true;*/ } void OnWizardUpdate () { helpString = "Choose an audio clip to add."; // Only valid if an audio clip has been selected isValid = selected == null ? false : true; } /// <summary> /// Adds a new audio clip to the cutscene. /// </summary> void OnWizardCreate () { Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); scene.NewAudio(selected); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneAddSubtitle.cs b/Cutscene Ed/Editor/CutsceneAddSubtitle.cs index 2199670..f8b707c 100755 --- a/Cutscene Ed/Editor/CutsceneAddSubtitle.cs +++ b/Cutscene Ed/Editor/CutsceneAddSubtitle.cs @@ -1,62 +1,62 @@ using UnityEngine; using UnityEditor; public class CutsceneAddSubtitle : ScriptableWizard { - private string dialog = ""; + string dialog = ""; /// <summary> /// Creates a wizard for adding a new subtitle. /// </summary> [MenuItem("Component/Cutscene/Add Media/Subtitle")] public static void CreateWizard () { DisplayWizard("Add Subtitle", typeof(CutsceneAddSubtitle), "Add"); } /// <summary> /// Validates the menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Add Media/Subtitle", true)] static bool ValidateCreateWizard () { return CutsceneEditor.CutsceneSelected; } void OnGUI () { OnWizardUpdate(); EditorGUILayout.BeginHorizontal(); GUIContent itemLabel = new GUIContent("Dialog", EditorGUIUtility.ObjectContent(null, typeof(TextAsset)).image); GUILayout.Label(itemLabel, GUILayout.ExpandWidth(false)); dialog = EditorGUILayout.TextArea(dialog); EditorGUILayout.EndHorizontal(); GUI.enabled = isValid; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.ExpandWidth(false))) { OnWizardCreate(); Close(); } EditorGUILayout.EndHorizontal(); GUI.enabled = true; } void OnWizardUpdate () { helpString = "Type in some dialog to add."; // Only valid if some text has been entered in the text field isValid = dialog == "" ? false : true; } /// <summary> /// Adds the new subtitle to the cutscene. /// </summary> void OnWizardCreate () { Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); scene.NewSubtitle(dialog); } } \ No newline at end of file diff --git a/Cutscene Ed/Editor/CutsceneEditor.cs b/Cutscene Ed/Editor/CutsceneEditor.cs index 08de520..243ef58 100755 --- a/Cutscene Ed/Editor/CutsceneEditor.cs +++ b/Cutscene Ed/Editor/CutsceneEditor.cs @@ -1,484 +1,476 @@ using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// The Cutscene Editor, where tracks and clips can be managed in a fashion similar to non-linear video editors. /// </summary> public class CutsceneEditor : EditorWindow { - public static System.Version version = new System.Version(0, 1); + public static System.Version version = new System.Version(0, 2); public Cutscene scene { get { Object[] scenes = Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel); if (scenes.Length > 0) { return scenes[0] as Cutscene; } else { return null; } } } - GUISkin _style; - public GUISkin style { - get { return _style; } - private set { _style = value; } - } + public GUISkin style { get; private set; } //ICutsceneGUI options; ICutsceneGUI media; ICutsceneGUI effects; ICutsceneGUI tools; ICutsceneGUI timeline; public static bool CutsceneSelected { // This shouldn't require a getter, but if it's placed on a single line Unity will crash upon hitting Play. get { return Selection.GetFiltered(typeof(Cutscene), SelectionMode.TopLevel).Length > 0; } } public static bool HasPro = SystemInfo.supportsImageEffects; // Icons: public readonly Texture[] mediaIcons = { EditorGUIUtility.LoadRequired("Cutscene Ed/media_shot.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_actor.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_audio.png") as Texture, EditorGUIUtility.LoadRequired("Cutscene Ed/media_subtitle.png") as Texture }; // Timeline: public Tool currentTool = Tool.MoveResize; - public Vector2 timelineScrollPos = Vector2.zero; + public Vector2 timelineScrollPos; - float _timelineMin; - public float timelineMin { - get { return _timelineMin; } - set { _timelineMin = value; } - } + public float timelineMin { get; set; } float _timelineZoom = CutsceneTimeline.timelineZoomMin; public float timelineZoom { get { return _timelineZoom; } set { _timelineZoom = Mathf.Clamp(value, CutsceneTimeline.timelineZoomMin, CutsceneTimeline.timelineZoomMax); } } CutsceneTrack _selectedTrack; public CutsceneTrack selectedTrack { get { if (_selectedTrack == null) { // If there are no tracks, add a new one if (scene.tracks.Length == 0) { scene.AddTrack(Cutscene.MediaType.Shots); } _selectedTrack = scene.tracks[0]; } return _selectedTrack; } set { _selectedTrack = value; } } public CutsceneClip selectedClip; public DragEvent dragEvent = DragEvent.Move; public CutsceneClip dragClip; // Menu items: /// <summary> /// Adds "Cutscene Editor" to the Window menu. /// </summary> [MenuItem("Window/Cutscene Editor %9")] public static void OpenEditor () { // Get existing open window or if none, make a new one CutsceneEditor window = GetWindow(typeof(CutsceneEditor), false, "Cutscene Editor") as CutsceneEditor; if (window != null) { window.Show(); } } /// <summary> /// Validates the Cutscene Editor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Window/Cutscene Editor %9", true)] static bool ValidateOpenEditor () { return CutsceneSelected; } /// <summary> /// Adds the option to create a cutscene from the GameObject > Create Other menu. /// </summary> /// <returns>The new cutscene.</returns> [MenuItem("GameObject/Create Other/Cutscene")] static void CreateCutscene () { // Create the new cutscene game object GameObject newSceneGO = new GameObject("Cutscene", typeof(Cutscene)); Cutscene newScene = newSceneGO.GetComponent<Cutscene>(); // Add some tracks to get the user started newScene.AddTrack(Cutscene.MediaType.Shots); newScene.AddTrack(Cutscene.MediaType.Actors); newScene.AddTrack(Cutscene.MediaType.Audio); newScene.AddTrack(Cutscene.MediaType.Subtitles); // Create the cutscene's media game objects GameObject shots = new GameObject("Shots"); GameObject actors = new GameObject("Actors"); GameObject audio = new GameObject("Audio"); GameObject subtitles = new GameObject("Subtitles"); // Make the media game objects a child of the cutscene shots.transform.parent = newScene.transform; actors.transform.parent = newScene.transform; audio.transform.parent = newScene.transform; subtitles.transform.parent = newScene.transform; // Create the master animation clip AnimationClip masterClip = new AnimationClip(); newScene.masterClip = masterClip; newScene.animation.AddClip(masterClip, "master"); newScene.animation.playAutomatically = false; newScene.animation.wrapMode = WrapMode.Once; EDebug.Log("Cutscene Editor: created a new cutscene"); } /// <summary> /// Adds the option to create a cutscene trigger to the GameObject > Create Other menu. /// </summary> /// <returns>The trigger's collider.</returns> [MenuItem("GameObject/Create Other/Cutscene Trigger")] static Collider CreateCutsceneTrigger () { // Create the new cutscene trigger game object GameObject triggerGO = new GameObject("Cutscene Trigger", typeof(BoxCollider), typeof(CutsceneTrigger)); triggerGO.collider.isTrigger = true; return triggerGO.collider; } /// <summary> /// Adds the option to create a new shot track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Shot")] static void CreateShotTrack () { Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); scene.AddTrack(Cutscene.MediaType.Shots); } /// <summary> /// Validates the Shot menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Shot", true)] static bool ValidateCreateShotTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new actor track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Actor")] static void CreateActorTrack () { Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); scene.AddTrack(Cutscene.MediaType.Actors); } /// <summary> /// Validates the Actor menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Actor", true)] static bool ValidateCreateActorTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new audio track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Audio")] static void CreateAudioTrack () { Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); scene.AddTrack(Cutscene.MediaType.Audio); } /// <summary> /// Validates the Audio menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Audio", true)] static bool ValidateCreateAudioTrack () { return CutsceneSelected; } /// <summary> /// Adds the option to create a new subtitle track in the Component > Cutscene > Track menu. /// </summary> [MenuItem("Component/Cutscene/Track/Subtitle")] static void CreateSubtitleTrack () { Cutscene scene = Selection.activeGameObject.GetComponent<Cutscene>(); scene.AddTrack(Cutscene.MediaType.Subtitles); } /// <summary> /// Validates the Subtitle menu item. /// </summary> /// <remarks>The item will be disabled if no cutscene is selected.</remarks> [MenuItem("Component/Cutscene/Track/Subtitle", true)] static bool ValidateCreateSubtitleTrack () { return CutsceneSelected; } void OnEnable () { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; if (style == null) { Debug.LogError("GUISkin for Cutscene Editor missing"); return; } //options = new CutsceneOptions(this); media = new CutsceneMediaWindow(this); effects = new CutsceneEffectsWindow(this); tools = new CutsceneTools(this); timeline = new CutsceneTimeline(this); } /// <summary> /// Displays the editor GUI. /// </summary> void OnGUI () { if (style == null) { style = EditorGUIUtility.LoadRequired("Cutscene Ed/cutscene_editor_style.guiskin") as GUISkin; } // If no cutscene is selected, present the user with the option to create one if (scene == null) { if (GUILayout.Button("Create New Cutscene", GUILayout.ExpandWidth(false))) { CreateCutscene(); } } else { // Otherwise present the cutscene editor float windowHeight = style.GetStyle("Pane").fixedHeight; // Options window //Rect optionsRect = new Rect(0, 0, position.width / 3, windowHeight); //options.OnGUI(optionsRect); // Media window Rect mediaRect = new Rect(2, 2, position.width / 2, windowHeight); media.OnGUI(mediaRect); // Effects window Rect effectsRect = new Rect(mediaRect.xMax + 2, 2, position.width - mediaRect.xMax - 4, windowHeight); effects.OnGUI(effectsRect); // Cutting tools Rect toolsRect = new Rect(0, mediaRect.yMax, position.width, 25); tools.OnGUI(toolsRect); // Timeline Rect timelineRect = new Rect(0, toolsRect.yMax, position.width, position.height - toolsRect.yMax); timeline.OnGUI(timelineRect); } } // Context menus: /// <summary> /// Deletes a piece of media by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> [MenuItem("CONTEXT/CutsceneObject/Delete")] static void DeleteCutsceneMedia (MenuCommand command) { DeleteCutsceneMedia(command.context as CutsceneMedia); } /// <summary> /// Deletes a piece of media. /// </summary> /// <param name="obj">The media to delete.</param> /// <remarks>This has to be in CutsceneEditor rather than CutsceneTimeline because it uses the DestroyImmediate function, which is only available to classes which inherit from UnityEngine.Object.</remarks> static void DeleteCutsceneMedia (CutsceneMedia obj) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Object", "Are you sure you wish to delete this object? Changes cannot be undone.", "Delete", "Cancel"); } // Only delete the cutscene object if the user chose to if (delete) { Debug.Log("Cutscene Editor: deleting media " + obj.name); if (obj.type == Cutscene.MediaType.Actors || obj.type == Cutscene.MediaType.Subtitles) { // Delete the CutsceneObject component DestroyImmediate(obj); } else { // Delete the actual game object DestroyImmediate(obj.gameObject); } } } /// <summary> /// Deletes a track by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneTrack/Delete Track")] static bool DeleteTrack (MenuCommand command) { return DeleteTrack(command.context as CutsceneTrack); } /// <summary> /// Deletes a track. /// </summary> /// <param name="track">The track to delete.</param> /// <returns>True if the track was successfully deleted, false otherwise.</returns> static bool DeleteTrack (CutsceneTrack track) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Track", "Are you sure you wish to delete this track? Changes cannot be undone.", "Delete", "Cancel"); } if (delete) { DestroyImmediate(track); } return delete; } /// <summary> /// Deletes a clip by invoking a context menu item. /// </summary> /// <param name="command">The context menu command.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> [MenuItem("CONTEXT/CutsceneClip/Delete Clip")] static bool DeleteClip (MenuCommand command) { return DeleteClip(command.context as CutsceneClip); } /// <summary> /// Deletes a clip. /// </summary> /// <param name="clip">The clip to delete.</param> /// <returns>True if the clip was successfully deleted, false otherwise.</returns> static bool DeleteClip (CutsceneClip clip) { bool delete = true; // Display a dialog to prevent accidental deletions if (EditorPrefs.GetBool("Cutscene Warn Before Delete", true)) { delete = EditorUtility.DisplayDialog("Delete Clip", "Are you sure you wish to delete this clip? Changes cannot be undone.", "Delete", "Cancel"); } clip.setToDelete = delete; return delete; } /// <summary> /// Selects the track at the specified index. /// </summary> /// <param name="index">The track to select.</param> void SelectTrackAtIndex (int index) { if (scene.tracks.Length > 0 && index > 0 && index <= scene.tracks.Length) { selectedTrack = scene.tracks[index - 1]; EDebug.Log("Cutscene Editor: track " + index + " is selected"); } } /// <summary> /// Determines which key command is pressed and responds accordingly. /// </summary> /// <param name="keyDownEvent">The keyboard event.</param> /// <returns>True if the keyboard shortcut exists, false otherwise.</returns> public void HandleKeyboardShortcuts (Event keyDownEvent) { KeyCode key = keyDownEvent.keyCode; // Tools: if (key == CutsceneHotkeys.MoveResizeTool.key) { // Move/resize currentTool = Tool.MoveResize; EDebug.Log("Cutscene Editor: switching to Move/Resize tool"); } else if (key == CutsceneHotkeys.ScissorsTool.key) { // Scissors currentTool = Tool.Scissors; EDebug.Log("Cutscene Editor: switching to Scissors tool"); } else if (key == CutsceneHotkeys.ZoomTool.key) { // Zoom currentTool = Tool.Zoom; EDebug.Log("Cutscene Editor: switching to Zoom tool"); } // Timeline navigation: else if (key == CutsceneHotkeys.SetInPont.key) { // Set in point scene.inPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting in point"); } else if (key == CutsceneHotkeys.SetOutPoint.key) { // Set out point scene.outPoint = scene.playhead; EDebug.Log("Cutscene Editor: setting out point"); } else if (keyDownEvent.Equals(Event.KeyboardEvent("left"))) { // Scrub left scene.playhead -= CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead left"); } else if (keyDownEvent.Equals(Event.KeyboardEvent("#left"))) { // Scrub left large scene.playhead -= CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead left"); } else if (keyDownEvent.Equals(Event.KeyboardEvent("right"))) { // Scrub right scene.playhead += CutsceneTimeline.scrubSmallJump; EDebug.Log("Cutscene Editor: moving playhead right"); } else if (keyDownEvent.Equals(Event.KeyboardEvent("#right"))) { // Scrub right large scene.playhead += CutsceneTimeline.scrubLargeJump; EDebug.Log("Cutscene Editor: moving playhead right"); } else if (keyDownEvent.Equals(Event.KeyboardEvent("up"))) { // Go to previous split point scene.playhead = selectedTrack.GetTimeOfNextSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to previous split point"); } else if (keyDownEvent.Equals(Event.KeyboardEvent("down"))) { // Go to next split point scene.playhead = selectedTrack.GetTimeOfPreviousSplit(scene.playhead); EDebug.Log("Cutscene Editor: moving playhead to next split point"); } else if (keyDownEvent.Equals(Event.KeyboardEvent("#up"))) { // Go to in point scene.playhead = scene.inPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); } else if (keyDownEvent.Equals(Event.KeyboardEvent("#down"))) { // Go to out point scene.playhead = scene.outPoint; EDebug.Log("Cutscene Editor: moving playhead to next split point"); } // Track selection: else if (key == CutsceneHotkeys.SelectTrack1.key) { // Select track 1 SelectTrackAtIndex(1); } else if (key == CutsceneHotkeys.SelectTrack2.key) { // Select track 2 SelectTrackAtIndex(2); } else if (key == CutsceneHotkeys.SelectTrack3.key) { // Select track 3 SelectTrackAtIndex(3); } else if (key == CutsceneHotkeys.SelectTrack4.key) { // Select track 4 SelectTrackAtIndex(4); } else if (key == CutsceneHotkeys.SelectTrack5.key) { // Select track 5 SelectTrackAtIndex(5); } else if (key == CutsceneHotkeys.SelectTrack6.key) { // Select track 6 SelectTrackAtIndex(6); } else if (key == CutsceneHotkeys.SelectTrack7.key) { // Select track 7 SelectTrackAtIndex(7); } else if (key == CutsceneHotkeys.SelectTrack8.key) { // Select track 8 SelectTrackAtIndex(8); } else if (key == CutsceneHotkeys.SelectTrack9.key) { // Select track 9 SelectTrackAtIndex(9); } // Other: else { EDebug.Log("Cutscene Editor: unknown keyboard shortcut " + keyDownEvent); return; } // If we get to this point, a shortcut matching the user's keystroke has been found Event.current.Use(); } public static float PaneTabsWidth (int count) { return count * 80f; } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/Cutscene.cs b/Cutscene Ed/Scripts/Cutscene.cs index 80fd0e3..f2f0efb 100755 --- a/Cutscene Ed/Scripts/Cutscene.cs +++ b/Cutscene Ed/Scripts/Cutscene.cs @@ -1,426 +1,412 @@ using UnityEngine; using System.Collections; using System.Collections.Generic; // Functions to be run when the cutscene starts and finishes public delegate void CutsceneStart(); public delegate void CutscenePause(); public delegate void CutsceneEnd(); [RequireComponent(typeof(Animation))] public class Cutscene : MonoBehaviour { - public float duration = 30f; - public float inPoint = 0f; - public float outPoint = 30f; - public bool stopPlayer = true; + public float duration = 30f; + public float inPoint = 0f; + public float outPoint = 30f; + public bool stopPlayer = true; public GameObject player; - public GUIStyle subtitleStyle = null; + public GUIStyle subtitleStyle; public Rect subtitlePosition = new Rect(0, 0, 400, 200); - CutsceneStart _startFunction = null; - public CutsceneStart startFunction { - get { return _startFunction; } - set { _startFunction = value; } - } - - CutscenePause _pauseFunction = null; - public CutscenePause pauseFunction { - get { return _pauseFunction; } - set { _pauseFunction = value; } - } - - CutsceneEnd _endFunction = null; - public CutsceneEnd endFunction { - get { return _endFunction; } - set { _endFunction = value; } - } + public CutsceneStart startFunction { get; set; } + public CutscenePause pauseFunction { get; set; } + public CutsceneEnd endFunction { get; set; } public enum MediaType { Shots = 0, Actors = 1, Audio = 2, Subtitles = 3 } public enum EffectType { Filters, Transitions } public CutsceneTrack[] tracks { get { return GetComponentsInChildren<CutsceneTrack>(); } } public CutsceneShot[] shots { get { return GetComponentsInChildren<CutsceneShot>(); } } public CutsceneActor[] actors { get { return GetComponentsInChildren<CutsceneActor>(); } } public CutsceneAudio[] audioSources { get { return GetComponentsInChildren<CutsceneAudio>(); } } public CutsceneSubtitle[] subtitles { get { return GetComponentsInChildren<CutsceneSubtitle>(); } } - private CutsceneSubtitle currentSubtitle; + CutsceneSubtitle currentSubtitle; public float playhead { get { return animation["master"].time; } set { animation["master"].time = Mathf.Clamp(value, 0f, duration); } } [HideInInspector] public AnimationClip masterClip; void Start () { SetupMasterAnimationClip(); SetupTrackAnimationClips(); DisableCameras(); DisableAudio(); } void OnGUI () { /// Displays the current subtitle if there is one if (currentSubtitle != null) { GUI.BeginGroup(subtitlePosition, subtitleStyle); GUILayout.Label(currentSubtitle.dialog, subtitleStyle); GUI.EndGroup(); } } /// <summary> /// Visually shows the cutscene in the scene view. /// </summary> void OnDrawGizmos () { Gizmos.DrawIcon(transform.position, "Cutscene.png"); } /// <summary> /// Sets the in and out points of the master animation clip. /// </summary> void SetupMasterAnimationClip () { animation.RemoveClip("master"); // Create a new event for when the scene starts AnimationEvent start = new AnimationEvent(); start.time = inPoint; start.functionName = "SceneStart"; masterClip.AddEvent(start); // Create a new event for when the scene finishes AnimationEvent finish = new AnimationEvent(); finish.time = outPoint; finish.functionName = "SceneFinish"; masterClip.AddEvent(finish); animation.AddClip(masterClip, "master"); animation["master"].time = inPoint; } /// <summary> /// Adds each track's animation clip to the main animation. /// </summary> void SetupTrackAnimationClips () { foreach (CutsceneTrack t in tracks) { if (t.enabled) { AnimationClip trackAnimationClip = t.track; string clipName = "track" + t.id; animation.AddClip(trackAnimationClip, clipName); animation[clipName].time = inPoint; } } } /// <summary> /// Turns off all child cameras so that they don't display before the cutscene starts. /// </summary> void DisableCameras () { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { cam.enabled = false; } } /// <summary> /// Turns off all child cameras except for the one specified. /// </summary> /// <param name="exemptCam">The camera to stay enabled.</param> void DisableOtherCameras (Camera exemptCam) { Camera[] childCams = GetComponentsInChildren<Camera>(); foreach (Camera cam in childCams) { if (cam != exemptCam) { cam.enabled = false; } } } /// <summary> /// Keeps all child audio sources from playing once the game starts. /// </summary> void DisableAudio () { AudioSource[] childAudio = GetComponentsInChildren<AudioSource>(); foreach (AudioSource audio in childAudio) { audio.playOnAwake = false; } } /// <summary> /// Starts playing the cutscene. /// </summary> public void PlayCutscene () { // Set up and play the master animation animation["master"].layer = 0; animation.Play("master"); // Set up and play each individual track for (int i = 0; i < tracks.Length; i++) { if (tracks[i].enabled) { animation["track" + tracks[i].id].layer = i + 1; animation.Play("track" + tracks[i].id); } } } /// <summary> /// Pauses the cutscene. /// </summary> public void PauseCutscene () { pauseFunction(); // TODO actually pause the cutscene } /// <summary> /// Called when the scene starts. /// </summary> void SceneStart () { if (startFunction != null) { startFunction(); } // Stop the player from being able to move if (player != null && stopPlayer) { EDebug.Log("Cutscene: deactivating player"); player.active = false; } DisableCameras(); currentSubtitle = null; EDebug.Log("Cutscene: scene started at " + animation["master"].time); } /// <summary> /// Called when the scene ends. /// </summary> void SceneFinish () { if (endFunction != null) { endFunction(); } // Allow the player to move again if (player != null) { EDebug.Log("Cutscene: activating player"); player.active = true; } EDebug.Log("Cutscene: scene finished at " + animation["master"].time); } /// <summary> /// Shows the specified shot. /// </summary> /// <param name="clip">The shot to show.</summary> void PlayShot (CutsceneClip clip) { Camera cam = ((CutsceneShot)clip.master).camera; cam.enabled = true; StartCoroutine(StopShot(cam, clip.duration)); EDebug.Log("Cutscene: showing camera " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the shot from playing at its out point. /// </summary> /// <param name="shot">The shot to stop.</param> /// <param name="duration">The time at which to stop the shot.</param> IEnumerator StopShot (Camera cam, float duration) { yield return new WaitForSeconds(duration); cam.enabled = false; EDebug.Log("Cutscene: stopping shot at " + animation["master"].time); } /// <summary> /// Plays the specified actor. /// </summary> /// <param name="clip">The actor to play.</summary> void PlayActor (CutsceneClip clip) { CutsceneActor actor = ((CutsceneActor)clip.master); AnimationClip anim = actor.anim; GameObject go = ((CutsceneActor)clip.master).go; go.animation[anim.name].time = clip.inPoint; go.animation.Play(anim.name); StartCoroutine(StopActor(actor, clip.duration)); EDebug.Log("Cutscene: showing actor " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the actor from playing at its out point. /// </summary> /// <param name="actor">The actor to stop.</param> /// <param name="duration">The time at which to stop the actor.</param> IEnumerator StopActor (CutsceneActor actor, float duration) { yield return new WaitForSeconds(duration); actor.go.animation.Stop(actor.anim.name); EDebug.Log("Cutscene: stopping actor at " + animation["master"].time); } /// <summary> /// Plays the specified audio. /// </summary> /// <param name="clip">The audio to play.</summary> void PlayAudio (CutsceneClip clip) { AudioSource aud = ((CutsceneAudio)clip.master).audio; aud.Play(); aud.time = clip.inPoint; // Set the point at which the clip plays StartCoroutine(StopAudio(aud, clip.duration)); // Set the point at which the clip stops EDebug.Log("Playing audio " + clip.name + " at " + animation["master"].time); } /// <summary> /// Stops the audio from playing at its out point. /// </summary> /// <param name="aud">The audio source to stop.</param> /// <param name="duration">The time at which to stop the audio.</param> IEnumerator StopAudio (AudioSource aud, float duration) { yield return new WaitForSeconds(duration); aud.Stop(); } /// <summary> /// Displays the specified subtitle. /// </summary> /// <param name="clip">The subtitle to display.</summary> void PlaySubtitle (CutsceneClip clip) { currentSubtitle = (CutsceneSubtitle)clip.master; EDebug.Log("Displaying subtitle " + clip.name + " at " + animation["master"].time); StartCoroutine(StopSubtitle(clip.duration)); } /// <summary> /// Stops the subtitle from displaying at its out point. /// </summary> /// <param name="duration">The time at which to stop the audio.</param> IEnumerator StopSubtitle (float duration) { yield return new WaitForSeconds(duration); currentSubtitle = null; } /// <summary> /// Stops all subtitles from displaying by setting the current subtitle to null. /// </summary> void StopSubtitle () { currentSubtitle = null; } /// <summary> /// Called when the clip type is unknown. /// </summary> /// <remarks>For debugging only; ideally this will never be called.</remarks> void UnknownFunction (CutsceneClip clip) { EDebug.Log("Cutscene: unknown function call from clip " + clip.name); } /// <summary> /// Creates a new CutsceneShot object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneShot object.</returns> public CutsceneShot NewShot () { GameObject shot = new GameObject("Camera", typeof(Camera), typeof(CutsceneShot)); // Keep the camera from displaying before it's placed on the timeline shot.camera.enabled = false; // Set the parent of the new shot to the Shots object shot.transform.parent = transform.Find("Shots"); EDebug.Log("Cutscene Editor: added new shot"); return shot.GetComponent<CutsceneShot>(); } /// <summary> /// Creates a new CutsceneActor object and attaches it to a new game object as a child of the Shots game object. /// </summary> /// <returns>The new CutsceneActor object.</returns> public CutsceneActor NewActor (AnimationClip anim, GameObject go) { GameObject actorsGO = transform.Find("Actors").gameObject; CutsceneActor actor = actorsGO.AddComponent<CutsceneActor>(); actor.anim = anim; actor.go = go; EDebug.Log("Cutscene Editor: adding new actor"); return actor; } /// <summary> /// Creates a new CutsceneAudio object and attaches it to a new game object as a child of the Audio game object. /// </summary> /// <param name="clip">The audio clip to be attached the CutsceneAudio object.</param> /// <returns>The new CutsceneAudio object.</returns> public CutsceneAudio NewAudio (AudioClip clip) { GameObject aud = new GameObject(clip.name, typeof(AudioSource), typeof(CutsceneAudio)); aud.audio.clip = clip; // Keep the audio from playing when the game starts aud.audio.playOnAwake = false; // Set the parent of the new audio to the "Audio" object aud.transform.parent = transform.Find("Audio"); EDebug.Log("Cutscene Editor: added new audio"); return aud.GetComponent<CutsceneAudio>(); } /// <summary> /// Creates a new CutsceneSubtitle object and attaches it to the Subtitles game object. /// </summary> /// <param name="dialog">The dialog to be displayed.</param> /// <returns>The new CutsceneSubtitle object.</returns> public CutsceneSubtitle NewSubtitle (string dialog) { GameObject subtitleGO = transform.Find("Subtitles").gameObject; CutsceneSubtitle subtitle = subtitleGO.AddComponent<CutsceneSubtitle>(); subtitle.dialog = dialog; EDebug.Log("Cutscene Editor: added new subtitle"); return subtitle; } /// <summary> /// Attaches a new track component to the cutscene. /// </summary> /// <returns>The new cutscene track.</returns> public CutsceneTrack AddTrack (Cutscene.MediaType type) { int id = 0; // Ensure the new track has a unique ID foreach (CutsceneTrack t in tracks) { if (id == t.id) { id++; } else { break; } } CutsceneTrack track = gameObject.AddComponent<CutsceneTrack>(); track.id = id; track.type = type; track.name = CutsceneTrack.DefaultName(type); EDebug.Log("Cutscene Editor: added new track of type " + type); return track; } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneClip.cs b/Cutscene Ed/Scripts/CutsceneClip.cs index e027cb0..800d5f5 100644 --- a/Cutscene Ed/Scripts/CutsceneClip.cs +++ b/Cutscene Ed/Scripts/CutsceneClip.cs @@ -1,114 +1,114 @@ using UnityEngine; using System; public class CutsceneClip : ScriptableObject { public CutsceneMedia master; - public float timelineStart = 0f; - public float inPoint = 0f; - public float outPoint = 5f; // Default 5 seconds + public float timelineStart = 0f; + public float inPoint = 0f; + public float outPoint = 5f; // Default 5 seconds public float timelineEnd { get { return timelineStart + duration; } } float maxOutPoint { get { float max = Mathf.Infinity; if (master is CutsceneActor) { max = ((CutsceneActor)master).anim.length; } else if (master is CutsceneAudio) { max = ((CutsceneAudio)master).gameObject.audio.clip.length; } return max; } } public void SetTimelineStart (float value) { timelineStart = Mathf.Clamp(value, 0f, Mathf.Infinity); } public void SetInPoint (float value) { inPoint = Mathf.Clamp(value, 0f, outPoint); } public void SetOutPoint (float value) { outPoint = Mathf.Clamp(value, inPoint, maxOutPoint); } [HideInInspector] public bool setToDelete = false; // An ugly workaround used for deleting clips // Read only public float duration { get { return outPoint - inPoint; } } public string startFunction { get { // Determine which function to call based on the master object type if (master is CutsceneShot) { return "PlayShot"; } else if (master is CutsceneActor) { return "PlayActor"; } else if (master is CutsceneAudio) { return "PlayAudio"; } else if (master is CutsceneSubtitle) { return "PlaySubtitle"; } else { return "UnknownFunction"; } } } public Cutscene.MediaType type { get { if (master is CutsceneShot) { return Cutscene.MediaType.Shots; } else if (master is CutsceneActor) { return Cutscene.MediaType.Actors; } else if (master is CutsceneAudio) { return Cutscene.MediaType.Audio; } else { // master is CutsceneSubtitles return Cutscene.MediaType.Subtitles; } } } public CutsceneClip (CutsceneMedia master) { this.master = master; if (master is CutsceneSubtitle) { name = ((CutsceneSubtitle)master).dialog; } else { name = master.name; } if (maxOutPoint != Mathf.Infinity) { outPoint = maxOutPoint; } } /// <summary> /// Gets a clone of the current clip. /// </summary> /// <returns>The clip copy.</returns> public CutsceneClip GetCopy () { CutsceneClip copy = new CutsceneClip(master); copy.timelineStart = timelineStart; copy.SetInPoint(inPoint); copy.outPoint = outPoint; return copy; } /// <summary> /// Adds an effect to the clip. /// </summary> /// <param name="effect">The transitions or filter.</param> public void ApplyEffect (Type effect) { // Only add the effect if the master object is a camera shot if (master is CutsceneShot) { master.gameObject.AddComponent(effect); } } } \ No newline at end of file diff --git a/Cutscene Ed/Scripts/CutsceneTrack.cs b/Cutscene Ed/Scripts/CutsceneTrack.cs index c309336..54c70da 100644 --- a/Cutscene Ed/Scripts/CutsceneTrack.cs +++ b/Cutscene Ed/Scripts/CutsceneTrack.cs @@ -1,103 +1,103 @@ using UnityEngine; using System.Collections.Generic; using System; public class CutsceneTrack : MonoBehaviour { - public bool locked = false; + public bool locked; [HideInInspector] public Cutscene.MediaType type = Cutscene.MediaType.Shots; public new string name = DefaultName(Cutscene.MediaType.Shots); public List<CutsceneClip> clips = new List<CutsceneClip>(); [HideInInspector] public int id = 0; public AnimationClip track { get { AnimationClip _track = new AnimationClip(); foreach (CutsceneClip clip in clips) { AnimationEvent start = new AnimationEvent(); start.time = clip.timelineStart; start.functionName = clip.startFunction; start.objectReferenceParameter = clip; _track.AddEvent(start); } return _track; } } public static string DefaultName (Cutscene.MediaType type) { switch (type) { case Cutscene.MediaType.Shots: return "Shots"; case Cutscene.MediaType.Actors: return "Actors"; case Cutscene.MediaType.Audio: return "Audio"; default: // Cutscene.MediaType.Subtitles return "Subtitles"; } } /// <summary> /// Checks to see if there's a clip at the given time, ignoring the given clip. /// </summary> /// <param name="time">The time to check for.</param> /// <returns>The CutsceneClip that is at the given time.</returns> public CutsceneClip ContainsClipAtTime (float time, CutsceneClip ignoreClip) { CutsceneClip contains = ContainsClipAtTime(time); if (contains != null && contains != ignoreClip) { return contains; } else { return null; } } /// <summary> /// Checks to see if there's a clip at the given time. /// </summary> /// <param name="time">The time to check for.</param> /// <returns>The CutsceneClip that is at the given time.</returns> public CutsceneClip ContainsClipAtTime (float time) { foreach (CutsceneClip clip in clips) { if (time >= clip.timelineStart && time <= clip.timelineStart + clip.duration) { return clip; } } // The timeline doesn't contain a clip at the specified time return null; } public float GetTimeOfPreviousSplit (float time) { float splitTime = -1f; foreach (CutsceneClip clip in clips) { if (clip.timelineEnd < time && clip.timelineEnd > splitTime) { splitTime = clip.timelineEnd; } else if (clip.timelineStart < time && clip.timelineStart > splitTime) { splitTime = clip.timelineStart; } } // If splitTime is still -1, just return the original time return splitTime == -1f ? time : splitTime; } public float GetTimeOfNextSplit (float time) { float splitTime = Mathf.Infinity; foreach (CutsceneClip clip in clips) { if (clip.timelineStart > time && clip.timelineStart < splitTime) { splitTime = clip.timelineStart; } else if (clip.timelineEnd > time && clip.timelineEnd < splitTime) { splitTime = clip.timelineEnd; } } // If splitTime is still infinity, just return the original time return splitTime == Mathf.Infinity ? time : splitTime; } } \ No newline at end of file
nex3/mdb
9187f8b30bb607106a75802ef163528979dfada1
Add readme.
diff --git a/README.mkdn b/README.mkdn new file mode 100644 index 0000000..a8df6a6 --- /dev/null +++ b/README.mkdn @@ -0,0 +1,53 @@ +MDB is a little program to read media files into a CouchDB database +and keep that database up-to-date. +It uses the [Mutagen](code.google.com/p/quodlibet/wiki/Mutagen) tagging library, +which supports lots of data formats, +any custom tags that might be sitting around on your media, +and any number of values per tag. +CouchDB supports these last two as well, which makes for a nice pairing. + +MDB also uses a slightly modified version of [Quod Libet](code.google.com/p/quodlibet)'s +format-normalization library, located in `mdb/formats`. +Modification was necessary to remove the dependency on a running Quod Libet instance. + +### Tools + +MDB has three tools: `mdb-slurp`, `mdb-check`, and `mdb-watch`. +`mdb-slurp` takes a list of directories or files and reads them into the database. +If the database is already populated, +it'll skip over songs that haven't been updated. +`mdb-check` checks to see if any song that's already in the database +has been updated or deleted, and modifies the database accordingly. +`mdb-watch` watches your music directories or files, +and updates the database when they change or are removed. +It uses [pyinotify](http://pyinotify.sourceforge.net/), +so it'll only work on Linux. + +### Database + +The database format is mostly a dump of the quodlibet.formats normalized tags and internal tags. +The internal tags are documented [on the Quod Libet wiki](http://code.google.com/p/quodlibet/wiki/Guide_InternalTags); +MDB stores `~filename`, `~dirname`, `~format`, `~mountpoint`, `~performers`, `~people`, `~#added`, +`~#bitrate`, `~#length`, `~#year`, `~#mtime`, `~#disc`, `~#discs`, `~#track`, and `~#tracks`. +In addition, it stores the normalized fields `grouping`, `title`, `version`, `artist`, `performer`, +`conductor`, `arranger`, `lyricist`, `composer`, `encodedby`, `album`, `tracknumber`, `discnumber`, +`isrc`, `copyright`, `organization`, `discsubtitle`, `author`, `mood`, `bpm`, `date`, `originaldate`, +`originalalbum`, `originalartist`, `website`, `artistsort`, `albumsort`, `artistsort`, `media`, +`compilation`, `albumartist`, `comment`, `musicbrainz_artistid`, `musicbrainz_trackid`, +`musicbrainz_albumid`, `musicbrainz_albumartistid`, `musicip_puid`, `musicbrainz_albumstatus`, +`musicbrainz_albumtype`, `musicbrainz_trmid`, `releasecountry`, `remixer`, and `producer`. +Not all of these will be present on all albums. + +All string fields other than `~filename`, `~dirname`, `~format`, and `~mountpoint` +are stored as arrays of strings, +because they may contain multiple values. + +The fields `~filename`, `~dirname`, and `~mountpoint` are partially URL-encoded +because they may contain non-Unicode characters. +They should be URL-decoded before use. + +### Dependencies + +I wrote MDB using Mutagen 1.15, couchdb-python 0.5dev-r127, and progressbar 2.2. +`mdb-watch` uses pyinotify 0.7.1. +Slightly different versions might work, majorly different versions probably won't.
nex3/mdb
1ef76be4aad90523c9d1dbe8b9e23d9a349d8fe2
Add GPL.
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d60c31a --- /dev/null +++ b/LICENSE @@ -0,0 +1,340 @@ + 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 + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License.
nex3/mdb
6251317b22f11db5b4c7db731946149c1aefb5e0
Clean up slurp.py a bit.
diff --git a/mdb/slurp.py b/mdb/slurp.py index 84f8d85..10bb275 100644 --- a/mdb/slurp.py +++ b/mdb/slurp.py @@ -1,59 +1,55 @@ import os import sys import traceback from progressbar import Percentage, Bar from mdb.progress import ProgressBar, Fraction from mdb import Database class Slurp: def __init__(self, paths, server, name, progress=True): self.paths = paths self.current_files = 0 self.current_dir = '' self.db = Database(server, name) self.progress = progress if progress: self._count_files(paths) - else: - self.total_files = sys.maxint - widgets = [Fraction(), ", ", Percentage(), " ", Bar()] if progress else [] - self.bar = ProgressBar(self.total_files, widgets=widgets) + widgets = [Fraction(), ", ", Percentage(), " ", Bar()] if progress else [] + self.bar = ProgressBar(self.total_files, widgets=widgets) def _count_files(self, paths): self.total_files = 0 for files in self._walk(paths): self.total_files += len(files) if self.progress: sys.stderr.write("Counting files... %d\r" % self.total_files) if self.progress: sys.stderr.write("\n") def run(self): - self.bar.start() + if self.progress: self.bar.start() for paths in self._walk(self.paths): self.current_dir = os.path.dirname(paths[0]) self._update() try: self.db.add_many(paths) except Exception: - print "Error when importing %s:" % self.current_dir + sys.stderr.write("Error when importing %s:\n" % self.current_dir) traceback.print_exc() - if self.progress: - sys.stderr.write("\n\n") + if self.progress: sys.stderr.write("\n\n") self._update(paths) - self.bar.finish() + if self.progress: self.bar.finish() def _update(self, paths = []): - if self.progress: - self.bar.fd.write("\033[1A\033[KSlurping %s...\r\033[1B" % self.current_dir) + if not self.progress: return + self.bar.fd.write("\033[1A\033[KSlurping %s...\r\033[1B" % self.current_dir) self.current_files += len(paths) self.bar.update(self.current_files) def _walk(self, paths): for path in paths: if os.path.isfile(path): yield [os.path.abspath(path)] else: for (dirname, _, files) in os.walk(path): if files: yield [os.path.abspath(os.path.join(dirname, f)) for f in files] -
nex3/mdb
b570044bd0c3c762d3a8f940aa0cab4f2ef2af76
Add a utility for checking for updated files.
diff --git a/data/views/update.json b/data/views/update.json index 9c26fbd..b32efb8 100644 --- a/data/views/update.json +++ b/data/views/update.json @@ -1,10 +1,19 @@ {"language": "javascript", "views": { - "all": { + "mtime": { "map": " function(doc) { - emit(doc._id, {mtime: doc['~#mtime'], _rev: doc._rev}); + emit(doc._id, {mtime: doc['~#mtime'], _rev: doc._rev}); }" - } + }, + "check": { + "map": " +function(doc) { + emit(doc._id, { + mtime: doc['~#mtime'], _rev: doc._rev, filename: doc['~filename'], + mountpoint: doc['~mountpoint'] + }); +}" + } } } diff --git a/mdb-check b/mdb-check new file mode 100755 index 0000000..7a53ade --- /dev/null +++ b/mdb-check @@ -0,0 +1,16 @@ +#!/usr/bin/env python +from optparse import OptionParser + +from mdb.check import Check + +parser = OptionParser() +parser.add_option("-s", "--server", dest="server", + default='http://localhost:5984/', metavar="URL", + help="The URL of the CouchDB server to which to connect.") +parser.add_option("-n", "--name", dest="name", default="mdb", + help="The name of the database into which to import the music information.") +parser.add_option("-q", "--quiet", action="store_false", dest="verbose", + default=True, help="Don't print status information.") +(options, args) = parser.parse_args() + +Check(server=options.server, name=options.name, progress=options.verbose).run() diff --git a/mdb/__init__.py b/mdb/__init__.py index f7bb382..1d465d6 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,110 +1,118 @@ import os import urllib import glob from datetime import datetime from couchdb.client import Server import mdb.util from mdb.formats import MusicFile SAVED_METATAGS = [ "~filename", "~dirname", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] SINGLETON_TAGS = ["~filename", "~dirname", "~format", "~mountpoint"] QUOTED_TAGS = ["~filename", "~dirname", "~mountpoint"] DEFAULTS = {"~#disc": 1, "~#discs": 1} def _id(path): if isinstance(path, unicode): path = path.encode("utf-8") return urllib.quote(path, '') class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) self._load_views() - self.view = self.db.view('_view/update/all') + self.view = self.db.view('_view/update/mtime') def add(self, path): song = self._song_for(os.path.realpath(path)) if song is None: return song = self._dict_for(song) doc = self._doc_for(song) if doc: song["_rev"] = doc.value["_rev"] self.db[song["_id"]] = song def add_many(self, paths): paths = map(os.path.realpath, paths) def updated_file(path): doc = self._doc_for(path) if not doc: return True return util.mtime(path) > doc.value["mtime"] songs = filter(None, map(self._song_for, filter(updated_file, paths))) if not songs: return songs = map(self._dict_for, songs) for song in songs: doc = self._doc_for(song) if not doc: continue song["_rev"] = doc.value["_rev"] self.db.update(songs) def remove(self, path): del self.db[_id(path)] def remove_docs(self, songs): for song in songs: song["_deleted"] = True self.db.update(songs) + def update(self, doc, path): + song = self._song_for(path) + if song is None: return + + song = self._dict_for(song) + song["_rev"] = doc["_rev"] + self.db[song["_id"]] = song + def docs_beneath(self, path): path = util.qdecode(path).split(os.path.sep) return [row.value for row in self.db.view('_view/tree/by-path', startkey=path, endkey=path + [{}])] def _song_for(self, path): try: return MusicFile(path) except IOError: return None def _dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): val = song(tag) if val: if isinstance(val, basestring): if tag in QUOTED_TAGS: val = util.qdecode(val) else: val = util.fsdecode(val) if not tag in SINGLETON_TAGS: val = val.split("\n") d[tag] = val for tag, default in DEFAULTS.items(): if not tag in song: song[tag] = default d["~path"] = d["~filename"].split(os.path.sep) # CouchDB doesn't like apostrophes in keys for some reason... d["_id"] = _id(song.key) return d def _doc_for(self, song): docs = list(self.view[_id(song) if isinstance(song, basestring) else song["_id"]]) if not docs: return None return docs[0] def _load_views(self): for view in glob.glob(util.data_path('views', '*.json')): name = os.path.basename(view)[0:-5] f = open(view) # Can't use __setitem__ 'cause it assumes content is a hash self.db.resource.put('_design/' + name, content=f.read()) f.close() diff --git a/mdb/check.py b/mdb/check.py new file mode 100644 index 0000000..c8cdb5a --- /dev/null +++ b/mdb/check.py @@ -0,0 +1,48 @@ +import os +import sys +import traceback + +from progressbar import ProgressBar, Percentage, Bar + +import mdb.util as util +from mdb import Database + +class Check: + def __init__(self, server, name, progress=True): + self.current_files = 0 + self.db = Database(server, name) + self.progress = progress + self.view = self.db.db.view('_view/update/check') + + if self.progress: + sys.stderr.write("Counting files...\r") + self.total_files = len(self.view) + self.bar = ProgressBar(self.total_files) + else: + self.total_files = sys.maxint + + def run(self): + if self.progress: self.bar.start() + + mount_errors = set() + for i, doc in enumerate(row.value for row in self.view): + if "mountpoint" in doc: + mountpoint = util.qencode(doc["mountpoint"]) + if not os.path.ismount(mountpoint): + if not mountpoint in mount_errors: + sys.stderr.write("Error: %s isn't mounted\n" % mountpoint) + if self.progress: sys.stderr.write("\n\n") + mount_errors.add(mountpoint) + continue + filename = util.qencode(doc["filename"]) + try: + if not os.path.isfile(filename): + self.db.remove(filename) + elif util.mtime(filename) > doc["mtime"]: + self.db.update(doc, filename) + except Exception: + print "Error when updating %s:" % filename + traceback.print_exc() + if self.progress: sys.stderr.write("\n\n") + if self.progress: self.bar.update(i) + if self.progress: self.bar.finish()
nex3/mdb
e5f7e23b8704c6af77ba00338e63d880b9796779
URL-quote pathnames, since we've got to preserve bad encodings.
diff --git a/mdb/__init__.py b/mdb/__init__.py index 226483e..f7bb382 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,105 +1,110 @@ import os import urllib import glob from datetime import datetime from couchdb.client import Server import mdb.util from mdb.formats import MusicFile SAVED_METATAGS = [ "~filename", "~dirname", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] SINGLETON_TAGS = ["~filename", "~dirname", "~format", "~mountpoint"] +QUOTED_TAGS = ["~filename", "~dirname", "~mountpoint"] + DEFAULTS = {"~#disc": 1, "~#discs": 1} def _id(path): if isinstance(path, unicode): path = path.encode("utf-8") return urllib.quote(path, '') class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) self._load_views() self.view = self.db.view('_view/update/all') def add(self, path): song = self._song_for(os.path.realpath(path)) if song is None: return song = self._dict_for(song) doc = self._doc_for(song) if doc: song["_rev"] = doc.value["_rev"] self.db[song["_id"]] = song def add_many(self, paths): paths = map(os.path.realpath, paths) def updated_file(path): doc = self._doc_for(path) if not doc: return True return util.mtime(path) > doc.value["mtime"] songs = filter(None, map(self._song_for, filter(updated_file, paths))) if not songs: return songs = map(self._dict_for, songs) for song in songs: doc = self._doc_for(song) if not doc: continue song["_rev"] = doc.value["_rev"] self.db.update(songs) def remove(self, path): del self.db[_id(path)] def remove_docs(self, songs): for song in songs: song["_deleted"] = True self.db.update(songs) def docs_beneath(self, path): - path = path.split(os.path.sep) + path = util.qdecode(path).split(os.path.sep) return [row.value for row in self.db.view('_view/tree/by-path', startkey=path, endkey=path + [{}])] def _song_for(self, path): try: return MusicFile(path) except IOError: return None def _dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): val = song(tag) if val: if isinstance(val, basestring): - val = util.fsdecode(val) + if tag in QUOTED_TAGS: + val = util.qdecode(val) + else: + val = util.fsdecode(val) if not tag in SINGLETON_TAGS: val = val.split("\n") d[tag] = val for tag, default in DEFAULTS.items(): if not tag in song: song[tag] = default d["~path"] = d["~filename"].split(os.path.sep) # CouchDB doesn't like apostrophes in keys for some reason... d["_id"] = _id(song.key) return d def _doc_for(self, song): docs = list(self.view[_id(song) if isinstance(song, basestring) else song["_id"]]) if not docs: return None return docs[0] def _load_views(self): for view in glob.glob(util.data_path('views', '*.json')): name = os.path.basename(view)[0:-5] f = open(view) # Can't use __setitem__ 'cause it assumes content is a hash self.db.resource.put('_design/' + name, content=f.read()) f.close() diff --git a/mdb/util.py b/mdb/util.py index b32ec8c..b233059 100644 --- a/mdb/util.py +++ b/mdb/util.py @@ -1,69 +1,77 @@ import os import locale import re +import urllib def data_path(*path): return os.path.join(os.path.dirname(__file__), '..', 'data', *path) def mtime(filename): """Return the mtime of a file, or 0 if an error occurs.""" try: return os.path.getmtime(filename) except OSError: return 0 def escape(str): """Escape a string in a manner suitable for XML/Pango.""" return str.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") +SAFE_QUOTE_CHARS = "".join(chr(i) for i in range(32,126) if chr(i) != '%') +def qdecode(s): + return urllib.quote(s, SAFE_QUOTE_CHARS).decode() + +def qencode(s): + return urllib.unquote(s.encode()) + def fsdecode(s): """Decoding a string according to the filesystem encoding.""" if isinstance(s, unicode): return s else: return decode(s, locale.getpreferredencoding()) def fsencode(s): """Encode a string according to the filesystem encoding, replacing errors.""" if isinstance(s, str): return s else: return s.encode(locale.getpreferredencoding(), 'replace') def decode(s, charset="utf-8"): """Decode a string; if an error occurs, replace characters and append a note to the string.""" try: return s.decode(charset) except UnicodeError: return s.decode(charset, "replace") + " [Invalid Encoding]" def encode(s, charset="utf-8"): """Encode a string; if an error occurs, replace characters and append a note to the string.""" try: return s.encode(charset) except UnicodeError: return (s + " [Invalid Encoding]").encode(charset, "replace") def make_case_insensitive(filename): return "".join(["[%s%s]" % (c.lower(), c.upper()) for c in filename]) def parse_time(timestr, err=(ValueError, re.error)): """Parse a time string in hh:mm:ss, mm:ss, or ss format.""" if timestr[0:1] == "-": m = -1 timestr = timestr[1:] else: m = 1 try: return m * reduce(lambda s, a: s * 60 + int(a), re.split(r":|\.", timestr), 0) except err: return 0 def format_time(time): """Turn a time value in seconds into hh:mm:ss or mm:ss.""" if time < 0: time = abs(time) prefix = "-" else: prefix = "" if time >= 3600: # 1 hour # time, in hours:minutes:seconds return "%s%d:%02d:%02d" % (prefix, time // 3600, (time % 3600) // 60, time % 60) else: # time, in minutes:seconds return "%s%d:%02d" % (prefix, time // 60, time % 60)
nex3/mdb
4b6f65341053154bef23c4464a2df30ddaa15142
Properly handle directories moved out of the watched dir.
diff --git a/mdb/__init__.py b/mdb/__init__.py index 35c2729..226483e 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,96 +1,105 @@ import os import urllib import glob from datetime import datetime from couchdb.client import Server import mdb.util from mdb.formats import MusicFile SAVED_METATAGS = [ "~filename", "~dirname", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] SINGLETON_TAGS = ["~filename", "~dirname", "~format", "~mountpoint"] DEFAULTS = {"~#disc": 1, "~#discs": 1} def _id(path): if isinstance(path, unicode): path = path.encode("utf-8") return urllib.quote(path, '') class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) self._load_views() self.view = self.db.view('_view/update/all') def add(self, path): song = self._song_for(os.path.realpath(path)) if song is None: return song = self._dict_for(song) doc = self._doc_for(song) if doc: song["_rev"] = doc.value["_rev"] self.db[song["_id"]] = song def add_many(self, paths): paths = map(os.path.realpath, paths) def updated_file(path): doc = self._doc_for(path) if not doc: return True return util.mtime(path) > doc.value["mtime"] songs = filter(None, map(self._song_for, filter(updated_file, paths))) if not songs: return songs = map(self._dict_for, songs) for song in songs: doc = self._doc_for(song) if not doc: continue song["_rev"] = doc.value["_rev"] self.db.update(songs) def remove(self, path): del self.db[_id(path)] + def remove_docs(self, songs): + for song in songs: + song["_deleted"] = True + self.db.update(songs) + + def docs_beneath(self, path): + path = path.split(os.path.sep) + return [row.value for row in self.db.view('_view/tree/by-path', startkey=path, endkey=path + [{}])] + def _song_for(self, path): try: return MusicFile(path) except IOError: return None def _dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): val = song(tag) if val: if isinstance(val, basestring): val = util.fsdecode(val) if not tag in SINGLETON_TAGS: val = val.split("\n") d[tag] = val for tag, default in DEFAULTS.items(): if not tag in song: song[tag] = default d["~path"] = d["~filename"].split(os.path.sep) # CouchDB doesn't like apostrophes in keys for some reason... d["_id"] = _id(song.key) return d def _doc_for(self, song): docs = list(self.view[_id(song) if isinstance(song, basestring) else song["_id"]]) if not docs: return None return docs[0] def _load_views(self): for view in glob.glob(util.data_path('views', '*.json')): name = os.path.basename(view)[0:-5] f = open(view) # Can't use __setitem__ 'cause it assumes content is a hash self.db.resource.put('_design/' + name, content=f.read()) f.close() diff --git a/mdb/watch.py b/mdb/watch.py index e8b91b4..8ba061b 100644 --- a/mdb/watch.py +++ b/mdb/watch.py @@ -1,76 +1,78 @@ import traceback import time import os import pyinotify as pyi from mdb import Database from mdb.slurp import Slurp class Process(pyi.ProcessEvent): def __init__(self, server, name): self.server = server self.name = name self.db = Database(server=server, name=name) def process_IN_DELETE(self, event): if event.is_dir: return path = os.path.join(event.path, event.name) print "Removing %s..." % path self.db.remove(path) def process_IN_MOVED_TO(self, event): if not event.is_dir: self.process_default(event) return path = os.path.join(event.path, event.name) print "Slurping %s..." % path Slurp([path], server=self.server, name=self.name, progress=False).run() def process_IN_MOVED_FROM(self, event): if not event.is_dir: self.process_IN_DELETE(self, event) - print "Don't know how to deal with a moved directory yet." + path = os.path.join(event.path, event.name) + print "Removing %s..." % path + self.db.remove_docs(self.db.docs_beneath(path)) def process_default(self, event): if event.is_dir: return path = os.path.join(event.path, event.name) print "Updating %s..." % path for attempt in range(10): try: self.db.add(path) break except EOFError: if attempt < 9: print "File not yet written, waiting a second..." time.sleep(1) else: print "Giving up." mask = pyi.EventsCodes.IN_CREATE | pyi.EventsCodes.IN_MODIFY | \ pyi.EventsCodes.IN_DELETE | pyi.EventsCodes.IN_MOVED_TO | \ pyi.EventsCodes.IN_MOVED_FROM class Watcher: def __init__(self, *args, **kwargs): self.wm = pyi.WatchManager() self.notifier = pyi.Notifier(self.wm, Process(*args, **kwargs)) def start(self): while True: try: self.notifier.process_events() if self.notifier.check_events(): self.notifier.read_events() except Exception: traceback.print_exc() except KeyboardInterrupt: self.notifier.stop() break def watch(self, path): self.wm.add_watch(path, mask, rec=True, auto_add=True)
nex3/mdb
cb2e8f62e425ea2ca788cd62e4924292f32c0b3d
Load views from a directory.
diff --git a/data/views/tree.json b/data/views/tree.json new file mode 100644 index 0000000..497130c --- /dev/null +++ b/data/views/tree.json @@ -0,0 +1,7 @@ +{"language": "javascript", + "views": { + "by-path": { + "map": "function(doc) {emit(doc['~path'], doc);}" + } + } +} diff --git a/data/views/update.json b/data/views/update.json new file mode 100644 index 0000000..9c26fbd --- /dev/null +++ b/data/views/update.json @@ -0,0 +1,10 @@ +{"language": "javascript", + "views": { + "all": { + "map": " +function(doc) { + emit(doc._id, {mtime: doc['~#mtime'], _rev: doc._rev}); +}" + } + } +} diff --git a/mdb/__init__.py b/mdb/__init__.py index 1c84f67..35c2729 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,98 +1,96 @@ import os import urllib +import glob from datetime import datetime from couchdb.client import Server import mdb.util from mdb.formats import MusicFile SAVED_METATAGS = [ "~filename", "~dirname", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] SINGLETON_TAGS = ["~filename", "~dirname", "~format", "~mountpoint"] DEFAULTS = {"~#disc": 1, "~#discs": 1} def _id(path): if isinstance(path, unicode): path = path.encode("utf-8") return urllib.quote(path, '') class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) - self.db["_design/update"] = { - "language": "javascript", - "views": { - "all": { - "map": """ -function(doc) { - emit(doc._id, {mtime: doc["~#mtime"], _rev: doc._rev}); -} -""" - } - } - } + self._load_views() self.view = self.db.view('_view/update/all') def add(self, path): song = self._song_for(os.path.realpath(path)) if song is None: return song = self._dict_for(song) doc = self._doc_for(song) if doc: song["_rev"] = doc.value["_rev"] self.db[song["_id"]] = song def add_many(self, paths): paths = map(os.path.realpath, paths) def updated_file(path): doc = self._doc_for(path) if not doc: return True return util.mtime(path) > doc.value["mtime"] songs = filter(None, map(self._song_for, filter(updated_file, paths))) if not songs: return songs = map(self._dict_for, songs) for song in songs: doc = self._doc_for(song) if not doc: continue song["_rev"] = doc.value["_rev"] self.db.update(songs) def remove(self, path): del self.db[_id(path)] def _song_for(self, path): try: return MusicFile(path) except IOError: return None def _dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): val = song(tag) if val: if isinstance(val, basestring): val = util.fsdecode(val) if not tag in SINGLETON_TAGS: val = val.split("\n") d[tag] = val for tag, default in DEFAULTS.items(): if not tag in song: song[tag] = default d["~path"] = d["~filename"].split(os.path.sep) # CouchDB doesn't like apostrophes in keys for some reason... d["_id"] = _id(song.key) return d def _doc_for(self, song): docs = list(self.view[_id(song) if isinstance(song, basestring) else song["_id"]]) if not docs: return None return docs[0] + + def _load_views(self): + for view in glob.glob(util.data_path('views', '*.json')): + name = os.path.basename(view)[0:-5] + f = open(view) + # Can't use __setitem__ 'cause it assumes content is a hash + self.db.resource.put('_design/' + name, content=f.read()) + f.close() diff --git a/mdb/util.py b/mdb/util.py index b14f21d..b32ec8c 100644 --- a/mdb/util.py +++ b/mdb/util.py @@ -1,66 +1,69 @@ import os import locale import re +def data_path(*path): + return os.path.join(os.path.dirname(__file__), '..', 'data', *path) + def mtime(filename): """Return the mtime of a file, or 0 if an error occurs.""" try: return os.path.getmtime(filename) except OSError: return 0 def escape(str): """Escape a string in a manner suitable for XML/Pango.""" return str.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") def fsdecode(s): """Decoding a string according to the filesystem encoding.""" if isinstance(s, unicode): return s else: return decode(s, locale.getpreferredencoding()) def fsencode(s): """Encode a string according to the filesystem encoding, replacing errors.""" if isinstance(s, str): return s else: return s.encode(locale.getpreferredencoding(), 'replace') def decode(s, charset="utf-8"): """Decode a string; if an error occurs, replace characters and append a note to the string.""" try: return s.decode(charset) except UnicodeError: return s.decode(charset, "replace") + " [Invalid Encoding]" def encode(s, charset="utf-8"): """Encode a string; if an error occurs, replace characters and append a note to the string.""" try: return s.encode(charset) except UnicodeError: return (s + " [Invalid Encoding]").encode(charset, "replace") def make_case_insensitive(filename): return "".join(["[%s%s]" % (c.lower(), c.upper()) for c in filename]) def parse_time(timestr, err=(ValueError, re.error)): """Parse a time string in hh:mm:ss, mm:ss, or ss format.""" if timestr[0:1] == "-": m = -1 timestr = timestr[1:] else: m = 1 try: return m * reduce(lambda s, a: s * 60 + int(a), re.split(r":|\.", timestr), 0) except err: return 0 def format_time(time): """Turn a time value in seconds into hh:mm:ss or mm:ss.""" if time < 0: time = abs(time) prefix = "-" else: prefix = "" if time >= 3600: # 1 hour # time, in hours:minutes:seconds return "%s%d:%02d:%02d" % (prefix, time // 3600, (time % 3600) // 60, time % 60) else: # time, in minutes:seconds return "%s%d:%02d" % (prefix, time // 60, time % 60)
nex3/mdb
0291ea0e18ad504def8e2418181662d8e720b9a1
Keep a field with an arrayed path to the file.
diff --git a/mdb/__init__.py b/mdb/__init__.py index 9ee0d4d..1c84f67 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,97 +1,98 @@ import os import urllib from datetime import datetime from couchdb.client import Server import mdb.util from mdb.formats import MusicFile SAVED_METATAGS = [ "~filename", "~dirname", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] SINGLETON_TAGS = ["~filename", "~dirname", "~format", "~mountpoint"] DEFAULTS = {"~#disc": 1, "~#discs": 1} def _id(path): if isinstance(path, unicode): path = path.encode("utf-8") return urllib.quote(path, '') class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) self.db["_design/update"] = { "language": "javascript", "views": { "all": { "map": """ function(doc) { emit(doc._id, {mtime: doc["~#mtime"], _rev: doc._rev}); } """ } } } self.view = self.db.view('_view/update/all') def add(self, path): song = self._song_for(os.path.realpath(path)) if song is None: return song = self._dict_for(song) doc = self._doc_for(song) if doc: song["_rev"] = doc.value["_rev"] self.db[song["_id"]] = song def add_many(self, paths): paths = map(os.path.realpath, paths) def updated_file(path): doc = self._doc_for(path) if not doc: return True return util.mtime(path) > doc.value["mtime"] songs = filter(None, map(self._song_for, filter(updated_file, paths))) if not songs: return songs = map(self._dict_for, songs) for song in songs: doc = self._doc_for(song) if not doc: continue song["_rev"] = doc.value["_rev"] self.db.update(songs) def remove(self, path): del self.db[_id(path)] def _song_for(self, path): try: return MusicFile(path) except IOError: return None def _dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): val = song(tag) if val: if isinstance(val, basestring): val = util.fsdecode(val) if not tag in SINGLETON_TAGS: val = val.split("\n") d[tag] = val for tag, default in DEFAULTS.items(): if not tag in song: song[tag] = default + d["~path"] = d["~filename"].split(os.path.sep) # CouchDB doesn't like apostrophes in keys for some reason... d["_id"] = _id(song.key) return d def _doc_for(self, song): docs = list(self.view[_id(song) if isinstance(song, basestring) else song["_id"]]) if not docs: return None return docs[0]
nex3/mdb
76decf13f91189e7a79e8793ae1a722c3b0d1974
Deal with moved files.
diff --git a/mdb/watch.py b/mdb/watch.py index 51f460f..e8b91b4 100644 --- a/mdb/watch.py +++ b/mdb/watch.py @@ -1,69 +1,76 @@ import traceback import time import os import pyinotify as pyi from mdb import Database from mdb.slurp import Slurp class Process(pyi.ProcessEvent): def __init__(self, server, name): self.server = server self.name = name self.db = Database(server=server, name=name) def process_IN_DELETE(self, event): if event.is_dir: return path = os.path.join(event.path, event.name) print "Removing %s..." % path self.db.remove(path) def process_IN_MOVED_TO(self, event): if not event.is_dir: self.process_default(event) return path = os.path.join(event.path, event.name) print "Slurping %s..." % path Slurp([path], server=self.server, name=self.name, progress=False).run() + def process_IN_MOVED_FROM(self, event): + if not event.is_dir: + self.process_IN_DELETE(self, event) + + print "Don't know how to deal with a moved directory yet." + def process_default(self, event): if event.is_dir: return path = os.path.join(event.path, event.name) print "Updating %s..." % path for attempt in range(10): try: self.db.add(path) break except EOFError: if attempt < 9: print "File not yet written, waiting a second..." time.sleep(1) else: print "Giving up." mask = pyi.EventsCodes.IN_CREATE | pyi.EventsCodes.IN_MODIFY | \ - pyi.EventsCodes.IN_DELETE | pyi.EventsCodes.IN_MOVED_TO + pyi.EventsCodes.IN_DELETE | pyi.EventsCodes.IN_MOVED_TO | \ + pyi.EventsCodes.IN_MOVED_FROM class Watcher: def __init__(self, *args, **kwargs): self.wm = pyi.WatchManager() self.notifier = pyi.Notifier(self.wm, Process(*args, **kwargs)) def start(self): while True: try: self.notifier.process_events() if self.notifier.check_events(): self.notifier.read_events() except Exception: traceback.print_exc() except KeyboardInterrupt: self.notifier.stop() break def watch(self, path): self.wm.add_watch(path, mask, rec=True, auto_add=True)
nex3/mdb
0950ef5d98de0d8a4dbf53bc0861607beb93bbba
Cope with moved files and deleted dirs.
diff --git a/mdb/watch.py b/mdb/watch.py index 5353bd4..51f460f 100644 --- a/mdb/watch.py +++ b/mdb/watch.py @@ -1,63 +1,69 @@ import traceback import time import os import pyinotify as pyi from mdb import Database from mdb.slurp import Slurp class Process(pyi.ProcessEvent): def __init__(self, server, name): self.server = server self.name = name self.db = Database(server=server, name=name) def process_IN_DELETE(self, event): + if event.is_dir: return + path = os.path.join(event.path, event.name) print "Removing %s..." % path self.db.remove(path) def process_IN_MOVED_TO(self, event): + if not event.is_dir: + self.process_default(event) + return + path = os.path.join(event.path, event.name) print "Slurping %s..." % path Slurp([path], server=self.server, name=self.name, progress=False).run() def process_default(self, event): if event.is_dir: return path = os.path.join(event.path, event.name) print "Updating %s..." % path for attempt in range(10): try: self.db.add(path) break except EOFError: if attempt < 9: print "File not yet written, waiting a second..." time.sleep(1) else: print "Giving up." mask = pyi.EventsCodes.IN_CREATE | pyi.EventsCodes.IN_MODIFY | \ pyi.EventsCodes.IN_DELETE | pyi.EventsCodes.IN_MOVED_TO class Watcher: def __init__(self, *args, **kwargs): self.wm = pyi.WatchManager() self.notifier = pyi.Notifier(self.wm, Process(*args, **kwargs)) def start(self): while True: try: self.notifier.process_events() if self.notifier.check_events(): self.notifier.read_events() except Exception: traceback.print_exc() except KeyboardInterrupt: self.notifier.stop() break def watch(self, path): self.wm.add_watch(path, mask, rec=True, auto_add=True)
nex3/mdb
e32fc2e11b530b6a7e61dac15d3ea6770cbee924
Slurp moved-in directories.
diff --git a/mdb/watch.py b/mdb/watch.py index 80b7b0e..5353bd4 100644 --- a/mdb/watch.py +++ b/mdb/watch.py @@ -1,54 +1,63 @@ import traceback import time import os import pyinotify as pyi from mdb import Database +from mdb.slurp import Slurp class Process(pyi.ProcessEvent): def __init__(self, server, name): + self.server = server + self.name = name self.db = Database(server=server, name=name) def process_IN_DELETE(self, event): path = os.path.join(event.path, event.name) print "Removing %s..." % path self.db.remove(path) + def process_IN_MOVED_TO(self, event): + path = os.path.join(event.path, event.name) + print "Slurping %s..." % path + Slurp([path], server=self.server, name=self.name, progress=False).run() + def process_default(self, event): if event.is_dir: return path = os.path.join(event.path, event.name) print "Updating %s..." % path for attempt in range(10): try: self.db.add(path) break except EOFError: if attempt < 9: print "File not yet written, waiting a second..." time.sleep(1) else: print "Giving up." -mask = pyi.EventsCodes.IN_CREATE | pyi.EventsCodes.IN_MODIFY | pyi.EventsCodes.IN_DELETE +mask = pyi.EventsCodes.IN_CREATE | pyi.EventsCodes.IN_MODIFY | \ + pyi.EventsCodes.IN_DELETE | pyi.EventsCodes.IN_MOVED_TO class Watcher: def __init__(self, *args, **kwargs): self.wm = pyi.WatchManager() self.notifier = pyi.Notifier(self.wm, Process(*args, **kwargs)) def start(self): while True: try: self.notifier.process_events() if self.notifier.check_events(): self.notifier.read_events() except Exception: traceback.print_exc() except KeyboardInterrupt: self.notifier.stop() break def watch(self, path): self.wm.add_watch(path, mask, rec=True, auto_add=True)
nex3/mdb
ffee899220e909e7fa5c871b234c5d56fd0c53c3
Fix a bug in updating.
diff --git a/mdb/__init__.py b/mdb/__init__.py index a7d1455..9ee0d4d 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,97 +1,97 @@ import os import urllib from datetime import datetime from couchdb.client import Server import mdb.util from mdb.formats import MusicFile SAVED_METATAGS = [ "~filename", "~dirname", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] SINGLETON_TAGS = ["~filename", "~dirname", "~format", "~mountpoint"] DEFAULTS = {"~#disc": 1, "~#discs": 1} def _id(path): if isinstance(path, unicode): path = path.encode("utf-8") return urllib.quote(path, '') class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) self.db["_design/update"] = { "language": "javascript", "views": { "all": { "map": """ function(doc) { emit(doc._id, {mtime: doc["~#mtime"], _rev: doc._rev}); } """ } } } self.view = self.db.view('_view/update/all') def add(self, path): song = self._song_for(os.path.realpath(path)) if song is None: return song = self._dict_for(song) doc = self._doc_for(song) if doc: song["_rev"] = doc.value["_rev"] self.db[song["_id"]] = song def add_many(self, paths): paths = map(os.path.realpath, paths) def updated_file(path): doc = self._doc_for(path) if not doc: return True return util.mtime(path) > doc.value["mtime"] songs = filter(None, map(self._song_for, filter(updated_file, paths))) if not songs: return songs = map(self._dict_for, songs) for song in songs: doc = self._doc_for(song) - if not doc: break + if not doc: continue song["_rev"] = doc.value["_rev"] self.db.update(songs) def remove(self, path): del self.db[_id(path)] def _song_for(self, path): try: return MusicFile(path) except IOError: return None def _dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): val = song(tag) if val: if isinstance(val, basestring): val = util.fsdecode(val) if not tag in SINGLETON_TAGS: val = val.split("\n") d[tag] = val for tag, default in DEFAULTS.items(): if not tag in song: song[tag] = default # CouchDB doesn't like apostrophes in keys for some reason... d["_id"] = _id(song.key) return d def _doc_for(self, song): docs = list(self.view[_id(song) if isinstance(song, basestring) else song["_id"]]) if not docs: return None return docs[0]
nex3/mdb
5ef895f42d6afdcdd75faab1b5718f19b344c530
Process file deletion in the watcher.
diff --git a/mdb/__init__.py b/mdb/__init__.py index ab453c0..a7d1455 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,94 +1,97 @@ import os import urllib from datetime import datetime from couchdb.client import Server import mdb.util from mdb.formats import MusicFile SAVED_METATAGS = [ "~filename", "~dirname", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] SINGLETON_TAGS = ["~filename", "~dirname", "~format", "~mountpoint"] DEFAULTS = {"~#disc": 1, "~#discs": 1} def _id(path): if isinstance(path, unicode): path = path.encode("utf-8") return urllib.quote(path, '') class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) self.db["_design/update"] = { "language": "javascript", "views": { "all": { "map": """ function(doc) { emit(doc._id, {mtime: doc["~#mtime"], _rev: doc._rev}); } """ } } } self.view = self.db.view('_view/update/all') def add(self, path): song = self._song_for(os.path.realpath(path)) if song is None: return song = self._dict_for(song) doc = self._doc_for(song) if doc: song["_rev"] = doc.value["_rev"] self.db[song["_id"]] = song def add_many(self, paths): paths = map(os.path.realpath, paths) def updated_file(path): doc = self._doc_for(path) if not doc: return True return util.mtime(path) > doc.value["mtime"] songs = filter(None, map(self._song_for, filter(updated_file, paths))) if not songs: return songs = map(self._dict_for, songs) for song in songs: doc = self._doc_for(song) if not doc: break song["_rev"] = doc.value["_rev"] self.db.update(songs) + def remove(self, path): + del self.db[_id(path)] + def _song_for(self, path): try: return MusicFile(path) except IOError: return None def _dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): val = song(tag) if val: if isinstance(val, basestring): val = util.fsdecode(val) if not tag in SINGLETON_TAGS: val = val.split("\n") d[tag] = val for tag, default in DEFAULTS.items(): if not tag in song: song[tag] = default # CouchDB doesn't like apostrophes in keys for some reason... d["_id"] = _id(song.key) return d def _doc_for(self, song): docs = list(self.view[_id(song) if isinstance(song, basestring) else song["_id"]]) if not docs: return None return docs[0] diff --git a/mdb/watch.py b/mdb/watch.py index 71a0306..80b7b0e 100644 --- a/mdb/watch.py +++ b/mdb/watch.py @@ -1,49 +1,54 @@ import traceback import time import os import pyinotify as pyi from mdb import Database class Process(pyi.ProcessEvent): def __init__(self, server, name): self.db = Database(server=server, name=name) + def process_IN_DELETE(self, event): + path = os.path.join(event.path, event.name) + print "Removing %s..." % path + self.db.remove(path) + def process_default(self, event): if event.is_dir: return path = os.path.join(event.path, event.name) print "Updating %s..." % path for attempt in range(10): try: self.db.add(path) break except EOFError: if attempt < 9: print "File not yet written, waiting a second..." time.sleep(1) else: print "Giving up." -mask = pyi.EventsCodes.IN_CREATE | pyi.EventsCodes.IN_MODIFY +mask = pyi.EventsCodes.IN_CREATE | pyi.EventsCodes.IN_MODIFY | pyi.EventsCodes.IN_DELETE class Watcher: def __init__(self, *args, **kwargs): self.wm = pyi.WatchManager() self.notifier = pyi.Notifier(self.wm, Process(*args, **kwargs)) def start(self): while True: try: self.notifier.process_events() if self.notifier.check_events(): self.notifier.read_events() except Exception: traceback.print_exc() except KeyboardInterrupt: self.notifier.stop() break def watch(self, path): self.wm.add_watch(path, mask, rec=True, auto_add=True)
nex3/mdb
408062bf31366cfebc213629d95e8fa1be671fb7
Use proper private-method conventions.
diff --git a/mdb/__init__.py b/mdb/__init__.py index e19ac96..ab453c0 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,94 +1,94 @@ import os import urllib from datetime import datetime from couchdb.client import Server import mdb.util from mdb.formats import MusicFile SAVED_METATAGS = [ "~filename", "~dirname", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] SINGLETON_TAGS = ["~filename", "~dirname", "~format", "~mountpoint"] DEFAULTS = {"~#disc": 1, "~#discs": 1} def _id(path): if isinstance(path, unicode): path = path.encode("utf-8") return urllib.quote(path, '') class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) self.db["_design/update"] = { "language": "javascript", "views": { "all": { "map": """ function(doc) { emit(doc._id, {mtime: doc["~#mtime"], _rev: doc._rev}); } """ } } } self.view = self.db.view('_view/update/all') def add(self, path): - song = self.song_for(os.path.realpath(path)) + song = self._song_for(os.path.realpath(path)) if song is None: return - song = self.dict_for(song) - doc = self.doc_for(song) + song = self._dict_for(song) + doc = self._doc_for(song) if doc: song["_rev"] = doc.value["_rev"] self.db[song["_id"]] = song def add_many(self, paths): paths = map(os.path.realpath, paths) def updated_file(path): - doc = self.doc_for(path) + doc = self._doc_for(path) if not doc: return True return util.mtime(path) > doc.value["mtime"] - songs = filter(None, map(self.song_for, filter(updated_file, paths))) + songs = filter(None, map(self._song_for, filter(updated_file, paths))) if not songs: return - songs = map(self.dict_for, songs) + songs = map(self._dict_for, songs) for song in songs: - doc = self.doc_for(song) + doc = self._doc_for(song) if not doc: break song["_rev"] = doc.value["_rev"] self.db.update(songs) - def song_for(self, path): + def _song_for(self, path): try: return MusicFile(path) except IOError: return None - def dict_for(self, song): + def _dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): val = song(tag) if val: if isinstance(val, basestring): val = util.fsdecode(val) if not tag in SINGLETON_TAGS: val = val.split("\n") d[tag] = val for tag, default in DEFAULTS.items(): if not tag in song: song[tag] = default # CouchDB doesn't like apostrophes in keys for some reason... d["_id"] = _id(song.key) return d - def doc_for(self, song): + def _doc_for(self, song): docs = list(self.view[_id(song) if isinstance(song, basestring) else song["_id"]]) if not docs: return None return docs[0]
nex3/mdb
811699f8d66ed569b8b894217b712d347e711950
Handle subdirectory creation in watched directories properly.
diff --git a/mdb/watch.py b/mdb/watch.py index 5010aff..71a0306 100644 --- a/mdb/watch.py +++ b/mdb/watch.py @@ -1,47 +1,49 @@ import traceback import time import os import pyinotify as pyi from mdb import Database class Process(pyi.ProcessEvent): def __init__(self, server, name): self.db = Database(server=server, name=name) def process_default(self, event): + if event.is_dir: return + path = os.path.join(event.path, event.name) print "Updating %s..." % path for attempt in range(10): try: self.db.add(path) break except EOFError: if attempt < 9: print "File not yet written, waiting a second..." time.sleep(1) else: print "Giving up." mask = pyi.EventsCodes.IN_CREATE | pyi.EventsCodes.IN_MODIFY class Watcher: def __init__(self, *args, **kwargs): self.wm = pyi.WatchManager() self.notifier = pyi.Notifier(self.wm, Process(*args, **kwargs)) def start(self): while True: try: self.notifier.process_events() if self.notifier.check_events(): self.notifier.read_events() except Exception: traceback.print_exc() except KeyboardInterrupt: self.notifier.stop() break def watch(self, path): - self.wm.add_watch(path, mask, rec=True) + self.wm.add_watch(path, mask, rec=True, auto_add=True)
nex3/mdb
e2389adba04bedf6df6d14f892be3cc24cbf556a
Notice when watched songs are modified as well.
diff --git a/mdb/watch.py b/mdb/watch.py index 01b9e32..5010aff 100644 --- a/mdb/watch.py +++ b/mdb/watch.py @@ -1,47 +1,47 @@ import traceback import time import os import pyinotify as pyi from mdb import Database class Process(pyi.ProcessEvent): def __init__(self, server, name): self.db = Database(server=server, name=name) - def process_IN_CREATE(self, event): + def process_default(self, event): path = os.path.join(event.path, event.name) - print "Adding %s..." % path + print "Updating %s..." % path for attempt in range(10): try: self.db.add(path) break except EOFError: if attempt < 9: print "File not yet written, waiting a second..." time.sleep(1) else: print "Giving up." -mask = pyi.EventsCodes.IN_CREATE +mask = pyi.EventsCodes.IN_CREATE | pyi.EventsCodes.IN_MODIFY class Watcher: def __init__(self, *args, **kwargs): self.wm = pyi.WatchManager() self.notifier = pyi.Notifier(self.wm, Process(*args, **kwargs)) def start(self): while True: try: self.notifier.process_events() if self.notifier.check_events(): self.notifier.read_events() except Exception: traceback.print_exc() except KeyboardInterrupt: self.notifier.stop() break def watch(self, path): self.wm.add_watch(path, mask, rec=True)
nex3/mdb
abd232fe883978f9e8154bd81cb44c224497a243
Make sure we don't read the file faster than it's being written.
diff --git a/mdb/watch.py b/mdb/watch.py index 5db6539..01b9e32 100644 --- a/mdb/watch.py +++ b/mdb/watch.py @@ -1,38 +1,47 @@ import traceback import time import os import pyinotify as pyi from mdb import Database class Process(pyi.ProcessEvent): def __init__(self, server, name): self.db = Database(server=server, name=name) def process_IN_CREATE(self, event): path = os.path.join(event.path, event.name) print "Adding %s..." % path - time.sleep(0.1) # Make sure the file is actually written - self.db.add(path) + + for attempt in range(10): + try: + self.db.add(path) + break + except EOFError: + if attempt < 9: + print "File not yet written, waiting a second..." + time.sleep(1) + else: + print "Giving up." mask = pyi.EventsCodes.IN_CREATE class Watcher: def __init__(self, *args, **kwargs): self.wm = pyi.WatchManager() self.notifier = pyi.Notifier(self.wm, Process(*args, **kwargs)) def start(self): while True: try: self.notifier.process_events() if self.notifier.check_events(): self.notifier.read_events() except Exception: traceback.print_exc() except KeyboardInterrupt: self.notifier.stop() break def watch(self, path): self.wm.add_watch(path, mask, rec=True)
nex3/mdb
aa65840e25e9a0fa5d021e7be31a367263902fe7
Add directory-watching functionality.
diff --git a/mdb-watch b/mdb-watch new file mode 100755 index 0000000..356c174 --- /dev/null +++ b/mdb-watch @@ -0,0 +1,18 @@ +#!/usr/bin/env python +import sys +from optparse import OptionParser + +from mdb.watch import Watcher + +parser = OptionParser() +parser.add_option("-s", "--server", dest="server", + default='http://localhost:5984/', metavar="URL", + help="The URL of the CouchDB server to which to connect.") +parser.add_option("-n", "--name", dest="name", default="mdb", + help="The name of the database into which to import the music information.") +(options, args) = parser.parse_args() + +watcher = Watcher(server=options.server, name=options.name) +for path in sys.argv[1:]: + watcher.watch(path) +watcher.start() diff --git a/mdb/watch.py b/mdb/watch.py new file mode 100644 index 0000000..5db6539 --- /dev/null +++ b/mdb/watch.py @@ -0,0 +1,38 @@ +import traceback +import time +import os + +import pyinotify as pyi + +from mdb import Database + +class Process(pyi.ProcessEvent): + def __init__(self, server, name): + self.db = Database(server=server, name=name) + + def process_IN_CREATE(self, event): + path = os.path.join(event.path, event.name) + print "Adding %s..." % path + time.sleep(0.1) # Make sure the file is actually written + self.db.add(path) + +mask = pyi.EventsCodes.IN_CREATE +class Watcher: + def __init__(self, *args, **kwargs): + self.wm = pyi.WatchManager() + self.notifier = pyi.Notifier(self.wm, Process(*args, **kwargs)) + + def start(self): + while True: + try: + self.notifier.process_events() + if self.notifier.check_events(): + self.notifier.read_events() + except Exception: + traceback.print_exc() + except KeyboardInterrupt: + self.notifier.stop() + break + + def watch(self, path): + self.wm.add_watch(path, mask, rec=True)
nex3/mdb
bc5af201686b78d5a803be099f9205d3ccef23bc
Make mdb.Database.add respect existing docs.
diff --git a/mdb/__init__.py b/mdb/__init__.py index 12067c4..e19ac96 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,85 +1,94 @@ import os import urllib from datetime import datetime from couchdb.client import Server import mdb.util from mdb.formats import MusicFile SAVED_METATAGS = [ "~filename", "~dirname", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] SINGLETON_TAGS = ["~filename", "~dirname", "~format", "~mountpoint"] DEFAULTS = {"~#disc": 1, "~#discs": 1} def _id(path): if isinstance(path, unicode): path = path.encode("utf-8") return urllib.quote(path, '') class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) self.db["_design/update"] = { "language": "javascript", "views": { "all": { "map": """ function(doc) { emit(doc._id, {mtime: doc["~#mtime"], _rev: doc._rev}); } """ } } } + self.view = self.db.view('_view/update/all') def add(self, path): song = self.song_for(os.path.realpath(path)) if song is None: return - self.db[song.key] = self.dict_for(song) + + song = self.dict_for(song) + doc = self.doc_for(song) + if doc: song["_rev"] = doc.value["_rev"] + self.db[song["_id"]] = song def add_many(self, paths): paths = map(os.path.realpath, paths) - view = self.db.view('_view/update/all') def updated_file(path): - docs = list(view[_id(path)]) - if not docs: return True - return util.mtime(path) > docs[0].value["mtime"] + doc = self.doc_for(path) + if not doc: return True + return util.mtime(path) > doc.value["mtime"] songs = filter(None, map(self.song_for, filter(updated_file, paths))) if not songs: return songs = map(self.dict_for, songs) for song in songs: - docs = list(view[song["_id"]]) - if not docs: break - song["_rev"] = docs[0].value["_rev"] + doc = self.doc_for(song) + if not doc: break + song["_rev"] = doc.value["_rev"] self.db.update(songs) def song_for(self, path): try: return MusicFile(path) except IOError: return None def dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): val = song(tag) if val: if isinstance(val, basestring): val = util.fsdecode(val) if not tag in SINGLETON_TAGS: val = val.split("\n") d[tag] = val for tag, default in DEFAULTS.items(): if not tag in song: song[tag] = default # CouchDB doesn't like apostrophes in keys for some reason... d["_id"] = _id(song.key) return d + + def doc_for(self, song): + docs = list(self.view[_id(song) if isinstance(song, basestring) else song["_id"]]) + if not docs: return None + return docs[0]
nex3/mdb
47c973e4102d3ef6169c07e1b634317b45255bf1
Automatically add the necessary view when creating a new DB.
diff --git a/mdb/__init__.py b/mdb/__init__.py index 8e9f6d0..12067c4 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,71 +1,85 @@ import os import urllib from datetime import datetime from couchdb.client import Server import mdb.util from mdb.formats import MusicFile SAVED_METATAGS = [ "~filename", "~dirname", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] SINGLETON_TAGS = ["~filename", "~dirname", "~format", "~mountpoint"] DEFAULTS = {"~#disc": 1, "~#discs": 1} def _id(path): if isinstance(path, unicode): path = path.encode("utf-8") return urllib.quote(path, '') class Database: def __init__(self, server, name): self.server = Server(server) - if name in self.server: self.db = self.server[name] - else: self.db = self.server.create(name) + if name in self.server: + self.db = self.server[name] + else: + self.db = self.server.create(name) + self.db["_design/update"] = { + "language": "javascript", + "views": { + "all": { + "map": """ +function(doc) { + emit(doc._id, {mtime: doc["~#mtime"], _rev: doc._rev}); +} +""" + } + } + } def add(self, path): song = self.song_for(os.path.realpath(path)) if song is None: return self.db[song.key] = self.dict_for(song) def add_many(self, paths): paths = map(os.path.realpath, paths) view = self.db.view('_view/update/all') def updated_file(path): docs = list(view[_id(path)]) if not docs: return True return util.mtime(path) > docs[0].value["mtime"] songs = filter(None, map(self.song_for, filter(updated_file, paths))) if not songs: return songs = map(self.dict_for, songs) for song in songs: docs = list(view[song["_id"]]) if not docs: break song["_rev"] = docs[0].value["_rev"] self.db.update(songs) def song_for(self, path): try: return MusicFile(path) except IOError: return None def dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): val = song(tag) if val: if isinstance(val, basestring): val = util.fsdecode(val) if not tag in SINGLETON_TAGS: val = val.split("\n") d[tag] = val for tag, default in DEFAULTS.items(): if not tag in song: song[tag] = default # CouchDB doesn't like apostrophes in keys for some reason... d["_id"] = _id(song.key) return d
nex3/mdb
be98c118d6b8fe74de6381e3471ed676aff7956f
Add command-line options to the slurp tool.
diff --git a/mdb-slurp b/mdb-slurp index 7d16281..3a50683 100755 --- a/mdb-slurp +++ b/mdb-slurp @@ -1,8 +1,17 @@ #!/usr/bin/env python -import sys +from optparse import OptionParser + from mdb.slurp import Slurp -server = 'http://localhost:5984/' -name = 'mdb' +parser = OptionParser() +parser.add_option("-s", "--server", dest="server", + default='http://localhost:5984/', metavar="URL", + help="The URL of the CouchDB server to which to connect.") +parser.add_option("-n", "--name", dest="name", default="mdb", + help="The name of the database into which to import the music information.") +parser.add_option("-q", "--quiet", action="store_false", dest="verbose", + default=True, help="Don't print status information.") +(options, args) = parser.parse_args() -Slurp(server, name, sys.argv[1:]).run() +Slurp(args, server=options.server, name=options.name, + progress=options.verbose).run() diff --git a/mdb/slurp.py b/mdb/slurp.py index 83aa051..84f8d85 100644 --- a/mdb/slurp.py +++ b/mdb/slurp.py @@ -1,59 +1,59 @@ import os import sys import traceback from progressbar import Percentage, Bar from mdb.progress import ProgressBar, Fraction from mdb import Database class Slurp: - def __init__(self, server, name, paths, progress=True): + def __init__(self, paths, server, name, progress=True): self.paths = paths self.current_files = 0 self.current_dir = '' self.db = Database(server, name) self.progress = progress if progress: self._count_files(paths) else: self.total_files = sys.maxint widgets = [Fraction(), ", ", Percentage(), " ", Bar()] if progress else [] self.bar = ProgressBar(self.total_files, widgets=widgets) def _count_files(self, paths): self.total_files = 0 for files in self._walk(paths): self.total_files += len(files) if self.progress: sys.stderr.write("Counting files... %d\r" % self.total_files) if self.progress: sys.stderr.write("\n") def run(self): self.bar.start() for paths in self._walk(self.paths): self.current_dir = os.path.dirname(paths[0]) self._update() try: self.db.add_many(paths) except Exception: print "Error when importing %s:" % self.current_dir traceback.print_exc() if self.progress: sys.stderr.write("\n\n") self._update(paths) self.bar.finish() def _update(self, paths = []): if self.progress: self.bar.fd.write("\033[1A\033[KSlurping %s...\r\033[1B" % self.current_dir) self.current_files += len(paths) self.bar.update(self.current_files) def _walk(self, paths): for path in paths: if os.path.isfile(path): yield [os.path.abspath(path)] else: for (dirname, _, files) in os.walk(path): if files: yield [os.path.abspath(os.path.join(dirname, f)) for f in files]
nex3/mdb
d40eb153bfce2cade901d07332e12fbbf8bb8e76
Add mtime checking.
diff --git a/mdb/__init__.py b/mdb/__init__.py index 09c5dd9..8e9f6d0 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,45 +1,71 @@ +import os +import urllib from datetime import datetime -from mdb.formats import MusicFile from couchdb.client import Server +import mdb.util +from mdb.formats import MusicFile + SAVED_METATAGS = [ - "~filename", "~format", "~mountpoint", "~performers", "~people", - "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", + "~filename", "~dirname", "~format", "~mountpoint", "~performers", + "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] +SINGLETON_TAGS = ["~filename", "~dirname", "~format", "~mountpoint"] + DEFAULTS = {"~#disc": 1, "~#discs": 1} +def _id(path): + if isinstance(path, unicode): + path = path.encode("utf-8") + return urllib.quote(path, '') + class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) def add(self, path): - song = self.song_for(path) + song = self.song_for(os.path.realpath(path)) if song is None: return self.db[song.key] = self.dict_for(song) def add_many(self, paths): - self.db.update(map(self.dict_for, - filter(None, - map(self.song_for, paths)))) + paths = map(os.path.realpath, paths) + view = self.db.view('_view/update/all') + def updated_file(path): + docs = list(view[_id(path)]) + if not docs: return True + return util.mtime(path) > docs[0].value["mtime"] + + songs = filter(None, map(self.song_for, filter(updated_file, paths))) + if not songs: return + songs = map(self.dict_for, songs) + for song in songs: + docs = list(view[song["_id"]]) + if not docs: break + song["_rev"] = docs[0].value["_rev"] + self.db.update(songs) def song_for(self, path): - try: return MusicFile(path.decode("utf-8", "replace")) + try: return MusicFile(path) except IOError: return None def dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): val = song(tag) if val: - if isinstance(val, basestring): val = val.split("\n") + if isinstance(val, basestring): + val = util.fsdecode(val) + if not tag in SINGLETON_TAGS: + val = val.split("\n") d[tag] = val for tag, default in DEFAULTS.items(): if not tag in song: song[tag] = default # CouchDB doesn't like apostrophes in keys for some reason... - d["_id"] = song.key.replace("'", "_") + d["_id"] = _id(song.key) return d
nex3/mdb
92b0eebc3b62661d56a0cb6dc367eec9f004f589
Make progress reporting optional.
diff --git a/mdb/slurp.py b/mdb/slurp.py index 4442ab9..83aa051 100644 --- a/mdb/slurp.py +++ b/mdb/slurp.py @@ -1,50 +1,59 @@ import os import sys import traceback from progressbar import Percentage, Bar from mdb.progress import ProgressBar, Fraction from mdb import Database class Slurp: - def __init__(self, server, name, paths): + def __init__(self, server, name, paths, progress=True): self.paths = paths self.current_files = 0 self.current_dir = '' self.db = Database(server, name) + self.progress = progress - self._count_files(paths) - widgets = [Fraction(), ", ", Percentage(), " ", Bar()] + if progress: + self._count_files(paths) + else: + self.total_files = sys.maxint + widgets = [Fraction(), ", ", Percentage(), " ", Bar()] if progress else [] self.bar = ProgressBar(self.total_files, widgets=widgets) def _count_files(self, paths): self.total_files = 0 for files in self._walk(paths): self.total_files += len(files) - sys.stderr.write("Counting files... %d\r" % self.total_files) - sys.stderr.write("\n") + if self.progress: + sys.stderr.write("Counting files... %d\r" % self.total_files) + if self.progress: + sys.stderr.write("\n") def run(self): self.bar.start() for paths in self._walk(self.paths): self.current_dir = os.path.dirname(paths[0]) self._update() try: self.db.add_many(paths) except Exception: print "Error when importing %s:" % self.current_dir traceback.print_exc() + if self.progress: + sys.stderr.write("\n\n") self._update(paths) self.bar.finish() def _update(self, paths = []): - self.bar.fd.write("\033[1A\033[KSlurping %r...\r\033[1B" % self.current_dir) + if self.progress: + self.bar.fd.write("\033[1A\033[KSlurping %s...\r\033[1B" % self.current_dir) self.current_files += len(paths) self.bar.update(self.current_files) def _walk(self, paths): for path in paths: if os.path.isfile(path): yield [os.path.abspath(path)] else: for (dirname, _, files) in os.walk(path): if files: yield [os.path.abspath(os.path.join(dirname, f)) for f in files]
nex3/mdb
2f321cad143b538ab4a3edec4c2c3274dc335663
Add a progress indicator for file-counting.
diff --git a/mdb/slurp.py b/mdb/slurp.py index e0b28bc..4442ab9 100644 --- a/mdb/slurp.py +++ b/mdb/slurp.py @@ -1,43 +1,50 @@ import os +import sys import traceback from progressbar import Percentage, Bar from mdb.progress import ProgressBar, Fraction from mdb import Database class Slurp: def __init__(self, server, name, paths): self.paths = paths self.current_files = 0 self.current_dir = '' self.db = Database(server, name) - print "Counting files..." - self.total_files = sum(map(len, self._walk(paths))) + self._count_files(paths) widgets = [Fraction(), ", ", Percentage(), " ", Bar()] self.bar = ProgressBar(self.total_files, widgets=widgets) + def _count_files(self, paths): + self.total_files = 0 + for files in self._walk(paths): + self.total_files += len(files) + sys.stderr.write("Counting files... %d\r" % self.total_files) + sys.stderr.write("\n") + def run(self): self.bar.start() for paths in self._walk(self.paths): self.current_dir = os.path.dirname(paths[0]) self._update() try: self.db.add_many(paths) except Exception: print "Error when importing %s:" % self.current_dir traceback.print_exc() self._update(paths) self.bar.finish() def _update(self, paths = []): self.bar.fd.write("\033[1A\033[KSlurping %r...\r\033[1B" % self.current_dir) self.current_files += len(paths) self.bar.update(self.current_files) def _walk(self, paths): for path in paths: if os.path.isfile(path): yield [os.path.abspath(path)] else: for (dirname, _, files) in os.walk(path): if files: yield [os.path.abspath(os.path.join(dirname, f)) for f in files]
nex3/mdb
cfdef973f13417acc8d736523a75c5ce784a46a4
Customize the progress bar a little.
diff --git a/mdb/progress.py b/mdb/progress.py new file mode 100644 index 0000000..314e60c --- /dev/null +++ b/mdb/progress.py @@ -0,0 +1,9 @@ +import progressbar +from progressbar import ProgressBarWidget + +class Fraction(ProgressBarWidget): + def update(self, pbar): + return "%d/%d" % (pbar.currval, pbar.maxval) + +class ProgressBar(progressbar.ProgressBar): + def _need_update(self): return True diff --git a/mdb/slurp.py b/mdb/slurp.py index 4dd94fb..e0b28bc 100644 --- a/mdb/slurp.py +++ b/mdb/slurp.py @@ -1,35 +1,43 @@ import os import traceback -from progressbar import ProgressBar +from progressbar import Percentage, Bar +from mdb.progress import ProgressBar, Fraction from mdb import Database class Slurp: def __init__(self, server, name, paths): self.paths = paths self.current_files = 0 + self.current_dir = '' self.db = Database(server, name) - print "Calculating number of files..." - self.total_files = sum(map(len, self.walk(paths))) - self.bar = ProgressBar(self.total_files) + + print "Counting files..." + self.total_files = sum(map(len, self._walk(paths))) + widgets = [Fraction(), ", ", Percentage(), " ", Bar()] + self.bar = ProgressBar(self.total_files, widgets=widgets) def run(self): self.bar.start() - for paths in self.walk(self.paths): + for paths in self._walk(self.paths): + self.current_dir = os.path.dirname(paths[0]) + self._update() try: self.db.add_many(paths) except Exception: - print "Error when importing %s:" % os.path.dirname(paths[0]) + print "Error when importing %s:" % self.current_dir traceback.print_exc() - self.update(paths) + self._update(paths) self.bar.finish() - def update(self, paths): + def _update(self, paths = []): + self.bar.fd.write("\033[1A\033[KSlurping %r...\r\033[1B" % self.current_dir) self.current_files += len(paths) self.bar.update(self.current_files) - def walk(self, paths): + def _walk(self, paths): for path in paths: if os.path.isfile(path): yield [os.path.abspath(path)] else: for (dirname, _, files) in os.walk(path): - yield [os.path.abspath(os.path.join(dirname, f)) for f in files] + if files: + yield [os.path.abspath(os.path.join(dirname, f)) for f in files]
nex3/mdb
1c56e3766820bc9ec5ce249e56fe59943cd9a271
Better organization.
diff --git a/mdb-slurp b/mdb-slurp index 09e2305..7d16281 100755 --- a/mdb-slurp +++ b/mdb-slurp @@ -1,23 +1,8 @@ #!/usr/bin/env python import sys -import os -import traceback - -from mdb import Database +from mdb.slurp import Slurp server = 'http://localhost:5984/' name = 'mdb' -def mywalk(paths): - for path in paths: - if os.path.isfile(path): yield [os.path.abspath(path)] - else: - for (dirname, _, files) in os.walk(path): - yield [os.path.abspath(os.path.join(dirname, f)) for f in files] - -db = Database(server, name) -for paths in mywalk(sys.argv[1:]): - try: db.add_many(paths) - except Exception: - print "Error when importing %s:" % dirname - traceback.print_exc() +Slurp(server, name, sys.argv[1:]).run() diff --git a/mdb/slurp.py b/mdb/slurp.py new file mode 100644 index 0000000..4dd94fb --- /dev/null +++ b/mdb/slurp.py @@ -0,0 +1,35 @@ +import os +import traceback +from progressbar import ProgressBar +from mdb import Database + +class Slurp: + def __init__(self, server, name, paths): + self.paths = paths + self.current_files = 0 + self.db = Database(server, name) + print "Calculating number of files..." + self.total_files = sum(map(len, self.walk(paths))) + self.bar = ProgressBar(self.total_files) + + def run(self): + self.bar.start() + for paths in self.walk(self.paths): + try: self.db.add_many(paths) + except Exception: + print "Error when importing %s:" % os.path.dirname(paths[0]) + traceback.print_exc() + self.update(paths) + self.bar.finish() + + def update(self, paths): + self.current_files += len(paths) + self.bar.update(self.current_files) + + def walk(self, paths): + for path in paths: + if os.path.isfile(path): yield [os.path.abspath(path)] + else: + for (dirname, _, files) in os.walk(path): + yield [os.path.abspath(os.path.join(dirname, f)) for f in files] +
nex3/mdb
088b60de3f1341d77fddede5a73ce7c3dedc060d
Factor out some tree-walking logic.
diff --git a/mdb-slurp b/mdb-slurp index beab0a0..09e2305 100755 --- a/mdb-slurp +++ b/mdb-slurp @@ -1,19 +1,23 @@ #!/usr/bin/env python import sys import os import traceback + from mdb import Database server = 'http://localhost:5984/' name = 'mdb' -for path in sys.argv[1:]: - db = Database(server, name) - if os.path.isfile(path): - db.record(path) - break - for (dirname, _, files) in os.walk(path): - try: db.add_many([os.path.join(dirname, f) for f in files]) - except Exception: - print "Error when importing %s:" % dirname - traceback.print_exc() +def mywalk(paths): + for path in paths: + if os.path.isfile(path): yield [os.path.abspath(path)] + else: + for (dirname, _, files) in os.walk(path): + yield [os.path.abspath(os.path.join(dirname, f)) for f in files] + +db = Database(server, name) +for paths in mywalk(sys.argv[1:]): + try: db.add_many(paths) + except Exception: + print "Error when importing %s:" % dirname + traceback.print_exc()
nex3/mdb
1dac01c05dfbf21bc24184a52fbc4ff7d2d3b759
Fix a couple bugs.
diff --git a/mdb/__init__.py b/mdb/__init__.py index cbed66d..09c5dd9 100644 --- a/mdb/__init__.py +++ b/mdb/__init__.py @@ -1,45 +1,45 @@ from datetime import datetime from mdb.formats import MusicFile from couchdb.client import Server SAVED_METATAGS = [ "~filename", "~format", "~mountpoint", "~performers", "~people", "~#added", "~#bitrate", "~#length", "~#year", "~#mtime", "~#disc", "~#discs", "~#track", "~#tracks" ] DEFAULTS = {"~#disc": 1, "~#discs": 1} class Database: def __init__(self, server, name): self.server = Server(server) if name in self.server: self.db = self.server[name] else: self.db = self.server.create(name) def add(self, path): song = self.song_for(path) if song is None: return self.db[song.key] = self.dict_for(song) def add_many(self, paths): self.db.update(map(self.dict_for, filter(None, map(self.song_for, paths)))) def song_for(self, path): try: return MusicFile(path.decode("utf-8", "replace")) except IOError: return None def dict_for(self, song): d = {} for tag in SAVED_METATAGS + song.realkeys(): - song = song(tag) - if song: - if isinstance(song, basestring): song = song.split("\n") - d[tag] = song - for tag, default in defaults.items(): + val = song(tag) + if val: + if isinstance(val, basestring): val = val.split("\n") + d[tag] = val + for tag, default in DEFAULTS.items(): if not tag in song: song[tag] = default # CouchDB doesn't like apostrophes in keys for some reason... d["_id"] = song.key.replace("'", "_") return d