repo
string
commit
string
message
string
diff
string
webcracy/activity_streams-workshop
cf5d1d156cba8796cffa541a16454ae4404eb588
added hints to the form
diff --git a/app/views/activities/_form.html.haml b/app/views/activities/_form.html.haml index f970e40..f25101f 100644 --- a/app/views/activities/_form.html.haml +++ b/app/views/activities/_form.html.haml @@ -1,75 +1,81 @@ - form_for @activity, :html => {:class => 'hform largeform sticky '} do |f| = f.error_messages - f.fields_for :actor, @activity.actor || @activity.build_actor do |actor| %fieldset %legend Actor %p - = actor.label :url_id, "Id" - = actor.text_field :url_id + = actor.label :url_id, "Id", :class => "hint" + %span.hint.quiet An URL (documentation) + = actor.text_field :url_id %p = actor.label :title - + %span.hint.quiet + A String (documentation) = actor.text_field :title + %fieldset %legend Verb %p = f.label :verb + %span.hint.quiet (documentation) = f.select :verb, Activity.verbs_to_select - f.fields_for :object, @activity.object || @activity.build_object do |object| %fieldset %legend Object %p = object.label :url_id, "Id" - + %span.hint.quiet An URL (documentation) = object.text_field :url_id %p = object.label :object_type + %span.hint.quiet (documentation) = object.select :object_type, Obj.to_select %p = object.label :title - + %span.hint.quiet A String (documentation) = object.text_field :title - f.fields_for :target, @activity.target || @activity.build_target do |target| %fieldset %legend Target %p = target.label :url_id, "Id" - + %span.hint.quiet An URL (documentation) = target.text_field :url_id %p = target.label :object_type + %span.hint.quiet (documentation) = target.select :object_type, Target.to_select %p = target.label :title - + %span.hint.quiet A String (documentation) = target.text_field :title %fieldset %legend Activity %p = f.label :title - + %span.hint.quiet HTML (documentation) = f.text_field :title %p = f.label :summary - + %span.hint.quiet HTML (documentation) = f.text_area :summary %p = f.label :published_at - + %span.hint.quiet (documentation) = f.datetime_select :published_at, {}, :class => "compact" %p = f.submit diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css index c7d214c..e0c51f7 100644 --- a/public/stylesheets/application.css +++ b/public/stylesheets/application.css @@ -1,158 +1,164 @@ body { background-color: #4b7399; font-family: Verdana, Helvetica, Arial; font-size: 14px; } a { color: blue; } a img { border: none; } .clear { clear: both; height: 0; overflow: hidden; } + +.quiet { + text-decoration: none; + font-size: small; + color: gray; +} #container { width: 75%; margin: 0 auto; background: white; padding: 20px 40px; border: solid 1px black; margin-top: 20px; } #flash_notice, #flash_error { padding: 5px 8px; margin: 10px 0; } #flash_notice { background-color: #ccffcc; border: solid 1px #66cc66; } #flash_error { background-color: #ffcccc; border: solid 1px #cc6666; } .fieldWithErrors { display: inline; } #errorExplanation { width: 400px; border: 2px solid #cf0000; padding: 0; padding-bottom: 12px; margin-bottom: 20px; background-color: #f0f0f0; } #errorExplanation h2 { text-align: left; padding: 5px 5px 5px 15px; margin: 0; font-weight: bold; font-size: 12px; background-color: #cc0000; color: white; } #errorExplanation p { color: #333333; margin-bottom: 0; padding: 8px; } #errorExplanation ul { margin: 2px 24px; } #errorExplanation ul li { font-size: 12px; list-style: disc; } .CodeRay { background-color: #232323; border: 1px solid black; font-family: "Courier New", "Terminal", monospace; color: #e6e0db; padding: 3px 5px; overflow: auto; font-size: 12px; margin: 12px 0; } .CodeRay pre { margin: 0px; padding: 0px; } .CodeRay .an { color: #e7be69; } .CodeRay .c { color: #bc9358; font-style: italic; } .CodeRay .ch { color: #509e4f; } .CodeRay .cl { color: white; } .CodeRay .co { color: white; } .CodeRay .fl { color: #a4c260; } .CodeRay .fu { color: #ffc56d; } .CodeRay .gv { color: #d0cffe; } .CodeRay .i { color: #a4c260; } .CodeRay .il { background: #151515; } .CodeRay .iv { color: #d0cffe; } .CodeRay .pp { color: #e7be69; } .CodeRay .r { color: #cb7832; } .CodeRay .rx { color: #a4c260; } .CodeRay .s { color: #a4c260; } .CodeRay .sy { color: #6c9cbd; } .CodeRay .ta { color: #e7be69; } .CodeRay .pc { color: #6c9cbd; } /* hFORM */ form.hform p { margin-bottom: 10px; } form.hform p label { float: left; width: 100px; } form.hform p input { width: 200px; } form.hform p select { width: 200px; } form.hform p input.button { width: auto; } form.hform p input.checkbox { width: auto; } form.hform p input.radio { width: auto; } form.hform p.checkbox { margin-left: 100px; } form.hform p.checkbox label { float: none; } form.hform p.checkbox input { width: auto; } /* hFORM modification: largeform (forms that use this class should require hform first)*/ form.largeform {margin-left: 50px;} form.largeform {width: 550px;} form.largeform fieldset.outter {padding: 20px 0 0 30px;} form.largeform legend.outter {font-size: 1.2em;} form.largeform h3 { color:#AFAFAF; border-bottom:1px solid;font-size:18px;line-height:20px;margin:40px 0px 20px 0px; width:400px;} form.largeform p { margin-bottom: 20px; } form.largeform p label { float: left; width: 150px; } form.largeform p input { width: 160px; } form.largeform p.checkbox { margin-left: 150px; } form.largeform p.compact_select { width: 100%; height: 30px; } form.largeform p.action_hint { margin: -5px 0 5px 0; padding-left: 3px; background-color: #FFA; width: 300px;} form.largeform p.submit {margin-top: 40px;} form.largeform span.action_hint { line-height: 16px; font-size: 10px; height: 16px; padding: 2px 0 0 20px; text-transform: uppercase; font-weight: ; } form.largeform span.action_hint.email { background: url('/images/email.png') no-repeat; } form.largeform span.action_hint.twitter { background: url('/images/twitter_2.png') no-repeat; } form.largeform span.compact_select { width: 200px; clear:both;} form.largeform span.hint { clear: both; float: left; width: 145px; margin-right: 5px; line-height: 12px; font-size: 11px; } form.largeform input[type="text"], form.largeform input[type="password"] { height: 1.6em; font-size: 1em; padding-left: 5px; width: 220px; } form.largeform input[type="text"].compact { padding-left: 2px; width: 35px;} form.largeform select { height: 1.6em; line-height: 1.4em; font-size: 11px; padding-left: 5px;} form.largeform select.compact { width:auto; padding-left: 1px;} form.largeform div#inner_email.inner_fieldset {margin-bottom: 10px; } form.largeform div.inner_fieldset {margin-left: 148px; padding-left: 2px; } form.largeform div.inner_fieldset.actions { -webkit-border-radius:2px; -moz-border-radius:2px;} form.largeform.sticky {margin-left: 0 !important;} \ No newline at end of file
webcracy/activity_streams-workshop
cbf46d344f675ab938c3270b7102e5932e17a9f4
protected activities from anonymous reading
diff --git a/app/controllers/activities_controller.rb b/app/controllers/activities_controller.rb index f8bfd83..015df71 100644 --- a/app/controllers/activities_controller.rb +++ b/app/controllers/activities_controller.rb @@ -1,61 +1,81 @@ class ActivitiesController < ApplicationController - before_filter :login_or_oauth_required, :except => [:index, :new, :create, :show_from_permalink] def index - @activities = Activity.find(:all) + if logged_in? + @activities = current_user.activities + else + @activities = (session[:activities] || []).map { |a| Activity.find(a) rescue nil }.compact + end end def show - @activity = Activity.find(params[:id]) + @activity = find_from_session_or_user(params[:id]) end def show_from_permalink @activity = Activity.find_by_permalink(params[:id]) render :action => 'show' end def new @activity = Activity.new end def create @activity = Activity.new(params[:activity]) @activity.user = current_user if @activity.save unless logged_in? session[:activities] ||= [] session[:activities] << @activity.id end flash[:notice] = "Successfully created activity." redirect_to @activity else render :action => 'new' end end def edit - @activity = Activity.find(params[:id]) + @activity = find_from_session_or_user(params[:id]) end def update - @activity = Activity.find(params[:id]) + @activity = find_from_session_or_user(params[:id]) @activity.user = current_user if @activity.update_attributes(params[:activity]) flash[:notice] = "Successfully updated activity." redirect_to @activity else render :action => 'edit' end end def destroy - @activity = Activity.find(params[:id]) + @activity = find_from_session_or_user(params[:id]) @activity.destroy flash[:notice] = "Successfully destroyed activity." redirect_to activities_url end + + private + def find_from_session_or_user(id) + # if the user is logged in, find from owned activities... + if logged_in? + current_user.activities.find(id) + + # ... otherwhise, search for the activity id on the session + else + if session[:activities].find(id.to_i).present? + Activity.find(params[:id]) + else + # everything fails, so give back 404 + raise ActiveRecord::RecordNotfound + end + end + end end
webcracy/activity_streams-workshop
cc0ed2f49474b8bec46dc3310f6d4ca399238792
added more verbs and object-types
diff --git a/app/models/activity.rb b/app/models/activity.rb index 8c658d4..9c6a23e 100644 --- a/app/models/activity.rb +++ b/app/models/activity.rb @@ -1,119 +1,129 @@ class Activity < ActiveRecord::Base include ActionView::Helpers include ActionController::UrlWriter default_url_options[:host] = APP_CONFIG[:domain] attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang attr_accessible :actor_attributes, :target_attributes, :object_attributes has_many :activity_objects, :dependent => :destroy has_one :actor has_one :object, :class_name => 'Obj' has_one :target belongs_to :user validates_presence_of :actor validates_presence_of :verb validates_presence_of :object validates_presence_of :published_at before_create :add_permalink accepts_nested_attributes_for :actor, :object, :target, :reject_if => proc { |p| p['url_id'].blank? } def self.verbs_to_select [ - ['POST', "http://activitystrea.ms/schema/1.0/post"] + ['POST', "http://activitystrea.ms/schema/1.0/post"], + ['FAVORITE', "http://activitystrea.ms/schema/1.0/favorite"], + ['FOLLOW', 'http://activitystrea.ms/schema/1.0/follow'], + ['LIKE', 'http://activitystrea.ms/schema/1.0/like'], + ['MAKE-FRIEND', 'http://activitystrea.ms/schema/1.0/make-friend'], + ['JOIN', 'http://activitystrea.ms/schema/1.0/join'], + ['PLAY', 'http://activitystrea.ms/schema/1.0/play'], + ['SAVE', 'http://activitystrea.ms/schema/1.0/save'], + ['SHARE', 'http://activitystrea.ms/schema/1.0/share'], + ['TAG', 'http://activitystrea.ms/schema/1.0/tag'], + ['UPDATE', 'http://activitystrea.ms/schema/1.0/update'] ] end def to_sentence msg = "<a href='/activities/#{self.id}'>#{self.object.title}</a> - #{time_ago_in_words published_at} ago<br/>" msg += "<a href='#{self.actor.url_id}'>#{self.actor.title}</a> | #{self.verb} | <a href='#{self.object.url_id}'>#{self.object.object_type}</a>" end def to_json a = { :id => activity_url(self), :permalinkUrl => activity_url(self), :title => self.title, :summary => self.summary, :postedTime => self.published_at.to_s(:w3cdtf), :actor => { :id => self.actor.url_id, :title => self.actor.title, }, :object => { :id => self.object.url_id, :title => self.object.title, :objectType => self.object.object_type } } if self.target.present? a[:target] = { :id => self.target.url_id, :title => self.target.title, :objectType => self.target.object_type } end return JSON.pretty_generate({ :data => { :lang => "en-US", :id => self.id, :items => [ a ] } }.stringify_keys) end def to_xml builder = Builder::XmlMarkup.new(:indent => 2) builder.entry do |b| b.id activity_url(self) b.permalink activity_url(self) b.published self.published_at.to_s(:w3cdtf) b.title self.title b.summary self.summary b.author do b.id self.actor.url_id b.title self.actor.title end b.activity :verb, self.verb b.activity :actor do b.id self.actor.url_id b.title self.actor.title, :type => 'text' end b.activity :object do b.id self.object.url_id b.title self.object.title, :type => 'text' b.activity :"object-type", self.object.object_type end if self.target.present? b.activity :target do b.id self.target.url_id b.title self.target.title, :type => 'text' b.activity :"object-type", self.target.object_type end end end end def add_permalink hash = hash_gen(self) while Activity.find_by_permalink(hash) self.add_permalink end self.permalink = hash end private def hash_gen(activity) return Digest::SHA1.hexdigest(activity.verb.to_s+activity.title.to_s+activity.summary.to_s+Time.now.to_f.to_s).to_s end end diff --git a/app/models/obj.rb b/app/models/obj.rb index 3c41b42..c39f806 100644 --- a/app/models/obj.rb +++ b/app/models/obj.rb @@ -1,9 +1,27 @@ class Obj < ActivityObject validates_presence_of :url_id def self.to_select [ - ['PHOTO', "http://activitystrea.ms/schema/1.0/photo"] + ['ARTICLE', 'http://activitystrea.ms/schema/1.0/article'], + ['AUDIO', 'http://activitystrea.ms/schema/1.0/audio'], + ['BOOKMARK', 'http://activitystrea.ms/schema/1.0/bookmark'], + ['COMMENT', 'http://activitystrea.ms/schema/1.0/comment'], + ['FILE', 'http://activitystrea.ms/schema/1.0/file'], + ['FOLDER', 'http://activitystrea.ms/schema/1.0/folder'], + ['GROUP', 'http://activitystrea.ms/schema/1.0/group'], + ['LIST', 'http://activitystrea.ms/schema/1.0/list'], + ['NOTE', 'http://activitystrea.ms/schema/1.0/note'], + ['PERSON', 'http://activitystrea.ms/schema/1.0/person'], + ['PHOTO', "http://activitystrea.ms/schema/1.0/photo"], + ['PHOTO ALBUM', 'http://activitystrea.ms/schema/1.0/photo-album'], + ['PLACE', 'http://activitystrea.ms/schema/1.0/place'], + ['PLAYLIST', 'http://activitystrea.ms/schema/1.0/playlist'], + ['PRODUCT', 'http://activitystrea.ms/schema/1.0/product'], + ['REVIEW', 'http://activitystrea.ms/schema/1.0/review'], + ['SERVICE', 'http://activitystrea.ms/schema/1.0/service'], + ['STATUS', 'http://activitystrea.ms/schema/1.0/status'], + ['VIDEO', 'http://activitystrea.ms/schema/1.0/video'] ] end end diff --git a/app/models/target.rb b/app/models/target.rb index f46766d..a9ada5d 100644 --- a/app/models/target.rb +++ b/app/models/target.rb @@ -1,7 +1,2 @@ -class Target < ActivityObject - def self.to_select - [ - ['PHOTO-ALBUM', 'http://activitystrea.ms/schema/1.0/photo-album'] - ] - end +class Target < Obj end
webcracy/activity_streams-workshop
ad5fe82135f5985f46c1f2fa78df16da606abc71
added permalink to activities. requires db:migrate
diff --git a/app/controllers/activities_controller.rb b/app/controllers/activities_controller.rb index d15b7a9..f8bfd83 100644 --- a/app/controllers/activities_controller.rb +++ b/app/controllers/activities_controller.rb @@ -1,54 +1,61 @@ class ActivitiesController < ApplicationController + before_filter :login_or_oauth_required, :except => [:index, :new, :create, :show_from_permalink] + def index @activities = Activity.find(:all) end def show @activity = Activity.find(params[:id]) end + def show_from_permalink + @activity = Activity.find_by_permalink(params[:id]) + render :action => 'show' + end + def new @activity = Activity.new end def create @activity = Activity.new(params[:activity]) @activity.user = current_user if @activity.save unless logged_in? session[:activities] ||= [] session[:activities] << @activity.id end flash[:notice] = "Successfully created activity." redirect_to @activity else render :action => 'new' end end def edit @activity = Activity.find(params[:id]) end def update @activity = Activity.find(params[:id]) @activity.user = current_user if @activity.update_attributes(params[:activity]) flash[:notice] = "Successfully updated activity." redirect_to @activity else render :action => 'edit' end end def destroy @activity = Activity.find(params[:id]) @activity.destroy flash[:notice] = "Successfully destroyed activity." redirect_to activities_url end end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index a729bcf..deeba3b 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -1,43 +1,44 @@ # This controller handles the login/logout function of the site. class SessionsController < ApplicationController # Be sure to include AuthenticationSystem in Application Controller instead include AuthenticatedSystem # render new.rhtml def new + redirect_to oauth_consumers_path end def create logout_keeping_session! user = User.authenticate(params[:login], params[:password]) if user # Protects against session fixation attacks, causes request forgery # protection if user resubmits an earlier form using back # button. Uncomment if you understand the tradeoffs. # reset_session self.current_user = user new_cookie_flag = (params[:remember_me] == "1") handle_remember_cookie! new_cookie_flag redirect_back_or_default('/') flash[:notice] = "Logged in successfully" else note_failed_signin @login = params[:login] @remember_me = params[:remember_me] render :action => 'new' end end def destroy logout_killing_session! flash[:notice] = "You have been logged out." redirect_back_or_default('/') end protected # Track failed login attempts def note_failed_signin flash[:error] = "Couldn't log you in as '#{params[:login]}'" logger.warn "Failed login for '#{params[:login]}' from #{request.remote_ip} at #{Time.now.utc}" end end diff --git a/app/models/activity.rb b/app/models/activity.rb index c0f4601..8c658d4 100644 --- a/app/models/activity.rb +++ b/app/models/activity.rb @@ -1,102 +1,119 @@ class Activity < ActiveRecord::Base include ActionView::Helpers include ActionController::UrlWriter default_url_options[:host] = APP_CONFIG[:domain] attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang attr_accessible :actor_attributes, :target_attributes, :object_attributes has_many :activity_objects, :dependent => :destroy has_one :actor has_one :object, :class_name => 'Obj' has_one :target belongs_to :user - validates_presence_of :actor - validates_presence_of :verb - validates_presence_of :object - validates_presence_of :published_at + validates_presence_of :actor + validates_presence_of :verb + validates_presence_of :object + validates_presence_of :published_at + + before_create :add_permalink accepts_nested_attributes_for :actor, :object, :target, :reject_if => proc { |p| p['url_id'].blank? } def self.verbs_to_select [ ['POST', "http://activitystrea.ms/schema/1.0/post"] ] end def to_sentence msg = "<a href='/activities/#{self.id}'>#{self.object.title}</a> - #{time_ago_in_words published_at} ago<br/>" msg += "<a href='#{self.actor.url_id}'>#{self.actor.title}</a> | #{self.verb} | <a href='#{self.object.url_id}'>#{self.object.object_type}</a>" end def to_json a = { :id => activity_url(self), :permalinkUrl => activity_url(self), :title => self.title, :summary => self.summary, :postedTime => self.published_at.to_s(:w3cdtf), :actor => { :id => self.actor.url_id, :title => self.actor.title, }, :object => { :id => self.object.url_id, :title => self.object.title, :objectType => self.object.object_type } } if self.target.present? a[:target] = { :id => self.target.url_id, :title => self.target.title, :objectType => self.target.object_type } end return JSON.pretty_generate({ :data => { :lang => "en-US", :id => self.id, :items => [ a ] } }.stringify_keys) end def to_xml builder = Builder::XmlMarkup.new(:indent => 2) builder.entry do |b| b.id activity_url(self) b.permalink activity_url(self) b.published self.published_at.to_s(:w3cdtf) b.title self.title b.summary self.summary b.author do b.id self.actor.url_id b.title self.actor.title end b.activity :verb, self.verb b.activity :actor do b.id self.actor.url_id b.title self.actor.title, :type => 'text' end b.activity :object do b.id self.object.url_id b.title self.object.title, :type => 'text' b.activity :"object-type", self.object.object_type end if self.target.present? b.activity :target do b.id self.target.url_id b.title self.target.title, :type => 'text' b.activity :"object-type", self.target.object_type end end end end + + def add_permalink + hash = hash_gen(self) + while Activity.find_by_permalink(hash) + self.add_permalink + end + self.permalink = hash + end + + + private + + def hash_gen(activity) + return Digest::SHA1.hexdigest(activity.verb.to_s+activity.title.to_s+activity.summary.to_s+Time.now.to_f.to_s).to_s + end end diff --git a/app/views/activities/index.html.haml b/app/views/activities/index.html.haml index c3877e9..ca6a072 100644 --- a/app/views/activities/index.html.haml +++ b/app/views/activities/index.html.haml @@ -1,6 +1,10 @@ - title "Activities" - for activity in @activities - %p= activity.to_sentence + %p + = activity.to_sentence + %br + = link_to 'Permalink', permalink_path(activity.permalink) + %p= link_to "New Activity", new_activity_path diff --git a/app/views/activities/show.html.haml b/app/views/activities/show.html.haml index 7a36145..6e4a651 100644 --- a/app/views/activities/show.html.haml +++ b/app/views/activities/show.html.haml @@ -1,31 +1,33 @@ - title "Activity" +%p= link_to "Permalink", permalink_path(:id => @activity.permalink) + %p - link_to @activity.actor.url_id do = @activity.actor.title.present? ? @activity.actor.title : @activity.actor.url_id %abbr{:title => @activity.verb}= @activity.verb.split('/').last.upcase - link_to @activity.object.url_id do = @activity.object.title.present? ? @activity.object.title : @activity.object.url_id - if @activity.target.present? - link_to @activity.target.url_id do = @activity.target.title.present? ? @activity.target.title : @activity.target.url_id = time_ago_in_words @activity.published_at ago %h3 JSON ~ CodeRay.scan(@activity.to_json, 'json').div(:line_numbers => :table, :css => :class) %h3 XML ~ CodeRay.scan(@activity.to_xml, 'xml').div(:line_numbers => :table, :css => :class) %p = link_to "Edit", edit_activity_path(@activity) | = link_to "Destroy", @activity, :confirm => 'Are you sure?', :method => :delete | = link_to "Create another", new_activity_path diff --git a/config/routes.rb b/config/routes.rb index 122d4ee..e115a3e 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,12 +1,12 @@ ActionController::Routing::Routes.draw do |map| map.resources :activities map.resources :oauth_consumers,:member=>{:callback=>:get} map.resources :users map.resource :session - + map.permalink '/a/:id', :controller => 'activities', :action => 'show_from_permalink' map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.login '/login', :controller => 'OauthConsumers', :action => 'index' map.root :controller => 'activities', :action => "new" end diff --git a/db/migrate/20100714110115_add_permalink_to_activities.rb b/db/migrate/20100714110115_add_permalink_to_activities.rb new file mode 100644 index 0000000..e0ef6ce --- /dev/null +++ b/db/migrate/20100714110115_add_permalink_to_activities.rb @@ -0,0 +1,9 @@ +class AddPermalinkToActivities < ActiveRecord::Migration + def self.up + add_column :activities, :permalink, :string + end + + def self.down + remove_column :activities, :permalink + end +end diff --git a/db/schema.rb b/db/schema.rb index df89895..fe88121 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,67 +1,68 @@ # 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 => 20100713144023) do +ActiveRecord::Schema.define(:version => 20100714110115) do create_table "activities", :force => true do |t| t.integer "user_id" t.string "url_id" t.string "verb" t.string "title" t.text "summary" t.string "lang" t.datetime "published_at" t.datetime "created_at" t.datetime "updated_at" + t.string "permalink" end add_index "activities", ["user_id"], :name => "index_activities_on_user_id" create_table "activity_objects", :force => true do |t| t.integer "activity_id" t.string "type" t.string "url_id" t.string "title" t.datetime "published_at" t.datetime "created_at" t.datetime "updated_at" t.string "object_type" end add_index "activity_objects", ["activity_id"], :name => "index_activity_objects_on_activity_id" add_index "activity_objects", ["type"], :name => "index_activity_objects_on_type" create_table "consumer_tokens", :force => true do |t| t.integer "user_id" t.string "type", :limit => 30 t.string "token", :limit => 1024 t.string "secret" t.datetime "created_at" t.datetime "updated_at" end add_index "consumer_tokens", ["token"], :name => "index_consumer_tokens_on_token", :unique => true create_table "users", :force => true do |t| t.string "login", :limit => 40 t.string "name", :limit => 100, :default => "" t.string "email", :limit => 100 t.string "crypted_password", :limit => 40 t.string "salt", :limit => 40 t.datetime "created_at" t.datetime "updated_at" t.string "remember_token", :limit => 40 t.datetime "remember_token_expires_at" end add_index "users", ["login"], :name => "index_users_on_login", :unique => true end
webcracy/activity_streams-workshop
b564500f63fb08cb3036a7ebc2da7cfb566b6e0f
beautified forms
diff --git a/app/controllers/oauth_consumers_controller.rb b/app/controllers/oauth_consumers_controller.rb index 40c9ae1..3218f87 100644 --- a/app/controllers/oauth_consumers_controller.rb +++ b/app/controllers/oauth_consumers_controller.rb @@ -1,92 +1,92 @@ require 'oauth/controllers/consumer_controller' class OauthConsumersController < ApplicationController include Oauth::Controllers::ConsumerController before_filter :load_consumer skip_before_filter :login_required def index if logged_in? @consumer_tokens=ConsumerToken.all :conditions=>{:user_id=>current_user.id} @services=OAUTH_CREDENTIALS.keys-@consumer_tokens.collect{|c| c.class.service_name} end end # This callback method is heavily modified from the plugin's original to allow session and user creation # from an Aidentiti Oauth Authorization def callback - @request_token_secret = (session[:yammer_token] ? session[:yammer_token][:request_secret] : session[params[:oauth_token]]) + @request_token_secret = session[params[:oauth_token]] if @request_token_secret if params[:id] == 'aidentiti' # Create an Aidentiti Oauth Consumer to grab the user's credential @consumer = AidentitiToken.consumer access_token = get_access_token(@consumer, params[:oauth_token], @request_token_secret, params[:oauth_verifier]) # Save the Consumer's token and use it to create the client @token = AidentitiToken.create(:token => access_token.token, :secret => access_token.secret) aidentiti_client = Aidentiti::Base.new(@token.client) # Make the call to Aidentiti user_profile = aidentiti_client.grab_credentials.user # Do we need to create this user, or just load it? user = User.find_or_create_by_email(:email => user_profile.email, :login => user_profile.login) user.password = user.password_confirmation = user.login.reverse user.save # Transfer any activities this user created as anonymous to the new found user if session[:activities].present? session[:activities].each do |a| activity = Activity.find(a) rescue nil activity.try(:update_attribute, :user_id, user.id) end session[:activities] = [] end # Create a new session reset_session self.current_user = user new_cookie_flag = true handle_remember_cookie! new_cookie_flag # Keep the Aidentiti Oauth Token table clean old_consumer = AidentitiToken.find_by_user_id(user.id).delete if AidentitiToken.find_by_user_id(user.id) # Wrap up by assigning the @token.user_id = user.id # elsif params[:id] == 'yammer' # here you could use program specific behaviour for other oauth providers end if @token.save flash[:notice] = "#{params[:id].humanize} was successfully connected to your account" go_back else flash[:error] = "An error happened, please try connecting again" redirect_to oauth_consumer_url(params[:id]) end end end protected # Change this to decide where you want to redirect user to after callback is finished. # params[:id] holds the service name so you could use this to redirect to various parts # of your application depending on what service you're connecting to. def go_back redirect_to root_url end def load_consumer consumer_key=params[:id].to_sym throw RecordNotFound unless OAUTH_CREDENTIALS.include?(consumer_key) @consumer="#{consumer_key.to_s.camelcase}Token".constantize if current_user @[email protected]_by_user_id current_user.id end end def get_access_token(consumer, token,secret,oauth_verifier) request_token=OAuth::RequestToken.new consumer,token,secret options={} options[:oauth_verifier]=oauth_verifier if oauth_verifier access_token=request_token.get_access_token options access_token end end diff --git a/app/views/activities/_form.html.haml b/app/views/activities/_form.html.haml index a8830ad..f970e40 100644 --- a/app/views/activities/_form.html.haml +++ b/app/views/activities/_form.html.haml @@ -1,76 +1,75 @@ -- form_for @activity do |f| +- form_for @activity, :html => {:class => 'hform largeform sticky '} do |f| = f.error_messages - f.fields_for :actor, @activity.actor || @activity.build_actor do |actor| - %fieldset + %fieldset %legend Actor %p = actor.label :url_id, "Id" - %br = actor.text_field :url_id %p = actor.label :title - %br + = actor.text_field :title %fieldset %legend Verb %p = f.label :verb = f.select :verb, Activity.verbs_to_select - f.fields_for :object, @activity.object || @activity.build_object do |object| %fieldset %legend Object %p = object.label :url_id, "Id" - %br + = object.text_field :url_id %p = object.label :object_type = object.select :object_type, Obj.to_select %p = object.label :title - %br + = object.text_field :title - f.fields_for :target, @activity.target || @activity.build_target do |target| %fieldset %legend Target %p = target.label :url_id, "Id" - %br + = target.text_field :url_id %p = target.label :object_type = target.select :object_type, Target.to_select %p = target.label :title - %br + = target.text_field :title %fieldset %legend Activity %p = f.label :title - %br + = f.text_field :title %p = f.label :summary - %br + = f.text_area :summary %p = f.label :published_at - %br - = f.datetime_select :published_at + + = f.datetime_select :published_at, {}, :class => "compact" %p = f.submit diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css index c43400f..c7d214c 100644 --- a/public/stylesheets/application.css +++ b/public/stylesheets/application.css @@ -1,113 +1,158 @@ body { background-color: #4b7399; font-family: Verdana, Helvetica, Arial; font-size: 14px; } a { color: blue; } a img { border: none; } .clear { clear: both; height: 0; overflow: hidden; } #container { width: 75%; margin: 0 auto; background: white; padding: 20px 40px; border: solid 1px black; margin-top: 20px; } #flash_notice, #flash_error { padding: 5px 8px; margin: 10px 0; } #flash_notice { background-color: #ccffcc; border: solid 1px #66cc66; } #flash_error { background-color: #ffcccc; border: solid 1px #cc6666; } .fieldWithErrors { display: inline; } #errorExplanation { width: 400px; border: 2px solid #cf0000; padding: 0; padding-bottom: 12px; margin-bottom: 20px; background-color: #f0f0f0; } #errorExplanation h2 { text-align: left; padding: 5px 5px 5px 15px; margin: 0; font-weight: bold; font-size: 12px; background-color: #cc0000; color: white; } #errorExplanation p { color: #333333; margin-bottom: 0; padding: 8px; } #errorExplanation ul { margin: 2px 24px; } #errorExplanation ul li { font-size: 12px; list-style: disc; } .CodeRay { background-color: #232323; border: 1px solid black; font-family: "Courier New", "Terminal", monospace; color: #e6e0db; padding: 3px 5px; overflow: auto; font-size: 12px; margin: 12px 0; } .CodeRay pre { margin: 0px; padding: 0px; } .CodeRay .an { color: #e7be69; } .CodeRay .c { color: #bc9358; font-style: italic; } .CodeRay .ch { color: #509e4f; } .CodeRay .cl { color: white; } .CodeRay .co { color: white; } .CodeRay .fl { color: #a4c260; } .CodeRay .fu { color: #ffc56d; } .CodeRay .gv { color: #d0cffe; } .CodeRay .i { color: #a4c260; } .CodeRay .il { background: #151515; } .CodeRay .iv { color: #d0cffe; } .CodeRay .pp { color: #e7be69; } .CodeRay .r { color: #cb7832; } .CodeRay .rx { color: #a4c260; } .CodeRay .s { color: #a4c260; } .CodeRay .sy { color: #6c9cbd; } .CodeRay .ta { color: #e7be69; } .CodeRay .pc { color: #6c9cbd; } + + +/* hFORM */ +form.hform p { margin-bottom: 10px; } +form.hform p label { float: left; width: 100px; } +form.hform p input { width: 200px; } +form.hform p select { width: 200px; } +form.hform p input.button { width: auto; } +form.hform p input.checkbox { width: auto; } +form.hform p input.radio { width: auto; } +form.hform p.checkbox { margin-left: 100px; } +form.hform p.checkbox label { float: none; } +form.hform p.checkbox input { width: auto; } + + +/* hFORM modification: largeform (forms that use this class should require hform first)*/ +form.largeform {margin-left: 50px;} +form.largeform {width: 550px;} +form.largeform fieldset.outter {padding: 20px 0 0 30px;} +form.largeform legend.outter {font-size: 1.2em;} +form.largeform h3 { color:#AFAFAF; border-bottom:1px solid;font-size:18px;line-height:20px;margin:40px 0px 20px 0px; width:400px;} +form.largeform p { margin-bottom: 20px; } +form.largeform p label { float: left; width: 150px; } +form.largeform p input { width: 160px; } +form.largeform p.checkbox { margin-left: 150px; } +form.largeform p.compact_select { width: 100%; height: 30px; } +form.largeform p.action_hint { margin: -5px 0 5px 0; padding-left: 3px; background-color: #FFA; width: 300px;} +form.largeform p.submit {margin-top: 40px;} +form.largeform span.action_hint { line-height: 16px; font-size: 10px; height: 16px; padding: 2px 0 0 20px; text-transform: uppercase; font-weight: ; } +form.largeform span.action_hint.email { background: url('/images/email.png') no-repeat; } +form.largeform span.action_hint.twitter { background: url('/images/twitter_2.png') no-repeat; } +form.largeform span.compact_select { width: 200px; clear:both;} +form.largeform span.hint { clear: both; float: left; width: 145px; margin-right: 5px; line-height: 12px; font-size: 11px; } +form.largeform input[type="text"], +form.largeform input[type="password"] { + height: 1.6em; font-size: 1em; padding-left: 5px; width: 220px; + } +form.largeform input[type="text"].compact { padding-left: 2px; width: 35px;} +form.largeform select { height: 1.6em; line-height: 1.4em; font-size: 11px; padding-left: 5px;} +form.largeform select.compact { width:auto; padding-left: 1px;} +form.largeform div#inner_email.inner_fieldset {margin-bottom: 10px; } +form.largeform div.inner_fieldset {margin-left: 148px; padding-left: 2px; } +form.largeform div.inner_fieldset.actions { -webkit-border-radius:2px; -moz-border-radius:2px;} + +form.largeform.sticky {margin-left: 0 !important;} \ No newline at end of file
webcracy/activity_streams-workshop
19f97b714759b7f26cbd405eed2cefcf6b2fd427
user has many activities
diff --git a/app/models/user.rb b/app/models/user.rb index b6c451c..caf6dda 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,54 +1,54 @@ require 'digest/sha1' class User < ActiveRecord::Base include Authentication include Authentication::ByPassword include Authentication::ByCookieToken validates_presence_of :login validates_length_of :login, :within => 3..40 validates_uniqueness_of :login validates_format_of :login, :with => Authentication.login_regex, :message => Authentication.bad_login_message validates_format_of :name, :with => Authentication.name_regex, :message => Authentication.bad_name_message, :allow_nil => true validates_length_of :name, :maximum => 100 validates_presence_of :email validates_length_of :email, :within => 6..100 #[email protected] validates_uniqueness_of :email validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_message - + has_many :activities, :dependent => :destroy # HACK HACK HACK -- how to do attr_accessible from here? # prevents a user from submitting a crafted form that bypasses activation # anything else you want your user to change should be added here. attr_accessible :login, :email, :name, :password, :password_confirmation # Authenticates a user by their login name and unencrypted password. Returns the user or nil. # # uff. this is really an authorization, not authentication routine. # We really need a Dispatch Chain here or something. # This will also let us return a human error message. # def self.authenticate(login, password) return nil if login.blank? || password.blank? u = find_by_login(login.downcase) # need to get the salt u && u.authenticated?(password) ? u : nil end def login=(value) write_attribute :login, (value ? value.downcase : nil) end def email=(value) write_attribute :email, (value ? value.downcase : nil) end protected end
webcracy/activity_streams-workshop
8d04c40cb9ee1c0c35eaf9254ccf83be91dce3ca
recreated the index for activities and a .to_sentence method that can be enhanced
diff --git a/app/controllers/activities_controller.rb b/app/controllers/activities_controller.rb index c57c191..9b38567 100644 --- a/app/controllers/activities_controller.rb +++ b/app/controllers/activities_controller.rb @@ -1,44 +1,49 @@ class ActivitiesController < ApplicationController + + def index + @activities = Activity.find(:all) + end + def show @activity = Activity.find(params[:id]) end def new @activity = Activity.new end def create @activity = Activity.new(params[:activity]) @activity.user = current_user if @activity.save flash[:notice] = "Successfully created activity." redirect_to @activity else render :action => 'new' end end def edit @activity = Activity.find(params[:id]) end def update @activity = Activity.find(params[:id]) @activity.user = current_user if @activity.update_attributes(params[:activity]) flash[:notice] = "Successfully updated activity." redirect_to @activity else render :action => 'edit' end end def destroy @activity = Activity.find(params[:id]) @activity.destroy flash[:notice] = "Successfully destroyed activity." redirect_to activities_url end end diff --git a/app/models/activity.rb b/app/models/activity.rb index 9b27724..bb33767 100644 --- a/app/models/activity.rb +++ b/app/models/activity.rb @@ -1,93 +1,99 @@ class Activity < ActiveRecord::Base + include ActionView::Helpers attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang attr_accessible :actor_attributes, :target_attributes, :object_attributes has_many :activity_objects, :dependent => :destroy has_one :actor has_one :object, :class_name => 'Obj' has_one :target belongs_to :user validates_presence_of :actor validates_presence_of :verb validates_presence_of :object validates_presence_of :published_at accepts_nested_attributes_for :actor, :object, :target, :reject_if => proc { |p| p['url_id'].blank? } def self.verbs_to_select [ ['POST', "http://activitystrea.ms/schema/1.0/post"] ] end + + def to_sentence + msg = "<a href='/activities/#{self.id}'>#{self.object.title}</a> - #{time_ago_in_words published_at} ago<br/>" + msg += "<a href='#{self.actor.url_id}'>#{self.actor.title}</a> | #{self.verb} | <a href='#{self.object.url_id}'>#{self.object.object_type}</a>" + end def to_json a = { :id => self.id, # XXX must be an URL :permalinkUrl => self.id, # XXX must be an URL :title => self.title, :summary => self.summary, :postedTime => self.published_at.to_s(:w3cdtf), :actor => { :id => self.actor.url_id, :title => self.actor.title, }, :object => { :id => self.object.url_id, :title => self.object.title, :objectType => self.object.object_type } } if self.target.present? a[:target] = { :id => self.target.url_id, :title => self.target.title, :objectType => self.target.object_type } end return JSON.pretty_generate({ :data => { :lang => "en-US", :id => self.id, :items => [ a ] } }.stringify_keys) end def to_xml builder = Builder::XmlMarkup.new(:indent => 2) builder.entry do |b| b.id self.id b.permalink self.id b.published self.published_at.to_s(:w3cdtf) b.title self.title b.summary self.summary b.author do b.id self.actor.url_id b.title self.actor.title end b.activity :verb, self.verb b.activity :actor do b.id self.actor.url_id b.title self.actor.title, :type => 'text' end b.activity :object do b.id self.object.url_id b.title self.object.title, :type => 'text' b.activity "object-type", self.object.object_type end if self.target.present? b.activity :target do b.id self.target.url_id b.title self.target.title, :type => 'text' b.activity "object-type", self.target.object_type end end end end end diff --git a/app/views/activities/index.html.haml b/app/views/activities/index.html.haml index d25878d..c3877e9 100644 --- a/app/views/activities/index.html.haml +++ b/app/views/activities/index.html.haml @@ -1,23 +1,6 @@ - title "Activities" -%table - %tr - %th Url - %th Published at - %th Verb - %th Title - %th Body - %th Lang - - for activity in @activities - %tr - %td= h activity.url_id - %td= h activity.published_at - %td= h activity.verb - %td= h activity.title - %td= h activity.body - %td= h activity.lang - %td= link_to 'Show', activity - %td= link_to 'Edit', edit_activity_path(activity) - %td= link_to 'Destroy', activity, :confirm => 'Are you sure?', :method => :delete +- for activity in @activities + %p= activity.to_sentence %p= link_to "New Activity", new_activity_path
webcracy/activity_streams-workshop
2df235c30808f72c42f341beb2591ebae898cf20
now an anonymous user can create activites, and they are saved the first time he/she/it logs in :)
diff --git a/app/controllers/activities_controller.rb b/app/controllers/activities_controller.rb index c57c191..b5810c1 100644 --- a/app/controllers/activities_controller.rb +++ b/app/controllers/activities_controller.rb @@ -1,44 +1,49 @@ class ActivitiesController < ApplicationController def show @activity = Activity.find(params[:id]) end def new @activity = Activity.new end def create @activity = Activity.new(params[:activity]) @activity.user = current_user if @activity.save + unless logged_in? + session[:activities] ||= [] + session[:activities] << @activity.id + end + flash[:notice] = "Successfully created activity." redirect_to @activity else render :action => 'new' end end def edit @activity = Activity.find(params[:id]) end def update @activity = Activity.find(params[:id]) @activity.user = current_user if @activity.update_attributes(params[:activity]) flash[:notice] = "Successfully updated activity." redirect_to @activity else render :action => 'edit' end end def destroy @activity = Activity.find(params[:id]) @activity.destroy flash[:notice] = "Successfully destroyed activity." redirect_to activities_url end end diff --git a/app/controllers/oauth_consumers_controller.rb b/app/controllers/oauth_consumers_controller.rb index 39358a7..40c9ae1 100644 --- a/app/controllers/oauth_consumers_controller.rb +++ b/app/controllers/oauth_consumers_controller.rb @@ -1,82 +1,92 @@ require 'oauth/controllers/consumer_controller' class OauthConsumersController < ApplicationController include Oauth::Controllers::ConsumerController before_filter :load_consumer skip_before_filter :login_required def index if logged_in? @consumer_tokens=ConsumerToken.all :conditions=>{:user_id=>current_user.id} @services=OAUTH_CREDENTIALS.keys-@consumer_tokens.collect{|c| c.class.service_name} end end # This callback method is heavily modified from the plugin's original to allow session and user creation # from an Aidentiti Oauth Authorization def callback @request_token_secret = (session[:yammer_token] ? session[:yammer_token][:request_secret] : session[params[:oauth_token]]) if @request_token_secret if params[:id] == 'aidentiti' # Create an Aidentiti Oauth Consumer to grab the user's credential @consumer = AidentitiToken.consumer access_token = get_access_token(@consumer, params[:oauth_token], @request_token_secret, params[:oauth_verifier]) # Save the Consumer's token and use it to create the client @token = AidentitiToken.create(:token => access_token.token, :secret => access_token.secret) aidentiti_client = Aidentiti::Base.new(@token.client) # Make the call to Aidentiti user_profile = aidentiti_client.grab_credentials.user # Do we need to create this user, or just load it? user = User.find_or_create_by_email(:email => user_profile.email, :login => user_profile.login) user.password = user.password_confirmation = user.login.reverse user.save + + # Transfer any activities this user created as anonymous to the new found user + if session[:activities].present? + session[:activities].each do |a| + activity = Activity.find(a) rescue nil + activity.try(:update_attribute, :user_id, user.id) + end + session[:activities] = [] + end + # Create a new session reset_session self.current_user = user new_cookie_flag = true handle_remember_cookie! new_cookie_flag # Keep the Aidentiti Oauth Token table clean old_consumer = AidentitiToken.find_by_user_id(user.id).delete if AidentitiToken.find_by_user_id(user.id) # Wrap up by assigning the @token.user_id = user.id # elsif params[:id] == 'yammer' # here you could use program specific behaviour for other oauth providers end if @token.save flash[:notice] = "#{params[:id].humanize} was successfully connected to your account" go_back else flash[:error] = "An error happened, please try connecting again" redirect_to oauth_consumer_url(params[:id]) end end end protected # Change this to decide where you want to redirect user to after callback is finished. # params[:id] holds the service name so you could use this to redirect to various parts # of your application depending on what service you're connecting to. def go_back redirect_to root_url end def load_consumer consumer_key=params[:id].to_sym throw RecordNotFound unless OAUTH_CREDENTIALS.include?(consumer_key) @consumer="#{consumer_key.to_s.camelcase}Token".constantize if current_user @[email protected]_by_user_id current_user.id end end def get_access_token(consumer, token,secret,oauth_verifier) request_token=OAuth::RequestToken.new consumer,token,secret options={} options[:oauth_verifier]=oauth_verifier if oauth_verifier access_token=request_token.get_access_token options access_token end end
webcracy/activity_streams-workshop
e390c272a95c541b648fee6cedc20d83df2321f1
cleaned login route
diff --git a/config/routes.rb b/config/routes.rb index cdbf22d..122d4ee 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,12 +1,12 @@ ActionController::Routing::Routes.draw do |map| map.resources :activities map.resources :oauth_consumers,:member=>{:callback=>:get} map.resources :users map.resource :session map.logout '/logout', :controller => 'sessions', :action => 'destroy' - map.login '/oauth_consumers', :controller => 'OauthConsumers', :action => 'index' + map.login '/login', :controller => 'OauthConsumers', :action => 'index' map.root :controller => 'activities', :action => "new" end
webcracy/activity_streams-workshop
623386e4d1c1cef234e2328544e2e102f5104695
cleaned some routes
diff --git a/config/routes.rb b/config/routes.rb index 6ec8a48..cdbf22d 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,14 +1,12 @@ ActionController::Routing::Routes.draw do |map| map.resources :activities map.resources :oauth_consumers,:member=>{:callback=>:get} map.resources :users map.resource :session map.logout '/logout', :controller => 'sessions', :action => 'destroy' - map.login '/login', :controller => 'sessions', :action => 'new' - map.register '/register', :controller => 'users', :action => 'create' - map.signup '/signup', :controller => 'users', :action => 'new' + map.login '/oauth_consumers', :controller => 'OauthConsumers', :action => 'index' map.root :controller => 'activities', :action => "new" end
webcracy/activity_streams-workshop
adf49db3cf7501459528afb82e349413e27fdc27
some cleanup on the activity show view
diff --git a/app/views/activities/show.html.haml b/app/views/activities/show.html.haml index 21d4898..7a36145 100644 --- a/app/views/activities/show.html.haml +++ b/app/views/activities/show.html.haml @@ -1,24 +1,31 @@ - title "Activity" %p - = @activity.actor.url_id - = @activity.verb - = @activity.object.url_id + - link_to @activity.actor.url_id do + = @activity.actor.title.present? ? @activity.actor.title : @activity.actor.url_id + + %abbr{:title => @activity.verb}= @activity.verb.split('/').last.upcase + + - link_to @activity.object.url_id do + = @activity.object.title.present? ? @activity.object.title : @activity.object.url_id + - if @activity.target.present? - = @activity.target.url_id + - link_to @activity.target.url_id do + = @activity.target.title.present? ? @activity.target.title : @activity.target.url_id + = time_ago_in_words @activity.published_at ago %h3 JSON ~ CodeRay.scan(@activity.to_json, 'json').div(:line_numbers => :table, :css => :class) %h3 XML ~ CodeRay.scan(@activity.to_xml, 'xml').div(:line_numbers => :table, :css => :class) %p = link_to "Edit", edit_activity_path(@activity) | = link_to "Destroy", @activity, :confirm => 'Are you sure?', :method => :delete | = link_to "Create another", new_activity_path
webcracy/activity_streams-workshop
c38c6e39ac8b01575f84622705b36cc9773a2de3
now using real URL ids on the activity model
diff --git a/app/models/activity.rb b/app/models/activity.rb index 9b27724..f383b3b 100644 --- a/app/models/activity.rb +++ b/app/models/activity.rb @@ -1,93 +1,96 @@ class Activity < ActiveRecord::Base + include ActionController::UrlWriter + default_url_options[:host] = APP_CONFIG[:domain] + attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang attr_accessible :actor_attributes, :target_attributes, :object_attributes has_many :activity_objects, :dependent => :destroy has_one :actor has_one :object, :class_name => 'Obj' has_one :target belongs_to :user validates_presence_of :actor validates_presence_of :verb validates_presence_of :object validates_presence_of :published_at accepts_nested_attributes_for :actor, :object, :target, :reject_if => proc { |p| p['url_id'].blank? } def self.verbs_to_select [ ['POST', "http://activitystrea.ms/schema/1.0/post"] ] end def to_json a = { - :id => self.id, # XXX must be an URL - :permalinkUrl => self.id, # XXX must be an URL + :id => activity_url(self), + :permalinkUrl => activity_url(self), :title => self.title, :summary => self.summary, :postedTime => self.published_at.to_s(:w3cdtf), :actor => { :id => self.actor.url_id, :title => self.actor.title, }, :object => { :id => self.object.url_id, :title => self.object.title, :objectType => self.object.object_type } } if self.target.present? a[:target] = { :id => self.target.url_id, :title => self.target.title, :objectType => self.target.object_type } end return JSON.pretty_generate({ :data => { :lang => "en-US", :id => self.id, :items => [ a ] } }.stringify_keys) end def to_xml builder = Builder::XmlMarkup.new(:indent => 2) builder.entry do |b| - b.id self.id - b.permalink self.id + b.id activity_url(self) + b.permalink activity_url(self) b.published self.published_at.to_s(:w3cdtf) b.title self.title b.summary self.summary b.author do b.id self.actor.url_id b.title self.actor.title end b.activity :verb, self.verb b.activity :actor do b.id self.actor.url_id b.title self.actor.title, :type => 'text' end b.activity :object do b.id self.object.url_id b.title self.object.title, :type => 'text' - b.activity "object-type", self.object.object_type + b.activity :"object-type", self.object.object_type end if self.target.present? b.activity :target do b.id self.target.url_id b.title self.target.title, :type => 'text' - b.activity "object-type", self.target.object_type + b.activity :"object-type", self.target.object_type end end end end end
webcracy/activity_streams-workshop
2456f193317f2fc732624eed6bc1834bd7f3c9a1
added missing belongs_to :user on activity model
diff --git a/app/models/activity.rb b/app/models/activity.rb index 84c78d7..9b27724 100644 --- a/app/models/activity.rb +++ b/app/models/activity.rb @@ -1,91 +1,93 @@ class Activity < ActiveRecord::Base attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang attr_accessible :actor_attributes, :target_attributes, :object_attributes has_many :activity_objects, :dependent => :destroy has_one :actor has_one :object, :class_name => 'Obj' has_one :target + belongs_to :user + validates_presence_of :actor validates_presence_of :verb validates_presence_of :object validates_presence_of :published_at accepts_nested_attributes_for :actor, :object, :target, :reject_if => proc { |p| p['url_id'].blank? } def self.verbs_to_select [ ['POST', "http://activitystrea.ms/schema/1.0/post"] ] end def to_json a = { :id => self.id, # XXX must be an URL :permalinkUrl => self.id, # XXX must be an URL :title => self.title, :summary => self.summary, :postedTime => self.published_at.to_s(:w3cdtf), :actor => { :id => self.actor.url_id, :title => self.actor.title, }, :object => { :id => self.object.url_id, :title => self.object.title, :objectType => self.object.object_type } } if self.target.present? a[:target] = { :id => self.target.url_id, :title => self.target.title, :objectType => self.target.object_type } end return JSON.pretty_generate({ :data => { :lang => "en-US", :id => self.id, :items => [ a ] } }.stringify_keys) end def to_xml builder = Builder::XmlMarkup.new(:indent => 2) builder.entry do |b| b.id self.id b.permalink self.id b.published self.published_at.to_s(:w3cdtf) b.title self.title b.summary self.summary b.author do b.id self.actor.url_id b.title self.actor.title end b.activity :verb, self.verb b.activity :actor do b.id self.actor.url_id b.title self.actor.title, :type => 'text' end b.activity :object do b.id self.object.url_id b.title self.object.title, :type => 'text' b.activity "object-type", self.object.object_type end if self.target.present? b.activity :target do b.id self.target.url_id b.title self.target.title, :type => 'text' b.activity "object-type", self.target.object_type end end end end end
webcracy/activity_streams-workshop
16f6ec8ea9f09651fff88e4c6baffdf0c895a9e8
added builder to .gems
diff --git a/.gems b/.gems index 71efb07..36e8591 100644 --- a/.gems +++ b/.gems @@ -1,8 +1,9 @@ rails --version 2.3.8 oauth oauth-plugin haml mash httparty json coderay +builder \ No newline at end of file
webcracy/activity_streams-workshop
72f8afef1221ccac473b17ed4964673349b34853
basic JSON and XML generation, with syntax highlight
diff --git a/.gems b/.gems index eb65aaf..71efb07 100644 --- a/.gems +++ b/.gems @@ -1,6 +1,8 @@ rails --version 2.3.8 oauth oauth-plugin haml mash -httparty \ No newline at end of file +httparty +json +coderay diff --git a/app/models/activity.rb b/app/models/activity.rb index 4ebcbff..84c78d7 100644 --- a/app/models/activity.rb +++ b/app/models/activity.rb @@ -1,23 +1,91 @@ class Activity < ActiveRecord::Base attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang attr_accessible :actor_attributes, :target_attributes, :object_attributes has_many :activity_objects, :dependent => :destroy has_one :actor has_one :object, :class_name => 'Obj' has_one :target validates_presence_of :actor validates_presence_of :verb validates_presence_of :object validates_presence_of :published_at accepts_nested_attributes_for :actor, :object, :target, :reject_if => proc { |p| p['url_id'].blank? } def self.verbs_to_select [ ['POST', "http://activitystrea.ms/schema/1.0/post"] ] end + + def to_json + a = { + :id => self.id, # XXX must be an URL + :permalinkUrl => self.id, # XXX must be an URL + :title => self.title, + :summary => self.summary, + :postedTime => self.published_at.to_s(:w3cdtf), + :actor => { + :id => self.actor.url_id, + :title => self.actor.title, + }, + :object => { + :id => self.object.url_id, + :title => self.object.title, + :objectType => self.object.object_type + } + } + + if self.target.present? + a[:target] = { + :id => self.target.url_id, + :title => self.target.title, + :objectType => self.target.object_type + } + end + + return JSON.pretty_generate({ + :data => { + :lang => "en-US", + :id => self.id, + :items => [ a ] + } + }.stringify_keys) + end + + def to_xml + builder = Builder::XmlMarkup.new(:indent => 2) + builder.entry do |b| + b.id self.id + b.permalink self.id + b.published self.published_at.to_s(:w3cdtf) + b.title self.title + b.summary self.summary + b.author do + b.id self.actor.url_id + b.title self.actor.title + end + b.activity :verb, self.verb + b.activity :actor do + b.id self.actor.url_id + b.title self.actor.title, :type => 'text' + end + b.activity :object do + b.id self.object.url_id + b.title self.object.title, :type => 'text' + b.activity "object-type", self.object.object_type + end + + if self.target.present? + b.activity :target do + b.id self.target.url_id + b.title self.target.title, :type => 'text' + b.activity "object-type", self.target.object_type + end + end + end + end end diff --git a/app/views/activities/show.html.haml b/app/views/activities/show.html.haml index 6264b3f..21d4898 100644 --- a/app/views/activities/show.html.haml +++ b/app/views/activities/show.html.haml @@ -1,18 +1,24 @@ - title "Activity" %p = @activity.actor.url_id = @activity.verb = @activity.object.url_id - if @activity.target.present? = @activity.target.url_id = time_ago_in_words @activity.published_at ago +%h3 JSON +~ CodeRay.scan(@activity.to_json, 'json').div(:line_numbers => :table, :css => :class) + +%h3 XML +~ CodeRay.scan(@activity.to_xml, 'xml').div(:line_numbers => :table, :css => :class) + %p = link_to "Edit", edit_activity_path(@activity) | = link_to "Destroy", @activity, :confirm => 'Are you sure?', :method => :delete | = link_to "Create another", new_activity_path diff --git a/config/environment.rb b/config/environment.rb index 21c5d7a..a8a15be 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,46 +1,49 @@ # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.8' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" config.gem 'haml' config.gem 'oauth' config.gem 'oauth-plugin' config.gem 'mash' - config.gem 'httparty' + config.gem 'httparty' + config.gem 'json' + config.gem 'coderay' + config.gem 'builder' # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'UTC' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de -end \ No newline at end of file +end diff --git a/config/initializers/time_additions.rb b/config/initializers/time_additions.rb new file mode 100644 index 0000000..9450f5b --- /dev/null +++ b/config/initializers/time_additions.rb @@ -0,0 +1 @@ +Time::DATE_FORMATS[:w3cdtf] = lambda { |time| time.strftime("%Y-%m-%dT%H:%M:%S#{time.formatted_offset}") } diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css index f54d248..c43400f 100644 --- a/public/stylesheets/application.css +++ b/public/stylesheets/application.css @@ -1,63 +1,113 @@ body { background-color: #4b7399; font-family: Verdana, Helvetica, Arial; font-size: 14px; } a { color: blue; } a img { border: none; } .clear { clear: both; height: 0; overflow: hidden; } #container { width: 75%; margin: 0 auto; background: white; padding: 20px 40px; border: solid 1px black; margin-top: 20px; } #flash_notice, #flash_error { padding: 5px 8px; margin: 10px 0; } #flash_notice { background-color: #ccffcc; border: solid 1px #66cc66; } #flash_error { background-color: #ffcccc; border: solid 1px #cc6666; } .fieldWithErrors { display: inline; } #errorExplanation { width: 400px; border: 2px solid #cf0000; padding: 0; padding-bottom: 12px; margin-bottom: 20px; background-color: #f0f0f0; } #errorExplanation h2 { text-align: left; padding: 5px 5px 5px 15px; margin: 0; font-weight: bold; font-size: 12px; background-color: #cc0000; color: white; } #errorExplanation p { color: #333333; margin-bottom: 0; padding: 8px; } #errorExplanation ul { margin: 2px 24px; } #errorExplanation ul li { font-size: 12px; list-style: disc; } + +.CodeRay { + background-color: #232323; + border: 1px solid black; + font-family: "Courier New", "Terminal", monospace; + color: #e6e0db; + padding: 3px 5px; + overflow: auto; + font-size: 12px; + margin: 12px 0; } + .CodeRay pre { + margin: 0px; + padding: 0px; } + .CodeRay .an { + color: #e7be69; } + .CodeRay .c { + color: #bc9358; + font-style: italic; } + .CodeRay .ch { + color: #509e4f; } + .CodeRay .cl { + color: white; } + .CodeRay .co { + color: white; } + .CodeRay .fl { + color: #a4c260; } + .CodeRay .fu { + color: #ffc56d; } + .CodeRay .gv { + color: #d0cffe; } + .CodeRay .i { + color: #a4c260; } + .CodeRay .il { + background: #151515; } + .CodeRay .iv { + color: #d0cffe; } + .CodeRay .pp { + color: #e7be69; } + .CodeRay .r { + color: #cb7832; } + .CodeRay .rx { + color: #a4c260; } + .CodeRay .s { + color: #a4c260; } + .CodeRay .sy { + color: #6c9cbd; } + .CodeRay .ta { + color: #e7be69; } + .CodeRay .pc { + color: #6c9cbd; } diff --git a/public/stylesheets/sass/application.sass b/public/stylesheets/sass/application.sass index 8cfddab..5c92206 100644 --- a/public/stylesheets/sass/application.sass +++ b/public/stylesheets/sass/application.sass @@ -1,67 +1,119 @@ !primary_color = #4B7399 body :background-color = !primary_color :font :family Verdana, Helvetica, Arial :size 14px a :color #0000FF img :border none .clear :clear both :height 0 :overflow hidden #container :width 75% :margin 0 auto :background #fff :padding 20px 40px :border solid 1px black :margin-top 20px #flash_notice, #flash_error :padding 5px 8px :margin 10px 0 #flash_notice :background-color #CFC :border solid 1px #6C6 #flash_error :background-color #FCC :border solid 1px #C66 .fieldWithErrors :display inline #errorExplanation :width 400px :border 2px solid #CF0000 :padding 0 :padding-bottom 12px :margin-bottom 20px :background-color #f0f0f0 h2 :text-align left :padding 5px 5px 5px 15px :margin 0 :font :weight bold :size 12px :background-color #c00 :color #fff p :color #333 :margin-bottom 0 :padding 8px ul :margin 2px 24px li :font-size 12px :list-style disc + +.CodeRay + background-color: #232323 + border: 1px solid black + font-family: 'Courier New', 'Terminal', monospace + color: #E6E0DB + padding: 3px 5px + overflow: auto + font-size: 12px + margin: 12px 0 + pre + margin: 0px + padding: 0px + + .an + color: #E7BE69 + .c + color: #BC9358 + font-style: italic + .ch + color: #509E4F + .cl + color: #FFF + .co + color: #FFF + .fl + color: #A4C260 + .fu + color: #FFC56D + .gv + color: #D0CFFE + .i + color: #A4C260 + .il + background: #151515 + .iv + color: #D0CFFE + .pp + color: #E7BE69 + .r + color: #CB7832 + .rx + color: #A4C260 + .s + color: #A4C260 + .sy + color: #6C9CBD + .ta + color: #E7BE69 + .pc + color: #6C9CBD +
webcracy/activity_streams-workshop
38b169f4455046366efeed03c13006304ec197d1
changed root route to new activity
diff --git a/config/routes.rb b/config/routes.rb index a62d189..6ec8a48 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,14 +1,14 @@ ActionController::Routing::Routes.draw do |map| - map.resources :activities + map.resources :activities map.resources :oauth_consumers,:member=>{:callback=>:get} map.resources :users map.resource :session map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.login '/login', :controller => 'sessions', :action => 'new' map.register '/register', :controller => 'users', :action => 'create' map.signup '/signup', :controller => 'users', :action => 'new' - map.root :controller => 'oauth_consumers' + map.root :controller => 'activities', :action => "new" end
webcracy/activity_streams-workshop
848fae3fb91c2ba6bf8ebb562d349263557d9b3e
gave some love to the activity show page
diff --git a/app/controllers/activities_controller.rb b/app/controllers/activities_controller.rb index 88c8658..c57c191 100644 --- a/app/controllers/activities_controller.rb +++ b/app/controllers/activities_controller.rb @@ -1,44 +1,44 @@ class ActivitiesController < ApplicationController - def index - @activities = Activity.all - end - def show @activity = Activity.find(params[:id]) end def new @activity = Activity.new end def create @activity = Activity.new(params[:activity]) + @activity.user = current_user + if @activity.save flash[:notice] = "Successfully created activity." redirect_to @activity else render :action => 'new' end end def edit @activity = Activity.find(params[:id]) end def update @activity = Activity.find(params[:id]) + @activity.user = current_user + if @activity.update_attributes(params[:activity]) flash[:notice] = "Successfully updated activity." redirect_to @activity else render :action => 'edit' end end def destroy @activity = Activity.find(params[:id]) @activity.destroy flash[:notice] = "Successfully destroyed activity." redirect_to activities_url end end diff --git a/app/views/activities/show.html.haml b/app/views/activities/show.html.haml index a08b5c6..6264b3f 100644 --- a/app/views/activities/show.html.haml +++ b/app/views/activities/show.html.haml @@ -1,27 +1,18 @@ - title "Activity" %p - %strong Url: - =h @activity.url_id -%p - %strong Published At: - =h @activity.published_at -%p - %strong Verb: - =h @activity.verb -%p - %strong Title: - =h @activity.title -%p - %strong Body: - =h @activity.body -%p - %strong Lang: - =h @activity.lang + = @activity.actor.url_id + = @activity.verb + = @activity.object.url_id + - if @activity.target.present? + = @activity.target.url_id + = time_ago_in_words @activity.published_at + ago + %p = link_to "Edit", edit_activity_path(@activity) | = link_to "Destroy", @activity, :confirm => 'Are you sure?', :method => :delete | - = link_to "View All", activities_path + = link_to "Create another", new_activity_path
webcracy/activity_streams-workshop
d35b3357f3709aa365b28f6e598635a23c151c21
basic validations for activity form
diff --git a/app/models/activity.rb b/app/models/activity.rb index 897ddcb..4ebcbff 100644 --- a/app/models/activity.rb +++ b/app/models/activity.rb @@ -1,17 +1,23 @@ class Activity < ActiveRecord::Base attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang + attr_accessible :actor_attributes, :target_attributes, :object_attributes has_many :activity_objects, :dependent => :destroy has_one :actor has_one :object, :class_name => 'Obj' has_one :target - accepts_nested_attributes_for :actor, :object, :target + validates_presence_of :actor + validates_presence_of :verb + validates_presence_of :object + validates_presence_of :published_at + + accepts_nested_attributes_for :actor, :object, :target, :reject_if => proc { |p| p['url_id'].blank? } def self.verbs_to_select [ ['POST', "http://activitystrea.ms/schema/1.0/post"] ] end end diff --git a/app/models/activity_object.rb b/app/models/activity_object.rb index fd83f9e..dc8537d 100644 --- a/app/models/activity_object.rb +++ b/app/models/activity_object.rb @@ -1,5 +1,7 @@ class ActivityObject < ActiveRecord::Base - attr_accessible :activity_id, :type, :url_id, :title, :published_at + attr_accessible :activity_id, :type, :url_id, :title, :published_at, :object_type belongs_to :activity + + validates_format_of :url_id, :with => URI::regexp(%w(http https)), :allow_blank => true end diff --git a/app/models/actor.rb b/app/models/actor.rb index 596e8e2..079cf52 100644 --- a/app/models/actor.rb +++ b/app/models/actor.rb @@ -1,3 +1,3 @@ class Actor < ActivityObject - + validates_presence_of :url_id end diff --git a/app/models/obj.rb b/app/models/obj.rb index 286435b..3c41b42 100644 --- a/app/models/obj.rb +++ b/app/models/obj.rb @@ -1,7 +1,9 @@ class Obj < ActivityObject + validates_presence_of :url_id + def self.to_select [ ['PHOTO', "http://activitystrea.ms/schema/1.0/photo"] ] end end diff --git a/app/views/activities/_form.html.haml b/app/views/activities/_form.html.haml index 77daf3b..a8830ad 100644 --- a/app/views/activities/_form.html.haml +++ b/app/views/activities/_form.html.haml @@ -1,76 +1,76 @@ - form_for @activity do |f| = f.error_messages - f.fields_for :actor, @activity.actor || @activity.build_actor do |actor| %fieldset %legend Actor %p - = actor.label :id + = actor.label :url_id, "Id" %br - = actor.text_field :id + = actor.text_field :url_id %p = actor.label :title %br = actor.text_field :title %fieldset %legend Verb %p = f.label :verb = f.select :verb, Activity.verbs_to_select - f.fields_for :object, @activity.object || @activity.build_object do |object| %fieldset %legend Object %p - = object.label :id + = object.label :url_id, "Id" %br - = object.text_field :id + = object.text_field :url_id %p = object.label :object_type = object.select :object_type, Obj.to_select %p = object.label :title %br = object.text_field :title - f.fields_for :target, @activity.target || @activity.build_target do |target| %fieldset %legend Target %p - = target.label :id + = target.label :url_id, "Id" %br - = target.text_field :id + = target.text_field :url_id %p = target.label :object_type = target.select :object_type, Target.to_select %p = target.label :title %br = target.text_field :title %fieldset %legend Activity %p = f.label :title %br = f.text_field :title %p = f.label :summary %br = f.text_area :summary %p = f.label :published_at %br = f.datetime_select :published_at %p = f.submit
webcracy/activity_streams-workshop
2b35e112e02106a723896f1c8e7d8a765d5af6f7
Initial activity form implementation
diff --git a/app/models/activity.rb b/app/models/activity.rb index 35e2a59..897ddcb 100644 --- a/app/models/activity.rb +++ b/app/models/activity.rb @@ -1,9 +1,17 @@ class Activity < ActiveRecord::Base attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang has_many :activity_objects, :dependent => :destroy has_one :actor has_one :object, :class_name => 'Obj' has_one :target + + accepts_nested_attributes_for :actor, :object, :target + + def self.verbs_to_select + [ + ['POST', "http://activitystrea.ms/schema/1.0/post"] + ] + end end diff --git a/app/models/obj.rb b/app/models/obj.rb index 7d5cbaf..286435b 100644 --- a/app/models/obj.rb +++ b/app/models/obj.rb @@ -1,3 +1,7 @@ class Obj < ActivityObject - + def self.to_select + [ + ['PHOTO', "http://activitystrea.ms/schema/1.0/photo"] + ] + end end diff --git a/app/models/target.rb b/app/models/target.rb index 4c22fe7..f46766d 100644 --- a/app/models/target.rb +++ b/app/models/target.rb @@ -1,3 +1,7 @@ class Target < ActivityObject - + def self.to_select + [ + ['PHOTO-ALBUM', 'http://activitystrea.ms/schema/1.0/photo-album'] + ] + end end diff --git a/app/views/activities/_form.html.haml b/app/views/activities/_form.html.haml index cd84083..77daf3b 100644 --- a/app/views/activities/_form.html.haml +++ b/app/views/activities/_form.html.haml @@ -1,28 +1,76 @@ - form_for @activity do |f| = f.error_messages - %p - = f.label :url_id - %br - = f.text_field :url_id - %p - = f.label :published_at - %br - = f.datetime_select :published_at - %p - = f.label :verb - %br - = f.text_field :verb - %p - = f.label :title - %br - = f.text_field :title - %p - = f.label :body - %br - = f.text_area :body - %p - = f.label :lang - %br - = f.text_field :lang + + - f.fields_for :actor, @activity.actor || @activity.build_actor do |actor| + %fieldset + %legend Actor + %p + = actor.label :id + %br + = actor.text_field :id + + %p + = actor.label :title + %br + = actor.text_field :title + + %fieldset + %legend Verb + %p + = f.label :verb + = f.select :verb, Activity.verbs_to_select + + - f.fields_for :object, @activity.object || @activity.build_object do |object| + %fieldset + %legend Object + %p + = object.label :id + %br + = object.text_field :id + + %p + = object.label :object_type + = object.select :object_type, Obj.to_select + + %p + = object.label :title + %br + = object.text_field :title + + - f.fields_for :target, @activity.target || @activity.build_target do |target| + %fieldset + %legend Target + %p + = target.label :id + %br + = target.text_field :id + + %p + = target.label :object_type + = target.select :object_type, Target.to_select + + %p + = target.label :title + %br + = target.text_field :title + + %fieldset + %legend Activity + + %p + = f.label :title + %br + = f.text_field :title + + %p + = f.label :summary + %br + = f.text_area :summary + + %p + = f.label :published_at + %br + = f.datetime_select :published_at + %p = f.submit diff --git a/db/migrate/20100713144023_add_object_type_to_activity_object.rb b/db/migrate/20100713144023_add_object_type_to_activity_object.rb new file mode 100644 index 0000000..645b624 --- /dev/null +++ b/db/migrate/20100713144023_add_object_type_to_activity_object.rb @@ -0,0 +1,9 @@ +class AddObjectTypeToActivityObject < ActiveRecord::Migration + def self.up + add_column :activity_objects, :object_type, :string + end + + def self.down + remove_column :activity_objects, :object_type + end +end
webcracy/activity_streams-workshop
d1cca7d59d0f63e54a3baf27737d435bf7cf0a1c
Renamed body to summary in activity object
diff --git a/app/models/activity.rb b/app/models/activity.rb index 2d66a1d..35e2a59 100644 --- a/app/models/activity.rb +++ b/app/models/activity.rb @@ -1,9 +1,9 @@ class Activity < ActiveRecord::Base - attr_accessible :url_id, :published_at, :verb, :title, :body, :lang + attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang has_many :activity_objects, :dependent => :destroy has_one :actor has_one :object, :class_name => 'Obj' has_one :target end diff --git a/db/migrate/20100713143338_rename_body_to_summary_in_activity.rb b/db/migrate/20100713143338_rename_body_to_summary_in_activity.rb new file mode 100644 index 0000000..723b684 --- /dev/null +++ b/db/migrate/20100713143338_rename_body_to_summary_in_activity.rb @@ -0,0 +1,9 @@ +class RenameBodyToSummaryInActivity < ActiveRecord::Migration + def self.up + rename_column :activities, :body, :summary + end + + def self.down + rename_column :activities, :summary, :body + end +end diff --git a/db/schema.rb b/db/schema.rb index e43572a..df89895 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,66 +1,67 @@ # 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 => 20100713133745) do +ActiveRecord::Schema.define(:version => 20100713144023) do create_table "activities", :force => true do |t| t.integer "user_id" t.string "url_id" t.string "verb" t.string "title" - t.text "body" + t.text "summary" t.string "lang" t.datetime "published_at" t.datetime "created_at" t.datetime "updated_at" end add_index "activities", ["user_id"], :name => "index_activities_on_user_id" create_table "activity_objects", :force => true do |t| t.integer "activity_id" t.string "type" t.string "url_id" t.string "title" t.datetime "published_at" t.datetime "created_at" t.datetime "updated_at" + t.string "object_type" end add_index "activity_objects", ["activity_id"], :name => "index_activity_objects_on_activity_id" add_index "activity_objects", ["type"], :name => "index_activity_objects_on_type" create_table "consumer_tokens", :force => true do |t| t.integer "user_id" t.string "type", :limit => 30 t.string "token", :limit => 1024 t.string "secret" t.datetime "created_at" t.datetime "updated_at" end add_index "consumer_tokens", ["token"], :name => "index_consumer_tokens_on_token", :unique => true create_table "users", :force => true do |t| t.string "login", :limit => 40 t.string "name", :limit => 100, :default => "" t.string "email", :limit => 100 t.string "crypted_password", :limit => 40 t.string "salt", :limit => 40 t.datetime "created_at" t.datetime "updated_at" t.string "remember_token", :limit => 40 t.datetime "remember_token_expires_at" end add_index "users", ["login"], :name => "index_users_on_login", :unique => true end
webcracy/activity_streams-workshop
ff7aea89fd640c8ab8defe231a86346ce74c8f39
fixed user_bar and flash notice conflict
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml index 36e0608..d02f0ee 100644 --- a/app/views/layouts/application.html.haml +++ b/app/views/layouts/application.html.haml @@ -1,23 +1,23 @@ !!! Strict %html{html_attrs} %head %title = h(yield(:title) || "Activity Streams Workshop") %meta{"http-equiv"=>"Content-Type", :content=>"text/html; charset=utf-8"}/ = stylesheet_link_tag 'application' = javascript_include_tag :defaults = yield(:head) %body #container - #user_bar{:style => 'float:right;'} + #user_bar{:style => 'text-align: right; width: 100%;'} = render :partial => 'users/user_bar' - flash.each do |name, msg| = content_tag :div, msg, :id => "flash_#{name}" - if show_title? %h1=h yield(:title) = yield
webcracy/activity_streams-workshop
ed1ac27aefc8b433b63e623799bde01d59c37eb8
Renamed class Object to Obj
diff --git a/app/models/activity.rb b/app/models/activity.rb index f143815..2d66a1d 100644 --- a/app/models/activity.rb +++ b/app/models/activity.rb @@ -1,9 +1,9 @@ class Activity < ActiveRecord::Base attr_accessible :url_id, :published_at, :verb, :title, :body, :lang has_many :activity_objects, :dependent => :destroy has_one :actor - has_one :object + has_one :object, :class_name => 'Obj' has_one :target end diff --git a/app/models/obj.rb b/app/models/obj.rb new file mode 100644 index 0000000..7d5cbaf --- /dev/null +++ b/app/models/obj.rb @@ -0,0 +1,3 @@ +class Obj < ActivityObject + +end diff --git a/app/models/object.rb b/app/models/object.rb deleted file mode 100644 index ae19bae..0000000 --- a/app/models/object.rb +++ /dev/null @@ -1,3 +0,0 @@ -class Object < ActivityObject - -end
webcracy/activity_streams-workshop
bba2f0d33608171d325e0af5c74346caf798ffc8
heroku forced this commit... soz
diff --git a/config/environment.rb b/config/environment.rb index 21c5d7a..0785e38 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,46 +1,43 @@ # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.8' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" config.gem 'haml' config.gem 'oauth' config.gem 'oauth-plugin' - config.gem 'mash' - config.gem 'httparty' - # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'UTC' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de end \ No newline at end of file
webcracy/activity_streams-workshop
87b0f5fcb65956e46f0e32b6a9405a2725cf2cf5
fixed forwardable requirement
diff --git a/.gems b/.gems index ad73726..eb65aaf 100644 --- a/.gems +++ b/.gems @@ -1,7 +1,6 @@ rails --version 2.3.8 oauth oauth-plugin haml -forwardable mash httparty \ No newline at end of file diff --git a/config/environment.rb b/config/environment.rb index 3fda0aa..21c5d7a 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,47 +1,46 @@ # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.8' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" config.gem 'haml' config.gem 'oauth' config.gem 'oauth-plugin' - config.gem 'forwardable' config.gem 'mash' config.gem 'httparty' # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'UTC' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de end \ No newline at end of file
webcracy/activity_streams-workshop
da80b6ccf805f5985f1caedf31bd63155d07ca81
added aidentiti lib gems to manifest
diff --git a/.gems b/.gems index 1c90ad6..ad73726 100644 --- a/.gems +++ b/.gems @@ -1,4 +1,7 @@ rails --version 2.3.8 oauth oauth-plugin -haml \ No newline at end of file +haml +forwardable +mash +httparty \ No newline at end of file diff --git a/config/environment.rb b/config/environment.rb index e62767f..3fda0aa 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,44 +1,47 @@ # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.8' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" config.gem 'haml' config.gem 'oauth' config.gem 'oauth-plugin' + config.gem 'forwardable' + config.gem 'mash' + config.gem 'httparty' # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'UTC' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de end \ No newline at end of file
webcracy/activity_streams-workshop
abb4d8ac84d7168a39edfa2c0379073f6a6183f5
minor tweaks
diff --git a/.gems b/.gems index a20bca5..1c90ad6 100644 --- a/.gems +++ b/.gems @@ -1,3 +1,4 @@ +rails --version 2.3.8 oauth oauth-plugin haml \ No newline at end of file diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml index 26a6e32..36e0608 100644 --- a/app/views/layouts/application.html.haml +++ b/app/views/layouts/application.html.haml @@ -1,22 +1,23 @@ !!! Strict %html{html_attrs} %head %title - = h(yield(:title) || "Untitled") + = h(yield(:title) || "Activity Streams Workshop") %meta{"http-equiv"=>"Content-Type", :content=>"text/html; charset=utf-8"}/ = stylesheet_link_tag 'application' = javascript_include_tag :defaults = yield(:head) %body #container #user_bar{:style => 'float:right;'} = render :partial => 'users/user_bar' + - flash.each do |name, msg| = content_tag :div, msg, :id => "flash_#{name}" - if show_title? %h1=h yield(:title) = yield
webcracy/activity_streams-workshop
d08d2e1e81286f1f15dc246137bc08d9925fd41a
clean routes.rb file
diff --git a/config/routes.rb b/config/routes.rb index 555bada..a62d189 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,58 +1,14 @@ ActionController::Routing::Routes.draw do |map| map.resources :activities - map.resources :oauth_consumers,:member=>{:callback=>:get} map.resources :users map.resource :session - map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.login '/login', :controller => 'sessions', :action => 'new' map.register '/register', :controller => 'users', :action => 'create' map.signup '/signup', :controller => 'users', :action => 'new' map.root :controller => 'oauth_consumers' - - # 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 or commenting them out if you're using named routes and resources. - map.connect ':controller/:action/:id' - map.connect ':controller/:action/:id.:format' end
webcracy/activity_streams-workshop
61fd300e6f0509968d3c40fe1f86b3b0da0484b3
integrated user_bar in the layout
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml index 5e9370f..24772e3 100644 --- a/app/views/layouts/application.html.haml +++ b/app/views/layouts/application.html.haml @@ -1,19 +1,21 @@ !!! Strict %html{html_attrs} %head %title = h(yield(:title) || "Untitled") %meta{"http-equiv"=>"Content-Type", :content=>"text/html; charset=utf-8"}/ = stylesheet_link_tag 'application' = yield(:head) %body #container + #user_bar{:style => 'float:right;'} + = render :partial => 'users/user_bar' - flash.each do |name, msg| = content_tag :div, msg, :id => "flash_#{name}" - if show_title? %h1=h yield(:title) = yield diff --git a/app/views/users/_user_bar.html.erb b/app/views/users/_user_bar.html.erb index 0c53629..e15c1a2 100644 --- a/app/views/users/_user_bar.html.erb +++ b/app/views/users/_user_bar.html.erb @@ -1,8 +1,9 @@ <% if logged_in? -%> - <div id="user-bar-greeting">Logged in as <%= link_to_current_user :content_method => :login %></div> - <div id="user-bar-action" >(<%= link_to "Log out", logout_path, { :title => "Log out" } %>)</div> -<% else -%> - <div id="user-bar-greeting"><%= link_to_login_with_IP 'Not logged in', :style => 'border: none;' %></div> - <div id="user-bar-action" ><%= link_to "Log in", login_path, { :title => "Log in" } %> / - <%= link_to "Sign up", signup_path, { :title => "Create an account" } %></div> + <div id="user-bar-greeting"> + Logged in as <%= current_user.email %> + <!-- <%= link_to_current_user :content_method => :login %> --> + </div> + <div id="user-bar-action" style="text-align: right;"> + (<%= link_to "Log out", logout_path, { :title => "Log out" } %>) + </div> <% end -%>
webcracy/activity_streams-workshop
ffb1d5069233517f9e02dbd4ccf4a0598f592c26
added basic models
diff --git a/app/controllers/activities_controller.rb b/app/controllers/activities_controller.rb new file mode 100644 index 0000000..88c8658 --- /dev/null +++ b/app/controllers/activities_controller.rb @@ -0,0 +1,44 @@ +class ActivitiesController < ApplicationController + def index + @activities = Activity.all + end + + def show + @activity = Activity.find(params[:id]) + end + + def new + @activity = Activity.new + end + + def create + @activity = Activity.new(params[:activity]) + if @activity.save + flash[:notice] = "Successfully created activity." + redirect_to @activity + else + render :action => 'new' + end + end + + def edit + @activity = Activity.find(params[:id]) + end + + def update + @activity = Activity.find(params[:id]) + if @activity.update_attributes(params[:activity]) + flash[:notice] = "Successfully updated activity." + redirect_to @activity + else + render :action => 'edit' + end + end + + def destroy + @activity = Activity.find(params[:id]) + @activity.destroy + flash[:notice] = "Successfully destroyed activity." + redirect_to activities_url + end +end diff --git a/app/helpers/activities_helper.rb b/app/helpers/activities_helper.rb new file mode 100644 index 0000000..4e9784c --- /dev/null +++ b/app/helpers/activities_helper.rb @@ -0,0 +1,2 @@ +module ActivitiesHelper +end diff --git a/app/models/activity.rb b/app/models/activity.rb new file mode 100644 index 0000000..f143815 --- /dev/null +++ b/app/models/activity.rb @@ -0,0 +1,9 @@ +class Activity < ActiveRecord::Base + attr_accessible :url_id, :published_at, :verb, :title, :body, :lang + + has_many :activity_objects, :dependent => :destroy + + has_one :actor + has_one :object + has_one :target +end diff --git a/app/models/activity_object.rb b/app/models/activity_object.rb new file mode 100644 index 0000000..fd83f9e --- /dev/null +++ b/app/models/activity_object.rb @@ -0,0 +1,5 @@ +class ActivityObject < ActiveRecord::Base + attr_accessible :activity_id, :type, :url_id, :title, :published_at + + belongs_to :activity +end diff --git a/app/models/actor.rb b/app/models/actor.rb new file mode 100644 index 0000000..596e8e2 --- /dev/null +++ b/app/models/actor.rb @@ -0,0 +1,3 @@ +class Actor < ActivityObject + +end diff --git a/app/models/object.rb b/app/models/object.rb new file mode 100644 index 0000000..ae19bae --- /dev/null +++ b/app/models/object.rb @@ -0,0 +1,3 @@ +class Object < ActivityObject + +end diff --git a/app/models/target.rb b/app/models/target.rb new file mode 100644 index 0000000..4c22fe7 --- /dev/null +++ b/app/models/target.rb @@ -0,0 +1,3 @@ +class Target < ActivityObject + +end diff --git a/app/views/activities/_form.html.haml b/app/views/activities/_form.html.haml new file mode 100644 index 0000000..cd84083 --- /dev/null +++ b/app/views/activities/_form.html.haml @@ -0,0 +1,28 @@ +- form_for @activity do |f| + = f.error_messages + %p + = f.label :url_id + %br + = f.text_field :url_id + %p + = f.label :published_at + %br + = f.datetime_select :published_at + %p + = f.label :verb + %br + = f.text_field :verb + %p + = f.label :title + %br + = f.text_field :title + %p + = f.label :body + %br + = f.text_area :body + %p + = f.label :lang + %br + = f.text_field :lang + %p + = f.submit diff --git a/app/views/activities/edit.html.haml b/app/views/activities/edit.html.haml new file mode 100644 index 0000000..4fd3613 --- /dev/null +++ b/app/views/activities/edit.html.haml @@ -0,0 +1,8 @@ +- title "Edit Activity" + += render :partial => 'form' + +%p + = link_to "Show", activity_path(@activity) + | + = link_to "View All", activities_path diff --git a/app/views/activities/index.html.haml b/app/views/activities/index.html.haml new file mode 100644 index 0000000..d25878d --- /dev/null +++ b/app/views/activities/index.html.haml @@ -0,0 +1,23 @@ +- title "Activities" + +%table + %tr + %th Url + %th Published at + %th Verb + %th Title + %th Body + %th Lang + - for activity in @activities + %tr + %td= h activity.url_id + %td= h activity.published_at + %td= h activity.verb + %td= h activity.title + %td= h activity.body + %td= h activity.lang + %td= link_to 'Show', activity + %td= link_to 'Edit', edit_activity_path(activity) + %td= link_to 'Destroy', activity, :confirm => 'Are you sure?', :method => :delete + +%p= link_to "New Activity", new_activity_path diff --git a/app/views/activities/new.html.haml b/app/views/activities/new.html.haml new file mode 100644 index 0000000..2271379 --- /dev/null +++ b/app/views/activities/new.html.haml @@ -0,0 +1,5 @@ +- title "New Activity" + += render :partial => 'form' + +%p= link_to "Back to List", activities_path diff --git a/app/views/activities/show.html.haml b/app/views/activities/show.html.haml new file mode 100644 index 0000000..a08b5c6 --- /dev/null +++ b/app/views/activities/show.html.haml @@ -0,0 +1,27 @@ +- title "Activity" + +%p + %strong Url: + =h @activity.url_id +%p + %strong Published At: + =h @activity.published_at +%p + %strong Verb: + =h @activity.verb +%p + %strong Title: + =h @activity.title +%p + %strong Body: + =h @activity.body +%p + %strong Lang: + =h @activity.lang + +%p + = link_to "Edit", edit_activity_path(@activity) + | + = link_to "Destroy", @activity, :confirm => 'Are you sure?', :method => :delete + | + = link_to "View All", activities_path diff --git a/config/routes.rb b/config/routes.rb index 42b9225..555bada 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,56 +1,58 @@ ActionController::Routing::Routes.draw do |map| + map.resources :activities + map.resources :oauth_consumers,:member=>{:callback=>:get} map.resources :users map.resource :session map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.login '/login', :controller => 'sessions', :action => 'new' map.register '/register', :controller => 'users', :action => 'create' map.signup '/signup', :controller => 'users', :action => 'new' map.root :controller => 'oauth_consumers' # 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 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/20100713133403_create_activities.rb b/db/migrate/20100713133403_create_activities.rb new file mode 100644 index 0000000..10d62c8 --- /dev/null +++ b/db/migrate/20100713133403_create_activities.rb @@ -0,0 +1,22 @@ +class CreateActivities < ActiveRecord::Migration + def self.up + create_table :activities do |t| + t.integer :user_id + t.string :url_id + t.string :verb + t.string :title + t.text :body + t.string :lang + t.datetime :published_at + t.timestamps + end + + add_index :activities, :user_id + end + + def self.down + remove_index :activities + + drop_table :activities + end +end diff --git a/db/migrate/20100713133745_create_activity_objects.rb b/db/migrate/20100713133745_create_activity_objects.rb new file mode 100644 index 0000000..ae03a61 --- /dev/null +++ b/db/migrate/20100713133745_create_activity_objects.rb @@ -0,0 +1,22 @@ +class CreateActivityObjects < ActiveRecord::Migration + def self.up + create_table :activity_objects do |t| + t.integer :activity_id + t.string :type + t.string :url_id + t.string :title + t.datetime :published_at + t.timestamps + end + + add_index :activity_objects, :activity_id + add_index :activity_objects, :type + end + + def self.down + remove_index :activity_objects, :type + remove_index :activity_objects, :activity_id + + drop_table :activity_objects + end +end diff --git a/db/schema.rb b/db/schema.rb index 1e987e4..e43572a 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,39 +1,66 @@ # 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 => 20100713115031) do +ActiveRecord::Schema.define(:version => 20100713133745) do + + create_table "activities", :force => true do |t| + t.integer "user_id" + t.string "url_id" + t.string "verb" + t.string "title" + t.text "body" + t.string "lang" + t.datetime "published_at" + t.datetime "created_at" + t.datetime "updated_at" + end + + add_index "activities", ["user_id"], :name => "index_activities_on_user_id" + + create_table "activity_objects", :force => true do |t| + t.integer "activity_id" + t.string "type" + t.string "url_id" + t.string "title" + t.datetime "published_at" + t.datetime "created_at" + t.datetime "updated_at" + end + + add_index "activity_objects", ["activity_id"], :name => "index_activity_objects_on_activity_id" + add_index "activity_objects", ["type"], :name => "index_activity_objects_on_type" create_table "consumer_tokens", :force => true do |t| t.integer "user_id" t.string "type", :limit => 30 t.string "token", :limit => 1024 t.string "secret" t.datetime "created_at" t.datetime "updated_at" end add_index "consumer_tokens", ["token"], :name => "index_consumer_tokens_on_token", :unique => true create_table "users", :force => true do |t| t.string "login", :limit => 40 t.string "name", :limit => 100, :default => "" t.string "email", :limit => 100 t.string "crypted_password", :limit => 40 t.string "salt", :limit => 40 t.datetime "created_at" t.datetime "updated_at" t.string "remember_token", :limit => 40 t.datetime "remember_token_expires_at" end add_index "users", ["login"], :name => "index_users_on_login", :unique => true end diff --git a/test/fixtures/activities.yml b/test/fixtures/activities.yml new file mode 100644 index 0000000..d49c148 --- /dev/null +++ b/test/fixtures/activities.yml @@ -0,0 +1,15 @@ +one: + url_id: MyString + published_at: 2010-07-13 14:34:03 + verb: MyString + title: MyString + body: MyText + lang: MyString + +two: + url_id: MyString + published_at: 2010-07-13 14:34:03 + verb: MyString + title: MyString + body: MyText + lang: MyString diff --git a/test/fixtures/activity_objects.yml b/test/fixtures/activity_objects.yml new file mode 100644 index 0000000..6f47c66 --- /dev/null +++ b/test/fixtures/activity_objects.yml @@ -0,0 +1,13 @@ +one: + activity_id: 1 + type: MyString + url_id: MyString + title: MyString + published_at: 2010-07-13 14:37:45 + +two: + activity_id: 1 + type: MyString + url_id: MyString + title: MyString + published_at: 2010-07-13 14:37:45 diff --git a/test/functional/activities_controller_test.rb b/test/functional/activities_controller_test.rb new file mode 100644 index 0000000..8e5b4d0 --- /dev/null +++ b/test/functional/activities_controller_test.rb @@ -0,0 +1,54 @@ +require 'test_helper' + +class ActivitiesControllerTest < ActionController::TestCase + def test_index + get :index + assert_template 'index' + end + + def test_show + get :show, :id => Activity.first + assert_template 'show' + end + + def test_new + get :new + assert_template 'new' + end + + def test_create_invalid + Activity.any_instance.stubs(:valid?).returns(false) + post :create + assert_template 'new' + end + + def test_create_valid + Activity.any_instance.stubs(:valid?).returns(true) + post :create + assert_redirected_to activity_url(assigns(:activity)) + end + + def test_edit + get :edit, :id => Activity.first + assert_template 'edit' + end + + def test_update_invalid + Activity.any_instance.stubs(:valid?).returns(false) + put :update, :id => Activity.first + assert_template 'edit' + end + + def test_update_valid + Activity.any_instance.stubs(:valid?).returns(true) + put :update, :id => Activity.first + assert_redirected_to activity_url(assigns(:activity)) + end + + def test_destroy + activity = Activity.first + delete :destroy, :id => activity + assert_redirected_to activities_url + assert !Activity.exists?(activity.id) + end +end diff --git a/test/unit/activity_object_test.rb b/test/unit/activity_object_test.rb new file mode 100644 index 0000000..385fcfe --- /dev/null +++ b/test/unit/activity_object_test.rb @@ -0,0 +1,7 @@ +require 'test_helper' + +class ActivityObjectTest < ActiveSupport::TestCase + def test_should_be_valid + assert ActivityObject.new.valid? + end +end diff --git a/test/unit/activity_test.rb b/test/unit/activity_test.rb new file mode 100644 index 0000000..56c6e2d --- /dev/null +++ b/test/unit/activity_test.rb @@ -0,0 +1,7 @@ +require 'test_helper' + +class ActivityTest < ActiveSupport::TestCase + def test_should_be_valid + assert Activity.new.valid? + end +end
webcracy/activity_streams-workshop
b69d5287c648f524ae454a13362b0af30f6c231d
enabled authentication through aidentiti
diff --git a/app/controllers/oauth_consumers_controller.rb b/app/controllers/oauth_consumers_controller.rb index 2bea80d..39358a7 100644 --- a/app/controllers/oauth_consumers_controller.rb +++ b/app/controllers/oauth_consumers_controller.rb @@ -1,19 +1,82 @@ require 'oauth/controllers/consumer_controller' class OauthConsumersController < ApplicationController include Oauth::Controllers::ConsumerController + before_filter :load_consumer + skip_before_filter :login_required + def index - @consumer_tokens=ConsumerToken.all :conditions=>{:user_id=>current_user.id} - @services=OAUTH_CREDENTIALS.keys-@consumer_tokens.collect{|c| c.class.service_name} + if logged_in? + @consumer_tokens=ConsumerToken.all :conditions=>{:user_id=>current_user.id} + @services=OAUTH_CREDENTIALS.keys-@consumer_tokens.collect{|c| c.class.service_name} + end + end + + # This callback method is heavily modified from the plugin's original to allow session and user creation + # from an Aidentiti Oauth Authorization + def callback + @request_token_secret = (session[:yammer_token] ? session[:yammer_token][:request_secret] : session[params[:oauth_token]]) + if @request_token_secret + if params[:id] == 'aidentiti' + # Create an Aidentiti Oauth Consumer to grab the user's credential + @consumer = AidentitiToken.consumer + access_token = get_access_token(@consumer, params[:oauth_token], @request_token_secret, params[:oauth_verifier]) + # Save the Consumer's token and use it to create the client + @token = AidentitiToken.create(:token => access_token.token, :secret => access_token.secret) + aidentiti_client = Aidentiti::Base.new(@token.client) + # Make the call to Aidentiti + user_profile = aidentiti_client.grab_credentials.user + # Do we need to create this user, or just load it? + user = User.find_or_create_by_email(:email => user_profile.email, :login => user_profile.login) + user.password = user.password_confirmation = user.login.reverse + user.save + # Create a new session + reset_session + self.current_user = user + new_cookie_flag = true + handle_remember_cookie! new_cookie_flag + # Keep the Aidentiti Oauth Token table clean + old_consumer = AidentitiToken.find_by_user_id(user.id).delete if AidentitiToken.find_by_user_id(user.id) + # Wrap up by assigning the + @token.user_id = user.id + # elsif params[:id] == 'yammer' + # here you could use program specific behaviour for other oauth providers + end + if @token.save + flash[:notice] = "#{params[:id].humanize} was successfully connected to your account" + go_back + else + flash[:error] = "An error happened, please try connecting again" + redirect_to oauth_consumer_url(params[:id]) + end + end + end protected # Change this to decide where you want to redirect user to after callback is finished. # params[:id] holds the service name so you could use this to redirect to various parts # of your application depending on what service you're connecting to. def go_back redirect_to root_url end + def load_consumer + consumer_key=params[:id].to_sym + throw RecordNotFound unless OAUTH_CREDENTIALS.include?(consumer_key) + @consumer="#{consumer_key.to_s.camelcase}Token".constantize + if current_user + @[email protected]_by_user_id current_user.id + end + end + + def get_access_token(consumer, token,secret,oauth_verifier) + request_token=OAuth::RequestToken.new consumer,token,secret + options={} + options[:oauth_verifier]=oauth_verifier if oauth_verifier + access_token=request_token.get_access_token options + access_token + end + end diff --git a/app/models/aidentiti_token.rb b/app/models/aidentiti_token.rb new file mode 100644 index 0000000..ff4d434 --- /dev/null +++ b/app/models/aidentiti_token.rb @@ -0,0 +1,17 @@ +require 'aidentiti' +class AidentitiToken < ConsumerToken + + def self.consumer + @consumer||=OAuth::Consumer.new credentials[:key],credentials[:secret],credentials[:options] + end + + def client + unless @client + aidentiti_oauth = Aidentiti::OAuth.new AidentitiToken.consumer.key,AidentitiToken.consumer.secret,AidentitiToken.consumer.options + aidentiti_oauth.authorize_from_access token,secret + @client=Aidentiti::Base.new(aidentiti_oauth) + end + @client + end + +end \ No newline at end of file diff --git a/app/views/oauth_consumers/index.html.haml b/app/views/oauth_consumers/index.html.haml index 2e8d0ef..1e32c35 100644 --- a/app/views/oauth_consumers/index.html.haml +++ b/app/views/oauth_consumers/index.html.haml @@ -1,18 +1,28 @@ %h1 Services --if @consumer_tokens.empty? - %p - You are currently not connected to any external services. --else - %p You are connected to the following services: - %ul - -@consumer_tokens.each do |token| - %li - =link_to token.class.service_name.to_s.humanize, oauth_consumer_path(token.class.service_name) --unless @services.empty? - %h3 You can connect to the following services: - %ul - [email protected] do |service| - %li - =link_to service.to_s.humanize,oauth_consumer_path(service) + +-if @consumer_tokens and @services + -if @consumer_tokens.empty? + %p + You are currently not connected to any external services. + -else + %p You are connected to the following services: + %ul + -@consumer_tokens.each do |token| + %li + =link_to token.class.service_name.to_s.humanize, oauth_consumer_path(token.class.service_name) + -if current_user + %br + %span= "You are authenticated as #{current_user.email}" + + -unless @services.empty? + %h3 You can connect to the following services: + %ul + [email protected] do |service| + %li + =link_to service.to_s.humanize,oauth_consumer_path(service) +-else + %h3 Authenticate with Aidentiti + %p + =link_to "Authenticate with Aidentiti", '/oauth_consumers/aidentiti' \ No newline at end of file diff --git a/lib/aidentiti.rb b/lib/aidentiti.rb new file mode 100644 index 0000000..1e8c88c --- /dev/null +++ b/lib/aidentiti.rb @@ -0,0 +1,28 @@ +require 'forwardable' +require 'mash' +require 'httparty' + +module Aidentiti + class AidentitiError < StandardError + attr_reader :data + + def initialize(data) + @data = data + super + end + end + + class RateLimitExceeded < AidentitiError; end + class Unauthorized < AidentitiError; end + class General < AidentitiError; end + + class Unavailable < StandardError; end + class InformAidentiti < StandardError; end + class NotFound < StandardError; end +end + +directory = File.expand_path(File.dirname(__FILE__)) + +require File.join(directory, 'aidentiti', 'oauth') +require File.join(directory, 'aidentiti', 'request') +require File.join(directory, 'aidentiti', 'base') \ No newline at end of file diff --git a/lib/aidentiti/base.rb b/lib/aidentiti/base.rb new file mode 100644 index 0000000..5751974 --- /dev/null +++ b/lib/aidentiti/base.rb @@ -0,0 +1,198 @@ +module Aidentiti + class Base + extend Forwardable + + def_delegators :client, :get, :post + + attr_reader :client + + def initialize(client) + @client = client + end + + # Aidentiti + def grab_credentials + perform_get('/api/grab_credentials.json') + end + + # Aidentiti + def grab_relationships + perform_get('/api/grab_relationships.json') + end + + def vocabulary(id) + perform_get('/api/vocabulary.json', :query => {:id => id}) + end + + def vocabularies + perform_get('/api/vocabularies.json') + end + + # Aidentiti + def grab_hierarchy + perform_get('/api/grab_hierarchy.json') + end + + # Aidentiti + def post_activity(activity) + perform_post('/api/activity.json', {:body => activity.to_json,:headers => {'Content-Type' => 'application/json', 'Accept' => 'application/json'}}) + end + + # Aidentiti + def test_activity(activity) + perform_post('/api/activity_test.json', {:body => activity.to_json,:headers => {'Content-Type' => 'application/json', 'Accept' => 'application/json'}}) + end + + # Options: since_id, max_id, count, page, since + def friends_timeline(query={}) + perform_get('/statuses/friends_timeline.json', :query => query) + end + + # Options: id, user_id, screen_name, since_id, max_id, page, since + def user_timeline(query={}) + perform_get('/statuses/user_timeline.json', :query => query) + end + + def status(id) + perform_get("/statuses/show/#{id}.json") + end + + # Options: in_reply_to_status_id + def update(status, query={}) + perform_post("/statuses/update.json", :body => {:status => status}.merge(query)) + end + + # Options: since_id, max_id, since, page + def replies(query={}) + perform_get('/statuses/replies.json', :query => query) + end + + def status_destroy(id) + perform_post("/statuses/destroy/#{id}.json") + end + + # Options: id, user_id, screen_name, page + def friends(query={}) + perform_get('/statuses/friends.json', :query => query) + end + + # Options: id, user_id, screen_name, page + def followers(query={}) + perform_get('/statuses/followers.json', :query => query) + end + + def user(id, query={}) + perform_get("/users/show/#{id}.json", :query => query) + end + + # Options: since, since_id, page + def direct_messages(query={}) + perform_get("/direct_messages.json", :query => query) + end + + # Options: since, since_id, page + def direct_messages_sent(query={}) + perform_get("/direct_messages/sent.json", :query => query) + end + + def direct_message_create(user, text) + perform_post("/direct_messages/new.json", :body => {:user => user, :text => text}) + end + + def direct_message_destroy(id) + perform_post("/direct_messages/destroy/#{id}.json") + end + + def friendship_create(id, follow=false) + body = {} + body.merge!(:follow => follow) if follow + perform_post("/friendships/create/#{id}.json", :body => body) + end + + def friendship_destroy(id) + perform_post("/friendships/destroy/#{id}.json") + end + + def friendship_exists?(a, b) + perform_get("/friendships/exists.json", :query => {:user_a => a, :user_b => b}) + end + + # Options: id, user_id, screen_name + def friend_ids(query={}) + perform_get("/friends/ids.json", :query => query, :mash => false) + end + + # Options: id, user_id, screen_name + def follower_ids(query={}) + perform_get("/followers/ids.json", :query => query, :mash => false) + end + + def verify_credentials + perform_get("/account/verify_credentials.json") + end + + # Device must be sms, im or none + def update_delivery_device(device) + perform_post('/account/update_delivery_device.json', :body => {:device => device}) + end + + # One or more of the following must be present: + # profile_background_color, profile_text_color, profile_link_color, + # profile_sidebar_fill_color, profile_sidebar_border_color + def update_profile_colors(colors={}) + perform_post('/account/update_profile_colors.json', :body => colors) + end + + def rate_limit_status + perform_get('/account/rate_limit_status.json') + end + + # One or more of the following must be present: + # name, email, url, location, description + def update_profile(body={}) + perform_post('/account/update_profile.json', :body => body) + end + + # Options: id, page + def favorites(query={}) + perform_get('/favorites.json', :query => query) + end + + def favorite_create(id) + perform_post("/favorites/create/#{id}.json") + end + + def favorite_destroy(id) + perform_post("/favorites/destroy/#{id}.json") + end + + def enable_notifications(id) + perform_post("/notifications/follow/#{id}.json") + end + + def disable_notifications(id) + perform_post("/notifications/leave/#{id}.json") + end + + def block(id) + perform_post("/blocks/create/#{id}.json") + end + + def unblock(id) + perform_post("/blocks/destroy/#{id}.json") + end + + def help + perform_get('/help/test.json') + end + + private + def perform_get(path, options={}) + Aidentiti::Request.get(self, path, options) + end + + def perform_post(path, options={}) + Aidentiti::Request.post(self, path, options) + end + end +end \ No newline at end of file diff --git a/lib/aidentiti/oauth.rb b/lib/aidentiti/oauth.rb new file mode 100644 index 0000000..cd9f538 --- /dev/null +++ b/lib/aidentiti/oauth.rb @@ -0,0 +1,56 @@ +module Aidentiti + class OAuth + extend Forwardable + def_delegators :access_token, :get, :post + + attr_reader :ctoken, :csecret, :consumer_options + + # Options + # :sign_in => true to just sign in with twitter instead of doing oauth authorization + # (http://apiwiki.twitter.com/Sign-in-with-Twitter) + def initialize(ctoken, csecret, options={}) + @ctoken, @csecret, @consumer_options = ctoken, csecret, options + + if options[:sign_in] + @consumer_options[:authorize_path] = '/oauth/authenticate' + end + end + + def consumer + @consumer ||= ::OAuth::Consumer.new(@ctoken, @csecret, consumer_options) + end + + def set_callback_url(url) + clear_request_token + request_token(:oauth_callback => url) + end + + # Note: If using oauth with a web app, be sure to provide :oauth_callback. + # Options: + # :oauth_callback => String, url that twitter should redirect to + def request_token(options={}) + @request_token ||= consumer.get_request_token(options) + end + + # For web apps use params[:oauth_verifier], for desktop apps, + # use the verifier is the pin that twitter gives users. + def authorize_from_request(rtoken, rsecret, verifier_or_pin) + request_token = ::OAuth::RequestToken.new(consumer, rtoken, rsecret) + access_token = request_token.get_access_token(:oauth_verifier => verifier_or_pin) + @atoken, @asecret = access_token.token, access_token.secret + end + + def access_token + @access_token ||= ::OAuth::AccessToken.new(consumer, @atoken, @asecret) + end + + def authorize_from_access(atoken, asecret) + @atoken, @asecret = atoken, asecret + end + + private + def clear_request_token + @request_token = nil + end + end +end \ No newline at end of file diff --git a/lib/aidentiti/request.rb b/lib/aidentiti/request.rb new file mode 100644 index 0000000..8ca4e36 --- /dev/null +++ b/lib/aidentiti/request.rb @@ -0,0 +1,102 @@ +module Aidentiti + class Request + extend Forwardable + + def self.get(client, path, options={}) + new(client, :get, path, options).perform + end + + def self.post(client, path, options={}) + new(client, :post, path, options).perform + end + + attr_reader :client, :method, :path, :options + + def_delegators :client, :get, :post + + def initialize(client, method, path, options={}) + @client, @method, @path, @options = client, method, path, {:mash => true}.merge(options) + end + + def uri + @uri ||= begin + uri = URI.parse(path) + + if options[:query] && options[:query] != {} + uri.query = to_query(options[:query]) + end + + uri.to_s + end + end + + def perform + make_friendly(send("perform_#{method}")) + end + + private + def perform_get + send(:get, uri, options[:headers]) + end + + def perform_post + send(:post, uri, options[:body], options[:headers]) + end + + def make_friendly(response) + raise_errors(response) + data = parse(response) + options[:mash] ? mash(data) : data + end + + def raise_errors(response) + case response.code.to_i + when 400 + data = parse(response) + raise RateLimitExceeded.new(data), "(#{response.code}): #{response.message} - #{data['error'] if data}" + when 401 + data = parse(response) + raise Unauthorized.new(data), "(#{response.code}): #{response.message} - #{data['error'] if data}" + when 403 + data = parse(response) + raise General.new(data), "(#{response.code}): #{response.message} - #{data['error'] if data}" + when 404 + raise NotFound, "(#{response.code}): #{response.message}" + when 500 + raise InformAidentiti, "Aidentiti had an internal error. Please let them know. (#{response.code}): #{response.message}" + when 502..503 + raise Unavailable, "(#{response.code}): #{response.message}" + end + end + + def parse(response) + Crack::JSON.parse(response.body) + end + + def mash(obj) + if obj.is_a?(Array) + obj.map { |item| make_mash_with_consistent_hash(item) } + elsif obj.is_a?(Hash) + make_mash_with_consistent_hash(obj) + else + obj + end + end + + # Lame workaround for the fact that mash doesn't hash correctly + def make_mash_with_consistent_hash(obj) + m = Mash.new(obj) + def m.hash + inspect.hash + end + return m + end + + def to_query(options) + options.inject([]) do |collection, opt| + collection << "#{opt[0]}=#{opt[1]}" + collection + end * '&' + end + end +end \ No newline at end of file
webcracy/activity_streams-workshop
78fa4bdec7b9ace83d68b094ff58fae971419b3b
enabled oauth
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 6635a3f..f4dcf38 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,10 +1,11 @@ # Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base + include AuthenticatedSystem helper :all # include all helpers, all the time protect_from_forgery # See ActionController::RequestForgeryProtection for details - + # Scrub sensitive parameters from your log # filter_parameter_logging :password end diff --git a/config/routes.rb b/config/routes.rb index 347bae6..42b9225 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,53 +1,56 @@ ActionController::Routing::Routes.draw do |map| + map.resources :oauth_consumers,:member=>{:callback=>:get} + map.resources :users + map.resource :session + map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.login '/login', :controller => 'sessions', :action => 'new' map.register '/register', :controller => 'users', :action => 'create' map.signup '/signup', :controller => 'users', :action => 'new' - map.resources :users - - map.resource :session + + map.root :controller => 'oauth_consumers' # 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 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/schema.rb b/db/schema.rb new file mode 100644 index 0000000..1e987e4 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,39 @@ +# 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 => 20100713115031) do + + create_table "consumer_tokens", :force => true do |t| + t.integer "user_id" + t.string "type", :limit => 30 + t.string "token", :limit => 1024 + t.string "secret" + t.datetime "created_at" + t.datetime "updated_at" + end + + add_index "consumer_tokens", ["token"], :name => "index_consumer_tokens_on_token", :unique => true + + create_table "users", :force => true do |t| + t.string "login", :limit => 40 + t.string "name", :limit => 100, :default => "" + t.string "email", :limit => 100 + t.string "crypted_password", :limit => 40 + t.string "salt", :limit => 40 + t.datetime "created_at" + t.datetime "updated_at" + t.string "remember_token", :limit => 40 + t.datetime "remember_token_expires_at" + end + + add_index "users", ["login"], :name => "index_users_on_login", :unique => true + +end diff --git a/log/development.log b/log/development.log deleted file mode 100644 index e69de29..0000000 diff --git a/log/production.log b/log/production.log deleted file mode 100644 index e69de29..0000000 diff --git a/log/server.log b/log/server.log deleted file mode 100644 index e69de29..0000000 diff --git a/log/test.log b/log/test.log deleted file mode 100644 index e69de29..0000000
webcracy/activity_streams-workshop
02298e777c4eac6b3e3f0e72ae7de30a50f0e803
added oauth_consumers and aidentiti oauth credentials
diff --git a/.gems b/.gems new file mode 100644 index 0000000..a20bca5 --- /dev/null +++ b/.gems @@ -0,0 +1,3 @@ +oauth +oauth-plugin +haml \ No newline at end of file diff --git a/app/controllers/oauth_consumers_controller.rb b/app/controllers/oauth_consumers_controller.rb new file mode 100644 index 0000000..2bea80d --- /dev/null +++ b/app/controllers/oauth_consumers_controller.rb @@ -0,0 +1,19 @@ +require 'oauth/controllers/consumer_controller' +class OauthConsumersController < ApplicationController + include Oauth::Controllers::ConsumerController + + def index + @consumer_tokens=ConsumerToken.all :conditions=>{:user_id=>current_user.id} + @services=OAUTH_CREDENTIALS.keys-@consumer_tokens.collect{|c| c.class.service_name} + end + + protected + + # Change this to decide where you want to redirect user to after callback is finished. + # params[:id] holds the service name so you could use this to redirect to various parts + # of your application depending on what service you're connecting to. + def go_back + redirect_to root_url + end + +end diff --git a/app/models/consumer_token.rb b/app/models/consumer_token.rb new file mode 100644 index 0000000..224d6ec --- /dev/null +++ b/app/models/consumer_token.rb @@ -0,0 +1,5 @@ +require 'oauth/models/consumers/token' +class ConsumerToken < ActiveRecord::Base + include Oauth::Models::Consumers::Token + +end \ No newline at end of file diff --git a/app/views/oauth_consumers/index.html.haml b/app/views/oauth_consumers/index.html.haml new file mode 100644 index 0000000..2e8d0ef --- /dev/null +++ b/app/views/oauth_consumers/index.html.haml @@ -0,0 +1,18 @@ +%h1 Services + +-if @consumer_tokens.empty? + %p + You are currently not connected to any external services. +-else + %p You are connected to the following services: + %ul + -@consumer_tokens.each do |token| + %li + =link_to token.class.service_name.to_s.humanize, oauth_consumer_path(token.class.service_name) + +-unless @services.empty? + %h3 You can connect to the following services: + %ul + [email protected] do |service| + %li + =link_to service.to_s.humanize,oauth_consumer_path(service) diff --git a/app/views/oauth_consumers/show.html.haml b/app/views/oauth_consumers/show.html.haml new file mode 100644 index 0000000..e7358b0 --- /dev/null +++ b/app/views/oauth_consumers/show.html.haml @@ -0,0 +1,8 @@ +%h1 + You are already Connected to + =params[:id].humanize +-form_tag oauth_consumer_path(params[:id]),:method=>:delete do + =submit_tag "Disconnect" + or + =submit_tag "Reconnect" + if you experienced a problem. \ No newline at end of file diff --git a/config/environment.rb b/config/environment.rb index c07d230..e62767f 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,43 +1,44 @@ # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.8' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" + config.gem 'haml' config.gem 'oauth' config.gem 'oauth-plugin' # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'UTC' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de end \ No newline at end of file diff --git a/config/initializers/oauth_consumers.rb b/config/initializers/oauth_consumers.rb new file mode 100644 index 0000000..d481a55 --- /dev/null +++ b/config/initializers/oauth_consumers.rb @@ -0,0 +1,49 @@ +# edit this file to contain credentials for the OAuth services you support. +# each entry needs a corresponding token model. +# +# eg. :twitter => TwitterToken, :hour_feed => HourFeedToken etc. +# +OAUTH_CREDENTIALS={ + :aidentiti=>{ + :key=>"qciv8b7LsZHxXTrIj9KlQ", + :secret=>"XTbIpD6mXzMybFGZHkBKMjzQGYzh2uknGWjYp9Qhs8", + :options=>{ + :site=>"http://aidentiti.heroku.com" + } + }, +# :google=>{ +# :key=>"", +# :secret=>"", +# :scope=>"" # see http://code.google.com/apis/gdata/faq.html#AuthScopes +# }, +# :agree2=>{ +# :key=>"", +# :secret=>"" +# }, +# :fireeagle=>{ +# :key=>"", +# :secret=>"" +# }, +# :hour_feed=>{ +# :key=>"", +# :secret=>"", +# :options=>{ # OAuth::Consumer options +# :site=>"http://hourfeed.com" # Remember to add a site for a generic OAuth site +# } +# }, +# :nu_bux=>{ +# :key=>"", +# :secret=>"", +# :super_class=>"OpenTransactToken", # if a OAuth service follows a particular standard +# # with a token implementation you can set the superclass +# # to use +# :options=>{ # OAuth::Consumer options +# :site=>"http://nubux.heroku.com" +# } +# } +} +# +OAUTH_CREDENTIALS={ +} unless defined? OAUTH_CREDENTIALS + +load 'oauth/models/consumers/service_loader.rb' \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 24b78eb..347bae6 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,51 +1,53 @@ ActionController::Routing::Routes.draw do |map| + map.resources :oauth_consumers,:member=>{:callback=>:get} + map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.login '/login', :controller => 'sessions', :action => 'new' map.register '/register', :controller => 'users', :action => 'create' map.signup '/signup', :controller => 'users', :action => 'new' map.resources :users map.resource :session # 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 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/20100713115031_create_oauth_consumer_tokens.rb b/db/migrate/20100713115031_create_oauth_consumer_tokens.rb new file mode 100644 index 0000000..198f924 --- /dev/null +++ b/db/migrate/20100713115031_create_oauth_consumer_tokens.rb @@ -0,0 +1,20 @@ +class CreateOauthConsumerTokens < ActiveRecord::Migration + def self.up + + create_table :consumer_tokens do |t| + t.integer :user_id + t.string :type, :limit => 30 + t.string :token, :limit => 1024 # This has to be huge because of Yahoo's excessively large tokens + t.string :secret + t.timestamps + end + + add_index :consumer_tokens, :token, :unique + + end + + def self.down + drop_table :consumer_tokens + end + +end
brunsky/WS171-packages-apps-Camera
52ae3b802365592277c69b45f3e36b42fe59d95c
Let the direction of MovieView be landscape always.
diff --git a/src/com/android/camera/MovieView.java b/src/com/android/camera/MovieView.java index b88529f..244acc6 100644 --- a/src/com/android/camera/MovieView.java +++ b/src/com/android/camera/MovieView.java @@ -1,262 +1,265 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.pm.ActivityInfo; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.provider.MediaStore.Video; import android.view.View; import android.widget.MediaController; import android.widget.VideoView; public class MovieView extends Activity implements MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener { private static final String TAG = "MovieView"; // Copied from MediaPlaybackService in the Music Player app. Should be public, but isn't. private static final String SERVICECMD = "com.android.music.musicservicecommand"; private static final String CMDNAME = "command"; private static final String CMDPAUSE = "pause"; private VideoView mVideoView; private View mProgressView; private boolean mFinishOnCompletion; private Uri mUri; // State maintained for proper onPause/OnResume behaviour. private int mPositionWhenPaused = -1; private boolean mWasPlayingWhenPaused = false; public MovieView() { } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.movie_view); mVideoView = (VideoView) findViewById(R.id.surface_view); mProgressView = findViewById(R.id.progress_indicator); Intent intent = getIntent(); - if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { - int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, - ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); - if (orientation != getRequestedOrientation()) { - setRequestedOrientation(orientation); - } - } + //Gill --modify 20100726 --start + //if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { + // int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, + // ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); + // if (orientation != getRequestedOrientation()) { + // setRequestedOrientation(orientation); + // } + //} + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + //Gill --modify 20100726 --end mFinishOnCompletion = intent.getBooleanExtra(MediaStore.EXTRA_FINISH_ON_COMPLETION, true); mUri = intent.getData(); // For streams that we expect to be slow to start up, show a // progress spinner until playback starts. String scheme = mUri.getScheme(); if ("http".equalsIgnoreCase(scheme) || "rtsp".equalsIgnoreCase(scheme)) { mHandler.postDelayed(mPlayingChecker, 250); } else { mProgressView.setVisibility(View.GONE); } mVideoView.setOnErrorListener(this); mVideoView.setOnCompletionListener(this); mVideoView.setVideoURI(mUri); mVideoView.setMediaController(new MediaController(this)); mVideoView.requestFocus(); // make the video view handle keys for seeking and pausing Intent i = new Intent(SERVICECMD); i.putExtra(CMDNAME, CMDPAUSE); sendBroadcast(i); { final Integer bookmark = getBookmark(); if (bookmark != null) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.resume_playing_title); builder.setMessage(String.format( getString(R.string.resume_playing_message), MenuHelper.formatDuration(this, bookmark))); builder.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { finish(); }}); builder.setPositiveButton(R.string.resume_playing_resume, new OnClickListener(){ public void onClick(DialogInterface dialog, int which) { mVideoView.seekTo(bookmark); mVideoView.start(); }}); builder.setNegativeButton(R.string.resume_playing_restart, new OnClickListener(){ public void onClick(DialogInterface dialog, int which) { mVideoView.start(); }}); builder.show(); } else { mVideoView.start(); } } } /* @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); } */ private static boolean uriSupportsBookmarks(Uri uri) { String scheme = uri.getScheme(); String authority = uri.getAuthority(); return ("content".equalsIgnoreCase(scheme) && MediaStore.AUTHORITY.equalsIgnoreCase(authority)); } private Integer getBookmark() { if (!uriSupportsBookmarks(mUri)) { return null; } String[] projection = new String[]{Video.VideoColumns.DURATION, Video.VideoColumns.BOOKMARK}; try { Cursor cursor = getContentResolver().query(mUri, projection, null, null, null); if (cursor != null) { try { if ( cursor.moveToFirst() ) { int duration = getCursorInteger(cursor, 0); int bookmark = getCursorInteger(cursor, 1); final int ONE_MINUTE = 60 * 1000; final int TWO_MINUTES = 2 * ONE_MINUTE; final int FIVE_MINUTES = 5 * ONE_MINUTE; if ((bookmark < TWO_MINUTES) || (duration < FIVE_MINUTES) || (bookmark > (duration - ONE_MINUTE))) { return null; } return new Integer(bookmark); } } finally { cursor.close(); } } } catch (SQLiteException e) { // ignore } return null; } private int getCursorInteger(Cursor cursor, int index) { try { return cursor.getInt(index); } catch (SQLiteException e) { return 0; } catch (NumberFormatException e) { return 0; } } private void setBookmark(int bookmark) { if (!uriSupportsBookmarks(mUri)) { return; } ContentValues values = new ContentValues(); values.put(Video.VideoColumns.BOOKMARK, Integer.toString(bookmark)); try { getContentResolver().update(mUri, values, null, null); } catch (SecurityException ex) { // Ignore, can happen if we try to set the bookmark on a read-only resource // such as a video attached to GMail. } catch (SQLiteException e) { // ignore. can happen if the content doesn't support a bookmark column. } catch (UnsupportedOperationException e) { // ignore. can happen if the external volume is already detached.getIntExtragetIntExtra } } @Override public void onPause() { mHandler.removeCallbacksAndMessages(null); setBookmark(mVideoView.getCurrentPosition()); mPositionWhenPaused = mVideoView.getCurrentPosition(); mWasPlayingWhenPaused = mVideoView.isPlaying(); mVideoView.stopPlayback(); super.onPause(); } @Override public void onResume() { if (mPositionWhenPaused >= 0) { mVideoView.setVideoURI(mUri); mVideoView.seekTo(mPositionWhenPaused); if (mWasPlayingWhenPaused) { mVideoView.start(); } } super.onResume(); } Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { } }; Runnable mPlayingChecker = new Runnable() { public void run() { if (mVideoView.isPlaying()) { mProgressView.setVisibility(View.GONE); } else { mHandler.postDelayed(mPlayingChecker, 250); } } }; public boolean onError(MediaPlayer player, int arg1, int arg2) { mHandler.removeCallbacksAndMessages(null); mProgressView.setVisibility(View.GONE); return false; } public void onCompletion(MediaPlayer mp) { if (mFinishOnCompletion) { finish(); } } }
brunsky/WS171-packages-apps-Camera
0e0094f5e55059eb3147d819b47cb50c15c39c21
fix orientation
diff --git a/src/com/android/camera/MovieView.java b/src/com/android/camera/MovieView.java index 80b485e..b88529f 100644 --- a/src/com/android/camera/MovieView.java +++ b/src/com/android/camera/MovieView.java @@ -1,263 +1,262 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.pm.ActivityInfo; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.provider.MediaStore.Video; import android.view.View; import android.widget.MediaController; import android.widget.VideoView; public class MovieView extends Activity implements MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener { private static final String TAG = "MovieView"; // Copied from MediaPlaybackService in the Music Player app. Should be public, but isn't. private static final String SERVICECMD = "com.android.music.musicservicecommand"; private static final String CMDNAME = "command"; private static final String CMDPAUSE = "pause"; private VideoView mVideoView; private View mProgressView; private boolean mFinishOnCompletion; private Uri mUri; // State maintained for proper onPause/OnResume behaviour. private int mPositionWhenPaused = -1; private boolean mWasPlayingWhenPaused = false; public MovieView() { } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.movie_view); mVideoView = (VideoView) findViewById(R.id.surface_view); mProgressView = findViewById(R.id.progress_indicator); Intent intent = getIntent(); - /* + if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); if (orientation != getRequestedOrientation()) { setRequestedOrientation(orientation); } } - */ - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); + mFinishOnCompletion = intent.getBooleanExtra(MediaStore.EXTRA_FINISH_ON_COMPLETION, true); mUri = intent.getData(); // For streams that we expect to be slow to start up, show a // progress spinner until playback starts. String scheme = mUri.getScheme(); if ("http".equalsIgnoreCase(scheme) || "rtsp".equalsIgnoreCase(scheme)) { mHandler.postDelayed(mPlayingChecker, 250); } else { mProgressView.setVisibility(View.GONE); } mVideoView.setOnErrorListener(this); mVideoView.setOnCompletionListener(this); mVideoView.setVideoURI(mUri); mVideoView.setMediaController(new MediaController(this)); mVideoView.requestFocus(); // make the video view handle keys for seeking and pausing Intent i = new Intent(SERVICECMD); i.putExtra(CMDNAME, CMDPAUSE); sendBroadcast(i); { final Integer bookmark = getBookmark(); if (bookmark != null) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.resume_playing_title); builder.setMessage(String.format( getString(R.string.resume_playing_message), MenuHelper.formatDuration(this, bookmark))); builder.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { finish(); }}); builder.setPositiveButton(R.string.resume_playing_resume, new OnClickListener(){ public void onClick(DialogInterface dialog, int which) { mVideoView.seekTo(bookmark); mVideoView.start(); }}); builder.setNegativeButton(R.string.resume_playing_restart, new OnClickListener(){ public void onClick(DialogInterface dialog, int which) { mVideoView.start(); }}); builder.show(); } else { mVideoView.start(); } } } /* @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); } */ private static boolean uriSupportsBookmarks(Uri uri) { String scheme = uri.getScheme(); String authority = uri.getAuthority(); return ("content".equalsIgnoreCase(scheme) && MediaStore.AUTHORITY.equalsIgnoreCase(authority)); } private Integer getBookmark() { if (!uriSupportsBookmarks(mUri)) { return null; } String[] projection = new String[]{Video.VideoColumns.DURATION, Video.VideoColumns.BOOKMARK}; try { Cursor cursor = getContentResolver().query(mUri, projection, null, null, null); if (cursor != null) { try { if ( cursor.moveToFirst() ) { int duration = getCursorInteger(cursor, 0); int bookmark = getCursorInteger(cursor, 1); final int ONE_MINUTE = 60 * 1000; final int TWO_MINUTES = 2 * ONE_MINUTE; final int FIVE_MINUTES = 5 * ONE_MINUTE; if ((bookmark < TWO_MINUTES) || (duration < FIVE_MINUTES) || (bookmark > (duration - ONE_MINUTE))) { return null; } return new Integer(bookmark); } } finally { cursor.close(); } } } catch (SQLiteException e) { // ignore } return null; } private int getCursorInteger(Cursor cursor, int index) { try { return cursor.getInt(index); } catch (SQLiteException e) { return 0; } catch (NumberFormatException e) { return 0; } } private void setBookmark(int bookmark) { if (!uriSupportsBookmarks(mUri)) { return; } ContentValues values = new ContentValues(); values.put(Video.VideoColumns.BOOKMARK, Integer.toString(bookmark)); try { getContentResolver().update(mUri, values, null, null); } catch (SecurityException ex) { // Ignore, can happen if we try to set the bookmark on a read-only resource // such as a video attached to GMail. } catch (SQLiteException e) { // ignore. can happen if the content doesn't support a bookmark column. } catch (UnsupportedOperationException e) { // ignore. can happen if the external volume is already detached.getIntExtragetIntExtra } } @Override public void onPause() { mHandler.removeCallbacksAndMessages(null); setBookmark(mVideoView.getCurrentPosition()); mPositionWhenPaused = mVideoView.getCurrentPosition(); mWasPlayingWhenPaused = mVideoView.isPlaying(); mVideoView.stopPlayback(); super.onPause(); } @Override public void onResume() { if (mPositionWhenPaused >= 0) { mVideoView.setVideoURI(mUri); mVideoView.seekTo(mPositionWhenPaused); if (mWasPlayingWhenPaused) { mVideoView.start(); } } super.onResume(); } Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { } }; Runnable mPlayingChecker = new Runnable() { public void run() { if (mVideoView.isPlaying()) { mProgressView.setVisibility(View.GONE); } else { mHandler.postDelayed(mPlayingChecker, 250); } } }; public boolean onError(MediaPlayer player, int arg1, int arg2) { mHandler.removeCallbacksAndMessages(null); mProgressView.setVisibility(View.GONE); return false; } public void onCompletion(MediaPlayer mp) { if (mFinishOnCompletion) { finish(); } } }
brunsky/WS171-packages-apps-Camera
109c1936d6c7b51bc59598d9c4b27ab4bebf5725
ws171v2
diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 534f669..7e4b524 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,230 +1,220 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.camera" android:sharedUserId="android.media"> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.SET_WALLPAPER" /> <!-- Needed by the ZoomRingController to set the bit saying we've already shown the tutorial toast. --> <uses-permission android:name="android.permission.WRITE_SETTINGS"/> - <application android:icon="@drawable/ic_launcher_camera" + <application android:icon="@drawable/ic_launcher_gallery" android:label="@string/camera_label" android:taskAffinity=""> <service android:name="UploadService" android:process="android.process.media" /> <receiver android:name="CameraButtonIntentReceiver"> <intent-filter> <action android:name="android.intent.action.CAMERA_BUTTON"/> </intent-filter> </receiver> <activity android:name="Camera" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" android:screenOrientation="landscape" android:clearTaskOnLaunch="true" android:taskAffinity="android.task.camera"> - <intent-filter> - <action android:name="android.intent.action.MAIN" /> - <category android:name="android.intent.category.DEFAULT" /> - <category android:name="android.intent.category.LAUNCHER" /> - </intent-filter> <intent-filter> <action android:name="android.media.action.IMAGE_CAPTURE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.media.action.STILL_IMAGE_CAMERA" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="VideoCamera" android:label="@string/video_camera_label" android:configChanges="orientation|keyboardHidden" - android:icon="@drawable/ic_launcher_video_camera" + android:icon="@drawable/ic_launcher_gallery" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" android:screenOrientation="landscape" android:clearTaskOnLaunch="true" android:taskAffinity="android.task.videocamera"> - <intent-filter> - <action android:name="android.intent.action.MAIN" /> - <category android:name="android.intent.category.DEFAULT" /> - <category android:name="android.intent.category.LAUNCHER" /> - </intent-filter> <intent-filter> <action android:name="android.media.action.VIDEO_CAMERA" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.media.action.VIDEO_CAPTURE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="GalleryPicker" android:label="@string/gallery_picker_label" android:configChanges="orientation|keyboardHidden" android:icon="@drawable/ic_launcher_gallery" android:clearTaskOnLaunch="true" android:taskAffinity="android.task.pictures"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="ImageGallery2" android:label="@string/gallery_label" android:configChanges="orientation|keyboardHidden" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/video" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.GET_CONTENT" /> <category android:name="android.intent.category.OPENABLE" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.GET_CONTENT" /> <category android:name="android.intent.category.OPENABLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> </activity> <activity android:name="CropImage" android:process=":CropImage" android:configChanges="orientation|keyboardHidden" android:label="@string/crop_label"> <intent-filter android:label="@string/crop_label"> <action android:name="com.android.camera.action.CROP" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.ALTERNATIVE" /> <category android:name="android.intent.category.SELECTED_ALTERNATIVE" /> </intent-filter> </activity> <activity android:name="ViewImage" android:label="@string/view_label" android:configChanges="orientation|keyboardHidden"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> </activity> <activity android:name="MovieView" android:label="@string/movieviewlabel" - android:screenOrientation="landscape" + android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="rtsp" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="http" /> <data android:mimeType="video/mp4" /> <data android:mimeType="video/3gp" /> <data android:mimeType="video/3gpp" /> <data android:mimeType="video/3gpp2" /> </intent-filter> </activity> <activity android:name="CameraSettings" android:label="@string/preferences_label"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEVELOPMENT_PREFERENCE" /> </intent-filter> </activity> <activity android:name="GallerySettings" android:label="@string/preferences_label"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEVELOPMENT_PREFERENCE" /> </intent-filter> </activity> <activity android:name="SlideShow" android:label="Raw Image Viewer" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.TEST" /> </intent-filter> </activity> <activity android:name=".Wallpaper" android:label="@string/camera_setas_wallpaper" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.ATTACH_DATA" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name=".PickWallpaper" android:label="@string/camera_pick_wallpaper" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.SET_WALLPAPER" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <receiver android:name="PhotoAppWidgetProvider" android:label="@string/gadget_title"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/appwidget_info" /> </receiver> <!-- We configure a widget by asking to pick a photo, then crop it, and store the config internally --> <activity android:name="PhotoAppWidgetConfigure"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" /> </intent-filter> </activity> <!-- We also allow direct binding where the caller provides a bitmap and appWidgetId to bind. We require the permission because this changes our internal database without user confirmation. --> <activity android:name="PhotoAppWidgetBind" android:exported="true" android:theme="@android:style/Theme.NoDisplay" android:permission="android.permission.BIND_APPWIDGET" /> </application> </manifest> diff --git a/res/values-de/strings.xml b/res/values-de/strings.xml index aebb514..2b2756e 100644 --- a/res/values-de/strings.xml +++ b/res/values-de/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Alle Bilder"</string> <string name="all_videos">"Alle Videos"</string> - <string name="camera_label">"Kamera"</string> + <string name="camera_label">"Galerie"</string> <string name="video_camera_label">"Camcorder"</string> <string name="gallery_picker_label">"Galerie"</string> <string name="gallery_camera_bucket_name">"Kamerabilder"</string> <string name="gallery_camera_videos_bucket_name">"Kameravideos"</string> <string name="switch_to_video_lable">"Zu Video wechseln"</string> <string name="switch_to_camera_lable">"Zu Kamera wechseln"</string> <string name="crop_label">"Bild zuschneiden"</string> <string name="view_label">"Bild anzeigen"</string> - <string name="preferences_label">"Kameraeinstellungen"</string> + <string name="preferences_label">"Einstellungen"</string> <string name="wait">"Bitte warten..."</string> <string name="no_storage">"Legen Sie vor Verwendung der Kamera eine SD-Karte ein."</string> <string name="not_enough_space">"Ihre SD-Karte ist voll."</string> <string name="preparing_sd">"SD-Karte wird vorbereitet..."</string> <string name="wallpaper">"Hintergrund wird eingestellt, bitte warten..."</string> <string name="savingImage">"Bild wird gespeichert..."</string> <string name="runningFaceDetection">"Bitte warten..."</string> <string name="flip_orientation">"Ausrichtung drehen"</string> <string name="settings">"Einstellungen"</string> <string name="view">"Anzeigen"</string> <string name="details">"Details"</string> <string name="rotate">"Drehen"</string> <string name="rotate_left">"Nach links drehen"</string> <string name="rotate_right">"Nach rechts drehen"</string> <string name="slide_show">"Diashow"</string> <string name="capture_picture">"Bild aufnehmen"</string> <string name="capture_video">"Video aufnehmen"</string> <string name="crop_save_text">"Speichern"</string> <string name="crop_discard_text">"Verwerfen"</string> <string name="confirm_delete_title">"Löschen"</string> <string name="confirm_delete_message">"Das Bild wird gelöscht."</string> <string name="confirm_delete_video_message">"Das Video wird gelöscht."</string> <string name="camera_toss">"Löschen"</string> <string name="camera_gallery">"Galerie"</string> <string name="camera_share">"Senden"</string> - <string name="camera_set">"Festlegen als"</string> + <string name="camera_set">"als Hintergrundsbild setzen"</string> <string name="camera_play">"Wiedergeben"</string> <string name="camera_attach">"Anhängen"</string> <string name="camera_cancel">"Abbrechen"</string> <string name="camera_crop">"Zuschneiden"</string> <string name="camera_tossing">"Löschvorgang..."</string> <string name="no_way_to_share_image">"Dieses Bild kann nicht weitergeleitet werden."</string> <string name="no_way_to_share_video">"Dieses Video kann nicht weitergeleitet werden."</string> <string name="video_play">"Wiedergeben"</string> <string name="camera_gallery_photos_text">"Galerie"</string> <string name="camera_pick_wallpaper">"Bilder"</string> <string name="camera_setas_wallpaper">"Hintergrund"</string> <string name="pref_gallery_category">"Allgemeine Einstellungen"</string> <string name="pref_slideshow_category">"Einstellungen für Diashow"</string> <string name="pref_camera_general_settings_category">"Allgemeine Einstellungen"</string> <string name="pref_gallery_size_title">"Anzeigegröße"</string> <string name="pref_gallery_size_summary">"Anzeigegröße für Bilder und Videos auswählen"</string> <string name="pref_gallery_size_dialogtitle">"Bildgröße"</string> <string-array name="pref_gallery_size_choices"> <item>"Groß"</item> <item>"Klein"</item> </string-array> <string name="pref_gallery_sort_title">"Sortierreihenfolge"</string> <string name="pref_gallery_sort_summary">"Sortierreihenfolge für Bilder und Videos auswählen"</string> <string name="pref_gallery_sort_dialogtitle">"Sortierreihenfolge für Bilder"</string> <string-array name="pref_gallery_sort_choices"> <item>"Neue zuerst"</item> <item>"Neue zuletzt"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Diashow-Intervall"</string> <string name="pref_gallery_slideshow_interval_summary">"Auswählen, wie lange jedes Bild in der Diashow angezeigt werden soll"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Diashow-Intervall"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 Sekunden"</item> <item>"3 Sekunden"</item> <item>"4 Sekunden"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Diashow-Übergang"</string> <string name="pref_gallery_slideshow_transition_summary">"Effekt auswählen, der beim Wechsel zum nächsten Bild angewendet wird"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Diashow-Übergang"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ein- und ausblenden"</item> <item>"Einblendung von links - rechts"</item> <item>"Einblendung von oben - unten"</item> <item>"Zufällige Auswahl"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Diashow wiederholen"</string> <string name="pref_gallery_slideshow_repeat_summary">"Diashow mehrmals anzeigen"</string> <string name="pref_gallery_slideshow_shuffle_title">"Bilder mischen"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Bilder in zufälliger Reihenfolge anzeigen"</string> <string name="pref_camera_recordlocation_title">"Aufnahmeort speichern"</string> <string name="pref_camera_recordlocation_summary">"Aufnahmeort in Bilddaten speichern"</string> <string name="pref_camera_videoquality_category">"Videoqualität"</string> <string name="pref_camera_videoquality_title">"Videoqualität auswählen"</string> <string name="pref_camera_videoquality_entry_0">"Niedrig (für MMS-Mitteilungen)"</string> <string name="pref_camera_videoquality_entry_1">"Hoch (für SD-Karte)"</string> <string name="pref_camera_videoquality_dialogtitle">"Videoqualität"</string> <string name="camerasettings">"Einstellungen"</string> <string name="image_gallery_NoImageView_text">"Keine Medien gefunden."</string> <string name="pref_gallery_confirm_delete_title">"Löschvorgang bestätigen"</string> <string name="pref_gallery_confirm_delete_summary">"Bestätigung vor dem Löschen eines Bildes oder Videos anzeigen"</string> <string name="details_panel_title">"Details"</string> <string name="details_file_size">"Dateigröße:"</string> <string name="details_image_resolution">"Auflösung:"</string> <string name="details_duration">"Dauer:"</string> <string name="details_date_taken">"Aufnahmedatum:"</string> <string name="details_frame_rate">"Framerate:"</string> <string name="details_bit_rate">"Bitrate:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbit/s"</string> <string name="details_mbps">"%1$g Mbit/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Bildoptionen"</string> <string name="video_context_menu_header">"Videooptionen"</string> <string name="multiface_crop_help">"Tippen Sie zum Beginnen auf ein Gesicht."</string> <string name="photos_gallery_title">"Galerie"</string> <string name="pick_photos_gallery_title">"Bild auswählen"</string> <string name="videos_gallery_title">"Galerie"</string> <string name="pick_videos_gallery_title">"Video auswählen"</string> <string name="loading_progress_format_string">"noch <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Bild senden via"</string> <string name="setImage">"Bild festlegen als"</string> <string name="sendVideo">"Video weiterleiten via"</string> <string name="movieviewlabel">"Filme"</string> <string name="loading_video">"Video wird geladen..."</string> <string name="spaceIsLow_title">"Geringer Speicherplatz"</string> <string name="spaceIsLow_content">"Auf Ihrer SD-Karte ist nicht mehr genügend Speicherplatz vorhanden. Ändern Sie die Qualitätseinstellung oder löschen Sie Elemente aus der Galerie."</string> <string name="resume_playing_title">"Mit Video fortfahren"</string> <string name="resume_playing_message">"Mit Wiedergabe fortfahren ab %s ?"</string> <string name="resume_playing_resume">"Mit Wiedergabe fortfahren"</string> <string name="resume_playing_restart">"Starten"</string> <string name="gadget_title">"Bildrahmen"</string> <string name="file_info_title">"Dateiinfo:"</string> <string name="video_exceed_mms_limit">"Das aufgenommene Video ist zu groß und kann nicht per MMS gesendet werden. Nehmen Sie einen kürzeren Clip auf."</string> <string name="too_large_to_attach">"Dateianhang zu groß"</string> </resources> diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml index fbb84c8..3bcbcbb 100644 --- a/res/values-es/strings.xml +++ b/res/values-es/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Todas las imágenes"</string> <string name="all_videos">"Todos los vídeos"</string> - <string name="camera_label">"Cámara"</string> + <string name="camera_label">"Galería"</string> <string name="video_camera_label">"Videocámara"</string> <string name="gallery_picker_label">"Galería"</string> <string name="gallery_camera_bucket_name">"Imágenes de cámara"</string> <string name="gallery_camera_videos_bucket_name">"Vídeos de cámara"</string> <string name="switch_to_video_lable">"Cambiar a vídeo"</string> <string name="switch_to_camera_lable">"Cambiar a cámara"</string> <string name="crop_label">"Recortar imagen"</string> <string name="view_label">"Ver imagen"</string> - <string name="preferences_label">"Configuración de cámara"</string> + <string name="preferences_label">"Configuración"</string> <string name="wait">"Por favor, espera..."</string> <string name="no_storage">"Inserta o activa la tarjeta SD para poder utilizar la cámara."</string> <string name="not_enough_space">"La tarjeta SD está llena."</string> <string name="preparing_sd">"Preparando tarjeta SD…"</string> <string name="wallpaper">"Estableciendo fondo de pantalla..."</string> <string name="savingImage">"Guardando imagen..."</string> <string name="runningFaceDetection">"Por favor, espera..."</string> <string name="flip_orientation">"Cambiar orientación"</string> <string name="settings">"Ajustes"</string> <string name="view">"Ver"</string> <string name="details">"Detalles"</string> <string name="rotate">"Girar"</string> <string name="rotate_left">"Girar a la izquierda"</string> <string name="rotate_right">"Girar a la derecha"</string> <string name="slide_show">"Presentación"</string> <string name="capture_picture">"Capturar imagen"</string> <string name="capture_video">"Capturar vídeo"</string> <string name="crop_save_text">"Guardar"</string> <string name="crop_discard_text">"Descartar"</string> <string name="confirm_delete_title">"Suprimir"</string> <string name="confirm_delete_message">"Se eliminará la imagen."</string> <string name="confirm_delete_video_message">"Se eliminará el vídeo."</string> <string name="camera_toss">"Suprimir"</string> <string name="camera_gallery">"Galería"</string> <string name="camera_share">"Compartir"</string> - <string name="camera_set">"Establecer como"</string> + <string name="camera_set">"Fije como papel pintado"</string> <string name="camera_play">"Reproducir"</string> <string name="camera_attach">"Adjuntar"</string> <string name="camera_cancel">"Cancelar"</string> <string name="camera_crop">"Recortar"</string> <string name="camera_tossing">"Eliminando..."</string> <string name="no_way_to_share_image">"Esta imagen no se puede compartir."</string> <string name="no_way_to_share_video">"Este vídeo no se puede compartir."</string> <string name="video_play">"Reproducir"</string> <string name="camera_gallery_photos_text">"Galería"</string> <string name="camera_pick_wallpaper">"Imágenes"</string> <string name="camera_setas_wallpaper">"Fondo de pantalla"</string> <string name="pref_gallery_category">"Configuración general"</string> <string name="pref_slideshow_category">"Configuración de presentación"</string> <string name="pref_camera_general_settings_category">"Configuración general"</string> <string name="pref_gallery_size_title">"Tamaño de visualización"</string> <string name="pref_gallery_size_summary">"Seleccionar el tamaño de visualización de imágenes y vídeos"</string> <string name="pref_gallery_size_dialogtitle">"Tamaño de imagen"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Pequeña"</item> </string-array> <string name="pref_gallery_sort_title">"Orden"</string> <string name="pref_gallery_sort_summary">"Seleccionar el orden de imágenes y vídeos"</string> <string name="pref_gallery_sort_dialogtitle">"Ordenación de imágenes"</string> <string-array name="pref_gallery_sort_choices"> <item>"Más recientes primero"</item> <item>"Más recientes al final"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalo de presentación"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleccionar la duración de cada diapositiva"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo de presentación"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 segundos"</item> <item>"3 segundos"</item> <item>"4 segundos"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transición de diapositivas"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleccionar el efecto que se aplicará al pasar de una diapositiva a otra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transición de diapositivas"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Fundido de entrada y salida"</item> <item>"Transición de izquierda a derecha"</item> <item>"Transición de arriba a abajo"</item> <item>"Selección aleatoria"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Repetir presentación"</string> <string name="pref_gallery_slideshow_repeat_summary">"Mostrar presentación más de una vez"</string> <string name="pref_gallery_slideshow_shuffle_title">"Orden aleatorio"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imágenes en orden aleatorio"</string> <string name="pref_camera_recordlocation_title">"Almacenar en imágenes"</string> <string name="pref_camera_recordlocation_summary">"Registrar ubicación en datos de imagen"</string> <string name="pref_camera_videoquality_category">"Calidad de vídeo"</string> <string name="pref_camera_videoquality_title">"Seleccionar calidad de vídeo"</string> <string name="pref_camera_videoquality_entry_0">"Baja (para mensajes MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (para tarjeta SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Calidad de vídeo"</string> <string name="camerasettings">"Ajustes"</string> <string name="image_gallery_NoImageView_text">"No se ha encontrado ningún elemento."</string> <string name="pref_gallery_confirm_delete_title">"Confirmar eliminaciones"</string> <string name="pref_gallery_confirm_delete_summary">"Mostrar confirmación antes de eliminar una imagen o un vídeo"</string> <string name="details_panel_title">"Detalles"</string> <string name="details_file_size">"Tamaño de archivo:"</string> <string name="details_image_resolution">"Resolución:"</string> <string name="details_duration">"Duración:"</string> <string name="details_date_taken">"Fecha de realización:"</string> <string name="details_frame_rate">"Frecuencia de imagen:"</string> <string name="details_bit_rate">"Velocidad binaria:"</string> <string name="details_codec">"Códec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"Aceptar"</string> <string name="context_menu_header">"Opciones de imagen"</string> <string name="video_context_menu_header">"Opciones de vídeo"</string> <string name="multiface_crop_help">"Toca una cara para empezar."</string> <string name="photos_gallery_title">"Galería"</string> <string name="pick_photos_gallery_title">"Seleccionar imagen"</string> <string name="videos_gallery_title">"Galería"</string> <string name="pick_videos_gallery_title">"Seleccionar vídeo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> <string name="sendImage">"Compartir imagen por"</string> <string name="setImage">"Establecer imagen como"</string> <string name="sendVideo">"Compartir vídeo a través de"</string> <string name="movieviewlabel">"Películas"</string> <string name="loading_video">"Cargando vídeo…"</string> <string name="spaceIsLow_title">"Poco espacio"</string> <string name="spaceIsLow_content">"No queda espacio en la tarjeta SD. Cambia la configuración de calidad o elimina elementos de la galería."</string> <string name="resume_playing_title">"Reanudar vídeo"</string> <string name="resume_playing_message">"Reanudar reproducción a partir de %s ?"</string> <string name="resume_playing_resume">"Reanudar reproducción"</string> <string name="resume_playing_restart">"Volver a reproducir"</string> <string name="gadget_title">"Picture frame"</string> <string name="file_info_title">"Información de archivo:"</string> <string name="video_exceed_mms_limit">"El vídeo que has grabado es demasiado grande para enviarlo a través de MMS. Intenta grabar un vídeo de menor duración."</string> <string name="too_large_to_attach">"El archivo es demasiado grande para adjuntarlo."</string> </resources> diff --git a/res/values-fr/strings.xml b/res/values-fr/strings.xml index f3214ad..689fed0 100644 --- a/res/values-fr/strings.xml +++ b/res/values-fr/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Toutes les images"</string> <string name="all_videos">"Toutes les vidéos"</string> - <string name="camera_label">"Appareil photo"</string> + <string name="camera_label">"Galerie"</string> <string name="video_camera_label">"Caméra"</string> <string name="gallery_picker_label">"Galerie"</string> <string name="gallery_camera_bucket_name">"Photos de l\'appareil"</string> <string name="gallery_camera_videos_bucket_name">"Vidéos de la caméra"</string> <string name="switch_to_video_lable">"Passer en mode vidéo"</string> <string name="switch_to_camera_lable">"Passer en mode appareil photo"</string> <string name="crop_label">"Rogner l\'image"</string> <string name="view_label">"Afficher l\'image"</string> - <string name="preferences_label">"Paramètres de l\'appareil photo"</string> + <string name="preferences_label">"Paramètres"</string> <string name="wait">"Veuillez patienter..."</string> <string name="no_storage">"Veuillez insérer une carte SD avant d\'utiliser l\'appareil photo."</string> <string name="not_enough_space">"Votre carte SD est pleine."</string> <string name="preparing_sd">"Préparation de la carte SD..."</string> <string name="wallpaper">"Configuration du fond d\'écran en cours. Veuillez patienter..."</string> <string name="savingImage">"Enregistrement de l\'image"</string> <string name="runningFaceDetection">"Veuillez patienter..."</string> <string name="flip_orientation">"Orientation"</string> <string name="settings">"Paramètres"</string> <string name="view">"Afficher"</string> <string name="details">"Détails"</string> <string name="rotate">"Faire pivoter"</string> <string name="rotate_left">"Faire pivoter à gauche"</string> <string name="rotate_right">"Faire pivoter à droite"</string> <string name="slide_show">"Diaporama"</string> <string name="capture_picture">"Prendre une photo"</string> <string name="capture_video">"Prendre une vidéo"</string> <string name="crop_save_text">"Enregistrer"</string> <string name="crop_discard_text">"Annuler"</string> <string name="confirm_delete_title">"Supprimer"</string> <string name="confirm_delete_message">"L\'image sera supprimée."</string> <string name="confirm_delete_video_message">"La vidéo va être supprimée."</string> <string name="camera_toss">"Supprimer"</string> <string name="camera_gallery">"Galerie"</string> <string name="camera_share">"Partager"</string> - <string name="camera_set">"Définir comme"</string> + <string name="camera_set">"Placez comme papier peint"</string> <string name="camera_play">"Lire"</string> <string name="camera_attach">"Pièce jointe"</string> <string name="camera_cancel">"Annuler"</string> <string name="camera_crop">"Rogner"</string> <string name="camera_tossing">"Suppression..."</string> <string name="no_way_to_share_image">"Impossible de partager cette image."</string> <string name="no_way_to_share_video">"Cette vidéo ne peut pas être partagée."</string> <string name="video_play">"Lire"</string> <string name="camera_gallery_photos_text">"Galerie"</string> <string name="camera_pick_wallpaper">"Images"</string> <string name="camera_setas_wallpaper">"Fond d\'écran"</string> <string name="pref_gallery_category">"Paramètres généraux"</string> <string name="pref_slideshow_category">"Paramètres du diaporama"</string> <string name="pref_camera_general_settings_category">"Paramètres généraux"</string> <string name="pref_gallery_size_title">"Taille d\'affichage"</string> <string name="pref_gallery_size_summary">"Sélectionner la taille d\'affichage des images et des vidéos"</string> <string name="pref_gallery_size_dialogtitle">"Taille de l\'image"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Petite"</item> </string-array> <string name="pref_gallery_sort_title">"Ordre de tri"</string> <string name="pref_gallery_sort_summary">"Sélectionner l\'ordre de tri des images et des vidéos"</string> <string name="pref_gallery_sort_dialogtitle">"Trier les images"</string> <string-array name="pref_gallery_sort_choices"> <item>"La plus récente en premier"</item> <item>"La plus récente en dernier"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalle entre photos"</string> <string name="pref_gallery_slideshow_interval_summary">"Sélectionner la durée d\'affichage de chaque diapositive dans le diaporama"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalle du diaporama"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 secondes"</item> <item>"3 secondes"</item> <item>"4 secondes"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transition du diaporama"</string> <string name="pref_gallery_slideshow_transition_summary">"Sélectionner l\'effet utilisé lors de la transition d\'une diapositive à une autre"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transition du diaporama"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ouverture et fermeture en fondu"</item> <item>"Glisser de gauche à droite"</item> <item>"Glisser de haut en bas"</item> <item>"Sélection aléatoire"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Rejouer le diaporama"</string> <string name="pref_gallery_slideshow_repeat_summary">"Rejouer le diaporama plusieurs fois"</string> <string name="pref_gallery_slideshow_shuffle_title">"Lecture aléatoire"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Afficher les images"</string> <string name="pref_camera_recordlocation_title">"Enregistrer le lieu"</string> <string name="pref_camera_recordlocation_summary">"Enregistrer la position géographique dans les données d\'image"</string> <string name="pref_camera_videoquality_category">"Paramètres vidéo"</string> <string name="pref_camera_videoquality_title">"Qualité vidéo"</string> <string name="pref_camera_videoquality_entry_0">"Basse (MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Haute (carte SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Qualité vidéo"</string> <string name="camerasettings">"Paramètres"</string> <string name="image_gallery_NoImageView_text">"Aucun fichier trouvé."</string> <string name="pref_gallery_confirm_delete_title">"Confirmer suppressions"</string> <string name="pref_gallery_confirm_delete_summary">"Afficher une confirmation avant de supprimer une image ou une vidéo"</string> <string name="details_panel_title">"Détails"</string> <string name="details_file_size">"Taille du fichier :"</string> <string name="details_image_resolution">"Résolution :"</string> <string name="details_duration">"Durée :"</string> <string name="details_date_taken">"Date de création :"</string> <string name="details_frame_rate">"Fréquence d\'images :"</string> <string name="details_bit_rate">"Débit :"</string> <string name="details_codec">"Codec :"</string> <string name="details_format">"Format :"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d ips"</string> <string name="details_kbps">"%1$d Kbits/s"</string> <string name="details_mbps">"%1$g Mbits/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Options de l\'image"</string> <string name="video_context_menu_header">"Options vidéo"</string> <string name="multiface_crop_help">"Appuyez sur un visage pour commencer."</string> <string name="photos_gallery_title">"Galerie"</string> <string name="pick_photos_gallery_title">"Sélectionnez une image"</string> <string name="videos_gallery_title">"Galerie"</string> <string name="pick_videos_gallery_title">"Sélectionnez une vidéo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> vignettes restantes"</string> <string name="sendImage">"Partager l\'image via"</string> <string name="setImage">"Définir l\'image comme"</string> <string name="sendVideo">"Partager la vidéo via"</string> <string name="movieviewlabel">"Films"</string> <string name="loading_video">"Chargement de la vidéo..."</string> <string name="spaceIsLow_title">"L\'espace restant est faible"</string> <string name="spaceIsLow_content">"Votre carte SD est pleine. Modifiez le paramètre de qualité ou supprimez des éléments de la galerie."</string> <string name="resume_playing_title">"Reprendre la vidéo"</string> <string name="resume_playing_message">"Reprendre la lecture à partir de %s ?"</string> <string name="resume_playing_resume">"Reprendre la lecture"</string> <string name="resume_playing_restart">"Démarrer"</string> <string name="gadget_title">"Cadre d\'image"</string> <string name="file_info_title">"Informations sur le fichier :"</string> <string name="video_exceed_mms_limit">"La vidéo que vous avez enregistrée est trop volumineuse et ne peut être envoyée par MMS. Enregistrez une vidéo plus courte."</string> <string name="too_large_to_attach">"Impossible de joindre le fichier, car il est trop volumineux."</string> </resources> diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml index 1440582..e0cdf54 100644 --- a/res/values-ja/strings.xml +++ b/res/values-ja/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"すべての写真"</string> <string name="all_videos">"すべての動画"</string> - <string name="camera_label">"カメラ"</string> + <string name="camera_label">"ギャラリー"</string> <string name="video_camera_label">"ビデオ録画"</string> <string name="gallery_picker_label">"ギャラリー"</string> <string name="gallery_camera_bucket_name">"カメラ (写真)"</string> <string name="gallery_camera_videos_bucket_name">"カメラ (動画)"</string> <string name="switch_to_video_lable">"ムービーに切替"</string> <string name="switch_to_camera_lable">"写真に切替"</string> <string name="crop_label">"トリミング"</string> <string name="view_label">"画像を表示"</string> - <string name="preferences_label">"カメラ設定"</string> + <string name="preferences_label">"設定"</string> <string name="wait">"お待ちください..."</string> <string name="no_storage">"カメラを使用する前にSDカードを挿入してください。"</string> <string name="not_enough_space">"SDカードがいっぱいです。"</string> <string name="preparing_sd">"SDカードの準備中..."</string> <string name="wallpaper">"壁紙を設定しています。しばらくお待ちください..."</string> <string name="savingImage">"写真を保存中..."</string> <string name="runningFaceDetection">"お待ちください..."</string> <string name="flip_orientation">"画面の向きを変更"</string> <string name="settings">"設定"</string> <string name="view">"表示"</string> <string name="details">"詳細情報"</string> <string name="rotate">"回転"</string> <string name="rotate_left">"左に回転"</string> <string name="rotate_right">"右に回転"</string> <string name="slide_show">"スライドショー"</string> <string name="capture_picture">"写真撮影"</string> <string name="capture_video">"ムービー撮影"</string> <string name="crop_save_text">"保存"</string> <string name="crop_discard_text">"キャンセル"</string> <string name="confirm_delete_title">"削除"</string> <string name="confirm_delete_message">"画像を削除します。"</string> <string name="confirm_delete_video_message">"動画を削除します。"</string> <string name="camera_toss">"削除"</string> <string name="camera_gallery">"ギャラリー"</string> <string name="camera_share">"共有"</string> - <string name="camera_set">"この画像を登録する"</string> + <string name="camera_set">"ウォールペーパーに設定"</string> <string name="camera_play">"再生"</string> <string name="camera_attach">"添付"</string> <string name="camera_cancel">"キャンセル"</string> <string name="camera_crop">"トリミング"</string> <string name="camera_tossing">"削除中..."</string> <string name="no_way_to_share_image">"この画像は共有できません。"</string> <string name="no_way_to_share_video">"この動画は共有できません。"</string> <string name="video_play">"再生"</string> <string name="camera_gallery_photos_text">"ギャラリー"</string> <string name="camera_pick_wallpaper">"画像"</string> <string name="camera_setas_wallpaper">"壁紙"</string> <string name="pref_gallery_category">"全般設定"</string> <string name="pref_slideshow_category">"スライドショー設定"</string> <string name="pref_camera_general_settings_category">"全般設定"</string> <string name="pref_gallery_size_title">"表示サイズ"</string> <string name="pref_gallery_size_summary">"画像や動画の表示サイズ"</string> <string name="pref_gallery_size_dialogtitle">"画像サイズ"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"表示順序"</string> <string name="pref_gallery_sort_summary">"画像や動画の表示順序を選択"</string> <string name="pref_gallery_sort_dialogtitle">"画像並べ替え"</string> <string-array name="pref_gallery_sort_choices"> <item>"日付の新しい順"</item> <item>"日付の古い順"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"スライドの再生間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"各スライドの表示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"スライドの再生間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2秒"</item> <item>"3秒"</item> <item>"4秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"スライド切り替え"</string> <string name="pref_gallery_slideshow_transition_summary">"スライドが切り替わるときの効果"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"スライド切り替え"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"フェードイン&amp;アウト"</item> <item>"左右にスライド"</item> <item>"上下にスライド"</item> <item>"ランダムに選択"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"リピート再生"</string> <string name="pref_gallery_slideshow_repeat_summary">"スライドショーを繰り返し再生"</string> <string name="pref_gallery_slideshow_shuffle_title">"スライドのシャッフル"</string> <string name="pref_gallery_slideshow_shuffle_summary">"順不同に表示する"</string> <string name="pref_camera_recordlocation_title">"位置情報を写真に記録する"</string> <string name="pref_camera_recordlocation_summary">"位置情報を写真データに記録する"</string> <string name="pref_camera_videoquality_category">"動画のクオリティ"</string> <string name="pref_camera_videoquality_title">"動画の画質を選択"</string> <string name="pref_camera_videoquality_entry_0">"低 (MMSメッセージ向け)"</string> <string name="pref_camera_videoquality_entry_1">"高 (SDカード向け)"</string> <string name="pref_camera_videoquality_dialogtitle">"動画のクオリティ"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"メディアが見つかりません。"</string> <string name="pref_gallery_confirm_delete_title">"削除確認"</string> <string name="pref_gallery_confirm_delete_summary">"画像や動画を削除する前に確認する"</string> <string name="details_panel_title">"詳細情報"</string> <string name="details_file_size">"ファイルサイズ:"</string> <string name="details_image_resolution">"解像度:"</string> <string name="details_duration">"再生時間:"</string> <string name="details_date_taken">"撮影日:"</string> <string name="details_frame_rate">"フレームレート:"</string> <string name="details_bit_rate">"ビットレート:"</string> <string name="details_codec">"コーデック:"</string> <string name="details_format">"形式:"</string> <string name="details_dimension_x">"%1$dx%2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$dfps"</string> <string name="details_kbps">"%1$dKbps"</string> <string name="details_mbps">"%1$gMbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"画像オプション"</string> <string name="video_context_menu_header">"動画オプション"</string> <string name="multiface_crop_help">"顔をタップして開始します。"</string> <string name="photos_gallery_title">"ギャラリー"</string> <string name="pick_photos_gallery_title">"画像を選択"</string> <string name="videos_gallery_title">"ギャラリー"</string> <string name="pick_videos_gallery_title">"動画を選択"</string> <string name="loading_progress_format_string">"残り<xliff:g id="COUNTER">%d</xliff:g>件"</string> <string name="sendImage">"画像を共有:"</string> <string name="setImage">"この画像を登録する"</string> <string name="sendVideo">"動画を共有"</string> <string name="movieviewlabel">"映画"</string> <string name="loading_video">"動画を読み込み中..."</string> <string name="spaceIsLow_title">"空き容量が残り少なくなっています"</string> <string name="spaceIsLow_content">"SDカードの容量が足りません。クオリティ設定を変更するか、ギャラリーからアイテムを削除してください。"</string> <string name="resume_playing_title">"動画の再開"</string> <string name="resume_playing_message">"再生を%sから再開しますか?"</string> <string name="resume_playing_resume">"再生を再開"</string> <string name="resume_playing_restart">"最初から再生"</string> <string name="gadget_title">"写真フレーム"</string> <string name="file_info_title">"ファイル情報:"</string> <string name="video_exceed_mms_limit">"録画した動画のサイズが大きすぎるため送信できません。録画時間を短縮してみてください。"</string> <string name="too_large_to_attach">"添付ファイルが大きすぎます。"</string> </resources> diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml index 3143387..515c9c6 100644 --- a/res/values-zh-rCN/strings.xml +++ b/res/values-zh-rCN/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"所有图片"</string> <string name="all_videos">"所有视频"</string> - <string name="camera_label">"相机"</string> + <string name="camera_label">"图库"</string> <string name="video_camera_label">"摄像机"</string> <string name="gallery_picker_label">"图库"</string> <string name="gallery_camera_bucket_name">"用相机拍摄的照片"</string> <string name="gallery_camera_videos_bucket_name">"用相机拍摄的视频"</string> <string name="switch_to_video_lable">"切换到视频"</string> <string name="switch_to_camera_lable">"切换到相机"</string> <string name="crop_label">"修剪图片"</string> <string name="view_label">"查看图片"</string> - <string name="preferences_label">"相机设置"</string> + <string name="preferences_label">"设置"</string> <string name="wait">"请稍候..."</string> <string name="no_storage">"使用相机前请先插入 SD 卡。"</string> <string name="not_enough_space">"SD 卡已满。"</string> <string name="preparing_sd">"正在准备 SD 卡..."</string> <string name="wallpaper">"正在设置壁纸,请稍候..."</string> <string name="savingImage">"正在保存图片..."</string> <string name="runningFaceDetection">"请稍候..."</string> <string name="flip_orientation">"反转方向"</string> <string name="settings">"设置"</string> <string name="view">"查看"</string> <string name="details">"详细信息"</string> <string name="rotate">"旋转"</string> <string name="rotate_left">"向左旋转"</string> <string name="rotate_right">"向右旋转"</string> <string name="slide_show">"播放幻灯片"</string> <string name="capture_picture">"拍摄照片"</string> <string name="capture_video">"拍摄视频"</string> <string name="crop_save_text">"保存"</string> <string name="crop_discard_text">"舍弃"</string> <string name="confirm_delete_title">"删除"</string> <string name="confirm_delete_message">"将会删除此照片。"</string> <string name="confirm_delete_video_message">"将会删除视频。"</string> <string name="camera_toss">"删除"</string> <string name="camera_gallery">"图库"</string> <string name="camera_share">"分享"</string> - <string name="camera_set">"设置为"</string> + <string name="camera_set">"设为桌面背景"</string> <string name="camera_play">"播放"</string> <string name="camera_attach">"附加"</string> <string name="camera_cancel">"取消"</string> <string name="camera_crop">"修剪"</string> <string name="camera_tossing">"正在删除..."</string> <string name="no_way_to_share_image">"无法分享此图片。"</string> <string name="no_way_to_share_video">"无法分享此视频。"</string> <string name="video_play">"播放"</string> <string name="camera_gallery_photos_text">"图库"</string> <string name="camera_pick_wallpaper">"图片"</string> <string name="camera_setas_wallpaper">"壁纸"</string> <string name="pref_gallery_category">"常规设置"</string> <string name="pref_slideshow_category">"幻灯片设置"</string> <string name="pref_camera_general_settings_category">"常规设置"</string> <string name="pref_gallery_size_title">"显示大小"</string> <string name="pref_gallery_size_summary">"选择图片和视频的显示大小"</string> <string name="pref_gallery_size_dialogtitle">"图片大小"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"排列顺序"</string> <string name="pref_gallery_sort_summary">"选择图片和视频的排列顺序"</string> <string name="pref_gallery_sort_dialogtitle">"图片排序"</string> <string-array name="pref_gallery_sort_choices"> <item>"最新的图片在最前面"</item> <item>"最新的图片在最后面"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"幻灯片播放间隔"</string> <string name="pref_gallery_slideshow_interval_summary">"选择每张幻灯片在播放过程中呈现的时间"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"幻灯片播放间隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 秒"</item> <item>"3 秒"</item> <item>"4 秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"幻灯片切换"</string> <string name="pref_gallery_slideshow_transition_summary">"选择幻灯片切换时应用的效果"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"幻灯片切换"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"淡入淡出"</item> <item>"自左至右滑动"</item> <item>"自上至下滑动"</item> <item>"随机选择"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"重复播放幻灯片"</string> <string name="pref_gallery_slideshow_repeat_summary">"循环播放幻灯片"</string> <string name="pref_gallery_slideshow_shuffle_title">"随机播放幻灯片"</string> <string name="pref_gallery_slideshow_shuffle_summary">"以随机顺序显示图片"</string> <string name="pref_camera_recordlocation_title">"在照片中存储位置"</string> <string name="pref_camera_recordlocation_summary">"在照片数据中记录位置"</string> <string name="pref_camera_videoquality_category">"视频画质"</string> <string name="pref_camera_videoquality_title">"选择视频画质"</string> <string name="pref_camera_videoquality_entry_0">"低(对于彩信)"</string> <string name="pref_camera_videoquality_entry_1">"高(对于 SD 卡)"</string> <string name="pref_camera_videoquality_dialogtitle">"视频画质"</string> <string name="camerasettings">"设置"</string> <string name="image_gallery_NoImageView_text">"找不到媒体。"</string> <string name="pref_gallery_confirm_delete_title">"确认删除"</string> <string name="pref_gallery_confirm_delete_summary">"在删除图片或视频前显示确认消息"</string> <string name="details_panel_title">"详细信息"</string> <string name="details_file_size">"文件大小:"</string> <string name="details_image_resolution">"分辨率:"</string> <string name="details_duration">"持续时间:"</string> <string name="details_date_taken">"拍摄日期:"</string> <string name="details_frame_rate">"帧频:"</string> <string name="details_bit_rate">"比特率:"</string> <string name="details_codec">"编解码器:"</string> <string name="details_format">"格式:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"确定"</string> <string name="context_menu_header">"图片选项"</string> <string name="video_context_menu_header">"视频选项"</string> <string name="multiface_crop_help">"点按一张脸开始裁剪。"</string> <string name="photos_gallery_title">"图库"</string> <string name="pick_photos_gallery_title">"选择图片"</string> <string name="videos_gallery_title">"图库"</string> <string name="pick_videos_gallery_title">"选择视频"</string> <string name="loading_progress_format_string">"还剩 <xliff:g id="COUNTER">%d</xliff:g> 个"</string> <string name="sendImage">"图片分享方式"</string> <string name="setImage">"将图片设置为"</string> <string name="sendVideo">"分享视频的方式"</string> <string name="movieviewlabel">"电影"</string> <string name="loading_video">"正在载入视频..."</string> <string name="spaceIsLow_title">"存储空间不足"</string> <string name="spaceIsLow_content">"SD 卡空间不足。请更改画质设置或从图库中删除部分项。"</string> <string name="resume_playing_title">"重新播放视频"</string> <string name="resume_playing_message">"从 %s 开始重新播放?"</string> <string name="resume_playing_resume">"重新播放"</string> <string name="resume_playing_restart">"重新开始"</string> <string name="gadget_title">"相框"</string> <string name="file_info_title">"文件信息:"</string> <string name="video_exceed_mms_limit">"您录制的视频太大,无法用彩信发送。请尝试录制短一点的剪辑。"</string> <string name="too_large_to_attach">"文件太大,无法附加。"</string> </resources> diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml index 8a701eb..c763ad4 100644 --- a/res/values-zh-rTW/strings.xml +++ b/res/values-zh-rTW/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"所有相片"</string> <string name="all_videos">"所有影片"</string> - <string name="camera_label">"相機"</string> + <string name="camera_label">"圖庫"</string> <string name="video_camera_label">"攝錄影機"</string> <string name="gallery_picker_label">"圖庫"</string> <string name="gallery_camera_bucket_name">"相機圖片"</string> <string name="gallery_camera_videos_bucket_name">"相機影片"</string> <string name="switch_to_video_lable">"切換為影片"</string> <string name="switch_to_camera_lable">"切換為相機"</string> <string name="crop_label">"裁剪相片"</string> <string name="view_label">"檢視相片"</string> - <string name="preferences_label">"相機設定"</string> + <string name="preferences_label">"設定"</string> <string name="wait">"請稍候…"</string> <string name="no_storage">"使用相機前請先插入 SD 卡。"</string> <string name="not_enough_space">"SD 卡已滿。"</string> <string name="preparing_sd">"正在準備 SD 卡..."</string> <string name="wallpaper">"設定桌布中,請稍候…"</string> <string name="savingImage">"儲存相片中…"</string> <string name="runningFaceDetection">"請稍候…"</string> <string name="flip_orientation">"旋轉方向"</string> <string name="settings">"設定"</string> <string name="view">"檢視"</string> <string name="details">"詳細資料"</string> <string name="rotate">"旋轉"</string> <string name="rotate_left">"向左旋轉"</string> <string name="rotate_right">"向右旋轉"</string> <string name="slide_show">"投影片"</string> <string name="capture_picture">"拍攝照片"</string> <string name="capture_video">"拍攝影片"</string> <string name="crop_save_text">"儲存"</string> <string name="crop_discard_text">"放棄"</string> <string name="confirm_delete_title">"刪除"</string> <string name="confirm_delete_message">"刪除相片?"</string> <string name="confirm_delete_video_message">"刪除這部影片?"</string> <string name="camera_toss">"刪除"</string> <string name="camera_gallery">"圖庫"</string> <string name="camera_share">"分享"</string> - <string name="camera_set">"設為"</string> + <string name="camera_set">"設為桌布"</string> <string name="camera_play">"播放"</string> <string name="camera_attach">"附加"</string> <string name="camera_cancel">"取消"</string> <string name="camera_crop">"裁剪"</string> <string name="camera_tossing">"刪除中…"</string> <string name="no_way_to_share_image">"此相片無法分享。"</string> <string name="no_way_to_share_video">"此影片無法分享。"</string> <string name="video_play">"播放"</string> <string name="camera_gallery_photos_text">"圖庫"</string> <string name="camera_pick_wallpaper">"圖片"</string> <string name="camera_setas_wallpaper">"桌布"</string> <string name="pref_gallery_category">"一般設定"</string> <string name="pref_slideshow_category">"投影片設定"</string> <string name="pref_camera_general_settings_category">"一般設定"</string> <string name="pref_gallery_size_title">"顯示大小"</string> <string name="pref_gallery_size_summary">"選取相片和影片的顯示大小"</string> <string name="pref_gallery_size_dialogtitle">"相片大小"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"排序順序"</string> <string name="pref_gallery_sort_summary">"選取相片和影片的排序順序"</string> <string name="pref_gallery_sort_dialogtitle">"圖片排序"</string> <string-array name="pref_gallery_sort_choices"> <item>"最新的在前"</item> <item>"最新的在後"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"投影片顯示間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"選取每張投影片顯示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"投影片顯示間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 秒"</item> <item>"3 秒"</item> <item>"4 秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"投影片轉場特效"</string> <string name="pref_gallery_slideshow_transition_summary">"選取更換相片時的轉場特效"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"投影片轉場特效"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"淡入淡出"</item> <item>"左右滑動"</item> <item>"上下滑動"</item> <item>"隨機選取"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"重複播放投影片"</string> <string name="pref_gallery_slideshow_repeat_summary">"旋環播放投影片"</string> <string name="pref_gallery_slideshow_shuffle_title">"隨機播放投影片"</string> <string name="pref_gallery_slideshow_shuffle_summary">"隨機顯示相片"</string> <string name="pref_camera_recordlocation_title">"在相片儲存位置資訊"</string> <string name="pref_camera_recordlocation_summary">"在相片中記錄位置資訊"</string> <string name="pref_camera_videoquality_category">"影片品質"</string> <string name="pref_camera_videoquality_title">"選取影片品質"</string> <string name="pref_camera_videoquality_entry_0">"低 (適用於多媒體簡訊)"</string> <string name="pref_camera_videoquality_entry_1">"高 (適用於 SD 卡)"</string> <string name="pref_camera_videoquality_dialogtitle">"影片品質"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"找不到媒體。"</string> <string name="pref_gallery_confirm_delete_title">"刪除確認"</string> <string name="pref_gallery_confirm_delete_summary">"刪除相片或影片前要顯示確認"</string> <string name="details_panel_title">"詳細資料"</string> <string name="details_file_size">"檔案大小:"</string> <string name="details_image_resolution">"解析度:"</string> <string name="details_duration">"所需時間:"</string> <string name="details_date_taken">"拍攝日期:"</string> <string name="details_frame_rate">"影格速率:"</string> <string name="details_bit_rate">"位元速率:"</string> <string name="details_codec">"編碼器:"</string> <string name="details_format">"格式:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"確定"</string> <string name="context_menu_header">"圖片選項"</string> <string name="video_context_menu_header">"影片選項"</string> <string name="multiface_crop_help">"輕觸所需的臉孔開始裁剪。"</string> <string name="photos_gallery_title">"圖庫"</string> <string name="pick_photos_gallery_title">"選取相片"</string> <string name="videos_gallery_title">"圖庫"</string> <string name="pick_videos_gallery_title">"選取影片"</string> <string name="loading_progress_format_string">"還有 <xliff:g id="COUNTER">%d</xliff:g> 張"</string> <string name="sendImage">"透過…分享圖片"</string> <string name="setImage">"設定相片為…"</string> <string name="sendVideo">"透過…分享影片"</string> <string name="movieviewlabel">"電影"</string> <string name="loading_video">"正在載入影片…"</string> <string name="spaceIsLow_title">"空間不足"</string> <string name="spaceIsLow_content">"您的 SD 卡空間已快用完。請變更品質設定或刪除圖庫中的項目。"</string> <string name="resume_playing_title">"繼續播放影片"</string> <string name="resume_playing_message">"要從 %s 繼續播放嗎?"</string> <string name="resume_playing_resume">"繼續播放"</string> <string name="resume_playing_restart">"重新開始"</string> <string name="gadget_title">"相框"</string> <string name="file_info_title">"檔案資訊:"</string> <string name="video_exceed_mms_limit">"您所錄製的影片太大,無法透過 MMS 傳送。請試著錄製較短的影片。"</string> <string name="too_large_to_attach">"檔案過大,超過附件大小限制。"</string> </resources> diff --git a/res/values/strings.xml b/res/values/strings.xml index 7408f57..bcfe6b8 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -1,465 +1,465 @@ <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <!-- General strings --> <!-- label for the icon meaning 'show me all the images' --> <string name="all_images">All pictures</string> <!-- label for the icon meaning 'show me all the videos' --> <string name="all_videos">All videos</string> <!-- label for the icon meaning 'show me all the images that were taken with the camera' --> - <string name="camera_label">Camera</string> + <string name="camera_label">Gallery</string> <!-- label for the 'video recording application shown in the top level 'all applications' --> <string name="video_camera_label">Camcorder</string> <!-- label for the 'pictures application shown in the top level 'all applications' --> <string name="gallery_picker_label">Gallery</string> <!-- unused (do not translate) --> <string name="gallery_label">Pictures</string> <!-- label for the folder that contains Camera pictures in the gallery --> <string name="gallery_camera_bucket_name">Camera pictures</string> <!-- label for the folder that contains Camera videos in the gallery --> <string name="gallery_camera_videos_bucket_name">Camera videos</string> <!-- menu pick: switch to Video cam mode --> <string name="switch_to_video_lable">Switch to video</string> <!-- menu pick: switch to camera mode --> <string name="switch_to_camera_lable">Switch to camera</string> <!-- menu pick: crop the currently selected image --> <string name="crop_label">Crop picture</string> <!-- menu pick: view the currently selected image --> <string name="view_label">View picture</string> <!-- menu pick: go to the preferences screen for the camera or image gallery --> - <string name="preferences_label">Camera settings</string> + <string name="preferences_label">settings</string> <!-- alert to the user to wait for some operation to complete --> <string name="wait">Please wait\u2026</string> <!-- alert to the user to that an SD card must be installed before using the camera --> <string name="no_storage">Please insert an SD card before using the camera.</string> <!-- alert to the user to that the SD card is too full to complete the operation --> <string name="not_enough_space">Your SD card is full.</string> <!-- alert to the user to that the SD card is being disk-checked --> <string name="preparing_sd">Preparing SD card\u2026</string> <!-- Toast/alert after saving wallpaper --> <string name="wallpaper">Setting wallpaper, please wait\u2026</string> <!-- Settings stuff --> <!-- Toast/alert that the image is being saved to the SD card --> <string name="savingImage">Saving picture\u2026</string> <!-- Toast/alert that the face detection is being run --> <string name="runningFaceDetection">Please wait\u2026</string> <!-- Menu items: --> <!-- menu pick to change the orientation of the screen --> <string name="flip_orientation">Flip orientation</string> <!-- menu pick to go to the settings screen --> <string name="settings">Settings</string> <!-- menu pick to view the currently selected image --> <string name="view">View</string> <!-- menu pick to view the details of the currently selected image --> <string name="details">Details</string> <!-- menu pick to rotate the currently selected image (brings up submenu) --> <string name="rotate">Rotate</string> <!-- menu pick to rotate the currently selected image to the left --> <string name="rotate_left">Rotate left</string> <!-- menu pick to rotate the currently selected image to the right --> <string name="rotate_right">Rotate right</string> <!-- menu pick to start a slide show --> <string name="slide_show">Slideshow</string> <!-- menu pick to go to camera mode to capture a picture --> <string name="capture_picture">Capture picture</string> <!-- menu pick to go to video mode to capture a video --> <string name="capture_video">Capture video</string> <!-- button indicating that the cropped image should be saved --> <string name="crop_save_text">Save</string> <!-- button indicating that the cropped image should be reverted back to the original --> <string name="crop_discard_text">Discard</string> <!-- Confirmation dialog title after deleting a picture --> <string name="confirm_delete_title">Delete</string> <!-- Confirmation dialog message after deleting a picture --> <string name="confirm_delete_message">The picture will be deleted.</string> <!-- Confirmation dialog message after deleting a video --> <string name="confirm_delete_video_message">The video will be deleted.</string> <!-- button indicating that the picture just taken should be deleted --> <string name="camera_toss">Delete</string> <!-- Lable for the button that takes the user to the camera pictures Gallery --> <string name="camera_gallery">Gallery</string> <!-- button indicating that the picture just taken should be shared by email, mms, etc --> <string name="camera_share">Share</string> <!-- button indicating that the picture just taken should be set as a contact photo, wallpaper, etc --> - <string name="camera_set">Set as</string> + <string name="camera_set">Set as Wallpaper</string> <!-- button indicating that the video just taken should be played --> <string name="camera_play">Play</string> <!-- button indicating that the video just taken should be accepted as an attachment --> <string name="camera_attach">Attach</string> <!-- button indicating that the video recording session should be canceled --> <string name="camera_cancel">Cancel</string> <!-- button indicating that the picture just taken should be cropped --> <string name="camera_crop">Crop</string> <!-- Toast after deleting a picture --> <string name="camera_tossing">Deleting\u2026</string> <!-- Toast after trying to share a picture indicating that there are no applications which are capable of so doing. --> <string name="no_way_to_share_image">This picture cannot be shared.</string> <!-- Toast after trying to share a video indicating that there are no applications which are capable of so doing. --> <string name="no_way_to_share_video">This video cannot be shared.</string> <!-- Menu item for playing the video. --> <string name="video_play">Play</string> <!-- Button indicating to go to the image gallery --> <string name="camera_gallery_photos_text">Gallery</string> <!-- String indicating an action of picking a picture to use as wallpaper (e.g. set wallpaper from "Pictures") --> <string name="camera_pick_wallpaper">Pictures</string> <string name="camera_setas_wallpaper">Wallpaper</string> <!-- Settings screen, section heading --> <string name="pref_gallery_category">General settings</string> <!-- Settings screen, section heading --> <string name="pref_slideshow_category">Slideshow settings</string> <string name="pref_camera_general_settings_category">General settings</string> <!-- Settings screen, setting summary text --> <string name="pref_gallery_size_title">Display size</string> <!-- Settings screen, title for preference for image size to be used in the im --> <string name="pref_gallery_size_summary">Select the display size of pictures and videos</string> <!-- Title of dialog that appears after selecting Picture size setting option --> <string name="pref_gallery_size_dialogtitle">Picture size</string> <!-- Options in dialog that appears after selecting Picture size setting option --> <string-array name="pref_gallery_size_choices"> <!-- size choice of "large" --> <item>Large</item> <!-- size choice of "small" --> <item>Small</item> </string-array> <!-- Do not translate. Option values in dialog that appears after selecting Picture size setting option --> <string-array name="pref_gallery_size_values"> <!-- do not translate --> <item>1</item> <!-- do not translate --> <item>0</item> </string-array> <!-- Do not translate. Default option value in dialog that appears after selecting Picture size setting option --> <string name="default_value_pref_gallery_size">1</string> <!-- Settings screen, setting option name --> <string name="pref_gallery_sort_title">Sort order</string> <!-- Settings screen, setting summary text --> <string name="pref_gallery_sort_summary">Select the sort order of pictures and videos</string> <!-- Title of dialog that appears after selecting Picture sort setting option --> <string name="pref_gallery_sort_dialogtitle">Picture sort</string> <!-- Options in dialog that appears after selecting Picture sort setting option --> <string-array name="pref_gallery_sort_choices"> <!-- Preference choice to show "newest first" --> <item>Newest first</item> <!-- Preference choice to show "newest last" --> <item>Newest last</item> </string-array> <!-- Do not translate. Option values in dialog that appears after selecting Picture sort setting option --> <string-array name="pref_gallery_sort_values"> <!-- do not translate --> <item>descending</item> <!-- do not translate --> <item>ascending</item> </string-array> <!-- Do not translate. Default option value in dialog that appears after selecting Picture sort setting option --> <string name="default_value_pref_gallery_sort">descending</string> <!-- Settings screen, setting option name --> <string name="pref_gallery_slideshow_interval_title">Slideshow interval</string> <!-- Settings screen, setting summary text --> <string name="pref_gallery_slideshow_interval_summary">Select how long each slide displays in the show</string> <!-- Title of dialog that appears after selecting Slideshow interval setting option --> <string name="pref_gallery_slideshow_interval_dialogtitle">Slideshow interval</string> <!-- Options in dialog that appears after selecting Slideshow interval setting option --> <string-array name="pref_gallery_slideshow_interval_choices"> <!-- slide show interval "N seconds" where N is 2 --> <item>2 seconds</item> <!-- slide show interval "N seconds" where N is 3 --> <item>3 seconds</item> <!-- slide show interval "N seconds" where N is 4 --> <item>4 seconds</item> </string-array> <!-- Do not translate. Option values in dialog that appears after selecting Slideshow interval setting option --> <string-array name="pref_gallery_slideshow_interval_values"> <!-- do not translate --> <item>"2"</item> <!-- do not translate --> <item>"3"</item> <!-- do not translate --> <item>"4"</item> </string-array> <!-- Do not translate. Default option value in dialog that appears after selecting Slideshow interval setting option --> <string name="default_value_pref_gallery_slideshow_interval">"2"</string> <!-- Settings screen, setting option name --> <string name="pref_gallery_slideshow_transition_title">Slideshow transition</string> <!-- Settings screen, setting summary text --> <string name="pref_gallery_slideshow_transition_summary">Select the effect used when moving from one slide to the next</string> <!-- Title of dialog that appears after selecting Slideshow transition setting option --> <string name="pref_gallery_slideshow_transition_dialogtitle">Slideshow transition</string> <!-- Options in dialog that appears after selecting Slideshow transition setting option --> <string-array name="pref_gallery_slideshow_transition_choices"> <!-- Slide show transition to fade in and fade out --> <item>Fade in &amp; out</item> <!-- Slide show transition to slide in and out from the left and right --> <item>Slide left - right</item> <!-- Slide show transition to slide in and out from the top and bottom --> <item>Slide up - down</item> <!-- Slide show transition to be chosen randomly --> <item>Random selection</item> </string-array> <!-- Do not translate. Option values in dialog that appears after selecting Slideshow transition setting option --> <string-array name="pref_gallery_slideshow_transition_values"> <!-- do not translate --> <item>"0"</item> <!-- do not translate --> <item>"1"</item> <!-- do not translate --> <item>"2"</item> <!-- do not translate --> <item>"-1"</item> </string-array> <!-- Do not translate. Default option value in dialog that appears after selecting Slideshow transition setting option --> <string name="default_value_pref_gallery_slideshow_transition">"0"</string> <!-- Settings screen, setting check box name --> <string name="pref_gallery_slideshow_repeat_title">Repeat slideshow</string> <!-- Settings screen, setting summary text --> <string name="pref_gallery_slideshow_repeat_summary">Play slideshow more than once</string> <!-- Settings screen, setting check box name --> <string name="pref_gallery_slideshow_shuffle_title">Shuffle slides</string> <!-- Settings screen, setting summary text --> <string name="pref_gallery_slideshow_shuffle_summary">Show pictures in random order</string> <!-- Settings screen, setting title text --> <string name="pref_camera_recordlocation_title">Store location in pictures</string> <!-- Settings screen, setting summary text --> <string name="pref_camera_recordlocation_summary">Record location in picture data</string> <!-- Do not translate --> <string name="pref_camera_upload_albumname_title">Picasa album name</string> <!-- Do not translate --> <string name="pref_camera_upload_albumname_summary">Name the destination album for your pictures (<xliff:g id="summary">%s</xliff:g>)</string> <!-- Do not translate --> <string name="pref_camera_upload_albumname_dialogtitle">Picasa album name</string> <!-- Settings screen, Video quality category title --> <string name="pref_camera_videoquality_category">Video quality</string> <!-- Default video quality setting. A numerical value. Do not translate. --> <string name="pref_camera_videoquality_default">1</string> <!-- Settings screen, Select Video quality title --> <string name="pref_camera_videoquality_title">Select video quality</string> <!-- Settings screen, Video quality dialog radio button choices --> <string name="pref_camera_videoquality_entry_0">Low (for MMS messages)</string> <string name="pref_camera_videoquality_entry_1">High (for SD card)</string> <!-- Settings screen, Video codec dialog title --> <string name="pref_camera_videoquality_dialogtitle">Video quality</string> <!-- Menu item to go to the settings screen --> <string name="camerasettings">Settings</string> <!-- Text message indicating that there are no pictures or videos in a particular bucket on the SD card --> <string name="image_gallery_NoImageView_text">No media found.</string> <!-- Preference title for whether the user should be prompted form confirmation when deleting images --> <string name="pref_gallery_confirm_delete_title">Confirm deletions</string> <!-- Preference summary for whether the user should be prompted form confirmation when deleting images --> <string name="pref_gallery_confirm_delete_summary">Show confirmation before deleting a picture or video</string> <!-- Details stuff --> <!-- Do not translate --> <string name="details_title_text">myvideo</string> <!-- Do not translate --> <string name="details_tags_text">monster</string> <!-- Do not translate --> <string name="details_category_label">Category:</string> <!-- Do not translate --> <string name="details_description_label">Description:</string> <!-- Do not translate --> <string name="details_publicView_text">Public</string> <!-- Do not translate --> <string name="details_tags_label">Tags:</string> <!-- Do not translate --> <string name="details_description_text">testdescription</string> <!-- Do not translate --> <string name="details_title_label">Title:</string> <!-- Do not translate --> <string name="details_save_text">Save</string> <!-- Do not translate --> <string name="details_language_label">Language:</string> <!-- Do not translate --> <string name="details_privateView_text">Private</string> <!-- Title of Details dialog --> <string name="details_panel_title">Details</string> <!-- Label in message of Details dialog --> <string name="details_file_size">File size:</string> <!-- Label in message of Details dialog --> <string name="details_image_resolution">Resolution:</string> <!-- Label in message of Details dialog --> <string name="details_duration">Duration:</string> <!-- Label in message of Details dialog --> <string name="details_date_taken">Date taken:</string> <!-- Label in message of Details dialog --> <string name="details_frame_rate">Frame rate:</string> <!-- Label in message of Details dialog --> <string name="details_bit_rate">Bit rate:</string> <!-- Label in message of Details dialog --> <string name="details_codec">Codec:</string> <!-- Label in message of Details dialog --> <string name="details_format">Format:</string> <!-- Used to format image dimensions in Details dialog. e.g. 64 x 64 --> <string name="details_dimension_x">%1$d x %2$d</string> <!-- Used to format short video duration in Details dialog. minutes:seconds e.g. 00:30 --> <string name="details_ms">%1$02d:%2$02d</string> <!-- Used to format video duration in Details dialog. hours:minutes:seconds e.g. 0:21:30 --> <string name="details_hms">%1$d:%2$02d:%3$02d</string> <!-- Unit of measure in the Details dialog frames per second. e.g. 20 fps --> <string name="details_fps">%1$d fps</string> <!-- Unit of measure in the Details dialog K bits per second. e.g. 192 Kbps --> <string name="details_kbps">%1$d Kbps</string> <!-- Unit of measure in the Details dialog M bits per second. e.g. 2.3 Mbps --> <string name="details_mbps">%1$g Mbps</string> <!-- Details dialog "OK" button. Dismisses dialog. --> <string name="details_ok">OK</string> <!-- Text of context menu when an image is selected --> <string name="context_menu_header">Picture options</string> <!-- Text of context menu when a video is selected --> <string name="video_context_menu_header">Video options</string> <!-- Hint that appears when cropping an image with more than one face --> <string name="multiface_crop_help">Tap a face to begin.</string> <!-- Activity title when in the image gallery to see pictures --> <string name="photos_gallery_title">Gallery</string> <!-- Activity title when in the image gallery to select a picture --> <string name="pick_photos_gallery_title">Select picture</string> <!-- Activity title when in the image gallery to see videos --> <string name="videos_gallery_title">Gallery</string> <!-- Activity title when in the image gallery to select a video --> <string name="pick_videos_gallery_title">Select video</string> <!-- onscreen text indicating the progress of generating thumbnails. Basically some number followed by the word "remaining" --> <string name="loading_progress_format_string"><xliff:g id="counter">%d</xliff:g> remaining</string> <!-- Displayed in the title of the dialog for things to do with a picture that is to be sent to another application: --> <string name="sendImage">Share picture via</string> <!-- Displayed in the title of the dialog for things to do with a picture that is to be "set as" (e.g. set as contact photo or set as wallpaper) --> <string name="setImage">Set picture as</string> <!-- Displayed in the title of the dialog for things to do with a video that is to be sent to another application. --> <string name="sendVideo">Share video via</string> <!-- Activity label. This might show up in the activity-picker --> <string name="movieviewlabel">Movies</string> <!-- shown in the video player view while the video is being loaded, before it starts playing --> <string name="loading_video">Loading video\u2026</string> <!-- Low-memory dialog title --> <string name="spaceIsLow_title">Space is low</string> <!-- Low-memory dialog message --> <string name="spaceIsLow_content">Your SD card is running out of space. Change the quality setting or delete items from Gallery.</string> <!-- Movie View Resume Playing dialog title --> <string name="resume_playing_title">Resume video</string> <!-- Movie View Start Playing dialog title --> <string name="resume_playing_message">Resume playing from %s ?</string> <!-- Movie View Start Playing button "Resume from bookmark" --> <string name="resume_playing_resume">Resume playing</string> <!-- Movie View Start Playing button "Beginning" --> <string name="resume_playing_restart">Start over</string> <!-- Title for picture frame gadget to show in list of all available gadgets --> <string name="gadget_title">Picture frame</string> <!-- Video Camera format string for new video files. Passed to java.text.SimpleDateFormat. Do not localize --> <string name="video_file_name_format" translatable="false">"'video'-yyyy-MM-dd-HH-mm-ss"</string> <!-- Title for the file information dialog --> <string name="file_info_title">File info:</string> <!-- The video is execeed the size limit of a MMS, and suggest user to record a shorter length clip --> <string name="video_exceed_mms_limit">The video you recorded is too large to send via MMS. Try recording a shorter length clip.</string> <!-- Displayed as a toast when a video file is too large to attach to a Gmail message. --> <string name="too_large_to_attach">File too large to attach.</string> </resources> diff --git a/src/com/android/camera/MenuHelper.java b/src/com/android/camera/MenuHelper.java index a88f020..c8ca584 100644 --- a/src/com/android/camera/MenuHelper.java +++ b/src/com/android/camera/MenuHelper.java @@ -100,651 +100,653 @@ public class MenuHelper { public void run(MenuCallback r); } public interface MenuCallback { public void run(Uri uri, ImageManager.IImage image); } private static void closeSilently(Closeable target) { try { if (target != null) target.close(); } catch (Throwable t) { // ignore all exceptions, that's what silently means } } public static long getImageFileSize(ImageManager.IImage image) { java.io.InputStream data = image.fullSizeImageData(); if (data == null) return -1; try { return data.available(); } catch (java.io.IOException ex) { return -1; } finally { closeSilently(data); } } // This is a hack before we find a solution to pass a permission to other // applications. See bug #1735149. // Checks if the URI starts with "content://mms". public static boolean isMMSUri(Uri uri) { return (uri != null) && uri.getScheme().equals("content") && uri.getAuthority().equals("mms"); } public static void enableShareMenuItem(Menu menu, boolean enabled) { MenuItem item = menu.findItem(MENU_IMAGE_SHARE); if (item != null) { item.setVisible(enabled); item.setEnabled(enabled); } } static MenuItemsResult addImageMenuItems( Menu menu, int inclusions, final boolean isImage, final Activity activity, final Handler handler, final Runnable onDelete, final MenuInvoker onInvoke) { final ArrayList<MenuItem> requiresWriteAccessItems = new ArrayList<MenuItem>(); final ArrayList<MenuItem> requiresNoDrmAccessItems = new ArrayList<MenuItem>(); if (isImage && ((inclusions & INCLUDE_ROTATE_MENU) != 0)) { SubMenu rotateSubmenu = menu.addSubMenu(IMAGE_SAVING_ITEM, MENU_IMAGE_ROTATE, 40, R.string.rotate).setIcon(android.R.drawable.ic_menu_rotate); // Don't show the rotate submenu if the item at hand is read only // since the items within the submenu won't be shown anyway. This is // really a framework bug in that it shouldn't show the submenu if // the submenu has no visible items. requiresWriteAccessItems.add(rotateSubmenu.getItem()); if (rotateSubmenu != null) { requiresWriteAccessItems.add(rotateSubmenu.add(0, MENU_IMAGE_ROTATE_LEFT, 50, R.string.rotate_left).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null || image.isReadonly()) return; image.rotateImageBy(-90); } }); return true; } }).setAlphabeticShortcut('l')); requiresWriteAccessItems.add(rotateSubmenu.add(0, MENU_IMAGE_ROTATE_RIGHT, 60, R.string.rotate_right).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null || image.isReadonly()) return; image.rotateImageBy(90); } }); return true; } }).setAlphabeticShortcut('r')); } } if (isImage && ((inclusions & INCLUDE_CROP_MENU) != 0)) { MenuItem autoCrop = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_CROP, 73, R.string.camera_crop).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (u == null) return; Intent cropIntent = new Intent(); cropIntent.setClass(activity, CropImage.class); cropIntent.setData(u); activity.startActivityForResult(cropIntent, RESULT_COMMON_MENU_CROP); } }); return true; } }); autoCrop.setIcon(android.R.drawable.ic_menu_crop); requiresWriteAccessItems.add(autoCrop); } if (isImage && ((inclusions & INCLUDE_SET_MENU) != 0)) { MenuItem setMenu = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_SET, 75, R.string.camera_set); setMenu.setIcon(android.R.drawable.ic_menu_set_as); setMenu.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (u == null || image == null) return; if (Config.LOGV) Log.v(TAG, "in callback u is " + u + "; mime type is " + image.getMimeType()); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA); intent.setDataAndType(u, image.getMimeType()); intent.putExtra("mimeType", image.getMimeType()); activity.startActivity(Intent.createChooser(intent, activity.getText(R.string.setImage))); } }); return true; } }); } if ((inclusions & INCLUDE_SHARE_MENU) != 0) { if (Config.LOGV) Log.v(TAG, ">>>>> add share"); MenuItem item1 = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_SHARE, 10, R.string.camera_share).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null) return; if (!isImage && getImageFileSize(image) > SHARE_FILE_LENGTH_LIMIT ) { Toast.makeText(activity, R.string.too_large_to_attach, Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); String mimeType = image.getMimeType(); intent.setType(mimeType); intent.putExtra(Intent.EXTRA_STREAM, u); boolean isImage = ImageManager.isImageMimeType(mimeType); try { activity.startActivity(Intent.createChooser(intent, activity.getText( isImage ? R.string.sendImage : R.string.sendVideo))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(activity, isImage ? R.string.no_way_to_share_image : R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } }); return true; } }); item1.setIcon(android.R.drawable.ic_menu_share); MenuItem item = item1; requiresNoDrmAccessItems.add(item); } if ((inclusions & INCLUDE_DELETE_MENU) != 0) { MenuItem deleteItem = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_TOSS, 70, R.string.camera_toss); requiresWriteAccessItems.add(deleteItem); deleteItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { deleteImpl(activity, onDelete, isImage); return true; } }) .setAlphabeticShortcut('d') .setIcon(android.R.drawable.ic_menu_delete); } if ((inclusions & INCLUDE_DETAILS_MENU) != 0) { MenuItem detailsMenu = menu.add(0, 0, 80, R.string.details).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null) return; AlertDialog.Builder builder = new AlertDialog.Builder(activity); final View d = View.inflate(activity, R.layout.detailsview, null); ImageView imageView = (ImageView) d.findViewById(R.id.details_thumbnail_image); imageView.setImageBitmap(image.miniThumbBitmap()); TextView textView = (TextView) d.findViewById(R.id.details_image_title); textView.setText(image.getDisplayName()); long length = getImageFileSize(image); String lengthString = lengthString = length < 0 ? "" : android.text.format.Formatter.formatFileSize(activity, length); ((TextView)d.findViewById(R.id.details_file_size_value)) .setText(lengthString); int dimensionWidth = 0; int dimensionHeight = 0; if (isImage) { dimensionWidth = image.getWidth(); dimensionHeight = image.getHeight(); d.findViewById(R.id.details_duration_row).setVisibility(View.GONE); d.findViewById(R.id.details_frame_rate_row).setVisibility(View.GONE); d.findViewById(R.id.details_bit_rate_row).setVisibility(View.GONE); d.findViewById(R.id.details_format_row).setVisibility(View.GONE); d.findViewById(R.id.details_codec_row).setVisibility(View.GONE); } else { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setMode(MediaMetadataRetriever.MODE_GET_METADATA_ONLY); retriever.setDataSource(image.getDataPath()); try { dimensionWidth = Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)); dimensionHeight = Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); } catch (NumberFormatException e) { dimensionWidth = 0; dimensionHeight = 0; } try { int durationMs = Integer.parseInt(retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_DURATION)); String durationValue = formatDuration( activity, durationMs); ((TextView)d.findViewById(R.id.details_duration_value)) .setText(durationValue); } catch (NumberFormatException e) { d.findViewById(R.id.details_frame_rate_row) .setVisibility(View.GONE); } try { String frame_rate = String.format( activity.getString(R.string.details_fps), Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_FRAME_RATE))); ((TextView)d.findViewById(R.id.details_frame_rate_value)) .setText(frame_rate); } catch (NumberFormatException e) { d.findViewById(R.id.details_frame_rate_row) .setVisibility(View.GONE); } try { long bitRate = Long.parseLong(retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_BIT_RATE)); String bps; if (bitRate < 1000000) { bps = String.format( activity.getString(R.string.details_kbps), bitRate / 1000); } else { bps = String.format( activity.getString(R.string.details_mbps), ((double) bitRate) / 1000000.0); } ((TextView)d.findViewById(R.id.details_bit_rate_value)) .setText(bps); } catch (NumberFormatException e) { d.findViewById(R.id.details_bit_rate_row) .setVisibility(View.GONE); } String format = retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_FORMAT); ((TextView)d.findViewById(R.id.details_format_value)) .setText(format); String codec = retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_CODEC); if (codec == null) { d.findViewById(R.id.details_codec_row). setVisibility(View.GONE); } else { ((TextView)d.findViewById(R.id.details_codec_value)) .setText(codec); } } catch(RuntimeException ex) { // Assume this is a corrupt video file. } finally { try { retriever.release(); } catch (RuntimeException ex) { // Ignore failures while cleaning up. } } } String dimensionsString = String.format( activity.getString(R.string.details_dimension_x), dimensionWidth, dimensionHeight); ((TextView)d.findViewById(R.id.details_resolution_value)) .setText(dimensionsString); String dateString = ""; long dateTaken = image.getDateTaken(); if (dateTaken != 0) { java.util.Date date = new java.util.Date(image.getDateTaken()); java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(); dateString = dateFormat.format(date); ((TextView)d.findViewById(R.id.details_date_taken_value)) .setText(dateString); } else { d.findViewById(R.id.details_date_taken_row) .setVisibility(View.GONE); } builder.setNeutralButton(R.string.details_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setIcon(android.R.drawable.ic_dialog_info) .setTitle(R.string.details_panel_title) .setView(d) .show(); } }); return true; } }); detailsMenu.setIcon(R.drawable.ic_menu_view_details); } if ((!isImage) && ((inclusions & INCLUDE_VIEWPLAY_MENU) != 0)) { menu.add(VIDEO_SAVING_ITEM, MENU_VIDEO_PLAY, 0, R.string.video_play) .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri uri, IImage image) { if (image != null) { Intent intent = new Intent(Intent.ACTION_VIEW, image.fullSizeImageUri()); activity.startActivity(intent); } }}); return true; } }); } return new MenuItemsResult() { public void gettingReadyToOpen(Menu menu, ImageManager.IImage image) { // protect against null here. this isn't strictly speaking required // but if a client app isn't handling sdcard removal properly it // could happen if (image == null) { return; } boolean readOnly = image.isReadonly(); boolean isDrm = image.isDrm(); if (Config.LOGV) Log.v(TAG, "readOnly: " + readOnly + "; drm: " + isDrm); for (MenuItem item: requiresWriteAccessItems) { if (Config.LOGV) Log.v(TAG, "item is " + item.toString()); item.setVisible(!readOnly); item.setEnabled(!readOnly); } for (MenuItem item: requiresNoDrmAccessItems) { if (Config.LOGV) Log.v(TAG, "item is " + item.toString()); item.setVisible(!isDrm); item.setEnabled(!isDrm); } } public void aboutToCall(MenuItem menu, ImageManager.IImage image) { } }; } static void deletePhoto(Activity activity, Runnable onDelete) { deleteImpl(activity, onDelete, true); } static void deleteVideo(Activity activity, Runnable onDelete) { deleteImpl(activity, onDelete, false); } static void deleteImage(Activity activity, Runnable onDelete, IImage image) { if (image != null) { deleteImpl(activity, onDelete, ImageManager.isImage(image)); } } private static void deleteImpl(Activity activity, final Runnable onDelete, boolean isPhoto) { boolean confirm = android.preference.PreferenceManager.getDefaultSharedPreferences(activity).getBoolean("pref_gallery_confirm_delete_key", true); if (!confirm) { if (onDelete != null) onDelete.run(); } else { displayDeleteDialog(activity, onDelete, isPhoto); } } public static void displayDeleteDialog(Activity activity, final Runnable onDelete, boolean isPhoto) { android.app.AlertDialog.Builder b = new android.app.AlertDialog.Builder(activity); b.setIcon(android.R.drawable.ic_dialog_alert); b.setTitle(R.string.confirm_delete_title); b.setMessage(isPhoto? R.string.confirm_delete_message : R.string.confirm_delete_video_message); b.setPositiveButton(android.R.string.ok, new android.content.DialogInterface.OnClickListener() { public void onClick(android.content.DialogInterface v, int x) { if (onDelete != null) onDelete.run(); } }); b.setNegativeButton(android.R.string.cancel, new android.content.DialogInterface.OnClickListener() { public void onClick(android.content.DialogInterface v, int x) { } }); b.create().show(); } static void addSwitchModeMenuItem(Menu menu, final Activity activity, final boolean switchToVideo) { int group = switchToVideo ? MenuHelper.IMAGE_MODE_ITEM : MenuHelper.VIDEO_MODE_ITEM; int labelId = switchToVideo ? R.string.switch_to_video_lable : R.string.switch_to_camera_lable; int iconId = switchToVideo ? R.drawable.ic_menu_camera_video_view : android.R.drawable.ic_menu_camera; MenuItem item = menu.add(group, MENU_SWITCH_CAMERA_MODE, 0, labelId).setOnMenuItemClickListener( new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { String action = switchToVideo ? MediaStore.INTENT_ACTION_VIDEO_CAMERA : MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA; Intent intent = new Intent(action); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); activity.startActivity(intent); return true; } }); item.setIcon(iconId); } static void gotoStillImageCapture(Activity activity) { Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Log.e(TAG, "Could not start still image capture activity", e); } } static void gotoCameraImageGallery(Activity activity) { gotoGallery(activity, R.string.gallery_camera_bucket_name, ImageManager.INCLUDE_IMAGES); } static void gotoCameraVideoGallery(Activity activity) { gotoGallery(activity, R.string.gallery_camera_videos_bucket_name, ImageManager.INCLUDE_VIDEOS); } static private void gotoGallery(Activity activity, int windowTitleId, int mediaTypes) { Uri target = Images.Media.INTERNAL_CONTENT_URI.buildUpon().appendQueryParameter("bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build(); Intent intent = new Intent(Intent.ACTION_VIEW, target); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("windowTitle", activity.getString(windowTitleId)); intent.putExtra("mediaTypes", mediaTypes); // Request unspecified so that we match the current camera orientation rather than // matching the "flip orientation" preference. // Disabled because people don't care for it. Also it's // not as compelling now that we have implemented have quick orientation flipping. // intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, // android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Log.e(TAG, "Could not start gallery activity", e); } } static void addCapturePictureMenuItems(Menu menu, final Activity activity) { - menu.add(0, MENU_CAPTURE_PICTURE, 1, R.string.capture_picture) - .setOnMenuItemClickListener( - new MenuItem.OnMenuItemClickListener() { - public boolean onMenuItemClick(MenuItem item) { - Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA); - intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - try { - activity.startActivity(intent); - } catch (android.content.ActivityNotFoundException e) { - // Ignore exception - } - return true; - } - }) - .setIcon(android.R.drawable.ic_menu_camera); + //GILL MARKED + //menu.add(0, MENU_CAPTURE_PICTURE, 1, R.string.capture_picture) + // .setOnMenuItemClickListener( + // new MenuItem.OnMenuItemClickListener() { + // public boolean onMenuItemClick(MenuItem item) { + // Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA); + // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + // try { + // activity.startActivity(intent); + // } catch (android.content.ActivityNotFoundException e) { + // // Ignore exception + // } + // return true; + // } + //}) + //.setIcon(android.R.drawable.ic_menu_camera); } static void addCaptureVideoMenuItems(Menu menu, final Activity activity) { - menu.add(0, MENU_CAPTURE_VIDEO, 2, R.string.capture_video) - .setOnMenuItemClickListener( - new MenuItem.OnMenuItemClickListener() { - public boolean onMenuItemClick(MenuItem item) { - Intent intent = new Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA); - intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - try { - activity.startActivity(intent); - } catch (android.content.ActivityNotFoundException e) { - // Ignore exception - } - return true; - } - }) - .setIcon(R.drawable.ic_menu_camera_video_view); + //GILL MARKED + //menu.add(0, MENU_CAPTURE_VIDEO, 2, R.string.capture_video) + // .setOnMenuItemClickListener( + // new MenuItem.OnMenuItemClickListener() { + // public boolean onMenuItemClick(MenuItem item) { + // Intent intent = new Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA); + // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + // try { + // activity.startActivity(intent); + // } catch (android.content.ActivityNotFoundException e) { + // // Ignore exception + // } + // return true; + // } + //}) + //.setIcon(R.drawable.ic_menu_camera_video_view); } static void addCaptureMenuItems(Menu menu, final Activity activity) { addCapturePictureMenuItems(menu, activity); addCaptureVideoMenuItems(menu, activity); } static MenuItem addFlipOrientation(Menu menu, final Activity activity, final SharedPreferences prefs) { // position 41 after rotate // D return menu .add(Menu.CATEGORY_SECONDARY, 304, 41, R.string.flip_orientation) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // Check what our actual orientation is int current = activity.getResources().getConfiguration().orientation; int newOrientation = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; if (current == Configuration.ORIENTATION_LANDSCAPE) { newOrientation = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; } SharedPreferences.Editor editor = prefs.edit(); editor.putInt("nuorientation", newOrientation); editor.commit(); requestOrientation(activity, prefs, true); return true; } }) .setIcon(android.R.drawable.ic_menu_always_landscape_portrait); } static void requestOrientation(Activity activity, SharedPreferences prefs) { requestOrientation(activity, prefs, false); } static private void requestOrientation(Activity activity, SharedPreferences prefs, boolean ignoreIntentExtra) { // Disable orientation for now. If it is set to SCREEN_ORIENTATION_SENSOR, // a duplicated orientation will be observed. return; } static void setFlipOrientationEnabled(Activity activity, MenuItem flipItem) { int keyboard = activity.getResources().getConfiguration().hardKeyboardHidden; flipItem.setEnabled(keyboard != android.content.res.Configuration.HARDKEYBOARDHIDDEN_NO); } public static String formatDuration(final Activity activity, int durationMs) { int duration = durationMs / 1000; int h = duration / 3600; int m = (duration - h * 3600) / 60; int s = duration - (h * 3600 + m * 60); String durationValue; if (h == 0) { durationValue = String.format( activity.getString(R.string.details_ms), m, s); } else { durationValue = String.format( activity.getString(R.string.details_hms), h, m, s); } return durationValue; } public static void showStorageToast(Activity activity) { showStorageToast(activity, calculatePicturesRemaining()); } public static void showStorageToast(Activity activity, int remaining) { String noStorageText = null; if (remaining == MenuHelper.NO_STORAGE_ERROR) { String state = Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING) { noStorageText = activity.getString(R.string.preparing_sd); } else { noStorageText = activity.getString(R.string.no_storage); } } else if (remaining < 1) { noStorageText = activity.getString(R.string.not_enough_space); } if (noStorageText != null) { Toast.makeText(activity, noStorageText, 5000).show(); } } public static int calculatePicturesRemaining() { try { if (!ImageManager.hasStorage()) { return NO_STORAGE_ERROR; } else { String storageDirectory = Environment.getExternalStorageDirectory().toString(); StatFs stat = new StatFs(storageDirectory); float remaining = ((float)stat.getAvailableBlocks() * (float)stat.getBlockSize()) / 400000F; return (int)remaining; } } catch (Exception ex) { // if we can't stat the filesystem then we don't know how many // pictures are remaining. it might be zero but just leave it // blank since we really don't know. return CANNOT_STAT_ERROR; } } } diff --git a/src/com/android/camera/MovieView.java b/src/com/android/camera/MovieView.java index bf0e6ca..80b485e 100644 --- a/src/com/android/camera/MovieView.java +++ b/src/com/android/camera/MovieView.java @@ -1,255 +1,263 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.pm.ActivityInfo; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.provider.MediaStore.Video; import android.view.View; import android.widget.MediaController; import android.widget.VideoView; public class MovieView extends Activity implements MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener { private static final String TAG = "MovieView"; // Copied from MediaPlaybackService in the Music Player app. Should be public, but isn't. private static final String SERVICECMD = "com.android.music.musicservicecommand"; private static final String CMDNAME = "command"; private static final String CMDPAUSE = "pause"; private VideoView mVideoView; private View mProgressView; private boolean mFinishOnCompletion; private Uri mUri; // State maintained for proper onPause/OnResume behaviour. private int mPositionWhenPaused = -1; private boolean mWasPlayingWhenPaused = false; public MovieView() { } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.movie_view); mVideoView = (VideoView) findViewById(R.id.surface_view); mProgressView = findViewById(R.id.progress_indicator); - Intent intent = getIntent(); - if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { + Intent intent = getIntent(); + /* + if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); if (orientation != getRequestedOrientation()) { setRequestedOrientation(orientation); } } + */ + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); mFinishOnCompletion = intent.getBooleanExtra(MediaStore.EXTRA_FINISH_ON_COMPLETION, true); mUri = intent.getData(); // For streams that we expect to be slow to start up, show a // progress spinner until playback starts. String scheme = mUri.getScheme(); if ("http".equalsIgnoreCase(scheme) || "rtsp".equalsIgnoreCase(scheme)) { mHandler.postDelayed(mPlayingChecker, 250); } else { mProgressView.setVisibility(View.GONE); } mVideoView.setOnErrorListener(this); mVideoView.setOnCompletionListener(this); mVideoView.setVideoURI(mUri); mVideoView.setMediaController(new MediaController(this)); mVideoView.requestFocus(); // make the video view handle keys for seeking and pausing Intent i = new Intent(SERVICECMD); i.putExtra(CMDNAME, CMDPAUSE); sendBroadcast(i); { final Integer bookmark = getBookmark(); if (bookmark != null) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.resume_playing_title); builder.setMessage(String.format( getString(R.string.resume_playing_message), MenuHelper.formatDuration(this, bookmark))); builder.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { finish(); }}); builder.setPositiveButton(R.string.resume_playing_resume, new OnClickListener(){ public void onClick(DialogInterface dialog, int which) { mVideoView.seekTo(bookmark); mVideoView.start(); }}); builder.setNegativeButton(R.string.resume_playing_restart, new OnClickListener(){ public void onClick(DialogInterface dialog, int which) { mVideoView.start(); }}); builder.show(); } else { mVideoView.start(); } } } - +/* + @Override + public void onConfigurationChanged(android.content.res.Configuration newConfig) { + super.onConfigurationChanged(newConfig); + } +*/ private static boolean uriSupportsBookmarks(Uri uri) { String scheme = uri.getScheme(); String authority = uri.getAuthority(); return ("content".equalsIgnoreCase(scheme) && MediaStore.AUTHORITY.equalsIgnoreCase(authority)); } private Integer getBookmark() { if (!uriSupportsBookmarks(mUri)) { return null; } String[] projection = new String[]{Video.VideoColumns.DURATION, Video.VideoColumns.BOOKMARK}; try { Cursor cursor = getContentResolver().query(mUri, projection, null, null, null); if (cursor != null) { try { if ( cursor.moveToFirst() ) { int duration = getCursorInteger(cursor, 0); int bookmark = getCursorInteger(cursor, 1); final int ONE_MINUTE = 60 * 1000; final int TWO_MINUTES = 2 * ONE_MINUTE; final int FIVE_MINUTES = 5 * ONE_MINUTE; if ((bookmark < TWO_MINUTES) || (duration < FIVE_MINUTES) || (bookmark > (duration - ONE_MINUTE))) { return null; } return new Integer(bookmark); } } finally { cursor.close(); } } } catch (SQLiteException e) { // ignore } return null; } private int getCursorInteger(Cursor cursor, int index) { try { return cursor.getInt(index); } catch (SQLiteException e) { return 0; } catch (NumberFormatException e) { return 0; } } private void setBookmark(int bookmark) { if (!uriSupportsBookmarks(mUri)) { return; } ContentValues values = new ContentValues(); values.put(Video.VideoColumns.BOOKMARK, Integer.toString(bookmark)); try { getContentResolver().update(mUri, values, null, null); } catch (SecurityException ex) { // Ignore, can happen if we try to set the bookmark on a read-only resource // such as a video attached to GMail. } catch (SQLiteException e) { // ignore. can happen if the content doesn't support a bookmark column. } catch (UnsupportedOperationException e) { - // ignore. can happen if the external volume is already detached. + // ignore. can happen if the external volume is already detached.getIntExtragetIntExtra } } @Override public void onPause() { mHandler.removeCallbacksAndMessages(null); setBookmark(mVideoView.getCurrentPosition()); mPositionWhenPaused = mVideoView.getCurrentPosition(); mWasPlayingWhenPaused = mVideoView.isPlaying(); mVideoView.stopPlayback(); super.onPause(); } @Override public void onResume() { if (mPositionWhenPaused >= 0) { mVideoView.setVideoURI(mUri); mVideoView.seekTo(mPositionWhenPaused); if (mWasPlayingWhenPaused) { mVideoView.start(); } } super.onResume(); } Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { } }; Runnable mPlayingChecker = new Runnable() { public void run() { if (mVideoView.isPlaying()) { mProgressView.setVisibility(View.GONE); } else { mHandler.postDelayed(mPlayingChecker, 250); } } }; public boolean onError(MediaPlayer player, int arg1, int arg2) { mHandler.removeCallbacksAndMessages(null); mProgressView.setVisibility(View.GONE); return false; } public void onCompletion(MediaPlayer mp) { if (mFinishOnCompletion) { finish(); } } }
brunsky/WS171-packages-apps-Camera
faf2f17dcde317466d2d44523ec5c56795a8dcf6
AI 150759: Import updated Cupcake translations.
diff --git a/res/values-da/strings.xml b/res/values-da/strings.xml index afbde5b..58084b3 100644 --- a/res/values-da/strings.xml +++ b/res/values-da/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Alle billeder"</string> <string name="all_videos">"Alle videoer"</string> <string name="camera_label">"Kamera"</string> <string name="video_camera_label">"Videokamera"</string> <string name="gallery_picker_label">"Galleri"</string> <string name="gallery_camera_bucket_name">"Kamerabilleder"</string> <string name="gallery_camera_videos_bucket_name">"Kameravideoer"</string> <string name="switch_to_video_lable">"Skift til video"</string> <string name="switch_to_camera_lable">"Skift til kamera"</string> <string name="crop_label">"Beskær billede"</string> <string name="view_label">"Vis billede"</string> <string name="preferences_label">"Kameraindstillinger"</string> <string name="wait">"Vent ..."</string> <string name="no_storage">"Indsæt et SD-kort, inden du bruger kameraet."</string> <string name="not_enough_space">"Dit SD-kort er fuldt."</string> <string name="preparing_sd">"Forbereder SD-kort ..."</string> <string name="wallpaper">"Indstiller tapet. Vent et øjeblik ..."</string> <string name="savingImage">"Gemmer billede ..."</string> <string name="runningFaceDetection">"Vent ..."</string> <string name="flip_orientation">"Skift retning"</string> <string name="settings">"Indstillinger"</string> <string name="view">"Vis"</string> <string name="details">"Detaljer"</string> <string name="rotate">"Roter"</string> <string name="rotate_left">"Roter til venstre"</string> <string name="rotate_right">"Roter til højre"</string> <string name="slide_show">"Diasshow"</string> - <string name="capture_picture">"Fotografer billede"</string> - <string name="capture_video">"Fotografer video"</string> + <string name="capture_picture">"Tag billede"</string> + <string name="capture_video">"Optag video"</string> <string name="crop_save_text">"Gem"</string> <string name="crop_discard_text">"Kassér"</string> <string name="confirm_delete_title">"Slet"</string> <string name="confirm_delete_message">"Billedet slettes."</string> <string name="confirm_delete_video_message">"Videoen slettes."</string> <string name="camera_toss">"Slet"</string> <string name="camera_gallery">"Galleri"</string> <string name="camera_share">"Del"</string> <string name="camera_set">"Indstil som"</string> <string name="camera_play">"Afspil"</string> <string name="camera_attach">"Vedhæft"</string> <string name="camera_cancel">"Annuller"</string> <string name="camera_crop">"Beskær"</string> <string name="camera_tossing">"Sletter ..."</string> <string name="no_way_to_share_image">"Dette billede kan ikke deles."</string> <string name="no_way_to_share_video">"Denne video kan ikke deles."</string> <string name="video_play">"Afspil"</string> <string name="camera_gallery_photos_text">"Galleri"</string> <string name="camera_pick_wallpaper">"Billeder"</string> <string name="camera_setas_wallpaper">"Tapet"</string> <string name="pref_gallery_category">"Generelle indstillinger"</string> <string name="pref_slideshow_category">"Diasshowindstillinger"</string> <string name="pref_camera_general_settings_category">"Generelle indstillinger"</string> <string name="pref_gallery_size_title">"Visningsstørrelse"</string> <string name="pref_gallery_size_summary">"Vælg, hvilken størrelse billeder og videoer skal vises i"</string> <string name="pref_gallery_size_dialogtitle">"Billedstørrelse"</string> <string-array name="pref_gallery_size_choices"> <item>"Stor"</item> <item>"Lille"</item> </string-array> <string name="pref_gallery_sort_title">"Sorter rækkefølge"</string> <string name="pref_gallery_sort_summary">"Vælg rækkefølge på billeder og videoer"</string> <string name="pref_gallery_sort_dialogtitle">"Sorter billeder"</string> <string-array name="pref_gallery_sort_choices"> <item>"Nyeste først"</item> <item>"Nyeste sidst"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Diasshowinterval"</string> <string name="pref_gallery_slideshow_interval_summary">"Vælg, hvor længe hvert dias skal vises i showet"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Diasshowinterval"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 sekunder"</item> <item>"3 sekunder"</item> <item>"4 sekunder"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Diasshowovergang"</string> <string name="pref_gallery_slideshow_transition_summary">"Vælg den effekt, der skal bruges, når man går fra et dias til det næste"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Diasshowovergang"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ton ind og ud"</item> <item>"Glid til venstre – højre"</item> <item>"Glid op – ned"</item> <item>"Tilfældigt udvalg"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Gentag diasshow"</string> <string name="pref_gallery_slideshow_repeat_summary">"Afspil diasshow mere end en gang"</string> <string name="pref_gallery_slideshow_shuffle_title">"Bland dias"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Vis billeder i tilfældig rækkefølge"</string> - <string name="pref_camera_recordlocation_title">"Gem placeringer i billeder"</string> + <string name="pref_camera_recordlocation_title">"Gem plac. i billeder"</string> <string name="pref_camera_recordlocation_summary">"Registrer placering i billeddata"</string> <string name="pref_camera_videoquality_category">"Videokvalitet"</string> <string name="pref_camera_videoquality_title">"Vælg videokvalitet"</string> <string name="pref_camera_videoquality_entry_0">"Lav (til MMS-beskeder)"</string> <string name="pref_camera_videoquality_entry_1">"Høj (til SD-kort)"</string> <string name="pref_camera_videoquality_dialogtitle">"Videokvalitet"</string> <string name="camerasettings">"Indstillinger"</string> <string name="image_gallery_NoImageView_text">"Der blev ikke fundet nogen medier."</string> <string name="pref_gallery_confirm_delete_title">"Bekræft sletninger"</string> <string name="pref_gallery_confirm_delete_summary">"Vis bekræftelse, inden der slettes et billede eller en video"</string> <string name="details_panel_title">"Detaljer"</string> <string name="details_file_size">"Filstørrelse:"</string> <string name="details_image_resolution">"Opløsning:"</string> <string name="details_duration">"Varighed:"</string> <string name="details_date_taken">"Dato taget:"</string> <string name="details_frame_rate">"Rammefrekvens"</string> <string name="details_bit_rate">"Bithastighed:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Billedvalgmuligheder"</string> <string name="video_context_menu_header">"Videovalgmuligheder"</string> <string name="multiface_crop_help">"Tryk på et ansigt for at begynde."</string> <string name="photos_gallery_title">"Galleri"</string> <string name="pick_photos_gallery_title">"Vælg billede"</string> <string name="videos_gallery_title">"Galleri"</string> <string name="pick_videos_gallery_title">"Vælg video"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> tilbage"</string> <string name="sendImage">"Del billede via"</string> <string name="setImage">"Indstil billedet som"</string> <string name="sendVideo">"Del video via"</string> <string name="movieviewlabel">"Film"</string> <string name="loading_video">"Indlæser video ..."</string> <string name="spaceIsLow_title">"Der er ikke så meget plads"</string> <string name="spaceIsLow_content">"Dit SD-kort er ved at løbe tør for plads. Skift kvalitetsindstillingerne, eller slet elementer fra Galleriet."</string> <string name="resume_playing_title">"Genoptag video"</string> <string name="resume_playing_message">"Genoptag afspilning fra %s ?"</string> <string name="resume_playing_resume">"Genoptag afspilning"</string> <string name="resume_playing_restart">"Start igen"</string> <string name="gadget_title">"Billedramme"</string> <string name="file_info_title">"Filoplysninger:"</string> <string name="video_exceed_mms_limit">"Den video, du optog, er for stor til at sende via MMS. Prøv at optage et klip af kortere varighed."</string> <string name="too_large_to_attach">"Filen er for stor til at vedhæfte."</string> </resources> diff --git a/res/values-el/strings.xml b/res/values-el/strings.xml index 663986a..3c089ce 100644 --- a/res/values-el/strings.xml +++ b/res/values-el/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Όλες οι εικόνες"</string> <string name="all_videos">"Όλα τα βίντεο"</string> - <string name="camera_label">"Φωτογραφική μηχανή"</string> - <string name="video_camera_label">"Βιντεοκάμερα"</string> + <string name="camera_label">"Φωτογ.μηχανή"</string> + <string name="video_camera_label">"Βιντεοκάμ."</string> <string name="gallery_picker_label">"Συλλογή"</string> <string name="gallery_camera_bucket_name">"Εικόνες φωτογραφικής μηχανής"</string> <string name="gallery_camera_videos_bucket_name">"Βίντεο φωτογραφικής μηχανής"</string> <string name="switch_to_video_lable">"Αλλαγή σε λειτουργία βίντεο"</string> <string name="switch_to_camera_lable">"Αλλαγή σε λειτουργία φωτογραφικής μηχανής"</string> <string name="crop_label">"Περικοπή εικόνας"</string> <string name="view_label">"Προβολή εικόνας"</string> <string name="preferences_label">"Ρυθμίσεις φωτογραφικής μηχανής"</string> <string name="wait">"Περιμένετε..."</string> <string name="no_storage">"Πριν χρησιμοποιήσετε τη φωτογραφική μηχανή, εισάγετε μία κάρτα SD."</string> <string name="not_enough_space">"Η κάρτα SD είναι πλήρης."</string> <string name="preparing_sd">"Προετοιμασία κάρτας SD…"</string> <string name="wallpaper">"Ρύθμιση ταπετσαρίας, περιμένετε..."</string> <string name="savingImage">"Αποθήκευση εικόνας..."</string> <string name="runningFaceDetection">"Περιμένετε..."</string> <string name="flip_orientation">"Αλλαγή προσανατολισμού"</string> <string name="settings">"Ρυθμίσεις"</string> <string name="view">"Προβολή"</string> <string name="details">"Λεπτομέρειες"</string> <string name="rotate">"Περιστροφή"</string> <string name="rotate_left">"Αριστερή περιστροφή"</string> <string name="rotate_right">"Δεξιά περιστροφή"</string> - <string name="slide_show">"Προβολή διαφανειών (slideshow)"</string> + <string name="slide_show">"Προβολή διαφανειών"</string> <string name="capture_picture">"Λήψη εικόνας"</string> <string name="capture_video">"Λήψη βίντεο"</string> <string name="crop_save_text">"Αποθήκευση"</string> <string name="crop_discard_text">"Απόρριψη"</string> <string name="confirm_delete_title">"Διαγραφή"</string> <string name="confirm_delete_message">"Η εικόνα θα διαγραφεί."</string> <string name="confirm_delete_video_message">"Το βίντεο θα διαγραφεί."</string> <string name="camera_toss">"Διαγραφή"</string> <string name="camera_gallery">"Συλλογή"</string> <string name="camera_share">"Κοινή χρήση"</string> <string name="camera_set">"Ορισμός ως"</string> <string name="camera_play">"Αναπαραγωγή"</string> <string name="camera_attach">"Επισύναψη"</string> <string name="camera_cancel">"Ακύρωση"</string> <string name="camera_crop">"Περικοπή"</string> <string name="camera_tossing">"Διαγραφή..."</string> <string name="no_way_to_share_image">"Δεν είναι δυνατή η κοινή χρήση αυτής της εικόνας."</string> <string name="no_way_to_share_video">"Δεν είναι δυνατή η κοινή χρήση αυτού του βίντεο."</string> <string name="video_play">"Αναπαραγωγή"</string> <string name="camera_gallery_photos_text">"Συλλογή"</string> <string name="camera_pick_wallpaper">"Εικόνες"</string> <string name="camera_setas_wallpaper">"Ταπετσαρία"</string> <string name="pref_gallery_category">"Γενικές ρυθμίσεις"</string> <string name="pref_slideshow_category">"Ρυθμίσεις προβολής διαφανειών (slideshow)"</string> <string name="pref_camera_general_settings_category">"Γενικές ρυθμίσεις"</string> <string name="pref_gallery_size_title">"Μέγεθος προβολής"</string> <string name="pref_gallery_size_summary">"Επιλέξτε το μέγεθος προβολής των εικόνων και των βίντεο"</string> <string name="pref_gallery_size_dialogtitle">"Μέγεθος εικόνας"</string> <string-array name="pref_gallery_size_choices"> <item>"Μεγάλο"</item> <item>"Μικρό"</item> </string-array> <string name="pref_gallery_sort_title">"Σειρά ταξινόμησης"</string> <string name="pref_gallery_sort_summary">"Επιλέξτε τη σειρά ταξινόμησης των εικόνων και των βίντεο"</string> <string name="pref_gallery_sort_dialogtitle">"Ταξινόμηση εικόνων"</string> <string-array name="pref_gallery_sort_choices"> <item>"Πρώτα οι πιο πρόσφατες"</item> <item>"Οι πιο πρόσφατες τελευταίες"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Διάστημα προβολής διαφανειών (slideshow)"</string> <string name="pref_gallery_slideshow_interval_summary">"Επιλέξτε πόση ώρα θα προβάλλεται κάθε διαφάνεια στην προβολή διαφανειών"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Διάστημα προβολής διαφανειών (slideshow)"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 δευτερόλεπτα"</item> <item>"3 δευτερόλεπτα"</item> <item>"4 δευτερόλεπτα"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Εναλλαγή προβολής διαφανειών (slideshow)"</string> - <string name="pref_gallery_slideshow_transition_summary">"Επιλέξτε το εφέ που θα χρησιμοποιηθεί κατά τη μετάβαση από τη μία διαφάνεια στην επόμενη"</string> + <string name="pref_gallery_slideshow_transition_summary">"Επιλ. του εφέ που θα χρησιμοποιηθεί κατά τη μετάβαση από μία διαφάνεια στην επόμενη"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Εναλλαγή προβολής διαφανειών (slideshow)"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Σταδιακή εμφάνιση &amp; εξαφάνιση"</item> <item>"Ολίσθηση αριστερά - δεξιά"</item> <item>"Ολίσθηση πάνω - κάτω"</item> <item>"Τυχαία επιλογή"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Επανάληψη προβολής διαφανειών (slideshow)"</string> - <string name="pref_gallery_slideshow_repeat_summary">"Αναπαραγωγή προβολής διαφανειών (slideshow) περισσότερες από μία φορά"</string> + <string name="pref_gallery_slideshow_repeat_summary">"Αναπαρ.προβ.διαφαν.περισσότ.από μία φορά"</string> <string name="pref_gallery_slideshow_shuffle_title">"Τυχαία αναπαραγωγή διαφανειών"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Εμφάνιση εικόνων με τυχαία σειρά"</string> <string name="pref_camera_recordlocation_title">"Αποθήκευση τοποθεσίας στις εικόνες"</string> <string name="pref_camera_recordlocation_summary">"Εγγραφή τοποθεσίας στα δεδομένα εικόνας"</string> <string name="pref_camera_videoquality_category">"Ποιότητα βίντεο"</string> <string name="pref_camera_videoquality_title">"Επιλογή ποιότητας βίντεο"</string> <string name="pref_camera_videoquality_entry_0">"Χαμηλή (για μηνύματα MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Υψηλή (για κάρτα SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Ποιότητα βίντεο"</string> <string name="camerasettings">"Ρυθμίσεις"</string> <string name="image_gallery_NoImageView_text">"Δεν βρέθηκαν μέσα."</string> <string name="pref_gallery_confirm_delete_title">"Επιβεβαίωση διαγραφών"</string> - <string name="pref_gallery_confirm_delete_summary">"Εμφάνιση μηνύματος επιβεβαίωσης πριν τη διαγραφή μιας εικόνας ή ενός βίντεο"</string> + <string name="pref_gallery_confirm_delete_summary">"Εμφ.μηνύμ.επιβεβ.πριν τη διαγρ.μιας εικόν.ή ενός βίντ."</string> <string name="details_panel_title">"Λεπτομέρειες"</string> <string name="details_file_size">"Μέγεθος αρχείου:"</string> <string name="details_image_resolution">"Ανάλυση:"</string> <string name="details_duration">"Διάρκεια:"</string> <string name="details_date_taken">"Ημερομηνία λήψης:"</string> <string name="details_frame_rate">"Ρυθμός καρέ:"</string> <string name="details_bit_rate">"Ρυθμός δεδομένων:"</string> <string name="details_codec">"Κωδικοποιητής:"</string> <string name="details_format">"Μορφή:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Επιλογές εικόνας"</string> <string name="video_context_menu_header">"Επιλογές βίντεο"</string> <string name="multiface_crop_help">"Πατήστε σε ένα πρόσωπο για να ξεκινήσετε."</string> <string name="photos_gallery_title">"Συλλογή"</string> <string name="pick_photos_gallery_title">"Επιλογή εικόνας"</string> <string name="videos_gallery_title">"Συλλογή"</string> <string name="pick_videos_gallery_title">"Επιλογή βίντεο"</string> <string name="loading_progress_format_string">"Απομένουν <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Κοινή χρήση εικόνας μέσω"</string> <string name="setImage">"Ορισμός εικόνας ως"</string> <string name="sendVideo">"Κοινή χρήση βίντεο μέσω"</string> <string name="movieviewlabel">"Ταινίες"</string> <string name="loading_video">"Φόρτωση βίντεο..."</string> <string name="spaceIsLow_title">"Ο διαθέσιμος χώρος είναι ελάχιστος"</string> <string name="spaceIsLow_content">"Ο διαθέσιμος χώρος στην κάρτα SD είναι ελάχιστος. Αλλάξτε τη ρύθμιση ποιότητας ή διαγράψτε στοιχεία από τη συλλογή."</string> <string name="resume_playing_title">"Συνέχιση βίντεο"</string> <string name="resume_playing_message">"Συνέχιση αναπαραγωγής από το %s;"</string> <string name="resume_playing_resume">"Συνέχιση αναπαραγωγής"</string> <string name="resume_playing_restart">"Έναρξη από την αρχή"</string> <string name="gadget_title">"Πλαίσιο εικόνας"</string> <string name="file_info_title">"Πληροφορίες αρχείου:"</string> <string name="video_exceed_mms_limit">"Το βίντεο που εγγράψατε είναι πολύ μεγάλο για να αποσταλεί μέσω μηνύματος MMS. Δοκιμάστε να εγγράψετε μικρότερου μεγέθους βίντεο."</string> <string name="too_large_to_attach">"Πολύ μεγάλο αρχείο για επισύναψη."</string> </resources> diff --git a/res/values-es-rUS/strings.xml b/res/values-es-rUS/strings.xml index a8b3b51..2e50c73 100644 --- a/res/values-es-rUS/strings.xml +++ b/res/values-es-rUS/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Todas las imágenes"</string> <string name="all_videos">"Todos los videos"</string> <string name="camera_label">"Cámara"</string> <string name="video_camera_label">"Cámara de video"</string> <string name="gallery_picker_label">"Galería"</string> <string name="gallery_camera_bucket_name">"Imágenes de la cámara"</string> <string name="gallery_camera_videos_bucket_name">"Videos de la cámara"</string> <string name="switch_to_video_lable">"Cambiar a video"</string> <string name="switch_to_camera_lable">"Cambiar a cámara"</string> <string name="crop_label">"Cortar la imagen"</string> <string name="view_label">"Ver imagen"</string> <string name="preferences_label">"Configuración de cámara"</string> <string name="wait">"Espera, por favor..."</string> <string name="no_storage">"Inserta una tarjeta SD antes de utilizar la cámara."</string> <string name="not_enough_space">"Tu tarjeta SD está llena."</string> <string name="preparing_sd">"Preparando la tarjeta SD..."</string> <string name="wallpaper">"Configurando papel tapiz. Espera, por favor..."</string> <string name="savingImage">"Guardando imagen..."</string> <string name="runningFaceDetection">"Espera, por favor..."</string> <string name="flip_orientation">"Girar la orientación"</string> <string name="settings">"Configuración"</string> <string name="view">"Ver"</string> <string name="details">"Detalles"</string> <string name="rotate">"Rotar"</string> <string name="rotate_left">"Rotar hacia la izquierda"</string> <string name="rotate_right">"Rotar hacia la derecha"</string> <string name="slide_show">"Presentación de diapositivas"</string> <string name="capture_picture">"Capturar imagen"</string> <string name="capture_video">"Capturar video"</string> <string name="crop_save_text">"Guardar"</string> <string name="crop_discard_text">"Eliminar"</string> <string name="confirm_delete_title">"Eliminar"</string> <string name="confirm_delete_message">"La imagen se eliminará."</string> <string name="confirm_delete_video_message">"El video se eliminará."</string> <string name="camera_toss">"Eliminar"</string> <string name="camera_gallery">"Galería"</string> <string name="camera_share">"Compartir"</string> <string name="camera_set">"Definir como"</string> <string name="camera_play">"Reproducir"</string> <string name="camera_attach">"Adjuntar"</string> <string name="camera_cancel">"Cancelar"</string> <string name="camera_crop">"Cortar"</string> <string name="camera_tossing">"Eliminando..."</string> <string name="no_way_to_share_image">"Esta imagen no se puede compartir."</string> <string name="no_way_to_share_video">"Este video no se puede compartir."</string> <string name="video_play">"Reproducir"</string> <string name="camera_gallery_photos_text">"Galería"</string> <string name="camera_pick_wallpaper">"Imágenes"</string> <string name="camera_setas_wallpaper">"Papel tapiz"</string> <string name="pref_gallery_category">"Configuración general"</string> - <string name="pref_slideshow_category">"Configuración de presentación de diapositivas"</string> + <string name="pref_slideshow_category">"Conf. present. de diapositivas"</string> <string name="pref_camera_general_settings_category">"Configuración general"</string> <string name="pref_gallery_size_title">"Visualizar tamaño"</string> <string name="pref_gallery_size_summary">"Seleccionar el tamaño de visualización de imágenes y videos"</string> <string name="pref_gallery_size_dialogtitle">"Tamaño de imagen"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Pequeño"</item> </string-array> <string name="pref_gallery_sort_title">"Ordenar"</string> <string name="pref_gallery_sort_summary">"Selecciona el orden de imágenes y videos"</string> <string name="pref_gallery_sort_dialogtitle">"Orden de imágenes"</string> <string-array name="pref_gallery_sort_choices"> <item>"Lo más nuevo primero"</item> <item>"Lo más nuevo al final"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalo de la presentación"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleccionar cuánto tiempo se visualizará cada diapositiva en la presentación"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo de la presentación"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 segundos"</item> <item>"3 segundos"</item> <item>"4 segundos"</item> </string-array> - <string name="pref_gallery_slideshow_transition_title">"Transición de la presentación de diapositivas"</string> + <string name="pref_gallery_slideshow_transition_title">"Transic. de la present. de diapos."</string> <string name="pref_gallery_slideshow_transition_summary">"Seleccionar el efecto utilizado al pasar de una diapositiva a otra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transición de la presentación de diapositivas"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Fundido de entrada/salida"</item> <item>"Deslizar hacia la izquierda/derecha"</item> <item>"Deslizar hacia arriba/abajo"</item> <item>"Selección aleatoria"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Repetir la presentación"</string> <string name="pref_gallery_slideshow_repeat_summary">"Reproducir la presentación de diapositivas más de una vez"</string> <string name="pref_gallery_slideshow_shuffle_title">"Arrastrar diapositivas"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imágenes en orden aleatorio"</string> - <string name="pref_camera_recordlocation_title">"Almacenar ubicación en imágenes"</string> + <string name="pref_camera_recordlocation_title">"Almac. ubic. en imág."</string> <string name="pref_camera_recordlocation_summary">"Grabar la ubicación en los datos de la imagen"</string> <string name="pref_camera_videoquality_category">"Calidad del video"</string> <string name="pref_camera_videoquality_title">"Seleccionar calidad de video"</string> <string name="pref_camera_videoquality_entry_0">"Bajo (para mensajes MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (para tarjeta SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Calidad del video"</string> <string name="camerasettings">"Configuración"</string> <string name="image_gallery_NoImageView_text">"No se han encontrado medios."</string> <string name="pref_gallery_confirm_delete_title">"Confirmar eliminaciones"</string> <string name="pref_gallery_confirm_delete_summary">"Mostrar configuración antes de eliminar una imagen o un video"</string> <string name="details_panel_title">"Detalles"</string> <string name="details_file_size">"Tamaño de archivo:"</string> <string name="details_image_resolution">"Resolución:"</string> <string name="details_duration">"Duración:"</string> <string name="details_date_taken">"Fecha:"</string> <string name="details_frame_rate">"Frecuencia de visualización:"</string> <string name="details_bit_rate">"Frecuencia de bits:"</string> <string name="details_codec">"Códec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"Aceptar"</string> <string name="context_menu_header">"Opciones de imagen"</string> <string name="video_context_menu_header">"Opciones de video"</string> <string name="multiface_crop_help">"Golpea una cara para comenzar."</string> <string name="photos_gallery_title">"Galería"</string> <string name="pick_photos_gallery_title">"Seleccionar imagen"</string> <string name="videos_gallery_title">"Galería"</string> <string name="pick_videos_gallery_title">"Seleccionar video"</string> <string name="loading_progress_format_string">"Quedan <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Compartir imagen mediante"</string> <string name="setImage">"Definir imagen como"</string> <string name="sendVideo">"Compartir video mediante"</string> <string name="movieviewlabel">"Películas"</string> <string name="loading_video">"Cargando el video..."</string> <string name="spaceIsLow_title">"El espacio es pequeño"</string> <string name="spaceIsLow_content">"Tu tarjeta SD se está quedando sin espacio. Cambia la configuración de calidad o elimina elementos de la galería."</string> <string name="resume_playing_title">"Retomar video"</string> <string name="resume_playing_message">"¿Deseas retomar la reproducción desde %s?"</string> <string name="resume_playing_resume">"Retomar la reproducción"</string> <string name="resume_playing_restart">"Empezar de nuevo"</string> <string name="gadget_title">"Marco de imagen"</string> <string name="file_info_title">"Información del archivo:"</string> <string name="video_exceed_mms_limit">"El video que has grabado es demasiado grande para enviarlo por MMS. Intenta grabar uno más corto."</string> <string name="too_large_to_attach">"El archivo es demasiado grande para adjuntarlo."</string> </resources> diff --git a/res/values-pt/strings.xml b/res/values-pt/strings.xml index cd3847f..145ed01 100644 --- a/res/values-pt/strings.xml +++ b/res/values-pt/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Todas as imagens"</string> <string name="all_videos">"Todos os vídeos"</string> <string name="camera_label">"Câmera"</string> <string name="video_camera_label">"Filmadora"</string> <string name="gallery_picker_label">"Galeria"</string> <string name="gallery_camera_bucket_name">"Imagens da câmera"</string> <string name="gallery_camera_videos_bucket_name">"Vídeos de câmera"</string> <string name="switch_to_video_lable">"Alternar para vídeo"</string> <string name="switch_to_camera_lable">"Alternar para câmera"</string> <string name="crop_label">"Cortar imagem"</string> <string name="view_label">"Visualizar imagem"</string> <string name="preferences_label">"Configurações da câmera"</string> <string name="wait">"Aguarde..."</string> <string name="no_storage">"Insira um cartão SD antes de usar a câmera."</string> <string name="not_enough_space">"O seu cartão SD está cheio."</string> <string name="preparing_sd">"Preparando o cartão SD…"</string> <string name="wallpaper">"Configurando o papel de parede, aguarde…"</string> <string name="savingImage">"Salvando imagem…"</string> <string name="runningFaceDetection">"Aguarde..."</string> <string name="flip_orientation">"Orientação do giro"</string> <string name="settings">"Configurações"</string> <string name="view">"Exibir"</string> <string name="details">"Detalhes"</string> <string name="rotate">"Girar"</string> <string name="rotate_left">"Girar para a esquerda"</string> <string name="rotate_right">"Girar para a direita"</string> <string name="slide_show">"Apresentação de slides"</string> <string name="capture_picture">"Capturar imagem"</string> <string name="capture_video">"Capturar vídeo"</string> <string name="crop_save_text">"Salvar"</string> <string name="crop_discard_text">"Descartar"</string> <string name="confirm_delete_title">"Excluir"</string> <string name="confirm_delete_message">"A imagem será excluída."</string> <string name="confirm_delete_video_message">"O vídeo será excluído."</string> <string name="camera_toss">"Excluir"</string> <string name="camera_gallery">"Galeria"</string> <string name="camera_share">"Compartilhar"</string> <string name="camera_set">"Definir como"</string> <string name="camera_play">"Reproduzir"</string> <string name="camera_attach">"Anexar"</string> <string name="camera_cancel">"Cancelar"</string> <string name="camera_crop">"Cortar"</string> <string name="camera_tossing">"Excluindo…"</string> <string name="no_way_to_share_image">"Esta imagem não pode ser compartilhada."</string> <string name="no_way_to_share_video">"Este vídeo não pode ser compartilhado."</string> <string name="video_play">"Reproduzir"</string> <string name="camera_gallery_photos_text">"Galeria"</string> <string name="camera_pick_wallpaper">"Imagens"</string> <string name="camera_setas_wallpaper">"Papel de parede"</string> <string name="pref_gallery_category">"Configurações gerais"</string> <string name="pref_slideshow_category">"Configurações da apresentação de slides"</string> <string name="pref_camera_general_settings_category">"Configurações gerais"</string> <string name="pref_gallery_size_title">"Tamanho da exibição"</string> <string name="pref_gallery_size_summary">"Selecione o tamanho de exibição das imagens e vídeos"</string> <string name="pref_gallery_size_dialogtitle">"Tamanho da imagem"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Pequeno"</item> </string-array> <string name="pref_gallery_sort_title">"Ordem de classificação"</string> <string name="pref_gallery_sort_summary">"Selecione a ordem de classificação das imagens e dos vídeos."</string> <string name="pref_gallery_sort_dialogtitle">"Classificação de imagens"</string> <string-array name="pref_gallery_sort_choices"> - <item>"Primeiro o mais recente"</item> - <item>"Último mais recente"</item> + <item>"O mais recente primeiro"</item> + <item>"O mais recente por último"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalo da apresentação de slides"</string> <string name="pref_gallery_slideshow_interval_summary">"Selecione a duração de exibição de cada slide na apresentação."</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo da apresentação de slides"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 segundos"</item> <item>"3 segundos"</item> <item>"4 segundos"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transição da apresentação de slides"</string> <string name="pref_gallery_slideshow_transition_summary">"Selecione o efeito usado ao passar de um slide para o próximo."</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transição da apresentação de slides"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Aparecimento/desaparecimento gradual (fade in/out)"</item> <item>"Deslizar para a esquerda - direita"</item> <item>"Deslizar para cima - para baixo"</item> <item>"Seleção aleatória"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Repetir apresentação de slides"</string> <string name="pref_gallery_slideshow_repeat_summary">"Reproduzir apresentação de slides mais de uma vez"</string> <string name="pref_gallery_slideshow_shuffle_title">"Reproduzir slides aleatoriamente"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imagens em ordem aleatória"</string> <string name="pref_camera_recordlocation_title">"Armazenar o local nas imagens"</string> <string name="pref_camera_recordlocation_summary">"Gravar o local nos dados da imagem"</string> <string name="pref_camera_videoquality_category">"Qualidade do vídeo"</string> <string name="pref_camera_videoquality_title">"Selecionar a qualidade do vídeo"</string> <string name="pref_camera_videoquality_entry_0">"Baixa (para mensagens MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (para cartão SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Qualidade do vídeo"</string> <string name="camerasettings">"Configurações"</string> <string name="image_gallery_NoImageView_text">"Nenhuma mídia encontrada."</string> <string name="pref_gallery_confirm_delete_title">"Confirmar exclusões"</string> <string name="pref_gallery_confirm_delete_summary">"Mostrar confirmação antes de excluir uma imagem ou vídeo."</string> <string name="details_panel_title">"Detalhes"</string> <string name="details_file_size">"Tamanho do arquivo:"</string> <string name="details_image_resolution">"Resolução:"</string> <string name="details_duration">"Duração:"</string> <string name="details_date_taken">"Data de obtenção:"</string> <string name="details_frame_rate">"Taxa de frame:"</string> <string name="details_bit_rate">"Taxa de bits:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opções da imagem"</string> <string name="video_context_menu_header">"Opções de vídeo"</string> <string name="multiface_crop_help">"Toque em uma face para começar."</string> <string name="photos_gallery_title">"Galeria"</string> <string name="pick_photos_gallery_title">"Selecionar imagem"</string> <string name="videos_gallery_title">"Galeria"</string> <string name="pick_videos_gallery_title">"Selecionar vídeo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> <string name="sendImage">"Compartilhar imagem via"</string> <string name="setImage">"Definir imagem como"</string> <string name="sendVideo">"Compartilhar vídeo via"</string> <string name="movieviewlabel">"Filmes"</string> <string name="loading_video">"Carregando vídeo..."</string> <string name="spaceIsLow_title">"O espaço é pouco"</string> <string name="spaceIsLow_content">"O seu cartão SD está sem espaço. Mude a configuração de qualidade ou exclua itens da Galeria."</string> <string name="resume_playing_title">"Retomar vídeo"</string> <string name="resume_playing_message">"Retomar reprodução de %s ?"</string> <string name="resume_playing_resume">"Retomar a reprodução"</string> <string name="resume_playing_restart">"Reiniciar"</string> <string name="gadget_title">"Frame da imagem"</string> <string name="file_info_title">"Informações do arquivo:"</string> <string name="video_exceed_mms_limit">"O vídeo gravado é muito grande para ser enviado via MMS. Tente gravar um clipe mais curto."</string> <string name="too_large_to_attach">"Arquivo muito grande para ser anexado."</string> </resources> diff --git a/res/values-ru/strings.xml b/res/values-ru/strings.xml index 91238c0..1e471df 100644 --- a/res/values-ru/strings.xml +++ b/res/values-ru/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Все картинки"</string> <string name="all_videos">"Все видео"</string> <string name="camera_label">"Фотографии"</string> <string name="video_camera_label">"Видеокамера"</string> <string name="gallery_picker_label">"Фотоальбом"</string> <string name="gallery_camera_bucket_name">"Снимки, сделанные камерой"</string> <string name="gallery_camera_videos_bucket_name">"Видео"</string> <string name="switch_to_video_lable">"Переключить на видео"</string> - <string name="switch_to_camera_lable">"Переключить на камеру"</string> + <string name="switch_to_camera_lable">"Переключить на фото"</string> <string name="crop_label">"Обрезать фотографию"</string> <string name="view_label">"Просмотр картинки"</string> <string name="preferences_label">"Настройки камеры"</string> <string name="wait">"Подождите..."</string> <string name="no_storage">"Прежде чем использовать камеру, вставьте SD-карту."</string> <string name="not_enough_space">"Ваша SD-карта заполнена."</string> <string name="preparing_sd">"Подготовка карты SD..."</string> <string name="wallpaper">"Установка обоев, подождите..."</string> <string name="savingImage">"Сохранение картинки..."</string> <string name="runningFaceDetection">"Подождите..."</string> <string name="flip_orientation">"Изменить ориентацию"</string> <string name="settings">"Настройки"</string> <string name="view">"Просмотр"</string> <string name="details">"Сведения"</string> <string name="rotate">"Повернуть"</string> <string name="rotate_left">"Повернуть влево"</string> <string name="rotate_right">"Повернуть вправо"</string> <string name="slide_show">"Слайд-шоу"</string> <string name="capture_picture">"Сделать фотографию"</string> <string name="capture_video">"Снять видео"</string> <string name="crop_save_text">"Сохранить"</string> <string name="crop_discard_text">"Отменить"</string> <string name="confirm_delete_title">"Удалить"</string> <string name="confirm_delete_message">"Картинка будет удалена."</string> <string name="confirm_delete_video_message">"Видео будет удалено."</string> <string name="camera_toss">"Удалить"</string> <string name="camera_gallery">"Фотоальбом"</string> <string name="camera_share">"Отправить"</string> <string name="camera_set">"Установить как"</string> <string name="camera_play">"Воспроизвести"</string> <string name="camera_attach">"Вложить"</string> <string name="camera_cancel">"Отмена"</string> <string name="camera_crop">"Обрезать"</string> <string name="camera_tossing">"Удаление..."</string> <string name="no_way_to_share_image">"Эту фотографию нельзя отправить."</string> <string name="no_way_to_share_video">"Это видео нельзя отправить."</string> <string name="video_play">"Воспроизвести"</string> <string name="camera_gallery_photos_text">"Фотоальбом"</string> <string name="camera_pick_wallpaper">"Картинки"</string> <string name="camera_setas_wallpaper">"Обои"</string> <string name="pref_gallery_category">"Общие настройки"</string> <string name="pref_slideshow_category">"Настройки слайд-шоу"</string> <string name="pref_camera_general_settings_category">"Общие настройки"</string> <string name="pref_gallery_size_title">"Отображаемый размер"</string> <string name="pref_gallery_size_summary">"Выбор отображаемого размера изображений и видео"</string> <string name="pref_gallery_size_dialogtitle">"Размер картинки"</string> <string-array name="pref_gallery_size_choices"> <item>"Большой"</item> <item>"Небольшой"</item> </string-array> <string name="pref_gallery_sort_title">"Порядок сортировки"</string> <string name="pref_gallery_sort_summary">"Выберите порядок сортировки изображений и видео"</string> <string name="pref_gallery_sort_dialogtitle">"Сортировать картинки"</string> <string-array name="pref_gallery_sort_choices"> <item>"Сначала новые"</item> <item>"Сначала старые"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Интервал в слайд-шоу"</string> <string name="pref_gallery_slideshow_interval_summary">"Выбор длительности показа каждого слайда"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Интервал слайд-шоу"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 сек."</item> <item>"3 сек."</item> <item>"4 сек."</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Переход в слайд-шоу"</string> <string name="pref_gallery_slideshow_transition_summary">"Выбор эффекта при переходе от одного слайда к другому"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Переход в слайд-шоу"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Затемнение и проявление"</item> <item>"Прокрутка слева направо"</item> <item>"Прокрутка сверху вниз"</item> <item>"Случайный выбор"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Повтор слайд-шоу"</string> <string name="pref_gallery_slideshow_repeat_summary">"Воспроизвести слайд-шоу более одного раза"</string> <string name="pref_gallery_slideshow_shuffle_title">"Перемешать слайды"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Показ фотографий в случайном порядке"</string> - <string name="pref_camera_recordlocation_title">"Сохранять местоположение в фотографиях"</string> + <string name="pref_camera_recordlocation_title">"Сохранять местоположение"</string> <string name="pref_camera_recordlocation_summary">"Записывать местоположение в данных фотографии"</string> <string name="pref_camera_videoquality_category">"Качество видео"</string> <string name="pref_camera_videoquality_title">"Выбор качества видео"</string> <string name="pref_camera_videoquality_entry_0">"Низкое (для сообщений MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Высокое (для SD-карты)"</string> <string name="pref_camera_videoquality_dialogtitle">"Качество видео"</string> <string name="camerasettings">"Настройки"</string> <string name="image_gallery_NoImageView_text">"Нет мультимедийных материалов."</string> <string name="pref_gallery_confirm_delete_title">"Подтверждать удаление"</string> <string name="pref_gallery_confirm_delete_summary">"Запрашивать подтверждения перед удалением изображения или видео"</string> <string name="details_panel_title">"Сведения"</string> <string name="details_file_size">"Размер файла:"</string> <string name="details_image_resolution">"Разрешение:"</string> <string name="details_duration">"Продолжительность:"</string> <string name="details_date_taken">"Дата съемки:"</string> <string name="details_frame_rate">"Частота кадров:"</string> <string name="details_bit_rate">"Битрейт:"</string> <string name="details_codec">"Кодек:"</string> <string name="details_format">"Формат:"</string> <string name="details_dimension_x">"%1$d на %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d кадров/с"</string> <string name="details_kbps">"%1$d кбит/с"</string> <string name="details_mbps">"%1$g Мбит/с"</string> <string name="details_ok">"ОК"</string> <string name="context_menu_header">"Параметры картинки"</string> <string name="video_context_menu_header">"Параметры видео"</string> <string name="multiface_crop_help">"Нажмите лицо, чтобы начать."</string> <string name="photos_gallery_title">"Фотоальбом"</string> - <string name="pick_photos_gallery_title">"Выбор картинок"</string> + <string name="pick_photos_gallery_title">"Выберите картинку"</string> <string name="videos_gallery_title">"Фотоальбом"</string> <string name="pick_videos_gallery_title">"Выбор видео"</string> <string name="loading_progress_format_string">"Осталось: <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Отправить картинку через"</string> <string name="setImage">"Установить картинку как"</string> <string name="sendVideo">"Отправить видео при помощи"</string> <string name="movieviewlabel">"Фильмы"</string> <string name="loading_video">"Загрузка видео…"</string> <string name="spaceIsLow_title">"Мало свободного места"</string> <string name="spaceIsLow_content">"Место на вашей SD-карте заканчивается. Измените настройки качества или удалите содержимое из фотоальбома."</string> <string name="resume_playing_title">"Продолжение просмотра видео"</string> <string name="resume_playing_message">"Продолжить воспроизведение с %s?"</string> <string name="resume_playing_resume">"Продолжить воспроизведение"</string> <string name="resume_playing_restart">"Начать с начала"</string> <string name="gadget_title">"Рамка фотографии"</string> <string name="file_info_title">"Сведения о файле:"</string> <string name="video_exceed_mms_limit">"Записанное видео имеет слишком большой размер для отправки в MMS. Запишите более короткий ролик."</string> <string name="too_large_to_attach">"Файл имеет слишком большой размер и не может быть вложен."</string> </resources> diff --git a/res/values-tr/strings.xml b/res/values-tr/strings.xml index dcbc6a2..dbd9acf 100644 --- a/res/values-tr/strings.xml +++ b/res/values-tr/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Tüm resimler"</string> <string name="all_videos">"Tüm videolar"</string> <string name="camera_label">"Kamera"</string> <string name="video_camera_label">"Video Kamera"</string> <string name="gallery_picker_label">"Galeri"</string> <string name="gallery_camera_bucket_name">"Kamera resimleri"</string> <string name="gallery_camera_videos_bucket_name">"Kamera videoları"</string> <string name="switch_to_video_lable">"Videoya geç"</string> <string name="switch_to_camera_lable">"Kameraya geç"</string> <string name="crop_label">"Resmi kırp"</string> <string name="view_label">"Resmi görüntüle"</string> <string name="preferences_label">"Kamera ayarları"</string> <string name="wait">"Lütfen bekleyin..."</string> <string name="no_storage">"Kamerayı kullanmadan önce lütfen bir SD kart takın."</string> <string name="not_enough_space">"SD kartınız dolu."</string> <string name="preparing_sd">"SD kart hazırlanıyor..."</string> <string name="wallpaper">"Duvar kağıdı ayarlanıyor, lütfen bekleyin..."</string> <string name="savingImage">"Resim kaydediliyor..."</string> <string name="runningFaceDetection">"Lütfen bekleyin..."</string> <string name="flip_orientation">"Yönü değiştir"</string> <string name="settings">"Ayarlar"</string> <string name="view">"Görüntüle"</string> <string name="details">"Ayrıntılar"</string> <string name="rotate">"Döndür"</string> <string name="rotate_left">"Sola döndür"</string> <string name="rotate_right">"Sağa döndür"</string> <string name="slide_show">"Slayt gösterisi"</string> <string name="capture_picture">"Fotoğraf çek"</string> <string name="capture_video">"Video çek"</string> <string name="crop_save_text">"Kaydet"</string> <string name="crop_discard_text">"Sil"</string> <string name="confirm_delete_title">"Sil"</string> <string name="confirm_delete_message">"Resim silinecek."</string> <string name="confirm_delete_video_message">"Video silinecek."</string> <string name="camera_toss">"Sil"</string> <string name="camera_gallery">"Galeri"</string> <string name="camera_share">"Paylaş"</string> <string name="camera_set">"Şu şekilde ayarla:"</string> <string name="camera_play">"Yürüt"</string> <string name="camera_attach">"Ekle"</string> <string name="camera_cancel">"İptal"</string> <string name="camera_crop">"Kırp"</string> <string name="camera_tossing">"Siliniyor..."</string> <string name="no_way_to_share_image">"Bu resim paylaşılamıyor."</string> <string name="no_way_to_share_video">"Bu video paylaşılamıyor."</string> <string name="video_play">"Yürüt"</string> <string name="camera_gallery_photos_text">"Galeri"</string> <string name="camera_pick_wallpaper">"Resimler"</string> <string name="camera_setas_wallpaper">"Duvar Kağıdı"</string> <string name="pref_gallery_category">"Genel ayarlar"</string> <string name="pref_slideshow_category">"Slayt gösterisi ayarları"</string> <string name="pref_camera_general_settings_category">"Genel ayarlar"</string> <string name="pref_gallery_size_title">"Görüntü boyutu"</string> <string name="pref_gallery_size_summary">"Resimlerin ve videoların görüntülenme boyutunu seçin"</string> <string name="pref_gallery_size_dialogtitle">"Resim boyutu"</string> <string-array name="pref_gallery_size_choices"> <item>"Büyük"</item> <item>"Küçük"</item> </string-array> <string name="pref_gallery_sort_title">"Sıralama düzeni"</string> <string name="pref_gallery_sort_summary">"Resimlerin ve videoların sıralama düzenini seçin"</string> <string name="pref_gallery_sort_dialogtitle">"Resim sıralama"</string> <string-array name="pref_gallery_sort_choices"> <item>"Önce en yenisi"</item> <item>"En yenisi en sonra"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Slayt gösterisi aralığı"</string> <string name="pref_gallery_slideshow_interval_summary">"Her slaytın slayt gösterisinde ne kadar süreyle görüntüleneceğini seçin"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Slayt gösterisi aralığı"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 saniye"</item> <item>"3 saniye"</item> <item>"4 saniye"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Slayt gösterisi geçişi"</string> <string name="pref_gallery_slideshow_transition_summary">"Bir slayttan diğerine geçerken kullanılan efekti seçin"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Slayt gösterisi geçişi"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Rengi açma ve karartma"</item> <item>"Sağa - sola kaydır"</item> <item>"Sonraki - önceki slayta geç"</item> <item>"Rasgele seçim"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Slayt gösterisini tekrar et"</string> <string name="pref_gallery_slideshow_repeat_summary">"Slayt gösterisini birden fazla kez yürüt"</string> <string name="pref_gallery_slideshow_shuffle_title">"Slaytları karıştır"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Resimleri rasgele sırada göster"</string> <string name="pref_camera_recordlocation_title">"Resimlerde konumu depola"</string> <string name="pref_camera_recordlocation_summary">"Konumu resim verilerinde kaydet"</string> <string name="pref_camera_videoquality_category">"Video kalitesi"</string> <string name="pref_camera_videoquality_title">"Video kalitesini seç"</string> - <string name="pref_camera_videoquality_entry_0">"Düşük (MMS iletileri için)"</string> + <string name="pref_camera_videoquality_entry_0">"Düşük (MMS mesajları için)"</string> <string name="pref_camera_videoquality_entry_1">"Yüksek (SD kart için)"</string> <string name="pref_camera_videoquality_dialogtitle">"Video kalitesi"</string> <string name="camerasettings">"Ayarlar"</string> <string name="image_gallery_NoImageView_text">"Medya bulunamadı."</string> <string name="pref_gallery_confirm_delete_title">"Silme işlemlerini doğrula"</string> <string name="pref_gallery_confirm_delete_summary">"Bir resmi veya videoyu silmeden önce doğrulama göster"</string> <string name="details_panel_title">"Ayrıntılar"</string> <string name="details_file_size">"Dosya boyutu:"</string> <string name="details_image_resolution">"Çözünürlük:"</string> <string name="details_duration">"Süre:"</string> <string name="details_date_taken">"Çekim tarihi:"</string> <string name="details_frame_rate">"Çerçeve oranı:"</string> <string name="details_bit_rate">"Bit hızı:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Biçim:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d f/s"</string> <string name="details_kbps">"%1$d Kb/s"</string> <string name="details_mbps">"%1$g Mb/s"</string> <string name="details_ok">"Tamam"</string> <string name="context_menu_header">"Resim seçenekleri"</string> <string name="video_context_menu_header">"Video seçenekleri"</string> <string name="multiface_crop_help">"Başlamak için bir yüze hafifçe dokunun"</string> <string name="photos_gallery_title">"Galeri"</string> <string name="pick_photos_gallery_title">"Resmi seç"</string> <string name="videos_gallery_title">"Galeri"</string> <string name="pick_videos_gallery_title">"Video seç"</string> <string name="loading_progress_format_string">"Kalan: <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Resmi şunun aracılığıyla paylaş:"</string> <string name="setImage">"Resmi şu şekilde ayarla:"</string> <string name="sendVideo">"Videoyu şunun aracılığıyla paylaş:"</string> <string name="movieviewlabel">"Filmler"</string> <string name="loading_video">"Video yükleniyor..."</string> <string name="spaceIsLow_title">"Alan az"</string> <string name="spaceIsLow_content">"SD kartınızda boş alan azalıyor. Kalite ayarlarını değiştirin veya Galeri\'den öğe silin."</string> <string name="resume_playing_title">"Videoyu sürdür"</string> <string name="resume_playing_message">"Yürütme şuradan devam ettirilsin mi: %s ?"</string> <string name="resume_playing_resume">"Yürütmeyi sürdür"</string> <string name="resume_playing_restart">"Başlat"</string> <string name="gadget_title">"Resim çerçevesi"</string> <string name="file_info_title">"Dosya bilgileri:"</string> <string name="video_exceed_mms_limit">"Kaydettiğiniz video MMS ile gönderilemeyecek kadar büyük. Daha kısa bir klip kaydetmeyi deneyin."</string> <string name="too_large_to_attach">"Dosya eklenemeyecek kadar büyük."</string> </resources> diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml index 68a9024..3143387 100644 --- a/res/values-zh-rCN/strings.xml +++ b/res/values-zh-rCN/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"所有图片"</string> <string name="all_videos">"所有视频"</string> <string name="camera_label">"相机"</string> <string name="video_camera_label">"摄像机"</string> <string name="gallery_picker_label">"图库"</string> <string name="gallery_camera_bucket_name">"用相机拍摄的照片"</string> <string name="gallery_camera_videos_bucket_name">"用相机拍摄的视频"</string> <string name="switch_to_video_lable">"切换到视频"</string> <string name="switch_to_camera_lable">"切换到相机"</string> <string name="crop_label">"修剪图片"</string> <string name="view_label">"查看图片"</string> <string name="preferences_label">"相机设置"</string> <string name="wait">"请稍候..."</string> <string name="no_storage">"使用相机前请先插入 SD 卡。"</string> <string name="not_enough_space">"SD 卡已满。"</string> <string name="preparing_sd">"正在准备 SD 卡..."</string> <string name="wallpaper">"正在设置壁纸,请稍候..."</string> - <string name="savingImage">"正在保存照片..."</string> + <string name="savingImage">"正在保存图片..."</string> <string name="runningFaceDetection">"请稍候..."</string> <string name="flip_orientation">"反转方向"</string> <string name="settings">"设置"</string> <string name="view">"查看"</string> <string name="details">"详细信息"</string> <string name="rotate">"旋转"</string> <string name="rotate_left">"向左旋转"</string> <string name="rotate_right">"向右旋转"</string> <string name="slide_show">"播放幻灯片"</string> <string name="capture_picture">"拍摄照片"</string> <string name="capture_video">"拍摄视频"</string> <string name="crop_save_text">"保存"</string> <string name="crop_discard_text">"舍弃"</string> <string name="confirm_delete_title">"删除"</string> <string name="confirm_delete_message">"将会删除此照片。"</string> <string name="confirm_delete_video_message">"将会删除视频。"</string> <string name="camera_toss">"删除"</string> <string name="camera_gallery">"图库"</string> <string name="camera_share">"分享"</string> <string name="camera_set">"设置为"</string> <string name="camera_play">"播放"</string> <string name="camera_attach">"附加"</string> <string name="camera_cancel">"取消"</string> <string name="camera_crop">"修剪"</string> <string name="camera_tossing">"正在删除..."</string> <string name="no_way_to_share_image">"无法分享此图片。"</string> <string name="no_way_to_share_video">"无法分享此视频。"</string> <string name="video_play">"播放"</string> <string name="camera_gallery_photos_text">"图库"</string> <string name="camera_pick_wallpaper">"图片"</string> <string name="camera_setas_wallpaper">"壁纸"</string> <string name="pref_gallery_category">"常规设置"</string> <string name="pref_slideshow_category">"幻灯片设置"</string> <string name="pref_camera_general_settings_category">"常规设置"</string> <string name="pref_gallery_size_title">"显示大小"</string> <string name="pref_gallery_size_summary">"选择图片和视频的显示大小"</string> <string name="pref_gallery_size_dialogtitle">"图片大小"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> - <string name="pref_gallery_sort_title">"排序顺序"</string> - <string name="pref_gallery_sort_summary">"选择图片和视频的排序顺序"</string> + <string name="pref_gallery_sort_title">"排列顺序"</string> + <string name="pref_gallery_sort_summary">"选择图片和视频的排列顺序"</string> <string name="pref_gallery_sort_dialogtitle">"图片排序"</string> <string-array name="pref_gallery_sort_choices"> <item>"最新的图片在最前面"</item> <item>"最新的图片在最后面"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"幻灯片播放间隔"</string> - <string name="pref_gallery_slideshow_interval_summary">"选择每张幻灯片在播放过程中持续显示的时间"</string> + <string name="pref_gallery_slideshow_interval_summary">"选择每张幻灯片在播放过程中呈现的时间"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"幻灯片播放间隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 秒"</item> <item>"3 秒"</item> <item>"4 秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"幻灯片切换"</string> <string name="pref_gallery_slideshow_transition_summary">"选择幻灯片切换时应用的效果"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"幻灯片切换"</string> <string-array name="pref_gallery_slideshow_transition_choices"> - <item>"淡入和淡出"</item> + <item>"淡入淡出"</item> <item>"自左至右滑动"</item> <item>"自上至下滑动"</item> <item>"随机选择"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"重复播放幻灯片"</string> <string name="pref_gallery_slideshow_repeat_summary">"循环播放幻灯片"</string> <string name="pref_gallery_slideshow_shuffle_title">"随机播放幻灯片"</string> <string name="pref_gallery_slideshow_shuffle_summary">"以随机顺序显示图片"</string> <string name="pref_camera_recordlocation_title">"在照片中存储位置"</string> <string name="pref_camera_recordlocation_summary">"在照片数据中记录位置"</string> <string name="pref_camera_videoquality_category">"视频画质"</string> <string name="pref_camera_videoquality_title">"选择视频画质"</string> <string name="pref_camera_videoquality_entry_0">"低(对于彩信)"</string> <string name="pref_camera_videoquality_entry_1">"高(对于 SD 卡)"</string> <string name="pref_camera_videoquality_dialogtitle">"视频画质"</string> <string name="camerasettings">"设置"</string> <string name="image_gallery_NoImageView_text">"找不到媒体。"</string> <string name="pref_gallery_confirm_delete_title">"确认删除"</string> <string name="pref_gallery_confirm_delete_summary">"在删除图片或视频前显示确认消息"</string> <string name="details_panel_title">"详细信息"</string> <string name="details_file_size">"文件大小:"</string> <string name="details_image_resolution">"分辨率:"</string> <string name="details_duration">"持续时间:"</string> <string name="details_date_taken">"拍摄日期:"</string> <string name="details_frame_rate">"帧频:"</string> <string name="details_bit_rate">"比特率:"</string> <string name="details_codec">"编解码器:"</string> <string name="details_format">"格式:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"确定"</string> <string name="context_menu_header">"图片选项"</string> <string name="video_context_menu_header">"视频选项"</string> <string name="multiface_crop_help">"点按一张脸开始裁剪。"</string> <string name="photos_gallery_title">"图库"</string> <string name="pick_photos_gallery_title">"选择图片"</string> <string name="videos_gallery_title">"图库"</string> <string name="pick_videos_gallery_title">"选择视频"</string> <string name="loading_progress_format_string">"还剩 <xliff:g id="COUNTER">%d</xliff:g> 个"</string> <string name="sendImage">"图片分享方式"</string> <string name="setImage">"将图片设置为"</string> <string name="sendVideo">"分享视频的方式"</string> <string name="movieviewlabel">"电影"</string> <string name="loading_video">"正在载入视频..."</string> <string name="spaceIsLow_title">"存储空间不足"</string> <string name="spaceIsLow_content">"SD 卡空间不足。请更改画质设置或从图库中删除部分项。"</string> <string name="resume_playing_title">"重新播放视频"</string> <string name="resume_playing_message">"从 %s 开始重新播放?"</string> <string name="resume_playing_resume">"重新播放"</string> <string name="resume_playing_restart">"重新开始"</string> <string name="gadget_title">"相框"</string> <string name="file_info_title">"文件信息:"</string> <string name="video_exceed_mms_limit">"您录制的视频太大,无法用彩信发送。请尝试录制短一点的剪辑。"</string> <string name="too_large_to_attach">"文件太大,无法附加。"</string> </resources>
brunsky/WS171-packages-apps-Camera
126c996937a5284263f416c65461eccd57f8c134
AI 150497: Import updated Portuguese translations.
diff --git a/res/values-pt-rPT/strings.xml b/res/values-pt-rPT/strings.xml index 90dfea3..123da2b 100644 --- a/res/values-pt-rPT/strings.xml +++ b/res/values-pt-rPT/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Todas as imagens"</string> <string name="all_videos">"Todos os vídeos"</string> <string name="camera_label">"Câmara"</string> <string name="video_camera_label">"Câmara de vídeo"</string> <string name="gallery_picker_label">"Galeria"</string> <string name="gallery_camera_bucket_name">"Imagens da câmara"</string> <string name="gallery_camera_videos_bucket_name">"Vídeos da câmara"</string> <string name="switch_to_video_lable">"Mudar para vídeo"</string> <string name="switch_to_camera_lable">"Mudar para câmara"</string> <string name="crop_label">"Recortar imagem"</string> <string name="view_label">"Ver imagem"</string> <string name="preferences_label">"Definições da câmara"</string> <string name="wait">"Aguarde..."</string> <string name="no_storage">"Insira um cartão SD antes de utilizar a câmara."</string> <string name="not_enough_space">"O cartão SD está cheio."</string> <string name="preparing_sd">"A preparar o cartão SD..."</string> <string name="wallpaper">"A definir a imagem de fundo, aguarde..."</string> <string name="savingImage">"A guardar imagem..."</string> <string name="runningFaceDetection">"Aguarde..."</string> <string name="flip_orientation">"Inverter a orientação"</string> <string name="settings">"Definições"</string> <string name="view">"Ver"</string> <string name="details">"Detalhes"</string> <string name="rotate">"Rodar"</string> <string name="rotate_left">"Rodar para a esquerda"</string> <string name="rotate_right">"Rodar para a direita"</string> <string name="slide_show">"Apresentação de diapositivos"</string> <string name="capture_picture">"Capturar imagem"</string> <string name="capture_video">"Capturar vídeo"</string> <string name="crop_save_text">"Guardar"</string> <string name="crop_discard_text">"Rejeitar"</string> <string name="confirm_delete_title">"Eliminar"</string> <string name="confirm_delete_message">"A imagem será eliminada."</string> <string name="confirm_delete_video_message">"O vídeo será eliminado."</string> <string name="camera_toss">"Eliminar"</string> <string name="camera_gallery">"Galeria"</string> <string name="camera_share">"Partilhar"</string> <string name="camera_set">"Definir como"</string> <string name="camera_play">"Reproduzir"</string> <string name="camera_attach">"Anexar"</string> <string name="camera_cancel">"Cancelar"</string> <string name="camera_crop">"Recortar"</string> <string name="camera_tossing">"A eliminar..."</string> <string name="no_way_to_share_image">"Não é possível partilhar esta imagem."</string> <string name="no_way_to_share_video">"Não é possível partilhar este vídeo."</string> <string name="video_play">"Reproduzir"</string> <string name="camera_gallery_photos_text">"Galeria"</string> <string name="camera_pick_wallpaper">"Imagens"</string> <string name="camera_setas_wallpaper">"Imagem de fundo"</string> <string name="pref_gallery_category">"Definições gerais"</string> <string name="pref_slideshow_category">"Definições da apresentação de diapositivos"</string> <string name="pref_camera_general_settings_category">"Definições gerais"</string> <string name="pref_gallery_size_title">"Tamanho da visualização"</string> <string name="pref_gallery_size_summary">"Seleccione o tamanho da apresentação de imagens e vídeo"</string> <string name="pref_gallery_size_dialogtitle">"Tamanho da imagem"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Pequeno"</item> </string-array> <string name="pref_gallery_sort_title">"Ordenação"</string> <string name="pref_gallery_sort_summary">"Seleccione a sequência de ordenação das imagens e dos vídeos"</string> <string name="pref_gallery_sort_dialogtitle">"Ordenação de imagens"</string> <string-array name="pref_gallery_sort_choices"> <item>"As mais recentes primeiro"</item> <item>"As mais recentes por último"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalo da apresentação de diapositivos"</string> - <string name="pref_gallery_slideshow_interval_summary">"Seleccionar o tempo de apresentação de cada diapositivo"</string> + <string name="pref_gallery_slideshow_interval_summary">"Seleccione o tempo de apresentação de cada diapositivo"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo da apresentação de diapositivos"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 segundos"</item> <item>"3 segundos"</item> <item>"4 segundos"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transição da apresentação de diapositivos"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleccione o efeito a utilizar na transição entre slides"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transição da apresentação de diapositivos"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Aumentar e diminuir gradualmente"</item> <item>"Apresentar diapositivos da esquerda para a direita"</item> <item>"Apresentar diapositivos de cima para baixo"</item> <item>"Selecção aleatória"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Repetir apresentação de diapositivos"</string> - <string name="pref_gallery_slideshow_repeat_summary">"Repetir·a·apresentação·de·diapositivos"</string> + <string name="pref_gallery_slideshow_repeat_summary">"Repetir a apresentação de diapositivos"</string> <string name="pref_gallery_slideshow_shuffle_title">"Reproduzir diapositivos aleatoriamente"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imagens por ordem aleatória"</string> <string name="pref_camera_recordlocation_title">"Armazenar localização nas imagens"</string> <string name="pref_camera_recordlocation_summary">"Gravar localização nos dados da imagem"</string> <string name="pref_camera_videoquality_category">"Qualidade de vídeo"</string> <string name="pref_camera_videoquality_title">"Seleccione a qualidade de vídeo"</string> <string name="pref_camera_videoquality_entry_0">"Baixa (para mensagens MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (para cartão SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Qualidade de vídeo"</string> <string name="camerasettings">"Definições"</string> <string name="image_gallery_NoImageView_text">"Nenhum suporte de dados encontrado."</string> <string name="pref_gallery_confirm_delete_title">"Confirmar a eliminação"</string> <string name="pref_gallery_confirm_delete_summary">"Mostrar confirmação antes de eliminar uma imagem ou vídeo"</string> <string name="details_panel_title">"Detalhes"</string> <string name="details_file_size">"Tamanho do ficheiro:"</string> <string name="details_image_resolution">"Resolução:"</string> <string name="details_duration">"Duração:"</string> <string name="details_date_taken">"Data da captura:"</string> <string name="details_frame_rate">"Velocidade de fotogramas:"</string> <string name="details_bit_rate">"Velocidade de transmissão:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opções de imagem"</string> <string name="video_context_menu_header">"Opções de vídeo"</string> <string name="multiface_crop_help">"Toque num rosto para começar."</string> <string name="photos_gallery_title">"Galeria"</string> <string name="pick_photos_gallery_title">"Seleccionar imagem"</string> <string name="videos_gallery_title">"Galeria"</string> <string name="pick_videos_gallery_title">"Seleccionar vídeo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> <string name="sendImage">"Partilhar a imagem através de"</string> <string name="setImage">"Definir imagem como:"</string> <string name="sendVideo">"Partilhar vídeo através de"</string> <string name="movieviewlabel">"Filmes"</string> <string name="loading_video">"A carregar vídeo..."</string> <string name="spaceIsLow_title">"O espaço é reduzido"</string> <string name="spaceIsLow_content">"Está a ficar sem espaço no cartão SD. Altere as definições de qualidade ou elimine itens da Galeria."</string> <string name="resume_playing_title">"Retomar o vídeo"</string> <string name="resume_playing_message">"Retomar reprodução a partir de %s?"</string> <string name="resume_playing_resume">"Retomar a reprodução"</string> <string name="resume_playing_restart">"Recomeçar"</string> <string name="gadget_title">"Moldura da imagem"</string> <string name="file_info_title">"Informações do ficheiro:"</string> <string name="video_exceed_mms_limit">"O vídeo que gravou é demasiado grande para ser enviado por MMS. Tente gravar um filme mais curto."</string> <string name="too_large_to_attach">"Ficheiro demasiado grande para anexar."</string> </resources>
brunsky/WS171-packages-apps-Camera
7da85f905b01fa00611261ef1d35b0c5feccab85
AI 150481: Import revised translations. Fix ko_KO -> ko->KR in build config.
diff --git a/res/values-sv/strings.xml b/res/values-sv/strings.xml index 55c56b1..b40edcf 100644 --- a/res/values-sv/strings.xml +++ b/res/values-sv/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Alla bilder"</string> <string name="all_videos">"Alla videor"</string> <string name="camera_label">"Kamera"</string> <string name="video_camera_label">"Videokamera"</string> <string name="gallery_picker_label">"Galleri"</string> <string name="gallery_camera_bucket_name">"Kamerabilder"</string> <string name="gallery_camera_videos_bucket_name">"Kameravideor"</string> <string name="switch_to_video_lable">"Växla till video"</string> <string name="switch_to_camera_lable">"Växla till kamera"</string> <string name="crop_label">"Beskär bild"</string> <string name="view_label">"Visa bild"</string> <string name="preferences_label">"Kamerainställningar"</string> <string name="wait">"Vänta…"</string> <string name="no_storage">"Sätt i ett SD-kort innan du använder kameran."</string> <string name="not_enough_space">"Ditt SD-kort är fullt."</string> <string name="preparing_sd">"Förbereder SD-kort…"</string> <string name="wallpaper">"Anger bakgrund, vänta…"</string> <string name="savingImage">"Sparar bild…"</string> <string name="runningFaceDetection">"Vänta…"</string> <string name="flip_orientation">"Ändra riktning"</string> <string name="settings">"Inställningar"</string> <string name="view">"Visa"</string> <string name="details">"Information"</string> <string name="rotate">"Rotera"</string> <string name="rotate_left">"Rotera åt vänster"</string> <string name="rotate_right">"Rotera åt höger"</string> <string name="slide_show">"Bildspel"</string> <string name="capture_picture">"Fota"</string> <string name="capture_video">"Spela in video"</string> <string name="crop_save_text">"Spara"</string> <string name="crop_discard_text">"Ignorera"</string> <string name="confirm_delete_title">"Ta bort"</string> <string name="confirm_delete_message">"Bilden kommer att tas bort."</string> <string name="confirm_delete_video_message">"Videon kommer att tas bort."</string> <string name="camera_toss">"Ta bort"</string> <string name="camera_gallery">"Galleri"</string> <string name="camera_share">"Dela"</string> <string name="camera_set">"Använd som"</string> <string name="camera_play">"Spela"</string> <string name="camera_attach">"Bifoga"</string> <string name="camera_cancel">"Avbryt"</string> <string name="camera_crop">"Beskär"</string> <string name="camera_tossing">"Tar bort…"</string> <string name="no_way_to_share_image">"Den här bilden kan inte delas."</string> <string name="no_way_to_share_video">"Den här videon kan inte delas."</string> <string name="video_play">"Spela"</string> <string name="camera_gallery_photos_text">"Galleri"</string> <string name="camera_pick_wallpaper">"Bilder"</string> <string name="camera_setas_wallpaper">"Bakgrund"</string> <string name="pref_gallery_category">"Allmänna inställningar"</string> <string name="pref_slideshow_category">"Bildspelsinställningar"</string> <string name="pref_camera_general_settings_category">"Allmänna inställningar"</string> <string name="pref_gallery_size_title">"Visningsstorlek"</string> <string name="pref_gallery_size_summary">"Välj visningsstorlek för bilder och videor"</string> <string name="pref_gallery_size_dialogtitle">"Bildstorlek"</string> <string-array name="pref_gallery_size_choices"> - <item>"Stora"</item> + <item>"Stor"</item> <item>"Liten"</item> </string-array> <string name="pref_gallery_sort_title">"Sorteringsordning"</string> <string name="pref_gallery_sort_summary">"Välj sorteringsordning för bilder och videor"</string> <string name="pref_gallery_sort_dialogtitle">"Sortera bilder"</string> <string-array name="pref_gallery_sort_choices"> <item>"Nyast först"</item> - <item>"Nyaste först"</item> + <item>"Nyast sist"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Bildspelsintervall"</string> <string name="pref_gallery_slideshow_interval_summary">"Ange hur länge varje bild ska visas i bildspelet"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Bildspelsintervall"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 sekunder"</item> <item>"3 sekunder"</item> <item>"4 sekunder"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Bildspelsövergång"</string> <string name="pref_gallery_slideshow_transition_summary">"Välj vilken effekt som ska användas i växlingen mellan bilder"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Bildspelsövergång"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Tonas fram och bort"</item> <item>"Skjuts åt vänster eller höger"</item> <item>"Skjuts upp och ner"</item> <item>"Slumpmässigt urval"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Upprepa bildspel"</string> <string name="pref_gallery_slideshow_repeat_summary">"Visa bildspel mer än en gång"</string> <string name="pref_gallery_slideshow_shuffle_title">"Blanda bilder"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Visa bilder i slumpmässig ordning"</string> <string name="pref_camera_recordlocation_title">"Spara plats i bilder"</string> <string name="pref_camera_recordlocation_summary">"Registrera plats i bilddata"</string> <string name="pref_camera_videoquality_category">"Videokvalitet"</string> <string name="pref_camera_videoquality_title">"Välj videokvalitet"</string> <string name="pref_camera_videoquality_entry_0">"Låg (för MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Hög (för SD-kort)"</string> <string name="pref_camera_videoquality_dialogtitle">"Videokvalitet"</string> <string name="camerasettings">"Inställningar"</string> <string name="image_gallery_NoImageView_text">"Inga medieobjekt hittades."</string> <string name="pref_gallery_confirm_delete_title">"Bekräfta borttagningar"</string> <string name="pref_gallery_confirm_delete_summary">"Visa bekräftelse innan bild eller video tas bort"</string> <string name="details_panel_title">"Information"</string> <string name="details_file_size">"Filstorlek:"</string> <string name="details_image_resolution">"Upplösning:"</string> <string name="details_duration">"Varaktighet:"</string> <string name="details_date_taken">"Togs den:"</string> <string name="details_frame_rate">"Bildrutefrekvens"</string> <string name="details_bit_rate">"Bithastighet:"</string> <string name="details_codec">"Kodek:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d bildrutor/s"</string> <string name="details_kbps">"%1$d kbit/s"</string> <string name="details_mbps">"%1$g Mbit/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Bildalternativ"</string> <string name="video_context_menu_header">"Videoalternativ"</string> <string name="multiface_crop_help">"Peka på ett ansikte när du vill börja."</string> <string name="photos_gallery_title">"Galleri"</string> <string name="pick_photos_gallery_title">"Välj bild"</string> <string name="videos_gallery_title">"Galleri"</string> <string name="pick_videos_gallery_title">"Välj video"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> återstår"</string> <string name="sendImage">"Dela bild via"</string> <string name="setImage">"Använd bild som"</string> <string name="sendVideo">"Dela video via"</string> <string name="movieviewlabel">"Filmer"</string> <string name="loading_video">"Läser in video…"</string> <string name="spaceIsLow_title">"Utrymmet börjar ta slut"</string> <string name="spaceIsLow_content">"Ditt SD-kort börjar bli fullt. Ändra inställningen för kvalitet eller ta bort objekt från Galleri."</string> <string name="resume_playing_title">"Fortsätt spela videon"</string> <string name="resume_playing_message">"Fortsätt spela upp från %s?"</string> <string name="resume_playing_resume">"Fortsätt spela upp"</string> <string name="resume_playing_restart">"Börja om"</string> <string name="gadget_title">"Bildram"</string> <string name="file_info_title">"Filinformation:"</string> <string name="video_exceed_mms_limit">"Videon som du spelade in är för stor för att skickas via MMS. Försök spela in ett kortare klipp."</string> <string name="too_large_to_attach">"Filen är för stor för att bifogas."</string> </resources> diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml index b3a889e..68a9024 100644 --- a/res/values-zh-rCN/strings.xml +++ b/res/values-zh-rCN/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <string name="all_images">"所有照片"</string> + <string name="all_images">"所有图片"</string> <string name="all_videos">"所有视频"</string> <string name="camera_label">"相机"</string> - <string name="video_camera_label">"便携式摄像机"</string> + <string name="video_camera_label">"摄像机"</string> <string name="gallery_picker_label">"图库"</string> <string name="gallery_camera_bucket_name">"用相机拍摄的照片"</string> <string name="gallery_camera_videos_bucket_name">"用相机拍摄的视频"</string> <string name="switch_to_video_lable">"切换到视频"</string> <string name="switch_to_camera_lable">"切换到相机"</string> - <string name="crop_label">"修剪照片"</string> - <string name="view_label">"查看照片"</string> + <string name="crop_label">"修剪图片"</string> + <string name="view_label">"查看图片"</string> <string name="preferences_label">"相机设置"</string> <string name="wait">"请稍候..."</string> <string name="no_storage">"使用相机前请先插入 SD 卡。"</string> <string name="not_enough_space">"SD 卡已满。"</string> <string name="preparing_sd">"正在准备 SD 卡..."</string> <string name="wallpaper">"正在设置壁纸,请稍候..."</string> <string name="savingImage">"正在保存照片..."</string> <string name="runningFaceDetection">"请稍候..."</string> <string name="flip_orientation">"反转方向"</string> <string name="settings">"设置"</string> <string name="view">"查看"</string> <string name="details">"详细信息"</string> <string name="rotate">"旋转"</string> <string name="rotate_left">"向左旋转"</string> <string name="rotate_right">"向右旋转"</string> - <string name="slide_show">"幻灯片放映"</string> + <string name="slide_show">"播放幻灯片"</string> <string name="capture_picture">"拍摄照片"</string> <string name="capture_video">"拍摄视频"</string> <string name="crop_save_text">"保存"</string> <string name="crop_discard_text">"舍弃"</string> <string name="confirm_delete_title">"删除"</string> - <string name="confirm_delete_message">"将会删除照片。"</string> + <string name="confirm_delete_message">"将会删除此照片。"</string> <string name="confirm_delete_video_message">"将会删除视频。"</string> <string name="camera_toss">"删除"</string> <string name="camera_gallery">"图库"</string> <string name="camera_share">"分享"</string> <string name="camera_set">"设置为"</string> <string name="camera_play">"播放"</string> <string name="camera_attach">"附加"</string> <string name="camera_cancel">"取消"</string> <string name="camera_crop">"修剪"</string> <string name="camera_tossing">"正在删除..."</string> - <string name="no_way_to_share_image">"无法分享此照片。"</string> + <string name="no_way_to_share_image">"无法分享此图片。"</string> <string name="no_way_to_share_video">"无法分享此视频。"</string> <string name="video_play">"播放"</string> <string name="camera_gallery_photos_text">"图库"</string> - <string name="camera_pick_wallpaper">"照片"</string> + <string name="camera_pick_wallpaper">"图片"</string> <string name="camera_setas_wallpaper">"壁纸"</string> <string name="pref_gallery_category">"常规设置"</string> <string name="pref_slideshow_category">"幻灯片设置"</string> <string name="pref_camera_general_settings_category">"常规设置"</string> <string name="pref_gallery_size_title">"显示大小"</string> <string name="pref_gallery_size_summary">"选择图片和视频的显示大小"</string> - <string name="pref_gallery_size_dialogtitle">"照片大小"</string> + <string name="pref_gallery_size_dialogtitle">"图片大小"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"排序顺序"</string> <string name="pref_gallery_sort_summary">"选择图片和视频的排序顺序"</string> - <string name="pref_gallery_sort_dialogtitle">"照片排序"</string> + <string name="pref_gallery_sort_dialogtitle">"图片排序"</string> <string-array name="pref_gallery_sort_choices"> - <item>"最新的照片在最前面"</item> - <item>"最新的照片在最后面"</item> + <item>"最新的图片在最前面"</item> + <item>"最新的图片在最后面"</item> </string-array> - <string name="pref_gallery_slideshow_interval_title">"幻灯片放映间隔"</string> - <string name="pref_gallery_slideshow_interval_summary">"选择每张幻灯片在放映过程中持续显示的时间"</string> - <string name="pref_gallery_slideshow_interval_dialogtitle">"幻灯片放映间隔"</string> + <string name="pref_gallery_slideshow_interval_title">"幻灯片播放间隔"</string> + <string name="pref_gallery_slideshow_interval_summary">"选择每张幻灯片在播放过程中持续显示的时间"</string> + <string name="pref_gallery_slideshow_interval_dialogtitle">"幻灯片播放间隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 秒"</item> <item>"3 秒"</item> <item>"4 秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"幻灯片切换"</string> - <string name="pref_gallery_slideshow_transition_summary">"选择从一张幻灯片移动到下一张时应用的效果"</string> + <string name="pref_gallery_slideshow_transition_summary">"选择幻灯片切换时应用的效果"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"幻灯片切换"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"淡入和淡出"</item> <item>"自左至右滑动"</item> <item>"自上至下滑动"</item> <item>"随机选择"</item> </string-array> - <string name="pref_gallery_slideshow_repeat_title">"重复放映幻灯片"</string> - <string name="pref_gallery_slideshow_repeat_summary">"多次播放幻灯片"</string> - <string name="pref_gallery_slideshow_shuffle_title">"随机放映幻灯片"</string> - <string name="pref_gallery_slideshow_shuffle_summary">"以随机顺序显示照片"</string> + <string name="pref_gallery_slideshow_repeat_title">"重复播放幻灯片"</string> + <string name="pref_gallery_slideshow_repeat_summary">"循环播放幻灯片"</string> + <string name="pref_gallery_slideshow_shuffle_title">"随机播放幻灯片"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"以随机顺序显示图片"</string> <string name="pref_camera_recordlocation_title">"在照片中存储位置"</string> <string name="pref_camera_recordlocation_summary">"在照片数据中记录位置"</string> <string name="pref_camera_videoquality_category">"视频画质"</string> <string name="pref_camera_videoquality_title">"选择视频画质"</string> <string name="pref_camera_videoquality_entry_0">"低(对于彩信)"</string> <string name="pref_camera_videoquality_entry_1">"高(对于 SD 卡)"</string> <string name="pref_camera_videoquality_dialogtitle">"视频画质"</string> <string name="camerasettings">"设置"</string> <string name="image_gallery_NoImageView_text">"找不到媒体。"</string> <string name="pref_gallery_confirm_delete_title">"确认删除"</string> - <string name="pref_gallery_confirm_delete_summary">"在删除图片或视频前显示确认"</string> + <string name="pref_gallery_confirm_delete_summary">"在删除图片或视频前显示确认消息"</string> <string name="details_panel_title">"详细信息"</string> <string name="details_file_size">"文件大小:"</string> <string name="details_image_resolution">"分辨率:"</string> <string name="details_duration">"持续时间:"</string> <string name="details_date_taken">"拍摄日期:"</string> <string name="details_frame_rate">"帧频:"</string> <string name="details_bit_rate">"比特率:"</string> <string name="details_codec">"编解码器:"</string> <string name="details_format">"格式:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"确定"</string> - <string name="context_menu_header">"照片选项"</string> + <string name="context_menu_header">"图片选项"</string> <string name="video_context_menu_header">"视频选项"</string> <string name="multiface_crop_help">"点按一张脸开始裁剪。"</string> <string name="photos_gallery_title">"图库"</string> - <string name="pick_photos_gallery_title">"选择照片"</string> + <string name="pick_photos_gallery_title">"选择图片"</string> <string name="videos_gallery_title">"图库"</string> <string name="pick_videos_gallery_title">"选择视频"</string> <string name="loading_progress_format_string">"还剩 <xliff:g id="COUNTER">%d</xliff:g> 个"</string> - <string name="sendImage">"分享照片的方式"</string> - <string name="setImage">"将照片设置为"</string> + <string name="sendImage">"图片分享方式"</string> + <string name="setImage">"将图片设置为"</string> <string name="sendVideo">"分享视频的方式"</string> <string name="movieviewlabel">"电影"</string> <string name="loading_video">"正在载入视频..."</string> <string name="spaceIsLow_title">"存储空间不足"</string> <string name="spaceIsLow_content">"SD 卡空间不足。请更改画质设置或从图库中删除部分项。"</string> <string name="resume_playing_title">"重新播放视频"</string> <string name="resume_playing_message">"从 %s 开始重新播放?"</string> <string name="resume_playing_resume">"重新播放"</string> <string name="resume_playing_restart">"重新开始"</string> <string name="gadget_title">"相框"</string> <string name="file_info_title">"文件信息:"</string> <string name="video_exceed_mms_limit">"您录制的视频太大,无法用彩信发送。请尝试录制短一点的剪辑。"</string> <string name="too_large_to_attach">"文件太大,无法附加。"</string> </resources>
brunsky/WS171-packages-apps-Camera
6b7ca686049abe06c2400169f5121dc6faaaec9e
AI 150245: Import and add to the l10n builds new and updated translations for: zh_CN, es_US, ru, ko, da, el, tr, pt, pt_PT, sv.
diff --git a/res/values-da/arrays.xml b/res/values-da/arrays.xml new file mode 100644 index 0000000..dfbf090 --- /dev/null +++ b/res/values-da/arrays.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <!-- no translation found for pref_camera_videoquality_entries:0 (4155278146225809483) --> + <!-- no translation found for pref_camera_videoquality_entries:1 (2439895494739176281) --> + <string-array name="pref_camera_videoquality_entryvalues"> + <item>"0"</item> + <item>"1"</item> + </string-array> +</resources> diff --git a/res/values-da/strings.xml b/res/values-da/strings.xml new file mode 100644 index 0000000..afbde5b --- /dev/null +++ b/res/values-da/strings.xml @@ -0,0 +1,155 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <string name="all_images">"Alle billeder"</string> + <string name="all_videos">"Alle videoer"</string> + <string name="camera_label">"Kamera"</string> + <string name="video_camera_label">"Videokamera"</string> + <string name="gallery_picker_label">"Galleri"</string> + <string name="gallery_camera_bucket_name">"Kamerabilleder"</string> + <string name="gallery_camera_videos_bucket_name">"Kameravideoer"</string> + <string name="switch_to_video_lable">"Skift til video"</string> + <string name="switch_to_camera_lable">"Skift til kamera"</string> + <string name="crop_label">"Beskær billede"</string> + <string name="view_label">"Vis billede"</string> + <string name="preferences_label">"Kameraindstillinger"</string> + <string name="wait">"Vent ..."</string> + <string name="no_storage">"Indsæt et SD-kort, inden du bruger kameraet."</string> + <string name="not_enough_space">"Dit SD-kort er fuldt."</string> + <string name="preparing_sd">"Forbereder SD-kort ..."</string> + <string name="wallpaper">"Indstiller tapet. Vent et øjeblik ..."</string> + <string name="savingImage">"Gemmer billede ..."</string> + <string name="runningFaceDetection">"Vent ..."</string> + <string name="flip_orientation">"Skift retning"</string> + <string name="settings">"Indstillinger"</string> + <string name="view">"Vis"</string> + <string name="details">"Detaljer"</string> + <string name="rotate">"Roter"</string> + <string name="rotate_left">"Roter til venstre"</string> + <string name="rotate_right">"Roter til højre"</string> + <string name="slide_show">"Diasshow"</string> + <string name="capture_picture">"Fotografer billede"</string> + <string name="capture_video">"Fotografer video"</string> + <string name="crop_save_text">"Gem"</string> + <string name="crop_discard_text">"Kassér"</string> + <string name="confirm_delete_title">"Slet"</string> + <string name="confirm_delete_message">"Billedet slettes."</string> + <string name="confirm_delete_video_message">"Videoen slettes."</string> + <string name="camera_toss">"Slet"</string> + <string name="camera_gallery">"Galleri"</string> + <string name="camera_share">"Del"</string> + <string name="camera_set">"Indstil som"</string> + <string name="camera_play">"Afspil"</string> + <string name="camera_attach">"Vedhæft"</string> + <string name="camera_cancel">"Annuller"</string> + <string name="camera_crop">"Beskær"</string> + <string name="camera_tossing">"Sletter ..."</string> + <string name="no_way_to_share_image">"Dette billede kan ikke deles."</string> + <string name="no_way_to_share_video">"Denne video kan ikke deles."</string> + <string name="video_play">"Afspil"</string> + <string name="camera_gallery_photos_text">"Galleri"</string> + <string name="camera_pick_wallpaper">"Billeder"</string> + <string name="camera_setas_wallpaper">"Tapet"</string> + <string name="pref_gallery_category">"Generelle indstillinger"</string> + <string name="pref_slideshow_category">"Diasshowindstillinger"</string> + <string name="pref_camera_general_settings_category">"Generelle indstillinger"</string> + <string name="pref_gallery_size_title">"Visningsstørrelse"</string> + <string name="pref_gallery_size_summary">"Vælg, hvilken størrelse billeder og videoer skal vises i"</string> + <string name="pref_gallery_size_dialogtitle">"Billedstørrelse"</string> + <string-array name="pref_gallery_size_choices"> + <item>"Stor"</item> + <item>"Lille"</item> + </string-array> + <string name="pref_gallery_sort_title">"Sorter rækkefølge"</string> + <string name="pref_gallery_sort_summary">"Vælg rækkefølge på billeder og videoer"</string> + <string name="pref_gallery_sort_dialogtitle">"Sorter billeder"</string> + <string-array name="pref_gallery_sort_choices"> + <item>"Nyeste først"</item> + <item>"Nyeste sidst"</item> + </string-array> + <string name="pref_gallery_slideshow_interval_title">"Diasshowinterval"</string> + <string name="pref_gallery_slideshow_interval_summary">"Vælg, hvor længe hvert dias skal vises i showet"</string> + <string name="pref_gallery_slideshow_interval_dialogtitle">"Diasshowinterval"</string> + <string-array name="pref_gallery_slideshow_interval_choices"> + <item>"2 sekunder"</item> + <item>"3 sekunder"</item> + <item>"4 sekunder"</item> + </string-array> + <string name="pref_gallery_slideshow_transition_title">"Diasshowovergang"</string> + <string name="pref_gallery_slideshow_transition_summary">"Vælg den effekt, der skal bruges, når man går fra et dias til det næste"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"Diasshowovergang"</string> + <string-array name="pref_gallery_slideshow_transition_choices"> + <item>"Ton ind og ud"</item> + <item>"Glid til venstre – højre"</item> + <item>"Glid op – ned"</item> + <item>"Tilfældigt udvalg"</item> + </string-array> + <string name="pref_gallery_slideshow_repeat_title">"Gentag diasshow"</string> + <string name="pref_gallery_slideshow_repeat_summary">"Afspil diasshow mere end en gang"</string> + <string name="pref_gallery_slideshow_shuffle_title">"Bland dias"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"Vis billeder i tilfældig rækkefølge"</string> + <string name="pref_camera_recordlocation_title">"Gem placeringer i billeder"</string> + <string name="pref_camera_recordlocation_summary">"Registrer placering i billeddata"</string> + <string name="pref_camera_videoquality_category">"Videokvalitet"</string> + <string name="pref_camera_videoquality_title">"Vælg videokvalitet"</string> + <string name="pref_camera_videoquality_entry_0">"Lav (til MMS-beskeder)"</string> + <string name="pref_camera_videoquality_entry_1">"Høj (til SD-kort)"</string> + <string name="pref_camera_videoquality_dialogtitle">"Videokvalitet"</string> + <string name="camerasettings">"Indstillinger"</string> + <string name="image_gallery_NoImageView_text">"Der blev ikke fundet nogen medier."</string> + <string name="pref_gallery_confirm_delete_title">"Bekræft sletninger"</string> + <string name="pref_gallery_confirm_delete_summary">"Vis bekræftelse, inden der slettes et billede eller en video"</string> + <string name="details_panel_title">"Detaljer"</string> + <string name="details_file_size">"Filstørrelse:"</string> + <string name="details_image_resolution">"Opløsning:"</string> + <string name="details_duration">"Varighed:"</string> + <string name="details_date_taken">"Dato taget:"</string> + <string name="details_frame_rate">"Rammefrekvens"</string> + <string name="details_bit_rate">"Bithastighed:"</string> + <string name="details_codec">"Codec:"</string> + <string name="details_format">"Format:"</string> + <string name="details_dimension_x">"%1$d x %2$d"</string> + <string name="details_ms">"%1$02d:%2$02d"</string> + <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> + <string name="details_fps">"%1$d fps"</string> + <string name="details_kbps">"%1$d Kbps"</string> + <string name="details_mbps">"%1$g Mbps"</string> + <string name="details_ok">"OK"</string> + <string name="context_menu_header">"Billedvalgmuligheder"</string> + <string name="video_context_menu_header">"Videovalgmuligheder"</string> + <string name="multiface_crop_help">"Tryk på et ansigt for at begynde."</string> + <string name="photos_gallery_title">"Galleri"</string> + <string name="pick_photos_gallery_title">"Vælg billede"</string> + <string name="videos_gallery_title">"Galleri"</string> + <string name="pick_videos_gallery_title">"Vælg video"</string> + <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> tilbage"</string> + <string name="sendImage">"Del billede via"</string> + <string name="setImage">"Indstil billedet som"</string> + <string name="sendVideo">"Del video via"</string> + <string name="movieviewlabel">"Film"</string> + <string name="loading_video">"Indlæser video ..."</string> + <string name="spaceIsLow_title">"Der er ikke så meget plads"</string> + <string name="spaceIsLow_content">"Dit SD-kort er ved at løbe tør for plads. Skift kvalitetsindstillingerne, eller slet elementer fra Galleriet."</string> + <string name="resume_playing_title">"Genoptag video"</string> + <string name="resume_playing_message">"Genoptag afspilning fra %s ?"</string> + <string name="resume_playing_resume">"Genoptag afspilning"</string> + <string name="resume_playing_restart">"Start igen"</string> + <string name="gadget_title">"Billedramme"</string> + <string name="file_info_title">"Filoplysninger:"</string> + <string name="video_exceed_mms_limit">"Den video, du optog, er for stor til at sende via MMS. Prøv at optage et klip af kortere varighed."</string> + <string name="too_large_to_attach">"Filen er for stor til at vedhæfte."</string> +</resources> diff --git a/res/values-el/arrays.xml b/res/values-el/arrays.xml new file mode 100644 index 0000000..dfbf090 --- /dev/null +++ b/res/values-el/arrays.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <!-- no translation found for pref_camera_videoquality_entries:0 (4155278146225809483) --> + <!-- no translation found for pref_camera_videoquality_entries:1 (2439895494739176281) --> + <string-array name="pref_camera_videoquality_entryvalues"> + <item>"0"</item> + <item>"1"</item> + </string-array> +</resources> diff --git a/res/values-el/strings.xml b/res/values-el/strings.xml new file mode 100644 index 0000000..663986a --- /dev/null +++ b/res/values-el/strings.xml @@ -0,0 +1,155 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <string name="all_images">"Όλες οι εικόνες"</string> + <string name="all_videos">"Όλα τα βίντεο"</string> + <string name="camera_label">"Φωτογραφική μηχανή"</string> + <string name="video_camera_label">"Βιντεοκάμερα"</string> + <string name="gallery_picker_label">"Συλλογή"</string> + <string name="gallery_camera_bucket_name">"Εικόνες φωτογραφικής μηχανής"</string> + <string name="gallery_camera_videos_bucket_name">"Βίντεο φωτογραφικής μηχανής"</string> + <string name="switch_to_video_lable">"Αλλαγή σε λειτουργία βίντεο"</string> + <string name="switch_to_camera_lable">"Αλλαγή σε λειτουργία φωτογραφικής μηχανής"</string> + <string name="crop_label">"Περικοπή εικόνας"</string> + <string name="view_label">"Προβολή εικόνας"</string> + <string name="preferences_label">"Ρυθμίσεις φωτογραφικής μηχανής"</string> + <string name="wait">"Περιμένετε..."</string> + <string name="no_storage">"Πριν χρησιμοποιήσετε τη φωτογραφική μηχανή, εισάγετε μία κάρτα SD."</string> + <string name="not_enough_space">"Η κάρτα SD είναι πλήρης."</string> + <string name="preparing_sd">"Προετοιμασία κάρτας SD…"</string> + <string name="wallpaper">"Ρύθμιση ταπετσαρίας, περιμένετε..."</string> + <string name="savingImage">"Αποθήκευση εικόνας..."</string> + <string name="runningFaceDetection">"Περιμένετε..."</string> + <string name="flip_orientation">"Αλλαγή προσανατολισμού"</string> + <string name="settings">"Ρυθμίσεις"</string> + <string name="view">"Προβολή"</string> + <string name="details">"Λεπτομέρειες"</string> + <string name="rotate">"Περιστροφή"</string> + <string name="rotate_left">"Αριστερή περιστροφή"</string> + <string name="rotate_right">"Δεξιά περιστροφή"</string> + <string name="slide_show">"Προβολή διαφανειών (slideshow)"</string> + <string name="capture_picture">"Λήψη εικόνας"</string> + <string name="capture_video">"Λήψη βίντεο"</string> + <string name="crop_save_text">"Αποθήκευση"</string> + <string name="crop_discard_text">"Απόρριψη"</string> + <string name="confirm_delete_title">"Διαγραφή"</string> + <string name="confirm_delete_message">"Η εικόνα θα διαγραφεί."</string> + <string name="confirm_delete_video_message">"Το βίντεο θα διαγραφεί."</string> + <string name="camera_toss">"Διαγραφή"</string> + <string name="camera_gallery">"Συλλογή"</string> + <string name="camera_share">"Κοινή χρήση"</string> + <string name="camera_set">"Ορισμός ως"</string> + <string name="camera_play">"Αναπαραγωγή"</string> + <string name="camera_attach">"Επισύναψη"</string> + <string name="camera_cancel">"Ακύρωση"</string> + <string name="camera_crop">"Περικοπή"</string> + <string name="camera_tossing">"Διαγραφή..."</string> + <string name="no_way_to_share_image">"Δεν είναι δυνατή η κοινή χρήση αυτής της εικόνας."</string> + <string name="no_way_to_share_video">"Δεν είναι δυνατή η κοινή χρήση αυτού του βίντεο."</string> + <string name="video_play">"Αναπαραγωγή"</string> + <string name="camera_gallery_photos_text">"Συλλογή"</string> + <string name="camera_pick_wallpaper">"Εικόνες"</string> + <string name="camera_setas_wallpaper">"Ταπετσαρία"</string> + <string name="pref_gallery_category">"Γενικές ρυθμίσεις"</string> + <string name="pref_slideshow_category">"Ρυθμίσεις προβολής διαφανειών (slideshow)"</string> + <string name="pref_camera_general_settings_category">"Γενικές ρυθμίσεις"</string> + <string name="pref_gallery_size_title">"Μέγεθος προβολής"</string> + <string name="pref_gallery_size_summary">"Επιλέξτε το μέγεθος προβολής των εικόνων και των βίντεο"</string> + <string name="pref_gallery_size_dialogtitle">"Μέγεθος εικόνας"</string> + <string-array name="pref_gallery_size_choices"> + <item>"Μεγάλο"</item> + <item>"Μικρό"</item> + </string-array> + <string name="pref_gallery_sort_title">"Σειρά ταξινόμησης"</string> + <string name="pref_gallery_sort_summary">"Επιλέξτε τη σειρά ταξινόμησης των εικόνων και των βίντεο"</string> + <string name="pref_gallery_sort_dialogtitle">"Ταξινόμηση εικόνων"</string> + <string-array name="pref_gallery_sort_choices"> + <item>"Πρώτα οι πιο πρόσφατες"</item> + <item>"Οι πιο πρόσφατες τελευταίες"</item> + </string-array> + <string name="pref_gallery_slideshow_interval_title">"Διάστημα προβολής διαφανειών (slideshow)"</string> + <string name="pref_gallery_slideshow_interval_summary">"Επιλέξτε πόση ώρα θα προβάλλεται κάθε διαφάνεια στην προβολή διαφανειών"</string> + <string name="pref_gallery_slideshow_interval_dialogtitle">"Διάστημα προβολής διαφανειών (slideshow)"</string> + <string-array name="pref_gallery_slideshow_interval_choices"> + <item>"2 δευτερόλεπτα"</item> + <item>"3 δευτερόλεπτα"</item> + <item>"4 δευτερόλεπτα"</item> + </string-array> + <string name="pref_gallery_slideshow_transition_title">"Εναλλαγή προβολής διαφανειών (slideshow)"</string> + <string name="pref_gallery_slideshow_transition_summary">"Επιλέξτε το εφέ που θα χρησιμοποιηθεί κατά τη μετάβαση από τη μία διαφάνεια στην επόμενη"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"Εναλλαγή προβολής διαφανειών (slideshow)"</string> + <string-array name="pref_gallery_slideshow_transition_choices"> + <item>"Σταδιακή εμφάνιση &amp; εξαφάνιση"</item> + <item>"Ολίσθηση αριστερά - δεξιά"</item> + <item>"Ολίσθηση πάνω - κάτω"</item> + <item>"Τυχαία επιλογή"</item> + </string-array> + <string name="pref_gallery_slideshow_repeat_title">"Επανάληψη προβολής διαφανειών (slideshow)"</string> + <string name="pref_gallery_slideshow_repeat_summary">"Αναπαραγωγή προβολής διαφανειών (slideshow) περισσότερες από μία φορά"</string> + <string name="pref_gallery_slideshow_shuffle_title">"Τυχαία αναπαραγωγή διαφανειών"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"Εμφάνιση εικόνων με τυχαία σειρά"</string> + <string name="pref_camera_recordlocation_title">"Αποθήκευση τοποθεσίας στις εικόνες"</string> + <string name="pref_camera_recordlocation_summary">"Εγγραφή τοποθεσίας στα δεδομένα εικόνας"</string> + <string name="pref_camera_videoquality_category">"Ποιότητα βίντεο"</string> + <string name="pref_camera_videoquality_title">"Επιλογή ποιότητας βίντεο"</string> + <string name="pref_camera_videoquality_entry_0">"Χαμηλή (για μηνύματα MMS)"</string> + <string name="pref_camera_videoquality_entry_1">"Υψηλή (για κάρτα SD)"</string> + <string name="pref_camera_videoquality_dialogtitle">"Ποιότητα βίντεο"</string> + <string name="camerasettings">"Ρυθμίσεις"</string> + <string name="image_gallery_NoImageView_text">"Δεν βρέθηκαν μέσα."</string> + <string name="pref_gallery_confirm_delete_title">"Επιβεβαίωση διαγραφών"</string> + <string name="pref_gallery_confirm_delete_summary">"Εμφάνιση μηνύματος επιβεβαίωσης πριν τη διαγραφή μιας εικόνας ή ενός βίντεο"</string> + <string name="details_panel_title">"Λεπτομέρειες"</string> + <string name="details_file_size">"Μέγεθος αρχείου:"</string> + <string name="details_image_resolution">"Ανάλυση:"</string> + <string name="details_duration">"Διάρκεια:"</string> + <string name="details_date_taken">"Ημερομηνία λήψης:"</string> + <string name="details_frame_rate">"Ρυθμός καρέ:"</string> + <string name="details_bit_rate">"Ρυθμός δεδομένων:"</string> + <string name="details_codec">"Κωδικοποιητής:"</string> + <string name="details_format">"Μορφή:"</string> + <string name="details_dimension_x">"%1$d x %2$d"</string> + <string name="details_ms">"%1$02d:%2$02d"</string> + <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> + <string name="details_fps">"%1$d fps"</string> + <string name="details_kbps">"%1$d Kbps"</string> + <string name="details_mbps">"%1$g Mbps"</string> + <string name="details_ok">"OK"</string> + <string name="context_menu_header">"Επιλογές εικόνας"</string> + <string name="video_context_menu_header">"Επιλογές βίντεο"</string> + <string name="multiface_crop_help">"Πατήστε σε ένα πρόσωπο για να ξεκινήσετε."</string> + <string name="photos_gallery_title">"Συλλογή"</string> + <string name="pick_photos_gallery_title">"Επιλογή εικόνας"</string> + <string name="videos_gallery_title">"Συλλογή"</string> + <string name="pick_videos_gallery_title">"Επιλογή βίντεο"</string> + <string name="loading_progress_format_string">"Απομένουν <xliff:g id="COUNTER">%d</xliff:g>"</string> + <string name="sendImage">"Κοινή χρήση εικόνας μέσω"</string> + <string name="setImage">"Ορισμός εικόνας ως"</string> + <string name="sendVideo">"Κοινή χρήση βίντεο μέσω"</string> + <string name="movieviewlabel">"Ταινίες"</string> + <string name="loading_video">"Φόρτωση βίντεο..."</string> + <string name="spaceIsLow_title">"Ο διαθέσιμος χώρος είναι ελάχιστος"</string> + <string name="spaceIsLow_content">"Ο διαθέσιμος χώρος στην κάρτα SD είναι ελάχιστος. Αλλάξτε τη ρύθμιση ποιότητας ή διαγράψτε στοιχεία από τη συλλογή."</string> + <string name="resume_playing_title">"Συνέχιση βίντεο"</string> + <string name="resume_playing_message">"Συνέχιση αναπαραγωγής από το %s;"</string> + <string name="resume_playing_resume">"Συνέχιση αναπαραγωγής"</string> + <string name="resume_playing_restart">"Έναρξη από την αρχή"</string> + <string name="gadget_title">"Πλαίσιο εικόνας"</string> + <string name="file_info_title">"Πληροφορίες αρχείου:"</string> + <string name="video_exceed_mms_limit">"Το βίντεο που εγγράψατε είναι πολύ μεγάλο για να αποσταλεί μέσω μηνύματος MMS. Δοκιμάστε να εγγράψετε μικρότερου μεγέθους βίντεο."</string> + <string name="too_large_to_attach">"Πολύ μεγάλο αρχείο για επισύναψη."</string> +</resources> diff --git a/res/values-es-rUS/arrays.xml b/res/values-es-rUS/arrays.xml new file mode 100644 index 0000000..dfbf090 --- /dev/null +++ b/res/values-es-rUS/arrays.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <!-- no translation found for pref_camera_videoquality_entries:0 (4155278146225809483) --> + <!-- no translation found for pref_camera_videoquality_entries:1 (2439895494739176281) --> + <string-array name="pref_camera_videoquality_entryvalues"> + <item>"0"</item> + <item>"1"</item> + </string-array> +</resources> diff --git a/res/values-es-rUS/strings.xml b/res/values-es-rUS/strings.xml new file mode 100644 index 0000000..a8b3b51 --- /dev/null +++ b/res/values-es-rUS/strings.xml @@ -0,0 +1,155 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <string name="all_images">"Todas las imágenes"</string> + <string name="all_videos">"Todos los videos"</string> + <string name="camera_label">"Cámara"</string> + <string name="video_camera_label">"Cámara de video"</string> + <string name="gallery_picker_label">"Galería"</string> + <string name="gallery_camera_bucket_name">"Imágenes de la cámara"</string> + <string name="gallery_camera_videos_bucket_name">"Videos de la cámara"</string> + <string name="switch_to_video_lable">"Cambiar a video"</string> + <string name="switch_to_camera_lable">"Cambiar a cámara"</string> + <string name="crop_label">"Cortar la imagen"</string> + <string name="view_label">"Ver imagen"</string> + <string name="preferences_label">"Configuración de cámara"</string> + <string name="wait">"Espera, por favor..."</string> + <string name="no_storage">"Inserta una tarjeta SD antes de utilizar la cámara."</string> + <string name="not_enough_space">"Tu tarjeta SD está llena."</string> + <string name="preparing_sd">"Preparando la tarjeta SD..."</string> + <string name="wallpaper">"Configurando papel tapiz. Espera, por favor..."</string> + <string name="savingImage">"Guardando imagen..."</string> + <string name="runningFaceDetection">"Espera, por favor..."</string> + <string name="flip_orientation">"Girar la orientación"</string> + <string name="settings">"Configuración"</string> + <string name="view">"Ver"</string> + <string name="details">"Detalles"</string> + <string name="rotate">"Rotar"</string> + <string name="rotate_left">"Rotar hacia la izquierda"</string> + <string name="rotate_right">"Rotar hacia la derecha"</string> + <string name="slide_show">"Presentación de diapositivas"</string> + <string name="capture_picture">"Capturar imagen"</string> + <string name="capture_video">"Capturar video"</string> + <string name="crop_save_text">"Guardar"</string> + <string name="crop_discard_text">"Eliminar"</string> + <string name="confirm_delete_title">"Eliminar"</string> + <string name="confirm_delete_message">"La imagen se eliminará."</string> + <string name="confirm_delete_video_message">"El video se eliminará."</string> + <string name="camera_toss">"Eliminar"</string> + <string name="camera_gallery">"Galería"</string> + <string name="camera_share">"Compartir"</string> + <string name="camera_set">"Definir como"</string> + <string name="camera_play">"Reproducir"</string> + <string name="camera_attach">"Adjuntar"</string> + <string name="camera_cancel">"Cancelar"</string> + <string name="camera_crop">"Cortar"</string> + <string name="camera_tossing">"Eliminando..."</string> + <string name="no_way_to_share_image">"Esta imagen no se puede compartir."</string> + <string name="no_way_to_share_video">"Este video no se puede compartir."</string> + <string name="video_play">"Reproducir"</string> + <string name="camera_gallery_photos_text">"Galería"</string> + <string name="camera_pick_wallpaper">"Imágenes"</string> + <string name="camera_setas_wallpaper">"Papel tapiz"</string> + <string name="pref_gallery_category">"Configuración general"</string> + <string name="pref_slideshow_category">"Configuración de presentación de diapositivas"</string> + <string name="pref_camera_general_settings_category">"Configuración general"</string> + <string name="pref_gallery_size_title">"Visualizar tamaño"</string> + <string name="pref_gallery_size_summary">"Seleccionar el tamaño de visualización de imágenes y videos"</string> + <string name="pref_gallery_size_dialogtitle">"Tamaño de imagen"</string> + <string-array name="pref_gallery_size_choices"> + <item>"Grande"</item> + <item>"Pequeño"</item> + </string-array> + <string name="pref_gallery_sort_title">"Ordenar"</string> + <string name="pref_gallery_sort_summary">"Selecciona el orden de imágenes y videos"</string> + <string name="pref_gallery_sort_dialogtitle">"Orden de imágenes"</string> + <string-array name="pref_gallery_sort_choices"> + <item>"Lo más nuevo primero"</item> + <item>"Lo más nuevo al final"</item> + </string-array> + <string name="pref_gallery_slideshow_interval_title">"Intervalo de la presentación"</string> + <string name="pref_gallery_slideshow_interval_summary">"Seleccionar cuánto tiempo se visualizará cada diapositiva en la presentación"</string> + <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo de la presentación"</string> + <string-array name="pref_gallery_slideshow_interval_choices"> + <item>"2 segundos"</item> + <item>"3 segundos"</item> + <item>"4 segundos"</item> + </string-array> + <string name="pref_gallery_slideshow_transition_title">"Transición de la presentación de diapositivas"</string> + <string name="pref_gallery_slideshow_transition_summary">"Seleccionar el efecto utilizado al pasar de una diapositiva a otra"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"Transición de la presentación de diapositivas"</string> + <string-array name="pref_gallery_slideshow_transition_choices"> + <item>"Fundido de entrada/salida"</item> + <item>"Deslizar hacia la izquierda/derecha"</item> + <item>"Deslizar hacia arriba/abajo"</item> + <item>"Selección aleatoria"</item> + </string-array> + <string name="pref_gallery_slideshow_repeat_title">"Repetir la presentación"</string> + <string name="pref_gallery_slideshow_repeat_summary">"Reproducir la presentación de diapositivas más de una vez"</string> + <string name="pref_gallery_slideshow_shuffle_title">"Arrastrar diapositivas"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imágenes en orden aleatorio"</string> + <string name="pref_camera_recordlocation_title">"Almacenar ubicación en imágenes"</string> + <string name="pref_camera_recordlocation_summary">"Grabar la ubicación en los datos de la imagen"</string> + <string name="pref_camera_videoquality_category">"Calidad del video"</string> + <string name="pref_camera_videoquality_title">"Seleccionar calidad de video"</string> + <string name="pref_camera_videoquality_entry_0">"Bajo (para mensajes MMS)"</string> + <string name="pref_camera_videoquality_entry_1">"Alta (para tarjeta SD)"</string> + <string name="pref_camera_videoquality_dialogtitle">"Calidad del video"</string> + <string name="camerasettings">"Configuración"</string> + <string name="image_gallery_NoImageView_text">"No se han encontrado medios."</string> + <string name="pref_gallery_confirm_delete_title">"Confirmar eliminaciones"</string> + <string name="pref_gallery_confirm_delete_summary">"Mostrar configuración antes de eliminar una imagen o un video"</string> + <string name="details_panel_title">"Detalles"</string> + <string name="details_file_size">"Tamaño de archivo:"</string> + <string name="details_image_resolution">"Resolución:"</string> + <string name="details_duration">"Duración:"</string> + <string name="details_date_taken">"Fecha:"</string> + <string name="details_frame_rate">"Frecuencia de visualización:"</string> + <string name="details_bit_rate">"Frecuencia de bits:"</string> + <string name="details_codec">"Códec:"</string> + <string name="details_format">"Formato:"</string> + <string name="details_dimension_x">"%1$d x %2$d"</string> + <string name="details_ms">"%1$02d:%2$02d"</string> + <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> + <string name="details_fps">"%1$d fps"</string> + <string name="details_kbps">"%1$d Kbps"</string> + <string name="details_mbps">"%1$g Mbps"</string> + <string name="details_ok">"Aceptar"</string> + <string name="context_menu_header">"Opciones de imagen"</string> + <string name="video_context_menu_header">"Opciones de video"</string> + <string name="multiface_crop_help">"Golpea una cara para comenzar."</string> + <string name="photos_gallery_title">"Galería"</string> + <string name="pick_photos_gallery_title">"Seleccionar imagen"</string> + <string name="videos_gallery_title">"Galería"</string> + <string name="pick_videos_gallery_title">"Seleccionar video"</string> + <string name="loading_progress_format_string">"Quedan <xliff:g id="COUNTER">%d</xliff:g>"</string> + <string name="sendImage">"Compartir imagen mediante"</string> + <string name="setImage">"Definir imagen como"</string> + <string name="sendVideo">"Compartir video mediante"</string> + <string name="movieviewlabel">"Películas"</string> + <string name="loading_video">"Cargando el video..."</string> + <string name="spaceIsLow_title">"El espacio es pequeño"</string> + <string name="spaceIsLow_content">"Tu tarjeta SD se está quedando sin espacio. Cambia la configuración de calidad o elimina elementos de la galería."</string> + <string name="resume_playing_title">"Retomar video"</string> + <string name="resume_playing_message">"¿Deseas retomar la reproducción desde %s?"</string> + <string name="resume_playing_resume">"Retomar la reproducción"</string> + <string name="resume_playing_restart">"Empezar de nuevo"</string> + <string name="gadget_title">"Marco de imagen"</string> + <string name="file_info_title">"Información del archivo:"</string> + <string name="video_exceed_mms_limit">"El video que has grabado es demasiado grande para enviarlo por MMS. Intenta grabar uno más corto."</string> + <string name="too_large_to_attach">"El archivo es demasiado grande para adjuntarlo."</string> +</resources> diff --git a/res/values-ko/strings.xml b/res/values-ko/strings.xml index b1b4e24..6f958e0 100644 --- a/res/values-ko/strings.xml +++ b/res/values-ko/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"모든 사진"</string> <string name="all_videos">"모든 동영상"</string> <string name="camera_label">"카메라"</string> <string name="video_camera_label">"캠코더"</string> <string name="gallery_picker_label">"갤러리"</string> <string name="gallery_camera_bucket_name">"카메라 사진"</string> <string name="gallery_camera_videos_bucket_name">"카메라 동영상"</string> <string name="switch_to_video_lable">"동영상으로 전환"</string> <string name="switch_to_camera_lable">"카메라로 전환"</string> <string name="crop_label">"사진 자르기"</string> <string name="view_label">"사진 보기"</string> <string name="preferences_label">"카메라 설정"</string> <string name="wait">"잠시 기다려 주세요..."</string> - <string name="no_storage">"카메라를 사용하기 전에 먼저 SD 카드를 넣으세요."</string> + <string name="no_storage">"카메라를 사용하려면 SD 카드를 넣으세요."</string> <string name="not_enough_space">"SD 카드가 꽉 찼습니다."</string> <string name="preparing_sd">"SD 카드 준비중..."</string> - <string name="wallpaper">"배경화면 설정 중. 잠시 기다려 주세요..."</string> + <string name="wallpaper">"배경화면을 설정하는 중입니다. 잠시 기다려 주세요..."</string> <string name="savingImage">"사진 저장 중..."</string> <string name="runningFaceDetection">"잠시 기다려 주세요..."</string> <string name="flip_orientation">"방향 바꾸기"</string> <string name="settings">"설정"</string> <string name="view">"보기"</string> - <string name="details">"상세정보"</string> + <string name="details">"세부정보"</string> <string name="rotate">"회전"</string> <string name="rotate_left">"왼쪽으로 회전"</string> <string name="rotate_right">"오른쪽으로 회전"</string> <string name="slide_show">"슬라이드쇼"</string> <string name="capture_picture">"사진촬영"</string> <string name="capture_video">"동영상 캡처"</string> <string name="crop_save_text">"저장"</string> - <string name="crop_discard_text">"무시"</string> + <string name="crop_discard_text">"취소"</string> <string name="confirm_delete_title">"삭제"</string> <string name="confirm_delete_message">"사진이 삭제됩니다."</string> <string name="confirm_delete_video_message">"동영상이 삭제됩니다."</string> <string name="camera_toss">"삭제"</string> <string name="camera_gallery">"갤러리"</string> <string name="camera_share">"공유"</string> - <string name="camera_set">"사진 설정"</string> + <string name="camera_set">"다음으로 설정"</string> <string name="camera_play">"재생"</string> <string name="camera_attach">"첨부"</string> <string name="camera_cancel">"취소"</string> <string name="camera_crop">"자르기"</string> <string name="camera_tossing">"삭제 중..."</string> - <string name="no_way_to_share_image">"공유할 수 없는 사진입니다."</string> - <string name="no_way_to_share_video">"공유할 수 없는 동영상입니다."</string> + <string name="no_way_to_share_image">"사진을 공유할 수 없습니다."</string> + <string name="no_way_to_share_video">"동영상을 공유할 수 없습니다."</string> <string name="video_play">"재생"</string> <string name="camera_gallery_photos_text">"갤러리"</string> <string name="camera_pick_wallpaper">"사진"</string> <string name="camera_setas_wallpaper">"배경화면"</string> <string name="pref_gallery_category">"일반 설정"</string> <string name="pref_slideshow_category">"슬라이드쇼 설정"</string> <string name="pref_camera_general_settings_category">"일반 설정"</string> <string name="pref_gallery_size_title">"디스플레이 크기"</string> <string name="pref_gallery_size_summary">"사진 및 동영상 표시 크기 선택"</string> <string name="pref_gallery_size_dialogtitle">"사진 크기"</string> <string-array name="pref_gallery_size_choices"> <item>"크게"</item> <item>"작게"</item> </string-array> <string name="pref_gallery_sort_title">"정렬 순서"</string> <string name="pref_gallery_sort_summary">"사진 및 동영상 정렬 순서 선택"</string> <string name="pref_gallery_sort_dialogtitle">"사진 정렬"</string> <string-array name="pref_gallery_sort_choices"> <item>"가장 최근 사진 먼저"</item> - <item>"가장 최근 사진 마지막에"</item> + <item>"가장 오래된 사진 먼저"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"슬라이드쇼 간격"</string> <string name="pref_gallery_slideshow_interval_summary">"쇼에서 각 슬라이드를 표시할 시간 선택"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"슬라이드쇼 간격"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2초"</item> <item>"3초"</item> <item>"4초"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"슬라이드쇼 화면전환"</string> <string name="pref_gallery_slideshow_transition_summary">"슬라이드 간에 이동할 때 사용할 효과 선택"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"슬라이드쇼 화면전환"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"페이드 인/아웃"</item> - <item>"왼쪽에서 오른쪽으로/오른쪽에서 왼쪽으로"</item> - <item>"위에서 아래로/아래에서 위로"</item> + <item>"슬라이드 왼쪽 - 오른쪽"</item> + <item>"슬라이드 위 - 아래"</item> <item>"무작위 선택"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"슬라이드쇼 반복"</string> <string name="pref_gallery_slideshow_repeat_summary">"슬라이드쇼를 한 번 이상 재생"</string> <string name="pref_gallery_slideshow_shuffle_title">"슬라이드 섞기"</string> - <string name="pref_gallery_slideshow_shuffle_summary">"사진을 무작위 순서로 표시"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"무작위로 사진 표시"</string> <string name="pref_camera_recordlocation_title">"사진에 위치 저장"</string> <string name="pref_camera_recordlocation_summary">"사진 데이터에 위치 기록"</string> <string name="pref_camera_videoquality_category">"동영상 화질"</string> <string name="pref_camera_videoquality_title">"동영상 화질 선택"</string> - <string name="pref_camera_videoquality_entry_0">"낮음(MMS 메시지용)"</string> + <string name="pref_camera_videoquality_entry_0">"저화질(MMS 메시지용)"</string> <string name="pref_camera_videoquality_entry_1">"높음(SD 카드용)"</string> <string name="pref_camera_videoquality_dialogtitle">"동영상 화질"</string> <string name="camerasettings">"설정"</string> <string name="image_gallery_NoImageView_text">"미디어 파일이 없습니다."</string> <string name="pref_gallery_confirm_delete_title">"삭제 확인"</string> <string name="pref_gallery_confirm_delete_summary">"사진 및 동영상 삭제 전 확인 표시"</string> - <string name="details_panel_title">"상세정보"</string> + <string name="details_panel_title">"세부정보"</string> <string name="details_file_size">"파일 크기:"</string> <string name="details_image_resolution">"해상도:"</string> <string name="details_duration">"재생 시간:"</string> - <string name="details_date_taken">"찍은 날짜:"</string> + <string name="details_date_taken">"촬영 날짜:"</string> <string name="details_frame_rate">"프레임 속도:"</string> <string name="details_bit_rate">"비트 전송률:"</string> <string name="details_codec">"코덱:"</string> <string name="details_format">"형식:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$dfps"</string> <string name="details_kbps">"%1$dKbps"</string> <string name="details_mbps">"%1$gMbps"</string> <string name="details_ok">"확인"</string> <string name="context_menu_header">"사진 옵션"</string> <string name="video_context_menu_header">"동영상 옵션"</string> <string name="multiface_crop_help">"시작하려면 얼굴을 탭하세요."</string> <string name="photos_gallery_title">"갤러리"</string> <string name="pick_photos_gallery_title">"사진 선택"</string> <string name="videos_gallery_title">"갤러리"</string> <string name="pick_videos_gallery_title">"동영상 선택"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g>개 남음"</string> <string name="sendImage">"사진 공유 응용프로그램"</string> - <string name="setImage">"사진 설정"</string> + <string name="setImage">"사진을 다음으로 설정"</string> <string name="sendVideo">"동영상 공유 응용프로그램"</string> <string name="movieviewlabel">"영화"</string> <string name="loading_video">"동영상 로드 중..."</string> - <string name="spaceIsLow_title">"공간부족"</string> + <string name="spaceIsLow_title">"공간 부족"</string> <string name="spaceIsLow_content">"SD 카드의 공간이 부족합니다. 화질 설정을 변경하거나 갤러리에서 항목을 삭제하세요."</string> <string name="resume_playing_title">"동영상 다시 시작"</string> <string name="resume_playing_message">"%s에서 재생을 다시 시작하시겠습니까?"</string> <string name="resume_playing_resume">"재생 다시 시작"</string> <string name="resume_playing_restart">"시작"</string> <string name="gadget_title">"사진 프레임"</string> <string name="file_info_title">"파일 정보:"</string> <string name="video_exceed_mms_limit">"녹화한 동영상이 너무 커서 MMS를 통해 전송할 수 없습니다. 클립의 길이를 더 짧게 녹화하세요."</string> <string name="too_large_to_attach">"파일이 너무 커서 첨부할 수 없습니다."</string> </resources> diff --git a/res/values-pt-rPT/arrays.xml b/res/values-pt-rPT/arrays.xml new file mode 100644 index 0000000..dfbf090 --- /dev/null +++ b/res/values-pt-rPT/arrays.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <!-- no translation found for pref_camera_videoquality_entries:0 (4155278146225809483) --> + <!-- no translation found for pref_camera_videoquality_entries:1 (2439895494739176281) --> + <string-array name="pref_camera_videoquality_entryvalues"> + <item>"0"</item> + <item>"1"</item> + </string-array> +</resources> diff --git a/res/values-pt-rPT/strings.xml b/res/values-pt-rPT/strings.xml new file mode 100644 index 0000000..90dfea3 --- /dev/null +++ b/res/values-pt-rPT/strings.xml @@ -0,0 +1,155 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <string name="all_images">"Todas as imagens"</string> + <string name="all_videos">"Todos os vídeos"</string> + <string name="camera_label">"Câmara"</string> + <string name="video_camera_label">"Câmara de vídeo"</string> + <string name="gallery_picker_label">"Galeria"</string> + <string name="gallery_camera_bucket_name">"Imagens da câmara"</string> + <string name="gallery_camera_videos_bucket_name">"Vídeos da câmara"</string> + <string name="switch_to_video_lable">"Mudar para vídeo"</string> + <string name="switch_to_camera_lable">"Mudar para câmara"</string> + <string name="crop_label">"Recortar imagem"</string> + <string name="view_label">"Ver imagem"</string> + <string name="preferences_label">"Definições da câmara"</string> + <string name="wait">"Aguarde..."</string> + <string name="no_storage">"Insira um cartão SD antes de utilizar a câmara."</string> + <string name="not_enough_space">"O cartão SD está cheio."</string> + <string name="preparing_sd">"A preparar o cartão SD..."</string> + <string name="wallpaper">"A definir a imagem de fundo, aguarde..."</string> + <string name="savingImage">"A guardar imagem..."</string> + <string name="runningFaceDetection">"Aguarde..."</string> + <string name="flip_orientation">"Inverter a orientação"</string> + <string name="settings">"Definições"</string> + <string name="view">"Ver"</string> + <string name="details">"Detalhes"</string> + <string name="rotate">"Rodar"</string> + <string name="rotate_left">"Rodar para a esquerda"</string> + <string name="rotate_right">"Rodar para a direita"</string> + <string name="slide_show">"Apresentação de diapositivos"</string> + <string name="capture_picture">"Capturar imagem"</string> + <string name="capture_video">"Capturar vídeo"</string> + <string name="crop_save_text">"Guardar"</string> + <string name="crop_discard_text">"Rejeitar"</string> + <string name="confirm_delete_title">"Eliminar"</string> + <string name="confirm_delete_message">"A imagem será eliminada."</string> + <string name="confirm_delete_video_message">"O vídeo será eliminado."</string> + <string name="camera_toss">"Eliminar"</string> + <string name="camera_gallery">"Galeria"</string> + <string name="camera_share">"Partilhar"</string> + <string name="camera_set">"Definir como"</string> + <string name="camera_play">"Reproduzir"</string> + <string name="camera_attach">"Anexar"</string> + <string name="camera_cancel">"Cancelar"</string> + <string name="camera_crop">"Recortar"</string> + <string name="camera_tossing">"A eliminar..."</string> + <string name="no_way_to_share_image">"Não é possível partilhar esta imagem."</string> + <string name="no_way_to_share_video">"Não é possível partilhar este vídeo."</string> + <string name="video_play">"Reproduzir"</string> + <string name="camera_gallery_photos_text">"Galeria"</string> + <string name="camera_pick_wallpaper">"Imagens"</string> + <string name="camera_setas_wallpaper">"Imagem de fundo"</string> + <string name="pref_gallery_category">"Definições gerais"</string> + <string name="pref_slideshow_category">"Definições da apresentação de diapositivos"</string> + <string name="pref_camera_general_settings_category">"Definições gerais"</string> + <string name="pref_gallery_size_title">"Tamanho da visualização"</string> + <string name="pref_gallery_size_summary">"Seleccione o tamanho da apresentação de imagens e vídeo"</string> + <string name="pref_gallery_size_dialogtitle">"Tamanho da imagem"</string> + <string-array name="pref_gallery_size_choices"> + <item>"Grande"</item> + <item>"Pequeno"</item> + </string-array> + <string name="pref_gallery_sort_title">"Ordenação"</string> + <string name="pref_gallery_sort_summary">"Seleccione a sequência de ordenação das imagens e dos vídeos"</string> + <string name="pref_gallery_sort_dialogtitle">"Ordenação de imagens"</string> + <string-array name="pref_gallery_sort_choices"> + <item>"As mais recentes primeiro"</item> + <item>"As mais recentes por último"</item> + </string-array> + <string name="pref_gallery_slideshow_interval_title">"Intervalo da apresentação de diapositivos"</string> + <string name="pref_gallery_slideshow_interval_summary">"Seleccionar o tempo de apresentação de cada diapositivo"</string> + <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo da apresentação de diapositivos"</string> + <string-array name="pref_gallery_slideshow_interval_choices"> + <item>"2 segundos"</item> + <item>"3 segundos"</item> + <item>"4 segundos"</item> + </string-array> + <string name="pref_gallery_slideshow_transition_title">"Transição da apresentação de diapositivos"</string> + <string name="pref_gallery_slideshow_transition_summary">"Seleccione o efeito a utilizar na transição entre slides"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"Transição da apresentação de diapositivos"</string> + <string-array name="pref_gallery_slideshow_transition_choices"> + <item>"Aumentar e diminuir gradualmente"</item> + <item>"Apresentar diapositivos da esquerda para a direita"</item> + <item>"Apresentar diapositivos de cima para baixo"</item> + <item>"Selecção aleatória"</item> + </string-array> + <string name="pref_gallery_slideshow_repeat_title">"Repetir apresentação de diapositivos"</string> + <string name="pref_gallery_slideshow_repeat_summary">"Repetir·a·apresentação·de·diapositivos"</string> + <string name="pref_gallery_slideshow_shuffle_title">"Reproduzir diapositivos aleatoriamente"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imagens por ordem aleatória"</string> + <string name="pref_camera_recordlocation_title">"Armazenar localização nas imagens"</string> + <string name="pref_camera_recordlocation_summary">"Gravar localização nos dados da imagem"</string> + <string name="pref_camera_videoquality_category">"Qualidade de vídeo"</string> + <string name="pref_camera_videoquality_title">"Seleccione a qualidade de vídeo"</string> + <string name="pref_camera_videoquality_entry_0">"Baixa (para mensagens MMS)"</string> + <string name="pref_camera_videoquality_entry_1">"Alta (para cartão SD)"</string> + <string name="pref_camera_videoquality_dialogtitle">"Qualidade de vídeo"</string> + <string name="camerasettings">"Definições"</string> + <string name="image_gallery_NoImageView_text">"Nenhum suporte de dados encontrado."</string> + <string name="pref_gallery_confirm_delete_title">"Confirmar a eliminação"</string> + <string name="pref_gallery_confirm_delete_summary">"Mostrar confirmação antes de eliminar uma imagem ou vídeo"</string> + <string name="details_panel_title">"Detalhes"</string> + <string name="details_file_size">"Tamanho do ficheiro:"</string> + <string name="details_image_resolution">"Resolução:"</string> + <string name="details_duration">"Duração:"</string> + <string name="details_date_taken">"Data da captura:"</string> + <string name="details_frame_rate">"Velocidade de fotogramas:"</string> + <string name="details_bit_rate">"Velocidade de transmissão:"</string> + <string name="details_codec">"Codec:"</string> + <string name="details_format">"Formato:"</string> + <string name="details_dimension_x">"%1$d x %2$d"</string> + <string name="details_ms">"%1$02d:%2$02d"</string> + <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> + <string name="details_fps">"%1$d fps"</string> + <string name="details_kbps">"%1$d Kbps"</string> + <string name="details_mbps">"%1$g Mbps"</string> + <string name="details_ok">"OK"</string> + <string name="context_menu_header">"Opções de imagem"</string> + <string name="video_context_menu_header">"Opções de vídeo"</string> + <string name="multiface_crop_help">"Toque num rosto para começar."</string> + <string name="photos_gallery_title">"Galeria"</string> + <string name="pick_photos_gallery_title">"Seleccionar imagem"</string> + <string name="videos_gallery_title">"Galeria"</string> + <string name="pick_videos_gallery_title">"Seleccionar vídeo"</string> + <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> + <string name="sendImage">"Partilhar a imagem através de"</string> + <string name="setImage">"Definir imagem como:"</string> + <string name="sendVideo">"Partilhar vídeo através de"</string> + <string name="movieviewlabel">"Filmes"</string> + <string name="loading_video">"A carregar vídeo..."</string> + <string name="spaceIsLow_title">"O espaço é reduzido"</string> + <string name="spaceIsLow_content">"Está a ficar sem espaço no cartão SD. Altere as definições de qualidade ou elimine itens da Galeria."</string> + <string name="resume_playing_title">"Retomar o vídeo"</string> + <string name="resume_playing_message">"Retomar reprodução a partir de %s?"</string> + <string name="resume_playing_resume">"Retomar a reprodução"</string> + <string name="resume_playing_restart">"Recomeçar"</string> + <string name="gadget_title">"Moldura da imagem"</string> + <string name="file_info_title">"Informações do ficheiro:"</string> + <string name="video_exceed_mms_limit">"O vídeo que gravou é demasiado grande para ser enviado por MMS. Tente gravar um filme mais curto."</string> + <string name="too_large_to_attach">"Ficheiro demasiado grande para anexar."</string> +</resources> diff --git a/res/values-pt/strings.xml b/res/values-pt/strings.xml index 9f093fb..cd3847f 100644 --- a/res/values-pt/strings.xml +++ b/res/values-pt/strings.xml @@ -1,188 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Todas as imagens"</string> <string name="all_videos">"Todos os vídeos"</string> <string name="camera_label">"Câmera"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> + <string name="video_camera_label">"Filmadora"</string> <string name="gallery_picker_label">"Galeria"</string> <string name="gallery_camera_bucket_name">"Imagens da câmera"</string> - <string name="gallery_camera_videos_bucket_name">"Vídeos da câmera"</string> + <string name="gallery_camera_videos_bucket_name">"Vídeos de câmera"</string> <string name="switch_to_video_lable">"Alternar para vídeo"</string> <string name="switch_to_camera_lable">"Alternar para câmera"</string> <string name="crop_label">"Cortar imagem"</string> <string name="view_label">"Visualizar imagem"</string> <string name="preferences_label">"Configurações da câmera"</string> <string name="wait">"Aguarde..."</string> <string name="no_storage">"Insira um cartão SD antes de usar a câmera."</string> - <string name="not_enough_space">"Seu cartão SD está cheio."</string> - <!-- no translation found for preparing_sd (2914969119574812666) --> - <skip /> - <string name="wallpaper">"Configurando papel de parede, aguarde..."</string> - <string name="savingImage">"Salvando imagem..."</string> + <string name="not_enough_space">"O seu cartão SD está cheio."</string> + <string name="preparing_sd">"Preparando o cartão SD…"</string> + <string name="wallpaper">"Configurando o papel de parede, aguarde…"</string> + <string name="savingImage">"Salvando imagem…"</string> <string name="runningFaceDetection">"Aguarde..."</string> - <string name="flip_orientation">"Inverter orientação"</string> + <string name="flip_orientation">"Orientação do giro"</string> <string name="settings">"Configurações"</string> - <string name="view">"Visualizar"</string> + <string name="view">"Exibir"</string> <string name="details">"Detalhes"</string> <string name="rotate">"Girar"</string> <string name="rotate_left">"Girar para a esquerda"</string> <string name="rotate_right">"Girar para a direita"</string> <string name="slide_show">"Apresentação de slides"</string> <string name="capture_picture">"Capturar imagem"</string> <string name="capture_video">"Capturar vídeo"</string> <string name="crop_save_text">"Salvar"</string> <string name="crop_discard_text">"Descartar"</string> <string name="confirm_delete_title">"Excluir"</string> <string name="confirm_delete_message">"A imagem será excluída."</string> <string name="confirm_delete_video_message">"O vídeo será excluído."</string> <string name="camera_toss">"Excluir"</string> - <!-- no translation found for camera_gallery (815753042966032398) --> - <skip /> + <string name="camera_gallery">"Galeria"</string> <string name="camera_share">"Compartilhar"</string> <string name="camera_set">"Definir como"</string> <string name="camera_play">"Reproduzir"</string> - <!-- no translation found for camera_attach (4048659554893435232) --> - <skip /> - <!-- no translation found for camera_cancel (8203341746672085747) --> - <skip /> + <string name="camera_attach">"Anexar"</string> + <string name="camera_cancel">"Cancelar"</string> <string name="camera_crop">"Cortar"</string> - <string name="camera_tossing">"Excluindo..."</string> + <string name="camera_tossing">"Excluindo…"</string> <string name="no_way_to_share_image">"Esta imagem não pode ser compartilhada."</string> <string name="no_way_to_share_video">"Este vídeo não pode ser compartilhado."</string> - <!-- no translation found for video_play (5287787282508002895) --> - <skip /> + <string name="video_play">"Reproduzir"</string> <string name="camera_gallery_photos_text">"Galeria"</string> <string name="camera_pick_wallpaper">"Imagens"</string> <string name="camera_setas_wallpaper">"Papel de parede"</string> <string name="pref_gallery_category">"Configurações gerais"</string> <string name="pref_slideshow_category">"Configurações da apresentação de slides"</string> <string name="pref_camera_general_settings_category">"Configurações gerais"</string> - <!-- no translation found for pref_gallery_size_title (1363406603879434418) --> - <skip /> - <!-- no translation found for pref_gallery_size_summary (8179967445295243638) --> - <skip /> + <string name="pref_gallery_size_title">"Tamanho da exibição"</string> + <string name="pref_gallery_size_summary">"Selecione o tamanho de exibição das imagens e vídeos"</string> <string name="pref_gallery_size_dialogtitle">"Tamanho da imagem"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Pequeno"</item> </string-array> - <!-- no translation found for pref_gallery_sort_title (7447949250045443386) --> - <skip /> - <!-- no translation found for pref_gallery_sort_summary (6644398051645595214) --> - <skip /> - <string name="pref_gallery_sort_dialogtitle">"Classificar imagens"</string> + <string name="pref_gallery_sort_title">"Ordem de classificação"</string> + <string name="pref_gallery_sort_summary">"Selecione a ordem de classificação das imagens e dos vídeos."</string> + <string name="pref_gallery_sort_dialogtitle">"Classificação de imagens"</string> <string-array name="pref_gallery_sort_choices"> - <item>"As mais novas primeiro"</item> - <item>"As mais novas por último"</item> + <item>"Primeiro o mais recente"</item> + <item>"Último mais recente"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalo da apresentação de slides"</string> - <string name="pref_gallery_slideshow_interval_summary">"Selecione o tempo que cada slide deve ser exibido na apresentação"</string> + <string name="pref_gallery_slideshow_interval_summary">"Selecione a duração de exibição de cada slide na apresentação."</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo da apresentação de slides"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 segundos"</item> <item>"3 segundos"</item> <item>"4 segundos"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transição da apresentação de slides"</string> - <string name="pref_gallery_slideshow_transition_summary">"Selecione o efeito a ser usado ao passar para o próximo slide"</string> + <string name="pref_gallery_slideshow_transition_summary">"Selecione o efeito usado ao passar de um slide para o próximo."</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transição da apresentação de slides"</string> <string-array name="pref_gallery_slideshow_transition_choices"> - <item>"Suavizar cor"</item> - <item>"Deslizar da esquerda para a direita"</item> - <item>"Deslizar de cima para baixo"</item> + <item>"Aparecimento/desaparecimento gradual (fade in/out)"</item> + <item>"Deslizar para a esquerda - direita"</item> + <item>"Deslizar para cima - para baixo"</item> <item>"Seleção aleatória"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Repetir apresentação de slides"</string> - <string name="pref_gallery_slideshow_repeat_summary">"Reproduzir slides mais de uma vez"</string> - <string name="pref_gallery_slideshow_shuffle_title">"Seleção automática de slides"</string> + <string name="pref_gallery_slideshow_repeat_summary">"Reproduzir apresentação de slides mais de uma vez"</string> + <string name="pref_gallery_slideshow_shuffle_title">"Reproduzir slides aleatoriamente"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imagens em ordem aleatória"</string> - <string name="pref_camera_recordlocation_title">"Armazenar local nas imagens"</string> - <string name="pref_camera_recordlocation_summary">"Registrar local nos dados da imagem"</string> + <string name="pref_camera_recordlocation_title">"Armazenar o local nas imagens"</string> + <string name="pref_camera_recordlocation_summary">"Gravar o local nos dados da imagem"</string> <string name="pref_camera_videoquality_category">"Qualidade do vídeo"</string> - <!-- no translation found for pref_camera_videoquality_title (3836197291744160920) --> - <skip /> + <string name="pref_camera_videoquality_title">"Selecionar a qualidade do vídeo"</string> <string name="pref_camera_videoquality_entry_0">"Baixa (para mensagens MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (para cartão SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Qualidade do vídeo"</string> <string name="camerasettings">"Configurações"</string> - <!-- no translation found for image_gallery_NoImageView_text (409595259802877447) --> - <skip /> + <string name="image_gallery_NoImageView_text">"Nenhuma mídia encontrada."</string> <string name="pref_gallery_confirm_delete_title">"Confirmar exclusões"</string> - <!-- no translation found for pref_gallery_confirm_delete_summary (5253456492765525245) --> - <skip /> + <string name="pref_gallery_confirm_delete_summary">"Mostrar confirmação antes de excluir uma imagem ou vídeo."</string> <string name="details_panel_title">"Detalhes"</string> <string name="details_file_size">"Tamanho do arquivo:"</string> <string name="details_image_resolution">"Resolução:"</string> - <!-- no translation found for details_duration (1028116471387901402) --> - <skip /> - <string name="details_date_taken">"Data em que foi tirada:"</string> - <!-- no translation found for details_frame_rate (122397836963498191) --> - <skip /> - <!-- no translation found for details_bit_rate (5632311789455402186) --> - <skip /> - <!-- no translation found for details_codec (5580300450432398126) --> - <skip /> - <!-- no translation found for details_format (3700860266600796363) --> - <skip /> - <!-- no translation found for details_dimension_x (4479200210424701240) --> - <skip /> - <!-- no translation found for details_ms (940634969189855292) --> - <skip /> - <!-- no translation found for details_hms (3215779248094151255) --> - <skip /> - <!-- no translation found for details_fps (2707670327505979317) --> - <skip /> - <!-- no translation found for details_kbps (59196416864960850) --> - <skip /> - <!-- no translation found for details_mbps (3978720645766601106) --> - <skip /> - <!-- no translation found for details_ok (6848594369924424312) --> - <skip /> - <string name="context_menu_header">"Opções de imagem"</string> + <string name="details_duration">"Duração:"</string> + <string name="details_date_taken">"Data de obtenção:"</string> + <string name="details_frame_rate">"Taxa de frame:"</string> + <string name="details_bit_rate">"Taxa de bits:"</string> + <string name="details_codec">"Codec:"</string> + <string name="details_format">"Formato:"</string> + <string name="details_dimension_x">"%1$d x %2$d"</string> + <string name="details_ms">"%1$02d:%2$02d"</string> + <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> + <string name="details_fps">"%1$d fps"</string> + <string name="details_kbps">"%1$d Kbps"</string> + <string name="details_mbps">"%1$g Mbps"</string> + <string name="details_ok">"OK"</string> + <string name="context_menu_header">"Opções da imagem"</string> <string name="video_context_menu_header">"Opções de vídeo"</string> - <string name="multiface_crop_help">"Toque em um rosto para começar."</string> + <string name="multiface_crop_help">"Toque em uma face para começar."</string> <string name="photos_gallery_title">"Galeria"</string> <string name="pick_photos_gallery_title">"Selecionar imagem"</string> <string name="videos_gallery_title">"Galeria"</string> <string name="pick_videos_gallery_title">"Selecionar vídeo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> <string name="sendImage">"Compartilhar imagem via"</string> <string name="setImage">"Definir imagem como"</string> <string name="sendVideo">"Compartilhar vídeo via"</string> <string name="movieviewlabel">"Filmes"</string> - <string name="loading_video">"Carregando vídeo…"</string> - <string name="spaceIsLow_title">"Pouco espaço disponível"</string> - <string name="spaceIsLow_content">"O cartão SD não possui mais espaço disponível. Altere as configurações de qualidade ou exclua itens da Galeria."</string> - <!-- no translation found for resume_playing_title (8996677350649355013) --> - <skip /> - <!-- no translation found for resume_playing_message (5184414518126703481) --> - <skip /> - <!-- no translation found for resume_playing_resume (3847915469173852416) --> - <skip /> - <!-- no translation found for resume_playing_restart (5471008499835769292) --> - <skip /> - <!-- no translation found for gadget_title (259405922673466798) --> - <skip /> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="loading_video">"Carregando vídeo..."</string> + <string name="spaceIsLow_title">"O espaço é pouco"</string> + <string name="spaceIsLow_content">"O seu cartão SD está sem espaço. Mude a configuração de qualidade ou exclua itens da Galeria."</string> + <string name="resume_playing_title">"Retomar vídeo"</string> + <string name="resume_playing_message">"Retomar reprodução de %s ?"</string> + <string name="resume_playing_resume">"Retomar a reprodução"</string> + <string name="resume_playing_restart">"Reiniciar"</string> + <string name="gadget_title">"Frame da imagem"</string> + <string name="file_info_title">"Informações do arquivo:"</string> + <string name="video_exceed_mms_limit">"O vídeo gravado é muito grande para ser enviado via MMS. Tente gravar um clipe mais curto."</string> + <string name="too_large_to_attach">"Arquivo muito grande para ser anexado."</string> </resources> diff --git a/res/values-ru/strings.xml b/res/values-ru/strings.xml index ef609e3..91238c0 100644 --- a/res/values-ru/strings.xml +++ b/res/values-ru/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <string name="all_images">"Все изображения"</string> + <string name="all_images">"Все картинки"</string> <string name="all_videos">"Все видео"</string> - <string name="camera_label">"Камера"</string> + <string name="camera_label">"Фотографии"</string> <string name="video_camera_label">"Видеокамера"</string> - <string name="gallery_picker_label">"Галерея"</string> - <string name="gallery_camera_bucket_name">"Фотографии с камеры"</string> - <string name="gallery_camera_videos_bucket_name">"Видео с камеры"</string> - <string name="switch_to_video_lable">"Перейти в режим видео"</string> - <string name="switch_to_camera_lable">"Перейти в режим камеры"</string> - <string name="crop_label">"Обрезать изображение"</string> - <string name="view_label">"Просмотреть изображение"</string> + <string name="gallery_picker_label">"Фотоальбом"</string> + <string name="gallery_camera_bucket_name">"Снимки, сделанные камерой"</string> + <string name="gallery_camera_videos_bucket_name">"Видео"</string> + <string name="switch_to_video_lable">"Переключить на видео"</string> + <string name="switch_to_camera_lable">"Переключить на камеру"</string> + <string name="crop_label">"Обрезать фотографию"</string> + <string name="view_label">"Просмотр картинки"</string> <string name="preferences_label">"Настройки камеры"</string> - <string name="wait">"Подождите…"</string> - <string name="no_storage">"Перед использованием камеры вставьте карту SD."</string> - <string name="not_enough_space">"Карта SD заполнена."</string> + <string name="wait">"Подождите..."</string> + <string name="no_storage">"Прежде чем использовать камеру, вставьте SD-карту."</string> + <string name="not_enough_space">"Ваша SD-карта заполнена."</string> <string name="preparing_sd">"Подготовка карты SD..."</string> - <string name="wallpaper">"Установка фонового рисунка, подождите…"</string> - <string name="savingImage">"Идет сохранение изображения…"</string> - <string name="runningFaceDetection">"Подождите…"</string> + <string name="wallpaper">"Установка обоев, подождите..."</string> + <string name="savingImage">"Сохранение картинки..."</string> + <string name="runningFaceDetection">"Подождите..."</string> <string name="flip_orientation">"Изменить ориентацию"</string> <string name="settings">"Настройки"</string> - <string name="view">"Просмотреть"</string> + <string name="view">"Просмотр"</string> <string name="details">"Сведения"</string> <string name="rotate">"Повернуть"</string> - <string name="rotate_left">"Повернуть налево"</string> - <string name="rotate_right">"Повернуть направо"</string> + <string name="rotate_left">"Повернуть влево"</string> + <string name="rotate_right">"Повернуть вправо"</string> <string name="slide_show">"Слайд-шоу"</string> <string name="capture_picture">"Сделать фотографию"</string> <string name="capture_video">"Снять видео"</string> <string name="crop_save_text">"Сохранить"</string> <string name="crop_discard_text">"Отменить"</string> - <string name="confirm_delete_title">"Удаление"</string> - <string name="confirm_delete_message">"Изображение будет удалено."</string> + <string name="confirm_delete_title">"Удалить"</string> + <string name="confirm_delete_message">"Картинка будет удалена."</string> <string name="confirm_delete_video_message">"Видео будет удалено."</string> - <string name="camera_toss">"Удаление"</string> - <string name="camera_gallery">"Галерея"</string> + <string name="camera_toss">"Удалить"</string> + <string name="camera_gallery">"Фотоальбом"</string> <string name="camera_share">"Отправить"</string> <string name="camera_set">"Установить как"</string> <string name="camera_play">"Воспроизвести"</string> <string name="camera_attach">"Вложить"</string> <string name="camera_cancel">"Отмена"</string> <string name="camera_crop">"Обрезать"</string> - <string name="camera_tossing">"Идет удаление…"</string> - <string name="no_way_to_share_image">"Отправить это изображение нельзя."</string> - <string name="no_way_to_share_video">"Отправить это видео нельзя."</string> + <string name="camera_tossing">"Удаление..."</string> + <string name="no_way_to_share_image">"Эту фотографию нельзя отправить."</string> + <string name="no_way_to_share_video">"Это видео нельзя отправить."</string> <string name="video_play">"Воспроизвести"</string> - <string name="camera_gallery_photos_text">"Галерея"</string> - <string name="camera_pick_wallpaper">"Изображения"</string> - <string name="camera_setas_wallpaper">"Фоновый рисунок"</string> + <string name="camera_gallery_photos_text">"Фотоальбом"</string> + <string name="camera_pick_wallpaper">"Картинки"</string> + <string name="camera_setas_wallpaper">"Обои"</string> <string name="pref_gallery_category">"Общие настройки"</string> <string name="pref_slideshow_category">"Настройки слайд-шоу"</string> <string name="pref_camera_general_settings_category">"Общие настройки"</string> <string name="pref_gallery_size_title">"Отображаемый размер"</string> <string name="pref_gallery_size_summary">"Выбор отображаемого размера изображений и видео"</string> - <string name="pref_gallery_size_dialogtitle">"Размер изображения"</string> + <string name="pref_gallery_size_dialogtitle">"Размер картинки"</string> <string-array name="pref_gallery_size_choices"> - <item>"Крупный"</item> - <item>"Мелкий"</item> + <item>"Большой"</item> + <item>"Небольшой"</item> </string-array> <string name="pref_gallery_sort_title">"Порядок сортировки"</string> <string name="pref_gallery_sort_summary">"Выберите порядок сортировки изображений и видео"</string> - <string name="pref_gallery_sort_dialogtitle">"Сортировка изображений"</string> + <string name="pref_gallery_sort_dialogtitle">"Сортировать картинки"</string> <string-array name="pref_gallery_sort_choices"> - <item>"Начиная с новых"</item> - <item>"Заканчивая новыми"</item> + <item>"Сначала новые"</item> + <item>"Сначала старые"</item> </string-array> - <string name="pref_gallery_slideshow_interval_title">"Интервал слайд-шоу"</string> - <string name="pref_gallery_slideshow_interval_summary">"Выберите время отображения каждого слайда"</string> + <string name="pref_gallery_slideshow_interval_title">"Интервал в слайд-шоу"</string> + <string name="pref_gallery_slideshow_interval_summary">"Выбор длительности показа каждого слайда"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Интервал слайд-шоу"</string> <string-array name="pref_gallery_slideshow_interval_choices"> - <item>"2 секунды"</item> - <item>"3 секунды"</item> - <item>"4 секунды"</item> + <item>"2 сек."</item> + <item>"3 сек."</item> + <item>"4 сек."</item> </string-array> - <string name="pref_gallery_slideshow_transition_title">"Переходы слайд-шоу"</string> - <string name="pref_gallery_slideshow_transition_summary">"Выберите эффект для перехода от одного слайда к другому"</string> - <string name="pref_gallery_slideshow_transition_dialogtitle">"Переходы слайд-шоу"</string> + <string name="pref_gallery_slideshow_transition_title">"Переход в слайд-шоу"</string> + <string name="pref_gallery_slideshow_transition_summary">"Выбор эффекта при переходе от одного слайда к другому"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"Переход в слайд-шоу"</string> <string-array name="pref_gallery_slideshow_transition_choices"> - <item>"Затемнение"</item> - <item>"Слайды слева направо"</item> - <item>"Слайды сверху вниз"</item> + <item>"Затемнение и проявление"</item> + <item>"Прокрутка слева направо"</item> + <item>"Прокрутка сверху вниз"</item> <item>"Случайный выбор"</item> </string-array> - <string name="pref_gallery_slideshow_repeat_title">"Повторить слайд-шоу"</string> - <string name="pref_gallery_slideshow_repeat_summary">"Воспроизвести слайд-шоу несколько раз"</string> + <string name="pref_gallery_slideshow_repeat_title">"Повтор слайд-шоу"</string> + <string name="pref_gallery_slideshow_repeat_summary">"Воспроизвести слайд-шоу более одного раза"</string> <string name="pref_gallery_slideshow_shuffle_title">"Перемешать слайды"</string> - <string name="pref_gallery_slideshow_shuffle_summary">"Показывать изображения в случайном порядке"</string> - <string name="pref_camera_recordlocation_title">"Сохранять адрес в изображениях"</string> - <string name="pref_camera_recordlocation_summary">"Записывать адрес в данные изображения"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"Показ фотографий в случайном порядке"</string> + <string name="pref_camera_recordlocation_title">"Сохранять местоположение в фотографиях"</string> + <string name="pref_camera_recordlocation_summary">"Записывать местоположение в данных фотографии"</string> <string name="pref_camera_videoquality_category">"Качество видео"</string> <string name="pref_camera_videoquality_title">"Выбор качества видео"</string> - <string name="pref_camera_videoquality_entry_0">"Низкое (для MMS)"</string> - <string name="pref_camera_videoquality_entry_1">"Высокое (для карты SD)"</string> + <string name="pref_camera_videoquality_entry_0">"Низкое (для сообщений MMS)"</string> + <string name="pref_camera_videoquality_entry_1">"Высокое (для SD-карты)"</string> <string name="pref_camera_videoquality_dialogtitle">"Качество видео"</string> <string name="camerasettings">"Настройки"</string> <string name="image_gallery_NoImageView_text">"Нет мультимедийных материалов."</string> - <string name="pref_gallery_confirm_delete_title">"Подтверждение удаления"</string> + <string name="pref_gallery_confirm_delete_title">"Подтверждать удаление"</string> <string name="pref_gallery_confirm_delete_summary">"Запрашивать подтверждения перед удалением изображения или видео"</string> <string name="details_panel_title">"Сведения"</string> <string name="details_file_size">"Размер файла:"</string> <string name="details_image_resolution">"Разрешение:"</string> <string name="details_duration">"Продолжительность:"</string> <string name="details_date_taken">"Дата съемки:"</string> <string name="details_frame_rate">"Частота кадров:"</string> <string name="details_bit_rate">"Битрейт:"</string> <string name="details_codec">"Кодек:"</string> <string name="details_format">"Формат:"</string> <string name="details_dimension_x">"%1$d на %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d кадров/с"</string> <string name="details_kbps">"%1$d кбит/с"</string> - <string name="details_mbps">"%1$g мбит/с"</string> + <string name="details_mbps">"%1$g Мбит/с"</string> <string name="details_ok">"ОК"</string> - <string name="context_menu_header">"Параметры изображения"</string> + <string name="context_menu_header">"Параметры картинки"</string> <string name="video_context_menu_header">"Параметры видео"</string> - <string name="multiface_crop_help">"Чтобы начать, выберите лицо."</string> - <string name="photos_gallery_title">"Галерея"</string> - <string name="pick_photos_gallery_title">"Выбор изображения"</string> - <string name="videos_gallery_title">"Галерея"</string> - <string name="pick_videos_gallery_title">"Выбрать видео"</string> + <string name="multiface_crop_help">"Нажмите лицо, чтобы начать."</string> + <string name="photos_gallery_title">"Фотоальбом"</string> + <string name="pick_photos_gallery_title">"Выбор картинок"</string> + <string name="videos_gallery_title">"Фотоальбом"</string> + <string name="pick_videos_gallery_title">"Выбор видео"</string> <string name="loading_progress_format_string">"Осталось: <xliff:g id="COUNTER">%d</xliff:g>"</string> - <string name="sendImage">"Отправить изображение при помощи"</string> - <string name="setImage">"Установить изображение как"</string> + <string name="sendImage">"Отправить картинку через"</string> + <string name="setImage">"Установить картинку как"</string> <string name="sendVideo">"Отправить видео при помощи"</string> <string name="movieviewlabel">"Фильмы"</string> - <string name="loading_video">"Идет загрузка видео…"</string> - <string name="spaceIsLow_title">"Осталось мало места"</string> - <string name="spaceIsLow_content">"Место на карте SD заканчивается. Измените настройки качества или удалите элементы из галереи."</string> + <string name="loading_video">"Загрузка видео…"</string> + <string name="spaceIsLow_title">"Мало свободного места"</string> + <string name="spaceIsLow_content">"Место на вашей SD-карте заканчивается. Измените настройки качества или удалите содержимое из фотоальбома."</string> <string name="resume_playing_title">"Продолжение просмотра видео"</string> - <string name="resume_playing_message">"Продолжить воспроизведение с %s ?"</string> + <string name="resume_playing_message">"Продолжить воспроизведение с %s?"</string> <string name="resume_playing_resume">"Продолжить воспроизведение"</string> <string name="resume_playing_restart">"Начать с начала"</string> <string name="gadget_title">"Рамка фотографии"</string> <string name="file_info_title">"Сведения о файле:"</string> <string name="video_exceed_mms_limit">"Записанное видео имеет слишком большой размер для отправки в MMS. Запишите более короткий ролик."</string> <string name="too_large_to_attach">"Файл имеет слишком большой размер и не может быть вложен."</string> </resources> diff --git a/res/values-sv/arrays.xml b/res/values-sv/arrays.xml new file mode 100644 index 0000000..dfbf090 --- /dev/null +++ b/res/values-sv/arrays.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <!-- no translation found for pref_camera_videoquality_entries:0 (4155278146225809483) --> + <!-- no translation found for pref_camera_videoquality_entries:1 (2439895494739176281) --> + <string-array name="pref_camera_videoquality_entryvalues"> + <item>"0"</item> + <item>"1"</item> + </string-array> +</resources> diff --git a/res/values-sv/strings.xml b/res/values-sv/strings.xml new file mode 100644 index 0000000..55c56b1 --- /dev/null +++ b/res/values-sv/strings.xml @@ -0,0 +1,155 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <string name="all_images">"Alla bilder"</string> + <string name="all_videos">"Alla videor"</string> + <string name="camera_label">"Kamera"</string> + <string name="video_camera_label">"Videokamera"</string> + <string name="gallery_picker_label">"Galleri"</string> + <string name="gallery_camera_bucket_name">"Kamerabilder"</string> + <string name="gallery_camera_videos_bucket_name">"Kameravideor"</string> + <string name="switch_to_video_lable">"Växla till video"</string> + <string name="switch_to_camera_lable">"Växla till kamera"</string> + <string name="crop_label">"Beskär bild"</string> + <string name="view_label">"Visa bild"</string> + <string name="preferences_label">"Kamerainställningar"</string> + <string name="wait">"Vänta…"</string> + <string name="no_storage">"Sätt i ett SD-kort innan du använder kameran."</string> + <string name="not_enough_space">"Ditt SD-kort är fullt."</string> + <string name="preparing_sd">"Förbereder SD-kort…"</string> + <string name="wallpaper">"Anger bakgrund, vänta…"</string> + <string name="savingImage">"Sparar bild…"</string> + <string name="runningFaceDetection">"Vänta…"</string> + <string name="flip_orientation">"Ändra riktning"</string> + <string name="settings">"Inställningar"</string> + <string name="view">"Visa"</string> + <string name="details">"Information"</string> + <string name="rotate">"Rotera"</string> + <string name="rotate_left">"Rotera åt vänster"</string> + <string name="rotate_right">"Rotera åt höger"</string> + <string name="slide_show">"Bildspel"</string> + <string name="capture_picture">"Fota"</string> + <string name="capture_video">"Spela in video"</string> + <string name="crop_save_text">"Spara"</string> + <string name="crop_discard_text">"Ignorera"</string> + <string name="confirm_delete_title">"Ta bort"</string> + <string name="confirm_delete_message">"Bilden kommer att tas bort."</string> + <string name="confirm_delete_video_message">"Videon kommer att tas bort."</string> + <string name="camera_toss">"Ta bort"</string> + <string name="camera_gallery">"Galleri"</string> + <string name="camera_share">"Dela"</string> + <string name="camera_set">"Använd som"</string> + <string name="camera_play">"Spela"</string> + <string name="camera_attach">"Bifoga"</string> + <string name="camera_cancel">"Avbryt"</string> + <string name="camera_crop">"Beskär"</string> + <string name="camera_tossing">"Tar bort…"</string> + <string name="no_way_to_share_image">"Den här bilden kan inte delas."</string> + <string name="no_way_to_share_video">"Den här videon kan inte delas."</string> + <string name="video_play">"Spela"</string> + <string name="camera_gallery_photos_text">"Galleri"</string> + <string name="camera_pick_wallpaper">"Bilder"</string> + <string name="camera_setas_wallpaper">"Bakgrund"</string> + <string name="pref_gallery_category">"Allmänna inställningar"</string> + <string name="pref_slideshow_category">"Bildspelsinställningar"</string> + <string name="pref_camera_general_settings_category">"Allmänna inställningar"</string> + <string name="pref_gallery_size_title">"Visningsstorlek"</string> + <string name="pref_gallery_size_summary">"Välj visningsstorlek för bilder och videor"</string> + <string name="pref_gallery_size_dialogtitle">"Bildstorlek"</string> + <string-array name="pref_gallery_size_choices"> + <item>"Stora"</item> + <item>"Liten"</item> + </string-array> + <string name="pref_gallery_sort_title">"Sorteringsordning"</string> + <string name="pref_gallery_sort_summary">"Välj sorteringsordning för bilder och videor"</string> + <string name="pref_gallery_sort_dialogtitle">"Sortera bilder"</string> + <string-array name="pref_gallery_sort_choices"> + <item>"Nyast först"</item> + <item>"Nyaste först"</item> + </string-array> + <string name="pref_gallery_slideshow_interval_title">"Bildspelsintervall"</string> + <string name="pref_gallery_slideshow_interval_summary">"Ange hur länge varje bild ska visas i bildspelet"</string> + <string name="pref_gallery_slideshow_interval_dialogtitle">"Bildspelsintervall"</string> + <string-array name="pref_gallery_slideshow_interval_choices"> + <item>"2 sekunder"</item> + <item>"3 sekunder"</item> + <item>"4 sekunder"</item> + </string-array> + <string name="pref_gallery_slideshow_transition_title">"Bildspelsövergång"</string> + <string name="pref_gallery_slideshow_transition_summary">"Välj vilken effekt som ska användas i växlingen mellan bilder"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"Bildspelsövergång"</string> + <string-array name="pref_gallery_slideshow_transition_choices"> + <item>"Tonas fram och bort"</item> + <item>"Skjuts åt vänster eller höger"</item> + <item>"Skjuts upp och ner"</item> + <item>"Slumpmässigt urval"</item> + </string-array> + <string name="pref_gallery_slideshow_repeat_title">"Upprepa bildspel"</string> + <string name="pref_gallery_slideshow_repeat_summary">"Visa bildspel mer än en gång"</string> + <string name="pref_gallery_slideshow_shuffle_title">"Blanda bilder"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"Visa bilder i slumpmässig ordning"</string> + <string name="pref_camera_recordlocation_title">"Spara plats i bilder"</string> + <string name="pref_camera_recordlocation_summary">"Registrera plats i bilddata"</string> + <string name="pref_camera_videoquality_category">"Videokvalitet"</string> + <string name="pref_camera_videoquality_title">"Välj videokvalitet"</string> + <string name="pref_camera_videoquality_entry_0">"Låg (för MMS)"</string> + <string name="pref_camera_videoquality_entry_1">"Hög (för SD-kort)"</string> + <string name="pref_camera_videoquality_dialogtitle">"Videokvalitet"</string> + <string name="camerasettings">"Inställningar"</string> + <string name="image_gallery_NoImageView_text">"Inga medieobjekt hittades."</string> + <string name="pref_gallery_confirm_delete_title">"Bekräfta borttagningar"</string> + <string name="pref_gallery_confirm_delete_summary">"Visa bekräftelse innan bild eller video tas bort"</string> + <string name="details_panel_title">"Information"</string> + <string name="details_file_size">"Filstorlek:"</string> + <string name="details_image_resolution">"Upplösning:"</string> + <string name="details_duration">"Varaktighet:"</string> + <string name="details_date_taken">"Togs den:"</string> + <string name="details_frame_rate">"Bildrutefrekvens"</string> + <string name="details_bit_rate">"Bithastighet:"</string> + <string name="details_codec">"Kodek:"</string> + <string name="details_format">"Format:"</string> + <string name="details_dimension_x">"%1$d x %2$d"</string> + <string name="details_ms">"%1$02d:%2$02d"</string> + <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> + <string name="details_fps">"%1$d bildrutor/s"</string> + <string name="details_kbps">"%1$d kbit/s"</string> + <string name="details_mbps">"%1$g Mbit/s"</string> + <string name="details_ok">"OK"</string> + <string name="context_menu_header">"Bildalternativ"</string> + <string name="video_context_menu_header">"Videoalternativ"</string> + <string name="multiface_crop_help">"Peka på ett ansikte när du vill börja."</string> + <string name="photos_gallery_title">"Galleri"</string> + <string name="pick_photos_gallery_title">"Välj bild"</string> + <string name="videos_gallery_title">"Galleri"</string> + <string name="pick_videos_gallery_title">"Välj video"</string> + <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> återstår"</string> + <string name="sendImage">"Dela bild via"</string> + <string name="setImage">"Använd bild som"</string> + <string name="sendVideo">"Dela video via"</string> + <string name="movieviewlabel">"Filmer"</string> + <string name="loading_video">"Läser in video…"</string> + <string name="spaceIsLow_title">"Utrymmet börjar ta slut"</string> + <string name="spaceIsLow_content">"Ditt SD-kort börjar bli fullt. Ändra inställningen för kvalitet eller ta bort objekt från Galleri."</string> + <string name="resume_playing_title">"Fortsätt spela videon"</string> + <string name="resume_playing_message">"Fortsätt spela upp från %s?"</string> + <string name="resume_playing_resume">"Fortsätt spela upp"</string> + <string name="resume_playing_restart">"Börja om"</string> + <string name="gadget_title">"Bildram"</string> + <string name="file_info_title">"Filinformation:"</string> + <string name="video_exceed_mms_limit">"Videon som du spelade in är för stor för att skickas via MMS. Försök spela in ett kortare klipp."</string> + <string name="too_large_to_attach">"Filen är för stor för att bifogas."</string> +</resources> diff --git a/res/values-tr/arrays.xml b/res/values-tr/arrays.xml new file mode 100644 index 0000000..dfbf090 --- /dev/null +++ b/res/values-tr/arrays.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <!-- no translation found for pref_camera_videoquality_entries:0 (4155278146225809483) --> + <!-- no translation found for pref_camera_videoquality_entries:1 (2439895494739176281) --> + <string-array name="pref_camera_videoquality_entryvalues"> + <item>"0"</item> + <item>"1"</item> + </string-array> +</resources> diff --git a/res/values-tr/strings.xml b/res/values-tr/strings.xml new file mode 100644 index 0000000..dcbc6a2 --- /dev/null +++ b/res/values-tr/strings.xml @@ -0,0 +1,155 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <string name="all_images">"Tüm resimler"</string> + <string name="all_videos">"Tüm videolar"</string> + <string name="camera_label">"Kamera"</string> + <string name="video_camera_label">"Video Kamera"</string> + <string name="gallery_picker_label">"Galeri"</string> + <string name="gallery_camera_bucket_name">"Kamera resimleri"</string> + <string name="gallery_camera_videos_bucket_name">"Kamera videoları"</string> + <string name="switch_to_video_lable">"Videoya geç"</string> + <string name="switch_to_camera_lable">"Kameraya geç"</string> + <string name="crop_label">"Resmi kırp"</string> + <string name="view_label">"Resmi görüntüle"</string> + <string name="preferences_label">"Kamera ayarları"</string> + <string name="wait">"Lütfen bekleyin..."</string> + <string name="no_storage">"Kamerayı kullanmadan önce lütfen bir SD kart takın."</string> + <string name="not_enough_space">"SD kartınız dolu."</string> + <string name="preparing_sd">"SD kart hazırlanıyor..."</string> + <string name="wallpaper">"Duvar kağıdı ayarlanıyor, lütfen bekleyin..."</string> + <string name="savingImage">"Resim kaydediliyor..."</string> + <string name="runningFaceDetection">"Lütfen bekleyin..."</string> + <string name="flip_orientation">"Yönü değiştir"</string> + <string name="settings">"Ayarlar"</string> + <string name="view">"Görüntüle"</string> + <string name="details">"Ayrıntılar"</string> + <string name="rotate">"Döndür"</string> + <string name="rotate_left">"Sola döndür"</string> + <string name="rotate_right">"Sağa döndür"</string> + <string name="slide_show">"Slayt gösterisi"</string> + <string name="capture_picture">"Fotoğraf çek"</string> + <string name="capture_video">"Video çek"</string> + <string name="crop_save_text">"Kaydet"</string> + <string name="crop_discard_text">"Sil"</string> + <string name="confirm_delete_title">"Sil"</string> + <string name="confirm_delete_message">"Resim silinecek."</string> + <string name="confirm_delete_video_message">"Video silinecek."</string> + <string name="camera_toss">"Sil"</string> + <string name="camera_gallery">"Galeri"</string> + <string name="camera_share">"Paylaş"</string> + <string name="camera_set">"Şu şekilde ayarla:"</string> + <string name="camera_play">"Yürüt"</string> + <string name="camera_attach">"Ekle"</string> + <string name="camera_cancel">"İptal"</string> + <string name="camera_crop">"Kırp"</string> + <string name="camera_tossing">"Siliniyor..."</string> + <string name="no_way_to_share_image">"Bu resim paylaşılamıyor."</string> + <string name="no_way_to_share_video">"Bu video paylaşılamıyor."</string> + <string name="video_play">"Yürüt"</string> + <string name="camera_gallery_photos_text">"Galeri"</string> + <string name="camera_pick_wallpaper">"Resimler"</string> + <string name="camera_setas_wallpaper">"Duvar Kağıdı"</string> + <string name="pref_gallery_category">"Genel ayarlar"</string> + <string name="pref_slideshow_category">"Slayt gösterisi ayarları"</string> + <string name="pref_camera_general_settings_category">"Genel ayarlar"</string> + <string name="pref_gallery_size_title">"Görüntü boyutu"</string> + <string name="pref_gallery_size_summary">"Resimlerin ve videoların görüntülenme boyutunu seçin"</string> + <string name="pref_gallery_size_dialogtitle">"Resim boyutu"</string> + <string-array name="pref_gallery_size_choices"> + <item>"Büyük"</item> + <item>"Küçük"</item> + </string-array> + <string name="pref_gallery_sort_title">"Sıralama düzeni"</string> + <string name="pref_gallery_sort_summary">"Resimlerin ve videoların sıralama düzenini seçin"</string> + <string name="pref_gallery_sort_dialogtitle">"Resim sıralama"</string> + <string-array name="pref_gallery_sort_choices"> + <item>"Önce en yenisi"</item> + <item>"En yenisi en sonra"</item> + </string-array> + <string name="pref_gallery_slideshow_interval_title">"Slayt gösterisi aralığı"</string> + <string name="pref_gallery_slideshow_interval_summary">"Her slaytın slayt gösterisinde ne kadar süreyle görüntüleneceğini seçin"</string> + <string name="pref_gallery_slideshow_interval_dialogtitle">"Slayt gösterisi aralığı"</string> + <string-array name="pref_gallery_slideshow_interval_choices"> + <item>"2 saniye"</item> + <item>"3 saniye"</item> + <item>"4 saniye"</item> + </string-array> + <string name="pref_gallery_slideshow_transition_title">"Slayt gösterisi geçişi"</string> + <string name="pref_gallery_slideshow_transition_summary">"Bir slayttan diğerine geçerken kullanılan efekti seçin"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"Slayt gösterisi geçişi"</string> + <string-array name="pref_gallery_slideshow_transition_choices"> + <item>"Rengi açma ve karartma"</item> + <item>"Sağa - sola kaydır"</item> + <item>"Sonraki - önceki slayta geç"</item> + <item>"Rasgele seçim"</item> + </string-array> + <string name="pref_gallery_slideshow_repeat_title">"Slayt gösterisini tekrar et"</string> + <string name="pref_gallery_slideshow_repeat_summary">"Slayt gösterisini birden fazla kez yürüt"</string> + <string name="pref_gallery_slideshow_shuffle_title">"Slaytları karıştır"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"Resimleri rasgele sırada göster"</string> + <string name="pref_camera_recordlocation_title">"Resimlerde konumu depola"</string> + <string name="pref_camera_recordlocation_summary">"Konumu resim verilerinde kaydet"</string> + <string name="pref_camera_videoquality_category">"Video kalitesi"</string> + <string name="pref_camera_videoquality_title">"Video kalitesini seç"</string> + <string name="pref_camera_videoquality_entry_0">"Düşük (MMS iletileri için)"</string> + <string name="pref_camera_videoquality_entry_1">"Yüksek (SD kart için)"</string> + <string name="pref_camera_videoquality_dialogtitle">"Video kalitesi"</string> + <string name="camerasettings">"Ayarlar"</string> + <string name="image_gallery_NoImageView_text">"Medya bulunamadı."</string> + <string name="pref_gallery_confirm_delete_title">"Silme işlemlerini doğrula"</string> + <string name="pref_gallery_confirm_delete_summary">"Bir resmi veya videoyu silmeden önce doğrulama göster"</string> + <string name="details_panel_title">"Ayrıntılar"</string> + <string name="details_file_size">"Dosya boyutu:"</string> + <string name="details_image_resolution">"Çözünürlük:"</string> + <string name="details_duration">"Süre:"</string> + <string name="details_date_taken">"Çekim tarihi:"</string> + <string name="details_frame_rate">"Çerçeve oranı:"</string> + <string name="details_bit_rate">"Bit hızı:"</string> + <string name="details_codec">"Codec:"</string> + <string name="details_format">"Biçim:"</string> + <string name="details_dimension_x">"%1$d x %2$d"</string> + <string name="details_ms">"%1$02d:%2$02d"</string> + <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> + <string name="details_fps">"%1$d f/s"</string> + <string name="details_kbps">"%1$d Kb/s"</string> + <string name="details_mbps">"%1$g Mb/s"</string> + <string name="details_ok">"Tamam"</string> + <string name="context_menu_header">"Resim seçenekleri"</string> + <string name="video_context_menu_header">"Video seçenekleri"</string> + <string name="multiface_crop_help">"Başlamak için bir yüze hafifçe dokunun"</string> + <string name="photos_gallery_title">"Galeri"</string> + <string name="pick_photos_gallery_title">"Resmi seç"</string> + <string name="videos_gallery_title">"Galeri"</string> + <string name="pick_videos_gallery_title">"Video seç"</string> + <string name="loading_progress_format_string">"Kalan: <xliff:g id="COUNTER">%d</xliff:g>"</string> + <string name="sendImage">"Resmi şunun aracılığıyla paylaş:"</string> + <string name="setImage">"Resmi şu şekilde ayarla:"</string> + <string name="sendVideo">"Videoyu şunun aracılığıyla paylaş:"</string> + <string name="movieviewlabel">"Filmler"</string> + <string name="loading_video">"Video yükleniyor..."</string> + <string name="spaceIsLow_title">"Alan az"</string> + <string name="spaceIsLow_content">"SD kartınızda boş alan azalıyor. Kalite ayarlarını değiştirin veya Galeri\'den öğe silin."</string> + <string name="resume_playing_title">"Videoyu sürdür"</string> + <string name="resume_playing_message">"Yürütme şuradan devam ettirilsin mi: %s ?"</string> + <string name="resume_playing_resume">"Yürütmeyi sürdür"</string> + <string name="resume_playing_restart">"Başlat"</string> + <string name="gadget_title">"Resim çerçevesi"</string> + <string name="file_info_title">"Dosya bilgileri:"</string> + <string name="video_exceed_mms_limit">"Kaydettiğiniz video MMS ile gönderilemeyecek kadar büyük. Daha kısa bir klip kaydetmeyi deneyin."</string> + <string name="too_large_to_attach">"Dosya eklenemeyecek kadar büyük."</string> +</resources> diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml index 2d0bb24..b3a889e 100644 --- a/res/values-zh-rCN/strings.xml +++ b/res/values-zh-rCN/strings.xml @@ -1,157 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <string name="all_images">"所有图片"</string> + <string name="all_images">"所有照片"</string> <string name="all_videos">"所有视频"</string> <string name="camera_label">"相机"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> - <string name="gallery_picker_label">"图片库"</string> - <string name="gallery_camera_bucket_name">"相机照片"</string> - <string name="gallery_camera_videos_bucket_name">"相机视频"</string> + <string name="video_camera_label">"便携式摄像机"</string> + <string name="gallery_picker_label">"图库"</string> + <string name="gallery_camera_bucket_name">"用相机拍摄的照片"</string> + <string name="gallery_camera_videos_bucket_name">"用相机拍摄的视频"</string> <string name="switch_to_video_lable">"切换到视频"</string> <string name="switch_to_camera_lable">"切换到相机"</string> - <string name="crop_label">"裁切图片"</string> - <string name="view_label">"查看图片"</string> + <string name="crop_label">"修剪照片"</string> + <string name="view_label">"查看照片"</string> <string name="preferences_label">"相机设置"</string> <string name="wait">"请稍候..."</string> - <string name="no_storage">"请在使用相机之前插入 SD 卡。"</string> - <string name="not_enough_space">"您的 SD 卡已满。"</string> + <string name="no_storage">"使用相机前请先插入 SD 卡。"</string> + <string name="not_enough_space">"SD 卡已满。"</string> <string name="preparing_sd">"正在准备 SD 卡..."</string> <string name="wallpaper">"正在设置壁纸,请稍候..."</string> - <string name="savingImage">"正在保存图片..."</string> + <string name="savingImage">"正在保存照片..."</string> <string name="runningFaceDetection">"请稍候..."</string> <string name="flip_orientation">"反转方向"</string> <string name="settings">"设置"</string> <string name="view">"查看"</string> <string name="details">"详细信息"</string> <string name="rotate">"旋转"</string> <string name="rotate_left">"向左旋转"</string> <string name="rotate_right">"向右旋转"</string> - <string name="slide_show">"幻灯片演示"</string> + <string name="slide_show">"幻灯片放映"</string> <string name="capture_picture">"拍摄照片"</string> <string name="capture_video">"拍摄视频"</string> <string name="crop_save_text">"保存"</string> - <string name="crop_discard_text">"放弃"</string> + <string name="crop_discard_text">"舍弃"</string> <string name="confirm_delete_title">"删除"</string> - <string name="confirm_delete_message">"会删除该图片。"</string> - <string name="confirm_delete_video_message">"会删除该视频。"</string> + <string name="confirm_delete_message">"将会删除照片。"</string> + <string name="confirm_delete_video_message">"将会删除视频。"</string> <string name="camera_toss">"删除"</string> - <string name="camera_gallery">"图片库"</string> - <string name="camera_share">"共享"</string> + <string name="camera_gallery">"图库"</string> + <string name="camera_share">"分享"</string> <string name="camera_set">"设置为"</string> <string name="camera_play">"播放"</string> <string name="camera_attach">"附加"</string> <string name="camera_cancel">"取消"</string> - <string name="camera_crop">"裁切"</string> + <string name="camera_crop">"修剪"</string> <string name="camera_tossing">"正在删除..."</string> - <string name="no_way_to_share_image">"无法共享此图片。"</string> - <string name="no_way_to_share_video">"无法共享此视频。"</string> - <!-- no translation found for video_play (5287787282508002895) --> - <skip /> - <string name="camera_gallery_photos_text">"图片库"</string> - <string name="camera_pick_wallpaper">"图片"</string> + <string name="no_way_to_share_image">"无法分享此照片。"</string> + <string name="no_way_to_share_video">"无法分享此视频。"</string> + <string name="video_play">"播放"</string> + <string name="camera_gallery_photos_text">"图库"</string> + <string name="camera_pick_wallpaper">"照片"</string> <string name="camera_setas_wallpaper">"壁纸"</string> <string name="pref_gallery_category">"常规设置"</string> - <string name="pref_slideshow_category">"幻灯片演示设置"</string> + <string name="pref_slideshow_category">"幻灯片设置"</string> <string name="pref_camera_general_settings_category">"常规设置"</string> <string name="pref_gallery_size_title">"显示大小"</string> <string name="pref_gallery_size_summary">"选择图片和视频的显示大小"</string> - <string name="pref_gallery_size_dialogtitle">"图片大小"</string> + <string name="pref_gallery_size_dialogtitle">"照片大小"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"排序顺序"</string> <string name="pref_gallery_sort_summary">"选择图片和视频的排序顺序"</string> - <string name="pref_gallery_sort_dialogtitle">"图片排序"</string> + <string name="pref_gallery_sort_dialogtitle">"照片排序"</string> <string-array name="pref_gallery_sort_choices"> - <item>"最新的在最前面"</item> - <item>"最新的在最后面"</item> + <item>"最新的照片在最前面"</item> + <item>"最新的照片在最后面"</item> </string-array> - <string name="pref_gallery_slideshow_interval_title">"幻灯片演示间隔"</string> - <string name="pref_gallery_slideshow_interval_summary">"选择每张幻灯片在演示中显示的时间长度"</string> - <string name="pref_gallery_slideshow_interval_dialogtitle">"幻灯片演示间隔"</string> + <string name="pref_gallery_slideshow_interval_title">"幻灯片放映间隔"</string> + <string name="pref_gallery_slideshow_interval_summary">"选择每张幻灯片在放映过程中持续显示的时间"</string> + <string name="pref_gallery_slideshow_interval_dialogtitle">"幻灯片放映间隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 秒"</item> <item>"3 秒"</item> <item>"4 秒"</item> </string-array> - <string name="pref_gallery_slideshow_transition_title">"幻灯片演示过渡"</string> - <string name="pref_gallery_slideshow_transition_summary">"选择从一张幻灯片移动到下一张时使用的效果"</string> - <string name="pref_gallery_slideshow_transition_dialogtitle">"幻灯片演示过渡"</string> + <string name="pref_gallery_slideshow_transition_title">"幻灯片切换"</string> + <string name="pref_gallery_slideshow_transition_summary">"选择从一张幻灯片移动到下一张时应用的效果"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"幻灯片切换"</string> <string-array name="pref_gallery_slideshow_transition_choices"> - <item>"逐渐增强和逐渐减弱"</item> + <item>"淡入和淡出"</item> <item>"自左至右滑动"</item> <item>"自上至下滑动"</item> <item>"随机选择"</item> </string-array> - <string name="pref_gallery_slideshow_repeat_title">"重复幻灯片演示"</string> - <string name="pref_gallery_slideshow_repeat_summary">"多次播放幻灯片演示"</string> - <string name="pref_gallery_slideshow_shuffle_title">"随机演示幻灯片"</string> - <string name="pref_gallery_slideshow_shuffle_summary">"以随机顺序显示图片"</string> - <string name="pref_camera_recordlocation_title">"在图片中存储位置"</string> - <string name="pref_camera_recordlocation_summary">"通过图片数据记录位置"</string> - <string name="pref_camera_videoquality_category">"视频质量"</string> - <string name="pref_camera_videoquality_title">"选择视频质量"</string> + <string name="pref_gallery_slideshow_repeat_title">"重复放映幻灯片"</string> + <string name="pref_gallery_slideshow_repeat_summary">"多次播放幻灯片"</string> + <string name="pref_gallery_slideshow_shuffle_title">"随机放映幻灯片"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"以随机顺序显示照片"</string> + <string name="pref_camera_recordlocation_title">"在照片中存储位置"</string> + <string name="pref_camera_recordlocation_summary">"在照片数据中记录位置"</string> + <string name="pref_camera_videoquality_category">"视频画质"</string> + <string name="pref_camera_videoquality_title">"选择视频画质"</string> <string name="pref_camera_videoquality_entry_0">"低(对于彩信)"</string> <string name="pref_camera_videoquality_entry_1">"高(对于 SD 卡)"</string> - <string name="pref_camera_videoquality_dialogtitle">"视频质量"</string> + <string name="pref_camera_videoquality_dialogtitle">"视频画质"</string> <string name="camerasettings">"设置"</string> <string name="image_gallery_NoImageView_text">"找不到媒体。"</string> <string name="pref_gallery_confirm_delete_title">"确认删除"</string> <string name="pref_gallery_confirm_delete_summary">"在删除图片或视频前显示确认"</string> <string name="details_panel_title">"详细信息"</string> <string name="details_file_size">"文件大小:"</string> <string name="details_image_resolution">"分辨率:"</string> <string name="details_duration">"持续时间:"</string> <string name="details_date_taken">"拍摄日期:"</string> <string name="details_frame_rate">"帧频:"</string> <string name="details_bit_rate">"比特率:"</string> <string name="details_codec">"编解码器:"</string> <string name="details_format">"格式:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"确定"</string> - <string name="context_menu_header">"图片选项"</string> + <string name="context_menu_header">"照片选项"</string> <string name="video_context_menu_header">"视频选项"</string> - <string name="multiface_crop_help">"轻击一张脸开始裁切。"</string> - <string name="photos_gallery_title">"图片库"</string> - <string name="pick_photos_gallery_title">"选择图片"</string> - <string name="videos_gallery_title">"图片库"</string> + <string name="multiface_crop_help">"点按一张脸开始裁剪。"</string> + <string name="photos_gallery_title">"图库"</string> + <string name="pick_photos_gallery_title">"选择照片"</string> + <string name="videos_gallery_title">"图库"</string> <string name="pick_videos_gallery_title">"选择视频"</string> - <string name="loading_progress_format_string">"还剩 <xliff:g id="COUNTER">%d</xliff:g>"</string> - <string name="sendImage">"共享图片的方式"</string> - <string name="setImage">"将图片设置为"</string> - <string name="sendVideo">"共享视频的方式"</string> + <string name="loading_progress_format_string">"还剩 <xliff:g id="COUNTER">%d</xliff:g> 个"</string> + <string name="sendImage">"分享照片的方式"</string> + <string name="setImage">"将照片设置为"</string> + <string name="sendVideo">"分享视频的方式"</string> <string name="movieviewlabel">"电影"</string> <string name="loading_video">"正在载入视频..."</string> - <string name="spaceIsLow_title">"空间不足"</string> - <string name="spaceIsLow_content">"您的 SD 卡已满。请更改质量设置或删除图片库中的内容。"</string> + <string name="spaceIsLow_title">"存储空间不足"</string> + <string name="spaceIsLow_content">"SD 卡空间不足。请更改画质设置或从图库中删除部分项。"</string> <string name="resume_playing_title">"重新播放视频"</string> <string name="resume_playing_message">"从 %s 开始重新播放?"</string> <string name="resume_playing_resume">"重新播放"</string> <string name="resume_playing_restart">"重新开始"</string> <string name="gadget_title">"相框"</string> <string name="file_info_title">"文件信息:"</string> <string name="video_exceed_mms_limit">"您录制的视频太大,无法用彩信发送。请尝试录制短一点的剪辑。"</string> <string name="too_large_to_attach">"文件太大,无法附加。"</string> </resources>
brunsky/WS171-packages-apps-Camera
ce28aa21b335ed1d16307e920bc3166f27f166a5
AI 149721: Import Portuguese translations.
diff --git a/res/values-pt/arrays.xml b/res/values-pt/arrays.xml new file mode 100644 index 0000000..dfbf090 --- /dev/null +++ b/res/values-pt/arrays.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <!-- no translation found for pref_camera_videoquality_entries:0 (4155278146225809483) --> + <!-- no translation found for pref_camera_videoquality_entries:1 (2439895494739176281) --> + <string-array name="pref_camera_videoquality_entryvalues"> + <item>"0"</item> + <item>"1"</item> + </string-array> +</resources> diff --git a/res/values-pt/strings.xml b/res/values-pt/strings.xml new file mode 100644 index 0000000..9f093fb --- /dev/null +++ b/res/values-pt/strings.xml @@ -0,0 +1,188 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <string name="all_images">"Todas as imagens"</string> + <string name="all_videos">"Todos os vídeos"</string> + <string name="camera_label">"Câmera"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> + <string name="gallery_picker_label">"Galeria"</string> + <string name="gallery_camera_bucket_name">"Imagens da câmera"</string> + <string name="gallery_camera_videos_bucket_name">"Vídeos da câmera"</string> + <string name="switch_to_video_lable">"Alternar para vídeo"</string> + <string name="switch_to_camera_lable">"Alternar para câmera"</string> + <string name="crop_label">"Cortar imagem"</string> + <string name="view_label">"Visualizar imagem"</string> + <string name="preferences_label">"Configurações da câmera"</string> + <string name="wait">"Aguarde..."</string> + <string name="no_storage">"Insira um cartão SD antes de usar a câmera."</string> + <string name="not_enough_space">"Seu cartão SD está cheio."</string> + <!-- no translation found for preparing_sd (2914969119574812666) --> + <skip /> + <string name="wallpaper">"Configurando papel de parede, aguarde..."</string> + <string name="savingImage">"Salvando imagem..."</string> + <string name="runningFaceDetection">"Aguarde..."</string> + <string name="flip_orientation">"Inverter orientação"</string> + <string name="settings">"Configurações"</string> + <string name="view">"Visualizar"</string> + <string name="details">"Detalhes"</string> + <string name="rotate">"Girar"</string> + <string name="rotate_left">"Girar para a esquerda"</string> + <string name="rotate_right">"Girar para a direita"</string> + <string name="slide_show">"Apresentação de slides"</string> + <string name="capture_picture">"Capturar imagem"</string> + <string name="capture_video">"Capturar vídeo"</string> + <string name="crop_save_text">"Salvar"</string> + <string name="crop_discard_text">"Descartar"</string> + <string name="confirm_delete_title">"Excluir"</string> + <string name="confirm_delete_message">"A imagem será excluída."</string> + <string name="confirm_delete_video_message">"O vídeo será excluído."</string> + <string name="camera_toss">"Excluir"</string> + <!-- no translation found for camera_gallery (815753042966032398) --> + <skip /> + <string name="camera_share">"Compartilhar"</string> + <string name="camera_set">"Definir como"</string> + <string name="camera_play">"Reproduzir"</string> + <!-- no translation found for camera_attach (4048659554893435232) --> + <skip /> + <!-- no translation found for camera_cancel (8203341746672085747) --> + <skip /> + <string name="camera_crop">"Cortar"</string> + <string name="camera_tossing">"Excluindo..."</string> + <string name="no_way_to_share_image">"Esta imagem não pode ser compartilhada."</string> + <string name="no_way_to_share_video">"Este vídeo não pode ser compartilhado."</string> + <!-- no translation found for video_play (5287787282508002895) --> + <skip /> + <string name="camera_gallery_photos_text">"Galeria"</string> + <string name="camera_pick_wallpaper">"Imagens"</string> + <string name="camera_setas_wallpaper">"Papel de parede"</string> + <string name="pref_gallery_category">"Configurações gerais"</string> + <string name="pref_slideshow_category">"Configurações da apresentação de slides"</string> + <string name="pref_camera_general_settings_category">"Configurações gerais"</string> + <!-- no translation found for pref_gallery_size_title (1363406603879434418) --> + <skip /> + <!-- no translation found for pref_gallery_size_summary (8179967445295243638) --> + <skip /> + <string name="pref_gallery_size_dialogtitle">"Tamanho da imagem"</string> + <string-array name="pref_gallery_size_choices"> + <item>"Grande"</item> + <item>"Pequeno"</item> + </string-array> + <!-- no translation found for pref_gallery_sort_title (7447949250045443386) --> + <skip /> + <!-- no translation found for pref_gallery_sort_summary (6644398051645595214) --> + <skip /> + <string name="pref_gallery_sort_dialogtitle">"Classificar imagens"</string> + <string-array name="pref_gallery_sort_choices"> + <item>"As mais novas primeiro"</item> + <item>"As mais novas por último"</item> + </string-array> + <string name="pref_gallery_slideshow_interval_title">"Intervalo da apresentação de slides"</string> + <string name="pref_gallery_slideshow_interval_summary">"Selecione o tempo que cada slide deve ser exibido na apresentação"</string> + <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo da apresentação de slides"</string> + <string-array name="pref_gallery_slideshow_interval_choices"> + <item>"2 segundos"</item> + <item>"3 segundos"</item> + <item>"4 segundos"</item> + </string-array> + <string name="pref_gallery_slideshow_transition_title">"Transição da apresentação de slides"</string> + <string name="pref_gallery_slideshow_transition_summary">"Selecione o efeito a ser usado ao passar para o próximo slide"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"Transição da apresentação de slides"</string> + <string-array name="pref_gallery_slideshow_transition_choices"> + <item>"Suavizar cor"</item> + <item>"Deslizar da esquerda para a direita"</item> + <item>"Deslizar de cima para baixo"</item> + <item>"Seleção aleatória"</item> + </string-array> + <string name="pref_gallery_slideshow_repeat_title">"Repetir apresentação de slides"</string> + <string name="pref_gallery_slideshow_repeat_summary">"Reproduzir slides mais de uma vez"</string> + <string name="pref_gallery_slideshow_shuffle_title">"Seleção automática de slides"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imagens em ordem aleatória"</string> + <string name="pref_camera_recordlocation_title">"Armazenar local nas imagens"</string> + <string name="pref_camera_recordlocation_summary">"Registrar local nos dados da imagem"</string> + <string name="pref_camera_videoquality_category">"Qualidade do vídeo"</string> + <!-- no translation found for pref_camera_videoquality_title (3836197291744160920) --> + <skip /> + <string name="pref_camera_videoquality_entry_0">"Baixa (para mensagens MMS)"</string> + <string name="pref_camera_videoquality_entry_1">"Alta (para cartão SD)"</string> + <string name="pref_camera_videoquality_dialogtitle">"Qualidade do vídeo"</string> + <string name="camerasettings">"Configurações"</string> + <!-- no translation found for image_gallery_NoImageView_text (409595259802877447) --> + <skip /> + <string name="pref_gallery_confirm_delete_title">"Confirmar exclusões"</string> + <!-- no translation found for pref_gallery_confirm_delete_summary (5253456492765525245) --> + <skip /> + <string name="details_panel_title">"Detalhes"</string> + <string name="details_file_size">"Tamanho do arquivo:"</string> + <string name="details_image_resolution">"Resolução:"</string> + <!-- no translation found for details_duration (1028116471387901402) --> + <skip /> + <string name="details_date_taken">"Data em que foi tirada:"</string> + <!-- no translation found for details_frame_rate (122397836963498191) --> + <skip /> + <!-- no translation found for details_bit_rate (5632311789455402186) --> + <skip /> + <!-- no translation found for details_codec (5580300450432398126) --> + <skip /> + <!-- no translation found for details_format (3700860266600796363) --> + <skip /> + <!-- no translation found for details_dimension_x (4479200210424701240) --> + <skip /> + <!-- no translation found for details_ms (940634969189855292) --> + <skip /> + <!-- no translation found for details_hms (3215779248094151255) --> + <skip /> + <!-- no translation found for details_fps (2707670327505979317) --> + <skip /> + <!-- no translation found for details_kbps (59196416864960850) --> + <skip /> + <!-- no translation found for details_mbps (3978720645766601106) --> + <skip /> + <!-- no translation found for details_ok (6848594369924424312) --> + <skip /> + <string name="context_menu_header">"Opções de imagem"</string> + <string name="video_context_menu_header">"Opções de vídeo"</string> + <string name="multiface_crop_help">"Toque em um rosto para começar."</string> + <string name="photos_gallery_title">"Galeria"</string> + <string name="pick_photos_gallery_title">"Selecionar imagem"</string> + <string name="videos_gallery_title">"Galeria"</string> + <string name="pick_videos_gallery_title">"Selecionar vídeo"</string> + <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> + <string name="sendImage">"Compartilhar imagem via"</string> + <string name="setImage">"Definir imagem como"</string> + <string name="sendVideo">"Compartilhar vídeo via"</string> + <string name="movieviewlabel">"Filmes"</string> + <string name="loading_video">"Carregando vídeo…"</string> + <string name="spaceIsLow_title">"Pouco espaço disponível"</string> + <string name="spaceIsLow_content">"O cartão SD não possui mais espaço disponível. Altere as configurações de qualidade ou exclua itens da Galeria."</string> + <!-- no translation found for resume_playing_title (8996677350649355013) --> + <skip /> + <!-- no translation found for resume_playing_message (5184414518126703481) --> + <skip /> + <!-- no translation found for resume_playing_resume (3847915469173852416) --> + <skip /> + <!-- no translation found for resume_playing_restart (5471008499835769292) --> + <skip /> + <!-- no translation found for gadget_title (259405922673466798) --> + <skip /> + <!-- no translation found for file_info_title (1628963357466012538) --> + <skip /> + <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> + <skip /> + <!-- no translation found for too_large_to_attach (8944461117941172986) --> + <skip /> +</resources>
brunsky/WS171-packages-apps-Camera
e655d54160e5a56d4909f2459eeae9012e9f187f
AI 149135: Add RECORD_AUDIO permission to camera app. Due to an oversight, the RECORD_AUDIO permission was not being enforced. This change adds the permission to the camera app so that when it is enforced, it won't throw an exception. BUG=1868334
diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 8c79f8c..534f669 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,229 +1,230 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.camera" android:sharedUserId="android.media"> <uses-permission android:name="android.permission.CAMERA" /> + <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.SET_WALLPAPER" /> <!-- Needed by the ZoomRingController to set the bit saying we've already shown the tutorial toast. --> <uses-permission android:name="android.permission.WRITE_SETTINGS"/> <application android:icon="@drawable/ic_launcher_camera" android:label="@string/camera_label" android:taskAffinity=""> <service android:name="UploadService" android:process="android.process.media" /> <receiver android:name="CameraButtonIntentReceiver"> <intent-filter> <action android:name="android.intent.action.CAMERA_BUTTON"/> </intent-filter> </receiver> <activity android:name="Camera" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" android:screenOrientation="landscape" android:clearTaskOnLaunch="true" android:taskAffinity="android.task.camera"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.media.action.IMAGE_CAPTURE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.media.action.STILL_IMAGE_CAMERA" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="VideoCamera" android:label="@string/video_camera_label" android:configChanges="orientation|keyboardHidden" android:icon="@drawable/ic_launcher_video_camera" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" android:screenOrientation="landscape" android:clearTaskOnLaunch="true" android:taskAffinity="android.task.videocamera"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.media.action.VIDEO_CAMERA" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.media.action.VIDEO_CAPTURE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="GalleryPicker" android:label="@string/gallery_picker_label" android:configChanges="orientation|keyboardHidden" android:icon="@drawable/ic_launcher_gallery" android:clearTaskOnLaunch="true" android:taskAffinity="android.task.pictures"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="ImageGallery2" android:label="@string/gallery_label" android:configChanges="orientation|keyboardHidden" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/video" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.GET_CONTENT" /> <category android:name="android.intent.category.OPENABLE" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.GET_CONTENT" /> <category android:name="android.intent.category.OPENABLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> </activity> <activity android:name="CropImage" android:process=":CropImage" android:configChanges="orientation|keyboardHidden" android:label="@string/crop_label"> <intent-filter android:label="@string/crop_label"> <action android:name="com.android.camera.action.CROP" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.ALTERNATIVE" /> <category android:name="android.intent.category.SELECTED_ALTERNATIVE" /> </intent-filter> </activity> <activity android:name="ViewImage" android:label="@string/view_label" android:configChanges="orientation|keyboardHidden"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> </activity> <activity android:name="MovieView" android:label="@string/movieviewlabel" android:screenOrientation="landscape" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="rtsp" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="http" /> <data android:mimeType="video/mp4" /> <data android:mimeType="video/3gp" /> <data android:mimeType="video/3gpp" /> <data android:mimeType="video/3gpp2" /> </intent-filter> </activity> <activity android:name="CameraSettings" android:label="@string/preferences_label"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEVELOPMENT_PREFERENCE" /> </intent-filter> </activity> <activity android:name="GallerySettings" android:label="@string/preferences_label"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEVELOPMENT_PREFERENCE" /> </intent-filter> </activity> <activity android:name="SlideShow" android:label="Raw Image Viewer" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.TEST" /> </intent-filter> </activity> <activity android:name=".Wallpaper" android:label="@string/camera_setas_wallpaper" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.ATTACH_DATA" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name=".PickWallpaper" android:label="@string/camera_pick_wallpaper" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.SET_WALLPAPER" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <receiver android:name="PhotoAppWidgetProvider" android:label="@string/gadget_title"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/appwidget_info" /> </receiver> <!-- We configure a widget by asking to pick a photo, then crop it, and store the config internally --> <activity android:name="PhotoAppWidgetConfigure"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" /> </intent-filter> </activity> <!-- We also allow direct binding where the caller provides a bitmap and appWidgetId to bind. We require the permission because this changes our internal database without user confirmation. --> <activity android:name="PhotoAppWidgetBind" android:exported="true" android:theme="@android:style/Theme.NoDisplay" android:permission="android.permission.BIND_APPWIDGET" /> </application> </manifest>
brunsky/WS171-packages-apps-Camera
b104585af4b09f3c7e3dd16eaebb6c96d5064c99
AI 148147: Import lots of zh_TW translation changes.
diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml index f4c3396..8a701eb 100644 --- a/res/values-zh-rTW/strings.xml +++ b/res/values-zh-rTW/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"所有相片"</string> <string name="all_videos">"所有影片"</string> <string name="camera_label">"相機"</string> <string name="video_camera_label">"攝錄影機"</string> <string name="gallery_picker_label">"圖庫"</string> <string name="gallery_camera_bucket_name">"相機圖片"</string> <string name="gallery_camera_videos_bucket_name">"相機影片"</string> <string name="switch_to_video_lable">"切換為影片"</string> <string name="switch_to_camera_lable">"切換為相機"</string> - <string name="crop_label">"裁切相片"</string> + <string name="crop_label">"裁剪相片"</string> <string name="view_label">"檢視相片"</string> <string name="preferences_label">"相機設定"</string> <string name="wait">"請稍候…"</string> <string name="no_storage">"使用相機前請先插入 SD 卡。"</string> <string name="not_enough_space">"SD 卡已滿。"</string> <string name="preparing_sd">"正在準備 SD 卡..."</string> <string name="wallpaper">"設定桌布中,請稍候…"</string> <string name="savingImage">"儲存相片中…"</string> <string name="runningFaceDetection">"請稍候…"</string> <string name="flip_orientation">"旋轉方向"</string> <string name="settings">"設定"</string> <string name="view">"檢視"</string> <string name="details">"詳細資料"</string> <string name="rotate">"旋轉"</string> <string name="rotate_left">"向左旋轉"</string> <string name="rotate_right">"向右旋轉"</string> <string name="slide_show">"投影片"</string> - <string name="capture_picture">"拍攝圖片"</string> + <string name="capture_picture">"拍攝照片"</string> <string name="capture_video">"拍攝影片"</string> <string name="crop_save_text">"儲存"</string> <string name="crop_discard_text">"放棄"</string> <string name="confirm_delete_title">"刪除"</string> <string name="confirm_delete_message">"刪除相片?"</string> <string name="confirm_delete_video_message">"刪除這部影片?"</string> <string name="camera_toss">"刪除"</string> <string name="camera_gallery">"圖庫"</string> <string name="camera_share">"分享"</string> <string name="camera_set">"設為"</string> <string name="camera_play">"播放"</string> <string name="camera_attach">"附加"</string> <string name="camera_cancel">"取消"</string> - <string name="camera_crop">"裁切"</string> + <string name="camera_crop">"裁剪"</string> <string name="camera_tossing">"刪除中…"</string> <string name="no_way_to_share_image">"此相片無法分享。"</string> <string name="no_way_to_share_video">"此影片無法分享。"</string> <string name="video_play">"播放"</string> <string name="camera_gallery_photos_text">"圖庫"</string> - <string name="camera_pick_wallpaper">"相片"</string> + <string name="camera_pick_wallpaper">"圖片"</string> <string name="camera_setas_wallpaper">"桌布"</string> <string name="pref_gallery_category">"一般設定"</string> <string name="pref_slideshow_category">"投影片設定"</string> <string name="pref_camera_general_settings_category">"一般設定"</string> <string name="pref_gallery_size_title">"顯示大小"</string> <string name="pref_gallery_size_summary">"選取相片和影片的顯示大小"</string> <string name="pref_gallery_size_dialogtitle">"相片大小"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"排序順序"</string> <string name="pref_gallery_sort_summary">"選取相片和影片的排序順序"</string> <string name="pref_gallery_sort_dialogtitle">"圖片排序"</string> <string-array name="pref_gallery_sort_choices"> <item>"最新的在前"</item> <item>"最新的在後"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"投影片顯示間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"選取每張投影片顯示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"投影片顯示間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 秒"</item> <item>"3 秒"</item> <item>"4 秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"投影片轉場特效"</string> <string name="pref_gallery_slideshow_transition_summary">"選取更換相片時的轉場特效"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"投影片轉場特效"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"淡入淡出"</item> <item>"左右滑動"</item> <item>"上下滑動"</item> <item>"隨機選取"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"重複播放投影片"</string> <string name="pref_gallery_slideshow_repeat_summary">"旋環播放投影片"</string> <string name="pref_gallery_slideshow_shuffle_title">"隨機播放投影片"</string> <string name="pref_gallery_slideshow_shuffle_summary">"隨機顯示相片"</string> <string name="pref_camera_recordlocation_title">"在相片儲存位置資訊"</string> <string name="pref_camera_recordlocation_summary">"在相片中記錄位置資訊"</string> <string name="pref_camera_videoquality_category">"影片品質"</string> <string name="pref_camera_videoquality_title">"選取影片品質"</string> <string name="pref_camera_videoquality_entry_0">"低 (適用於多媒體簡訊)"</string> <string name="pref_camera_videoquality_entry_1">"高 (適用於 SD 卡)"</string> <string name="pref_camera_videoquality_dialogtitle">"影片品質"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"找不到媒體。"</string> <string name="pref_gallery_confirm_delete_title">"刪除確認"</string> <string name="pref_gallery_confirm_delete_summary">"刪除相片或影片前要顯示確認"</string> <string name="details_panel_title">"詳細資料"</string> <string name="details_file_size">"檔案大小:"</string> <string name="details_image_resolution">"解析度:"</string> <string name="details_duration">"所需時間:"</string> <string name="details_date_taken">"拍攝日期:"</string> <string name="details_frame_rate">"影格速率:"</string> <string name="details_bit_rate">"位元速率:"</string> <string name="details_codec">"編碼器:"</string> <string name="details_format">"格式:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"確定"</string> <string name="context_menu_header">"圖片選項"</string> <string name="video_context_menu_header">"影片選項"</string> - <string name="multiface_crop_help">"選取版面開始裁切"</string> + <string name="multiface_crop_help">"輕觸所需的臉孔開始裁剪。"</string> <string name="photos_gallery_title">"圖庫"</string> <string name="pick_photos_gallery_title">"選取相片"</string> <string name="videos_gallery_title">"圖庫"</string> <string name="pick_videos_gallery_title">"選取影片"</string> <string name="loading_progress_format_string">"還有 <xliff:g id="COUNTER">%d</xliff:g> 張"</string> <string name="sendImage">"透過…分享圖片"</string> <string name="setImage">"設定相片為…"</string> <string name="sendVideo">"透過…分享影片"</string> <string name="movieviewlabel">"電影"</string> <string name="loading_video">"正在載入影片…"</string> <string name="spaceIsLow_title">"空間不足"</string> <string name="spaceIsLow_content">"您的 SD 卡空間已快用完。請變更品質設定或刪除圖庫中的項目。"</string> <string name="resume_playing_title">"繼續播放影片"</string> <string name="resume_playing_message">"要從 %s 繼續播放嗎?"</string> <string name="resume_playing_resume">"繼續播放"</string> <string name="resume_playing_restart">"重新開始"</string> <string name="gadget_title">"相框"</string> <string name="file_info_title">"檔案資訊:"</string> <string name="video_exceed_mms_limit">"您所錄製的影片太大,無法透過 MMS 傳送。請試著錄製較短的影片。"</string> <string name="too_large_to_attach">"檔案過大,超過附件大小限制。"</string> </resources>
brunsky/WS171-packages-apps-Camera
9ed793acf61c4c5dc7369c5b7d4b19c2a9b47e91
AI 148026: Update zh_TW translations.
diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml index 68b84dd..f4c3396 100644 --- a/res/values-zh-rTW/strings.xml +++ b/res/values-zh-rTW/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"所有相片"</string> <string name="all_videos">"所有影片"</string> <string name="camera_label">"相機"</string> <string name="video_camera_label">"攝錄影機"</string> <string name="gallery_picker_label">"圖庫"</string> <string name="gallery_camera_bucket_name">"相機圖片"</string> <string name="gallery_camera_videos_bucket_name">"相機影片"</string> <string name="switch_to_video_lable">"切換為影片"</string> <string name="switch_to_camera_lable">"切換為相機"</string> <string name="crop_label">"裁切相片"</string> <string name="view_label">"檢視相片"</string> <string name="preferences_label">"相機設定"</string> <string name="wait">"請稍候…"</string> <string name="no_storage">"使用相機前請先插入 SD 卡。"</string> <string name="not_enough_space">"SD 卡已滿。"</string> <string name="preparing_sd">"正在準備 SD 卡..."</string> <string name="wallpaper">"設定桌布中,請稍候…"</string> <string name="savingImage">"儲存相片中…"</string> <string name="runningFaceDetection">"請稍候…"</string> <string name="flip_orientation">"旋轉方向"</string> <string name="settings">"設定"</string> <string name="view">"檢視"</string> <string name="details">"詳細資料"</string> <string name="rotate">"旋轉"</string> <string name="rotate_left">"向左旋轉"</string> <string name="rotate_right">"向右旋轉"</string> <string name="slide_show">"投影片"</string> <string name="capture_picture">"拍攝圖片"</string> <string name="capture_video">"拍攝影片"</string> <string name="crop_save_text">"儲存"</string> <string name="crop_discard_text">"放棄"</string> <string name="confirm_delete_title">"刪除"</string> <string name="confirm_delete_message">"刪除相片?"</string> <string name="confirm_delete_video_message">"刪除這部影片?"</string> <string name="camera_toss">"刪除"</string> <string name="camera_gallery">"圖庫"</string> <string name="camera_share">"分享"</string> <string name="camera_set">"設為"</string> <string name="camera_play">"播放"</string> <string name="camera_attach">"附加"</string> <string name="camera_cancel">"取消"</string> <string name="camera_crop">"裁切"</string> <string name="camera_tossing">"刪除中…"</string> <string name="no_way_to_share_image">"此相片無法分享。"</string> <string name="no_way_to_share_video">"此影片無法分享。"</string> <string name="video_play">"播放"</string> <string name="camera_gallery_photos_text">"圖庫"</string> <string name="camera_pick_wallpaper">"相片"</string> <string name="camera_setas_wallpaper">"桌布"</string> <string name="pref_gallery_category">"一般設定"</string> <string name="pref_slideshow_category">"投影片設定"</string> <string name="pref_camera_general_settings_category">"一般設定"</string> <string name="pref_gallery_size_title">"顯示大小"</string> <string name="pref_gallery_size_summary">"選取相片和影片的顯示大小"</string> <string name="pref_gallery_size_dialogtitle">"相片大小"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"排序順序"</string> <string name="pref_gallery_sort_summary">"選取相片和影片的排序順序"</string> <string name="pref_gallery_sort_dialogtitle">"圖片排序"</string> <string-array name="pref_gallery_sort_choices"> <item>"最新的在前"</item> <item>"最新的在後"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"投影片顯示間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"選取每張投影片顯示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"投影片顯示間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 秒"</item> <item>"3 秒"</item> <item>"4 秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"投影片轉場特效"</string> <string name="pref_gallery_slideshow_transition_summary">"選取更換相片時的轉場特效"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"投影片轉場特效"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"淡入淡出"</item> <item>"左右滑動"</item> <item>"上下滑動"</item> <item>"隨機選取"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"重複播放投影片"</string> <string name="pref_gallery_slideshow_repeat_summary">"旋環播放投影片"</string> <string name="pref_gallery_slideshow_shuffle_title">"隨機播放投影片"</string> <string name="pref_gallery_slideshow_shuffle_summary">"隨機顯示相片"</string> <string name="pref_camera_recordlocation_title">"在相片儲存位置資訊"</string> <string name="pref_camera_recordlocation_summary">"在相片中記錄位置資訊"</string> <string name="pref_camera_videoquality_category">"影片品質"</string> <string name="pref_camera_videoquality_title">"選取影片品質"</string> <string name="pref_camera_videoquality_entry_0">"低 (適用於多媒體簡訊)"</string> <string name="pref_camera_videoquality_entry_1">"高 (適用於 SD 卡)"</string> <string name="pref_camera_videoquality_dialogtitle">"影片品質"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"找不到媒體。"</string> <string name="pref_gallery_confirm_delete_title">"刪除確認"</string> <string name="pref_gallery_confirm_delete_summary">"刪除相片或影片前要顯示確認"</string> <string name="details_panel_title">"詳細資料"</string> <string name="details_file_size">"檔案大小:"</string> <string name="details_image_resolution">"解析度:"</string> <string name="details_duration">"所需時間:"</string> <string name="details_date_taken">"拍攝日期:"</string> <string name="details_frame_rate">"影格速率:"</string> <string name="details_bit_rate">"位元速率:"</string> <string name="details_codec">"編碼器:"</string> <string name="details_format">"格式:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"確定"</string> <string name="context_menu_header">"圖片選項"</string> <string name="video_context_menu_header">"影片選項"</string> <string name="multiface_crop_help">"選取版面開始裁切"</string> <string name="photos_gallery_title">"圖庫"</string> <string name="pick_photos_gallery_title">"選取相片"</string> <string name="videos_gallery_title">"圖庫"</string> <string name="pick_videos_gallery_title">"選取影片"</string> <string name="loading_progress_format_string">"還有 <xliff:g id="COUNTER">%d</xliff:g> 張"</string> <string name="sendImage">"透過…分享圖片"</string> <string name="setImage">"設定相片為…"</string> <string name="sendVideo">"透過…分享影片"</string> <string name="movieviewlabel">"電影"</string> <string name="loading_video">"正在載入影片…"</string> <string name="spaceIsLow_title">"空間不足"</string> <string name="spaceIsLow_content">"您的 SD 卡空間已快用完。請變更品質設定或刪除圖庫中的項目。"</string> <string name="resume_playing_title">"繼續播放影片"</string> <string name="resume_playing_message">"要從 %s 繼續播放嗎?"</string> <string name="resume_playing_resume">"繼續播放"</string> <string name="resume_playing_restart">"重新開始"</string> <string name="gadget_title">"相框"</string> <string name="file_info_title">"檔案資訊:"</string> <string name="video_exceed_mms_limit">"您所錄製的影片太大,無法透過 MMS 傳送。請試著錄製較短的影片。"</string> - <string name="too_large_to_attach">"檔案太大,超過附檔上限。"</string> + <string name="too_large_to_attach">"檔案過大,超過附件大小限制。"</string> </resources>
brunsky/WS171-packages-apps-Camera
27828f556f61d8ef6c5e15b0eee0baf991ad8c9f
AI 147962: Import updated zh_TW translations.
diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml index eb85929..68b84dd 100644 --- a/res/values-zh-rTW/strings.xml +++ b/res/values-zh-rTW/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"所有相片"</string> <string name="all_videos">"所有影片"</string> <string name="camera_label">"相機"</string> <string name="video_camera_label">"攝錄影機"</string> <string name="gallery_picker_label">"圖庫"</string> - <string name="gallery_camera_bucket_name">"攝影機圖片"</string> - <string name="gallery_camera_videos_bucket_name">"攝影機影片"</string> + <string name="gallery_camera_bucket_name">"相機圖片"</string> + <string name="gallery_camera_videos_bucket_name">"相機影片"</string> <string name="switch_to_video_lable">"切換為影片"</string> - <string name="switch_to_camera_lable">"切換為攝影機"</string> + <string name="switch_to_camera_lable">"切換為相機"</string> <string name="crop_label">"裁切相片"</string> <string name="view_label">"檢視相片"</string> <string name="preferences_label">"相機設定"</string> <string name="wait">"請稍候…"</string> <string name="no_storage">"使用相機前請先插入 SD 卡。"</string> <string name="not_enough_space">"SD 卡已滿。"</string> <string name="preparing_sd">"正在準備 SD 卡..."</string> <string name="wallpaper">"設定桌布中,請稍候…"</string> <string name="savingImage">"儲存相片中…"</string> <string name="runningFaceDetection">"請稍候…"</string> <string name="flip_orientation">"旋轉方向"</string> <string name="settings">"設定"</string> <string name="view">"檢視"</string> <string name="details">"詳細資料"</string> <string name="rotate">"旋轉"</string> <string name="rotate_left">"向左旋轉"</string> <string name="rotate_right">"向右旋轉"</string> <string name="slide_show">"投影片"</string> <string name="capture_picture">"拍攝圖片"</string> <string name="capture_video">"拍攝影片"</string> <string name="crop_save_text">"儲存"</string> <string name="crop_discard_text">"放棄"</string> <string name="confirm_delete_title">"刪除"</string> - <string name="confirm_delete_message">"此相片會被刪除。"</string> - <string name="confirm_delete_video_message">"將刪除此影片。"</string> + <string name="confirm_delete_message">"刪除相片?"</string> + <string name="confirm_delete_video_message">"刪除這部影片?"</string> <string name="camera_toss">"刪除"</string> <string name="camera_gallery">"圖庫"</string> <string name="camera_share">"分享"</string> <string name="camera_set">"設為"</string> <string name="camera_play">"播放"</string> <string name="camera_attach">"附加"</string> <string name="camera_cancel">"取消"</string> <string name="camera_crop">"裁切"</string> <string name="camera_tossing">"刪除中…"</string> <string name="no_way_to_share_image">"此相片無法分享。"</string> <string name="no_way_to_share_video">"此影片無法分享。"</string> <string name="video_play">"播放"</string> <string name="camera_gallery_photos_text">"圖庫"</string> <string name="camera_pick_wallpaper">"相片"</string> <string name="camera_setas_wallpaper">"桌布"</string> <string name="pref_gallery_category">"一般設定"</string> <string name="pref_slideshow_category">"投影片設定"</string> <string name="pref_camera_general_settings_category">"一般設定"</string> <string name="pref_gallery_size_title">"顯示大小"</string> - <string name="pref_gallery_size_summary">"選取相片和影片顯示大小"</string> + <string name="pref_gallery_size_summary">"選取相片和影片的顯示大小"</string> <string name="pref_gallery_size_dialogtitle">"相片大小"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"排序順序"</string> - <string name="pref_gallery_sort_summary">"選取相片和影片排序順序"</string> + <string name="pref_gallery_sort_summary">"選取相片和影片的排序順序"</string> <string name="pref_gallery_sort_dialogtitle">"圖片排序"</string> <string-array name="pref_gallery_sort_choices"> - <item>"最新的優先"</item> - <item>"最舊的優先"</item> + <item>"最新的在前"</item> + <item>"最新的在後"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"投影片顯示間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"選取每張投影片顯示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"投影片顯示間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 秒"</item> <item>"3 秒"</item> <item>"4 秒"</item> </string-array> - <string name="pref_gallery_slideshow_transition_title">"投影片轉場效果"</string> - <string name="pref_gallery_slideshow_transition_summary">"選取相片更換時的轉場效果"</string> - <string name="pref_gallery_slideshow_transition_dialogtitle">"投影片轉場效果"</string> + <string name="pref_gallery_slideshow_transition_title">"投影片轉場特效"</string> + <string name="pref_gallery_slideshow_transition_summary">"選取更換相片時的轉場特效"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"投影片轉場特效"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"淡入淡出"</item> <item>"左右滑動"</item> <item>"上下滑動"</item> <item>"隨機選取"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"重複播放投影片"</string> - <string name="pref_gallery_slideshow_repeat_summary">"播放投影片多次"</string> + <string name="pref_gallery_slideshow_repeat_summary">"旋環播放投影片"</string> <string name="pref_gallery_slideshow_shuffle_title">"隨機播放投影片"</string> <string name="pref_gallery_slideshow_shuffle_summary">"隨機顯示相片"</string> <string name="pref_camera_recordlocation_title">"在相片儲存位置資訊"</string> - <string name="pref_camera_recordlocation_summary">"在相片中紀錄位置資訊"</string> + <string name="pref_camera_recordlocation_summary">"在相片中記錄位置資訊"</string> <string name="pref_camera_videoquality_category">"影片品質"</string> <string name="pref_camera_videoquality_title">"選取影片品質"</string> <string name="pref_camera_videoquality_entry_0">"低 (適用於多媒體簡訊)"</string> <string name="pref_camera_videoquality_entry_1">"高 (適用於 SD 卡)"</string> <string name="pref_camera_videoquality_dialogtitle">"影片品質"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"找不到媒體。"</string> <string name="pref_gallery_confirm_delete_title">"刪除確認"</string> <string name="pref_gallery_confirm_delete_summary">"刪除相片或影片前要顯示確認"</string> <string name="details_panel_title">"詳細資料"</string> <string name="details_file_size">"檔案大小:"</string> <string name="details_image_resolution">"解析度:"</string> <string name="details_duration">"所需時間:"</string> <string name="details_date_taken">"拍攝日期:"</string> <string name="details_frame_rate">"影格速率:"</string> <string name="details_bit_rate">"位元速率:"</string> <string name="details_codec">"編碼器:"</string> <string name="details_format">"格式:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"確定"</string> <string name="context_menu_header">"圖片選項"</string> <string name="video_context_menu_header">"影片選項"</string> <string name="multiface_crop_help">"選取版面開始裁切"</string> <string name="photos_gallery_title">"圖庫"</string> <string name="pick_photos_gallery_title">"選取相片"</string> <string name="videos_gallery_title">"圖庫"</string> <string name="pick_videos_gallery_title">"選取影片"</string> <string name="loading_progress_format_string">"還有 <xliff:g id="COUNTER">%d</xliff:g> 張"</string> <string name="sendImage">"透過…分享圖片"</string> <string name="setImage">"設定相片為…"</string> <string name="sendVideo">"透過…分享影片"</string> <string name="movieviewlabel">"電影"</string> <string name="loading_video">"正在載入影片…"</string> <string name="spaceIsLow_title">"空間不足"</string> <string name="spaceIsLow_content">"您的 SD 卡空間已快用完。請變更品質設定或刪除圖庫中的項目。"</string> <string name="resume_playing_title">"繼續播放影片"</string> <string name="resume_playing_message">"要從 %s 繼續播放嗎?"</string> <string name="resume_playing_resume">"繼續播放"</string> <string name="resume_playing_restart">"重新開始"</string> <string name="gadget_title">"相框"</string> <string name="file_info_title">"檔案資訊:"</string> <string name="video_exceed_mms_limit">"您所錄製的影片太大,無法透過 MMS 傳送。請試著錄製較短的影片。"</string> <string name="too_large_to_attach">"檔案太大,超過附檔上限。"</string> </resources>
brunsky/WS171-packages-apps-Camera
4b6a185dfa87894705a971b62353a8ce5f7f3b91
AI 147492: Update zh_TW translations.
diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml index 2c92912..eb85929 100644 --- a/res/values-zh-rTW/strings.xml +++ b/res/values-zh-rTW/strings.xml @@ -1,157 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"所有相片"</string> <string name="all_videos">"所有影片"</string> <string name="camera_label">"相機"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> + <string name="video_camera_label">"攝錄影機"</string> <string name="gallery_picker_label">"圖庫"</string> <string name="gallery_camera_bucket_name">"攝影機圖片"</string> <string name="gallery_camera_videos_bucket_name">"攝影機影片"</string> <string name="switch_to_video_lable">"切換為影片"</string> <string name="switch_to_camera_lable">"切換為攝影機"</string> <string name="crop_label">"裁切相片"</string> <string name="view_label">"檢視相片"</string> <string name="preferences_label">"相機設定"</string> <string name="wait">"請稍候…"</string> <string name="no_storage">"使用相機前請先插入 SD 卡。"</string> <string name="not_enough_space">"SD 卡已滿。"</string> <string name="preparing_sd">"正在準備 SD 卡..."</string> <string name="wallpaper">"設定桌布中,請稍候…"</string> <string name="savingImage">"儲存相片中…"</string> <string name="runningFaceDetection">"請稍候…"</string> <string name="flip_orientation">"旋轉方向"</string> <string name="settings">"設定"</string> <string name="view">"檢視"</string> <string name="details">"詳細資料"</string> <string name="rotate">"旋轉"</string> <string name="rotate_left">"向左旋轉"</string> <string name="rotate_right">"向右旋轉"</string> <string name="slide_show">"投影片"</string> <string name="capture_picture">"拍攝圖片"</string> <string name="capture_video">"拍攝影片"</string> <string name="crop_save_text">"儲存"</string> <string name="crop_discard_text">"放棄"</string> <string name="confirm_delete_title">"刪除"</string> <string name="confirm_delete_message">"此相片會被刪除。"</string> <string name="confirm_delete_video_message">"將刪除此影片。"</string> <string name="camera_toss">"刪除"</string> <string name="camera_gallery">"圖庫"</string> <string name="camera_share">"分享"</string> <string name="camera_set">"設為"</string> <string name="camera_play">"播放"</string> <string name="camera_attach">"附加"</string> <string name="camera_cancel">"取消"</string> <string name="camera_crop">"裁切"</string> <string name="camera_tossing">"刪除中…"</string> <string name="no_way_to_share_image">"此相片無法分享。"</string> <string name="no_way_to_share_video">"此影片無法分享。"</string> - <!-- no translation found for video_play (5287787282508002895) --> - <skip /> + <string name="video_play">"播放"</string> <string name="camera_gallery_photos_text">"圖庫"</string> <string name="camera_pick_wallpaper">"相片"</string> <string name="camera_setas_wallpaper">"桌布"</string> <string name="pref_gallery_category">"一般設定"</string> <string name="pref_slideshow_category">"投影片設定"</string> <string name="pref_camera_general_settings_category">"一般設定"</string> <string name="pref_gallery_size_title">"顯示大小"</string> <string name="pref_gallery_size_summary">"選取相片和影片顯示大小"</string> <string name="pref_gallery_size_dialogtitle">"相片大小"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"排序順序"</string> <string name="pref_gallery_sort_summary">"選取相片和影片排序順序"</string> <string name="pref_gallery_sort_dialogtitle">"圖片排序"</string> <string-array name="pref_gallery_sort_choices"> <item>"最新的優先"</item> <item>"最舊的優先"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"投影片顯示間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"選取每張投影片顯示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"投影片顯示間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 秒"</item> <item>"3 秒"</item> <item>"4 秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"投影片轉場效果"</string> <string name="pref_gallery_slideshow_transition_summary">"選取相片更換時的轉場效果"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"投影片轉場效果"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"淡入淡出"</item> <item>"左右滑動"</item> <item>"上下滑動"</item> <item>"隨機選取"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"重複播放投影片"</string> <string name="pref_gallery_slideshow_repeat_summary">"播放投影片多次"</string> <string name="pref_gallery_slideshow_shuffle_title">"隨機播放投影片"</string> <string name="pref_gallery_slideshow_shuffle_summary">"隨機顯示相片"</string> <string name="pref_camera_recordlocation_title">"在相片儲存位置資訊"</string> <string name="pref_camera_recordlocation_summary">"在相片中紀錄位置資訊"</string> <string name="pref_camera_videoquality_category">"影片品質"</string> <string name="pref_camera_videoquality_title">"選取影片品質"</string> <string name="pref_camera_videoquality_entry_0">"低 (適用於多媒體簡訊)"</string> <string name="pref_camera_videoquality_entry_1">"高 (適用於 SD 卡)"</string> <string name="pref_camera_videoquality_dialogtitle">"影片品質"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"找不到媒體。"</string> <string name="pref_gallery_confirm_delete_title">"刪除確認"</string> <string name="pref_gallery_confirm_delete_summary">"刪除相片或影片前要顯示確認"</string> <string name="details_panel_title">"詳細資料"</string> <string name="details_file_size">"檔案大小:"</string> <string name="details_image_resolution">"解析度:"</string> <string name="details_duration">"所需時間:"</string> <string name="details_date_taken">"拍攝日期:"</string> <string name="details_frame_rate">"影格速率:"</string> <string name="details_bit_rate">"位元速率:"</string> <string name="details_codec">"編碼器:"</string> <string name="details_format">"格式:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"確定"</string> <string name="context_menu_header">"圖片選項"</string> <string name="video_context_menu_header">"影片選項"</string> <string name="multiface_crop_help">"選取版面開始裁切"</string> <string name="photos_gallery_title">"圖庫"</string> <string name="pick_photos_gallery_title">"選取相片"</string> <string name="videos_gallery_title">"圖庫"</string> <string name="pick_videos_gallery_title">"選取影片"</string> <string name="loading_progress_format_string">"還有 <xliff:g id="COUNTER">%d</xliff:g> 張"</string> <string name="sendImage">"透過…分享圖片"</string> <string name="setImage">"設定相片為…"</string> <string name="sendVideo">"透過…分享影片"</string> <string name="movieviewlabel">"電影"</string> <string name="loading_video">"正在載入影片…"</string> <string name="spaceIsLow_title">"空間不足"</string> <string name="spaceIsLow_content">"您的 SD 卡空間已快用完。請變更品質設定或刪除圖庫中的項目。"</string> <string name="resume_playing_title">"繼續播放影片"</string> <string name="resume_playing_message">"要從 %s 繼續播放嗎?"</string> <string name="resume_playing_resume">"繼續播放"</string> <string name="resume_playing_restart">"重新開始"</string> <string name="gadget_title">"相框"</string> <string name="file_info_title">"檔案資訊:"</string> <string name="video_exceed_mms_limit">"您所錄製的影片太大,無法透過 MMS 傳送。請試著錄製較短的影片。"</string> <string name="too_large_to_attach">"檔案太大,超過附檔上限。"</string> </resources>
brunsky/WS171-packages-apps-Camera
22caca3ba8b7041d112a0d0895a431df16b15cd1
AI 147406: Import revised translations.
diff --git a/res/values-pl/strings.xml b/res/values-pl/strings.xml index f29d3d2..fb63ba3 100644 --- a/res/values-pl/strings.xml +++ b/res/values-pl/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Wszystkie zdjęcia"</string> <string name="all_videos">"Wszystkie filmy"</string> <string name="camera_label">"Aparat"</string> <string name="video_camera_label">"Kamera"</string> <string name="gallery_picker_label">"Galeria"</string> <string name="gallery_camera_bucket_name">"Zdjęcia z aparatu"</string> <string name="gallery_camera_videos_bucket_name">"Filmy z aparatu"</string> <string name="switch_to_video_lable">"Przełącz na wideo"</string> <string name="switch_to_camera_lable">"Przełącz na aparat"</string> <string name="crop_label">"Przytnij zdjęcie"</string> <string name="view_label">"Wyświetl zdjęcie"</string> <string name="preferences_label">"Ustawienia aparatu"</string> - <string name="wait">"Poczekaj…"</string> + <string name="wait">"Proszę czekać…"</string> <string name="no_storage">"Zanim zaczniesz korzystać z aparatu fotograficznego, włóż kartę SD."</string> <string name="not_enough_space">"Karta SD jest pełna."</string> <string name="preparing_sd">"Przygotowywanie karty SD..."</string> - <string name="wallpaper">"Ustawianie tapety, poczekaj…"</string> + <string name="wallpaper">"Ustawianie tapety, proszę czekać…"</string> <string name="savingImage">"Trwa zapisywanie zdjęcia…"</string> - <string name="runningFaceDetection">"Poczekaj…"</string> + <string name="runningFaceDetection">"Proszę czekać…"</string> <string name="flip_orientation">"Zmień orientację"</string> <string name="settings">"Ustawienia"</string> <string name="view">"Wyświetl"</string> <string name="details">"Szczegóły"</string> <string name="rotate">"Obróć"</string> <string name="rotate_left">"Obróć w lewo"</string> <string name="rotate_right">"Obróć w prawo"</string> <string name="slide_show">"Pokaz slajdów"</string> <string name="capture_picture">"Zrób zdjęcie"</string> <string name="capture_video">"Nagraj film wideo"</string> <string name="crop_save_text">"Zapisz"</string> <string name="crop_discard_text">"Odrzuć"</string> <string name="confirm_delete_title">"Usuń"</string> <string name="confirm_delete_message">"Zdjęcie zostanie usunięte."</string> <string name="confirm_delete_video_message">"Film wideo zostanie usunięty."</string> <string name="camera_toss">"Usuń"</string> <string name="camera_gallery">"Galeria"</string> <string name="camera_share">"Prześlij"</string> <string name="camera_set">"Ustaw jako"</string> <string name="camera_play">"Odtwórz"</string> <string name="camera_attach">"Załącz"</string> <string name="camera_cancel">"Anuluj"</string> <string name="camera_crop">"Przytnij"</string> <string name="camera_tossing">"Trwa usuwanie…"</string> <string name="no_way_to_share_image">"Nie można przesłać tego zdjęcia."</string> <string name="no_way_to_share_video">"Nie można przesłać tego filmu."</string> <string name="video_play">"Odtwórz"</string> <string name="camera_gallery_photos_text">"Galeria"</string> <string name="camera_pick_wallpaper">"Zdjęcia"</string> <string name="camera_setas_wallpaper">"Tapeta"</string> <string name="pref_gallery_category">"Ustawienia ogólne"</string> <string name="pref_slideshow_category">"Ustawienia pokazu slajdów"</string> <string name="pref_camera_general_settings_category">"Ustawienia ogólne"</string> <string name="pref_gallery_size_title">"Rozmiar zdjęć i filmów"</string> <string name="pref_gallery_size_summary">"Ustaw wyświetlany rozmiar zdjęć i filmów"</string> <string name="pref_gallery_size_dialogtitle">"Rozmiar"</string> <string-array name="pref_gallery_size_choices"> <item>"Duży"</item> <item>"Mały"</item> </string-array> <string name="pref_gallery_sort_title">"Kolejność sortowania"</string> <string name="pref_gallery_sort_summary">"Wybierz kolejność sortowania zdjęć i filmów"</string> <string name="pref_gallery_sort_dialogtitle">"Sortowanie zdjęć"</string> <string-array name="pref_gallery_sort_choices"> <item>"Od najnowszego"</item> <item>"Od najstarszego"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Interwał pokazu slajdów"</string> <string name="pref_gallery_slideshow_interval_summary">"Wybierz, jak długo mają być wyświetlane poszczególne zdjęcia w pokazie slajdów"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Interwał pokazu slajdów"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 sekundy"</item> <item>"3 sekundy"</item> <item>"4 sekundy"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Efekty pokazu slajdów"</string> <string name="pref_gallery_slideshow_transition_summary">"Wybierz efekt używany przy przejściu z jednego zdjęcia do kolejnego"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Efekty pokazu slajdów"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Pojawianie i znikanie"</item> <item>"Przesuwanie z lewa w prawo"</item> <item>"Przesuwanie góra-dół"</item> <item>"Wybór losowy"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Powtórz pokaz slajdów"</string> <string name="pref_gallery_slideshow_repeat_summary">"Wyświetlaj pokaz slajdów więcej niż raz"</string> <string name="pref_gallery_slideshow_shuffle_title">"Losowa kolejność"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Wyświetlaj zdjęcia w kolejności losowej"</string> - <string name="pref_camera_recordlocation_title">"Zapisuj lokalizację w zdjęciach"</string> + <string name="pref_camera_recordlocation_title">"Lokalizacja w zdjęciach"</string> <string name="pref_camera_recordlocation_summary">"Zapisz lokalizację w danych zdjęcia"</string> <string name="pref_camera_videoquality_category">"Jakość wideo"</string> <string name="pref_camera_videoquality_title">"Wybierz jakość wideo"</string> <string name="pref_camera_videoquality_entry_0">"Niska (dla wiadomości MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Wysoka (dla karty SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Jakość wideo"</string> <string name="camerasettings">"Ustawienia"</string> <string name="image_gallery_NoImageView_text">"Brak plików"</string> <string name="pref_gallery_confirm_delete_title">"Potwierdzanie usuwania"</string> <string name="pref_gallery_confirm_delete_summary">"Wyświetl potwierdzenie przed usunięciem zdjęcia lub filmu"</string> <string name="details_panel_title">"Szczegóły"</string> <string name="details_file_size">"Rozmiar pliku:"</string> <string name="details_image_resolution">"Rozdzielczość:"</string> <string name="details_duration">"Czas trwania:"</string> <string name="details_date_taken">"Data zrobienia zdjęcia:"</string> <string name="details_frame_rate">"Szybkość klatek:"</string> <string name="details_bit_rate">"Szybkość transmisji:"</string> <string name="details_codec">"Kodek:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d ramek/s"</string> <string name="details_kbps">"%1$d Kb/s"</string> <string name="details_mbps">"%1$g Mb/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opcje zdjęć"</string> <string name="video_context_menu_header">"Opcje wideo"</string> <string name="multiface_crop_help">"Dotknij twarzy, aby rozpocząć"</string> <string name="photos_gallery_title">"Galeria"</string> <string name="pick_photos_gallery_title">"Wybierz zdjęcie"</string> <string name="videos_gallery_title">"Galeria"</string> <string name="pick_videos_gallery_title">"Wybierz film wideo"</string> <string name="loading_progress_format_string">"Pozostało <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Prześlij zdjęcie następującą drogą:"</string> <string name="setImage">"Ustaw zdjęcie jako"</string> <string name="sendVideo">"Prześlij film następującą drogą:"</string> <string name="movieviewlabel">"Filmy"</string> <string name="loading_video">"Ładowanie filmu..."</string> <string name="spaceIsLow_title">"Miejsca jest mało"</string> <string name="spaceIsLow_content">"Na karcie SD brakuje miejsca. Zmień ustawienie jakości lub usuń elementy z Galerii."</string> <string name="resume_playing_title">"Wznów film"</string> <string name="resume_playing_message">"Wznowić odtwarzanie od %s?"</string> <string name="resume_playing_resume">"Wznów odtwarzanie"</string> <string name="resume_playing_restart">"Rozpocznij"</string> <string name="gadget_title">"Ramka zdjęcia"</string> <string name="file_info_title">"Informacje o pliku:"</string> <string name="video_exceed_mms_limit">"Nagrany film wideo jest zbyt duży, aby wysłać go w wiadomości MMS. Spróbuj nagrać krótszy film wideo."</string> <string name="too_large_to_attach">"Plik jest zbyt duży do załączenia."</string> </resources>
brunsky/WS171-packages-apps-Camera
e5ca4f5d7fe2bee3edff92adb04360c8113fdf49
AI 146517: Import translation changes. DO NOT MERGE
diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml index 0668e1c..fbb84c8 100644 --- a/res/values-es/strings.xml +++ b/res/values-es/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Todas las imágenes"</string> <string name="all_videos">"Todos los vídeos"</string> <string name="camera_label">"Cámara"</string> <string name="video_camera_label">"Videocámara"</string> <string name="gallery_picker_label">"Galería"</string> <string name="gallery_camera_bucket_name">"Imágenes de cámara"</string> <string name="gallery_camera_videos_bucket_name">"Vídeos de cámara"</string> <string name="switch_to_video_lable">"Cambiar a vídeo"</string> <string name="switch_to_camera_lable">"Cambiar a cámara"</string> <string name="crop_label">"Recortar imagen"</string> <string name="view_label">"Ver imagen"</string> <string name="preferences_label">"Configuración de cámara"</string> <string name="wait">"Por favor, espera..."</string> - <string name="no_storage">"Antes de utilizar la cámara, debes insertar una tarjeta SD."</string> + <string name="no_storage">"Inserta o activa la tarjeta SD para poder utilizar la cámara."</string> <string name="not_enough_space">"La tarjeta SD está llena."</string> <string name="preparing_sd">"Preparando tarjeta SD…"</string> <string name="wallpaper">"Estableciendo fondo de pantalla..."</string> <string name="savingImage">"Guardando imagen..."</string> <string name="runningFaceDetection">"Por favor, espera..."</string> <string name="flip_orientation">"Cambiar orientación"</string> <string name="settings">"Ajustes"</string> <string name="view">"Ver"</string> <string name="details">"Detalles"</string> <string name="rotate">"Girar"</string> <string name="rotate_left">"Girar a la izquierda"</string> <string name="rotate_right">"Girar a la derecha"</string> <string name="slide_show">"Presentación"</string> <string name="capture_picture">"Capturar imagen"</string> <string name="capture_video">"Capturar vídeo"</string> <string name="crop_save_text">"Guardar"</string> <string name="crop_discard_text">"Descartar"</string> <string name="confirm_delete_title">"Suprimir"</string> <string name="confirm_delete_message">"Se eliminará la imagen."</string> <string name="confirm_delete_video_message">"Se eliminará el vídeo."</string> <string name="camera_toss">"Suprimir"</string> <string name="camera_gallery">"Galería"</string> <string name="camera_share">"Compartir"</string> <string name="camera_set">"Establecer como"</string> <string name="camera_play">"Reproducir"</string> <string name="camera_attach">"Adjuntar"</string> <string name="camera_cancel">"Cancelar"</string> <string name="camera_crop">"Recortar"</string> <string name="camera_tossing">"Eliminando..."</string> <string name="no_way_to_share_image">"Esta imagen no se puede compartir."</string> <string name="no_way_to_share_video">"Este vídeo no se puede compartir."</string> <string name="video_play">"Reproducir"</string> <string name="camera_gallery_photos_text">"Galería"</string> <string name="camera_pick_wallpaper">"Imágenes"</string> <string name="camera_setas_wallpaper">"Fondo de pantalla"</string> <string name="pref_gallery_category">"Configuración general"</string> <string name="pref_slideshow_category">"Configuración de presentación"</string> <string name="pref_camera_general_settings_category">"Configuración general"</string> <string name="pref_gallery_size_title">"Tamaño de visualización"</string> <string name="pref_gallery_size_summary">"Seleccionar el tamaño de visualización de imágenes y vídeos"</string> <string name="pref_gallery_size_dialogtitle">"Tamaño de imagen"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Pequeña"</item> </string-array> <string name="pref_gallery_sort_title">"Orden"</string> <string name="pref_gallery_sort_summary">"Seleccionar el orden de imágenes y vídeos"</string> <string name="pref_gallery_sort_dialogtitle">"Ordenación de imágenes"</string> <string-array name="pref_gallery_sort_choices"> <item>"Más recientes primero"</item> <item>"Más recientes al final"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalo de presentación"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleccionar la duración de cada diapositiva"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo de presentación"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 segundos"</item> <item>"3 segundos"</item> <item>"4 segundos"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transición de diapositivas"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleccionar el efecto que se aplicará al pasar de una diapositiva a otra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transición de diapositivas"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Fundido de entrada y salida"</item> <item>"Transición de izquierda a derecha"</item> <item>"Transición de arriba a abajo"</item> <item>"Selección aleatoria"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Repetir presentación"</string> <string name="pref_gallery_slideshow_repeat_summary">"Mostrar presentación más de una vez"</string> <string name="pref_gallery_slideshow_shuffle_title">"Orden aleatorio"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imágenes en orden aleatorio"</string> <string name="pref_camera_recordlocation_title">"Almacenar en imágenes"</string> <string name="pref_camera_recordlocation_summary">"Registrar ubicación en datos de imagen"</string> <string name="pref_camera_videoquality_category">"Calidad de vídeo"</string> <string name="pref_camera_videoquality_title">"Seleccionar calidad de vídeo"</string> <string name="pref_camera_videoquality_entry_0">"Baja (para mensajes MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (para tarjeta SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Calidad de vídeo"</string> <string name="camerasettings">"Ajustes"</string> <string name="image_gallery_NoImageView_text">"No se ha encontrado ningún elemento."</string> <string name="pref_gallery_confirm_delete_title">"Confirmar eliminaciones"</string> <string name="pref_gallery_confirm_delete_summary">"Mostrar confirmación antes de eliminar una imagen o un vídeo"</string> <string name="details_panel_title">"Detalles"</string> <string name="details_file_size">"Tamaño de archivo:"</string> <string name="details_image_resolution">"Resolución:"</string> <string name="details_duration">"Duración:"</string> <string name="details_date_taken">"Fecha de realización:"</string> <string name="details_frame_rate">"Frecuencia de imagen:"</string> <string name="details_bit_rate">"Velocidad binaria:"</string> <string name="details_codec">"Códec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"Aceptar"</string> <string name="context_menu_header">"Opciones de imagen"</string> <string name="video_context_menu_header">"Opciones de vídeo"</string> <string name="multiface_crop_help">"Toca una cara para empezar."</string> <string name="photos_gallery_title">"Galería"</string> <string name="pick_photos_gallery_title">"Seleccionar imagen"</string> <string name="videos_gallery_title">"Galería"</string> <string name="pick_videos_gallery_title">"Seleccionar vídeo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> <string name="sendImage">"Compartir imagen por"</string> <string name="setImage">"Establecer imagen como"</string> <string name="sendVideo">"Compartir vídeo a través de"</string> <string name="movieviewlabel">"Películas"</string> <string name="loading_video">"Cargando vídeo…"</string> <string name="spaceIsLow_title">"Poco espacio"</string> <string name="spaceIsLow_content">"No queda espacio en la tarjeta SD. Cambia la configuración de calidad o elimina elementos de la galería."</string> <string name="resume_playing_title">"Reanudar vídeo"</string> <string name="resume_playing_message">"Reanudar reproducción a partir de %s ?"</string> <string name="resume_playing_resume">"Reanudar reproducción"</string> <string name="resume_playing_restart">"Volver a reproducir"</string> <string name="gadget_title">"Picture frame"</string> <string name="file_info_title">"Información de archivo:"</string> <string name="video_exceed_mms_limit">"El vídeo que has grabado es demasiado grande para enviarlo a través de MMS. Intenta grabar un vídeo de menor duración."</string> <string name="too_large_to_attach">"El archivo es demasiado grande para adjuntarlo."</string> </resources>
brunsky/WS171-packages-apps-Camera
439027c09fc350e5b2b21b1315f3a2db5c1a1c30
AI 146365: Import revised translations. DO NOT MERGE
diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml index 7c58b28..9a73840 100644 --- a/res/values-it/strings.xml +++ b/res/values-it/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Tutte le foto"</string> <string name="all_videos">"Tutti i video"</string> <string name="camera_label">"Fotocamera"</string> <string name="video_camera_label">"Videocamera"</string> <string name="gallery_picker_label">"Galleria"</string> <string name="gallery_camera_bucket_name">"Foto"</string> <string name="gallery_camera_videos_bucket_name">"Video fotocamera"</string> <string name="switch_to_video_lable">"Passa a video"</string> <string name="switch_to_camera_lable">"Passa a fotocamera"</string> <string name="crop_label">"Ritaglia foto"</string> <string name="view_label">"Visualizza foto"</string> <string name="preferences_label">"Impostazioni fotocamera"</string> <string name="wait">"Attendere..."</string> <string name="no_storage">"Per usare la fotocamera devi inserire una scheda SD."</string> <string name="not_enough_space">"La scheda SD è piena."</string> <string name="preparing_sd">"Preparazione scheda SD…"</string> <string name="wallpaper">"Impostazione sfondo, attendi..."</string> <string name="savingImage">"Salvataggio foto..."</string> <string name="runningFaceDetection">"Attendere..."</string> <string name="flip_orientation">"Capovolgi orientamento"</string> <string name="settings">"Impostazioni"</string> <string name="view">"Visualizza"</string> <string name="details">"Dettagli"</string> <string name="rotate">"Ruota"</string> <string name="rotate_left">"Ruota a sinistra"</string> <string name="rotate_right">"Ruota a destra"</string> <string name="slide_show">"Presentazione"</string> <string name="capture_picture">"Scatta foto"</string> <string name="capture_video">"Registra video"</string> <string name="crop_save_text">"Salva"</string> <string name="crop_discard_text">"Annulla"</string> <string name="confirm_delete_title">"Elimina"</string> <string name="confirm_delete_message">"La foto verrà eliminata."</string> <string name="confirm_delete_video_message">"Il video verrà eliminato."</string> <string name="camera_toss">"Elimina"</string> <string name="camera_gallery">"Galleria"</string> <string name="camera_share">"Condividi"</string> <string name="camera_set">"Imposta come"</string> <string name="camera_play">"Riproduci"</string> <string name="camera_attach">"Allega"</string> <string name="camera_cancel">"Annulla"</string> <string name="camera_crop">"Ritaglia"</string> <string name="camera_tossing">"Eliminazione..."</string> <string name="no_way_to_share_image">"Impossibile condividere la foto."</string> <string name="no_way_to_share_video">"Impossibile condividere il video."</string> <string name="video_play">"Riproduci"</string> <string name="camera_gallery_photos_text">"Galleria"</string> <string name="camera_pick_wallpaper">"Foto"</string> <string name="camera_setas_wallpaper">"Sfondo"</string> <string name="pref_gallery_category">"Impostazioni generali"</string> <string name="pref_slideshow_category">"Impostazioni presentazione"</string> <string name="pref_camera_general_settings_category">"Impostazioni generali"</string> <string name="pref_gallery_size_title">"Dimensioni schermo"</string> <string name="pref_gallery_size_summary">"Seleziona dimensioni di visualizz. di foto e video"</string> <string name="pref_gallery_size_dialogtitle">"Dimensioni foto"</string> <string-array name="pref_gallery_size_choices"> <item>"Grandi"</item> <item>"Piccole"</item> </string-array> <string name="pref_gallery_sort_title">"Ordinamento"</string> <string name="pref_gallery_sort_summary">"Seleziona l\'ordinamento di foto e video"</string> <string name="pref_gallery_sort_dialogtitle">"Ordine foto"</string> <string-array name="pref_gallery_sort_choices"> <item>"Da più recente"</item> <item>"Da meno recente"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervallo presentazione"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleziona la durata di ogni diapositiva"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervallo presentazione"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 secondi"</item> <item>"3 secondi"</item> <item>"4 secondi"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transizione presentazione"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleziona l\'effetto da usare per passare da una diapositiva all\'altra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transizione diapositive"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Dissolvenza"</item> <item>"Da sinistra a destra"</item> <item>"Dall\'alto verso il basso"</item> <item>"Selezione casuale"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Ripeti presentazione"</string> <string name="pref_gallery_slideshow_repeat_summary">"Riproduci più volte la presentazione"</string> <string name="pref_gallery_slideshow_shuffle_title">"Riproduzione casuale"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostra le foto in ordine casuale"</string> <string name="pref_camera_recordlocation_title">"Salva località nelle foto"</string> <string name="pref_camera_recordlocation_summary">"Registra località nei dati della foto"</string> <string name="pref_camera_videoquality_category">"Qualità video"</string> <string name="pref_camera_videoquality_title">"Seleziona la qualità video"</string> <string name="pref_camera_videoquality_entry_0">"Bassa (per MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (per scheda SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Qualità video"</string> <string name="camerasettings">"Impostazioni"</string> <string name="image_gallery_NoImageView_text">"Nessun media trovato."</string> <string name="pref_gallery_confirm_delete_title">"Conferma eliminazioni"</string> <string name="pref_gallery_confirm_delete_summary">"Mostra conferma prima di eliminare una foto o un video"</string> <string name="details_panel_title">"Dettagli"</string> <string name="details_file_size">"Dim. file:"</string> <string name="details_image_resolution">"Risoluzione:"</string> <string name="details_duration">"Durata:"</string> <string name="details_date_taken">"Data scatto:"</string> <string name="details_frame_rate">"Frequenza fotogrammi:"</string> <string name="details_bit_rate">"Velocità in bit:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opzioni foto"</string> <string name="video_context_menu_header">"Opzioni video"</string> <string name="multiface_crop_help">"Tocca un viso per iniziare."</string> <string name="photos_gallery_title">"Galleria"</string> <string name="pick_photos_gallery_title">"Seleziona foto"</string> <string name="videos_gallery_title">"Galleria"</string> <string name="pick_videos_gallery_title">"Seleziona video"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> rimanenti"</string> <string name="sendImage">"Condividi foto via"</string> <string name="setImage">"Imposta foto come"</string> - <string name="sendVideo">"Condividi video via"</string> + <string name="sendVideo">"Condividi video tramite"</string> <string name="movieviewlabel">"Film"</string> <string name="loading_video">"Caricamento video..."</string> <string name="spaceIsLow_title">"Spazio in esaurimento"</string> <string name="spaceIsLow_content">"Lo spazio della scheda SD si sta esaurendo. Cambia l\'impostazione di qualità o elimina elementi nella galleria."</string> <string name="resume_playing_title">"Riprendi video"</string> <string name="resume_playing_message">"Riprendi riproduzione da %s ?"</string> <string name="resume_playing_resume">"Riprendi riproduzione"</string> <string name="resume_playing_restart">"Ricomincia"</string> <string name="gadget_title">"Cornice immagine"</string> <string name="file_info_title">"Info file:"</string> <string name="video_exceed_mms_limit">"Il video registrato è troppo grande per essere inviato tramite MMS. Prova a registrare un clip più corto."</string> <string name="too_large_to_attach">"File troppo grande. Impossibile allegarlo."</string> </resources> diff --git a/res/values-nb/strings.xml b/res/values-nb/strings.xml index 63adfaa..8e7a9a8 100644 --- a/res/values-nb/strings.xml +++ b/res/values-nb/strings.xml @@ -1,158 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Alle bilder"</string> <string name="all_videos">"Alle videoer"</string> <string name="camera_label">"Kamera"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> + <string name="video_camera_label">"Video"</string> <string name="gallery_picker_label">"Galleri"</string> <string name="gallery_camera_bucket_name">"Bilder fra kamera"</string> <string name="gallery_camera_videos_bucket_name">"Videoer fra kamera"</string> <string name="switch_to_video_lable">"Bytt til video"</string> <string name="switch_to_camera_lable">"Bytt til kamera"</string> <string name="crop_label">"Beskjær bilde"</string> <string name="view_label">"Se på bilde"</string> <string name="preferences_label">"Kamerainnstillinger"</string> <string name="wait">"Vent litt…"</string> <string name="no_storage">"Sett inn et minnekort før du bruker kameraet."</string> <string name="not_enough_space">"Minnekortet er fullt."</string> <string name="preparing_sd">"Forbereder minnekort…"</string> <string name="wallpaper">"Setter bakgrunnsbilde, vent litt…"</string> <string name="savingImage">"Lagrer bilde…"</string> <string name="runningFaceDetection">"Vent litt…"</string> <string name="flip_orientation">"Roter skjerm"</string> <string name="settings">"Innstillinger"</string> <string name="view">"Vis"</string> <string name="details">"Detaljer"</string> <string name="rotate">"Roter"</string> <string name="rotate_left">"Roter mot venstre"</string> <string name="rotate_right">"Roter mot høyre"</string> <string name="slide_show">"Lysbildevisning"</string> <string name="capture_picture">"Ta bilde"</string> <string name="capture_video">"Ta opp video"</string> <string name="crop_save_text">"Lagre"</string> <string name="crop_discard_text">"Forkast"</string> <string name="confirm_delete_title">"Slett"</string> <string name="confirm_delete_message">"Bildet vil bli slettet."</string> <string name="confirm_delete_video_message">"Videoen vil bli slettet."</string> <string name="camera_toss">"Slett"</string> <string name="camera_gallery">"Galleri"</string> <string name="camera_share">"Del"</string> <string name="camera_set">"Bruk som"</string> <string name="camera_play">"Spill"</string> <string name="camera_attach">"Legg ved"</string> <string name="camera_cancel">"Avbryt"</string> <string name="camera_crop">"Beskjær"</string> <string name="camera_tossing">"Sletter…"</string> <string name="no_way_to_share_image">"Bildet kan ikke deles."</string> <string name="no_way_to_share_video">"Videoen kan ikke deles."</string> - <!-- no translation found for video_play (5287787282508002895) --> - <skip /> + <string name="video_play">"Spill"</string> <string name="camera_gallery_photos_text">"Galleri"</string> <string name="camera_pick_wallpaper">"Bilder"</string> <string name="camera_setas_wallpaper">"Bakgrunnsbilder"</string> <string name="pref_gallery_category">"Generelle innstillinger"</string> <string name="pref_slideshow_category">"Innstillinger for lysbildevisning"</string> <string name="pref_camera_general_settings_category">"Generelle innstillinger"</string> <string name="pref_gallery_size_title">"Bildestørrelse"</string> <string name="pref_gallery_size_summary">"Velg hvor stort bilder skal vises"</string> <string name="pref_gallery_size_dialogtitle">"Bildestørrelse"</string> <string-array name="pref_gallery_size_choices"> <item>"Stor"</item> <item>"Liten"</item> </string-array> <string name="pref_gallery_sort_title">"Bildesortering"</string> <string name="pref_gallery_sort_summary">"Velg i hvilken rekkefølge bildene skal sorteres"</string> <string name="pref_gallery_sort_dialogtitle">"Bildesortering"</string> <string-array name="pref_gallery_sort_choices"> <item>"Nyeste først"</item> <item>"Nyeste sist"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Pause i lysbildevisning"</string> <string name="pref_gallery_slideshow_interval_summary">"Velg hvor lenge hvert lysbilde skal vises"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Pause i lysbildevisning"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 sekunder"</item> <item>"3 sekunder"</item> <item>"4 sekunder"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Lysbildeovergang"</string> <string name="pref_gallery_slideshow_transition_summary">"Velg effekten som skal brukes mellom lysbilder"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Lysbildevergang"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ton inn og ut"</item> <item>"Skli venstre - høyre"</item> <item>"Skli opp - ned"</item> <item>"Tilfeldig"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Gjenta lysbildeserie"</string> <string name="pref_gallery_slideshow_repeat_summary">"Vis lydbildeserie mer enn en gang"</string> <string name="pref_gallery_slideshow_shuffle_title">"Stokk lysbilder"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Vis bilder i tilfeldig rekkefølge"</string> <string name="pref_camera_recordlocation_title">"Lagre sted i bilder"</string> <string name="pref_camera_recordlocation_summary">"Lagre sted i bildedata"</string> <string name="pref_camera_videoquality_category">"Videokvalitet"</string> <string name="pref_camera_videoquality_title">"Videokvalitet"</string> <string name="pref_camera_videoquality_entry_0">"Lav (for MMS-meldinger)"</string> <string name="pref_camera_videoquality_entry_1">"Høy (for minnekort)"</string> <string name="pref_camera_videoquality_dialogtitle">"Videokvalitet"</string> <string name="camerasettings">"Innstillinger"</string> <string name="image_gallery_NoImageView_text">"Fant ingen bilder."</string> <string name="pref_gallery_confirm_delete_title">"Bekreft sletting"</string> <string name="pref_gallery_confirm_delete_summary">"Vis bekreftelse før bilder slettes"</string> <string name="details_panel_title">"Detaljer"</string> <string name="details_file_size">"Filstørrelse:"</string> <string name="details_image_resolution">"Oppløsning:"</string> <string name="details_duration">"Varighet:"</string> <string name="details_date_taken">"Dato tatt:"</string> <string name="details_frame_rate">"Bildefrekvens:"</string> <string name="details_bit_rate">"Bitrate:"</string> <string name="details_codec">"Kodek:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Bildeinnstillinger"</string> <string name="video_context_menu_header">"Videoinnstillinger"</string> <string name="multiface_crop_help">"Trykk på et ansikt for å begynne."</string> <string name="photos_gallery_title">"Galleri"</string> <string name="pick_photos_gallery_title">"Velg bilde"</string> <string name="videos_gallery_title">"Galleri"</string> <string name="pick_videos_gallery_title">"Velg video"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> gjenstår"</string> <string name="sendImage">"Del bilde via"</string> <string name="setImage">"Bruk bilde som"</string> <string name="sendVideo">"Del video via"</string> <string name="movieviewlabel">"Filmer"</string> <string name="loading_video">"Laster video…"</string> <string name="spaceIsLow_title">"Lite plass"</string> <string name="spaceIsLow_content">"Minnekortet begynner å gå tom for plass. Endre kvalitetsinnstillingen eller slett bilder fra galleriet."</string> <string name="resume_playing_title">"Fortsett avspilling"</string> <string name="resume_playing_message">"Fortsett avspilling fra %s?"</string> <string name="resume_playing_resume">"Fortsett avspilling"</string> <string name="resume_playing_restart">"Begynn på nytt"</string> <string name="gadget_title">"Bilderamme"</string> <string name="file_info_title">"Filinformasjon:"</string> <string name="video_exceed_mms_limit">"Videoen er for stor til å sendes over MMS. Prøv å ta opp en kortere video."</string> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="too_large_to_attach">"Filen er for stor til å legges ved."</string> </resources>
brunsky/WS171-packages-apps-Camera
002391bb77e4ced7580235a558ab402134ef8d84
AI 146175: Import updated translations.
diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml index a631efa..0668e1c 100644 --- a/res/values-es/strings.xml +++ b/res/values-es/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Todas las imágenes"</string> <string name="all_videos">"Todos los vídeos"</string> <string name="camera_label">"Cámara"</string> <string name="video_camera_label">"Videocámara"</string> <string name="gallery_picker_label">"Galería"</string> <string name="gallery_camera_bucket_name">"Imágenes de cámara"</string> <string name="gallery_camera_videos_bucket_name">"Vídeos de cámara"</string> <string name="switch_to_video_lable">"Cambiar a vídeo"</string> <string name="switch_to_camera_lable">"Cambiar a cámara"</string> <string name="crop_label">"Recortar imagen"</string> <string name="view_label">"Ver imagen"</string> <string name="preferences_label">"Configuración de cámara"</string> <string name="wait">"Por favor, espera..."</string> <string name="no_storage">"Antes de utilizar la cámara, debes insertar una tarjeta SD."</string> <string name="not_enough_space">"La tarjeta SD está llena."</string> <string name="preparing_sd">"Preparando tarjeta SD…"</string> <string name="wallpaper">"Estableciendo fondo de pantalla..."</string> <string name="savingImage">"Guardando imagen..."</string> <string name="runningFaceDetection">"Por favor, espera..."</string> <string name="flip_orientation">"Cambiar orientación"</string> <string name="settings">"Ajustes"</string> <string name="view">"Ver"</string> <string name="details">"Detalles"</string> <string name="rotate">"Girar"</string> <string name="rotate_left">"Girar a la izquierda"</string> <string name="rotate_right">"Girar a la derecha"</string> <string name="slide_show">"Presentación"</string> <string name="capture_picture">"Capturar imagen"</string> <string name="capture_video">"Capturar vídeo"</string> <string name="crop_save_text">"Guardar"</string> <string name="crop_discard_text">"Descartar"</string> <string name="confirm_delete_title">"Suprimir"</string> <string name="confirm_delete_message">"Se eliminará la imagen."</string> <string name="confirm_delete_video_message">"Se eliminará el vídeo."</string> <string name="camera_toss">"Suprimir"</string> <string name="camera_gallery">"Galería"</string> <string name="camera_share">"Compartir"</string> <string name="camera_set">"Establecer como"</string> <string name="camera_play">"Reproducir"</string> <string name="camera_attach">"Adjuntar"</string> <string name="camera_cancel">"Cancelar"</string> <string name="camera_crop">"Recortar"</string> <string name="camera_tossing">"Eliminando..."</string> <string name="no_way_to_share_image">"Esta imagen no se puede compartir."</string> <string name="no_way_to_share_video">"Este vídeo no se puede compartir."</string> <string name="video_play">"Reproducir"</string> <string name="camera_gallery_photos_text">"Galería"</string> <string name="camera_pick_wallpaper">"Imágenes"</string> <string name="camera_setas_wallpaper">"Fondo de pantalla"</string> <string name="pref_gallery_category">"Configuración general"</string> <string name="pref_slideshow_category">"Configuración de presentación"</string> <string name="pref_camera_general_settings_category">"Configuración general"</string> <string name="pref_gallery_size_title">"Tamaño de visualización"</string> <string name="pref_gallery_size_summary">"Seleccionar el tamaño de visualización de imágenes y vídeos"</string> <string name="pref_gallery_size_dialogtitle">"Tamaño de imagen"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Pequeña"</item> </string-array> <string name="pref_gallery_sort_title">"Orden"</string> <string name="pref_gallery_sort_summary">"Seleccionar el orden de imágenes y vídeos"</string> <string name="pref_gallery_sort_dialogtitle">"Ordenación de imágenes"</string> <string-array name="pref_gallery_sort_choices"> <item>"Más recientes primero"</item> <item>"Más recientes al final"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalo de presentación"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleccionar la duración de cada diapositiva"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo de presentación"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 segundos"</item> <item>"3 segundos"</item> <item>"4 segundos"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transición de diapositivas"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleccionar el efecto que se aplicará al pasar de una diapositiva a otra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transición de diapositivas"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Fundido de entrada y salida"</item> <item>"Transición de izquierda a derecha"</item> <item>"Transición de arriba a abajo"</item> <item>"Selección aleatoria"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Repetir presentación"</string> <string name="pref_gallery_slideshow_repeat_summary">"Mostrar presentación más de una vez"</string> - <string name="pref_gallery_slideshow_shuffle_title">"Reproducir aleatoriamente"</string> + <string name="pref_gallery_slideshow_shuffle_title">"Orden aleatorio"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imágenes en orden aleatorio"</string> - <string name="pref_camera_recordlocation_title">"Almacenar ubicación en imágenes"</string> + <string name="pref_camera_recordlocation_title">"Almacenar en imágenes"</string> <string name="pref_camera_recordlocation_summary">"Registrar ubicación en datos de imagen"</string> <string name="pref_camera_videoquality_category">"Calidad de vídeo"</string> <string name="pref_camera_videoquality_title">"Seleccionar calidad de vídeo"</string> <string name="pref_camera_videoquality_entry_0">"Baja (para mensajes MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (para tarjeta SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Calidad de vídeo"</string> <string name="camerasettings">"Ajustes"</string> <string name="image_gallery_NoImageView_text">"No se ha encontrado ningún elemento."</string> <string name="pref_gallery_confirm_delete_title">"Confirmar eliminaciones"</string> <string name="pref_gallery_confirm_delete_summary">"Mostrar confirmación antes de eliminar una imagen o un vídeo"</string> <string name="details_panel_title">"Detalles"</string> <string name="details_file_size">"Tamaño de archivo:"</string> <string name="details_image_resolution">"Resolución:"</string> <string name="details_duration">"Duración:"</string> <string name="details_date_taken">"Fecha de realización:"</string> <string name="details_frame_rate">"Frecuencia de imagen:"</string> <string name="details_bit_rate">"Velocidad binaria:"</string> <string name="details_codec">"Códec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"Aceptar"</string> <string name="context_menu_header">"Opciones de imagen"</string> <string name="video_context_menu_header">"Opciones de vídeo"</string> <string name="multiface_crop_help">"Toca una cara para empezar."</string> <string name="photos_gallery_title">"Galería"</string> <string name="pick_photos_gallery_title">"Seleccionar imagen"</string> <string name="videos_gallery_title">"Galería"</string> <string name="pick_videos_gallery_title">"Seleccionar vídeo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> <string name="sendImage">"Compartir imagen por"</string> <string name="setImage">"Establecer imagen como"</string> <string name="sendVideo">"Compartir vídeo a través de"</string> <string name="movieviewlabel">"Películas"</string> <string name="loading_video">"Cargando vídeo…"</string> <string name="spaceIsLow_title">"Poco espacio"</string> <string name="spaceIsLow_content">"No queda espacio en la tarjeta SD. Cambia la configuración de calidad o elimina elementos de la galería."</string> <string name="resume_playing_title">"Reanudar vídeo"</string> <string name="resume_playing_message">"Reanudar reproducción a partir de %s ?"</string> <string name="resume_playing_resume">"Reanudar reproducción"</string> <string name="resume_playing_restart">"Volver a reproducir"</string> <string name="gadget_title">"Picture frame"</string> <string name="file_info_title">"Información de archivo:"</string> <string name="video_exceed_mms_limit">"El vídeo que has grabado es demasiado grande para enviarlo a través de MMS. Intenta grabar un vídeo de menor duración."</string> <string name="too_large_to_attach">"El archivo es demasiado grande para adjuntarlo."</string> </resources> diff --git a/res/values-fr/strings.xml b/res/values-fr/strings.xml index e0285e4..f3214ad 100644 --- a/res/values-fr/strings.xml +++ b/res/values-fr/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Toutes les images"</string> <string name="all_videos">"Toutes les vidéos"</string> <string name="camera_label">"Appareil photo"</string> <string name="video_camera_label">"Caméra"</string> <string name="gallery_picker_label">"Galerie"</string> <string name="gallery_camera_bucket_name">"Photos de l\'appareil"</string> <string name="gallery_camera_videos_bucket_name">"Vidéos de la caméra"</string> <string name="switch_to_video_lable">"Passer en mode vidéo"</string> <string name="switch_to_camera_lable">"Passer en mode appareil photo"</string> <string name="crop_label">"Rogner l\'image"</string> <string name="view_label">"Afficher l\'image"</string> <string name="preferences_label">"Paramètres de l\'appareil photo"</string> <string name="wait">"Veuillez patienter..."</string> <string name="no_storage">"Veuillez insérer une carte SD avant d\'utiliser l\'appareil photo."</string> <string name="not_enough_space">"Votre carte SD est pleine."</string> <string name="preparing_sd">"Préparation de la carte SD..."</string> - <string name="wallpaper">"Configuration de l\'arrière-plan en cours. Veuillez patienter..."</string> + <string name="wallpaper">"Configuration du fond d\'écran en cours. Veuillez patienter..."</string> <string name="savingImage">"Enregistrement de l\'image"</string> <string name="runningFaceDetection">"Veuillez patienter..."</string> <string name="flip_orientation">"Orientation"</string> <string name="settings">"Paramètres"</string> <string name="view">"Afficher"</string> <string name="details">"Détails"</string> <string name="rotate">"Faire pivoter"</string> <string name="rotate_left">"Faire pivoter à gauche"</string> <string name="rotate_right">"Faire pivoter à droite"</string> <string name="slide_show">"Diaporama"</string> <string name="capture_picture">"Prendre une photo"</string> <string name="capture_video">"Prendre une vidéo"</string> <string name="crop_save_text">"Enregistrer"</string> <string name="crop_discard_text">"Annuler"</string> <string name="confirm_delete_title">"Supprimer"</string> <string name="confirm_delete_message">"L\'image sera supprimée."</string> <string name="confirm_delete_video_message">"La vidéo va être supprimée."</string> <string name="camera_toss">"Supprimer"</string> <string name="camera_gallery">"Galerie"</string> <string name="camera_share">"Partager"</string> <string name="camera_set">"Définir comme"</string> <string name="camera_play">"Lire"</string> <string name="camera_attach">"Pièce jointe"</string> <string name="camera_cancel">"Annuler"</string> <string name="camera_crop">"Rogner"</string> <string name="camera_tossing">"Suppression..."</string> <string name="no_way_to_share_image">"Impossible de partager cette image."</string> <string name="no_way_to_share_video">"Cette vidéo ne peut pas être partagée."</string> <string name="video_play">"Lire"</string> <string name="camera_gallery_photos_text">"Galerie"</string> <string name="camera_pick_wallpaper">"Images"</string> - <string name="camera_setas_wallpaper">"Arrière-plan"</string> + <string name="camera_setas_wallpaper">"Fond d\'écran"</string> <string name="pref_gallery_category">"Paramètres généraux"</string> <string name="pref_slideshow_category">"Paramètres du diaporama"</string> <string name="pref_camera_general_settings_category">"Paramètres généraux"</string> <string name="pref_gallery_size_title">"Taille d\'affichage"</string> <string name="pref_gallery_size_summary">"Sélectionner la taille d\'affichage des images et des vidéos"</string> <string name="pref_gallery_size_dialogtitle">"Taille de l\'image"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Petite"</item> </string-array> <string name="pref_gallery_sort_title">"Ordre de tri"</string> <string name="pref_gallery_sort_summary">"Sélectionner l\'ordre de tri des images et des vidéos"</string> <string name="pref_gallery_sort_dialogtitle">"Trier les images"</string> <string-array name="pref_gallery_sort_choices"> <item>"La plus récente en premier"</item> <item>"La plus récente en dernier"</item> </string-array> - <string name="pref_gallery_slideshow_interval_title">"Intervalle du diaporama"</string> + <string name="pref_gallery_slideshow_interval_title">"Intervalle entre photos"</string> <string name="pref_gallery_slideshow_interval_summary">"Sélectionner la durée d\'affichage de chaque diapositive dans le diaporama"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalle du diaporama"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 secondes"</item> <item>"3 secondes"</item> <item>"4 secondes"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transition du diaporama"</string> <string name="pref_gallery_slideshow_transition_summary">"Sélectionner l\'effet utilisé lors de la transition d\'une diapositive à une autre"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transition du diaporama"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ouverture et fermeture en fondu"</item> <item>"Glisser de gauche à droite"</item> <item>"Glisser de haut en bas"</item> <item>"Sélection aléatoire"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Rejouer le diaporama"</string> <string name="pref_gallery_slideshow_repeat_summary">"Rejouer le diaporama plusieurs fois"</string> <string name="pref_gallery_slideshow_shuffle_title">"Lecture aléatoire"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Afficher les images"</string> <string name="pref_camera_recordlocation_title">"Enregistrer le lieu"</string> <string name="pref_camera_recordlocation_summary">"Enregistrer la position géographique dans les données d\'image"</string> <string name="pref_camera_videoquality_category">"Paramètres vidéo"</string> <string name="pref_camera_videoquality_title">"Qualité vidéo"</string> - <string name="pref_camera_videoquality_entry_0">"Basse (pour les MMS)"</string> - <string name="pref_camera_videoquality_entry_1">"Haute (pour la carte SD)"</string> + <string name="pref_camera_videoquality_entry_0">"Basse (MMS)"</string> + <string name="pref_camera_videoquality_entry_1">"Haute (carte SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Qualité vidéo"</string> <string name="camerasettings">"Paramètres"</string> <string name="image_gallery_NoImageView_text">"Aucun fichier trouvé."</string> <string name="pref_gallery_confirm_delete_title">"Confirmer suppressions"</string> <string name="pref_gallery_confirm_delete_summary">"Afficher une confirmation avant de supprimer une image ou une vidéo"</string> <string name="details_panel_title">"Détails"</string> <string name="details_file_size">"Taille du fichier :"</string> <string name="details_image_resolution">"Résolution :"</string> <string name="details_duration">"Durée :"</string> <string name="details_date_taken">"Date de création :"</string> <string name="details_frame_rate">"Fréquence d\'images :"</string> <string name="details_bit_rate">"Débit :"</string> <string name="details_codec">"Codec :"</string> <string name="details_format">"Format :"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d ips"</string> <string name="details_kbps">"%1$d Kbits/s"</string> <string name="details_mbps">"%1$g Mbits/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Options de l\'image"</string> <string name="video_context_menu_header">"Options vidéo"</string> - <string name="multiface_crop_help">"Cliquez sur un visage pour commencer."</string> + <string name="multiface_crop_help">"Appuyez sur un visage pour commencer."</string> <string name="photos_gallery_title">"Galerie"</string> <string name="pick_photos_gallery_title">"Sélectionnez une image"</string> <string name="videos_gallery_title">"Galerie"</string> <string name="pick_videos_gallery_title">"Sélectionnez une vidéo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> vignettes restantes"</string> <string name="sendImage">"Partager l\'image via"</string> <string name="setImage">"Définir l\'image comme"</string> <string name="sendVideo">"Partager la vidéo via"</string> <string name="movieviewlabel">"Films"</string> <string name="loading_video">"Chargement de la vidéo..."</string> <string name="spaceIsLow_title">"L\'espace restant est faible"</string> <string name="spaceIsLow_content">"Votre carte SD est pleine. Modifiez le paramètre de qualité ou supprimez des éléments de la galerie."</string> <string name="resume_playing_title">"Reprendre la vidéo"</string> <string name="resume_playing_message">"Reprendre la lecture à partir de %s ?"</string> <string name="resume_playing_resume">"Reprendre la lecture"</string> <string name="resume_playing_restart">"Démarrer"</string> <string name="gadget_title">"Cadre d\'image"</string> <string name="file_info_title">"Informations sur le fichier :"</string> <string name="video_exceed_mms_limit">"La vidéo que vous avez enregistrée est trop volumineuse et ne peut être envoyée par MMS. Enregistrez une vidéo plus courte."</string> <string name="too_large_to_attach">"Impossible de joindre le fichier, car il est trop volumineux."</string> </resources> diff --git a/res/values-nl/strings.xml b/res/values-nl/strings.xml index 1362592..d6bb6b3 100644 --- a/res/values-nl/strings.xml +++ b/res/values-nl/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Alle foto\'s"</string> <string name="all_videos">"Alle video\'s"</string> <string name="camera_label">"Camera"</string> <string name="video_camera_label">"Camcorder"</string> <string name="gallery_picker_label">"Galerij"</string> <string name="gallery_camera_bucket_name">"Camerafoto\'s"</string> <string name="gallery_camera_videos_bucket_name">"Cameravideo\'s"</string> <string name="switch_to_video_lable">"Overschakelen naar video"</string> <string name="switch_to_camera_lable">"Overschakelen naar camera"</string> <string name="crop_label">"Foto bijsnijden"</string> <string name="view_label">"Foto weergeven"</string> <string name="preferences_label">"Camera-instellingen"</string> <string name="wait">"Een ogenblik geduld..."</string> <string name="no_storage">"Plaats een SD-kaart voordat u de camera gebruikt."</string> <string name="not_enough_space">"De SD-kaart is vol."</string> <string name="preparing_sd">"SD-kaart voorbereiden…"</string> <string name="wallpaper">"Achtergrond wordt ingesteld. Een ogenblik geduld..."</string> <string name="savingImage">"Foto opslaan..."</string> <string name="runningFaceDetection">"Een ogenblik geduld..."</string> <string name="flip_orientation">"Stand draaien"</string> <string name="settings">"Instellingen"</string> <string name="view">"Weergeven"</string> <string name="details">"Details"</string> <string name="rotate">"Draaien"</string> <string name="rotate_left">"Linksom draaien"</string> <string name="rotate_right">"Rechtsom draaien"</string> <string name="slide_show">"Diavoorstelling"</string> <string name="capture_picture">"Foto nemen"</string> <string name="capture_video">"Video opnemen"</string> <string name="crop_save_text">"Opslaan"</string> <string name="crop_discard_text">"Ongedaan maken"</string> <string name="confirm_delete_title">"Verwijderen"</string> <string name="confirm_delete_message">"De foto wordt verwijderd."</string> - <string name="confirm_delete_video_message">"De video wordt verwijderd"</string> + <string name="confirm_delete_video_message">"De video wordt verwijderd."</string> <string name="camera_toss">"Verwijderen"</string> <string name="camera_gallery">"Galerij"</string> <string name="camera_share">"Delen"</string> <string name="camera_set">"Instellen als"</string> <string name="camera_play">"Afspelen"</string> <string name="camera_attach">"Bijvoegen"</string> <string name="camera_cancel">"Annuleren"</string> <string name="camera_crop">"Bijsnijden"</string> <string name="camera_tossing">"Verwijderen..."</string> <string name="no_way_to_share_image">"Deze foto kan niet worden gedeeld."</string> <string name="no_way_to_share_video">"Deze video kan niet worden gedeeld."</string> <string name="video_play">"Afspelen"</string> <string name="camera_gallery_photos_text">"Galerij"</string> <string name="camera_pick_wallpaper">"Foto\'s"</string> <string name="camera_setas_wallpaper">"Achtergrond"</string> <string name="pref_gallery_category">"Algemene instellingen"</string> <string name="pref_slideshow_category">"Instellingen van diavoorstelling"</string> <string name="pref_camera_general_settings_category">"Algemene instellingen"</string> <string name="pref_gallery_size_title">"Weergavegrootte"</string> <string name="pref_gallery_size_summary">"De weergavegrootte van foto\'s en video\'s selecteren"</string> <string name="pref_gallery_size_dialogtitle">"Grootte van foto"</string> <string-array name="pref_gallery_size_choices"> <item>"Groot"</item> <item>"Klein"</item> </string-array> <string name="pref_gallery_sort_title">"Sorteervolgorde"</string> <string name="pref_gallery_sort_summary">"De sorteervolgorde van foto\'s en video\'s selecteren"</string> <string name="pref_gallery_sort_dialogtitle">"Foto\'s sorteren"</string> <string-array name="pref_gallery_sort_choices"> <item>"Nieuwste eerst"</item> <item>"Nieuwste laatst"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Interval in diavoorstelling"</string> <string name="pref_gallery_slideshow_interval_summary">"Selecteren hoe lang elke dia wordt weergegeven in de voorstelling"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Interval in diavoorstelling"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 seconden"</item> <item>"3 seconden"</item> <item>"4 seconden"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Overgangen in diavoorstellingen"</string> <string name="pref_gallery_slideshow_transition_summary">"Het effect selecteren dat wordt gebruikt om naar de volgende dia te gaan"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Overgangen in diavoorstellingen"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Infaden/uitfaden"</item> <item>"Dia vanaf linkerkant/rechterkant"</item> <item>"Dia vanaf bovenkant/onderkant"</item> <item>"Willekeurige selectie"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Diavoorstelling herhalen"</string> <string name="pref_gallery_slideshow_repeat_summary">"Diavoorstelling meerdere keren afspelen"</string> <string name="pref_gallery_slideshow_shuffle_title">"Dia\'s in willekeurige volgorde weergeven"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Foto\'s in willekeurige volgorde weergeven"</string> <string name="pref_camera_recordlocation_title">"Locatie opslaan in foto\'s"</string> <string name="pref_camera_recordlocation_summary">"Locatie vastleggen in de gegevens van de foto"</string> <string name="pref_camera_videoquality_category">"Videokwaliteit"</string> <string name="pref_camera_videoquality_title">"Videokwaliteit selecteren"</string> <string name="pref_camera_videoquality_entry_0">"Laag (voor MMS-berichten)"</string> <string name="pref_camera_videoquality_entry_1">"Hoog (voor SD-kaart)"</string> <string name="pref_camera_videoquality_dialogtitle">"Videokwaliteit"</string> <string name="camerasettings">"Instellingen"</string> <string name="image_gallery_NoImageView_text">"Geen medium gevonden."</string> <string name="pref_gallery_confirm_delete_title">"Verwijderen bevestigen"</string> <string name="pref_gallery_confirm_delete_summary">"Bevestiging weergeven voordat een foto of video wordt verwijderd"</string> <string name="details_panel_title">"Details"</string> <string name="details_file_size">"Bestandsgrootte:"</string> <string name="details_image_resolution">"Resolutie:"</string> <string name="details_duration">"Duur:"</string> <string name="details_date_taken">"Gemaakt op:"</string> <string name="details_frame_rate">"Framesnelheid:"</string> <string name="details_bit_rate">"Bitsnelheid:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Indeling:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opties voor foto\'s"</string> <string name="video_context_menu_header">"Video-opties"</string> <string name="multiface_crop_help">"Tik op een gezicht om te beginnen."</string> <string name="photos_gallery_title">"Galerij"</string> <string name="pick_photos_gallery_title">"Foto selecteren"</string> <string name="videos_gallery_title">"Galerij"</string> <string name="pick_videos_gallery_title">"Video selecteren"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> resterend"</string> <string name="sendImage">"Foto delen via"</string> <string name="setImage">"Foto instellen als"</string> <string name="sendVideo">"Video delen via"</string> <string name="movieviewlabel">"Films"</string> <string name="loading_video">"Video laden..."</string> <string name="spaceIsLow_title">"Er is weinig ruimte"</string> <string name="spaceIsLow_content">"Er is weinig ruimte beschikbaar op uw SD-kaart. U kunt de kwaliteitsinstelling wijzigen of items uit de galerij verwijderen."</string> <string name="resume_playing_title">"Video hervatten"</string> <string name="resume_playing_message">"Afspelen hervatten vanaf %s ?"</string> <string name="resume_playing_resume">"Afspelen hervatten"</string> <string name="resume_playing_restart">"Opnieuw starten"</string> <string name="gadget_title">"Fotolijstje"</string> <string name="file_info_title">"Bestandsinformatie:"</string> <string name="video_exceed_mms_limit">"De video die u heeft opgenomen, is te lang om via MMS te verzenden. Neem een kortere video op."</string> <string name="too_large_to_attach">"Bestand is te groot om bij te voegen."</string> </resources>
brunsky/WS171-packages-apps-Camera
19713a8471b667a4d5bc20d3c38d13cc34896ec2
AI 145782: Import updated translations. DO NOT MERGE
diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml index 949462b..1440582 100644 --- a/res/values-ja/strings.xml +++ b/res/values-ja/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"すべての写真"</string> <string name="all_videos">"すべての動画"</string> <string name="camera_label">"カメラ"</string> <string name="video_camera_label">"ビデオ録画"</string> <string name="gallery_picker_label">"ギャラリー"</string> <string name="gallery_camera_bucket_name">"カメラ (写真)"</string> <string name="gallery_camera_videos_bucket_name">"カメラ (動画)"</string> <string name="switch_to_video_lable">"ムービーに切替"</string> <string name="switch_to_camera_lable">"写真に切替"</string> <string name="crop_label">"トリミング"</string> <string name="view_label">"画像を表示"</string> <string name="preferences_label">"カメラ設定"</string> <string name="wait">"お待ちください..."</string> <string name="no_storage">"カメラを使用する前にSDカードを挿入してください。"</string> <string name="not_enough_space">"SDカードがいっぱいです。"</string> <string name="preparing_sd">"SDカードの準備中..."</string> <string name="wallpaper">"壁紙を設定しています。しばらくお待ちください..."</string> <string name="savingImage">"写真を保存中..."</string> <string name="runningFaceDetection">"お待ちください..."</string> <string name="flip_orientation">"画面の向きを変更"</string> <string name="settings">"設定"</string> <string name="view">"表示"</string> - <string name="details">"詳細"</string> + <string name="details">"詳細情報"</string> <string name="rotate">"回転"</string> <string name="rotate_left">"左に回転"</string> <string name="rotate_right">"右に回転"</string> <string name="slide_show">"スライドショー"</string> <string name="capture_picture">"写真撮影"</string> <string name="capture_video">"ムービー撮影"</string> <string name="crop_save_text">"保存"</string> <string name="crop_discard_text">"キャンセル"</string> <string name="confirm_delete_title">"削除"</string> <string name="confirm_delete_message">"画像を削除します。"</string> <string name="confirm_delete_video_message">"動画を削除します。"</string> <string name="camera_toss">"削除"</string> <string name="camera_gallery">"ギャラリー"</string> <string name="camera_share">"共有"</string> - <string name="camera_set">"連絡先等に設定する"</string> + <string name="camera_set">"この画像を登録する"</string> <string name="camera_play">"再生"</string> <string name="camera_attach">"添付"</string> <string name="camera_cancel">"キャンセル"</string> <string name="camera_crop">"トリミング"</string> <string name="camera_tossing">"削除中..."</string> <string name="no_way_to_share_image">"この画像は共有できません。"</string> <string name="no_way_to_share_video">"この動画は共有できません。"</string> <string name="video_play">"再生"</string> <string name="camera_gallery_photos_text">"ギャラリー"</string> <string name="camera_pick_wallpaper">"画像"</string> <string name="camera_setas_wallpaper">"壁紙"</string> <string name="pref_gallery_category">"全般設定"</string> <string name="pref_slideshow_category">"スライドショー設定"</string> <string name="pref_camera_general_settings_category">"全般設定"</string> <string name="pref_gallery_size_title">"表示サイズ"</string> <string name="pref_gallery_size_summary">"画像や動画の表示サイズ"</string> <string name="pref_gallery_size_dialogtitle">"画像サイズ"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"表示順序"</string> <string name="pref_gallery_sort_summary">"画像や動画の表示順序を選択"</string> <string name="pref_gallery_sort_dialogtitle">"画像並べ替え"</string> <string-array name="pref_gallery_sort_choices"> <item>"日付の新しい順"</item> <item>"日付の古い順"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"スライドの再生間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"各スライドの表示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"スライドの再生間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2秒"</item> <item>"3秒"</item> <item>"4秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"スライド切り替え"</string> <string name="pref_gallery_slideshow_transition_summary">"スライドが切り替わるときの効果"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"スライド切り替え"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"フェードイン&amp;アウト"</item> <item>"左右にスライド"</item> <item>"上下にスライド"</item> <item>"ランダムに選択"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"リピート再生"</string> <string name="pref_gallery_slideshow_repeat_summary">"スライドショーを繰り返し再生"</string> <string name="pref_gallery_slideshow_shuffle_title">"スライドのシャッフル"</string> <string name="pref_gallery_slideshow_shuffle_summary">"順不同に表示する"</string> <string name="pref_camera_recordlocation_title">"位置情報を写真に記録する"</string> <string name="pref_camera_recordlocation_summary">"位置情報を写真データに記録する"</string> <string name="pref_camera_videoquality_category">"動画のクオリティ"</string> <string name="pref_camera_videoquality_title">"動画の画質を選択"</string> <string name="pref_camera_videoquality_entry_0">"低 (MMSメッセージ向け)"</string> <string name="pref_camera_videoquality_entry_1">"高 (SDカード向け)"</string> <string name="pref_camera_videoquality_dialogtitle">"動画のクオリティ"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"メディアが見つかりません。"</string> <string name="pref_gallery_confirm_delete_title">"削除確認"</string> <string name="pref_gallery_confirm_delete_summary">"画像や動画を削除する前に確認する"</string> - <string name="details_panel_title">"詳細"</string> + <string name="details_panel_title">"詳細情報"</string> <string name="details_file_size">"ファイルサイズ:"</string> <string name="details_image_resolution">"解像度:"</string> <string name="details_duration">"再生時間:"</string> <string name="details_date_taken">"撮影日:"</string> <string name="details_frame_rate">"フレームレート:"</string> <string name="details_bit_rate">"ビットレート:"</string> <string name="details_codec">"コーデック:"</string> <string name="details_format">"形式:"</string> <string name="details_dimension_x">"%1$dx%2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$dfps"</string> <string name="details_kbps">"%1$dKbps"</string> <string name="details_mbps">"%1$gMbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"画像オプション"</string> <string name="video_context_menu_header">"動画オプション"</string> <string name="multiface_crop_help">"顔をタップして開始します。"</string> <string name="photos_gallery_title">"ギャラリー"</string> <string name="pick_photos_gallery_title">"画像を選択"</string> <string name="videos_gallery_title">"ギャラリー"</string> <string name="pick_videos_gallery_title">"動画を選択"</string> <string name="loading_progress_format_string">"残り<xliff:g id="COUNTER">%d</xliff:g>件"</string> <string name="sendImage">"画像を共有:"</string> - <string name="setImage">"設定タイプ:"</string> + <string name="setImage">"この画像を登録する"</string> <string name="sendVideo">"動画を共有"</string> <string name="movieviewlabel">"映画"</string> <string name="loading_video">"動画を読み込み中..."</string> <string name="spaceIsLow_title">"空き容量が残り少なくなっています"</string> <string name="spaceIsLow_content">"SDカードの容量が足りません。クオリティ設定を変更するか、ギャラリーからアイテムを削除してください。"</string> <string name="resume_playing_title">"動画の再開"</string> <string name="resume_playing_message">"再生を%sから再開しますか?"</string> <string name="resume_playing_resume">"再生を再開"</string> <string name="resume_playing_restart">"最初から再生"</string> <string name="gadget_title">"写真フレーム"</string> <string name="file_info_title">"ファイル情報:"</string> <string name="video_exceed_mms_limit">"録画した動画のサイズが大きすぎるため送信できません。録画時間を短縮してみてください。"</string> <string name="too_large_to_attach">"添付ファイルが大きすぎます。"</string> </resources>
brunsky/WS171-packages-apps-Camera
375f459549704d9002fa1cd35796c6ddcb9fc6c4
AI 145225: Import more revised translations into cupcake.
diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml index 2ccdf61..a631efa 100644 --- a/res/values-es/strings.xml +++ b/res/values-es/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Todas las imágenes"</string> <string name="all_videos">"Todos los vídeos"</string> <string name="camera_label">"Cámara"</string> <string name="video_camera_label">"Videocámara"</string> <string name="gallery_picker_label">"Galería"</string> <string name="gallery_camera_bucket_name">"Imágenes de cámara"</string> <string name="gallery_camera_videos_bucket_name">"Vídeos de cámara"</string> <string name="switch_to_video_lable">"Cambiar a vídeo"</string> <string name="switch_to_camera_lable">"Cambiar a cámara"</string> <string name="crop_label">"Recortar imagen"</string> <string name="view_label">"Ver imagen"</string> <string name="preferences_label">"Configuración de cámara"</string> <string name="wait">"Por favor, espera..."</string> <string name="no_storage">"Antes de utilizar la cámara, debes insertar una tarjeta SD."</string> <string name="not_enough_space">"La tarjeta SD está llena."</string> <string name="preparing_sd">"Preparando tarjeta SD…"</string> <string name="wallpaper">"Estableciendo fondo de pantalla..."</string> <string name="savingImage">"Guardando imagen..."</string> <string name="runningFaceDetection">"Por favor, espera..."</string> <string name="flip_orientation">"Cambiar orientación"</string> <string name="settings">"Ajustes"</string> <string name="view">"Ver"</string> <string name="details">"Detalles"</string> <string name="rotate">"Girar"</string> <string name="rotate_left">"Girar a la izquierda"</string> <string name="rotate_right">"Girar a la derecha"</string> <string name="slide_show">"Presentación"</string> <string name="capture_picture">"Capturar imagen"</string> <string name="capture_video">"Capturar vídeo"</string> <string name="crop_save_text">"Guardar"</string> <string name="crop_discard_text">"Descartar"</string> <string name="confirm_delete_title">"Suprimir"</string> <string name="confirm_delete_message">"Se eliminará la imagen."</string> <string name="confirm_delete_video_message">"Se eliminará el vídeo."</string> <string name="camera_toss">"Suprimir"</string> <string name="camera_gallery">"Galería"</string> <string name="camera_share">"Compartir"</string> <string name="camera_set">"Establecer como"</string> <string name="camera_play">"Reproducir"</string> <string name="camera_attach">"Adjuntar"</string> <string name="camera_cancel">"Cancelar"</string> <string name="camera_crop">"Recortar"</string> <string name="camera_tossing">"Eliminando..."</string> <string name="no_way_to_share_image">"Esta imagen no se puede compartir."</string> <string name="no_way_to_share_video">"Este vídeo no se puede compartir."</string> <string name="video_play">"Reproducir"</string> <string name="camera_gallery_photos_text">"Galería"</string> <string name="camera_pick_wallpaper">"Imágenes"</string> <string name="camera_setas_wallpaper">"Fondo de pantalla"</string> <string name="pref_gallery_category">"Configuración general"</string> <string name="pref_slideshow_category">"Configuración de presentación"</string> <string name="pref_camera_general_settings_category">"Configuración general"</string> <string name="pref_gallery_size_title">"Tamaño de visualización"</string> <string name="pref_gallery_size_summary">"Seleccionar el tamaño de visualización de imágenes y vídeos"</string> <string name="pref_gallery_size_dialogtitle">"Tamaño de imagen"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Pequeña"</item> </string-array> <string name="pref_gallery_sort_title">"Orden"</string> <string name="pref_gallery_sort_summary">"Seleccionar el orden de imágenes y vídeos"</string> <string name="pref_gallery_sort_dialogtitle">"Ordenación de imágenes"</string> <string-array name="pref_gallery_sort_choices"> <item>"Más recientes primero"</item> <item>"Más recientes al final"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalo de presentación"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleccionar la duración de cada diapositiva"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo de presentación"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 segundos"</item> <item>"3 segundos"</item> <item>"4 segundos"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transición de diapositivas"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleccionar el efecto que se aplicará al pasar de una diapositiva a otra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transición de diapositivas"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Fundido de entrada y salida"</item> <item>"Transición de izquierda a derecha"</item> <item>"Transición de arriba a abajo"</item> <item>"Selección aleatoria"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Repetir presentación"</string> <string name="pref_gallery_slideshow_repeat_summary">"Mostrar presentación más de una vez"</string> - <string name="pref_gallery_slideshow_shuffle_title">"Reproducir en orden aleatorio"</string> + <string name="pref_gallery_slideshow_shuffle_title">"Reproducir aleatoriamente"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imágenes en orden aleatorio"</string> <string name="pref_camera_recordlocation_title">"Almacenar ubicación en imágenes"</string> <string name="pref_camera_recordlocation_summary">"Registrar ubicación en datos de imagen"</string> <string name="pref_camera_videoquality_category">"Calidad de vídeo"</string> <string name="pref_camera_videoquality_title">"Seleccionar calidad de vídeo"</string> <string name="pref_camera_videoquality_entry_0">"Baja (para mensajes MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (para tarjeta SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Calidad de vídeo"</string> <string name="camerasettings">"Ajustes"</string> <string name="image_gallery_NoImageView_text">"No se ha encontrado ningún elemento."</string> <string name="pref_gallery_confirm_delete_title">"Confirmar eliminaciones"</string> <string name="pref_gallery_confirm_delete_summary">"Mostrar confirmación antes de eliminar una imagen o un vídeo"</string> <string name="details_panel_title">"Detalles"</string> <string name="details_file_size">"Tamaño de archivo:"</string> <string name="details_image_resolution">"Resolución:"</string> <string name="details_duration">"Duración:"</string> <string name="details_date_taken">"Fecha de realización:"</string> <string name="details_frame_rate">"Frecuencia de imagen:"</string> <string name="details_bit_rate">"Velocidad binaria:"</string> <string name="details_codec">"Códec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"Aceptar"</string> <string name="context_menu_header">"Opciones de imagen"</string> <string name="video_context_menu_header">"Opciones de vídeo"</string> <string name="multiface_crop_help">"Toca una cara para empezar."</string> <string name="photos_gallery_title">"Galería"</string> <string name="pick_photos_gallery_title">"Seleccionar imagen"</string> <string name="videos_gallery_title">"Galería"</string> <string name="pick_videos_gallery_title">"Seleccionar vídeo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> <string name="sendImage">"Compartir imagen por"</string> <string name="setImage">"Establecer imagen como"</string> <string name="sendVideo">"Compartir vídeo a través de"</string> <string name="movieviewlabel">"Películas"</string> <string name="loading_video">"Cargando vídeo…"</string> <string name="spaceIsLow_title">"Poco espacio"</string> <string name="spaceIsLow_content">"No queda espacio en la tarjeta SD. Cambia la configuración de calidad o elimina elementos de la galería."</string> <string name="resume_playing_title">"Reanudar vídeo"</string> <string name="resume_playing_message">"Reanudar reproducción a partir de %s ?"</string> <string name="resume_playing_resume">"Reanudar reproducción"</string> <string name="resume_playing_restart">"Volver a reproducir"</string> <string name="gadget_title">"Picture frame"</string> <string name="file_info_title">"Información de archivo:"</string> <string name="video_exceed_mms_limit">"El vídeo que has grabado es demasiado grande para enviarlo a través de MMS. Intenta grabar un vídeo de menor duración."</string> <string name="too_large_to_attach">"El archivo es demasiado grande para adjuntarlo."</string> </resources>
brunsky/WS171-packages-apps-Camera
bb7a581c312a1880f4c69a13b39ec718dfe9d627
AI 144977: Import revised translations. DO NOT MERGE
diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml index ccb461a..2ccdf61 100644 --- a/res/values-es/strings.xml +++ b/res/values-es/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Todas las imágenes"</string> <string name="all_videos">"Todos los vídeos"</string> <string name="camera_label">"Cámara"</string> <string name="video_camera_label">"Videocámara"</string> <string name="gallery_picker_label">"Galería"</string> <string name="gallery_camera_bucket_name">"Imágenes de cámara"</string> <string name="gallery_camera_videos_bucket_name">"Vídeos de cámara"</string> <string name="switch_to_video_lable">"Cambiar a vídeo"</string> <string name="switch_to_camera_lable">"Cambiar a cámara"</string> <string name="crop_label">"Recortar imagen"</string> <string name="view_label">"Ver imagen"</string> <string name="preferences_label">"Configuración de cámara"</string> <string name="wait">"Por favor, espera..."</string> <string name="no_storage">"Antes de utilizar la cámara, debes insertar una tarjeta SD."</string> <string name="not_enough_space">"La tarjeta SD está llena."</string> <string name="preparing_sd">"Preparando tarjeta SD…"</string> <string name="wallpaper">"Estableciendo fondo de pantalla..."</string> <string name="savingImage">"Guardando imagen..."</string> <string name="runningFaceDetection">"Por favor, espera..."</string> <string name="flip_orientation">"Cambiar orientación"</string> <string name="settings">"Ajustes"</string> <string name="view">"Ver"</string> <string name="details">"Detalles"</string> <string name="rotate">"Girar"</string> <string name="rotate_left">"Girar a la izquierda"</string> <string name="rotate_right">"Girar a la derecha"</string> <string name="slide_show">"Presentación"</string> <string name="capture_picture">"Capturar imagen"</string> <string name="capture_video">"Capturar vídeo"</string> <string name="crop_save_text">"Guardar"</string> <string name="crop_discard_text">"Descartar"</string> <string name="confirm_delete_title">"Suprimir"</string> <string name="confirm_delete_message">"Se eliminará la imagen."</string> <string name="confirm_delete_video_message">"Se eliminará el vídeo."</string> <string name="camera_toss">"Suprimir"</string> <string name="camera_gallery">"Galería"</string> <string name="camera_share">"Compartir"</string> <string name="camera_set">"Establecer como"</string> <string name="camera_play">"Reproducir"</string> <string name="camera_attach">"Adjuntar"</string> <string name="camera_cancel">"Cancelar"</string> <string name="camera_crop">"Recortar"</string> <string name="camera_tossing">"Eliminando..."</string> <string name="no_way_to_share_image">"Esta imagen no se puede compartir."</string> <string name="no_way_to_share_video">"Este vídeo no se puede compartir."</string> <string name="video_play">"Reproducir"</string> <string name="camera_gallery_photos_text">"Galería"</string> <string name="camera_pick_wallpaper">"Imágenes"</string> <string name="camera_setas_wallpaper">"Fondo de pantalla"</string> <string name="pref_gallery_category">"Configuración general"</string> <string name="pref_slideshow_category">"Configuración de presentación"</string> <string name="pref_camera_general_settings_category">"Configuración general"</string> <string name="pref_gallery_size_title">"Tamaño de visualización"</string> <string name="pref_gallery_size_summary">"Seleccionar el tamaño de visualización de imágenes y vídeos"</string> <string name="pref_gallery_size_dialogtitle">"Tamaño de imagen"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Pequeña"</item> </string-array> <string name="pref_gallery_sort_title">"Orden"</string> <string name="pref_gallery_sort_summary">"Seleccionar el orden de imágenes y vídeos"</string> <string name="pref_gallery_sort_dialogtitle">"Ordenación de imágenes"</string> <string-array name="pref_gallery_sort_choices"> <item>"Más recientes primero"</item> <item>"Más recientes al final"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalo de presentación"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleccionar la duración de cada diapositiva"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo de presentación"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 segundos"</item> <item>"3 segundos"</item> <item>"4 segundos"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transición de diapositivas"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleccionar el efecto que se aplicará al pasar de una diapositiva a otra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transición de diapositivas"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Fundido de entrada y salida"</item> <item>"Transición de izquierda a derecha"</item> <item>"Transición de arriba a abajo"</item> <item>"Selección aleatoria"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Repetir presentación"</string> <string name="pref_gallery_slideshow_repeat_summary">"Mostrar presentación más de una vez"</string> - <string name="pref_gallery_slideshow_shuffle_title">"Reproducir diapositivas en orden aleatorio"</string> + <string name="pref_gallery_slideshow_shuffle_title">"Reproducir en orden aleatorio"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imágenes en orden aleatorio"</string> <string name="pref_camera_recordlocation_title">"Almacenar ubicación en imágenes"</string> <string name="pref_camera_recordlocation_summary">"Registrar ubicación en datos de imagen"</string> <string name="pref_camera_videoquality_category">"Calidad de vídeo"</string> <string name="pref_camera_videoquality_title">"Seleccionar calidad de vídeo"</string> <string name="pref_camera_videoquality_entry_0">"Baja (para mensajes MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (para tarjeta SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Calidad de vídeo"</string> <string name="camerasettings">"Ajustes"</string> <string name="image_gallery_NoImageView_text">"No se ha encontrado ningún elemento."</string> <string name="pref_gallery_confirm_delete_title">"Confirmar eliminaciones"</string> <string name="pref_gallery_confirm_delete_summary">"Mostrar confirmación antes de eliminar una imagen o un vídeo"</string> <string name="details_panel_title">"Detalles"</string> <string name="details_file_size">"Tamaño de archivo:"</string> <string name="details_image_resolution">"Resolución:"</string> <string name="details_duration">"Duración:"</string> <string name="details_date_taken">"Fecha de realización:"</string> <string name="details_frame_rate">"Frecuencia de imagen:"</string> <string name="details_bit_rate">"Velocidad binaria:"</string> <string name="details_codec">"Códec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"Aceptar"</string> <string name="context_menu_header">"Opciones de imagen"</string> <string name="video_context_menu_header">"Opciones de vídeo"</string> - <string name="multiface_crop_help">"Selecciona una cara para empezar."</string> + <string name="multiface_crop_help">"Toca una cara para empezar."</string> <string name="photos_gallery_title">"Galería"</string> <string name="pick_photos_gallery_title">"Seleccionar imagen"</string> <string name="videos_gallery_title">"Galería"</string> <string name="pick_videos_gallery_title">"Seleccionar vídeo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> <string name="sendImage">"Compartir imagen por"</string> <string name="setImage">"Establecer imagen como"</string> <string name="sendVideo">"Compartir vídeo a través de"</string> <string name="movieviewlabel">"Películas"</string> <string name="loading_video">"Cargando vídeo…"</string> <string name="spaceIsLow_title">"Poco espacio"</string> <string name="spaceIsLow_content">"No queda espacio en la tarjeta SD. Cambia la configuración de calidad o elimina elementos de la galería."</string> <string name="resume_playing_title">"Reanudar vídeo"</string> <string name="resume_playing_message">"Reanudar reproducción a partir de %s ?"</string> <string name="resume_playing_resume">"Reanudar reproducción"</string> <string name="resume_playing_restart">"Volver a reproducir"</string> <string name="gadget_title">"Picture frame"</string> <string name="file_info_title">"Información de archivo:"</string> <string name="video_exceed_mms_limit">"El vídeo que has grabado es demasiado grande para enviarlo a través de MMS. Intenta grabar un vídeo de menor duración."</string> <string name="too_large_to_attach">"El archivo es demasiado grande para adjuntarlo."</string> </resources> diff --git a/res/values-fr/strings.xml b/res/values-fr/strings.xml index c235b3d..e0285e4 100644 --- a/res/values-fr/strings.xml +++ b/res/values-fr/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Toutes les images"</string> <string name="all_videos">"Toutes les vidéos"</string> <string name="camera_label">"Appareil photo"</string> <string name="video_camera_label">"Caméra"</string> <string name="gallery_picker_label">"Galerie"</string> <string name="gallery_camera_bucket_name">"Photos de l\'appareil"</string> <string name="gallery_camera_videos_bucket_name">"Vidéos de la caméra"</string> <string name="switch_to_video_lable">"Passer en mode vidéo"</string> <string name="switch_to_camera_lable">"Passer en mode appareil photo"</string> <string name="crop_label">"Rogner l\'image"</string> <string name="view_label">"Afficher l\'image"</string> <string name="preferences_label">"Paramètres de l\'appareil photo"</string> <string name="wait">"Veuillez patienter..."</string> <string name="no_storage">"Veuillez insérer une carte SD avant d\'utiliser l\'appareil photo."</string> <string name="not_enough_space">"Votre carte SD est pleine."</string> <string name="preparing_sd">"Préparation de la carte SD..."</string> <string name="wallpaper">"Configuration de l\'arrière-plan en cours. Veuillez patienter..."</string> <string name="savingImage">"Enregistrement de l\'image"</string> <string name="runningFaceDetection">"Veuillez patienter..."</string> <string name="flip_orientation">"Orientation"</string> <string name="settings">"Paramètres"</string> <string name="view">"Afficher"</string> <string name="details">"Détails"</string> <string name="rotate">"Faire pivoter"</string> <string name="rotate_left">"Faire pivoter à gauche"</string> <string name="rotate_right">"Faire pivoter à droite"</string> <string name="slide_show">"Diaporama"</string> <string name="capture_picture">"Prendre une photo"</string> <string name="capture_video">"Prendre une vidéo"</string> <string name="crop_save_text">"Enregistrer"</string> <string name="crop_discard_text">"Annuler"</string> <string name="confirm_delete_title">"Supprimer"</string> <string name="confirm_delete_message">"L\'image sera supprimée."</string> <string name="confirm_delete_video_message">"La vidéo va être supprimée."</string> <string name="camera_toss">"Supprimer"</string> <string name="camera_gallery">"Galerie"</string> <string name="camera_share">"Partager"</string> <string name="camera_set">"Définir comme"</string> <string name="camera_play">"Lire"</string> - <string name="camera_attach">"Joindre"</string> + <string name="camera_attach">"Pièce jointe"</string> <string name="camera_cancel">"Annuler"</string> <string name="camera_crop">"Rogner"</string> <string name="camera_tossing">"Suppression..."</string> <string name="no_way_to_share_image">"Impossible de partager cette image."</string> <string name="no_way_to_share_video">"Cette vidéo ne peut pas être partagée."</string> <string name="video_play">"Lire"</string> <string name="camera_gallery_photos_text">"Galerie"</string> <string name="camera_pick_wallpaper">"Images"</string> <string name="camera_setas_wallpaper">"Arrière-plan"</string> <string name="pref_gallery_category">"Paramètres généraux"</string> <string name="pref_slideshow_category">"Paramètres du diaporama"</string> <string name="pref_camera_general_settings_category">"Paramètres généraux"</string> <string name="pref_gallery_size_title">"Taille d\'affichage"</string> <string name="pref_gallery_size_summary">"Sélectionner la taille d\'affichage des images et des vidéos"</string> <string name="pref_gallery_size_dialogtitle">"Taille de l\'image"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Petite"</item> </string-array> <string name="pref_gallery_sort_title">"Ordre de tri"</string> <string name="pref_gallery_sort_summary">"Sélectionner l\'ordre de tri des images et des vidéos"</string> <string name="pref_gallery_sort_dialogtitle">"Trier les images"</string> <string-array name="pref_gallery_sort_choices"> <item>"La plus récente en premier"</item> <item>"La plus récente en dernier"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalle du diaporama"</string> <string name="pref_gallery_slideshow_interval_summary">"Sélectionner la durée d\'affichage de chaque diapositive dans le diaporama"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalle du diaporama"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 secondes"</item> <item>"3 secondes"</item> <item>"4 secondes"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transition du diaporama"</string> <string name="pref_gallery_slideshow_transition_summary">"Sélectionner l\'effet utilisé lors de la transition d\'une diapositive à une autre"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transition du diaporama"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ouverture et fermeture en fondu"</item> <item>"Glisser de gauche à droite"</item> <item>"Glisser de haut en bas"</item> <item>"Sélection aléatoire"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Rejouer le diaporama"</string> <string name="pref_gallery_slideshow_repeat_summary">"Rejouer le diaporama plusieurs fois"</string> <string name="pref_gallery_slideshow_shuffle_title">"Lecture aléatoire"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Afficher les images"</string> <string name="pref_camera_recordlocation_title">"Enregistrer le lieu"</string> <string name="pref_camera_recordlocation_summary">"Enregistrer la position géographique dans les données d\'image"</string> <string name="pref_camera_videoquality_category">"Paramètres vidéo"</string> <string name="pref_camera_videoquality_title">"Qualité vidéo"</string> <string name="pref_camera_videoquality_entry_0">"Basse (pour les MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Haute (pour la carte SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Qualité vidéo"</string> <string name="camerasettings">"Paramètres"</string> <string name="image_gallery_NoImageView_text">"Aucun fichier trouvé."</string> <string name="pref_gallery_confirm_delete_title">"Confirmer suppressions"</string> <string name="pref_gallery_confirm_delete_summary">"Afficher une confirmation avant de supprimer une image ou une vidéo"</string> <string name="details_panel_title">"Détails"</string> <string name="details_file_size">"Taille du fichier :"</string> <string name="details_image_resolution">"Résolution :"</string> <string name="details_duration">"Durée :"</string> <string name="details_date_taken">"Date de création :"</string> <string name="details_frame_rate">"Fréquence d\'images :"</string> <string name="details_bit_rate">"Débit :"</string> <string name="details_codec">"Codec :"</string> <string name="details_format">"Format :"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d ips"</string> <string name="details_kbps">"%1$d Kbits/s"</string> <string name="details_mbps">"%1$g Mbits/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Options de l\'image"</string> <string name="video_context_menu_header">"Options vidéo"</string> <string name="multiface_crop_help">"Cliquez sur un visage pour commencer."</string> <string name="photos_gallery_title">"Galerie"</string> <string name="pick_photos_gallery_title">"Sélectionnez une image"</string> <string name="videos_gallery_title">"Galerie"</string> <string name="pick_videos_gallery_title">"Sélectionnez une vidéo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> vignettes restantes"</string> <string name="sendImage">"Partager l\'image via"</string> <string name="setImage">"Définir l\'image comme"</string> <string name="sendVideo">"Partager la vidéo via"</string> <string name="movieviewlabel">"Films"</string> <string name="loading_video">"Chargement de la vidéo..."</string> <string name="spaceIsLow_title">"L\'espace restant est faible"</string> <string name="spaceIsLow_content">"Votre carte SD est pleine. Modifiez le paramètre de qualité ou supprimez des éléments de la galerie."</string> <string name="resume_playing_title">"Reprendre la vidéo"</string> <string name="resume_playing_message">"Reprendre la lecture à partir de %s ?"</string> <string name="resume_playing_resume">"Reprendre la lecture"</string> <string name="resume_playing_restart">"Démarrer"</string> <string name="gadget_title">"Cadre d\'image"</string> <string name="file_info_title">"Informations sur le fichier :"</string> <string name="video_exceed_mms_limit">"La vidéo que vous avez enregistrée est trop volumineuse et ne peut être envoyée par MMS. Enregistrez une vidéo plus courte."</string> <string name="too_large_to_attach">"Impossible de joindre le fichier, car il est trop volumineux."</string> </resources> diff --git a/res/values-pl/strings.xml b/res/values-pl/strings.xml index eb14f35..f29d3d2 100644 --- a/res/values-pl/strings.xml +++ b/res/values-pl/strings.xml @@ -1,155 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Wszystkie zdjęcia"</string> <string name="all_videos">"Wszystkie filmy"</string> <string name="camera_label">"Aparat"</string> <string name="video_camera_label">"Kamera"</string> <string name="gallery_picker_label">"Galeria"</string> <string name="gallery_camera_bucket_name">"Zdjęcia z aparatu"</string> <string name="gallery_camera_videos_bucket_name">"Filmy z aparatu"</string> <string name="switch_to_video_lable">"Przełącz na wideo"</string> <string name="switch_to_camera_lable">"Przełącz na aparat"</string> <string name="crop_label">"Przytnij zdjęcie"</string> <string name="view_label">"Wyświetl zdjęcie"</string> <string name="preferences_label">"Ustawienia aparatu"</string> <string name="wait">"Poczekaj…"</string> <string name="no_storage">"Zanim zaczniesz korzystać z aparatu fotograficznego, włóż kartę SD."</string> <string name="not_enough_space">"Karta SD jest pełna."</string> <string name="preparing_sd">"Przygotowywanie karty SD..."</string> <string name="wallpaper">"Ustawianie tapety, poczekaj…"</string> <string name="savingImage">"Trwa zapisywanie zdjęcia…"</string> <string name="runningFaceDetection">"Poczekaj…"</string> <string name="flip_orientation">"Zmień orientację"</string> <string name="settings">"Ustawienia"</string> <string name="view">"Wyświetl"</string> <string name="details">"Szczegóły"</string> <string name="rotate">"Obróć"</string> <string name="rotate_left">"Obróć w lewo"</string> <string name="rotate_right">"Obróć w prawo"</string> <string name="slide_show">"Pokaz slajdów"</string> <string name="capture_picture">"Zrób zdjęcie"</string> <string name="capture_video">"Nagraj film wideo"</string> <string name="crop_save_text">"Zapisz"</string> <string name="crop_discard_text">"Odrzuć"</string> <string name="confirm_delete_title">"Usuń"</string> <string name="confirm_delete_message">"Zdjęcie zostanie usunięte."</string> <string name="confirm_delete_video_message">"Film wideo zostanie usunięty."</string> <string name="camera_toss">"Usuń"</string> <string name="camera_gallery">"Galeria"</string> <string name="camera_share">"Prześlij"</string> <string name="camera_set">"Ustaw jako"</string> <string name="camera_play">"Odtwórz"</string> <string name="camera_attach">"Załącz"</string> <string name="camera_cancel">"Anuluj"</string> <string name="camera_crop">"Przytnij"</string> <string name="camera_tossing">"Trwa usuwanie…"</string> <string name="no_way_to_share_image">"Nie można przesłać tego zdjęcia."</string> <string name="no_way_to_share_video">"Nie można przesłać tego filmu."</string> <string name="video_play">"Odtwórz"</string> <string name="camera_gallery_photos_text">"Galeria"</string> <string name="camera_pick_wallpaper">"Zdjęcia"</string> <string name="camera_setas_wallpaper">"Tapeta"</string> <string name="pref_gallery_category">"Ustawienia ogólne"</string> <string name="pref_slideshow_category">"Ustawienia pokazu slajdów"</string> <string name="pref_camera_general_settings_category">"Ustawienia ogólne"</string> <string name="pref_gallery_size_title">"Rozmiar zdjęć i filmów"</string> <string name="pref_gallery_size_summary">"Ustaw wyświetlany rozmiar zdjęć i filmów"</string> <string name="pref_gallery_size_dialogtitle">"Rozmiar"</string> <string-array name="pref_gallery_size_choices"> <item>"Duży"</item> <item>"Mały"</item> </string-array> <string name="pref_gallery_sort_title">"Kolejność sortowania"</string> <string name="pref_gallery_sort_summary">"Wybierz kolejność sortowania zdjęć i filmów"</string> <string name="pref_gallery_sort_dialogtitle">"Sortowanie zdjęć"</string> <string-array name="pref_gallery_sort_choices"> <item>"Od najnowszego"</item> <item>"Od najstarszego"</item> </string-array> - <string name="pref_gallery_slideshow_interval_title">"Pokaz slajdów – interwał"</string> + <string name="pref_gallery_slideshow_interval_title">"Interwał pokazu slajdów"</string> <string name="pref_gallery_slideshow_interval_summary">"Wybierz, jak długo mają być wyświetlane poszczególne zdjęcia w pokazie slajdów"</string> - <string name="pref_gallery_slideshow_interval_dialogtitle">"Pokaz slajdów – interwał"</string> + <string name="pref_gallery_slideshow_interval_dialogtitle">"Interwał pokazu slajdów"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 sekundy"</item> <item>"3 sekundy"</item> <item>"4 sekundy"</item> </string-array> - <string name="pref_gallery_slideshow_transition_title">"Pokaz slajdów – efekty"</string> + <string name="pref_gallery_slideshow_transition_title">"Efekty pokazu slajdów"</string> <string name="pref_gallery_slideshow_transition_summary">"Wybierz efekt używany przy przejściu z jednego zdjęcia do kolejnego"</string> - <string name="pref_gallery_slideshow_transition_dialogtitle">"Pokaz slajdów – efekty"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"Efekty pokazu slajdów"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Pojawianie i znikanie"</item> <item>"Przesuwanie z lewa w prawo"</item> <item>"Przesuwanie góra-dół"</item> <item>"Wybór losowy"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Powtórz pokaz slajdów"</string> <string name="pref_gallery_slideshow_repeat_summary">"Wyświetlaj pokaz slajdów więcej niż raz"</string> <string name="pref_gallery_slideshow_shuffle_title">"Losowa kolejność"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Wyświetlaj zdjęcia w kolejności losowej"</string> <string name="pref_camera_recordlocation_title">"Zapisuj lokalizację w zdjęciach"</string> <string name="pref_camera_recordlocation_summary">"Zapisz lokalizację w danych zdjęcia"</string> <string name="pref_camera_videoquality_category">"Jakość wideo"</string> <string name="pref_camera_videoquality_title">"Wybierz jakość wideo"</string> <string name="pref_camera_videoquality_entry_0">"Niska (dla wiadomości MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Wysoka (dla karty SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Jakość wideo"</string> <string name="camerasettings">"Ustawienia"</string> - <string name="image_gallery_NoImageView_text">"Brak plików."</string> + <string name="image_gallery_NoImageView_text">"Brak plików"</string> <string name="pref_gallery_confirm_delete_title">"Potwierdzanie usuwania"</string> <string name="pref_gallery_confirm_delete_summary">"Wyświetl potwierdzenie przed usunięciem zdjęcia lub filmu"</string> <string name="details_panel_title">"Szczegóły"</string> <string name="details_file_size">"Rozmiar pliku:"</string> <string name="details_image_resolution">"Rozdzielczość:"</string> <string name="details_duration">"Czas trwania:"</string> <string name="details_date_taken">"Data zrobienia zdjęcia:"</string> <string name="details_frame_rate">"Szybkość klatek:"</string> <string name="details_bit_rate">"Szybkość transmisji:"</string> <string name="details_codec">"Kodek:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d ramek/s"</string> <string name="details_kbps">"%1$d Kb/s"</string> <string name="details_mbps">"%1$g Mb/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opcje zdjęć"</string> <string name="video_context_menu_header">"Opcje wideo"</string> <string name="multiface_crop_help">"Dotknij twarzy, aby rozpocząć"</string> <string name="photos_gallery_title">"Galeria"</string> <string name="pick_photos_gallery_title">"Wybierz zdjęcie"</string> <string name="videos_gallery_title">"Galeria"</string> <string name="pick_videos_gallery_title">"Wybierz film wideo"</string> <string name="loading_progress_format_string">"Pozostało <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Prześlij zdjęcie następującą drogą:"</string> <string name="setImage">"Ustaw zdjęcie jako"</string> <string name="sendVideo">"Prześlij film następującą drogą:"</string> <string name="movieviewlabel">"Filmy"</string> <string name="loading_video">"Ładowanie filmu..."</string> <string name="spaceIsLow_title">"Miejsca jest mało"</string> <string name="spaceIsLow_content">"Na karcie SD brakuje miejsca. Zmień ustawienie jakości lub usuń elementy z Galerii."</string> <string name="resume_playing_title">"Wznów film"</string> <string name="resume_playing_message">"Wznowić odtwarzanie od %s?"</string> <string name="resume_playing_resume">"Wznów odtwarzanie"</string> <string name="resume_playing_restart">"Rozpocznij"</string> <string name="gadget_title">"Ramka zdjęcia"</string> <string name="file_info_title">"Informacje o pliku:"</string> <string name="video_exceed_mms_limit">"Nagrany film wideo jest zbyt duży, aby wysłać go w wiadomości MMS. Spróbuj nagrać krótszy film wideo."</string> <string name="too_large_to_attach">"Plik jest zbyt duży do załączenia."</string> </resources>
brunsky/WS171-packages-apps-Camera
8f9a47c9c8a2a8b5efc8b3384784af7dae78fc37
AI 144891: Import a bunch of revised translations.
diff --git a/res/values-cs/strings.xml b/res/values-cs/strings.xml index 74a8e37..5f859ec 100644 --- a/res/values-cs/strings.xml +++ b/res/values-cs/strings.xml @@ -1,157 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Všechny fotografie"</string> <string name="all_videos">"Všechna videa"</string> <string name="camera_label">"Fotoaparát"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> + <string name="video_camera_label">"Videokamera"</string> <string name="gallery_picker_label">"Galerie"</string> <string name="gallery_camera_bucket_name">"Pořízené fotografie"</string> <string name="gallery_camera_videos_bucket_name">"Pořízená videa"</string> <string name="switch_to_video_lable">"Přepnout do režimu video"</string> <string name="switch_to_camera_lable">"Přepnout do režimu fotoaparát"</string> <string name="crop_label">"Oříznout fotografii"</string> <string name="view_label">"Zobrazit fotografii"</string> <string name="preferences_label">"Nastavení fotoaparátu"</string> <string name="wait">"Čekejte prosím..."</string> <string name="no_storage">"Než začnete používat fotoaparát, vložte kartu SD."</string> <string name="not_enough_space">"Vaše karta SD je plná."</string> <string name="preparing_sd">"Příprava karty SD..."</string> <string name="wallpaper">"Nastavování tapety, čekejte prosím..."</string> <string name="savingImage">"Ukládání fotografie..."</string> <string name="runningFaceDetection">"Čekejte prosím..."</string> <string name="flip_orientation">"Změnit orientaci"</string> <string name="settings">"Nastavení"</string> <string name="view">"Zobrazit"</string> <string name="details">"Podrobnosti"</string> <string name="rotate">"Otočit"</string> <string name="rotate_left">"Otočit doleva"</string> <string name="rotate_right">"Otočit doprava"</string> <string name="slide_show">"Prezentace"</string> <string name="capture_picture">"Fotografovat"</string> <string name="capture_video">"Natočit video"</string> <string name="crop_save_text">"Uložit"</string> <string name="crop_discard_text">"Zahodit"</string> <string name="confirm_delete_title">"Smazat"</string> <string name="confirm_delete_message">"Fotografie bude smazána."</string> <string name="confirm_delete_video_message">"Video bude smazáno."</string> <string name="camera_toss">"Smazat"</string> <string name="camera_gallery">"Galerie"</string> <string name="camera_share">"Sdílet"</string> <string name="camera_set">"Použít jako"</string> <string name="camera_play">"Přehrát"</string> <string name="camera_attach">"Připojit přílohu"</string> <string name="camera_cancel">"Zrušit"</string> <string name="camera_crop">"Oříznout"</string> <string name="camera_tossing">"Mazání..."</string> <string name="no_way_to_share_image">"Tuto fotografii nelze sdílet."</string> <string name="no_way_to_share_video">"Toto video nelze sdílet."</string> - <!-- no translation found for video_play (5287787282508002895) --> - <skip /> + <string name="video_play">"Přehrát"</string> <string name="camera_gallery_photos_text">"Galerie"</string> <string name="camera_pick_wallpaper">"Fotografie"</string> <string name="camera_setas_wallpaper">"Tapeta"</string> <string name="pref_gallery_category">"Obecné nastavení"</string> <string name="pref_slideshow_category">"Nastavení prezentace"</string> <string name="pref_camera_general_settings_category">"Obecné nastavení"</string> <string name="pref_gallery_size_title">"Zobrazovaná velikost"</string> <string name="pref_gallery_size_summary">"Vyberte zobrazovanou velikost obrázků a videí"</string> <string name="pref_gallery_size_dialogtitle">"Velikost fotografie"</string> <string-array name="pref_gallery_size_choices"> <item>"Velké"</item> <item>"Malé"</item> </string-array> <string name="pref_gallery_sort_title">"Řazení"</string> <string name="pref_gallery_sort_summary">"Vyberte způsob řazení obrázků a videí"</string> <string name="pref_gallery_sort_dialogtitle">"Řazení fotografií"</string> <string-array name="pref_gallery_sort_choices"> <item>"Od nejnovějších"</item> <item>"Od nejstarších"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Interval prezentace"</string> <string name="pref_gallery_slideshow_interval_summary">"Vyberte, jak dlouho má být zobrazen každý snímek"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Interval prezentace"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 sekundy"</item> <item>"3 sekundy"</item> <item>"4 sekundy"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Přechod v prezentaci"</string> <string name="pref_gallery_slideshow_transition_summary">"Vyberte efekt, který má být použit při přechodu z jednoho snímku na další"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Přechod v prezentaci"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Prolínat"</item> <item>"Posouvat zleva doprava"</item> <item>"Posouvat shora dolů"</item> <item>"Náhodný výběr"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Opakovat prezentaci"</string> <string name="pref_gallery_slideshow_repeat_summary">"Přehrát prezentaci více než jednou"</string> <string name="pref_gallery_slideshow_shuffle_title">"Náhodné pořadí snímků"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Zobrazit fotografie v náhodném pořadí"</string> <string name="pref_camera_recordlocation_title">"K fotografiím ukládat místo pořízení"</string> - <string name="pref_camera_recordlocation_summary">"V datech fotografie zaznamenat místo pořízení"</string> + <string name="pref_camera_recordlocation_summary">"V údajích o fotografii zaznamenat místo pořízení"</string> <string name="pref_camera_videoquality_category">"Kvalita videa"</string> <string name="pref_camera_videoquality_title">"Vybrat kvalitu videa"</string> <string name="pref_camera_videoquality_entry_0">"Nízká (pro zprávy MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Vysoká (pro kartu SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Kvalita videa"</string> <string name="camerasettings">"Nastavení"</string> <string name="image_gallery_NoImageView_text">"Žádná média nebyla nalezena."</string> <string name="pref_gallery_confirm_delete_title">"Potvrdit smazání"</string> - <string name="pref_gallery_confirm_delete_summary">"Žádat potvrzení před smazáním obrázku nebo videa"</string> + <string name="pref_gallery_confirm_delete_summary">"Požadovat potvrzení před smazáním obrázku nebo videa"</string> <string name="details_panel_title">"Podrobnosti"</string> <string name="details_file_size">"Velikost souboru:"</string> <string name="details_image_resolution">"Rozlišení:"</string> <string name="details_duration">"Délka:"</string> <string name="details_date_taken">"Datum pořízení:"</string> <string name="details_frame_rate">"Počet snímků za sekundu:"</string> <string name="details_bit_rate">"Bitová rychlost:"</string> <string name="details_codec">"Kodek:"</string> <string name="details_format">"Formát:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d snímků/s"</string> <string name="details_kbps">"%1$d Kb/s"</string> <string name="details_mbps">"%1$g Mb/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Možnosti fotografií"</string> <string name="video_context_menu_header">"Možnosti videa"</string> <string name="multiface_crop_help">"Začněte klepnutím na obličej."</string> <string name="photos_gallery_title">"Galerie"</string> <string name="pick_photos_gallery_title">"Vyberte fotografii"</string> <string name="videos_gallery_title">"Galerie"</string> <string name="pick_videos_gallery_title">"Vybrat video"</string> <string name="loading_progress_format_string">"Zbývá <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Sdílet fotografii pomocí"</string> <string name="setImage">"Fotografie bude použita jako"</string> <string name="sendVideo">"Sdílet video pomocí"</string> <string name="movieviewlabel">"Filmy"</string> <string name="loading_video">"Načítání videa..."</string> <string name="spaceIsLow_title">"Dochází volné místo"</string> <string name="spaceIsLow_content">"Na vaší kartě SD je málo místa. Změňte nastavení kvality nebo smažte položky z Galerie."</string> <string name="resume_playing_title">"Pokračovat v přehrávání videa"</string> <string name="resume_playing_message">"Pokračovat v přehrávání od %s?"</string> <string name="resume_playing_resume">"Pokračovat v přehrávání"</string> <string name="resume_playing_restart">"Začít znovu"</string> <string name="gadget_title">"Rámeček fotografie"</string> <string name="file_info_title">"Informace o souboru:"</string> <string name="video_exceed_mms_limit">"Zaznamenané video je pro odeslání ve zprávě MMS příliš velké. Zkuste zaznamenat kratší videoklip."</string> <string name="too_large_to_attach">"Soubor nelze připojit, protože je příliš velký."</string> </resources> diff --git a/res/values-de/strings.xml b/res/values-de/strings.xml index 0924e60..aebb514 100644 --- a/res/values-de/strings.xml +++ b/res/values-de/strings.xml @@ -1,156 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Alle Bilder"</string> <string name="all_videos">"Alle Videos"</string> <string name="camera_label">"Kamera"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> + <string name="video_camera_label">"Camcorder"</string> <string name="gallery_picker_label">"Galerie"</string> <string name="gallery_camera_bucket_name">"Kamerabilder"</string> <string name="gallery_camera_videos_bucket_name">"Kameravideos"</string> <string name="switch_to_video_lable">"Zu Video wechseln"</string> <string name="switch_to_camera_lable">"Zu Kamera wechseln"</string> <string name="crop_label">"Bild zuschneiden"</string> <string name="view_label">"Bild anzeigen"</string> <string name="preferences_label">"Kameraeinstellungen"</string> <string name="wait">"Bitte warten..."</string> <string name="no_storage">"Legen Sie vor Verwendung der Kamera eine SD-Karte ein."</string> <string name="not_enough_space">"Ihre SD-Karte ist voll."</string> <string name="preparing_sd">"SD-Karte wird vorbereitet..."</string> <string name="wallpaper">"Hintergrund wird eingestellt, bitte warten..."</string> <string name="savingImage">"Bild wird gespeichert..."</string> <string name="runningFaceDetection">"Bitte warten..."</string> <string name="flip_orientation">"Ausrichtung drehen"</string> <string name="settings">"Einstellungen"</string> <string name="view">"Anzeigen"</string> <string name="details">"Details"</string> <string name="rotate">"Drehen"</string> <string name="rotate_left">"Nach links drehen"</string> <string name="rotate_right">"Nach rechts drehen"</string> <string name="slide_show">"Diashow"</string> <string name="capture_picture">"Bild aufnehmen"</string> <string name="capture_video">"Video aufnehmen"</string> <string name="crop_save_text">"Speichern"</string> <string name="crop_discard_text">"Verwerfen"</string> <string name="confirm_delete_title">"Löschen"</string> <string name="confirm_delete_message">"Das Bild wird gelöscht."</string> <string name="confirm_delete_video_message">"Das Video wird gelöscht."</string> <string name="camera_toss">"Löschen"</string> <string name="camera_gallery">"Galerie"</string> <string name="camera_share">"Senden"</string> <string name="camera_set">"Festlegen als"</string> <string name="camera_play">"Wiedergeben"</string> <string name="camera_attach">"Anhängen"</string> <string name="camera_cancel">"Abbrechen"</string> <string name="camera_crop">"Zuschneiden"</string> <string name="camera_tossing">"Löschvorgang..."</string> <string name="no_way_to_share_image">"Dieses Bild kann nicht weitergeleitet werden."</string> <string name="no_way_to_share_video">"Dieses Video kann nicht weitergeleitet werden."</string> - <string name="video_play">"Play"</string> + <string name="video_play">"Wiedergeben"</string> <string name="camera_gallery_photos_text">"Galerie"</string> <string name="camera_pick_wallpaper">"Bilder"</string> <string name="camera_setas_wallpaper">"Hintergrund"</string> <string name="pref_gallery_category">"Allgemeine Einstellungen"</string> <string name="pref_slideshow_category">"Einstellungen für Diashow"</string> <string name="pref_camera_general_settings_category">"Allgemeine Einstellungen"</string> <string name="pref_gallery_size_title">"Anzeigegröße"</string> <string name="pref_gallery_size_summary">"Anzeigegröße für Bilder und Videos auswählen"</string> <string name="pref_gallery_size_dialogtitle">"Bildgröße"</string> <string-array name="pref_gallery_size_choices"> <item>"Groß"</item> <item>"Klein"</item> </string-array> <string name="pref_gallery_sort_title">"Sortierreihenfolge"</string> <string name="pref_gallery_sort_summary">"Sortierreihenfolge für Bilder und Videos auswählen"</string> <string name="pref_gallery_sort_dialogtitle">"Sortierreihenfolge für Bilder"</string> <string-array name="pref_gallery_sort_choices"> <item>"Neue zuerst"</item> <item>"Neue zuletzt"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Diashow-Intervall"</string> <string name="pref_gallery_slideshow_interval_summary">"Auswählen, wie lange jedes Bild in der Diashow angezeigt werden soll"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Diashow-Intervall"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 Sekunden"</item> <item>"3 Sekunden"</item> <item>"4 Sekunden"</item> </string-array> - <string name="pref_gallery_slideshow_transition_title">"Diashow - Übergang"</string> + <string name="pref_gallery_slideshow_transition_title">"Diashow-Übergang"</string> <string name="pref_gallery_slideshow_transition_summary">"Effekt auswählen, der beim Wechsel zum nächsten Bild angewendet wird"</string> - <string name="pref_gallery_slideshow_transition_dialogtitle">"Diashow - Übergang"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"Diashow-Übergang"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ein- und ausblenden"</item> <item>"Einblendung von links - rechts"</item> <item>"Einblendung von oben - unten"</item> <item>"Zufällige Auswahl"</item> </string-array> - <string name="pref_gallery_slideshow_repeat_title">"Diashow erneut anzeigen?"</string> + <string name="pref_gallery_slideshow_repeat_title">"Diashow wiederholen"</string> <string name="pref_gallery_slideshow_repeat_summary">"Diashow mehrmals anzeigen"</string> <string name="pref_gallery_slideshow_shuffle_title">"Bilder mischen"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Bilder in zufälliger Reihenfolge anzeigen"</string> - <string name="pref_camera_recordlocation_title">"Aufnahmeort in Bildern speichern"</string> + <string name="pref_camera_recordlocation_title">"Aufnahmeort speichern"</string> <string name="pref_camera_recordlocation_summary">"Aufnahmeort in Bilddaten speichern"</string> <string name="pref_camera_videoquality_category">"Videoqualität"</string> <string name="pref_camera_videoquality_title">"Videoqualität auswählen"</string> <string name="pref_camera_videoquality_entry_0">"Niedrig (für MMS-Mitteilungen)"</string> <string name="pref_camera_videoquality_entry_1">"Hoch (für SD-Karte)"</string> <string name="pref_camera_videoquality_dialogtitle">"Videoqualität"</string> <string name="camerasettings">"Einstellungen"</string> <string name="image_gallery_NoImageView_text">"Keine Medien gefunden."</string> <string name="pref_gallery_confirm_delete_title">"Löschvorgang bestätigen"</string> <string name="pref_gallery_confirm_delete_summary">"Bestätigung vor dem Löschen eines Bildes oder Videos anzeigen"</string> <string name="details_panel_title">"Details"</string> <string name="details_file_size">"Dateigröße:"</string> <string name="details_image_resolution">"Auflösung:"</string> <string name="details_duration">"Dauer:"</string> <string name="details_date_taken">"Aufnahmedatum:"</string> <string name="details_frame_rate">"Framerate:"</string> <string name="details_bit_rate">"Bitrate:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbit/s"</string> <string name="details_mbps">"%1$g Mbit/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Bildoptionen"</string> <string name="video_context_menu_header">"Videooptionen"</string> <string name="multiface_crop_help">"Tippen Sie zum Beginnen auf ein Gesicht."</string> <string name="photos_gallery_title">"Galerie"</string> <string name="pick_photos_gallery_title">"Bild auswählen"</string> <string name="videos_gallery_title">"Galerie"</string> <string name="pick_videos_gallery_title">"Video auswählen"</string> <string name="loading_progress_format_string">"noch <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Bild senden via"</string> <string name="setImage">"Bild festlegen als"</string> <string name="sendVideo">"Video weiterleiten via"</string> <string name="movieviewlabel">"Filme"</string> <string name="loading_video">"Video wird geladen..."</string> <string name="spaceIsLow_title">"Geringer Speicherplatz"</string> <string name="spaceIsLow_content">"Auf Ihrer SD-Karte ist nicht mehr genügend Speicherplatz vorhanden. Ändern Sie die Qualitätseinstellung oder löschen Sie Elemente aus der Galerie."</string> <string name="resume_playing_title">"Mit Video fortfahren"</string> <string name="resume_playing_message">"Mit Wiedergabe fortfahren ab %s ?"</string> <string name="resume_playing_resume">"Mit Wiedergabe fortfahren"</string> <string name="resume_playing_restart">"Starten"</string> <string name="gadget_title">"Bildrahmen"</string> <string name="file_info_title">"Dateiinfo:"</string> <string name="video_exceed_mms_limit">"Das aufgenommene Video ist zu groß und kann nicht per MMS gesendet werden. Nehmen Sie einen kürzeren Clip auf."</string> <string name="too_large_to_attach">"Dateianhang zu groß"</string> </resources> diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml index 65abe35..ccb461a 100644 --- a/res/values-es/strings.xml +++ b/res/values-es/strings.xml @@ -1,157 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Todas las imágenes"</string> <string name="all_videos">"Todos los vídeos"</string> <string name="camera_label">"Cámara"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> + <string name="video_camera_label">"Videocámara"</string> <string name="gallery_picker_label">"Galería"</string> <string name="gallery_camera_bucket_name">"Imágenes de cámara"</string> <string name="gallery_camera_videos_bucket_name">"Vídeos de cámara"</string> <string name="switch_to_video_lable">"Cambiar a vídeo"</string> <string name="switch_to_camera_lable">"Cambiar a cámara"</string> <string name="crop_label">"Recortar imagen"</string> <string name="view_label">"Ver imagen"</string> <string name="preferences_label">"Configuración de cámara"</string> <string name="wait">"Por favor, espera..."</string> <string name="no_storage">"Antes de utilizar la cámara, debes insertar una tarjeta SD."</string> <string name="not_enough_space">"La tarjeta SD está llena."</string> <string name="preparing_sd">"Preparando tarjeta SD…"</string> <string name="wallpaper">"Estableciendo fondo de pantalla..."</string> <string name="savingImage">"Guardando imagen..."</string> <string name="runningFaceDetection">"Por favor, espera..."</string> <string name="flip_orientation">"Cambiar orientación"</string> <string name="settings">"Ajustes"</string> <string name="view">"Ver"</string> <string name="details">"Detalles"</string> <string name="rotate">"Girar"</string> <string name="rotate_left">"Girar a la izquierda"</string> <string name="rotate_right">"Girar a la derecha"</string> <string name="slide_show">"Presentación"</string> <string name="capture_picture">"Capturar imagen"</string> <string name="capture_video">"Capturar vídeo"</string> <string name="crop_save_text">"Guardar"</string> <string name="crop_discard_text">"Descartar"</string> <string name="confirm_delete_title">"Suprimir"</string> <string name="confirm_delete_message">"Se eliminará la imagen."</string> <string name="confirm_delete_video_message">"Se eliminará el vídeo."</string> <string name="camera_toss">"Suprimir"</string> <string name="camera_gallery">"Galería"</string> <string name="camera_share">"Compartir"</string> <string name="camera_set">"Establecer como"</string> <string name="camera_play">"Reproducir"</string> <string name="camera_attach">"Adjuntar"</string> <string name="camera_cancel">"Cancelar"</string> <string name="camera_crop">"Recortar"</string> <string name="camera_tossing">"Eliminando..."</string> <string name="no_way_to_share_image">"Esta imagen no se puede compartir."</string> <string name="no_way_to_share_video">"Este vídeo no se puede compartir."</string> - <!-- no translation found for video_play (5287787282508002895) --> - <skip /> + <string name="video_play">"Reproducir"</string> <string name="camera_gallery_photos_text">"Galería"</string> <string name="camera_pick_wallpaper">"Imágenes"</string> <string name="camera_setas_wallpaper">"Fondo de pantalla"</string> <string name="pref_gallery_category">"Configuración general"</string> <string name="pref_slideshow_category">"Configuración de presentación"</string> <string name="pref_camera_general_settings_category">"Configuración general"</string> <string name="pref_gallery_size_title">"Tamaño de visualización"</string> <string name="pref_gallery_size_summary">"Seleccionar el tamaño de visualización de imágenes y vídeos"</string> <string name="pref_gallery_size_dialogtitle">"Tamaño de imagen"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Pequeña"</item> </string-array> <string name="pref_gallery_sort_title">"Orden"</string> <string name="pref_gallery_sort_summary">"Seleccionar el orden de imágenes y vídeos"</string> <string name="pref_gallery_sort_dialogtitle">"Ordenación de imágenes"</string> <string-array name="pref_gallery_sort_choices"> <item>"Más recientes primero"</item> <item>"Más recientes al final"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalo de presentación"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleccionar la duración de cada diapositiva"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo de presentación"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 segundos"</item> <item>"3 segundos"</item> <item>"4 segundos"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transición de diapositivas"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleccionar el efecto que se aplicará al pasar de una diapositiva a otra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transición de diapositivas"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Fundido de entrada y salida"</item> <item>"Transición de izquierda a derecha"</item> <item>"Transición de arriba a abajo"</item> <item>"Selección aleatoria"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Repetir presentación"</string> <string name="pref_gallery_slideshow_repeat_summary">"Mostrar presentación más de una vez"</string> <string name="pref_gallery_slideshow_shuffle_title">"Reproducir diapositivas en orden aleatorio"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imágenes en orden aleatorio"</string> <string name="pref_camera_recordlocation_title">"Almacenar ubicación en imágenes"</string> <string name="pref_camera_recordlocation_summary">"Registrar ubicación en datos de imagen"</string> <string name="pref_camera_videoquality_category">"Calidad de vídeo"</string> <string name="pref_camera_videoquality_title">"Seleccionar calidad de vídeo"</string> <string name="pref_camera_videoquality_entry_0">"Baja (para mensajes MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (para tarjeta SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Calidad de vídeo"</string> <string name="camerasettings">"Ajustes"</string> <string name="image_gallery_NoImageView_text">"No se ha encontrado ningún elemento."</string> <string name="pref_gallery_confirm_delete_title">"Confirmar eliminaciones"</string> <string name="pref_gallery_confirm_delete_summary">"Mostrar confirmación antes de eliminar una imagen o un vídeo"</string> <string name="details_panel_title">"Detalles"</string> <string name="details_file_size">"Tamaño de archivo:"</string> <string name="details_image_resolution">"Resolución:"</string> <string name="details_duration">"Duración:"</string> <string name="details_date_taken">"Fecha de realización:"</string> <string name="details_frame_rate">"Frecuencia de imagen:"</string> <string name="details_bit_rate">"Velocidad binaria:"</string> <string name="details_codec">"Códec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"Aceptar"</string> <string name="context_menu_header">"Opciones de imagen"</string> <string name="video_context_menu_header">"Opciones de vídeo"</string> <string name="multiface_crop_help">"Selecciona una cara para empezar."</string> <string name="photos_gallery_title">"Galería"</string> <string name="pick_photos_gallery_title">"Seleccionar imagen"</string> <string name="videos_gallery_title">"Galería"</string> <string name="pick_videos_gallery_title">"Seleccionar vídeo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> <string name="sendImage">"Compartir imagen por"</string> <string name="setImage">"Establecer imagen como"</string> <string name="sendVideo">"Compartir vídeo a través de"</string> <string name="movieviewlabel">"Películas"</string> <string name="loading_video">"Cargando vídeo…"</string> <string name="spaceIsLow_title">"Poco espacio"</string> <string name="spaceIsLow_content">"No queda espacio en la tarjeta SD. Cambia la configuración de calidad o elimina elementos de la galería."</string> <string name="resume_playing_title">"Reanudar vídeo"</string> <string name="resume_playing_message">"Reanudar reproducción a partir de %s ?"</string> <string name="resume_playing_resume">"Reanudar reproducción"</string> <string name="resume_playing_restart">"Volver a reproducir"</string> <string name="gadget_title">"Picture frame"</string> <string name="file_info_title">"Información de archivo:"</string> <string name="video_exceed_mms_limit">"El vídeo que has grabado es demasiado grande para enviarlo a través de MMS. Intenta grabar un vídeo de menor duración."</string> <string name="too_large_to_attach">"El archivo es demasiado grande para adjuntarlo."</string> </resources> diff --git a/res/values-fr/strings.xml b/res/values-fr/strings.xml index 5a82537..c235b3d 100644 --- a/res/values-fr/strings.xml +++ b/res/values-fr/strings.xml @@ -1,157 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Toutes les images"</string> <string name="all_videos">"Toutes les vidéos"</string> <string name="camera_label">"Appareil photo"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> + <string name="video_camera_label">"Caméra"</string> <string name="gallery_picker_label">"Galerie"</string> <string name="gallery_camera_bucket_name">"Photos de l\'appareil"</string> <string name="gallery_camera_videos_bucket_name">"Vidéos de la caméra"</string> <string name="switch_to_video_lable">"Passer en mode vidéo"</string> <string name="switch_to_camera_lable">"Passer en mode appareil photo"</string> <string name="crop_label">"Rogner l\'image"</string> <string name="view_label">"Afficher l\'image"</string> <string name="preferences_label">"Paramètres de l\'appareil photo"</string> <string name="wait">"Veuillez patienter..."</string> <string name="no_storage">"Veuillez insérer une carte SD avant d\'utiliser l\'appareil photo."</string> <string name="not_enough_space">"Votre carte SD est pleine."</string> <string name="preparing_sd">"Préparation de la carte SD..."</string> <string name="wallpaper">"Configuration de l\'arrière-plan en cours. Veuillez patienter..."</string> <string name="savingImage">"Enregistrement de l\'image"</string> <string name="runningFaceDetection">"Veuillez patienter..."</string> <string name="flip_orientation">"Orientation"</string> <string name="settings">"Paramètres"</string> <string name="view">"Afficher"</string> <string name="details">"Détails"</string> <string name="rotate">"Faire pivoter"</string> <string name="rotate_left">"Faire pivoter à gauche"</string> <string name="rotate_right">"Faire pivoter à droite"</string> <string name="slide_show">"Diaporama"</string> <string name="capture_picture">"Prendre une photo"</string> <string name="capture_video">"Prendre une vidéo"</string> <string name="crop_save_text">"Enregistrer"</string> <string name="crop_discard_text">"Annuler"</string> <string name="confirm_delete_title">"Supprimer"</string> <string name="confirm_delete_message">"L\'image sera supprimée."</string> <string name="confirm_delete_video_message">"La vidéo va être supprimée."</string> <string name="camera_toss">"Supprimer"</string> <string name="camera_gallery">"Galerie"</string> <string name="camera_share">"Partager"</string> <string name="camera_set">"Définir comme"</string> <string name="camera_play">"Lire"</string> <string name="camera_attach">"Joindre"</string> <string name="camera_cancel">"Annuler"</string> <string name="camera_crop">"Rogner"</string> <string name="camera_tossing">"Suppression..."</string> <string name="no_way_to_share_image">"Impossible de partager cette image."</string> <string name="no_way_to_share_video">"Cette vidéo ne peut pas être partagée."</string> - <!-- no translation found for video_play (5287787282508002895) --> - <skip /> + <string name="video_play">"Lire"</string> <string name="camera_gallery_photos_text">"Galerie"</string> <string name="camera_pick_wallpaper">"Images"</string> <string name="camera_setas_wallpaper">"Arrière-plan"</string> <string name="pref_gallery_category">"Paramètres généraux"</string> <string name="pref_slideshow_category">"Paramètres du diaporama"</string> <string name="pref_camera_general_settings_category">"Paramètres généraux"</string> <string name="pref_gallery_size_title">"Taille d\'affichage"</string> <string name="pref_gallery_size_summary">"Sélectionner la taille d\'affichage des images et des vidéos"</string> <string name="pref_gallery_size_dialogtitle">"Taille de l\'image"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Petite"</item> </string-array> <string name="pref_gallery_sort_title">"Ordre de tri"</string> <string name="pref_gallery_sort_summary">"Sélectionner l\'ordre de tri des images et des vidéos"</string> <string name="pref_gallery_sort_dialogtitle">"Trier les images"</string> <string-array name="pref_gallery_sort_choices"> <item>"La plus récente en premier"</item> <item>"La plus récente en dernier"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalle du diaporama"</string> <string name="pref_gallery_slideshow_interval_summary">"Sélectionner la durée d\'affichage de chaque diapositive dans le diaporama"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalle du diaporama"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 secondes"</item> <item>"3 secondes"</item> <item>"4 secondes"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transition du diaporama"</string> <string name="pref_gallery_slideshow_transition_summary">"Sélectionner l\'effet utilisé lors de la transition d\'une diapositive à une autre"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transition du diaporama"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ouverture et fermeture en fondu"</item> <item>"Glisser de gauche à droite"</item> <item>"Glisser de haut en bas"</item> <item>"Sélection aléatoire"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Rejouer le diaporama"</string> <string name="pref_gallery_slideshow_repeat_summary">"Rejouer le diaporama plusieurs fois"</string> <string name="pref_gallery_slideshow_shuffle_title">"Lecture aléatoire"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Afficher les images"</string> <string name="pref_camera_recordlocation_title">"Enregistrer le lieu"</string> <string name="pref_camera_recordlocation_summary">"Enregistrer la position géographique dans les données d\'image"</string> <string name="pref_camera_videoquality_category">"Paramètres vidéo"</string> <string name="pref_camera_videoquality_title">"Qualité vidéo"</string> <string name="pref_camera_videoquality_entry_0">"Basse (pour les MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Haute (pour la carte SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Qualité vidéo"</string> <string name="camerasettings">"Paramètres"</string> <string name="image_gallery_NoImageView_text">"Aucun fichier trouvé."</string> <string name="pref_gallery_confirm_delete_title">"Confirmer suppressions"</string> <string name="pref_gallery_confirm_delete_summary">"Afficher une confirmation avant de supprimer une image ou une vidéo"</string> <string name="details_panel_title">"Détails"</string> <string name="details_file_size">"Taille du fichier :"</string> <string name="details_image_resolution">"Résolution :"</string> <string name="details_duration">"Durée :"</string> <string name="details_date_taken">"Date de création :"</string> <string name="details_frame_rate">"Fréquence d\'images :"</string> <string name="details_bit_rate">"Débit :"</string> <string name="details_codec">"Codec :"</string> <string name="details_format">"Format :"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d ips"</string> <string name="details_kbps">"%1$d Kbits/s"</string> <string name="details_mbps">"%1$g Mbits/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Options de l\'image"</string> <string name="video_context_menu_header">"Options vidéo"</string> <string name="multiface_crop_help">"Cliquez sur un visage pour commencer."</string> <string name="photos_gallery_title">"Galerie"</string> <string name="pick_photos_gallery_title">"Sélectionnez une image"</string> <string name="videos_gallery_title">"Galerie"</string> <string name="pick_videos_gallery_title">"Sélectionnez une vidéo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> vignettes restantes"</string> <string name="sendImage">"Partager l\'image via"</string> <string name="setImage">"Définir l\'image comme"</string> <string name="sendVideo">"Partager la vidéo via"</string> <string name="movieviewlabel">"Films"</string> <string name="loading_video">"Chargement de la vidéo..."</string> <string name="spaceIsLow_title">"L\'espace restant est faible"</string> <string name="spaceIsLow_content">"Votre carte SD est pleine. Modifiez le paramètre de qualité ou supprimez des éléments de la galerie."</string> <string name="resume_playing_title">"Reprendre la vidéo"</string> <string name="resume_playing_message">"Reprendre la lecture à partir de %s ?"</string> <string name="resume_playing_resume">"Reprendre la lecture"</string> <string name="resume_playing_restart">"Démarrer"</string> <string name="gadget_title">"Cadre d\'image"</string> <string name="file_info_title">"Informations sur le fichier :"</string> <string name="video_exceed_mms_limit">"La vidéo que vous avez enregistrée est trop volumineuse et ne peut être envoyée par MMS. Enregistrez une vidéo plus courte."</string> <string name="too_large_to_attach">"Impossible de joindre le fichier, car il est trop volumineux."</string> </resources> diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml index 20d9d40..7c58b28 100644 --- a/res/values-it/strings.xml +++ b/res/values-it/strings.xml @@ -1,157 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Tutte le foto"</string> <string name="all_videos">"Tutti i video"</string> <string name="camera_label">"Fotocamera"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> + <string name="video_camera_label">"Videocamera"</string> <string name="gallery_picker_label">"Galleria"</string> <string name="gallery_camera_bucket_name">"Foto"</string> <string name="gallery_camera_videos_bucket_name">"Video fotocamera"</string> <string name="switch_to_video_lable">"Passa a video"</string> <string name="switch_to_camera_lable">"Passa a fotocamera"</string> <string name="crop_label">"Ritaglia foto"</string> <string name="view_label">"Visualizza foto"</string> <string name="preferences_label">"Impostazioni fotocamera"</string> <string name="wait">"Attendere..."</string> <string name="no_storage">"Per usare la fotocamera devi inserire una scheda SD."</string> <string name="not_enough_space">"La scheda SD è piena."</string> <string name="preparing_sd">"Preparazione scheda SD…"</string> <string name="wallpaper">"Impostazione sfondo, attendi..."</string> <string name="savingImage">"Salvataggio foto..."</string> <string name="runningFaceDetection">"Attendere..."</string> <string name="flip_orientation">"Capovolgi orientamento"</string> <string name="settings">"Impostazioni"</string> <string name="view">"Visualizza"</string> <string name="details">"Dettagli"</string> <string name="rotate">"Ruota"</string> <string name="rotate_left">"Ruota a sinistra"</string> <string name="rotate_right">"Ruota a destra"</string> <string name="slide_show">"Presentazione"</string> <string name="capture_picture">"Scatta foto"</string> <string name="capture_video">"Registra video"</string> <string name="crop_save_text">"Salva"</string> <string name="crop_discard_text">"Annulla"</string> <string name="confirm_delete_title">"Elimina"</string> <string name="confirm_delete_message">"La foto verrà eliminata."</string> <string name="confirm_delete_video_message">"Il video verrà eliminato."</string> <string name="camera_toss">"Elimina"</string> <string name="camera_gallery">"Galleria"</string> <string name="camera_share">"Condividi"</string> <string name="camera_set">"Imposta come"</string> <string name="camera_play">"Riproduci"</string> <string name="camera_attach">"Allega"</string> <string name="camera_cancel">"Annulla"</string> <string name="camera_crop">"Ritaglia"</string> <string name="camera_tossing">"Eliminazione..."</string> <string name="no_way_to_share_image">"Impossibile condividere la foto."</string> <string name="no_way_to_share_video">"Impossibile condividere il video."</string> - <!-- no translation found for video_play (5287787282508002895) --> - <skip /> + <string name="video_play">"Riproduci"</string> <string name="camera_gallery_photos_text">"Galleria"</string> <string name="camera_pick_wallpaper">"Foto"</string> <string name="camera_setas_wallpaper">"Sfondo"</string> <string name="pref_gallery_category">"Impostazioni generali"</string> <string name="pref_slideshow_category">"Impostazioni presentazione"</string> <string name="pref_camera_general_settings_category">"Impostazioni generali"</string> <string name="pref_gallery_size_title">"Dimensioni schermo"</string> <string name="pref_gallery_size_summary">"Seleziona dimensioni di visualizz. di foto e video"</string> <string name="pref_gallery_size_dialogtitle">"Dimensioni foto"</string> <string-array name="pref_gallery_size_choices"> <item>"Grandi"</item> <item>"Piccole"</item> </string-array> <string name="pref_gallery_sort_title">"Ordinamento"</string> <string name="pref_gallery_sort_summary">"Seleziona l\'ordinamento di foto e video"</string> <string name="pref_gallery_sort_dialogtitle">"Ordine foto"</string> <string-array name="pref_gallery_sort_choices"> <item>"Da più recente"</item> <item>"Da meno recente"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervallo presentazione"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleziona la durata di ogni diapositiva"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervallo presentazione"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 secondi"</item> <item>"3 secondi"</item> <item>"4 secondi"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transizione presentazione"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleziona l\'effetto da usare per passare da una diapositiva all\'altra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transizione diapositive"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Dissolvenza"</item> <item>"Da sinistra a destra"</item> <item>"Dall\'alto verso il basso"</item> <item>"Selezione casuale"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Ripeti presentazione"</string> <string name="pref_gallery_slideshow_repeat_summary">"Riproduci più volte la presentazione"</string> <string name="pref_gallery_slideshow_shuffle_title">"Riproduzione casuale"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostra le foto in ordine casuale"</string> <string name="pref_camera_recordlocation_title">"Salva località nelle foto"</string> <string name="pref_camera_recordlocation_summary">"Registra località nei dati della foto"</string> <string name="pref_camera_videoquality_category">"Qualità video"</string> <string name="pref_camera_videoquality_title">"Seleziona la qualità video"</string> <string name="pref_camera_videoquality_entry_0">"Bassa (per MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (per scheda SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Qualità video"</string> <string name="camerasettings">"Impostazioni"</string> <string name="image_gallery_NoImageView_text">"Nessun media trovato."</string> <string name="pref_gallery_confirm_delete_title">"Conferma eliminazioni"</string> <string name="pref_gallery_confirm_delete_summary">"Mostra conferma prima di eliminare una foto o un video"</string> <string name="details_panel_title">"Dettagli"</string> <string name="details_file_size">"Dim. file:"</string> <string name="details_image_resolution">"Risoluzione:"</string> <string name="details_duration">"Durata:"</string> <string name="details_date_taken">"Data scatto:"</string> <string name="details_frame_rate">"Frequenza fotogrammi:"</string> <string name="details_bit_rate">"Velocità in bit:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opzioni foto"</string> <string name="video_context_menu_header">"Opzioni video"</string> <string name="multiface_crop_help">"Tocca un viso per iniziare."</string> <string name="photos_gallery_title">"Galleria"</string> <string name="pick_photos_gallery_title">"Seleziona foto"</string> <string name="videos_gallery_title">"Galleria"</string> <string name="pick_videos_gallery_title">"Seleziona video"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> rimanenti"</string> <string name="sendImage">"Condividi foto via"</string> <string name="setImage">"Imposta foto come"</string> <string name="sendVideo">"Condividi video via"</string> <string name="movieviewlabel">"Film"</string> <string name="loading_video">"Caricamento video..."</string> <string name="spaceIsLow_title">"Spazio in esaurimento"</string> <string name="spaceIsLow_content">"Lo spazio della scheda SD si sta esaurendo. Cambia l\'impostazione di qualità o elimina elementi nella galleria."</string> <string name="resume_playing_title">"Riprendi video"</string> <string name="resume_playing_message">"Riprendi riproduzione da %s ?"</string> <string name="resume_playing_resume">"Riprendi riproduzione"</string> <string name="resume_playing_restart">"Ricomincia"</string> <string name="gadget_title">"Cornice immagine"</string> <string name="file_info_title">"Info file:"</string> <string name="video_exceed_mms_limit">"Il video registrato è troppo grande per essere inviato tramite MMS. Prova a registrare un clip più corto."</string> <string name="too_large_to_attach">"File troppo grande. Impossibile allegarlo."</string> </resources> diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml index ba80031..949462b 100644 --- a/res/values-ja/strings.xml +++ b/res/values-ja/strings.xml @@ -1,157 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"すべての写真"</string> <string name="all_videos">"すべての動画"</string> <string name="camera_label">"カメラ"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> + <string name="video_camera_label">"ビデオ録画"</string> <string name="gallery_picker_label">"ギャラリー"</string> <string name="gallery_camera_bucket_name">"カメラ (写真)"</string> <string name="gallery_camera_videos_bucket_name">"カメラ (動画)"</string> <string name="switch_to_video_lable">"ムービーに切替"</string> <string name="switch_to_camera_lable">"写真に切替"</string> <string name="crop_label">"トリミング"</string> <string name="view_label">"画像を表示"</string> <string name="preferences_label">"カメラ設定"</string> <string name="wait">"お待ちください..."</string> <string name="no_storage">"カメラを使用する前にSDカードを挿入してください。"</string> <string name="not_enough_space">"SDカードがいっぱいです。"</string> <string name="preparing_sd">"SDカードの準備中..."</string> <string name="wallpaper">"壁紙を設定しています。しばらくお待ちください..."</string> <string name="savingImage">"写真を保存中..."</string> <string name="runningFaceDetection">"お待ちください..."</string> <string name="flip_orientation">"画面の向きを変更"</string> <string name="settings">"設定"</string> <string name="view">"表示"</string> <string name="details">"詳細"</string> <string name="rotate">"回転"</string> <string name="rotate_left">"左に回転"</string> <string name="rotate_right">"右に回転"</string> <string name="slide_show">"スライドショー"</string> <string name="capture_picture">"写真撮影"</string> <string name="capture_video">"ムービー撮影"</string> <string name="crop_save_text">"保存"</string> <string name="crop_discard_text">"キャンセル"</string> <string name="confirm_delete_title">"削除"</string> <string name="confirm_delete_message">"画像を削除します。"</string> <string name="confirm_delete_video_message">"動画を削除します。"</string> <string name="camera_toss">"削除"</string> <string name="camera_gallery">"ギャラリー"</string> <string name="camera_share">"共有"</string> <string name="camera_set">"連絡先等に設定する"</string> <string name="camera_play">"再生"</string> <string name="camera_attach">"添付"</string> <string name="camera_cancel">"キャンセル"</string> <string name="camera_crop">"トリミング"</string> <string name="camera_tossing">"削除中..."</string> <string name="no_way_to_share_image">"この画像は共有できません。"</string> <string name="no_way_to_share_video">"この動画は共有できません。"</string> - <!-- no translation found for video_play (5287787282508002895) --> - <skip /> + <string name="video_play">"再生"</string> <string name="camera_gallery_photos_text">"ギャラリー"</string> <string name="camera_pick_wallpaper">"画像"</string> <string name="camera_setas_wallpaper">"壁紙"</string> <string name="pref_gallery_category">"全般設定"</string> <string name="pref_slideshow_category">"スライドショー設定"</string> <string name="pref_camera_general_settings_category">"全般設定"</string> <string name="pref_gallery_size_title">"表示サイズ"</string> <string name="pref_gallery_size_summary">"画像や動画の表示サイズ"</string> <string name="pref_gallery_size_dialogtitle">"画像サイズ"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"表示順序"</string> <string name="pref_gallery_sort_summary">"画像や動画の表示順序を選択"</string> <string name="pref_gallery_sort_dialogtitle">"画像並べ替え"</string> <string-array name="pref_gallery_sort_choices"> <item>"日付の新しい順"</item> <item>"日付の古い順"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"スライドの再生間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"各スライドの表示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"スライドの再生間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2秒"</item> <item>"3秒"</item> <item>"4秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"スライド切り替え"</string> <string name="pref_gallery_slideshow_transition_summary">"スライドが切り替わるときの効果"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"スライド切り替え"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"フェードイン&amp;アウト"</item> <item>"左右にスライド"</item> <item>"上下にスライド"</item> <item>"ランダムに選択"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"リピート再生"</string> <string name="pref_gallery_slideshow_repeat_summary">"スライドショーを繰り返し再生"</string> <string name="pref_gallery_slideshow_shuffle_title">"スライドのシャッフル"</string> <string name="pref_gallery_slideshow_shuffle_summary">"順不同に表示する"</string> <string name="pref_camera_recordlocation_title">"位置情報を写真に記録する"</string> <string name="pref_camera_recordlocation_summary">"位置情報を写真データに記録する"</string> <string name="pref_camera_videoquality_category">"動画のクオリティ"</string> <string name="pref_camera_videoquality_title">"動画の画質を選択"</string> <string name="pref_camera_videoquality_entry_0">"低 (MMSメッセージ向け)"</string> <string name="pref_camera_videoquality_entry_1">"高 (SDカード向け)"</string> <string name="pref_camera_videoquality_dialogtitle">"動画のクオリティ"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"メディアが見つかりません。"</string> <string name="pref_gallery_confirm_delete_title">"削除確認"</string> <string name="pref_gallery_confirm_delete_summary">"画像や動画を削除する前に確認する"</string> <string name="details_panel_title">"詳細"</string> <string name="details_file_size">"ファイルサイズ:"</string> <string name="details_image_resolution">"解像度:"</string> <string name="details_duration">"再生時間:"</string> <string name="details_date_taken">"撮影日:"</string> <string name="details_frame_rate">"フレームレート:"</string> <string name="details_bit_rate">"ビットレート:"</string> <string name="details_codec">"コーデック:"</string> <string name="details_format">"形式:"</string> <string name="details_dimension_x">"%1$dx%2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$dfps"</string> <string name="details_kbps">"%1$dKbps"</string> <string name="details_mbps">"%1$gMbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"画像オプション"</string> <string name="video_context_menu_header">"動画オプション"</string> <string name="multiface_crop_help">"顔をタップして開始します。"</string> <string name="photos_gallery_title">"ギャラリー"</string> <string name="pick_photos_gallery_title">"画像を選択"</string> <string name="videos_gallery_title">"ギャラリー"</string> <string name="pick_videos_gallery_title">"動画を選択"</string> <string name="loading_progress_format_string">"残り<xliff:g id="COUNTER">%d</xliff:g>件"</string> <string name="sendImage">"画像を共有:"</string> <string name="setImage">"設定タイプ:"</string> <string name="sendVideo">"動画を共有"</string> <string name="movieviewlabel">"映画"</string> <string name="loading_video">"動画を読み込み中..."</string> <string name="spaceIsLow_title">"空き容量が残り少なくなっています"</string> <string name="spaceIsLow_content">"SDカードの容量が足りません。クオリティ設定を変更するか、ギャラリーからアイテムを削除してください。"</string> <string name="resume_playing_title">"動画の再開"</string> <string name="resume_playing_message">"再生を%sから再開しますか?"</string> <string name="resume_playing_resume">"再生を再開"</string> <string name="resume_playing_restart">"最初から再生"</string> <string name="gadget_title">"写真フレーム"</string> <string name="file_info_title">"ファイル情報:"</string> <string name="video_exceed_mms_limit">"録画した動画のサイズが大きすぎるため送信できません。録画時間を短縮してみてください。"</string> <string name="too_large_to_attach">"添付ファイルが大きすぎます。"</string> </resources> diff --git a/res/values-ko/strings.xml b/res/values-ko/strings.xml index b30594b..b1b4e24 100644 --- a/res/values-ko/strings.xml +++ b/res/values-ko/strings.xml @@ -1,157 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"모든 사진"</string> <string name="all_videos">"모든 동영상"</string> <string name="camera_label">"카메라"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> + <string name="video_camera_label">"캠코더"</string> <string name="gallery_picker_label">"갤러리"</string> <string name="gallery_camera_bucket_name">"카메라 사진"</string> <string name="gallery_camera_videos_bucket_name">"카메라 동영상"</string> <string name="switch_to_video_lable">"동영상으로 전환"</string> <string name="switch_to_camera_lable">"카메라로 전환"</string> <string name="crop_label">"사진 자르기"</string> <string name="view_label">"사진 보기"</string> <string name="preferences_label">"카메라 설정"</string> <string name="wait">"잠시 기다려 주세요..."</string> <string name="no_storage">"카메라를 사용하기 전에 먼저 SD 카드를 넣으세요."</string> <string name="not_enough_space">"SD 카드가 꽉 찼습니다."</string> <string name="preparing_sd">"SD 카드 준비중..."</string> <string name="wallpaper">"배경화면 설정 중. 잠시 기다려 주세요..."</string> <string name="savingImage">"사진 저장 중..."</string> <string name="runningFaceDetection">"잠시 기다려 주세요..."</string> <string name="flip_orientation">"방향 바꾸기"</string> <string name="settings">"설정"</string> <string name="view">"보기"</string> <string name="details">"상세정보"</string> <string name="rotate">"회전"</string> <string name="rotate_left">"왼쪽으로 회전"</string> <string name="rotate_right">"오른쪽으로 회전"</string> <string name="slide_show">"슬라이드쇼"</string> <string name="capture_picture">"사진촬영"</string> <string name="capture_video">"동영상 캡처"</string> <string name="crop_save_text">"저장"</string> <string name="crop_discard_text">"무시"</string> <string name="confirm_delete_title">"삭제"</string> <string name="confirm_delete_message">"사진이 삭제됩니다."</string> <string name="confirm_delete_video_message">"동영상이 삭제됩니다."</string> <string name="camera_toss">"삭제"</string> <string name="camera_gallery">"갤러리"</string> <string name="camera_share">"공유"</string> <string name="camera_set">"사진 설정"</string> <string name="camera_play">"재생"</string> <string name="camera_attach">"첨부"</string> <string name="camera_cancel">"취소"</string> <string name="camera_crop">"자르기"</string> <string name="camera_tossing">"삭제 중..."</string> <string name="no_way_to_share_image">"공유할 수 없는 사진입니다."</string> <string name="no_way_to_share_video">"공유할 수 없는 동영상입니다."</string> - <!-- no translation found for video_play (5287787282508002895) --> - <skip /> + <string name="video_play">"재생"</string> <string name="camera_gallery_photos_text">"갤러리"</string> <string name="camera_pick_wallpaper">"사진"</string> <string name="camera_setas_wallpaper">"배경화면"</string> <string name="pref_gallery_category">"일반 설정"</string> <string name="pref_slideshow_category">"슬라이드쇼 설정"</string> <string name="pref_camera_general_settings_category">"일반 설정"</string> <string name="pref_gallery_size_title">"디스플레이 크기"</string> <string name="pref_gallery_size_summary">"사진 및 동영상 표시 크기 선택"</string> <string name="pref_gallery_size_dialogtitle">"사진 크기"</string> <string-array name="pref_gallery_size_choices"> <item>"크게"</item> <item>"작게"</item> </string-array> <string name="pref_gallery_sort_title">"정렬 순서"</string> <string name="pref_gallery_sort_summary">"사진 및 동영상 정렬 순서 선택"</string> <string name="pref_gallery_sort_dialogtitle">"사진 정렬"</string> <string-array name="pref_gallery_sort_choices"> <item>"가장 최근 사진 먼저"</item> <item>"가장 최근 사진 마지막에"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"슬라이드쇼 간격"</string> <string name="pref_gallery_slideshow_interval_summary">"쇼에서 각 슬라이드를 표시할 시간 선택"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"슬라이드쇼 간격"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2초"</item> <item>"3초"</item> <item>"4초"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"슬라이드쇼 화면전환"</string> <string name="pref_gallery_slideshow_transition_summary">"슬라이드 간에 이동할 때 사용할 효과 선택"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"슬라이드쇼 화면전환"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"페이드 인/아웃"</item> <item>"왼쪽에서 오른쪽으로/오른쪽에서 왼쪽으로"</item> <item>"위에서 아래로/아래에서 위로"</item> <item>"무작위 선택"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"슬라이드쇼 반복"</string> <string name="pref_gallery_slideshow_repeat_summary">"슬라이드쇼를 한 번 이상 재생"</string> <string name="pref_gallery_slideshow_shuffle_title">"슬라이드 섞기"</string> <string name="pref_gallery_slideshow_shuffle_summary">"사진을 무작위 순서로 표시"</string> <string name="pref_camera_recordlocation_title">"사진에 위치 저장"</string> <string name="pref_camera_recordlocation_summary">"사진 데이터에 위치 기록"</string> <string name="pref_camera_videoquality_category">"동영상 화질"</string> <string name="pref_camera_videoquality_title">"동영상 화질 선택"</string> <string name="pref_camera_videoquality_entry_0">"낮음(MMS 메시지용)"</string> <string name="pref_camera_videoquality_entry_1">"높음(SD 카드용)"</string> <string name="pref_camera_videoquality_dialogtitle">"동영상 화질"</string> <string name="camerasettings">"설정"</string> <string name="image_gallery_NoImageView_text">"미디어 파일이 없습니다."</string> <string name="pref_gallery_confirm_delete_title">"삭제 확인"</string> <string name="pref_gallery_confirm_delete_summary">"사진 및 동영상 삭제 전 확인 표시"</string> <string name="details_panel_title">"상세정보"</string> <string name="details_file_size">"파일 크기:"</string> <string name="details_image_resolution">"해상도:"</string> <string name="details_duration">"재생 시간:"</string> <string name="details_date_taken">"찍은 날짜:"</string> <string name="details_frame_rate">"프레임 속도:"</string> <string name="details_bit_rate">"비트 전송률:"</string> <string name="details_codec">"코덱:"</string> <string name="details_format">"형식:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$dfps"</string> <string name="details_kbps">"%1$dKbps"</string> <string name="details_mbps">"%1$gMbps"</string> <string name="details_ok">"확인"</string> <string name="context_menu_header">"사진 옵션"</string> <string name="video_context_menu_header">"동영상 옵션"</string> <string name="multiface_crop_help">"시작하려면 얼굴을 탭하세요."</string> <string name="photos_gallery_title">"갤러리"</string> <string name="pick_photos_gallery_title">"사진 선택"</string> <string name="videos_gallery_title">"갤러리"</string> <string name="pick_videos_gallery_title">"동영상 선택"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g>개 남음"</string> <string name="sendImage">"사진 공유 응용프로그램"</string> <string name="setImage">"사진 설정"</string> <string name="sendVideo">"동영상 공유 응용프로그램"</string> <string name="movieviewlabel">"영화"</string> <string name="loading_video">"동영상 로드 중..."</string> <string name="spaceIsLow_title">"공간부족"</string> <string name="spaceIsLow_content">"SD 카드의 공간이 부족합니다. 화질 설정을 변경하거나 갤러리에서 항목을 삭제하세요."</string> <string name="resume_playing_title">"동영상 다시 시작"</string> <string name="resume_playing_message">"%s에서 재생을 다시 시작하시겠습니까?"</string> <string name="resume_playing_resume">"재생 다시 시작"</string> <string name="resume_playing_restart">"시작"</string> <string name="gadget_title">"사진 프레임"</string> <string name="file_info_title">"파일 정보:"</string> <string name="video_exceed_mms_limit">"녹화한 동영상이 너무 커서 MMS를 통해 전송할 수 없습니다. 클립의 길이를 더 짧게 녹화하세요."</string> <string name="too_large_to_attach">"파일이 너무 커서 첨부할 수 없습니다."</string> </resources> diff --git a/res/values-nl/strings.xml b/res/values-nl/strings.xml index e6a6ad7..1362592 100644 --- a/res/values-nl/strings.xml +++ b/res/values-nl/strings.xml @@ -1,157 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Alle foto\'s"</string> <string name="all_videos">"Alle video\'s"</string> <string name="camera_label">"Camera"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> + <string name="video_camera_label">"Camcorder"</string> <string name="gallery_picker_label">"Galerij"</string> <string name="gallery_camera_bucket_name">"Camerafoto\'s"</string> <string name="gallery_camera_videos_bucket_name">"Cameravideo\'s"</string> <string name="switch_to_video_lable">"Overschakelen naar video"</string> <string name="switch_to_camera_lable">"Overschakelen naar camera"</string> <string name="crop_label">"Foto bijsnijden"</string> <string name="view_label">"Foto weergeven"</string> <string name="preferences_label">"Camera-instellingen"</string> <string name="wait">"Een ogenblik geduld..."</string> <string name="no_storage">"Plaats een SD-kaart voordat u de camera gebruikt."</string> <string name="not_enough_space">"De SD-kaart is vol."</string> <string name="preparing_sd">"SD-kaart voorbereiden…"</string> <string name="wallpaper">"Achtergrond wordt ingesteld. Een ogenblik geduld..."</string> <string name="savingImage">"Foto opslaan..."</string> <string name="runningFaceDetection">"Een ogenblik geduld..."</string> <string name="flip_orientation">"Stand draaien"</string> <string name="settings">"Instellingen"</string> <string name="view">"Weergeven"</string> <string name="details">"Details"</string> <string name="rotate">"Draaien"</string> <string name="rotate_left">"Linksom draaien"</string> <string name="rotate_right">"Rechtsom draaien"</string> <string name="slide_show">"Diavoorstelling"</string> <string name="capture_picture">"Foto nemen"</string> <string name="capture_video">"Video opnemen"</string> <string name="crop_save_text">"Opslaan"</string> <string name="crop_discard_text">"Ongedaan maken"</string> <string name="confirm_delete_title">"Verwijderen"</string> <string name="confirm_delete_message">"De foto wordt verwijderd."</string> <string name="confirm_delete_video_message">"De video wordt verwijderd"</string> <string name="camera_toss">"Verwijderen"</string> <string name="camera_gallery">"Galerij"</string> <string name="camera_share">"Delen"</string> <string name="camera_set">"Instellen als"</string> <string name="camera_play">"Afspelen"</string> <string name="camera_attach">"Bijvoegen"</string> <string name="camera_cancel">"Annuleren"</string> <string name="camera_crop">"Bijsnijden"</string> <string name="camera_tossing">"Verwijderen..."</string> <string name="no_way_to_share_image">"Deze foto kan niet worden gedeeld."</string> <string name="no_way_to_share_video">"Deze video kan niet worden gedeeld."</string> - <!-- no translation found for video_play (5287787282508002895) --> - <skip /> + <string name="video_play">"Afspelen"</string> <string name="camera_gallery_photos_text">"Galerij"</string> <string name="camera_pick_wallpaper">"Foto\'s"</string> <string name="camera_setas_wallpaper">"Achtergrond"</string> <string name="pref_gallery_category">"Algemene instellingen"</string> <string name="pref_slideshow_category">"Instellingen van diavoorstelling"</string> <string name="pref_camera_general_settings_category">"Algemene instellingen"</string> <string name="pref_gallery_size_title">"Weergavegrootte"</string> <string name="pref_gallery_size_summary">"De weergavegrootte van foto\'s en video\'s selecteren"</string> <string name="pref_gallery_size_dialogtitle">"Grootte van foto"</string> <string-array name="pref_gallery_size_choices"> <item>"Groot"</item> <item>"Klein"</item> </string-array> <string name="pref_gallery_sort_title">"Sorteervolgorde"</string> <string name="pref_gallery_sort_summary">"De sorteervolgorde van foto\'s en video\'s selecteren"</string> <string name="pref_gallery_sort_dialogtitle">"Foto\'s sorteren"</string> <string-array name="pref_gallery_sort_choices"> <item>"Nieuwste eerst"</item> - <item>"Nieuwste eerst"</item> + <item>"Nieuwste laatst"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Interval in diavoorstelling"</string> <string name="pref_gallery_slideshow_interval_summary">"Selecteren hoe lang elke dia wordt weergegeven in de voorstelling"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Interval in diavoorstelling"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 seconden"</item> <item>"3 seconden"</item> <item>"4 seconden"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Overgangen in diavoorstellingen"</string> <string name="pref_gallery_slideshow_transition_summary">"Het effect selecteren dat wordt gebruikt om naar de volgende dia te gaan"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Overgangen in diavoorstellingen"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Infaden/uitfaden"</item> <item>"Dia vanaf linkerkant/rechterkant"</item> <item>"Dia vanaf bovenkant/onderkant"</item> <item>"Willekeurige selectie"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Diavoorstelling herhalen"</string> <string name="pref_gallery_slideshow_repeat_summary">"Diavoorstelling meerdere keren afspelen"</string> <string name="pref_gallery_slideshow_shuffle_title">"Dia\'s in willekeurige volgorde weergeven"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Foto\'s in willekeurige volgorde weergeven"</string> <string name="pref_camera_recordlocation_title">"Locatie opslaan in foto\'s"</string> <string name="pref_camera_recordlocation_summary">"Locatie vastleggen in de gegevens van de foto"</string> <string name="pref_camera_videoquality_category">"Videokwaliteit"</string> <string name="pref_camera_videoquality_title">"Videokwaliteit selecteren"</string> <string name="pref_camera_videoquality_entry_0">"Laag (voor MMS-berichten)"</string> <string name="pref_camera_videoquality_entry_1">"Hoog (voor SD-kaart)"</string> <string name="pref_camera_videoquality_dialogtitle">"Videokwaliteit"</string> <string name="camerasettings">"Instellingen"</string> <string name="image_gallery_NoImageView_text">"Geen medium gevonden."</string> <string name="pref_gallery_confirm_delete_title">"Verwijderen bevestigen"</string> <string name="pref_gallery_confirm_delete_summary">"Bevestiging weergeven voordat een foto of video wordt verwijderd"</string> <string name="details_panel_title">"Details"</string> <string name="details_file_size">"Bestandsgrootte:"</string> <string name="details_image_resolution">"Resolutie:"</string> <string name="details_duration">"Duur:"</string> <string name="details_date_taken">"Gemaakt op:"</string> <string name="details_frame_rate">"Framesnelheid:"</string> <string name="details_bit_rate">"Bitsnelheid:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Indeling:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opties voor foto\'s"</string> <string name="video_context_menu_header">"Video-opties"</string> <string name="multiface_crop_help">"Tik op een gezicht om te beginnen."</string> <string name="photos_gallery_title">"Galerij"</string> <string name="pick_photos_gallery_title">"Foto selecteren"</string> <string name="videos_gallery_title">"Galerij"</string> <string name="pick_videos_gallery_title">"Video selecteren"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> resterend"</string> <string name="sendImage">"Foto delen via"</string> <string name="setImage">"Foto instellen als"</string> <string name="sendVideo">"Video delen via"</string> <string name="movieviewlabel">"Films"</string> <string name="loading_video">"Video laden..."</string> <string name="spaceIsLow_title">"Er is weinig ruimte"</string> <string name="spaceIsLow_content">"Er is weinig ruimte beschikbaar op uw SD-kaart. U kunt de kwaliteitsinstelling wijzigen of items uit de galerij verwijderen."</string> <string name="resume_playing_title">"Video hervatten"</string> <string name="resume_playing_message">"Afspelen hervatten vanaf %s ?"</string> <string name="resume_playing_resume">"Afspelen hervatten"</string> <string name="resume_playing_restart">"Opnieuw starten"</string> <string name="gadget_title">"Fotolijstje"</string> <string name="file_info_title">"Bestandsinformatie:"</string> <string name="video_exceed_mms_limit">"De video die u heeft opgenomen, is te lang om via MMS te verzenden. Neem een kortere video op."</string> <string name="too_large_to_attach">"Bestand is te groot om bij te voegen."</string> </resources> diff --git a/res/values-pl/strings.xml b/res/values-pl/strings.xml index be0250e..eb14f35 100644 --- a/res/values-pl/strings.xml +++ b/res/values-pl/strings.xml @@ -1,157 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Wszystkie zdjęcia"</string> <string name="all_videos">"Wszystkie filmy"</string> <string name="camera_label">"Aparat"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> + <string name="video_camera_label">"Kamera"</string> <string name="gallery_picker_label">"Galeria"</string> <string name="gallery_camera_bucket_name">"Zdjęcia z aparatu"</string> <string name="gallery_camera_videos_bucket_name">"Filmy z aparatu"</string> <string name="switch_to_video_lable">"Przełącz na wideo"</string> <string name="switch_to_camera_lable">"Przełącz na aparat"</string> <string name="crop_label">"Przytnij zdjęcie"</string> <string name="view_label">"Wyświetl zdjęcie"</string> <string name="preferences_label">"Ustawienia aparatu"</string> <string name="wait">"Poczekaj…"</string> <string name="no_storage">"Zanim zaczniesz korzystać z aparatu fotograficznego, włóż kartę SD."</string> <string name="not_enough_space">"Karta SD jest pełna."</string> <string name="preparing_sd">"Przygotowywanie karty SD..."</string> <string name="wallpaper">"Ustawianie tapety, poczekaj…"</string> <string name="savingImage">"Trwa zapisywanie zdjęcia…"</string> <string name="runningFaceDetection">"Poczekaj…"</string> <string name="flip_orientation">"Zmień orientację"</string> <string name="settings">"Ustawienia"</string> <string name="view">"Wyświetl"</string> <string name="details">"Szczegóły"</string> <string name="rotate">"Obróć"</string> <string name="rotate_left">"Obróć w lewo"</string> <string name="rotate_right">"Obróć w prawo"</string> <string name="slide_show">"Pokaz slajdów"</string> <string name="capture_picture">"Zrób zdjęcie"</string> <string name="capture_video">"Nagraj film wideo"</string> <string name="crop_save_text">"Zapisz"</string> <string name="crop_discard_text">"Odrzuć"</string> <string name="confirm_delete_title">"Usuń"</string> <string name="confirm_delete_message">"Zdjęcie zostanie usunięte."</string> <string name="confirm_delete_video_message">"Film wideo zostanie usunięty."</string> <string name="camera_toss">"Usuń"</string> <string name="camera_gallery">"Galeria"</string> <string name="camera_share">"Prześlij"</string> <string name="camera_set">"Ustaw jako"</string> <string name="camera_play">"Odtwórz"</string> <string name="camera_attach">"Załącz"</string> <string name="camera_cancel">"Anuluj"</string> <string name="camera_crop">"Przytnij"</string> <string name="camera_tossing">"Trwa usuwanie…"</string> <string name="no_way_to_share_image">"Nie można przesłać tego zdjęcia."</string> <string name="no_way_to_share_video">"Nie można przesłać tego filmu."</string> - <!-- no translation found for video_play (5287787282508002895) --> - <skip /> + <string name="video_play">"Odtwórz"</string> <string name="camera_gallery_photos_text">"Galeria"</string> <string name="camera_pick_wallpaper">"Zdjęcia"</string> <string name="camera_setas_wallpaper">"Tapeta"</string> <string name="pref_gallery_category">"Ustawienia ogólne"</string> <string name="pref_slideshow_category">"Ustawienia pokazu slajdów"</string> <string name="pref_camera_general_settings_category">"Ustawienia ogólne"</string> <string name="pref_gallery_size_title">"Rozmiar zdjęć i filmów"</string> <string name="pref_gallery_size_summary">"Ustaw wyświetlany rozmiar zdjęć i filmów"</string> <string name="pref_gallery_size_dialogtitle">"Rozmiar"</string> <string-array name="pref_gallery_size_choices"> <item>"Duży"</item> <item>"Mały"</item> </string-array> <string name="pref_gallery_sort_title">"Kolejność sortowania"</string> <string name="pref_gallery_sort_summary">"Wybierz kolejność sortowania zdjęć i filmów"</string> <string name="pref_gallery_sort_dialogtitle">"Sortowanie zdjęć"</string> <string-array name="pref_gallery_sort_choices"> <item>"Od najnowszego"</item> <item>"Od najstarszego"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Pokaz slajdów – interwał"</string> <string name="pref_gallery_slideshow_interval_summary">"Wybierz, jak długo mają być wyświetlane poszczególne zdjęcia w pokazie slajdów"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Pokaz slajdów – interwał"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 sekundy"</item> <item>"3 sekundy"</item> <item>"4 sekundy"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Pokaz slajdów – efekty"</string> <string name="pref_gallery_slideshow_transition_summary">"Wybierz efekt używany przy przejściu z jednego zdjęcia do kolejnego"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Pokaz slajdów – efekty"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Pojawianie i znikanie"</item> <item>"Przesuwanie z lewa w prawo"</item> <item>"Przesuwanie góra-dół"</item> <item>"Wybór losowy"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Powtórz pokaz slajdów"</string> <string name="pref_gallery_slideshow_repeat_summary">"Wyświetlaj pokaz slajdów więcej niż raz"</string> <string name="pref_gallery_slideshow_shuffle_title">"Losowa kolejność"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Wyświetlaj zdjęcia w kolejności losowej"</string> <string name="pref_camera_recordlocation_title">"Zapisuj lokalizację w zdjęciach"</string> <string name="pref_camera_recordlocation_summary">"Zapisz lokalizację w danych zdjęcia"</string> <string name="pref_camera_videoquality_category">"Jakość wideo"</string> <string name="pref_camera_videoquality_title">"Wybierz jakość wideo"</string> <string name="pref_camera_videoquality_entry_0">"Niska (dla wiadomości MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Wysoka (dla karty SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Jakość wideo"</string> <string name="camerasettings">"Ustawienia"</string> <string name="image_gallery_NoImageView_text">"Brak plików."</string> <string name="pref_gallery_confirm_delete_title">"Potwierdzanie usuwania"</string> <string name="pref_gallery_confirm_delete_summary">"Wyświetl potwierdzenie przed usunięciem zdjęcia lub filmu"</string> <string name="details_panel_title">"Szczegóły"</string> <string name="details_file_size">"Rozmiar pliku:"</string> <string name="details_image_resolution">"Rozdzielczość:"</string> <string name="details_duration">"Czas trwania:"</string> <string name="details_date_taken">"Data zrobienia zdjęcia:"</string> <string name="details_frame_rate">"Szybkość klatek:"</string> <string name="details_bit_rate">"Szybkość transmisji:"</string> <string name="details_codec">"Kodek:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d ramek/s"</string> <string name="details_kbps">"%1$d Kb/s"</string> <string name="details_mbps">"%1$g Mb/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opcje zdjęć"</string> <string name="video_context_menu_header">"Opcje wideo"</string> <string name="multiface_crop_help">"Dotknij twarzy, aby rozpocząć"</string> <string name="photos_gallery_title">"Galeria"</string> <string name="pick_photos_gallery_title">"Wybierz zdjęcie"</string> <string name="videos_gallery_title">"Galeria"</string> <string name="pick_videos_gallery_title">"Wybierz film wideo"</string> <string name="loading_progress_format_string">"Pozostało <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Prześlij zdjęcie następującą drogą:"</string> <string name="setImage">"Ustaw zdjęcie jako"</string> <string name="sendVideo">"Prześlij film następującą drogą:"</string> <string name="movieviewlabel">"Filmy"</string> <string name="loading_video">"Ładowanie filmu..."</string> <string name="spaceIsLow_title">"Miejsca jest mało"</string> <string name="spaceIsLow_content">"Na karcie SD brakuje miejsca. Zmień ustawienie jakości lub usuń elementy z Galerii."</string> <string name="resume_playing_title">"Wznów film"</string> <string name="resume_playing_message">"Wznowić odtwarzanie od %s?"</string> <string name="resume_playing_resume">"Wznów odtwarzanie"</string> <string name="resume_playing_restart">"Rozpocznij"</string> <string name="gadget_title">"Ramka zdjęcia"</string> <string name="file_info_title">"Informacje o pliku:"</string> <string name="video_exceed_mms_limit">"Nagrany film wideo jest zbyt duży, aby wysłać go w wiadomości MMS. Spróbuj nagrać krótszy film wideo."</string> <string name="too_large_to_attach">"Plik jest zbyt duży do załączenia."</string> </resources> diff --git a/res/values-ru/strings.xml b/res/values-ru/strings.xml index 940dbba..ef609e3 100644 --- a/res/values-ru/strings.xml +++ b/res/values-ru/strings.xml @@ -1,157 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Все изображения"</string> <string name="all_videos">"Все видео"</string> <string name="camera_label">"Камера"</string> - <!-- no translation found for video_camera_label (2899292505526427293) --> - <skip /> + <string name="video_camera_label">"Видеокамера"</string> <string name="gallery_picker_label">"Галерея"</string> <string name="gallery_camera_bucket_name">"Фотографии с камеры"</string> <string name="gallery_camera_videos_bucket_name">"Видео с камеры"</string> <string name="switch_to_video_lable">"Перейти в режим видео"</string> <string name="switch_to_camera_lable">"Перейти в режим камеры"</string> <string name="crop_label">"Обрезать изображение"</string> <string name="view_label">"Просмотреть изображение"</string> <string name="preferences_label">"Настройки камеры"</string> <string name="wait">"Подождите…"</string> <string name="no_storage">"Перед использованием камеры вставьте карту SD."</string> <string name="not_enough_space">"Карта SD заполнена."</string> <string name="preparing_sd">"Подготовка карты SD..."</string> <string name="wallpaper">"Установка фонового рисунка, подождите…"</string> <string name="savingImage">"Идет сохранение изображения…"</string> <string name="runningFaceDetection">"Подождите…"</string> <string name="flip_orientation">"Изменить ориентацию"</string> <string name="settings">"Настройки"</string> <string name="view">"Просмотреть"</string> <string name="details">"Сведения"</string> <string name="rotate">"Повернуть"</string> <string name="rotate_left">"Повернуть налево"</string> <string name="rotate_right">"Повернуть направо"</string> <string name="slide_show">"Слайд-шоу"</string> <string name="capture_picture">"Сделать фотографию"</string> <string name="capture_video">"Снять видео"</string> <string name="crop_save_text">"Сохранить"</string> <string name="crop_discard_text">"Отменить"</string> <string name="confirm_delete_title">"Удаление"</string> <string name="confirm_delete_message">"Изображение будет удалено."</string> <string name="confirm_delete_video_message">"Видео будет удалено."</string> <string name="camera_toss">"Удаление"</string> <string name="camera_gallery">"Галерея"</string> <string name="camera_share">"Отправить"</string> <string name="camera_set">"Установить как"</string> <string name="camera_play">"Воспроизвести"</string> <string name="camera_attach">"Вложить"</string> <string name="camera_cancel">"Отмена"</string> <string name="camera_crop">"Обрезать"</string> <string name="camera_tossing">"Идет удаление…"</string> <string name="no_way_to_share_image">"Отправить это изображение нельзя."</string> <string name="no_way_to_share_video">"Отправить это видео нельзя."</string> - <!-- no translation found for video_play (5287787282508002895) --> - <skip /> + <string name="video_play">"Воспроизвести"</string> <string name="camera_gallery_photos_text">"Галерея"</string> <string name="camera_pick_wallpaper">"Изображения"</string> <string name="camera_setas_wallpaper">"Фоновый рисунок"</string> <string name="pref_gallery_category">"Общие настройки"</string> <string name="pref_slideshow_category">"Настройки слайд-шоу"</string> <string name="pref_camera_general_settings_category">"Общие настройки"</string> <string name="pref_gallery_size_title">"Отображаемый размер"</string> <string name="pref_gallery_size_summary">"Выбор отображаемого размера изображений и видео"</string> <string name="pref_gallery_size_dialogtitle">"Размер изображения"</string> <string-array name="pref_gallery_size_choices"> <item>"Крупный"</item> <item>"Мелкий"</item> </string-array> <string name="pref_gallery_sort_title">"Порядок сортировки"</string> <string name="pref_gallery_sort_summary">"Выберите порядок сортировки изображений и видео"</string> <string name="pref_gallery_sort_dialogtitle">"Сортировка изображений"</string> <string-array name="pref_gallery_sort_choices"> <item>"Начиная с новых"</item> <item>"Заканчивая новыми"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Интервал слайд-шоу"</string> <string name="pref_gallery_slideshow_interval_summary">"Выберите время отображения каждого слайда"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Интервал слайд-шоу"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 секунды"</item> <item>"3 секунды"</item> <item>"4 секунды"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Переходы слайд-шоу"</string> <string name="pref_gallery_slideshow_transition_summary">"Выберите эффект для перехода от одного слайда к другому"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Переходы слайд-шоу"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Затемнение"</item> <item>"Слайды слева направо"</item> <item>"Слайды сверху вниз"</item> <item>"Случайный выбор"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Повторить слайд-шоу"</string> <string name="pref_gallery_slideshow_repeat_summary">"Воспроизвести слайд-шоу несколько раз"</string> <string name="pref_gallery_slideshow_shuffle_title">"Перемешать слайды"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Показывать изображения в случайном порядке"</string> <string name="pref_camera_recordlocation_title">"Сохранять адрес в изображениях"</string> <string name="pref_camera_recordlocation_summary">"Записывать адрес в данные изображения"</string> <string name="pref_camera_videoquality_category">"Качество видео"</string> <string name="pref_camera_videoquality_title">"Выбор качества видео"</string> <string name="pref_camera_videoquality_entry_0">"Низкое (для MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Высокое (для карты SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Качество видео"</string> <string name="camerasettings">"Настройки"</string> <string name="image_gallery_NoImageView_text">"Нет мультимедийных материалов."</string> <string name="pref_gallery_confirm_delete_title">"Подтверждение удаления"</string> <string name="pref_gallery_confirm_delete_summary">"Запрашивать подтверждения перед удалением изображения или видео"</string> <string name="details_panel_title">"Сведения"</string> <string name="details_file_size">"Размер файла:"</string> <string name="details_image_resolution">"Разрешение:"</string> <string name="details_duration">"Продолжительность:"</string> <string name="details_date_taken">"Дата съемки:"</string> <string name="details_frame_rate">"Частота кадров:"</string> <string name="details_bit_rate">"Битрейт:"</string> <string name="details_codec">"Кодек:"</string> <string name="details_format">"Формат:"</string> <string name="details_dimension_x">"%1$d на %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d кадров/с"</string> <string name="details_kbps">"%1$d кбит/с"</string> <string name="details_mbps">"%1$g мбит/с"</string> <string name="details_ok">"ОК"</string> <string name="context_menu_header">"Параметры изображения"</string> <string name="video_context_menu_header">"Параметры видео"</string> <string name="multiface_crop_help">"Чтобы начать, выберите лицо."</string> <string name="photos_gallery_title">"Галерея"</string> <string name="pick_photos_gallery_title">"Выбор изображения"</string> <string name="videos_gallery_title">"Галерея"</string> <string name="pick_videos_gallery_title">"Выбрать видео"</string> <string name="loading_progress_format_string">"Осталось: <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Отправить изображение при помощи"</string> <string name="setImage">"Установить изображение как"</string> <string name="sendVideo">"Отправить видео при помощи"</string> <string name="movieviewlabel">"Фильмы"</string> <string name="loading_video">"Идет загрузка видео…"</string> <string name="spaceIsLow_title">"Осталось мало места"</string> <string name="spaceIsLow_content">"Место на карте SD заканчивается. Измените настройки качества или удалите элементы из галереи."</string> <string name="resume_playing_title">"Продолжение просмотра видео"</string> <string name="resume_playing_message">"Продолжить воспроизведение с %s ?"</string> <string name="resume_playing_resume">"Продолжить воспроизведение"</string> <string name="resume_playing_restart">"Начать с начала"</string> <string name="gadget_title">"Рамка фотографии"</string> <string name="file_info_title">"Сведения о файле:"</string> <string name="video_exceed_mms_limit">"Записанное видео имеет слишком большой размер для отправки в MMS. Запишите более короткий ролик."</string> <string name="too_large_to_attach">"Файл имеет слишком большой размер и не может быть вложен."</string> </resources>
brunsky/WS171-packages-apps-Camera
d5c7566d97f6a267c6fbad8d04059cf676a04837
AI 144556: Pick up today's modified translations.
diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml index bbbdbc2..65abe35 100644 --- a/res/values-es/strings.xml +++ b/res/values-es/strings.xml @@ -1,157 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Todas las imágenes"</string> <string name="all_videos">"Todos los vídeos"</string> <string name="camera_label">"Cámara"</string> <!-- no translation found for video_camera_label (2899292505526427293) --> <skip /> <string name="gallery_picker_label">"Galería"</string> <string name="gallery_camera_bucket_name">"Imágenes de cámara"</string> <string name="gallery_camera_videos_bucket_name">"Vídeos de cámara"</string> <string name="switch_to_video_lable">"Cambiar a vídeo"</string> <string name="switch_to_camera_lable">"Cambiar a cámara"</string> <string name="crop_label">"Recortar imagen"</string> <string name="view_label">"Ver imagen"</string> <string name="preferences_label">"Configuración de cámara"</string> <string name="wait">"Por favor, espera..."</string> <string name="no_storage">"Antes de utilizar la cámara, debes insertar una tarjeta SD."</string> <string name="not_enough_space">"La tarjeta SD está llena."</string> <string name="preparing_sd">"Preparando tarjeta SD…"</string> - <string name="wallpaper">"Estableciendo fondo de pantalla; por favor, espera..."</string> + <string name="wallpaper">"Estableciendo fondo de pantalla..."</string> <string name="savingImage">"Guardando imagen..."</string> <string name="runningFaceDetection">"Por favor, espera..."</string> <string name="flip_orientation">"Cambiar orientación"</string> <string name="settings">"Ajustes"</string> <string name="view">"Ver"</string> <string name="details">"Detalles"</string> <string name="rotate">"Girar"</string> <string name="rotate_left">"Girar a la izquierda"</string> <string name="rotate_right">"Girar a la derecha"</string> <string name="slide_show">"Presentación"</string> <string name="capture_picture">"Capturar imagen"</string> <string name="capture_video">"Capturar vídeo"</string> <string name="crop_save_text">"Guardar"</string> <string name="crop_discard_text">"Descartar"</string> <string name="confirm_delete_title">"Suprimir"</string> <string name="confirm_delete_message">"Se eliminará la imagen."</string> <string name="confirm_delete_video_message">"Se eliminará el vídeo."</string> <string name="camera_toss">"Suprimir"</string> <string name="camera_gallery">"Galería"</string> <string name="camera_share">"Compartir"</string> <string name="camera_set">"Establecer como"</string> <string name="camera_play">"Reproducir"</string> <string name="camera_attach">"Adjuntar"</string> <string name="camera_cancel">"Cancelar"</string> <string name="camera_crop">"Recortar"</string> <string name="camera_tossing">"Eliminando..."</string> <string name="no_way_to_share_image">"Esta imagen no se puede compartir."</string> <string name="no_way_to_share_video">"Este vídeo no se puede compartir."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galería"</string> <string name="camera_pick_wallpaper">"Imágenes"</string> <string name="camera_setas_wallpaper">"Fondo de pantalla"</string> <string name="pref_gallery_category">"Configuración general"</string> <string name="pref_slideshow_category">"Configuración de presentación"</string> <string name="pref_camera_general_settings_category">"Configuración general"</string> <string name="pref_gallery_size_title">"Tamaño de visualización"</string> <string name="pref_gallery_size_summary">"Seleccionar el tamaño de visualización de imágenes y vídeos"</string> <string name="pref_gallery_size_dialogtitle">"Tamaño de imagen"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Pequeña"</item> </string-array> <string name="pref_gallery_sort_title">"Orden"</string> <string name="pref_gallery_sort_summary">"Seleccionar el orden de imágenes y vídeos"</string> <string name="pref_gallery_sort_dialogtitle">"Ordenación de imágenes"</string> <string-array name="pref_gallery_sort_choices"> <item>"Más recientes primero"</item> <item>"Más recientes al final"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalo de presentación"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleccionar la duración de cada diapositiva"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo de presentación"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 segundos"</item> <item>"3 segundos"</item> <item>"4 segundos"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transición de diapositivas"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleccionar el efecto que se aplicará al pasar de una diapositiva a otra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transición de diapositivas"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Fundido de entrada y salida"</item> <item>"Transición de izquierda a derecha"</item> <item>"Transición de arriba a abajo"</item> <item>"Selección aleatoria"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Repetir presentación"</string> <string name="pref_gallery_slideshow_repeat_summary">"Mostrar presentación más de una vez"</string> <string name="pref_gallery_slideshow_shuffle_title">"Reproducir diapositivas en orden aleatorio"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imágenes en orden aleatorio"</string> <string name="pref_camera_recordlocation_title">"Almacenar ubicación en imágenes"</string> <string name="pref_camera_recordlocation_summary">"Registrar ubicación en datos de imagen"</string> <string name="pref_camera_videoquality_category">"Calidad de vídeo"</string> <string name="pref_camera_videoquality_title">"Seleccionar calidad de vídeo"</string> <string name="pref_camera_videoquality_entry_0">"Baja (para mensajes MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (para tarjeta SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Calidad de vídeo"</string> <string name="camerasettings">"Ajustes"</string> <string name="image_gallery_NoImageView_text">"No se ha encontrado ningún elemento."</string> <string name="pref_gallery_confirm_delete_title">"Confirmar eliminaciones"</string> <string name="pref_gallery_confirm_delete_summary">"Mostrar confirmación antes de eliminar una imagen o un vídeo"</string> <string name="details_panel_title">"Detalles"</string> <string name="details_file_size">"Tamaño de archivo:"</string> <string name="details_image_resolution">"Resolución:"</string> <string name="details_duration">"Duración:"</string> <string name="details_date_taken">"Fecha de realización:"</string> <string name="details_frame_rate">"Frecuencia de imagen:"</string> <string name="details_bit_rate">"Velocidad binaria:"</string> <string name="details_codec">"Códec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"Aceptar"</string> <string name="context_menu_header">"Opciones de imagen"</string> <string name="video_context_menu_header">"Opciones de vídeo"</string> <string name="multiface_crop_help">"Selecciona una cara para empezar."</string> <string name="photos_gallery_title">"Galería"</string> <string name="pick_photos_gallery_title">"Seleccionar imagen"</string> <string name="videos_gallery_title">"Galería"</string> <string name="pick_videos_gallery_title">"Seleccionar vídeo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> <string name="sendImage">"Compartir imagen por"</string> <string name="setImage">"Establecer imagen como"</string> <string name="sendVideo">"Compartir vídeo a través de"</string> <string name="movieviewlabel">"Películas"</string> <string name="loading_video">"Cargando vídeo…"</string> <string name="spaceIsLow_title">"Poco espacio"</string> <string name="spaceIsLow_content">"No queda espacio en la tarjeta SD. Cambia la configuración de calidad o elimina elementos de la galería."</string> <string name="resume_playing_title">"Reanudar vídeo"</string> <string name="resume_playing_message">"Reanudar reproducción a partir de %s ?"</string> <string name="resume_playing_resume">"Reanudar reproducción"</string> <string name="resume_playing_restart">"Volver a reproducir"</string> <string name="gadget_title">"Picture frame"</string> <string name="file_info_title">"Información de archivo:"</string> <string name="video_exceed_mms_limit">"El vídeo que has grabado es demasiado grande para enviarlo a través de MMS. Intenta grabar un vídeo de menor duración."</string> <string name="too_large_to_attach">"El archivo es demasiado grande para adjuntarlo."</string> </resources> diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml index ebc5309..ba80031 100644 --- a/res/values-ja/strings.xml +++ b/res/values-ja/strings.xml @@ -1,157 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"すべての写真"</string> <string name="all_videos">"すべての動画"</string> <string name="camera_label">"カメラ"</string> <!-- no translation found for video_camera_label (2899292505526427293) --> <skip /> <string name="gallery_picker_label">"ギャラリー"</string> <string name="gallery_camera_bucket_name">"カメラ (写真)"</string> <string name="gallery_camera_videos_bucket_name">"カメラ (動画)"</string> <string name="switch_to_video_lable">"ムービーに切替"</string> <string name="switch_to_camera_lable">"写真に切替"</string> <string name="crop_label">"トリミング"</string> <string name="view_label">"画像を表示"</string> <string name="preferences_label">"カメラ設定"</string> <string name="wait">"お待ちください..."</string> <string name="no_storage">"カメラを使用する前にSDカードを挿入してください。"</string> <string name="not_enough_space">"SDカードがいっぱいです。"</string> <string name="preparing_sd">"SDカードの準備中..."</string> <string name="wallpaper">"壁紙を設定しています。しばらくお待ちください..."</string> <string name="savingImage">"写真を保存中..."</string> <string name="runningFaceDetection">"お待ちください..."</string> <string name="flip_orientation">"画面の向きを変更"</string> <string name="settings">"設定"</string> <string name="view">"表示"</string> <string name="details">"詳細"</string> <string name="rotate">"回転"</string> <string name="rotate_left">"左に回転"</string> <string name="rotate_right">"右に回転"</string> <string name="slide_show">"スライドショー"</string> <string name="capture_picture">"写真撮影"</string> <string name="capture_video">"ムービー撮影"</string> <string name="crop_save_text">"保存"</string> - <string name="crop_discard_text">"破棄"</string> + <string name="crop_discard_text">"キャンセル"</string> <string name="confirm_delete_title">"削除"</string> <string name="confirm_delete_message">"画像を削除します。"</string> <string name="confirm_delete_video_message">"動画を削除します。"</string> <string name="camera_toss">"削除"</string> <string name="camera_gallery">"ギャラリー"</string> <string name="camera_share">"共有"</string> <string name="camera_set">"連絡先等に設定する"</string> <string name="camera_play">"再生"</string> <string name="camera_attach">"添付"</string> <string name="camera_cancel">"キャンセル"</string> <string name="camera_crop">"トリミング"</string> <string name="camera_tossing">"削除中..."</string> <string name="no_way_to_share_image">"この画像は共有できません。"</string> <string name="no_way_to_share_video">"この動画は共有できません。"</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"ギャラリー"</string> <string name="camera_pick_wallpaper">"画像"</string> <string name="camera_setas_wallpaper">"壁紙"</string> <string name="pref_gallery_category">"全般設定"</string> <string name="pref_slideshow_category">"スライドショー設定"</string> <string name="pref_camera_general_settings_category">"全般設定"</string> <string name="pref_gallery_size_title">"表示サイズ"</string> <string name="pref_gallery_size_summary">"画像や動画の表示サイズ"</string> <string name="pref_gallery_size_dialogtitle">"画像サイズ"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"表示順序"</string> <string name="pref_gallery_sort_summary">"画像や動画の表示順序を選択"</string> <string name="pref_gallery_sort_dialogtitle">"画像並べ替え"</string> <string-array name="pref_gallery_sort_choices"> <item>"日付の新しい順"</item> <item>"日付の古い順"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"スライドの再生間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"各スライドの表示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"スライドの再生間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2秒"</item> <item>"3秒"</item> <item>"4秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"スライド切り替え"</string> <string name="pref_gallery_slideshow_transition_summary">"スライドが切り替わるときの効果"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"スライド切り替え"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"フェードイン&amp;アウト"</item> <item>"左右にスライド"</item> <item>"上下にスライド"</item> <item>"ランダムに選択"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"リピート再生"</string> <string name="pref_gallery_slideshow_repeat_summary">"スライドショーを繰り返し再生"</string> <string name="pref_gallery_slideshow_shuffle_title">"スライドのシャッフル"</string> <string name="pref_gallery_slideshow_shuffle_summary">"順不同に表示する"</string> <string name="pref_camera_recordlocation_title">"位置情報を写真に記録する"</string> <string name="pref_camera_recordlocation_summary">"位置情報を写真データに記録する"</string> <string name="pref_camera_videoquality_category">"動画のクオリティ"</string> <string name="pref_camera_videoquality_title">"動画の画質を選択"</string> <string name="pref_camera_videoquality_entry_0">"低 (MMSメッセージ向け)"</string> <string name="pref_camera_videoquality_entry_1">"高 (SDカード向け)"</string> <string name="pref_camera_videoquality_dialogtitle">"動画のクオリティ"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"メディアが見つかりません。"</string> <string name="pref_gallery_confirm_delete_title">"削除確認"</string> <string name="pref_gallery_confirm_delete_summary">"画像や動画を削除する前に確認する"</string> <string name="details_panel_title">"詳細"</string> <string name="details_file_size">"ファイルサイズ:"</string> <string name="details_image_resolution">"解像度:"</string> <string name="details_duration">"再生時間:"</string> <string name="details_date_taken">"撮影日:"</string> <string name="details_frame_rate">"フレームレート:"</string> <string name="details_bit_rate">"ビットレート:"</string> <string name="details_codec">"コーデック:"</string> <string name="details_format">"形式:"</string> <string name="details_dimension_x">"%1$dx%2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$dfps"</string> <string name="details_kbps">"%1$dKbps"</string> <string name="details_mbps">"%1$gMbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"画像オプション"</string> <string name="video_context_menu_header">"動画オプション"</string> <string name="multiface_crop_help">"顔をタップして開始します。"</string> <string name="photos_gallery_title">"ギャラリー"</string> <string name="pick_photos_gallery_title">"画像を選択"</string> <string name="videos_gallery_title">"ギャラリー"</string> <string name="pick_videos_gallery_title">"動画を選択"</string> <string name="loading_progress_format_string">"残り<xliff:g id="COUNTER">%d</xliff:g>件"</string> <string name="sendImage">"画像を共有:"</string> <string name="setImage">"設定タイプ:"</string> <string name="sendVideo">"動画を共有"</string> <string name="movieviewlabel">"映画"</string> <string name="loading_video">"動画を読み込み中..."</string> <string name="spaceIsLow_title">"空き容量が残り少なくなっています"</string> <string name="spaceIsLow_content">"SDカードの容量が足りません。クオリティ設定を変更するか、ギャラリーからアイテムを削除してください。"</string> <string name="resume_playing_title">"動画の再開"</string> <string name="resume_playing_message">"再生を%sから再開しますか?"</string> <string name="resume_playing_resume">"再生を再開"</string> <string name="resume_playing_restart">"最初から再生"</string> <string name="gadget_title">"写真フレーム"</string> <string name="file_info_title">"ファイル情報:"</string> <string name="video_exceed_mms_limit">"録画した動画のサイズが大きすぎるため送信できません。録画時間を短縮してみてください。"</string> <string name="too_large_to_attach">"添付ファイルが大きすぎます。"</string> </resources>
brunsky/WS171-packages-apps-Camera
5a9e3f016c3b2a2ad48908ad87a4b960dfee5736
AI 144335: Import US Spanish translations, and a few Japanese changes.
diff --git a/res/values-es-rUS/arrays.xml b/res/values-es-rUS/arrays.xml new file mode 100644 index 0000000..dfbf090 --- /dev/null +++ b/res/values-es-rUS/arrays.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <!-- no translation found for pref_camera_videoquality_entries:0 (4155278146225809483) --> + <!-- no translation found for pref_camera_videoquality_entries:1 (2439895494739176281) --> + <string-array name="pref_camera_videoquality_entryvalues"> + <item>"0"</item> + <item>"1"</item> + </string-array> +</resources> diff --git a/res/values-es-rUS/strings.xml b/res/values-es-rUS/strings.xml new file mode 100644 index 0000000..7916de9 --- /dev/null +++ b/res/values-es-rUS/strings.xml @@ -0,0 +1,157 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2009 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<resources xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <string name="all_images">"Todas las imágenes"</string> + <string name="all_videos">"Todos los videos"</string> + <string name="camera_label">"Cámara"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> + <string name="gallery_picker_label">"Galería"</string> + <string name="gallery_camera_bucket_name">"Imágenes de la cámara"</string> + <string name="gallery_camera_videos_bucket_name">"Videos de la cámara"</string> + <string name="switch_to_video_lable">"Cambiar a video"</string> + <string name="switch_to_camera_lable">"Cambiar a cámara"</string> + <string name="crop_label">"Cortar la imagen"</string> + <string name="view_label">"Ver imagen"</string> + <string name="preferences_label">"Configuración de cámara"</string> + <string name="wait">"Espera, por favor..."</string> + <string name="no_storage">"Inserta una tarjeta SD antes de utilizar la cámara."</string> + <string name="not_enough_space">"Tu tarjeta SD está llena."</string> + <string name="preparing_sd">"Preparando la tarjeta SD..."</string> + <string name="wallpaper">"Configurando papel tapiz. Espera, por favor..."</string> + <string name="savingImage">"Guardando imagen..."</string> + <string name="runningFaceDetection">"Espera, por favor..."</string> + <string name="flip_orientation">"Girar la orientación"</string> + <string name="settings">"Configuración"</string> + <string name="view">"Ver"</string> + <string name="details">"Detalles"</string> + <string name="rotate">"Rotar"</string> + <string name="rotate_left">"Rotar hacia la izquierda"</string> + <string name="rotate_right">"Rotar hacia la derecha"</string> + <string name="slide_show">"Presentación de diapositivas"</string> + <string name="capture_picture">"Capturar imagen"</string> + <string name="capture_video">"Capturar video"</string> + <string name="crop_save_text">"Guardar"</string> + <string name="crop_discard_text">"Eliminar"</string> + <string name="confirm_delete_title">"Eliminar"</string> + <string name="confirm_delete_message">"La imagen se eliminará."</string> + <string name="confirm_delete_video_message">"El video se eliminará."</string> + <string name="camera_toss">"Eliminar"</string> + <string name="camera_gallery">"Galería"</string> + <string name="camera_share">"Compartir"</string> + <string name="camera_set">"Definir como"</string> + <string name="camera_play">"Reproducir"</string> + <string name="camera_attach">"Adjuntar"</string> + <string name="camera_cancel">"Cancelar"</string> + <string name="camera_crop">"Cortar"</string> + <string name="camera_tossing">"Eliminando..."</string> + <string name="no_way_to_share_image">"Esta imagen no se puede compartir."</string> + <string name="no_way_to_share_video">"Este video no se puede compartir."</string> + <!-- no translation found for video_play (5287787282508002895) --> + <skip /> + <string name="camera_gallery_photos_text">"Galería"</string> + <string name="camera_pick_wallpaper">"Imágenes"</string> + <string name="camera_setas_wallpaper">"Papel tapiz"</string> + <string name="pref_gallery_category">"Configuración general"</string> + <string name="pref_slideshow_category">"Configuración de presentación de diapositivas"</string> + <string name="pref_camera_general_settings_category">"Configuración general"</string> + <string name="pref_gallery_size_title">"Visualizar tamaño"</string> + <string name="pref_gallery_size_summary">"Seleccionar el tamaño de visualización de imágenes y videos"</string> + <string name="pref_gallery_size_dialogtitle">"Tamaño de imagen"</string> + <string-array name="pref_gallery_size_choices"> + <item>"Grande"</item> + <item>"Pequeño"</item> + </string-array> + <string name="pref_gallery_sort_title">"Ordenar"</string> + <string name="pref_gallery_sort_summary">"Selecciona el orden de imágenes y videos"</string> + <string name="pref_gallery_sort_dialogtitle">"Orden de imágenes"</string> + <string-array name="pref_gallery_sort_choices"> + <item>"Lo más nuevo primero"</item> + <item>"Lo más nuevo al final"</item> + </string-array> + <string name="pref_gallery_slideshow_interval_title">"Intervalo de la presentación"</string> + <string name="pref_gallery_slideshow_interval_summary">"Seleccionar cuánto tiempo se visualizará cada diapositiva en la presentación"</string> + <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo de la presentación"</string> + <string-array name="pref_gallery_slideshow_interval_choices"> + <item>"2 segundos"</item> + <item>"3 segundos"</item> + <item>"4 segundos"</item> + </string-array> + <string name="pref_gallery_slideshow_transition_title">"Transición de la presentación de diapositivas"</string> + <string name="pref_gallery_slideshow_transition_summary">"Seleccionar el efecto utilizado al pasar de una diapositiva a otra"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"Transición de la presentación de diapositivas"</string> + <string-array name="pref_gallery_slideshow_transition_choices"> + <item>"Fundido de entrada/salida"</item> + <item>"Deslizar hacia la izquierda/derecha"</item> + <item>"Deslizar hacia arriba/abajo"</item> + <item>"Selección aleatoria"</item> + </string-array> + <string name="pref_gallery_slideshow_repeat_title">"Repetir la presentación"</string> + <string name="pref_gallery_slideshow_repeat_summary">"Reproducir la presentación de diapositivas más de una vez"</string> + <string name="pref_gallery_slideshow_shuffle_title">"Arrastrar diapositivas"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imágenes en orden aleatorio"</string> + <string name="pref_camera_recordlocation_title">"Almacenar ubicación en imágenes"</string> + <string name="pref_camera_recordlocation_summary">"Grabar la ubicación en los datos de la imagen"</string> + <string name="pref_camera_videoquality_category">"Calidad del video"</string> + <string name="pref_camera_videoquality_title">"Seleccionar calidad de video"</string> + <string name="pref_camera_videoquality_entry_0">"Bajo (para mensajes MMS)"</string> + <string name="pref_camera_videoquality_entry_1">"Alta (para tarjeta SD)"</string> + <string name="pref_camera_videoquality_dialogtitle">"Calidad del video"</string> + <string name="camerasettings">"Configuración"</string> + <string name="image_gallery_NoImageView_text">"No se han encontrado medios."</string> + <string name="pref_gallery_confirm_delete_title">"Confirmar eliminaciones"</string> + <string name="pref_gallery_confirm_delete_summary">"Mostrar configuración antes de eliminar una imagen o un video"</string> + <string name="details_panel_title">"Detalles"</string> + <string name="details_file_size">"Tamaño de archivo:"</string> + <string name="details_image_resolution">"Resolución:"</string> + <string name="details_duration">"Duración:"</string> + <string name="details_date_taken">"Fecha:"</string> + <string name="details_frame_rate">"Frecuencia de visualización:"</string> + <string name="details_bit_rate">"Frecuencia de bits:"</string> + <string name="details_codec">"Códec:"</string> + <string name="details_format">"Formato:"</string> + <string name="details_dimension_x">"%1$d x %2$d"</string> + <string name="details_ms">"%1$02d:%2$02d"</string> + <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> + <string name="details_fps">"%1$d fps"</string> + <string name="details_kbps">"%1$d Kbps"</string> + <string name="details_mbps">"%1$g Mbps"</string> + <string name="details_ok">"Aceptar"</string> + <string name="context_menu_header">"Opciones de imagen"</string> + <string name="video_context_menu_header">"Opciones de video"</string> + <string name="multiface_crop_help">"Golpea una cara para comenzar."</string> + <string name="photos_gallery_title">"Galería"</string> + <string name="pick_photos_gallery_title">"Seleccionar imagen"</string> + <string name="videos_gallery_title">"Galería"</string> + <string name="pick_videos_gallery_title">"Seleccionar video"</string> + <string name="loading_progress_format_string">"Quedan <xliff:g id="COUNTER">%d</xliff:g>"</string> + <string name="sendImage">"Compartir imagen mediante"</string> + <string name="setImage">"Definir imagen como"</string> + <string name="sendVideo">"Compartir video mediante"</string> + <string name="movieviewlabel">"Películas"</string> + <string name="loading_video">"Cargando el video..."</string> + <string name="spaceIsLow_title">"El espacio es pequeño"</string> + <string name="spaceIsLow_content">"Tu tarjeta SD se está quedando sin espacio. Cambia la configuración de calidad o elimina elementos de la galería."</string> + <string name="resume_playing_title">"Retomar video"</string> + <string name="resume_playing_message">"¿Deseas retomar la reproducción desde %s?"</string> + <string name="resume_playing_resume">"Retomar la reproducción"</string> + <string name="resume_playing_restart">"Empezar de nuevo"</string> + <string name="gadget_title">"Marco de imagen"</string> + <string name="file_info_title">"Información del archivo:"</string> + <string name="video_exceed_mms_limit">"El video que has grabado es demasiado grande para enviarlo por MMS. Intenta grabar uno más corto."</string> + <string name="too_large_to_attach">"El archivo es demasiado grande para adjuntarlo."</string> +</resources> diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml index 2f183e2..ebc5309 100644 --- a/res/values-ja/strings.xml +++ b/res/values-ja/strings.xml @@ -1,157 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"すべての写真"</string> <string name="all_videos">"すべての動画"</string> <string name="camera_label">"カメラ"</string> <!-- no translation found for video_camera_label (2899292505526427293) --> <skip /> <string name="gallery_picker_label">"ギャラリー"</string> <string name="gallery_camera_bucket_name">"カメラ (写真)"</string> <string name="gallery_camera_videos_bucket_name">"カメラ (動画)"</string> <string name="switch_to_video_lable">"ムービーに切替"</string> <string name="switch_to_camera_lable">"写真に切替"</string> <string name="crop_label">"トリミング"</string> <string name="view_label">"画像を表示"</string> <string name="preferences_label">"カメラ設定"</string> <string name="wait">"お待ちください..."</string> <string name="no_storage">"カメラを使用する前にSDカードを挿入してください。"</string> <string name="not_enough_space">"SDカードがいっぱいです。"</string> <string name="preparing_sd">"SDカードの準備中..."</string> <string name="wallpaper">"壁紙を設定しています。しばらくお待ちください..."</string> <string name="savingImage">"写真を保存中..."</string> <string name="runningFaceDetection">"お待ちください..."</string> <string name="flip_orientation">"画面の向きを変更"</string> <string name="settings">"設定"</string> <string name="view">"表示"</string> <string name="details">"詳細"</string> <string name="rotate">"回転"</string> <string name="rotate_left">"左に回転"</string> <string name="rotate_right">"右に回転"</string> <string name="slide_show">"スライドショー"</string> <string name="capture_picture">"写真撮影"</string> <string name="capture_video">"ムービー撮影"</string> <string name="crop_save_text">"保存"</string> <string name="crop_discard_text">"破棄"</string> <string name="confirm_delete_title">"削除"</string> <string name="confirm_delete_message">"画像を削除します。"</string> <string name="confirm_delete_video_message">"動画を削除します。"</string> <string name="camera_toss">"削除"</string> <string name="camera_gallery">"ギャラリー"</string> <string name="camera_share">"共有"</string> - <string name="camera_set">"設定"</string> + <string name="camera_set">"連絡先等に設定する"</string> <string name="camera_play">"再生"</string> <string name="camera_attach">"添付"</string> <string name="camera_cancel">"キャンセル"</string> <string name="camera_crop">"トリミング"</string> <string name="camera_tossing">"削除中..."</string> <string name="no_way_to_share_image">"この画像は共有できません。"</string> <string name="no_way_to_share_video">"この動画は共有できません。"</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"ギャラリー"</string> <string name="camera_pick_wallpaper">"画像"</string> <string name="camera_setas_wallpaper">"壁紙"</string> <string name="pref_gallery_category">"全般設定"</string> <string name="pref_slideshow_category">"スライドショー設定"</string> <string name="pref_camera_general_settings_category">"全般設定"</string> <string name="pref_gallery_size_title">"表示サイズ"</string> - <string name="pref_gallery_size_summary">"写真と動画の表示サイズを選択"</string> + <string name="pref_gallery_size_summary">"画像や動画の表示サイズ"</string> <string name="pref_gallery_size_dialogtitle">"画像サイズ"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> - <string name="pref_gallery_sort_title">"並び替え順"</string> - <string name="pref_gallery_sort_summary">"画像と動画の表示順序を選択"</string> + <string name="pref_gallery_sort_title">"表示順序"</string> + <string name="pref_gallery_sort_summary">"画像や動画の表示順序を選択"</string> <string name="pref_gallery_sort_dialogtitle">"画像並べ替え"</string> <string-array name="pref_gallery_sort_choices"> <item>"日付の新しい順"</item> <item>"日付の古い順"</item> </string-array> - <string name="pref_gallery_slideshow_interval_title">"スライドショーの間隔"</string> + <string name="pref_gallery_slideshow_interval_title">"スライドの再生間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"各スライドの表示時間"</string> - <string name="pref_gallery_slideshow_interval_dialogtitle">"スライドショーの間隔"</string> + <string name="pref_gallery_slideshow_interval_dialogtitle">"スライドの再生間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2秒"</item> <item>"3秒"</item> <item>"4秒"</item> </string-array> - <string name="pref_gallery_slideshow_transition_title">"スライドショーのトランジション"</string> - <string name="pref_gallery_slideshow_transition_summary">"スライドが切り替わるときの効果を選択"</string> - <string name="pref_gallery_slideshow_transition_dialogtitle">"スライドショーのトランジション"</string> + <string name="pref_gallery_slideshow_transition_title">"スライド切り替え"</string> + <string name="pref_gallery_slideshow_transition_summary">"スライドが切り替わるときの効果"</string> + <string name="pref_gallery_slideshow_transition_dialogtitle">"スライド切り替え"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"フェードイン&amp;アウト"</item> <item>"左右にスライド"</item> <item>"上下にスライド"</item> <item>"ランダムに選択"</item> </string-array> - <string name="pref_gallery_slideshow_repeat_title">"スライドショーを繰り返す"</string> - <string name="pref_gallery_slideshow_repeat_summary">"スライドショーを繰り返す"</string> + <string name="pref_gallery_slideshow_repeat_title">"リピート再生"</string> + <string name="pref_gallery_slideshow_repeat_summary">"スライドショーを繰り返し再生"</string> <string name="pref_gallery_slideshow_shuffle_title">"スライドのシャッフル"</string> - <string name="pref_gallery_slideshow_shuffle_summary">"画像をランダムに表示する"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"順不同に表示する"</string> <string name="pref_camera_recordlocation_title">"位置情報を写真に記録する"</string> <string name="pref_camera_recordlocation_summary">"位置情報を写真データに記録する"</string> <string name="pref_camera_videoquality_category">"動画のクオリティ"</string> <string name="pref_camera_videoquality_title">"動画の画質を選択"</string> <string name="pref_camera_videoquality_entry_0">"低 (MMSメッセージ向け)"</string> <string name="pref_camera_videoquality_entry_1">"高 (SDカード向け)"</string> <string name="pref_camera_videoquality_dialogtitle">"動画のクオリティ"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"メディアが見つかりません。"</string> <string name="pref_gallery_confirm_delete_title">"削除確認"</string> - <string name="pref_gallery_confirm_delete_summary">"画像や動画を削除する前に確認メッセージを表示"</string> + <string name="pref_gallery_confirm_delete_summary">"画像や動画を削除する前に確認する"</string> <string name="details_panel_title">"詳細"</string> <string name="details_file_size">"ファイルサイズ:"</string> <string name="details_image_resolution">"解像度:"</string> <string name="details_duration">"再生時間:"</string> <string name="details_date_taken">"撮影日:"</string> <string name="details_frame_rate">"フレームレート:"</string> <string name="details_bit_rate">"ビットレート:"</string> <string name="details_codec">"コーデック:"</string> <string name="details_format">"形式:"</string> <string name="details_dimension_x">"%1$dx%2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$dfps"</string> <string name="details_kbps">"%1$dKbps"</string> <string name="details_mbps">"%1$gMbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"画像オプション"</string> <string name="video_context_menu_header">"動画オプション"</string> <string name="multiface_crop_help">"顔をタップして開始します。"</string> <string name="photos_gallery_title">"ギャラリー"</string> <string name="pick_photos_gallery_title">"画像を選択"</string> <string name="videos_gallery_title">"ギャラリー"</string> <string name="pick_videos_gallery_title">"動画を選択"</string> <string name="loading_progress_format_string">"残り<xliff:g id="COUNTER">%d</xliff:g>件"</string> <string name="sendImage">"画像を共有:"</string> <string name="setImage">"設定タイプ:"</string> <string name="sendVideo">"動画を共有"</string> <string name="movieviewlabel">"映画"</string> <string name="loading_video">"動画を読み込み中..."</string> <string name="spaceIsLow_title">"空き容量が残り少なくなっています"</string> <string name="spaceIsLow_content">"SDカードの容量が足りません。クオリティ設定を変更するか、ギャラリーからアイテムを削除してください。"</string> <string name="resume_playing_title">"動画の再開"</string> <string name="resume_playing_message">"再生を%sから再開しますか?"</string> <string name="resume_playing_resume">"再生を再開"</string> <string name="resume_playing_restart">"最初から再生"</string> <string name="gadget_title">"写真フレーム"</string> <string name="file_info_title">"ファイル情報:"</string> <string name="video_exceed_mms_limit">"録画した動画のサイズが大きすぎるため送信できません。録画時間を短縮してみてください。"</string> <string name="too_large_to_attach">"添付ファイルが大きすぎます。"</string> </resources>
brunsky/WS171-packages-apps-Camera
d5e3b4765502cd917c95f2d441fd02d2bdadb0e4
AI 143861: Automated g4 rollback of changelist 143772. *** Reason for rollback *** Revert temporary change for testing. *** Original change description *** Remove camcorder icon from launcher. This is a temporary measure for monkey testing purposes.
diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 5184057..8c79f8c 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,222 +1,229 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.camera" android:sharedUserId="android.media"> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.SET_WALLPAPER" /> <!-- Needed by the ZoomRingController to set the bit saying we've already shown the tutorial toast. --> <uses-permission android:name="android.permission.WRITE_SETTINGS"/> <application android:icon="@drawable/ic_launcher_camera" android:label="@string/camera_label" android:taskAffinity=""> <service android:name="UploadService" android:process="android.process.media" /> <receiver android:name="CameraButtonIntentReceiver"> <intent-filter> <action android:name="android.intent.action.CAMERA_BUTTON"/> </intent-filter> </receiver> <activity android:name="Camera" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" android:screenOrientation="landscape" android:clearTaskOnLaunch="true" android:taskAffinity="android.task.camera"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.media.action.IMAGE_CAPTURE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.media.action.STILL_IMAGE_CAMERA" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="VideoCamera" + android:label="@string/video_camera_label" android:configChanges="orientation|keyboardHidden" + android:icon="@drawable/ic_launcher_video_camera" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" android:screenOrientation="landscape" android:clearTaskOnLaunch="true" - android:taskAffinity="android.task.camera"> + android:taskAffinity="android.task.videocamera"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> <intent-filter> <action android:name="android.media.action.VIDEO_CAMERA" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.media.action.VIDEO_CAPTURE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="GalleryPicker" android:label="@string/gallery_picker_label" android:configChanges="orientation|keyboardHidden" android:icon="@drawable/ic_launcher_gallery" android:clearTaskOnLaunch="true" android:taskAffinity="android.task.pictures"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="ImageGallery2" android:label="@string/gallery_label" android:configChanges="orientation|keyboardHidden" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/video" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.GET_CONTENT" /> <category android:name="android.intent.category.OPENABLE" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.GET_CONTENT" /> <category android:name="android.intent.category.OPENABLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> </activity> <activity android:name="CropImage" android:process=":CropImage" android:configChanges="orientation|keyboardHidden" android:label="@string/crop_label"> <intent-filter android:label="@string/crop_label"> <action android:name="com.android.camera.action.CROP" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.ALTERNATIVE" /> <category android:name="android.intent.category.SELECTED_ALTERNATIVE" /> </intent-filter> </activity> <activity android:name="ViewImage" android:label="@string/view_label" android:configChanges="orientation|keyboardHidden"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> </activity> <activity android:name="MovieView" android:label="@string/movieviewlabel" android:screenOrientation="landscape" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="rtsp" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="http" /> <data android:mimeType="video/mp4" /> <data android:mimeType="video/3gp" /> <data android:mimeType="video/3gpp" /> <data android:mimeType="video/3gpp2" /> </intent-filter> </activity> <activity android:name="CameraSettings" android:label="@string/preferences_label"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEVELOPMENT_PREFERENCE" /> </intent-filter> </activity> <activity android:name="GallerySettings" android:label="@string/preferences_label"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEVELOPMENT_PREFERENCE" /> </intent-filter> </activity> <activity android:name="SlideShow" android:label="Raw Image Viewer" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.TEST" /> </intent-filter> </activity> <activity android:name=".Wallpaper" android:label="@string/camera_setas_wallpaper" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.ATTACH_DATA" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name=".PickWallpaper" android:label="@string/camera_pick_wallpaper" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.SET_WALLPAPER" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <receiver android:name="PhotoAppWidgetProvider" android:label="@string/gadget_title"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/appwidget_info" /> </receiver> <!-- We configure a widget by asking to pick a photo, then crop it, and store the config internally --> <activity android:name="PhotoAppWidgetConfigure"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" /> </intent-filter> </activity> <!-- We also allow direct binding where the caller provides a bitmap and appWidgetId to bind. We require the permission because this changes our internal database without user confirmation. --> <activity android:name="PhotoAppWidgetBind" android:exported="true" android:theme="@android:style/Theme.NoDisplay" android:permission="android.permission.BIND_APPWIDGET" /> </application> </manifest>
brunsky/WS171-packages-apps-Camera
5a1777cc03bba321599a5e405c0bd5433c15c35b
AI 143772: Remove camcorder icon from launcher. This is a temporary measure for monkey testing purposes.
diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 8c79f8c..5184057 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,229 +1,222 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.camera" android:sharedUserId="android.media"> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.SET_WALLPAPER" /> <!-- Needed by the ZoomRingController to set the bit saying we've already shown the tutorial toast. --> <uses-permission android:name="android.permission.WRITE_SETTINGS"/> <application android:icon="@drawable/ic_launcher_camera" android:label="@string/camera_label" android:taskAffinity=""> <service android:name="UploadService" android:process="android.process.media" /> <receiver android:name="CameraButtonIntentReceiver"> <intent-filter> <action android:name="android.intent.action.CAMERA_BUTTON"/> </intent-filter> </receiver> <activity android:name="Camera" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" android:screenOrientation="landscape" android:clearTaskOnLaunch="true" android:taskAffinity="android.task.camera"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.media.action.IMAGE_CAPTURE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.media.action.STILL_IMAGE_CAMERA" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="VideoCamera" - android:label="@string/video_camera_label" android:configChanges="orientation|keyboardHidden" - android:icon="@drawable/ic_launcher_video_camera" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" android:screenOrientation="landscape" android:clearTaskOnLaunch="true" - android:taskAffinity="android.task.videocamera"> - <intent-filter> - <action android:name="android.intent.action.MAIN" /> - <category android:name="android.intent.category.DEFAULT" /> - <category android:name="android.intent.category.LAUNCHER" /> - </intent-filter> + android:taskAffinity="android.task.camera"> <intent-filter> <action android:name="android.media.action.VIDEO_CAMERA" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.media.action.VIDEO_CAPTURE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="GalleryPicker" android:label="@string/gallery_picker_label" android:configChanges="orientation|keyboardHidden" android:icon="@drawable/ic_launcher_gallery" android:clearTaskOnLaunch="true" android:taskAffinity="android.task.pictures"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="ImageGallery2" android:label="@string/gallery_label" android:configChanges="orientation|keyboardHidden" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/video" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.GET_CONTENT" /> <category android:name="android.intent.category.OPENABLE" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.GET_CONTENT" /> <category android:name="android.intent.category.OPENABLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> </activity> <activity android:name="CropImage" android:process=":CropImage" android:configChanges="orientation|keyboardHidden" android:label="@string/crop_label"> <intent-filter android:label="@string/crop_label"> <action android:name="com.android.camera.action.CROP" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.ALTERNATIVE" /> <category android:name="android.intent.category.SELECTED_ALTERNATIVE" /> </intent-filter> </activity> <activity android:name="ViewImage" android:label="@string/view_label" android:configChanges="orientation|keyboardHidden"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> </activity> <activity android:name="MovieView" android:label="@string/movieviewlabel" android:screenOrientation="landscape" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="rtsp" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="http" /> <data android:mimeType="video/mp4" /> <data android:mimeType="video/3gp" /> <data android:mimeType="video/3gpp" /> <data android:mimeType="video/3gpp2" /> </intent-filter> </activity> <activity android:name="CameraSettings" android:label="@string/preferences_label"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEVELOPMENT_PREFERENCE" /> </intent-filter> </activity> <activity android:name="GallerySettings" android:label="@string/preferences_label"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEVELOPMENT_PREFERENCE" /> </intent-filter> </activity> <activity android:name="SlideShow" android:label="Raw Image Viewer" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.TEST" /> </intent-filter> </activity> <activity android:name=".Wallpaper" android:label="@string/camera_setas_wallpaper" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.ATTACH_DATA" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name=".PickWallpaper" android:label="@string/camera_pick_wallpaper" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.SET_WALLPAPER" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <receiver android:name="PhotoAppWidgetProvider" android:label="@string/gadget_title"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/appwidget_info" /> </receiver> <!-- We configure a widget by asking to pick a photo, then crop it, and store the config internally --> <activity android:name="PhotoAppWidgetConfigure"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" /> </intent-filter> </activity> <!-- We also allow direct binding where the caller provides a bitmap and appWidgetId to bind. We require the permission because this changes our internal database without user confirmation. --> <activity android:name="PhotoAppWidgetBind" android:exported="true" android:theme="@android:style/Theme.NoDisplay" android:permission="android.permission.BIND_APPWIDGET" /> </application> </manifest>
brunsky/WS171-packages-apps-Camera
244160941f0cb67cb18091b029b7efc3f5194ce3
AI 143547: Import revised translations. BUG=1738388
diff --git a/res/values-cs/strings.xml b/res/values-cs/strings.xml index a1fc3e3..74a8e37 100644 --- a/res/values-cs/strings.xml +++ b/res/values-cs/strings.xml @@ -1,155 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Všechny fotografie"</string> <string name="all_videos">"Všechna videa"</string> <string name="camera_label">"Fotoaparát"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> <string name="gallery_picker_label">"Galerie"</string> <string name="gallery_camera_bucket_name">"Pořízené fotografie"</string> <string name="gallery_camera_videos_bucket_name">"Pořízená videa"</string> <string name="switch_to_video_lable">"Přepnout do režimu video"</string> <string name="switch_to_camera_lable">"Přepnout do režimu fotoaparát"</string> <string name="crop_label">"Oříznout fotografii"</string> <string name="view_label">"Zobrazit fotografii"</string> <string name="preferences_label">"Nastavení fotoaparátu"</string> <string name="wait">"Čekejte prosím..."</string> <string name="no_storage">"Než začnete používat fotoaparát, vložte kartu SD."</string> <string name="not_enough_space">"Vaše karta SD je plná."</string> <string name="preparing_sd">"Příprava karty SD..."</string> <string name="wallpaper">"Nastavování tapety, čekejte prosím..."</string> <string name="savingImage">"Ukládání fotografie..."</string> <string name="runningFaceDetection">"Čekejte prosím..."</string> <string name="flip_orientation">"Změnit orientaci"</string> <string name="settings">"Nastavení"</string> <string name="view">"Zobrazit"</string> <string name="details">"Podrobnosti"</string> <string name="rotate">"Otočit"</string> <string name="rotate_left">"Otočit doleva"</string> <string name="rotate_right">"Otočit doprava"</string> <string name="slide_show">"Prezentace"</string> <string name="capture_picture">"Fotografovat"</string> <string name="capture_video">"Natočit video"</string> <string name="crop_save_text">"Uložit"</string> <string name="crop_discard_text">"Zahodit"</string> <string name="confirm_delete_title">"Smazat"</string> <string name="confirm_delete_message">"Fotografie bude smazána."</string> <string name="confirm_delete_video_message">"Video bude smazáno."</string> <string name="camera_toss">"Smazat"</string> <string name="camera_gallery">"Galerie"</string> <string name="camera_share">"Sdílet"</string> <string name="camera_set">"Použít jako"</string> <string name="camera_play">"Přehrát"</string> <string name="camera_attach">"Připojit přílohu"</string> <string name="camera_cancel">"Zrušit"</string> <string name="camera_crop">"Oříznout"</string> <string name="camera_tossing">"Mazání..."</string> <string name="no_way_to_share_image">"Tuto fotografii nelze sdílet."</string> <string name="no_way_to_share_video">"Toto video nelze sdílet."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galerie"</string> <string name="camera_pick_wallpaper">"Fotografie"</string> <string name="camera_setas_wallpaper">"Tapeta"</string> <string name="pref_gallery_category">"Obecné nastavení"</string> <string name="pref_slideshow_category">"Nastavení prezentace"</string> <string name="pref_camera_general_settings_category">"Obecné nastavení"</string> <string name="pref_gallery_size_title">"Zobrazovaná velikost"</string> <string name="pref_gallery_size_summary">"Vyberte zobrazovanou velikost obrázků a videí"</string> <string name="pref_gallery_size_dialogtitle">"Velikost fotografie"</string> <string-array name="pref_gallery_size_choices"> <item>"Velké"</item> <item>"Malé"</item> </string-array> <string name="pref_gallery_sort_title">"Řazení"</string> <string name="pref_gallery_sort_summary">"Vyberte způsob řazení obrázků a videí"</string> <string name="pref_gallery_sort_dialogtitle">"Řazení fotografií"</string> <string-array name="pref_gallery_sort_choices"> <item>"Od nejnovějších"</item> <item>"Od nejstarších"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Interval prezentace"</string> <string name="pref_gallery_slideshow_interval_summary">"Vyberte, jak dlouho má být zobrazen každý snímek"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Interval prezentace"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 sekundy"</item> <item>"3 sekundy"</item> <item>"4 sekundy"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Přechod v prezentaci"</string> <string name="pref_gallery_slideshow_transition_summary">"Vyberte efekt, který má být použit při přechodu z jednoho snímku na další"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Přechod v prezentaci"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Prolínat"</item> <item>"Posouvat zleva doprava"</item> <item>"Posouvat shora dolů"</item> <item>"Náhodný výběr"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Opakovat prezentaci"</string> <string name="pref_gallery_slideshow_repeat_summary">"Přehrát prezentaci více než jednou"</string> <string name="pref_gallery_slideshow_shuffle_title">"Náhodné pořadí snímků"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Zobrazit fotografie v náhodném pořadí"</string> <string name="pref_camera_recordlocation_title">"K fotografiím ukládat místo pořízení"</string> <string name="pref_camera_recordlocation_summary">"V datech fotografie zaznamenat místo pořízení"</string> <string name="pref_camera_videoquality_category">"Kvalita videa"</string> <string name="pref_camera_videoquality_title">"Vybrat kvalitu videa"</string> <string name="pref_camera_videoquality_entry_0">"Nízká (pro zprávy MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Vysoká (pro kartu SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Kvalita videa"</string> <string name="camerasettings">"Nastavení"</string> <string name="image_gallery_NoImageView_text">"Žádná média nebyla nalezena."</string> <string name="pref_gallery_confirm_delete_title">"Potvrdit smazání"</string> <string name="pref_gallery_confirm_delete_summary">"Žádat potvrzení před smazáním obrázku nebo videa"</string> <string name="details_panel_title">"Podrobnosti"</string> <string name="details_file_size">"Velikost souboru:"</string> <string name="details_image_resolution">"Rozlišení:"</string> <string name="details_duration">"Délka:"</string> <string name="details_date_taken">"Datum pořízení:"</string> <string name="details_frame_rate">"Počet snímků za sekundu:"</string> <string name="details_bit_rate">"Bitová rychlost:"</string> <string name="details_codec">"Kodek:"</string> <string name="details_format">"Formát:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d snímků/s"</string> <string name="details_kbps">"%1$d Kb/s"</string> <string name="details_mbps">"%1$g Mb/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Možnosti fotografií"</string> <string name="video_context_menu_header">"Možnosti videa"</string> <string name="multiface_crop_help">"Začněte klepnutím na obličej."</string> <string name="photos_gallery_title">"Galerie"</string> <string name="pick_photos_gallery_title">"Vyberte fotografii"</string> <string name="videos_gallery_title">"Galerie"</string> <string name="pick_videos_gallery_title">"Vybrat video"</string> <string name="loading_progress_format_string">"Zbývá <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Sdílet fotografii pomocí"</string> <string name="setImage">"Fotografie bude použita jako"</string> <string name="sendVideo">"Sdílet video pomocí"</string> <string name="movieviewlabel">"Filmy"</string> <string name="loading_video">"Načítání videa..."</string> <string name="spaceIsLow_title">"Dochází volné místo"</string> <string name="spaceIsLow_content">"Na vaší kartě SD je málo místa. Změňte nastavení kvality nebo smažte položky z Galerie."</string> <string name="resume_playing_title">"Pokračovat v přehrávání videa"</string> <string name="resume_playing_message">"Pokračovat v přehrávání od %s?"</string> <string name="resume_playing_resume">"Pokračovat v přehrávání"</string> <string name="resume_playing_restart">"Začít znovu"</string> <string name="gadget_title">"Rámeček fotografie"</string> <string name="file_info_title">"Informace o souboru:"</string> <string name="video_exceed_mms_limit">"Zaznamenané video je pro odeslání ve zprávě MMS příliš velké. Zkuste zaznamenat kratší videoklip."</string> <string name="too_large_to_attach">"Soubor nelze připojit, protože je příliš velký."</string> </resources> diff --git a/res/values-de/strings.xml b/res/values-de/strings.xml index ad1373b..0924e60 100644 --- a/res/values-de/strings.xml +++ b/res/values-de/strings.xml @@ -1,154 +1,156 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Alle Bilder"</string> <string name="all_videos">"Alle Videos"</string> <string name="camera_label">"Kamera"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> <string name="gallery_picker_label">"Galerie"</string> <string name="gallery_camera_bucket_name">"Kamerabilder"</string> <string name="gallery_camera_videos_bucket_name">"Kameravideos"</string> <string name="switch_to_video_lable">"Zu Video wechseln"</string> <string name="switch_to_camera_lable">"Zu Kamera wechseln"</string> <string name="crop_label">"Bild zuschneiden"</string> <string name="view_label">"Bild anzeigen"</string> <string name="preferences_label">"Kameraeinstellungen"</string> <string name="wait">"Bitte warten..."</string> <string name="no_storage">"Legen Sie vor Verwendung der Kamera eine SD-Karte ein."</string> <string name="not_enough_space">"Ihre SD-Karte ist voll."</string> <string name="preparing_sd">"SD-Karte wird vorbereitet..."</string> <string name="wallpaper">"Hintergrund wird eingestellt, bitte warten..."</string> <string name="savingImage">"Bild wird gespeichert..."</string> <string name="runningFaceDetection">"Bitte warten..."</string> <string name="flip_orientation">"Ausrichtung drehen"</string> <string name="settings">"Einstellungen"</string> <string name="view">"Anzeigen"</string> <string name="details">"Details"</string> <string name="rotate">"Drehen"</string> <string name="rotate_left">"Nach links drehen"</string> <string name="rotate_right">"Nach rechts drehen"</string> <string name="slide_show">"Diashow"</string> <string name="capture_picture">"Bild aufnehmen"</string> <string name="capture_video">"Video aufnehmen"</string> <string name="crop_save_text">"Speichern"</string> <string name="crop_discard_text">"Verwerfen"</string> <string name="confirm_delete_title">"Löschen"</string> <string name="confirm_delete_message">"Das Bild wird gelöscht."</string> <string name="confirm_delete_video_message">"Das Video wird gelöscht."</string> <string name="camera_toss">"Löschen"</string> <string name="camera_gallery">"Galerie"</string> <string name="camera_share">"Senden"</string> <string name="camera_set">"Festlegen als"</string> <string name="camera_play">"Wiedergeben"</string> <string name="camera_attach">"Anhängen"</string> <string name="camera_cancel">"Abbrechen"</string> <string name="camera_crop">"Zuschneiden"</string> <string name="camera_tossing">"Löschvorgang..."</string> <string name="no_way_to_share_image">"Dieses Bild kann nicht weitergeleitet werden."</string> <string name="no_way_to_share_video">"Dieses Video kann nicht weitergeleitet werden."</string> <string name="video_play">"Play"</string> <string name="camera_gallery_photos_text">"Galerie"</string> <string name="camera_pick_wallpaper">"Bilder"</string> <string name="camera_setas_wallpaper">"Hintergrund"</string> <string name="pref_gallery_category">"Allgemeine Einstellungen"</string> <string name="pref_slideshow_category">"Einstellungen für Diashow"</string> <string name="pref_camera_general_settings_category">"Allgemeine Einstellungen"</string> <string name="pref_gallery_size_title">"Anzeigegröße"</string> <string name="pref_gallery_size_summary">"Anzeigegröße für Bilder und Videos auswählen"</string> <string name="pref_gallery_size_dialogtitle">"Bildgröße"</string> <string-array name="pref_gallery_size_choices"> <item>"Groß"</item> <item>"Klein"</item> </string-array> <string name="pref_gallery_sort_title">"Sortierreihenfolge"</string> <string name="pref_gallery_sort_summary">"Sortierreihenfolge für Bilder und Videos auswählen"</string> <string name="pref_gallery_sort_dialogtitle">"Sortierreihenfolge für Bilder"</string> <string-array name="pref_gallery_sort_choices"> <item>"Neue zuerst"</item> <item>"Neue zuletzt"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Diashow-Intervall"</string> <string name="pref_gallery_slideshow_interval_summary">"Auswählen, wie lange jedes Bild in der Diashow angezeigt werden soll"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Diashow-Intervall"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 Sekunden"</item> <item>"3 Sekunden"</item> <item>"4 Sekunden"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Diashow - Übergang"</string> <string name="pref_gallery_slideshow_transition_summary">"Effekt auswählen, der beim Wechsel zum nächsten Bild angewendet wird"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Diashow - Übergang"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ein- und ausblenden"</item> <item>"Einblendung von links - rechts"</item> <item>"Einblendung von oben - unten"</item> <item>"Zufällige Auswahl"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Diashow erneut anzeigen?"</string> <string name="pref_gallery_slideshow_repeat_summary">"Diashow mehrmals anzeigen"</string> <string name="pref_gallery_slideshow_shuffle_title">"Bilder mischen"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Bilder in zufälliger Reihenfolge anzeigen"</string> <string name="pref_camera_recordlocation_title">"Aufnahmeort in Bildern speichern"</string> <string name="pref_camera_recordlocation_summary">"Aufnahmeort in Bilddaten speichern"</string> <string name="pref_camera_videoquality_category">"Videoqualität"</string> <string name="pref_camera_videoquality_title">"Videoqualität auswählen"</string> <string name="pref_camera_videoquality_entry_0">"Niedrig (für MMS-Mitteilungen)"</string> <string name="pref_camera_videoquality_entry_1">"Hoch (für SD-Karte)"</string> <string name="pref_camera_videoquality_dialogtitle">"Videoqualität"</string> <string name="camerasettings">"Einstellungen"</string> <string name="image_gallery_NoImageView_text">"Keine Medien gefunden."</string> <string name="pref_gallery_confirm_delete_title">"Löschvorgang bestätigen"</string> <string name="pref_gallery_confirm_delete_summary">"Bestätigung vor dem Löschen eines Bildes oder Videos anzeigen"</string> <string name="details_panel_title">"Details"</string> <string name="details_file_size">"Dateigröße:"</string> <string name="details_image_resolution">"Auflösung:"</string> <string name="details_duration">"Dauer:"</string> <string name="details_date_taken">"Aufnahmedatum:"</string> <string name="details_frame_rate">"Framerate:"</string> <string name="details_bit_rate">"Bitrate:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbit/s"</string> <string name="details_mbps">"%1$g Mbit/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Bildoptionen"</string> <string name="video_context_menu_header">"Videooptionen"</string> <string name="multiface_crop_help">"Tippen Sie zum Beginnen auf ein Gesicht."</string> <string name="photos_gallery_title">"Galerie"</string> <string name="pick_photos_gallery_title">"Bild auswählen"</string> <string name="videos_gallery_title">"Galerie"</string> <string name="pick_videos_gallery_title">"Video auswählen"</string> <string name="loading_progress_format_string">"noch <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Bild senden via"</string> <string name="setImage">"Bild festlegen als"</string> <string name="sendVideo">"Video weiterleiten via"</string> <string name="movieviewlabel">"Filme"</string> <string name="loading_video">"Video wird geladen..."</string> <string name="spaceIsLow_title">"Geringer Speicherplatz"</string> <string name="spaceIsLow_content">"Auf Ihrer SD-Karte ist nicht mehr genügend Speicherplatz vorhanden. Ändern Sie die Qualitätseinstellung oder löschen Sie Elemente aus der Galerie."</string> <string name="resume_playing_title">"Mit Video fortfahren"</string> <string name="resume_playing_message">"Mit Wiedergabe fortfahren ab %s ?"</string> <string name="resume_playing_resume">"Mit Wiedergabe fortfahren"</string> <string name="resume_playing_restart">"Starten"</string> <string name="gadget_title">"Bildrahmen"</string> <string name="file_info_title">"Dateiinfo:"</string> <string name="video_exceed_mms_limit">"Das aufgenommene Video ist zu groß und kann nicht per MMS gesendet werden. Nehmen Sie einen kürzeren Clip auf."</string> <string name="too_large_to_attach">"Dateianhang zu groß"</string> </resources> diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml index 120742c..bbbdbc2 100644 --- a/res/values-es/strings.xml +++ b/res/values-es/strings.xml @@ -1,155 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Todas las imágenes"</string> <string name="all_videos">"Todos los vídeos"</string> <string name="camera_label">"Cámara"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> <string name="gallery_picker_label">"Galería"</string> <string name="gallery_camera_bucket_name">"Imágenes de cámara"</string> <string name="gallery_camera_videos_bucket_name">"Vídeos de cámara"</string> <string name="switch_to_video_lable">"Cambiar a vídeo"</string> <string name="switch_to_camera_lable">"Cambiar a cámara"</string> <string name="crop_label">"Recortar imagen"</string> <string name="view_label">"Ver imagen"</string> <string name="preferences_label">"Configuración de cámara"</string> <string name="wait">"Por favor, espera..."</string> <string name="no_storage">"Antes de utilizar la cámara, debes insertar una tarjeta SD."</string> <string name="not_enough_space">"La tarjeta SD está llena."</string> <string name="preparing_sd">"Preparando tarjeta SD…"</string> <string name="wallpaper">"Estableciendo fondo de pantalla; por favor, espera..."</string> <string name="savingImage">"Guardando imagen..."</string> <string name="runningFaceDetection">"Por favor, espera..."</string> <string name="flip_orientation">"Cambiar orientación"</string> <string name="settings">"Ajustes"</string> <string name="view">"Ver"</string> <string name="details">"Detalles"</string> <string name="rotate">"Girar"</string> <string name="rotate_left">"Girar a la izquierda"</string> <string name="rotate_right">"Girar a la derecha"</string> <string name="slide_show">"Presentación"</string> <string name="capture_picture">"Capturar imagen"</string> <string name="capture_video">"Capturar vídeo"</string> <string name="crop_save_text">"Guardar"</string> <string name="crop_discard_text">"Descartar"</string> <string name="confirm_delete_title">"Suprimir"</string> <string name="confirm_delete_message">"Se eliminará la imagen."</string> <string name="confirm_delete_video_message">"Se eliminará el vídeo."</string> <string name="camera_toss">"Suprimir"</string> <string name="camera_gallery">"Galería"</string> <string name="camera_share">"Compartir"</string> <string name="camera_set">"Establecer como"</string> <string name="camera_play">"Reproducir"</string> <string name="camera_attach">"Adjuntar"</string> <string name="camera_cancel">"Cancelar"</string> <string name="camera_crop">"Recortar"</string> <string name="camera_tossing">"Eliminando..."</string> <string name="no_way_to_share_image">"Esta imagen no se puede compartir."</string> <string name="no_way_to_share_video">"Este vídeo no se puede compartir."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galería"</string> <string name="camera_pick_wallpaper">"Imágenes"</string> <string name="camera_setas_wallpaper">"Fondo de pantalla"</string> <string name="pref_gallery_category">"Configuración general"</string> <string name="pref_slideshow_category">"Configuración de presentación"</string> <string name="pref_camera_general_settings_category">"Configuración general"</string> <string name="pref_gallery_size_title">"Tamaño de visualización"</string> <string name="pref_gallery_size_summary">"Seleccionar el tamaño de visualización de imágenes y vídeos"</string> <string name="pref_gallery_size_dialogtitle">"Tamaño de imagen"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Pequeña"</item> </string-array> <string name="pref_gallery_sort_title">"Orden"</string> <string name="pref_gallery_sort_summary">"Seleccionar el orden de imágenes y vídeos"</string> <string name="pref_gallery_sort_dialogtitle">"Ordenación de imágenes"</string> <string-array name="pref_gallery_sort_choices"> <item>"Más recientes primero"</item> <item>"Más recientes al final"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalo de presentación"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleccionar la duración de cada diapositiva"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo de presentación"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 segundos"</item> <item>"3 segundos"</item> <item>"4 segundos"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transición de diapositivas"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleccionar el efecto que se aplicará al pasar de una diapositiva a otra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transición de diapositivas"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Fundido de entrada y salida"</item> <item>"Transición de izquierda a derecha"</item> <item>"Transición de arriba a abajo"</item> <item>"Selección aleatoria"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Repetir presentación"</string> <string name="pref_gallery_slideshow_repeat_summary">"Mostrar presentación más de una vez"</string> <string name="pref_gallery_slideshow_shuffle_title">"Reproducir diapositivas en orden aleatorio"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imágenes en orden aleatorio"</string> <string name="pref_camera_recordlocation_title">"Almacenar ubicación en imágenes"</string> <string name="pref_camera_recordlocation_summary">"Registrar ubicación en datos de imagen"</string> <string name="pref_camera_videoquality_category">"Calidad de vídeo"</string> <string name="pref_camera_videoquality_title">"Seleccionar calidad de vídeo"</string> <string name="pref_camera_videoquality_entry_0">"Baja (para mensajes MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (para tarjeta SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Calidad de vídeo"</string> <string name="camerasettings">"Ajustes"</string> <string name="image_gallery_NoImageView_text">"No se ha encontrado ningún elemento."</string> <string name="pref_gallery_confirm_delete_title">"Confirmar eliminaciones"</string> <string name="pref_gallery_confirm_delete_summary">"Mostrar confirmación antes de eliminar una imagen o un vídeo"</string> <string name="details_panel_title">"Detalles"</string> <string name="details_file_size">"Tamaño de archivo:"</string> <string name="details_image_resolution">"Resolución:"</string> <string name="details_duration">"Duración:"</string> <string name="details_date_taken">"Fecha de realización:"</string> <string name="details_frame_rate">"Frecuencia de imagen:"</string> <string name="details_bit_rate">"Velocidad binaria:"</string> <string name="details_codec">"Códec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"Aceptar"</string> <string name="context_menu_header">"Opciones de imagen"</string> <string name="video_context_menu_header">"Opciones de vídeo"</string> <string name="multiface_crop_help">"Selecciona una cara para empezar."</string> <string name="photos_gallery_title">"Galería"</string> <string name="pick_photos_gallery_title">"Seleccionar imagen"</string> <string name="videos_gallery_title">"Galería"</string> <string name="pick_videos_gallery_title">"Seleccionar vídeo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> <string name="sendImage">"Compartir imagen por"</string> <string name="setImage">"Establecer imagen como"</string> <string name="sendVideo">"Compartir vídeo a través de"</string> <string name="movieviewlabel">"Películas"</string> <string name="loading_video">"Cargando vídeo…"</string> <string name="spaceIsLow_title">"Poco espacio"</string> <string name="spaceIsLow_content">"No queda espacio en la tarjeta SD. Cambia la configuración de calidad o elimina elementos de la galería."</string> <string name="resume_playing_title">"Reanudar vídeo"</string> <string name="resume_playing_message">"Reanudar reproducción a partir de %s ?"</string> <string name="resume_playing_resume">"Reanudar reproducción"</string> <string name="resume_playing_restart">"Volver a reproducir"</string> <string name="gadget_title">"Picture frame"</string> <string name="file_info_title">"Información de archivo:"</string> <string name="video_exceed_mms_limit">"El vídeo que has grabado es demasiado grande para enviarlo a través de MMS. Intenta grabar un vídeo de menor duración."</string> <string name="too_large_to_attach">"El archivo es demasiado grande para adjuntarlo."</string> </resources> diff --git a/res/values-fr/strings.xml b/res/values-fr/strings.xml index 5813dde..5a82537 100644 --- a/res/values-fr/strings.xml +++ b/res/values-fr/strings.xml @@ -1,155 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Toutes les images"</string> <string name="all_videos">"Toutes les vidéos"</string> <string name="camera_label">"Appareil photo"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> <string name="gallery_picker_label">"Galerie"</string> <string name="gallery_camera_bucket_name">"Photos de l\'appareil"</string> <string name="gallery_camera_videos_bucket_name">"Vidéos de la caméra"</string> <string name="switch_to_video_lable">"Passer en mode vidéo"</string> <string name="switch_to_camera_lable">"Passer en mode appareil photo"</string> <string name="crop_label">"Rogner l\'image"</string> <string name="view_label">"Afficher l\'image"</string> <string name="preferences_label">"Paramètres de l\'appareil photo"</string> <string name="wait">"Veuillez patienter..."</string> <string name="no_storage">"Veuillez insérer une carte SD avant d\'utiliser l\'appareil photo."</string> <string name="not_enough_space">"Votre carte SD est pleine."</string> <string name="preparing_sd">"Préparation de la carte SD..."</string> <string name="wallpaper">"Configuration de l\'arrière-plan en cours. Veuillez patienter..."</string> <string name="savingImage">"Enregistrement de l\'image"</string> <string name="runningFaceDetection">"Veuillez patienter..."</string> <string name="flip_orientation">"Orientation"</string> <string name="settings">"Paramètres"</string> <string name="view">"Afficher"</string> <string name="details">"Détails"</string> <string name="rotate">"Faire pivoter"</string> <string name="rotate_left">"Faire pivoter à gauche"</string> <string name="rotate_right">"Faire pivoter à droite"</string> <string name="slide_show">"Diaporama"</string> <string name="capture_picture">"Prendre une photo"</string> <string name="capture_video">"Prendre une vidéo"</string> <string name="crop_save_text">"Enregistrer"</string> <string name="crop_discard_text">"Annuler"</string> <string name="confirm_delete_title">"Supprimer"</string> <string name="confirm_delete_message">"L\'image sera supprimée."</string> <string name="confirm_delete_video_message">"La vidéo va être supprimée."</string> <string name="camera_toss">"Supprimer"</string> <string name="camera_gallery">"Galerie"</string> <string name="camera_share">"Partager"</string> <string name="camera_set">"Définir comme"</string> <string name="camera_play">"Lire"</string> <string name="camera_attach">"Joindre"</string> <string name="camera_cancel">"Annuler"</string> <string name="camera_crop">"Rogner"</string> <string name="camera_tossing">"Suppression..."</string> <string name="no_way_to_share_image">"Impossible de partager cette image."</string> <string name="no_way_to_share_video">"Cette vidéo ne peut pas être partagée."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galerie"</string> <string name="camera_pick_wallpaper">"Images"</string> <string name="camera_setas_wallpaper">"Arrière-plan"</string> <string name="pref_gallery_category">"Paramètres généraux"</string> <string name="pref_slideshow_category">"Paramètres du diaporama"</string> <string name="pref_camera_general_settings_category">"Paramètres généraux"</string> <string name="pref_gallery_size_title">"Taille d\'affichage"</string> <string name="pref_gallery_size_summary">"Sélectionner la taille d\'affichage des images et des vidéos"</string> <string name="pref_gallery_size_dialogtitle">"Taille de l\'image"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Petite"</item> </string-array> <string name="pref_gallery_sort_title">"Ordre de tri"</string> <string name="pref_gallery_sort_summary">"Sélectionner l\'ordre de tri des images et des vidéos"</string> <string name="pref_gallery_sort_dialogtitle">"Trier les images"</string> <string-array name="pref_gallery_sort_choices"> <item>"La plus récente en premier"</item> <item>"La plus récente en dernier"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalle du diaporama"</string> <string name="pref_gallery_slideshow_interval_summary">"Sélectionner la durée d\'affichage de chaque diapositive dans le diaporama"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalle du diaporama"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 secondes"</item> <item>"3 secondes"</item> <item>"4 secondes"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transition du diaporama"</string> <string name="pref_gallery_slideshow_transition_summary">"Sélectionner l\'effet utilisé lors de la transition d\'une diapositive à une autre"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transition du diaporama"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ouverture et fermeture en fondu"</item> <item>"Glisser de gauche à droite"</item> <item>"Glisser de haut en bas"</item> <item>"Sélection aléatoire"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Rejouer le diaporama"</string> <string name="pref_gallery_slideshow_repeat_summary">"Rejouer le diaporama plusieurs fois"</string> <string name="pref_gallery_slideshow_shuffle_title">"Lecture aléatoire"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Afficher les images"</string> <string name="pref_camera_recordlocation_title">"Enregistrer le lieu"</string> <string name="pref_camera_recordlocation_summary">"Enregistrer la position géographique dans les données d\'image"</string> <string name="pref_camera_videoquality_category">"Paramètres vidéo"</string> <string name="pref_camera_videoquality_title">"Qualité vidéo"</string> <string name="pref_camera_videoquality_entry_0">"Basse (pour les MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Haute (pour la carte SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Qualité vidéo"</string> <string name="camerasettings">"Paramètres"</string> <string name="image_gallery_NoImageView_text">"Aucun fichier trouvé."</string> <string name="pref_gallery_confirm_delete_title">"Confirmer suppressions"</string> <string name="pref_gallery_confirm_delete_summary">"Afficher une confirmation avant de supprimer une image ou une vidéo"</string> <string name="details_panel_title">"Détails"</string> <string name="details_file_size">"Taille du fichier :"</string> <string name="details_image_resolution">"Résolution :"</string> <string name="details_duration">"Durée :"</string> <string name="details_date_taken">"Date de création :"</string> <string name="details_frame_rate">"Fréquence d\'images :"</string> <string name="details_bit_rate">"Débit :"</string> <string name="details_codec">"Codec :"</string> <string name="details_format">"Format :"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d ips"</string> <string name="details_kbps">"%1$d Kbits/s"</string> <string name="details_mbps">"%1$g Mbits/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Options de l\'image"</string> <string name="video_context_menu_header">"Options vidéo"</string> <string name="multiface_crop_help">"Cliquez sur un visage pour commencer."</string> <string name="photos_gallery_title">"Galerie"</string> <string name="pick_photos_gallery_title">"Sélectionnez une image"</string> <string name="videos_gallery_title">"Galerie"</string> <string name="pick_videos_gallery_title">"Sélectionnez une vidéo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> vignettes restantes"</string> <string name="sendImage">"Partager l\'image via"</string> <string name="setImage">"Définir l\'image comme"</string> <string name="sendVideo">"Partager la vidéo via"</string> <string name="movieviewlabel">"Films"</string> <string name="loading_video">"Chargement de la vidéo..."</string> <string name="spaceIsLow_title">"L\'espace restant est faible"</string> <string name="spaceIsLow_content">"Votre carte SD est pleine. Modifiez le paramètre de qualité ou supprimez des éléments de la galerie."</string> <string name="resume_playing_title">"Reprendre la vidéo"</string> <string name="resume_playing_message">"Reprendre la lecture à partir de %s ?"</string> <string name="resume_playing_resume">"Reprendre la lecture"</string> <string name="resume_playing_restart">"Démarrer"</string> <string name="gadget_title">"Cadre d\'image"</string> <string name="file_info_title">"Informations sur le fichier :"</string> <string name="video_exceed_mms_limit">"La vidéo que vous avez enregistrée est trop volumineuse et ne peut être envoyée par MMS. Enregistrez une vidéo plus courte."</string> <string name="too_large_to_attach">"Impossible de joindre le fichier, car il est trop volumineux."</string> </resources> diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml index 0dab680..20d9d40 100644 --- a/res/values-it/strings.xml +++ b/res/values-it/strings.xml @@ -1,155 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Tutte le foto"</string> <string name="all_videos">"Tutti i video"</string> <string name="camera_label">"Fotocamera"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> <string name="gallery_picker_label">"Galleria"</string> <string name="gallery_camera_bucket_name">"Foto"</string> <string name="gallery_camera_videos_bucket_name">"Video fotocamera"</string> <string name="switch_to_video_lable">"Passa a video"</string> <string name="switch_to_camera_lable">"Passa a fotocamera"</string> <string name="crop_label">"Ritaglia foto"</string> <string name="view_label">"Visualizza foto"</string> <string name="preferences_label">"Impostazioni fotocamera"</string> <string name="wait">"Attendere..."</string> <string name="no_storage">"Per usare la fotocamera devi inserire una scheda SD."</string> <string name="not_enough_space">"La scheda SD è piena."</string> <string name="preparing_sd">"Preparazione scheda SD…"</string> <string name="wallpaper">"Impostazione sfondo, attendi..."</string> <string name="savingImage">"Salvataggio foto..."</string> <string name="runningFaceDetection">"Attendere..."</string> <string name="flip_orientation">"Capovolgi orientamento"</string> <string name="settings">"Impostazioni"</string> <string name="view">"Visualizza"</string> <string name="details">"Dettagli"</string> <string name="rotate">"Ruota"</string> <string name="rotate_left">"Ruota a sinistra"</string> <string name="rotate_right">"Ruota a destra"</string> <string name="slide_show">"Presentazione"</string> <string name="capture_picture">"Scatta foto"</string> <string name="capture_video">"Registra video"</string> <string name="crop_save_text">"Salva"</string> <string name="crop_discard_text">"Annulla"</string> <string name="confirm_delete_title">"Elimina"</string> <string name="confirm_delete_message">"La foto verrà eliminata."</string> <string name="confirm_delete_video_message">"Il video verrà eliminato."</string> <string name="camera_toss">"Elimina"</string> <string name="camera_gallery">"Galleria"</string> <string name="camera_share">"Condividi"</string> <string name="camera_set">"Imposta come"</string> <string name="camera_play">"Riproduci"</string> <string name="camera_attach">"Allega"</string> <string name="camera_cancel">"Annulla"</string> <string name="camera_crop">"Ritaglia"</string> <string name="camera_tossing">"Eliminazione..."</string> <string name="no_way_to_share_image">"Impossibile condividere la foto."</string> <string name="no_way_to_share_video">"Impossibile condividere il video."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galleria"</string> <string name="camera_pick_wallpaper">"Foto"</string> <string name="camera_setas_wallpaper">"Sfondo"</string> <string name="pref_gallery_category">"Impostazioni generali"</string> <string name="pref_slideshow_category">"Impostazioni presentazione"</string> <string name="pref_camera_general_settings_category">"Impostazioni generali"</string> <string name="pref_gallery_size_title">"Dimensioni schermo"</string> <string name="pref_gallery_size_summary">"Seleziona dimensioni di visualizz. di foto e video"</string> <string name="pref_gallery_size_dialogtitle">"Dimensioni foto"</string> <string-array name="pref_gallery_size_choices"> <item>"Grandi"</item> <item>"Piccole"</item> </string-array> <string name="pref_gallery_sort_title">"Ordinamento"</string> <string name="pref_gallery_sort_summary">"Seleziona l\'ordinamento di foto e video"</string> <string name="pref_gallery_sort_dialogtitle">"Ordine foto"</string> <string-array name="pref_gallery_sort_choices"> <item>"Da più recente"</item> <item>"Da meno recente"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervallo presentazione"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleziona la durata di ogni diapositiva"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervallo presentazione"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 secondi"</item> <item>"3 secondi"</item> <item>"4 secondi"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transizione presentazione"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleziona l\'effetto da usare per passare da una diapositiva all\'altra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transizione diapositive"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Dissolvenza"</item> <item>"Da sinistra a destra"</item> <item>"Dall\'alto verso il basso"</item> <item>"Selezione casuale"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Ripeti presentazione"</string> <string name="pref_gallery_slideshow_repeat_summary">"Riproduci più volte la presentazione"</string> <string name="pref_gallery_slideshow_shuffle_title">"Riproduzione casuale"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostra le foto in ordine casuale"</string> <string name="pref_camera_recordlocation_title">"Salva località nelle foto"</string> <string name="pref_camera_recordlocation_summary">"Registra località nei dati della foto"</string> <string name="pref_camera_videoquality_category">"Qualità video"</string> <string name="pref_camera_videoquality_title">"Seleziona la qualità video"</string> <string name="pref_camera_videoquality_entry_0">"Bassa (per MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (per scheda SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Qualità video"</string> <string name="camerasettings">"Impostazioni"</string> <string name="image_gallery_NoImageView_text">"Nessun media trovato."</string> <string name="pref_gallery_confirm_delete_title">"Conferma eliminazioni"</string> <string name="pref_gallery_confirm_delete_summary">"Mostra conferma prima di eliminare una foto o un video"</string> <string name="details_panel_title">"Dettagli"</string> <string name="details_file_size">"Dim. file:"</string> <string name="details_image_resolution">"Risoluzione:"</string> <string name="details_duration">"Durata:"</string> <string name="details_date_taken">"Data scatto:"</string> <string name="details_frame_rate">"Frequenza fotogrammi:"</string> <string name="details_bit_rate">"Velocità in bit:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opzioni foto"</string> <string name="video_context_menu_header">"Opzioni video"</string> <string name="multiface_crop_help">"Tocca un viso per iniziare."</string> <string name="photos_gallery_title">"Galleria"</string> <string name="pick_photos_gallery_title">"Seleziona foto"</string> <string name="videos_gallery_title">"Galleria"</string> <string name="pick_videos_gallery_title">"Seleziona video"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> rimanenti"</string> <string name="sendImage">"Condividi foto via"</string> <string name="setImage">"Imposta foto come"</string> <string name="sendVideo">"Condividi video via"</string> <string name="movieviewlabel">"Film"</string> <string name="loading_video">"Caricamento video..."</string> <string name="spaceIsLow_title">"Spazio in esaurimento"</string> <string name="spaceIsLow_content">"Lo spazio della scheda SD si sta esaurendo. Cambia l\'impostazione di qualità o elimina elementi nella galleria."</string> <string name="resume_playing_title">"Riprendi video"</string> <string name="resume_playing_message">"Riprendi riproduzione da %s ?"</string> <string name="resume_playing_resume">"Riprendi riproduzione"</string> <string name="resume_playing_restart">"Ricomincia"</string> <string name="gadget_title">"Cornice immagine"</string> <string name="file_info_title">"Info file:"</string> <string name="video_exceed_mms_limit">"Il video registrato è troppo grande per essere inviato tramite MMS. Prova a registrare un clip più corto."</string> <string name="too_large_to_attach">"File troppo grande. Impossibile allegarlo."</string> </resources> diff --git a/res/values-ko/strings.xml b/res/values-ko/strings.xml index 5cd51a9..b30594b 100644 --- a/res/values-ko/strings.xml +++ b/res/values-ko/strings.xml @@ -1,155 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"모든 사진"</string> <string name="all_videos">"모든 동영상"</string> <string name="camera_label">"카메라"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> <string name="gallery_picker_label">"갤러리"</string> <string name="gallery_camera_bucket_name">"카메라 사진"</string> <string name="gallery_camera_videos_bucket_name">"카메라 동영상"</string> <string name="switch_to_video_lable">"동영상으로 전환"</string> <string name="switch_to_camera_lable">"카메라로 전환"</string> <string name="crop_label">"사진 자르기"</string> <string name="view_label">"사진 보기"</string> <string name="preferences_label">"카메라 설정"</string> <string name="wait">"잠시 기다려 주세요..."</string> <string name="no_storage">"카메라를 사용하기 전에 먼저 SD 카드를 넣으세요."</string> <string name="not_enough_space">"SD 카드가 꽉 찼습니다."</string> <string name="preparing_sd">"SD 카드 준비중..."</string> <string name="wallpaper">"배경화면 설정 중. 잠시 기다려 주세요..."</string> <string name="savingImage">"사진 저장 중..."</string> <string name="runningFaceDetection">"잠시 기다려 주세요..."</string> <string name="flip_orientation">"방향 바꾸기"</string> <string name="settings">"설정"</string> <string name="view">"보기"</string> <string name="details">"상세정보"</string> <string name="rotate">"회전"</string> <string name="rotate_left">"왼쪽으로 회전"</string> <string name="rotate_right">"오른쪽으로 회전"</string> <string name="slide_show">"슬라이드쇼"</string> <string name="capture_picture">"사진촬영"</string> <string name="capture_video">"동영상 캡처"</string> <string name="crop_save_text">"저장"</string> <string name="crop_discard_text">"무시"</string> <string name="confirm_delete_title">"삭제"</string> <string name="confirm_delete_message">"사진이 삭제됩니다."</string> <string name="confirm_delete_video_message">"동영상이 삭제됩니다."</string> <string name="camera_toss">"삭제"</string> <string name="camera_gallery">"갤러리"</string> <string name="camera_share">"공유"</string> <string name="camera_set">"사진 설정"</string> <string name="camera_play">"재생"</string> <string name="camera_attach">"첨부"</string> <string name="camera_cancel">"취소"</string> <string name="camera_crop">"자르기"</string> <string name="camera_tossing">"삭제 중..."</string> <string name="no_way_to_share_image">"공유할 수 없는 사진입니다."</string> <string name="no_way_to_share_video">"공유할 수 없는 동영상입니다."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"갤러리"</string> <string name="camera_pick_wallpaper">"사진"</string> <string name="camera_setas_wallpaper">"배경화면"</string> <string name="pref_gallery_category">"일반 설정"</string> <string name="pref_slideshow_category">"슬라이드쇼 설정"</string> <string name="pref_camera_general_settings_category">"일반 설정"</string> <string name="pref_gallery_size_title">"디스플레이 크기"</string> <string name="pref_gallery_size_summary">"사진 및 동영상 표시 크기 선택"</string> <string name="pref_gallery_size_dialogtitle">"사진 크기"</string> <string-array name="pref_gallery_size_choices"> <item>"크게"</item> <item>"작게"</item> </string-array> <string name="pref_gallery_sort_title">"정렬 순서"</string> <string name="pref_gallery_sort_summary">"사진 및 동영상 정렬 순서 선택"</string> <string name="pref_gallery_sort_dialogtitle">"사진 정렬"</string> <string-array name="pref_gallery_sort_choices"> <item>"가장 최근 사진 먼저"</item> <item>"가장 최근 사진 마지막에"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"슬라이드쇼 간격"</string> <string name="pref_gallery_slideshow_interval_summary">"쇼에서 각 슬라이드를 표시할 시간 선택"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"슬라이드쇼 간격"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2초"</item> <item>"3초"</item> <item>"4초"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"슬라이드쇼 화면전환"</string> <string name="pref_gallery_slideshow_transition_summary">"슬라이드 간에 이동할 때 사용할 효과 선택"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"슬라이드쇼 화면전환"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"페이드 인/아웃"</item> <item>"왼쪽에서 오른쪽으로/오른쪽에서 왼쪽으로"</item> <item>"위에서 아래로/아래에서 위로"</item> <item>"무작위 선택"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"슬라이드쇼 반복"</string> <string name="pref_gallery_slideshow_repeat_summary">"슬라이드쇼를 한 번 이상 재생"</string> <string name="pref_gallery_slideshow_shuffle_title">"슬라이드 섞기"</string> <string name="pref_gallery_slideshow_shuffle_summary">"사진을 무작위 순서로 표시"</string> <string name="pref_camera_recordlocation_title">"사진에 위치 저장"</string> <string name="pref_camera_recordlocation_summary">"사진 데이터에 위치 기록"</string> <string name="pref_camera_videoquality_category">"동영상 화질"</string> <string name="pref_camera_videoquality_title">"동영상 화질 선택"</string> <string name="pref_camera_videoquality_entry_0">"낮음(MMS 메시지용)"</string> <string name="pref_camera_videoquality_entry_1">"높음(SD 카드용)"</string> <string name="pref_camera_videoquality_dialogtitle">"동영상 화질"</string> <string name="camerasettings">"설정"</string> <string name="image_gallery_NoImageView_text">"미디어 파일이 없습니다."</string> <string name="pref_gallery_confirm_delete_title">"삭제 확인"</string> <string name="pref_gallery_confirm_delete_summary">"사진 및 동영상 삭제 전 확인 표시"</string> <string name="details_panel_title">"상세정보"</string> <string name="details_file_size">"파일 크기:"</string> <string name="details_image_resolution">"해상도:"</string> <string name="details_duration">"재생 시간:"</string> <string name="details_date_taken">"찍은 날짜:"</string> <string name="details_frame_rate">"프레임 속도:"</string> <string name="details_bit_rate">"비트 전송률:"</string> <string name="details_codec">"코덱:"</string> <string name="details_format">"형식:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$dfps"</string> <string name="details_kbps">"%1$dKbps"</string> <string name="details_mbps">"%1$gMbps"</string> <string name="details_ok">"확인"</string> <string name="context_menu_header">"사진 옵션"</string> <string name="video_context_menu_header">"동영상 옵션"</string> <string name="multiface_crop_help">"시작하려면 얼굴을 탭하세요."</string> <string name="photos_gallery_title">"갤러리"</string> <string name="pick_photos_gallery_title">"사진 선택"</string> <string name="videos_gallery_title">"갤러리"</string> <string name="pick_videos_gallery_title">"동영상 선택"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g>개 남음"</string> <string name="sendImage">"사진 공유 응용프로그램"</string> <string name="setImage">"사진 설정"</string> <string name="sendVideo">"동영상 공유 응용프로그램"</string> <string name="movieviewlabel">"영화"</string> <string name="loading_video">"동영상 로드 중..."</string> <string name="spaceIsLow_title">"공간부족"</string> <string name="spaceIsLow_content">"SD 카드의 공간이 부족합니다. 화질 설정을 변경하거나 갤러리에서 항목을 삭제하세요."</string> <string name="resume_playing_title">"동영상 다시 시작"</string> <string name="resume_playing_message">"%s에서 재생을 다시 시작하시겠습니까?"</string> <string name="resume_playing_resume">"재생 다시 시작"</string> <string name="resume_playing_restart">"시작"</string> <string name="gadget_title">"사진 프레임"</string> <string name="file_info_title">"파일 정보:"</string> <string name="video_exceed_mms_limit">"녹화한 동영상이 너무 커서 MMS를 통해 전송할 수 없습니다. 클립의 길이를 더 짧게 녹화하세요."</string> <string name="too_large_to_attach">"파일이 너무 커서 첨부할 수 없습니다."</string> </resources> diff --git a/res/values-nb/strings.xml b/res/values-nb/strings.xml index b391b90..63adfaa 100644 --- a/res/values-nb/strings.xml +++ b/res/values-nb/strings.xml @@ -1,156 +1,158 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Alle bilder"</string> <string name="all_videos">"Alle videoer"</string> <string name="camera_label">"Kamera"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> <string name="gallery_picker_label">"Galleri"</string> <string name="gallery_camera_bucket_name">"Bilder fra kamera"</string> <string name="gallery_camera_videos_bucket_name">"Videoer fra kamera"</string> <string name="switch_to_video_lable">"Bytt til video"</string> <string name="switch_to_camera_lable">"Bytt til kamera"</string> <string name="crop_label">"Beskjær bilde"</string> <string name="view_label">"Se på bilde"</string> <string name="preferences_label">"Kamerainnstillinger"</string> <string name="wait">"Vent litt…"</string> <string name="no_storage">"Sett inn et minnekort før du bruker kameraet."</string> <string name="not_enough_space">"Minnekortet er fullt."</string> <string name="preparing_sd">"Forbereder minnekort…"</string> <string name="wallpaper">"Setter bakgrunnsbilde, vent litt…"</string> <string name="savingImage">"Lagrer bilde…"</string> <string name="runningFaceDetection">"Vent litt…"</string> <string name="flip_orientation">"Roter skjerm"</string> <string name="settings">"Innstillinger"</string> <string name="view">"Vis"</string> <string name="details">"Detaljer"</string> <string name="rotate">"Roter"</string> <string name="rotate_left">"Roter mot venstre"</string> <string name="rotate_right">"Roter mot høyre"</string> <string name="slide_show">"Lysbildevisning"</string> <string name="capture_picture">"Ta bilde"</string> <string name="capture_video">"Ta opp video"</string> <string name="crop_save_text">"Lagre"</string> <string name="crop_discard_text">"Forkast"</string> <string name="confirm_delete_title">"Slett"</string> <string name="confirm_delete_message">"Bildet vil bli slettet."</string> <string name="confirm_delete_video_message">"Videoen vil bli slettet."</string> <string name="camera_toss">"Slett"</string> <string name="camera_gallery">"Galleri"</string> <string name="camera_share">"Del"</string> <string name="camera_set">"Bruk som"</string> <string name="camera_play">"Spill"</string> <string name="camera_attach">"Legg ved"</string> <string name="camera_cancel">"Avbryt"</string> <string name="camera_crop">"Beskjær"</string> <string name="camera_tossing">"Sletter…"</string> <string name="no_way_to_share_image">"Bildet kan ikke deles."</string> <string name="no_way_to_share_video">"Videoen kan ikke deles."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galleri"</string> <string name="camera_pick_wallpaper">"Bilder"</string> <string name="camera_setas_wallpaper">"Bakgrunnsbilder"</string> <string name="pref_gallery_category">"Generelle innstillinger"</string> <string name="pref_slideshow_category">"Innstillinger for lysbildevisning"</string> <string name="pref_camera_general_settings_category">"Generelle innstillinger"</string> <string name="pref_gallery_size_title">"Bildestørrelse"</string> <string name="pref_gallery_size_summary">"Velg hvor stort bilder skal vises"</string> <string name="pref_gallery_size_dialogtitle">"Bildestørrelse"</string> <string-array name="pref_gallery_size_choices"> <item>"Stor"</item> <item>"Liten"</item> </string-array> <string name="pref_gallery_sort_title">"Bildesortering"</string> <string name="pref_gallery_sort_summary">"Velg i hvilken rekkefølge bildene skal sorteres"</string> <string name="pref_gallery_sort_dialogtitle">"Bildesortering"</string> <string-array name="pref_gallery_sort_choices"> <item>"Nyeste først"</item> <item>"Nyeste sist"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Pause i lysbildevisning"</string> <string name="pref_gallery_slideshow_interval_summary">"Velg hvor lenge hvert lysbilde skal vises"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Pause i lysbildevisning"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 sekunder"</item> <item>"3 sekunder"</item> <item>"4 sekunder"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Lysbildeovergang"</string> <string name="pref_gallery_slideshow_transition_summary">"Velg effekten som skal brukes mellom lysbilder"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Lysbildevergang"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ton inn og ut"</item> <item>"Skli venstre - høyre"</item> <item>"Skli opp - ned"</item> <item>"Tilfeldig"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Gjenta lysbildeserie"</string> <string name="pref_gallery_slideshow_repeat_summary">"Vis lydbildeserie mer enn en gang"</string> <string name="pref_gallery_slideshow_shuffle_title">"Stokk lysbilder"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Vis bilder i tilfeldig rekkefølge"</string> <string name="pref_camera_recordlocation_title">"Lagre sted i bilder"</string> <string name="pref_camera_recordlocation_summary">"Lagre sted i bildedata"</string> <string name="pref_camera_videoquality_category">"Videokvalitet"</string> <string name="pref_camera_videoquality_title">"Videokvalitet"</string> <string name="pref_camera_videoquality_entry_0">"Lav (for MMS-meldinger)"</string> <string name="pref_camera_videoquality_entry_1">"Høy (for minnekort)"</string> <string name="pref_camera_videoquality_dialogtitle">"Videokvalitet"</string> <string name="camerasettings">"Innstillinger"</string> <string name="image_gallery_NoImageView_text">"Fant ingen bilder."</string> <string name="pref_gallery_confirm_delete_title">"Bekreft sletting"</string> <string name="pref_gallery_confirm_delete_summary">"Vis bekreftelse før bilder slettes"</string> <string name="details_panel_title">"Detaljer"</string> <string name="details_file_size">"Filstørrelse:"</string> <string name="details_image_resolution">"Oppløsning:"</string> <string name="details_duration">"Varighet:"</string> <string name="details_date_taken">"Dato tatt:"</string> <string name="details_frame_rate">"Bildefrekvens:"</string> <string name="details_bit_rate">"Bitrate:"</string> <string name="details_codec">"Kodek:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Bildeinnstillinger"</string> <string name="video_context_menu_header">"Videoinnstillinger"</string> <string name="multiface_crop_help">"Trykk på et ansikt for å begynne."</string> <string name="photos_gallery_title">"Galleri"</string> <string name="pick_photos_gallery_title">"Velg bilde"</string> <string name="videos_gallery_title">"Galleri"</string> <string name="pick_videos_gallery_title">"Velg video"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> gjenstår"</string> <string name="sendImage">"Del bilde via"</string> <string name="setImage">"Bruk bilde som"</string> <string name="sendVideo">"Del video via"</string> <string name="movieviewlabel">"Filmer"</string> <string name="loading_video">"Laster video…"</string> <string name="spaceIsLow_title">"Lite plass"</string> <string name="spaceIsLow_content">"Minnekortet begynner å gå tom for plass. Endre kvalitetsinnstillingen eller slett bilder fra galleriet."</string> <string name="resume_playing_title">"Fortsett avspilling"</string> <string name="resume_playing_message">"Fortsett avspilling fra %s?"</string> <string name="resume_playing_resume">"Fortsett avspilling"</string> <string name="resume_playing_restart">"Begynn på nytt"</string> <string name="gadget_title">"Bilderamme"</string> <string name="file_info_title">"Filinformasjon:"</string> <string name="video_exceed_mms_limit">"Videoen er for stor til å sendes over MMS. Prøv å ta opp en kortere video."</string> <!-- no translation found for too_large_to_attach (8944461117941172986) --> <skip /> </resources> diff --git a/res/values-nl/strings.xml b/res/values-nl/strings.xml index 321ce4d..e6a6ad7 100644 --- a/res/values-nl/strings.xml +++ b/res/values-nl/strings.xml @@ -1,155 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Alle foto\'s"</string> <string name="all_videos">"Alle video\'s"</string> <string name="camera_label">"Camera"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> <string name="gallery_picker_label">"Galerij"</string> <string name="gallery_camera_bucket_name">"Camerafoto\'s"</string> <string name="gallery_camera_videos_bucket_name">"Cameravideo\'s"</string> <string name="switch_to_video_lable">"Overschakelen naar video"</string> <string name="switch_to_camera_lable">"Overschakelen naar camera"</string> <string name="crop_label">"Foto bijsnijden"</string> <string name="view_label">"Foto weergeven"</string> <string name="preferences_label">"Camera-instellingen"</string> <string name="wait">"Een ogenblik geduld..."</string> <string name="no_storage">"Plaats een SD-kaart voordat u de camera gebruikt."</string> <string name="not_enough_space">"De SD-kaart is vol."</string> <string name="preparing_sd">"SD-kaart voorbereiden…"</string> <string name="wallpaper">"Achtergrond wordt ingesteld. Een ogenblik geduld..."</string> <string name="savingImage">"Foto opslaan..."</string> <string name="runningFaceDetection">"Een ogenblik geduld..."</string> <string name="flip_orientation">"Stand draaien"</string> <string name="settings">"Instellingen"</string> <string name="view">"Weergeven"</string> <string name="details">"Details"</string> <string name="rotate">"Draaien"</string> <string name="rotate_left">"Linksom draaien"</string> <string name="rotate_right">"Rechtsom draaien"</string> <string name="slide_show">"Diavoorstelling"</string> <string name="capture_picture">"Foto nemen"</string> <string name="capture_video">"Video opnemen"</string> <string name="crop_save_text">"Opslaan"</string> <string name="crop_discard_text">"Ongedaan maken"</string> <string name="confirm_delete_title">"Verwijderen"</string> <string name="confirm_delete_message">"De foto wordt verwijderd."</string> <string name="confirm_delete_video_message">"De video wordt verwijderd"</string> <string name="camera_toss">"Verwijderen"</string> <string name="camera_gallery">"Galerij"</string> <string name="camera_share">"Delen"</string> <string name="camera_set">"Instellen als"</string> <string name="camera_play">"Afspelen"</string> <string name="camera_attach">"Bijvoegen"</string> <string name="camera_cancel">"Annuleren"</string> <string name="camera_crop">"Bijsnijden"</string> <string name="camera_tossing">"Verwijderen..."</string> <string name="no_way_to_share_image">"Deze foto kan niet worden gedeeld."</string> <string name="no_way_to_share_video">"Deze video kan niet worden gedeeld."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galerij"</string> <string name="camera_pick_wallpaper">"Foto\'s"</string> <string name="camera_setas_wallpaper">"Achtergrond"</string> <string name="pref_gallery_category">"Algemene instellingen"</string> <string name="pref_slideshow_category">"Instellingen van diavoorstelling"</string> <string name="pref_camera_general_settings_category">"Algemene instellingen"</string> <string name="pref_gallery_size_title">"Weergavegrootte"</string> <string name="pref_gallery_size_summary">"De weergavegrootte van foto\'s en video\'s selecteren"</string> <string name="pref_gallery_size_dialogtitle">"Grootte van foto"</string> <string-array name="pref_gallery_size_choices"> <item>"Groot"</item> <item>"Klein"</item> </string-array> <string name="pref_gallery_sort_title">"Sorteervolgorde"</string> <string name="pref_gallery_sort_summary">"De sorteervolgorde van foto\'s en video\'s selecteren"</string> <string name="pref_gallery_sort_dialogtitle">"Foto\'s sorteren"</string> <string-array name="pref_gallery_sort_choices"> <item>"Nieuwste eerst"</item> <item>"Nieuwste eerst"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Interval in diavoorstelling"</string> <string name="pref_gallery_slideshow_interval_summary">"Selecteren hoe lang elke dia wordt weergegeven in de voorstelling"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Interval in diavoorstelling"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 seconden"</item> <item>"3 seconden"</item> <item>"4 seconden"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Overgangen in diavoorstellingen"</string> <string name="pref_gallery_slideshow_transition_summary">"Het effect selecteren dat wordt gebruikt om naar de volgende dia te gaan"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Overgangen in diavoorstellingen"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Infaden/uitfaden"</item> <item>"Dia vanaf linkerkant/rechterkant"</item> <item>"Dia vanaf bovenkant/onderkant"</item> <item>"Willekeurige selectie"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Diavoorstelling herhalen"</string> <string name="pref_gallery_slideshow_repeat_summary">"Diavoorstelling meerdere keren afspelen"</string> <string name="pref_gallery_slideshow_shuffle_title">"Dia\'s in willekeurige volgorde weergeven"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Foto\'s in willekeurige volgorde weergeven"</string> <string name="pref_camera_recordlocation_title">"Locatie opslaan in foto\'s"</string> <string name="pref_camera_recordlocation_summary">"Locatie vastleggen in de gegevens van de foto"</string> <string name="pref_camera_videoquality_category">"Videokwaliteit"</string> <string name="pref_camera_videoquality_title">"Videokwaliteit selecteren"</string> <string name="pref_camera_videoquality_entry_0">"Laag (voor MMS-berichten)"</string> <string name="pref_camera_videoquality_entry_1">"Hoog (voor SD-kaart)"</string> <string name="pref_camera_videoquality_dialogtitle">"Videokwaliteit"</string> <string name="camerasettings">"Instellingen"</string> <string name="image_gallery_NoImageView_text">"Geen medium gevonden."</string> <string name="pref_gallery_confirm_delete_title">"Verwijderen bevestigen"</string> <string name="pref_gallery_confirm_delete_summary">"Bevestiging weergeven voordat een foto of video wordt verwijderd"</string> <string name="details_panel_title">"Details"</string> <string name="details_file_size">"Bestandsgrootte:"</string> <string name="details_image_resolution">"Resolutie:"</string> <string name="details_duration">"Duur:"</string> <string name="details_date_taken">"Gemaakt op:"</string> <string name="details_frame_rate">"Framesnelheid:"</string> <string name="details_bit_rate">"Bitsnelheid:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Indeling:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opties voor foto\'s"</string> <string name="video_context_menu_header">"Video-opties"</string> <string name="multiface_crop_help">"Tik op een gezicht om te beginnen."</string> <string name="photos_gallery_title">"Galerij"</string> <string name="pick_photos_gallery_title">"Foto selecteren"</string> <string name="videos_gallery_title">"Galerij"</string> <string name="pick_videos_gallery_title">"Video selecteren"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> resterend"</string> <string name="sendImage">"Foto delen via"</string> <string name="setImage">"Foto instellen als"</string> <string name="sendVideo">"Video delen via"</string> <string name="movieviewlabel">"Films"</string> <string name="loading_video">"Video laden..."</string> <string name="spaceIsLow_title">"Er is weinig ruimte"</string> <string name="spaceIsLow_content">"Er is weinig ruimte beschikbaar op uw SD-kaart. U kunt de kwaliteitsinstelling wijzigen of items uit de galerij verwijderen."</string> <string name="resume_playing_title">"Video hervatten"</string> <string name="resume_playing_message">"Afspelen hervatten vanaf %s ?"</string> <string name="resume_playing_resume">"Afspelen hervatten"</string> <string name="resume_playing_restart">"Opnieuw starten"</string> <string name="gadget_title">"Fotolijstje"</string> <string name="file_info_title">"Bestandsinformatie:"</string> <string name="video_exceed_mms_limit">"De video die u heeft opgenomen, is te lang om via MMS te verzenden. Neem een kortere video op."</string> <string name="too_large_to_attach">"Bestand is te groot om bij te voegen."</string> </resources> diff --git a/res/values-pl/strings.xml b/res/values-pl/strings.xml index fa62ac3..be0250e 100644 --- a/res/values-pl/strings.xml +++ b/res/values-pl/strings.xml @@ -1,155 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Wszystkie zdjęcia"</string> <string name="all_videos">"Wszystkie filmy"</string> <string name="camera_label">"Aparat"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> <string name="gallery_picker_label">"Galeria"</string> <string name="gallery_camera_bucket_name">"Zdjęcia z aparatu"</string> <string name="gallery_camera_videos_bucket_name">"Filmy z aparatu"</string> <string name="switch_to_video_lable">"Przełącz na wideo"</string> <string name="switch_to_camera_lable">"Przełącz na aparat"</string> <string name="crop_label">"Przytnij zdjęcie"</string> <string name="view_label">"Wyświetl zdjęcie"</string> <string name="preferences_label">"Ustawienia aparatu"</string> <string name="wait">"Poczekaj…"</string> <string name="no_storage">"Zanim zaczniesz korzystać z aparatu fotograficznego, włóż kartę SD."</string> <string name="not_enough_space">"Karta SD jest pełna."</string> <string name="preparing_sd">"Przygotowywanie karty SD..."</string> <string name="wallpaper">"Ustawianie tapety, poczekaj…"</string> <string name="savingImage">"Trwa zapisywanie zdjęcia…"</string> <string name="runningFaceDetection">"Poczekaj…"</string> <string name="flip_orientation">"Zmień orientację"</string> <string name="settings">"Ustawienia"</string> <string name="view">"Wyświetl"</string> <string name="details">"Szczegóły"</string> <string name="rotate">"Obróć"</string> <string name="rotate_left">"Obróć w lewo"</string> <string name="rotate_right">"Obróć w prawo"</string> <string name="slide_show">"Pokaz slajdów"</string> <string name="capture_picture">"Zrób zdjęcie"</string> <string name="capture_video">"Nagraj film wideo"</string> <string name="crop_save_text">"Zapisz"</string> <string name="crop_discard_text">"Odrzuć"</string> <string name="confirm_delete_title">"Usuń"</string> <string name="confirm_delete_message">"Zdjęcie zostanie usunięte."</string> <string name="confirm_delete_video_message">"Film wideo zostanie usunięty."</string> <string name="camera_toss">"Usuń"</string> <string name="camera_gallery">"Galeria"</string> <string name="camera_share">"Prześlij"</string> <string name="camera_set">"Ustaw jako"</string> <string name="camera_play">"Odtwórz"</string> <string name="camera_attach">"Załącz"</string> <string name="camera_cancel">"Anuluj"</string> <string name="camera_crop">"Przytnij"</string> <string name="camera_tossing">"Trwa usuwanie…"</string> <string name="no_way_to_share_image">"Nie można przesłać tego zdjęcia."</string> <string name="no_way_to_share_video">"Nie można przesłać tego filmu."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galeria"</string> <string name="camera_pick_wallpaper">"Zdjęcia"</string> <string name="camera_setas_wallpaper">"Tapeta"</string> <string name="pref_gallery_category">"Ustawienia ogólne"</string> <string name="pref_slideshow_category">"Ustawienia pokazu slajdów"</string> <string name="pref_camera_general_settings_category">"Ustawienia ogólne"</string> <string name="pref_gallery_size_title">"Rozmiar zdjęć i filmów"</string> <string name="pref_gallery_size_summary">"Ustaw wyświetlany rozmiar zdjęć i filmów"</string> <string name="pref_gallery_size_dialogtitle">"Rozmiar"</string> <string-array name="pref_gallery_size_choices"> <item>"Duży"</item> <item>"Mały"</item> </string-array> <string name="pref_gallery_sort_title">"Kolejność sortowania"</string> <string name="pref_gallery_sort_summary">"Wybierz kolejność sortowania zdjęć i filmów"</string> <string name="pref_gallery_sort_dialogtitle">"Sortowanie zdjęć"</string> <string-array name="pref_gallery_sort_choices"> <item>"Od najnowszego"</item> <item>"Od najstarszego"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Pokaz slajdów – interwał"</string> <string name="pref_gallery_slideshow_interval_summary">"Wybierz, jak długo mają być wyświetlane poszczególne zdjęcia w pokazie slajdów"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Pokaz slajdów – interwał"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 sekundy"</item> <item>"3 sekundy"</item> <item>"4 sekundy"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Pokaz slajdów – efekty"</string> <string name="pref_gallery_slideshow_transition_summary">"Wybierz efekt używany przy przejściu z jednego zdjęcia do kolejnego"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Pokaz slajdów – efekty"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Pojawianie i znikanie"</item> <item>"Przesuwanie z lewa w prawo"</item> <item>"Przesuwanie góra-dół"</item> <item>"Wybór losowy"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Powtórz pokaz slajdów"</string> <string name="pref_gallery_slideshow_repeat_summary">"Wyświetlaj pokaz slajdów więcej niż raz"</string> <string name="pref_gallery_slideshow_shuffle_title">"Losowa kolejność"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Wyświetlaj zdjęcia w kolejności losowej"</string> <string name="pref_camera_recordlocation_title">"Zapisuj lokalizację w zdjęciach"</string> <string name="pref_camera_recordlocation_summary">"Zapisz lokalizację w danych zdjęcia"</string> <string name="pref_camera_videoquality_category">"Jakość wideo"</string> <string name="pref_camera_videoquality_title">"Wybierz jakość wideo"</string> <string name="pref_camera_videoquality_entry_0">"Niska (dla wiadomości MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Wysoka (dla karty SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Jakość wideo"</string> <string name="camerasettings">"Ustawienia"</string> <string name="image_gallery_NoImageView_text">"Brak plików."</string> <string name="pref_gallery_confirm_delete_title">"Potwierdzanie usuwania"</string> <string name="pref_gallery_confirm_delete_summary">"Wyświetl potwierdzenie przed usunięciem zdjęcia lub filmu"</string> <string name="details_panel_title">"Szczegóły"</string> <string name="details_file_size">"Rozmiar pliku:"</string> <string name="details_image_resolution">"Rozdzielczość:"</string> <string name="details_duration">"Czas trwania:"</string> <string name="details_date_taken">"Data zrobienia zdjęcia:"</string> <string name="details_frame_rate">"Szybkość klatek:"</string> <string name="details_bit_rate">"Szybkość transmisji:"</string> <string name="details_codec">"Kodek:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d ramek/s"</string> <string name="details_kbps">"%1$d Kb/s"</string> <string name="details_mbps">"%1$g Mb/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opcje zdjęć"</string> <string name="video_context_menu_header">"Opcje wideo"</string> <string name="multiface_crop_help">"Dotknij twarzy, aby rozpocząć"</string> <string name="photos_gallery_title">"Galeria"</string> <string name="pick_photos_gallery_title">"Wybierz zdjęcie"</string> <string name="videos_gallery_title">"Galeria"</string> <string name="pick_videos_gallery_title">"Wybierz film wideo"</string> <string name="loading_progress_format_string">"Pozostało <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Prześlij zdjęcie następującą drogą:"</string> <string name="setImage">"Ustaw zdjęcie jako"</string> <string name="sendVideo">"Prześlij film następującą drogą:"</string> <string name="movieviewlabel">"Filmy"</string> <string name="loading_video">"Ładowanie filmu..."</string> <string name="spaceIsLow_title">"Miejsca jest mało"</string> <string name="spaceIsLow_content">"Na karcie SD brakuje miejsca. Zmień ustawienie jakości lub usuń elementy z Galerii."</string> <string name="resume_playing_title">"Wznów film"</string> <string name="resume_playing_message">"Wznowić odtwarzanie od %s?"</string> <string name="resume_playing_resume">"Wznów odtwarzanie"</string> <string name="resume_playing_restart">"Rozpocznij"</string> <string name="gadget_title">"Ramka zdjęcia"</string> <string name="file_info_title">"Informacje o pliku:"</string> <string name="video_exceed_mms_limit">"Nagrany film wideo jest zbyt duży, aby wysłać go w wiadomości MMS. Spróbuj nagrać krótszy film wideo."</string> <string name="too_large_to_attach">"Plik jest zbyt duży do załączenia."</string> </resources> diff --git a/res/values-ru/strings.xml b/res/values-ru/strings.xml index bb0c594..940dbba 100644 --- a/res/values-ru/strings.xml +++ b/res/values-ru/strings.xml @@ -1,155 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Все изображения"</string> <string name="all_videos">"Все видео"</string> <string name="camera_label">"Камера"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> <string name="gallery_picker_label">"Галерея"</string> <string name="gallery_camera_bucket_name">"Фотографии с камеры"</string> <string name="gallery_camera_videos_bucket_name">"Видео с камеры"</string> <string name="switch_to_video_lable">"Перейти в режим видео"</string> <string name="switch_to_camera_lable">"Перейти в режим камеры"</string> <string name="crop_label">"Обрезать изображение"</string> <string name="view_label">"Просмотреть изображение"</string> <string name="preferences_label">"Настройки камеры"</string> <string name="wait">"Подождите…"</string> <string name="no_storage">"Перед использованием камеры вставьте карту SD."</string> <string name="not_enough_space">"Карта SD заполнена."</string> <string name="preparing_sd">"Подготовка карты SD..."</string> <string name="wallpaper">"Установка фонового рисунка, подождите…"</string> <string name="savingImage">"Идет сохранение изображения…"</string> <string name="runningFaceDetection">"Подождите…"</string> <string name="flip_orientation">"Изменить ориентацию"</string> <string name="settings">"Настройки"</string> <string name="view">"Просмотреть"</string> <string name="details">"Сведения"</string> <string name="rotate">"Повернуть"</string> <string name="rotate_left">"Повернуть налево"</string> <string name="rotate_right">"Повернуть направо"</string> <string name="slide_show">"Слайд-шоу"</string> <string name="capture_picture">"Сделать фотографию"</string> <string name="capture_video">"Снять видео"</string> <string name="crop_save_text">"Сохранить"</string> <string name="crop_discard_text">"Отменить"</string> <string name="confirm_delete_title">"Удаление"</string> <string name="confirm_delete_message">"Изображение будет удалено."</string> <string name="confirm_delete_video_message">"Видео будет удалено."</string> <string name="camera_toss">"Удаление"</string> <string name="camera_gallery">"Галерея"</string> <string name="camera_share">"Отправить"</string> <string name="camera_set">"Установить как"</string> <string name="camera_play">"Воспроизвести"</string> <string name="camera_attach">"Вложить"</string> <string name="camera_cancel">"Отмена"</string> <string name="camera_crop">"Обрезать"</string> <string name="camera_tossing">"Идет удаление…"</string> <string name="no_way_to_share_image">"Отправить это изображение нельзя."</string> <string name="no_way_to_share_video">"Отправить это видео нельзя."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Галерея"</string> <string name="camera_pick_wallpaper">"Изображения"</string> <string name="camera_setas_wallpaper">"Фоновый рисунок"</string> <string name="pref_gallery_category">"Общие настройки"</string> <string name="pref_slideshow_category">"Настройки слайд-шоу"</string> <string name="pref_camera_general_settings_category">"Общие настройки"</string> <string name="pref_gallery_size_title">"Отображаемый размер"</string> <string name="pref_gallery_size_summary">"Выбор отображаемого размера изображений и видео"</string> <string name="pref_gallery_size_dialogtitle">"Размер изображения"</string> <string-array name="pref_gallery_size_choices"> <item>"Крупный"</item> <item>"Мелкий"</item> </string-array> <string name="pref_gallery_sort_title">"Порядок сортировки"</string> <string name="pref_gallery_sort_summary">"Выберите порядок сортировки изображений и видео"</string> <string name="pref_gallery_sort_dialogtitle">"Сортировка изображений"</string> <string-array name="pref_gallery_sort_choices"> <item>"Начиная с новых"</item> <item>"Заканчивая новыми"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Интервал слайд-шоу"</string> <string name="pref_gallery_slideshow_interval_summary">"Выберите время отображения каждого слайда"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Интервал слайд-шоу"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 секунды"</item> <item>"3 секунды"</item> <item>"4 секунды"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Переходы слайд-шоу"</string> <string name="pref_gallery_slideshow_transition_summary">"Выберите эффект для перехода от одного слайда к другому"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Переходы слайд-шоу"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Затемнение"</item> <item>"Слайды слева направо"</item> <item>"Слайды сверху вниз"</item> <item>"Случайный выбор"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Повторить слайд-шоу"</string> <string name="pref_gallery_slideshow_repeat_summary">"Воспроизвести слайд-шоу несколько раз"</string> <string name="pref_gallery_slideshow_shuffle_title">"Перемешать слайды"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Показывать изображения в случайном порядке"</string> <string name="pref_camera_recordlocation_title">"Сохранять адрес в изображениях"</string> <string name="pref_camera_recordlocation_summary">"Записывать адрес в данные изображения"</string> <string name="pref_camera_videoquality_category">"Качество видео"</string> <string name="pref_camera_videoquality_title">"Выбор качества видео"</string> <string name="pref_camera_videoquality_entry_0">"Низкое (для MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Высокое (для карты SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Качество видео"</string> <string name="camerasettings">"Настройки"</string> <string name="image_gallery_NoImageView_text">"Нет мультимедийных материалов."</string> <string name="pref_gallery_confirm_delete_title">"Подтверждение удаления"</string> <string name="pref_gallery_confirm_delete_summary">"Запрашивать подтверждения перед удалением изображения или видео"</string> <string name="details_panel_title">"Сведения"</string> <string name="details_file_size">"Размер файла:"</string> <string name="details_image_resolution">"Разрешение:"</string> <string name="details_duration">"Продолжительность:"</string> <string name="details_date_taken">"Дата съемки:"</string> <string name="details_frame_rate">"Частота кадров:"</string> <string name="details_bit_rate">"Битрейт:"</string> <string name="details_codec">"Кодек:"</string> <string name="details_format">"Формат:"</string> <string name="details_dimension_x">"%1$d на %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d кадров/с"</string> <string name="details_kbps">"%1$d кбит/с"</string> <string name="details_mbps">"%1$g мбит/с"</string> <string name="details_ok">"ОК"</string> <string name="context_menu_header">"Параметры изображения"</string> <string name="video_context_menu_header">"Параметры видео"</string> <string name="multiface_crop_help">"Чтобы начать, выберите лицо."</string> <string name="photos_gallery_title">"Галерея"</string> <string name="pick_photos_gallery_title">"Выбор изображения"</string> <string name="videos_gallery_title">"Галерея"</string> <string name="pick_videos_gallery_title">"Выбрать видео"</string> <string name="loading_progress_format_string">"Осталось: <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Отправить изображение при помощи"</string> <string name="setImage">"Установить изображение как"</string> <string name="sendVideo">"Отправить видео при помощи"</string> <string name="movieviewlabel">"Фильмы"</string> <string name="loading_video">"Идет загрузка видео…"</string> <string name="spaceIsLow_title">"Осталось мало места"</string> <string name="spaceIsLow_content">"Место на карте SD заканчивается. Измените настройки качества или удалите элементы из галереи."</string> <string name="resume_playing_title">"Продолжение просмотра видео"</string> <string name="resume_playing_message">"Продолжить воспроизведение с %s ?"</string> <string name="resume_playing_resume">"Продолжить воспроизведение"</string> <string name="resume_playing_restart">"Начать с начала"</string> <string name="gadget_title">"Рамка фотографии"</string> <string name="file_info_title">"Сведения о файле:"</string> <string name="video_exceed_mms_limit">"Записанное видео имеет слишком большой размер для отправки в MMS. Запишите более короткий ролик."</string> <string name="too_large_to_attach">"Файл имеет слишком большой размер и не может быть вложен."</string> </resources> diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml index 4ed6bd4..2d0bb24 100644 --- a/res/values-zh-rCN/strings.xml +++ b/res/values-zh-rCN/strings.xml @@ -1,155 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"所有图片"</string> <string name="all_videos">"所有视频"</string> <string name="camera_label">"相机"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> <string name="gallery_picker_label">"图片库"</string> <string name="gallery_camera_bucket_name">"相机照片"</string> <string name="gallery_camera_videos_bucket_name">"相机视频"</string> <string name="switch_to_video_lable">"切换到视频"</string> <string name="switch_to_camera_lable">"切换到相机"</string> <string name="crop_label">"裁切图片"</string> <string name="view_label">"查看图片"</string> <string name="preferences_label">"相机设置"</string> <string name="wait">"请稍候..."</string> <string name="no_storage">"请在使用相机之前插入 SD 卡。"</string> <string name="not_enough_space">"您的 SD 卡已满。"</string> <string name="preparing_sd">"正在准备 SD 卡..."</string> <string name="wallpaper">"正在设置壁纸,请稍候..."</string> <string name="savingImage">"正在保存图片..."</string> <string name="runningFaceDetection">"请稍候..."</string> <string name="flip_orientation">"反转方向"</string> <string name="settings">"设置"</string> <string name="view">"查看"</string> <string name="details">"详细信息"</string> <string name="rotate">"旋转"</string> <string name="rotate_left">"向左旋转"</string> <string name="rotate_right">"向右旋转"</string> <string name="slide_show">"幻灯片演示"</string> <string name="capture_picture">"拍摄照片"</string> <string name="capture_video">"拍摄视频"</string> <string name="crop_save_text">"保存"</string> <string name="crop_discard_text">"放弃"</string> <string name="confirm_delete_title">"删除"</string> <string name="confirm_delete_message">"会删除该图片。"</string> <string name="confirm_delete_video_message">"会删除该视频。"</string> <string name="camera_toss">"删除"</string> <string name="camera_gallery">"图片库"</string> <string name="camera_share">"共享"</string> <string name="camera_set">"设置为"</string> <string name="camera_play">"播放"</string> <string name="camera_attach">"附加"</string> <string name="camera_cancel">"取消"</string> <string name="camera_crop">"裁切"</string> <string name="camera_tossing">"正在删除..."</string> <string name="no_way_to_share_image">"无法共享此图片。"</string> <string name="no_way_to_share_video">"无法共享此视频。"</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"图片库"</string> <string name="camera_pick_wallpaper">"图片"</string> <string name="camera_setas_wallpaper">"壁纸"</string> <string name="pref_gallery_category">"常规设置"</string> <string name="pref_slideshow_category">"幻灯片演示设置"</string> <string name="pref_camera_general_settings_category">"常规设置"</string> <string name="pref_gallery_size_title">"显示大小"</string> <string name="pref_gallery_size_summary">"选择图片和视频的显示大小"</string> <string name="pref_gallery_size_dialogtitle">"图片大小"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"排序顺序"</string> <string name="pref_gallery_sort_summary">"选择图片和视频的排序顺序"</string> <string name="pref_gallery_sort_dialogtitle">"图片排序"</string> <string-array name="pref_gallery_sort_choices"> <item>"最新的在最前面"</item> <item>"最新的在最后面"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"幻灯片演示间隔"</string> <string name="pref_gallery_slideshow_interval_summary">"选择每张幻灯片在演示中显示的时间长度"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"幻灯片演示间隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 秒"</item> <item>"3 秒"</item> <item>"4 秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"幻灯片演示过渡"</string> <string name="pref_gallery_slideshow_transition_summary">"选择从一张幻灯片移动到下一张时使用的效果"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"幻灯片演示过渡"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"逐渐增强和逐渐减弱"</item> <item>"自左至右滑动"</item> <item>"自上至下滑动"</item> <item>"随机选择"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"重复幻灯片演示"</string> <string name="pref_gallery_slideshow_repeat_summary">"多次播放幻灯片演示"</string> <string name="pref_gallery_slideshow_shuffle_title">"随机演示幻灯片"</string> <string name="pref_gallery_slideshow_shuffle_summary">"以随机顺序显示图片"</string> <string name="pref_camera_recordlocation_title">"在图片中存储位置"</string> <string name="pref_camera_recordlocation_summary">"通过图片数据记录位置"</string> <string name="pref_camera_videoquality_category">"视频质量"</string> <string name="pref_camera_videoquality_title">"选择视频质量"</string> <string name="pref_camera_videoquality_entry_0">"低(对于彩信)"</string> <string name="pref_camera_videoquality_entry_1">"高(对于 SD 卡)"</string> <string name="pref_camera_videoquality_dialogtitle">"视频质量"</string> <string name="camerasettings">"设置"</string> <string name="image_gallery_NoImageView_text">"找不到媒体。"</string> <string name="pref_gallery_confirm_delete_title">"确认删除"</string> <string name="pref_gallery_confirm_delete_summary">"在删除图片或视频前显示确认"</string> <string name="details_panel_title">"详细信息"</string> <string name="details_file_size">"文件大小:"</string> <string name="details_image_resolution">"分辨率:"</string> <string name="details_duration">"持续时间:"</string> <string name="details_date_taken">"拍摄日期:"</string> <string name="details_frame_rate">"帧频:"</string> <string name="details_bit_rate">"比特率:"</string> <string name="details_codec">"编解码器:"</string> <string name="details_format">"格式:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"确定"</string> <string name="context_menu_header">"图片选项"</string> <string name="video_context_menu_header">"视频选项"</string> <string name="multiface_crop_help">"轻击一张脸开始裁切。"</string> <string name="photos_gallery_title">"图片库"</string> <string name="pick_photos_gallery_title">"选择图片"</string> <string name="videos_gallery_title">"图片库"</string> <string name="pick_videos_gallery_title">"选择视频"</string> <string name="loading_progress_format_string">"还剩 <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"共享图片的方式"</string> <string name="setImage">"将图片设置为"</string> <string name="sendVideo">"共享视频的方式"</string> <string name="movieviewlabel">"电影"</string> <string name="loading_video">"正在载入视频..."</string> <string name="spaceIsLow_title">"空间不足"</string> <string name="spaceIsLow_content">"您的 SD 卡已满。请更改质量设置或删除图片库中的内容。"</string> <string name="resume_playing_title">"重新播放视频"</string> <string name="resume_playing_message">"从 %s 开始重新播放?"</string> <string name="resume_playing_resume">"重新播放"</string> <string name="resume_playing_restart">"重新开始"</string> <string name="gadget_title">"相框"</string> <string name="file_info_title">"文件信息:"</string> <string name="video_exceed_mms_limit">"您录制的视频太大,无法用彩信发送。请尝试录制短一点的剪辑。"</string> <string name="too_large_to_attach">"文件太大,无法附加。"</string> </resources> diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml index 93965fd..2c92912 100644 --- a/res/values-zh-rTW/strings.xml +++ b/res/values-zh-rTW/strings.xml @@ -1,155 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"所有相片"</string> <string name="all_videos">"所有影片"</string> <string name="camera_label">"相機"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> <string name="gallery_picker_label">"圖庫"</string> <string name="gallery_camera_bucket_name">"攝影機圖片"</string> <string name="gallery_camera_videos_bucket_name">"攝影機影片"</string> <string name="switch_to_video_lable">"切換為影片"</string> <string name="switch_to_camera_lable">"切換為攝影機"</string> <string name="crop_label">"裁切相片"</string> <string name="view_label">"檢視相片"</string> <string name="preferences_label">"相機設定"</string> <string name="wait">"請稍候…"</string> <string name="no_storage">"使用相機前請先插入 SD 卡。"</string> <string name="not_enough_space">"SD 卡已滿。"</string> <string name="preparing_sd">"正在準備 SD 卡..."</string> <string name="wallpaper">"設定桌布中,請稍候…"</string> <string name="savingImage">"儲存相片中…"</string> <string name="runningFaceDetection">"請稍候…"</string> <string name="flip_orientation">"旋轉方向"</string> <string name="settings">"設定"</string> <string name="view">"檢視"</string> <string name="details">"詳細資料"</string> <string name="rotate">"旋轉"</string> <string name="rotate_left">"向左旋轉"</string> <string name="rotate_right">"向右旋轉"</string> <string name="slide_show">"投影片"</string> <string name="capture_picture">"拍攝圖片"</string> <string name="capture_video">"拍攝影片"</string> <string name="crop_save_text">"儲存"</string> <string name="crop_discard_text">"放棄"</string> <string name="confirm_delete_title">"刪除"</string> <string name="confirm_delete_message">"此相片會被刪除。"</string> <string name="confirm_delete_video_message">"將刪除此影片。"</string> <string name="camera_toss">"刪除"</string> <string name="camera_gallery">"圖庫"</string> <string name="camera_share">"分享"</string> <string name="camera_set">"設為"</string> <string name="camera_play">"播放"</string> <string name="camera_attach">"附加"</string> <string name="camera_cancel">"取消"</string> <string name="camera_crop">"裁切"</string> <string name="camera_tossing">"刪除中…"</string> <string name="no_way_to_share_image">"此相片無法分享。"</string> <string name="no_way_to_share_video">"此影片無法分享。"</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"圖庫"</string> <string name="camera_pick_wallpaper">"相片"</string> <string name="camera_setas_wallpaper">"桌布"</string> <string name="pref_gallery_category">"一般設定"</string> <string name="pref_slideshow_category">"投影片設定"</string> <string name="pref_camera_general_settings_category">"一般設定"</string> <string name="pref_gallery_size_title">"顯示大小"</string> <string name="pref_gallery_size_summary">"選取相片和影片顯示大小"</string> <string name="pref_gallery_size_dialogtitle">"相片大小"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"排序順序"</string> <string name="pref_gallery_sort_summary">"選取相片和影片排序順序"</string> <string name="pref_gallery_sort_dialogtitle">"圖片排序"</string> <string-array name="pref_gallery_sort_choices"> <item>"最新的優先"</item> <item>"最舊的優先"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"投影片顯示間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"選取每張投影片顯示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"投影片顯示間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 秒"</item> <item>"3 秒"</item> <item>"4 秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"投影片轉場效果"</string> <string name="pref_gallery_slideshow_transition_summary">"選取相片更換時的轉場效果"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"投影片轉場效果"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"淡入淡出"</item> <item>"左右滑動"</item> <item>"上下滑動"</item> <item>"隨機選取"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"重複播放投影片"</string> <string name="pref_gallery_slideshow_repeat_summary">"播放投影片多次"</string> <string name="pref_gallery_slideshow_shuffle_title">"隨機播放投影片"</string> <string name="pref_gallery_slideshow_shuffle_summary">"隨機顯示相片"</string> <string name="pref_camera_recordlocation_title">"在相片儲存位置資訊"</string> <string name="pref_camera_recordlocation_summary">"在相片中紀錄位置資訊"</string> <string name="pref_camera_videoquality_category">"影片品質"</string> <string name="pref_camera_videoquality_title">"選取影片品質"</string> <string name="pref_camera_videoquality_entry_0">"低 (適用於多媒體簡訊)"</string> <string name="pref_camera_videoquality_entry_1">"高 (適用於 SD 卡)"</string> <string name="pref_camera_videoquality_dialogtitle">"影片品質"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"找不到媒體。"</string> <string name="pref_gallery_confirm_delete_title">"刪除確認"</string> <string name="pref_gallery_confirm_delete_summary">"刪除相片或影片前要顯示確認"</string> <string name="details_panel_title">"詳細資料"</string> <string name="details_file_size">"檔案大小:"</string> <string name="details_image_resolution">"解析度:"</string> <string name="details_duration">"所需時間:"</string> <string name="details_date_taken">"拍攝日期:"</string> <string name="details_frame_rate">"影格速率:"</string> <string name="details_bit_rate">"位元速率:"</string> <string name="details_codec">"編碼器:"</string> <string name="details_format">"格式:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"確定"</string> <string name="context_menu_header">"圖片選項"</string> <string name="video_context_menu_header">"影片選項"</string> <string name="multiface_crop_help">"選取版面開始裁切"</string> <string name="photos_gallery_title">"圖庫"</string> <string name="pick_photos_gallery_title">"選取相片"</string> <string name="videos_gallery_title">"圖庫"</string> <string name="pick_videos_gallery_title">"選取影片"</string> <string name="loading_progress_format_string">"還有 <xliff:g id="COUNTER">%d</xliff:g> 張"</string> <string name="sendImage">"透過…分享圖片"</string> <string name="setImage">"設定相片為…"</string> <string name="sendVideo">"透過…分享影片"</string> <string name="movieviewlabel">"電影"</string> <string name="loading_video">"正在載入影片…"</string> <string name="spaceIsLow_title">"空間不足"</string> <string name="spaceIsLow_content">"您的 SD 卡空間已快用完。請變更品質設定或刪除圖庫中的項目。"</string> <string name="resume_playing_title">"繼續播放影片"</string> <string name="resume_playing_message">"要從 %s 繼續播放嗎?"</string> <string name="resume_playing_resume">"繼續播放"</string> <string name="resume_playing_restart">"重新開始"</string> <string name="gadget_title">"相框"</string> <string name="file_info_title">"檔案資訊:"</string> <string name="video_exceed_mms_limit">"您所錄製的影片太大,無法透過 MMS 傳送。請試著錄製較短的影片。"</string> <string name="too_large_to_attach">"檔案太大,超過附檔上限。"</string> </resources>
brunsky/WS171-packages-apps-Camera
291f5d5e6128802839d31b3909c21283fb823de1
Automated import from //branches/cupcake/...@143012,143012
diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml index 03acbf0..2f183e2 100644 --- a/res/values-ja/strings.xml +++ b/res/values-ja/strings.xml @@ -1,155 +1,157 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"すべての写真"</string> <string name="all_videos">"すべての動画"</string> <string name="camera_label">"カメラ"</string> + <!-- no translation found for video_camera_label (2899292505526427293) --> + <skip /> <string name="gallery_picker_label">"ギャラリー"</string> <string name="gallery_camera_bucket_name">"カメラ (写真)"</string> <string name="gallery_camera_videos_bucket_name">"カメラ (動画)"</string> <string name="switch_to_video_lable">"ムービーに切替"</string> <string name="switch_to_camera_lable">"写真に切替"</string> <string name="crop_label">"トリミング"</string> <string name="view_label">"画像を表示"</string> <string name="preferences_label">"カメラ設定"</string> <string name="wait">"お待ちください..."</string> <string name="no_storage">"カメラを使用する前にSDカードを挿入してください。"</string> <string name="not_enough_space">"SDカードがいっぱいです。"</string> <string name="preparing_sd">"SDカードの準備中..."</string> <string name="wallpaper">"壁紙を設定しています。しばらくお待ちください..."</string> <string name="savingImage">"写真を保存中..."</string> <string name="runningFaceDetection">"お待ちください..."</string> <string name="flip_orientation">"画面の向きを変更"</string> <string name="settings">"設定"</string> <string name="view">"表示"</string> <string name="details">"詳細"</string> <string name="rotate">"回転"</string> <string name="rotate_left">"左に回転"</string> <string name="rotate_right">"右に回転"</string> <string name="slide_show">"スライドショー"</string> <string name="capture_picture">"写真撮影"</string> <string name="capture_video">"ムービー撮影"</string> <string name="crop_save_text">"保存"</string> <string name="crop_discard_text">"破棄"</string> <string name="confirm_delete_title">"削除"</string> <string name="confirm_delete_message">"画像を削除します。"</string> <string name="confirm_delete_video_message">"動画を削除します。"</string> <string name="camera_toss">"削除"</string> <string name="camera_gallery">"ギャラリー"</string> <string name="camera_share">"共有"</string> <string name="camera_set">"設定"</string> <string name="camera_play">"再生"</string> <string name="camera_attach">"添付"</string> <string name="camera_cancel">"キャンセル"</string> <string name="camera_crop">"トリミング"</string> <string name="camera_tossing">"削除中..."</string> <string name="no_way_to_share_image">"この画像は共有できません。"</string> <string name="no_way_to_share_video">"この動画は共有できません。"</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"ギャラリー"</string> <string name="camera_pick_wallpaper">"画像"</string> <string name="camera_setas_wallpaper">"壁紙"</string> <string name="pref_gallery_category">"全般設定"</string> <string name="pref_slideshow_category">"スライドショー設定"</string> <string name="pref_camera_general_settings_category">"全般設定"</string> <string name="pref_gallery_size_title">"表示サイズ"</string> <string name="pref_gallery_size_summary">"写真と動画の表示サイズを選択"</string> <string name="pref_gallery_size_dialogtitle">"画像サイズ"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"並び替え順"</string> <string name="pref_gallery_sort_summary">"画像と動画の表示順序を選択"</string> <string name="pref_gallery_sort_dialogtitle">"画像並べ替え"</string> <string-array name="pref_gallery_sort_choices"> <item>"日付の新しい順"</item> <item>"日付の古い順"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"スライドショーの間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"各スライドの表示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"スライドショーの間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2秒"</item> <item>"3秒"</item> <item>"4秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"スライドショーのトランジション"</string> <string name="pref_gallery_slideshow_transition_summary">"スライドが切り替わるときの効果を選択"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"スライドショーのトランジション"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"フェードイン&amp;アウト"</item> <item>"左右にスライド"</item> <item>"上下にスライド"</item> <item>"ランダムに選択"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"スライドショーを繰り返す"</string> <string name="pref_gallery_slideshow_repeat_summary">"スライドショーを繰り返す"</string> <string name="pref_gallery_slideshow_shuffle_title">"スライドのシャッフル"</string> <string name="pref_gallery_slideshow_shuffle_summary">"画像をランダムに表示する"</string> <string name="pref_camera_recordlocation_title">"位置情報を写真に記録する"</string> <string name="pref_camera_recordlocation_summary">"位置情報を写真データに記録する"</string> <string name="pref_camera_videoquality_category">"動画のクオリティ"</string> <string name="pref_camera_videoquality_title">"動画の画質を選択"</string> <string name="pref_camera_videoquality_entry_0">"低 (MMSメッセージ向け)"</string> <string name="pref_camera_videoquality_entry_1">"高 (SDカード向け)"</string> <string name="pref_camera_videoquality_dialogtitle">"動画のクオリティ"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"メディアが見つかりません。"</string> <string name="pref_gallery_confirm_delete_title">"削除確認"</string> <string name="pref_gallery_confirm_delete_summary">"画像や動画を削除する前に確認メッセージを表示"</string> <string name="details_panel_title">"詳細"</string> <string name="details_file_size">"ファイルサイズ:"</string> <string name="details_image_resolution">"解像度:"</string> <string name="details_duration">"再生時間:"</string> <string name="details_date_taken">"撮影日:"</string> <string name="details_frame_rate">"フレームレート:"</string> <string name="details_bit_rate">"ビットレート:"</string> <string name="details_codec">"コーデック:"</string> <string name="details_format">"形式:"</string> <string name="details_dimension_x">"%1$dx%2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$dfps"</string> <string name="details_kbps">"%1$dKbps"</string> <string name="details_mbps">"%1$gMbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"画像オプション"</string> <string name="video_context_menu_header">"動画オプション"</string> <string name="multiface_crop_help">"顔をタップして開始します。"</string> <string name="photos_gallery_title">"ギャラリー"</string> <string name="pick_photos_gallery_title">"画像を選択"</string> <string name="videos_gallery_title">"ギャラリー"</string> <string name="pick_videos_gallery_title">"動画を選択"</string> <string name="loading_progress_format_string">"残り<xliff:g id="COUNTER">%d</xliff:g>件"</string> <string name="sendImage">"画像を共有:"</string> <string name="setImage">"設定タイプ:"</string> <string name="sendVideo">"動画を共有"</string> <string name="movieviewlabel">"映画"</string> <string name="loading_video">"動画を読み込み中..."</string> <string name="spaceIsLow_title">"空き容量が残り少なくなっています"</string> <string name="spaceIsLow_content">"SDカードの容量が足りません。クオリティ設定を変更するか、ギャラリーからアイテムを削除してください。"</string> <string name="resume_playing_title">"動画の再開"</string> <string name="resume_playing_message">"再生を%sから再開しますか?"</string> <string name="resume_playing_resume">"再生を再開"</string> <string name="resume_playing_restart">"最初から再生"</string> <string name="gadget_title">"写真フレーム"</string> <string name="file_info_title">"ファイル情報:"</string> <string name="video_exceed_mms_limit">"録画した動画のサイズが大きすぎるため送信できません。録画時間を短縮してみてください。"</string> <string name="too_large_to_attach">"添付ファイルが大きすぎます。"</string> </resources>
brunsky/WS171-packages-apps-Camera
3f6a772ad10e2a71f182c946ebf8a48ff5e34c72
Automated import from //branches/cupcake/...@142891,142891
diff --git a/res/layout/viewimage.xml b/res/layout/viewimage.xml index b0d2034..a25375f 100644 --- a/res/layout/viewimage.xml +++ b/res/layout/viewimage.xml @@ -1,160 +1,159 @@ <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:id="@+id/rootLayout" - android:layout_width="fill_parent" - android:layout_height="fill_parent"> + android:id="@+id/rootLayout" + android:layout_width="fill_parent" + android:layout_height="fill_parent"> - <AbsoluteLayout android:id="@+id/slideShowContainer" - android:layout_width="fill_parent" - android:layout_height="fill_parent"> - <view android:id="@+id/image1_slideShow" - class="com.android.camera.ViewImage$ImageViewTouch" - android:background="#00000000" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - /> - <view android:id="@+id/image2_slideShow" - class="com.android.camera.ViewImage$ImageViewTouch" - android:background="#00000000" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - /> - </AbsoluteLayout> + <AbsoluteLayout android:id="@+id/slideShowContainer" + android:layout_width="fill_parent" + android:layout_height="fill_parent"> + <view android:id="@+id/image1_slideShow" + class="com.android.camera.ViewImage$ImageViewTouch" + android:background="#00000000" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + /> + <view android:id="@+id/image2_slideShow" + class="com.android.camera.ViewImage$ImageViewTouch" + android:background="#00000000" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + /> + </AbsoluteLayout> + + <AbsoluteLayout android:id="@+id/abs" + android:layout_width="fill_parent" + android:layout_height="fill_parent"> + <view class="com.android.camera.ViewImage$ScrollHandler" android:id="@+id/scroller" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:orientation="horizontal" + android:background="#FF000000" + android:layout_x="0dip" + android:layout_y="0dip"> + + <view android:id="@+id/image1" + class="com.android.camera.ViewImage$ImageViewTouch" + android:background="#FF000000" + android:layout_width="0dip" + android:layout_height="fill_parent" /> + + <View android:id="@+id/padding1" + android:layout_height="fill_parent" + android:layout_width="0dip" /> + + <view android:id="@+id/image2" + class="com.android.camera.ViewImage$ImageViewTouch" + android:background="#FF000000" + android:layout_width="0dip" + android:layout_height="fill_parent"/> + + <View android:id="@+id/padding2" + android:layout_height="fill_parent" + android:layout_width="0dip" /> + + <view android:id="@+id/image3" + class="com.android.camera.ViewImage$ImageViewTouch" + android:background="#FF000000" + android:layout_width="0dip" + android:layout_height="fill_parent"/> + </view> + </AbsoluteLayout> + + <ImageView android:id="@+id/prev_image" + android:clickable="true" + android:layout_width="wrap_content" android:layout_height="fill_parent" + android:layout_alignParentLeft="true" + android:layout_centerVertical="true" + android:visibility="invisible" + android:src="@drawable/btn_camera_arrow_left" + /> - <AbsoluteLayout android:id="@+id/abs" - android:layout_width="fill_parent" - android:layout_height="fill_parent"> - <view class="com.android.camera.ViewImage$ScrollHandler" android:id="@+id/scroller" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:orientation="horizontal" - - android:background="#FF000000" - android:layout_x="0dip" - android:layout_y="0dip"> - - <view android:id="@+id/image1" - class="com.android.camera.ViewImage$ImageViewTouch" - android:background="#FF000000" - android:layout_width="0dip" - android:layout_height="fill_parent" /> - - <View android:id="@+id/padding1" - android:layout_height="fill_parent" - android:layout_width="0dip" /> - - <view android:id="@+id/image2" - class="com.android.camera.ViewImage$ImageViewTouch" - android:background="#FF000000" - android:layout_width="0dip" - android:layout_height="fill_parent"/> + <ImageView android:id="@+id/next_image" + android:clickable="true" + android:layout_width="wrap_content" android:layout_height="fill_parent" + android:layout_alignParentRight="true" + android:layout_centerVertical="true" + android:visibility="invisible" + android:src="@drawable/btn_camera_arrow_right" + /> - <View android:id="@+id/padding2" - android:layout_height="fill_parent" - android:layout_width="0dip" /> - - <view android:id="@+id/image3" - class="com.android.camera.ViewImage$ImageViewTouch" - android:background="#FF000000" - android:layout_width="0dip" - android:layout_height="fill_parent"/> - </view> - </AbsoluteLayout> - - <ImageView - android:visibility="gone" - android:id="@+id/shutter_button" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:src="@drawable/ic_camera_indicator_photo" - android:background="@drawable/ic_btn_camera_background" - android:clickable="true" - android:focusable="true" - android:layout_alignParentRight="true" - android:layout_alignParentTop="true" - android:layout_marginRight="10dip" - android:layout_marginTop="10dip" - android:scaleType="center"/> - + <ImageView + android:visibility="gone" + android:id="@+id/shutter_button" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:src="@drawable/ic_camera_indicator_photo" + android:background="@drawable/ic_btn_camera_background" + android:clickable="true" + android:focusable="true" + android:layout_alignParentRight="true" + android:layout_alignParentTop="true" + android:layout_marginRight="5dip" + android:layout_marginTop="5dip" + android:scaleType="center"/> + <LinearLayout android:visibility="gone" android:id="@+id/action_icon_panel" - android:layout_alignBottom="@id/shutter_button" - android:layout_toLeftOf="@id/shutter_button" + android:layout_alignBottom="@id/shutter_button" + android:layout_toLeftOf="@id/shutter_button" android:layout_marginRight="38dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <com.android.camera.ActionMenuButton - android:id="@+id/gallery" - android:drawableTop="@drawable/ic_menu_gallery" - android:text="@string/camera_gallery" - style="@style/OnscreenActionIcon" + android:id="@+id/gallery" + android:drawableTop="@drawable/ic_menu_gallery" + android:text="@string/camera_gallery" + style="@style/OnscreenActionIcon" /> <com.android.camera.ActionMenuButton - android:id="@+id/setas" - android:drawableTop="@drawable/ic_menu_set_as" - android:text="@string/camera_set" - style="@style/OnscreenActionIcon" + android:id="@+id/setas" + android:drawableTop="@drawable/ic_menu_set_as" + android:text="@string/camera_set" + style="@style/OnscreenActionIcon" /> <com.android.camera.ActionMenuButton - android:id="@+id/share" - android:drawableTop="@drawable/ic_menu_share" - android:text="@string/camera_share" - style="@style/OnscreenActionIcon" + android:id="@+id/share" + android:drawableTop="@drawable/ic_menu_share" + android:text="@string/camera_share" + style="@style/OnscreenActionIcon" /> <com.android.camera.ActionMenuButton - android:id="@+id/discard" - android:drawableTop="@drawable/ic_menu_delete" - android:text="@string/camera_toss" - style="@style/OnscreenActionIcon" + android:id="@+id/discard" + android:drawableTop="@drawable/ic_menu_delete" + android:text="@string/camera_toss" + style="@style/OnscreenActionIcon" /> <com.android.camera.ActionMenuButton - android:id="@+id/attach" - android:drawableTop="@drawable/ic_menu_attach" - android:text="@string/camera_attach" - style="@style/OnscreenActionIcon" + android:id="@+id/attach" + android:drawableTop="@drawable/ic_menu_attach" + android:text="@string/camera_attach" + style="@style/OnscreenActionIcon" /> <com.android.camera.ActionMenuButton - android:id="@+id/cancel" - android:drawableTop="@drawable/ic_menu_cancel" - android:text="@string/camera_cancel" - style="@style/OnscreenActionIcon" + android:id="@+id/cancel" + android:drawableTop="@drawable/ic_menu_cancel" + android:text="@string/camera_cancel" + style="@style/OnscreenActionIcon" /> </LinearLayout> - <ImageView android:id="@+id/prev_image" - android:clickable="true" - android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_alignParentLeft="true" - android:layout_centerVertical="true" - android:visibility="invisible" - android:src="@drawable/btn_camera_arrow_left" - /> - - <ImageView android:id="@+id/next_image" - android:clickable="true" - android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_alignParentRight="true" - android:layout_centerVertical="true" - android:visibility="invisible" - android:src="@drawable/btn_camera_arrow_right" - /> - </RelativeLayout> diff --git a/src/com/android/camera/ViewImage.java b/src/com/android/camera/ViewImage.java index f1f25b7..00445a0 100644 --- a/src/com/android/camera/ViewImage.java +++ b/src/com/android/camera/ViewImage.java @@ -1,1481 +1,1485 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.util.Random; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.util.AttributeSet; import android.util.Config; import android.util.Log; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import android.widget.Scroller; import android.widget.Toast; import android.widget.ZoomButtonsController; import com.android.camera.ImageManager.IImage; public class ViewImage extends Activity implements View.OnClickListener { private static final String TAG = "ViewImage"; - private static final int TOUCH_AREA_WIDTH = 60; private ImageGetter mGetter; private Uri mSavedUri; static final boolean sSlideShowHidesStatusBar = true; // Choices for what adjacents to load. static private final int[] sOrder_adjacents = new int[] { 0, 1, -1 }; static private final int[] sOrder_slideshow = new int[] { 0 }; private LocalHandler mHandler = new LocalHandler(); private Random mRandom = new Random(System.currentTimeMillis()); private int [] mShuffleOrder; private boolean mUseShuffleOrder = false; private boolean mSlideShowLoop = false; private static final int MODE_NORMAL = 1; private static final int MODE_SLIDESHOW = 2; private int mMode = MODE_NORMAL; private boolean mFullScreenInNormalMode; private boolean mShowActionIcons; private View mActionIconPanel; private View mShutterButton; private boolean mSortAscending = false; private int mSlideShowInterval; private int mLastSlideShowImage; private boolean mFirst = true; private int mCurrentPosition = 0; private boolean mLayoutComplete = false; // represents which style animation to use private int mAnimationIndex; private Animation [] mSlideShowInAnimation; private Animation [] mSlideShowOutAnimation; private SharedPreferences mPrefs; private View mNextImageView, mPrevImageView; private Animation mHideNextImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mHidePrevImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mShowNextImageViewAnimation = new AlphaAnimation(0F, 1F); private Animation mShowPrevImageViewAnimation = new AlphaAnimation(0F, 1F); static final int sPadding = 20; static final int sHysteresis = sPadding * 2; static final int sBaseScrollDuration = 1000; // ms private ImageManager.IImageList mAllImages; private int mSlideShowImageCurrent = 0; private ImageViewTouch [] mSlideShowImageViews = new ImageViewTouch[2]; private GestureDetector mGestureDetector; private ZoomButtonsController mZoomButtonsController; // Array of image views. The center view is the one the user is focused // on. The one at the zeroth position and the second position reflect // the images to the left/right of the center image. private ImageViewTouch[] mImageViews = new ImageViewTouch[3]; // Container for the three image views. This guy can be "scrolled" // to reveal the image prior to and after the center image. private ScrollHandler mScroller; private MenuHelper.MenuItemsResult mImageMenuRunnable; private Runnable mDismissOnScreenControlsRunnable; private boolean mCameraReviewMode; private void updateNextPrevControls() { boolean showPrev = mCurrentPosition > 0; boolean showNext = mCurrentPosition < mAllImages.getCount() - 1; boolean prevIsVisible = mPrevImageView.getVisibility() == View.VISIBLE; boolean nextIsVisible = mNextImageView.getVisibility() == View.VISIBLE; if (showPrev && !prevIsVisible) { Animation a = mShowPrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.VISIBLE); } else if (!showPrev && prevIsVisible) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.GONE); } if (showNext && !nextIsVisible) { Animation a = mShowNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.VISIBLE); } else if (!showNext && nextIsVisible) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.GONE); } } private void showOnScreenControls() { + mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); updateNextPrevControls(); updateZoomButtonsEnabled(); mZoomButtonsController.setVisible(true); - scheduleDismissOnScreenControls(); } @Override public boolean dispatchTouchEvent(MotionEvent m) { boolean sup = super.dispatchTouchEvent(m); + + // This is a hack to show the on screen controls. We should make sure + // this event is not handled by others(ie. sup == false), and listen for + // the events on zoom/prev/next buttons. + // However, since we have no other pressable views, it is OK now. + // TODO: Fix the above issue. + if (mMode == MODE_NORMAL) { + switch (m.getAction()) { + case MotionEvent.ACTION_DOWN: + showOnScreenControls(); + break; + case MotionEvent.ACTION_UP: + scheduleDismissOnScreenControls(); + break; + } + } + if (sup == false) { if (mMode == MODE_SLIDESHOW) { mSlideShowImageViews[mSlideShowImageCurrent].handleTouchEvent(m); - } else if (mMode == MODE_NORMAL){ + } else if (mMode == MODE_NORMAL) { mImageViews[1].handleTouchEvent(m); } return true; } return true; } private void scheduleDismissOnScreenControls() { mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); mHandler.postDelayed(mDismissOnScreenControlsRunnable, 1500); } private void updateZoomButtonsEnabled() { ImageViewTouch imageView = mImageViews[1]; float scale = imageView.getScale(); mZoomButtonsController.setZoomInEnabled(scale < imageView.mMaxZoom); mZoomButtonsController.setZoomOutEnabled(scale > 1); } @Override protected void onDestroy() { // This is necessary to make the ZoomButtonsController unregister // its configuration change receiver. if (mZoomButtonsController != null) { mZoomButtonsController.setVisible(false); } super.onDestroy(); } private void setupZoomButtonController(View rootView) { mGestureDetector = new GestureDetector(this, new MyGestureListener()); mZoomButtonsController = new ZoomButtonsController(rootView); mZoomButtonsController.setAutoDismissed(false); mZoomButtonsController.setOnZoomListener( new ZoomButtonsController.OnZoomListener() { public void onVisibilityChanged(boolean visible) { if (visible) { updateZoomButtonsEnabled(); } } public void onZoom(boolean zoomIn) { if (zoomIn) { mImageViews[1].zoomIn(); } else { mImageViews[1].zoomOut(); } - showOnScreenControls(); } }); } private class MyGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { ImageViewTouch imageView = mImageViews[1]; if (imageView.getScale() > 1F) { imageView.postTranslate(-distanceX, -distanceY, sUseBounce); imageView.center(true, true, false); } - showOnScreenControls(); return true; } @Override public boolean onSingleTapUp(MotionEvent e) { - int viewWidth = mImageViews[1].getWidth(); - int x = (int) e.getX(); - int y = (int) e.getY(); - if (x < TOUCH_AREA_WIDTH) { - moveNextOrPrevious(-1); - } else if (x > viewWidth - TOUCH_AREA_WIDTH) { - moveNextOrPrevious(1); - } setMode(MODE_NORMAL); - showOnScreenControls(); return true; } } private void setupDismissOnScreenControlRunnable() { mDismissOnScreenControlsRunnable = new Runnable() { public void run() { if (!mShowActionIcons) { if (mNextImageView.getVisibility() == View.VISIBLE) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.INVISIBLE); } if (mPrevImageView.getVisibility() == View.VISIBLE) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.INVISIBLE); } mZoomButtonsController.setVisible(false); } } }; } private boolean isPickIntent() { String action = getIntent().getAction(); return (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)); } private static final boolean sUseBounce = false; private static final boolean sAnimateTransitions = false; public static class ImageViewTouch extends ImageViewTouchBase { private ViewImage mViewImage; private boolean mEnableTrackballScroll; public ImageViewTouch(Context context) { super(context); mViewImage = (ViewImage) context; } public ImageViewTouch(Context context, AttributeSet attrs) { super(context, attrs); mViewImage = (ViewImage) context; } public void setEnableTrackballScroll(boolean enable) { mEnableTrackballScroll = enable; } protected void postTranslate(float dx, float dy, boolean bounceOK) { super.postTranslate(dx, dy); - if (dx != 0F || dy != 0F) { - mViewImage.showOnScreenControls(); - } if (!sUseBounce) { center(true, false, false); } } protected ScrollHandler scrollHandler() { return mViewImage.mScroller; } public boolean handleTouchEvent(MotionEvent m) { return mViewImage.mGestureDetector.onTouchEvent(m); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Don't respond to arrow keys if trackball scrolling is not enabled if (!mEnableTrackballScroll) { if ((keyCode >= KeyEvent.KEYCODE_DPAD_UP) && (keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT)) { return super.onKeyDown(keyCode, event); } } int current = mViewImage.mCurrentPosition; int nextImagePos = -2; // default no next image try { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: { if (mViewImage.isPickIntent()) { ImageManager.IImage img = mViewImage.mAllImages.getImageAt(mViewImage.mCurrentPosition); mViewImage.setResult(RESULT_OK, new Intent().setData(img.fullSizeImageUri())); mViewImage.finish(); } break; } case KeyEvent.KEYCODE_DPAD_LEFT: { panBy(sPanRate, 0); int maxOffset = (current == 0) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(true, maxOffset)) { nextImagePos = current - 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_RIGHT: { panBy(-sPanRate, 0); int maxOffset = (current == mViewImage.mAllImages.getCount() - 1) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(false, maxOffset)) { nextImagePos = current + 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_UP: { panBy(0, sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DPAD_DOWN: { panBy(0, -sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DEL: MenuHelper.deletePhoto( mViewImage, mViewImage.mDeletePhotoRunnable); break; } } finally { if (nextImagePos >= 0 && nextImagePos < mViewImage.mAllImages.getCount()) { synchronized (mViewImage) { mViewImage.setMode(MODE_NORMAL); mViewImage.setImage(nextImagePos); } } else if (nextImagePos != -2) { center(true, true, false); } } return super.onKeyDown(keyCode, event); } protected boolean isShiftedToNextImage(boolean left, int maxOffset) { boolean retval; Bitmap bitmap = mBitmapDisplayed; Matrix m = getImageViewMatrix(); if (left) { float [] t1 = new float[] { 0, 0 }; m.mapPoints(t1); retval = t1[0] > maxOffset; } else { int width = bitmap != null ? bitmap.getWidth() : getWidth(); float [] t1 = new float[] { width, 0 }; m.mapPoints(t1); retval = t1[0] + maxOffset < getWidth(); } return retval; } protected void scrollX(int deltaX) { scrollHandler().scrollBy(deltaX, 0); } protected int getScrollOffset() { return scrollHandler().getScrollX(); } } static class ScrollHandler extends LinearLayout { private Runnable mFirstLayoutCompletedCallback = null; private Scroller mScrollerHelper; private ViewImage mViewImage; private int mWidth = -1; public ScrollHandler(Context context) { super(context); mScrollerHelper = new Scroller(context); mViewImage = (ViewImage) context; } public ScrollHandler(Context context, AttributeSet attrs) { super(context, attrs); mScrollerHelper = new Scroller(context); mViewImage = (ViewImage) context; } public void startScrollTo(int newX, int newY) { int oldX = getScrollX(); int oldY = getScrollY(); int deltaX = newX - oldX; int deltaY = newY - oldY; if (mWidth == -1) { mWidth = findViewById(R.id.image2).getWidth(); } int viewWidth = mWidth; int duration = viewWidth > 0 ? sBaseScrollDuration * Math.abs(deltaX) / viewWidth : 0; mScrollerHelper.startScroll(oldX, oldY, deltaX, deltaY, duration); invalidate(); } @Override public void computeScroll() { if (mScrollerHelper.computeScrollOffset()) { scrollTo(mScrollerHelper.getCurrX(), mScrollerHelper.getCurrY()); postInvalidate(); // So we draw again } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int width = right - left; int x = 0; for (View v : new View[] { findViewById(R.id.image1), findViewById(R.id.image2), findViewById(R.id.image3) }) { v.layout(x, 0, x + width, bottom); x += (width + sPadding); } findViewById(R.id.padding1).layout(width, 0, width + sPadding, bottom); findViewById(R.id.padding2).layout(width + sPadding + width, 0, width + sPadding + width + sPadding, bottom); if (changed) { mViewImage.mLayoutComplete = true; mViewImage.onLayoutChanged(); } } } private void animateScrollTo(int xNew, int yNew) { mScroller.startScrollTo(xNew, yNew); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (! mCameraReviewMode) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.slide_show); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { setMode(MODE_SLIDESHOW); mLastSlideShowImage = mCurrentPosition; loadNextImage(mCurrentPosition, 0, true); return true; } }); item.setIcon(android.R.drawable.ic_menu_slideshow); } final SelectedImageGetter selectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return mAllImages.getImageAt(mCurrentPosition); } public Uri getCurrentImageUri() { return mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); } }; mImageMenuRunnable = MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL, true, ViewImage.this, mHandler, mDeletePhotoRunnable, new MenuHelper.MenuInvoker() { public void run(MenuHelper.MenuCallback cb) { setMode(MODE_NORMAL); cb.run(selectedImageGetter.getCurrentImageUri(), selectedImageGetter.getCurrentImage()); for (ImageViewTouchBase iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } setImage(mCurrentPosition); } }); if (true) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 1000, R.string.camerasettings); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent preferences = new Intent(); preferences.setClass(ViewImage.this, GallerySettings.class); startActivity(preferences); return true; } }); item.setAlphabeticShortcut('p'); item.setIcon(android.R.drawable.ic_menu_preferences); } // Hidden menu just so the shortcut will bring up the zoom controls menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.camerasettings) // the string resource is a placeholder .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { showOnScreenControls(); + scheduleDismissOnScreenControls(); return true; } }) .setAlphabeticShortcut('z') .setVisible(false); return true; } protected Runnable mDeletePhotoRunnable = new Runnable() { public void run() { mAllImages.removeImageAt(mCurrentPosition); if (mAllImages.getCount() == 0) { finish(); } else { if (mCurrentPosition == mAllImages.getCount()) { mCurrentPosition -= 1; } } for (ImageViewTouchBase iv: mImageViews) { iv.setImageBitmapResetBase(null, true, true); } setImage(mCurrentPosition); } }; @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); setMode(MODE_NORMAL); if (mImageMenuRunnable != null) { mImageMenuRunnable.gettingReadyToOpen(menu, mAllImages.getImageAt(mCurrentPosition)); } Uri uri = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); MenuHelper.enableShareMenuItem(menu, !MenuHelper.isMMSUri(uri)); return true; } private void onLayoutChanged() { // if we get here after "onPause" then ignore the event if (mGetter == null) return; mDismissOnScreenControlsRunnable.run(); mGetter.cancelCurrent(); for (ImageViewTouch iv: mImageViews) { iv.clear(); } mFirst = true; setImage(mCurrentPosition); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { boolean b = super.onMenuItemSelected(featureId, item); if (mImageMenuRunnable != null) mImageMenuRunnable.aboutToCall(item, mAllImages.getImageAt(mCurrentPosition)); return b; } /* * Here's the loading strategy. For any given image, load the thumbnail * into memory and post a callback to display the resulting bitmap. * * Then proceed to load the full image bitmap. Three things can * happen at this point: * * 1. the image fails to load because the UI thread decided * to move on to a different image. This "cancellation" happens * by virtue of the UI thread closing the stream containing the * image being decoded. BitmapFactory.decodeStream returns null * in this case. * * 2. the image loaded successfully. At that point we post * a callback to the UI thread to actually show the bitmap. * * 3. when the post runs it checks to see if the image that was * loaded is still the one we want. The UI may have moved on * to some other image and if so we just drop the newly loaded * bitmap on the floor. */ interface ImageGetterCallback { public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb); public boolean wantsThumbnail(int pos, int offset); public boolean wantsFullImage(int pos, int offset); public int fullImageSizeToUse(int pos, int offset); public void completed(boolean wasCanceled); public int [] loadOrder(); } class ImageGetter { // The thread which does the work. private Thread mGetterThread; // The base position that's being retrieved. The actual images retrieved // are this base plus each of the offets. private int mCurrentPosition = -1; // The callback to invoke for each image. private ImageGetterCallback mCB; // This is the loader cancelable that gets set while we're loading an image. // If we change position we can cancel the current load using this. private ImageManager.IGetBitmap_cancelable mLoad; // True if we're canceling the current load. private boolean mCancelCurrent = false; // True when the therad should exit. private boolean mDone = false; // True when the loader thread is waiting for work. private boolean mReady = false; private void cancelCurrent() { synchronized (this) { if (!mReady) { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { if (Config.LOGV) Log.v(TAG, "canceling load object"); load.cancel(); } mCancelCurrent = false; } } } public ImageGetter() { mGetterThread = new Thread(new Runnable() { private Runnable callback(final int position, final int offset, final boolean isThumb, final Bitmap bitmap) { return new Runnable() { public void run() { // check for inflight callbacks that aren't applicable any longer // before delivering them if (!isCanceled() && position == mCurrentPosition) { mCB.imageLoaded(position, offset, bitmap, isThumb); } else if (bitmap != null) { bitmap.recycle(); } } }; } private Runnable completedCallback(final boolean wasCanceled) { return new Runnable() { public void run() { mCB.completed(wasCanceled); } }; } public void run() { int lastPosition = -1; while (!mDone) { synchronized (ImageGetter.this) { mReady = true; ImageGetter.this.notify(); if (mCurrentPosition == -1 || lastPosition == mCurrentPosition) { try { ImageGetter.this.wait(); } catch (InterruptedException ex) { continue; } } lastPosition = mCurrentPosition; mReady = false; } if (lastPosition != -1) { int imageCount = mAllImages.getCount(); int [] order = mCB.loadOrder(); for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (image == null || isCanceled()) { break; } if (mCB.wantsThumbnail(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting THUMBNAIL load at offset " + offset); Bitmap b = image.thumbBitmap(); mHandler.postGetterCallback(callback(lastPosition, offset, true, b)); } } } for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (mCB.wantsFullImage(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting FULL IMAGE load at offset " + offset); int sizeToUse = mCB.fullImageSizeToUse(lastPosition, offset); if (image != null && !isCanceled()) { mLoad = image.fullSizeBitmap_cancelable(sizeToUse); } if (mLoad != null) { long t1; if (Config.LOGV) t1 = System.currentTimeMillis(); // The return value could be null if the // bitmap is too big, or we cancelled it. Bitmap b = mLoad.get(); if (Config.LOGV && b != null) { long t2 = System.currentTimeMillis(); Log.v(TAG, "loading full image for " + image.fullSizeImageUri() + " with requested size " + sizeToUse + " took " + (t2 - t1) + " and returned a bitmap with size " + b.getWidth() + " / " + b.getHeight()); } mLoad = null; if (b != null) { if (isCanceled()) { b.recycle(); } else { mHandler.postGetterCallback(callback(lastPosition, offset, false, b)); } } } } } } mHandler.postGetterCallback(completedCallback(isCanceled())); } } } }); mGetterThread.setName("ImageGettter"); mGetterThread.start(); } private boolean isCanceled() { synchronized (this) { return mCancelCurrent; } } public void setPosition(int position, ImageGetterCallback cb) { synchronized (this) { if (!mReady) { try { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { load.cancel(); } // if the thread is waiting before loading the full size // image then this will free it up ImageGetter.this.notify(); ImageGetter.this.wait(); mCancelCurrent = false; } catch (InterruptedException ex) { // not sure what to do here } } } mCurrentPosition = position; mCB = cb; synchronized (this) { ImageGetter.this.notify(); } } public void stop() { synchronized (this) { mDone = true; ImageGetter.this.notify(); } try { mGetterThread.join(); } catch (InterruptedException ex) { } } } private void setImage(int pos) { if (!mLayoutComplete) return; final boolean left = (pos == mCurrentPosition - 1); final boolean right = (pos == mCurrentPosition + 1); mCurrentPosition = pos; ImageViewTouchBase current = mImageViews[1]; current.mSuppMatrix.reset(); current.setImageMatrix(current.getImageViewMatrix()); if (false) { Log.v(TAG, "before..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } if (!mFirst) { if (left) { mImageViews[2].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[0]); } else if (right) { mImageViews[0].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[2]); } } if (false) { Log.v(TAG, "after copy..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } for (ImageViewTouchBase ivt: mImageViews) { ivt.mIsZooming = false; } int width = mImageViews[1].getWidth(); int from; int to = width + sPadding; if (mFirst) { from = to; mFirst = false; } else { from = left ? (width + sPadding) + mScroller.getScrollX() : mScroller.getScrollX() - (width + sPadding); } if (sAnimateTransitions) { mScroller.scrollTo(from, 0); animateScrollTo(to, 0); } else { mScroller.scrollTo(to, 0); } ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { if (!mShowActionIcons) { mImageViews[1].setFocusableInTouchMode(true); mImageViews[1].requestFocus(); } } public boolean wantsThumbnail(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; return ivt.mThumbBitmap == null; } public boolean wantsFullImage(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; if (ivt.mBitmapDisplayed != null && !ivt.mBitmapIsThumbnail) { return false; } if (offset != 0) { return false; } return true; } public int fullImageSizeToUse(int pos, int offset) { // TODO // this number should be bigger so that we can zoom. we may need to // get fancier and read in the fuller size image as the user starts // to zoom. use -1 to get the full full size image. // for now use 480 so we don't run out of memory final int imageViewSize = 480; return imageViewSize; } public int [] loadOrder() { return sOrder_adjacents; } public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb) { // shouldn't get here after onPause() ImageViewTouchBase ivt = mImageViews[1 + offset]; if (offset == 0) updateZoomButtonsEnabled(); ivt.setImageBitmapResetBase(bitmap, isThumb, isThumb); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { mGetter.setPosition(pos, cb); } showOnScreenControls(); + scheduleDismissOnScreenControls(); } @Override public void onCreate(Bundle instanceState) { super.onCreate(instanceState); Intent intent = getIntent(); mCameraReviewMode = intent.getBooleanExtra("com.android.camera.ReviewMode", false); mFullScreenInNormalMode = intent.getBooleanExtra(MediaStore.EXTRA_FULL_SCREEN, true); mShowActionIcons = intent.getBooleanExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, false); setRequestedOrientation(); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.viewimage); mImageViews[0] = (ImageViewTouch) findViewById(R.id.image1); mImageViews[1] = (ImageViewTouch) findViewById(R.id.image2); mImageViews[2] = (ImageViewTouch) findViewById(R.id.image3); for(ImageViewTouch v : mImageViews) { v.setEnableTrackballScroll(!mShowActionIcons); } mScroller = (ScrollHandler)findViewById(R.id.scroller); makeGetter(); mAnimationIndex = -1; mSlideShowInAnimation = new Animation[] { makeInAnimation(R.anim.transition_in), makeInAnimation(R.anim.slide_in), makeInAnimation(R.anim.slide_in_vertical), }; mSlideShowOutAnimation = new Animation[] { makeOutAnimation(R.anim.transition_out), makeOutAnimation(R.anim.slide_out), makeOutAnimation(R.anim.slide_out_vertical), }; mSlideShowImageViews[0] = (ImageViewTouch) findViewById(R.id.image1_slideShow); mSlideShowImageViews[1] = (ImageViewTouch) findViewById(R.id.image2_slideShow); for (ImageViewTouch v : mSlideShowImageViews) { v.setImageBitmapResetBase(null, true, true); v.setVisibility(View.INVISIBLE); v.setEnableTrackballScroll(!mShowActionIcons); } mActionIconPanel = findViewById(R.id.action_icon_panel); { int[] pickIds = {R.id.attach, R.id.cancel}; int[] normalIds = {R.id.gallery, R.id.setas, R.id.share, R.id.discard}; int[] hideIds = pickIds; int[] connectIds = normalIds; if (isPickIntent()) { hideIds = normalIds; connectIds = pickIds; } for(int id : hideIds) { mActionIconPanel.findViewById(id).setVisibility(View.GONE); } for(int id : connectIds) { View view = mActionIconPanel.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } mShutterButton = findViewById(R.id.shutter_button); mShutterButton.setOnClickListener(this); Uri uri = getIntent().getData(); if (Config.LOGV) Log.v(TAG, "uri is " + uri); if (instanceState != null) { if (instanceState.containsKey("uri")) { uri = Uri.parse(instanceState.getString("uri")); } } if (uri == null) { finish(); return; } init(uri); Bundle b = getIntent().getExtras(); boolean slideShow = b != null ? b.getBoolean("slideshow", false) : false; if (slideShow) { setMode(MODE_SLIDESHOW); loadNextImage(mCurrentPosition, 0, true); } else { if (mFullScreenInNormalMode) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } } setupZoomButtonController(findViewById(R.id.rootLayout)); setupDismissOnScreenControlRunnable(); mNextImageView = findViewById(R.id.next_image); mPrevImageView = findViewById(R.id.prev_image); mNextImageView.setOnClickListener(this); mPrevImageView.setOnClickListener(this); if (mShowActionIcons) { mNextImageView.setFocusable(true); mPrevImageView.setFocusable(true); } } private void setRequestedOrientation() { Intent intent = getIntent(); if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); if (orientation != getRequestedOrientation()) { setRequestedOrientation(orientation); } } else { MenuHelper.requestOrientation(this, mPrefs); } } private Animation makeInAnimation(int id) { Animation inAnimation = AnimationUtils.loadAnimation(this, id); return inAnimation; } private Animation makeOutAnimation(int id) { Animation outAnimation = AnimationUtils.loadAnimation(this, id); return outAnimation; } private void setMode(int mode) { if (mMode == mode) { return; } findViewById(R.id.slideShowContainer).setVisibility(mode == MODE_SLIDESHOW ? View.VISIBLE : View.GONE); findViewById(R.id.abs) .setVisibility(mode == MODE_NORMAL ? View.VISIBLE : View.GONE); Window win = getWindow(); mMode = mode; if (mode == MODE_SLIDESHOW) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (sSlideShowHidesStatusBar) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } for (ImageViewTouchBase ivt: mImageViews) { ivt.clear(); } mActionIconPanel.setVisibility(View.GONE); mShutterButton.setVisibility(View.GONE); if (false) { Log.v(TAG, "current is " + this.mSlideShowImageCurrent); this.mSlideShowImageViews[0].dump(); this.mSlideShowImageViews[0].dump(); } findViewById(R.id.slideShowContainer).getRootView().requestLayout(); mUseShuffleOrder = mPrefs.getBoolean("pref_gallery_slideshow_shuffle_key", false); mSlideShowLoop = mPrefs.getBoolean("pref_gallery_slideshow_repeat_key", false); try { mAnimationIndex = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_transition_key", "0")); } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mAnimationIndex = 0; } try { mSlideShowInterval = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_interval_key", "3")) * 1000; } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mSlideShowInterval = 3000; } if (Config.LOGV) { Log.v(TAG, "read prefs... shuffle: " + mUseShuffleOrder); Log.v(TAG, "read prefs... loop: " + mSlideShowLoop); Log.v(TAG, "read prefs... animidx: " + mAnimationIndex); Log.v(TAG, "read prefs... interval: " + mSlideShowInterval); } if (mUseShuffleOrder) { generateShuffleOrder(); } } else { if (Config.LOGV) Log.v(TAG, "slide show mode off, mCurrentPosition == " + mCurrentPosition); win.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (mFullScreenInNormalMode) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mGetter != null) mGetter.cancelCurrent(); if (sSlideShowHidesStatusBar) { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } ImageViewTouchBase dst = mImageViews[1]; dst.mLastXTouchPos = -1; dst.mLastYTouchPos = -1; for (ImageViewTouchBase ivt: mSlideShowImageViews) { ivt.clear(); } mShuffleOrder = null; // mGetter null is a proxy for being paused if (mGetter != null) { mFirst = true; // don't animate setImage(mCurrentPosition); } } // this line shouldn't be necessary but the view hierarchy doesn't // seem to realize that the window layout changed mScroller.requestLayout(); } private void generateShuffleOrder() { if (mShuffleOrder == null || mShuffleOrder.length != mAllImages.getCount()) { mShuffleOrder = new int[mAllImages.getCount()]; } for (int i = 0; i < mShuffleOrder.length; i++) { mShuffleOrder[i] = i; } for (int i = mShuffleOrder.length - 1; i > 0; i--) { int r = mRandom.nextInt(i); int tmp = mShuffleOrder[r]; mShuffleOrder[r] = mShuffleOrder[i]; mShuffleOrder[i] = tmp; } } private void loadNextImage(final int requestedPos, final long delay, final boolean firstCall) { if (firstCall && mUseShuffleOrder) { generateShuffleOrder(); } final long targetDisplayTime = System.currentTimeMillis() + delay; ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { } public boolean wantsThumbnail(int pos, int offset) { return true; } public boolean wantsFullImage(int pos, int offset) { return false; } public int [] loadOrder() { return sOrder_slideshow; } public int fullImageSizeToUse(int pos, int offset) { return 480; // TODO compute this } public void imageLoaded(final int pos, final int offset, final Bitmap bitmap, final boolean isThumb) { long timeRemaining = Math.max(0, targetDisplayTime - System.currentTimeMillis()); mHandler.postDelayedGetterCallback(new Runnable() { public void run() { if (mMode == MODE_NORMAL) return; ImageViewTouchBase oldView = mSlideShowImageViews[mSlideShowImageCurrent]; if (++mSlideShowImageCurrent == mSlideShowImageViews.length) { mSlideShowImageCurrent = 0; } ImageViewTouchBase newView = mSlideShowImageViews[mSlideShowImageCurrent]; newView.setVisibility(View.VISIBLE); newView.setImageBitmapResetBase(bitmap, isThumb, isThumb); newView.bringToFront(); int animation = 0; if (mAnimationIndex == -1) { int n = mRandom.nextInt(mSlideShowInAnimation.length); animation = n; } else { animation = mAnimationIndex; } Animation aIn = mSlideShowInAnimation[animation]; newView.setAnimation(aIn); newView.setVisibility(View.VISIBLE); aIn.startNow(); Animation aOut = mSlideShowOutAnimation[animation]; oldView.setVisibility(View.INVISIBLE); oldView.setAnimation(aOut); aOut.startNow(); mCurrentPosition = requestedPos; if (mCurrentPosition == mLastSlideShowImage && !firstCall) { if (mSlideShowLoop) { if (mUseShuffleOrder) { generateShuffleOrder(); } } else { setMode(MODE_NORMAL); return; } } if (Config.LOGV) Log.v(TAG, "mCurrentPosition is now " + mCurrentPosition); loadNextImage((mCurrentPosition + 1) % mAllImages.getCount(), mSlideShowInterval, false); } }, timeRemaining); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { int pos = requestedPos; if (mShuffleOrder != null) { pos = mShuffleOrder[pos]; } mGetter.setPosition(pos, cb); } } private void makeGetter() { mGetter = new ImageGetter(); } private boolean desiredSortOrder() { String sortOrder = mPrefs.getString("pref_gallery_sort_key", null); boolean sortAscending = false; if (sortOrder != null) { sortAscending = sortOrder.equals("ascending"); } if (mCameraReviewMode) { // Force left-arrow older pictures, right-arrow newer pictures. sortAscending = true; } return sortAscending; } private void init(Uri uri) { if (uri == null) return; mSortAscending = desiredSortOrder(); int sort = mSortAscending ? ImageManager.SORT_ASCENDING : ImageManager.SORT_DESCENDING; mAllImages = ImageManager.makeImageList(uri, this, sort); uri = uri.buildUpon().query(null).build(); // TODO smarter/faster here please for (int i = 0; i < mAllImages.getCount(); i++) { ImageManager.IImage image = mAllImages.getImageAt(i); if (image.fullSizeImageUri().equals(uri)) { mCurrentPosition = i; mLastSlideShowImage = mCurrentPosition; break; } } } private Uri getCurrentUri() { ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); Uri uri = null; if (image != null){ String bucket = null; uri = image.fullSizeImageUri(); if(getIntent() != null && getIntent().getData() != null) bucket = getIntent().getData().getQueryParameter("bucketId"); if(bucket != null) uri = uri.buildUpon().appendQueryParameter("bucketId", bucket).build(); } return uri; } @Override public void onSaveInstanceState(Bundle b) { super.onSaveInstanceState(b); Uri uri = getCurrentUri(); if (uri != null) { b.putString("uri", uri.toString()); } if (mMode == MODE_SLIDESHOW) { b.putBoolean("slideshow", true); } } @Override public void onResume() { super.onResume(); init(mSavedUri); // normally this will never be zero but if one "backs" into this // activity after removing the sdcard it could be zero. in that // case just "finish" since there's nothing useful that can happen. int count = mAllImages.getCount(); if (count == 0) { finish(); } else if (count <= mCurrentPosition) { mCurrentPosition = count - 1; } ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); if (mGetter == null) { makeGetter(); } mFirst = true; setImage(mCurrentPosition); } @Override public void onPause() { super.onPause(); mGetter.cancelCurrent(); mGetter.stop(); mGetter = null; setMode(MODE_NORMAL); // removing all callback in the message queue mHandler.removeAllGetterCallbacks(); mSavedUri = getCurrentUri(); mAllImages.deactivate(); mDismissOnScreenControlsRunnable.run(); if (mDismissOnScreenControlsRunnable != null) mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); for (ImageViewTouch iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } for (ImageViewTouch iv: mSlideShowImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } } public void onClick(View v) { switch (v.getId()) { case R.id.shutter_button: { if (mCameraReviewMode) { finish(); } else { MenuHelper.gotoStillImageCapture(this); } } break; case R.id.gallery: { MenuHelper.gotoCameraImageGallery(this); } break; case R.id.discard: { MenuHelper.deletePhoto(this, mDeletePhotoRunnable); } break; case R.id.share: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); if (MenuHelper.isMMSUri(u)) return; Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_STREAM, u); try { startActivity(Intent.createChooser(intent, getText(R.string.sendImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_image, Toast.LENGTH_SHORT).show(); } } break; case R.id.setas: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA, u);
brunsky/WS171-packages-apps-Camera
bd8dd53c7194d62b93f075c84f913459fb618362
Automated import from //branches/cupcake/...@142872,142872
diff --git a/src/com/android/camera/MenuHelper.java b/src/com/android/camera/MenuHelper.java index 17d3edb..a88f020 100644 --- a/src/com/android/camera/MenuHelper.java +++ b/src/com/android/camera/MenuHelper.java @@ -1,743 +1,750 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.io.Closeable; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.StatFs; import android.provider.MediaStore; import android.provider.MediaStore.Images; import android.util.Config; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.MenuItem.OnMenuItemClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.camera.ImageManager.IImage; public class MenuHelper { static private final String TAG = "MenuHelper"; static public final int GENERIC_ITEM = 1; static public final int IMAGE_SAVING_ITEM = 2; static public final int VIDEO_SAVING_ITEM = 3; static public final int IMAGE_MODE_ITEM = 4; static public final int VIDEO_MODE_ITEM = 5; static public final int MENU_ITEM_MAX = 5; static public final int INCLUDE_ALL = 0xFFFFFFFF; static public final int INCLUDE_VIEWPLAY_MENU = (1 << 0); static public final int INCLUDE_SHARE_MENU = (1 << 1); static public final int INCLUDE_SET_MENU = (1 << 2); static public final int INCLUDE_CROP_MENU = (1 << 3); static public final int INCLUDE_DELETE_MENU = (1 << 4); static public final int INCLUDE_ROTATE_MENU = (1 << 5); static public final int INCLUDE_DETAILS_MENU = (1 << 6); static public final int MENU_SWITCH_CAMERA_MODE = 0; static public final int MENU_CAPTURE_PICTURE = 1; static public final int MENU_CAPTURE_VIDEO = 2; static public final int MENU_IMAGE_SHARE = 10; static public final int MENU_IMAGE_SET = 14; static public final int MENU_IMAGE_SET_WALLPAPER = 15; static public final int MENU_IMAGE_SET_CONTACT = 16; static public final int MENU_IMAGE_SET_MYFAVE = 17; static public final int MENU_IMAGE_CROP = 18; static public final int MENU_IMAGE_ROTATE = 19; static public final int MENU_IMAGE_ROTATE_LEFT = 20; static public final int MENU_IMAGE_ROTATE_RIGHT = 21; static public final int MENU_IMAGE_TOSS = 22; static public final int MENU_VIDEO_PLAY = 23; static public final int MENU_VIDEO_SHARE = 24; static public final int MENU_VIDEO_TOSS = 27; static private final long SHARE_FILE_LENGTH_LIMIT = 3L * 1024L * 1024L; public static final int NO_STORAGE_ERROR = -1; public static final int CANNOT_STAT_ERROR = -2; /** Activity result code used to report crop results. */ public static final int RESULT_COMMON_MENU_CROP = 490; public interface MenuItemsResult { public void gettingReadyToOpen(Menu menu, ImageManager.IImage image); public void aboutToCall(MenuItem item, ImageManager.IImage image); } public interface MenuInvoker { public void run(MenuCallback r); } public interface MenuCallback { public void run(Uri uri, ImageManager.IImage image); } private static void closeSilently(Closeable target) { try { if (target != null) target.close(); } catch (Throwable t) { // ignore all exceptions, that's what silently means } } public static long getImageFileSize(ImageManager.IImage image) { java.io.InputStream data = image.fullSizeImageData(); if (data == null) return -1; try { return data.available(); } catch (java.io.IOException ex) { return -1; } finally { closeSilently(data); } } // This is a hack before we find a solution to pass a permission to other // applications. See bug #1735149. // Checks if the URI starts with "content://mms". public static boolean isMMSUri(Uri uri) { return (uri != null) && uri.getScheme().equals("content") && uri.getAuthority().equals("mms"); } + public static void enableShareMenuItem(Menu menu, boolean enabled) { + MenuItem item = menu.findItem(MENU_IMAGE_SHARE); + if (item != null) { + item.setVisible(enabled); + item.setEnabled(enabled); + } + } + static MenuItemsResult addImageMenuItems( Menu menu, int inclusions, final boolean isImage, final Activity activity, final Handler handler, final Runnable onDelete, final MenuInvoker onInvoke) { final ArrayList<MenuItem> requiresWriteAccessItems = new ArrayList<MenuItem>(); final ArrayList<MenuItem> requiresNoDrmAccessItems = new ArrayList<MenuItem>(); if (isImage && ((inclusions & INCLUDE_ROTATE_MENU) != 0)) { SubMenu rotateSubmenu = menu.addSubMenu(IMAGE_SAVING_ITEM, MENU_IMAGE_ROTATE, 40, R.string.rotate).setIcon(android.R.drawable.ic_menu_rotate); // Don't show the rotate submenu if the item at hand is read only // since the items within the submenu won't be shown anyway. This is // really a framework bug in that it shouldn't show the submenu if // the submenu has no visible items. requiresWriteAccessItems.add(rotateSubmenu.getItem()); if (rotateSubmenu != null) { requiresWriteAccessItems.add(rotateSubmenu.add(0, MENU_IMAGE_ROTATE_LEFT, 50, R.string.rotate_left).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null || image.isReadonly()) return; image.rotateImageBy(-90); } }); return true; } }).setAlphabeticShortcut('l')); requiresWriteAccessItems.add(rotateSubmenu.add(0, MENU_IMAGE_ROTATE_RIGHT, 60, R.string.rotate_right).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null || image.isReadonly()) return; image.rotateImageBy(90); } }); return true; } }).setAlphabeticShortcut('r')); } } if (isImage && ((inclusions & INCLUDE_CROP_MENU) != 0)) { MenuItem autoCrop = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_CROP, 73, R.string.camera_crop).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (u == null) return; Intent cropIntent = new Intent(); cropIntent.setClass(activity, CropImage.class); cropIntent.setData(u); activity.startActivityForResult(cropIntent, RESULT_COMMON_MENU_CROP); } }); return true; } }); autoCrop.setIcon(android.R.drawable.ic_menu_crop); requiresWriteAccessItems.add(autoCrop); } if (isImage && ((inclusions & INCLUDE_SET_MENU) != 0)) { MenuItem setMenu = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_SET, 75, R.string.camera_set); setMenu.setIcon(android.R.drawable.ic_menu_set_as); setMenu.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (u == null || image == null) return; if (Config.LOGV) Log.v(TAG, "in callback u is " + u + "; mime type is " + image.getMimeType()); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA); intent.setDataAndType(u, image.getMimeType()); intent.putExtra("mimeType", image.getMimeType()); activity.startActivity(Intent.createChooser(intent, activity.getText(R.string.setImage))); } }); return true; } }); } if ((inclusions & INCLUDE_SHARE_MENU) != 0) { if (Config.LOGV) Log.v(TAG, ">>>>> add share"); MenuItem item1 = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_SHARE, 10, R.string.camera_share).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null) return; - if (isMMSUri(u)) return; if (!isImage && getImageFileSize(image) > SHARE_FILE_LENGTH_LIMIT ) { Toast.makeText(activity, R.string.too_large_to_attach, Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); String mimeType = image.getMimeType(); intent.setType(mimeType); intent.putExtra(Intent.EXTRA_STREAM, u); boolean isImage = ImageManager.isImageMimeType(mimeType); try { activity.startActivity(Intent.createChooser(intent, activity.getText( isImage ? R.string.sendImage : R.string.sendVideo))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(activity, isImage ? R.string.no_way_to_share_image : R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } }); return true; } }); item1.setIcon(android.R.drawable.ic_menu_share); MenuItem item = item1; requiresNoDrmAccessItems.add(item); } if ((inclusions & INCLUDE_DELETE_MENU) != 0) { MenuItem deleteItem = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_TOSS, 70, R.string.camera_toss); requiresWriteAccessItems.add(deleteItem); deleteItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { deleteImpl(activity, onDelete, isImage); return true; } }) .setAlphabeticShortcut('d') .setIcon(android.R.drawable.ic_menu_delete); } if ((inclusions & INCLUDE_DETAILS_MENU) != 0) { MenuItem detailsMenu = menu.add(0, 0, 80, R.string.details).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null) return; AlertDialog.Builder builder = new AlertDialog.Builder(activity); final View d = View.inflate(activity, R.layout.detailsview, null); ImageView imageView = (ImageView) d.findViewById(R.id.details_thumbnail_image); imageView.setImageBitmap(image.miniThumbBitmap()); TextView textView = (TextView) d.findViewById(R.id.details_image_title); textView.setText(image.getDisplayName()); long length = getImageFileSize(image); String lengthString = lengthString = length < 0 ? "" : android.text.format.Formatter.formatFileSize(activity, length); ((TextView)d.findViewById(R.id.details_file_size_value)) .setText(lengthString); int dimensionWidth = 0; int dimensionHeight = 0; if (isImage) { dimensionWidth = image.getWidth(); dimensionHeight = image.getHeight(); d.findViewById(R.id.details_duration_row).setVisibility(View.GONE); d.findViewById(R.id.details_frame_rate_row).setVisibility(View.GONE); d.findViewById(R.id.details_bit_rate_row).setVisibility(View.GONE); d.findViewById(R.id.details_format_row).setVisibility(View.GONE); d.findViewById(R.id.details_codec_row).setVisibility(View.GONE); } else { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setMode(MediaMetadataRetriever.MODE_GET_METADATA_ONLY); retriever.setDataSource(image.getDataPath()); try { dimensionWidth = Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)); dimensionHeight = Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); } catch (NumberFormatException e) { dimensionWidth = 0; dimensionHeight = 0; } try { int durationMs = Integer.parseInt(retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_DURATION)); String durationValue = formatDuration( activity, durationMs); ((TextView)d.findViewById(R.id.details_duration_value)) .setText(durationValue); } catch (NumberFormatException e) { d.findViewById(R.id.details_frame_rate_row) .setVisibility(View.GONE); } try { String frame_rate = String.format( activity.getString(R.string.details_fps), Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_FRAME_RATE))); ((TextView)d.findViewById(R.id.details_frame_rate_value)) .setText(frame_rate); } catch (NumberFormatException e) { d.findViewById(R.id.details_frame_rate_row) .setVisibility(View.GONE); } try { long bitRate = Long.parseLong(retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_BIT_RATE)); String bps; if (bitRate < 1000000) { bps = String.format( activity.getString(R.string.details_kbps), bitRate / 1000); } else { bps = String.format( activity.getString(R.string.details_mbps), ((double) bitRate) / 1000000.0); } ((TextView)d.findViewById(R.id.details_bit_rate_value)) .setText(bps); } catch (NumberFormatException e) { d.findViewById(R.id.details_bit_rate_row) .setVisibility(View.GONE); } String format = retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_FORMAT); ((TextView)d.findViewById(R.id.details_format_value)) .setText(format); String codec = retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_CODEC); if (codec == null) { d.findViewById(R.id.details_codec_row). setVisibility(View.GONE); } else { ((TextView)d.findViewById(R.id.details_codec_value)) .setText(codec); } } catch(RuntimeException ex) { // Assume this is a corrupt video file. } finally { try { retriever.release(); } catch (RuntimeException ex) { // Ignore failures while cleaning up. } } } String dimensionsString = String.format( activity.getString(R.string.details_dimension_x), dimensionWidth, dimensionHeight); ((TextView)d.findViewById(R.id.details_resolution_value)) .setText(dimensionsString); String dateString = ""; long dateTaken = image.getDateTaken(); if (dateTaken != 0) { java.util.Date date = new java.util.Date(image.getDateTaken()); java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(); dateString = dateFormat.format(date); ((TextView)d.findViewById(R.id.details_date_taken_value)) .setText(dateString); } else { d.findViewById(R.id.details_date_taken_row) .setVisibility(View.GONE); } builder.setNeutralButton(R.string.details_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setIcon(android.R.drawable.ic_dialog_info) .setTitle(R.string.details_panel_title) .setView(d) .show(); } }); return true; } }); detailsMenu.setIcon(R.drawable.ic_menu_view_details); } if ((!isImage) && ((inclusions & INCLUDE_VIEWPLAY_MENU) != 0)) { menu.add(VIDEO_SAVING_ITEM, MENU_VIDEO_PLAY, 0, R.string.video_play) .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri uri, IImage image) { if (image != null) { Intent intent = new Intent(Intent.ACTION_VIEW, image.fullSizeImageUri()); activity.startActivity(intent); } }}); return true; } }); } return new MenuItemsResult() { public void gettingReadyToOpen(Menu menu, ImageManager.IImage image) { // protect against null here. this isn't strictly speaking required // but if a client app isn't handling sdcard removal properly it // could happen if (image == null) { return; } boolean readOnly = image.isReadonly(); boolean isDrm = image.isDrm(); if (Config.LOGV) Log.v(TAG, "readOnly: " + readOnly + "; drm: " + isDrm); for (MenuItem item: requiresWriteAccessItems) { if (Config.LOGV) Log.v(TAG, "item is " + item.toString()); item.setVisible(!readOnly); item.setEnabled(!readOnly); } for (MenuItem item: requiresNoDrmAccessItems) { if (Config.LOGV) Log.v(TAG, "item is " + item.toString()); item.setVisible(!isDrm); item.setEnabled(!isDrm); } } public void aboutToCall(MenuItem menu, ImageManager.IImage image) { } }; } static void deletePhoto(Activity activity, Runnable onDelete) { deleteImpl(activity, onDelete, true); } static void deleteVideo(Activity activity, Runnable onDelete) { deleteImpl(activity, onDelete, false); } static void deleteImage(Activity activity, Runnable onDelete, IImage image) { if (image != null) { deleteImpl(activity, onDelete, ImageManager.isImage(image)); } } private static void deleteImpl(Activity activity, final Runnable onDelete, boolean isPhoto) { boolean confirm = android.preference.PreferenceManager.getDefaultSharedPreferences(activity).getBoolean("pref_gallery_confirm_delete_key", true); if (!confirm) { if (onDelete != null) onDelete.run(); } else { displayDeleteDialog(activity, onDelete, isPhoto); } } public static void displayDeleteDialog(Activity activity, final Runnable onDelete, boolean isPhoto) { android.app.AlertDialog.Builder b = new android.app.AlertDialog.Builder(activity); b.setIcon(android.R.drawable.ic_dialog_alert); b.setTitle(R.string.confirm_delete_title); b.setMessage(isPhoto? R.string.confirm_delete_message : R.string.confirm_delete_video_message); b.setPositiveButton(android.R.string.ok, new android.content.DialogInterface.OnClickListener() { public void onClick(android.content.DialogInterface v, int x) { if (onDelete != null) onDelete.run(); } }); b.setNegativeButton(android.R.string.cancel, new android.content.DialogInterface.OnClickListener() { public void onClick(android.content.DialogInterface v, int x) { } }); b.create().show(); } static void addSwitchModeMenuItem(Menu menu, final Activity activity, final boolean switchToVideo) { int group = switchToVideo ? MenuHelper.IMAGE_MODE_ITEM : MenuHelper.VIDEO_MODE_ITEM; int labelId = switchToVideo ? R.string.switch_to_video_lable : R.string.switch_to_camera_lable; int iconId = switchToVideo ? R.drawable.ic_menu_camera_video_view : android.R.drawable.ic_menu_camera; MenuItem item = menu.add(group, MENU_SWITCH_CAMERA_MODE, 0, labelId).setOnMenuItemClickListener( new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { String action = switchToVideo ? MediaStore.INTENT_ACTION_VIDEO_CAMERA : MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA; Intent intent = new Intent(action); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); activity.startActivity(intent); return true; } }); item.setIcon(iconId); } static void gotoStillImageCapture(Activity activity) { Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Log.e(TAG, "Could not start still image capture activity", e); } } static void gotoCameraImageGallery(Activity activity) { gotoGallery(activity, R.string.gallery_camera_bucket_name, ImageManager.INCLUDE_IMAGES); } static void gotoCameraVideoGallery(Activity activity) { gotoGallery(activity, R.string.gallery_camera_videos_bucket_name, ImageManager.INCLUDE_VIDEOS); } static private void gotoGallery(Activity activity, int windowTitleId, int mediaTypes) { Uri target = Images.Media.INTERNAL_CONTENT_URI.buildUpon().appendQueryParameter("bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build(); Intent intent = new Intent(Intent.ACTION_VIEW, target); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("windowTitle", activity.getString(windowTitleId)); intent.putExtra("mediaTypes", mediaTypes); // Request unspecified so that we match the current camera orientation rather than // matching the "flip orientation" preference. // Disabled because people don't care for it. Also it's // not as compelling now that we have implemented have quick orientation flipping. // intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, // android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Log.e(TAG, "Could not start gallery activity", e); } } static void addCapturePictureMenuItems(Menu menu, final Activity activity) { menu.add(0, MENU_CAPTURE_PICTURE, 1, R.string.capture_picture) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { activity.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { // Ignore exception } return true; } }) .setIcon(android.R.drawable.ic_menu_camera); } static void addCaptureVideoMenuItems(Menu menu, final Activity activity) { menu.add(0, MENU_CAPTURE_VIDEO, 2, R.string.capture_video) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { activity.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { // Ignore exception } return true; } }) .setIcon(R.drawable.ic_menu_camera_video_view); } static void addCaptureMenuItems(Menu menu, final Activity activity) { addCapturePictureMenuItems(menu, activity); addCaptureVideoMenuItems(menu, activity); } static MenuItem addFlipOrientation(Menu menu, final Activity activity, final SharedPreferences prefs) { // position 41 after rotate // D return menu .add(Menu.CATEGORY_SECONDARY, 304, 41, R.string.flip_orientation) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // Check what our actual orientation is int current = activity.getResources().getConfiguration().orientation; int newOrientation = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; if (current == Configuration.ORIENTATION_LANDSCAPE) { newOrientation = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; } SharedPreferences.Editor editor = prefs.edit(); editor.putInt("nuorientation", newOrientation); editor.commit(); requestOrientation(activity, prefs, true); return true; } }) .setIcon(android.R.drawable.ic_menu_always_landscape_portrait); } static void requestOrientation(Activity activity, SharedPreferences prefs) { requestOrientation(activity, prefs, false); } static private void requestOrientation(Activity activity, SharedPreferences prefs, boolean ignoreIntentExtra) { // Disable orientation for now. If it is set to SCREEN_ORIENTATION_SENSOR, // a duplicated orientation will be observed. return; } static void setFlipOrientationEnabled(Activity activity, MenuItem flipItem) { int keyboard = activity.getResources().getConfiguration().hardKeyboardHidden; flipItem.setEnabled(keyboard != android.content.res.Configuration.HARDKEYBOARDHIDDEN_NO); } public static String formatDuration(final Activity activity, int durationMs) { int duration = durationMs / 1000; int h = duration / 3600; int m = (duration - h * 3600) / 60; int s = duration - (h * 3600 + m * 60); String durationValue; if (h == 0) { durationValue = String.format( activity.getString(R.string.details_ms), m, s); } else { durationValue = String.format( activity.getString(R.string.details_hms), h, m, s); } return durationValue; } public static void showStorageToast(Activity activity) { showStorageToast(activity, calculatePicturesRemaining()); } public static void showStorageToast(Activity activity, int remaining) { String noStorageText = null; if (remaining == MenuHelper.NO_STORAGE_ERROR) { String state = Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING) { noStorageText = activity.getString(R.string.preparing_sd); } else { noStorageText = activity.getString(R.string.no_storage); } } else if (remaining < 1) { noStorageText = activity.getString(R.string.not_enough_space); } if (noStorageText != null) { Toast.makeText(activity, noStorageText, 5000).show(); } } public static int calculatePicturesRemaining() { try { if (!ImageManager.hasStorage()) { return NO_STORAGE_ERROR; } else { String storageDirectory = Environment.getExternalStorageDirectory().toString(); StatFs stat = new StatFs(storageDirectory); float remaining = ((float)stat.getAvailableBlocks() * (float)stat.getBlockSize()) / 400000F; return (int)remaining; } } catch (Exception ex) { // if we can't stat the filesystem then we don't know how many // pictures are remaining. it might be zero but just leave it // blank since we really don't know. return CANNOT_STAT_ERROR; } } } diff --git a/src/com/android/camera/VideoCamera.java b/src/com/android/camera/VideoCamera.java index c8d5f7d..186d827 100644 --- a/src/com/android/camera/VideoCamera.java +++ b/src/com/android/camera/VideoCamera.java @@ -1,810 +1,809 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.location.LocationManager; import android.media.MediaRecorder; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.StatFs; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.MediaStore.Video; import android.text.format.DateFormat; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.MenuItem.OnMenuItemClickListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class VideoCamera extends Activity implements View.OnClickListener, ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback, MediaRecorder.OnErrorListener, MediaRecorder.OnInfoListener { private static final String TAG = "videocamera"; private static final boolean DEBUG = true; private static final boolean DEBUG_SUPPRESS_AUDIO_RECORDING = DEBUG && false; private static final int CLEAR_SCREEN_DELAY = 4; private static final int UPDATE_RECORD_TIME = 5; private static final int SCREEN_DELAY = 2 * 60 * 1000; private static final long NO_STORAGE_ERROR = -1L; private static final long CANNOT_STAT_ERROR = -2L; private static final long LOW_STORAGE_THRESHOLD = 512L * 1024L; private static final long SHARE_FILE_LENGTH_LIMIT = 3L * 1024L * 1024L; private static final int STORAGE_STATUS_OK = 0; private static final int STORAGE_STATUS_LOW = 1; private static final int STORAGE_STATUS_NONE = 2; public static final int MENU_SETTINGS = 6; public static final int MENU_GALLERY_PHOTOS = 7; public static final int MENU_GALLERY_VIDEOS = 8; public static final int MENU_SAVE_GALLERY_PHOTO = 34; public static final int MENU_SAVE_PLAY_VIDEO = 35; public static final int MENU_SAVE_SELECT_VIDEO = 36; public static final int MENU_SAVE_NEW_VIDEO = 37; SharedPreferences mPreferences; private static final float VIDEO_ASPECT_RATIO = 176.0f / 144.0f; VideoPreview mVideoPreview; SurfaceHolder mSurfaceHolder = null; ImageView mVideoFrame; private boolean mIsVideoCaptureIntent; // mLastPictureButton and mThumbController // are non-null only if isVideoCaptureIntent() is true; private ImageView mLastPictureButton; private ThumbnailController mThumbController; private static final int MAX_RECORDING_DURATION_MS = 10 * 60 * 1000; private int mStorageStatus = STORAGE_STATUS_OK; private MediaRecorder mMediaRecorder; private boolean mMediaRecorderRecording = false; private long mRecordingStartTime; // The video file that the hardware camera is about to record into // (or is recording into.) private String mCameraVideoFilename; private FileDescriptor mCameraVideoFileDescriptor; // The video file that has already been recorded, and that is being // examined by the user. private String mCurrentVideoFilename; private long mCurrentVideoFileLength = 0L; private Uri mCurrentVideoUri; private ContentValues mCurrentVideoValues; boolean mPausing = false; static ContentResolver mContentResolver; int mCurrentZoomIndex = 0; private ShutterButton mShutterButton; private TextView mRecordingTimeView; private boolean mRecordingTimeCountsDown = false; ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>(); View mPostPictureAlert; LocationManager mLocationManager = null; private Handler mHandler = new MainHandler(); /** This Handler is used to post message back onto the main thread of the application */ private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case CLEAR_SCREEN_DELAY: { clearScreenOnFlag(); break; } case UPDATE_RECORD_TIME: { if (mMediaRecorderRecording) { long now = SystemClock.uptimeMillis(); long delta = now - mRecordingStartTime; // Starting a minute before reaching the max duration // limit, we'll countdown the remaining time instead. boolean countdown_remaining_time = (delta >= MAX_RECORDING_DURATION_MS - 60000); if (countdown_remaining_time) { delta = Math.max(0, MAX_RECORDING_DURATION_MS - delta); } long seconds = (delta + 500) / 1000; // round to nearest long minutes = seconds / 60; long hours = minutes / 60; long remainderMinutes = minutes - (hours * 60); long remainderSeconds = seconds - (minutes * 60); String secondsString = Long.toString(remainderSeconds); if (secondsString.length() < 2) { secondsString = "0" + secondsString; } String minutesString = Long.toString(remainderMinutes); if (minutesString.length() < 2) { minutesString = "0" + minutesString; } String text = minutesString + ":" + secondsString; if (hours > 0) { String hoursString = Long.toString(hours); if (hoursString.length() < 2) { hoursString = "0" + hoursString; } text = hoursString + ":" + text; } mRecordingTimeView.setText(text); if (mRecordingTimeCountsDown != countdown_remaining_time) { // Avoid setting the color on every update, do it only // when it needs changing. mRecordingTimeCountsDown = countdown_remaining_time; int color = getResources().getColor( countdown_remaining_time ? R.color.recording_time_remaining_text : R.color.recording_time_elapsed_text); mRecordingTimeView.setTextColor(color); } // Work around a limitation of the T-Mobile G1: The T-Mobile // hardware blitter can't pixel-accurately scale and clip at the same time, // and the SurfaceFlinger doesn't attempt to work around this limitation. // In order to avoid visual corruption we must manually refresh the entire // surface view when changing any overlapping view's contents. mVideoPreview.invalidate(); mHandler.sendEmptyMessageDelayed(UPDATE_RECORD_TIME, 1000); } break; } default: Log.v(TAG, "Unhandled message: " + msg.what); break; } } }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_EJECT)) { updateAndShowStorageHint(false); stopVideoRecording(); initializeVideo(); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { updateAndShowStorageHint(true); initializeVideo(); } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) { // SD card unavailable // handled in ACTION_MEDIA_EJECT } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { Toast.makeText(VideoCamera.this, getResources().getString(R.string.wait), 5000); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { updateAndShowStorageHint(true); } } }; static private String createName(long dateTaken) { return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString(); } /** Called with the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mContentResolver = getContentResolver(); //setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.video_camera); mVideoPreview = (VideoPreview) findViewById(R.id.camera_preview); mVideoPreview.setAspectRatio(VIDEO_ASPECT_RATIO); // don't set mSurfaceHolder here. We have it set ONLY within // surfaceCreated / surfaceDestroyed, other parts of the code // assume that when it is set, the surface is also set. SurfaceHolder holder = mVideoPreview.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mPostPictureAlert = findViewById(R.id.post_picture_panel); int[] ids = new int[]{R.id.play, R.id.share, R.id.discard, R.id.cancel, R.id.attach}; for (int id : ids) { findViewById(id).setOnClickListener(this); } mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); mRecordingTimeView = (TextView) findViewById(R.id.recording_time); mVideoFrame = (ImageView) findViewById(R.id.video_frame); mIsVideoCaptureIntent = isVideoCaptureIntent(); if (!mIsVideoCaptureIntent) { mLastPictureButton = (ImageView) findViewById(R.id.last_picture_button); mLastPictureButton.setOnClickListener(this); Drawable frame = getResources().getDrawable(R.drawable.frame_thumbnail); mThumbController = new ThumbnailController(mLastPictureButton, frame, mContentResolver); mThumbController.loadData(ImageManager.getLastVideoThumbPath()); } } private void startShareVideoActivity() { - if (MenuHelper.isMMSUri(mCurrentVideoUri)) return; if (mCurrentVideoFileLength > SHARE_FILE_LENGTH_LIMIT) { Toast.makeText(VideoCamera.this, R.string.too_large_to_attach, Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("video/3gpp"); intent.putExtra(Intent.EXTRA_STREAM, mCurrentVideoUri); try { startActivity(Intent.createChooser(intent, getText(R.string.sendVideo))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(VideoCamera.this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } public void onClick(View v) { switch (v.getId()) { case R.id.gallery: MenuHelper.gotoCameraVideoGallery(this); break; case R.id.attach: doReturnToCaller(true); break; case R.id.cancel: doReturnToCaller(false); break; case R.id.discard: { Runnable deleteCallback = new Runnable() { public void run() { discardCurrentVideoAndStartPreview(); } }; MenuHelper.deleteVideo(this, deleteCallback); break; } case R.id.share: { startShareVideoActivity(); break; } case R.id.play: { doPlayCurrentVideo(); break; } case R.id.last_picture_button: { stopVideoRecordingAndShowAlert(); break; } } } public void onShutterButtonFocus(ShutterButton button, boolean pressed) { // Do nothing (everything happens in onShutterButtonClick). } public void onShutterButtonClick(ShutterButton button) { switch (button.getId()) { case R.id.shutter_button: if (mMediaRecorderRecording) { if (mIsVideoCaptureIntent) { stopVideoRecordingAndShowAlert(); } else { stopVideoRecordingAndGetThumbnail(); initializeVideo(); } } else if (isAlertVisible()) { if (mIsVideoCaptureIntent) { discardCurrentVideoAndStartPreview(); } else { hideAlertAndStartVideoRecording(); } } else { startVideoRecording(); } break; } } private void doPlayCurrentVideo() { Log.e(TAG, "Playing current video: " + mCurrentVideoUri); Intent intent = new Intent(Intent.ACTION_VIEW, mCurrentVideoUri); try { startActivity(intent); } catch (android.content.ActivityNotFoundException ex) { Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex); } } private void discardCurrentVideoAndStartPreview() { deleteCurrentVideo(); hideAlertAndStartPreview(); } private OnScreenHint mStorageHint; private void updateAndShowStorageHint(boolean mayHaveSd) { mStorageStatus = getStorageStatus(mayHaveSd); showStorageHint(); } private void showStorageHint() { String errorMessage = null; switch (mStorageStatus) { case STORAGE_STATUS_NONE: errorMessage = getString(R.string.no_storage); break; case STORAGE_STATUS_LOW: errorMessage = getString(R.string.spaceIsLow_content); } if (errorMessage != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, errorMessage); } else { mStorageHint.setText(errorMessage); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } private int getStorageStatus(boolean mayHaveSd) { long remaining = mayHaveSd ? getAvailableStorage() : NO_STORAGE_ERROR; if (remaining == NO_STORAGE_ERROR) { return STORAGE_STATUS_NONE; } return remaining < LOW_STORAGE_THRESHOLD ? STORAGE_STATUS_LOW : STORAGE_STATUS_OK; } @Override public void onResume() { super.onResume(); setScreenTimeoutLong(); mPausing = false; // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_EJECT); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); mStorageStatus = getStorageStatus(true); mHandler.postDelayed(new Runnable() { public void run() { showStorageHint(); } }, 200); initializeVideo(); } @Override public void onStop() { setScreenTimeoutSystemDefault(); super.onStop(); } @Override protected void onPause() { super.onPause(); // This is similar to what mShutterButton.performClick() does, // but not quite the same. if (mMediaRecorderRecording) { if (mIsVideoCaptureIntent) { stopVideoRecordingAndShowAlert(); } else { stopVideoRecordingAndGetThumbnail(); } } else { stopVideoRecording(); } mPausing = true; unregisterReceiver(mReceiver); setScreenTimeoutSystemDefault(); if (!mIsVideoCaptureIntent) { mThumbController.storeData(ImageManager.getLastVideoThumbPath()); } if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { setScreenTimeoutLong(); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mMediaRecorderRecording) { mShutterButton.performClick(); return true; } else if(isAlertVisible()) { hideAlertAndStartPreview(); return true; } break; case KeyEvent.KEYCODE_CAMERA: if (event.getRepeatCount() == 0) { mShutterButton.performClick(); return true; } break; case KeyEvent.KEYCODE_DPAD_CENTER: if (event.getRepeatCount() == 0) { mShutterButton.performClick(); return true; } break; case KeyEvent.KEYCODE_MENU: if (mMediaRecorderRecording) { mShutterButton.performClick(); return true; } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_CAMERA: mShutterButton.setPressed(false); return true; } return super.onKeyUp(keyCode, event); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { if (mPausing) { // We're pausing, the screen is off and we already stopped // video recording. We don't want to start the camera again // in this case in order to conserve power. // The fact that surfaceChanged is called _after_ an onPause appears // to be legitimate since in that case the lockscreen always returns // to portrait orientation possibly triggering the notification. return; } stopVideoRecording(); initializeVideo(); } public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; } public void surfaceDestroyed(SurfaceHolder holder) { mSurfaceHolder = null; } void gotoGallery() { MenuHelper.gotoCameraVideoGallery(this); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); for (int i = 1; i <= MenuHelper.MENU_ITEM_MAX; i++) { if (i != MenuHelper.GENERIC_ITEM) { menu.setGroupVisible(i, false); } } menu.setGroupVisible(MenuHelper.VIDEO_MODE_ITEM, true); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (mIsVideoCaptureIntent) { // No options menu for attach mode. return false; } else { addBaseMenuItems(menu); int menuFlags = MenuHelper.INCLUDE_ALL & ~MenuHelper.INCLUDE_ROTATE_MENU & ~MenuHelper.INCLUDE_DETAILS_MENU; MenuHelper.addImageMenuItems( menu, menuFlags, false, VideoCamera.this, mHandler, // Handler for deletion new Runnable() { public void run() { // What do we do here? // mContentResolver.delete(uri, null, null); } }, new MenuHelper.MenuInvoker() { public void run(final MenuHelper.MenuCallback cb) { } }); MenuItem gallery = menu.add(MenuHelper.IMAGE_SAVING_ITEM, MENU_SAVE_GALLERY_PHOTO, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); } return true; } private boolean isVideoCaptureIntent() { String action = getIntent().getAction(); return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action)); } private void doReturnToCaller(boolean success) { Intent resultIntent = new Intent(); int resultCode; if (success) { resultCode = RESULT_OK; resultIntent.setData(mCurrentVideoUri); } else { resultCode = RESULT_CANCELED; } setResult(resultCode, resultIntent); finish(); } /** * Returns * @return number of bytes available, or an ERROR code. */ private static long getAvailableStorage() { try { if (!ImageManager.hasStorage()) { return NO_STORAGE_ERROR; } else { String storageDirectory = Environment.getExternalStorageDirectory().toString(); StatFs stat = new StatFs(storageDirectory); return ((long)stat.getAvailableBlocks() * (long)stat.getBlockSize()); } } catch (Exception ex) { // if we can't stat the filesystem then we don't know how many // free bytes exist. It might be zero but just leave it // blank since we really don't know. return CANNOT_STAT_ERROR; } } private void cleanupEmptyFile() { if (mCameraVideoFilename != null) { File f = new File(mCameraVideoFilename); if (f.length() == 0 && f.delete()) { Log.v(TAG, "Empty video file deleted: " + mCameraVideoFilename); mCameraVideoFilename = null; } } } // initializeVideo() starts preview and prepare media recorder. // Returns false if initializeVideo fails private boolean initializeVideo() { Log.v(TAG, "initializeVideo"); // We will call initializeVideo() again when the alert is hidden. if (isAlertVisible()) return false; Intent intent = getIntent(); Bundle myExtras = intent.getExtras(); if (mIsVideoCaptureIntent && myExtras != null) { Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); if (saveUri != null) { try { mCameraVideoFileDescriptor = mContentResolver. openFileDescriptor(saveUri, "rw").getFileDescriptor(); mCurrentVideoUri = saveUri; } catch (java.io.FileNotFoundException ex) { // invalid uri Log.e(TAG, ex.toString()); } } } releaseMediaRecorder(); if (mSurfaceHolder == null) { Log.v(TAG, "SurfaceHolder is null"); return false; } mMediaRecorder = new MediaRecorder(); if (DEBUG_SUPPRESS_AUDIO_RECORDING) { Log.v(TAG, "DEBUG_SUPPRESS_AUDIO_RECORDING is true."); } else { mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); } mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mMediaRecorder.setMaxDuration(MAX_RECORDING_DURATION_MS); if (mStorageStatus != STORAGE_STATUS_OK) { mMediaRecorder.setOutputFile("/dev/null"); } else { // We try Uri in intent first. If it doesn't work, use our own instead. if (mCameraVideoFileDescriptor != null) { mMediaRecorder.setOutputFile(mCameraVideoFileDescriptor); } else { createVideoPath(); mMediaRecorder.setOutputFile(mCameraVideoFilename); } } boolean videoQualityHigh = getBooleanPreference(CameraSettings.KEY_VIDEO_QUALITY, CameraSettings.DEFAULT_VIDEO_QUALITY_VALUE); if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) { int extraVideoQuality = intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); videoQualityHigh = (extraVideoQuality > 0); } // Use the same frame rate for both, since internally // if the frame rate is too large, it can cause camera to become // unstable. We need to fix the MediaRecorder to disable the support // of setting frame rate for now. mMediaRecorder.setVideoFrameRate(20); if (videoQualityHigh) { mMediaRecorder.setVideoSize(352,288); } else { mMediaRecorder.setVideoSize(176,144); } mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); if (!DEBUG_SUPPRESS_AUDIO_RECORDING) { mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); } mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); long remaining = getAvailableStorage(); // remaining >= LOW_STORAGE_THRESHOLD at this point, reserve a quarter // of that to make it more likely that recording can complete successfully. try { mMediaRecorder.setMaxFileSize(remaining - LOW_STORAGE_THRESHOLD / 4); } catch (RuntimeException exception) { // We are going to ignore failure of setMaxFileSize here, as // a) The composer selected may simply not support it, or // b) The underlying media framework may not handle 64-bit range // on the size restriction. } try { mMediaRecorder.prepare(); } catch (IOException exception) { Log.e(TAG, "prepare failed for " + mCameraVideoFilename); releaseMediaRecorder(); // TODO: add more exception handling logic here return false; } mMediaRecorderRecording = false; if (!mIsVideoCaptureIntent && !mThumbController.isUriValid()) { updateLastVideo(); } if (!mIsVideoCaptureIntent) { mThumbController.updateDisplayIfNeeded(); } return true; } private void releaseMediaRecorder() { Log.v(TAG, "Releasing media recorder."); if (mMediaRecorder != null) { cleanupEmptyFile(); mMediaRecorder.reset(); mMediaRecorder.release(); mMediaRecorder = null; } } private int getIntPreference(String key, int defaultValue) { String s = mPreferences.getString(key, ""); int result = defaultValue; try { result = Integer.parseInt(s); } catch (NumberFormatException e) { // Ignore, result is already the default value. diff --git a/src/com/android/camera/ViewImage.java b/src/com/android/camera/ViewImage.java index 5004774..f1f25b7 100644 --- a/src/com/android/camera/ViewImage.java +++ b/src/com/android/camera/ViewImage.java @@ -94,1024 +94,1027 @@ public class ViewImage extends Activity implements View.OnClickListener private Animation [] mSlideShowOutAnimation; private SharedPreferences mPrefs; private View mNextImageView, mPrevImageView; private Animation mHideNextImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mHidePrevImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mShowNextImageViewAnimation = new AlphaAnimation(0F, 1F); private Animation mShowPrevImageViewAnimation = new AlphaAnimation(0F, 1F); static final int sPadding = 20; static final int sHysteresis = sPadding * 2; static final int sBaseScrollDuration = 1000; // ms private ImageManager.IImageList mAllImages; private int mSlideShowImageCurrent = 0; private ImageViewTouch [] mSlideShowImageViews = new ImageViewTouch[2]; private GestureDetector mGestureDetector; private ZoomButtonsController mZoomButtonsController; // Array of image views. The center view is the one the user is focused // on. The one at the zeroth position and the second position reflect // the images to the left/right of the center image. private ImageViewTouch[] mImageViews = new ImageViewTouch[3]; // Container for the three image views. This guy can be "scrolled" // to reveal the image prior to and after the center image. private ScrollHandler mScroller; private MenuHelper.MenuItemsResult mImageMenuRunnable; private Runnable mDismissOnScreenControlsRunnable; private boolean mCameraReviewMode; private void updateNextPrevControls() { boolean showPrev = mCurrentPosition > 0; boolean showNext = mCurrentPosition < mAllImages.getCount() - 1; boolean prevIsVisible = mPrevImageView.getVisibility() == View.VISIBLE; boolean nextIsVisible = mNextImageView.getVisibility() == View.VISIBLE; if (showPrev && !prevIsVisible) { Animation a = mShowPrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.VISIBLE); } else if (!showPrev && prevIsVisible) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.GONE); } if (showNext && !nextIsVisible) { Animation a = mShowNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.VISIBLE); } else if (!showNext && nextIsVisible) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.GONE); } } private void showOnScreenControls() { updateNextPrevControls(); updateZoomButtonsEnabled(); mZoomButtonsController.setVisible(true); scheduleDismissOnScreenControls(); } @Override public boolean dispatchTouchEvent(MotionEvent m) { boolean sup = super.dispatchTouchEvent(m); if (sup == false) { if (mMode == MODE_SLIDESHOW) { mSlideShowImageViews[mSlideShowImageCurrent].handleTouchEvent(m); } else if (mMode == MODE_NORMAL){ mImageViews[1].handleTouchEvent(m); } return true; } return true; } private void scheduleDismissOnScreenControls() { mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); mHandler.postDelayed(mDismissOnScreenControlsRunnable, 1500); } private void updateZoomButtonsEnabled() { ImageViewTouch imageView = mImageViews[1]; float scale = imageView.getScale(); mZoomButtonsController.setZoomInEnabled(scale < imageView.mMaxZoom); mZoomButtonsController.setZoomOutEnabled(scale > 1); } @Override protected void onDestroy() { // This is necessary to make the ZoomButtonsController unregister // its configuration change receiver. if (mZoomButtonsController != null) { mZoomButtonsController.setVisible(false); } super.onDestroy(); } private void setupZoomButtonController(View rootView) { mGestureDetector = new GestureDetector(this, new MyGestureListener()); mZoomButtonsController = new ZoomButtonsController(rootView); mZoomButtonsController.setAutoDismissed(false); mZoomButtonsController.setOnZoomListener( new ZoomButtonsController.OnZoomListener() { public void onVisibilityChanged(boolean visible) { if (visible) { updateZoomButtonsEnabled(); } } public void onZoom(boolean zoomIn) { if (zoomIn) { mImageViews[1].zoomIn(); } else { mImageViews[1].zoomOut(); } showOnScreenControls(); } }); } private class MyGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { ImageViewTouch imageView = mImageViews[1]; if (imageView.getScale() > 1F) { imageView.postTranslate(-distanceX, -distanceY, sUseBounce); imageView.center(true, true, false); } showOnScreenControls(); return true; } @Override public boolean onSingleTapUp(MotionEvent e) { int viewWidth = mImageViews[1].getWidth(); int x = (int) e.getX(); int y = (int) e.getY(); if (x < TOUCH_AREA_WIDTH) { moveNextOrPrevious(-1); } else if (x > viewWidth - TOUCH_AREA_WIDTH) { moveNextOrPrevious(1); } setMode(MODE_NORMAL); showOnScreenControls(); return true; } } private void setupDismissOnScreenControlRunnable() { mDismissOnScreenControlsRunnable = new Runnable() { public void run() { if (!mShowActionIcons) { if (mNextImageView.getVisibility() == View.VISIBLE) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.INVISIBLE); } if (mPrevImageView.getVisibility() == View.VISIBLE) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.INVISIBLE); } mZoomButtonsController.setVisible(false); } } }; } private boolean isPickIntent() { String action = getIntent().getAction(); return (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)); } private static final boolean sUseBounce = false; private static final boolean sAnimateTransitions = false; public static class ImageViewTouch extends ImageViewTouchBase { private ViewImage mViewImage; private boolean mEnableTrackballScroll; public ImageViewTouch(Context context) { super(context); mViewImage = (ViewImage) context; } public ImageViewTouch(Context context, AttributeSet attrs) { super(context, attrs); mViewImage = (ViewImage) context; } public void setEnableTrackballScroll(boolean enable) { mEnableTrackballScroll = enable; } protected void postTranslate(float dx, float dy, boolean bounceOK) { super.postTranslate(dx, dy); if (dx != 0F || dy != 0F) { mViewImage.showOnScreenControls(); } if (!sUseBounce) { center(true, false, false); } } protected ScrollHandler scrollHandler() { return mViewImage.mScroller; } public boolean handleTouchEvent(MotionEvent m) { return mViewImage.mGestureDetector.onTouchEvent(m); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Don't respond to arrow keys if trackball scrolling is not enabled if (!mEnableTrackballScroll) { if ((keyCode >= KeyEvent.KEYCODE_DPAD_UP) && (keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT)) { return super.onKeyDown(keyCode, event); } } int current = mViewImage.mCurrentPosition; int nextImagePos = -2; // default no next image try { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: { if (mViewImage.isPickIntent()) { ImageManager.IImage img = mViewImage.mAllImages.getImageAt(mViewImage.mCurrentPosition); mViewImage.setResult(RESULT_OK, new Intent().setData(img.fullSizeImageUri())); mViewImage.finish(); } break; } case KeyEvent.KEYCODE_DPAD_LEFT: { panBy(sPanRate, 0); int maxOffset = (current == 0) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(true, maxOffset)) { nextImagePos = current - 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_RIGHT: { panBy(-sPanRate, 0); int maxOffset = (current == mViewImage.mAllImages.getCount() - 1) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(false, maxOffset)) { nextImagePos = current + 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_UP: { panBy(0, sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DPAD_DOWN: { panBy(0, -sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DEL: MenuHelper.deletePhoto( mViewImage, mViewImage.mDeletePhotoRunnable); break; } } finally { if (nextImagePos >= 0 && nextImagePos < mViewImage.mAllImages.getCount()) { synchronized (mViewImage) { mViewImage.setMode(MODE_NORMAL); mViewImage.setImage(nextImagePos); } } else if (nextImagePos != -2) { center(true, true, false); } } return super.onKeyDown(keyCode, event); } protected boolean isShiftedToNextImage(boolean left, int maxOffset) { boolean retval; Bitmap bitmap = mBitmapDisplayed; Matrix m = getImageViewMatrix(); if (left) { float [] t1 = new float[] { 0, 0 }; m.mapPoints(t1); retval = t1[0] > maxOffset; } else { int width = bitmap != null ? bitmap.getWidth() : getWidth(); float [] t1 = new float[] { width, 0 }; m.mapPoints(t1); retval = t1[0] + maxOffset < getWidth(); } return retval; } protected void scrollX(int deltaX) { scrollHandler().scrollBy(deltaX, 0); } protected int getScrollOffset() { return scrollHandler().getScrollX(); } } static class ScrollHandler extends LinearLayout { private Runnable mFirstLayoutCompletedCallback = null; private Scroller mScrollerHelper; private ViewImage mViewImage; private int mWidth = -1; public ScrollHandler(Context context) { super(context); mScrollerHelper = new Scroller(context); mViewImage = (ViewImage) context; } public ScrollHandler(Context context, AttributeSet attrs) { super(context, attrs); mScrollerHelper = new Scroller(context); mViewImage = (ViewImage) context; } public void startScrollTo(int newX, int newY) { int oldX = getScrollX(); int oldY = getScrollY(); int deltaX = newX - oldX; int deltaY = newY - oldY; if (mWidth == -1) { mWidth = findViewById(R.id.image2).getWidth(); } int viewWidth = mWidth; int duration = viewWidth > 0 ? sBaseScrollDuration * Math.abs(deltaX) / viewWidth : 0; mScrollerHelper.startScroll(oldX, oldY, deltaX, deltaY, duration); invalidate(); } @Override public void computeScroll() { if (mScrollerHelper.computeScrollOffset()) { scrollTo(mScrollerHelper.getCurrX(), mScrollerHelper.getCurrY()); postInvalidate(); // So we draw again } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int width = right - left; int x = 0; for (View v : new View[] { findViewById(R.id.image1), findViewById(R.id.image2), findViewById(R.id.image3) }) { v.layout(x, 0, x + width, bottom); x += (width + sPadding); } findViewById(R.id.padding1).layout(width, 0, width + sPadding, bottom); findViewById(R.id.padding2).layout(width + sPadding + width, 0, width + sPadding + width + sPadding, bottom); if (changed) { mViewImage.mLayoutComplete = true; mViewImage.onLayoutChanged(); } } } private void animateScrollTo(int xNew, int yNew) { mScroller.startScrollTo(xNew, yNew); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (! mCameraReviewMode) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.slide_show); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { setMode(MODE_SLIDESHOW); mLastSlideShowImage = mCurrentPosition; loadNextImage(mCurrentPosition, 0, true); return true; } }); item.setIcon(android.R.drawable.ic_menu_slideshow); } final SelectedImageGetter selectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return mAllImages.getImageAt(mCurrentPosition); } public Uri getCurrentImageUri() { return mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); } }; mImageMenuRunnable = MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL, true, ViewImage.this, mHandler, mDeletePhotoRunnable, new MenuHelper.MenuInvoker() { public void run(MenuHelper.MenuCallback cb) { setMode(MODE_NORMAL); cb.run(selectedImageGetter.getCurrentImageUri(), selectedImageGetter.getCurrentImage()); for (ImageViewTouchBase iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } setImage(mCurrentPosition); } }); if (true) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 1000, R.string.camerasettings); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent preferences = new Intent(); preferences.setClass(ViewImage.this, GallerySettings.class); startActivity(preferences); return true; } }); item.setAlphabeticShortcut('p'); item.setIcon(android.R.drawable.ic_menu_preferences); } // Hidden menu just so the shortcut will bring up the zoom controls menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.camerasettings) // the string resource is a placeholder .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { showOnScreenControls(); return true; } }) .setAlphabeticShortcut('z') .setVisible(false); return true; } protected Runnable mDeletePhotoRunnable = new Runnable() { public void run() { mAllImages.removeImageAt(mCurrentPosition); if (mAllImages.getCount() == 0) { finish(); } else { if (mCurrentPosition == mAllImages.getCount()) { mCurrentPosition -= 1; } } for (ImageViewTouchBase iv: mImageViews) { iv.setImageBitmapResetBase(null, true, true); } setImage(mCurrentPosition); } }; @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); setMode(MODE_NORMAL); if (mImageMenuRunnable != null) { mImageMenuRunnable.gettingReadyToOpen(menu, mAllImages.getImageAt(mCurrentPosition)); } + Uri uri = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); + MenuHelper.enableShareMenuItem(menu, !MenuHelper.isMMSUri(uri)); + return true; } private void onLayoutChanged() { // if we get here after "onPause" then ignore the event if (mGetter == null) return; mDismissOnScreenControlsRunnable.run(); mGetter.cancelCurrent(); for (ImageViewTouch iv: mImageViews) { iv.clear(); } mFirst = true; setImage(mCurrentPosition); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { boolean b = super.onMenuItemSelected(featureId, item); if (mImageMenuRunnable != null) mImageMenuRunnable.aboutToCall(item, mAllImages.getImageAt(mCurrentPosition)); return b; } /* * Here's the loading strategy. For any given image, load the thumbnail * into memory and post a callback to display the resulting bitmap. * * Then proceed to load the full image bitmap. Three things can * happen at this point: * * 1. the image fails to load because the UI thread decided * to move on to a different image. This "cancellation" happens * by virtue of the UI thread closing the stream containing the * image being decoded. BitmapFactory.decodeStream returns null * in this case. * * 2. the image loaded successfully. At that point we post * a callback to the UI thread to actually show the bitmap. * * 3. when the post runs it checks to see if the image that was * loaded is still the one we want. The UI may have moved on * to some other image and if so we just drop the newly loaded * bitmap on the floor. */ interface ImageGetterCallback { public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb); public boolean wantsThumbnail(int pos, int offset); public boolean wantsFullImage(int pos, int offset); public int fullImageSizeToUse(int pos, int offset); public void completed(boolean wasCanceled); public int [] loadOrder(); } class ImageGetter { // The thread which does the work. private Thread mGetterThread; // The base position that's being retrieved. The actual images retrieved // are this base plus each of the offets. private int mCurrentPosition = -1; // The callback to invoke for each image. private ImageGetterCallback mCB; // This is the loader cancelable that gets set while we're loading an image. // If we change position we can cancel the current load using this. private ImageManager.IGetBitmap_cancelable mLoad; // True if we're canceling the current load. private boolean mCancelCurrent = false; // True when the therad should exit. private boolean mDone = false; // True when the loader thread is waiting for work. private boolean mReady = false; private void cancelCurrent() { synchronized (this) { if (!mReady) { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { if (Config.LOGV) Log.v(TAG, "canceling load object"); load.cancel(); } mCancelCurrent = false; } } } public ImageGetter() { mGetterThread = new Thread(new Runnable() { private Runnable callback(final int position, final int offset, final boolean isThumb, final Bitmap bitmap) { return new Runnable() { public void run() { // check for inflight callbacks that aren't applicable any longer // before delivering them if (!isCanceled() && position == mCurrentPosition) { mCB.imageLoaded(position, offset, bitmap, isThumb); } else if (bitmap != null) { bitmap.recycle(); } } }; } private Runnable completedCallback(final boolean wasCanceled) { return new Runnable() { public void run() { mCB.completed(wasCanceled); } }; } public void run() { int lastPosition = -1; while (!mDone) { synchronized (ImageGetter.this) { mReady = true; ImageGetter.this.notify(); if (mCurrentPosition == -1 || lastPosition == mCurrentPosition) { try { ImageGetter.this.wait(); } catch (InterruptedException ex) { continue; } } lastPosition = mCurrentPosition; mReady = false; } if (lastPosition != -1) { int imageCount = mAllImages.getCount(); int [] order = mCB.loadOrder(); for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (image == null || isCanceled()) { break; } if (mCB.wantsThumbnail(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting THUMBNAIL load at offset " + offset); Bitmap b = image.thumbBitmap(); mHandler.postGetterCallback(callback(lastPosition, offset, true, b)); } } } for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (mCB.wantsFullImage(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting FULL IMAGE load at offset " + offset); int sizeToUse = mCB.fullImageSizeToUse(lastPosition, offset); if (image != null && !isCanceled()) { mLoad = image.fullSizeBitmap_cancelable(sizeToUse); } if (mLoad != null) { long t1; if (Config.LOGV) t1 = System.currentTimeMillis(); // The return value could be null if the // bitmap is too big, or we cancelled it. Bitmap b = mLoad.get(); if (Config.LOGV && b != null) { long t2 = System.currentTimeMillis(); Log.v(TAG, "loading full image for " + image.fullSizeImageUri() + " with requested size " + sizeToUse + " took " + (t2 - t1) + " and returned a bitmap with size " + b.getWidth() + " / " + b.getHeight()); } mLoad = null; if (b != null) { if (isCanceled()) { b.recycle(); } else { mHandler.postGetterCallback(callback(lastPosition, offset, false, b)); } } } } } } mHandler.postGetterCallback(completedCallback(isCanceled())); } } } }); mGetterThread.setName("ImageGettter"); mGetterThread.start(); } private boolean isCanceled() { synchronized (this) { return mCancelCurrent; } } public void setPosition(int position, ImageGetterCallback cb) { synchronized (this) { if (!mReady) { try { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { load.cancel(); } // if the thread is waiting before loading the full size // image then this will free it up ImageGetter.this.notify(); ImageGetter.this.wait(); mCancelCurrent = false; } catch (InterruptedException ex) { // not sure what to do here } } } mCurrentPosition = position; mCB = cb; synchronized (this) { ImageGetter.this.notify(); } } public void stop() { synchronized (this) { mDone = true; ImageGetter.this.notify(); } try { mGetterThread.join(); } catch (InterruptedException ex) { } } } private void setImage(int pos) { if (!mLayoutComplete) return; final boolean left = (pos == mCurrentPosition - 1); final boolean right = (pos == mCurrentPosition + 1); mCurrentPosition = pos; ImageViewTouchBase current = mImageViews[1]; current.mSuppMatrix.reset(); current.setImageMatrix(current.getImageViewMatrix()); if (false) { Log.v(TAG, "before..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } if (!mFirst) { if (left) { mImageViews[2].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[0]); } else if (right) { mImageViews[0].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[2]); } } if (false) { Log.v(TAG, "after copy..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } for (ImageViewTouchBase ivt: mImageViews) { ivt.mIsZooming = false; } int width = mImageViews[1].getWidth(); int from; int to = width + sPadding; if (mFirst) { from = to; mFirst = false; } else { from = left ? (width + sPadding) + mScroller.getScrollX() : mScroller.getScrollX() - (width + sPadding); } if (sAnimateTransitions) { mScroller.scrollTo(from, 0); animateScrollTo(to, 0); } else { mScroller.scrollTo(to, 0); } ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { if (!mShowActionIcons) { mImageViews[1].setFocusableInTouchMode(true); mImageViews[1].requestFocus(); } } public boolean wantsThumbnail(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; return ivt.mThumbBitmap == null; } public boolean wantsFullImage(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; if (ivt.mBitmapDisplayed != null && !ivt.mBitmapIsThumbnail) { return false; } if (offset != 0) { return false; } return true; } public int fullImageSizeToUse(int pos, int offset) { // TODO // this number should be bigger so that we can zoom. we may need to // get fancier and read in the fuller size image as the user starts // to zoom. use -1 to get the full full size image. // for now use 480 so we don't run out of memory final int imageViewSize = 480; return imageViewSize; } public int [] loadOrder() { return sOrder_adjacents; } public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb) { // shouldn't get here after onPause() ImageViewTouchBase ivt = mImageViews[1 + offset]; if (offset == 0) updateZoomButtonsEnabled(); ivt.setImageBitmapResetBase(bitmap, isThumb, isThumb); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { mGetter.setPosition(pos, cb); } showOnScreenControls(); } @Override public void onCreate(Bundle instanceState) { super.onCreate(instanceState); Intent intent = getIntent(); mCameraReviewMode = intent.getBooleanExtra("com.android.camera.ReviewMode", false); mFullScreenInNormalMode = intent.getBooleanExtra(MediaStore.EXTRA_FULL_SCREEN, true); mShowActionIcons = intent.getBooleanExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, false); setRequestedOrientation(); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.viewimage); mImageViews[0] = (ImageViewTouch) findViewById(R.id.image1); mImageViews[1] = (ImageViewTouch) findViewById(R.id.image2); mImageViews[2] = (ImageViewTouch) findViewById(R.id.image3); for(ImageViewTouch v : mImageViews) { v.setEnableTrackballScroll(!mShowActionIcons); } mScroller = (ScrollHandler)findViewById(R.id.scroller); makeGetter(); mAnimationIndex = -1; mSlideShowInAnimation = new Animation[] { makeInAnimation(R.anim.transition_in), makeInAnimation(R.anim.slide_in), makeInAnimation(R.anim.slide_in_vertical), }; mSlideShowOutAnimation = new Animation[] { makeOutAnimation(R.anim.transition_out), makeOutAnimation(R.anim.slide_out), makeOutAnimation(R.anim.slide_out_vertical), }; mSlideShowImageViews[0] = (ImageViewTouch) findViewById(R.id.image1_slideShow); mSlideShowImageViews[1] = (ImageViewTouch) findViewById(R.id.image2_slideShow); for (ImageViewTouch v : mSlideShowImageViews) { v.setImageBitmapResetBase(null, true, true); v.setVisibility(View.INVISIBLE); v.setEnableTrackballScroll(!mShowActionIcons); } mActionIconPanel = findViewById(R.id.action_icon_panel); { int[] pickIds = {R.id.attach, R.id.cancel}; int[] normalIds = {R.id.gallery, R.id.setas, R.id.share, R.id.discard}; int[] hideIds = pickIds; int[] connectIds = normalIds; if (isPickIntent()) { hideIds = normalIds; connectIds = pickIds; } for(int id : hideIds) { mActionIconPanel.findViewById(id).setVisibility(View.GONE); } for(int id : connectIds) { View view = mActionIconPanel.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } mShutterButton = findViewById(R.id.shutter_button); mShutterButton.setOnClickListener(this); Uri uri = getIntent().getData(); if (Config.LOGV) Log.v(TAG, "uri is " + uri); if (instanceState != null) { if (instanceState.containsKey("uri")) { uri = Uri.parse(instanceState.getString("uri")); } } if (uri == null) { finish(); return; } init(uri); Bundle b = getIntent().getExtras(); boolean slideShow = b != null ? b.getBoolean("slideshow", false) : false; if (slideShow) { setMode(MODE_SLIDESHOW); loadNextImage(mCurrentPosition, 0, true); } else { if (mFullScreenInNormalMode) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } } setupZoomButtonController(findViewById(R.id.rootLayout)); setupDismissOnScreenControlRunnable(); mNextImageView = findViewById(R.id.next_image); mPrevImageView = findViewById(R.id.prev_image); mNextImageView.setOnClickListener(this); mPrevImageView.setOnClickListener(this); if (mShowActionIcons) { mNextImageView.setFocusable(true); mPrevImageView.setFocusable(true); } } private void setRequestedOrientation() { Intent intent = getIntent(); if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); if (orientation != getRequestedOrientation()) { setRequestedOrientation(orientation); } } else { MenuHelper.requestOrientation(this, mPrefs); } } private Animation makeInAnimation(int id) { Animation inAnimation = AnimationUtils.loadAnimation(this, id); return inAnimation; } private Animation makeOutAnimation(int id) { Animation outAnimation = AnimationUtils.loadAnimation(this, id); return outAnimation; } private void setMode(int mode) { if (mMode == mode) { return; } findViewById(R.id.slideShowContainer).setVisibility(mode == MODE_SLIDESHOW ? View.VISIBLE : View.GONE); findViewById(R.id.abs) .setVisibility(mode == MODE_NORMAL ? View.VISIBLE : View.GONE);
brunsky/WS171-packages-apps-Camera
ee0aecff03a1a13bdc935affaab741997c252bae
Automated import from //branches/cupcake/...@142866,142866
diff --git a/AndroidManifest.xml b/AndroidManifest.xml index ea8f12e..8c79f8c 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,223 +1,229 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.camera" android:sharedUserId="android.media"> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.SET_WALLPAPER" /> <!-- Needed by the ZoomRingController to set the bit saying we've already shown the tutorial toast. --> <uses-permission android:name="android.permission.WRITE_SETTINGS"/> <application android:icon="@drawable/ic_launcher_camera" android:label="@string/camera_label" android:taskAffinity=""> <service android:name="UploadService" android:process="android.process.media" /> <receiver android:name="CameraButtonIntentReceiver"> <intent-filter> <action android:name="android.intent.action.CAMERA_BUTTON"/> </intent-filter> </receiver> <activity android:name="Camera" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" android:screenOrientation="landscape" android:clearTaskOnLaunch="true" android:taskAffinity="android.task.camera"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.media.action.IMAGE_CAPTURE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.media.action.STILL_IMAGE_CAMERA" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="VideoCamera" + android:label="@string/video_camera_label" android:configChanges="orientation|keyboardHidden" + android:icon="@drawable/ic_launcher_video_camera" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" android:screenOrientation="landscape" android:clearTaskOnLaunch="true" - android:taskAffinity="android.task.camera"> + android:taskAffinity="android.task.videocamera"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> <intent-filter> <action android:name="android.media.action.VIDEO_CAMERA" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.media.action.VIDEO_CAPTURE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="GalleryPicker" android:label="@string/gallery_picker_label" android:configChanges="orientation|keyboardHidden" android:icon="@drawable/ic_launcher_gallery" android:clearTaskOnLaunch="true" android:taskAffinity="android.task.pictures"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> - <activity android:name="ImageGallery2" android:label="@string/gallery_label" android:configChanges="orientation|keyboardHidden" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/video" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.GET_CONTENT" /> <category android:name="android.intent.category.OPENABLE" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.GET_CONTENT" /> <category android:name="android.intent.category.OPENABLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> </activity> <activity android:name="CropImage" android:process=":CropImage" android:configChanges="orientation|keyboardHidden" android:label="@string/crop_label"> <intent-filter android:label="@string/crop_label"> <action android:name="com.android.camera.action.CROP" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.ALTERNATIVE" /> <category android:name="android.intent.category.SELECTED_ALTERNATIVE" /> </intent-filter> </activity> <activity android:name="ViewImage" android:label="@string/view_label" android:configChanges="orientation|keyboardHidden"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> </activity> <activity android:name="MovieView" android:label="@string/movieviewlabel" android:screenOrientation="landscape" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="rtsp" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="video/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="http" /> <data android:mimeType="video/mp4" /> <data android:mimeType="video/3gp" /> <data android:mimeType="video/3gpp" /> <data android:mimeType="video/3gpp2" /> </intent-filter> </activity> <activity android:name="CameraSettings" android:label="@string/preferences_label"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEVELOPMENT_PREFERENCE" /> </intent-filter> </activity> <activity android:name="GallerySettings" android:label="@string/preferences_label"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEVELOPMENT_PREFERENCE" /> </intent-filter> </activity> <activity android:name="SlideShow" android:label="Raw Image Viewer" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.TEST" /> </intent-filter> </activity> <activity android:name=".Wallpaper" android:label="@string/camera_setas_wallpaper" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.ATTACH_DATA" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name=".PickWallpaper" android:label="@string/camera_pick_wallpaper" android:icon="@drawable/ic_launcher_gallery"> <intent-filter> <action android:name="android.intent.action.SET_WALLPAPER" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <receiver android:name="PhotoAppWidgetProvider" android:label="@string/gadget_title"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/appwidget_info" /> </receiver> <!-- We configure a widget by asking to pick a photo, then crop it, and store the config internally --> <activity android:name="PhotoAppWidgetConfigure"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" /> </intent-filter> </activity> <!-- We also allow direct binding where the caller provides a bitmap and appWidgetId to bind. We require the permission because this changes our internal database without user confirmation. --> <activity android:name="PhotoAppWidgetBind" android:exported="true" android:theme="@android:style/Theme.NoDisplay" android:permission="android.permission.BIND_APPWIDGET" /> </application> </manifest> diff --git a/res/drawable/ic_launcher_video_camera.png b/res/drawable/ic_launcher_video_camera.png new file mode 100755 index 0000000..e80255a Binary files /dev/null and b/res/drawable/ic_launcher_video_camera.png differ diff --git a/res/values/strings.xml b/res/values/strings.xml index cea087d..7408f57 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -1,462 +1,465 @@ <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <!-- General strings --> <!-- label for the icon meaning 'show me all the images' --> <string name="all_images">All pictures</string> <!-- label for the icon meaning 'show me all the videos' --> <string name="all_videos">All videos</string> <!-- label for the icon meaning 'show me all the images that were taken with the camera' --> <string name="camera_label">Camera</string> + <!-- label for the 'video recording application shown in the top level 'all applications' --> + <string name="video_camera_label">Camcorder</string> + <!-- label for the 'pictures application shown in the top level 'all applications' --> <string name="gallery_picker_label">Gallery</string> <!-- unused (do not translate) --> <string name="gallery_label">Pictures</string> <!-- label for the folder that contains Camera pictures in the gallery --> <string name="gallery_camera_bucket_name">Camera pictures</string> <!-- label for the folder that contains Camera videos in the gallery --> <string name="gallery_camera_videos_bucket_name">Camera videos</string> <!-- menu pick: switch to Video cam mode --> <string name="switch_to_video_lable">Switch to video</string> <!-- menu pick: switch to camera mode --> <string name="switch_to_camera_lable">Switch to camera</string> <!-- menu pick: crop the currently selected image --> <string name="crop_label">Crop picture</string> <!-- menu pick: view the currently selected image --> <string name="view_label">View picture</string> <!-- menu pick: go to the preferences screen for the camera or image gallery --> <string name="preferences_label">Camera settings</string> <!-- alert to the user to wait for some operation to complete --> <string name="wait">Please wait\u2026</string> <!-- alert to the user to that an SD card must be installed before using the camera --> <string name="no_storage">Please insert an SD card before using the camera.</string> <!-- alert to the user to that the SD card is too full to complete the operation --> <string name="not_enough_space">Your SD card is full.</string> <!-- alert to the user to that the SD card is being disk-checked --> <string name="preparing_sd">Preparing SD card\u2026</string> <!-- Toast/alert after saving wallpaper --> <string name="wallpaper">Setting wallpaper, please wait\u2026</string> <!-- Settings stuff --> <!-- Toast/alert that the image is being saved to the SD card --> <string name="savingImage">Saving picture\u2026</string> <!-- Toast/alert that the face detection is being run --> <string name="runningFaceDetection">Please wait\u2026</string> <!-- Menu items: --> <!-- menu pick to change the orientation of the screen --> <string name="flip_orientation">Flip orientation</string> <!-- menu pick to go to the settings screen --> <string name="settings">Settings</string> <!-- menu pick to view the currently selected image --> <string name="view">View</string> <!-- menu pick to view the details of the currently selected image --> <string name="details">Details</string> <!-- menu pick to rotate the currently selected image (brings up submenu) --> <string name="rotate">Rotate</string> <!-- menu pick to rotate the currently selected image to the left --> <string name="rotate_left">Rotate left</string> <!-- menu pick to rotate the currently selected image to the right --> <string name="rotate_right">Rotate right</string> <!-- menu pick to start a slide show --> <string name="slide_show">Slideshow</string> <!-- menu pick to go to camera mode to capture a picture --> <string name="capture_picture">Capture picture</string> <!-- menu pick to go to video mode to capture a video --> <string name="capture_video">Capture video</string> <!-- button indicating that the cropped image should be saved --> <string name="crop_save_text">Save</string> <!-- button indicating that the cropped image should be reverted back to the original --> <string name="crop_discard_text">Discard</string> <!-- Confirmation dialog title after deleting a picture --> <string name="confirm_delete_title">Delete</string> <!-- Confirmation dialog message after deleting a picture --> <string name="confirm_delete_message">The picture will be deleted.</string> <!-- Confirmation dialog message after deleting a video --> <string name="confirm_delete_video_message">The video will be deleted.</string> <!-- button indicating that the picture just taken should be deleted --> <string name="camera_toss">Delete</string> <!-- Lable for the button that takes the user to the camera pictures Gallery --> <string name="camera_gallery">Gallery</string> <!-- button indicating that the picture just taken should be shared by email, mms, etc --> <string name="camera_share">Share</string> <!-- button indicating that the picture just taken should be set as a contact photo, wallpaper, etc --> <string name="camera_set">Set as</string> <!-- button indicating that the video just taken should be played --> <string name="camera_play">Play</string> <!-- button indicating that the video just taken should be accepted as an attachment --> <string name="camera_attach">Attach</string> <!-- button indicating that the video recording session should be canceled --> <string name="camera_cancel">Cancel</string> <!-- button indicating that the picture just taken should be cropped --> <string name="camera_crop">Crop</string> <!-- Toast after deleting a picture --> <string name="camera_tossing">Deleting\u2026</string> <!-- Toast after trying to share a picture indicating that there are no applications which are capable of so doing. --> <string name="no_way_to_share_image">This picture cannot be shared.</string> <!-- Toast after trying to share a video indicating that there are no applications which are capable of so doing. --> <string name="no_way_to_share_video">This video cannot be shared.</string> <!-- Menu item for playing the video. --> <string name="video_play">Play</string> <!-- Button indicating to go to the image gallery --> <string name="camera_gallery_photos_text">Gallery</string> <!-- String indicating an action of picking a picture to use as wallpaper (e.g. set wallpaper from "Pictures") --> <string name="camera_pick_wallpaper">Pictures</string> <string name="camera_setas_wallpaper">Wallpaper</string> <!-- Settings screen, section heading --> <string name="pref_gallery_category">General settings</string> <!-- Settings screen, section heading --> <string name="pref_slideshow_category">Slideshow settings</string> <string name="pref_camera_general_settings_category">General settings</string> <!-- Settings screen, setting summary text --> <string name="pref_gallery_size_title">Display size</string> <!-- Settings screen, title for preference for image size to be used in the im --> <string name="pref_gallery_size_summary">Select the display size of pictures and videos</string> <!-- Title of dialog that appears after selecting Picture size setting option --> <string name="pref_gallery_size_dialogtitle">Picture size</string> <!-- Options in dialog that appears after selecting Picture size setting option --> <string-array name="pref_gallery_size_choices"> <!-- size choice of "large" --> <item>Large</item> <!-- size choice of "small" --> <item>Small</item> </string-array> <!-- Do not translate. Option values in dialog that appears after selecting Picture size setting option --> <string-array name="pref_gallery_size_values"> <!-- do not translate --> <item>1</item> <!-- do not translate --> <item>0</item> </string-array> <!-- Do not translate. Default option value in dialog that appears after selecting Picture size setting option --> <string name="default_value_pref_gallery_size">1</string> <!-- Settings screen, setting option name --> <string name="pref_gallery_sort_title">Sort order</string> <!-- Settings screen, setting summary text --> <string name="pref_gallery_sort_summary">Select the sort order of pictures and videos</string> <!-- Title of dialog that appears after selecting Picture sort setting option --> <string name="pref_gallery_sort_dialogtitle">Picture sort</string> <!-- Options in dialog that appears after selecting Picture sort setting option --> <string-array name="pref_gallery_sort_choices"> <!-- Preference choice to show "newest first" --> <item>Newest first</item> <!-- Preference choice to show "newest last" --> <item>Newest last</item> </string-array> <!-- Do not translate. Option values in dialog that appears after selecting Picture sort setting option --> <string-array name="pref_gallery_sort_values"> <!-- do not translate --> <item>descending</item> <!-- do not translate --> <item>ascending</item> </string-array> <!-- Do not translate. Default option value in dialog that appears after selecting Picture sort setting option --> <string name="default_value_pref_gallery_sort">descending</string> <!-- Settings screen, setting option name --> <string name="pref_gallery_slideshow_interval_title">Slideshow interval</string> <!-- Settings screen, setting summary text --> <string name="pref_gallery_slideshow_interval_summary">Select how long each slide displays in the show</string> <!-- Title of dialog that appears after selecting Slideshow interval setting option --> <string name="pref_gallery_slideshow_interval_dialogtitle">Slideshow interval</string> <!-- Options in dialog that appears after selecting Slideshow interval setting option --> <string-array name="pref_gallery_slideshow_interval_choices"> <!-- slide show interval "N seconds" where N is 2 --> <item>2 seconds</item> <!-- slide show interval "N seconds" where N is 3 --> <item>3 seconds</item> <!-- slide show interval "N seconds" where N is 4 --> <item>4 seconds</item> </string-array> <!-- Do not translate. Option values in dialog that appears after selecting Slideshow interval setting option --> <string-array name="pref_gallery_slideshow_interval_values"> <!-- do not translate --> <item>"2"</item> <!-- do not translate --> <item>"3"</item> <!-- do not translate --> <item>"4"</item> </string-array> <!-- Do not translate. Default option value in dialog that appears after selecting Slideshow interval setting option --> <string name="default_value_pref_gallery_slideshow_interval">"2"</string> <!-- Settings screen, setting option name --> <string name="pref_gallery_slideshow_transition_title">Slideshow transition</string> <!-- Settings screen, setting summary text --> <string name="pref_gallery_slideshow_transition_summary">Select the effect used when moving from one slide to the next</string> <!-- Title of dialog that appears after selecting Slideshow transition setting option --> <string name="pref_gallery_slideshow_transition_dialogtitle">Slideshow transition</string> <!-- Options in dialog that appears after selecting Slideshow transition setting option --> <string-array name="pref_gallery_slideshow_transition_choices"> <!-- Slide show transition to fade in and fade out --> <item>Fade in &amp; out</item> <!-- Slide show transition to slide in and out from the left and right --> <item>Slide left - right</item> <!-- Slide show transition to slide in and out from the top and bottom --> <item>Slide up - down</item> <!-- Slide show transition to be chosen randomly --> <item>Random selection</item> </string-array> <!-- Do not translate. Option values in dialog that appears after selecting Slideshow transition setting option --> <string-array name="pref_gallery_slideshow_transition_values"> <!-- do not translate --> <item>"0"</item> <!-- do not translate --> <item>"1"</item> <!-- do not translate --> <item>"2"</item> <!-- do not translate --> <item>"-1"</item> </string-array> <!-- Do not translate. Default option value in dialog that appears after selecting Slideshow transition setting option --> <string name="default_value_pref_gallery_slideshow_transition">"0"</string> <!-- Settings screen, setting check box name --> <string name="pref_gallery_slideshow_repeat_title">Repeat slideshow</string> <!-- Settings screen, setting summary text --> <string name="pref_gallery_slideshow_repeat_summary">Play slideshow more than once</string> <!-- Settings screen, setting check box name --> <string name="pref_gallery_slideshow_shuffle_title">Shuffle slides</string> <!-- Settings screen, setting summary text --> <string name="pref_gallery_slideshow_shuffle_summary">Show pictures in random order</string> <!-- Settings screen, setting title text --> <string name="pref_camera_recordlocation_title">Store location in pictures</string> <!-- Settings screen, setting summary text --> <string name="pref_camera_recordlocation_summary">Record location in picture data</string> <!-- Do not translate --> <string name="pref_camera_upload_albumname_title">Picasa album name</string> <!-- Do not translate --> <string name="pref_camera_upload_albumname_summary">Name the destination album for your pictures (<xliff:g id="summary">%s</xliff:g>)</string> <!-- Do not translate --> <string name="pref_camera_upload_albumname_dialogtitle">Picasa album name</string> <!-- Settings screen, Video quality category title --> <string name="pref_camera_videoquality_category">Video quality</string> <!-- Default video quality setting. A numerical value. Do not translate. --> <string name="pref_camera_videoquality_default">1</string> <!-- Settings screen, Select Video quality title --> <string name="pref_camera_videoquality_title">Select video quality</string> <!-- Settings screen, Video quality dialog radio button choices --> <string name="pref_camera_videoquality_entry_0">Low (for MMS messages)</string> <string name="pref_camera_videoquality_entry_1">High (for SD card)</string> <!-- Settings screen, Video codec dialog title --> <string name="pref_camera_videoquality_dialogtitle">Video quality</string> <!-- Menu item to go to the settings screen --> <string name="camerasettings">Settings</string> <!-- Text message indicating that there are no pictures or videos in a particular bucket on the SD card --> <string name="image_gallery_NoImageView_text">No media found.</string> <!-- Preference title for whether the user should be prompted form confirmation when deleting images --> <string name="pref_gallery_confirm_delete_title">Confirm deletions</string> <!-- Preference summary for whether the user should be prompted form confirmation when deleting images --> <string name="pref_gallery_confirm_delete_summary">Show confirmation before deleting a picture or video</string> <!-- Details stuff --> <!-- Do not translate --> <string name="details_title_text">myvideo</string> <!-- Do not translate --> <string name="details_tags_text">monster</string> <!-- Do not translate --> <string name="details_category_label">Category:</string> <!-- Do not translate --> <string name="details_description_label">Description:</string> <!-- Do not translate --> <string name="details_publicView_text">Public</string> <!-- Do not translate --> <string name="details_tags_label">Tags:</string> <!-- Do not translate --> <string name="details_description_text">testdescription</string> <!-- Do not translate --> <string name="details_title_label">Title:</string> <!-- Do not translate --> <string name="details_save_text">Save</string> <!-- Do not translate --> <string name="details_language_label">Language:</string> <!-- Do not translate --> <string name="details_privateView_text">Private</string> <!-- Title of Details dialog --> <string name="details_panel_title">Details</string> <!-- Label in message of Details dialog --> <string name="details_file_size">File size:</string> <!-- Label in message of Details dialog --> <string name="details_image_resolution">Resolution:</string> <!-- Label in message of Details dialog --> <string name="details_duration">Duration:</string> <!-- Label in message of Details dialog --> <string name="details_date_taken">Date taken:</string> <!-- Label in message of Details dialog --> <string name="details_frame_rate">Frame rate:</string> <!-- Label in message of Details dialog --> <string name="details_bit_rate">Bit rate:</string> <!-- Label in message of Details dialog --> <string name="details_codec">Codec:</string> <!-- Label in message of Details dialog --> <string name="details_format">Format:</string> <!-- Used to format image dimensions in Details dialog. e.g. 64 x 64 --> <string name="details_dimension_x">%1$d x %2$d</string> <!-- Used to format short video duration in Details dialog. minutes:seconds e.g. 00:30 --> <string name="details_ms">%1$02d:%2$02d</string> <!-- Used to format video duration in Details dialog. hours:minutes:seconds e.g. 0:21:30 --> <string name="details_hms">%1$d:%2$02d:%3$02d</string> <!-- Unit of measure in the Details dialog frames per second. e.g. 20 fps --> <string name="details_fps">%1$d fps</string> <!-- Unit of measure in the Details dialog K bits per second. e.g. 192 Kbps --> <string name="details_kbps">%1$d Kbps</string> <!-- Unit of measure in the Details dialog M bits per second. e.g. 2.3 Mbps --> <string name="details_mbps">%1$g Mbps</string> <!-- Details dialog "OK" button. Dismisses dialog. --> <string name="details_ok">OK</string> <!-- Text of context menu when an image is selected --> <string name="context_menu_header">Picture options</string> <!-- Text of context menu when a video is selected --> <string name="video_context_menu_header">Video options</string> <!-- Hint that appears when cropping an image with more than one face --> <string name="multiface_crop_help">Tap a face to begin.</string> <!-- Activity title when in the image gallery to see pictures --> <string name="photos_gallery_title">Gallery</string> <!-- Activity title when in the image gallery to select a picture --> <string name="pick_photos_gallery_title">Select picture</string> <!-- Activity title when in the image gallery to see videos --> <string name="videos_gallery_title">Gallery</string> <!-- Activity title when in the image gallery to select a video --> <string name="pick_videos_gallery_title">Select video</string> <!-- onscreen text indicating the progress of generating thumbnails. Basically some number followed by the word "remaining" --> <string name="loading_progress_format_string"><xliff:g id="counter">%d</xliff:g> remaining</string> <!-- Displayed in the title of the dialog for things to do with a picture that is to be sent to another application: --> <string name="sendImage">Share picture via</string> <!-- Displayed in the title of the dialog for things to do with a picture that is to be "set as" (e.g. set as contact photo or set as wallpaper) --> <string name="setImage">Set picture as</string> <!-- Displayed in the title of the dialog for things to do with a video that is to be sent to another application. --> <string name="sendVideo">Share video via</string> <!-- Activity label. This might show up in the activity-picker --> <string name="movieviewlabel">Movies</string> <!-- shown in the video player view while the video is being loaded, before it starts playing --> <string name="loading_video">Loading video\u2026</string> <!-- Low-memory dialog title --> <string name="spaceIsLow_title">Space is low</string> <!-- Low-memory dialog message --> <string name="spaceIsLow_content">Your SD card is running out of space. Change the quality setting or delete items from Gallery.</string> <!-- Movie View Resume Playing dialog title --> <string name="resume_playing_title">Resume video</string> <!-- Movie View Start Playing dialog title --> <string name="resume_playing_message">Resume playing from %s ?</string> <!-- Movie View Start Playing button "Resume from bookmark" --> <string name="resume_playing_resume">Resume playing</string> <!-- Movie View Start Playing button "Beginning" --> <string name="resume_playing_restart">Start over</string> <!-- Title for picture frame gadget to show in list of all available gadgets --> <string name="gadget_title">Picture frame</string> <!-- Video Camera format string for new video files. Passed to java.text.SimpleDateFormat. Do not localize --> <string name="video_file_name_format" translatable="false">"'video'-yyyy-MM-dd-HH-mm-ss"</string> <!-- Title for the file information dialog --> <string name="file_info_title">File info:</string> <!-- The video is execeed the size limit of a MMS, and suggest user to record a shorter length clip --> <string name="video_exceed_mms_limit">The video you recorded is too large to send via MMS. Try recording a shorter length clip.</string> <!-- Displayed as a toast when a video file is too large to attach to a Gmail message. --> <string name="too_large_to_attach">File too large to attach.</string> </resources>
brunsky/WS171-packages-apps-Camera
ac23cbaf6a83a142008087b3f1a9062c489d6637
Automated import from //branches/cupcake/...@142832,142832
diff --git a/src/com/android/camera/ViewImage.java b/src/com/android/camera/ViewImage.java index c7de24e..5004774 100644 --- a/src/com/android/camera/ViewImage.java +++ b/src/com/android/camera/ViewImage.java @@ -1,1579 +1,1546 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.util.Random; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.util.AttributeSet; import android.util.Config; import android.util.Log; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import android.widget.Scroller; import android.widget.Toast; import android.widget.ZoomButtonsController; import com.android.camera.ImageManager.IImage; public class ViewImage extends Activity implements View.OnClickListener { private static final String TAG = "ViewImage"; private static final int TOUCH_AREA_WIDTH = 60; private ImageGetter mGetter; private Uri mSavedUri; static final boolean sSlideShowHidesStatusBar = true; // Choices for what adjacents to load. static private final int[] sOrder_adjacents = new int[] { 0, 1, -1 }; static private final int[] sOrder_slideshow = new int[] { 0 }; private LocalHandler mHandler = new LocalHandler(); private Random mRandom = new Random(System.currentTimeMillis()); private int [] mShuffleOrder; private boolean mUseShuffleOrder = false; private boolean mSlideShowLoop = false; private static final int MODE_NORMAL = 1; private static final int MODE_SLIDESHOW = 2; private int mMode = MODE_NORMAL; private boolean mFullScreenInNormalMode; private boolean mShowActionIcons; private View mActionIconPanel; private View mShutterButton; private boolean mSortAscending = false; private int mSlideShowInterval; private int mLastSlideShowImage; private boolean mFirst = true; private int mCurrentPosition = 0; private boolean mLayoutComplete = false; // represents which style animation to use private int mAnimationIndex; private Animation [] mSlideShowInAnimation; private Animation [] mSlideShowOutAnimation; private SharedPreferences mPrefs; private View mNextImageView, mPrevImageView; private Animation mHideNextImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mHidePrevImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mShowNextImageViewAnimation = new AlphaAnimation(0F, 1F); private Animation mShowPrevImageViewAnimation = new AlphaAnimation(0F, 1F); static final int sPadding = 20; static final int sHysteresis = sPadding * 2; static final int sBaseScrollDuration = 1000; // ms private ImageManager.IImageList mAllImages; private int mSlideShowImageCurrent = 0; private ImageViewTouch [] mSlideShowImageViews = new ImageViewTouch[2]; private GestureDetector mGestureDetector; private ZoomButtonsController mZoomButtonsController; // Array of image views. The center view is the one the user is focused // on. The one at the zeroth position and the second position reflect // the images to the left/right of the center image. private ImageViewTouch[] mImageViews = new ImageViewTouch[3]; // Container for the three image views. This guy can be "scrolled" // to reveal the image prior to and after the center image. private ScrollHandler mScroller; private MenuHelper.MenuItemsResult mImageMenuRunnable; private Runnable mDismissOnScreenControlsRunnable; private boolean mCameraReviewMode; - private int mCurrentOrientation; - private void updateNextPrevControls() { boolean showPrev = mCurrentPosition > 0; boolean showNext = mCurrentPosition < mAllImages.getCount() - 1; boolean prevIsVisible = mPrevImageView.getVisibility() == View.VISIBLE; boolean nextIsVisible = mNextImageView.getVisibility() == View.VISIBLE; if (showPrev && !prevIsVisible) { Animation a = mShowPrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.VISIBLE); } else if (!showPrev && prevIsVisible) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.GONE); } if (showNext && !nextIsVisible) { Animation a = mShowNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.VISIBLE); } else if (!showNext && nextIsVisible) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.GONE); } } private void showOnScreenControls() { updateNextPrevControls(); updateZoomButtonsEnabled(); mZoomButtonsController.setVisible(true); scheduleDismissOnScreenControls(); } @Override public boolean dispatchTouchEvent(MotionEvent m) { boolean sup = super.dispatchTouchEvent(m); if (sup == false) { if (mMode == MODE_SLIDESHOW) { mSlideShowImageViews[mSlideShowImageCurrent].handleTouchEvent(m); } else if (mMode == MODE_NORMAL){ mImageViews[1].handleTouchEvent(m); } return true; } return true; } private void scheduleDismissOnScreenControls() { mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); mHandler.postDelayed(mDismissOnScreenControlsRunnable, 1500); } private void updateZoomButtonsEnabled() { ImageViewTouch imageView = mImageViews[1]; float scale = imageView.getScale(); mZoomButtonsController.setZoomInEnabled(scale < imageView.mMaxZoom); mZoomButtonsController.setZoomOutEnabled(scale > 1); } @Override protected void onDestroy() { // This is necessary to make the ZoomButtonsController unregister // its configuration change receiver. if (mZoomButtonsController != null) { mZoomButtonsController.setVisible(false); } super.onDestroy(); } private void setupZoomButtonController(View rootView) { mGestureDetector = new GestureDetector(this, new MyGestureListener()); mZoomButtonsController = new ZoomButtonsController(rootView); mZoomButtonsController.setAutoDismissed(false); mZoomButtonsController.setOnZoomListener( new ZoomButtonsController.OnZoomListener() { public void onVisibilityChanged(boolean visible) { if (visible) { updateZoomButtonsEnabled(); } } public void onZoom(boolean zoomIn) { if (zoomIn) { mImageViews[1].zoomIn(); } else { mImageViews[1].zoomOut(); } showOnScreenControls(); } - }); } private class MyGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { ImageViewTouch imageView = mImageViews[1]; if (imageView.getScale() > 1F) { imageView.postTranslate(-distanceX, -distanceY, sUseBounce); imageView.center(true, true, false); } showOnScreenControls(); return true; } @Override public boolean onSingleTapUp(MotionEvent e) { - int viewWidth = mImageViews[1].getWidth(); int x = (int) e.getX(); int y = (int) e.getY(); if (x < TOUCH_AREA_WIDTH) { moveNextOrPrevious(-1); } else if (x > viewWidth - TOUCH_AREA_WIDTH) { moveNextOrPrevious(1); } setMode(MODE_NORMAL); showOnScreenControls(); return true; } } private void setupDismissOnScreenControlRunnable() { mDismissOnScreenControlsRunnable = new Runnable() { public void run() { if (!mShowActionIcons) { if (mNextImageView.getVisibility() == View.VISIBLE) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.INVISIBLE); } if (mPrevImageView.getVisibility() == View.VISIBLE) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.INVISIBLE); } mZoomButtonsController.setVisible(false); } } }; } private boolean isPickIntent() { String action = getIntent().getAction(); return (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)); } private static final boolean sUseBounce = false; private static final boolean sAnimateTransitions = false; public static class ImageViewTouch extends ImageViewTouchBase { private ViewImage mViewImage; private boolean mEnableTrackballScroll; public ImageViewTouch(Context context) { super(context); mViewImage = (ViewImage) context; } public ImageViewTouch(Context context, AttributeSet attrs) { super(context, attrs); mViewImage = (ViewImage) context; } public void setEnableTrackballScroll(boolean enable) { mEnableTrackballScroll = enable; } protected void postTranslate(float dx, float dy, boolean bounceOK) { super.postTranslate(dx, dy); if (dx != 0F || dy != 0F) { mViewImage.showOnScreenControls(); } if (!sUseBounce) { center(true, false, false); } } protected ScrollHandler scrollHandler() { return mViewImage.mScroller; } public boolean handleTouchEvent(MotionEvent m) { return mViewImage.mGestureDetector.onTouchEvent(m); } @Override - public boolean onKeyDown(int keyCode, KeyEvent event) - { + public boolean onKeyDown(int keyCode, KeyEvent event) { // Don't respond to arrow keys if trackball scrolling is not enabled if (!mEnableTrackballScroll) { if ((keyCode >= KeyEvent.KEYCODE_DPAD_UP) && (keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT)) { return super.onKeyDown(keyCode, event); } } int current = mViewImage.mCurrentPosition; int nextImagePos = -2; // default no next image try { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: { if (mViewImage.isPickIntent()) { ImageManager.IImage img = mViewImage.mAllImages.getImageAt(mViewImage.mCurrentPosition); mViewImage.setResult(RESULT_OK, new Intent().setData(img.fullSizeImageUri())); mViewImage.finish(); } break; } case KeyEvent.KEYCODE_DPAD_LEFT: { panBy(sPanRate, 0); int maxOffset = (current == 0) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(true, maxOffset)) { nextImagePos = current - 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_RIGHT: { panBy(-sPanRate, 0); int maxOffset = (current == mViewImage.mAllImages.getCount() - 1) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(false, maxOffset)) { nextImagePos = current + 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_UP: { panBy(0, sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DPAD_DOWN: { panBy(0, -sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DEL: MenuHelper.deletePhoto( mViewImage, mViewImage.mDeletePhotoRunnable); break; } } finally { if (nextImagePos >= 0 && nextImagePos < mViewImage.mAllImages.getCount()) { synchronized (mViewImage) { mViewImage.setMode(MODE_NORMAL); mViewImage.setImage(nextImagePos); } } else if (nextImagePos != -2) { center(true, true, false); } } return super.onKeyDown(keyCode, event); } protected boolean isShiftedToNextImage(boolean left, int maxOffset) { boolean retval; Bitmap bitmap = mBitmapDisplayed; Matrix m = getImageViewMatrix(); if (left) { float [] t1 = new float[] { 0, 0 }; m.mapPoints(t1); retval = t1[0] > maxOffset; } else { int width = bitmap != null ? bitmap.getWidth() : getWidth(); float [] t1 = new float[] { width, 0 }; m.mapPoints(t1); retval = t1[0] + maxOffset < getWidth(); } return retval; } protected void scrollX(int deltaX) { scrollHandler().scrollBy(deltaX, 0); } protected int getScrollOffset() { return scrollHandler().getScrollX(); } } static class ScrollHandler extends LinearLayout { private Runnable mFirstLayoutCompletedCallback = null; private Scroller mScrollerHelper; + private ViewImage mViewImage; private int mWidth = -1; public ScrollHandler(Context context) { super(context); mScrollerHelper = new Scroller(context); + mViewImage = (ViewImage) context; } public ScrollHandler(Context context, AttributeSet attrs) { super(context, attrs); mScrollerHelper = new Scroller(context); - } - - public void setLayoutCompletedCallback(Runnable r) { - mFirstLayoutCompletedCallback = r; + mViewImage = (ViewImage) context; } public void startScrollTo(int newX, int newY) { int oldX = getScrollX(); int oldY = getScrollY(); int deltaX = newX - oldX; int deltaY = newY - oldY; if (mWidth == -1) { mWidth = findViewById(R.id.image2).getWidth(); } int viewWidth = mWidth; int duration = viewWidth > 0 ? sBaseScrollDuration * Math.abs(deltaX) / viewWidth : 0; mScrollerHelper.startScroll(oldX, oldY, deltaX, deltaY, duration); invalidate(); } @Override public void computeScroll() { if (mScrollerHelper.computeScrollOffset()) { scrollTo(mScrollerHelper.getCurrX(), mScrollerHelper.getCurrY()); postInvalidate(); // So we draw again } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int width = right - left; int x = 0; for (View v : new View[] { findViewById(R.id.image1), findViewById(R.id.image2), findViewById(R.id.image3) }) { v.layout(x, 0, x + width, bottom); x += (width + sPadding); } findViewById(R.id.padding1).layout(width, 0, width + sPadding, bottom); - findViewById(R.id.padding2).layout(width+sPadding+width, 0, width+sPadding+width+sPadding, bottom); + findViewById(R.id.padding2).layout(width + sPadding + width, + 0, width + sPadding + width + sPadding, bottom); if (changed) { - if (mFirstLayoutCompletedCallback != null) { - mFirstLayoutCompletedCallback.run(); - } + mViewImage.mLayoutComplete = true; + mViewImage.onLayoutChanged(); } } } private void animateScrollTo(int xNew, int yNew) { mScroller.startScrollTo(xNew, yNew); } @Override - public boolean onCreateOptionsMenu(Menu menu) - { + public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (! mCameraReviewMode) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.slide_show); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { setMode(MODE_SLIDESHOW); mLastSlideShowImage = mCurrentPosition; loadNextImage(mCurrentPosition, 0, true); return true; } }); item.setIcon(android.R.drawable.ic_menu_slideshow); } final SelectedImageGetter selectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return mAllImages.getImageAt(mCurrentPosition); } public Uri getCurrentImageUri() { return mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); } }; mImageMenuRunnable = MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL, true, ViewImage.this, mHandler, mDeletePhotoRunnable, new MenuHelper.MenuInvoker() { public void run(MenuHelper.MenuCallback cb) { setMode(MODE_NORMAL); cb.run(selectedImageGetter.getCurrentImageUri(), selectedImageGetter.getCurrentImage()); for (ImageViewTouchBase iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } setImage(mCurrentPosition); } }); if (true) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 1000, R.string.camerasettings); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent preferences = new Intent(); preferences.setClass(ViewImage.this, GallerySettings.class); startActivity(preferences); return true; } }); item.setAlphabeticShortcut('p'); item.setIcon(android.R.drawable.ic_menu_preferences); } // Hidden menu just so the shortcut will bring up the zoom controls menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.camerasettings) // the string resource is a placeholder .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { showOnScreenControls(); return true; } }) .setAlphabeticShortcut('z') .setVisible(false); return true; } protected Runnable mDeletePhotoRunnable = new Runnable() { public void run() { mAllImages.removeImageAt(mCurrentPosition); if (mAllImages.getCount() == 0) { finish(); } else { if (mCurrentPosition == mAllImages.getCount()) { mCurrentPosition -= 1; } } for (ImageViewTouchBase iv: mImageViews) { iv.setImageBitmapResetBase(null, true, true); } setImage(mCurrentPosition); } }; @Override - public boolean onPrepareOptionsMenu(Menu menu) - { + public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); setMode(MODE_NORMAL); if (mImageMenuRunnable != null) { mImageMenuRunnable.gettingReadyToOpen(menu, mAllImages.getImageAt(mCurrentPosition)); } return true; } - @Override - public void onConfigurationChanged(android.content.res.Configuration newConfig) { - super.onConfigurationChanged(newConfig); - boolean changed = mCurrentOrientation != newConfig.orientation; - mCurrentOrientation = newConfig.orientation; - if (changed) { - if (mGetter != null) { - // kill off any background image fetching - mGetter.cancelCurrent(); - mGetter.stop(); - } - makeGetter(); - mFirst = true; - - // clear off the current set of images since we need to reload - // them at the right size - for (ImageViewTouchBase iv: mImageViews) { - iv.clear(); - } - MenuHelper.requestOrientation(this, mPrefs); + private void onLayoutChanged() { + // if we get here after "onPause" then ignore the event + if (mGetter == null) return; + mDismissOnScreenControlsRunnable.run(); + mGetter.cancelCurrent(); + for (ImageViewTouch iv: mImageViews) { + iv.clear(); } + mFirst = true; + setImage(mCurrentPosition); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { boolean b = super.onMenuItemSelected(featureId, item); if (mImageMenuRunnable != null) mImageMenuRunnable.aboutToCall(item, mAllImages.getImageAt(mCurrentPosition)); return b; } /* * Here's the loading strategy. For any given image, load the thumbnail * into memory and post a callback to display the resulting bitmap. * * Then proceed to load the full image bitmap. Three things can * happen at this point: * * 1. the image fails to load because the UI thread decided * to move on to a different image. This "cancellation" happens * by virtue of the UI thread closing the stream containing the * image being decoded. BitmapFactory.decodeStream returns null * in this case. * * 2. the image loaded successfully. At that point we post * a callback to the UI thread to actually show the bitmap. * * 3. when the post runs it checks to see if the image that was * loaded is still the one we want. The UI may have moved on * to some other image and if so we just drop the newly loaded * bitmap on the floor. */ interface ImageGetterCallback { public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb); public boolean wantsThumbnail(int pos, int offset); public boolean wantsFullImage(int pos, int offset); public int fullImageSizeToUse(int pos, int offset); public void completed(boolean wasCanceled); public int [] loadOrder(); } class ImageGetter { // The thread which does the work. private Thread mGetterThread; // The base position that's being retrieved. The actual images retrieved // are this base plus each of the offets. private int mCurrentPosition = -1; // The callback to invoke for each image. private ImageGetterCallback mCB; // This is the loader cancelable that gets set while we're loading an image. // If we change position we can cancel the current load using this. private ImageManager.IGetBitmap_cancelable mLoad; // True if we're canceling the current load. private boolean mCancelCurrent = false; // True when the therad should exit. private boolean mDone = false; // True when the loader thread is waiting for work. private boolean mReady = false; private void cancelCurrent() { synchronized (this) { if (!mReady) { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { if (Config.LOGV) Log.v(TAG, "canceling load object"); load.cancel(); } mCancelCurrent = false; } } } public ImageGetter() { mGetterThread = new Thread(new Runnable() { private Runnable callback(final int position, final int offset, final boolean isThumb, final Bitmap bitmap) { return new Runnable() { public void run() { // check for inflight callbacks that aren't applicable any longer // before delivering them if (!isCanceled() && position == mCurrentPosition) { mCB.imageLoaded(position, offset, bitmap, isThumb); - } else { - if (bitmap != null) - bitmap.recycle(); + } else if (bitmap != null) { + bitmap.recycle(); } } }; } private Runnable completedCallback(final boolean wasCanceled) { return new Runnable() { public void run() { mCB.completed(wasCanceled); } }; } public void run() { int lastPosition = -1; while (!mDone) { synchronized (ImageGetter.this) { mReady = true; ImageGetter.this.notify(); if (mCurrentPosition == -1 || lastPosition == mCurrentPosition) { try { ImageGetter.this.wait(); } catch (InterruptedException ex) { continue; } } lastPosition = mCurrentPosition; mReady = false; } if (lastPosition != -1) { int imageCount = mAllImages.getCount(); int [] order = mCB.loadOrder(); for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (image == null || isCanceled()) { break; } if (mCB.wantsThumbnail(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting THUMBNAIL load at offset " + offset); Bitmap b = image.thumbBitmap(); mHandler.postGetterCallback(callback(lastPosition, offset, true, b)); } } } for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (mCB.wantsFullImage(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting FULL IMAGE load at offset " + offset); int sizeToUse = mCB.fullImageSizeToUse(lastPosition, offset); if (image != null && !isCanceled()) { mLoad = image.fullSizeBitmap_cancelable(sizeToUse); } if (mLoad != null) { long t1; if (Config.LOGV) t1 = System.currentTimeMillis(); // The return value could be null if the // bitmap is too big, or we cancelled it. Bitmap b = mLoad.get(); if (Config.LOGV && b != null) { long t2 = System.currentTimeMillis(); Log.v(TAG, "loading full image for " + image.fullSizeImageUri() + " with requested size " + sizeToUse + " took " + (t2 - t1) + " and returned a bitmap with size " + b.getWidth() + " / " + b.getHeight()); } mLoad = null; if (b != null) { if (isCanceled()) { b.recycle(); } else { mHandler.postGetterCallback(callback(lastPosition, offset, false, b)); } } } } } } mHandler.postGetterCallback(completedCallback(isCanceled())); } } } }); mGetterThread.setName("ImageGettter"); mGetterThread.start(); } private boolean isCanceled() { synchronized (this) { return mCancelCurrent; } } public void setPosition(int position, ImageGetterCallback cb) { synchronized (this) { if (!mReady) { try { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { load.cancel(); } // if the thread is waiting before loading the full size // image then this will free it up ImageGetter.this.notify(); ImageGetter.this.wait(); mCancelCurrent = false; } catch (InterruptedException ex) { // not sure what to do here } } } mCurrentPosition = position; mCB = cb; synchronized (this) { ImageGetter.this.notify(); } } public void stop() { synchronized (this) { mDone = true; ImageGetter.this.notify(); } try { mGetterThread.join(); } catch (InterruptedException ex) { } } } private void setImage(int pos) { - if (!mLayoutComplete) { - return; - } + if (!mLayoutComplete) return; final boolean left = (pos == mCurrentPosition - 1); final boolean right = (pos == mCurrentPosition + 1); mCurrentPosition = pos; ImageViewTouchBase current = mImageViews[1]; current.mSuppMatrix.reset(); current.setImageMatrix(current.getImageViewMatrix()); if (false) { Log.v(TAG, "before..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } if (!mFirst) { if (left) { mImageViews[2].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[0]); } else if (right) { mImageViews[0].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[2]); } } if (false) { Log.v(TAG, "after copy..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } for (ImageViewTouchBase ivt: mImageViews) { ivt.mIsZooming = false; } int width = mImageViews[1].getWidth(); int from; int to = width + sPadding; if (mFirst) { from = to; mFirst = false; } else { from = left ? (width + sPadding) + mScroller.getScrollX() : mScroller.getScrollX() - (width + sPadding); } if (sAnimateTransitions) { mScroller.scrollTo(from, 0); animateScrollTo(to, 0); } else { mScroller.scrollTo(to, 0); } ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { if (!mShowActionIcons) { mImageViews[1].setFocusableInTouchMode(true); mImageViews[1].requestFocus(); } } public boolean wantsThumbnail(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; return ivt.mThumbBitmap == null; } public boolean wantsFullImage(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; if (ivt.mBitmapDisplayed != null && !ivt.mBitmapIsThumbnail) { return false; } if (offset != 0) { return false; } return true; } public int fullImageSizeToUse(int pos, int offset) { // TODO // this number should be bigger so that we can zoom. we may need to // get fancier and read in the fuller size image as the user starts // to zoom. use -1 to get the full full size image. // for now use 480 so we don't run out of memory final int imageViewSize = 480; return imageViewSize; } public int [] loadOrder() { return sOrder_adjacents; } public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb) { // shouldn't get here after onPause() ImageViewTouchBase ivt = mImageViews[1 + offset]; if (offset == 0) updateZoomButtonsEnabled(); ivt.setImageBitmapResetBase(bitmap, isThumb, isThumb); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { mGetter.setPosition(pos, cb); } + showOnScreenControls(); } @Override - public void onCreate(Bundle instanceState) - { + public void onCreate(Bundle instanceState) { super.onCreate(instanceState); Intent intent = getIntent(); mCameraReviewMode = intent.getBooleanExtra("com.android.camera.ReviewMode", false); mFullScreenInNormalMode = intent.getBooleanExtra(MediaStore.EXTRA_FULL_SCREEN, true); mShowActionIcons = intent.getBooleanExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, false); + setRequestedOrientation(); + mPrefs = PreferenceManager.getDefaultSharedPreferences(this); - mCurrentOrientation = getResources().getConfiguration().orientation; setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.viewimage); mImageViews[0] = (ImageViewTouch) findViewById(R.id.image1); mImageViews[1] = (ImageViewTouch) findViewById(R.id.image2); mImageViews[2] = (ImageViewTouch) findViewById(R.id.image3); for(ImageViewTouch v : mImageViews) { v.setEnableTrackballScroll(!mShowActionIcons); } mScroller = (ScrollHandler)findViewById(R.id.scroller); makeGetter(); mAnimationIndex = -1; mSlideShowInAnimation = new Animation[] { makeInAnimation(R.anim.transition_in), makeInAnimation(R.anim.slide_in), makeInAnimation(R.anim.slide_in_vertical), }; mSlideShowOutAnimation = new Animation[] { makeOutAnimation(R.anim.transition_out), makeOutAnimation(R.anim.slide_out), makeOutAnimation(R.anim.slide_out_vertical), }; mSlideShowImageViews[0] = (ImageViewTouch) findViewById(R.id.image1_slideShow); mSlideShowImageViews[1] = (ImageViewTouch) findViewById(R.id.image2_slideShow); for (ImageViewTouch v : mSlideShowImageViews) { v.setImageBitmapResetBase(null, true, true); v.setVisibility(View.INVISIBLE); v.setEnableTrackballScroll(!mShowActionIcons); } mActionIconPanel = findViewById(R.id.action_icon_panel); { int[] pickIds = {R.id.attach, R.id.cancel}; int[] normalIds = {R.id.gallery, R.id.setas, R.id.share, R.id.discard}; int[] hideIds = pickIds; int[] connectIds = normalIds; if (isPickIntent()) { hideIds = normalIds; connectIds = pickIds; } for(int id : hideIds) { mActionIconPanel.findViewById(id).setVisibility(View.GONE); } for(int id : connectIds) { View view = mActionIconPanel.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } mShutterButton = findViewById(R.id.shutter_button); mShutterButton.setOnClickListener(this); Uri uri = getIntent().getData(); if (Config.LOGV) Log.v(TAG, "uri is " + uri); if (instanceState != null) { if (instanceState.containsKey("uri")) { uri = Uri.parse(instanceState.getString("uri")); } } if (uri == null) { finish(); return; } init(uri); Bundle b = getIntent().getExtras(); boolean slideShow = b != null ? b.getBoolean("slideshow", false) : false; if (slideShow) { setMode(MODE_SLIDESHOW); loadNextImage(mCurrentPosition, 0, true); } else { if (mFullScreenInNormalMode) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } } setupZoomButtonController(findViewById(R.id.rootLayout)); setupDismissOnScreenControlRunnable(); mNextImageView = findViewById(R.id.next_image); mPrevImageView = findViewById(R.id.prev_image); mNextImageView.setOnClickListener(this); mPrevImageView.setOnClickListener(this); if (mShowActionIcons) { mNextImageView.setFocusable(true); mPrevImageView.setFocusable(true); } - - setOrientation(); } - private void setOrientation() { + private void setRequestedOrientation() { Intent intent = getIntent(); if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); if (orientation != getRequestedOrientation()) { setRequestedOrientation(orientation); } } else { MenuHelper.requestOrientation(this, mPrefs); } } private Animation makeInAnimation(int id) { Animation inAnimation = AnimationUtils.loadAnimation(this, id); return inAnimation; } private Animation makeOutAnimation(int id) { Animation outAnimation = AnimationUtils.loadAnimation(this, id); return outAnimation; } private void setMode(int mode) { if (mMode == mode) { return; } findViewById(R.id.slideShowContainer).setVisibility(mode == MODE_SLIDESHOW ? View.VISIBLE : View.GONE); findViewById(R.id.abs) .setVisibility(mode == MODE_NORMAL ? View.VISIBLE : View.GONE); Window win = getWindow(); mMode = mode; if (mode == MODE_SLIDESHOW) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (sSlideShowHidesStatusBar) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } for (ImageViewTouchBase ivt: mImageViews) { ivt.clear(); } mActionIconPanel.setVisibility(View.GONE); mShutterButton.setVisibility(View.GONE); if (false) { Log.v(TAG, "current is " + this.mSlideShowImageCurrent); this.mSlideShowImageViews[0].dump(); this.mSlideShowImageViews[0].dump(); } findViewById(R.id.slideShowContainer).getRootView().requestLayout(); mUseShuffleOrder = mPrefs.getBoolean("pref_gallery_slideshow_shuffle_key", false); mSlideShowLoop = mPrefs.getBoolean("pref_gallery_slideshow_repeat_key", false); try { mAnimationIndex = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_transition_key", "0")); } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mAnimationIndex = 0; } try { mSlideShowInterval = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_interval_key", "3")) * 1000; } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mSlideShowInterval = 3000; } if (Config.LOGV) { Log.v(TAG, "read prefs... shuffle: " + mUseShuffleOrder); Log.v(TAG, "read prefs... loop: " + mSlideShowLoop); Log.v(TAG, "read prefs... animidx: " + mAnimationIndex); Log.v(TAG, "read prefs... interval: " + mSlideShowInterval); } if (mUseShuffleOrder) { generateShuffleOrder(); } } else { if (Config.LOGV) Log.v(TAG, "slide show mode off, mCurrentPosition == " + mCurrentPosition); win.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (mFullScreenInNormalMode) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mGetter != null) mGetter.cancelCurrent(); if (sSlideShowHidesStatusBar) { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } ImageViewTouchBase dst = mImageViews[1]; dst.mLastXTouchPos = -1; dst.mLastYTouchPos = -1; for (ImageViewTouchBase ivt: mSlideShowImageViews) { ivt.clear(); } mShuffleOrder = null; // mGetter null is a proxy for being paused if (mGetter != null) { mFirst = true; // don't animate setImage(mCurrentPosition); } } // this line shouldn't be necessary but the view hierarchy doesn't // seem to realize that the window layout changed mScroller.requestLayout(); } private void generateShuffleOrder() { if (mShuffleOrder == null || mShuffleOrder.length != mAllImages.getCount()) { mShuffleOrder = new int[mAllImages.getCount()]; } for (int i = 0; i < mShuffleOrder.length; i++) { mShuffleOrder[i] = i; } for (int i = mShuffleOrder.length - 1; i > 0; i--) { int r = mRandom.nextInt(i); int tmp = mShuffleOrder[r]; mShuffleOrder[r] = mShuffleOrder[i]; mShuffleOrder[i] = tmp; } } private void loadNextImage(final int requestedPos, final long delay, final boolean firstCall) { if (firstCall && mUseShuffleOrder) { generateShuffleOrder(); } final long targetDisplayTime = System.currentTimeMillis() + delay; ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { } public boolean wantsThumbnail(int pos, int offset) { return true; } public boolean wantsFullImage(int pos, int offset) { return false; } public int [] loadOrder() { return sOrder_slideshow; } public int fullImageSizeToUse(int pos, int offset) { return 480; // TODO compute this } public void imageLoaded(final int pos, final int offset, final Bitmap bitmap, final boolean isThumb) { long timeRemaining = Math.max(0, targetDisplayTime - System.currentTimeMillis()); mHandler.postDelayedGetterCallback(new Runnable() { public void run() { if (mMode == MODE_NORMAL) return; ImageViewTouchBase oldView = mSlideShowImageViews[mSlideShowImageCurrent]; if (++mSlideShowImageCurrent == mSlideShowImageViews.length) { mSlideShowImageCurrent = 0; } ImageViewTouchBase newView = mSlideShowImageViews[mSlideShowImageCurrent]; newView.setVisibility(View.VISIBLE); newView.setImageBitmapResetBase(bitmap, isThumb, isThumb); newView.bringToFront(); int animation = 0; if (mAnimationIndex == -1) { int n = mRandom.nextInt(mSlideShowInAnimation.length); animation = n; } else { animation = mAnimationIndex; } Animation aIn = mSlideShowInAnimation[animation]; newView.setAnimation(aIn); newView.setVisibility(View.VISIBLE); aIn.startNow(); Animation aOut = mSlideShowOutAnimation[animation]; oldView.setVisibility(View.INVISIBLE); oldView.setAnimation(aOut); aOut.startNow(); mCurrentPosition = requestedPos; if (mCurrentPosition == mLastSlideShowImage && !firstCall) { if (mSlideShowLoop) { if (mUseShuffleOrder) { generateShuffleOrder(); } } else { setMode(MODE_NORMAL); return; } } if (Config.LOGV) Log.v(TAG, "mCurrentPosition is now " + mCurrentPosition); loadNextImage((mCurrentPosition + 1) % mAllImages.getCount(), mSlideShowInterval, false); } }, timeRemaining); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { int pos = requestedPos; if (mShuffleOrder != null) { pos = mShuffleOrder[pos]; } mGetter.setPosition(pos, cb); } } private void makeGetter() { mGetter = new ImageGetter(); } private boolean desiredSortOrder() { String sortOrder = mPrefs.getString("pref_gallery_sort_key", null); boolean sortAscending = false; if (sortOrder != null) { sortAscending = sortOrder.equals("ascending"); } if (mCameraReviewMode) { // Force left-arrow older pictures, right-arrow newer pictures. sortAscending = true; } return sortAscending; } private void init(Uri uri) { if (uri == null) return; - + mSortAscending = desiredSortOrder(); int sort = mSortAscending ? ImageManager.SORT_ASCENDING : ImageManager.SORT_DESCENDING; mAllImages = ImageManager.makeImageList(uri, this, sort); uri = uri.buildUpon().query(null).build(); // TODO smarter/faster here please for (int i = 0; i < mAllImages.getCount(); i++) { ImageManager.IImage image = mAllImages.getImageAt(i); if (image.fullSizeImageUri().equals(uri)) { mCurrentPosition = i; mLastSlideShowImage = mCurrentPosition; break; } } } private Uri getCurrentUri() { ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); Uri uri = null; if (image != null){ String bucket = null; uri = image.fullSizeImageUri(); if(getIntent() != null && getIntent().getData() != null) bucket = getIntent().getData().getQueryParameter("bucketId"); if(bucket != null) uri = uri.buildUpon().appendQueryParameter("bucketId", bucket).build(); } return uri; } - + @Override public void onSaveInstanceState(Bundle b) { super.onSaveInstanceState(b); - + Uri uri = getCurrentUri(); if (uri != null) { b.putString("uri", uri.toString()); } - + if (mMode == MODE_SLIDESHOW) { b.putBoolean("slideshow", true); } } - + @Override - public void onResume() - { + public void onResume() { super.onResume(); - + init(mSavedUri); // normally this will never be zero but if one "backs" into this // activity after removing the sdcard it could be zero. in that // case just "finish" since there's nothing useful that can happen. int count = mAllImages.getCount(); if (count == 0) { finish(); } else if (count <= mCurrentPosition) { mCurrentPosition = count - 1; } ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); if (mGetter == null) { makeGetter(); } mFirst = true; - mScroller.setLayoutCompletedCallback(new Runnable() { - public void run() { - mLayoutComplete = true; - setImage(mCurrentPosition); - } - }); setImage(mCurrentPosition); - - setOrientation(); } @Override - public void onPause() - { + public void onPause() { super.onPause(); mGetter.cancelCurrent(); mGetter.stop(); mGetter = null; setMode(MODE_NORMAL); // removing all callback in the message queue mHandler.removeAllGetterCallbacks(); - + mSavedUri = getCurrentUri(); mAllImages.deactivate(); mDismissOnScreenControlsRunnable.run(); if (mDismissOnScreenControlsRunnable != null) mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); for (ImageViewTouch iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } for (ImageViewTouch iv: mSlideShowImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } } public void onClick(View v) { switch (v.getId()) { case R.id.shutter_button: { if (mCameraReviewMode) { finish(); } else { MenuHelper.gotoStillImageCapture(this); } } break; case R.id.gallery: { MenuHelper.gotoCameraImageGallery(this); } break; case R.id.discard: { MenuHelper.deletePhoto(this, mDeletePhotoRunnable); } break; case R.id.share: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); if (MenuHelper.isMMSUri(u)) return; Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_STREAM, u); try { startActivity(Intent.createChooser(intent, getText(R.string.sendImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_image, Toast.LENGTH_SHORT).show(); } } break; case R.id.setas: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA, u); try { startActivity(Intent.createChooser(intent, getText(R.string.setImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } break; case R.id.next_image: { moveNextOrPrevious(1); } break; case R.id.prev_image: { moveNextOrPrevious(-1); } break; } } private void moveNextOrPrevious(int delta) { int nextImagePos = mCurrentPosition + delta; if ((0 <= nextImagePos) && (nextImagePos < mAllImages.getCount())) { setImage(nextImagePos); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case MenuHelper.RESULT_COMMON_MENU_CROP: if (resultCode == RESULT_OK) { // The CropImage activity passes back the Uri of the cropped image as // the Action rather than the Data. mSavedUri = Uri.parse(data.getAction()); } break; } } static class LocalHandler extends Handler { private static final int IMAGE_GETTER_CALLBACK = 1; @Override public void handleMessage(Message message) { switch(message.what) { case IMAGE_GETTER_CALLBACK: ((Runnable) message.obj).run(); } } public void postGetterCallback(Runnable callback) { postDelayedGetterCallback(callback, 0); } public void postDelayedGetterCallback(Runnable callback, long delay) { if (callback == null) throw new NullPointerException(); Message message = Message.obtain(); message.what = IMAGE_GETTER_CALLBACK; message.obj = callback; sendMessageDelayed(message, delay); } public void removeAllGetterCallbacks() { removeMessages(IMAGE_GETTER_CALLBACK); } } }
brunsky/WS171-packages-apps-Camera
f66aea7883f0a46c03180873c62ae2ec238d269e
Automated import from //branches/cupcake/...@142649,142649
diff --git a/res/drawable-land/photo_frame.9.png b/res/drawable-land/photo_frame.9.png new file mode 100644 index 0000000..7d479b5 Binary files /dev/null and b/res/drawable-land/photo_frame.9.png differ diff --git a/res/drawable/photo_frame.9.png b/res/drawable/photo_frame.9.png index b153260..9dbf362 100644 Binary files a/res/drawable/photo_frame.9.png and b/res/drawable/photo_frame.9.png differ diff --git a/res/drawable/photo_inner.9.png b/res/drawable/photo_inner.9.png new file mode 100644 index 0000000..0e77c7b Binary files /dev/null and b/res/drawable/photo_inner.9.png differ diff --git a/res/layout/photo_frame.xml b/res/layout/photo_frame.xml index 5537b1e..00ab25d 100644 --- a/res/layout/photo_frame.xml +++ b/res/layout/photo_frame.xml @@ -1,24 +1,37 @@ <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> -<ImageView xmlns:android="http://schemas.android.com/apk/res/android" - android:id="@+id/photo" +<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" - android:scaleType="center" - android:cropToPadding="true" android:background="@drawable/photo_frame" - /> + > + + <ImageView + android:id="@+id/photo" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:scaleType="center" + android:cropToPadding="true" + /> + + <ImageView + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:background="@drawable/photo_inner" + /> + +</FrameLayout> \ No newline at end of file
brunsky/WS171-packages-apps-Camera
498e12ddf70669047756553d45d2bbf612eb18d6
Automated import from //branches/cupcake/...@142643,142643
diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml index bd306eb..03acbf0 100644 --- a/res/values-ja/strings.xml +++ b/res/values-ja/strings.xml @@ -1,158 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"すべての写真"</string> <string name="all_videos">"すべての動画"</string> <string name="camera_label">"カメラ"</string> <string name="gallery_picker_label">"ギャラリー"</string> <string name="gallery_camera_bucket_name">"カメラ (写真)"</string> <string name="gallery_camera_videos_bucket_name">"カメラ (動画)"</string> <string name="switch_to_video_lable">"ムービーに切替"</string> <string name="switch_to_camera_lable">"写真に切替"</string> <string name="crop_label">"トリミング"</string> <string name="view_label">"画像を表示"</string> <string name="preferences_label">"カメラ設定"</string> <string name="wait">"お待ちください..."</string> <string name="no_storage">"カメラを使用する前にSDカードを挿入してください。"</string> <string name="not_enough_space">"SDカードがいっぱいです。"</string> <string name="preparing_sd">"SDカードの準備中..."</string> <string name="wallpaper">"壁紙を設定しています。しばらくお待ちください..."</string> <string name="savingImage">"写真を保存中..."</string> <string name="runningFaceDetection">"お待ちください..."</string> <string name="flip_orientation">"画面の向きを変更"</string> <string name="settings">"設定"</string> <string name="view">"表示"</string> <string name="details">"詳細"</string> <string name="rotate">"回転"</string> <string name="rotate_left">"左に回転"</string> <string name="rotate_right">"右に回転"</string> <string name="slide_show">"スライドショー"</string> <string name="capture_picture">"写真撮影"</string> <string name="capture_video">"ムービー撮影"</string> <string name="crop_save_text">"保存"</string> <string name="crop_discard_text">"破棄"</string> <string name="confirm_delete_title">"削除"</string> <string name="confirm_delete_message">"画像を削除します。"</string> <string name="confirm_delete_video_message">"動画を削除します。"</string> <string name="camera_toss">"削除"</string> <string name="camera_gallery">"ギャラリー"</string> <string name="camera_share">"共有"</string> <string name="camera_set">"設定"</string> <string name="camera_play">"再生"</string> <string name="camera_attach">"添付"</string> <string name="camera_cancel">"キャンセル"</string> <string name="camera_crop">"トリミング"</string> <string name="camera_tossing">"削除中..."</string> <string name="no_way_to_share_image">"この画像は共有できません。"</string> <string name="no_way_to_share_video">"この動画は共有できません。"</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"ギャラリー"</string> <string name="camera_pick_wallpaper">"画像"</string> <string name="camera_setas_wallpaper">"壁紙"</string> <string name="pref_gallery_category">"全般設定"</string> <string name="pref_slideshow_category">"スライドショー設定"</string> <string name="pref_camera_general_settings_category">"全般設定"</string> <string name="pref_gallery_size_title">"表示サイズ"</string> <string name="pref_gallery_size_summary">"写真と動画の表示サイズを選択"</string> <string name="pref_gallery_size_dialogtitle">"画像サイズ"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"並び替え順"</string> <string name="pref_gallery_sort_summary">"画像と動画の表示順序を選択"</string> <string name="pref_gallery_sort_dialogtitle">"画像並べ替え"</string> <string-array name="pref_gallery_sort_choices"> <item>"日付の新しい順"</item> <item>"日付の古い順"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"スライドショーの間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"各スライドの表示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"スライドショーの間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2秒"</item> <item>"3秒"</item> <item>"4秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"スライドショーのトランジション"</string> <string name="pref_gallery_slideshow_transition_summary">"スライドが切り替わるときの効果を選択"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"スライドショーのトランジション"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"フェードイン&amp;アウト"</item> <item>"左右にスライド"</item> <item>"上下にスライド"</item> <item>"ランダムに選択"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"スライドショーを繰り返す"</string> <string name="pref_gallery_slideshow_repeat_summary">"スライドショーを繰り返す"</string> <string name="pref_gallery_slideshow_shuffle_title">"スライドのシャッフル"</string> <string name="pref_gallery_slideshow_shuffle_summary">"画像をランダムに表示する"</string> <string name="pref_camera_recordlocation_title">"位置情報を写真に記録する"</string> <string name="pref_camera_recordlocation_summary">"位置情報を写真データに記録する"</string> <string name="pref_camera_videoquality_category">"動画のクオリティ"</string> <string name="pref_camera_videoquality_title">"動画の画質を選択"</string> <string name="pref_camera_videoquality_entry_0">"低 (MMSメッセージ向け)"</string> <string name="pref_camera_videoquality_entry_1">"高 (SDカード向け)"</string> <string name="pref_camera_videoquality_dialogtitle">"動画のクオリティ"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"メディアが見つかりません。"</string> <string name="pref_gallery_confirm_delete_title">"削除確認"</string> <string name="pref_gallery_confirm_delete_summary">"画像や動画を削除する前に確認メッセージを表示"</string> <string name="details_panel_title">"詳細"</string> <string name="details_file_size">"ファイルサイズ:"</string> <string name="details_image_resolution">"解像度:"</string> <string name="details_duration">"再生時間:"</string> <string name="details_date_taken">"撮影日:"</string> <string name="details_frame_rate">"フレームレート:"</string> <string name="details_bit_rate">"ビットレート:"</string> <string name="details_codec">"コーデック:"</string> <string name="details_format">"形式:"</string> <string name="details_dimension_x">"%1$dx%2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$dfps"</string> <string name="details_kbps">"%1$dKbps"</string> <string name="details_mbps">"%1$gMbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"画像オプション"</string> <string name="video_context_menu_header">"動画オプション"</string> <string name="multiface_crop_help">"顔をタップして開始します。"</string> <string name="photos_gallery_title">"ギャラリー"</string> <string name="pick_photos_gallery_title">"画像を選択"</string> <string name="videos_gallery_title">"ギャラリー"</string> <string name="pick_videos_gallery_title">"動画を選択"</string> <string name="loading_progress_format_string">"残り<xliff:g id="COUNTER">%d</xliff:g>件"</string> <string name="sendImage">"画像を共有:"</string> <string name="setImage">"設定タイプ:"</string> <string name="sendVideo">"動画を共有"</string> <string name="movieviewlabel">"映画"</string> <string name="loading_video">"動画を読み込み中..."</string> <string name="spaceIsLow_title">"空き容量が残り少なくなっています"</string> <string name="spaceIsLow_content">"SDカードの容量が足りません。クオリティ設定を変更するか、ギャラリーからアイテムを削除してください。"</string> <string name="resume_playing_title">"動画の再開"</string> <string name="resume_playing_message">"再生を%sから再開しますか?"</string> <string name="resume_playing_resume">"再生を再開"</string> <string name="resume_playing_restart">"最初から再生"</string> <string name="gadget_title">"写真フレーム"</string> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="file_info_title">"ファイル情報:"</string> + <string name="video_exceed_mms_limit">"録画した動画のサイズが大きすぎるため送信できません。録画時間を短縮してみてください。"</string> + <string name="too_large_to_attach">"添付ファイルが大きすぎます。"</string> </resources>
brunsky/WS171-packages-apps-Camera
37455c97737b721b820f41658e864c815b4369cc
Automated import from //branches/cupcake/...@142524,142524
diff --git a/src/com/android/camera/MenuHelper.java b/src/com/android/camera/MenuHelper.java index 9fae480..17d3edb 100644 --- a/src/com/android/camera/MenuHelper.java +++ b/src/com/android/camera/MenuHelper.java @@ -1,733 +1,743 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.io.Closeable; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.StatFs; import android.provider.MediaStore; import android.provider.MediaStore.Images; import android.util.Config; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.MenuItem.OnMenuItemClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.camera.ImageManager.IImage; public class MenuHelper { static private final String TAG = "MenuHelper"; static public final int GENERIC_ITEM = 1; static public final int IMAGE_SAVING_ITEM = 2; static public final int VIDEO_SAVING_ITEM = 3; static public final int IMAGE_MODE_ITEM = 4; static public final int VIDEO_MODE_ITEM = 5; static public final int MENU_ITEM_MAX = 5; static public final int INCLUDE_ALL = 0xFFFFFFFF; static public final int INCLUDE_VIEWPLAY_MENU = (1 << 0); static public final int INCLUDE_SHARE_MENU = (1 << 1); static public final int INCLUDE_SET_MENU = (1 << 2); static public final int INCLUDE_CROP_MENU = (1 << 3); static public final int INCLUDE_DELETE_MENU = (1 << 4); static public final int INCLUDE_ROTATE_MENU = (1 << 5); static public final int INCLUDE_DETAILS_MENU = (1 << 6); static public final int MENU_SWITCH_CAMERA_MODE = 0; static public final int MENU_CAPTURE_PICTURE = 1; static public final int MENU_CAPTURE_VIDEO = 2; static public final int MENU_IMAGE_SHARE = 10; static public final int MENU_IMAGE_SET = 14; static public final int MENU_IMAGE_SET_WALLPAPER = 15; static public final int MENU_IMAGE_SET_CONTACT = 16; static public final int MENU_IMAGE_SET_MYFAVE = 17; static public final int MENU_IMAGE_CROP = 18; static public final int MENU_IMAGE_ROTATE = 19; static public final int MENU_IMAGE_ROTATE_LEFT = 20; static public final int MENU_IMAGE_ROTATE_RIGHT = 21; static public final int MENU_IMAGE_TOSS = 22; static public final int MENU_VIDEO_PLAY = 23; static public final int MENU_VIDEO_SHARE = 24; static public final int MENU_VIDEO_TOSS = 27; static private final long SHARE_FILE_LENGTH_LIMIT = 3L * 1024L * 1024L; public static final int NO_STORAGE_ERROR = -1; public static final int CANNOT_STAT_ERROR = -2; /** Activity result code used to report crop results. */ public static final int RESULT_COMMON_MENU_CROP = 490; public interface MenuItemsResult { public void gettingReadyToOpen(Menu menu, ImageManager.IImage image); public void aboutToCall(MenuItem item, ImageManager.IImage image); } public interface MenuInvoker { public void run(MenuCallback r); } public interface MenuCallback { public void run(Uri uri, ImageManager.IImage image); } private static void closeSilently(Closeable target) { try { if (target != null) target.close(); } catch (Throwable t) { // ignore all exceptions, that's what silently means } } public static long getImageFileSize(ImageManager.IImage image) { java.io.InputStream data = image.fullSizeImageData(); if (data == null) return -1; try { return data.available(); } catch (java.io.IOException ex) { return -1; } finally { closeSilently(data); } } + // This is a hack before we find a solution to pass a permission to other + // applications. See bug #1735149. + // Checks if the URI starts with "content://mms". + public static boolean isMMSUri(Uri uri) { + return (uri != null) && + uri.getScheme().equals("content") && + uri.getAuthority().equals("mms"); + } + static MenuItemsResult addImageMenuItems( Menu menu, int inclusions, final boolean isImage, final Activity activity, final Handler handler, final Runnable onDelete, final MenuInvoker onInvoke) { final ArrayList<MenuItem> requiresWriteAccessItems = new ArrayList<MenuItem>(); final ArrayList<MenuItem> requiresNoDrmAccessItems = new ArrayList<MenuItem>(); if (isImage && ((inclusions & INCLUDE_ROTATE_MENU) != 0)) { SubMenu rotateSubmenu = menu.addSubMenu(IMAGE_SAVING_ITEM, MENU_IMAGE_ROTATE, 40, R.string.rotate).setIcon(android.R.drawable.ic_menu_rotate); // Don't show the rotate submenu if the item at hand is read only // since the items within the submenu won't be shown anyway. This is // really a framework bug in that it shouldn't show the submenu if // the submenu has no visible items. requiresWriteAccessItems.add(rotateSubmenu.getItem()); if (rotateSubmenu != null) { requiresWriteAccessItems.add(rotateSubmenu.add(0, MENU_IMAGE_ROTATE_LEFT, 50, R.string.rotate_left).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null || image.isReadonly()) return; image.rotateImageBy(-90); } }); return true; } }).setAlphabeticShortcut('l')); requiresWriteAccessItems.add(rotateSubmenu.add(0, MENU_IMAGE_ROTATE_RIGHT, 60, R.string.rotate_right).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null || image.isReadonly()) return; image.rotateImageBy(90); } }); return true; } }).setAlphabeticShortcut('r')); } } if (isImage && ((inclusions & INCLUDE_CROP_MENU) != 0)) { MenuItem autoCrop = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_CROP, 73, R.string.camera_crop).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (u == null) return; Intent cropIntent = new Intent(); cropIntent.setClass(activity, CropImage.class); cropIntent.setData(u); activity.startActivityForResult(cropIntent, RESULT_COMMON_MENU_CROP); } }); return true; } }); autoCrop.setIcon(android.R.drawable.ic_menu_crop); requiresWriteAccessItems.add(autoCrop); } if (isImage && ((inclusions & INCLUDE_SET_MENU) != 0)) { MenuItem setMenu = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_SET, 75, R.string.camera_set); setMenu.setIcon(android.R.drawable.ic_menu_set_as); setMenu.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (u == null || image == null) return; if (Config.LOGV) Log.v(TAG, "in callback u is " + u + "; mime type is " + image.getMimeType()); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA); intent.setDataAndType(u, image.getMimeType()); intent.putExtra("mimeType", image.getMimeType()); activity.startActivity(Intent.createChooser(intent, activity.getText(R.string.setImage))); } }); return true; } }); } if ((inclusions & INCLUDE_SHARE_MENU) != 0) { if (Config.LOGV) Log.v(TAG, ">>>>> add share"); MenuItem item1 = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_SHARE, 10, R.string.camera_share).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null) return; + if (isMMSUri(u)) return; if (!isImage && getImageFileSize(image) > SHARE_FILE_LENGTH_LIMIT ) { Toast.makeText(activity, R.string.too_large_to_attach, Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); String mimeType = image.getMimeType(); intent.setType(mimeType); intent.putExtra(Intent.EXTRA_STREAM, u); boolean isImage = ImageManager.isImageMimeType(mimeType); try { activity.startActivity(Intent.createChooser(intent, activity.getText( isImage ? R.string.sendImage : R.string.sendVideo))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(activity, isImage ? R.string.no_way_to_share_image : R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } }); return true; } }); item1.setIcon(android.R.drawable.ic_menu_share); MenuItem item = item1; requiresNoDrmAccessItems.add(item); } if ((inclusions & INCLUDE_DELETE_MENU) != 0) { MenuItem deleteItem = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_TOSS, 70, R.string.camera_toss); requiresWriteAccessItems.add(deleteItem); deleteItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { deleteImpl(activity, onDelete, isImage); return true; } }) .setAlphabeticShortcut('d') .setIcon(android.R.drawable.ic_menu_delete); } if ((inclusions & INCLUDE_DETAILS_MENU) != 0) { MenuItem detailsMenu = menu.add(0, 0, 80, R.string.details).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null) return; AlertDialog.Builder builder = new AlertDialog.Builder(activity); final View d = View.inflate(activity, R.layout.detailsview, null); ImageView imageView = (ImageView) d.findViewById(R.id.details_thumbnail_image); imageView.setImageBitmap(image.miniThumbBitmap()); TextView textView = (TextView) d.findViewById(R.id.details_image_title); textView.setText(image.getDisplayName()); long length = getImageFileSize(image); String lengthString = lengthString = length < 0 ? "" : android.text.format.Formatter.formatFileSize(activity, length); ((TextView)d.findViewById(R.id.details_file_size_value)) .setText(lengthString); int dimensionWidth = 0; int dimensionHeight = 0; if (isImage) { dimensionWidth = image.getWidth(); dimensionHeight = image.getHeight(); d.findViewById(R.id.details_duration_row).setVisibility(View.GONE); d.findViewById(R.id.details_frame_rate_row).setVisibility(View.GONE); d.findViewById(R.id.details_bit_rate_row).setVisibility(View.GONE); d.findViewById(R.id.details_format_row).setVisibility(View.GONE); d.findViewById(R.id.details_codec_row).setVisibility(View.GONE); } else { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setMode(MediaMetadataRetriever.MODE_GET_METADATA_ONLY); retriever.setDataSource(image.getDataPath()); try { dimensionWidth = Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)); dimensionHeight = Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); } catch (NumberFormatException e) { dimensionWidth = 0; dimensionHeight = 0; } try { int durationMs = Integer.parseInt(retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_DURATION)); String durationValue = formatDuration( activity, durationMs); ((TextView)d.findViewById(R.id.details_duration_value)) .setText(durationValue); } catch (NumberFormatException e) { d.findViewById(R.id.details_frame_rate_row) .setVisibility(View.GONE); } try { String frame_rate = String.format( activity.getString(R.string.details_fps), Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_FRAME_RATE))); ((TextView)d.findViewById(R.id.details_frame_rate_value)) .setText(frame_rate); } catch (NumberFormatException e) { d.findViewById(R.id.details_frame_rate_row) .setVisibility(View.GONE); } try { long bitRate = Long.parseLong(retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_BIT_RATE)); String bps; if (bitRate < 1000000) { bps = String.format( activity.getString(R.string.details_kbps), bitRate / 1000); } else { bps = String.format( activity.getString(R.string.details_mbps), ((double) bitRate) / 1000000.0); } ((TextView)d.findViewById(R.id.details_bit_rate_value)) .setText(bps); } catch (NumberFormatException e) { d.findViewById(R.id.details_bit_rate_row) .setVisibility(View.GONE); } String format = retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_FORMAT); ((TextView)d.findViewById(R.id.details_format_value)) .setText(format); String codec = retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_CODEC); if (codec == null) { d.findViewById(R.id.details_codec_row). setVisibility(View.GONE); } else { ((TextView)d.findViewById(R.id.details_codec_value)) .setText(codec); } } catch(RuntimeException ex) { // Assume this is a corrupt video file. } finally { try { retriever.release(); } catch (RuntimeException ex) { // Ignore failures while cleaning up. } } } String dimensionsString = String.format( activity.getString(R.string.details_dimension_x), dimensionWidth, dimensionHeight); ((TextView)d.findViewById(R.id.details_resolution_value)) .setText(dimensionsString); String dateString = ""; long dateTaken = image.getDateTaken(); if (dateTaken != 0) { java.util.Date date = new java.util.Date(image.getDateTaken()); java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(); dateString = dateFormat.format(date); ((TextView)d.findViewById(R.id.details_date_taken_value)) .setText(dateString); } else { d.findViewById(R.id.details_date_taken_row) .setVisibility(View.GONE); } builder.setNeutralButton(R.string.details_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setIcon(android.R.drawable.ic_dialog_info) .setTitle(R.string.details_panel_title) .setView(d) .show(); } }); return true; } }); detailsMenu.setIcon(R.drawable.ic_menu_view_details); } if ((!isImage) && ((inclusions & INCLUDE_VIEWPLAY_MENU) != 0)) { menu.add(VIDEO_SAVING_ITEM, MENU_VIDEO_PLAY, 0, R.string.video_play) .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri uri, IImage image) { if (image != null) { Intent intent = new Intent(Intent.ACTION_VIEW, image.fullSizeImageUri()); activity.startActivity(intent); } }}); return true; } }); } return new MenuItemsResult() { public void gettingReadyToOpen(Menu menu, ImageManager.IImage image) { // protect against null here. this isn't strictly speaking required // but if a client app isn't handling sdcard removal properly it // could happen if (image == null) { return; } boolean readOnly = image.isReadonly(); boolean isDrm = image.isDrm(); if (Config.LOGV) Log.v(TAG, "readOnly: " + readOnly + "; drm: " + isDrm); for (MenuItem item: requiresWriteAccessItems) { if (Config.LOGV) Log.v(TAG, "item is " + item.toString()); item.setVisible(!readOnly); item.setEnabled(!readOnly); } for (MenuItem item: requiresNoDrmAccessItems) { if (Config.LOGV) Log.v(TAG, "item is " + item.toString()); item.setVisible(!isDrm); item.setEnabled(!isDrm); } } public void aboutToCall(MenuItem menu, ImageManager.IImage image) { } }; } static void deletePhoto(Activity activity, Runnable onDelete) { deleteImpl(activity, onDelete, true); } static void deleteVideo(Activity activity, Runnable onDelete) { deleteImpl(activity, onDelete, false); } static void deleteImage(Activity activity, Runnable onDelete, IImage image) { if (image != null) { deleteImpl(activity, onDelete, ImageManager.isImage(image)); } } private static void deleteImpl(Activity activity, final Runnable onDelete, boolean isPhoto) { boolean confirm = android.preference.PreferenceManager.getDefaultSharedPreferences(activity).getBoolean("pref_gallery_confirm_delete_key", true); if (!confirm) { if (onDelete != null) onDelete.run(); } else { displayDeleteDialog(activity, onDelete, isPhoto); } } public static void displayDeleteDialog(Activity activity, final Runnable onDelete, boolean isPhoto) { android.app.AlertDialog.Builder b = new android.app.AlertDialog.Builder(activity); b.setIcon(android.R.drawable.ic_dialog_alert); b.setTitle(R.string.confirm_delete_title); b.setMessage(isPhoto? R.string.confirm_delete_message : R.string.confirm_delete_video_message); b.setPositiveButton(android.R.string.ok, new android.content.DialogInterface.OnClickListener() { public void onClick(android.content.DialogInterface v, int x) { if (onDelete != null) onDelete.run(); } }); b.setNegativeButton(android.R.string.cancel, new android.content.DialogInterface.OnClickListener() { public void onClick(android.content.DialogInterface v, int x) { } }); b.create().show(); } static void addSwitchModeMenuItem(Menu menu, final Activity activity, final boolean switchToVideo) { int group = switchToVideo ? MenuHelper.IMAGE_MODE_ITEM : MenuHelper.VIDEO_MODE_ITEM; int labelId = switchToVideo ? R.string.switch_to_video_lable : R.string.switch_to_camera_lable; int iconId = switchToVideo ? R.drawable.ic_menu_camera_video_view : android.R.drawable.ic_menu_camera; MenuItem item = menu.add(group, MENU_SWITCH_CAMERA_MODE, 0, labelId).setOnMenuItemClickListener( new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { String action = switchToVideo ? MediaStore.INTENT_ACTION_VIDEO_CAMERA : MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA; Intent intent = new Intent(action); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); activity.startActivity(intent); return true; } }); item.setIcon(iconId); } static void gotoStillImageCapture(Activity activity) { Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Log.e(TAG, "Could not start still image capture activity", e); } } static void gotoCameraImageGallery(Activity activity) { gotoGallery(activity, R.string.gallery_camera_bucket_name, ImageManager.INCLUDE_IMAGES); } static void gotoCameraVideoGallery(Activity activity) { gotoGallery(activity, R.string.gallery_camera_videos_bucket_name, ImageManager.INCLUDE_VIDEOS); } static private void gotoGallery(Activity activity, int windowTitleId, int mediaTypes) { Uri target = Images.Media.INTERNAL_CONTENT_URI.buildUpon().appendQueryParameter("bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build(); Intent intent = new Intent(Intent.ACTION_VIEW, target); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("windowTitle", activity.getString(windowTitleId)); intent.putExtra("mediaTypes", mediaTypes); // Request unspecified so that we match the current camera orientation rather than // matching the "flip orientation" preference. // Disabled because people don't care for it. Also it's // not as compelling now that we have implemented have quick orientation flipping. // intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, // android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Log.e(TAG, "Could not start gallery activity", e); } } static void addCapturePictureMenuItems(Menu menu, final Activity activity) { menu.add(0, MENU_CAPTURE_PICTURE, 1, R.string.capture_picture) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { activity.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { // Ignore exception } return true; } }) .setIcon(android.R.drawable.ic_menu_camera); } static void addCaptureVideoMenuItems(Menu menu, final Activity activity) { menu.add(0, MENU_CAPTURE_VIDEO, 2, R.string.capture_video) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { activity.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { // Ignore exception } return true; } }) .setIcon(R.drawable.ic_menu_camera_video_view); } static void addCaptureMenuItems(Menu menu, final Activity activity) { addCapturePictureMenuItems(menu, activity); addCaptureVideoMenuItems(menu, activity); } static MenuItem addFlipOrientation(Menu menu, final Activity activity, final SharedPreferences prefs) { // position 41 after rotate // D return menu .add(Menu.CATEGORY_SECONDARY, 304, 41, R.string.flip_orientation) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // Check what our actual orientation is int current = activity.getResources().getConfiguration().orientation; int newOrientation = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; if (current == Configuration.ORIENTATION_LANDSCAPE) { newOrientation = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; } SharedPreferences.Editor editor = prefs.edit(); editor.putInt("nuorientation", newOrientation); editor.commit(); requestOrientation(activity, prefs, true); return true; } }) .setIcon(android.R.drawable.ic_menu_always_landscape_portrait); } static void requestOrientation(Activity activity, SharedPreferences prefs) { requestOrientation(activity, prefs, false); } static private void requestOrientation(Activity activity, SharedPreferences prefs, boolean ignoreIntentExtra) { // Disable orientation for now. If it is set to SCREEN_ORIENTATION_SENSOR, // a duplicated orientation will be observed. return; } static void setFlipOrientationEnabled(Activity activity, MenuItem flipItem) { int keyboard = activity.getResources().getConfiguration().hardKeyboardHidden; flipItem.setEnabled(keyboard != android.content.res.Configuration.HARDKEYBOARDHIDDEN_NO); } public static String formatDuration(final Activity activity, int durationMs) { int duration = durationMs / 1000; int h = duration / 3600; int m = (duration - h * 3600) / 60; int s = duration - (h * 3600 + m * 60); String durationValue; if (h == 0) { durationValue = String.format( activity.getString(R.string.details_ms), m, s); } else { durationValue = String.format( activity.getString(R.string.details_hms), h, m, s); } return durationValue; } public static void showStorageToast(Activity activity) { showStorageToast(activity, calculatePicturesRemaining()); } public static void showStorageToast(Activity activity, int remaining) { String noStorageText = null; if (remaining == MenuHelper.NO_STORAGE_ERROR) { String state = Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING) { noStorageText = activity.getString(R.string.preparing_sd); } else { noStorageText = activity.getString(R.string.no_storage); } } else if (remaining < 1) { noStorageText = activity.getString(R.string.not_enough_space); } if (noStorageText != null) { Toast.makeText(activity, noStorageText, 5000).show(); } } public static int calculatePicturesRemaining() { try { if (!ImageManager.hasStorage()) { return NO_STORAGE_ERROR; } else { String storageDirectory = Environment.getExternalStorageDirectory().toString(); StatFs stat = new StatFs(storageDirectory); float remaining = ((float)stat.getAvailableBlocks() * (float)stat.getBlockSize()) / 400000F; return (int)remaining; } } catch (Exception ex) { // if we can't stat the filesystem then we don't know how many // pictures are remaining. it might be zero but just leave it // blank since we really don't know. return CANNOT_STAT_ERROR; } } } diff --git a/src/com/android/camera/VideoCamera.java b/src/com/android/camera/VideoCamera.java index 186d827..c8d5f7d 100644 --- a/src/com/android/camera/VideoCamera.java +++ b/src/com/android/camera/VideoCamera.java @@ -1,809 +1,810 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.location.LocationManager; import android.media.MediaRecorder; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.StatFs; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.MediaStore.Video; import android.text.format.DateFormat; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.MenuItem.OnMenuItemClickListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class VideoCamera extends Activity implements View.OnClickListener, ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback, MediaRecorder.OnErrorListener, MediaRecorder.OnInfoListener { private static final String TAG = "videocamera"; private static final boolean DEBUG = true; private static final boolean DEBUG_SUPPRESS_AUDIO_RECORDING = DEBUG && false; private static final int CLEAR_SCREEN_DELAY = 4; private static final int UPDATE_RECORD_TIME = 5; private static final int SCREEN_DELAY = 2 * 60 * 1000; private static final long NO_STORAGE_ERROR = -1L; private static final long CANNOT_STAT_ERROR = -2L; private static final long LOW_STORAGE_THRESHOLD = 512L * 1024L; private static final long SHARE_FILE_LENGTH_LIMIT = 3L * 1024L * 1024L; private static final int STORAGE_STATUS_OK = 0; private static final int STORAGE_STATUS_LOW = 1; private static final int STORAGE_STATUS_NONE = 2; public static final int MENU_SETTINGS = 6; public static final int MENU_GALLERY_PHOTOS = 7; public static final int MENU_GALLERY_VIDEOS = 8; public static final int MENU_SAVE_GALLERY_PHOTO = 34; public static final int MENU_SAVE_PLAY_VIDEO = 35; public static final int MENU_SAVE_SELECT_VIDEO = 36; public static final int MENU_SAVE_NEW_VIDEO = 37; SharedPreferences mPreferences; private static final float VIDEO_ASPECT_RATIO = 176.0f / 144.0f; VideoPreview mVideoPreview; SurfaceHolder mSurfaceHolder = null; ImageView mVideoFrame; private boolean mIsVideoCaptureIntent; // mLastPictureButton and mThumbController // are non-null only if isVideoCaptureIntent() is true; private ImageView mLastPictureButton; private ThumbnailController mThumbController; private static final int MAX_RECORDING_DURATION_MS = 10 * 60 * 1000; private int mStorageStatus = STORAGE_STATUS_OK; private MediaRecorder mMediaRecorder; private boolean mMediaRecorderRecording = false; private long mRecordingStartTime; // The video file that the hardware camera is about to record into // (or is recording into.) private String mCameraVideoFilename; private FileDescriptor mCameraVideoFileDescriptor; // The video file that has already been recorded, and that is being // examined by the user. private String mCurrentVideoFilename; private long mCurrentVideoFileLength = 0L; private Uri mCurrentVideoUri; private ContentValues mCurrentVideoValues; boolean mPausing = false; static ContentResolver mContentResolver; int mCurrentZoomIndex = 0; private ShutterButton mShutterButton; private TextView mRecordingTimeView; private boolean mRecordingTimeCountsDown = false; ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>(); View mPostPictureAlert; LocationManager mLocationManager = null; private Handler mHandler = new MainHandler(); /** This Handler is used to post message back onto the main thread of the application */ private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case CLEAR_SCREEN_DELAY: { clearScreenOnFlag(); break; } case UPDATE_RECORD_TIME: { if (mMediaRecorderRecording) { long now = SystemClock.uptimeMillis(); long delta = now - mRecordingStartTime; // Starting a minute before reaching the max duration // limit, we'll countdown the remaining time instead. boolean countdown_remaining_time = (delta >= MAX_RECORDING_DURATION_MS - 60000); if (countdown_remaining_time) { delta = Math.max(0, MAX_RECORDING_DURATION_MS - delta); } long seconds = (delta + 500) / 1000; // round to nearest long minutes = seconds / 60; long hours = minutes / 60; long remainderMinutes = minutes - (hours * 60); long remainderSeconds = seconds - (minutes * 60); String secondsString = Long.toString(remainderSeconds); if (secondsString.length() < 2) { secondsString = "0" + secondsString; } String minutesString = Long.toString(remainderMinutes); if (minutesString.length() < 2) { minutesString = "0" + minutesString; } String text = minutesString + ":" + secondsString; if (hours > 0) { String hoursString = Long.toString(hours); if (hoursString.length() < 2) { hoursString = "0" + hoursString; } text = hoursString + ":" + text; } mRecordingTimeView.setText(text); if (mRecordingTimeCountsDown != countdown_remaining_time) { // Avoid setting the color on every update, do it only // when it needs changing. mRecordingTimeCountsDown = countdown_remaining_time; int color = getResources().getColor( countdown_remaining_time ? R.color.recording_time_remaining_text : R.color.recording_time_elapsed_text); mRecordingTimeView.setTextColor(color); } // Work around a limitation of the T-Mobile G1: The T-Mobile // hardware blitter can't pixel-accurately scale and clip at the same time, // and the SurfaceFlinger doesn't attempt to work around this limitation. // In order to avoid visual corruption we must manually refresh the entire // surface view when changing any overlapping view's contents. mVideoPreview.invalidate(); mHandler.sendEmptyMessageDelayed(UPDATE_RECORD_TIME, 1000); } break; } default: Log.v(TAG, "Unhandled message: " + msg.what); break; } } }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_EJECT)) { updateAndShowStorageHint(false); stopVideoRecording(); initializeVideo(); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { updateAndShowStorageHint(true); initializeVideo(); } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) { // SD card unavailable // handled in ACTION_MEDIA_EJECT } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { Toast.makeText(VideoCamera.this, getResources().getString(R.string.wait), 5000); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { updateAndShowStorageHint(true); } } }; static private String createName(long dateTaken) { return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString(); } /** Called with the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mContentResolver = getContentResolver(); //setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.video_camera); mVideoPreview = (VideoPreview) findViewById(R.id.camera_preview); mVideoPreview.setAspectRatio(VIDEO_ASPECT_RATIO); // don't set mSurfaceHolder here. We have it set ONLY within // surfaceCreated / surfaceDestroyed, other parts of the code // assume that when it is set, the surface is also set. SurfaceHolder holder = mVideoPreview.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mPostPictureAlert = findViewById(R.id.post_picture_panel); int[] ids = new int[]{R.id.play, R.id.share, R.id.discard, R.id.cancel, R.id.attach}; for (int id : ids) { findViewById(id).setOnClickListener(this); } mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); mRecordingTimeView = (TextView) findViewById(R.id.recording_time); mVideoFrame = (ImageView) findViewById(R.id.video_frame); mIsVideoCaptureIntent = isVideoCaptureIntent(); if (!mIsVideoCaptureIntent) { mLastPictureButton = (ImageView) findViewById(R.id.last_picture_button); mLastPictureButton.setOnClickListener(this); Drawable frame = getResources().getDrawable(R.drawable.frame_thumbnail); mThumbController = new ThumbnailController(mLastPictureButton, frame, mContentResolver); mThumbController.loadData(ImageManager.getLastVideoThumbPath()); } } private void startShareVideoActivity() { + if (MenuHelper.isMMSUri(mCurrentVideoUri)) return; if (mCurrentVideoFileLength > SHARE_FILE_LENGTH_LIMIT) { Toast.makeText(VideoCamera.this, R.string.too_large_to_attach, Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("video/3gpp"); intent.putExtra(Intent.EXTRA_STREAM, mCurrentVideoUri); try { startActivity(Intent.createChooser(intent, getText(R.string.sendVideo))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(VideoCamera.this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } public void onClick(View v) { switch (v.getId()) { case R.id.gallery: MenuHelper.gotoCameraVideoGallery(this); break; case R.id.attach: doReturnToCaller(true); break; case R.id.cancel: doReturnToCaller(false); break; case R.id.discard: { Runnable deleteCallback = new Runnable() { public void run() { discardCurrentVideoAndStartPreview(); } }; MenuHelper.deleteVideo(this, deleteCallback); break; } case R.id.share: { startShareVideoActivity(); break; } case R.id.play: { doPlayCurrentVideo(); break; } case R.id.last_picture_button: { stopVideoRecordingAndShowAlert(); break; } } } public void onShutterButtonFocus(ShutterButton button, boolean pressed) { // Do nothing (everything happens in onShutterButtonClick). } public void onShutterButtonClick(ShutterButton button) { switch (button.getId()) { case R.id.shutter_button: if (mMediaRecorderRecording) { if (mIsVideoCaptureIntent) { stopVideoRecordingAndShowAlert(); } else { stopVideoRecordingAndGetThumbnail(); initializeVideo(); } } else if (isAlertVisible()) { if (mIsVideoCaptureIntent) { discardCurrentVideoAndStartPreview(); } else { hideAlertAndStartVideoRecording(); } } else { startVideoRecording(); } break; } } private void doPlayCurrentVideo() { Log.e(TAG, "Playing current video: " + mCurrentVideoUri); Intent intent = new Intent(Intent.ACTION_VIEW, mCurrentVideoUri); try { startActivity(intent); } catch (android.content.ActivityNotFoundException ex) { Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex); } } private void discardCurrentVideoAndStartPreview() { deleteCurrentVideo(); hideAlertAndStartPreview(); } private OnScreenHint mStorageHint; private void updateAndShowStorageHint(boolean mayHaveSd) { mStorageStatus = getStorageStatus(mayHaveSd); showStorageHint(); } private void showStorageHint() { String errorMessage = null; switch (mStorageStatus) { case STORAGE_STATUS_NONE: errorMessage = getString(R.string.no_storage); break; case STORAGE_STATUS_LOW: errorMessage = getString(R.string.spaceIsLow_content); } if (errorMessage != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, errorMessage); } else { mStorageHint.setText(errorMessage); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } private int getStorageStatus(boolean mayHaveSd) { long remaining = mayHaveSd ? getAvailableStorage() : NO_STORAGE_ERROR; if (remaining == NO_STORAGE_ERROR) { return STORAGE_STATUS_NONE; } return remaining < LOW_STORAGE_THRESHOLD ? STORAGE_STATUS_LOW : STORAGE_STATUS_OK; } @Override public void onResume() { super.onResume(); setScreenTimeoutLong(); mPausing = false; // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_EJECT); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); mStorageStatus = getStorageStatus(true); mHandler.postDelayed(new Runnable() { public void run() { showStorageHint(); } }, 200); initializeVideo(); } @Override public void onStop() { setScreenTimeoutSystemDefault(); super.onStop(); } @Override protected void onPause() { super.onPause(); // This is similar to what mShutterButton.performClick() does, // but not quite the same. if (mMediaRecorderRecording) { if (mIsVideoCaptureIntent) { stopVideoRecordingAndShowAlert(); } else { stopVideoRecordingAndGetThumbnail(); } } else { stopVideoRecording(); } mPausing = true; unregisterReceiver(mReceiver); setScreenTimeoutSystemDefault(); if (!mIsVideoCaptureIntent) { mThumbController.storeData(ImageManager.getLastVideoThumbPath()); } if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { setScreenTimeoutLong(); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mMediaRecorderRecording) { mShutterButton.performClick(); return true; } else if(isAlertVisible()) { hideAlertAndStartPreview(); return true; } break; case KeyEvent.KEYCODE_CAMERA: if (event.getRepeatCount() == 0) { mShutterButton.performClick(); return true; } break; case KeyEvent.KEYCODE_DPAD_CENTER: if (event.getRepeatCount() == 0) { mShutterButton.performClick(); return true; } break; case KeyEvent.KEYCODE_MENU: if (mMediaRecorderRecording) { mShutterButton.performClick(); return true; } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_CAMERA: mShutterButton.setPressed(false); return true; } return super.onKeyUp(keyCode, event); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { if (mPausing) { // We're pausing, the screen is off and we already stopped // video recording. We don't want to start the camera again // in this case in order to conserve power. // The fact that surfaceChanged is called _after_ an onPause appears // to be legitimate since in that case the lockscreen always returns // to portrait orientation possibly triggering the notification. return; } stopVideoRecording(); initializeVideo(); } public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; } public void surfaceDestroyed(SurfaceHolder holder) { mSurfaceHolder = null; } void gotoGallery() { MenuHelper.gotoCameraVideoGallery(this); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); for (int i = 1; i <= MenuHelper.MENU_ITEM_MAX; i++) { if (i != MenuHelper.GENERIC_ITEM) { menu.setGroupVisible(i, false); } } menu.setGroupVisible(MenuHelper.VIDEO_MODE_ITEM, true); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (mIsVideoCaptureIntent) { // No options menu for attach mode. return false; } else { addBaseMenuItems(menu); int menuFlags = MenuHelper.INCLUDE_ALL & ~MenuHelper.INCLUDE_ROTATE_MENU & ~MenuHelper.INCLUDE_DETAILS_MENU; MenuHelper.addImageMenuItems( menu, menuFlags, false, VideoCamera.this, mHandler, // Handler for deletion new Runnable() { public void run() { // What do we do here? // mContentResolver.delete(uri, null, null); } }, new MenuHelper.MenuInvoker() { public void run(final MenuHelper.MenuCallback cb) { } }); MenuItem gallery = menu.add(MenuHelper.IMAGE_SAVING_ITEM, MENU_SAVE_GALLERY_PHOTO, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); } return true; } private boolean isVideoCaptureIntent() { String action = getIntent().getAction(); return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action)); } private void doReturnToCaller(boolean success) { Intent resultIntent = new Intent(); int resultCode; if (success) { resultCode = RESULT_OK; resultIntent.setData(mCurrentVideoUri); } else { resultCode = RESULT_CANCELED; } setResult(resultCode, resultIntent); finish(); } /** * Returns * @return number of bytes available, or an ERROR code. */ private static long getAvailableStorage() { try { if (!ImageManager.hasStorage()) { return NO_STORAGE_ERROR; } else { String storageDirectory = Environment.getExternalStorageDirectory().toString(); StatFs stat = new StatFs(storageDirectory); return ((long)stat.getAvailableBlocks() * (long)stat.getBlockSize()); } } catch (Exception ex) { // if we can't stat the filesystem then we don't know how many // free bytes exist. It might be zero but just leave it // blank since we really don't know. return CANNOT_STAT_ERROR; } } private void cleanupEmptyFile() { if (mCameraVideoFilename != null) { File f = new File(mCameraVideoFilename); if (f.length() == 0 && f.delete()) { Log.v(TAG, "Empty video file deleted: " + mCameraVideoFilename); mCameraVideoFilename = null; } } } // initializeVideo() starts preview and prepare media recorder. // Returns false if initializeVideo fails private boolean initializeVideo() { Log.v(TAG, "initializeVideo"); // We will call initializeVideo() again when the alert is hidden. if (isAlertVisible()) return false; Intent intent = getIntent(); Bundle myExtras = intent.getExtras(); if (mIsVideoCaptureIntent && myExtras != null) { Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); if (saveUri != null) { try { mCameraVideoFileDescriptor = mContentResolver. openFileDescriptor(saveUri, "rw").getFileDescriptor(); mCurrentVideoUri = saveUri; } catch (java.io.FileNotFoundException ex) { // invalid uri Log.e(TAG, ex.toString()); } } } releaseMediaRecorder(); if (mSurfaceHolder == null) { Log.v(TAG, "SurfaceHolder is null"); return false; } mMediaRecorder = new MediaRecorder(); if (DEBUG_SUPPRESS_AUDIO_RECORDING) { Log.v(TAG, "DEBUG_SUPPRESS_AUDIO_RECORDING is true."); } else { mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); } mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mMediaRecorder.setMaxDuration(MAX_RECORDING_DURATION_MS); if (mStorageStatus != STORAGE_STATUS_OK) { mMediaRecorder.setOutputFile("/dev/null"); } else { // We try Uri in intent first. If it doesn't work, use our own instead. if (mCameraVideoFileDescriptor != null) { mMediaRecorder.setOutputFile(mCameraVideoFileDescriptor); } else { createVideoPath(); mMediaRecorder.setOutputFile(mCameraVideoFilename); } } boolean videoQualityHigh = getBooleanPreference(CameraSettings.KEY_VIDEO_QUALITY, CameraSettings.DEFAULT_VIDEO_QUALITY_VALUE); if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) { int extraVideoQuality = intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); videoQualityHigh = (extraVideoQuality > 0); } // Use the same frame rate for both, since internally // if the frame rate is too large, it can cause camera to become // unstable. We need to fix the MediaRecorder to disable the support // of setting frame rate for now. mMediaRecorder.setVideoFrameRate(20); if (videoQualityHigh) { mMediaRecorder.setVideoSize(352,288); } else { mMediaRecorder.setVideoSize(176,144); } mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); if (!DEBUG_SUPPRESS_AUDIO_RECORDING) { mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); } mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); long remaining = getAvailableStorage(); // remaining >= LOW_STORAGE_THRESHOLD at this point, reserve a quarter // of that to make it more likely that recording can complete successfully. try { mMediaRecorder.setMaxFileSize(remaining - LOW_STORAGE_THRESHOLD / 4); } catch (RuntimeException exception) { // We are going to ignore failure of setMaxFileSize here, as // a) The composer selected may simply not support it, or // b) The underlying media framework may not handle 64-bit range // on the size restriction. } try { mMediaRecorder.prepare(); } catch (IOException exception) { Log.e(TAG, "prepare failed for " + mCameraVideoFilename); releaseMediaRecorder(); // TODO: add more exception handling logic here return false; } mMediaRecorderRecording = false; if (!mIsVideoCaptureIntent && !mThumbController.isUriValid()) { updateLastVideo(); } if (!mIsVideoCaptureIntent) { mThumbController.updateDisplayIfNeeded(); } return true; } private void releaseMediaRecorder() { Log.v(TAG, "Releasing media recorder."); if (mMediaRecorder != null) { cleanupEmptyFile(); mMediaRecorder.reset(); mMediaRecorder.release(); mMediaRecorder = null; } } private int getIntPreference(String key, int defaultValue) { String s = mPreferences.getString(key, ""); int result = defaultValue; try { result = Integer.parseInt(s); } catch (NumberFormatException e) { // Ignore, result is already the default value. diff --git a/src/com/android/camera/ViewImage.java b/src/com/android/camera/ViewImage.java index ad2ce77..c7de24e 100644 --- a/src/com/android/camera/ViewImage.java +++ b/src/com/android/camera/ViewImage.java @@ -984,595 +984,596 @@ public class ViewImage extends Activity implements View.OnClickListener if (mGetter != null) { mGetter.setPosition(pos, cb); } showOnScreenControls(); } @Override public void onCreate(Bundle instanceState) { super.onCreate(instanceState); Intent intent = getIntent(); mCameraReviewMode = intent.getBooleanExtra("com.android.camera.ReviewMode", false); mFullScreenInNormalMode = intent.getBooleanExtra(MediaStore.EXTRA_FULL_SCREEN, true); mShowActionIcons = intent.getBooleanExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, false); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mCurrentOrientation = getResources().getConfiguration().orientation; setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.viewimage); mImageViews[0] = (ImageViewTouch) findViewById(R.id.image1); mImageViews[1] = (ImageViewTouch) findViewById(R.id.image2); mImageViews[2] = (ImageViewTouch) findViewById(R.id.image3); for(ImageViewTouch v : mImageViews) { v.setEnableTrackballScroll(!mShowActionIcons); } mScroller = (ScrollHandler)findViewById(R.id.scroller); makeGetter(); mAnimationIndex = -1; mSlideShowInAnimation = new Animation[] { makeInAnimation(R.anim.transition_in), makeInAnimation(R.anim.slide_in), makeInAnimation(R.anim.slide_in_vertical), }; mSlideShowOutAnimation = new Animation[] { makeOutAnimation(R.anim.transition_out), makeOutAnimation(R.anim.slide_out), makeOutAnimation(R.anim.slide_out_vertical), }; mSlideShowImageViews[0] = (ImageViewTouch) findViewById(R.id.image1_slideShow); mSlideShowImageViews[1] = (ImageViewTouch) findViewById(R.id.image2_slideShow); for (ImageViewTouch v : mSlideShowImageViews) { v.setImageBitmapResetBase(null, true, true); v.setVisibility(View.INVISIBLE); v.setEnableTrackballScroll(!mShowActionIcons); } mActionIconPanel = findViewById(R.id.action_icon_panel); { int[] pickIds = {R.id.attach, R.id.cancel}; int[] normalIds = {R.id.gallery, R.id.setas, R.id.share, R.id.discard}; int[] hideIds = pickIds; int[] connectIds = normalIds; if (isPickIntent()) { hideIds = normalIds; connectIds = pickIds; } for(int id : hideIds) { mActionIconPanel.findViewById(id).setVisibility(View.GONE); } for(int id : connectIds) { View view = mActionIconPanel.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } mShutterButton = findViewById(R.id.shutter_button); mShutterButton.setOnClickListener(this); Uri uri = getIntent().getData(); if (Config.LOGV) Log.v(TAG, "uri is " + uri); if (instanceState != null) { if (instanceState.containsKey("uri")) { uri = Uri.parse(instanceState.getString("uri")); } } if (uri == null) { finish(); return; } init(uri); Bundle b = getIntent().getExtras(); boolean slideShow = b != null ? b.getBoolean("slideshow", false) : false; if (slideShow) { setMode(MODE_SLIDESHOW); loadNextImage(mCurrentPosition, 0, true); } else { if (mFullScreenInNormalMode) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } } setupZoomButtonController(findViewById(R.id.rootLayout)); setupDismissOnScreenControlRunnable(); mNextImageView = findViewById(R.id.next_image); mPrevImageView = findViewById(R.id.prev_image); mNextImageView.setOnClickListener(this); mPrevImageView.setOnClickListener(this); if (mShowActionIcons) { mNextImageView.setFocusable(true); mPrevImageView.setFocusable(true); } setOrientation(); } private void setOrientation() { Intent intent = getIntent(); if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); if (orientation != getRequestedOrientation()) { setRequestedOrientation(orientation); } } else { MenuHelper.requestOrientation(this, mPrefs); } } private Animation makeInAnimation(int id) { Animation inAnimation = AnimationUtils.loadAnimation(this, id); return inAnimation; } private Animation makeOutAnimation(int id) { Animation outAnimation = AnimationUtils.loadAnimation(this, id); return outAnimation; } private void setMode(int mode) { if (mMode == mode) { return; } findViewById(R.id.slideShowContainer).setVisibility(mode == MODE_SLIDESHOW ? View.VISIBLE : View.GONE); findViewById(R.id.abs) .setVisibility(mode == MODE_NORMAL ? View.VISIBLE : View.GONE); Window win = getWindow(); mMode = mode; if (mode == MODE_SLIDESHOW) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (sSlideShowHidesStatusBar) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } for (ImageViewTouchBase ivt: mImageViews) { ivt.clear(); } mActionIconPanel.setVisibility(View.GONE); mShutterButton.setVisibility(View.GONE); if (false) { Log.v(TAG, "current is " + this.mSlideShowImageCurrent); this.mSlideShowImageViews[0].dump(); this.mSlideShowImageViews[0].dump(); } findViewById(R.id.slideShowContainer).getRootView().requestLayout(); mUseShuffleOrder = mPrefs.getBoolean("pref_gallery_slideshow_shuffle_key", false); mSlideShowLoop = mPrefs.getBoolean("pref_gallery_slideshow_repeat_key", false); try { mAnimationIndex = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_transition_key", "0")); } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mAnimationIndex = 0; } try { mSlideShowInterval = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_interval_key", "3")) * 1000; } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mSlideShowInterval = 3000; } if (Config.LOGV) { Log.v(TAG, "read prefs... shuffle: " + mUseShuffleOrder); Log.v(TAG, "read prefs... loop: " + mSlideShowLoop); Log.v(TAG, "read prefs... animidx: " + mAnimationIndex); Log.v(TAG, "read prefs... interval: " + mSlideShowInterval); } if (mUseShuffleOrder) { generateShuffleOrder(); } } else { if (Config.LOGV) Log.v(TAG, "slide show mode off, mCurrentPosition == " + mCurrentPosition); win.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (mFullScreenInNormalMode) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mGetter != null) mGetter.cancelCurrent(); if (sSlideShowHidesStatusBar) { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } ImageViewTouchBase dst = mImageViews[1]; dst.mLastXTouchPos = -1; dst.mLastYTouchPos = -1; for (ImageViewTouchBase ivt: mSlideShowImageViews) { ivt.clear(); } mShuffleOrder = null; // mGetter null is a proxy for being paused if (mGetter != null) { mFirst = true; // don't animate setImage(mCurrentPosition); } } // this line shouldn't be necessary but the view hierarchy doesn't // seem to realize that the window layout changed mScroller.requestLayout(); } private void generateShuffleOrder() { if (mShuffleOrder == null || mShuffleOrder.length != mAllImages.getCount()) { mShuffleOrder = new int[mAllImages.getCount()]; } for (int i = 0; i < mShuffleOrder.length; i++) { mShuffleOrder[i] = i; } for (int i = mShuffleOrder.length - 1; i > 0; i--) { int r = mRandom.nextInt(i); int tmp = mShuffleOrder[r]; mShuffleOrder[r] = mShuffleOrder[i]; mShuffleOrder[i] = tmp; } } private void loadNextImage(final int requestedPos, final long delay, final boolean firstCall) { if (firstCall && mUseShuffleOrder) { generateShuffleOrder(); } final long targetDisplayTime = System.currentTimeMillis() + delay; ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { } public boolean wantsThumbnail(int pos, int offset) { return true; } public boolean wantsFullImage(int pos, int offset) { return false; } public int [] loadOrder() { return sOrder_slideshow; } public int fullImageSizeToUse(int pos, int offset) { return 480; // TODO compute this } public void imageLoaded(final int pos, final int offset, final Bitmap bitmap, final boolean isThumb) { long timeRemaining = Math.max(0, targetDisplayTime - System.currentTimeMillis()); mHandler.postDelayedGetterCallback(new Runnable() { public void run() { if (mMode == MODE_NORMAL) return; ImageViewTouchBase oldView = mSlideShowImageViews[mSlideShowImageCurrent]; if (++mSlideShowImageCurrent == mSlideShowImageViews.length) { mSlideShowImageCurrent = 0; } ImageViewTouchBase newView = mSlideShowImageViews[mSlideShowImageCurrent]; newView.setVisibility(View.VISIBLE); newView.setImageBitmapResetBase(bitmap, isThumb, isThumb); newView.bringToFront(); int animation = 0; if (mAnimationIndex == -1) { int n = mRandom.nextInt(mSlideShowInAnimation.length); animation = n; } else { animation = mAnimationIndex; } Animation aIn = mSlideShowInAnimation[animation]; newView.setAnimation(aIn); newView.setVisibility(View.VISIBLE); aIn.startNow(); Animation aOut = mSlideShowOutAnimation[animation]; oldView.setVisibility(View.INVISIBLE); oldView.setAnimation(aOut); aOut.startNow(); mCurrentPosition = requestedPos; if (mCurrentPosition == mLastSlideShowImage && !firstCall) { if (mSlideShowLoop) { if (mUseShuffleOrder) { generateShuffleOrder(); } } else { setMode(MODE_NORMAL); return; } } if (Config.LOGV) Log.v(TAG, "mCurrentPosition is now " + mCurrentPosition); loadNextImage((mCurrentPosition + 1) % mAllImages.getCount(), mSlideShowInterval, false); } }, timeRemaining); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { int pos = requestedPos; if (mShuffleOrder != null) { pos = mShuffleOrder[pos]; } mGetter.setPosition(pos, cb); } } private void makeGetter() { mGetter = new ImageGetter(); } private boolean desiredSortOrder() { String sortOrder = mPrefs.getString("pref_gallery_sort_key", null); boolean sortAscending = false; if (sortOrder != null) { sortAscending = sortOrder.equals("ascending"); } if (mCameraReviewMode) { // Force left-arrow older pictures, right-arrow newer pictures. sortAscending = true; } return sortAscending; } private void init(Uri uri) { if (uri == null) return; mSortAscending = desiredSortOrder(); int sort = mSortAscending ? ImageManager.SORT_ASCENDING : ImageManager.SORT_DESCENDING; mAllImages = ImageManager.makeImageList(uri, this, sort); uri = uri.buildUpon().query(null).build(); // TODO smarter/faster here please for (int i = 0; i < mAllImages.getCount(); i++) { ImageManager.IImage image = mAllImages.getImageAt(i); if (image.fullSizeImageUri().equals(uri)) { mCurrentPosition = i; mLastSlideShowImage = mCurrentPosition; break; } } } private Uri getCurrentUri() { ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); Uri uri = null; if (image != null){ String bucket = null; uri = image.fullSizeImageUri(); if(getIntent() != null && getIntent().getData() != null) bucket = getIntent().getData().getQueryParameter("bucketId"); if(bucket != null) uri = uri.buildUpon().appendQueryParameter("bucketId", bucket).build(); } return uri; } @Override public void onSaveInstanceState(Bundle b) { super.onSaveInstanceState(b); Uri uri = getCurrentUri(); if (uri != null) { b.putString("uri", uri.toString()); } if (mMode == MODE_SLIDESHOW) { b.putBoolean("slideshow", true); } } @Override public void onResume() { super.onResume(); init(mSavedUri); // normally this will never be zero but if one "backs" into this // activity after removing the sdcard it could be zero. in that // case just "finish" since there's nothing useful that can happen. int count = mAllImages.getCount(); if (count == 0) { finish(); } else if (count <= mCurrentPosition) { mCurrentPosition = count - 1; } ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); if (mGetter == null) { makeGetter(); } mFirst = true; mScroller.setLayoutCompletedCallback(new Runnable() { public void run() { mLayoutComplete = true; setImage(mCurrentPosition); } }); setImage(mCurrentPosition); setOrientation(); } @Override public void onPause() { super.onPause(); mGetter.cancelCurrent(); mGetter.stop(); mGetter = null; setMode(MODE_NORMAL); // removing all callback in the message queue mHandler.removeAllGetterCallbacks(); mSavedUri = getCurrentUri(); mAllImages.deactivate(); mDismissOnScreenControlsRunnable.run(); if (mDismissOnScreenControlsRunnable != null) mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); for (ImageViewTouch iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } for (ImageViewTouch iv: mSlideShowImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } } public void onClick(View v) { switch (v.getId()) { case R.id.shutter_button: { if (mCameraReviewMode) { finish(); } else { MenuHelper.gotoStillImageCapture(this); } } break; case R.id.gallery: { MenuHelper.gotoCameraImageGallery(this); } break; case R.id.discard: { MenuHelper.deletePhoto(this, mDeletePhotoRunnable); } break; case R.id.share: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); + if (MenuHelper.isMMSUri(u)) return; Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_STREAM, u); try { startActivity(Intent.createChooser(intent, getText(R.string.sendImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_image, Toast.LENGTH_SHORT).show(); } } break; case R.id.setas: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA, u); try { startActivity(Intent.createChooser(intent, getText(R.string.setImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } break; case R.id.next_image: { moveNextOrPrevious(1); } break; case R.id.prev_image: { moveNextOrPrevious(-1); } break; } } private void moveNextOrPrevious(int delta) { int nextImagePos = mCurrentPosition + delta; if ((0 <= nextImagePos) && (nextImagePos < mAllImages.getCount())) { setImage(nextImagePos); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case MenuHelper.RESULT_COMMON_MENU_CROP: if (resultCode == RESULT_OK) { // The CropImage activity passes back the Uri of the cropped image as // the Action rather than the Data. mSavedUri = Uri.parse(data.getAction()); } break; } } static class LocalHandler extends Handler { private static final int IMAGE_GETTER_CALLBACK = 1; @Override public void handleMessage(Message message) { switch(message.what) { case IMAGE_GETTER_CALLBACK: ((Runnable) message.obj).run(); } } public void postGetterCallback(Runnable callback) { postDelayedGetterCallback(callback, 0); } public void postDelayedGetterCallback(Runnable callback, long delay) { if (callback == null) throw new NullPointerException(); Message message = Message.obtain(); message.what = IMAGE_GETTER_CALLBACK; message.obj = callback; sendMessageDelayed(message, delay); } public void removeAllGetterCallbacks() { removeMessages(IMAGE_GETTER_CALLBACK); } } }
brunsky/WS171-packages-apps-Camera
d0d2260f0eca42ad50f7f81fa68418c049144b71
Automated import from //branches/cupcake/...@142516,142516
diff --git a/src/com/android/camera/MenuHelper.java b/src/com/android/camera/MenuHelper.java index ed5803c..9fae480 100644 --- a/src/com/android/camera/MenuHelper.java +++ b/src/com/android/camera/MenuHelper.java @@ -1,733 +1,733 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.io.Closeable; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.StatFs; import android.provider.MediaStore; import android.provider.MediaStore.Images; import android.util.Config; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.MenuItem.OnMenuItemClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.camera.ImageManager.IImage; public class MenuHelper { static private final String TAG = "MenuHelper"; static public final int GENERIC_ITEM = 1; static public final int IMAGE_SAVING_ITEM = 2; static public final int VIDEO_SAVING_ITEM = 3; static public final int IMAGE_MODE_ITEM = 4; static public final int VIDEO_MODE_ITEM = 5; static public final int MENU_ITEM_MAX = 5; static public final int INCLUDE_ALL = 0xFFFFFFFF; static public final int INCLUDE_VIEWPLAY_MENU = (1 << 0); static public final int INCLUDE_SHARE_MENU = (1 << 1); static public final int INCLUDE_SET_MENU = (1 << 2); static public final int INCLUDE_CROP_MENU = (1 << 3); static public final int INCLUDE_DELETE_MENU = (1 << 4); static public final int INCLUDE_ROTATE_MENU = (1 << 5); - static public final int INCLUDE_DETAILS_MENU = (1 << 5); + static public final int INCLUDE_DETAILS_MENU = (1 << 6); static public final int MENU_SWITCH_CAMERA_MODE = 0; static public final int MENU_CAPTURE_PICTURE = 1; static public final int MENU_CAPTURE_VIDEO = 2; static public final int MENU_IMAGE_SHARE = 10; static public final int MENU_IMAGE_SET = 14; static public final int MENU_IMAGE_SET_WALLPAPER = 15; static public final int MENU_IMAGE_SET_CONTACT = 16; static public final int MENU_IMAGE_SET_MYFAVE = 17; static public final int MENU_IMAGE_CROP = 18; static public final int MENU_IMAGE_ROTATE = 19; static public final int MENU_IMAGE_ROTATE_LEFT = 20; static public final int MENU_IMAGE_ROTATE_RIGHT = 21; static public final int MENU_IMAGE_TOSS = 22; static public final int MENU_VIDEO_PLAY = 23; static public final int MENU_VIDEO_SHARE = 24; static public final int MENU_VIDEO_TOSS = 27; static private final long SHARE_FILE_LENGTH_LIMIT = 3L * 1024L * 1024L; public static final int NO_STORAGE_ERROR = -1; public static final int CANNOT_STAT_ERROR = -2; /** Activity result code used to report crop results. */ public static final int RESULT_COMMON_MENU_CROP = 490; public interface MenuItemsResult { public void gettingReadyToOpen(Menu menu, ImageManager.IImage image); public void aboutToCall(MenuItem item, ImageManager.IImage image); } public interface MenuInvoker { public void run(MenuCallback r); } public interface MenuCallback { public void run(Uri uri, ImageManager.IImage image); } private static void closeSilently(Closeable target) { try { if (target != null) target.close(); } catch (Throwable t) { // ignore all exceptions, that's what silently means } } public static long getImageFileSize(ImageManager.IImage image) { java.io.InputStream data = image.fullSizeImageData(); if (data == null) return -1; try { return data.available(); } catch (java.io.IOException ex) { return -1; } finally { closeSilently(data); } } static MenuItemsResult addImageMenuItems( Menu menu, int inclusions, final boolean isImage, final Activity activity, final Handler handler, final Runnable onDelete, final MenuInvoker onInvoke) { final ArrayList<MenuItem> requiresWriteAccessItems = new ArrayList<MenuItem>(); final ArrayList<MenuItem> requiresNoDrmAccessItems = new ArrayList<MenuItem>(); if (isImage && ((inclusions & INCLUDE_ROTATE_MENU) != 0)) { SubMenu rotateSubmenu = menu.addSubMenu(IMAGE_SAVING_ITEM, MENU_IMAGE_ROTATE, 40, R.string.rotate).setIcon(android.R.drawable.ic_menu_rotate); // Don't show the rotate submenu if the item at hand is read only // since the items within the submenu won't be shown anyway. This is // really a framework bug in that it shouldn't show the submenu if // the submenu has no visible items. requiresWriteAccessItems.add(rotateSubmenu.getItem()); if (rotateSubmenu != null) { requiresWriteAccessItems.add(rotateSubmenu.add(0, MENU_IMAGE_ROTATE_LEFT, 50, R.string.rotate_left).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null || image.isReadonly()) return; image.rotateImageBy(-90); } }); return true; } }).setAlphabeticShortcut('l')); requiresWriteAccessItems.add(rotateSubmenu.add(0, MENU_IMAGE_ROTATE_RIGHT, 60, R.string.rotate_right).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null || image.isReadonly()) return; image.rotateImageBy(90); } }); return true; } }).setAlphabeticShortcut('r')); } } if (isImage && ((inclusions & INCLUDE_CROP_MENU) != 0)) { MenuItem autoCrop = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_CROP, 73, R.string.camera_crop).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (u == null) return; Intent cropIntent = new Intent(); cropIntent.setClass(activity, CropImage.class); cropIntent.setData(u); activity.startActivityForResult(cropIntent, RESULT_COMMON_MENU_CROP); } }); return true; } }); autoCrop.setIcon(android.R.drawable.ic_menu_crop); requiresWriteAccessItems.add(autoCrop); } if (isImage && ((inclusions & INCLUDE_SET_MENU) != 0)) { MenuItem setMenu = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_SET, 75, R.string.camera_set); setMenu.setIcon(android.R.drawable.ic_menu_set_as); setMenu.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (u == null || image == null) return; if (Config.LOGV) Log.v(TAG, "in callback u is " + u + "; mime type is " + image.getMimeType()); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA); intent.setDataAndType(u, image.getMimeType()); intent.putExtra("mimeType", image.getMimeType()); activity.startActivity(Intent.createChooser(intent, activity.getText(R.string.setImage))); } }); return true; } }); } if ((inclusions & INCLUDE_SHARE_MENU) != 0) { if (Config.LOGV) Log.v(TAG, ">>>>> add share"); MenuItem item1 = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_SHARE, 10, R.string.camera_share).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null) return; if (!isImage && getImageFileSize(image) > SHARE_FILE_LENGTH_LIMIT ) { Toast.makeText(activity, R.string.too_large_to_attach, Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); String mimeType = image.getMimeType(); intent.setType(mimeType); intent.putExtra(Intent.EXTRA_STREAM, u); boolean isImage = ImageManager.isImageMimeType(mimeType); try { activity.startActivity(Intent.createChooser(intent, activity.getText( isImage ? R.string.sendImage : R.string.sendVideo))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(activity, isImage ? R.string.no_way_to_share_image : R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } }); return true; } }); item1.setIcon(android.R.drawable.ic_menu_share); MenuItem item = item1; requiresNoDrmAccessItems.add(item); } if ((inclusions & INCLUDE_DELETE_MENU) != 0) { MenuItem deleteItem = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_TOSS, 70, R.string.camera_toss); requiresWriteAccessItems.add(deleteItem); deleteItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { deleteImpl(activity, onDelete, isImage); return true; } }) .setAlphabeticShortcut('d') .setIcon(android.R.drawable.ic_menu_delete); } if ((inclusions & INCLUDE_DETAILS_MENU) != 0) { MenuItem detailsMenu = menu.add(0, 0, 80, R.string.details).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null) return; AlertDialog.Builder builder = new AlertDialog.Builder(activity); final View d = View.inflate(activity, R.layout.detailsview, null); ImageView imageView = (ImageView) d.findViewById(R.id.details_thumbnail_image); imageView.setImageBitmap(image.miniThumbBitmap()); TextView textView = (TextView) d.findViewById(R.id.details_image_title); textView.setText(image.getDisplayName()); long length = getImageFileSize(image); String lengthString = lengthString = length < 0 ? "" : android.text.format.Formatter.formatFileSize(activity, length); ((TextView)d.findViewById(R.id.details_file_size_value)) .setText(lengthString); int dimensionWidth = 0; int dimensionHeight = 0; if (isImage) { dimensionWidth = image.getWidth(); dimensionHeight = image.getHeight(); d.findViewById(R.id.details_duration_row).setVisibility(View.GONE); d.findViewById(R.id.details_frame_rate_row).setVisibility(View.GONE); d.findViewById(R.id.details_bit_rate_row).setVisibility(View.GONE); d.findViewById(R.id.details_format_row).setVisibility(View.GONE); d.findViewById(R.id.details_codec_row).setVisibility(View.GONE); } else { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setMode(MediaMetadataRetriever.MODE_GET_METADATA_ONLY); retriever.setDataSource(image.getDataPath()); try { dimensionWidth = Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)); dimensionHeight = Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); } catch (NumberFormatException e) { dimensionWidth = 0; dimensionHeight = 0; } try { int durationMs = Integer.parseInt(retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_DURATION)); String durationValue = formatDuration( activity, durationMs); ((TextView)d.findViewById(R.id.details_duration_value)) .setText(durationValue); } catch (NumberFormatException e) { d.findViewById(R.id.details_frame_rate_row) .setVisibility(View.GONE); } try { String frame_rate = String.format( activity.getString(R.string.details_fps), Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_FRAME_RATE))); ((TextView)d.findViewById(R.id.details_frame_rate_value)) .setText(frame_rate); } catch (NumberFormatException e) { d.findViewById(R.id.details_frame_rate_row) .setVisibility(View.GONE); } try { long bitRate = Long.parseLong(retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_BIT_RATE)); String bps; if (bitRate < 1000000) { bps = String.format( activity.getString(R.string.details_kbps), bitRate / 1000); } else { bps = String.format( activity.getString(R.string.details_mbps), ((double) bitRate) / 1000000.0); } ((TextView)d.findViewById(R.id.details_bit_rate_value)) .setText(bps); } catch (NumberFormatException e) { d.findViewById(R.id.details_bit_rate_row) .setVisibility(View.GONE); } String format = retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_FORMAT); ((TextView)d.findViewById(R.id.details_format_value)) .setText(format); String codec = retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_CODEC); if (codec == null) { d.findViewById(R.id.details_codec_row). setVisibility(View.GONE); } else { ((TextView)d.findViewById(R.id.details_codec_value)) .setText(codec); } } catch(RuntimeException ex) { // Assume this is a corrupt video file. } finally { try { retriever.release(); } catch (RuntimeException ex) { // Ignore failures while cleaning up. } } } String dimensionsString = String.format( activity.getString(R.string.details_dimension_x), dimensionWidth, dimensionHeight); ((TextView)d.findViewById(R.id.details_resolution_value)) .setText(dimensionsString); String dateString = ""; long dateTaken = image.getDateTaken(); if (dateTaken != 0) { java.util.Date date = new java.util.Date(image.getDateTaken()); java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(); dateString = dateFormat.format(date); ((TextView)d.findViewById(R.id.details_date_taken_value)) .setText(dateString); } else { d.findViewById(R.id.details_date_taken_row) .setVisibility(View.GONE); } builder.setNeutralButton(R.string.details_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setIcon(android.R.drawable.ic_dialog_info) .setTitle(R.string.details_panel_title) .setView(d) .show(); } }); return true; } }); detailsMenu.setIcon(R.drawable.ic_menu_view_details); } if ((!isImage) && ((inclusions & INCLUDE_VIEWPLAY_MENU) != 0)) { menu.add(VIDEO_SAVING_ITEM, MENU_VIDEO_PLAY, 0, R.string.video_play) .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri uri, IImage image) { if (image != null) { Intent intent = new Intent(Intent.ACTION_VIEW, image.fullSizeImageUri()); activity.startActivity(intent); } }}); return true; } }); } return new MenuItemsResult() { public void gettingReadyToOpen(Menu menu, ImageManager.IImage image) { // protect against null here. this isn't strictly speaking required // but if a client app isn't handling sdcard removal properly it // could happen if (image == null) { return; } boolean readOnly = image.isReadonly(); boolean isDrm = image.isDrm(); if (Config.LOGV) Log.v(TAG, "readOnly: " + readOnly + "; drm: " + isDrm); for (MenuItem item: requiresWriteAccessItems) { if (Config.LOGV) Log.v(TAG, "item is " + item.toString()); item.setVisible(!readOnly); item.setEnabled(!readOnly); } for (MenuItem item: requiresNoDrmAccessItems) { if (Config.LOGV) Log.v(TAG, "item is " + item.toString()); item.setVisible(!isDrm); item.setEnabled(!isDrm); } } public void aboutToCall(MenuItem menu, ImageManager.IImage image) { } }; } static void deletePhoto(Activity activity, Runnable onDelete) { deleteImpl(activity, onDelete, true); } - + static void deleteVideo(Activity activity, Runnable onDelete) { deleteImpl(activity, onDelete, false); } static void deleteImage(Activity activity, Runnable onDelete, IImage image) { if (image != null) { deleteImpl(activity, onDelete, ImageManager.isImage(image)); } } private static void deleteImpl(Activity activity, final Runnable onDelete, boolean isPhoto) { boolean confirm = android.preference.PreferenceManager.getDefaultSharedPreferences(activity).getBoolean("pref_gallery_confirm_delete_key", true); if (!confirm) { if (onDelete != null) onDelete.run(); } else { displayDeleteDialog(activity, onDelete, isPhoto); } } public static void displayDeleteDialog(Activity activity, final Runnable onDelete, boolean isPhoto) { android.app.AlertDialog.Builder b = new android.app.AlertDialog.Builder(activity); b.setIcon(android.R.drawable.ic_dialog_alert); b.setTitle(R.string.confirm_delete_title); b.setMessage(isPhoto? R.string.confirm_delete_message : R.string.confirm_delete_video_message); b.setPositiveButton(android.R.string.ok, new android.content.DialogInterface.OnClickListener() { public void onClick(android.content.DialogInterface v, int x) { if (onDelete != null) onDelete.run(); } }); b.setNegativeButton(android.R.string.cancel, new android.content.DialogInterface.OnClickListener() { public void onClick(android.content.DialogInterface v, int x) { } }); b.create().show(); } static void addSwitchModeMenuItem(Menu menu, final Activity activity, final boolean switchToVideo) { int group = switchToVideo ? MenuHelper.IMAGE_MODE_ITEM : MenuHelper.VIDEO_MODE_ITEM; int labelId = switchToVideo ? R.string.switch_to_video_lable : R.string.switch_to_camera_lable; int iconId = switchToVideo ? R.drawable.ic_menu_camera_video_view : android.R.drawable.ic_menu_camera; MenuItem item = menu.add(group, MENU_SWITCH_CAMERA_MODE, 0, labelId).setOnMenuItemClickListener( new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { String action = switchToVideo ? MediaStore.INTENT_ACTION_VIDEO_CAMERA : MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA; Intent intent = new Intent(action); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); - activity.finish(); activity.startActivity(intent); return true; } }); item.setIcon(iconId); } static void gotoStillImageCapture(Activity activity) { Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Log.e(TAG, "Could not start still image capture activity", e); } } static void gotoCameraImageGallery(Activity activity) { gotoGallery(activity, R.string.gallery_camera_bucket_name, ImageManager.INCLUDE_IMAGES); } static void gotoCameraVideoGallery(Activity activity) { gotoGallery(activity, R.string.gallery_camera_videos_bucket_name, ImageManager.INCLUDE_VIDEOS); } static private void gotoGallery(Activity activity, int windowTitleId, int mediaTypes) { Uri target = Images.Media.INTERNAL_CONTENT_URI.buildUpon().appendQueryParameter("bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build(); Intent intent = new Intent(Intent.ACTION_VIEW, target); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("windowTitle", activity.getString(windowTitleId)); intent.putExtra("mediaTypes", mediaTypes); // Request unspecified so that we match the current camera orientation rather than // matching the "flip orientation" preference. // Disabled because people don't care for it. Also it's // not as compelling now that we have implemented have quick orientation flipping. // intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, // android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Log.e(TAG, "Could not start gallery activity", e); } } static void addCapturePictureMenuItems(Menu menu, final Activity activity) { menu.add(0, MENU_CAPTURE_PICTURE, 1, R.string.capture_picture) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { activity.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { // Ignore exception } return true; } }) .setIcon(android.R.drawable.ic_menu_camera); } static void addCaptureVideoMenuItems(Menu menu, final Activity activity) { menu.add(0, MENU_CAPTURE_VIDEO, 2, R.string.capture_video) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { activity.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { // Ignore exception } return true; } }) .setIcon(R.drawable.ic_menu_camera_video_view); } static void addCaptureMenuItems(Menu menu, final Activity activity) { addCapturePictureMenuItems(menu, activity); addCaptureVideoMenuItems(menu, activity); } static MenuItem addFlipOrientation(Menu menu, final Activity activity, final SharedPreferences prefs) { // position 41 after rotate // D return menu .add(Menu.CATEGORY_SECONDARY, 304, 41, R.string.flip_orientation) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // Check what our actual orientation is int current = activity.getResources().getConfiguration().orientation; int newOrientation = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; if (current == Configuration.ORIENTATION_LANDSCAPE) { newOrientation = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; } SharedPreferences.Editor editor = prefs.edit(); editor.putInt("nuorientation", newOrientation); editor.commit(); requestOrientation(activity, prefs, true); return true; } }) .setIcon(android.R.drawable.ic_menu_always_landscape_portrait); } static void requestOrientation(Activity activity, SharedPreferences prefs) { requestOrientation(activity, prefs, false); } static private void requestOrientation(Activity activity, SharedPreferences prefs, boolean ignoreIntentExtra) { // Disable orientation for now. If it is set to SCREEN_ORIENTATION_SENSOR, // a duplicated orientation will be observed. return; } static void setFlipOrientationEnabled(Activity activity, MenuItem flipItem) { int keyboard = activity.getResources().getConfiguration().hardKeyboardHidden; flipItem.setEnabled(keyboard != android.content.res.Configuration.HARDKEYBOARDHIDDEN_NO); } public static String formatDuration(final Activity activity, int durationMs) { int duration = durationMs / 1000; int h = duration / 3600; int m = (duration - h * 3600) / 60; int s = duration - (h * 3600 + m * 60); String durationValue; if (h == 0) { durationValue = String.format( activity.getString(R.string.details_ms), m, s); } else { durationValue = String.format( activity.getString(R.string.details_hms), h, m, s); } return durationValue; } public static void showStorageToast(Activity activity) { showStorageToast(activity, calculatePicturesRemaining()); } public static void showStorageToast(Activity activity, int remaining) { String noStorageText = null; if (remaining == MenuHelper.NO_STORAGE_ERROR) { String state = Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING) { noStorageText = activity.getString(R.string.preparing_sd); } else { noStorageText = activity.getString(R.string.no_storage); } } else if (remaining < 1) { noStorageText = activity.getString(R.string.not_enough_space); } if (noStorageText != null) { Toast.makeText(activity, noStorageText, 5000).show(); } } public static int calculatePicturesRemaining() { try { if (!ImageManager.hasStorage()) { return NO_STORAGE_ERROR; } else { String storageDirectory = Environment.getExternalStorageDirectory().toString(); StatFs stat = new StatFs(storageDirectory); float remaining = ((float)stat.getAvailableBlocks() * (float)stat.getBlockSize()) / 400000F; return (int)remaining; } } catch (Exception ex) { // if we can't stat the filesystem then we don't know how many // pictures are remaining. it might be zero but just leave it // blank since we really don't know. return CANNOT_STAT_ERROR; } } } diff --git a/src/com/android/camera/VideoCamera.java b/src/com/android/camera/VideoCamera.java index 776755f..186d827 100644 --- a/src/com/android/camera/VideoCamera.java +++ b/src/com/android/camera/VideoCamera.java @@ -1,1189 +1,1191 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; -import android.database.Cursor; +import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.location.LocationManager; import android.media.MediaRecorder; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.StatFs; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.MediaStore.Video; import android.text.format.DateFormat; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.MenuItem.OnMenuItemClickListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class VideoCamera extends Activity implements View.OnClickListener, ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback, MediaRecorder.OnErrorListener, MediaRecorder.OnInfoListener { private static final String TAG = "videocamera"; private static final boolean DEBUG = true; private static final boolean DEBUG_SUPPRESS_AUDIO_RECORDING = DEBUG && false; private static final int CLEAR_SCREEN_DELAY = 4; private static final int UPDATE_RECORD_TIME = 5; private static final int SCREEN_DELAY = 2 * 60 * 1000; private static final long NO_STORAGE_ERROR = -1L; private static final long CANNOT_STAT_ERROR = -2L; private static final long LOW_STORAGE_THRESHOLD = 512L * 1024L; private static final long SHARE_FILE_LENGTH_LIMIT = 3L * 1024L * 1024L; private static final int STORAGE_STATUS_OK = 0; private static final int STORAGE_STATUS_LOW = 1; private static final int STORAGE_STATUS_NONE = 2; public static final int MENU_SETTINGS = 6; public static final int MENU_GALLERY_PHOTOS = 7; public static final int MENU_GALLERY_VIDEOS = 8; public static final int MENU_SAVE_GALLERY_PHOTO = 34; public static final int MENU_SAVE_PLAY_VIDEO = 35; public static final int MENU_SAVE_SELECT_VIDEO = 36; public static final int MENU_SAVE_NEW_VIDEO = 37; SharedPreferences mPreferences; private static final float VIDEO_ASPECT_RATIO = 176.0f / 144.0f; VideoPreview mVideoPreview; SurfaceHolder mSurfaceHolder = null; ImageView mVideoFrame; private boolean mIsVideoCaptureIntent; // mLastPictureButton and mThumbController // are non-null only if isVideoCaptureIntent() is true; private ImageView mLastPictureButton; private ThumbnailController mThumbController; private static final int MAX_RECORDING_DURATION_MS = 10 * 60 * 1000; private int mStorageStatus = STORAGE_STATUS_OK; private MediaRecorder mMediaRecorder; private boolean mMediaRecorderRecording = false; private long mRecordingStartTime; // The video file that the hardware camera is about to record into // (or is recording into.) private String mCameraVideoFilename; private FileDescriptor mCameraVideoFileDescriptor; // The video file that has already been recorded, and that is being // examined by the user. private String mCurrentVideoFilename; private long mCurrentVideoFileLength = 0L; private Uri mCurrentVideoUri; private ContentValues mCurrentVideoValues; boolean mPausing = false; static ContentResolver mContentResolver; int mCurrentZoomIndex = 0; private ShutterButton mShutterButton; private TextView mRecordingTimeView; private boolean mRecordingTimeCountsDown = false; ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>(); View mPostPictureAlert; LocationManager mLocationManager = null; private Handler mHandler = new MainHandler(); /** This Handler is used to post message back onto the main thread of the application */ private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case CLEAR_SCREEN_DELAY: { clearScreenOnFlag(); break; } case UPDATE_RECORD_TIME: { if (mMediaRecorderRecording) { long now = SystemClock.uptimeMillis(); long delta = now - mRecordingStartTime; // Starting a minute before reaching the max duration // limit, we'll countdown the remaining time instead. boolean countdown_remaining_time = (delta >= MAX_RECORDING_DURATION_MS - 60000); if (countdown_remaining_time) { delta = Math.max(0, MAX_RECORDING_DURATION_MS - delta); } long seconds = (delta + 500) / 1000; // round to nearest long minutes = seconds / 60; long hours = minutes / 60; long remainderMinutes = minutes - (hours * 60); long remainderSeconds = seconds - (minutes * 60); String secondsString = Long.toString(remainderSeconds); if (secondsString.length() < 2) { secondsString = "0" + secondsString; } String minutesString = Long.toString(remainderMinutes); if (minutesString.length() < 2) { minutesString = "0" + minutesString; } String text = minutesString + ":" + secondsString; if (hours > 0) { String hoursString = Long.toString(hours); if (hoursString.length() < 2) { hoursString = "0" + hoursString; } text = hoursString + ":" + text; } mRecordingTimeView.setText(text); if (mRecordingTimeCountsDown != countdown_remaining_time) { // Avoid setting the color on every update, do it only // when it needs changing. mRecordingTimeCountsDown = countdown_remaining_time; int color = getResources().getColor( countdown_remaining_time ? R.color.recording_time_remaining_text : R.color.recording_time_elapsed_text); mRecordingTimeView.setTextColor(color); } // Work around a limitation of the T-Mobile G1: The T-Mobile // hardware blitter can't pixel-accurately scale and clip at the same time, // and the SurfaceFlinger doesn't attempt to work around this limitation. // In order to avoid visual corruption we must manually refresh the entire // surface view when changing any overlapping view's contents. mVideoPreview.invalidate(); mHandler.sendEmptyMessageDelayed(UPDATE_RECORD_TIME, 1000); } break; } default: Log.v(TAG, "Unhandled message: " + msg.what); break; } } }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_EJECT)) { updateAndShowStorageHint(false); stopVideoRecording(); initializeVideo(); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { updateAndShowStorageHint(true); initializeVideo(); } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) { // SD card unavailable // handled in ACTION_MEDIA_EJECT } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { Toast.makeText(VideoCamera.this, getResources().getString(R.string.wait), 5000); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { updateAndShowStorageHint(true); } } }; static private String createName(long dateTaken) { return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString(); } /** Called with the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mContentResolver = getContentResolver(); //setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.video_camera); mVideoPreview = (VideoPreview) findViewById(R.id.camera_preview); mVideoPreview.setAspectRatio(VIDEO_ASPECT_RATIO); // don't set mSurfaceHolder here. We have it set ONLY within // surfaceCreated / surfaceDestroyed, other parts of the code // assume that when it is set, the surface is also set. SurfaceHolder holder = mVideoPreview.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mPostPictureAlert = findViewById(R.id.post_picture_panel); int[] ids = new int[]{R.id.play, R.id.share, R.id.discard, R.id.cancel, R.id.attach}; for (int id : ids) { findViewById(id).setOnClickListener(this); } mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); mRecordingTimeView = (TextView) findViewById(R.id.recording_time); mVideoFrame = (ImageView) findViewById(R.id.video_frame); mIsVideoCaptureIntent = isVideoCaptureIntent(); if (!mIsVideoCaptureIntent) { mLastPictureButton = (ImageView) findViewById(R.id.last_picture_button); mLastPictureButton.setOnClickListener(this); Drawable frame = getResources().getDrawable(R.drawable.frame_thumbnail); mThumbController = new ThumbnailController(mLastPictureButton, frame, mContentResolver); mThumbController.loadData(ImageManager.getLastVideoThumbPath()); } } private void startShareVideoActivity() { if (mCurrentVideoFileLength > SHARE_FILE_LENGTH_LIMIT) { Toast.makeText(VideoCamera.this, R.string.too_large_to_attach, Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("video/3gpp"); intent.putExtra(Intent.EXTRA_STREAM, mCurrentVideoUri); try { startActivity(Intent.createChooser(intent, getText(R.string.sendVideo))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(VideoCamera.this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } public void onClick(View v) { switch (v.getId()) { case R.id.gallery: MenuHelper.gotoCameraVideoGallery(this); break; case R.id.attach: doReturnToCaller(true); break; case R.id.cancel: doReturnToCaller(false); break; case R.id.discard: { Runnable deleteCallback = new Runnable() { public void run() { discardCurrentVideoAndStartPreview(); } }; MenuHelper.deleteVideo(this, deleteCallback); break; } case R.id.share: { startShareVideoActivity(); break; } case R.id.play: { doPlayCurrentVideo(); break; } case R.id.last_picture_button: { stopVideoRecordingAndShowAlert(); break; } } } public void onShutterButtonFocus(ShutterButton button, boolean pressed) { // Do nothing (everything happens in onShutterButtonClick). } public void onShutterButtonClick(ShutterButton button) { switch (button.getId()) { case R.id.shutter_button: if (mMediaRecorderRecording) { if (mIsVideoCaptureIntent) { stopVideoRecordingAndShowAlert(); } else { stopVideoRecordingAndGetThumbnail(); initializeVideo(); } } else if (isAlertVisible()) { if (mIsVideoCaptureIntent) { discardCurrentVideoAndStartPreview(); } else { hideAlertAndStartVideoRecording(); } } else { startVideoRecording(); } break; } } private void doPlayCurrentVideo() { Log.e(TAG, "Playing current video: " + mCurrentVideoUri); Intent intent = new Intent(Intent.ACTION_VIEW, mCurrentVideoUri); try { startActivity(intent); } catch (android.content.ActivityNotFoundException ex) { Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex); } } private void discardCurrentVideoAndStartPreview() { deleteCurrentVideo(); hideAlertAndStartPreview(); } private OnScreenHint mStorageHint; private void updateAndShowStorageHint(boolean mayHaveSd) { mStorageStatus = getStorageStatus(mayHaveSd); showStorageHint(); } private void showStorageHint() { String errorMessage = null; switch (mStorageStatus) { case STORAGE_STATUS_NONE: errorMessage = getString(R.string.no_storage); break; case STORAGE_STATUS_LOW: errorMessage = getString(R.string.spaceIsLow_content); } if (errorMessage != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, errorMessage); } else { mStorageHint.setText(errorMessage); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } private int getStorageStatus(boolean mayHaveSd) { long remaining = mayHaveSd ? getAvailableStorage() : NO_STORAGE_ERROR; if (remaining == NO_STORAGE_ERROR) { return STORAGE_STATUS_NONE; } return remaining < LOW_STORAGE_THRESHOLD ? STORAGE_STATUS_LOW : STORAGE_STATUS_OK; } @Override public void onResume() { super.onResume(); setScreenTimeoutLong(); mPausing = false; // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_EJECT); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); mStorageStatus = getStorageStatus(true); mHandler.postDelayed(new Runnable() { public void run() { showStorageHint(); } }, 200); initializeVideo(); } @Override public void onStop() { setScreenTimeoutSystemDefault(); super.onStop(); } @Override protected void onPause() { super.onPause(); // This is similar to what mShutterButton.performClick() does, // but not quite the same. if (mMediaRecorderRecording) { if (mIsVideoCaptureIntent) { stopVideoRecordingAndShowAlert(); } else { stopVideoRecordingAndGetThumbnail(); } } else { stopVideoRecording(); } mPausing = true; unregisterReceiver(mReceiver); setScreenTimeoutSystemDefault(); if (!mIsVideoCaptureIntent) { mThumbController.storeData(ImageManager.getLastVideoThumbPath()); } - + if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { setScreenTimeoutLong(); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mMediaRecorderRecording) { mShutterButton.performClick(); return true; } else if(isAlertVisible()) { hideAlertAndStartPreview(); return true; } break; case KeyEvent.KEYCODE_CAMERA: if (event.getRepeatCount() == 0) { mShutterButton.performClick(); return true; } break; case KeyEvent.KEYCODE_DPAD_CENTER: if (event.getRepeatCount() == 0) { mShutterButton.performClick(); return true; } break; case KeyEvent.KEYCODE_MENU: if (mMediaRecorderRecording) { mShutterButton.performClick(); return true; } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_CAMERA: mShutterButton.setPressed(false); return true; } return super.onKeyUp(keyCode, event); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { if (mPausing) { // We're pausing, the screen is off and we already stopped // video recording. We don't want to start the camera again // in this case in order to conserve power. // The fact that surfaceChanged is called _after_ an onPause appears // to be legitimate since in that case the lockscreen always returns // to portrait orientation possibly triggering the notification. return; } stopVideoRecording(); initializeVideo(); } public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; } public void surfaceDestroyed(SurfaceHolder holder) { mSurfaceHolder = null; } void gotoGallery() { MenuHelper.gotoCameraVideoGallery(this); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); for (int i = 1; i <= MenuHelper.MENU_ITEM_MAX; i++) { if (i != MenuHelper.GENERIC_ITEM) { menu.setGroupVisible(i, false); } } menu.setGroupVisible(MenuHelper.VIDEO_MODE_ITEM, true); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (mIsVideoCaptureIntent) { // No options menu for attach mode. return false; } else { addBaseMenuItems(menu); + int menuFlags = MenuHelper.INCLUDE_ALL & ~MenuHelper.INCLUDE_ROTATE_MENU + & ~MenuHelper.INCLUDE_DETAILS_MENU; MenuHelper.addImageMenuItems( menu, - MenuHelper.INCLUDE_ALL & ~MenuHelper.INCLUDE_ROTATE_MENU, + menuFlags, false, VideoCamera.this, mHandler, // Handler for deletion new Runnable() { public void run() { // What do we do here? // mContentResolver.delete(uri, null, null); } }, new MenuHelper.MenuInvoker() { public void run(final MenuHelper.MenuCallback cb) { } }); MenuItem gallery = menu.add(MenuHelper.IMAGE_SAVING_ITEM, MENU_SAVE_GALLERY_PHOTO, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); } return true; } private boolean isVideoCaptureIntent() { String action = getIntent().getAction(); return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action)); } private void doReturnToCaller(boolean success) { Intent resultIntent = new Intent(); int resultCode; if (success) { resultCode = RESULT_OK; resultIntent.setData(mCurrentVideoUri); } else { resultCode = RESULT_CANCELED; } setResult(resultCode, resultIntent); finish(); } /** * Returns * @return number of bytes available, or an ERROR code. */ private static long getAvailableStorage() { try { if (!ImageManager.hasStorage()) { return NO_STORAGE_ERROR; } else { String storageDirectory = Environment.getExternalStorageDirectory().toString(); StatFs stat = new StatFs(storageDirectory); return ((long)stat.getAvailableBlocks() * (long)stat.getBlockSize()); } } catch (Exception ex) { // if we can't stat the filesystem then we don't know how many // free bytes exist. It might be zero but just leave it // blank since we really don't know. return CANNOT_STAT_ERROR; } } private void cleanupEmptyFile() { if (mCameraVideoFilename != null) { File f = new File(mCameraVideoFilename); if (f.length() == 0 && f.delete()) { Log.v(TAG, "Empty video file deleted: " + mCameraVideoFilename); mCameraVideoFilename = null; } } } // initializeVideo() starts preview and prepare media recorder. // Returns false if initializeVideo fails private boolean initializeVideo() { Log.v(TAG, "initializeVideo"); // We will call initializeVideo() again when the alert is hidden. if (isAlertVisible()) return false; Intent intent = getIntent(); Bundle myExtras = intent.getExtras(); if (mIsVideoCaptureIntent && myExtras != null) { Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); if (saveUri != null) { try { mCameraVideoFileDescriptor = mContentResolver. openFileDescriptor(saveUri, "rw").getFileDescriptor(); mCurrentVideoUri = saveUri; } catch (java.io.FileNotFoundException ex) { // invalid uri Log.e(TAG, ex.toString()); } } } releaseMediaRecorder(); if (mSurfaceHolder == null) { Log.v(TAG, "SurfaceHolder is null"); return false; } mMediaRecorder = new MediaRecorder(); if (DEBUG_SUPPRESS_AUDIO_RECORDING) { Log.v(TAG, "DEBUG_SUPPRESS_AUDIO_RECORDING is true."); } else { mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); } mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mMediaRecorder.setMaxDuration(MAX_RECORDING_DURATION_MS); if (mStorageStatus != STORAGE_STATUS_OK) { mMediaRecorder.setOutputFile("/dev/null"); } else { // We try Uri in intent first. If it doesn't work, use our own instead. if (mCameraVideoFileDescriptor != null) { mMediaRecorder.setOutputFile(mCameraVideoFileDescriptor); } else { createVideoPath(); mMediaRecorder.setOutputFile(mCameraVideoFilename); } } boolean videoQualityHigh = getBooleanPreference(CameraSettings.KEY_VIDEO_QUALITY, CameraSettings.DEFAULT_VIDEO_QUALITY_VALUE); if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) { int extraVideoQuality = intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); videoQualityHigh = (extraVideoQuality > 0); } // Use the same frame rate for both, since internally // if the frame rate is too large, it can cause camera to become // unstable. We need to fix the MediaRecorder to disable the support // of setting frame rate for now. mMediaRecorder.setVideoFrameRate(20); if (videoQualityHigh) { mMediaRecorder.setVideoSize(352,288); } else { mMediaRecorder.setVideoSize(176,144); } mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); if (!DEBUG_SUPPRESS_AUDIO_RECORDING) { mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); } mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); long remaining = getAvailableStorage(); // remaining >= LOW_STORAGE_THRESHOLD at this point, reserve a quarter // of that to make it more likely that recording can complete successfully. try { mMediaRecorder.setMaxFileSize(remaining - LOW_STORAGE_THRESHOLD / 4); } catch (RuntimeException exception) { // We are going to ignore failure of setMaxFileSize here, as // a) The composer selected may simply not support it, or // b) The underlying media framework may not handle 64-bit range // on the size restriction. } try { mMediaRecorder.prepare(); } catch (IOException exception) { Log.e(TAG, "prepare failed for " + mCameraVideoFilename); releaseMediaRecorder(); // TODO: add more exception handling logic here return false; } mMediaRecorderRecording = false; if (!mIsVideoCaptureIntent && !mThumbController.isUriValid()) { updateLastVideo(); } if (!mIsVideoCaptureIntent) { mThumbController.updateDisplayIfNeeded(); } return true; } private void releaseMediaRecorder() { Log.v(TAG, "Releasing media recorder."); if (mMediaRecorder != null) { cleanupEmptyFile(); mMediaRecorder.reset(); mMediaRecorder.release(); mMediaRecorder = null; } } private int getIntPreference(String key, int defaultValue) { String s = mPreferences.getString(key, ""); int result = defaultValue; try { result = Integer.parseInt(s); } catch (NumberFormatException e) { // Ignore, result is already the default value. } return result; } private boolean getBooleanPreference(String key, boolean defaultValue) { return getIntPreference(key, defaultValue ? 1 : 0) != 0; } private void createVideoPath() { long dateTaken = System.currentTimeMillis(); String title = createName(dateTaken); String displayName = title + ".3gp"; // Used when emailing. String cameraDirPath = ImageManager.CAMERA_IMAGE_BUCKET_NAME; File cameraDir = new File(cameraDirPath); cameraDir.mkdirs(); SimpleDateFormat dateFormat = new SimpleDateFormat( getString(R.string.video_file_name_format)); Date date = new Date(dateTaken); String filepart = dateFormat.format(date); String filename = cameraDirPath + "/" + filepart + ".3gp"; ContentValues values = new ContentValues(7); values.put(Video.Media.TITLE, title); values.put(Video.Media.DISPLAY_NAME, displayName); values.put(Video.Media.DESCRIPTION, ""); values.put(Video.Media.DATE_TAKEN, dateTaken); values.put(Video.Media.MIME_TYPE, "video/3gpp"); values.put(Video.Media.DATA, filename); mCameraVideoFilename = filename; Log.v(TAG, "Current camera video filename: " + mCameraVideoFilename); mCurrentVideoValues = values; } private void registerVideo() { if (mCameraVideoFileDescriptor == null) { Uri videoTable = Uri.parse("content://media/external/video/media"); mCurrentVideoUri = mContentResolver.insert(videoTable, mCurrentVideoValues); Log.v(TAG, "Current video URI: " + mCurrentVideoUri); } mCurrentVideoValues = null; } private void deleteCurrentVideo() { if (mCurrentVideoFilename != null) { deleteVideoFile(mCurrentVideoFilename); mCurrentVideoFilename = null; } if (mCurrentVideoUri != null) { mContentResolver.delete(mCurrentVideoUri, null, null); mCurrentVideoUri = null; } updateAndShowStorageHint(true); } private void deleteVideoFile(String fileName) { Log.v(TAG, "Deleting video " + fileName); File f = new File(fileName); if (! f.delete()) { Log.v(TAG, "Could not delete " + fileName); } } private void addBaseMenuItems(Menu menu) { MenuHelper.addSwitchModeMenuItem(menu, this, false); { MenuItem gallery = menu.add(MenuHelper.IMAGE_MODE_ITEM, MENU_GALLERY_PHOTOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } { MenuItem gallery = menu.add(MenuHelper.VIDEO_MODE_ITEM, MENU_GALLERY_VIDEOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } MenuItem item = menu.add(MenuHelper.GENERIC_ITEM, MENU_SETTINGS, 0, R.string.settings).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(); intent.setClass(VideoCamera.this, CameraSettings.class); startActivity(intent); return true; } }); item.setIcon(android.R.drawable.ic_menu_preferences); } // from MediaRecorder.OnErrorListener public void onError(MediaRecorder mr, int what, int extra) { if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) { // We may have run out of space on the sdcard. stopVideoRecording(); updateAndShowStorageHint(true); } } // from MediaRecorder.OnInfoListener public void onInfo(MediaRecorder mr, int what, int extra) { if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) { mShutterButton.performClick(); } else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) { mShutterButton.performClick(); updateAndShowStorageHint(true); } } /* * Make sure we're not recording music playing in the background, ask * the MediaPlaybackService to pause playback. */ private void pauseAudioPlayback() { // Shamelessly copied from MediaPlaybackService.java, which // should be public, but isn't. Intent i = new Intent("com.android.music.musicservicecommand"); i.putExtra("command", "pause"); sendBroadcast(i); } private void startVideoRecording() { Log.v(TAG, "startVideoRecording"); if (!mMediaRecorderRecording) { if (mStorageStatus != STORAGE_STATUS_OK) { Log.v(TAG, "Storage issue, ignore the start request"); return; } // Check mMediaRecorder to see whether it is initialized or not. if (mMediaRecorder == null && initializeVideo() == false ) { Log.e(TAG, "Initialize video (MediaRecorder) failed."); return; } pauseAudioPlayback(); try { mMediaRecorder.setOnErrorListener(this); mMediaRecorder.setOnInfoListener(this); mMediaRecorder.start(); // Recording is now started } catch (RuntimeException e) { Log.e(TAG, "Could not start media recorder. ", e); return; } mMediaRecorderRecording = true; mRecordingStartTime = SystemClock.uptimeMillis(); updateRecordingIndicator(true); mRecordingTimeView.setText(""); mRecordingTimeView.setVisibility(View.VISIBLE); mHandler.sendEmptyMessage(UPDATE_RECORD_TIME); setScreenTimeoutInfinite(); hideLastPictureButton(); } } private void updateRecordingIndicator(boolean showRecording) { int drawableId = showRecording ? R.drawable.ic_camera_bar_indicator_record : R.drawable.ic_camera_indicator_video; Drawable drawable = getResources().getDrawable(drawableId); mShutterButton.setImageDrawable(drawable); } private void stopVideoRecordingAndGetThumbnail() { stopVideoRecording(); acquireVideoThumb(); } private void stopVideoRecordingAndShowAlert() { stopVideoRecording(); showAlert(); } private void showAlert() { int[] pickIds = {R.id.attach, R.id.cancel}; int[] normalIds = {R.id.gallery, R.id.share, R.id.discard}; int[] alwaysOnIds = {R.id.play}; int[] hideIds = pickIds; int[] connectIds = normalIds; if (mIsVideoCaptureIntent) { hideIds = normalIds; connectIds = pickIds; } for(int id : hideIds) { mPostPictureAlert.findViewById(id).setVisibility(View.GONE); } ActionMenuButton shareButton = (ActionMenuButton) mPostPictureAlert.findViewById(R.id.share); shareButton.setRestricted( mCurrentVideoFileLength > SHARE_FILE_LENGTH_LIMIT); connectAndFadeIn(connectIds); connectAndFadeIn(alwaysOnIds); hideLastPictureButton(); mPostPictureAlert.setVisibility(View.VISIBLE); // There are two cases we are here: // (1) We are in a capture video intent, and we are reviewing the video - // we just taken. + // we just taken. // (2) The thumbnail button is clicked: we review the video associated // with the thumbnail. // For the second case, we copy the associated URI and filename to // mCurrentVideoUri and mCurrentVideoFilename, so the video frame shown // and the target for actions (play, delete, ...) will be correct. if (!mIsVideoCaptureIntent) { mCurrentVideoUri = mThumbController.getUri(); mCurrentVideoFilename = getDataPath(mCurrentVideoUri); } String path = mCurrentVideoFilename; if (path != null) { Bitmap videoFrame = ImageManager.createVideoThumbnail(path); mVideoFrame.setImageBitmap(videoFrame); mVideoFrame.setVisibility(View.VISIBLE); } } private void hideAlert() { mVideoFrame.setVisibility(View.INVISIBLE); mPostPictureAlert.setVisibility(View.INVISIBLE); showLastPictureButton(); } private void connectAndFadeIn(int[] connectIds) { for(int id : connectIds) { View view = mPostPictureAlert.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.startAnimation(animation); } } private boolean isAlertVisible() { return mPostPictureAlert.getVisibility() == View.VISIBLE; } private void stopVideoRecording() { Log.v(TAG, "stopVideoRecording"); boolean needToRegisterRecording = false; if (mMediaRecorderRecording || mMediaRecorder != null) { if (mMediaRecorderRecording && mMediaRecorder != null) { try { mMediaRecorder.setOnErrorListener(null); mMediaRecorder.setOnInfoListener(null); mMediaRecorder.stop(); } catch (RuntimeException e) { Log.e(TAG, "stop fail: " + e.getMessage()); } mCurrentVideoFilename = mCameraVideoFilename; try { mCurrentVideoFileLength = new File(mCurrentVideoFilename).length(); } catch (RuntimeException e) { Log.e(TAG, "get file length fail: " + e.getMessage()); mCurrentVideoFileLength = 0; } Log.v(TAG, "Setting current video filename: " + mCurrentVideoFilename); needToRegisterRecording = true; mMediaRecorderRecording = false; } releaseMediaRecorder(); updateRecordingIndicator(false); mRecordingTimeView.setVisibility(View.GONE); setScreenTimeoutLong(); } if (needToRegisterRecording && mStorageStatus == STORAGE_STATUS_OK) { registerVideo(); } mCameraVideoFilename = null; mCameraVideoFileDescriptor = null; } private void setScreenTimeoutSystemDefault() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); clearScreenOnFlag(); } private void setScreenTimeoutLong() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); setScreenOnFlag(); mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); } private void setScreenTimeoutInfinite() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); setScreenOnFlag(); } private void clearScreenOnFlag() { Window w = getWindow(); final int keepScreenOnFlag = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; if ((w.getAttributes().flags & keepScreenOnFlag) != 0) { w.clearFlags(keepScreenOnFlag); } } private void setScreenOnFlag() { Window w = getWindow(); final int keepScreenOnFlag = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; if ((w.getAttributes().flags & keepScreenOnFlag) == 0) { w.addFlags(keepScreenOnFlag); } } private void hideAlertAndStartPreview() { hideAlert(); initializeVideo(); } private void hideAlertAndStartVideoRecording() { hideAlert(); startVideoRecording(); } private void acquireVideoThumb() { Bitmap videoFrame = ImageManager.createVideoThumbnail(mCurrentVideoFilename); mThumbController.setData(mCurrentVideoUri, videoFrame); } private void showLastPictureButton() { if (!mIsVideoCaptureIntent) { mLastPictureButton.setVisibility(View.VISIBLE); } } private void hideLastPictureButton() { if (!mIsVideoCaptureIntent) { mLastPictureButton.setVisibility(View.INVISIBLE); } } private static ImageManager.DataLocation dataLocation() { return ImageManager.DataLocation.EXTERNAL; } private void updateLastVideo() { ImageManager.IImageList list = ImageManager.instance().allImages( this, mContentResolver, dataLocation(), ImageManager.INCLUDE_VIDEOS, ImageManager.SORT_ASCENDING, ImageManager.CAMERA_IMAGE_BUCKET_ID); int count = list.getCount(); if (count > 0) { ImageManager.IImage image = list.getImageAt(count-1); Uri uri = image.fullSizeImageUri(); mThumbController.setData(uri, image.miniThumbBitmap()); } else { mThumbController.setData(null, null); } list.deactivate(); } private static final String[] DATA_PATH_PROJECTION = new String[] { "_data" }; private String getDataPath(Uri uri) { Cursor c = null; try { c = mContentResolver.query(uri, DATA_PATH_PROJECTION, null, null, null); if (c != null && c.moveToFirst()) { return c.getString(0); } else { return null; } } finally { if (c != null) c.close(); } } }
brunsky/WS171-packages-apps-Camera
46310cea4aa3943fd8cd8471405922e489895270
Automated import from //branches/cupcake/...@142187,142187
diff --git a/src/com/android/camera/Camera.java b/src/com/android/camera/Camera.java index 9cb30c9..46620f4 100644 --- a/src/com/android/camera/Camera.java +++ b/src/com/android/camera/Camera.java @@ -1,1595 +1,1614 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.hardware.Camera.PictureCallback; import android.hardware.Camera.Size; import android.location.Location; import android.location.LocationManager; import android.location.LocationProvider; import android.media.AudioManager; import android.media.ToneGenerator; import android.net.Uri; import android.os.Bundle; import android.os.Debug; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.text.format.DateFormat; import android.util.Config; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.OrientationEventListener; import android.view.SurfaceHolder; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.Toast; public class Camera extends Activity implements View.OnClickListener, ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback { private static final String TAG = "camera"; private static final boolean DEBUG = false; private static final boolean DEBUG_TIME_OPERATIONS = DEBUG && false; private static final int CROP_MSG = 1; private static final int RESTART_PREVIEW = 3; private static final int CLEAR_SCREEN_DELAY = 4; private static final int SCREEN_DELAY = 2 * 60 * 1000; private static final int FOCUS_BEEP_VOLUME = 100; public static final int MENU_SWITCH_TO_VIDEO = 0; public static final int MENU_SWITCH_TO_CAMERA = 1; public static final int MENU_FLASH_SETTING = 2; public static final int MENU_FLASH_AUTO = 3; public static final int MENU_FLASH_ON = 4; public static final int MENU_FLASH_OFF = 5; public static final int MENU_SETTINGS = 6; public static final int MENU_GALLERY_PHOTOS = 7; public static final int MENU_GALLERY_VIDEOS = 8; public static final int MENU_SAVE_SELECT_PHOTOS = 30; public static final int MENU_SAVE_NEW_PHOTO = 31; public static final int MENU_SAVE_GALLERY_PHOTO = 34; public static final int MENU_SAVE_GALLERY_VIDEO_PHOTO = 35; public static final int MENU_SAVE_CAMERA_DONE = 36; public static final int MENU_SAVE_CAMERA_VIDEO_DONE = 37; private OrientationEventListener mOrientationListener; private int mLastOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; private SharedPreferences mPreferences; private static final int IDLE = 1; private static final int SNAPSHOT_IN_PROGRESS = 2; private static final int SNAPSHOT_COMPLETED = 3; private int mStatus = IDLE; private static final String sTempCropFilename = "crop-temp"; private android.hardware.Camera mCameraDevice; private android.hardware.Camera.Parameters mParameters; private VideoPreview mSurfaceView; private SurfaceHolder mSurfaceHolder = null; private int mOriginalViewFinderWidth, mOriginalViewFinderHeight; private int mViewFinderWidth, mViewFinderHeight; private boolean mPreviewing = false; - private final Object mCameraLock = new Object(); - private Thread mStartPreviewThread = null; private Capturer mCaptureObject; private ImageCapture mImageCapture = null; private boolean mPausing = false; private static final int FOCUS_NOT_STARTED = 0; private static final int FOCUSING = 1; private static final int FOCUSING_SNAP_ON_FINISH = 2; private static final int FOCUS_SUCCESS = 3; private static final int FOCUS_FAIL = 4; private int mFocusState = FOCUS_NOT_STARTED; private static ContentResolver mContentResolver; private boolean mDidRegister = false; private ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>(); private LocationManager mLocationManager = null; private ShutterButton mShutterButton; private Animation mFocusBlinkAnimation; private View mFocusIndicator; private ImageView mGpsIndicator; private ToneGenerator mFocusToneGenerator; private ShutterCallback mShutterCallback = new ShutterCallback(); private RawPictureCallback mRawPictureCallback = new RawPictureCallback(); private AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback(); private long mFocusStartTime; private long mFocusCallbackTime; private long mCaptureStartTime; private long mShutterCallbackTime; private long mRawPictureCallbackTime; private int mPicturesRemaining; private boolean mRecordLocation; private boolean mKeepAndRestartPreview; private boolean mIsImageCaptureIntent; // mPostCaptureAlert, mLastPictureButton, mThumbController // are non-null only if isImageCaptureIntent() is true. private View mPostCaptureAlert; private ImageView mLastPictureButton; private ThumbnailController mThumbController; private Handler mHandler = new MainHandler(); private interface Capturer { Uri getLastCaptureUri(); void onSnap(); void dismissFreezeFrame(); } /** This Handler is used to post message back onto the main thread of the application */ private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case RESTART_PREVIEW: { if (mStatus == SNAPSHOT_IN_PROGRESS) { // We are still in the processing of taking the picture, wait. // This is strange. Why are we polling? // TODO remove polling mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, 100); } else if (mStatus == SNAPSHOT_COMPLETED){ mCaptureObject.dismissFreezeFrame(); hidePostCaptureAlert(); } break; } case CLEAR_SCREEN_DELAY: { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); break; } } } }; LocationListener [] mLocationListeners = new LocationListener[] { new LocationListener(LocationManager.GPS_PROVIDER), new LocationListener(LocationManager.NETWORK_PROVIDER) }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { // SD card available updateStorageHint(calculatePicturesRemaining()); } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED) || action.equals(Intent.ACTION_MEDIA_CHECKING)) { // SD card unavailable mPicturesRemaining = MenuHelper.NO_STORAGE_ERROR; updateStorageHint(mPicturesRemaining); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { Toast.makeText(Camera.this, getResources().getString(R.string.wait), 5000); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { updateStorageHint(); } } }; private class LocationListener implements android.location.LocationListener { Location mLastLocation; boolean mValid = false; String mProvider; public LocationListener(String provider) { mProvider = provider; mLastLocation = new Location(mProvider); } public void onLocationChanged(Location newLocation) { if (newLocation.getLatitude() == 0.0 && newLocation.getLongitude() == 0.0) { // Hack to filter out 0.0,0.0 locations return; } // If GPS is available before start camera, we won't get status // update so update GPS indicator when we receive data. if (mRecordLocation && LocationManager.GPS_PROVIDER.equals(mProvider)) { mGpsIndicator.setVisibility(View.VISIBLE); } mLastLocation.set(newLocation); mValid = true; } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { mValid = false; } public void onStatusChanged(String provider, int status, Bundle extras) { switch(status) { case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: { mValid = false; if (mRecordLocation && LocationManager.GPS_PROVIDER.equals(provider)) { mGpsIndicator.setVisibility(View.INVISIBLE); } break; } } } public Location current() { return mValid ? mLastLocation : null; } }; private boolean mImageSavingItem = false; private final class ShutterCallback implements android.hardware.Camera.ShutterCallback { public void onShutter() { if (DEBUG_TIME_OPERATIONS) { mShutterCallbackTime = System.currentTimeMillis(); Log.v(TAG, "Shutter lag was " + (mShutterCallbackTime - mCaptureStartTime) + " ms."); } // We are going to change the size of surface view and show captured // image. Set it to invisible now and set it back to visible in // surfaceChanged() so that users won't see the image is resized on // the screen. mSurfaceView.setVisibility(View.INVISIBLE); // Resize the SurfaceView to the aspect-ratio of the still image // and so that we can see the full image that was taken. Size pictureSize = mParameters.getPictureSize(); mSurfaceView.setAspectRatio(pictureSize.width, pictureSize.height); } }; private final class RawPictureCallback implements PictureCallback { public void onPictureTaken(byte [] rawData, android.hardware.Camera camera) { if (Config.LOGV) Log.v(TAG, "got RawPictureCallback..."); mRawPictureCallbackTime = System.currentTimeMillis(); if (DEBUG_TIME_OPERATIONS) { Log.v(TAG, (mRawPictureCallbackTime - mShutterCallbackTime) + "ms elapsed between" + " ShutterCallback and RawPictureCallback."); } } }; private final class JpegPictureCallback implements PictureCallback { Location mLocation; public JpegPictureCallback(Location loc) { mLocation = loc; } public void onPictureTaken(byte [] jpegData, android.hardware.Camera camera) { if (mPausing) { return; } if (Config.LOGV) Log.v(TAG, "got JpegPictureCallback..."); if (DEBUG_TIME_OPERATIONS) { long mJpegPictureCallback = System.currentTimeMillis(); Log.v(TAG, (mJpegPictureCallback - mRawPictureCallbackTime) + "ms elapsed between" + " RawPictureCallback and JpegPictureCallback."); } if (jpegData != null) { mImageCapture.storeImage(jpegData, camera, mLocation); } mStatus = SNAPSHOT_COMPLETED; if (mKeepAndRestartPreview) { long delay = 1500 - (System.currentTimeMillis() - mRawPictureCallbackTime); mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, Math.max(delay, 0)); } } }; private final class AutoFocusCallback implements android.hardware.Camera.AutoFocusCallback { public void onAutoFocus(boolean focused, android.hardware.Camera camera) { if (DEBUG_TIME_OPERATIONS) { mFocusCallbackTime = System.currentTimeMillis(); Log.v(TAG, "Auto focus took " + (mFocusCallbackTime - mFocusStartTime) + " ms."); } if (mFocusState == FOCUSING_SNAP_ON_FINISH && mCaptureObject != null) { // Take the picture no matter focus succeeds or fails. // No need to play the AF sound if we're about to play the shutter sound. mCaptureObject.onSnap(); clearFocusState(); } else if (mFocusState == FOCUSING) { // User is half-pressing the focus key. Play the focus tone. // Do not take the picture now. ToneGenerator tg = mFocusToneGenerator; if (tg != null) tg.startTone(ToneGenerator.TONE_PROP_BEEP2); if (focused) { mFocusState = FOCUS_SUCCESS; } else { mFocusState = FOCUS_FAIL; } } else if (mFocusState == FOCUS_NOT_STARTED) { // User has released the focus key before focus completes. // Do nothing. } updateFocusIndicator(); } }; private class ImageCapture implements Capturer { private boolean mCancel = false; private boolean mCapturing = false; private Uri mLastContentUri; private ImageManager.IAddImage_cancelable mAddImageCancelable; Bitmap mCaptureOnlyBitmap; /** These member variables are used for various debug timings */ private long mThreadTimeStart; private long mThreadTimeEnd; private long mWallTimeStart; private long mWallTimeEnd; public ImageCapture() { } /** * This method sets whether or not we are capturing a picture. This method must be called * with the ImageCapture.this lock held. */ public void setCapturingLocked(boolean capturing) { mCapturing = capturing; } public void dismissFreezeFrame() { if (mStatus == SNAPSHOT_IN_PROGRESS) { // If we are still in the process of taking a picture, then just post a message. mHandler.sendEmptyMessage(RESTART_PREVIEW); } else { restartPreview(); } } private void startTiming() { mWallTimeStart = SystemClock.elapsedRealtime(); mThreadTimeStart = Debug.threadCpuTimeNanos(); } private void stopTiming() { mThreadTimeEnd = Debug.threadCpuTimeNanos(); mWallTimeEnd = SystemClock.elapsedRealtime(); } private void storeImage(byte[] data, Location loc) { try { if (DEBUG_TIME_OPERATIONS) { startTiming(); } long dateTaken = System.currentTimeMillis(); String name = createName(dateTaken) + ".jpg"; mLastContentUri = ImageManager.instance().addImage( Camera.this, mContentResolver, name, "", dateTaken, // location for the database goes here loc, 0, // the dsp will use the right orientation so don't "double set it" ImageManager.CAMERA_IMAGE_BUCKET_NAME, name); if (mLastContentUri == null) { // this means we got an error mCancel = true; } if (!mCancel) { mAddImageCancelable = ImageManager.instance().storeImage(mLastContentUri, Camera.this, mContentResolver, 0, null, data); mAddImageCancelable.get(); mAddImageCancelable = null; } if (DEBUG_TIME_OPERATIONS) { stopTiming(); Log.d(TAG, "Storing image took " + (mWallTimeEnd - mWallTimeStart) + " ms. " + "Thread time was " + ((mThreadTimeEnd - mThreadTimeStart) / 1000000) + " ms."); } } catch (Exception ex) { Log.e(TAG, "Exception while compressing image.", ex); } } public void storeImage(byte[] data, android.hardware.Camera camera, Location loc) { boolean captureOnly = mIsImageCaptureIntent; if (!captureOnly) { storeImage(data, loc); sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", mLastContentUri)); setLastPictureThumb(data, mCaptureObject.getLastCaptureUri()); dismissFreezeFrame(); } else { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; if (DEBUG_TIME_OPERATIONS) { startTiming(); } mCaptureOnlyBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options); if (DEBUG_TIME_OPERATIONS) { stopTiming(); Log.d(TAG, "Decoded mCaptureOnly bitmap (" + mCaptureOnlyBitmap.getWidth() + "x" + mCaptureOnlyBitmap.getHeight() + " ) in " + (mWallTimeEnd - mWallTimeStart) + " ms. Thread time was " + ((mThreadTimeEnd - mThreadTimeStart) / 1000000) + " ms."); } showPostCaptureAlert(); cancelAutomaticPreviewRestart(); } mCapturing = false; if (mPausing) { closeCamera(); } } /* * Initiate the capture of an image. */ public void initiate(boolean captureOnly) { + if (mCameraDevice == null) { + return; + } + mCancel = false; mCapturing = true; + capture(captureOnly); } public Uri getLastCaptureUri() { return mLastContentUri; } public Bitmap getLastBitmap() { return mCaptureOnlyBitmap; } private void capture(boolean captureOnly) { mPreviewing = false; mCaptureOnlyBitmap = null; final int latchedOrientation = ImageManager.roundOrientation(mLastOrientation + 90); Location loc = mRecordLocation ? getCurrentLocation() : null; // Quality 75 has visible artifacts, and quality 90 looks great but the files begin to // get large. 85 is a good compromise between the two. mParameters.set("jpeg-quality", 85); mParameters.set("rotation", latchedOrientation); mParameters.remove("gps-latitude"); mParameters.remove("gps-longitude"); mParameters.remove("gps-altitude"); mParameters.remove("gps-timestamp"); if (loc != null) { double lat = loc.getLatitude(); double lon = loc.getLongitude(); boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d); if (hasLatLon) { String latString = String.valueOf(lat); String lonString = String.valueOf(lon); mParameters.set("gps-latitude", latString); mParameters.set("gps-longitude", lonString); if (loc.hasAltitude()) { mParameters.set("gps-altitude", String.valueOf(loc.getAltitude())); } else { // for NETWORK_PROVIDER location provider, we may have // no altitude information, but the driver needs it, so // we fake one. mParameters.set("gps-altitude", "0"); } if (loc.getTime() != 0) { // Location.getTime() is UTC in milliseconds. // gps-timestamp is UTC in seconds. long utcTimeSeconds = loc.getTime() / 1000; mParameters.set("gps-timestamp", String.valueOf(utcTimeSeconds)); } } else { loc = null; } } mCameraDevice.setParameters(mParameters); mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback, new JpegPictureCallback(loc)); } public void onSnap() { if (mPausing) { return; } if (DEBUG_TIME_OPERATIONS) mCaptureStartTime = System.currentTimeMillis(); // If we are already in the middle of taking a snapshot then we should just save // the image after we have returned from the camera service. if (mStatus == SNAPSHOT_IN_PROGRESS || mStatus == SNAPSHOT_COMPLETED) { mKeepAndRestartPreview = true; mHandler.sendEmptyMessage(RESTART_PREVIEW); return; } // Don't check the filesystem here, we can't afford the latency. Instead, check the // cached value which was calculated when the preview was restarted. if (mPicturesRemaining < 1) { updateStorageHint(mPicturesRemaining); return; } mStatus = SNAPSHOT_IN_PROGRESS; mKeepAndRestartPreview = true; boolean getContentAction = mIsImageCaptureIntent; if (getContentAction) { mImageCapture.initiate(true); } else { mImageCapture.initiate(false); } } private void clearLastBitmap() { if (mCaptureOnlyBitmap != null) { mCaptureOnlyBitmap.recycle(); mCaptureOnlyBitmap = null; } } } private void setLastPictureThumb(byte[] data, Uri uri) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 16; Bitmap lastPictureThumb = BitmapFactory.decodeByteArray(data, 0, data.length, options); mThumbController.setData(uri, lastPictureThumb); } static private String createName(long dateTaken) { return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString(); } static public Matrix GetDisplayMatrix(Bitmap b, ImageView v) { Matrix m = new Matrix(); float bw = (float)b.getWidth(); float bh = (float)b.getHeight(); float vw = (float)v.getWidth(); float vh = (float)v.getHeight(); float scale, x, y; if (bw*vh > vw*bh) { scale = vh / bh; x = (vw - scale*bw)*0.5F; y = 0; } else { scale = vw / bw; x = 0; y = (vh - scale*bh)*0.5F; } m.setScale(scale, scale, 0.5F, 0.5F); m.postTranslate(x, y); return m; } /** Called with the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); + // To reduce startup time, we open camera device in another thread. + // We make sure the camera is opened at the end of onCreate. + Thread openCameraThread = new Thread(new Runnable() { + public void run() { + mCameraDevice = android.hardware.Camera.open(); + } + }); + openCameraThread.start(); + // To reduce startup time, we run some service creation code in another thread. // We make sure the services are loaded at the end of onCreate(). Thread loadServiceThread = new Thread(new Runnable() { public void run() { mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mOrientationListener = new OrientationEventListener(Camera.this) { public void onOrientationChanged(int orientation) { // We keep the last known orientation. So if the user // first orient the camera then point the camera to // floor/sky, we still have the correct orientation. if (orientation != ORIENTATION_UNKNOWN) mLastOrientation = orientation; } }; } }); loadServiceThread.start(); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mContentResolver = getContentResolver(); Window win = getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.camera); mSurfaceView = (VideoPreview) findViewById(R.id.camera_preview); mGpsIndicator = (ImageView) findViewById(R.id.gps_indicator); // don't set mSurfaceHolder here. We have it set ONLY within // surfaceCreated / surfaceDestroyed, other parts of the code // assume that when it is set, the surface is also set. SurfaceHolder holder = mSurfaceView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mIsImageCaptureIntent = isImageCaptureIntent(); if (!mIsImageCaptureIntent) { mLastPictureButton = (ImageView) findViewById(R.id.last_picture_button); mLastPictureButton.setOnClickListener(this); Drawable frame = getResources().getDrawable(R.drawable.frame_thumbnail); mThumbController = new ThumbnailController(mLastPictureButton, frame, mContentResolver); mThumbController.loadData(ImageManager.getLastImageThumbPath()); } mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); mFocusIndicator = findViewById(R.id.focus_indicator); mFocusBlinkAnimation = AnimationUtils.loadAnimation(this, R.anim.auto_focus_blink); mFocusBlinkAnimation.setRepeatCount(Animation.INFINITE); mFocusBlinkAnimation.setRepeatMode(Animation.REVERSE); // We load the post_picture_panel layout only if it is needed. if (mIsImageCaptureIntent) { ViewGroup cameraView = (ViewGroup)findViewById(R.id.camera); getLayoutInflater().inflate(R.layout.post_picture_panel, cameraView); mPostCaptureAlert = findViewById(R.id.post_picture_panel); } // Make sure the services are loaded. try { + openCameraThread.join(); loadServiceThread.join(); } catch (InterruptedException ex) { } ImageManager.ensureOSXCompatibleFolder(); } @Override public void onStart() { super.onStart(); Thread t = new Thread(new Runnable() { public void run() { final boolean storageOK = calculatePicturesRemaining() > 0; if (!storageOK) { mHandler.post(new Runnable() { public void run() { updateStorageHint(mPicturesRemaining); } }); } } }); t.start(); } public void onClick(View v) { switch (v.getId()) { case R.id.last_picture_button: if (mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED) { viewLastImage(); } break; case R.id.attach: doAttach(); break; case R.id.cancel: doCancel(); } } private void doAttach() { if (mPausing) { return; } Bitmap bitmap = mImageCapture.getLastBitmap(); String cropValue = null; Uri saveUri = null; Bundle myExtras = getIntent().getExtras(); if (myExtras != null) { saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); cropValue = myExtras.getString("crop"); } if (cropValue == null) { /* * First handle the no crop case -- just return the value. If the caller * specifies a "save uri" then write the data to it's stream. Otherwise, * pass back a scaled down version of the bitmap directly in the extras. */ if (saveUri != null) { OutputStream outputStream = null; try { outputStream = mContentResolver.openOutputStream(saveUri); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, outputStream); outputStream.close(); setResult(RESULT_OK); finish(); } catch (IOException ex) { // } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { } } } } else { float scale = .5F; Matrix m = new Matrix(); m.setScale(scale, scale); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true); setResult(RESULT_OK, new Intent("inline-data").putExtra("data", bitmap)); finish(); } } else { /* * Save the image to a temp file and invoke the cropper */ Uri tempUri = null; FileOutputStream tempStream = null; try { File path = getFileStreamPath(sTempCropFilename); path.delete(); tempStream = openFileOutput(sTempCropFilename, 0); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, tempStream); tempStream.close(); tempUri = Uri.fromFile(path); } catch (FileNotFoundException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } catch (IOException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } finally { if (tempStream != null) { try { tempStream.close(); } catch (IOException ex) { } } } Bundle newExtras = new Bundle(); if (cropValue.equals("circle")) newExtras.putString("circleCrop", "true"); if (saveUri != null) newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, saveUri); else newExtras.putBoolean("return-data", true); Intent cropIntent = new Intent(); cropIntent.setClass(Camera.this, CropImage.class); cropIntent.setData(tempUri); cropIntent.putExtras(newExtras); startActivityForResult(cropIntent, CROP_MSG); } } private void doCancel() { setResult(RESULT_CANCELED, new Intent()); finish(); } public void onShutterButtonFocus(ShutterButton button, boolean pressed) { - if (!mPreviewing || mPausing) { + if (mPausing) { return; } switch (button.getId()) { case R.id.shutter_button: doFocus(pressed); break; } } public void onShutterButtonClick(ShutterButton button) { - if (!mPreviewing || mPausing) { + if (mPausing) { return; } switch (button.getId()) { case R.id.shutter_button: doSnap(); break; } } private void updateStorageHint() { updateStorageHint(MenuHelper.calculatePicturesRemaining()); } private OnScreenHint mStorageHint; private void updateStorageHint(int remaining) { String noStorageText = null; if (remaining == MenuHelper.NO_STORAGE_ERROR) { String state = Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING) { noStorageText = getString(R.string.preparing_sd); } else { noStorageText = getString(R.string.no_storage); } } else if (remaining < 1) { noStorageText = getString(R.string.not_enough_space); } if (noStorageText != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, noStorageText); } else { mStorageHint.setText(noStorageText); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } @Override public void onResume() { super.onResume(); mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); mPausing = false; mOrientationListener.enable(); mRecordLocation = mPreferences.getBoolean( "pref_camera_recordlocation_key", false); mGpsIndicator.setVisibility(View.INVISIBLE); // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); mDidRegister = true; mImageCapture = new ImageCapture(); restartPreview(); if (mRecordLocation) startReceivingLocationUpdates(); updateFocusIndicator(); try { mFocusToneGenerator = new ToneGenerator(AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME); } catch (RuntimeException e) { Log.w(TAG, "Exception caught while creating local tone generator: " + e); mFocusToneGenerator = null; } } private static ImageManager.DataLocation dataLocation() { return ImageManager.DataLocation.EXTERNAL; } @Override public void onStop() { keep(); stopPreview(); closeCamera(); mHandler.removeMessages(CLEAR_SCREEN_DELAY); super.onStop(); } @Override protected void onPause() { keep(); mPausing = true; mOrientationListener.disable(); stopPreview(); if (!mImageCapture.mCapturing) { closeCamera(); } if (mDidRegister) { unregisterReceiver(mReceiver); mDidRegister = false; } stopReceivingLocationUpdates(); if (mFocusToneGenerator != null) { mFocusToneGenerator.release(); mFocusToneGenerator = null; } if (!mIsImageCaptureIntent) { mThumbController.storeData(ImageManager.getLastImageThumbPath()); } if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } // If we are in an image capture intent and has taken // a picture, we just clear it in onPause. mImageCapture.clearLastBitmap(); mImageCapture = null; hidePostCaptureAlert(); super.onPause(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case CROP_MSG: { Intent intent = new Intent(); if (data != null) { Bundle extras = data.getExtras(); if (extras != null) { intent.putExtras(extras); } } setResult(resultCode, intent); finish(); File path = getFileStreamPath(sTempCropFilename); path.delete(); break; } } } private void autoFocus() { updateFocusIndicator(); if (mFocusState != FOCUSING && mFocusState != FOCUSING_SNAP_ON_FINISH) { if (mCameraDevice != null) { if (DEBUG_TIME_OPERATIONS) { mFocusStartTime = System.currentTimeMillis(); } mFocusState = FOCUSING; mCameraDevice.autoFocus(mAutoFocusCallback); } } } private void clearFocusState() { mFocusState = FOCUS_NOT_STARTED; } private void updateFocusIndicator() { mHandler.post(new Runnable() { public void run() { if (mFocusState == FOCUS_SUCCESS) { mFocusIndicator.setVisibility(View.VISIBLE); mFocusIndicator.clearAnimation(); } else if (mFocusState == FOCUS_FAIL) { mFocusIndicator.setVisibility(View.VISIBLE); mFocusIndicator.startAnimation(mFocusBlinkAnimation); } else { mFocusIndicator.setVisibility(View.GONE); mFocusIndicator.clearAnimation(); } } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mStatus == SNAPSHOT_IN_PROGRESS) { // ignore backs while we're taking a picture return true; } break; case KeyEvent.KEYCODE_FOCUS: if (event.getRepeatCount() == 0) { - if (mPreviewing) { - doFocus(true); - } + doFocus(true); } return true; case KeyEvent.KEYCODE_CAMERA: if (event.getRepeatCount() == 0) { - if (mPreviewing) { - doSnap(); - } + doSnap(); } return true; case KeyEvent.KEYCODE_DPAD_CENTER: // If we get a dpad center event without any focused view, move the // focus to the shutter button and press it. if (event.getRepeatCount() == 0) { // Start auto-focus immediately to reduce shutter lag. After the shutter button // gets the focus, doFocus() will be called again but it is fine. - if (mPreviewing) { - doFocus(true); - if (mShutterButton.isInTouchMode()) { - mShutterButton.requestFocusFromTouch(); - } else { - mShutterButton.requestFocus(); - } - mShutterButton.setPressed(true); + doFocus(true); + if (mShutterButton.isInTouchMode()) { + mShutterButton.requestFocusFromTouch(); + } else { + mShutterButton.requestFocus(); } + mShutterButton.setPressed(true); } return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_FOCUS: doFocus(false); return true; } return super.onKeyUp(keyCode, event); } private void doSnap() { // If the user has half-pressed the shutter and focus is completed, we // can take the photo right away. if ((mFocusState == FOCUS_SUCCESS || mFocusState == FOCUS_FAIL) || !mPreviewing) { // doesn't get set until the idler runs if (mCaptureObject != null) { mCaptureObject.onSnap(); } clearFocusState(); updateFocusIndicator(); } else if (mFocusState == FOCUSING) { // Half pressing the shutter (i.e. the focus button event) will // already have requested AF for us, so just request capture on // focus here. mFocusState = FOCUSING_SNAP_ON_FINISH; } else if (mFocusState == FOCUS_NOT_STARTED) { // Focus key down event is dropped for some reasons. Just ignore. } } private void doFocus(boolean pressed) { if (pressed) { // Focus key down. if (mPreviewing) { autoFocus(); } else if (mCaptureObject != null) { // Save and restart preview mCaptureObject.onSnap(); } } else { // Focus key up. if (mFocusState != FOCUSING_SNAP_ON_FINISH) { // User releases half-pressed focus key. clearFocusState(); updateFocusIndicator(); } } } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { mSurfaceView.setVisibility(View.VISIBLE); // if we're creating the surface, start the preview as well. boolean preview = holder.isCreating(); setViewFinder(w, h, preview); mCaptureObject = mImageCapture; } public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; } public void surfaceDestroyed(SurfaceHolder holder) { stopPreview(); mSurfaceHolder = null; } - // always call stopPreview before calling closeCamera private void closeCamera() { if (mCameraDevice != null) { mCameraDevice.release(); mCameraDevice = null; mPreviewing = false; } } + private boolean ensureCameraDevice() { + if (mCameraDevice == null) { + mCameraDevice = android.hardware.Camera.open(); + } + return mCameraDevice != null; + } + private void updateLastImage() { ImageManager.IImageList list = ImageManager.instance().allImages( this, mContentResolver, dataLocation(), ImageManager.INCLUDE_IMAGES, ImageManager.SORT_ASCENDING, ImageManager.CAMERA_IMAGE_BUCKET_ID); int count = list.getCount(); if (count > 0) { ImageManager.IImage image = list.getImageAt(count-1); Uri uri = image.fullSizeImageUri(); mThumbController.setData(uri, image.miniThumbBitmap()); } else { mThumbController.setData(null, null); } list.deactivate(); } private void restartPreview() { VideoPreview surfaceView = mSurfaceView; // make sure the surfaceview fills the whole screen when previewing surfaceView.setAspectRatio(VideoPreview.DONT_CARE); setViewFinder(mOriginalViewFinderWidth, mOriginalViewFinderHeight, true); mStatus = IDLE; // Calculate this in advance of each shot so we don't add to shutter latency. It's true that // someone else could write to the SD card in the mean time and fill it, but that could have // happened between the shutter press and saving the JPEG too. // TODO: The best longterm solution is to write a reserve file of maximum JPEG size, always // let the user take a picture, and delete that file if needed to save the new photo. calculatePicturesRemaining(); if (!mIsImageCaptureIntent && !mThumbController.isUriValid()) { updateLastImage(); } if (!mIsImageCaptureIntent) { mThumbController.updateDisplayIfNeeded(); } } private void setViewFinder(int w, int h, boolean startPreview) { if (mPausing) return; if (mPreviewing && w == mViewFinderWidth && h == mViewFinderHeight) { return; } + if (!ensureCameraDevice()) + return; + if (mSurfaceHolder == null) return; if (isFinishing()) return; if (mPausing) return; // remember view finder size mViewFinderWidth = w; mViewFinderHeight = h; if (mOriginalViewFinderHeight == 0) { mOriginalViewFinderWidth = w; mOriginalViewFinderHeight = h; } if (startPreview == false) return; /* - * start preview on a separate thread + * start the preview if we're asked to... */ - // start camera preview - synchronized(mCameraLock) { - if (mStartPreviewThread == null) { - mStartPreviewThread = new Thread(new Runnable() { - public void run() { - - // create camera object - synchronized(mCameraLock) { - if (mCameraDevice == null) { - mCameraDevice = android.hardware.Camera.open(); - } - } - // we want to start the preview and we're previewing already, - // stop the preview first (this will blank the screen). - if (mPreviewing) - stopPreview(); + // we want to start the preview and we're previewing already, + // stop the preview first (this will blank the screen). + if (mPreviewing) + stopPreview(); - // this blanks the screen if the surface changed, no-op otherwise - try { - mCameraDevice.setPreviewDisplay(mSurfaceHolder); - } catch (IOException exception) { - mCameraDevice.release(); - mCameraDevice = null; - // TODO: add more exception handling logic here - return; - } + // this blanks the screen if the surface changed, no-op otherwise + try { + mCameraDevice.setPreviewDisplay(mSurfaceHolder); + } catch (IOException exception) { + mCameraDevice.release(); + mCameraDevice = null; + // TODO: add more exception handling logic here + return; + } - // request the preview size, the hardware may not honor it, - // if we depended on it we would have to query the size again - mParameters = mCameraDevice.getParameters(); - mParameters.setPreviewSize(mViewFinderWidth, mViewFinderHeight); - try { - mCameraDevice.setParameters(mParameters); - } catch (IllegalArgumentException e) { - // Ignore this error, it happens in the simulator. - } + // request the preview size, the hardware may not honor it, + // if we depended on it we would have to query the size again + mParameters = mCameraDevice.getParameters(); + mParameters.setPreviewSize(w, h); + try { + mCameraDevice.setParameters(mParameters); + } catch (IllegalArgumentException e) { + // Ignore this error, it happens in the simulator. + } - final long wallTimeStart = SystemClock.elapsedRealtime(); - final long threadTimeStart = Debug.threadCpuTimeNanos(); - if (Config.LOGV) Log.v(TAG, "calling mCameraDevice.startPreview"); - try { - mCameraDevice.startPreview(); - } catch (Throwable e) { - // TODO: change Throwable to IOException once android.hardware.Camera.startPreview - // properly declares that it throws IOException. - } - synchronized(mCameraLock) { - mPreviewing = true; - mStartPreviewThread = null; - } + final long wallTimeStart = SystemClock.elapsedRealtime(); + final long threadTimeStart = Debug.threadCpuTimeNanos(); - long threadTimeEnd = Debug.threadCpuTimeNanos(); - long wallTimeEnd = SystemClock.elapsedRealtime(); - if ((wallTimeEnd - wallTimeStart) > 3000) { - Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart) + " ms. Thread time was" - + (threadTimeEnd - threadTimeStart) / 1000000 + " ms."); + final Object watchDogSync = new Object(); + Thread watchDog = new Thread(new Runnable() { + public void run() { + int next_warning = 1; + while (true) { + try { + synchronized (watchDogSync) { + watchDogSync.wait(1000); } + } catch (InterruptedException ex) { + // } - }); + if (mPreviewing) break; - mStartPreviewThread.start(); + int delay = (int) (SystemClock.elapsedRealtime() - wallTimeStart) / 1000; + if (delay >= next_warning) { + if (delay < 120) { + Log.e(TAG, "preview hasn't started yet in " + delay + " seconds"); + } else { + Log.e(TAG, "preview hasn't started yet in " + (delay / 60) + " minutes"); + } + if (next_warning < 60) { + next_warning <<= 1; + if (next_warning == 16) { + next_warning = 15; + } + } else { + next_warning += 60; + } + } + } } + }); + + watchDog.start(); + + if (Config.LOGV) + Log.v(TAG, "calling mCameraDevice.startPreview"); + try { + mCameraDevice.startPreview(); + } catch (Throwable e) { + // TODO: change Throwable to IOException once android.hardware.Camera.startPreview + // properly declares that it throws IOException. } - } + mPreviewing = true; - // wait for preview thread if it is running - private void joinPreviewThread() { - Thread startPreviewThread; - synchronized(mCameraLock) { - startPreviewThread = mStartPreviewThread; + synchronized (watchDogSync) { + watchDogSync.notify(); } - if (startPreviewThread != null) { - try { - startPreviewThread.join(); - } catch (InterruptedException ex) { - } + + long threadTimeEnd = Debug.threadCpuTimeNanos(); + long wallTimeEnd = SystemClock.elapsedRealtime(); + if ((wallTimeEnd - wallTimeStart) > 3000) { + Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart) + " ms. Thread time was" + + (threadTimeEnd - threadTimeStart) / 1000000 + " ms."); } } private void stopPreview() { - joinPreviewThread(); - synchronized(mCameraLock) { - if (mCameraDevice != null && mPreviewing) { - mCameraDevice.stopPreview(); - } - mPreviewing = false; + if (mCameraDevice != null && mPreviewing) { + mCameraDevice.stopPreview(); } - + mPreviewing = false; // If auto focus was in progress, it would have been canceled. clearFocusState(); } void gotoGallery() { MenuHelper.gotoCameraImageGallery(this); } private void viewLastImage() { if (mThumbController.isUriValid()) { Uri targetUri = mThumbController.getUri(); targetUri = targetUri.buildUpon(). appendQueryParameter("bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build(); Intent intent = new Intent(Intent.ACTION_VIEW, targetUri); intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true); intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true); intent.putExtra("com.android.camera.ReviewMode", true); try { startActivity(intent); } catch (android.content.ActivityNotFoundException ex) { // ignore. } } else { Log.e(TAG, "Can't view last image."); } } void keep() { if (mCaptureObject != null) { mCaptureObject.dismissFreezeFrame(); } }; private ImageManager.IImage getImageForURI(Uri uri) { ImageManager.IImageList list = ImageManager.instance().allImages( this, mContentResolver, dataLocation(), ImageManager.INCLUDE_IMAGES, ImageManager.SORT_ASCENDING); ImageManager.IImage image = list.getImageForUri(uri); list.deactivate(); return image; } private void startReceivingLocationUpdates() { if (mLocationManager != null) { try { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 1000, 0F, mLocationListeners[1]); } catch (java.lang.SecurityException ex) { // ok } catch (IllegalArgumentException ex) { if (Config.LOGD) { Log.d(TAG, "provider does not exist " + ex.getMessage()); } } try { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 1000, 0F, mLocationListeners[0]); } catch (java.lang.SecurityException ex) { // ok } catch (IllegalArgumentException ex) { if (Config.LOGD) { Log.d(TAG, "provider does not exist " + ex.getMessage()); } } } } private void stopReceivingLocationUpdates() { if (mLocationManager != null) { for (int i = 0; i < mLocationListeners.length; i++) { try { mLocationManager.removeUpdates(mLocationListeners[i]); } catch (Exception ex) { // ok } } } } private Location getCurrentLocation() { // go in best to worst order for (int i = 0; i < mLocationListeners.length; i++) { Location l = mLocationListeners[i].current(); if (l != null) return l; } return null; } @Override public void onOptionsMenuClosed(Menu menu) { super.onOptionsMenuClosed(menu); if (mImageSavingItem) { // save the image if we presented the "advanced" menu // which happens if "menu" is pressed while in // SNAPSHOT_IN_PROGRESS or SNAPSHOT_COMPLETED modes keep(); mHandler.sendEmptyMessage(RESTART_PREVIEW); } } @Override public boolean onMenuOpened(int featureId, Menu menu) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { if (mStatus == SNAPSHOT_IN_PROGRESS) { cancelAutomaticPreviewRestart(); } } return super.onMenuOpened(featureId, menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); for (int i = 1; i <= MenuHelper.MENU_ITEM_MAX; i++) { if (i != MenuHelper.GENERIC_ITEM) { menu.setGroupVisible(i, false); } } if (mStatus == SNAPSHOT_IN_PROGRESS || mStatus == SNAPSHOT_COMPLETED) { menu.setGroupVisible(MenuHelper.IMAGE_SAVING_ITEM, true); mImageSavingItem = true; } else { menu.setGroupVisible(MenuHelper.IMAGE_MODE_ITEM, true); mImageSavingItem = false; } return true; } private void cancelAutomaticPreviewRestart() { mKeepAndRestartPreview = false; mHandler.removeMessages(RESTART_PREVIEW); } private boolean isImageCaptureIntent() { String action = getIntent().getAction(); return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)); } private void showPostCaptureAlert() { if (mIsImageCaptureIntent) { mPostCaptureAlert.setVisibility(View.VISIBLE); int[] pickIds = {R.id.attach, R.id.cancel}; for(int id : pickIds) { View view = mPostCaptureAlert.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } } private void hidePostCaptureAlert() { if (mIsImageCaptureIntent) { mPostCaptureAlert.setVisibility(View.INVISIBLE); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (mIsImageCaptureIntent) { // No options menu for attach mode. return false; } else { addBaseMenuItems(menu); } return true; } SelectedImageGetter mSelectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return getImageForURI(getCurrentImageUri()); } public Uri getCurrentImageUri() { keep(); return mCaptureObject.getLastCaptureUri(); } }; private int calculatePicturesRemaining() { mPicturesRemaining = MenuHelper.calculatePicturesRemaining(); return mPicturesRemaining; } private void addBaseMenuItems(Menu menu) { MenuHelper.addSwitchModeMenuItem(menu, this, true); { MenuItem gallery = menu.add(MenuHelper.IMAGE_MODE_ITEM, MENU_GALLERY_PHOTOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } { MenuItem gallery = menu.add(MenuHelper.VIDEO_MODE_ITEM, MENU_GALLERY_VIDEOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } MenuItem item = menu.add(MenuHelper.GENERIC_ITEM, MENU_SETTINGS, 0, R.string.settings).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(); intent.setClass(Camera.this, CameraSettings.class); startActivity(intent); return true; } }); item.setIcon(android.R.drawable.ic_menu_preferences); } }
brunsky/WS171-packages-apps-Camera
e32f822f4dc68dc3d59fa33a758f629e50671483
Automated import from //branches/cupcake/...@142119,142119
diff --git a/src/com/android/camera/Camera.java b/src/com/android/camera/Camera.java index 46620f4..9cb30c9 100644 --- a/src/com/android/camera/Camera.java +++ b/src/com/android/camera/Camera.java @@ -1,1614 +1,1595 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.hardware.Camera.PictureCallback; import android.hardware.Camera.Size; import android.location.Location; import android.location.LocationManager; import android.location.LocationProvider; import android.media.AudioManager; import android.media.ToneGenerator; import android.net.Uri; import android.os.Bundle; import android.os.Debug; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.text.format.DateFormat; import android.util.Config; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.OrientationEventListener; import android.view.SurfaceHolder; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.Toast; public class Camera extends Activity implements View.OnClickListener, ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback { private static final String TAG = "camera"; private static final boolean DEBUG = false; private static final boolean DEBUG_TIME_OPERATIONS = DEBUG && false; private static final int CROP_MSG = 1; private static final int RESTART_PREVIEW = 3; private static final int CLEAR_SCREEN_DELAY = 4; private static final int SCREEN_DELAY = 2 * 60 * 1000; private static final int FOCUS_BEEP_VOLUME = 100; public static final int MENU_SWITCH_TO_VIDEO = 0; public static final int MENU_SWITCH_TO_CAMERA = 1; public static final int MENU_FLASH_SETTING = 2; public static final int MENU_FLASH_AUTO = 3; public static final int MENU_FLASH_ON = 4; public static final int MENU_FLASH_OFF = 5; public static final int MENU_SETTINGS = 6; public static final int MENU_GALLERY_PHOTOS = 7; public static final int MENU_GALLERY_VIDEOS = 8; public static final int MENU_SAVE_SELECT_PHOTOS = 30; public static final int MENU_SAVE_NEW_PHOTO = 31; public static final int MENU_SAVE_GALLERY_PHOTO = 34; public static final int MENU_SAVE_GALLERY_VIDEO_PHOTO = 35; public static final int MENU_SAVE_CAMERA_DONE = 36; public static final int MENU_SAVE_CAMERA_VIDEO_DONE = 37; private OrientationEventListener mOrientationListener; private int mLastOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; private SharedPreferences mPreferences; private static final int IDLE = 1; private static final int SNAPSHOT_IN_PROGRESS = 2; private static final int SNAPSHOT_COMPLETED = 3; private int mStatus = IDLE; private static final String sTempCropFilename = "crop-temp"; private android.hardware.Camera mCameraDevice; private android.hardware.Camera.Parameters mParameters; private VideoPreview mSurfaceView; private SurfaceHolder mSurfaceHolder = null; private int mOriginalViewFinderWidth, mOriginalViewFinderHeight; private int mViewFinderWidth, mViewFinderHeight; private boolean mPreviewing = false; + private final Object mCameraLock = new Object(); + private Thread mStartPreviewThread = null; private Capturer mCaptureObject; private ImageCapture mImageCapture = null; private boolean mPausing = false; private static final int FOCUS_NOT_STARTED = 0; private static final int FOCUSING = 1; private static final int FOCUSING_SNAP_ON_FINISH = 2; private static final int FOCUS_SUCCESS = 3; private static final int FOCUS_FAIL = 4; private int mFocusState = FOCUS_NOT_STARTED; private static ContentResolver mContentResolver; private boolean mDidRegister = false; private ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>(); private LocationManager mLocationManager = null; private ShutterButton mShutterButton; private Animation mFocusBlinkAnimation; private View mFocusIndicator; private ImageView mGpsIndicator; private ToneGenerator mFocusToneGenerator; private ShutterCallback mShutterCallback = new ShutterCallback(); private RawPictureCallback mRawPictureCallback = new RawPictureCallback(); private AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback(); private long mFocusStartTime; private long mFocusCallbackTime; private long mCaptureStartTime; private long mShutterCallbackTime; private long mRawPictureCallbackTime; private int mPicturesRemaining; private boolean mRecordLocation; private boolean mKeepAndRestartPreview; private boolean mIsImageCaptureIntent; // mPostCaptureAlert, mLastPictureButton, mThumbController // are non-null only if isImageCaptureIntent() is true. private View mPostCaptureAlert; private ImageView mLastPictureButton; private ThumbnailController mThumbController; private Handler mHandler = new MainHandler(); private interface Capturer { Uri getLastCaptureUri(); void onSnap(); void dismissFreezeFrame(); } /** This Handler is used to post message back onto the main thread of the application */ private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case RESTART_PREVIEW: { if (mStatus == SNAPSHOT_IN_PROGRESS) { // We are still in the processing of taking the picture, wait. // This is strange. Why are we polling? // TODO remove polling mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, 100); } else if (mStatus == SNAPSHOT_COMPLETED){ mCaptureObject.dismissFreezeFrame(); hidePostCaptureAlert(); } break; } case CLEAR_SCREEN_DELAY: { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); break; } } } }; LocationListener [] mLocationListeners = new LocationListener[] { new LocationListener(LocationManager.GPS_PROVIDER), new LocationListener(LocationManager.NETWORK_PROVIDER) }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { // SD card available updateStorageHint(calculatePicturesRemaining()); } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED) || action.equals(Intent.ACTION_MEDIA_CHECKING)) { // SD card unavailable mPicturesRemaining = MenuHelper.NO_STORAGE_ERROR; updateStorageHint(mPicturesRemaining); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { Toast.makeText(Camera.this, getResources().getString(R.string.wait), 5000); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { updateStorageHint(); } } }; private class LocationListener implements android.location.LocationListener { Location mLastLocation; boolean mValid = false; String mProvider; public LocationListener(String provider) { mProvider = provider; mLastLocation = new Location(mProvider); } public void onLocationChanged(Location newLocation) { if (newLocation.getLatitude() == 0.0 && newLocation.getLongitude() == 0.0) { // Hack to filter out 0.0,0.0 locations return; } // If GPS is available before start camera, we won't get status // update so update GPS indicator when we receive data. if (mRecordLocation && LocationManager.GPS_PROVIDER.equals(mProvider)) { mGpsIndicator.setVisibility(View.VISIBLE); } mLastLocation.set(newLocation); mValid = true; } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { mValid = false; } public void onStatusChanged(String provider, int status, Bundle extras) { switch(status) { case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: { mValid = false; if (mRecordLocation && LocationManager.GPS_PROVIDER.equals(provider)) { mGpsIndicator.setVisibility(View.INVISIBLE); } break; } } } public Location current() { return mValid ? mLastLocation : null; } }; private boolean mImageSavingItem = false; private final class ShutterCallback implements android.hardware.Camera.ShutterCallback { public void onShutter() { if (DEBUG_TIME_OPERATIONS) { mShutterCallbackTime = System.currentTimeMillis(); Log.v(TAG, "Shutter lag was " + (mShutterCallbackTime - mCaptureStartTime) + " ms."); } // We are going to change the size of surface view and show captured // image. Set it to invisible now and set it back to visible in // surfaceChanged() so that users won't see the image is resized on // the screen. mSurfaceView.setVisibility(View.INVISIBLE); // Resize the SurfaceView to the aspect-ratio of the still image // and so that we can see the full image that was taken. Size pictureSize = mParameters.getPictureSize(); mSurfaceView.setAspectRatio(pictureSize.width, pictureSize.height); } }; private final class RawPictureCallback implements PictureCallback { public void onPictureTaken(byte [] rawData, android.hardware.Camera camera) { if (Config.LOGV) Log.v(TAG, "got RawPictureCallback..."); mRawPictureCallbackTime = System.currentTimeMillis(); if (DEBUG_TIME_OPERATIONS) { Log.v(TAG, (mRawPictureCallbackTime - mShutterCallbackTime) + "ms elapsed between" + " ShutterCallback and RawPictureCallback."); } } }; private final class JpegPictureCallback implements PictureCallback { Location mLocation; public JpegPictureCallback(Location loc) { mLocation = loc; } public void onPictureTaken(byte [] jpegData, android.hardware.Camera camera) { if (mPausing) { return; } if (Config.LOGV) Log.v(TAG, "got JpegPictureCallback..."); if (DEBUG_TIME_OPERATIONS) { long mJpegPictureCallback = System.currentTimeMillis(); Log.v(TAG, (mJpegPictureCallback - mRawPictureCallbackTime) + "ms elapsed between" + " RawPictureCallback and JpegPictureCallback."); } if (jpegData != null) { mImageCapture.storeImage(jpegData, camera, mLocation); } mStatus = SNAPSHOT_COMPLETED; if (mKeepAndRestartPreview) { long delay = 1500 - (System.currentTimeMillis() - mRawPictureCallbackTime); mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, Math.max(delay, 0)); } } }; private final class AutoFocusCallback implements android.hardware.Camera.AutoFocusCallback { public void onAutoFocus(boolean focused, android.hardware.Camera camera) { if (DEBUG_TIME_OPERATIONS) { mFocusCallbackTime = System.currentTimeMillis(); Log.v(TAG, "Auto focus took " + (mFocusCallbackTime - mFocusStartTime) + " ms."); } if (mFocusState == FOCUSING_SNAP_ON_FINISH && mCaptureObject != null) { // Take the picture no matter focus succeeds or fails. // No need to play the AF sound if we're about to play the shutter sound. mCaptureObject.onSnap(); clearFocusState(); } else if (mFocusState == FOCUSING) { // User is half-pressing the focus key. Play the focus tone. // Do not take the picture now. ToneGenerator tg = mFocusToneGenerator; if (tg != null) tg.startTone(ToneGenerator.TONE_PROP_BEEP2); if (focused) { mFocusState = FOCUS_SUCCESS; } else { mFocusState = FOCUS_FAIL; } } else if (mFocusState == FOCUS_NOT_STARTED) { // User has released the focus key before focus completes. // Do nothing. } updateFocusIndicator(); } }; private class ImageCapture implements Capturer { private boolean mCancel = false; private boolean mCapturing = false; private Uri mLastContentUri; private ImageManager.IAddImage_cancelable mAddImageCancelable; Bitmap mCaptureOnlyBitmap; /** These member variables are used for various debug timings */ private long mThreadTimeStart; private long mThreadTimeEnd; private long mWallTimeStart; private long mWallTimeEnd; public ImageCapture() { } /** * This method sets whether or not we are capturing a picture. This method must be called * with the ImageCapture.this lock held. */ public void setCapturingLocked(boolean capturing) { mCapturing = capturing; } public void dismissFreezeFrame() { if (mStatus == SNAPSHOT_IN_PROGRESS) { // If we are still in the process of taking a picture, then just post a message. mHandler.sendEmptyMessage(RESTART_PREVIEW); } else { restartPreview(); } } private void startTiming() { mWallTimeStart = SystemClock.elapsedRealtime(); mThreadTimeStart = Debug.threadCpuTimeNanos(); } private void stopTiming() { mThreadTimeEnd = Debug.threadCpuTimeNanos(); mWallTimeEnd = SystemClock.elapsedRealtime(); } private void storeImage(byte[] data, Location loc) { try { if (DEBUG_TIME_OPERATIONS) { startTiming(); } long dateTaken = System.currentTimeMillis(); String name = createName(dateTaken) + ".jpg"; mLastContentUri = ImageManager.instance().addImage( Camera.this, mContentResolver, name, "", dateTaken, // location for the database goes here loc, 0, // the dsp will use the right orientation so don't "double set it" ImageManager.CAMERA_IMAGE_BUCKET_NAME, name); if (mLastContentUri == null) { // this means we got an error mCancel = true; } if (!mCancel) { mAddImageCancelable = ImageManager.instance().storeImage(mLastContentUri, Camera.this, mContentResolver, 0, null, data); mAddImageCancelable.get(); mAddImageCancelable = null; } if (DEBUG_TIME_OPERATIONS) { stopTiming(); Log.d(TAG, "Storing image took " + (mWallTimeEnd - mWallTimeStart) + " ms. " + "Thread time was " + ((mThreadTimeEnd - mThreadTimeStart) / 1000000) + " ms."); } } catch (Exception ex) { Log.e(TAG, "Exception while compressing image.", ex); } } public void storeImage(byte[] data, android.hardware.Camera camera, Location loc) { boolean captureOnly = mIsImageCaptureIntent; if (!captureOnly) { storeImage(data, loc); sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", mLastContentUri)); setLastPictureThumb(data, mCaptureObject.getLastCaptureUri()); dismissFreezeFrame(); } else { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; if (DEBUG_TIME_OPERATIONS) { startTiming(); } mCaptureOnlyBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options); if (DEBUG_TIME_OPERATIONS) { stopTiming(); Log.d(TAG, "Decoded mCaptureOnly bitmap (" + mCaptureOnlyBitmap.getWidth() + "x" + mCaptureOnlyBitmap.getHeight() + " ) in " + (mWallTimeEnd - mWallTimeStart) + " ms. Thread time was " + ((mThreadTimeEnd - mThreadTimeStart) / 1000000) + " ms."); } showPostCaptureAlert(); cancelAutomaticPreviewRestart(); } mCapturing = false; if (mPausing) { closeCamera(); } } /* * Initiate the capture of an image. */ public void initiate(boolean captureOnly) { - if (mCameraDevice == null) { - return; - } - mCancel = false; mCapturing = true; - capture(captureOnly); } public Uri getLastCaptureUri() { return mLastContentUri; } public Bitmap getLastBitmap() { return mCaptureOnlyBitmap; } private void capture(boolean captureOnly) { mPreviewing = false; mCaptureOnlyBitmap = null; final int latchedOrientation = ImageManager.roundOrientation(mLastOrientation + 90); Location loc = mRecordLocation ? getCurrentLocation() : null; // Quality 75 has visible artifacts, and quality 90 looks great but the files begin to // get large. 85 is a good compromise between the two. mParameters.set("jpeg-quality", 85); mParameters.set("rotation", latchedOrientation); mParameters.remove("gps-latitude"); mParameters.remove("gps-longitude"); mParameters.remove("gps-altitude"); mParameters.remove("gps-timestamp"); if (loc != null) { double lat = loc.getLatitude(); double lon = loc.getLongitude(); boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d); if (hasLatLon) { String latString = String.valueOf(lat); String lonString = String.valueOf(lon); mParameters.set("gps-latitude", latString); mParameters.set("gps-longitude", lonString); if (loc.hasAltitude()) { mParameters.set("gps-altitude", String.valueOf(loc.getAltitude())); } else { // for NETWORK_PROVIDER location provider, we may have // no altitude information, but the driver needs it, so // we fake one. mParameters.set("gps-altitude", "0"); } if (loc.getTime() != 0) { // Location.getTime() is UTC in milliseconds. // gps-timestamp is UTC in seconds. long utcTimeSeconds = loc.getTime() / 1000; mParameters.set("gps-timestamp", String.valueOf(utcTimeSeconds)); } } else { loc = null; } } mCameraDevice.setParameters(mParameters); mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback, new JpegPictureCallback(loc)); } public void onSnap() { if (mPausing) { return; } if (DEBUG_TIME_OPERATIONS) mCaptureStartTime = System.currentTimeMillis(); // If we are already in the middle of taking a snapshot then we should just save // the image after we have returned from the camera service. if (mStatus == SNAPSHOT_IN_PROGRESS || mStatus == SNAPSHOT_COMPLETED) { mKeepAndRestartPreview = true; mHandler.sendEmptyMessage(RESTART_PREVIEW); return; } // Don't check the filesystem here, we can't afford the latency. Instead, check the // cached value which was calculated when the preview was restarted. if (mPicturesRemaining < 1) { updateStorageHint(mPicturesRemaining); return; } mStatus = SNAPSHOT_IN_PROGRESS; mKeepAndRestartPreview = true; boolean getContentAction = mIsImageCaptureIntent; if (getContentAction) { mImageCapture.initiate(true); } else { mImageCapture.initiate(false); } } private void clearLastBitmap() { if (mCaptureOnlyBitmap != null) { mCaptureOnlyBitmap.recycle(); mCaptureOnlyBitmap = null; } } } private void setLastPictureThumb(byte[] data, Uri uri) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 16; Bitmap lastPictureThumb = BitmapFactory.decodeByteArray(data, 0, data.length, options); mThumbController.setData(uri, lastPictureThumb); } static private String createName(long dateTaken) { return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString(); } static public Matrix GetDisplayMatrix(Bitmap b, ImageView v) { Matrix m = new Matrix(); float bw = (float)b.getWidth(); float bh = (float)b.getHeight(); float vw = (float)v.getWidth(); float vh = (float)v.getHeight(); float scale, x, y; if (bw*vh > vw*bh) { scale = vh / bh; x = (vw - scale*bw)*0.5F; y = 0; } else { scale = vw / bw; x = 0; y = (vh - scale*bh)*0.5F; } m.setScale(scale, scale, 0.5F, 0.5F); m.postTranslate(x, y); return m; } /** Called with the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); - // To reduce startup time, we open camera device in another thread. - // We make sure the camera is opened at the end of onCreate. - Thread openCameraThread = new Thread(new Runnable() { - public void run() { - mCameraDevice = android.hardware.Camera.open(); - } - }); - openCameraThread.start(); - // To reduce startup time, we run some service creation code in another thread. // We make sure the services are loaded at the end of onCreate(). Thread loadServiceThread = new Thread(new Runnable() { public void run() { mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mOrientationListener = new OrientationEventListener(Camera.this) { public void onOrientationChanged(int orientation) { // We keep the last known orientation. So if the user // first orient the camera then point the camera to // floor/sky, we still have the correct orientation. if (orientation != ORIENTATION_UNKNOWN) mLastOrientation = orientation; } }; } }); loadServiceThread.start(); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mContentResolver = getContentResolver(); Window win = getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.camera); mSurfaceView = (VideoPreview) findViewById(R.id.camera_preview); mGpsIndicator = (ImageView) findViewById(R.id.gps_indicator); // don't set mSurfaceHolder here. We have it set ONLY within // surfaceCreated / surfaceDestroyed, other parts of the code // assume that when it is set, the surface is also set. SurfaceHolder holder = mSurfaceView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mIsImageCaptureIntent = isImageCaptureIntent(); if (!mIsImageCaptureIntent) { mLastPictureButton = (ImageView) findViewById(R.id.last_picture_button); mLastPictureButton.setOnClickListener(this); Drawable frame = getResources().getDrawable(R.drawable.frame_thumbnail); mThumbController = new ThumbnailController(mLastPictureButton, frame, mContentResolver); mThumbController.loadData(ImageManager.getLastImageThumbPath()); } mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); mFocusIndicator = findViewById(R.id.focus_indicator); mFocusBlinkAnimation = AnimationUtils.loadAnimation(this, R.anim.auto_focus_blink); mFocusBlinkAnimation.setRepeatCount(Animation.INFINITE); mFocusBlinkAnimation.setRepeatMode(Animation.REVERSE); // We load the post_picture_panel layout only if it is needed. if (mIsImageCaptureIntent) { ViewGroup cameraView = (ViewGroup)findViewById(R.id.camera); getLayoutInflater().inflate(R.layout.post_picture_panel, cameraView); mPostCaptureAlert = findViewById(R.id.post_picture_panel); } // Make sure the services are loaded. try { - openCameraThread.join(); loadServiceThread.join(); } catch (InterruptedException ex) { } ImageManager.ensureOSXCompatibleFolder(); } @Override public void onStart() { super.onStart(); Thread t = new Thread(new Runnable() { public void run() { final boolean storageOK = calculatePicturesRemaining() > 0; if (!storageOK) { mHandler.post(new Runnable() { public void run() { updateStorageHint(mPicturesRemaining); } }); } } }); t.start(); } public void onClick(View v) { switch (v.getId()) { case R.id.last_picture_button: if (mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED) { viewLastImage(); } break; case R.id.attach: doAttach(); break; case R.id.cancel: doCancel(); } } private void doAttach() { if (mPausing) { return; } Bitmap bitmap = mImageCapture.getLastBitmap(); String cropValue = null; Uri saveUri = null; Bundle myExtras = getIntent().getExtras(); if (myExtras != null) { saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); cropValue = myExtras.getString("crop"); } if (cropValue == null) { /* * First handle the no crop case -- just return the value. If the caller * specifies a "save uri" then write the data to it's stream. Otherwise, * pass back a scaled down version of the bitmap directly in the extras. */ if (saveUri != null) { OutputStream outputStream = null; try { outputStream = mContentResolver.openOutputStream(saveUri); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, outputStream); outputStream.close(); setResult(RESULT_OK); finish(); } catch (IOException ex) { // } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { } } } } else { float scale = .5F; Matrix m = new Matrix(); m.setScale(scale, scale); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true); setResult(RESULT_OK, new Intent("inline-data").putExtra("data", bitmap)); finish(); } } else { /* * Save the image to a temp file and invoke the cropper */ Uri tempUri = null; FileOutputStream tempStream = null; try { File path = getFileStreamPath(sTempCropFilename); path.delete(); tempStream = openFileOutput(sTempCropFilename, 0); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, tempStream); tempStream.close(); tempUri = Uri.fromFile(path); } catch (FileNotFoundException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } catch (IOException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } finally { if (tempStream != null) { try { tempStream.close(); } catch (IOException ex) { } } } Bundle newExtras = new Bundle(); if (cropValue.equals("circle")) newExtras.putString("circleCrop", "true"); if (saveUri != null) newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, saveUri); else newExtras.putBoolean("return-data", true); Intent cropIntent = new Intent(); cropIntent.setClass(Camera.this, CropImage.class); cropIntent.setData(tempUri); cropIntent.putExtras(newExtras); startActivityForResult(cropIntent, CROP_MSG); } } private void doCancel() { setResult(RESULT_CANCELED, new Intent()); finish(); } public void onShutterButtonFocus(ShutterButton button, boolean pressed) { - if (mPausing) { + if (!mPreviewing || mPausing) { return; } switch (button.getId()) { case R.id.shutter_button: doFocus(pressed); break; } } public void onShutterButtonClick(ShutterButton button) { - if (mPausing) { + if (!mPreviewing || mPausing) { return; } switch (button.getId()) { case R.id.shutter_button: doSnap(); break; } } private void updateStorageHint() { updateStorageHint(MenuHelper.calculatePicturesRemaining()); } private OnScreenHint mStorageHint; private void updateStorageHint(int remaining) { String noStorageText = null; if (remaining == MenuHelper.NO_STORAGE_ERROR) { String state = Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING) { noStorageText = getString(R.string.preparing_sd); } else { noStorageText = getString(R.string.no_storage); } } else if (remaining < 1) { noStorageText = getString(R.string.not_enough_space); } if (noStorageText != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, noStorageText); } else { mStorageHint.setText(noStorageText); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } @Override public void onResume() { super.onResume(); mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); mPausing = false; mOrientationListener.enable(); mRecordLocation = mPreferences.getBoolean( "pref_camera_recordlocation_key", false); mGpsIndicator.setVisibility(View.INVISIBLE); // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); mDidRegister = true; mImageCapture = new ImageCapture(); restartPreview(); if (mRecordLocation) startReceivingLocationUpdates(); updateFocusIndicator(); try { mFocusToneGenerator = new ToneGenerator(AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME); } catch (RuntimeException e) { Log.w(TAG, "Exception caught while creating local tone generator: " + e); mFocusToneGenerator = null; } } private static ImageManager.DataLocation dataLocation() { return ImageManager.DataLocation.EXTERNAL; } @Override public void onStop() { keep(); stopPreview(); closeCamera(); mHandler.removeMessages(CLEAR_SCREEN_DELAY); super.onStop(); } @Override protected void onPause() { keep(); mPausing = true; mOrientationListener.disable(); stopPreview(); if (!mImageCapture.mCapturing) { closeCamera(); } if (mDidRegister) { unregisterReceiver(mReceiver); mDidRegister = false; } stopReceivingLocationUpdates(); if (mFocusToneGenerator != null) { mFocusToneGenerator.release(); mFocusToneGenerator = null; } if (!mIsImageCaptureIntent) { mThumbController.storeData(ImageManager.getLastImageThumbPath()); } if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } // If we are in an image capture intent and has taken // a picture, we just clear it in onPause. mImageCapture.clearLastBitmap(); mImageCapture = null; hidePostCaptureAlert(); super.onPause(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case CROP_MSG: { Intent intent = new Intent(); if (data != null) { Bundle extras = data.getExtras(); if (extras != null) { intent.putExtras(extras); } } setResult(resultCode, intent); finish(); File path = getFileStreamPath(sTempCropFilename); path.delete(); break; } } } private void autoFocus() { updateFocusIndicator(); if (mFocusState != FOCUSING && mFocusState != FOCUSING_SNAP_ON_FINISH) { if (mCameraDevice != null) { if (DEBUG_TIME_OPERATIONS) { mFocusStartTime = System.currentTimeMillis(); } mFocusState = FOCUSING; mCameraDevice.autoFocus(mAutoFocusCallback); } } } private void clearFocusState() { mFocusState = FOCUS_NOT_STARTED; } private void updateFocusIndicator() { mHandler.post(new Runnable() { public void run() { if (mFocusState == FOCUS_SUCCESS) { mFocusIndicator.setVisibility(View.VISIBLE); mFocusIndicator.clearAnimation(); } else if (mFocusState == FOCUS_FAIL) { mFocusIndicator.setVisibility(View.VISIBLE); mFocusIndicator.startAnimation(mFocusBlinkAnimation); } else { mFocusIndicator.setVisibility(View.GONE); mFocusIndicator.clearAnimation(); } } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mStatus == SNAPSHOT_IN_PROGRESS) { // ignore backs while we're taking a picture return true; } break; case KeyEvent.KEYCODE_FOCUS: if (event.getRepeatCount() == 0) { - doFocus(true); + if (mPreviewing) { + doFocus(true); + } } return true; case KeyEvent.KEYCODE_CAMERA: if (event.getRepeatCount() == 0) { - doSnap(); + if (mPreviewing) { + doSnap(); + } } return true; case KeyEvent.KEYCODE_DPAD_CENTER: // If we get a dpad center event without any focused view, move the // focus to the shutter button and press it. if (event.getRepeatCount() == 0) { // Start auto-focus immediately to reduce shutter lag. After the shutter button // gets the focus, doFocus() will be called again but it is fine. - doFocus(true); - if (mShutterButton.isInTouchMode()) { - mShutterButton.requestFocusFromTouch(); - } else { - mShutterButton.requestFocus(); + if (mPreviewing) { + doFocus(true); + if (mShutterButton.isInTouchMode()) { + mShutterButton.requestFocusFromTouch(); + } else { + mShutterButton.requestFocus(); + } + mShutterButton.setPressed(true); } - mShutterButton.setPressed(true); } return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_FOCUS: doFocus(false); return true; } return super.onKeyUp(keyCode, event); } private void doSnap() { // If the user has half-pressed the shutter and focus is completed, we // can take the photo right away. if ((mFocusState == FOCUS_SUCCESS || mFocusState == FOCUS_FAIL) || !mPreviewing) { // doesn't get set until the idler runs if (mCaptureObject != null) { mCaptureObject.onSnap(); } clearFocusState(); updateFocusIndicator(); } else if (mFocusState == FOCUSING) { // Half pressing the shutter (i.e. the focus button event) will // already have requested AF for us, so just request capture on // focus here. mFocusState = FOCUSING_SNAP_ON_FINISH; } else if (mFocusState == FOCUS_NOT_STARTED) { // Focus key down event is dropped for some reasons. Just ignore. } } private void doFocus(boolean pressed) { if (pressed) { // Focus key down. if (mPreviewing) { autoFocus(); } else if (mCaptureObject != null) { // Save and restart preview mCaptureObject.onSnap(); } } else { // Focus key up. if (mFocusState != FOCUSING_SNAP_ON_FINISH) { // User releases half-pressed focus key. clearFocusState(); updateFocusIndicator(); } } } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { mSurfaceView.setVisibility(View.VISIBLE); // if we're creating the surface, start the preview as well. boolean preview = holder.isCreating(); setViewFinder(w, h, preview); mCaptureObject = mImageCapture; } public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; } public void surfaceDestroyed(SurfaceHolder holder) { stopPreview(); mSurfaceHolder = null; } + // always call stopPreview before calling closeCamera private void closeCamera() { if (mCameraDevice != null) { mCameraDevice.release(); mCameraDevice = null; mPreviewing = false; } } - private boolean ensureCameraDevice() { - if (mCameraDevice == null) { - mCameraDevice = android.hardware.Camera.open(); - } - return mCameraDevice != null; - } - private void updateLastImage() { ImageManager.IImageList list = ImageManager.instance().allImages( this, mContentResolver, dataLocation(), ImageManager.INCLUDE_IMAGES, ImageManager.SORT_ASCENDING, ImageManager.CAMERA_IMAGE_BUCKET_ID); int count = list.getCount(); if (count > 0) { ImageManager.IImage image = list.getImageAt(count-1); Uri uri = image.fullSizeImageUri(); mThumbController.setData(uri, image.miniThumbBitmap()); } else { mThumbController.setData(null, null); } list.deactivate(); } private void restartPreview() { VideoPreview surfaceView = mSurfaceView; // make sure the surfaceview fills the whole screen when previewing surfaceView.setAspectRatio(VideoPreview.DONT_CARE); setViewFinder(mOriginalViewFinderWidth, mOriginalViewFinderHeight, true); mStatus = IDLE; // Calculate this in advance of each shot so we don't add to shutter latency. It's true that // someone else could write to the SD card in the mean time and fill it, but that could have // happened between the shutter press and saving the JPEG too. // TODO: The best longterm solution is to write a reserve file of maximum JPEG size, always // let the user take a picture, and delete that file if needed to save the new photo. calculatePicturesRemaining(); if (!mIsImageCaptureIntent && !mThumbController.isUriValid()) { updateLastImage(); } if (!mIsImageCaptureIntent) { mThumbController.updateDisplayIfNeeded(); } } private void setViewFinder(int w, int h, boolean startPreview) { if (mPausing) return; if (mPreviewing && w == mViewFinderWidth && h == mViewFinderHeight) { return; } - if (!ensureCameraDevice()) - return; - if (mSurfaceHolder == null) return; if (isFinishing()) return; if (mPausing) return; // remember view finder size mViewFinderWidth = w; mViewFinderHeight = h; if (mOriginalViewFinderHeight == 0) { mOriginalViewFinderWidth = w; mOriginalViewFinderHeight = h; } if (startPreview == false) return; /* - * start the preview if we're asked to... + * start preview on a separate thread */ + // start camera preview + synchronized(mCameraLock) { + if (mStartPreviewThread == null) { + mStartPreviewThread = new Thread(new Runnable() { + public void run() { + + // create camera object + synchronized(mCameraLock) { + if (mCameraDevice == null) { + mCameraDevice = android.hardware.Camera.open(); + } + } - // we want to start the preview and we're previewing already, - // stop the preview first (this will blank the screen). - if (mPreviewing) - stopPreview(); - - // this blanks the screen if the surface changed, no-op otherwise - try { - mCameraDevice.setPreviewDisplay(mSurfaceHolder); - } catch (IOException exception) { - mCameraDevice.release(); - mCameraDevice = null; - // TODO: add more exception handling logic here - return; - } + // we want to start the preview and we're previewing already, + // stop the preview first (this will blank the screen). + if (mPreviewing) + stopPreview(); - // request the preview size, the hardware may not honor it, - // if we depended on it we would have to query the size again - mParameters = mCameraDevice.getParameters(); - mParameters.setPreviewSize(w, h); - try { - mCameraDevice.setParameters(mParameters); - } catch (IllegalArgumentException e) { - // Ignore this error, it happens in the simulator. - } + // this blanks the screen if the surface changed, no-op otherwise + try { + mCameraDevice.setPreviewDisplay(mSurfaceHolder); + } catch (IOException exception) { + mCameraDevice.release(); + mCameraDevice = null; + // TODO: add more exception handling logic here + return; + } + // request the preview size, the hardware may not honor it, + // if we depended on it we would have to query the size again + mParameters = mCameraDevice.getParameters(); + mParameters.setPreviewSize(mViewFinderWidth, mViewFinderHeight); + try { + mCameraDevice.setParameters(mParameters); + } catch (IllegalArgumentException e) { + // Ignore this error, it happens in the simulator. + } - final long wallTimeStart = SystemClock.elapsedRealtime(); - final long threadTimeStart = Debug.threadCpuTimeNanos(); + final long wallTimeStart = SystemClock.elapsedRealtime(); + final long threadTimeStart = Debug.threadCpuTimeNanos(); - final Object watchDogSync = new Object(); - Thread watchDog = new Thread(new Runnable() { - public void run() { - int next_warning = 1; - while (true) { - try { - synchronized (watchDogSync) { - watchDogSync.wait(1000); + if (Config.LOGV) Log.v(TAG, "calling mCameraDevice.startPreview"); + try { + mCameraDevice.startPreview(); + } catch (Throwable e) { + // TODO: change Throwable to IOException once android.hardware.Camera.startPreview + // properly declares that it throws IOException. } - } catch (InterruptedException ex) { - // - } - if (mPreviewing) break; - - int delay = (int) (SystemClock.elapsedRealtime() - wallTimeStart) / 1000; - if (delay >= next_warning) { - if (delay < 120) { - Log.e(TAG, "preview hasn't started yet in " + delay + " seconds"); - } else { - Log.e(TAG, "preview hasn't started yet in " + (delay / 60) + " minutes"); + synchronized(mCameraLock) { + mPreviewing = true; + mStartPreviewThread = null; } - if (next_warning < 60) { - next_warning <<= 1; - if (next_warning == 16) { - next_warning = 15; - } - } else { - next_warning += 60; + + long threadTimeEnd = Debug.threadCpuTimeNanos(); + long wallTimeEnd = SystemClock.elapsedRealtime(); + if ((wallTimeEnd - wallTimeStart) > 3000) { + Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart) + " ms. Thread time was" + + (threadTimeEnd - threadTimeStart) / 1000000 + " ms."); } } - } - } - }); + }); - watchDog.start(); - - if (Config.LOGV) - Log.v(TAG, "calling mCameraDevice.startPreview"); - try { - mCameraDevice.startPreview(); - } catch (Throwable e) { - // TODO: change Throwable to IOException once android.hardware.Camera.startPreview - // properly declares that it throws IOException. + mStartPreviewThread.start(); + } } - mPreviewing = true; + } - synchronized (watchDogSync) { - watchDogSync.notify(); + // wait for preview thread if it is running + private void joinPreviewThread() { + Thread startPreviewThread; + synchronized(mCameraLock) { + startPreviewThread = mStartPreviewThread; } - - long threadTimeEnd = Debug.threadCpuTimeNanos(); - long wallTimeEnd = SystemClock.elapsedRealtime(); - if ((wallTimeEnd - wallTimeStart) > 3000) { - Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart) + " ms. Thread time was" - + (threadTimeEnd - threadTimeStart) / 1000000 + " ms."); + if (startPreviewThread != null) { + try { + startPreviewThread.join(); + } catch (InterruptedException ex) { + } } } private void stopPreview() { - if (mCameraDevice != null && mPreviewing) { - mCameraDevice.stopPreview(); + joinPreviewThread(); + synchronized(mCameraLock) { + if (mCameraDevice != null && mPreviewing) { + mCameraDevice.stopPreview(); + } + mPreviewing = false; } - mPreviewing = false; + // If auto focus was in progress, it would have been canceled. clearFocusState(); } void gotoGallery() { MenuHelper.gotoCameraImageGallery(this); } private void viewLastImage() { if (mThumbController.isUriValid()) { Uri targetUri = mThumbController.getUri(); targetUri = targetUri.buildUpon(). appendQueryParameter("bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build(); Intent intent = new Intent(Intent.ACTION_VIEW, targetUri); intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true); intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true); intent.putExtra("com.android.camera.ReviewMode", true); try { startActivity(intent); } catch (android.content.ActivityNotFoundException ex) { // ignore. } } else { Log.e(TAG, "Can't view last image."); } } void keep() { if (mCaptureObject != null) { mCaptureObject.dismissFreezeFrame(); } }; private ImageManager.IImage getImageForURI(Uri uri) { ImageManager.IImageList list = ImageManager.instance().allImages( this, mContentResolver, dataLocation(), ImageManager.INCLUDE_IMAGES, ImageManager.SORT_ASCENDING); ImageManager.IImage image = list.getImageForUri(uri); list.deactivate(); return image; } private void startReceivingLocationUpdates() { if (mLocationManager != null) { try { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 1000, 0F, mLocationListeners[1]); } catch (java.lang.SecurityException ex) { // ok } catch (IllegalArgumentException ex) { if (Config.LOGD) { Log.d(TAG, "provider does not exist " + ex.getMessage()); } } try { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 1000, 0F, mLocationListeners[0]); } catch (java.lang.SecurityException ex) { // ok } catch (IllegalArgumentException ex) { if (Config.LOGD) { Log.d(TAG, "provider does not exist " + ex.getMessage()); } } } } private void stopReceivingLocationUpdates() { if (mLocationManager != null) { for (int i = 0; i < mLocationListeners.length; i++) { try { mLocationManager.removeUpdates(mLocationListeners[i]); } catch (Exception ex) { // ok } } } } private Location getCurrentLocation() { // go in best to worst order for (int i = 0; i < mLocationListeners.length; i++) { Location l = mLocationListeners[i].current(); if (l != null) return l; } return null; } @Override public void onOptionsMenuClosed(Menu menu) { super.onOptionsMenuClosed(menu); if (mImageSavingItem) { // save the image if we presented the "advanced" menu // which happens if "menu" is pressed while in // SNAPSHOT_IN_PROGRESS or SNAPSHOT_COMPLETED modes keep(); mHandler.sendEmptyMessage(RESTART_PREVIEW); } } @Override public boolean onMenuOpened(int featureId, Menu menu) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { if (mStatus == SNAPSHOT_IN_PROGRESS) { cancelAutomaticPreviewRestart(); } } return super.onMenuOpened(featureId, menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); for (int i = 1; i <= MenuHelper.MENU_ITEM_MAX; i++) { if (i != MenuHelper.GENERIC_ITEM) { menu.setGroupVisible(i, false); } } if (mStatus == SNAPSHOT_IN_PROGRESS || mStatus == SNAPSHOT_COMPLETED) { menu.setGroupVisible(MenuHelper.IMAGE_SAVING_ITEM, true); mImageSavingItem = true; } else { menu.setGroupVisible(MenuHelper.IMAGE_MODE_ITEM, true); mImageSavingItem = false; } return true; } private void cancelAutomaticPreviewRestart() { mKeepAndRestartPreview = false; mHandler.removeMessages(RESTART_PREVIEW); } private boolean isImageCaptureIntent() { String action = getIntent().getAction(); return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)); } private void showPostCaptureAlert() { if (mIsImageCaptureIntent) { mPostCaptureAlert.setVisibility(View.VISIBLE); int[] pickIds = {R.id.attach, R.id.cancel}; for(int id : pickIds) { View view = mPostCaptureAlert.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } } private void hidePostCaptureAlert() { if (mIsImageCaptureIntent) { mPostCaptureAlert.setVisibility(View.INVISIBLE); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (mIsImageCaptureIntent) { // No options menu for attach mode. return false; } else { addBaseMenuItems(menu); } return true; } SelectedImageGetter mSelectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return getImageForURI(getCurrentImageUri()); } public Uri getCurrentImageUri() { keep(); return mCaptureObject.getLastCaptureUri(); } }; private int calculatePicturesRemaining() { mPicturesRemaining = MenuHelper.calculatePicturesRemaining(); return mPicturesRemaining; } private void addBaseMenuItems(Menu menu) { MenuHelper.addSwitchModeMenuItem(menu, this, true); { MenuItem gallery = menu.add(MenuHelper.IMAGE_MODE_ITEM, MENU_GALLERY_PHOTOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } { MenuItem gallery = menu.add(MenuHelper.VIDEO_MODE_ITEM, MENU_GALLERY_VIDEOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } MenuItem item = menu.add(MenuHelper.GENERIC_ITEM, MENU_SETTINGS, 0, R.string.settings).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(); intent.setClass(Camera.this, CameraSettings.class); startActivity(intent); return true; } }); item.setIcon(android.R.drawable.ic_menu_preferences); } }
brunsky/WS171-packages-apps-Camera
9e2f6d6911f7c193839abae96865ff3edb8eb540
Automated import from //branches/cupcake/...@141968,141968
diff --git a/src/com/android/camera/ViewImage.java b/src/com/android/camera/ViewImage.java index 5979db8..ad2ce77 100644 --- a/src/com/android/camera/ViewImage.java +++ b/src/com/android/camera/ViewImage.java @@ -1,1591 +1,1578 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.util.Random; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.util.AttributeSet; import android.util.Config; import android.util.Log; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import android.widget.Scroller; import android.widget.Toast; import android.widget.ZoomButtonsController; import com.android.camera.ImageManager.IImage; public class ViewImage extends Activity implements View.OnClickListener { private static final String TAG = "ViewImage"; private static final int TOUCH_AREA_WIDTH = 60; private ImageGetter mGetter; - private boolean mInitialized; - private Uri mCurrentUri; + private Uri mSavedUri; static final boolean sSlideShowHidesStatusBar = true; // Choices for what adjacents to load. static private final int[] sOrder_adjacents = new int[] { 0, 1, -1 }; static private final int[] sOrder_slideshow = new int[] { 0 }; private LocalHandler mHandler = new LocalHandler(); private Random mRandom = new Random(System.currentTimeMillis()); private int [] mShuffleOrder; private boolean mUseShuffleOrder = false; private boolean mSlideShowLoop = false; private static final int MODE_NORMAL = 1; private static final int MODE_SLIDESHOW = 2; private int mMode = MODE_NORMAL; private boolean mFullScreenInNormalMode; private boolean mShowActionIcons; private View mActionIconPanel; private View mShutterButton; private boolean mSortAscending = false; private int mSlideShowInterval; private int mLastSlideShowImage; private boolean mFirst = true; private int mCurrentPosition = 0; private boolean mLayoutComplete = false; // represents which style animation to use private int mAnimationIndex; private Animation [] mSlideShowInAnimation; private Animation [] mSlideShowOutAnimation; private SharedPreferences mPrefs; private View mNextImageView, mPrevImageView; private Animation mHideNextImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mHidePrevImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mShowNextImageViewAnimation = new AlphaAnimation(0F, 1F); private Animation mShowPrevImageViewAnimation = new AlphaAnimation(0F, 1F); static final int sPadding = 20; static final int sHysteresis = sPadding * 2; static final int sBaseScrollDuration = 1000; // ms private ImageManager.IImageList mAllImages; private int mSlideShowImageCurrent = 0; private ImageViewTouch [] mSlideShowImageViews = new ImageViewTouch[2]; private GestureDetector mGestureDetector; private ZoomButtonsController mZoomButtonsController; // Array of image views. The center view is the one the user is focused // on. The one at the zeroth position and the second position reflect // the images to the left/right of the center image. private ImageViewTouch[] mImageViews = new ImageViewTouch[3]; // Container for the three image views. This guy can be "scrolled" // to reveal the image prior to and after the center image. private ScrollHandler mScroller; private MenuHelper.MenuItemsResult mImageMenuRunnable; private Runnable mDismissOnScreenControlsRunnable; private boolean mCameraReviewMode; private int mCurrentOrientation; private void updateNextPrevControls() { boolean showPrev = mCurrentPosition > 0; boolean showNext = mCurrentPosition < mAllImages.getCount() - 1; boolean prevIsVisible = mPrevImageView.getVisibility() == View.VISIBLE; boolean nextIsVisible = mNextImageView.getVisibility() == View.VISIBLE; if (showPrev && !prevIsVisible) { Animation a = mShowPrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.VISIBLE); } else if (!showPrev && prevIsVisible) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.GONE); } if (showNext && !nextIsVisible) { Animation a = mShowNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.VISIBLE); } else if (!showNext && nextIsVisible) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.GONE); } } private void showOnScreenControls() { updateNextPrevControls(); updateZoomButtonsEnabled(); mZoomButtonsController.setVisible(true); scheduleDismissOnScreenControls(); } @Override public boolean dispatchTouchEvent(MotionEvent m) { boolean sup = super.dispatchTouchEvent(m); if (sup == false) { if (mMode == MODE_SLIDESHOW) { mSlideShowImageViews[mSlideShowImageCurrent].handleTouchEvent(m); } else if (mMode == MODE_NORMAL){ mImageViews[1].handleTouchEvent(m); } return true; } return true; } private void scheduleDismissOnScreenControls() { mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); mHandler.postDelayed(mDismissOnScreenControlsRunnable, 1500); } private void updateZoomButtonsEnabled() { ImageViewTouch imageView = mImageViews[1]; float scale = imageView.getScale(); mZoomButtonsController.setZoomInEnabled(scale < imageView.mMaxZoom); mZoomButtonsController.setZoomOutEnabled(scale > 1); } @Override protected void onDestroy() { // This is necessary to make the ZoomButtonsController unregister // its configuration change receiver. if (mZoomButtonsController != null) { mZoomButtonsController.setVisible(false); } super.onDestroy(); } private void setupZoomButtonController(View rootView) { mGestureDetector = new GestureDetector(this, new MyGestureListener()); mZoomButtonsController = new ZoomButtonsController(rootView); mZoomButtonsController.setAutoDismissed(false); mZoomButtonsController.setOnZoomListener( new ZoomButtonsController.OnZoomListener() { public void onVisibilityChanged(boolean visible) { if (visible) { updateZoomButtonsEnabled(); } } public void onZoom(boolean zoomIn) { if (zoomIn) { mImageViews[1].zoomIn(); } else { mImageViews[1].zoomOut(); } showOnScreenControls(); } }); } private class MyGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { ImageViewTouch imageView = mImageViews[1]; if (imageView.getScale() > 1F) { imageView.postTranslate(-distanceX, -distanceY, sUseBounce); imageView.center(true, true, false); } showOnScreenControls(); return true; } @Override public boolean onSingleTapUp(MotionEvent e) { int viewWidth = mImageViews[1].getWidth(); int x = (int) e.getX(); int y = (int) e.getY(); if (x < TOUCH_AREA_WIDTH) { moveNextOrPrevious(-1); } else if (x > viewWidth - TOUCH_AREA_WIDTH) { moveNextOrPrevious(1); } setMode(MODE_NORMAL); showOnScreenControls(); return true; } } private void setupDismissOnScreenControlRunnable() { mDismissOnScreenControlsRunnable = new Runnable() { public void run() { if (!mShowActionIcons) { if (mNextImageView.getVisibility() == View.VISIBLE) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.INVISIBLE); } if (mPrevImageView.getVisibility() == View.VISIBLE) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.INVISIBLE); } mZoomButtonsController.setVisible(false); } } }; } private boolean isPickIntent() { String action = getIntent().getAction(); return (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)); } private static final boolean sUseBounce = false; private static final boolean sAnimateTransitions = false; public static class ImageViewTouch extends ImageViewTouchBase { private ViewImage mViewImage; private boolean mEnableTrackballScroll; public ImageViewTouch(Context context) { super(context); mViewImage = (ViewImage) context; } public ImageViewTouch(Context context, AttributeSet attrs) { super(context, attrs); mViewImage = (ViewImage) context; } public void setEnableTrackballScroll(boolean enable) { mEnableTrackballScroll = enable; } protected void postTranslate(float dx, float dy, boolean bounceOK) { super.postTranslate(dx, dy); if (dx != 0F || dy != 0F) { mViewImage.showOnScreenControls(); } if (!sUseBounce) { center(true, false, false); } } protected ScrollHandler scrollHandler() { return mViewImage.mScroller; } public boolean handleTouchEvent(MotionEvent m) { return mViewImage.mGestureDetector.onTouchEvent(m); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Don't respond to arrow keys if trackball scrolling is not enabled if (!mEnableTrackballScroll) { if ((keyCode >= KeyEvent.KEYCODE_DPAD_UP) && (keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT)) { return super.onKeyDown(keyCode, event); } } int current = mViewImage.mCurrentPosition; int nextImagePos = -2; // default no next image try { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: { if (mViewImage.isPickIntent()) { ImageManager.IImage img = mViewImage.mAllImages.getImageAt(mViewImage.mCurrentPosition); mViewImage.setResult(RESULT_OK, new Intent().setData(img.fullSizeImageUri())); mViewImage.finish(); } break; } case KeyEvent.KEYCODE_DPAD_LEFT: { panBy(sPanRate, 0); int maxOffset = (current == 0) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(true, maxOffset)) { nextImagePos = current - 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_RIGHT: { panBy(-sPanRate, 0); int maxOffset = (current == mViewImage.mAllImages.getCount() - 1) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(false, maxOffset)) { nextImagePos = current + 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_UP: { panBy(0, sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DPAD_DOWN: { panBy(0, -sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DEL: MenuHelper.deletePhoto( mViewImage, mViewImage.mDeletePhotoRunnable); break; } } finally { if (nextImagePos >= 0 && nextImagePos < mViewImage.mAllImages.getCount()) { synchronized (mViewImage) { mViewImage.setMode(MODE_NORMAL); mViewImage.setImage(nextImagePos); } } else if (nextImagePos != -2) { center(true, true, false); } } return super.onKeyDown(keyCode, event); } protected boolean isShiftedToNextImage(boolean left, int maxOffset) { boolean retval; Bitmap bitmap = mBitmapDisplayed; Matrix m = getImageViewMatrix(); if (left) { float [] t1 = new float[] { 0, 0 }; m.mapPoints(t1); retval = t1[0] > maxOffset; } else { int width = bitmap != null ? bitmap.getWidth() : getWidth(); float [] t1 = new float[] { width, 0 }; m.mapPoints(t1); retval = t1[0] + maxOffset < getWidth(); } return retval; } protected void scrollX(int deltaX) { scrollHandler().scrollBy(deltaX, 0); } protected int getScrollOffset() { return scrollHandler().getScrollX(); } } static class ScrollHandler extends LinearLayout { private Runnable mFirstLayoutCompletedCallback = null; private Scroller mScrollerHelper; private int mWidth = -1; public ScrollHandler(Context context) { super(context); mScrollerHelper = new Scroller(context); } public ScrollHandler(Context context, AttributeSet attrs) { super(context, attrs); mScrollerHelper = new Scroller(context); } public void setLayoutCompletedCallback(Runnable r) { mFirstLayoutCompletedCallback = r; } public void startScrollTo(int newX, int newY) { int oldX = getScrollX(); int oldY = getScrollY(); int deltaX = newX - oldX; int deltaY = newY - oldY; if (mWidth == -1) { mWidth = findViewById(R.id.image2).getWidth(); } int viewWidth = mWidth; int duration = viewWidth > 0 ? sBaseScrollDuration * Math.abs(deltaX) / viewWidth : 0; mScrollerHelper.startScroll(oldX, oldY, deltaX, deltaY, duration); invalidate(); } @Override public void computeScroll() { if (mScrollerHelper.computeScrollOffset()) { scrollTo(mScrollerHelper.getCurrX(), mScrollerHelper.getCurrY()); postInvalidate(); // So we draw again } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int width = right - left; int x = 0; for (View v : new View[] { findViewById(R.id.image1), findViewById(R.id.image2), findViewById(R.id.image3) }) { v.layout(x, 0, x + width, bottom); x += (width + sPadding); } findViewById(R.id.padding1).layout(width, 0, width + sPadding, bottom); findViewById(R.id.padding2).layout(width+sPadding+width, 0, width+sPadding+width+sPadding, bottom); if (changed) { if (mFirstLayoutCompletedCallback != null) { mFirstLayoutCompletedCallback.run(); } } } } private void animateScrollTo(int xNew, int yNew) { mScroller.startScrollTo(xNew, yNew); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (! mCameraReviewMode) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.slide_show); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { setMode(MODE_SLIDESHOW); mLastSlideShowImage = mCurrentPosition; loadNextImage(mCurrentPosition, 0, true); return true; } }); item.setIcon(android.R.drawable.ic_menu_slideshow); } final SelectedImageGetter selectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return mAllImages.getImageAt(mCurrentPosition); } public Uri getCurrentImageUri() { return mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); } }; mImageMenuRunnable = MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL, true, ViewImage.this, mHandler, mDeletePhotoRunnable, new MenuHelper.MenuInvoker() { public void run(MenuHelper.MenuCallback cb) { setMode(MODE_NORMAL); cb.run(selectedImageGetter.getCurrentImageUri(), selectedImageGetter.getCurrentImage()); for (ImageViewTouchBase iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } setImage(mCurrentPosition); } }); if (true) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 1000, R.string.camerasettings); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent preferences = new Intent(); preferences.setClass(ViewImage.this, GallerySettings.class); startActivity(preferences); return true; } }); item.setAlphabeticShortcut('p'); item.setIcon(android.R.drawable.ic_menu_preferences); } // Hidden menu just so the shortcut will bring up the zoom controls menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.camerasettings) // the string resource is a placeholder .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { showOnScreenControls(); return true; } }) .setAlphabeticShortcut('z') .setVisible(false); return true; } protected Runnable mDeletePhotoRunnable = new Runnable() { public void run() { mAllImages.removeImageAt(mCurrentPosition); if (mAllImages.getCount() == 0) { finish(); } else { if (mCurrentPosition == mAllImages.getCount()) { mCurrentPosition -= 1; } } for (ImageViewTouchBase iv: mImageViews) { iv.setImageBitmapResetBase(null, true, true); } setImage(mCurrentPosition); } }; @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); setMode(MODE_NORMAL); if (mImageMenuRunnable != null) { mImageMenuRunnable.gettingReadyToOpen(menu, mAllImages.getImageAt(mCurrentPosition)); } return true; } @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean changed = mCurrentOrientation != newConfig.orientation; mCurrentOrientation = newConfig.orientation; if (changed) { if (mGetter != null) { // kill off any background image fetching mGetter.cancelCurrent(); mGetter.stop(); } makeGetter(); mFirst = true; // clear off the current set of images since we need to reload // them at the right size for (ImageViewTouchBase iv: mImageViews) { iv.clear(); } MenuHelper.requestOrientation(this, mPrefs); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { boolean b = super.onMenuItemSelected(featureId, item); if (mImageMenuRunnable != null) mImageMenuRunnable.aboutToCall(item, mAllImages.getImageAt(mCurrentPosition)); return b; } /* * Here's the loading strategy. For any given image, load the thumbnail * into memory and post a callback to display the resulting bitmap. * * Then proceed to load the full image bitmap. Three things can * happen at this point: * * 1. the image fails to load because the UI thread decided * to move on to a different image. This "cancellation" happens * by virtue of the UI thread closing the stream containing the * image being decoded. BitmapFactory.decodeStream returns null * in this case. * * 2. the image loaded successfully. At that point we post * a callback to the UI thread to actually show the bitmap. * * 3. when the post runs it checks to see if the image that was * loaded is still the one we want. The UI may have moved on * to some other image and if so we just drop the newly loaded * bitmap on the floor. */ interface ImageGetterCallback { public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb); public boolean wantsThumbnail(int pos, int offset); public boolean wantsFullImage(int pos, int offset); public int fullImageSizeToUse(int pos, int offset); public void completed(boolean wasCanceled); public int [] loadOrder(); } class ImageGetter { // The thread which does the work. private Thread mGetterThread; // The base position that's being retrieved. The actual images retrieved // are this base plus each of the offets. private int mCurrentPosition = -1; // The callback to invoke for each image. private ImageGetterCallback mCB; // This is the loader cancelable that gets set while we're loading an image. // If we change position we can cancel the current load using this. private ImageManager.IGetBitmap_cancelable mLoad; // True if we're canceling the current load. private boolean mCancelCurrent = false; // True when the therad should exit. private boolean mDone = false; // True when the loader thread is waiting for work. private boolean mReady = false; private void cancelCurrent() { synchronized (this) { if (!mReady) { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { if (Config.LOGV) Log.v(TAG, "canceling load object"); load.cancel(); } mCancelCurrent = false; } } } public ImageGetter() { mGetterThread = new Thread(new Runnable() { private Runnable callback(final int position, final int offset, final boolean isThumb, final Bitmap bitmap) { return new Runnable() { public void run() { // check for inflight callbacks that aren't applicable any longer // before delivering them if (!isCanceled() && position == mCurrentPosition) { mCB.imageLoaded(position, offset, bitmap, isThumb); } else { if (bitmap != null) bitmap.recycle(); } } }; } private Runnable completedCallback(final boolean wasCanceled) { return new Runnable() { public void run() { mCB.completed(wasCanceled); } }; } public void run() { int lastPosition = -1; while (!mDone) { synchronized (ImageGetter.this) { mReady = true; ImageGetter.this.notify(); if (mCurrentPosition == -1 || lastPosition == mCurrentPosition) { try { ImageGetter.this.wait(); } catch (InterruptedException ex) { continue; } } lastPosition = mCurrentPosition; mReady = false; } if (lastPosition != -1) { int imageCount = mAllImages.getCount(); int [] order = mCB.loadOrder(); for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (image == null || isCanceled()) { break; } if (mCB.wantsThumbnail(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting THUMBNAIL load at offset " + offset); Bitmap b = image.thumbBitmap(); mHandler.postGetterCallback(callback(lastPosition, offset, true, b)); } } } for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (mCB.wantsFullImage(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting FULL IMAGE load at offset " + offset); int sizeToUse = mCB.fullImageSizeToUse(lastPosition, offset); if (image != null && !isCanceled()) { mLoad = image.fullSizeBitmap_cancelable(sizeToUse); } if (mLoad != null) { long t1; if (Config.LOGV) t1 = System.currentTimeMillis(); // The return value could be null if the // bitmap is too big, or we cancelled it. Bitmap b = mLoad.get(); if (Config.LOGV && b != null) { long t2 = System.currentTimeMillis(); Log.v(TAG, "loading full image for " + image.fullSizeImageUri() + " with requested size " + sizeToUse + " took " + (t2 - t1) + " and returned a bitmap with size " + b.getWidth() + " / " + b.getHeight()); } mLoad = null; if (b != null) { if (isCanceled()) { b.recycle(); } else { mHandler.postGetterCallback(callback(lastPosition, offset, false, b)); } } } } } } mHandler.postGetterCallback(completedCallback(isCanceled())); } } } }); mGetterThread.setName("ImageGettter"); mGetterThread.start(); } private boolean isCanceled() { synchronized (this) { return mCancelCurrent; } } public void setPosition(int position, ImageGetterCallback cb) { synchronized (this) { if (!mReady) { try { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { load.cancel(); } // if the thread is waiting before loading the full size // image then this will free it up ImageGetter.this.notify(); ImageGetter.this.wait(); mCancelCurrent = false; } catch (InterruptedException ex) { // not sure what to do here } } } mCurrentPosition = position; mCB = cb; synchronized (this) { ImageGetter.this.notify(); } } public void stop() { synchronized (this) { mDone = true; ImageGetter.this.notify(); } try { mGetterThread.join(); } catch (InterruptedException ex) { } } } private void setImage(int pos) { if (!mLayoutComplete) { return; } final boolean left = (pos == mCurrentPosition - 1); final boolean right = (pos == mCurrentPosition + 1); mCurrentPosition = pos; ImageViewTouchBase current = mImageViews[1]; current.mSuppMatrix.reset(); current.setImageMatrix(current.getImageViewMatrix()); if (false) { Log.v(TAG, "before..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } if (!mFirst) { if (left) { mImageViews[2].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[0]); } else if (right) { mImageViews[0].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[2]); } } if (false) { Log.v(TAG, "after copy..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } for (ImageViewTouchBase ivt: mImageViews) { ivt.mIsZooming = false; } int width = mImageViews[1].getWidth(); int from; int to = width + sPadding; if (mFirst) { from = to; mFirst = false; } else { from = left ? (width + sPadding) + mScroller.getScrollX() : mScroller.getScrollX() - (width + sPadding); } if (sAnimateTransitions) { mScroller.scrollTo(from, 0); animateScrollTo(to, 0); } else { mScroller.scrollTo(to, 0); } ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { if (!mShowActionIcons) { mImageViews[1].setFocusableInTouchMode(true); mImageViews[1].requestFocus(); } } public boolean wantsThumbnail(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; return ivt.mThumbBitmap == null; } public boolean wantsFullImage(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; if (ivt.mBitmapDisplayed != null && !ivt.mBitmapIsThumbnail) { return false; } if (offset != 0) { return false; } return true; } public int fullImageSizeToUse(int pos, int offset) { // TODO // this number should be bigger so that we can zoom. we may need to // get fancier and read in the fuller size image as the user starts // to zoom. use -1 to get the full full size image. // for now use 480 so we don't run out of memory final int imageViewSize = 480; return imageViewSize; } public int [] loadOrder() { return sOrder_adjacents; } public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb) { // shouldn't get here after onPause() ImageViewTouchBase ivt = mImageViews[1 + offset]; if (offset == 0) updateZoomButtonsEnabled(); ivt.setImageBitmapResetBase(bitmap, isThumb, isThumb); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { mGetter.setPosition(pos, cb); } showOnScreenControls(); } @Override public void onCreate(Bundle instanceState) { super.onCreate(instanceState); Intent intent = getIntent(); mCameraReviewMode = intent.getBooleanExtra("com.android.camera.ReviewMode", false); mFullScreenInNormalMode = intent.getBooleanExtra(MediaStore.EXTRA_FULL_SCREEN, true); mShowActionIcons = intent.getBooleanExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, false); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mCurrentOrientation = getResources().getConfiguration().orientation; setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.viewimage); mImageViews[0] = (ImageViewTouch) findViewById(R.id.image1); mImageViews[1] = (ImageViewTouch) findViewById(R.id.image2); mImageViews[2] = (ImageViewTouch) findViewById(R.id.image3); for(ImageViewTouch v : mImageViews) { v.setEnableTrackballScroll(!mShowActionIcons); } mScroller = (ScrollHandler)findViewById(R.id.scroller); makeGetter(); mAnimationIndex = -1; mSlideShowInAnimation = new Animation[] { makeInAnimation(R.anim.transition_in), makeInAnimation(R.anim.slide_in), makeInAnimation(R.anim.slide_in_vertical), }; mSlideShowOutAnimation = new Animation[] { makeOutAnimation(R.anim.transition_out), makeOutAnimation(R.anim.slide_out), makeOutAnimation(R.anim.slide_out_vertical), }; mSlideShowImageViews[0] = (ImageViewTouch) findViewById(R.id.image1_slideShow); mSlideShowImageViews[1] = (ImageViewTouch) findViewById(R.id.image2_slideShow); for (ImageViewTouch v : mSlideShowImageViews) { v.setImageBitmapResetBase(null, true, true); v.setVisibility(View.INVISIBLE); v.setEnableTrackballScroll(!mShowActionIcons); } mActionIconPanel = findViewById(R.id.action_icon_panel); { int[] pickIds = {R.id.attach, R.id.cancel}; int[] normalIds = {R.id.gallery, R.id.setas, R.id.share, R.id.discard}; int[] hideIds = pickIds; int[] connectIds = normalIds; if (isPickIntent()) { hideIds = normalIds; connectIds = pickIds; } for(int id : hideIds) { mActionIconPanel.findViewById(id).setVisibility(View.GONE); } for(int id : connectIds) { View view = mActionIconPanel.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } mShutterButton = findViewById(R.id.shutter_button); mShutterButton.setOnClickListener(this); - mCurrentUri = getIntent().getData(); + Uri uri = getIntent().getData(); if (Config.LOGV) - Log.v(TAG, "uri is " + mCurrentUri); + Log.v(TAG, "uri is " + uri); if (instanceState != null) { if (instanceState.containsKey("uri")) { - mCurrentUri = Uri.parse(instanceState.getString("uri")); + uri = Uri.parse(instanceState.getString("uri")); } } - if (mCurrentUri == null) { + if (uri == null) { finish(); return; } - init(mCurrentUri); + init(uri); Bundle b = getIntent().getExtras(); boolean slideShow = b != null ? b.getBoolean("slideshow", false) : false; if (slideShow) { setMode(MODE_SLIDESHOW); loadNextImage(mCurrentPosition, 0, true); } else { if (mFullScreenInNormalMode) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } } setupZoomButtonController(findViewById(R.id.rootLayout)); setupDismissOnScreenControlRunnable(); mNextImageView = findViewById(R.id.next_image); mPrevImageView = findViewById(R.id.prev_image); mNextImageView.setOnClickListener(this); mPrevImageView.setOnClickListener(this); if (mShowActionIcons) { mNextImageView.setFocusable(true); mPrevImageView.setFocusable(true); } setOrientation(); } private void setOrientation() { Intent intent = getIntent(); if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); if (orientation != getRequestedOrientation()) { setRequestedOrientation(orientation); } } else { MenuHelper.requestOrientation(this, mPrefs); } } private Animation makeInAnimation(int id) { Animation inAnimation = AnimationUtils.loadAnimation(this, id); return inAnimation; } private Animation makeOutAnimation(int id) { Animation outAnimation = AnimationUtils.loadAnimation(this, id); return outAnimation; } private void setMode(int mode) { if (mMode == mode) { return; } findViewById(R.id.slideShowContainer).setVisibility(mode == MODE_SLIDESHOW ? View.VISIBLE : View.GONE); findViewById(R.id.abs) .setVisibility(mode == MODE_NORMAL ? View.VISIBLE : View.GONE); Window win = getWindow(); mMode = mode; if (mode == MODE_SLIDESHOW) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (sSlideShowHidesStatusBar) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } for (ImageViewTouchBase ivt: mImageViews) { ivt.clear(); } mActionIconPanel.setVisibility(View.GONE); mShutterButton.setVisibility(View.GONE); if (false) { Log.v(TAG, "current is " + this.mSlideShowImageCurrent); this.mSlideShowImageViews[0].dump(); this.mSlideShowImageViews[0].dump(); } findViewById(R.id.slideShowContainer).getRootView().requestLayout(); mUseShuffleOrder = mPrefs.getBoolean("pref_gallery_slideshow_shuffle_key", false); mSlideShowLoop = mPrefs.getBoolean("pref_gallery_slideshow_repeat_key", false); try { mAnimationIndex = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_transition_key", "0")); } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mAnimationIndex = 0; } try { mSlideShowInterval = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_interval_key", "3")) * 1000; } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mSlideShowInterval = 3000; } if (Config.LOGV) { Log.v(TAG, "read prefs... shuffle: " + mUseShuffleOrder); Log.v(TAG, "read prefs... loop: " + mSlideShowLoop); Log.v(TAG, "read prefs... animidx: " + mAnimationIndex); Log.v(TAG, "read prefs... interval: " + mSlideShowInterval); } if (mUseShuffleOrder) { generateShuffleOrder(); } } else { if (Config.LOGV) Log.v(TAG, "slide show mode off, mCurrentPosition == " + mCurrentPosition); win.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (mFullScreenInNormalMode) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mGetter != null) mGetter.cancelCurrent(); if (sSlideShowHidesStatusBar) { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } ImageViewTouchBase dst = mImageViews[1]; dst.mLastXTouchPos = -1; dst.mLastYTouchPos = -1; for (ImageViewTouchBase ivt: mSlideShowImageViews) { ivt.clear(); } mShuffleOrder = null; // mGetter null is a proxy for being paused if (mGetter != null) { mFirst = true; // don't animate setImage(mCurrentPosition); } } // this line shouldn't be necessary but the view hierarchy doesn't // seem to realize that the window layout changed mScroller.requestLayout(); } private void generateShuffleOrder() { if (mShuffleOrder == null || mShuffleOrder.length != mAllImages.getCount()) { mShuffleOrder = new int[mAllImages.getCount()]; } for (int i = 0; i < mShuffleOrder.length; i++) { mShuffleOrder[i] = i; } for (int i = mShuffleOrder.length - 1; i > 0; i--) { int r = mRandom.nextInt(i); int tmp = mShuffleOrder[r]; mShuffleOrder[r] = mShuffleOrder[i]; mShuffleOrder[i] = tmp; } } private void loadNextImage(final int requestedPos, final long delay, final boolean firstCall) { if (firstCall && mUseShuffleOrder) { generateShuffleOrder(); } final long targetDisplayTime = System.currentTimeMillis() + delay; ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { } public boolean wantsThumbnail(int pos, int offset) { return true; } public boolean wantsFullImage(int pos, int offset) { return false; } public int [] loadOrder() { return sOrder_slideshow; } public int fullImageSizeToUse(int pos, int offset) { return 480; // TODO compute this } public void imageLoaded(final int pos, final int offset, final Bitmap bitmap, final boolean isThumb) { long timeRemaining = Math.max(0, targetDisplayTime - System.currentTimeMillis()); mHandler.postDelayedGetterCallback(new Runnable() { public void run() { if (mMode == MODE_NORMAL) return; ImageViewTouchBase oldView = mSlideShowImageViews[mSlideShowImageCurrent]; if (++mSlideShowImageCurrent == mSlideShowImageViews.length) { mSlideShowImageCurrent = 0; } ImageViewTouchBase newView = mSlideShowImageViews[mSlideShowImageCurrent]; newView.setVisibility(View.VISIBLE); newView.setImageBitmapResetBase(bitmap, isThumb, isThumb); newView.bringToFront(); int animation = 0; if (mAnimationIndex == -1) { int n = mRandom.nextInt(mSlideShowInAnimation.length); animation = n; } else { animation = mAnimationIndex; } Animation aIn = mSlideShowInAnimation[animation]; newView.setAnimation(aIn); newView.setVisibility(View.VISIBLE); aIn.startNow(); Animation aOut = mSlideShowOutAnimation[animation]; oldView.setVisibility(View.INVISIBLE); oldView.setAnimation(aOut); aOut.startNow(); mCurrentPosition = requestedPos; if (mCurrentPosition == mLastSlideShowImage && !firstCall) { if (mSlideShowLoop) { if (mUseShuffleOrder) { generateShuffleOrder(); } } else { setMode(MODE_NORMAL); return; } } if (Config.LOGV) Log.v(TAG, "mCurrentPosition is now " + mCurrentPosition); loadNextImage((mCurrentPosition + 1) % mAllImages.getCount(), mSlideShowInterval, false); } }, timeRemaining); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { int pos = requestedPos; if (mShuffleOrder != null) { pos = mShuffleOrder[pos]; } mGetter.setPosition(pos, cb); } } private void makeGetter() { mGetter = new ImageGetter(); } private boolean desiredSortOrder() { String sortOrder = mPrefs.getString("pref_gallery_sort_key", null); boolean sortAscending = false; if (sortOrder != null) { sortAscending = sortOrder.equals("ascending"); } if (mCameraReviewMode) { // Force left-arrow older pictures, right-arrow newer pictures. sortAscending = true; } return sortAscending; } private void init(Uri uri) { - if (mInitialized || (uri == null)) + if (uri == null) return; mSortAscending = desiredSortOrder(); int sort = mSortAscending ? ImageManager.SORT_ASCENDING : ImageManager.SORT_DESCENDING; mAllImages = ImageManager.makeImageList(uri, this, sort); uri = uri.buildUpon().query(null).build(); // TODO smarter/faster here please for (int i = 0; i < mAllImages.getCount(); i++) { ImageManager.IImage image = mAllImages.getImageAt(i); if (image.fullSizeImageUri().equals(uri)) { mCurrentPosition = i; mLastSlideShowImage = mCurrentPosition; break; } } - mInitialized = true; } - @Override - public void onSaveInstanceState(Bundle b) { - super.onSaveInstanceState(b); + private Uri getCurrentUri() { ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); - + Uri uri = null; if (image != null){ - Uri uri = image.fullSizeImageUri(); String bucket = null; - if(getIntent()!= null && getIntent().getData()!=null) + uri = image.fullSizeImageUri(); + if(getIntent() != null && getIntent().getData() != null) bucket = getIntent().getData().getQueryParameter("bucketId"); - if(bucket!=null) + if(bucket != null) uri = uri.buildUpon().appendQueryParameter("bucketId", bucket).build(); - - b.putString("uri", uri.toString()); } - if (mMode == MODE_SLIDESHOW) - b.putBoolean("slideshow", true); + return uri; } - protected void onRestoreInstanceState (Bundle b) { - if (b.containsKey("uri")) { - mCurrentUri = Uri.parse(b.getString("uri")); + @Override + public void onSaveInstanceState(Bundle b) { + super.onSaveInstanceState(b); + + Uri uri = getCurrentUri(); + if (uri != null) { + b.putString("uri", uri.toString()); + } + + if (mMode == MODE_SLIDESHOW) { + b.putBoolean("slideshow", true); } } - + @Override public void onResume() { super.onResume(); - if (mCurrentUri != null) { - init(mCurrentUri); - } + init(mSavedUri); // normally this will never be zero but if one "backs" into this // activity after removing the sdcard it could be zero. in that // case just "finish" since there's nothing useful that can happen. - if (mAllImages.getCount() == 0) { + int count = mAllImages.getCount(); + if (count == 0) { finish(); + } else if (count <= mCurrentPosition) { + mCurrentPosition = count - 1; } - mCurrentPosition = mAllImages.getCount() - 1; ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); - if (desiredSortOrder() != mSortAscending) { - init(image.fullSizeImageUri()); - } - if (mGetter == null) { makeGetter(); } mFirst = true; mScroller.setLayoutCompletedCallback(new Runnable() { public void run() { mLayoutComplete = true; setImage(mCurrentPosition); } }); setImage(mCurrentPosition); setOrientation(); } @Override public void onPause() { super.onPause(); mGetter.cancelCurrent(); mGetter.stop(); mGetter = null; setMode(MODE_NORMAL); // removing all callback in the message queue mHandler.removeAllGetterCallbacks(); + + mSavedUri = getCurrentUri(); mAllImages.deactivate(); mDismissOnScreenControlsRunnable.run(); if (mDismissOnScreenControlsRunnable != null) mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); for (ImageViewTouch iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } for (ImageViewTouch iv: mSlideShowImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } - - mInitialized = false; - } - - @Override - public void onStop() { - super.onStop(); } public void onClick(View v) { switch (v.getId()) { case R.id.shutter_button: { if (mCameraReviewMode) { finish(); } else { MenuHelper.gotoStillImageCapture(this); } } break; case R.id.gallery: { MenuHelper.gotoCameraImageGallery(this); } break; case R.id.discard: { MenuHelper.deletePhoto(this, mDeletePhotoRunnable); } break; case R.id.share: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_STREAM, u); try { startActivity(Intent.createChooser(intent, getText(R.string.sendImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_image, Toast.LENGTH_SHORT).show(); } } break; case R.id.setas: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA, u); try { startActivity(Intent.createChooser(intent, getText(R.string.setImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } break; case R.id.next_image: { moveNextOrPrevious(1); } break; case R.id.prev_image: { moveNextOrPrevious(-1); } break; } } private void moveNextOrPrevious(int delta) { int nextImagePos = mCurrentPosition + delta; if ((0 <= nextImagePos) && (nextImagePos < mAllImages.getCount())) { setImage(nextImagePos); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case MenuHelper.RESULT_COMMON_MENU_CROP: if (resultCode == RESULT_OK) { // The CropImage activity passes back the Uri of the cropped image as // the Action rather than the Data. - Uri dataUri = Uri.parse(data.getAction()); - init(dataUri); - // Clear mImageViews so we can reload the correct image in onResume(). - for (ImageViewTouch iv: mImageViews) { - iv.clear(); - } + mSavedUri = Uri.parse(data.getAction()); } break; } } static class LocalHandler extends Handler { private static final int IMAGE_GETTER_CALLBACK = 1; @Override public void handleMessage(Message message) { switch(message.what) { case IMAGE_GETTER_CALLBACK: ((Runnable) message.obj).run(); } } public void postGetterCallback(Runnable callback) { postDelayedGetterCallback(callback, 0); } public void postDelayedGetterCallback(Runnable callback, long delay) { if (callback == null) throw new NullPointerException(); Message message = Message.obtain(); message.what = IMAGE_GETTER_CALLBACK; message.obj = callback; sendMessageDelayed(message, delay); } public void removeAllGetterCallbacks() { removeMessages(IMAGE_GETTER_CALLBACK); } } }
brunsky/WS171-packages-apps-Camera
1d75a01d244fdf0dad1a14417c7b72169f551779
Automated import from //branches/cupcake/...@141966,141966
diff --git a/src/com/android/camera/ImageGallery2.java b/src/com/android/camera/ImageGallery2.java index 1e02555..8f9456b 100644 --- a/src/com/android/camera/ImageGallery2.java +++ b/src/com/android/camera/ImageGallery2.java @@ -1,776 +1,776 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import android.content.BroadcastReceiver; import android.app.Activity; import android.app.Dialog; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.util.AttributeSet; import android.util.Config; import android.util.Log; import android.view.ContextMenu; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.Window; import android.widget.TextView; import android.widget.Toast; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.widget.Scroller; import java.util.Calendar; import java.util.GregorianCalendar; import com.android.camera.ImageManager.IImage; public class ImageGallery2 extends Activity { private static final String TAG = "ImageGallery2"; private ImageManager.IImageList mAllImages; private int mInclusion; private boolean mSortAscending = false; private View mNoImagesView; public final static int CROP_MSG = 2; public final static int VIEW_MSG = 3; private static final String INSTANCE_STATE_TAG = "scrollY"; private Dialog mMediaScanningDialog; private MenuItem mSlideShowItem; private SharedPreferences mPrefs; private long mVideoSizeLimit = Long.MAX_VALUE; public ImageGallery2() { } BroadcastReceiver mReceiver = null; Handler mHandler = new Handler(); boolean mLayoutComplete; boolean mPausing = false; boolean mStopThumbnailChecking = false; CameraThread mThumbnailCheckThread; GridViewSpecial mGvs; @Override public void onCreate(Bundle icicle) { if (Config.LOGV) Log.v(TAG, "onCreate"); super.onCreate(icicle); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // must be called before setContentView() setContentView(R.layout.image_gallery_2); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_gallery_title); if (Config.LOGV) Log.v(TAG, "findView... " + findViewById(R.id.loading_indicator)); mGvs = (GridViewSpecial) findViewById(R.id.grid); mGvs.requestFocus(); if (isPickIntent()) { mVideoSizeLimit = getIntent().getLongExtra( MediaStore.EXTRA_SIZE_LIMIT, Long.MAX_VALUE); mGvs.mVideoSizeLimit = mVideoSizeLimit; } else { mVideoSizeLimit = Long.MAX_VALUE; mGvs.mVideoSizeLimit = mVideoSizeLimit; mGvs.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { if (mSelectedImageGetter.getCurrentImage() == null) return; boolean isImage = ImageManager.isImage(mSelectedImageGetter.getCurrentImage()); if (isImage) { menu.add(0, 0, 0, R.string.view).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { mGvs.onSelect(mGvs.mCurrentSelection); return true; } }); } menu.setHeaderTitle(isImage ? R.string.context_menu_header : R.string.video_context_menu_header); if ((mInclusion & (ImageManager.INCLUDE_IMAGES | ImageManager.INCLUDE_VIDEOS)) != 0) { MenuHelper.MenuItemsResult r = MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL, isImage, ImageGallery2.this, mHandler, mDeletePhotoRunnable, new MenuHelper.MenuInvoker() { public void run(MenuHelper.MenuCallback cb) { cb.run(mSelectedImageGetter.getCurrentImageUri(), mSelectedImageGetter.getCurrentImage()); mGvs.clearCache(); mGvs.invalidate(); mGvs.requestLayout(); mGvs.start(); mNoImagesView.setVisibility(mAllImages.getCount() > 0 ? View.GONE : View.VISIBLE); } }); if (r != null) r.gettingReadyToOpen(menu, mSelectedImageGetter.getCurrentImage()); if (isImage) { addSlideShowMenu(menu, 1000); } } } }); } } private MenuItem addSlideShowMenu(Menu menu, int position) { return menu.add(0, 207, position, R.string.slide_show) .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { ImageManager.IImage img = mSelectedImageGetter.getCurrentImage(); if (img == null) { img = mAllImages.getImageAt(0); if (img == null) { return true; } } Uri targetUri = img.fullSizeImageUri(); Uri thisUri = getIntent().getData(); if (thisUri != null) { String bucket = thisUri.getQueryParameter("bucketId"); if (bucket != null) { targetUri = targetUri.buildUpon().appendQueryParameter("bucketId", bucket).build(); } } Intent intent = new Intent(Intent.ACTION_VIEW, targetUri); intent.putExtra("slideshow", true); startActivity(intent); return true; } }) .setIcon(android.R.drawable.ic_menu_slideshow); } private Runnable mDeletePhotoRunnable = new Runnable() { public void run() { mGvs.clearCache(); IImage currentImage = mSelectedImageGetter.getCurrentImage(); if (currentImage != null) { mAllImages.removeImage(currentImage); } mGvs.invalidate(); mGvs.requestLayout(); mGvs.start(); mNoImagesView.setVisibility(mAllImages.isEmpty() ? View.VISIBLE : View.GONE); } }; private SelectedImageGetter mSelectedImageGetter = new SelectedImageGetter() { public Uri getCurrentImageUri() { ImageManager.IImage image = getCurrentImage(); if (image != null) return image.fullSizeImageUri(); else return null; } public ImageManager.IImage getCurrentImage() { int currentSelection = mGvs.mCurrentSelection; if (currentSelection < 0 || currentSelection >= mAllImages.getCount()) return null; else return mAllImages.getImageAt(currentSelection); } }; @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); mTargetScroll = mGvs.getScrollY(); } private Runnable mLongPressCallback = new Runnable() { public void run() { mGvs.select(-2, false); mGvs.showContextMenu(); } }; - private boolean isPaused() { + private boolean canHandleEvent() { // Don't process event in pause state. - return mPausing; + return (!mPausing) && (mGvs.mCurrentSpec != null); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { - if (isPaused()) return false; + if (!canHandleEvent()) return false; if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { mGvs.select(-2, false); // The keyUp doesn't get called when the longpress menu comes up. We only get here when the user // lets go of the center key before the longpress menu comes up. mHandler.removeCallbacks(mLongPressCallback); // open the photo if (mSelectedImageGetter.getCurrentImage() != null) { mGvs.onSelect(mGvs.mCurrentSelection); } return true; } return super.onKeyUp(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { - if (isPaused()) return false; + if (!canHandleEvent()) return false; boolean handled = true; int sel = mGvs.mCurrentSelection; int columns = mGvs.mCurrentSpec.mColumns; int count = mAllImages.getCount(); boolean pressed = false; if (mGvs.mShowSelection) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_RIGHT: if (sel != count && (sel % columns < columns - 1)) { sel += 1; } break; case KeyEvent.KEYCODE_DPAD_LEFT: if (sel > 0 && (sel % columns != 0)) { sel -= 1; } break; case KeyEvent.KEYCODE_DPAD_UP: if ((sel / columns) != 0) { sel -= columns; } break; case KeyEvent.KEYCODE_DPAD_DOWN: if ((sel / columns) != (sel+columns / columns)) { sel = Math.min(count-1, sel + columns); } break; case KeyEvent.KEYCODE_DPAD_CENTER: pressed = true; mHandler.postDelayed(mLongPressCallback, ViewConfiguration.getLongPressTimeout()); break; case KeyEvent.KEYCODE_DEL: MenuHelper.deleteImage(this, mDeletePhotoRunnable, mSelectedImageGetter.getCurrentImage()); break; default: handled = false; break; } } else { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_RIGHT: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_DOWN: int [] range = new int[2]; GridViewSpecial.ImageBlockManager ibm = mGvs.mImageBlockManager; if (ibm != null) { mGvs.mImageBlockManager.getVisibleRange(range); int topPos = range[0]; android.graphics.Rect r = mGvs.getRectForPosition(topPos); if (r.top < mGvs.getScrollY()) topPos += columns; topPos = Math.min(count - 1, topPos); sel = topPos; } break; default: handled = false; break; } } if (handled) { mGvs.select(sel, pressed); return true; } else return super.onKeyDown(keyCode, event); } private boolean isPickIntent() { String action = getIntent().getAction(); return (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)); } private void launchCropperOrFinish(ImageManager.IImage img) { Bundle myExtras = getIntent().getExtras(); long size = MenuHelper.getImageFileSize(img); if (size < 0) { // return if there image file is not available. return; } if (size > mVideoSizeLimit) { DialogInterface.OnClickListener buttonListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }; new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle(R.string.file_info_title) .setMessage(R.string.video_exceed_mms_limit) .setNeutralButton(R.string.details_ok, buttonListener) .show(); return; } String cropValue = myExtras != null ? myExtras.getString("crop") : null; if (cropValue != null) { Bundle newExtras = new Bundle(); if (cropValue.equals("circle")) newExtras.putString("circleCrop", "true"); Intent cropIntent = new Intent(); cropIntent.setData(img.fullSizeImageUri()); cropIntent.setClass(this, CropImage.class); cropIntent.putExtras(newExtras); /* pass through any extras that were passed in */ cropIntent.putExtras(myExtras); if (Config.LOGV) Log.v(TAG, "startSubActivity " + cropIntent); startActivityForResult(cropIntent, CROP_MSG); } else { Intent result = new Intent(null, img.fullSizeImageUri()); if (myExtras != null && myExtras.getString("return-data") != null) { Bitmap bitmap = img.fullSizeBitmap(1000); if (bitmap != null) result.putExtra("data", bitmap); } setResult(RESULT_OK, result); finish(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (Config.LOGV) Log.v(TAG, "onActivityResult: " + requestCode + "; resultCode is " + resultCode + "; data is " + data); switch (requestCode) { case MenuHelper.RESULT_COMMON_MENU_CROP: { if (resultCode == RESULT_OK) { // The CropImage activity passes back the Uri of the cropped image as // the Action rather than the Data. Uri dataUri = Uri.parse(data.getAction()); rebake(false,false); IImage image = mAllImages.getImageForUri(dataUri); if (image != null ) { int rowId = image.getRow(); mGvs.select(rowId, false); } } break; } case CROP_MSG: { if (Config.LOGV) Log.v(TAG, "onActivityResult " + data); if (resultCode == RESULT_OK) { setResult(resultCode, data); finish(); } break; } case VIEW_MSG: { if (Config.LOGV) Log.v(TAG, "got VIEW_MSG with " + data); ImageManager.IImage img = mAllImages.getImageForUri(data.getData()); launchCropperOrFinish(img); break; } } } @Override public void onPause() { super.onPause(); mPausing = true; stopCheckingThumbnails(); mGvs.onPause(); if (mReceiver != null) { unregisterReceiver(mReceiver); mReceiver = null; } // Now that we've paused the threads that are using the cursor it is safe // to deactivate it. mAllImages.deactivate(); } private void rebake(boolean unmounted, boolean scanning) { stopCheckingThumbnails(); mGvs.clearCache(); if (mAllImages != null) { mAllImages.deactivate(); mAllImages = null; } if (mMediaScanningDialog != null) { mMediaScanningDialog.cancel(); mMediaScanningDialog = null; } if (scanning) { mMediaScanningDialog = ProgressDialog.show( this, null, getResources().getString(R.string.wait), true, true); mAllImages = ImageManager.instance().emptyImageList(); } else { mAllImages = allImages(!unmounted); if (Config.LOGV) Log.v(TAG, "mAllImages is now " + mAllImages); mGvs.init(mHandler); mGvs.start(); mGvs.requestLayout(); checkThumbnails(); } } @Override protected void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); mTargetScroll = mGvs.getScrollY(); state.putInt(INSTANCE_STATE_TAG, mTargetScroll); } @Override protected void onRestoreInstanceState(Bundle state) { super.onRestoreInstanceState(state); mTargetScroll = state.getInt(INSTANCE_STATE_TAG, 0); } int mTargetScroll; @Override public void onResume() { super.onResume(); try { mGvs.setSizeChoice(Integer.parseInt(mPrefs.getString("pref_gallery_size_key", "1")), mTargetScroll); String sortOrder = mPrefs.getString("pref_gallery_sort_key", null); if (sortOrder != null) { mSortAscending = sortOrder.equals("ascending"); } } catch (Exception ex) { } mPausing = false; // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addAction(Intent.ACTION_MEDIA_EJECT); intentFilter.addDataScheme("file"); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (Config.LOGV) Log.v(TAG, "onReceiveIntent " + intent.getAction()); String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { // SD card available // TODO put up a "please wait" message // TODO also listen for the media scanner finished message } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) { // SD card unavailable if (Config.LOGV) Log.v(TAG, "sd card no longer available"); Toast.makeText(ImageGallery2.this, getResources().getString(R.string.wait), 5000); rebake(true, false); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { Toast.makeText(ImageGallery2.this, getResources().getString(R.string.wait), 5000); rebake(false, true); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { if (Config.LOGV) Log.v(TAG, "rebake because of ACTION_MEDIA_SCANNER_FINISHED"); rebake(false, false); } else if (action.equals(Intent.ACTION_MEDIA_EJECT)) { if (Config.LOGV) Log.v(TAG, "rebake because of ACTION_MEDIA_EJECT"); rebake(true, false); } } }; registerReceiver(mReceiver, intentFilter); MenuHelper.requestOrientation(this, mPrefs); rebake(false, ImageManager.isMediaScannerScanning(this)); } private void stopCheckingThumbnails() { mStopThumbnailChecking = true; if (mThumbnailCheckThread != null) { mThumbnailCheckThread.join(); } mStopThumbnailChecking = false; } private void checkThumbnails() { final long startTime = System.currentTimeMillis(); final long t1 = System.currentTimeMillis(); mThumbnailCheckThread = new CameraThread(new Runnable() { public void run() { android.content.res.Resources resources = getResources(); final TextView progressTextView = (TextView) findViewById(R.id.loading_text); final String progressTextFormatString = resources.getString(R.string.loading_progress_format_string); PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "ImageGallery2.checkThumbnails"); mWakeLock.acquire(); ImageManager.IImageList.ThumbCheckCallback r = new ImageManager.IImageList.ThumbCheckCallback() { boolean mDidSetProgress = false; public boolean checking(final int count, final int maxCount) { if (mStopThumbnailChecking) { return false; } if (!mLayoutComplete) { return true; } if (!mDidSetProgress) { mHandler.post(new Runnable() { public void run() { findViewById(R.id.loading_indicator).setVisibility(View.VISIBLE); } }); mDidSetProgress = true; } mGvs.postInvalidate(); if (System.currentTimeMillis() - startTime > 1000) { mHandler.post(new Runnable() { public void run() { String s = String.format(progressTextFormatString, maxCount - count); progressTextView.setText(s); } }); } return !mPausing; } }; ImageManager.IImageList imageList = allImages(true); imageList.checkThumbnails(r, imageList.getCount()); mWakeLock.release(); mThumbnailCheckThread = null; mHandler.post(new Runnable() { public void run() { findViewById(R.id.loading_indicator).setVisibility(View.GONE); } }); long t2 = System.currentTimeMillis(); if (Config.LOGV) Log.v(TAG, "check thumbnails thread finishing; took " + (t2-t1)); } }); mThumbnailCheckThread.setName("check_thumbnails"); mThumbnailCheckThread.start(); mThumbnailCheckThread.toBackground(); ImageManager.IImageList list = allImages(true); mNoImagesView.setVisibility(list.getCount() > 0 ? View.GONE : View.VISIBLE); } @Override public boolean onCreateOptionsMenu(android.view.Menu menu) { MenuItem item; if (isPickIntent()) { MenuHelper.addCapturePictureMenuItems(menu, this); } else { MenuHelper.addCaptureMenuItems(menu, this); if ((mInclusion & ImageManager.INCLUDE_IMAGES) != 0) { mSlideShowItem = addSlideShowMenu(menu, 5); } } item = menu.add(0, 0, 1000, R.string.camerasettings); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent preferences = new Intent(); preferences.setClass(ImageGallery2.this, GallerySettings.class); startActivity(preferences); return true; } }); item.setAlphabeticShortcut('p'); item.setIcon(android.R.drawable.ic_menu_preferences); return true; } @Override public boolean onPrepareOptionsMenu(android.view.Menu menu) { if ((mInclusion & ImageManager.INCLUDE_IMAGES) != 0) { boolean videoSelected = isVideoSelected(); // TODO: Only enable slide show if there is at least one image in the folder. if (mSlideShowItem != null) { mSlideShowItem.setEnabled(!videoSelected); } } return true; } private boolean isImageSelected() { IImage image = mSelectedImageGetter.getCurrentImage(); return (image != null) && ImageManager.isImage(image); } private boolean isVideoSelected() { IImage image = mSelectedImageGetter.getCurrentImage(); return (image != null) && ImageManager.isVideo(image); } private synchronized ImageManager.IImageList allImages(boolean assumeMounted) { if (mAllImages == null) { mNoImagesView = findViewById(R.id.no_images); mInclusion = ImageManager.INCLUDE_IMAGES | ImageManager.INCLUDE_VIDEOS; Intent intent = getIntent(); if (intent != null) { String type = intent.resolveType(this); if (Config.LOGV) Log.v(TAG, "allImages... type is " + type); TextView leftText = (TextView) findViewById(R.id.left_text); if (type != null) { if (type.equals("vnd.android.cursor.dir/image") || type.equals("image/*")) { mInclusion = ImageManager.INCLUDE_IMAGES; if (isPickIntent()) leftText.setText(R.string.pick_photos_gallery_title); else leftText.setText(R.string.photos_gallery_title); } if (type.equals("vnd.android.cursor.dir/video") || type.equals("video/*")) { mInclusion = ImageManager.INCLUDE_VIDEOS; if (isPickIntent()) leftText.setText(R.string.pick_videos_gallery_title); else leftText.setText(R.string.videos_gallery_title); } } Bundle extras = intent.getExtras(); String title = extras!= null ? extras.getString("windowTitle") : null; if (title != null && title.length() > 0) { leftText.setText(title); } if (extras != null) { mInclusion = (ImageManager.INCLUDE_IMAGES | ImageManager.INCLUDE_VIDEOS) & extras.getInt("mediaTypes", mInclusion); } if (extras != null && extras.getBoolean("pick-drm")) { Log.d(TAG, "pick-drm is true"); mInclusion = ImageManager.INCLUDE_DRM_IMAGES; } } if (Config.LOGV) Log.v(TAG, "computing images... mSortAscending is " + mSortAscending + "; assumeMounted is " + assumeMounted); Uri uri = getIntent().getData(); if (!assumeMounted) { mAllImages = ImageManager.instance().emptyImageList(); } else { mAllImages = ImageManager.instance().allImages( ImageGallery2.this, getContentResolver(), ImageManager.DataLocation.NONE, mInclusion, mSortAscending ? ImageManager.SORT_ASCENDING : ImageManager.SORT_DESCENDING, uri != null ? uri.getQueryParameter("bucketId") : null); } } return mAllImages; } public static class GridViewSpecial extends View { private ImageGallery2 mGallery; private Paint mGridViewPaint = new Paint(); private ImageBlockManager mImageBlockManager; private Handler mHandler; private LayoutSpec mCurrentSpec; private boolean mShowSelection = false; private int mCurrentSelection = -1; private boolean mCurrentSelectionPressed; private boolean mDirectionBiasDown = true; private final static boolean sDump = false; private long mVideoSizeLimit; class LayoutSpec { LayoutSpec(int cols, int w, int h, int leftEdgePadding, int rightEdgePadding, int intercellSpacing) { mColumns = cols; mCellWidth = w; mCellHeight = h; mLeftEdgePadding = leftEdgePadding; mRightEdgePadding = rightEdgePadding; mCellSpacing = intercellSpacing; } int mColumns; int mCellWidth, mCellHeight; int mLeftEdgePadding, mRightEdgePadding; int mCellSpacing; }; private LayoutSpec [] mCellSizeChoices = new LayoutSpec[] { new LayoutSpec(0, 67, 67, 14, 14, 8), @@ -1238,625 +1238,625 @@ public class ImageGallery2 extends Activity { final int firstVisBlock = (mScrollY - mCurrentSpec.mCellSpacing) / blockHeight; final int lastVisBlock = (mScrollY - mCurrentSpec.mCellSpacing + getHeight()) / blockHeight; final int preCache = sPagesPreCache; final int startBlock = Math.max(0, firstVisBlock - (preCache * sRowsPerPage)); // Log.v(TAG, "moveDataWindow directionBiasDown == " + directionBiasDown + "; preCache is " + preCache); synchronized (ImageBlockManager.this) { boolean any = false; ImageBlock [] blocks = mBlockCache; int numBlocks = blocks.length; int delta = startBlock - mBlockCacheFirstBlockNumber; mBlockCacheFirstBlockNumber = startBlock; if (Math.abs(delta) > numBlocks || forceRefresh) { for (int i = 0; i < numBlocks; i++) { int blockNum = startBlock + i; blocks[i].setStart(blockNum); any = true; } mBlockCacheStartOffset = 0; } else if (delta > 0) { mBlockCacheStartOffset += delta; if (mBlockCacheStartOffset >= numBlocks) mBlockCacheStartOffset -= numBlocks; for (int i = delta; i > 0; i--) { int index = (mBlockCacheStartOffset + numBlocks - i) % numBlocks; int blockNum = mBlockCacheFirstBlockNumber + numBlocks - i; blocks[index].setStart(blockNum); any = true; } } else if (delta < 0) { mBlockCacheStartOffset += delta; if (mBlockCacheStartOffset < 0) mBlockCacheStartOffset += numBlocks; for (int i = 0; i < -delta; i++) { int index = (mBlockCacheStartOffset + i) % numBlocks; int blockNum = mBlockCacheFirstBlockNumber + i; blocks[index].setStart(blockNum); any = true; } } for (int i = 0; i < numBlocks; i++) { int index = (mBlockCacheStartOffset + i) % numBlocks; ImageBlock block = blocks[index]; int blockNum = block.mBlockNumber; // mBlockCacheFirstBlockNumber + i; boolean isVis = blockNum >= firstVisBlock && blockNum <= lastVisBlock; // Log.v(TAG, "blockNum " + blockNum + " setting vis to " + isVis); block.setVisibility(isVis); } if (sDump) mImageBlockManager.dump(); if (any) { ImageBlockManager.this.notify(); mWorkCounter += 1; } } if (sDump) dump(); } private void check() { ImageBlock [] blocks = mBlockCache; int blockLength = blocks.length; // check the results for (int i = 0; i < blockLength; i++) { int index = (mBlockCacheStartOffset + i) % blockLength; if (blocks[index].mBlockNumber != mBlockCacheFirstBlockNumber + i) { if (blocks[index].mBlockNumber != -1) Log.e(TAG, "at " + i + " block cache corrupted; found " + blocks[index].mBlockNumber + " but wanted " + (mBlockCacheFirstBlockNumber + i) + "; offset is " + mBlockCacheStartOffset); } } if (true) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < blockLength; i++) { int index = (mBlockCacheStartOffset + i) % blockLength; ImageBlock b = blocks[index]; if (b.mRequestedMask != 0) sb.append("X"); else sb.append(String.valueOf(b.mBlockNumber) + " "); } if (Config.LOGV) Log.v(TAG, "moveDataWindow " + sb.toString()); } } void doDraw(Canvas canvas) { synchronized (ImageBlockManager.this) { ImageBlockManager.ImageBlock [] blocks = mBlockCache; int blockCount = 0; if (blocks[0] == null) { return; } final int thisHeight = getHeight(); final int thisWidth = getWidth(); final int height = blocks[0].mBitmap.getHeight(); final int scrollPos = mScrollY; int currentBlock = (scrollPos < 0) ? ((scrollPos-height+1) / height) : (scrollPos / height); while (true) { final int yPos = currentBlock * height; if (yPos >= scrollPos + thisHeight) break; if (currentBlock < 0) { canvas.drawRect(0, yPos, thisWidth, 0, mGridViewPaint); currentBlock += 1; continue; } int effectiveOffset = (mBlockCacheStartOffset + (currentBlock++ - mBlockCacheFirstBlockNumber)) % blocks.length; if (effectiveOffset < 0 || effectiveOffset >= blocks.length) { break; } ImageBlock block = blocks[effectiveOffset]; if (block == null) { break; } synchronized (block) { Bitmap b = block.mBitmap; if (b == null) { break; } canvas.drawBitmap(b, 0, yPos, mGridViewPaint); blockCount += 1; } } } } int blockHeight() { return mCurrentSpec.mCellSpacing + mCurrentSpec.mCellHeight; } private class ImageBlock { Drawable mCellOutline; Bitmap mBitmap = Bitmap.createBitmap(getWidth(), blockHeight(), Bitmap.Config.RGB_565);; Canvas mCanvas = new Canvas(mBitmap); Paint mPaint = new Paint(); int mBlockNumber; int mRequestedMask; // columns which have been requested to the loader int mCompletedMask; // columns which have been completed from the loader boolean mIsVisible; public void dump(StringBuilder line1, StringBuilder line2) { synchronized (ImageBlock.this) { // Log.v(TAG, "block " + mBlockNumber + " isVis == " + mIsVisible); line2.append(mCompletedMask != 0xF ? 'L' : '_'); line1.append(mIsVisible ? 'V' : ' '); } } ImageBlock() { mPaint.setTextSize(14F); mPaint.setStyle(Paint.Style.FILL); mBlockNumber = -1; mCellOutline = GridViewSpecial.this.getResources().getDrawable(android.R.drawable.gallery_thumb); } private void recycleBitmaps() { synchronized (ImageBlock.this) { mBitmap.recycle(); mBitmap = null; } } private void cancelExistingRequests() { synchronized (ImageBlock.this) { for (int i = 0; i < mCurrentSpec.mColumns; i++) { int mask = (1 << i); if ((mRequestedMask & mask) != 0) { int pos = (mBlockNumber * mCurrentSpec.mColumns) + i; if (mLoader.cancel(mGallery.mAllImages.getImageAt(pos))) { mRequestedMask &= ~mask; } } } } } private void setStart(final int blockNumber) { synchronized (ImageBlock.this) { if (blockNumber == mBlockNumber) return; cancelExistingRequests(); mBlockNumber = blockNumber; mRequestedMask = 0; mCompletedMask = 0; mCanvas.drawColor(0xFF000000); mPaint.setColor(0xFFDDDDDD); int imageNumber = blockNumber * mCurrentSpec.mColumns; int lastImageNumber = mGallery.mAllImages.getCount() - 1; int spacing = mCurrentSpec.mCellSpacing; int leftSpacing = mCurrentSpec.mLeftEdgePadding; final int yPos = spacing; for (int col = 0; col < mCurrentSpec.mColumns; col++) { if (imageNumber++ >= lastImageNumber) break; final int xPos = leftSpacing + (col * (mCurrentSpec.mCellWidth + spacing)); mCanvas.drawRect(xPos, yPos, xPos+mCurrentSpec.mCellWidth, yPos+mCurrentSpec.mCellHeight, mPaint); paintSel(0, xPos, yPos); } } } private boolean setVisibility(boolean isVis) { synchronized (ImageBlock.this) { boolean retval = mIsVisible != isVis; mIsVisible = isVis; return retval; } } private int startLoading() { synchronized (ImageBlock.this) { final int startRow = mBlockNumber; int count = mGallery.mAllImages.getCount(); if (startRow == -1) return 0; if ((startRow * mCurrentSpec.mColumns) >= count) { return 0; } int retVal = 0; int base = (mBlockNumber * mCurrentSpec.mColumns); for (int col = 0; col < mCurrentSpec.mColumns; col++) { if ((mCompletedMask & (1 << col)) != 0) { continue; } int spacing = mCurrentSpec.mCellSpacing; int leftSpacing = mCurrentSpec.mLeftEdgePadding; final int yPos = spacing; final int xPos = leftSpacing + (col * (mCurrentSpec.mCellWidth + spacing)); int pos = base + col; if (pos >= count) break; ImageManager.IImage image = mGallery.mAllImages.getImageAt(pos); if (image != null) { // Log.v(TAG, "calling loadImage " + (base + col)); loadImage(base, col, image, xPos, yPos); retVal += 1; } } return retVal; } } Bitmap resizeBitmap(Bitmap b) { // assume they're both square for now if (b == null || (b.getWidth() == mCurrentSpec.mCellWidth && b.getHeight() == mCurrentSpec.mCellHeight)) { return b; } float scale = (float) mCurrentSpec.mCellWidth / (float)b.getWidth(); Matrix m = new Matrix(); m.setScale(scale, scale, b.getWidth(), b.getHeight()); Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, false); return b2; } private void drawBitmap(ImageManager.IImage image, int base, int baseOffset, Bitmap b, int xPos, int yPos) { mCanvas.setBitmap(mBitmap); if (b != null) { // if the image is close to the target size then crop, otherwise scale // both the bitmap and the view should be square but I suppose that could // change in the future. int w = mCurrentSpec.mCellWidth; int h = mCurrentSpec.mCellHeight; int bw = b.getWidth(); int bh = b.getHeight(); int deltaW = bw - w; int deltaH = bh - h; if (deltaW < 10 && deltaH < 10) { int halfDeltaW = deltaW / 2; int halfDeltaH = deltaH / 2; android.graphics.Rect src = new android.graphics.Rect(0+halfDeltaW, 0+halfDeltaH, bw-halfDeltaW, bh-halfDeltaH); android.graphics.Rect dst = new android.graphics.Rect(xPos, yPos, xPos+w, yPos+h); if (src.width() != dst.width() || src.height() != dst.height()) { if (Config.LOGV){ Log.v(TAG, "nope... width doesn't match " + src.width() + " " + dst.width()); Log.v(TAG, "nope... height doesn't match " + src.height() + " " + dst.height()); } } mCanvas.drawBitmap(b, src, dst, mPaint); } else { android.graphics.Rect src = new android.graphics.Rect(0, 0, bw, bh); android.graphics.Rect dst = new android.graphics.Rect(xPos, yPos, xPos+w, yPos+h); mCanvas.drawBitmap(b, src, dst, mPaint); } } else { // If the thumbnail cannot be drawn, put up an error icon instead Bitmap error = mImageBlockManager.getErrorBitmap(image); int width = error.getWidth(); int height = error.getHeight(); Rect source = new Rect(0, 0, width, height); int left = (mCurrentSpec.mCellWidth - width) / 2 + xPos; int top = (mCurrentSpec.mCellHeight - height) / 2 + yPos; Rect dest = new Rect(left, top, left + width, top + height); mCanvas.drawBitmap(error, source, dest, mPaint); } if (ImageManager.isVideo(image)) { Drawable overlay = null; long size = MenuHelper.getImageFileSize(image); if (size >= 0 && size <= mVideoSizeLimit) { if (mVideoOverlay == null) { mVideoOverlay = getResources().getDrawable( R.drawable.ic_gallery_video_overlay); } overlay = mVideoOverlay; } else { if (mVideoMmsErrorOverlay == null) { mVideoMmsErrorOverlay = getResources().getDrawable( R.drawable.ic_error_mms_video_overlay); } overlay = mVideoMmsErrorOverlay; Paint paint = new Paint(); paint.setARGB(0x80, 0x00, 0x00, 0x00); mCanvas.drawRect(xPos, yPos, xPos + mCurrentSpec.mCellWidth, yPos + mCurrentSpec.mCellHeight, paint); } int width = overlay.getIntrinsicWidth(); int height = overlay.getIntrinsicHeight(); int left = (mCurrentSpec.mCellWidth - width) / 2 + xPos; int top = (mCurrentSpec.mCellHeight - height) / 2 + yPos; Rect newBounds = new Rect(left, top, left + width, top + height); overlay.setBounds(newBounds); overlay.draw(mCanvas); } paintSel(base + baseOffset, xPos, yPos); } private void repaintSelection() { int count = mGallery.mAllImages.getCount(); int startPos = mBlockNumber * mCurrentSpec.mColumns; synchronized (ImageBlock.this) { for (int i = 0; i < mCurrentSpec.mColumns; i++) { int pos = startPos + i; if (pos >= count) break; int row = 0; // i / mCurrentSpec.mColumns; int col = i - (row * mCurrentSpec.mColumns); // this is duplicated from getOrKick (TODO: don't duplicate this code) int spacing = mCurrentSpec.mCellSpacing; int leftSpacing = mCurrentSpec.mLeftEdgePadding; final int yPos = spacing + (row * (mCurrentSpec.mCellHeight + spacing)); final int xPos = leftSpacing + (col * (mCurrentSpec.mCellWidth + spacing)); paintSel(pos, xPos, yPos); } } } private void paintSel(int pos, int xPos, int yPos) { int[] stateSet = EMPTY_STATE_SET; if (pos == mCurrentSelection && mShowSelection) { if (mCurrentSelectionPressed) { stateSet = PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; } else { stateSet = ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; } } mCellOutline.setState(stateSet); mCanvas.setBitmap(mBitmap); mCellOutline.setBounds(xPos, yPos, xPos+mCurrentSpec.mCellWidth, yPos+mCurrentSpec.mCellHeight); mCellOutline.draw(mCanvas); } private void loadImage( final int base, final int baseOffset, final ImageManager.IImage image, final int xPos, final int yPos) { synchronized (ImageBlock.this) { final int startBlock = mBlockNumber; final int pos = base + baseOffset; final ImageLoader.LoadedCallback r = new ImageLoader.LoadedCallback() { public void run(Bitmap b) { boolean more = false; synchronized (ImageBlock.this) { if (startBlock != mBlockNumber) { // Log.v(TAG, "wanted block " + mBlockNumber + " but got " + startBlock); return; } if (mBitmap == null) { return; } drawBitmap(image, base, baseOffset, b, xPos, yPos); int mask = (1 << baseOffset); mRequestedMask &= ~mask; mCompletedMask |= mask; // Log.v(TAG, "for " + mBlockNumber + " mRequestedMask is " + String.format("%x", mRequestedMask) + " and mCompletedMask is " + String.format("%x", mCompletedMask)); if (mRequestedMask == 0) { if (mIsVisible) { postInvalidate(); } more = true; } } if (b != null) b.recycle(); if (more) { synchronized (ImageBlockManager.this) { ImageBlockManager.this.notify(); mWorkCounter += 1; } } if (sDump) ImageBlockManager.this.dump(); } }; mRequestedMask |= (1 << baseOffset); mLoader.getBitmap(image, pos, r, mIsVisible, false); } } } } public void init(Handler handler) { mHandler = handler; } public void onDraw(Canvas canvas) { super.onDraw(canvas); if (false) { canvas.drawRect(0, 0, getWidth(), getHeight(), mGridViewPaint); if (Config.LOGV) Log.v(TAG, "painting background w/h " + getWidth() + " / " + getHeight()); return; } if (mImageBlockManager != null) { mImageBlockManager.doDraw(canvas); mImageBlockManager.moveDataWindow(mDirectionBiasDown, false); } } @Override public void computeScroll() { if (mScroller != null) { boolean more = mScroller.computeScrollOffset(); scrollTo(0, (int)mScroller.getCurrY()); if (more) { postInvalidate(); // So we draw again } else { mScroller = null; } } else { super.computeScroll(); } } private android.graphics.Rect getRectForPosition(int pos) { int row = pos / mCurrentSpec.mColumns; int col = pos - (row * mCurrentSpec.mColumns); int left = mCurrentSpec.mLeftEdgePadding + (col * mCurrentSpec.mCellWidth) + (Math.max(0, col-1) * mCurrentSpec.mCellSpacing); int top = (row * mCurrentSpec.mCellHeight) + (row * mCurrentSpec.mCellSpacing); return new android.graphics.Rect(left, top, left + mCurrentSpec.mCellWidth + mCurrentSpec.mCellWidth, top + mCurrentSpec.mCellHeight + mCurrentSpec.mCellSpacing); } int computeSelectedIndex(android.view.MotionEvent ev) { int spacing = mCurrentSpec.mCellSpacing; int leftSpacing = mCurrentSpec.mLeftEdgePadding; int x = (int) ev.getX(); int y = (int) ev.getY(); int row = (mScrollY + y - spacing) / (mCurrentSpec.mCellHeight + spacing); int col = Math.min(mCurrentSpec.mColumns - 1, (x - leftSpacing) / (mCurrentSpec.mCellWidth + spacing)); return (row * mCurrentSpec.mColumns) + col; } @Override public boolean onTouchEvent(android.view.MotionEvent ev) { - if (mGallery.isPaused()) return false; + if (!mGallery.canHandleEvent()) return false; mGestureDetector.onTouchEvent(ev); return true; } private void onSelect(int index) { if (index >= 0 && index < mGallery.mAllImages.getCount()) { ImageManager.IImage img = mGallery.mAllImages.getImageAt(index); if (img == null) return; if (mGallery.isPickIntent()) { mGallery.launchCropperOrFinish(img); } else { Uri targetUri = img.fullSizeImageUri(); Uri thisUri = mGallery.getIntent().getData(); if (thisUri != null) { String bucket = thisUri.getQueryParameter("bucketId"); if (bucket != null) { targetUri = targetUri.buildUpon().appendQueryParameter("bucketId", bucket).build(); } } Intent intent = new Intent(Intent.ACTION_VIEW, targetUri); if (img instanceof ImageManager.VideoObject) { intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } try { mContext.startActivity(intent); } catch (Exception ex) { // sdcard removal?? } } } } @Override public void scrollBy(int x, int y) { scrollTo(x, mScrollY + y); } Toast mDateLocationToast; int [] mDateRange = new int[2]; private String month(int month) { String text = ""; switch (month) { case 0: text = "January"; break; case 1: text = "February"; break; case 2: text = "March"; break; case 3: text = "April"; break; case 4: text = "May"; break; case 5: text = "June"; break; case 6: text = "July"; break; case 7: text = "August"; break; case 8: text = "September"; break; case 9: text = "October"; break; case 10: text = "November"; break; case 11: text = "December"; break; } return text; } Runnable mToastRunnable = new Runnable() { public void run() { if (mDateLocationToast != null) { mDateLocationToast.cancel(); mDateLocationToast = null; } int count = mGallery.mAllImages.getCount(); if (count == 0) return; GridViewSpecial.this.mImageBlockManager.getVisibleRange(mDateRange); ImageManager.IImage firstImage = mGallery.mAllImages.getImageAt(mDateRange[0]); int lastOffset = Math.min(count-1, mDateRange[1]); ImageManager.IImage lastImage = mGallery.mAllImages.getImageAt(lastOffset); GregorianCalendar dateStart = new GregorianCalendar(); GregorianCalendar dateEnd = new GregorianCalendar(); dateStart.setTimeInMillis(firstImage.getDateTaken()); dateEnd.setTimeInMillis(lastImage.getDateTaken()); String text1 = month(dateStart.get(Calendar.MONTH)) + " " + dateStart.get(Calendar.YEAR); String text2 = month(dateEnd .get(Calendar.MONTH)) + " " + dateEnd .get(Calendar.YEAR); String text = text1; if (!text2.equals(text1)) text = text + " : " + text2; mDateLocationToast = Toast.makeText(mContext, text, Toast.LENGTH_LONG); mDateLocationToast.show(); } }; @Override public void scrollTo(int x, int y) { y = Math.min(mMaxScrollY, y); y = Math.max(mMinScrollY, y); if (y > mScrollY) mDirectionBiasDown = true; else if (y < mScrollY) mDirectionBiasDown = false; super.scrollTo(x, y); } } }
brunsky/WS171-packages-apps-Camera
96279b7b4b2130629cd83eb7ecfc061cc26aeead
Automated import from //branches/cupcake/...@141960,141960
diff --git a/src/com/android/camera/Camera.java b/src/com/android/camera/Camera.java index 2300387..46620f4 100644 --- a/src/com/android/camera/Camera.java +++ b/src/com/android/camera/Camera.java @@ -247,1025 +247,1027 @@ public class Camera extends Activity implements View.OnClickListener, // update so update GPS indicator when we receive data. if (mRecordLocation && LocationManager.GPS_PROVIDER.equals(mProvider)) { mGpsIndicator.setVisibility(View.VISIBLE); } mLastLocation.set(newLocation); mValid = true; } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { mValid = false; } public void onStatusChanged(String provider, int status, Bundle extras) { switch(status) { case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: { mValid = false; if (mRecordLocation && LocationManager.GPS_PROVIDER.equals(provider)) { mGpsIndicator.setVisibility(View.INVISIBLE); } break; } } } public Location current() { return mValid ? mLastLocation : null; } }; private boolean mImageSavingItem = false; private final class ShutterCallback implements android.hardware.Camera.ShutterCallback { public void onShutter() { if (DEBUG_TIME_OPERATIONS) { mShutterCallbackTime = System.currentTimeMillis(); Log.v(TAG, "Shutter lag was " + (mShutterCallbackTime - mCaptureStartTime) + " ms."); } // We are going to change the size of surface view and show captured // image. Set it to invisible now and set it back to visible in // surfaceChanged() so that users won't see the image is resized on // the screen. mSurfaceView.setVisibility(View.INVISIBLE); // Resize the SurfaceView to the aspect-ratio of the still image // and so that we can see the full image that was taken. Size pictureSize = mParameters.getPictureSize(); mSurfaceView.setAspectRatio(pictureSize.width, pictureSize.height); } }; private final class RawPictureCallback implements PictureCallback { public void onPictureTaken(byte [] rawData, android.hardware.Camera camera) { if (Config.LOGV) Log.v(TAG, "got RawPictureCallback..."); mRawPictureCallbackTime = System.currentTimeMillis(); if (DEBUG_TIME_OPERATIONS) { Log.v(TAG, (mRawPictureCallbackTime - mShutterCallbackTime) + "ms elapsed between" + " ShutterCallback and RawPictureCallback."); } } }; private final class JpegPictureCallback implements PictureCallback { Location mLocation; public JpegPictureCallback(Location loc) { mLocation = loc; } public void onPictureTaken(byte [] jpegData, android.hardware.Camera camera) { if (mPausing) { return; } if (Config.LOGV) Log.v(TAG, "got JpegPictureCallback..."); if (DEBUG_TIME_OPERATIONS) { long mJpegPictureCallback = System.currentTimeMillis(); Log.v(TAG, (mJpegPictureCallback - mRawPictureCallbackTime) + "ms elapsed between" + " RawPictureCallback and JpegPictureCallback."); } if (jpegData != null) { mImageCapture.storeImage(jpegData, camera, mLocation); } mStatus = SNAPSHOT_COMPLETED; if (mKeepAndRestartPreview) { long delay = 1500 - (System.currentTimeMillis() - mRawPictureCallbackTime); mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, Math.max(delay, 0)); } } }; private final class AutoFocusCallback implements android.hardware.Camera.AutoFocusCallback { public void onAutoFocus(boolean focused, android.hardware.Camera camera) { if (DEBUG_TIME_OPERATIONS) { mFocusCallbackTime = System.currentTimeMillis(); Log.v(TAG, "Auto focus took " + (mFocusCallbackTime - mFocusStartTime) + " ms."); } if (mFocusState == FOCUSING_SNAP_ON_FINISH && mCaptureObject != null) { // Take the picture no matter focus succeeds or fails. // No need to play the AF sound if we're about to play the shutter sound. mCaptureObject.onSnap(); clearFocusState(); } else if (mFocusState == FOCUSING) { // User is half-pressing the focus key. Play the focus tone. // Do not take the picture now. ToneGenerator tg = mFocusToneGenerator; if (tg != null) tg.startTone(ToneGenerator.TONE_PROP_BEEP2); if (focused) { mFocusState = FOCUS_SUCCESS; } else { mFocusState = FOCUS_FAIL; } } else if (mFocusState == FOCUS_NOT_STARTED) { // User has released the focus key before focus completes. // Do nothing. } updateFocusIndicator(); } }; private class ImageCapture implements Capturer { private boolean mCancel = false; private boolean mCapturing = false; private Uri mLastContentUri; private ImageManager.IAddImage_cancelable mAddImageCancelable; Bitmap mCaptureOnlyBitmap; /** These member variables are used for various debug timings */ private long mThreadTimeStart; private long mThreadTimeEnd; private long mWallTimeStart; private long mWallTimeEnd; public ImageCapture() { } /** * This method sets whether or not we are capturing a picture. This method must be called * with the ImageCapture.this lock held. */ public void setCapturingLocked(boolean capturing) { mCapturing = capturing; } public void dismissFreezeFrame() { if (mStatus == SNAPSHOT_IN_PROGRESS) { // If we are still in the process of taking a picture, then just post a message. mHandler.sendEmptyMessage(RESTART_PREVIEW); } else { restartPreview(); } } private void startTiming() { mWallTimeStart = SystemClock.elapsedRealtime(); mThreadTimeStart = Debug.threadCpuTimeNanos(); } private void stopTiming() { mThreadTimeEnd = Debug.threadCpuTimeNanos(); mWallTimeEnd = SystemClock.elapsedRealtime(); } private void storeImage(byte[] data, Location loc) { try { if (DEBUG_TIME_OPERATIONS) { startTiming(); } long dateTaken = System.currentTimeMillis(); String name = createName(dateTaken) + ".jpg"; mLastContentUri = ImageManager.instance().addImage( Camera.this, mContentResolver, name, "", dateTaken, // location for the database goes here loc, 0, // the dsp will use the right orientation so don't "double set it" ImageManager.CAMERA_IMAGE_BUCKET_NAME, name); if (mLastContentUri == null) { // this means we got an error mCancel = true; } if (!mCancel) { mAddImageCancelable = ImageManager.instance().storeImage(mLastContentUri, Camera.this, mContentResolver, 0, null, data); mAddImageCancelable.get(); mAddImageCancelable = null; } if (DEBUG_TIME_OPERATIONS) { stopTiming(); Log.d(TAG, "Storing image took " + (mWallTimeEnd - mWallTimeStart) + " ms. " + "Thread time was " + ((mThreadTimeEnd - mThreadTimeStart) / 1000000) + " ms."); } } catch (Exception ex) { Log.e(TAG, "Exception while compressing image.", ex); } } public void storeImage(byte[] data, android.hardware.Camera camera, Location loc) { boolean captureOnly = mIsImageCaptureIntent; if (!captureOnly) { storeImage(data, loc); sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", mLastContentUri)); setLastPictureThumb(data, mCaptureObject.getLastCaptureUri()); dismissFreezeFrame(); } else { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; if (DEBUG_TIME_OPERATIONS) { startTiming(); } mCaptureOnlyBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options); if (DEBUG_TIME_OPERATIONS) { stopTiming(); Log.d(TAG, "Decoded mCaptureOnly bitmap (" + mCaptureOnlyBitmap.getWidth() + "x" + mCaptureOnlyBitmap.getHeight() + " ) in " + (mWallTimeEnd - mWallTimeStart) + " ms. Thread time was " + ((mThreadTimeEnd - mThreadTimeStart) / 1000000) + " ms."); } showPostCaptureAlert(); cancelAutomaticPreviewRestart(); } mCapturing = false; if (mPausing) { closeCamera(); } } /* * Initiate the capture of an image. */ public void initiate(boolean captureOnly) { if (mCameraDevice == null) { return; } mCancel = false; mCapturing = true; capture(captureOnly); } public Uri getLastCaptureUri() { return mLastContentUri; } public Bitmap getLastBitmap() { return mCaptureOnlyBitmap; } private void capture(boolean captureOnly) { mPreviewing = false; mCaptureOnlyBitmap = null; final int latchedOrientation = ImageManager.roundOrientation(mLastOrientation + 90); Location loc = mRecordLocation ? getCurrentLocation() : null; // Quality 75 has visible artifacts, and quality 90 looks great but the files begin to // get large. 85 is a good compromise between the two. mParameters.set("jpeg-quality", 85); mParameters.set("rotation", latchedOrientation); mParameters.remove("gps-latitude"); mParameters.remove("gps-longitude"); mParameters.remove("gps-altitude"); mParameters.remove("gps-timestamp"); if (loc != null) { double lat = loc.getLatitude(); double lon = loc.getLongitude(); boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d); if (hasLatLon) { String latString = String.valueOf(lat); String lonString = String.valueOf(lon); mParameters.set("gps-latitude", latString); mParameters.set("gps-longitude", lonString); if (loc.hasAltitude()) { mParameters.set("gps-altitude", String.valueOf(loc.getAltitude())); } else { // for NETWORK_PROVIDER location provider, we may have // no altitude information, but the driver needs it, so // we fake one. mParameters.set("gps-altitude", "0"); } if (loc.getTime() != 0) { // Location.getTime() is UTC in milliseconds. // gps-timestamp is UTC in seconds. long utcTimeSeconds = loc.getTime() / 1000; mParameters.set("gps-timestamp", String.valueOf(utcTimeSeconds)); } } else { loc = null; } } mCameraDevice.setParameters(mParameters); mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback, new JpegPictureCallback(loc)); } public void onSnap() { if (mPausing) { return; } if (DEBUG_TIME_OPERATIONS) mCaptureStartTime = System.currentTimeMillis(); // If we are already in the middle of taking a snapshot then we should just save // the image after we have returned from the camera service. if (mStatus == SNAPSHOT_IN_PROGRESS || mStatus == SNAPSHOT_COMPLETED) { mKeepAndRestartPreview = true; mHandler.sendEmptyMessage(RESTART_PREVIEW); return; } // Don't check the filesystem here, we can't afford the latency. Instead, check the // cached value which was calculated when the preview was restarted. if (mPicturesRemaining < 1) { updateStorageHint(mPicturesRemaining); return; } mStatus = SNAPSHOT_IN_PROGRESS; mKeepAndRestartPreview = true; boolean getContentAction = mIsImageCaptureIntent; if (getContentAction) { mImageCapture.initiate(true); } else { mImageCapture.initiate(false); } } private void clearLastBitmap() { if (mCaptureOnlyBitmap != null) { mCaptureOnlyBitmap.recycle(); mCaptureOnlyBitmap = null; } } } private void setLastPictureThumb(byte[] data, Uri uri) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 16; Bitmap lastPictureThumb = BitmapFactory.decodeByteArray(data, 0, data.length, options); mThumbController.setData(uri, lastPictureThumb); } static private String createName(long dateTaken) { return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString(); } static public Matrix GetDisplayMatrix(Bitmap b, ImageView v) { Matrix m = new Matrix(); float bw = (float)b.getWidth(); float bh = (float)b.getHeight(); float vw = (float)v.getWidth(); float vh = (float)v.getHeight(); float scale, x, y; if (bw*vh > vw*bh) { scale = vh / bh; x = (vw - scale*bw)*0.5F; y = 0; } else { scale = vw / bw; x = 0; y = (vh - scale*bh)*0.5F; } m.setScale(scale, scale, 0.5F, 0.5F); m.postTranslate(x, y); return m; } /** Called with the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); // To reduce startup time, we open camera device in another thread. // We make sure the camera is opened at the end of onCreate. Thread openCameraThread = new Thread(new Runnable() { public void run() { mCameraDevice = android.hardware.Camera.open(); } }); openCameraThread.start(); // To reduce startup time, we run some service creation code in another thread. // We make sure the services are loaded at the end of onCreate(). Thread loadServiceThread = new Thread(new Runnable() { public void run() { mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mOrientationListener = new OrientationEventListener(Camera.this) { public void onOrientationChanged(int orientation) { // We keep the last known orientation. So if the user // first orient the camera then point the camera to // floor/sky, we still have the correct orientation. if (orientation != ORIENTATION_UNKNOWN) mLastOrientation = orientation; } }; } }); loadServiceThread.start(); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mContentResolver = getContentResolver(); Window win = getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.camera); mSurfaceView = (VideoPreview) findViewById(R.id.camera_preview); mGpsIndicator = (ImageView) findViewById(R.id.gps_indicator); // don't set mSurfaceHolder here. We have it set ONLY within // surfaceCreated / surfaceDestroyed, other parts of the code // assume that when it is set, the surface is also set. SurfaceHolder holder = mSurfaceView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mIsImageCaptureIntent = isImageCaptureIntent(); if (!mIsImageCaptureIntent) { mLastPictureButton = (ImageView) findViewById(R.id.last_picture_button); mLastPictureButton.setOnClickListener(this); Drawable frame = getResources().getDrawable(R.drawable.frame_thumbnail); mThumbController = new ThumbnailController(mLastPictureButton, frame, mContentResolver); mThumbController.loadData(ImageManager.getLastImageThumbPath()); } mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); mFocusIndicator = findViewById(R.id.focus_indicator); mFocusBlinkAnimation = AnimationUtils.loadAnimation(this, R.anim.auto_focus_blink); mFocusBlinkAnimation.setRepeatCount(Animation.INFINITE); mFocusBlinkAnimation.setRepeatMode(Animation.REVERSE); // We load the post_picture_panel layout only if it is needed. if (mIsImageCaptureIntent) { ViewGroup cameraView = (ViewGroup)findViewById(R.id.camera); getLayoutInflater().inflate(R.layout.post_picture_panel, cameraView); mPostCaptureAlert = findViewById(R.id.post_picture_panel); } // Make sure the services are loaded. try { openCameraThread.join(); loadServiceThread.join(); } catch (InterruptedException ex) { } ImageManager.ensureOSXCompatibleFolder(); } @Override public void onStart() { super.onStart(); Thread t = new Thread(new Runnable() { public void run() { final boolean storageOK = calculatePicturesRemaining() > 0; if (!storageOK) { mHandler.post(new Runnable() { public void run() { updateStorageHint(mPicturesRemaining); } }); } } }); t.start(); } public void onClick(View v) { switch (v.getId()) { case R.id.last_picture_button: - viewLastImage(); + if (mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED) { + viewLastImage(); + } break; case R.id.attach: doAttach(); break; case R.id.cancel: doCancel(); } } private void doAttach() { if (mPausing) { return; } Bitmap bitmap = mImageCapture.getLastBitmap(); String cropValue = null; Uri saveUri = null; Bundle myExtras = getIntent().getExtras(); if (myExtras != null) { saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); cropValue = myExtras.getString("crop"); } if (cropValue == null) { /* * First handle the no crop case -- just return the value. If the caller * specifies a "save uri" then write the data to it's stream. Otherwise, * pass back a scaled down version of the bitmap directly in the extras. */ if (saveUri != null) { OutputStream outputStream = null; try { outputStream = mContentResolver.openOutputStream(saveUri); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, outputStream); outputStream.close(); setResult(RESULT_OK); finish(); } catch (IOException ex) { // } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { } } } } else { float scale = .5F; Matrix m = new Matrix(); m.setScale(scale, scale); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true); setResult(RESULT_OK, new Intent("inline-data").putExtra("data", bitmap)); finish(); } } else { /* * Save the image to a temp file and invoke the cropper */ Uri tempUri = null; FileOutputStream tempStream = null; try { File path = getFileStreamPath(sTempCropFilename); path.delete(); tempStream = openFileOutput(sTempCropFilename, 0); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, tempStream); tempStream.close(); tempUri = Uri.fromFile(path); } catch (FileNotFoundException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } catch (IOException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } finally { if (tempStream != null) { try { tempStream.close(); } catch (IOException ex) { } } } Bundle newExtras = new Bundle(); if (cropValue.equals("circle")) newExtras.putString("circleCrop", "true"); if (saveUri != null) newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, saveUri); else newExtras.putBoolean("return-data", true); Intent cropIntent = new Intent(); cropIntent.setClass(Camera.this, CropImage.class); cropIntent.setData(tempUri); cropIntent.putExtras(newExtras); startActivityForResult(cropIntent, CROP_MSG); } } private void doCancel() { setResult(RESULT_CANCELED, new Intent()); finish(); } public void onShutterButtonFocus(ShutterButton button, boolean pressed) { if (mPausing) { return; } switch (button.getId()) { case R.id.shutter_button: doFocus(pressed); break; } } public void onShutterButtonClick(ShutterButton button) { if (mPausing) { return; } switch (button.getId()) { case R.id.shutter_button: doSnap(); break; } } private void updateStorageHint() { updateStorageHint(MenuHelper.calculatePicturesRemaining()); } private OnScreenHint mStorageHint; private void updateStorageHint(int remaining) { String noStorageText = null; if (remaining == MenuHelper.NO_STORAGE_ERROR) { String state = Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING) { noStorageText = getString(R.string.preparing_sd); } else { noStorageText = getString(R.string.no_storage); } } else if (remaining < 1) { noStorageText = getString(R.string.not_enough_space); } if (noStorageText != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, noStorageText); } else { mStorageHint.setText(noStorageText); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } @Override public void onResume() { super.onResume(); mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); mPausing = false; mOrientationListener.enable(); mRecordLocation = mPreferences.getBoolean( "pref_camera_recordlocation_key", false); mGpsIndicator.setVisibility(View.INVISIBLE); // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); mDidRegister = true; mImageCapture = new ImageCapture(); restartPreview(); if (mRecordLocation) startReceivingLocationUpdates(); updateFocusIndicator(); try { mFocusToneGenerator = new ToneGenerator(AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME); } catch (RuntimeException e) { Log.w(TAG, "Exception caught while creating local tone generator: " + e); mFocusToneGenerator = null; } } private static ImageManager.DataLocation dataLocation() { return ImageManager.DataLocation.EXTERNAL; } @Override public void onStop() { keep(); stopPreview(); closeCamera(); mHandler.removeMessages(CLEAR_SCREEN_DELAY); super.onStop(); } @Override protected void onPause() { keep(); mPausing = true; mOrientationListener.disable(); stopPreview(); if (!mImageCapture.mCapturing) { closeCamera(); } if (mDidRegister) { unregisterReceiver(mReceiver); mDidRegister = false; } stopReceivingLocationUpdates(); if (mFocusToneGenerator != null) { mFocusToneGenerator.release(); mFocusToneGenerator = null; } if (!mIsImageCaptureIntent) { mThumbController.storeData(ImageManager.getLastImageThumbPath()); } if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } // If we are in an image capture intent and has taken // a picture, we just clear it in onPause. mImageCapture.clearLastBitmap(); mImageCapture = null; hidePostCaptureAlert(); super.onPause(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case CROP_MSG: { Intent intent = new Intent(); if (data != null) { Bundle extras = data.getExtras(); if (extras != null) { intent.putExtras(extras); } } setResult(resultCode, intent); finish(); File path = getFileStreamPath(sTempCropFilename); path.delete(); break; } } } private void autoFocus() { updateFocusIndicator(); if (mFocusState != FOCUSING && mFocusState != FOCUSING_SNAP_ON_FINISH) { if (mCameraDevice != null) { if (DEBUG_TIME_OPERATIONS) { mFocusStartTime = System.currentTimeMillis(); } mFocusState = FOCUSING; mCameraDevice.autoFocus(mAutoFocusCallback); } } } private void clearFocusState() { mFocusState = FOCUS_NOT_STARTED; } private void updateFocusIndicator() { mHandler.post(new Runnable() { public void run() { if (mFocusState == FOCUS_SUCCESS) { mFocusIndicator.setVisibility(View.VISIBLE); mFocusIndicator.clearAnimation(); } else if (mFocusState == FOCUS_FAIL) { mFocusIndicator.setVisibility(View.VISIBLE); mFocusIndicator.startAnimation(mFocusBlinkAnimation); } else { mFocusIndicator.setVisibility(View.GONE); mFocusIndicator.clearAnimation(); } } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mStatus == SNAPSHOT_IN_PROGRESS) { // ignore backs while we're taking a picture return true; } break; case KeyEvent.KEYCODE_FOCUS: if (event.getRepeatCount() == 0) { doFocus(true); } return true; case KeyEvent.KEYCODE_CAMERA: if (event.getRepeatCount() == 0) { doSnap(); } return true; case KeyEvent.KEYCODE_DPAD_CENTER: // If we get a dpad center event without any focused view, move the // focus to the shutter button and press it. if (event.getRepeatCount() == 0) { // Start auto-focus immediately to reduce shutter lag. After the shutter button // gets the focus, doFocus() will be called again but it is fine. doFocus(true); if (mShutterButton.isInTouchMode()) { mShutterButton.requestFocusFromTouch(); } else { mShutterButton.requestFocus(); } mShutterButton.setPressed(true); } return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_FOCUS: doFocus(false); return true; } return super.onKeyUp(keyCode, event); } private void doSnap() { // If the user has half-pressed the shutter and focus is completed, we // can take the photo right away. if ((mFocusState == FOCUS_SUCCESS || mFocusState == FOCUS_FAIL) || !mPreviewing) { // doesn't get set until the idler runs if (mCaptureObject != null) { mCaptureObject.onSnap(); } clearFocusState(); updateFocusIndicator(); } else if (mFocusState == FOCUSING) { // Half pressing the shutter (i.e. the focus button event) will // already have requested AF for us, so just request capture on // focus here. mFocusState = FOCUSING_SNAP_ON_FINISH; } else if (mFocusState == FOCUS_NOT_STARTED) { // Focus key down event is dropped for some reasons. Just ignore. } } private void doFocus(boolean pressed) { if (pressed) { // Focus key down. if (mPreviewing) { autoFocus(); } else if (mCaptureObject != null) { // Save and restart preview mCaptureObject.onSnap(); } } else { // Focus key up. if (mFocusState != FOCUSING_SNAP_ON_FINISH) { // User releases half-pressed focus key. clearFocusState(); updateFocusIndicator(); } } } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { mSurfaceView.setVisibility(View.VISIBLE); // if we're creating the surface, start the preview as well. boolean preview = holder.isCreating(); setViewFinder(w, h, preview); mCaptureObject = mImageCapture; } public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; } public void surfaceDestroyed(SurfaceHolder holder) { stopPreview(); mSurfaceHolder = null; } private void closeCamera() { if (mCameraDevice != null) { mCameraDevice.release(); mCameraDevice = null; mPreviewing = false; } } private boolean ensureCameraDevice() { if (mCameraDevice == null) { mCameraDevice = android.hardware.Camera.open(); } return mCameraDevice != null; } private void updateLastImage() { ImageManager.IImageList list = ImageManager.instance().allImages( this, mContentResolver, dataLocation(), ImageManager.INCLUDE_IMAGES, ImageManager.SORT_ASCENDING, ImageManager.CAMERA_IMAGE_BUCKET_ID); int count = list.getCount(); if (count > 0) { ImageManager.IImage image = list.getImageAt(count-1); Uri uri = image.fullSizeImageUri(); mThumbController.setData(uri, image.miniThumbBitmap()); } else { mThumbController.setData(null, null); } list.deactivate(); } private void restartPreview() { VideoPreview surfaceView = mSurfaceView; // make sure the surfaceview fills the whole screen when previewing surfaceView.setAspectRatio(VideoPreview.DONT_CARE); setViewFinder(mOriginalViewFinderWidth, mOriginalViewFinderHeight, true); mStatus = IDLE; // Calculate this in advance of each shot so we don't add to shutter latency. It's true that // someone else could write to the SD card in the mean time and fill it, but that could have // happened between the shutter press and saving the JPEG too. // TODO: The best longterm solution is to write a reserve file of maximum JPEG size, always // let the user take a picture, and delete that file if needed to save the new photo. calculatePicturesRemaining(); if (!mIsImageCaptureIntent && !mThumbController.isUriValid()) { updateLastImage(); } if (!mIsImageCaptureIntent) { mThumbController.updateDisplayIfNeeded(); } } private void setViewFinder(int w, int h, boolean startPreview) { if (mPausing) return; if (mPreviewing && w == mViewFinderWidth && h == mViewFinderHeight) { return; } if (!ensureCameraDevice()) return; if (mSurfaceHolder == null) return; if (isFinishing()) return; if (mPausing) return; // remember view finder size mViewFinderWidth = w; mViewFinderHeight = h; if (mOriginalViewFinderHeight == 0) {
brunsky/WS171-packages-apps-Camera
aaa2318dc86eadc7be0163cc564a284e87eab651
Automated import from //branches/cupcake/...@141866,141866
diff --git a/res/values-cs/strings.xml b/res/values-cs/strings.xml index 4a84d72..a1fc3e3 100644 --- a/res/values-cs/strings.xml +++ b/res/values-cs/strings.xml @@ -1,158 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Všechny fotografie"</string> <string name="all_videos">"Všechna videa"</string> <string name="camera_label">"Fotoaparát"</string> <string name="gallery_picker_label">"Galerie"</string> <string name="gallery_camera_bucket_name">"Pořízené fotografie"</string> <string name="gallery_camera_videos_bucket_name">"Pořízená videa"</string> <string name="switch_to_video_lable">"Přepnout do režimu video"</string> <string name="switch_to_camera_lable">"Přepnout do režimu fotoaparát"</string> <string name="crop_label">"Oříznout fotografii"</string> <string name="view_label">"Zobrazit fotografii"</string> <string name="preferences_label">"Nastavení fotoaparátu"</string> <string name="wait">"Čekejte prosím..."</string> <string name="no_storage">"Než začnete používat fotoaparát, vložte kartu SD."</string> <string name="not_enough_space">"Vaše karta SD je plná."</string> <string name="preparing_sd">"Příprava karty SD..."</string> <string name="wallpaper">"Nastavování tapety, čekejte prosím..."</string> <string name="savingImage">"Ukládání fotografie..."</string> <string name="runningFaceDetection">"Čekejte prosím..."</string> <string name="flip_orientation">"Změnit orientaci"</string> <string name="settings">"Nastavení"</string> <string name="view">"Zobrazit"</string> <string name="details">"Podrobnosti"</string> <string name="rotate">"Otočit"</string> <string name="rotate_left">"Otočit doleva"</string> <string name="rotate_right">"Otočit doprava"</string> <string name="slide_show">"Prezentace"</string> <string name="capture_picture">"Fotografovat"</string> <string name="capture_video">"Natočit video"</string> <string name="crop_save_text">"Uložit"</string> <string name="crop_discard_text">"Zahodit"</string> <string name="confirm_delete_title">"Smazat"</string> <string name="confirm_delete_message">"Fotografie bude smazána."</string> <string name="confirm_delete_video_message">"Video bude smazáno."</string> <string name="camera_toss">"Smazat"</string> <string name="camera_gallery">"Galerie"</string> <string name="camera_share">"Sdílet"</string> <string name="camera_set">"Použít jako"</string> <string name="camera_play">"Přehrát"</string> <string name="camera_attach">"Připojit přílohu"</string> <string name="camera_cancel">"Zrušit"</string> <string name="camera_crop">"Oříznout"</string> <string name="camera_tossing">"Mazání..."</string> <string name="no_way_to_share_image">"Tuto fotografii nelze sdílet."</string> <string name="no_way_to_share_video">"Toto video nelze sdílet."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galerie"</string> <string name="camera_pick_wallpaper">"Fotografie"</string> <string name="camera_setas_wallpaper">"Tapeta"</string> <string name="pref_gallery_category">"Obecné nastavení"</string> <string name="pref_slideshow_category">"Nastavení prezentace"</string> <string name="pref_camera_general_settings_category">"Obecné nastavení"</string> <string name="pref_gallery_size_title">"Zobrazovaná velikost"</string> <string name="pref_gallery_size_summary">"Vyberte zobrazovanou velikost obrázků a videí"</string> <string name="pref_gallery_size_dialogtitle">"Velikost fotografie"</string> <string-array name="pref_gallery_size_choices"> <item>"Velké"</item> <item>"Malé"</item> </string-array> <string name="pref_gallery_sort_title">"Řazení"</string> <string name="pref_gallery_sort_summary">"Vyberte způsob řazení obrázků a videí"</string> <string name="pref_gallery_sort_dialogtitle">"Řazení fotografií"</string> <string-array name="pref_gallery_sort_choices"> <item>"Od nejnovějších"</item> <item>"Od nejstarších"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Interval prezentace"</string> <string name="pref_gallery_slideshow_interval_summary">"Vyberte, jak dlouho má být zobrazen každý snímek"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Interval prezentace"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 sekundy"</item> <item>"3 sekundy"</item> <item>"4 sekundy"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Přechod v prezentaci"</string> <string name="pref_gallery_slideshow_transition_summary">"Vyberte efekt, který má být použit při přechodu z jednoho snímku na další"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Přechod v prezentaci"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Prolínat"</item> <item>"Posouvat zleva doprava"</item> <item>"Posouvat shora dolů"</item> <item>"Náhodný výběr"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Opakovat prezentaci"</string> <string name="pref_gallery_slideshow_repeat_summary">"Přehrát prezentaci více než jednou"</string> <string name="pref_gallery_slideshow_shuffle_title">"Náhodné pořadí snímků"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Zobrazit fotografie v náhodném pořadí"</string> <string name="pref_camera_recordlocation_title">"K fotografiím ukládat místo pořízení"</string> <string name="pref_camera_recordlocation_summary">"V datech fotografie zaznamenat místo pořízení"</string> <string name="pref_camera_videoquality_category">"Kvalita videa"</string> <string name="pref_camera_videoquality_title">"Vybrat kvalitu videa"</string> <string name="pref_camera_videoquality_entry_0">"Nízká (pro zprávy MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Vysoká (pro kartu SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Kvalita videa"</string> <string name="camerasettings">"Nastavení"</string> <string name="image_gallery_NoImageView_text">"Žádná média nebyla nalezena."</string> <string name="pref_gallery_confirm_delete_title">"Potvrdit smazání"</string> <string name="pref_gallery_confirm_delete_summary">"Žádat potvrzení před smazáním obrázku nebo videa"</string> <string name="details_panel_title">"Podrobnosti"</string> <string name="details_file_size">"Velikost souboru:"</string> <string name="details_image_resolution">"Rozlišení:"</string> <string name="details_duration">"Délka:"</string> <string name="details_date_taken">"Datum pořízení:"</string> <string name="details_frame_rate">"Počet snímků za sekundu:"</string> <string name="details_bit_rate">"Bitová rychlost:"</string> <string name="details_codec">"Kodek:"</string> <string name="details_format">"Formát:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d snímků/s"</string> <string name="details_kbps">"%1$d Kb/s"</string> <string name="details_mbps">"%1$g Mb/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Možnosti fotografií"</string> <string name="video_context_menu_header">"Možnosti videa"</string> <string name="multiface_crop_help">"Začněte klepnutím na obličej."</string> <string name="photos_gallery_title">"Galerie"</string> <string name="pick_photos_gallery_title">"Vyberte fotografii"</string> <string name="videos_gallery_title">"Galerie"</string> <string name="pick_videos_gallery_title">"Vybrat video"</string> <string name="loading_progress_format_string">"Zbývá <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Sdílet fotografii pomocí"</string> <string name="setImage">"Fotografie bude použita jako"</string> <string name="sendVideo">"Sdílet video pomocí"</string> <string name="movieviewlabel">"Filmy"</string> <string name="loading_video">"Načítání videa..."</string> <string name="spaceIsLow_title">"Dochází volné místo"</string> <string name="spaceIsLow_content">"Na vaší kartě SD je málo místa. Změňte nastavení kvality nebo smažte položky z Galerie."</string> <string name="resume_playing_title">"Pokračovat v přehrávání videa"</string> <string name="resume_playing_message">"Pokračovat v přehrávání od %s?"</string> <string name="resume_playing_resume">"Pokračovat v přehrávání"</string> <string name="resume_playing_restart">"Začít znovu"</string> <string name="gadget_title">"Rámeček fotografie"</string> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="file_info_title">"Informace o souboru:"</string> + <string name="video_exceed_mms_limit">"Zaznamenané video je pro odeslání ve zprávě MMS příliš velké. Zkuste zaznamenat kratší videoklip."</string> + <string name="too_large_to_attach">"Soubor nelze připojit, protože je příliš velký."</string> </resources> diff --git a/res/values-de/strings.xml b/res/values-de/strings.xml index 5b6cae5..ad1373b 100644 --- a/res/values-de/strings.xml +++ b/res/values-de/strings.xml @@ -1,157 +1,154 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Alle Bilder"</string> <string name="all_videos">"Alle Videos"</string> <string name="camera_label">"Kamera"</string> <string name="gallery_picker_label">"Galerie"</string> <string name="gallery_camera_bucket_name">"Kamerabilder"</string> <string name="gallery_camera_videos_bucket_name">"Kameravideos"</string> <string name="switch_to_video_lable">"Zu Video wechseln"</string> <string name="switch_to_camera_lable">"Zu Kamera wechseln"</string> <string name="crop_label">"Bild zuschneiden"</string> <string name="view_label">"Bild anzeigen"</string> <string name="preferences_label">"Kameraeinstellungen"</string> <string name="wait">"Bitte warten..."</string> <string name="no_storage">"Legen Sie vor Verwendung der Kamera eine SD-Karte ein."</string> <string name="not_enough_space">"Ihre SD-Karte ist voll."</string> <string name="preparing_sd">"SD-Karte wird vorbereitet..."</string> <string name="wallpaper">"Hintergrund wird eingestellt, bitte warten..."</string> <string name="savingImage">"Bild wird gespeichert..."</string> <string name="runningFaceDetection">"Bitte warten..."</string> <string name="flip_orientation">"Ausrichtung drehen"</string> <string name="settings">"Einstellungen"</string> <string name="view">"Anzeigen"</string> <string name="details">"Details"</string> <string name="rotate">"Drehen"</string> <string name="rotate_left">"Nach links drehen"</string> <string name="rotate_right">"Nach rechts drehen"</string> <string name="slide_show">"Diashow"</string> <string name="capture_picture">"Bild aufnehmen"</string> <string name="capture_video">"Video aufnehmen"</string> <string name="crop_save_text">"Speichern"</string> <string name="crop_discard_text">"Verwerfen"</string> <string name="confirm_delete_title">"Löschen"</string> <string name="confirm_delete_message">"Das Bild wird gelöscht."</string> <string name="confirm_delete_video_message">"Das Video wird gelöscht."</string> <string name="camera_toss">"Löschen"</string> <string name="camera_gallery">"Galerie"</string> <string name="camera_share">"Senden"</string> <string name="camera_set">"Festlegen als"</string> <string name="camera_play">"Wiedergeben"</string> <string name="camera_attach">"Anhängen"</string> <string name="camera_cancel">"Abbrechen"</string> <string name="camera_crop">"Zuschneiden"</string> <string name="camera_tossing">"Löschvorgang..."</string> <string name="no_way_to_share_image">"Dieses Bild kann nicht weitergeleitet werden."</string> <string name="no_way_to_share_video">"Dieses Video kann nicht weitergeleitet werden."</string> <string name="video_play">"Play"</string> <string name="camera_gallery_photos_text">"Galerie"</string> <string name="camera_pick_wallpaper">"Bilder"</string> <string name="camera_setas_wallpaper">"Hintergrund"</string> <string name="pref_gallery_category">"Allgemeine Einstellungen"</string> <string name="pref_slideshow_category">"Einstellungen für Diashow"</string> <string name="pref_camera_general_settings_category">"Allgemeine Einstellungen"</string> <string name="pref_gallery_size_title">"Anzeigegröße"</string> <string name="pref_gallery_size_summary">"Anzeigegröße für Bilder und Videos auswählen"</string> <string name="pref_gallery_size_dialogtitle">"Bildgröße"</string> <string-array name="pref_gallery_size_choices"> <item>"Groß"</item> <item>"Klein"</item> </string-array> <string name="pref_gallery_sort_title">"Sortierreihenfolge"</string> <string name="pref_gallery_sort_summary">"Sortierreihenfolge für Bilder und Videos auswählen"</string> <string name="pref_gallery_sort_dialogtitle">"Sortierreihenfolge für Bilder"</string> <string-array name="pref_gallery_sort_choices"> <item>"Neue zuerst"</item> <item>"Neue zuletzt"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Diashow-Intervall"</string> <string name="pref_gallery_slideshow_interval_summary">"Auswählen, wie lange jedes Bild in der Diashow angezeigt werden soll"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Diashow-Intervall"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 Sekunden"</item> <item>"3 Sekunden"</item> <item>"4 Sekunden"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Diashow - Übergang"</string> <string name="pref_gallery_slideshow_transition_summary">"Effekt auswählen, der beim Wechsel zum nächsten Bild angewendet wird"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Diashow - Übergang"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ein- und ausblenden"</item> <item>"Einblendung von links - rechts"</item> <item>"Einblendung von oben - unten"</item> <item>"Zufällige Auswahl"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Diashow erneut anzeigen?"</string> <string name="pref_gallery_slideshow_repeat_summary">"Diashow mehrmals anzeigen"</string> <string name="pref_gallery_slideshow_shuffle_title">"Bilder mischen"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Bilder in zufälliger Reihenfolge anzeigen"</string> <string name="pref_camera_recordlocation_title">"Aufnahmeort in Bildern speichern"</string> <string name="pref_camera_recordlocation_summary">"Aufnahmeort in Bilddaten speichern"</string> <string name="pref_camera_videoquality_category">"Videoqualität"</string> <string name="pref_camera_videoquality_title">"Videoqualität auswählen"</string> <string name="pref_camera_videoquality_entry_0">"Niedrig (für MMS-Mitteilungen)"</string> <string name="pref_camera_videoquality_entry_1">"Hoch (für SD-Karte)"</string> <string name="pref_camera_videoquality_dialogtitle">"Videoqualität"</string> <string name="camerasettings">"Einstellungen"</string> <string name="image_gallery_NoImageView_text">"Keine Medien gefunden."</string> <string name="pref_gallery_confirm_delete_title">"Löschvorgang bestätigen"</string> <string name="pref_gallery_confirm_delete_summary">"Bestätigung vor dem Löschen eines Bildes oder Videos anzeigen"</string> <string name="details_panel_title">"Details"</string> <string name="details_file_size">"Dateigröße:"</string> <string name="details_image_resolution">"Auflösung:"</string> <string name="details_duration">"Dauer:"</string> <string name="details_date_taken">"Aufnahmedatum:"</string> <string name="details_frame_rate">"Framerate:"</string> <string name="details_bit_rate">"Bitrate:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbit/s"</string> <string name="details_mbps">"%1$g Mbit/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Bildoptionen"</string> <string name="video_context_menu_header">"Videooptionen"</string> <string name="multiface_crop_help">"Tippen Sie zum Beginnen auf ein Gesicht."</string> <string name="photos_gallery_title">"Galerie"</string> <string name="pick_photos_gallery_title">"Bild auswählen"</string> <string name="videos_gallery_title">"Galerie"</string> <string name="pick_videos_gallery_title">"Video auswählen"</string> <string name="loading_progress_format_string">"noch <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Bild senden via"</string> <string name="setImage">"Bild festlegen als"</string> <string name="sendVideo">"Video weiterleiten via"</string> <string name="movieviewlabel">"Filme"</string> <string name="loading_video">"Video wird geladen..."</string> <string name="spaceIsLow_title">"Geringer Speicherplatz"</string> <string name="spaceIsLow_content">"Auf Ihrer SD-Karte ist nicht mehr genügend Speicherplatz vorhanden. Ändern Sie die Qualitätseinstellung oder löschen Sie Elemente aus der Galerie."</string> <string name="resume_playing_title">"Mit Video fortfahren"</string> <string name="resume_playing_message">"Mit Wiedergabe fortfahren ab %s ?"</string> <string name="resume_playing_resume">"Mit Wiedergabe fortfahren"</string> <string name="resume_playing_restart">"Starten"</string> <string name="gadget_title">"Bildrahmen"</string> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="file_info_title">"Dateiinfo:"</string> + <string name="video_exceed_mms_limit">"Das aufgenommene Video ist zu groß und kann nicht per MMS gesendet werden. Nehmen Sie einen kürzeren Clip auf."</string> + <string name="too_large_to_attach">"Dateianhang zu groß"</string> </resources> diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml index d000e7e..120742c 100644 --- a/res/values-es/strings.xml +++ b/res/values-es/strings.xml @@ -1,158 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Todas las imágenes"</string> <string name="all_videos">"Todos los vídeos"</string> <string name="camera_label">"Cámara"</string> <string name="gallery_picker_label">"Galería"</string> <string name="gallery_camera_bucket_name">"Imágenes de cámara"</string> <string name="gallery_camera_videos_bucket_name">"Vídeos de cámara"</string> <string name="switch_to_video_lable">"Cambiar a vídeo"</string> <string name="switch_to_camera_lable">"Cambiar a cámara"</string> <string name="crop_label">"Recortar imagen"</string> <string name="view_label">"Ver imagen"</string> <string name="preferences_label">"Configuración de cámara"</string> <string name="wait">"Por favor, espera..."</string> <string name="no_storage">"Antes de utilizar la cámara, debes insertar una tarjeta SD."</string> <string name="not_enough_space">"La tarjeta SD está llena."</string> <string name="preparing_sd">"Preparando tarjeta SD…"</string> <string name="wallpaper">"Estableciendo fondo de pantalla; por favor, espera..."</string> <string name="savingImage">"Guardando imagen..."</string> <string name="runningFaceDetection">"Por favor, espera..."</string> <string name="flip_orientation">"Cambiar orientación"</string> <string name="settings">"Ajustes"</string> <string name="view">"Ver"</string> <string name="details">"Detalles"</string> <string name="rotate">"Girar"</string> <string name="rotate_left">"Girar a la izquierda"</string> <string name="rotate_right">"Girar a la derecha"</string> <string name="slide_show">"Presentación"</string> <string name="capture_picture">"Capturar imagen"</string> <string name="capture_video">"Capturar vídeo"</string> <string name="crop_save_text">"Guardar"</string> <string name="crop_discard_text">"Descartar"</string> <string name="confirm_delete_title">"Suprimir"</string> <string name="confirm_delete_message">"Se eliminará la imagen."</string> <string name="confirm_delete_video_message">"Se eliminará el vídeo."</string> <string name="camera_toss">"Suprimir"</string> <string name="camera_gallery">"Galería"</string> <string name="camera_share">"Compartir"</string> <string name="camera_set">"Establecer como"</string> <string name="camera_play">"Reproducir"</string> <string name="camera_attach">"Adjuntar"</string> <string name="camera_cancel">"Cancelar"</string> <string name="camera_crop">"Recortar"</string> <string name="camera_tossing">"Eliminando..."</string> <string name="no_way_to_share_image">"Esta imagen no se puede compartir."</string> <string name="no_way_to_share_video">"Este vídeo no se puede compartir."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galería"</string> <string name="camera_pick_wallpaper">"Imágenes"</string> <string name="camera_setas_wallpaper">"Fondo de pantalla"</string> <string name="pref_gallery_category">"Configuración general"</string> <string name="pref_slideshow_category">"Configuración de presentación"</string> <string name="pref_camera_general_settings_category">"Configuración general"</string> <string name="pref_gallery_size_title">"Tamaño de visualización"</string> <string name="pref_gallery_size_summary">"Seleccionar el tamaño de visualización de imágenes y vídeos"</string> <string name="pref_gallery_size_dialogtitle">"Tamaño de imagen"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Pequeña"</item> </string-array> <string name="pref_gallery_sort_title">"Orden"</string> <string name="pref_gallery_sort_summary">"Seleccionar el orden de imágenes y vídeos"</string> <string name="pref_gallery_sort_dialogtitle">"Ordenación de imágenes"</string> <string-array name="pref_gallery_sort_choices"> <item>"Más recientes primero"</item> <item>"Más recientes al final"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalo de presentación"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleccionar la duración de cada diapositiva"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalo de presentación"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 segundos"</item> <item>"3 segundos"</item> <item>"4 segundos"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transición de diapositivas"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleccionar el efecto que se aplicará al pasar de una diapositiva a otra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transición de diapositivas"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Fundido de entrada y salida"</item> <item>"Transición de izquierda a derecha"</item> <item>"Transición de arriba a abajo"</item> <item>"Selección aleatoria"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Repetir presentación"</string> <string name="pref_gallery_slideshow_repeat_summary">"Mostrar presentación más de una vez"</string> <string name="pref_gallery_slideshow_shuffle_title">"Reproducir diapositivas en orden aleatorio"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostrar imágenes en orden aleatorio"</string> <string name="pref_camera_recordlocation_title">"Almacenar ubicación en imágenes"</string> <string name="pref_camera_recordlocation_summary">"Registrar ubicación en datos de imagen"</string> <string name="pref_camera_videoquality_category">"Calidad de vídeo"</string> <string name="pref_camera_videoquality_title">"Seleccionar calidad de vídeo"</string> <string name="pref_camera_videoquality_entry_0">"Baja (para mensajes MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (para tarjeta SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Calidad de vídeo"</string> <string name="camerasettings">"Ajustes"</string> <string name="image_gallery_NoImageView_text">"No se ha encontrado ningún elemento."</string> <string name="pref_gallery_confirm_delete_title">"Confirmar eliminaciones"</string> <string name="pref_gallery_confirm_delete_summary">"Mostrar confirmación antes de eliminar una imagen o un vídeo"</string> <string name="details_panel_title">"Detalles"</string> <string name="details_file_size">"Tamaño de archivo:"</string> <string name="details_image_resolution">"Resolución:"</string> <string name="details_duration">"Duración:"</string> <string name="details_date_taken">"Fecha de realización:"</string> <string name="details_frame_rate">"Frecuencia de imagen:"</string> <string name="details_bit_rate">"Velocidad binaria:"</string> <string name="details_codec">"Códec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"Aceptar"</string> <string name="context_menu_header">"Opciones de imagen"</string> <string name="video_context_menu_header">"Opciones de vídeo"</string> <string name="multiface_crop_help">"Selecciona una cara para empezar."</string> <string name="photos_gallery_title">"Galería"</string> <string name="pick_photos_gallery_title">"Seleccionar imagen"</string> <string name="videos_gallery_title">"Galería"</string> <string name="pick_videos_gallery_title">"Seleccionar vídeo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> restantes"</string> <string name="sendImage">"Compartir imagen por"</string> <string name="setImage">"Establecer imagen como"</string> <string name="sendVideo">"Compartir vídeo a través de"</string> <string name="movieviewlabel">"Películas"</string> <string name="loading_video">"Cargando vídeo…"</string> <string name="spaceIsLow_title">"Poco espacio"</string> <string name="spaceIsLow_content">"No queda espacio en la tarjeta SD. Cambia la configuración de calidad o elimina elementos de la galería."</string> <string name="resume_playing_title">"Reanudar vídeo"</string> <string name="resume_playing_message">"Reanudar reproducción a partir de %s ?"</string> <string name="resume_playing_resume">"Reanudar reproducción"</string> <string name="resume_playing_restart">"Volver a reproducir"</string> <string name="gadget_title">"Picture frame"</string> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="file_info_title">"Información de archivo:"</string> + <string name="video_exceed_mms_limit">"El vídeo que has grabado es demasiado grande para enviarlo a través de MMS. Intenta grabar un vídeo de menor duración."</string> + <string name="too_large_to_attach">"El archivo es demasiado grande para adjuntarlo."</string> </resources> diff --git a/res/values-fr/strings.xml b/res/values-fr/strings.xml index 4908916..5813dde 100644 --- a/res/values-fr/strings.xml +++ b/res/values-fr/strings.xml @@ -1,158 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Toutes les images"</string> <string name="all_videos">"Toutes les vidéos"</string> <string name="camera_label">"Appareil photo"</string> <string name="gallery_picker_label">"Galerie"</string> <string name="gallery_camera_bucket_name">"Photos de l\'appareil"</string> <string name="gallery_camera_videos_bucket_name">"Vidéos de la caméra"</string> <string name="switch_to_video_lable">"Passer en mode vidéo"</string> <string name="switch_to_camera_lable">"Passer en mode appareil photo"</string> <string name="crop_label">"Rogner l\'image"</string> <string name="view_label">"Afficher l\'image"</string> <string name="preferences_label">"Paramètres de l\'appareil photo"</string> <string name="wait">"Veuillez patienter..."</string> <string name="no_storage">"Veuillez insérer une carte SD avant d\'utiliser l\'appareil photo."</string> <string name="not_enough_space">"Votre carte SD est pleine."</string> <string name="preparing_sd">"Préparation de la carte SD..."</string> <string name="wallpaper">"Configuration de l\'arrière-plan en cours. Veuillez patienter..."</string> <string name="savingImage">"Enregistrement de l\'image"</string> <string name="runningFaceDetection">"Veuillez patienter..."</string> <string name="flip_orientation">"Orientation"</string> <string name="settings">"Paramètres"</string> <string name="view">"Afficher"</string> <string name="details">"Détails"</string> <string name="rotate">"Faire pivoter"</string> <string name="rotate_left">"Faire pivoter à gauche"</string> <string name="rotate_right">"Faire pivoter à droite"</string> <string name="slide_show">"Diaporama"</string> <string name="capture_picture">"Prendre une photo"</string> <string name="capture_video">"Prendre une vidéo"</string> <string name="crop_save_text">"Enregistrer"</string> <string name="crop_discard_text">"Annuler"</string> <string name="confirm_delete_title">"Supprimer"</string> <string name="confirm_delete_message">"L\'image sera supprimée."</string> <string name="confirm_delete_video_message">"La vidéo va être supprimée."</string> <string name="camera_toss">"Supprimer"</string> <string name="camera_gallery">"Galerie"</string> <string name="camera_share">"Partager"</string> <string name="camera_set">"Définir comme"</string> <string name="camera_play">"Lire"</string> <string name="camera_attach">"Joindre"</string> <string name="camera_cancel">"Annuler"</string> <string name="camera_crop">"Rogner"</string> <string name="camera_tossing">"Suppression..."</string> <string name="no_way_to_share_image">"Impossible de partager cette image."</string> <string name="no_way_to_share_video">"Cette vidéo ne peut pas être partagée."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galerie"</string> <string name="camera_pick_wallpaper">"Images"</string> <string name="camera_setas_wallpaper">"Arrière-plan"</string> <string name="pref_gallery_category">"Paramètres généraux"</string> <string name="pref_slideshow_category">"Paramètres du diaporama"</string> <string name="pref_camera_general_settings_category">"Paramètres généraux"</string> <string name="pref_gallery_size_title">"Taille d\'affichage"</string> <string name="pref_gallery_size_summary">"Sélectionner la taille d\'affichage des images et des vidéos"</string> <string name="pref_gallery_size_dialogtitle">"Taille de l\'image"</string> <string-array name="pref_gallery_size_choices"> <item>"Grande"</item> <item>"Petite"</item> </string-array> <string name="pref_gallery_sort_title">"Ordre de tri"</string> <string name="pref_gallery_sort_summary">"Sélectionner l\'ordre de tri des images et des vidéos"</string> <string name="pref_gallery_sort_dialogtitle">"Trier les images"</string> <string-array name="pref_gallery_sort_choices"> <item>"La plus récente en premier"</item> <item>"La plus récente en dernier"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervalle du diaporama"</string> <string name="pref_gallery_slideshow_interval_summary">"Sélectionner la durée d\'affichage de chaque diapositive dans le diaporama"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervalle du diaporama"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 secondes"</item> <item>"3 secondes"</item> <item>"4 secondes"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transition du diaporama"</string> <string name="pref_gallery_slideshow_transition_summary">"Sélectionner l\'effet utilisé lors de la transition d\'une diapositive à une autre"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transition du diaporama"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ouverture et fermeture en fondu"</item> <item>"Glisser de gauche à droite"</item> <item>"Glisser de haut en bas"</item> <item>"Sélection aléatoire"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Rejouer le diaporama"</string> <string name="pref_gallery_slideshow_repeat_summary">"Rejouer le diaporama plusieurs fois"</string> <string name="pref_gallery_slideshow_shuffle_title">"Lecture aléatoire"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Afficher les images"</string> <string name="pref_camera_recordlocation_title">"Enregistrer le lieu"</string> <string name="pref_camera_recordlocation_summary">"Enregistrer la position géographique dans les données d\'image"</string> <string name="pref_camera_videoquality_category">"Paramètres vidéo"</string> <string name="pref_camera_videoquality_title">"Qualité vidéo"</string> <string name="pref_camera_videoquality_entry_0">"Basse (pour les MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Haute (pour la carte SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Qualité vidéo"</string> <string name="camerasettings">"Paramètres"</string> <string name="image_gallery_NoImageView_text">"Aucun fichier trouvé."</string> <string name="pref_gallery_confirm_delete_title">"Confirmer suppressions"</string> <string name="pref_gallery_confirm_delete_summary">"Afficher une confirmation avant de supprimer une image ou une vidéo"</string> <string name="details_panel_title">"Détails"</string> <string name="details_file_size">"Taille du fichier :"</string> <string name="details_image_resolution">"Résolution :"</string> <string name="details_duration">"Durée :"</string> <string name="details_date_taken">"Date de création :"</string> <string name="details_frame_rate">"Fréquence d\'images :"</string> <string name="details_bit_rate">"Débit :"</string> <string name="details_codec">"Codec :"</string> <string name="details_format">"Format :"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d ips"</string> <string name="details_kbps">"%1$d Kbits/s"</string> <string name="details_mbps">"%1$g Mbits/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Options de l\'image"</string> <string name="video_context_menu_header">"Options vidéo"</string> <string name="multiface_crop_help">"Cliquez sur un visage pour commencer."</string> <string name="photos_gallery_title">"Galerie"</string> <string name="pick_photos_gallery_title">"Sélectionnez une image"</string> <string name="videos_gallery_title">"Galerie"</string> <string name="pick_videos_gallery_title">"Sélectionnez une vidéo"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> vignettes restantes"</string> <string name="sendImage">"Partager l\'image via"</string> <string name="setImage">"Définir l\'image comme"</string> <string name="sendVideo">"Partager la vidéo via"</string> <string name="movieviewlabel">"Films"</string> <string name="loading_video">"Chargement de la vidéo..."</string> <string name="spaceIsLow_title">"L\'espace restant est faible"</string> <string name="spaceIsLow_content">"Votre carte SD est pleine. Modifiez le paramètre de qualité ou supprimez des éléments de la galerie."</string> <string name="resume_playing_title">"Reprendre la vidéo"</string> <string name="resume_playing_message">"Reprendre la lecture à partir de %s ?"</string> <string name="resume_playing_resume">"Reprendre la lecture"</string> <string name="resume_playing_restart">"Démarrer"</string> <string name="gadget_title">"Cadre d\'image"</string> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="file_info_title">"Informations sur le fichier :"</string> + <string name="video_exceed_mms_limit">"La vidéo que vous avez enregistrée est trop volumineuse et ne peut être envoyée par MMS. Enregistrez une vidéo plus courte."</string> + <string name="too_large_to_attach">"Impossible de joindre le fichier, car il est trop volumineux."</string> </resources> diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml index e92e78f..0dab680 100644 --- a/res/values-it/strings.xml +++ b/res/values-it/strings.xml @@ -1,158 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Tutte le foto"</string> <string name="all_videos">"Tutti i video"</string> <string name="camera_label">"Fotocamera"</string> <string name="gallery_picker_label">"Galleria"</string> <string name="gallery_camera_bucket_name">"Foto"</string> <string name="gallery_camera_videos_bucket_name">"Video fotocamera"</string> <string name="switch_to_video_lable">"Passa a video"</string> <string name="switch_to_camera_lable">"Passa a fotocamera"</string> <string name="crop_label">"Ritaglia foto"</string> <string name="view_label">"Visualizza foto"</string> <string name="preferences_label">"Impostazioni fotocamera"</string> <string name="wait">"Attendere..."</string> <string name="no_storage">"Per usare la fotocamera devi inserire una scheda SD."</string> <string name="not_enough_space">"La scheda SD è piena."</string> <string name="preparing_sd">"Preparazione scheda SD…"</string> <string name="wallpaper">"Impostazione sfondo, attendi..."</string> <string name="savingImage">"Salvataggio foto..."</string> <string name="runningFaceDetection">"Attendere..."</string> <string name="flip_orientation">"Capovolgi orientamento"</string> <string name="settings">"Impostazioni"</string> <string name="view">"Visualizza"</string> <string name="details">"Dettagli"</string> <string name="rotate">"Ruota"</string> <string name="rotate_left">"Ruota a sinistra"</string> <string name="rotate_right">"Ruota a destra"</string> <string name="slide_show">"Presentazione"</string> <string name="capture_picture">"Scatta foto"</string> <string name="capture_video">"Registra video"</string> <string name="crop_save_text">"Salva"</string> <string name="crop_discard_text">"Annulla"</string> <string name="confirm_delete_title">"Elimina"</string> <string name="confirm_delete_message">"La foto verrà eliminata."</string> <string name="confirm_delete_video_message">"Il video verrà eliminato."</string> <string name="camera_toss">"Elimina"</string> <string name="camera_gallery">"Galleria"</string> <string name="camera_share">"Condividi"</string> <string name="camera_set">"Imposta come"</string> <string name="camera_play">"Riproduci"</string> <string name="camera_attach">"Allega"</string> <string name="camera_cancel">"Annulla"</string> <string name="camera_crop">"Ritaglia"</string> <string name="camera_tossing">"Eliminazione..."</string> <string name="no_way_to_share_image">"Impossibile condividere la foto."</string> <string name="no_way_to_share_video">"Impossibile condividere il video."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galleria"</string> <string name="camera_pick_wallpaper">"Foto"</string> <string name="camera_setas_wallpaper">"Sfondo"</string> <string name="pref_gallery_category">"Impostazioni generali"</string> <string name="pref_slideshow_category">"Impostazioni presentazione"</string> <string name="pref_camera_general_settings_category">"Impostazioni generali"</string> <string name="pref_gallery_size_title">"Dimensioni schermo"</string> <string name="pref_gallery_size_summary">"Seleziona dimensioni di visualizz. di foto e video"</string> <string name="pref_gallery_size_dialogtitle">"Dimensioni foto"</string> <string-array name="pref_gallery_size_choices"> <item>"Grandi"</item> <item>"Piccole"</item> </string-array> <string name="pref_gallery_sort_title">"Ordinamento"</string> <string name="pref_gallery_sort_summary">"Seleziona l\'ordinamento di foto e video"</string> <string name="pref_gallery_sort_dialogtitle">"Ordine foto"</string> <string-array name="pref_gallery_sort_choices"> <item>"Da più recente"</item> <item>"Da meno recente"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Intervallo presentazione"</string> <string name="pref_gallery_slideshow_interval_summary">"Seleziona la durata di ogni diapositiva"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Intervallo presentazione"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 secondi"</item> <item>"3 secondi"</item> <item>"4 secondi"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Transizione presentazione"</string> <string name="pref_gallery_slideshow_transition_summary">"Seleziona l\'effetto da usare per passare da una diapositiva all\'altra"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Transizione diapositive"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Dissolvenza"</item> <item>"Da sinistra a destra"</item> <item>"Dall\'alto verso il basso"</item> <item>"Selezione casuale"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Ripeti presentazione"</string> <string name="pref_gallery_slideshow_repeat_summary">"Riproduci più volte la presentazione"</string> <string name="pref_gallery_slideshow_shuffle_title">"Riproduzione casuale"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Mostra le foto in ordine casuale"</string> <string name="pref_camera_recordlocation_title">"Salva località nelle foto"</string> <string name="pref_camera_recordlocation_summary">"Registra località nei dati della foto"</string> <string name="pref_camera_videoquality_category">"Qualità video"</string> <string name="pref_camera_videoquality_title">"Seleziona la qualità video"</string> <string name="pref_camera_videoquality_entry_0">"Bassa (per MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Alta (per scheda SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Qualità video"</string> <string name="camerasettings">"Impostazioni"</string> <string name="image_gallery_NoImageView_text">"Nessun media trovato."</string> <string name="pref_gallery_confirm_delete_title">"Conferma eliminazioni"</string> <string name="pref_gallery_confirm_delete_summary">"Mostra conferma prima di eliminare una foto o un video"</string> <string name="details_panel_title">"Dettagli"</string> <string name="details_file_size">"Dim. file:"</string> <string name="details_image_resolution">"Risoluzione:"</string> <string name="details_duration">"Durata:"</string> <string name="details_date_taken">"Data scatto:"</string> <string name="details_frame_rate">"Frequenza fotogrammi:"</string> <string name="details_bit_rate">"Velocità in bit:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Formato:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opzioni foto"</string> <string name="video_context_menu_header">"Opzioni video"</string> <string name="multiface_crop_help">"Tocca un viso per iniziare."</string> <string name="photos_gallery_title">"Galleria"</string> <string name="pick_photos_gallery_title">"Seleziona foto"</string> <string name="videos_gallery_title">"Galleria"</string> <string name="pick_videos_gallery_title">"Seleziona video"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> rimanenti"</string> <string name="sendImage">"Condividi foto via"</string> <string name="setImage">"Imposta foto come"</string> <string name="sendVideo">"Condividi video via"</string> <string name="movieviewlabel">"Film"</string> <string name="loading_video">"Caricamento video..."</string> <string name="spaceIsLow_title">"Spazio in esaurimento"</string> <string name="spaceIsLow_content">"Lo spazio della scheda SD si sta esaurendo. Cambia l\'impostazione di qualità o elimina elementi nella galleria."</string> <string name="resume_playing_title">"Riprendi video"</string> <string name="resume_playing_message">"Riprendi riproduzione da %s ?"</string> <string name="resume_playing_resume">"Riprendi riproduzione"</string> <string name="resume_playing_restart">"Ricomincia"</string> <string name="gadget_title">"Cornice immagine"</string> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="file_info_title">"Info file:"</string> + <string name="video_exceed_mms_limit">"Il video registrato è troppo grande per essere inviato tramite MMS. Prova a registrare un clip più corto."</string> + <string name="too_large_to_attach">"File troppo grande. Impossibile allegarlo."</string> </resources> diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml index 290cd6b..bd306eb 100644 --- a/res/values-ja/strings.xml +++ b/res/values-ja/strings.xml @@ -1,158 +1,158 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"すべての写真"</string> <string name="all_videos">"すべての動画"</string> <string name="camera_label">"カメラ"</string> <string name="gallery_picker_label">"ギャラリー"</string> <string name="gallery_camera_bucket_name">"カメラ (写真)"</string> <string name="gallery_camera_videos_bucket_name">"カメラ (動画)"</string> <string name="switch_to_video_lable">"ムービーに切替"</string> <string name="switch_to_camera_lable">"写真に切替"</string> - <string name="crop_label">"写真のトリミング"</string> - <string name="view_label">"写真を表示"</string> + <string name="crop_label">"トリミング"</string> + <string name="view_label">"画像を表示"</string> <string name="preferences_label">"カメラ設定"</string> <string name="wait">"お待ちください..."</string> <string name="no_storage">"カメラを使用する前にSDカードを挿入してください。"</string> <string name="not_enough_space">"SDカードがいっぱいです。"</string> <string name="preparing_sd">"SDカードの準備中..."</string> <string name="wallpaper">"壁紙を設定しています。しばらくお待ちください..."</string> <string name="savingImage">"写真を保存中..."</string> <string name="runningFaceDetection">"お待ちください..."</string> <string name="flip_orientation">"画面の向きを変更"</string> <string name="settings">"設定"</string> <string name="view">"表示"</string> <string name="details">"詳細"</string> <string name="rotate">"回転"</string> <string name="rotate_left">"左に回転"</string> <string name="rotate_right">"右に回転"</string> <string name="slide_show">"スライドショー"</string> <string name="capture_picture">"写真撮影"</string> <string name="capture_video">"ムービー撮影"</string> <string name="crop_save_text">"保存"</string> <string name="crop_discard_text">"破棄"</string> <string name="confirm_delete_title">"削除"</string> - <string name="confirm_delete_message">"写真を削除します。"</string> + <string name="confirm_delete_message">"画像を削除します。"</string> <string name="confirm_delete_video_message">"動画を削除します。"</string> <string name="camera_toss">"削除"</string> <string name="camera_gallery">"ギャラリー"</string> <string name="camera_share">"共有"</string> <string name="camera_set">"設定"</string> <string name="camera_play">"再生"</string> <string name="camera_attach">"添付"</string> <string name="camera_cancel">"キャンセル"</string> <string name="camera_crop">"トリミング"</string> <string name="camera_tossing">"削除中..."</string> - <string name="no_way_to_share_image">"この写真は共有できません。"</string> + <string name="no_way_to_share_image">"この画像は共有できません。"</string> <string name="no_way_to_share_video">"この動画は共有できません。"</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"ギャラリー"</string> - <string name="camera_pick_wallpaper">"写真"</string> + <string name="camera_pick_wallpaper">"画像"</string> <string name="camera_setas_wallpaper">"壁紙"</string> <string name="pref_gallery_category">"全般設定"</string> <string name="pref_slideshow_category">"スライドショー設定"</string> <string name="pref_camera_general_settings_category">"全般設定"</string> <string name="pref_gallery_size_title">"表示サイズ"</string> <string name="pref_gallery_size_summary">"写真と動画の表示サイズを選択"</string> - <string name="pref_gallery_size_dialogtitle">"写真サイズ"</string> + <string name="pref_gallery_size_dialogtitle">"画像サイズ"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"並び替え順"</string> - <string name="pref_gallery_sort_summary">"写真と動画の並び替え順を選択"</string> - <string name="pref_gallery_sort_dialogtitle">"写真の並べ替え"</string> + <string name="pref_gallery_sort_summary">"画像と動画の表示順序を選択"</string> + <string name="pref_gallery_sort_dialogtitle">"画像並べ替え"</string> <string-array name="pref_gallery_sort_choices"> <item>"日付の新しい順"</item> <item>"日付の古い順"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"スライドショーの間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"各スライドの表示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"スライドショーの間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2秒"</item> <item>"3秒"</item> <item>"4秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"スライドショーのトランジション"</string> <string name="pref_gallery_slideshow_transition_summary">"スライドが切り替わるときの効果を選択"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"スライドショーのトランジション"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"フェードイン&amp;アウト"</item> <item>"左右にスライド"</item> <item>"上下にスライド"</item> <item>"ランダムに選択"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"スライドショーを繰り返す"</string> <string name="pref_gallery_slideshow_repeat_summary">"スライドショーを繰り返す"</string> <string name="pref_gallery_slideshow_shuffle_title">"スライドのシャッフル"</string> - <string name="pref_gallery_slideshow_shuffle_summary">"写真をランダムに表示"</string> + <string name="pref_gallery_slideshow_shuffle_summary">"画像をランダムに表示する"</string> <string name="pref_camera_recordlocation_title">"位置情報を写真に記録する"</string> - <string name="pref_camera_recordlocation_summary">"写真データに位置情報を記録します"</string> + <string name="pref_camera_recordlocation_summary">"位置情報を写真データに記録する"</string> <string name="pref_camera_videoquality_category">"動画のクオリティ"</string> <string name="pref_camera_videoquality_title">"動画の画質を選択"</string> <string name="pref_camera_videoquality_entry_0">"低 (MMSメッセージ向け)"</string> <string name="pref_camera_videoquality_entry_1">"高 (SDカード向け)"</string> <string name="pref_camera_videoquality_dialogtitle">"動画のクオリティ"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"メディアが見つかりません。"</string> - <string name="pref_gallery_confirm_delete_title">"削除を確認"</string> - <string name="pref_gallery_confirm_delete_summary">"写真や動画を削除する前に確認メッセージを表示"</string> + <string name="pref_gallery_confirm_delete_title">"削除確認"</string> + <string name="pref_gallery_confirm_delete_summary">"画像や動画を削除する前に確認メッセージを表示"</string> <string name="details_panel_title">"詳細"</string> <string name="details_file_size">"ファイルサイズ:"</string> <string name="details_image_resolution">"解像度:"</string> <string name="details_duration">"再生時間:"</string> <string name="details_date_taken">"撮影日:"</string> <string name="details_frame_rate">"フレームレート:"</string> <string name="details_bit_rate">"ビットレート:"</string> <string name="details_codec">"コーデック:"</string> <string name="details_format">"形式:"</string> <string name="details_dimension_x">"%1$dx%2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$dfps"</string> <string name="details_kbps">"%1$dKbps"</string> <string name="details_mbps">"%1$gMbps"</string> <string name="details_ok">"OK"</string> - <string name="context_menu_header">"写真オプション"</string> + <string name="context_menu_header">"画像オプション"</string> <string name="video_context_menu_header">"動画オプション"</string> <string name="multiface_crop_help">"顔をタップして開始します。"</string> <string name="photos_gallery_title">"ギャラリー"</string> - <string name="pick_photos_gallery_title">"写真を選択"</string> + <string name="pick_photos_gallery_title">"画像を選択"</string> <string name="videos_gallery_title">"ギャラリー"</string> <string name="pick_videos_gallery_title">"動画を選択"</string> <string name="loading_progress_format_string">"残り<xliff:g id="COUNTER">%d</xliff:g>件"</string> - <string name="sendImage">"写真を共有"</string> - <string name="setImage">"写真を設定"</string> + <string name="sendImage">"画像を共有:"</string> + <string name="setImage">"設定タイプ:"</string> <string name="sendVideo">"動画を共有"</string> <string name="movieviewlabel">"映画"</string> <string name="loading_video">"動画を読み込み中..."</string> <string name="spaceIsLow_title">"空き容量が残り少なくなっています"</string> <string name="spaceIsLow_content">"SDカードの容量が足りません。クオリティ設定を変更するか、ギャラリーからアイテムを削除してください。"</string> <string name="resume_playing_title">"動画の再開"</string> <string name="resume_playing_message">"再生を%sから再開しますか?"</string> <string name="resume_playing_resume">"再生を再開"</string> <string name="resume_playing_restart">"最初から再生"</string> <string name="gadget_title">"写真フレーム"</string> <!-- no translation found for file_info_title (1628963357466012538) --> <skip /> <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> <skip /> <!-- no translation found for too_large_to_attach (8944461117941172986) --> <skip /> </resources> diff --git a/res/values-ko/strings.xml b/res/values-ko/strings.xml index 0b653ac..5cd51a9 100644 --- a/res/values-ko/strings.xml +++ b/res/values-ko/strings.xml @@ -1,158 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"모든 사진"</string> <string name="all_videos">"모든 동영상"</string> <string name="camera_label">"카메라"</string> <string name="gallery_picker_label">"갤러리"</string> <string name="gallery_camera_bucket_name">"카메라 사진"</string> <string name="gallery_camera_videos_bucket_name">"카메라 동영상"</string> <string name="switch_to_video_lable">"동영상으로 전환"</string> <string name="switch_to_camera_lable">"카메라로 전환"</string> <string name="crop_label">"사진 자르기"</string> <string name="view_label">"사진 보기"</string> <string name="preferences_label">"카메라 설정"</string> <string name="wait">"잠시 기다려 주세요..."</string> <string name="no_storage">"카메라를 사용하기 전에 먼저 SD 카드를 넣으세요."</string> <string name="not_enough_space">"SD 카드가 꽉 찼습니다."</string> <string name="preparing_sd">"SD 카드 준비중..."</string> <string name="wallpaper">"배경화면 설정 중. 잠시 기다려 주세요..."</string> <string name="savingImage">"사진 저장 중..."</string> <string name="runningFaceDetection">"잠시 기다려 주세요..."</string> <string name="flip_orientation">"방향 바꾸기"</string> <string name="settings">"설정"</string> <string name="view">"보기"</string> <string name="details">"상세정보"</string> <string name="rotate">"회전"</string> <string name="rotate_left">"왼쪽으로 회전"</string> <string name="rotate_right">"오른쪽으로 회전"</string> <string name="slide_show">"슬라이드쇼"</string> <string name="capture_picture">"사진촬영"</string> <string name="capture_video">"동영상 캡처"</string> <string name="crop_save_text">"저장"</string> <string name="crop_discard_text">"무시"</string> <string name="confirm_delete_title">"삭제"</string> <string name="confirm_delete_message">"사진이 삭제됩니다."</string> <string name="confirm_delete_video_message">"동영상이 삭제됩니다."</string> <string name="camera_toss">"삭제"</string> <string name="camera_gallery">"갤러리"</string> <string name="camera_share">"공유"</string> <string name="camera_set">"사진 설정"</string> <string name="camera_play">"재생"</string> <string name="camera_attach">"첨부"</string> <string name="camera_cancel">"취소"</string> <string name="camera_crop">"자르기"</string> <string name="camera_tossing">"삭제 중..."</string> <string name="no_way_to_share_image">"공유할 수 없는 사진입니다."</string> <string name="no_way_to_share_video">"공유할 수 없는 동영상입니다."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"갤러리"</string> <string name="camera_pick_wallpaper">"사진"</string> <string name="camera_setas_wallpaper">"배경화면"</string> <string name="pref_gallery_category">"일반 설정"</string> <string name="pref_slideshow_category">"슬라이드쇼 설정"</string> <string name="pref_camera_general_settings_category">"일반 설정"</string> <string name="pref_gallery_size_title">"디스플레이 크기"</string> <string name="pref_gallery_size_summary">"사진 및 동영상 표시 크기 선택"</string> <string name="pref_gallery_size_dialogtitle">"사진 크기"</string> <string-array name="pref_gallery_size_choices"> <item>"크게"</item> <item>"작게"</item> </string-array> <string name="pref_gallery_sort_title">"정렬 순서"</string> <string name="pref_gallery_sort_summary">"사진 및 동영상 정렬 순서 선택"</string> <string name="pref_gallery_sort_dialogtitle">"사진 정렬"</string> <string-array name="pref_gallery_sort_choices"> <item>"가장 최근 사진 먼저"</item> <item>"가장 최근 사진 마지막에"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"슬라이드쇼 간격"</string> <string name="pref_gallery_slideshow_interval_summary">"쇼에서 각 슬라이드를 표시할 시간 선택"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"슬라이드쇼 간격"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2초"</item> <item>"3초"</item> <item>"4초"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"슬라이드쇼 화면전환"</string> <string name="pref_gallery_slideshow_transition_summary">"슬라이드 간에 이동할 때 사용할 효과 선택"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"슬라이드쇼 화면전환"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"페이드 인/아웃"</item> <item>"왼쪽에서 오른쪽으로/오른쪽에서 왼쪽으로"</item> <item>"위에서 아래로/아래에서 위로"</item> <item>"무작위 선택"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"슬라이드쇼 반복"</string> <string name="pref_gallery_slideshow_repeat_summary">"슬라이드쇼를 한 번 이상 재생"</string> <string name="pref_gallery_slideshow_shuffle_title">"슬라이드 섞기"</string> <string name="pref_gallery_slideshow_shuffle_summary">"사진을 무작위 순서로 표시"</string> <string name="pref_camera_recordlocation_title">"사진에 위치 저장"</string> <string name="pref_camera_recordlocation_summary">"사진 데이터에 위치 기록"</string> <string name="pref_camera_videoquality_category">"동영상 화질"</string> <string name="pref_camera_videoquality_title">"동영상 화질 선택"</string> <string name="pref_camera_videoquality_entry_0">"낮음(MMS 메시지용)"</string> <string name="pref_camera_videoquality_entry_1">"높음(SD 카드용)"</string> <string name="pref_camera_videoquality_dialogtitle">"동영상 화질"</string> <string name="camerasettings">"설정"</string> <string name="image_gallery_NoImageView_text">"미디어 파일이 없습니다."</string> <string name="pref_gallery_confirm_delete_title">"삭제 확인"</string> <string name="pref_gallery_confirm_delete_summary">"사진 및 동영상 삭제 전 확인 표시"</string> <string name="details_panel_title">"상세정보"</string> <string name="details_file_size">"파일 크기:"</string> <string name="details_image_resolution">"해상도:"</string> <string name="details_duration">"재생 시간:"</string> <string name="details_date_taken">"찍은 날짜:"</string> <string name="details_frame_rate">"프레임 속도:"</string> <string name="details_bit_rate">"비트 전송률:"</string> <string name="details_codec">"코덱:"</string> <string name="details_format">"형식:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$dfps"</string> <string name="details_kbps">"%1$dKbps"</string> <string name="details_mbps">"%1$gMbps"</string> <string name="details_ok">"확인"</string> <string name="context_menu_header">"사진 옵션"</string> <string name="video_context_menu_header">"동영상 옵션"</string> <string name="multiface_crop_help">"시작하려면 얼굴을 탭하세요."</string> <string name="photos_gallery_title">"갤러리"</string> <string name="pick_photos_gallery_title">"사진 선택"</string> <string name="videos_gallery_title">"갤러리"</string> <string name="pick_videos_gallery_title">"동영상 선택"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g>개 남음"</string> <string name="sendImage">"사진 공유 응용프로그램"</string> <string name="setImage">"사진 설정"</string> <string name="sendVideo">"동영상 공유 응용프로그램"</string> <string name="movieviewlabel">"영화"</string> <string name="loading_video">"동영상 로드 중..."</string> <string name="spaceIsLow_title">"공간부족"</string> <string name="spaceIsLow_content">"SD 카드의 공간이 부족합니다. 화질 설정을 변경하거나 갤러리에서 항목을 삭제하세요."</string> <string name="resume_playing_title">"동영상 다시 시작"</string> <string name="resume_playing_message">"%s에서 재생을 다시 시작하시겠습니까?"</string> <string name="resume_playing_resume">"재생 다시 시작"</string> <string name="resume_playing_restart">"시작"</string> <string name="gadget_title">"사진 프레임"</string> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="file_info_title">"파일 정보:"</string> + <string name="video_exceed_mms_limit">"녹화한 동영상이 너무 커서 MMS를 통해 전송할 수 없습니다. 클립의 길이를 더 짧게 녹화하세요."</string> + <string name="too_large_to_attach">"파일이 너무 커서 첨부할 수 없습니다."</string> </resources> diff --git a/res/values-nb/strings.xml b/res/values-nb/strings.xml index f15a058..b391b90 100644 --- a/res/values-nb/strings.xml +++ b/res/values-nb/strings.xml @@ -1,158 +1,156 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Alle bilder"</string> <string name="all_videos">"Alle videoer"</string> <string name="camera_label">"Kamera"</string> <string name="gallery_picker_label">"Galleri"</string> <string name="gallery_camera_bucket_name">"Bilder fra kamera"</string> <string name="gallery_camera_videos_bucket_name">"Videoer fra kamera"</string> <string name="switch_to_video_lable">"Bytt til video"</string> <string name="switch_to_camera_lable">"Bytt til kamera"</string> <string name="crop_label">"Beskjær bilde"</string> <string name="view_label">"Se på bilde"</string> <string name="preferences_label">"Kamerainnstillinger"</string> <string name="wait">"Vent litt…"</string> <string name="no_storage">"Sett inn et minnekort før du bruker kameraet."</string> <string name="not_enough_space">"Minnekortet er fullt."</string> <string name="preparing_sd">"Forbereder minnekort…"</string> <string name="wallpaper">"Setter bakgrunnsbilde, vent litt…"</string> <string name="savingImage">"Lagrer bilde…"</string> <string name="runningFaceDetection">"Vent litt…"</string> <string name="flip_orientation">"Roter skjerm"</string> <string name="settings">"Innstillinger"</string> <string name="view">"Vis"</string> <string name="details">"Detaljer"</string> <string name="rotate">"Roter"</string> <string name="rotate_left">"Roter mot venstre"</string> <string name="rotate_right">"Roter mot høyre"</string> <string name="slide_show">"Lysbildevisning"</string> <string name="capture_picture">"Ta bilde"</string> <string name="capture_video">"Ta opp video"</string> <string name="crop_save_text">"Lagre"</string> <string name="crop_discard_text">"Forkast"</string> <string name="confirm_delete_title">"Slett"</string> <string name="confirm_delete_message">"Bildet vil bli slettet."</string> <string name="confirm_delete_video_message">"Videoen vil bli slettet."</string> <string name="camera_toss">"Slett"</string> <string name="camera_gallery">"Galleri"</string> <string name="camera_share">"Del"</string> <string name="camera_set">"Bruk som"</string> <string name="camera_play">"Spill"</string> <string name="camera_attach">"Legg ved"</string> <string name="camera_cancel">"Avbryt"</string> <string name="camera_crop">"Beskjær"</string> <string name="camera_tossing">"Sletter…"</string> <string name="no_way_to_share_image">"Bildet kan ikke deles."</string> <string name="no_way_to_share_video">"Videoen kan ikke deles."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galleri"</string> <string name="camera_pick_wallpaper">"Bilder"</string> <string name="camera_setas_wallpaper">"Bakgrunnsbilder"</string> <string name="pref_gallery_category">"Generelle innstillinger"</string> <string name="pref_slideshow_category">"Innstillinger for lysbildevisning"</string> <string name="pref_camera_general_settings_category">"Generelle innstillinger"</string> <string name="pref_gallery_size_title">"Bildestørrelse"</string> <string name="pref_gallery_size_summary">"Velg hvor stort bilder skal vises"</string> <string name="pref_gallery_size_dialogtitle">"Bildestørrelse"</string> <string-array name="pref_gallery_size_choices"> <item>"Stor"</item> <item>"Liten"</item> </string-array> <string name="pref_gallery_sort_title">"Bildesortering"</string> <string name="pref_gallery_sort_summary">"Velg i hvilken rekkefølge bildene skal sorteres"</string> <string name="pref_gallery_sort_dialogtitle">"Bildesortering"</string> <string-array name="pref_gallery_sort_choices"> <item>"Nyeste først"</item> <item>"Nyeste sist"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Pause i lysbildevisning"</string> <string name="pref_gallery_slideshow_interval_summary">"Velg hvor lenge hvert lysbilde skal vises"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Pause i lysbildevisning"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 sekunder"</item> <item>"3 sekunder"</item> <item>"4 sekunder"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Lysbildeovergang"</string> <string name="pref_gallery_slideshow_transition_summary">"Velg effekten som skal brukes mellom lysbilder"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Lysbildevergang"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Ton inn og ut"</item> <item>"Skli venstre - høyre"</item> <item>"Skli opp - ned"</item> <item>"Tilfeldig"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Gjenta lysbildeserie"</string> <string name="pref_gallery_slideshow_repeat_summary">"Vis lydbildeserie mer enn en gang"</string> <string name="pref_gallery_slideshow_shuffle_title">"Stokk lysbilder"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Vis bilder i tilfeldig rekkefølge"</string> <string name="pref_camera_recordlocation_title">"Lagre sted i bilder"</string> <string name="pref_camera_recordlocation_summary">"Lagre sted i bildedata"</string> <string name="pref_camera_videoquality_category">"Videokvalitet"</string> <string name="pref_camera_videoquality_title">"Videokvalitet"</string> <string name="pref_camera_videoquality_entry_0">"Lav (for MMS-meldinger)"</string> <string name="pref_camera_videoquality_entry_1">"Høy (for minnekort)"</string> <string name="pref_camera_videoquality_dialogtitle">"Videokvalitet"</string> <string name="camerasettings">"Innstillinger"</string> <string name="image_gallery_NoImageView_text">"Fant ingen bilder."</string> <string name="pref_gallery_confirm_delete_title">"Bekreft sletting"</string> <string name="pref_gallery_confirm_delete_summary">"Vis bekreftelse før bilder slettes"</string> <string name="details_panel_title">"Detaljer"</string> <string name="details_file_size">"Filstørrelse:"</string> <string name="details_image_resolution">"Oppløsning:"</string> <string name="details_duration">"Varighet:"</string> <string name="details_date_taken">"Dato tatt:"</string> <string name="details_frame_rate">"Bildefrekvens:"</string> <string name="details_bit_rate">"Bitrate:"</string> <string name="details_codec">"Kodek:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Bildeinnstillinger"</string> <string name="video_context_menu_header">"Videoinnstillinger"</string> <string name="multiface_crop_help">"Trykk på et ansikt for å begynne."</string> <string name="photos_gallery_title">"Galleri"</string> <string name="pick_photos_gallery_title">"Velg bilde"</string> <string name="videos_gallery_title">"Galleri"</string> <string name="pick_videos_gallery_title">"Velg video"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> gjenstår"</string> <string name="sendImage">"Del bilde via"</string> <string name="setImage">"Bruk bilde som"</string> <string name="sendVideo">"Del video via"</string> <string name="movieviewlabel">"Filmer"</string> <string name="loading_video">"Laster video…"</string> <string name="spaceIsLow_title">"Lite plass"</string> <string name="spaceIsLow_content">"Minnekortet begynner å gå tom for plass. Endre kvalitetsinnstillingen eller slett bilder fra galleriet."</string> <string name="resume_playing_title">"Fortsett avspilling"</string> <string name="resume_playing_message">"Fortsett avspilling fra %s?"</string> <string name="resume_playing_resume">"Fortsett avspilling"</string> <string name="resume_playing_restart">"Begynn på nytt"</string> <string name="gadget_title">"Bilderamme"</string> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> + <string name="file_info_title">"Filinformasjon:"</string> + <string name="video_exceed_mms_limit">"Videoen er for stor til å sendes over MMS. Prøv å ta opp en kortere video."</string> <!-- no translation found for too_large_to_attach (8944461117941172986) --> <skip /> </resources> diff --git a/res/values-nl/strings.xml b/res/values-nl/strings.xml index 5cc88eb..321ce4d 100644 --- a/res/values-nl/strings.xml +++ b/res/values-nl/strings.xml @@ -1,158 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Alle foto\'s"</string> <string name="all_videos">"Alle video\'s"</string> <string name="camera_label">"Camera"</string> <string name="gallery_picker_label">"Galerij"</string> <string name="gallery_camera_bucket_name">"Camerafoto\'s"</string> <string name="gallery_camera_videos_bucket_name">"Cameravideo\'s"</string> <string name="switch_to_video_lable">"Overschakelen naar video"</string> <string name="switch_to_camera_lable">"Overschakelen naar camera"</string> <string name="crop_label">"Foto bijsnijden"</string> <string name="view_label">"Foto weergeven"</string> <string name="preferences_label">"Camera-instellingen"</string> <string name="wait">"Een ogenblik geduld..."</string> <string name="no_storage">"Plaats een SD-kaart voordat u de camera gebruikt."</string> <string name="not_enough_space">"De SD-kaart is vol."</string> <string name="preparing_sd">"SD-kaart voorbereiden…"</string> <string name="wallpaper">"Achtergrond wordt ingesteld. Een ogenblik geduld..."</string> <string name="savingImage">"Foto opslaan..."</string> <string name="runningFaceDetection">"Een ogenblik geduld..."</string> <string name="flip_orientation">"Stand draaien"</string> <string name="settings">"Instellingen"</string> <string name="view">"Weergeven"</string> <string name="details">"Details"</string> <string name="rotate">"Draaien"</string> <string name="rotate_left">"Linksom draaien"</string> <string name="rotate_right">"Rechtsom draaien"</string> <string name="slide_show">"Diavoorstelling"</string> <string name="capture_picture">"Foto nemen"</string> <string name="capture_video">"Video opnemen"</string> <string name="crop_save_text">"Opslaan"</string> <string name="crop_discard_text">"Ongedaan maken"</string> <string name="confirm_delete_title">"Verwijderen"</string> <string name="confirm_delete_message">"De foto wordt verwijderd."</string> <string name="confirm_delete_video_message">"De video wordt verwijderd"</string> <string name="camera_toss">"Verwijderen"</string> <string name="camera_gallery">"Galerij"</string> <string name="camera_share">"Delen"</string> <string name="camera_set">"Instellen als"</string> <string name="camera_play">"Afspelen"</string> <string name="camera_attach">"Bijvoegen"</string> <string name="camera_cancel">"Annuleren"</string> <string name="camera_crop">"Bijsnijden"</string> <string name="camera_tossing">"Verwijderen..."</string> <string name="no_way_to_share_image">"Deze foto kan niet worden gedeeld."</string> <string name="no_way_to_share_video">"Deze video kan niet worden gedeeld."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galerij"</string> <string name="camera_pick_wallpaper">"Foto\'s"</string> <string name="camera_setas_wallpaper">"Achtergrond"</string> <string name="pref_gallery_category">"Algemene instellingen"</string> <string name="pref_slideshow_category">"Instellingen van diavoorstelling"</string> <string name="pref_camera_general_settings_category">"Algemene instellingen"</string> <string name="pref_gallery_size_title">"Weergavegrootte"</string> <string name="pref_gallery_size_summary">"De weergavegrootte van foto\'s en video\'s selecteren"</string> <string name="pref_gallery_size_dialogtitle">"Grootte van foto"</string> <string-array name="pref_gallery_size_choices"> <item>"Groot"</item> <item>"Klein"</item> </string-array> <string name="pref_gallery_sort_title">"Sorteervolgorde"</string> <string name="pref_gallery_sort_summary">"De sorteervolgorde van foto\'s en video\'s selecteren"</string> <string name="pref_gallery_sort_dialogtitle">"Foto\'s sorteren"</string> <string-array name="pref_gallery_sort_choices"> <item>"Nieuwste eerst"</item> <item>"Nieuwste eerst"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Interval in diavoorstelling"</string> <string name="pref_gallery_slideshow_interval_summary">"Selecteren hoe lang elke dia wordt weergegeven in de voorstelling"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Interval in diavoorstelling"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 seconden"</item> <item>"3 seconden"</item> <item>"4 seconden"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Overgangen in diavoorstellingen"</string> <string name="pref_gallery_slideshow_transition_summary">"Het effect selecteren dat wordt gebruikt om naar de volgende dia te gaan"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Overgangen in diavoorstellingen"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Infaden/uitfaden"</item> <item>"Dia vanaf linkerkant/rechterkant"</item> <item>"Dia vanaf bovenkant/onderkant"</item> <item>"Willekeurige selectie"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Diavoorstelling herhalen"</string> <string name="pref_gallery_slideshow_repeat_summary">"Diavoorstelling meerdere keren afspelen"</string> <string name="pref_gallery_slideshow_shuffle_title">"Dia\'s in willekeurige volgorde weergeven"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Foto\'s in willekeurige volgorde weergeven"</string> <string name="pref_camera_recordlocation_title">"Locatie opslaan in foto\'s"</string> <string name="pref_camera_recordlocation_summary">"Locatie vastleggen in de gegevens van de foto"</string> <string name="pref_camera_videoquality_category">"Videokwaliteit"</string> <string name="pref_camera_videoquality_title">"Videokwaliteit selecteren"</string> <string name="pref_camera_videoquality_entry_0">"Laag (voor MMS-berichten)"</string> <string name="pref_camera_videoquality_entry_1">"Hoog (voor SD-kaart)"</string> <string name="pref_camera_videoquality_dialogtitle">"Videokwaliteit"</string> <string name="camerasettings">"Instellingen"</string> <string name="image_gallery_NoImageView_text">"Geen medium gevonden."</string> <string name="pref_gallery_confirm_delete_title">"Verwijderen bevestigen"</string> <string name="pref_gallery_confirm_delete_summary">"Bevestiging weergeven voordat een foto of video wordt verwijderd"</string> <string name="details_panel_title">"Details"</string> <string name="details_file_size">"Bestandsgrootte:"</string> <string name="details_image_resolution">"Resolutie:"</string> <string name="details_duration">"Duur:"</string> <string name="details_date_taken">"Gemaakt op:"</string> <string name="details_frame_rate">"Framesnelheid:"</string> <string name="details_bit_rate">"Bitsnelheid:"</string> <string name="details_codec">"Codec:"</string> <string name="details_format">"Indeling:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opties voor foto\'s"</string> <string name="video_context_menu_header">"Video-opties"</string> <string name="multiface_crop_help">"Tik op een gezicht om te beginnen."</string> <string name="photos_gallery_title">"Galerij"</string> <string name="pick_photos_gallery_title">"Foto selecteren"</string> <string name="videos_gallery_title">"Galerij"</string> <string name="pick_videos_gallery_title">"Video selecteren"</string> <string name="loading_progress_format_string">"<xliff:g id="COUNTER">%d</xliff:g> resterend"</string> <string name="sendImage">"Foto delen via"</string> <string name="setImage">"Foto instellen als"</string> <string name="sendVideo">"Video delen via"</string> <string name="movieviewlabel">"Films"</string> <string name="loading_video">"Video laden..."</string> <string name="spaceIsLow_title">"Er is weinig ruimte"</string> <string name="spaceIsLow_content">"Er is weinig ruimte beschikbaar op uw SD-kaart. U kunt de kwaliteitsinstelling wijzigen of items uit de galerij verwijderen."</string> <string name="resume_playing_title">"Video hervatten"</string> <string name="resume_playing_message">"Afspelen hervatten vanaf %s ?"</string> <string name="resume_playing_resume">"Afspelen hervatten"</string> <string name="resume_playing_restart">"Opnieuw starten"</string> <string name="gadget_title">"Fotolijstje"</string> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="file_info_title">"Bestandsinformatie:"</string> + <string name="video_exceed_mms_limit">"De video die u heeft opgenomen, is te lang om via MMS te verzenden. Neem een kortere video op."</string> + <string name="too_large_to_attach">"Bestand is te groot om bij te voegen."</string> </resources> diff --git a/res/values-pl/strings.xml b/res/values-pl/strings.xml index ec05944..fa62ac3 100644 --- a/res/values-pl/strings.xml +++ b/res/values-pl/strings.xml @@ -1,158 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Wszystkie zdjęcia"</string> <string name="all_videos">"Wszystkie filmy"</string> <string name="camera_label">"Aparat"</string> <string name="gallery_picker_label">"Galeria"</string> <string name="gallery_camera_bucket_name">"Zdjęcia z aparatu"</string> <string name="gallery_camera_videos_bucket_name">"Filmy z aparatu"</string> <string name="switch_to_video_lable">"Przełącz na wideo"</string> <string name="switch_to_camera_lable">"Przełącz na aparat"</string> <string name="crop_label">"Przytnij zdjęcie"</string> <string name="view_label">"Wyświetl zdjęcie"</string> <string name="preferences_label">"Ustawienia aparatu"</string> <string name="wait">"Poczekaj…"</string> <string name="no_storage">"Zanim zaczniesz korzystać z aparatu fotograficznego, włóż kartę SD."</string> <string name="not_enough_space">"Karta SD jest pełna."</string> <string name="preparing_sd">"Przygotowywanie karty SD..."</string> <string name="wallpaper">"Ustawianie tapety, poczekaj…"</string> <string name="savingImage">"Trwa zapisywanie zdjęcia…"</string> <string name="runningFaceDetection">"Poczekaj…"</string> <string name="flip_orientation">"Zmień orientację"</string> <string name="settings">"Ustawienia"</string> <string name="view">"Wyświetl"</string> <string name="details">"Szczegóły"</string> <string name="rotate">"Obróć"</string> <string name="rotate_left">"Obróć w lewo"</string> <string name="rotate_right">"Obróć w prawo"</string> <string name="slide_show">"Pokaz slajdów"</string> <string name="capture_picture">"Zrób zdjęcie"</string> <string name="capture_video">"Nagraj film wideo"</string> <string name="crop_save_text">"Zapisz"</string> <string name="crop_discard_text">"Odrzuć"</string> <string name="confirm_delete_title">"Usuń"</string> <string name="confirm_delete_message">"Zdjęcie zostanie usunięte."</string> <string name="confirm_delete_video_message">"Film wideo zostanie usunięty."</string> <string name="camera_toss">"Usuń"</string> <string name="camera_gallery">"Galeria"</string> <string name="camera_share">"Prześlij"</string> <string name="camera_set">"Ustaw jako"</string> <string name="camera_play">"Odtwórz"</string> <string name="camera_attach">"Załącz"</string> <string name="camera_cancel">"Anuluj"</string> <string name="camera_crop">"Przytnij"</string> <string name="camera_tossing">"Trwa usuwanie…"</string> <string name="no_way_to_share_image">"Nie można przesłać tego zdjęcia."</string> <string name="no_way_to_share_video">"Nie można przesłać tego filmu."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Galeria"</string> <string name="camera_pick_wallpaper">"Zdjęcia"</string> <string name="camera_setas_wallpaper">"Tapeta"</string> <string name="pref_gallery_category">"Ustawienia ogólne"</string> <string name="pref_slideshow_category">"Ustawienia pokazu slajdów"</string> <string name="pref_camera_general_settings_category">"Ustawienia ogólne"</string> <string name="pref_gallery_size_title">"Rozmiar zdjęć i filmów"</string> <string name="pref_gallery_size_summary">"Ustaw wyświetlany rozmiar zdjęć i filmów"</string> <string name="pref_gallery_size_dialogtitle">"Rozmiar"</string> <string-array name="pref_gallery_size_choices"> <item>"Duży"</item> <item>"Mały"</item> </string-array> <string name="pref_gallery_sort_title">"Kolejność sortowania"</string> <string name="pref_gallery_sort_summary">"Wybierz kolejność sortowania zdjęć i filmów"</string> <string name="pref_gallery_sort_dialogtitle">"Sortowanie zdjęć"</string> <string-array name="pref_gallery_sort_choices"> <item>"Od najnowszego"</item> <item>"Od najstarszego"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Pokaz slajdów – interwał"</string> <string name="pref_gallery_slideshow_interval_summary">"Wybierz, jak długo mają być wyświetlane poszczególne zdjęcia w pokazie slajdów"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Pokaz slajdów – interwał"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 sekundy"</item> <item>"3 sekundy"</item> <item>"4 sekundy"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Pokaz slajdów – efekty"</string> <string name="pref_gallery_slideshow_transition_summary">"Wybierz efekt używany przy przejściu z jednego zdjęcia do kolejnego"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Pokaz slajdów – efekty"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Pojawianie i znikanie"</item> <item>"Przesuwanie z lewa w prawo"</item> <item>"Przesuwanie góra-dół"</item> <item>"Wybór losowy"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Powtórz pokaz slajdów"</string> <string name="pref_gallery_slideshow_repeat_summary">"Wyświetlaj pokaz slajdów więcej niż raz"</string> <string name="pref_gallery_slideshow_shuffle_title">"Losowa kolejność"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Wyświetlaj zdjęcia w kolejności losowej"</string> <string name="pref_camera_recordlocation_title">"Zapisuj lokalizację w zdjęciach"</string> <string name="pref_camera_recordlocation_summary">"Zapisz lokalizację w danych zdjęcia"</string> <string name="pref_camera_videoquality_category">"Jakość wideo"</string> <string name="pref_camera_videoquality_title">"Wybierz jakość wideo"</string> <string name="pref_camera_videoquality_entry_0">"Niska (dla wiadomości MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Wysoka (dla karty SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Jakość wideo"</string> <string name="camerasettings">"Ustawienia"</string> <string name="image_gallery_NoImageView_text">"Brak plików."</string> <string name="pref_gallery_confirm_delete_title">"Potwierdzanie usuwania"</string> <string name="pref_gallery_confirm_delete_summary">"Wyświetl potwierdzenie przed usunięciem zdjęcia lub filmu"</string> <string name="details_panel_title">"Szczegóły"</string> <string name="details_file_size">"Rozmiar pliku:"</string> <string name="details_image_resolution">"Rozdzielczość:"</string> <string name="details_duration">"Czas trwania:"</string> <string name="details_date_taken">"Data zrobienia zdjęcia:"</string> <string name="details_frame_rate">"Szybkość klatek:"</string> <string name="details_bit_rate">"Szybkość transmisji:"</string> <string name="details_codec">"Kodek:"</string> <string name="details_format">"Format:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d ramek/s"</string> <string name="details_kbps">"%1$d Kb/s"</string> <string name="details_mbps">"%1$g Mb/s"</string> <string name="details_ok">"OK"</string> <string name="context_menu_header">"Opcje zdjęć"</string> <string name="video_context_menu_header">"Opcje wideo"</string> <string name="multiface_crop_help">"Dotknij twarzy, aby rozpocząć"</string> <string name="photos_gallery_title">"Galeria"</string> <string name="pick_photos_gallery_title">"Wybierz zdjęcie"</string> <string name="videos_gallery_title">"Galeria"</string> <string name="pick_videos_gallery_title">"Wybierz film wideo"</string> <string name="loading_progress_format_string">"Pozostało <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Prześlij zdjęcie następującą drogą:"</string> <string name="setImage">"Ustaw zdjęcie jako"</string> <string name="sendVideo">"Prześlij film następującą drogą:"</string> <string name="movieviewlabel">"Filmy"</string> <string name="loading_video">"Ładowanie filmu..."</string> <string name="spaceIsLow_title">"Miejsca jest mało"</string> <string name="spaceIsLow_content">"Na karcie SD brakuje miejsca. Zmień ustawienie jakości lub usuń elementy z Galerii."</string> <string name="resume_playing_title">"Wznów film"</string> <string name="resume_playing_message">"Wznowić odtwarzanie od %s?"</string> <string name="resume_playing_resume">"Wznów odtwarzanie"</string> <string name="resume_playing_restart">"Rozpocznij"</string> <string name="gadget_title">"Ramka zdjęcia"</string> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="file_info_title">"Informacje o pliku:"</string> + <string name="video_exceed_mms_limit">"Nagrany film wideo jest zbyt duży, aby wysłać go w wiadomości MMS. Spróbuj nagrać krótszy film wideo."</string> + <string name="too_large_to_attach">"Plik jest zbyt duży do załączenia."</string> </resources> diff --git a/res/values-ru/strings.xml b/res/values-ru/strings.xml index 92d2f2e..bb0c594 100644 --- a/res/values-ru/strings.xml +++ b/res/values-ru/strings.xml @@ -1,158 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"Все изображения"</string> <string name="all_videos">"Все видео"</string> <string name="camera_label">"Камера"</string> <string name="gallery_picker_label">"Галерея"</string> <string name="gallery_camera_bucket_name">"Фотографии с камеры"</string> <string name="gallery_camera_videos_bucket_name">"Видео с камеры"</string> <string name="switch_to_video_lable">"Перейти в режим видео"</string> <string name="switch_to_camera_lable">"Перейти в режим камеры"</string> <string name="crop_label">"Обрезать изображение"</string> <string name="view_label">"Просмотреть изображение"</string> <string name="preferences_label">"Настройки камеры"</string> <string name="wait">"Подождите…"</string> <string name="no_storage">"Перед использованием камеры вставьте карту SD."</string> <string name="not_enough_space">"Карта SD заполнена."</string> <string name="preparing_sd">"Подготовка карты SD..."</string> <string name="wallpaper">"Установка фонового рисунка, подождите…"</string> <string name="savingImage">"Идет сохранение изображения…"</string> <string name="runningFaceDetection">"Подождите…"</string> <string name="flip_orientation">"Изменить ориентацию"</string> <string name="settings">"Настройки"</string> <string name="view">"Просмотреть"</string> <string name="details">"Сведения"</string> <string name="rotate">"Повернуть"</string> <string name="rotate_left">"Повернуть налево"</string> <string name="rotate_right">"Повернуть направо"</string> <string name="slide_show">"Слайд-шоу"</string> <string name="capture_picture">"Сделать фотографию"</string> <string name="capture_video">"Снять видео"</string> <string name="crop_save_text">"Сохранить"</string> <string name="crop_discard_text">"Отменить"</string> <string name="confirm_delete_title">"Удаление"</string> <string name="confirm_delete_message">"Изображение будет удалено."</string> <string name="confirm_delete_video_message">"Видео будет удалено."</string> <string name="camera_toss">"Удаление"</string> <string name="camera_gallery">"Галерея"</string> <string name="camera_share">"Отправить"</string> <string name="camera_set">"Установить как"</string> <string name="camera_play">"Воспроизвести"</string> <string name="camera_attach">"Вложить"</string> <string name="camera_cancel">"Отмена"</string> <string name="camera_crop">"Обрезать"</string> <string name="camera_tossing">"Идет удаление…"</string> <string name="no_way_to_share_image">"Отправить это изображение нельзя."</string> <string name="no_way_to_share_video">"Отправить это видео нельзя."</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"Галерея"</string> <string name="camera_pick_wallpaper">"Изображения"</string> <string name="camera_setas_wallpaper">"Фоновый рисунок"</string> <string name="pref_gallery_category">"Общие настройки"</string> <string name="pref_slideshow_category">"Настройки слайд-шоу"</string> <string name="pref_camera_general_settings_category">"Общие настройки"</string> <string name="pref_gallery_size_title">"Отображаемый размер"</string> <string name="pref_gallery_size_summary">"Выбор отображаемого размера изображений и видео"</string> <string name="pref_gallery_size_dialogtitle">"Размер изображения"</string> <string-array name="pref_gallery_size_choices"> <item>"Крупный"</item> <item>"Мелкий"</item> </string-array> <string name="pref_gallery_sort_title">"Порядок сортировки"</string> <string name="pref_gallery_sort_summary">"Выберите порядок сортировки изображений и видео"</string> <string name="pref_gallery_sort_dialogtitle">"Сортировка изображений"</string> <string-array name="pref_gallery_sort_choices"> <item>"Начиная с новых"</item> <item>"Заканчивая новыми"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"Интервал слайд-шоу"</string> <string name="pref_gallery_slideshow_interval_summary">"Выберите время отображения каждого слайда"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"Интервал слайд-шоу"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 секунды"</item> <item>"3 секунды"</item> <item>"4 секунды"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"Переходы слайд-шоу"</string> <string name="pref_gallery_slideshow_transition_summary">"Выберите эффект для перехода от одного слайда к другому"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"Переходы слайд-шоу"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"Затемнение"</item> <item>"Слайды слева направо"</item> <item>"Слайды сверху вниз"</item> <item>"Случайный выбор"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"Повторить слайд-шоу"</string> <string name="pref_gallery_slideshow_repeat_summary">"Воспроизвести слайд-шоу несколько раз"</string> <string name="pref_gallery_slideshow_shuffle_title">"Перемешать слайды"</string> <string name="pref_gallery_slideshow_shuffle_summary">"Показывать изображения в случайном порядке"</string> <string name="pref_camera_recordlocation_title">"Сохранять адрес в изображениях"</string> <string name="pref_camera_recordlocation_summary">"Записывать адрес в данные изображения"</string> <string name="pref_camera_videoquality_category">"Качество видео"</string> <string name="pref_camera_videoquality_title">"Выбор качества видео"</string> <string name="pref_camera_videoquality_entry_0">"Низкое (для MMS)"</string> <string name="pref_camera_videoquality_entry_1">"Высокое (для карты SD)"</string> <string name="pref_camera_videoquality_dialogtitle">"Качество видео"</string> <string name="camerasettings">"Настройки"</string> <string name="image_gallery_NoImageView_text">"Нет мультимедийных материалов."</string> <string name="pref_gallery_confirm_delete_title">"Подтверждение удаления"</string> <string name="pref_gallery_confirm_delete_summary">"Запрашивать подтверждения перед удалением изображения или видео"</string> <string name="details_panel_title">"Сведения"</string> <string name="details_file_size">"Размер файла:"</string> <string name="details_image_resolution">"Разрешение:"</string> <string name="details_duration">"Продолжительность:"</string> <string name="details_date_taken">"Дата съемки:"</string> <string name="details_frame_rate">"Частота кадров:"</string> <string name="details_bit_rate">"Битрейт:"</string> <string name="details_codec">"Кодек:"</string> <string name="details_format">"Формат:"</string> <string name="details_dimension_x">"%1$d на %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d кадров/с"</string> <string name="details_kbps">"%1$d кбит/с"</string> <string name="details_mbps">"%1$g мбит/с"</string> <string name="details_ok">"ОК"</string> <string name="context_menu_header">"Параметры изображения"</string> <string name="video_context_menu_header">"Параметры видео"</string> <string name="multiface_crop_help">"Чтобы начать, выберите лицо."</string> <string name="photos_gallery_title">"Галерея"</string> <string name="pick_photos_gallery_title">"Выбор изображения"</string> <string name="videos_gallery_title">"Галерея"</string> <string name="pick_videos_gallery_title">"Выбрать видео"</string> <string name="loading_progress_format_string">"Осталось: <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"Отправить изображение при помощи"</string> <string name="setImage">"Установить изображение как"</string> <string name="sendVideo">"Отправить видео при помощи"</string> <string name="movieviewlabel">"Фильмы"</string> <string name="loading_video">"Идет загрузка видео…"</string> <string name="spaceIsLow_title">"Осталось мало места"</string> <string name="spaceIsLow_content">"Место на карте SD заканчивается. Измените настройки качества или удалите элементы из галереи."</string> <string name="resume_playing_title">"Продолжение просмотра видео"</string> <string name="resume_playing_message">"Продолжить воспроизведение с %s ?"</string> <string name="resume_playing_resume">"Продолжить воспроизведение"</string> <string name="resume_playing_restart">"Начать с начала"</string> <string name="gadget_title">"Рамка фотографии"</string> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="file_info_title">"Сведения о файле:"</string> + <string name="video_exceed_mms_limit">"Записанное видео имеет слишком большой размер для отправки в MMS. Запишите более короткий ролик."</string> + <string name="too_large_to_attach">"Файл имеет слишком большой размер и не может быть вложен."</string> </resources> diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml index e0161d9..4ed6bd4 100644 --- a/res/values-zh-rCN/strings.xml +++ b/res/values-zh-rCN/strings.xml @@ -1,158 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"所有图片"</string> <string name="all_videos">"所有视频"</string> <string name="camera_label">"相机"</string> <string name="gallery_picker_label">"图片库"</string> <string name="gallery_camera_bucket_name">"相机照片"</string> <string name="gallery_camera_videos_bucket_name">"相机视频"</string> <string name="switch_to_video_lable">"切换到视频"</string> <string name="switch_to_camera_lable">"切换到相机"</string> <string name="crop_label">"裁切图片"</string> <string name="view_label">"查看图片"</string> <string name="preferences_label">"相机设置"</string> <string name="wait">"请稍候..."</string> <string name="no_storage">"请在使用相机之前插入 SD 卡。"</string> <string name="not_enough_space">"您的 SD 卡已满。"</string> <string name="preparing_sd">"正在准备 SD 卡..."</string> <string name="wallpaper">"正在设置壁纸,请稍候..."</string> <string name="savingImage">"正在保存图片..."</string> <string name="runningFaceDetection">"请稍候..."</string> <string name="flip_orientation">"反转方向"</string> <string name="settings">"设置"</string> <string name="view">"查看"</string> <string name="details">"详细信息"</string> <string name="rotate">"旋转"</string> <string name="rotate_left">"向左旋转"</string> <string name="rotate_right">"向右旋转"</string> <string name="slide_show">"幻灯片演示"</string> <string name="capture_picture">"拍摄照片"</string> <string name="capture_video">"拍摄视频"</string> <string name="crop_save_text">"保存"</string> <string name="crop_discard_text">"放弃"</string> <string name="confirm_delete_title">"删除"</string> <string name="confirm_delete_message">"会删除该图片。"</string> <string name="confirm_delete_video_message">"会删除该视频。"</string> <string name="camera_toss">"删除"</string> <string name="camera_gallery">"图片库"</string> <string name="camera_share">"共享"</string> <string name="camera_set">"设置为"</string> <string name="camera_play">"播放"</string> <string name="camera_attach">"附加"</string> <string name="camera_cancel">"取消"</string> <string name="camera_crop">"裁切"</string> <string name="camera_tossing">"正在删除..."</string> <string name="no_way_to_share_image">"无法共享此图片。"</string> <string name="no_way_to_share_video">"无法共享此视频。"</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"图片库"</string> <string name="camera_pick_wallpaper">"图片"</string> <string name="camera_setas_wallpaper">"壁纸"</string> <string name="pref_gallery_category">"常规设置"</string> <string name="pref_slideshow_category">"幻灯片演示设置"</string> <string name="pref_camera_general_settings_category">"常规设置"</string> <string name="pref_gallery_size_title">"显示大小"</string> <string name="pref_gallery_size_summary">"选择图片和视频的显示大小"</string> <string name="pref_gallery_size_dialogtitle">"图片大小"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"排序顺序"</string> <string name="pref_gallery_sort_summary">"选择图片和视频的排序顺序"</string> <string name="pref_gallery_sort_dialogtitle">"图片排序"</string> <string-array name="pref_gallery_sort_choices"> <item>"最新的在最前面"</item> <item>"最新的在最后面"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"幻灯片演示间隔"</string> <string name="pref_gallery_slideshow_interval_summary">"选择每张幻灯片在演示中显示的时间长度"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"幻灯片演示间隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 秒"</item> <item>"3 秒"</item> <item>"4 秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"幻灯片演示过渡"</string> <string name="pref_gallery_slideshow_transition_summary">"选择从一张幻灯片移动到下一张时使用的效果"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"幻灯片演示过渡"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"逐渐增强和逐渐减弱"</item> <item>"自左至右滑动"</item> <item>"自上至下滑动"</item> <item>"随机选择"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"重复幻灯片演示"</string> <string name="pref_gallery_slideshow_repeat_summary">"多次播放幻灯片演示"</string> <string name="pref_gallery_slideshow_shuffle_title">"随机演示幻灯片"</string> <string name="pref_gallery_slideshow_shuffle_summary">"以随机顺序显示图片"</string> <string name="pref_camera_recordlocation_title">"在图片中存储位置"</string> <string name="pref_camera_recordlocation_summary">"通过图片数据记录位置"</string> <string name="pref_camera_videoquality_category">"视频质量"</string> <string name="pref_camera_videoquality_title">"选择视频质量"</string> <string name="pref_camera_videoquality_entry_0">"低(对于彩信)"</string> <string name="pref_camera_videoquality_entry_1">"高(对于 SD 卡)"</string> <string name="pref_camera_videoquality_dialogtitle">"视频质量"</string> <string name="camerasettings">"设置"</string> <string name="image_gallery_NoImageView_text">"找不到媒体。"</string> <string name="pref_gallery_confirm_delete_title">"确认删除"</string> <string name="pref_gallery_confirm_delete_summary">"在删除图片或视频前显示确认"</string> <string name="details_panel_title">"详细信息"</string> <string name="details_file_size">"文件大小:"</string> <string name="details_image_resolution">"分辨率:"</string> <string name="details_duration">"持续时间:"</string> <string name="details_date_taken">"拍摄日期:"</string> <string name="details_frame_rate">"帧频:"</string> <string name="details_bit_rate">"比特率:"</string> <string name="details_codec">"编解码器:"</string> <string name="details_format">"格式:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"确定"</string> <string name="context_menu_header">"图片选项"</string> <string name="video_context_menu_header">"视频选项"</string> <string name="multiface_crop_help">"轻击一张脸开始裁切。"</string> <string name="photos_gallery_title">"图片库"</string> <string name="pick_photos_gallery_title">"选择图片"</string> <string name="videos_gallery_title">"图片库"</string> <string name="pick_videos_gallery_title">"选择视频"</string> <string name="loading_progress_format_string">"还剩 <xliff:g id="COUNTER">%d</xliff:g>"</string> <string name="sendImage">"共享图片的方式"</string> <string name="setImage">"将图片设置为"</string> <string name="sendVideo">"共享视频的方式"</string> <string name="movieviewlabel">"电影"</string> <string name="loading_video">"正在载入视频..."</string> <string name="spaceIsLow_title">"空间不足"</string> <string name="spaceIsLow_content">"您的 SD 卡已满。请更改质量设置或删除图片库中的内容。"</string> <string name="resume_playing_title">"重新播放视频"</string> <string name="resume_playing_message">"从 %s 开始重新播放?"</string> <string name="resume_playing_resume">"重新播放"</string> <string name="resume_playing_restart">"重新开始"</string> <string name="gadget_title">"相框"</string> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="file_info_title">"文件信息:"</string> + <string name="video_exceed_mms_limit">"您录制的视频太大,无法用彩信发送。请尝试录制短一点的剪辑。"</string> + <string name="too_large_to_attach">"文件太大,无法附加。"</string> </resources> diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml index dceb5eb..93965fd 100644 --- a/res/values-zh-rTW/strings.xml +++ b/res/values-zh-rTW/strings.xml @@ -1,158 +1,155 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2009 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="all_images">"所有相片"</string> <string name="all_videos">"所有影片"</string> <string name="camera_label">"相機"</string> <string name="gallery_picker_label">"圖庫"</string> <string name="gallery_camera_bucket_name">"攝影機圖片"</string> <string name="gallery_camera_videos_bucket_name">"攝影機影片"</string> <string name="switch_to_video_lable">"切換為影片"</string> <string name="switch_to_camera_lable">"切換為攝影機"</string> <string name="crop_label">"裁切相片"</string> <string name="view_label">"檢視相片"</string> <string name="preferences_label">"相機設定"</string> <string name="wait">"請稍候…"</string> <string name="no_storage">"使用相機前請先插入 SD 卡。"</string> <string name="not_enough_space">"SD 卡已滿。"</string> <string name="preparing_sd">"正在準備 SD 卡..."</string> <string name="wallpaper">"設定桌布中,請稍候…"</string> <string name="savingImage">"儲存相片中…"</string> <string name="runningFaceDetection">"請稍候…"</string> <string name="flip_orientation">"旋轉方向"</string> <string name="settings">"設定"</string> <string name="view">"檢視"</string> <string name="details">"詳細資料"</string> <string name="rotate">"旋轉"</string> <string name="rotate_left">"向左旋轉"</string> <string name="rotate_right">"向右旋轉"</string> <string name="slide_show">"投影片"</string> <string name="capture_picture">"拍攝圖片"</string> <string name="capture_video">"拍攝影片"</string> <string name="crop_save_text">"儲存"</string> <string name="crop_discard_text">"放棄"</string> <string name="confirm_delete_title">"刪除"</string> <string name="confirm_delete_message">"此相片會被刪除。"</string> <string name="confirm_delete_video_message">"將刪除此影片。"</string> <string name="camera_toss">"刪除"</string> <string name="camera_gallery">"圖庫"</string> <string name="camera_share">"分享"</string> <string name="camera_set">"設為"</string> <string name="camera_play">"播放"</string> <string name="camera_attach">"附加"</string> <string name="camera_cancel">"取消"</string> <string name="camera_crop">"裁切"</string> <string name="camera_tossing">"刪除中…"</string> <string name="no_way_to_share_image">"此相片無法分享。"</string> <string name="no_way_to_share_video">"此影片無法分享。"</string> <!-- no translation found for video_play (5287787282508002895) --> <skip /> <string name="camera_gallery_photos_text">"圖庫"</string> <string name="camera_pick_wallpaper">"相片"</string> <string name="camera_setas_wallpaper">"桌布"</string> <string name="pref_gallery_category">"一般設定"</string> <string name="pref_slideshow_category">"投影片設定"</string> <string name="pref_camera_general_settings_category">"一般設定"</string> <string name="pref_gallery_size_title">"顯示大小"</string> <string name="pref_gallery_size_summary">"選取相片和影片顯示大小"</string> <string name="pref_gallery_size_dialogtitle">"相片大小"</string> <string-array name="pref_gallery_size_choices"> <item>"大"</item> <item>"小"</item> </string-array> <string name="pref_gallery_sort_title">"排序順序"</string> <string name="pref_gallery_sort_summary">"選取相片和影片排序順序"</string> <string name="pref_gallery_sort_dialogtitle">"圖片排序"</string> <string-array name="pref_gallery_sort_choices"> <item>"最新的優先"</item> <item>"最舊的優先"</item> </string-array> <string name="pref_gallery_slideshow_interval_title">"投影片顯示間隔"</string> <string name="pref_gallery_slideshow_interval_summary">"選取每張投影片顯示時間"</string> <string name="pref_gallery_slideshow_interval_dialogtitle">"投影片顯示間隔"</string> <string-array name="pref_gallery_slideshow_interval_choices"> <item>"2 秒"</item> <item>"3 秒"</item> <item>"4 秒"</item> </string-array> <string name="pref_gallery_slideshow_transition_title">"投影片轉場效果"</string> <string name="pref_gallery_slideshow_transition_summary">"選取相片更換時的轉場效果"</string> <string name="pref_gallery_slideshow_transition_dialogtitle">"投影片轉場效果"</string> <string-array name="pref_gallery_slideshow_transition_choices"> <item>"淡入淡出"</item> <item>"左右滑動"</item> <item>"上下滑動"</item> <item>"隨機選取"</item> </string-array> <string name="pref_gallery_slideshow_repeat_title">"重複播放投影片"</string> <string name="pref_gallery_slideshow_repeat_summary">"播放投影片多次"</string> <string name="pref_gallery_slideshow_shuffle_title">"隨機播放投影片"</string> <string name="pref_gallery_slideshow_shuffle_summary">"隨機顯示相片"</string> <string name="pref_camera_recordlocation_title">"在相片儲存位置資訊"</string> <string name="pref_camera_recordlocation_summary">"在相片中紀錄位置資訊"</string> <string name="pref_camera_videoquality_category">"影片品質"</string> <string name="pref_camera_videoquality_title">"選取影片品質"</string> <string name="pref_camera_videoquality_entry_0">"低 (適用於多媒體簡訊)"</string> <string name="pref_camera_videoquality_entry_1">"高 (適用於 SD 卡)"</string> <string name="pref_camera_videoquality_dialogtitle">"影片品質"</string> <string name="camerasettings">"設定"</string> <string name="image_gallery_NoImageView_text">"找不到媒體。"</string> <string name="pref_gallery_confirm_delete_title">"刪除確認"</string> <string name="pref_gallery_confirm_delete_summary">"刪除相片或影片前要顯示確認"</string> <string name="details_panel_title">"詳細資料"</string> <string name="details_file_size">"檔案大小:"</string> <string name="details_image_resolution">"解析度:"</string> <string name="details_duration">"所需時間:"</string> <string name="details_date_taken">"拍攝日期:"</string> <string name="details_frame_rate">"影格速率:"</string> <string name="details_bit_rate">"位元速率:"</string> <string name="details_codec">"編碼器:"</string> <string name="details_format">"格式:"</string> <string name="details_dimension_x">"%1$d x %2$d"</string> <string name="details_ms">"%1$02d:%2$02d"</string> <string name="details_hms">"%1$d:%2$02d:%3$02d"</string> <string name="details_fps">"%1$d fps"</string> <string name="details_kbps">"%1$d Kbps"</string> <string name="details_mbps">"%1$g Mbps"</string> <string name="details_ok">"確定"</string> <string name="context_menu_header">"圖片選項"</string> <string name="video_context_menu_header">"影片選項"</string> <string name="multiface_crop_help">"選取版面開始裁切"</string> <string name="photos_gallery_title">"圖庫"</string> <string name="pick_photos_gallery_title">"選取相片"</string> <string name="videos_gallery_title">"圖庫"</string> <string name="pick_videos_gallery_title">"選取影片"</string> <string name="loading_progress_format_string">"還有 <xliff:g id="COUNTER">%d</xliff:g> 張"</string> <string name="sendImage">"透過…分享圖片"</string> <string name="setImage">"設定相片為…"</string> <string name="sendVideo">"透過…分享影片"</string> <string name="movieviewlabel">"電影"</string> <string name="loading_video">"正在載入影片…"</string> <string name="spaceIsLow_title">"空間不足"</string> <string name="spaceIsLow_content">"您的 SD 卡空間已快用完。請變更品質設定或刪除圖庫中的項目。"</string> <string name="resume_playing_title">"繼續播放影片"</string> <string name="resume_playing_message">"要從 %s 繼續播放嗎?"</string> <string name="resume_playing_resume">"繼續播放"</string> <string name="resume_playing_restart">"重新開始"</string> <string name="gadget_title">"相框"</string> - <!-- no translation found for file_info_title (1628963357466012538) --> - <skip /> - <!-- no translation found for video_exceed_mms_limit (3835075281230780010) --> - <skip /> - <!-- no translation found for too_large_to_attach (8944461117941172986) --> - <skip /> + <string name="file_info_title">"檔案資訊:"</string> + <string name="video_exceed_mms_limit">"您所錄製的影片太大,無法透過 MMS 傳送。請試著錄製較短的影片。"</string> + <string name="too_large_to_attach">"檔案太大,超過附檔上限。"</string> </resources>
brunsky/WS171-packages-apps-Camera
3ab53a9ab282acb3ab398ad72b6a1681bed15e66
Automated import from //branches/cupcake/...@141618,141618
diff --git a/src/com/android/camera/ViewImage.java b/src/com/android/camera/ViewImage.java index 2413a81..5979db8 100644 --- a/src/com/android/camera/ViewImage.java +++ b/src/com/android/camera/ViewImage.java @@ -1,1572 +1,1591 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.util.Random; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.util.AttributeSet; import android.util.Config; import android.util.Log; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import android.widget.Scroller; import android.widget.Toast; import android.widget.ZoomButtonsController; import com.android.camera.ImageManager.IImage; public class ViewImage extends Activity implements View.OnClickListener { private static final String TAG = "ViewImage"; private static final int TOUCH_AREA_WIDTH = 60; private ImageGetter mGetter; + private boolean mInitialized; + private Uri mCurrentUri; static final boolean sSlideShowHidesStatusBar = true; // Choices for what adjacents to load. static private final int[] sOrder_adjacents = new int[] { 0, 1, -1 }; static private final int[] sOrder_slideshow = new int[] { 0 }; private LocalHandler mHandler = new LocalHandler(); private Random mRandom = new Random(System.currentTimeMillis()); private int [] mShuffleOrder; private boolean mUseShuffleOrder = false; private boolean mSlideShowLoop = false; private static final int MODE_NORMAL = 1; private static final int MODE_SLIDESHOW = 2; private int mMode = MODE_NORMAL; private boolean mFullScreenInNormalMode; private boolean mShowActionIcons; private View mActionIconPanel; private View mShutterButton; private boolean mSortAscending = false; private int mSlideShowInterval; private int mLastSlideShowImage; private boolean mFirst = true; private int mCurrentPosition = 0; private boolean mLayoutComplete = false; // represents which style animation to use private int mAnimationIndex; private Animation [] mSlideShowInAnimation; private Animation [] mSlideShowOutAnimation; private SharedPreferences mPrefs; private View mNextImageView, mPrevImageView; private Animation mHideNextImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mHidePrevImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mShowNextImageViewAnimation = new AlphaAnimation(0F, 1F); private Animation mShowPrevImageViewAnimation = new AlphaAnimation(0F, 1F); static final int sPadding = 20; static final int sHysteresis = sPadding * 2; static final int sBaseScrollDuration = 1000; // ms private ImageManager.IImageList mAllImages; private int mSlideShowImageCurrent = 0; private ImageViewTouch [] mSlideShowImageViews = new ImageViewTouch[2]; private GestureDetector mGestureDetector; private ZoomButtonsController mZoomButtonsController; // Array of image views. The center view is the one the user is focused // on. The one at the zeroth position and the second position reflect // the images to the left/right of the center image. private ImageViewTouch[] mImageViews = new ImageViewTouch[3]; // Container for the three image views. This guy can be "scrolled" // to reveal the image prior to and after the center image. private ScrollHandler mScroller; private MenuHelper.MenuItemsResult mImageMenuRunnable; private Runnable mDismissOnScreenControlsRunnable; private boolean mCameraReviewMode; private int mCurrentOrientation; private void updateNextPrevControls() { boolean showPrev = mCurrentPosition > 0; boolean showNext = mCurrentPosition < mAllImages.getCount() - 1; boolean prevIsVisible = mPrevImageView.getVisibility() == View.VISIBLE; boolean nextIsVisible = mNextImageView.getVisibility() == View.VISIBLE; if (showPrev && !prevIsVisible) { Animation a = mShowPrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.VISIBLE); } else if (!showPrev && prevIsVisible) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.GONE); } if (showNext && !nextIsVisible) { Animation a = mShowNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.VISIBLE); } else if (!showNext && nextIsVisible) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.GONE); } } private void showOnScreenControls() { updateNextPrevControls(); updateZoomButtonsEnabled(); mZoomButtonsController.setVisible(true); scheduleDismissOnScreenControls(); } @Override public boolean dispatchTouchEvent(MotionEvent m) { boolean sup = super.dispatchTouchEvent(m); if (sup == false) { if (mMode == MODE_SLIDESHOW) { mSlideShowImageViews[mSlideShowImageCurrent].handleTouchEvent(m); } else if (mMode == MODE_NORMAL){ mImageViews[1].handleTouchEvent(m); } return true; } return true; } private void scheduleDismissOnScreenControls() { mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); mHandler.postDelayed(mDismissOnScreenControlsRunnable, 1500); } private void updateZoomButtonsEnabled() { ImageViewTouch imageView = mImageViews[1]; float scale = imageView.getScale(); mZoomButtonsController.setZoomInEnabled(scale < imageView.mMaxZoom); mZoomButtonsController.setZoomOutEnabled(scale > 1); } @Override protected void onDestroy() { // This is necessary to make the ZoomButtonsController unregister // its configuration change receiver. if (mZoomButtonsController != null) { mZoomButtonsController.setVisible(false); } super.onDestroy(); } private void setupZoomButtonController(View rootView) { mGestureDetector = new GestureDetector(this, new MyGestureListener()); mZoomButtonsController = new ZoomButtonsController(rootView); mZoomButtonsController.setAutoDismissed(false); mZoomButtonsController.setOnZoomListener( new ZoomButtonsController.OnZoomListener() { public void onVisibilityChanged(boolean visible) { if (visible) { updateZoomButtonsEnabled(); } } public void onZoom(boolean zoomIn) { if (zoomIn) { mImageViews[1].zoomIn(); } else { mImageViews[1].zoomOut(); } showOnScreenControls(); } }); } private class MyGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { ImageViewTouch imageView = mImageViews[1]; if (imageView.getScale() > 1F) { imageView.postTranslate(-distanceX, -distanceY, sUseBounce); imageView.center(true, true, false); } showOnScreenControls(); return true; } @Override public boolean onSingleTapUp(MotionEvent e) { int viewWidth = mImageViews[1].getWidth(); int x = (int) e.getX(); int y = (int) e.getY(); if (x < TOUCH_AREA_WIDTH) { moveNextOrPrevious(-1); } else if (x > viewWidth - TOUCH_AREA_WIDTH) { moveNextOrPrevious(1); } setMode(MODE_NORMAL); showOnScreenControls(); return true; } } private void setupDismissOnScreenControlRunnable() { mDismissOnScreenControlsRunnable = new Runnable() { public void run() { if (!mShowActionIcons) { if (mNextImageView.getVisibility() == View.VISIBLE) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.INVISIBLE); } if (mPrevImageView.getVisibility() == View.VISIBLE) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.INVISIBLE); } mZoomButtonsController.setVisible(false); } } }; } private boolean isPickIntent() { String action = getIntent().getAction(); return (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)); } private static final boolean sUseBounce = false; private static final boolean sAnimateTransitions = false; public static class ImageViewTouch extends ImageViewTouchBase { private ViewImage mViewImage; private boolean mEnableTrackballScroll; public ImageViewTouch(Context context) { super(context); mViewImage = (ViewImage) context; } public ImageViewTouch(Context context, AttributeSet attrs) { super(context, attrs); mViewImage = (ViewImage) context; } public void setEnableTrackballScroll(boolean enable) { mEnableTrackballScroll = enable; } protected void postTranslate(float dx, float dy, boolean bounceOK) { super.postTranslate(dx, dy); if (dx != 0F || dy != 0F) { mViewImage.showOnScreenControls(); } if (!sUseBounce) { center(true, false, false); } } protected ScrollHandler scrollHandler() { return mViewImage.mScroller; } public boolean handleTouchEvent(MotionEvent m) { return mViewImage.mGestureDetector.onTouchEvent(m); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Don't respond to arrow keys if trackball scrolling is not enabled if (!mEnableTrackballScroll) { if ((keyCode >= KeyEvent.KEYCODE_DPAD_UP) && (keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT)) { return super.onKeyDown(keyCode, event); } } int current = mViewImage.mCurrentPosition; int nextImagePos = -2; // default no next image try { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: { if (mViewImage.isPickIntent()) { ImageManager.IImage img = mViewImage.mAllImages.getImageAt(mViewImage.mCurrentPosition); mViewImage.setResult(RESULT_OK, new Intent().setData(img.fullSizeImageUri())); mViewImage.finish(); } break; } case KeyEvent.KEYCODE_DPAD_LEFT: { panBy(sPanRate, 0); int maxOffset = (current == 0) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(true, maxOffset)) { nextImagePos = current - 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_RIGHT: { panBy(-sPanRate, 0); int maxOffset = (current == mViewImage.mAllImages.getCount() - 1) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(false, maxOffset)) { nextImagePos = current + 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_UP: { panBy(0, sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DPAD_DOWN: { panBy(0, -sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DEL: MenuHelper.deletePhoto( mViewImage, mViewImage.mDeletePhotoRunnable); break; } } finally { if (nextImagePos >= 0 && nextImagePos < mViewImage.mAllImages.getCount()) { synchronized (mViewImage) { mViewImage.setMode(MODE_NORMAL); mViewImage.setImage(nextImagePos); } } else if (nextImagePos != -2) { center(true, true, false); } } return super.onKeyDown(keyCode, event); } protected boolean isShiftedToNextImage(boolean left, int maxOffset) { boolean retval; Bitmap bitmap = mBitmapDisplayed; Matrix m = getImageViewMatrix(); if (left) { float [] t1 = new float[] { 0, 0 }; m.mapPoints(t1); retval = t1[0] > maxOffset; } else { int width = bitmap != null ? bitmap.getWidth() : getWidth(); float [] t1 = new float[] { width, 0 }; m.mapPoints(t1); retval = t1[0] + maxOffset < getWidth(); } return retval; } protected void scrollX(int deltaX) { scrollHandler().scrollBy(deltaX, 0); } protected int getScrollOffset() { return scrollHandler().getScrollX(); } } static class ScrollHandler extends LinearLayout { private Runnable mFirstLayoutCompletedCallback = null; private Scroller mScrollerHelper; private int mWidth = -1; public ScrollHandler(Context context) { super(context); mScrollerHelper = new Scroller(context); } public ScrollHandler(Context context, AttributeSet attrs) { super(context, attrs); mScrollerHelper = new Scroller(context); } public void setLayoutCompletedCallback(Runnable r) { mFirstLayoutCompletedCallback = r; } public void startScrollTo(int newX, int newY) { int oldX = getScrollX(); int oldY = getScrollY(); int deltaX = newX - oldX; int deltaY = newY - oldY; if (mWidth == -1) { mWidth = findViewById(R.id.image2).getWidth(); } int viewWidth = mWidth; int duration = viewWidth > 0 ? sBaseScrollDuration * Math.abs(deltaX) / viewWidth : 0; mScrollerHelper.startScroll(oldX, oldY, deltaX, deltaY, duration); invalidate(); } @Override public void computeScroll() { if (mScrollerHelper.computeScrollOffset()) { scrollTo(mScrollerHelper.getCurrX(), mScrollerHelper.getCurrY()); postInvalidate(); // So we draw again } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int width = right - left; int x = 0; for (View v : new View[] { findViewById(R.id.image1), findViewById(R.id.image2), findViewById(R.id.image3) }) { v.layout(x, 0, x + width, bottom); x += (width + sPadding); } findViewById(R.id.padding1).layout(width, 0, width + sPadding, bottom); findViewById(R.id.padding2).layout(width+sPadding+width, 0, width+sPadding+width+sPadding, bottom); if (changed) { if (mFirstLayoutCompletedCallback != null) { mFirstLayoutCompletedCallback.run(); } } } } private void animateScrollTo(int xNew, int yNew) { mScroller.startScrollTo(xNew, yNew); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (! mCameraReviewMode) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.slide_show); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { setMode(MODE_SLIDESHOW); mLastSlideShowImage = mCurrentPosition; loadNextImage(mCurrentPosition, 0, true); return true; } }); item.setIcon(android.R.drawable.ic_menu_slideshow); } final SelectedImageGetter selectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return mAllImages.getImageAt(mCurrentPosition); } public Uri getCurrentImageUri() { return mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); } }; mImageMenuRunnable = MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL, true, ViewImage.this, mHandler, mDeletePhotoRunnable, new MenuHelper.MenuInvoker() { public void run(MenuHelper.MenuCallback cb) { setMode(MODE_NORMAL); cb.run(selectedImageGetter.getCurrentImageUri(), selectedImageGetter.getCurrentImage()); for (ImageViewTouchBase iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } setImage(mCurrentPosition); } }); if (true) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 1000, R.string.camerasettings); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent preferences = new Intent(); preferences.setClass(ViewImage.this, GallerySettings.class); startActivity(preferences); return true; } }); item.setAlphabeticShortcut('p'); item.setIcon(android.R.drawable.ic_menu_preferences); } // Hidden menu just so the shortcut will bring up the zoom controls menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.camerasettings) // the string resource is a placeholder .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { showOnScreenControls(); return true; } }) .setAlphabeticShortcut('z') .setVisible(false); return true; } protected Runnable mDeletePhotoRunnable = new Runnable() { public void run() { mAllImages.removeImageAt(mCurrentPosition); if (mAllImages.getCount() == 0) { finish(); } else { if (mCurrentPosition == mAllImages.getCount()) { mCurrentPosition -= 1; } } for (ImageViewTouchBase iv: mImageViews) { iv.setImageBitmapResetBase(null, true, true); } setImage(mCurrentPosition); } }; @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); setMode(MODE_NORMAL); if (mImageMenuRunnable != null) { mImageMenuRunnable.gettingReadyToOpen(menu, mAllImages.getImageAt(mCurrentPosition)); } return true; } @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean changed = mCurrentOrientation != newConfig.orientation; mCurrentOrientation = newConfig.orientation; if (changed) { if (mGetter != null) { // kill off any background image fetching mGetter.cancelCurrent(); mGetter.stop(); } makeGetter(); mFirst = true; // clear off the current set of images since we need to reload // them at the right size for (ImageViewTouchBase iv: mImageViews) { iv.clear(); } MenuHelper.requestOrientation(this, mPrefs); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { boolean b = super.onMenuItemSelected(featureId, item); if (mImageMenuRunnable != null) mImageMenuRunnable.aboutToCall(item, mAllImages.getImageAt(mCurrentPosition)); return b; } /* * Here's the loading strategy. For any given image, load the thumbnail * into memory and post a callback to display the resulting bitmap. * * Then proceed to load the full image bitmap. Three things can * happen at this point: * * 1. the image fails to load because the UI thread decided * to move on to a different image. This "cancellation" happens * by virtue of the UI thread closing the stream containing the * image being decoded. BitmapFactory.decodeStream returns null * in this case. * * 2. the image loaded successfully. At that point we post * a callback to the UI thread to actually show the bitmap. * * 3. when the post runs it checks to see if the image that was * loaded is still the one we want. The UI may have moved on * to some other image and if so we just drop the newly loaded * bitmap on the floor. */ interface ImageGetterCallback { public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb); public boolean wantsThumbnail(int pos, int offset); public boolean wantsFullImage(int pos, int offset); public int fullImageSizeToUse(int pos, int offset); public void completed(boolean wasCanceled); public int [] loadOrder(); } class ImageGetter { // The thread which does the work. private Thread mGetterThread; // The base position that's being retrieved. The actual images retrieved // are this base plus each of the offets. private int mCurrentPosition = -1; // The callback to invoke for each image. private ImageGetterCallback mCB; // This is the loader cancelable that gets set while we're loading an image. // If we change position we can cancel the current load using this. private ImageManager.IGetBitmap_cancelable mLoad; // True if we're canceling the current load. private boolean mCancelCurrent = false; // True when the therad should exit. private boolean mDone = false; // True when the loader thread is waiting for work. private boolean mReady = false; private void cancelCurrent() { synchronized (this) { if (!mReady) { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { if (Config.LOGV) Log.v(TAG, "canceling load object"); load.cancel(); } mCancelCurrent = false; } } } public ImageGetter() { mGetterThread = new Thread(new Runnable() { private Runnable callback(final int position, final int offset, final boolean isThumb, final Bitmap bitmap) { return new Runnable() { public void run() { // check for inflight callbacks that aren't applicable any longer // before delivering them if (!isCanceled() && position == mCurrentPosition) { mCB.imageLoaded(position, offset, bitmap, isThumb); } else { if (bitmap != null) bitmap.recycle(); } } }; } private Runnable completedCallback(final boolean wasCanceled) { return new Runnable() { public void run() { mCB.completed(wasCanceled); } }; } public void run() { int lastPosition = -1; while (!mDone) { synchronized (ImageGetter.this) { mReady = true; ImageGetter.this.notify(); if (mCurrentPosition == -1 || lastPosition == mCurrentPosition) { try { ImageGetter.this.wait(); } catch (InterruptedException ex) { continue; } } lastPosition = mCurrentPosition; mReady = false; } if (lastPosition != -1) { int imageCount = mAllImages.getCount(); int [] order = mCB.loadOrder(); for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (image == null || isCanceled()) { break; } if (mCB.wantsThumbnail(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting THUMBNAIL load at offset " + offset); Bitmap b = image.thumbBitmap(); mHandler.postGetterCallback(callback(lastPosition, offset, true, b)); } } } for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (mCB.wantsFullImage(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting FULL IMAGE load at offset " + offset); int sizeToUse = mCB.fullImageSizeToUse(lastPosition, offset); if (image != null && !isCanceled()) { mLoad = image.fullSizeBitmap_cancelable(sizeToUse); } if (mLoad != null) { long t1; if (Config.LOGV) t1 = System.currentTimeMillis(); // The return value could be null if the // bitmap is too big, or we cancelled it. Bitmap b = mLoad.get(); if (Config.LOGV && b != null) { long t2 = System.currentTimeMillis(); Log.v(TAG, "loading full image for " + image.fullSizeImageUri() + " with requested size " + sizeToUse + " took " + (t2 - t1) + " and returned a bitmap with size " + b.getWidth() + " / " + b.getHeight()); } mLoad = null; if (b != null) { if (isCanceled()) { b.recycle(); } else { mHandler.postGetterCallback(callback(lastPosition, offset, false, b)); } } } } } } mHandler.postGetterCallback(completedCallback(isCanceled())); } } } }); mGetterThread.setName("ImageGettter"); mGetterThread.start(); } private boolean isCanceled() { synchronized (this) { return mCancelCurrent; } } public void setPosition(int position, ImageGetterCallback cb) { synchronized (this) { if (!mReady) { try { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { load.cancel(); } // if the thread is waiting before loading the full size // image then this will free it up ImageGetter.this.notify(); ImageGetter.this.wait(); mCancelCurrent = false; } catch (InterruptedException ex) { // not sure what to do here } } } mCurrentPosition = position; mCB = cb; synchronized (this) { ImageGetter.this.notify(); } } public void stop() { synchronized (this) { mDone = true; ImageGetter.this.notify(); } try { mGetterThread.join(); } catch (InterruptedException ex) { } } } private void setImage(int pos) { if (!mLayoutComplete) { return; } final boolean left = (pos == mCurrentPosition - 1); final boolean right = (pos == mCurrentPosition + 1); mCurrentPosition = pos; ImageViewTouchBase current = mImageViews[1]; current.mSuppMatrix.reset(); current.setImageMatrix(current.getImageViewMatrix()); if (false) { Log.v(TAG, "before..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } if (!mFirst) { if (left) { mImageViews[2].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[0]); } else if (right) { mImageViews[0].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[2]); } } if (false) { Log.v(TAG, "after copy..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } for (ImageViewTouchBase ivt: mImageViews) { ivt.mIsZooming = false; } int width = mImageViews[1].getWidth(); int from; int to = width + sPadding; if (mFirst) { from = to; mFirst = false; } else { from = left ? (width + sPadding) + mScroller.getScrollX() : mScroller.getScrollX() - (width + sPadding); } if (sAnimateTransitions) { mScroller.scrollTo(from, 0); animateScrollTo(to, 0); } else { mScroller.scrollTo(to, 0); } ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { if (!mShowActionIcons) { mImageViews[1].setFocusableInTouchMode(true); mImageViews[1].requestFocus(); } } public boolean wantsThumbnail(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; return ivt.mThumbBitmap == null; } public boolean wantsFullImage(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; if (ivt.mBitmapDisplayed != null && !ivt.mBitmapIsThumbnail) { return false; } if (offset != 0) { return false; } return true; } public int fullImageSizeToUse(int pos, int offset) { // TODO // this number should be bigger so that we can zoom. we may need to // get fancier and read in the fuller size image as the user starts // to zoom. use -1 to get the full full size image. // for now use 480 so we don't run out of memory final int imageViewSize = 480; return imageViewSize; } public int [] loadOrder() { return sOrder_adjacents; } public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb) { // shouldn't get here after onPause() ImageViewTouchBase ivt = mImageViews[1 + offset]; if (offset == 0) updateZoomButtonsEnabled(); ivt.setImageBitmapResetBase(bitmap, isThumb, isThumb); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { mGetter.setPosition(pos, cb); } showOnScreenControls(); } @Override public void onCreate(Bundle instanceState) { super.onCreate(instanceState); Intent intent = getIntent(); mCameraReviewMode = intent.getBooleanExtra("com.android.camera.ReviewMode", false); mFullScreenInNormalMode = intent.getBooleanExtra(MediaStore.EXTRA_FULL_SCREEN, true); mShowActionIcons = intent.getBooleanExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, false); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mCurrentOrientation = getResources().getConfiguration().orientation; setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.viewimage); mImageViews[0] = (ImageViewTouch) findViewById(R.id.image1); mImageViews[1] = (ImageViewTouch) findViewById(R.id.image2); mImageViews[2] = (ImageViewTouch) findViewById(R.id.image3); for(ImageViewTouch v : mImageViews) { v.setEnableTrackballScroll(!mShowActionIcons); } mScroller = (ScrollHandler)findViewById(R.id.scroller); makeGetter(); mAnimationIndex = -1; mSlideShowInAnimation = new Animation[] { makeInAnimation(R.anim.transition_in), makeInAnimation(R.anim.slide_in), makeInAnimation(R.anim.slide_in_vertical), }; mSlideShowOutAnimation = new Animation[] { makeOutAnimation(R.anim.transition_out), makeOutAnimation(R.anim.slide_out), makeOutAnimation(R.anim.slide_out_vertical), }; mSlideShowImageViews[0] = (ImageViewTouch) findViewById(R.id.image1_slideShow); mSlideShowImageViews[1] = (ImageViewTouch) findViewById(R.id.image2_slideShow); for (ImageViewTouch v : mSlideShowImageViews) { v.setImageBitmapResetBase(null, true, true); v.setVisibility(View.INVISIBLE); v.setEnableTrackballScroll(!mShowActionIcons); } mActionIconPanel = findViewById(R.id.action_icon_panel); { int[] pickIds = {R.id.attach, R.id.cancel}; int[] normalIds = {R.id.gallery, R.id.setas, R.id.share, R.id.discard}; int[] hideIds = pickIds; int[] connectIds = normalIds; if (isPickIntent()) { hideIds = normalIds; connectIds = pickIds; } for(int id : hideIds) { mActionIconPanel.findViewById(id).setVisibility(View.GONE); } for(int id : connectIds) { View view = mActionIconPanel.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } mShutterButton = findViewById(R.id.shutter_button); mShutterButton.setOnClickListener(this); - Uri uri = getIntent().getData(); + mCurrentUri = getIntent().getData(); if (Config.LOGV) - Log.v(TAG, "uri is " + uri); + Log.v(TAG, "uri is " + mCurrentUri); if (instanceState != null) { if (instanceState.containsKey("uri")) { - uri = Uri.parse(instanceState.getString("uri")); + mCurrentUri = Uri.parse(instanceState.getString("uri")); } } - if (uri == null) { + if (mCurrentUri == null) { finish(); return; } - init(uri); + init(mCurrentUri); Bundle b = getIntent().getExtras(); boolean slideShow = b != null ? b.getBoolean("slideshow", false) : false; if (slideShow) { setMode(MODE_SLIDESHOW); loadNextImage(mCurrentPosition, 0, true); } else { if (mFullScreenInNormalMode) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } } setupZoomButtonController(findViewById(R.id.rootLayout)); setupDismissOnScreenControlRunnable(); mNextImageView = findViewById(R.id.next_image); mPrevImageView = findViewById(R.id.prev_image); mNextImageView.setOnClickListener(this); mPrevImageView.setOnClickListener(this); if (mShowActionIcons) { mNextImageView.setFocusable(true); mPrevImageView.setFocusable(true); } setOrientation(); } private void setOrientation() { Intent intent = getIntent(); if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); if (orientation != getRequestedOrientation()) { setRequestedOrientation(orientation); } } else { MenuHelper.requestOrientation(this, mPrefs); } } private Animation makeInAnimation(int id) { Animation inAnimation = AnimationUtils.loadAnimation(this, id); return inAnimation; } private Animation makeOutAnimation(int id) { Animation outAnimation = AnimationUtils.loadAnimation(this, id); return outAnimation; } private void setMode(int mode) { if (mMode == mode) { return; } findViewById(R.id.slideShowContainer).setVisibility(mode == MODE_SLIDESHOW ? View.VISIBLE : View.GONE); findViewById(R.id.abs) .setVisibility(mode == MODE_NORMAL ? View.VISIBLE : View.GONE); Window win = getWindow(); mMode = mode; if (mode == MODE_SLIDESHOW) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (sSlideShowHidesStatusBar) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } for (ImageViewTouchBase ivt: mImageViews) { ivt.clear(); } mActionIconPanel.setVisibility(View.GONE); mShutterButton.setVisibility(View.GONE); if (false) { Log.v(TAG, "current is " + this.mSlideShowImageCurrent); this.mSlideShowImageViews[0].dump(); this.mSlideShowImageViews[0].dump(); } findViewById(R.id.slideShowContainer).getRootView().requestLayout(); mUseShuffleOrder = mPrefs.getBoolean("pref_gallery_slideshow_shuffle_key", false); mSlideShowLoop = mPrefs.getBoolean("pref_gallery_slideshow_repeat_key", false); try { mAnimationIndex = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_transition_key", "0")); } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mAnimationIndex = 0; } try { mSlideShowInterval = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_interval_key", "3")) * 1000; } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mSlideShowInterval = 3000; } if (Config.LOGV) { Log.v(TAG, "read prefs... shuffle: " + mUseShuffleOrder); Log.v(TAG, "read prefs... loop: " + mSlideShowLoop); Log.v(TAG, "read prefs... animidx: " + mAnimationIndex); Log.v(TAG, "read prefs... interval: " + mSlideShowInterval); } if (mUseShuffleOrder) { generateShuffleOrder(); } } else { if (Config.LOGV) Log.v(TAG, "slide show mode off, mCurrentPosition == " + mCurrentPosition); win.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (mFullScreenInNormalMode) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mGetter != null) mGetter.cancelCurrent(); if (sSlideShowHidesStatusBar) { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } ImageViewTouchBase dst = mImageViews[1]; dst.mLastXTouchPos = -1; dst.mLastYTouchPos = -1; for (ImageViewTouchBase ivt: mSlideShowImageViews) { ivt.clear(); } mShuffleOrder = null; // mGetter null is a proxy for being paused if (mGetter != null) { mFirst = true; // don't animate setImage(mCurrentPosition); } } // this line shouldn't be necessary but the view hierarchy doesn't // seem to realize that the window layout changed mScroller.requestLayout(); } private void generateShuffleOrder() { if (mShuffleOrder == null || mShuffleOrder.length != mAllImages.getCount()) { mShuffleOrder = new int[mAllImages.getCount()]; } for (int i = 0; i < mShuffleOrder.length; i++) { mShuffleOrder[i] = i; } for (int i = mShuffleOrder.length - 1; i > 0; i--) { int r = mRandom.nextInt(i); int tmp = mShuffleOrder[r]; mShuffleOrder[r] = mShuffleOrder[i]; mShuffleOrder[i] = tmp; } } private void loadNextImage(final int requestedPos, final long delay, final boolean firstCall) { if (firstCall && mUseShuffleOrder) { generateShuffleOrder(); } final long targetDisplayTime = System.currentTimeMillis() + delay; ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { } public boolean wantsThumbnail(int pos, int offset) { return true; } public boolean wantsFullImage(int pos, int offset) { return false; } public int [] loadOrder() { return sOrder_slideshow; } public int fullImageSizeToUse(int pos, int offset) { return 480; // TODO compute this } public void imageLoaded(final int pos, final int offset, final Bitmap bitmap, final boolean isThumb) { long timeRemaining = Math.max(0, targetDisplayTime - System.currentTimeMillis()); mHandler.postDelayedGetterCallback(new Runnable() { public void run() { if (mMode == MODE_NORMAL) return; ImageViewTouchBase oldView = mSlideShowImageViews[mSlideShowImageCurrent]; if (++mSlideShowImageCurrent == mSlideShowImageViews.length) { mSlideShowImageCurrent = 0; } ImageViewTouchBase newView = mSlideShowImageViews[mSlideShowImageCurrent]; newView.setVisibility(View.VISIBLE); newView.setImageBitmapResetBase(bitmap, isThumb, isThumb); newView.bringToFront(); int animation = 0; if (mAnimationIndex == -1) { int n = mRandom.nextInt(mSlideShowInAnimation.length); animation = n; } else { animation = mAnimationIndex; } Animation aIn = mSlideShowInAnimation[animation]; newView.setAnimation(aIn); newView.setVisibility(View.VISIBLE); aIn.startNow(); Animation aOut = mSlideShowOutAnimation[animation]; oldView.setVisibility(View.INVISIBLE); oldView.setAnimation(aOut); aOut.startNow(); mCurrentPosition = requestedPos; if (mCurrentPosition == mLastSlideShowImage && !firstCall) { if (mSlideShowLoop) { if (mUseShuffleOrder) { generateShuffleOrder(); } } else { setMode(MODE_NORMAL); return; } } if (Config.LOGV) Log.v(TAG, "mCurrentPosition is now " + mCurrentPosition); loadNextImage((mCurrentPosition + 1) % mAllImages.getCount(), mSlideShowInterval, false); } }, timeRemaining); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { int pos = requestedPos; if (mShuffleOrder != null) { pos = mShuffleOrder[pos]; } mGetter.setPosition(pos, cb); } } private void makeGetter() { mGetter = new ImageGetter(); } private boolean desiredSortOrder() { String sortOrder = mPrefs.getString("pref_gallery_sort_key", null); boolean sortAscending = false; if (sortOrder != null) { sortAscending = sortOrder.equals("ascending"); } if (mCameraReviewMode) { // Force left-arrow older pictures, right-arrow newer pictures. sortAscending = true; } return sortAscending; } private void init(Uri uri) { + if (mInitialized || (uri == null)) + return; + mSortAscending = desiredSortOrder(); int sort = mSortAscending ? ImageManager.SORT_ASCENDING : ImageManager.SORT_DESCENDING; mAllImages = ImageManager.makeImageList(uri, this, sort); uri = uri.buildUpon().query(null).build(); // TODO smarter/faster here please for (int i = 0; i < mAllImages.getCount(); i++) { ImageManager.IImage image = mAllImages.getImageAt(i); if (image.fullSizeImageUri().equals(uri)) { mCurrentPosition = i; mLastSlideShowImage = mCurrentPosition; break; } } + mInitialized = true; } @Override public void onSaveInstanceState(Bundle b) { super.onSaveInstanceState(b); ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); if (image != null){ Uri uri = image.fullSizeImageUri(); String bucket = null; if(getIntent()!= null && getIntent().getData()!=null) bucket = getIntent().getData().getQueryParameter("bucketId"); if(bucket!=null) uri = uri.buildUpon().appendQueryParameter("bucketId", bucket).build(); b.putString("uri", uri.toString()); } if (mMode == MODE_SLIDESHOW) b.putBoolean("slideshow", true); } + + protected void onRestoreInstanceState (Bundle b) { + if (b.containsKey("uri")) { + mCurrentUri = Uri.parse(b.getString("uri")); + } + } @Override public void onResume() { super.onResume(); + + if (mCurrentUri != null) { + init(mCurrentUri); + } // normally this will never be zero but if one "backs" into this // activity after removing the sdcard it could be zero. in that // case just "finish" since there's nothing useful that can happen. if (mAllImages.getCount() == 0) { finish(); } + mCurrentPosition = mAllImages.getCount() - 1; ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); if (desiredSortOrder() != mSortAscending) { init(image.fullSizeImageUri()); } if (mGetter == null) { makeGetter(); } mFirst = true; mScroller.setLayoutCompletedCallback(new Runnable() { public void run() { mLayoutComplete = true; setImage(mCurrentPosition); } }); setImage(mCurrentPosition); setOrientation(); } @Override public void onPause() { super.onPause(); mGetter.cancelCurrent(); mGetter.stop(); mGetter = null; setMode(MODE_NORMAL); // removing all callback in the message queue mHandler.removeAllGetterCallbacks(); mAllImages.deactivate(); mDismissOnScreenControlsRunnable.run(); if (mDismissOnScreenControlsRunnable != null) mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); for (ImageViewTouch iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } for (ImageViewTouch iv: mSlideShowImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } + + mInitialized = false; } @Override public void onStop() { super.onStop(); } public void onClick(View v) { switch (v.getId()) { case R.id.shutter_button: { if (mCameraReviewMode) { finish(); } else { MenuHelper.gotoStillImageCapture(this); } } break; case R.id.gallery: { MenuHelper.gotoCameraImageGallery(this); } break; case R.id.discard: { MenuHelper.deletePhoto(this, mDeletePhotoRunnable); } break; case R.id.share: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_STREAM, u); try { startActivity(Intent.createChooser(intent, getText(R.string.sendImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_image, Toast.LENGTH_SHORT).show(); } } break; case R.id.setas: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA, u); try { startActivity(Intent.createChooser(intent, getText(R.string.setImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } break; case R.id.next_image: { moveNextOrPrevious(1); } break; case R.id.prev_image: { moveNextOrPrevious(-1); } break; } } private void moveNextOrPrevious(int delta) { int nextImagePos = mCurrentPosition + delta; if ((0 <= nextImagePos) && (nextImagePos < mAllImages.getCount())) { setImage(nextImagePos); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case MenuHelper.RESULT_COMMON_MENU_CROP: if (resultCode == RESULT_OK) { // The CropImage activity passes back the Uri of the cropped image as // the Action rather than the Data. Uri dataUri = Uri.parse(data.getAction()); init(dataUri); // Clear mImageViews so we can reload the correct image in onResume(). for (ImageViewTouch iv: mImageViews) { iv.clear(); } } break; } } static class LocalHandler extends Handler { private static final int IMAGE_GETTER_CALLBACK = 1; @Override public void handleMessage(Message message) { switch(message.what) { case IMAGE_GETTER_CALLBACK: ((Runnable) message.obj).run(); } } public void postGetterCallback(Runnable callback) { postDelayedGetterCallback(callback, 0); } public void postDelayedGetterCallback(Runnable callback, long delay) { if (callback == null) throw new NullPointerException(); Message message = Message.obtain(); message.what = IMAGE_GETTER_CALLBACK; message.obj = callback; sendMessageDelayed(message, delay); } public void removeAllGetterCallbacks() { removeMessages(IMAGE_GETTER_CALLBACK); } } }
brunsky/WS171-packages-apps-Camera
fd4a470bc9390644b98a7dcfbaca6c3ed7c31234
Automated import from //branches/cupcake/...@141606,141606
diff --git a/src/com/android/camera/ViewImage.java b/src/com/android/camera/ViewImage.java index b8379d2..2413a81 100644 --- a/src/com/android/camera/ViewImage.java +++ b/src/com/android/camera/ViewImage.java @@ -1,1550 +1,1572 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.util.Random; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.util.AttributeSet; import android.util.Config; import android.util.Log; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import android.widget.Scroller; import android.widget.Toast; import android.widget.ZoomButtonsController; import com.android.camera.ImageManager.IImage; public class ViewImage extends Activity implements View.OnClickListener { private static final String TAG = "ViewImage"; private static final int TOUCH_AREA_WIDTH = 60; private ImageGetter mGetter; static final boolean sSlideShowHidesStatusBar = true; // Choices for what adjacents to load. static private final int[] sOrder_adjacents = new int[] { 0, 1, -1 }; static private final int[] sOrder_slideshow = new int[] { 0 }; - Handler mHandler = new Handler() { - @Override - public void handleMessage(Message msg) { - } - }; + private LocalHandler mHandler = new LocalHandler(); private Random mRandom = new Random(System.currentTimeMillis()); private int [] mShuffleOrder; private boolean mUseShuffleOrder = false; private boolean mSlideShowLoop = false; private static final int MODE_NORMAL = 1; private static final int MODE_SLIDESHOW = 2; private int mMode = MODE_NORMAL; private boolean mFullScreenInNormalMode; private boolean mShowActionIcons; private View mActionIconPanel; private View mShutterButton; private boolean mSortAscending = false; private int mSlideShowInterval; private int mLastSlideShowImage; private boolean mFirst = true; private int mCurrentPosition = 0; private boolean mLayoutComplete = false; // represents which style animation to use private int mAnimationIndex; private Animation [] mSlideShowInAnimation; private Animation [] mSlideShowOutAnimation; private SharedPreferences mPrefs; private View mNextImageView, mPrevImageView; private Animation mHideNextImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mHidePrevImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mShowNextImageViewAnimation = new AlphaAnimation(0F, 1F); private Animation mShowPrevImageViewAnimation = new AlphaAnimation(0F, 1F); static final int sPadding = 20; static final int sHysteresis = sPadding * 2; static final int sBaseScrollDuration = 1000; // ms private ImageManager.IImageList mAllImages; private int mSlideShowImageCurrent = 0; private ImageViewTouch [] mSlideShowImageViews = new ImageViewTouch[2]; private GestureDetector mGestureDetector; private ZoomButtonsController mZoomButtonsController; // Array of image views. The center view is the one the user is focused // on. The one at the zeroth position and the second position reflect // the images to the left/right of the center image. private ImageViewTouch[] mImageViews = new ImageViewTouch[3]; // Container for the three image views. This guy can be "scrolled" // to reveal the image prior to and after the center image. private ScrollHandler mScroller; private MenuHelper.MenuItemsResult mImageMenuRunnable; private Runnable mDismissOnScreenControlsRunnable; private boolean mCameraReviewMode; private int mCurrentOrientation; private void updateNextPrevControls() { boolean showPrev = mCurrentPosition > 0; boolean showNext = mCurrentPosition < mAllImages.getCount() - 1; boolean prevIsVisible = mPrevImageView.getVisibility() == View.VISIBLE; boolean nextIsVisible = mNextImageView.getVisibility() == View.VISIBLE; if (showPrev && !prevIsVisible) { Animation a = mShowPrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.VISIBLE); } else if (!showPrev && prevIsVisible) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.GONE); } if (showNext && !nextIsVisible) { Animation a = mShowNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.VISIBLE); } else if (!showNext && nextIsVisible) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.GONE); } } private void showOnScreenControls() { updateNextPrevControls(); updateZoomButtonsEnabled(); mZoomButtonsController.setVisible(true); scheduleDismissOnScreenControls(); } @Override public boolean dispatchTouchEvent(MotionEvent m) { boolean sup = super.dispatchTouchEvent(m); if (sup == false) { if (mMode == MODE_SLIDESHOW) { mSlideShowImageViews[mSlideShowImageCurrent].handleTouchEvent(m); } else if (mMode == MODE_NORMAL){ mImageViews[1].handleTouchEvent(m); } return true; } return true; } private void scheduleDismissOnScreenControls() { mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); mHandler.postDelayed(mDismissOnScreenControlsRunnable, 1500); } private void updateZoomButtonsEnabled() { ImageViewTouch imageView = mImageViews[1]; float scale = imageView.getScale(); mZoomButtonsController.setZoomInEnabled(scale < imageView.mMaxZoom); mZoomButtonsController.setZoomOutEnabled(scale > 1); } @Override protected void onDestroy() { // This is necessary to make the ZoomButtonsController unregister // its configuration change receiver. if (mZoomButtonsController != null) { mZoomButtonsController.setVisible(false); } super.onDestroy(); } private void setupZoomButtonController(View rootView) { mGestureDetector = new GestureDetector(this, new MyGestureListener()); mZoomButtonsController = new ZoomButtonsController(rootView); mZoomButtonsController.setAutoDismissed(false); mZoomButtonsController.setOnZoomListener( new ZoomButtonsController.OnZoomListener() { public void onVisibilityChanged(boolean visible) { if (visible) { updateZoomButtonsEnabled(); } } public void onZoom(boolean zoomIn) { if (zoomIn) { mImageViews[1].zoomIn(); } else { mImageViews[1].zoomOut(); } showOnScreenControls(); } }); } private class MyGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { ImageViewTouch imageView = mImageViews[1]; if (imageView.getScale() > 1F) { imageView.postTranslate(-distanceX, -distanceY, sUseBounce); imageView.center(true, true, false); } showOnScreenControls(); return true; } @Override public boolean onSingleTapUp(MotionEvent e) { int viewWidth = mImageViews[1].getWidth(); int x = (int) e.getX(); int y = (int) e.getY(); if (x < TOUCH_AREA_WIDTH) { moveNextOrPrevious(-1); } else if (x > viewWidth - TOUCH_AREA_WIDTH) { moveNextOrPrevious(1); } setMode(MODE_NORMAL); showOnScreenControls(); return true; } } private void setupDismissOnScreenControlRunnable() { mDismissOnScreenControlsRunnable = new Runnable() { public void run() { if (!mShowActionIcons) { if (mNextImageView.getVisibility() == View.VISIBLE) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.INVISIBLE); } if (mPrevImageView.getVisibility() == View.VISIBLE) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.INVISIBLE); } mZoomButtonsController.setVisible(false); } } }; } private boolean isPickIntent() { String action = getIntent().getAction(); return (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)); } private static final boolean sUseBounce = false; private static final boolean sAnimateTransitions = false; public static class ImageViewTouch extends ImageViewTouchBase { private ViewImage mViewImage; private boolean mEnableTrackballScroll; public ImageViewTouch(Context context) { super(context); mViewImage = (ViewImage) context; } public ImageViewTouch(Context context, AttributeSet attrs) { super(context, attrs); mViewImage = (ViewImage) context; } public void setEnableTrackballScroll(boolean enable) { mEnableTrackballScroll = enable; } protected void postTranslate(float dx, float dy, boolean bounceOK) { super.postTranslate(dx, dy); if (dx != 0F || dy != 0F) { mViewImage.showOnScreenControls(); } if (!sUseBounce) { center(true, false, false); } } protected ScrollHandler scrollHandler() { return mViewImage.mScroller; } public boolean handleTouchEvent(MotionEvent m) { return mViewImage.mGestureDetector.onTouchEvent(m); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Don't respond to arrow keys if trackball scrolling is not enabled if (!mEnableTrackballScroll) { if ((keyCode >= KeyEvent.KEYCODE_DPAD_UP) && (keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT)) { return super.onKeyDown(keyCode, event); } } int current = mViewImage.mCurrentPosition; int nextImagePos = -2; // default no next image try { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: { if (mViewImage.isPickIntent()) { ImageManager.IImage img = mViewImage.mAllImages.getImageAt(mViewImage.mCurrentPosition); mViewImage.setResult(RESULT_OK, new Intent().setData(img.fullSizeImageUri())); mViewImage.finish(); } break; } case KeyEvent.KEYCODE_DPAD_LEFT: { panBy(sPanRate, 0); int maxOffset = (current == 0) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(true, maxOffset)) { nextImagePos = current - 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_RIGHT: { panBy(-sPanRate, 0); int maxOffset = (current == mViewImage.mAllImages.getCount() - 1) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(false, maxOffset)) { nextImagePos = current + 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_UP: { panBy(0, sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DPAD_DOWN: { panBy(0, -sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DEL: MenuHelper.deletePhoto( mViewImage, mViewImage.mDeletePhotoRunnable); break; } } finally { if (nextImagePos >= 0 && nextImagePos < mViewImage.mAllImages.getCount()) { synchronized (mViewImage) { mViewImage.setMode(MODE_NORMAL); mViewImage.setImage(nextImagePos); } } else if (nextImagePos != -2) { center(true, true, false); } } return super.onKeyDown(keyCode, event); } protected boolean isShiftedToNextImage(boolean left, int maxOffset) { boolean retval; Bitmap bitmap = mBitmapDisplayed; Matrix m = getImageViewMatrix(); if (left) { float [] t1 = new float[] { 0, 0 }; m.mapPoints(t1); retval = t1[0] > maxOffset; } else { int width = bitmap != null ? bitmap.getWidth() : getWidth(); float [] t1 = new float[] { width, 0 }; m.mapPoints(t1); retval = t1[0] + maxOffset < getWidth(); } return retval; } protected void scrollX(int deltaX) { scrollHandler().scrollBy(deltaX, 0); } protected int getScrollOffset() { return scrollHandler().getScrollX(); } } static class ScrollHandler extends LinearLayout { private Runnable mFirstLayoutCompletedCallback = null; private Scroller mScrollerHelper; private int mWidth = -1; public ScrollHandler(Context context) { super(context); mScrollerHelper = new Scroller(context); } public ScrollHandler(Context context, AttributeSet attrs) { super(context, attrs); mScrollerHelper = new Scroller(context); } public void setLayoutCompletedCallback(Runnable r) { mFirstLayoutCompletedCallback = r; } public void startScrollTo(int newX, int newY) { int oldX = getScrollX(); int oldY = getScrollY(); int deltaX = newX - oldX; int deltaY = newY - oldY; if (mWidth == -1) { mWidth = findViewById(R.id.image2).getWidth(); } int viewWidth = mWidth; int duration = viewWidth > 0 ? sBaseScrollDuration * Math.abs(deltaX) / viewWidth : 0; mScrollerHelper.startScroll(oldX, oldY, deltaX, deltaY, duration); invalidate(); } @Override public void computeScroll() { if (mScrollerHelper.computeScrollOffset()) { scrollTo(mScrollerHelper.getCurrX(), mScrollerHelper.getCurrY()); postInvalidate(); // So we draw again } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int width = right - left; int x = 0; for (View v : new View[] { findViewById(R.id.image1), findViewById(R.id.image2), findViewById(R.id.image3) }) { v.layout(x, 0, x + width, bottom); x += (width + sPadding); } findViewById(R.id.padding1).layout(width, 0, width + sPadding, bottom); findViewById(R.id.padding2).layout(width+sPadding+width, 0, width+sPadding+width+sPadding, bottom); if (changed) { if (mFirstLayoutCompletedCallback != null) { mFirstLayoutCompletedCallback.run(); } } } } private void animateScrollTo(int xNew, int yNew) { mScroller.startScrollTo(xNew, yNew); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (! mCameraReviewMode) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.slide_show); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { setMode(MODE_SLIDESHOW); mLastSlideShowImage = mCurrentPosition; loadNextImage(mCurrentPosition, 0, true); return true; } }); item.setIcon(android.R.drawable.ic_menu_slideshow); } final SelectedImageGetter selectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return mAllImages.getImageAt(mCurrentPosition); } public Uri getCurrentImageUri() { return mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); } }; mImageMenuRunnable = MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL, true, ViewImage.this, mHandler, mDeletePhotoRunnable, new MenuHelper.MenuInvoker() { public void run(MenuHelper.MenuCallback cb) { setMode(MODE_NORMAL); cb.run(selectedImageGetter.getCurrentImageUri(), selectedImageGetter.getCurrentImage()); for (ImageViewTouchBase iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } setImage(mCurrentPosition); } }); if (true) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 1000, R.string.camerasettings); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent preferences = new Intent(); preferences.setClass(ViewImage.this, GallerySettings.class); startActivity(preferences); return true; } }); item.setAlphabeticShortcut('p'); item.setIcon(android.R.drawable.ic_menu_preferences); } // Hidden menu just so the shortcut will bring up the zoom controls menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.camerasettings) // the string resource is a placeholder .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { showOnScreenControls(); return true; } }) .setAlphabeticShortcut('z') .setVisible(false); return true; } protected Runnable mDeletePhotoRunnable = new Runnable() { public void run() { mAllImages.removeImageAt(mCurrentPosition); if (mAllImages.getCount() == 0) { finish(); } else { if (mCurrentPosition == mAllImages.getCount()) { mCurrentPosition -= 1; } } for (ImageViewTouchBase iv: mImageViews) { iv.setImageBitmapResetBase(null, true, true); } setImage(mCurrentPosition); } }; @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); setMode(MODE_NORMAL); if (mImageMenuRunnable != null) { mImageMenuRunnable.gettingReadyToOpen(menu, mAllImages.getImageAt(mCurrentPosition)); } return true; } @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean changed = mCurrentOrientation != newConfig.orientation; mCurrentOrientation = newConfig.orientation; if (changed) { if (mGetter != null) { // kill off any background image fetching mGetter.cancelCurrent(); mGetter.stop(); } makeGetter(); mFirst = true; // clear off the current set of images since we need to reload // them at the right size for (ImageViewTouchBase iv: mImageViews) { iv.clear(); } MenuHelper.requestOrientation(this, mPrefs); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { boolean b = super.onMenuItemSelected(featureId, item); if (mImageMenuRunnable != null) mImageMenuRunnable.aboutToCall(item, mAllImages.getImageAt(mCurrentPosition)); return b; } /* * Here's the loading strategy. For any given image, load the thumbnail * into memory and post a callback to display the resulting bitmap. * * Then proceed to load the full image bitmap. Three things can * happen at this point: * * 1. the image fails to load because the UI thread decided * to move on to a different image. This "cancellation" happens * by virtue of the UI thread closing the stream containing the * image being decoded. BitmapFactory.decodeStream returns null * in this case. * * 2. the image loaded successfully. At that point we post * a callback to the UI thread to actually show the bitmap. * * 3. when the post runs it checks to see if the image that was * loaded is still the one we want. The UI may have moved on * to some other image and if so we just drop the newly loaded * bitmap on the floor. */ interface ImageGetterCallback { public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb); public boolean wantsThumbnail(int pos, int offset); public boolean wantsFullImage(int pos, int offset); public int fullImageSizeToUse(int pos, int offset); public void completed(boolean wasCanceled); public int [] loadOrder(); } class ImageGetter { // The thread which does the work. private Thread mGetterThread; // The base position that's being retrieved. The actual images retrieved // are this base plus each of the offets. private int mCurrentPosition = -1; // The callback to invoke for each image. private ImageGetterCallback mCB; // This is the loader cancelable that gets set while we're loading an image. // If we change position we can cancel the current load using this. private ImageManager.IGetBitmap_cancelable mLoad; // True if we're canceling the current load. private boolean mCancelCurrent = false; // True when the therad should exit. private boolean mDone = false; // True when the loader thread is waiting for work. private boolean mReady = false; private void cancelCurrent() { synchronized (this) { if (!mReady) { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { if (Config.LOGV) Log.v(TAG, "canceling load object"); load.cancel(); } mCancelCurrent = false; } } } public ImageGetter() { mGetterThread = new Thread(new Runnable() { private Runnable callback(final int position, final int offset, final boolean isThumb, final Bitmap bitmap) { return new Runnable() { public void run() { // check for inflight callbacks that aren't applicable any longer // before delivering them if (!isCanceled() && position == mCurrentPosition) { mCB.imageLoaded(position, offset, bitmap, isThumb); } else { if (bitmap != null) bitmap.recycle(); } } }; } private Runnable completedCallback(final boolean wasCanceled) { return new Runnable() { public void run() { mCB.completed(wasCanceled); } }; } public void run() { int lastPosition = -1; while (!mDone) { synchronized (ImageGetter.this) { mReady = true; ImageGetter.this.notify(); if (mCurrentPosition == -1 || lastPosition == mCurrentPosition) { try { ImageGetter.this.wait(); } catch (InterruptedException ex) { continue; } } lastPosition = mCurrentPosition; mReady = false; } if (lastPosition != -1) { int imageCount = mAllImages.getCount(); int [] order = mCB.loadOrder(); for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (image == null || isCanceled()) { break; } if (mCB.wantsThumbnail(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting THUMBNAIL load at offset " + offset); Bitmap b = image.thumbBitmap(); - mHandler.post(callback(lastPosition, offset, true, b)); + mHandler.postGetterCallback(callback(lastPosition, offset, true, b)); } } } for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (mCB.wantsFullImage(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting FULL IMAGE load at offset " + offset); int sizeToUse = mCB.fullImageSizeToUse(lastPosition, offset); if (image != null && !isCanceled()) { mLoad = image.fullSizeBitmap_cancelable(sizeToUse); } if (mLoad != null) { long t1; if (Config.LOGV) t1 = System.currentTimeMillis(); // The return value could be null if the // bitmap is too big, or we cancelled it. Bitmap b = mLoad.get(); if (Config.LOGV && b != null) { long t2 = System.currentTimeMillis(); Log.v(TAG, "loading full image for " + image.fullSizeImageUri() + " with requested size " + sizeToUse - + " took " + (t2-t1) + + " took " + (t2 - t1) + " and returned a bitmap with size " + b.getWidth() + " / " + b.getHeight()); } mLoad = null; if (b != null) { if (isCanceled()) { b.recycle(); } else { - mHandler.post(callback(lastPosition, offset, false, b)); + mHandler.postGetterCallback(callback(lastPosition, offset, false, b)); } } } } } } - mHandler.post(completedCallback(isCanceled())); + mHandler.postGetterCallback(completedCallback(isCanceled())); } } } }); mGetterThread.setName("ImageGettter"); mGetterThread.start(); } private boolean isCanceled() { synchronized (this) { return mCancelCurrent; } } public void setPosition(int position, ImageGetterCallback cb) { synchronized (this) { if (!mReady) { try { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { load.cancel(); } // if the thread is waiting before loading the full size // image then this will free it up ImageGetter.this.notify(); ImageGetter.this.wait(); mCancelCurrent = false; } catch (InterruptedException ex) { // not sure what to do here } } } mCurrentPosition = position; mCB = cb; synchronized (this) { ImageGetter.this.notify(); } } public void stop() { synchronized (this) { mDone = true; ImageGetter.this.notify(); } try { mGetterThread.join(); } catch (InterruptedException ex) { } } } private void setImage(int pos) { if (!mLayoutComplete) { return; } final boolean left = (pos == mCurrentPosition - 1); final boolean right = (pos == mCurrentPosition + 1); mCurrentPosition = pos; ImageViewTouchBase current = mImageViews[1]; current.mSuppMatrix.reset(); current.setImageMatrix(current.getImageViewMatrix()); if (false) { Log.v(TAG, "before..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } if (!mFirst) { if (left) { mImageViews[2].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[0]); } else if (right) { mImageViews[0].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[2]); } } if (false) { Log.v(TAG, "after copy..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } for (ImageViewTouchBase ivt: mImageViews) { ivt.mIsZooming = false; } int width = mImageViews[1].getWidth(); int from; int to = width + sPadding; if (mFirst) { from = to; mFirst = false; } else { from = left ? (width + sPadding) + mScroller.getScrollX() : mScroller.getScrollX() - (width + sPadding); } if (sAnimateTransitions) { mScroller.scrollTo(from, 0); animateScrollTo(to, 0); } else { mScroller.scrollTo(to, 0); } ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { if (!mShowActionIcons) { mImageViews[1].setFocusableInTouchMode(true); mImageViews[1].requestFocus(); } } public boolean wantsThumbnail(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; return ivt.mThumbBitmap == null; } public boolean wantsFullImage(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; if (ivt.mBitmapDisplayed != null && !ivt.mBitmapIsThumbnail) { return false; } if (offset != 0) { return false; } return true; } public int fullImageSizeToUse(int pos, int offset) { // TODO // this number should be bigger so that we can zoom. we may need to // get fancier and read in the fuller size image as the user starts // to zoom. use -1 to get the full full size image. // for now use 480 so we don't run out of memory final int imageViewSize = 480; return imageViewSize; } public int [] loadOrder() { return sOrder_adjacents; } public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb) { + // shouldn't get here after onPause() ImageViewTouchBase ivt = mImageViews[1 + offset]; if (offset == 0) updateZoomButtonsEnabled(); ivt.setImageBitmapResetBase(bitmap, isThumb, isThumb); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { mGetter.setPosition(pos, cb); } showOnScreenControls(); } @Override public void onCreate(Bundle instanceState) { super.onCreate(instanceState); Intent intent = getIntent(); mCameraReviewMode = intent.getBooleanExtra("com.android.camera.ReviewMode", false); mFullScreenInNormalMode = intent.getBooleanExtra(MediaStore.EXTRA_FULL_SCREEN, true); mShowActionIcons = intent.getBooleanExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, false); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mCurrentOrientation = getResources().getConfiguration().orientation; setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.viewimage); mImageViews[0] = (ImageViewTouch) findViewById(R.id.image1); mImageViews[1] = (ImageViewTouch) findViewById(R.id.image2); mImageViews[2] = (ImageViewTouch) findViewById(R.id.image3); for(ImageViewTouch v : mImageViews) { v.setEnableTrackballScroll(!mShowActionIcons); } mScroller = (ScrollHandler)findViewById(R.id.scroller); makeGetter(); mAnimationIndex = -1; mSlideShowInAnimation = new Animation[] { makeInAnimation(R.anim.transition_in), makeInAnimation(R.anim.slide_in), makeInAnimation(R.anim.slide_in_vertical), }; mSlideShowOutAnimation = new Animation[] { makeOutAnimation(R.anim.transition_out), makeOutAnimation(R.anim.slide_out), makeOutAnimation(R.anim.slide_out_vertical), }; mSlideShowImageViews[0] = (ImageViewTouch) findViewById(R.id.image1_slideShow); mSlideShowImageViews[1] = (ImageViewTouch) findViewById(R.id.image2_slideShow); for (ImageViewTouch v : mSlideShowImageViews) { v.setImageBitmapResetBase(null, true, true); v.setVisibility(View.INVISIBLE); v.setEnableTrackballScroll(!mShowActionIcons); } mActionIconPanel = findViewById(R.id.action_icon_panel); { int[] pickIds = {R.id.attach, R.id.cancel}; int[] normalIds = {R.id.gallery, R.id.setas, R.id.share, R.id.discard}; int[] hideIds = pickIds; int[] connectIds = normalIds; if (isPickIntent()) { hideIds = normalIds; connectIds = pickIds; } for(int id : hideIds) { mActionIconPanel.findViewById(id).setVisibility(View.GONE); } for(int id : connectIds) { View view = mActionIconPanel.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } mShutterButton = findViewById(R.id.shutter_button); mShutterButton.setOnClickListener(this); Uri uri = getIntent().getData(); if (Config.LOGV) Log.v(TAG, "uri is " + uri); if (instanceState != null) { if (instanceState.containsKey("uri")) { uri = Uri.parse(instanceState.getString("uri")); } } if (uri == null) { finish(); return; } init(uri); Bundle b = getIntent().getExtras(); boolean slideShow = b != null ? b.getBoolean("slideshow", false) : false; if (slideShow) { setMode(MODE_SLIDESHOW); loadNextImage(mCurrentPosition, 0, true); } else { if (mFullScreenInNormalMode) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } } setupZoomButtonController(findViewById(R.id.rootLayout)); setupDismissOnScreenControlRunnable(); mNextImageView = findViewById(R.id.next_image); mPrevImageView = findViewById(R.id.prev_image); mNextImageView.setOnClickListener(this); mPrevImageView.setOnClickListener(this); if (mShowActionIcons) { mNextImageView.setFocusable(true); mPrevImageView.setFocusable(true); } setOrientation(); } private void setOrientation() { Intent intent = getIntent(); if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); if (orientation != getRequestedOrientation()) { setRequestedOrientation(orientation); } } else { MenuHelper.requestOrientation(this, mPrefs); } } private Animation makeInAnimation(int id) { Animation inAnimation = AnimationUtils.loadAnimation(this, id); return inAnimation; } private Animation makeOutAnimation(int id) { Animation outAnimation = AnimationUtils.loadAnimation(this, id); return outAnimation; } private void setMode(int mode) { if (mMode == mode) { return; } findViewById(R.id.slideShowContainer).setVisibility(mode == MODE_SLIDESHOW ? View.VISIBLE : View.GONE); findViewById(R.id.abs) .setVisibility(mode == MODE_NORMAL ? View.VISIBLE : View.GONE); Window win = getWindow(); mMode = mode; if (mode == MODE_SLIDESHOW) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (sSlideShowHidesStatusBar) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } for (ImageViewTouchBase ivt: mImageViews) { ivt.clear(); } mActionIconPanel.setVisibility(View.GONE); mShutterButton.setVisibility(View.GONE); if (false) { Log.v(TAG, "current is " + this.mSlideShowImageCurrent); this.mSlideShowImageViews[0].dump(); this.mSlideShowImageViews[0].dump(); } findViewById(R.id.slideShowContainer).getRootView().requestLayout(); mUseShuffleOrder = mPrefs.getBoolean("pref_gallery_slideshow_shuffle_key", false); mSlideShowLoop = mPrefs.getBoolean("pref_gallery_slideshow_repeat_key", false); try { mAnimationIndex = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_transition_key", "0")); } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mAnimationIndex = 0; } try { mSlideShowInterval = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_interval_key", "3")) * 1000; } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mSlideShowInterval = 3000; } if (Config.LOGV) { Log.v(TAG, "read prefs... shuffle: " + mUseShuffleOrder); Log.v(TAG, "read prefs... loop: " + mSlideShowLoop); Log.v(TAG, "read prefs... animidx: " + mAnimationIndex); Log.v(TAG, "read prefs... interval: " + mSlideShowInterval); } if (mUseShuffleOrder) { generateShuffleOrder(); } } else { if (Config.LOGV) Log.v(TAG, "slide show mode off, mCurrentPosition == " + mCurrentPosition); win.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (mFullScreenInNormalMode) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mGetter != null) mGetter.cancelCurrent(); if (sSlideShowHidesStatusBar) { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } ImageViewTouchBase dst = mImageViews[1]; dst.mLastXTouchPos = -1; dst.mLastYTouchPos = -1; for (ImageViewTouchBase ivt: mSlideShowImageViews) { ivt.clear(); } mShuffleOrder = null; // mGetter null is a proxy for being paused if (mGetter != null) { mFirst = true; // don't animate setImage(mCurrentPosition); } } // this line shouldn't be necessary but the view hierarchy doesn't // seem to realize that the window layout changed mScroller.requestLayout(); } private void generateShuffleOrder() { if (mShuffleOrder == null || mShuffleOrder.length != mAllImages.getCount()) { mShuffleOrder = new int[mAllImages.getCount()]; } for (int i = 0; i < mShuffleOrder.length; i++) { mShuffleOrder[i] = i; } for (int i = mShuffleOrder.length - 1; i > 0; i--) { int r = mRandom.nextInt(i); int tmp = mShuffleOrder[r]; mShuffleOrder[r] = mShuffleOrder[i]; mShuffleOrder[i] = tmp; } } private void loadNextImage(final int requestedPos, final long delay, final boolean firstCall) { if (firstCall && mUseShuffleOrder) { generateShuffleOrder(); } final long targetDisplayTime = System.currentTimeMillis() + delay; ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { } public boolean wantsThumbnail(int pos, int offset) { return true; } public boolean wantsFullImage(int pos, int offset) { return false; } public int [] loadOrder() { return sOrder_slideshow; } public int fullImageSizeToUse(int pos, int offset) { return 480; // TODO compute this } public void imageLoaded(final int pos, final int offset, final Bitmap bitmap, final boolean isThumb) { long timeRemaining = Math.max(0, targetDisplayTime - System.currentTimeMillis()); - mHandler.postDelayed(new Runnable() { + mHandler.postDelayedGetterCallback(new Runnable() { public void run() { - if (mMode == MODE_NORMAL) { - return; - } + if (mMode == MODE_NORMAL) return; ImageViewTouchBase oldView = mSlideShowImageViews[mSlideShowImageCurrent]; if (++mSlideShowImageCurrent == mSlideShowImageViews.length) { mSlideShowImageCurrent = 0; } ImageViewTouchBase newView = mSlideShowImageViews[mSlideShowImageCurrent]; newView.setVisibility(View.VISIBLE); newView.setImageBitmapResetBase(bitmap, isThumb, isThumb); newView.bringToFront(); int animation = 0; if (mAnimationIndex == -1) { int n = mRandom.nextInt(mSlideShowInAnimation.length); animation = n; } else { animation = mAnimationIndex; } Animation aIn = mSlideShowInAnimation[animation]; newView.setAnimation(aIn); newView.setVisibility(View.VISIBLE); aIn.startNow(); Animation aOut = mSlideShowOutAnimation[animation]; oldView.setVisibility(View.INVISIBLE); oldView.setAnimation(aOut); aOut.startNow(); mCurrentPosition = requestedPos; - mHandler.post(new Runnable() { - public void run() { - if (mCurrentPosition == mLastSlideShowImage && !firstCall) { - if (mSlideShowLoop) { - if (mUseShuffleOrder) { - generateShuffleOrder(); - } - } else { - setMode(MODE_NORMAL); - return; - } + if (mCurrentPosition == mLastSlideShowImage && !firstCall) { + if (mSlideShowLoop) { + if (mUseShuffleOrder) { + generateShuffleOrder(); } - - if (Config.LOGV) - Log.v(TAG, "mCurrentPosition is now " + mCurrentPosition); - loadNextImage((mCurrentPosition + 1) % mAllImages.getCount(), mSlideShowInterval, false); + } else { + setMode(MODE_NORMAL); + return; } - }); + } + + if (Config.LOGV) + Log.v(TAG, "mCurrentPosition is now " + mCurrentPosition); + loadNextImage((mCurrentPosition + 1) % mAllImages.getCount(), mSlideShowInterval, false); } }, timeRemaining); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { int pos = requestedPos; if (mShuffleOrder != null) { pos = mShuffleOrder[pos]; } mGetter.setPosition(pos, cb); } } private void makeGetter() { mGetter = new ImageGetter(); } private boolean desiredSortOrder() { String sortOrder = mPrefs.getString("pref_gallery_sort_key", null); boolean sortAscending = false; if (sortOrder != null) { sortAscending = sortOrder.equals("ascending"); } if (mCameraReviewMode) { // Force left-arrow older pictures, right-arrow newer pictures. sortAscending = true; } return sortAscending; } private void init(Uri uri) { mSortAscending = desiredSortOrder(); int sort = mSortAscending ? ImageManager.SORT_ASCENDING : ImageManager.SORT_DESCENDING; mAllImages = ImageManager.makeImageList(uri, this, sort); uri = uri.buildUpon().query(null).build(); // TODO smarter/faster here please for (int i = 0; i < mAllImages.getCount(); i++) { ImageManager.IImage image = mAllImages.getImageAt(i); if (image.fullSizeImageUri().equals(uri)) { mCurrentPosition = i; mLastSlideShowImage = mCurrentPosition; break; } } } @Override public void onSaveInstanceState(Bundle b) { super.onSaveInstanceState(b); ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); if (image != null){ Uri uri = image.fullSizeImageUri(); String bucket = null; if(getIntent()!= null && getIntent().getData()!=null) bucket = getIntent().getData().getQueryParameter("bucketId"); if(bucket!=null) uri = uri.buildUpon().appendQueryParameter("bucketId", bucket).build(); b.putString("uri", uri.toString()); } if (mMode == MODE_SLIDESHOW) b.putBoolean("slideshow", true); } @Override public void onResume() { super.onResume(); // normally this will never be zero but if one "backs" into this // activity after removing the sdcard it could be zero. in that // case just "finish" since there's nothing useful that can happen. if (mAllImages.getCount() == 0) { finish(); } ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); if (desiredSortOrder() != mSortAscending) { init(image.fullSizeImageUri()); } if (mGetter == null) { makeGetter(); } mFirst = true; mScroller.setLayoutCompletedCallback(new Runnable() { public void run() { mLayoutComplete = true; setImage(mCurrentPosition); } }); setImage(mCurrentPosition); setOrientation(); } @Override public void onPause() { super.onPause(); mGetter.cancelCurrent(); mGetter.stop(); mGetter = null; setMode(MODE_NORMAL); + // removing all callback in the message queue + mHandler.removeAllGetterCallbacks(); + mAllImages.deactivate(); mDismissOnScreenControlsRunnable.run(); if (mDismissOnScreenControlsRunnable != null) mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); for (ImageViewTouch iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } for (ImageViewTouch iv: mSlideShowImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } } @Override public void onStop() { super.onStop(); } public void onClick(View v) { switch (v.getId()) { case R.id.shutter_button: { if (mCameraReviewMode) { finish(); } else { MenuHelper.gotoStillImageCapture(this); } } break; case R.id.gallery: { MenuHelper.gotoCameraImageGallery(this); } break; case R.id.discard: { MenuHelper.deletePhoto(this, mDeletePhotoRunnable); } break; case R.id.share: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_STREAM, u); try { startActivity(Intent.createChooser(intent, getText(R.string.sendImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_image, Toast.LENGTH_SHORT).show(); } } break; case R.id.setas: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA, u); try { startActivity(Intent.createChooser(intent, getText(R.string.setImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } break; case R.id.next_image: { moveNextOrPrevious(1); } break; case R.id.prev_image: { moveNextOrPrevious(-1); } break; } } private void moveNextOrPrevious(int delta) { int nextImagePos = mCurrentPosition + delta; if ((0 <= nextImagePos) && (nextImagePos < mAllImages.getCount())) { setImage(nextImagePos); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case MenuHelper.RESULT_COMMON_MENU_CROP: if (resultCode == RESULT_OK) { // The CropImage activity passes back the Uri of the cropped image as // the Action rather than the Data. Uri dataUri = Uri.parse(data.getAction()); init(dataUri); // Clear mImageViews so we can reload the correct image in onResume(). for (ImageViewTouch iv: mImageViews) { iv.clear(); } } break; } } + + static class LocalHandler extends Handler { + private static final int IMAGE_GETTER_CALLBACK = 1; + + @Override + public void handleMessage(Message message) { + switch(message.what) { + case IMAGE_GETTER_CALLBACK: + ((Runnable) message.obj).run(); + } + } + + public void postGetterCallback(Runnable callback) { + postDelayedGetterCallback(callback, 0); + } + + public void postDelayedGetterCallback(Runnable callback, long delay) { + if (callback == null) throw new NullPointerException(); + Message message = Message.obtain(); + message.what = IMAGE_GETTER_CALLBACK; + message.obj = callback; + sendMessageDelayed(message, delay); + } + + public void removeAllGetterCallbacks() { + removeMessages(IMAGE_GETTER_CALLBACK); + } + } }
brunsky/WS171-packages-apps-Camera
64a55a57767fac9174cc4837b13f8157167a987d
Automated import from //branches/cupcake/...@141602,141602
diff --git a/src/com/android/camera/MenuHelper.java b/src/com/android/camera/MenuHelper.java index 27b057b..ed5803c 100644 --- a/src/com/android/camera/MenuHelper.java +++ b/src/com/android/camera/MenuHelper.java @@ -1,729 +1,733 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.io.Closeable; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.StatFs; import android.provider.MediaStore; import android.provider.MediaStore.Images; import android.util.Config; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.MenuItem.OnMenuItemClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.camera.ImageManager.IImage; public class MenuHelper { static private final String TAG = "MenuHelper"; static public final int GENERIC_ITEM = 1; static public final int IMAGE_SAVING_ITEM = 2; static public final int VIDEO_SAVING_ITEM = 3; static public final int IMAGE_MODE_ITEM = 4; static public final int VIDEO_MODE_ITEM = 5; static public final int MENU_ITEM_MAX = 5; static public final int INCLUDE_ALL = 0xFFFFFFFF; static public final int INCLUDE_VIEWPLAY_MENU = (1 << 0); static public final int INCLUDE_SHARE_MENU = (1 << 1); static public final int INCLUDE_SET_MENU = (1 << 2); static public final int INCLUDE_CROP_MENU = (1 << 3); static public final int INCLUDE_DELETE_MENU = (1 << 4); static public final int INCLUDE_ROTATE_MENU = (1 << 5); static public final int INCLUDE_DETAILS_MENU = (1 << 5); static public final int MENU_SWITCH_CAMERA_MODE = 0; static public final int MENU_CAPTURE_PICTURE = 1; static public final int MENU_CAPTURE_VIDEO = 2; static public final int MENU_IMAGE_SHARE = 10; static public final int MENU_IMAGE_SET = 14; static public final int MENU_IMAGE_SET_WALLPAPER = 15; static public final int MENU_IMAGE_SET_CONTACT = 16; static public final int MENU_IMAGE_SET_MYFAVE = 17; static public final int MENU_IMAGE_CROP = 18; static public final int MENU_IMAGE_ROTATE = 19; static public final int MENU_IMAGE_ROTATE_LEFT = 20; static public final int MENU_IMAGE_ROTATE_RIGHT = 21; static public final int MENU_IMAGE_TOSS = 22; static public final int MENU_VIDEO_PLAY = 23; static public final int MENU_VIDEO_SHARE = 24; static public final int MENU_VIDEO_TOSS = 27; static private final long SHARE_FILE_LENGTH_LIMIT = 3L * 1024L * 1024L; public static final int NO_STORAGE_ERROR = -1; public static final int CANNOT_STAT_ERROR = -2; /** Activity result code used to report crop results. */ public static final int RESULT_COMMON_MENU_CROP = 490; public interface MenuItemsResult { public void gettingReadyToOpen(Menu menu, ImageManager.IImage image); public void aboutToCall(MenuItem item, ImageManager.IImage image); } public interface MenuInvoker { public void run(MenuCallback r); } public interface MenuCallback { public void run(Uri uri, ImageManager.IImage image); } private static void closeSilently(Closeable target) { try { if (target != null) target.close(); } catch (Throwable t) { // ignore all exceptions, that's what silently means } } public static long getImageFileSize(ImageManager.IImage image) { java.io.InputStream data = image.fullSizeImageData(); if (data == null) return -1; try { return data.available(); } catch (java.io.IOException ex) { return -1; } finally { closeSilently(data); } } static MenuItemsResult addImageMenuItems( Menu menu, int inclusions, final boolean isImage, final Activity activity, final Handler handler, final Runnable onDelete, final MenuInvoker onInvoke) { final ArrayList<MenuItem> requiresWriteAccessItems = new ArrayList<MenuItem>(); final ArrayList<MenuItem> requiresNoDrmAccessItems = new ArrayList<MenuItem>(); if (isImage && ((inclusions & INCLUDE_ROTATE_MENU) != 0)) { SubMenu rotateSubmenu = menu.addSubMenu(IMAGE_SAVING_ITEM, MENU_IMAGE_ROTATE, 40, R.string.rotate).setIcon(android.R.drawable.ic_menu_rotate); // Don't show the rotate submenu if the item at hand is read only // since the items within the submenu won't be shown anyway. This is // really a framework bug in that it shouldn't show the submenu if // the submenu has no visible items. requiresWriteAccessItems.add(rotateSubmenu.getItem()); if (rotateSubmenu != null) { requiresWriteAccessItems.add(rotateSubmenu.add(0, MENU_IMAGE_ROTATE_LEFT, 50, R.string.rotate_left).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null || image.isReadonly()) return; image.rotateImageBy(-90); } }); return true; } }).setAlphabeticShortcut('l')); requiresWriteAccessItems.add(rotateSubmenu.add(0, MENU_IMAGE_ROTATE_RIGHT, 60, R.string.rotate_right).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null || image.isReadonly()) return; image.rotateImageBy(90); } }); return true; } }).setAlphabeticShortcut('r')); } } if (isImage && ((inclusions & INCLUDE_CROP_MENU) != 0)) { MenuItem autoCrop = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_CROP, 73, R.string.camera_crop).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (u == null) return; Intent cropIntent = new Intent(); cropIntent.setClass(activity, CropImage.class); cropIntent.setData(u); activity.startActivityForResult(cropIntent, RESULT_COMMON_MENU_CROP); } }); return true; } }); autoCrop.setIcon(android.R.drawable.ic_menu_crop); requiresWriteAccessItems.add(autoCrop); } if (isImage && ((inclusions & INCLUDE_SET_MENU) != 0)) { MenuItem setMenu = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_SET, 75, R.string.camera_set); setMenu.setIcon(android.R.drawable.ic_menu_set_as); setMenu.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (u == null || image == null) return; if (Config.LOGV) Log.v(TAG, "in callback u is " + u + "; mime type is " + image.getMimeType()); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA); intent.setDataAndType(u, image.getMimeType()); intent.putExtra("mimeType", image.getMimeType()); activity.startActivity(Intent.createChooser(intent, activity.getText(R.string.setImage))); } }); return true; } }); } if ((inclusions & INCLUDE_SHARE_MENU) != 0) { if (Config.LOGV) Log.v(TAG, ">>>>> add share"); MenuItem item1 = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_SHARE, 10, R.string.camera_share).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null) return; if (!isImage && getImageFileSize(image) > SHARE_FILE_LENGTH_LIMIT ) { Toast.makeText(activity, R.string.too_large_to_attach, Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); String mimeType = image.getMimeType(); intent.setType(mimeType); intent.putExtra(Intent.EXTRA_STREAM, u); boolean isImage = ImageManager.isImageMimeType(mimeType); try { activity.startActivity(Intent.createChooser(intent, activity.getText( isImage ? R.string.sendImage : R.string.sendVideo))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(activity, isImage ? R.string.no_way_to_share_image : R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } }); return true; } }); item1.setIcon(android.R.drawable.ic_menu_share); MenuItem item = item1; requiresNoDrmAccessItems.add(item); } if ((inclusions & INCLUDE_DELETE_MENU) != 0) { MenuItem deleteItem = menu.add(IMAGE_SAVING_ITEM, MENU_IMAGE_TOSS, 70, R.string.camera_toss); requiresWriteAccessItems.add(deleteItem); deleteItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { - deleteImageImpl(activity, onDelete, isImage); + deleteImpl(activity, onDelete, isImage); return true; } }) .setAlphabeticShortcut('d') .setIcon(android.R.drawable.ic_menu_delete); } if ((inclusions & INCLUDE_DETAILS_MENU) != 0) { MenuItem detailsMenu = menu.add(0, 0, 80, R.string.details).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri u, ImageManager.IImage image) { if (image == null) return; AlertDialog.Builder builder = new AlertDialog.Builder(activity); final View d = View.inflate(activity, R.layout.detailsview, null); ImageView imageView = (ImageView) d.findViewById(R.id.details_thumbnail_image); imageView.setImageBitmap(image.miniThumbBitmap()); TextView textView = (TextView) d.findViewById(R.id.details_image_title); textView.setText(image.getDisplayName()); long length = getImageFileSize(image); String lengthString = lengthString = length < 0 ? "" : android.text.format.Formatter.formatFileSize(activity, length); ((TextView)d.findViewById(R.id.details_file_size_value)) .setText(lengthString); int dimensionWidth = 0; int dimensionHeight = 0; if (isImage) { dimensionWidth = image.getWidth(); dimensionHeight = image.getHeight(); d.findViewById(R.id.details_duration_row).setVisibility(View.GONE); d.findViewById(R.id.details_frame_rate_row).setVisibility(View.GONE); d.findViewById(R.id.details_bit_rate_row).setVisibility(View.GONE); d.findViewById(R.id.details_format_row).setVisibility(View.GONE); d.findViewById(R.id.details_codec_row).setVisibility(View.GONE); } else { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setMode(MediaMetadataRetriever.MODE_GET_METADATA_ONLY); retriever.setDataSource(image.getDataPath()); try { dimensionWidth = Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)); dimensionHeight = Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); } catch (NumberFormatException e) { dimensionWidth = 0; dimensionHeight = 0; } try { int durationMs = Integer.parseInt(retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_DURATION)); String durationValue = formatDuration( activity, durationMs); ((TextView)d.findViewById(R.id.details_duration_value)) .setText(durationValue); } catch (NumberFormatException e) { d.findViewById(R.id.details_frame_rate_row) .setVisibility(View.GONE); } try { String frame_rate = String.format( activity.getString(R.string.details_fps), Integer.parseInt( retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_FRAME_RATE))); ((TextView)d.findViewById(R.id.details_frame_rate_value)) .setText(frame_rate); } catch (NumberFormatException e) { d.findViewById(R.id.details_frame_rate_row) .setVisibility(View.GONE); } try { long bitRate = Long.parseLong(retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_BIT_RATE)); String bps; if (bitRate < 1000000) { bps = String.format( activity.getString(R.string.details_kbps), bitRate / 1000); } else { bps = String.format( activity.getString(R.string.details_mbps), ((double) bitRate) / 1000000.0); } ((TextView)d.findViewById(R.id.details_bit_rate_value)) .setText(bps); } catch (NumberFormatException e) { d.findViewById(R.id.details_bit_rate_row) .setVisibility(View.GONE); } String format = retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_VIDEO_FORMAT); ((TextView)d.findViewById(R.id.details_format_value)) .setText(format); String codec = retriever.extractMetadata( MediaMetadataRetriever.METADATA_KEY_CODEC); if (codec == null) { d.findViewById(R.id.details_codec_row). setVisibility(View.GONE); } else { ((TextView)d.findViewById(R.id.details_codec_value)) .setText(codec); } } catch(RuntimeException ex) { // Assume this is a corrupt video file. } finally { try { retriever.release(); } catch (RuntimeException ex) { // Ignore failures while cleaning up. } } } String dimensionsString = String.format( activity.getString(R.string.details_dimension_x), dimensionWidth, dimensionHeight); ((TextView)d.findViewById(R.id.details_resolution_value)) .setText(dimensionsString); String dateString = ""; long dateTaken = image.getDateTaken(); if (dateTaken != 0) { java.util.Date date = new java.util.Date(image.getDateTaken()); java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(); dateString = dateFormat.format(date); ((TextView)d.findViewById(R.id.details_date_taken_value)) .setText(dateString); } else { d.findViewById(R.id.details_date_taken_row) .setVisibility(View.GONE); } builder.setNeutralButton(R.string.details_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setIcon(android.R.drawable.ic_dialog_info) .setTitle(R.string.details_panel_title) .setView(d) .show(); } }); return true; } }); detailsMenu.setIcon(R.drawable.ic_menu_view_details); } if ((!isImage) && ((inclusions & INCLUDE_VIEWPLAY_MENU) != 0)) { menu.add(VIDEO_SAVING_ITEM, MENU_VIDEO_PLAY, 0, R.string.video_play) .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { onInvoke.run(new MenuCallback() { public void run(Uri uri, IImage image) { if (image != null) { Intent intent = new Intent(Intent.ACTION_VIEW, image.fullSizeImageUri()); activity.startActivity(intent); } }}); return true; } }); } return new MenuItemsResult() { public void gettingReadyToOpen(Menu menu, ImageManager.IImage image) { // protect against null here. this isn't strictly speaking required // but if a client app isn't handling sdcard removal properly it // could happen if (image == null) { return; } boolean readOnly = image.isReadonly(); boolean isDrm = image.isDrm(); if (Config.LOGV) Log.v(TAG, "readOnly: " + readOnly + "; drm: " + isDrm); for (MenuItem item: requiresWriteAccessItems) { if (Config.LOGV) Log.v(TAG, "item is " + item.toString()); item.setVisible(!readOnly); item.setEnabled(!readOnly); } for (MenuItem item: requiresNoDrmAccessItems) { if (Config.LOGV) Log.v(TAG, "item is " + item.toString()); item.setVisible(!isDrm); item.setEnabled(!isDrm); } } public void aboutToCall(MenuItem menu, ImageManager.IImage image) { } }; } static void deletePhoto(Activity activity, Runnable onDelete) { - deleteImageImpl(activity, onDelete, true); + deleteImpl(activity, onDelete, true); + } + + static void deleteVideo(Activity activity, Runnable onDelete) { + deleteImpl(activity, onDelete, false); } static void deleteImage(Activity activity, Runnable onDelete, IImage image) { if (image != null) { - deleteImageImpl(activity, onDelete, ImageManager.isImage(image)); + deleteImpl(activity, onDelete, ImageManager.isImage(image)); } } - private static void deleteImageImpl(Activity activity, final Runnable onDelete, boolean isPhoto) { + private static void deleteImpl(Activity activity, final Runnable onDelete, boolean isPhoto) { boolean confirm = android.preference.PreferenceManager.getDefaultSharedPreferences(activity).getBoolean("pref_gallery_confirm_delete_key", true); if (!confirm) { if (onDelete != null) onDelete.run(); } else { displayDeleteDialog(activity, onDelete, isPhoto); } } public static void displayDeleteDialog(Activity activity, final Runnable onDelete, boolean isPhoto) { android.app.AlertDialog.Builder b = new android.app.AlertDialog.Builder(activity); b.setIcon(android.R.drawable.ic_dialog_alert); b.setTitle(R.string.confirm_delete_title); b.setMessage(isPhoto? R.string.confirm_delete_message : R.string.confirm_delete_video_message); b.setPositiveButton(android.R.string.ok, new android.content.DialogInterface.OnClickListener() { public void onClick(android.content.DialogInterface v, int x) { if (onDelete != null) onDelete.run(); } }); b.setNegativeButton(android.R.string.cancel, new android.content.DialogInterface.OnClickListener() { public void onClick(android.content.DialogInterface v, int x) { } }); b.create().show(); } static void addSwitchModeMenuItem(Menu menu, final Activity activity, final boolean switchToVideo) { int group = switchToVideo ? MenuHelper.IMAGE_MODE_ITEM : MenuHelper.VIDEO_MODE_ITEM; int labelId = switchToVideo ? R.string.switch_to_video_lable : R.string.switch_to_camera_lable; int iconId = switchToVideo ? R.drawable.ic_menu_camera_video_view : android.R.drawable.ic_menu_camera; MenuItem item = menu.add(group, MENU_SWITCH_CAMERA_MODE, 0, labelId).setOnMenuItemClickListener( new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { String action = switchToVideo ? MediaStore.INTENT_ACTION_VIDEO_CAMERA : MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA; Intent intent = new Intent(action); intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); activity.finish(); activity.startActivity(intent); return true; } }); item.setIcon(iconId); } static void gotoStillImageCapture(Activity activity) { Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Log.e(TAG, "Could not start still image capture activity", e); } } static void gotoCameraImageGallery(Activity activity) { gotoGallery(activity, R.string.gallery_camera_bucket_name, ImageManager.INCLUDE_IMAGES); } static void gotoCameraVideoGallery(Activity activity) { gotoGallery(activity, R.string.gallery_camera_videos_bucket_name, ImageManager.INCLUDE_VIDEOS); } static private void gotoGallery(Activity activity, int windowTitleId, int mediaTypes) { Uri target = Images.Media.INTERNAL_CONTENT_URI.buildUpon().appendQueryParameter("bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build(); Intent intent = new Intent(Intent.ACTION_VIEW, target); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("windowTitle", activity.getString(windowTitleId)); intent.putExtra("mediaTypes", mediaTypes); // Request unspecified so that we match the current camera orientation rather than // matching the "flip orientation" preference. // Disabled because people don't care for it. Also it's // not as compelling now that we have implemented have quick orientation flipping. // intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, // android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Log.e(TAG, "Could not start gallery activity", e); } } static void addCapturePictureMenuItems(Menu menu, final Activity activity) { menu.add(0, MENU_CAPTURE_PICTURE, 1, R.string.capture_picture) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { activity.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { // Ignore exception } return true; } }) .setIcon(android.R.drawable.ic_menu_camera); } static void addCaptureVideoMenuItems(Menu menu, final Activity activity) { menu.add(0, MENU_CAPTURE_VIDEO, 2, R.string.capture_video) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { activity.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { // Ignore exception } return true; } }) .setIcon(R.drawable.ic_menu_camera_video_view); } static void addCaptureMenuItems(Menu menu, final Activity activity) { addCapturePictureMenuItems(menu, activity); addCaptureVideoMenuItems(menu, activity); } static MenuItem addFlipOrientation(Menu menu, final Activity activity, final SharedPreferences prefs) { // position 41 after rotate // D return menu .add(Menu.CATEGORY_SECONDARY, 304, 41, R.string.flip_orientation) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // Check what our actual orientation is int current = activity.getResources().getConfiguration().orientation; int newOrientation = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; if (current == Configuration.ORIENTATION_LANDSCAPE) { newOrientation = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; } SharedPreferences.Editor editor = prefs.edit(); editor.putInt("nuorientation", newOrientation); editor.commit(); requestOrientation(activity, prefs, true); return true; } }) .setIcon(android.R.drawable.ic_menu_always_landscape_portrait); } static void requestOrientation(Activity activity, SharedPreferences prefs) { requestOrientation(activity, prefs, false); } static private void requestOrientation(Activity activity, SharedPreferences prefs, boolean ignoreIntentExtra) { // Disable orientation for now. If it is set to SCREEN_ORIENTATION_SENSOR, // a duplicated orientation will be observed. return; } static void setFlipOrientationEnabled(Activity activity, MenuItem flipItem) { int keyboard = activity.getResources().getConfiguration().hardKeyboardHidden; flipItem.setEnabled(keyboard != android.content.res.Configuration.HARDKEYBOARDHIDDEN_NO); } public static String formatDuration(final Activity activity, int durationMs) { int duration = durationMs / 1000; int h = duration / 3600; int m = (duration - h * 3600) / 60; int s = duration - (h * 3600 + m * 60); String durationValue; if (h == 0) { durationValue = String.format( activity.getString(R.string.details_ms), m, s); } else { durationValue = String.format( activity.getString(R.string.details_hms), h, m, s); } return durationValue; } public static void showStorageToast(Activity activity) { showStorageToast(activity, calculatePicturesRemaining()); } public static void showStorageToast(Activity activity, int remaining) { String noStorageText = null; if (remaining == MenuHelper.NO_STORAGE_ERROR) { String state = Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING) { noStorageText = activity.getString(R.string.preparing_sd); } else { noStorageText = activity.getString(R.string.no_storage); } } else if (remaining < 1) { noStorageText = activity.getString(R.string.not_enough_space); } if (noStorageText != null) { Toast.makeText(activity, noStorageText, 5000).show(); } } public static int calculatePicturesRemaining() { try { if (!ImageManager.hasStorage()) { return NO_STORAGE_ERROR; } else { String storageDirectory = Environment.getExternalStorageDirectory().toString(); StatFs stat = new StatFs(storageDirectory); float remaining = ((float)stat.getAvailableBlocks() * (float)stat.getBlockSize()) / 400000F; return (int)remaining; } } catch (Exception ex) { // if we can't stat the filesystem then we don't know how many // pictures are remaining. it might be zero but just leave it // blank since we really don't know. return CANNOT_STAT_ERROR; } } } diff --git a/src/com/android/camera/VideoCamera.java b/src/com/android/camera/VideoCamera.java index 7f1b010..776755f 100644 --- a/src/com/android/camera/VideoCamera.java +++ b/src/com/android/camera/VideoCamera.java @@ -1,842 +1,847 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.location.LocationManager; import android.media.MediaRecorder; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.StatFs; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.MediaStore.Video; import android.text.format.DateFormat; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.MenuItem.OnMenuItemClickListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class VideoCamera extends Activity implements View.OnClickListener, ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback, MediaRecorder.OnErrorListener, MediaRecorder.OnInfoListener { private static final String TAG = "videocamera"; private static final boolean DEBUG = true; private static final boolean DEBUG_SUPPRESS_AUDIO_RECORDING = DEBUG && false; private static final int CLEAR_SCREEN_DELAY = 4; private static final int UPDATE_RECORD_TIME = 5; private static final int SCREEN_DELAY = 2 * 60 * 1000; private static final long NO_STORAGE_ERROR = -1L; private static final long CANNOT_STAT_ERROR = -2L; private static final long LOW_STORAGE_THRESHOLD = 512L * 1024L; private static final long SHARE_FILE_LENGTH_LIMIT = 3L * 1024L * 1024L; private static final int STORAGE_STATUS_OK = 0; private static final int STORAGE_STATUS_LOW = 1; private static final int STORAGE_STATUS_NONE = 2; public static final int MENU_SETTINGS = 6; public static final int MENU_GALLERY_PHOTOS = 7; public static final int MENU_GALLERY_VIDEOS = 8; public static final int MENU_SAVE_GALLERY_PHOTO = 34; public static final int MENU_SAVE_PLAY_VIDEO = 35; public static final int MENU_SAVE_SELECT_VIDEO = 36; public static final int MENU_SAVE_NEW_VIDEO = 37; SharedPreferences mPreferences; private static final float VIDEO_ASPECT_RATIO = 176.0f / 144.0f; VideoPreview mVideoPreview; SurfaceHolder mSurfaceHolder = null; ImageView mVideoFrame; private boolean mIsVideoCaptureIntent; // mLastPictureButton and mThumbController // are non-null only if isVideoCaptureIntent() is true; private ImageView mLastPictureButton; private ThumbnailController mThumbController; private static final int MAX_RECORDING_DURATION_MS = 10 * 60 * 1000; private int mStorageStatus = STORAGE_STATUS_OK; private MediaRecorder mMediaRecorder; private boolean mMediaRecorderRecording = false; private long mRecordingStartTime; // The video file that the hardware camera is about to record into // (or is recording into.) private String mCameraVideoFilename; private FileDescriptor mCameraVideoFileDescriptor; // The video file that has already been recorded, and that is being // examined by the user. private String mCurrentVideoFilename; private long mCurrentVideoFileLength = 0L; private Uri mCurrentVideoUri; private ContentValues mCurrentVideoValues; boolean mPausing = false; static ContentResolver mContentResolver; int mCurrentZoomIndex = 0; private ShutterButton mShutterButton; private TextView mRecordingTimeView; private boolean mRecordingTimeCountsDown = false; ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>(); View mPostPictureAlert; LocationManager mLocationManager = null; private Handler mHandler = new MainHandler(); /** This Handler is used to post message back onto the main thread of the application */ private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case CLEAR_SCREEN_DELAY: { clearScreenOnFlag(); break; } case UPDATE_RECORD_TIME: { if (mMediaRecorderRecording) { long now = SystemClock.uptimeMillis(); long delta = now - mRecordingStartTime; // Starting a minute before reaching the max duration // limit, we'll countdown the remaining time instead. boolean countdown_remaining_time = (delta >= MAX_RECORDING_DURATION_MS - 60000); if (countdown_remaining_time) { delta = Math.max(0, MAX_RECORDING_DURATION_MS - delta); } long seconds = (delta + 500) / 1000; // round to nearest long minutes = seconds / 60; long hours = minutes / 60; long remainderMinutes = minutes - (hours * 60); long remainderSeconds = seconds - (minutes * 60); String secondsString = Long.toString(remainderSeconds); if (secondsString.length() < 2) { secondsString = "0" + secondsString; } String minutesString = Long.toString(remainderMinutes); if (minutesString.length() < 2) { minutesString = "0" + minutesString; } String text = minutesString + ":" + secondsString; if (hours > 0) { String hoursString = Long.toString(hours); if (hoursString.length() < 2) { hoursString = "0" + hoursString; } text = hoursString + ":" + text; } mRecordingTimeView.setText(text); if (mRecordingTimeCountsDown != countdown_remaining_time) { // Avoid setting the color on every update, do it only // when it needs changing. mRecordingTimeCountsDown = countdown_remaining_time; int color = getResources().getColor( countdown_remaining_time ? R.color.recording_time_remaining_text : R.color.recording_time_elapsed_text); mRecordingTimeView.setTextColor(color); } // Work around a limitation of the T-Mobile G1: The T-Mobile // hardware blitter can't pixel-accurately scale and clip at the same time, // and the SurfaceFlinger doesn't attempt to work around this limitation. // In order to avoid visual corruption we must manually refresh the entire // surface view when changing any overlapping view's contents. mVideoPreview.invalidate(); mHandler.sendEmptyMessageDelayed(UPDATE_RECORD_TIME, 1000); } break; } default: Log.v(TAG, "Unhandled message: " + msg.what); break; } } }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_EJECT)) { updateAndShowStorageHint(false); stopVideoRecording(); initializeVideo(); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { updateAndShowStorageHint(true); initializeVideo(); } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) { // SD card unavailable // handled in ACTION_MEDIA_EJECT } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { Toast.makeText(VideoCamera.this, getResources().getString(R.string.wait), 5000); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { updateAndShowStorageHint(true); } } }; static private String createName(long dateTaken) { return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString(); } /** Called with the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mContentResolver = getContentResolver(); //setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.video_camera); mVideoPreview = (VideoPreview) findViewById(R.id.camera_preview); mVideoPreview.setAspectRatio(VIDEO_ASPECT_RATIO); // don't set mSurfaceHolder here. We have it set ONLY within // surfaceCreated / surfaceDestroyed, other parts of the code // assume that when it is set, the surface is also set. SurfaceHolder holder = mVideoPreview.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mPostPictureAlert = findViewById(R.id.post_picture_panel); int[] ids = new int[]{R.id.play, R.id.share, R.id.discard, R.id.cancel, R.id.attach}; for (int id : ids) { findViewById(id).setOnClickListener(this); } mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); mRecordingTimeView = (TextView) findViewById(R.id.recording_time); mVideoFrame = (ImageView) findViewById(R.id.video_frame); mIsVideoCaptureIntent = isVideoCaptureIntent(); if (!mIsVideoCaptureIntent) { mLastPictureButton = (ImageView) findViewById(R.id.last_picture_button); mLastPictureButton.setOnClickListener(this); Drawable frame = getResources().getDrawable(R.drawable.frame_thumbnail); mThumbController = new ThumbnailController(mLastPictureButton, frame, mContentResolver); mThumbController.loadData(ImageManager.getLastVideoThumbPath()); } } private void startShareVideoActivity() { if (mCurrentVideoFileLength > SHARE_FILE_LENGTH_LIMIT) { Toast.makeText(VideoCamera.this, R.string.too_large_to_attach, Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("video/3gpp"); intent.putExtra(Intent.EXTRA_STREAM, mCurrentVideoUri); try { startActivity(Intent.createChooser(intent, getText(R.string.sendVideo))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(VideoCamera.this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } public void onClick(View v) { switch (v.getId()) { case R.id.gallery: MenuHelper.gotoCameraVideoGallery(this); break; case R.id.attach: doReturnToCaller(true); break; case R.id.cancel: doReturnToCaller(false); break; case R.id.discard: { - discardCurrentVideoAndStartPreview(); + Runnable deleteCallback = new Runnable() { + public void run() { + discardCurrentVideoAndStartPreview(); + } + }; + MenuHelper.deleteVideo(this, deleteCallback); break; } case R.id.share: { startShareVideoActivity(); break; } case R.id.play: { doPlayCurrentVideo(); break; } case R.id.last_picture_button: { stopVideoRecordingAndShowAlert(); break; } } } public void onShutterButtonFocus(ShutterButton button, boolean pressed) { // Do nothing (everything happens in onShutterButtonClick). } public void onShutterButtonClick(ShutterButton button) { switch (button.getId()) { case R.id.shutter_button: if (mMediaRecorderRecording) { if (mIsVideoCaptureIntent) { stopVideoRecordingAndShowAlert(); } else { stopVideoRecordingAndGetThumbnail(); initializeVideo(); } } else if (isAlertVisible()) { if (mIsVideoCaptureIntent) { discardCurrentVideoAndStartPreview(); } else { hideAlertAndStartVideoRecording(); } } else { startVideoRecording(); } break; } } private void doPlayCurrentVideo() { Log.e(TAG, "Playing current video: " + mCurrentVideoUri); Intent intent = new Intent(Intent.ACTION_VIEW, mCurrentVideoUri); try { startActivity(intent); } catch (android.content.ActivityNotFoundException ex) { Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex); } } private void discardCurrentVideoAndStartPreview() { deleteCurrentVideo(); hideAlertAndStartPreview(); } private OnScreenHint mStorageHint; private void updateAndShowStorageHint(boolean mayHaveSd) { mStorageStatus = getStorageStatus(mayHaveSd); showStorageHint(); } private void showStorageHint() { String errorMessage = null; switch (mStorageStatus) { case STORAGE_STATUS_NONE: errorMessage = getString(R.string.no_storage); break; case STORAGE_STATUS_LOW: errorMessage = getString(R.string.spaceIsLow_content); } if (errorMessage != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, errorMessage); } else { mStorageHint.setText(errorMessage); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } private int getStorageStatus(boolean mayHaveSd) { long remaining = mayHaveSd ? getAvailableStorage() : NO_STORAGE_ERROR; if (remaining == NO_STORAGE_ERROR) { return STORAGE_STATUS_NONE; } return remaining < LOW_STORAGE_THRESHOLD ? STORAGE_STATUS_LOW : STORAGE_STATUS_OK; } @Override public void onResume() { super.onResume(); setScreenTimeoutLong(); mPausing = false; // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_EJECT); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); mStorageStatus = getStorageStatus(true); mHandler.postDelayed(new Runnable() { public void run() { showStorageHint(); } }, 200); initializeVideo(); } @Override public void onStop() { setScreenTimeoutSystemDefault(); super.onStop(); } @Override protected void onPause() { super.onPause(); // This is similar to what mShutterButton.performClick() does, // but not quite the same. if (mMediaRecorderRecording) { if (mIsVideoCaptureIntent) { stopVideoRecordingAndShowAlert(); } else { stopVideoRecordingAndGetThumbnail(); } } else { stopVideoRecording(); } mPausing = true; unregisterReceiver(mReceiver); setScreenTimeoutSystemDefault(); if (!mIsVideoCaptureIntent) { mThumbController.storeData(ImageManager.getLastVideoThumbPath()); } if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { setScreenTimeoutLong(); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mMediaRecorderRecording) { mShutterButton.performClick(); return true; } else if(isAlertVisible()) { hideAlertAndStartPreview(); return true; } break; case KeyEvent.KEYCODE_CAMERA: if (event.getRepeatCount() == 0) { mShutterButton.performClick(); return true; } break; case KeyEvent.KEYCODE_DPAD_CENTER: if (event.getRepeatCount() == 0) { mShutterButton.performClick(); return true; } break; case KeyEvent.KEYCODE_MENU: if (mMediaRecorderRecording) { mShutterButton.performClick(); return true; } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_CAMERA: mShutterButton.setPressed(false); return true; } return super.onKeyUp(keyCode, event); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { if (mPausing) { // We're pausing, the screen is off and we already stopped // video recording. We don't want to start the camera again // in this case in order to conserve power. // The fact that surfaceChanged is called _after_ an onPause appears // to be legitimate since in that case the lockscreen always returns // to portrait orientation possibly triggering the notification. return; } stopVideoRecording(); initializeVideo(); } public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; } public void surfaceDestroyed(SurfaceHolder holder) { mSurfaceHolder = null; } void gotoGallery() { MenuHelper.gotoCameraVideoGallery(this); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); for (int i = 1; i <= MenuHelper.MENU_ITEM_MAX; i++) { if (i != MenuHelper.GENERIC_ITEM) { menu.setGroupVisible(i, false); } } menu.setGroupVisible(MenuHelper.VIDEO_MODE_ITEM, true); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (mIsVideoCaptureIntent) { // No options menu for attach mode. return false; } else { addBaseMenuItems(menu); MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL & ~MenuHelper.INCLUDE_ROTATE_MENU, false, VideoCamera.this, mHandler, // Handler for deletion new Runnable() { public void run() { // What do we do here? // mContentResolver.delete(uri, null, null); } }, new MenuHelper.MenuInvoker() { public void run(final MenuHelper.MenuCallback cb) { } }); MenuItem gallery = menu.add(MenuHelper.IMAGE_SAVING_ITEM, MENU_SAVE_GALLERY_PHOTO, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); } return true; } private boolean isVideoCaptureIntent() { String action = getIntent().getAction(); return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action)); } private void doReturnToCaller(boolean success) { Intent resultIntent = new Intent(); int resultCode; if (success) { resultCode = RESULT_OK; resultIntent.setData(mCurrentVideoUri); } else { resultCode = RESULT_CANCELED; } setResult(resultCode, resultIntent); finish(); } /** * Returns * @return number of bytes available, or an ERROR code. */ private static long getAvailableStorage() { try { if (!ImageManager.hasStorage()) { return NO_STORAGE_ERROR; } else { String storageDirectory = Environment.getExternalStorageDirectory().toString(); StatFs stat = new StatFs(storageDirectory); return ((long)stat.getAvailableBlocks() * (long)stat.getBlockSize()); } } catch (Exception ex) { // if we can't stat the filesystem then we don't know how many // free bytes exist. It might be zero but just leave it // blank since we really don't know. return CANNOT_STAT_ERROR; } } private void cleanupEmptyFile() { if (mCameraVideoFilename != null) { File f = new File(mCameraVideoFilename); if (f.length() == 0 && f.delete()) { Log.v(TAG, "Empty video file deleted: " + mCameraVideoFilename); mCameraVideoFilename = null; } } } // initializeVideo() starts preview and prepare media recorder. // Returns false if initializeVideo fails private boolean initializeVideo() { Log.v(TAG, "initializeVideo"); // We will call initializeVideo() again when the alert is hidden. if (isAlertVisible()) return false; Intent intent = getIntent(); Bundle myExtras = intent.getExtras(); if (mIsVideoCaptureIntent && myExtras != null) { Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); if (saveUri != null) { try { mCameraVideoFileDescriptor = mContentResolver. openFileDescriptor(saveUri, "rw").getFileDescriptor(); mCurrentVideoUri = saveUri; } catch (java.io.FileNotFoundException ex) { // invalid uri Log.e(TAG, ex.toString()); } } } releaseMediaRecorder(); if (mSurfaceHolder == null) { Log.v(TAG, "SurfaceHolder is null"); return false; } mMediaRecorder = new MediaRecorder(); if (DEBUG_SUPPRESS_AUDIO_RECORDING) { Log.v(TAG, "DEBUG_SUPPRESS_AUDIO_RECORDING is true."); } else { mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); } mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mMediaRecorder.setMaxDuration(MAX_RECORDING_DURATION_MS); if (mStorageStatus != STORAGE_STATUS_OK) { mMediaRecorder.setOutputFile("/dev/null"); } else { // We try Uri in intent first. If it doesn't work, use our own instead. if (mCameraVideoFileDescriptor != null) { mMediaRecorder.setOutputFile(mCameraVideoFileDescriptor); } else { createVideoPath(); mMediaRecorder.setOutputFile(mCameraVideoFilename); } } boolean videoQualityHigh = getBooleanPreference(CameraSettings.KEY_VIDEO_QUALITY, CameraSettings.DEFAULT_VIDEO_QUALITY_VALUE); if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) { int extraVideoQuality = intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); videoQualityHigh = (extraVideoQuality > 0); } // Use the same frame rate for both, since internally // if the frame rate is too large, it can cause camera to become // unstable. We need to fix the MediaRecorder to disable the support // of setting frame rate for now. mMediaRecorder.setVideoFrameRate(20); if (videoQualityHigh) { mMediaRecorder.setVideoSize(352,288); } else { mMediaRecorder.setVideoSize(176,144); } mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); if (!DEBUG_SUPPRESS_AUDIO_RECORDING) { mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); } mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); long remaining = getAvailableStorage(); // remaining >= LOW_STORAGE_THRESHOLD at this point, reserve a quarter // of that to make it more likely that recording can complete successfully. try { mMediaRecorder.setMaxFileSize(remaining - LOW_STORAGE_THRESHOLD / 4); } catch (RuntimeException exception) { // We are going to ignore failure of setMaxFileSize here, as // a) The composer selected may simply not support it, or // b) The underlying media framework may not handle 64-bit range // on the size restriction. } try { mMediaRecorder.prepare(); } catch (IOException exception) { Log.e(TAG, "prepare failed for " + mCameraVideoFilename); releaseMediaRecorder(); // TODO: add more exception handling logic here return false; } mMediaRecorderRecording = false; if (!mIsVideoCaptureIntent && !mThumbController.isUriValid()) { updateLastVideo(); } if (!mIsVideoCaptureIntent) { mThumbController.updateDisplayIfNeeded(); } return true; } private void releaseMediaRecorder() { Log.v(TAG, "Releasing media recorder."); if (mMediaRecorder != null) { cleanupEmptyFile(); mMediaRecorder.reset(); mMediaRecorder.release(); mMediaRecorder = null; } } private int getIntPreference(String key, int defaultValue) { String s = mPreferences.getString(key, ""); int result = defaultValue; try { result = Integer.parseInt(s); } catch (NumberFormatException e) { // Ignore, result is already the default value. } return result; } private boolean getBooleanPreference(String key, boolean defaultValue) { return getIntPreference(key, defaultValue ? 1 : 0) != 0; } private void createVideoPath() { long dateTaken = System.currentTimeMillis(); String title = createName(dateTaken); String displayName = title + ".3gp"; // Used when emailing. String cameraDirPath = ImageManager.CAMERA_IMAGE_BUCKET_NAME; File cameraDir = new File(cameraDirPath); cameraDir.mkdirs(); SimpleDateFormat dateFormat = new SimpleDateFormat( getString(R.string.video_file_name_format)); Date date = new Date(dateTaken); String filepart = dateFormat.format(date); String filename = cameraDirPath + "/" + filepart + ".3gp"; ContentValues values = new ContentValues(7); values.put(Video.Media.TITLE, title); values.put(Video.Media.DISPLAY_NAME, displayName); values.put(Video.Media.DESCRIPTION, ""); values.put(Video.Media.DATE_TAKEN, dateTaken); values.put(Video.Media.MIME_TYPE, "video/3gpp"); values.put(Video.Media.DATA, filename); mCameraVideoFilename = filename; Log.v(TAG, "Current camera video filename: " + mCameraVideoFilename); mCurrentVideoValues = values; } private void registerVideo() { if (mCameraVideoFileDescriptor == null) { Uri videoTable = Uri.parse("content://media/external/video/media"); mCurrentVideoUri = mContentResolver.insert(videoTable, mCurrentVideoValues); Log.v(TAG, "Current video URI: " + mCurrentVideoUri); } mCurrentVideoValues = null; diff --git a/src/com/android/camera/ViewImage.java b/src/com/android/camera/ViewImage.java index 1376172..b8379d2 100644 --- a/src/com/android/camera/ViewImage.java +++ b/src/com/android/camera/ViewImage.java @@ -1,910 +1,910 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.util.Random; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.util.AttributeSet; import android.util.Config; import android.util.Log; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import android.widget.Scroller; import android.widget.Toast; import android.widget.ZoomButtonsController; import com.android.camera.ImageManager.IImage; public class ViewImage extends Activity implements View.OnClickListener { private static final String TAG = "ViewImage"; private static final int TOUCH_AREA_WIDTH = 60; private ImageGetter mGetter; static final boolean sSlideShowHidesStatusBar = true; // Choices for what adjacents to load. static private final int[] sOrder_adjacents = new int[] { 0, 1, -1 }; static private final int[] sOrder_slideshow = new int[] { 0 }; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { } }; private Random mRandom = new Random(System.currentTimeMillis()); private int [] mShuffleOrder; private boolean mUseShuffleOrder = false; private boolean mSlideShowLoop = false; private static final int MODE_NORMAL = 1; private static final int MODE_SLIDESHOW = 2; private int mMode = MODE_NORMAL; private boolean mFullScreenInNormalMode; private boolean mShowActionIcons; private View mActionIconPanel; private View mShutterButton; private boolean mSortAscending = false; private int mSlideShowInterval; private int mLastSlideShowImage; private boolean mFirst = true; private int mCurrentPosition = 0; private boolean mLayoutComplete = false; // represents which style animation to use private int mAnimationIndex; private Animation [] mSlideShowInAnimation; private Animation [] mSlideShowOutAnimation; private SharedPreferences mPrefs; private View mNextImageView, mPrevImageView; private Animation mHideNextImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mHidePrevImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mShowNextImageViewAnimation = new AlphaAnimation(0F, 1F); private Animation mShowPrevImageViewAnimation = new AlphaAnimation(0F, 1F); static final int sPadding = 20; static final int sHysteresis = sPadding * 2; static final int sBaseScrollDuration = 1000; // ms private ImageManager.IImageList mAllImages; private int mSlideShowImageCurrent = 0; private ImageViewTouch [] mSlideShowImageViews = new ImageViewTouch[2]; private GestureDetector mGestureDetector; private ZoomButtonsController mZoomButtonsController; // Array of image views. The center view is the one the user is focused // on. The one at the zeroth position and the second position reflect // the images to the left/right of the center image. private ImageViewTouch[] mImageViews = new ImageViewTouch[3]; // Container for the three image views. This guy can be "scrolled" // to reveal the image prior to and after the center image. private ScrollHandler mScroller; private MenuHelper.MenuItemsResult mImageMenuRunnable; private Runnable mDismissOnScreenControlsRunnable; private boolean mCameraReviewMode; private int mCurrentOrientation; private void updateNextPrevControls() { boolean showPrev = mCurrentPosition > 0; boolean showNext = mCurrentPosition < mAllImages.getCount() - 1; boolean prevIsVisible = mPrevImageView.getVisibility() == View.VISIBLE; boolean nextIsVisible = mNextImageView.getVisibility() == View.VISIBLE; if (showPrev && !prevIsVisible) { Animation a = mShowPrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.VISIBLE); } else if (!showPrev && prevIsVisible) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.GONE); } if (showNext && !nextIsVisible) { Animation a = mShowNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.VISIBLE); } else if (!showNext && nextIsVisible) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.GONE); } } private void showOnScreenControls() { updateNextPrevControls(); updateZoomButtonsEnabled(); mZoomButtonsController.setVisible(true); scheduleDismissOnScreenControls(); } @Override public boolean dispatchTouchEvent(MotionEvent m) { boolean sup = super.dispatchTouchEvent(m); if (sup == false) { if (mMode == MODE_SLIDESHOW) { mSlideShowImageViews[mSlideShowImageCurrent].handleTouchEvent(m); } else if (mMode == MODE_NORMAL){ mImageViews[1].handleTouchEvent(m); } return true; } return true; } private void scheduleDismissOnScreenControls() { mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); mHandler.postDelayed(mDismissOnScreenControlsRunnable, 1500); } private void updateZoomButtonsEnabled() { ImageViewTouch imageView = mImageViews[1]; float scale = imageView.getScale(); mZoomButtonsController.setZoomInEnabled(scale < imageView.mMaxZoom); mZoomButtonsController.setZoomOutEnabled(scale > 1); } @Override protected void onDestroy() { // This is necessary to make the ZoomButtonsController unregister // its configuration change receiver. if (mZoomButtonsController != null) { mZoomButtonsController.setVisible(false); } super.onDestroy(); } private void setupZoomButtonController(View rootView) { mGestureDetector = new GestureDetector(this, new MyGestureListener()); mZoomButtonsController = new ZoomButtonsController(rootView); mZoomButtonsController.setAutoDismissed(false); mZoomButtonsController.setOnZoomListener( new ZoomButtonsController.OnZoomListener() { public void onVisibilityChanged(boolean visible) { if (visible) { updateZoomButtonsEnabled(); } } public void onZoom(boolean zoomIn) { if (zoomIn) { mImageViews[1].zoomIn(); } else { mImageViews[1].zoomOut(); } showOnScreenControls(); } }); } private class MyGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { ImageViewTouch imageView = mImageViews[1]; if (imageView.getScale() > 1F) { imageView.postTranslate(-distanceX, -distanceY, sUseBounce); imageView.center(true, true, false); } showOnScreenControls(); return true; } @Override public boolean onSingleTapUp(MotionEvent e) { int viewWidth = mImageViews[1].getWidth(); int x = (int) e.getX(); int y = (int) e.getY(); if (x < TOUCH_AREA_WIDTH) { moveNextOrPrevious(-1); } else if (x > viewWidth - TOUCH_AREA_WIDTH) { moveNextOrPrevious(1); } setMode(MODE_NORMAL); showOnScreenControls(); return true; } } private void setupDismissOnScreenControlRunnable() { mDismissOnScreenControlsRunnable = new Runnable() { public void run() { if (!mShowActionIcons) { if (mNextImageView.getVisibility() == View.VISIBLE) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.INVISIBLE); } if (mPrevImageView.getVisibility() == View.VISIBLE) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.INVISIBLE); } mZoomButtonsController.setVisible(false); } } }; } private boolean isPickIntent() { String action = getIntent().getAction(); return (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)); } private static final boolean sUseBounce = false; private static final boolean sAnimateTransitions = false; public static class ImageViewTouch extends ImageViewTouchBase { private ViewImage mViewImage; private boolean mEnableTrackballScroll; public ImageViewTouch(Context context) { super(context); mViewImage = (ViewImage) context; } public ImageViewTouch(Context context, AttributeSet attrs) { super(context, attrs); mViewImage = (ViewImage) context; } public void setEnableTrackballScroll(boolean enable) { mEnableTrackballScroll = enable; } protected void postTranslate(float dx, float dy, boolean bounceOK) { super.postTranslate(dx, dy); if (dx != 0F || dy != 0F) { mViewImage.showOnScreenControls(); } if (!sUseBounce) { center(true, false, false); } } protected ScrollHandler scrollHandler() { return mViewImage.mScroller; } public boolean handleTouchEvent(MotionEvent m) { return mViewImage.mGestureDetector.onTouchEvent(m); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Don't respond to arrow keys if trackball scrolling is not enabled if (!mEnableTrackballScroll) { if ((keyCode >= KeyEvent.KEYCODE_DPAD_UP) && (keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT)) { return super.onKeyDown(keyCode, event); } } int current = mViewImage.mCurrentPosition; int nextImagePos = -2; // default no next image try { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: { if (mViewImage.isPickIntent()) { ImageManager.IImage img = mViewImage.mAllImages.getImageAt(mViewImage.mCurrentPosition); mViewImage.setResult(RESULT_OK, new Intent().setData(img.fullSizeImageUri())); mViewImage.finish(); } break; } case KeyEvent.KEYCODE_DPAD_LEFT: { panBy(sPanRate, 0); int maxOffset = (current == 0) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(true, maxOffset)) { nextImagePos = current - 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_RIGHT: { panBy(-sPanRate, 0); int maxOffset = (current == mViewImage.mAllImages.getCount() - 1) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(false, maxOffset)) { nextImagePos = current + 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_UP: { panBy(0, sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DPAD_DOWN: { panBy(0, -sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DEL: - MenuHelper.displayDeleteDialog(mViewImage, - mViewImage.mDeletePhotoRunnable, true); + MenuHelper.deletePhoto( + mViewImage, mViewImage.mDeletePhotoRunnable); break; } } finally { if (nextImagePos >= 0 && nextImagePos < mViewImage.mAllImages.getCount()) { synchronized (mViewImage) { mViewImage.setMode(MODE_NORMAL); mViewImage.setImage(nextImagePos); } } else if (nextImagePos != -2) { center(true, true, false); } } return super.onKeyDown(keyCode, event); } protected boolean isShiftedToNextImage(boolean left, int maxOffset) { boolean retval; Bitmap bitmap = mBitmapDisplayed; Matrix m = getImageViewMatrix(); if (left) { float [] t1 = new float[] { 0, 0 }; m.mapPoints(t1); retval = t1[0] > maxOffset; } else { int width = bitmap != null ? bitmap.getWidth() : getWidth(); float [] t1 = new float[] { width, 0 }; m.mapPoints(t1); retval = t1[0] + maxOffset < getWidth(); } return retval; } protected void scrollX(int deltaX) { scrollHandler().scrollBy(deltaX, 0); } protected int getScrollOffset() { return scrollHandler().getScrollX(); } } static class ScrollHandler extends LinearLayout { private Runnable mFirstLayoutCompletedCallback = null; private Scroller mScrollerHelper; private int mWidth = -1; public ScrollHandler(Context context) { super(context); mScrollerHelper = new Scroller(context); } public ScrollHandler(Context context, AttributeSet attrs) { super(context, attrs); mScrollerHelper = new Scroller(context); } public void setLayoutCompletedCallback(Runnable r) { mFirstLayoutCompletedCallback = r; } public void startScrollTo(int newX, int newY) { int oldX = getScrollX(); int oldY = getScrollY(); int deltaX = newX - oldX; int deltaY = newY - oldY; if (mWidth == -1) { mWidth = findViewById(R.id.image2).getWidth(); } int viewWidth = mWidth; int duration = viewWidth > 0 ? sBaseScrollDuration * Math.abs(deltaX) / viewWidth : 0; mScrollerHelper.startScroll(oldX, oldY, deltaX, deltaY, duration); invalidate(); } @Override public void computeScroll() { if (mScrollerHelper.computeScrollOffset()) { scrollTo(mScrollerHelper.getCurrX(), mScrollerHelper.getCurrY()); postInvalidate(); // So we draw again } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int width = right - left; int x = 0; for (View v : new View[] { findViewById(R.id.image1), findViewById(R.id.image2), findViewById(R.id.image3) }) { v.layout(x, 0, x + width, bottom); x += (width + sPadding); } findViewById(R.id.padding1).layout(width, 0, width + sPadding, bottom); findViewById(R.id.padding2).layout(width+sPadding+width, 0, width+sPadding+width+sPadding, bottom); if (changed) { if (mFirstLayoutCompletedCallback != null) { mFirstLayoutCompletedCallback.run(); } } } } private void animateScrollTo(int xNew, int yNew) { mScroller.startScrollTo(xNew, yNew); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (! mCameraReviewMode) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.slide_show); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { setMode(MODE_SLIDESHOW); mLastSlideShowImage = mCurrentPosition; loadNextImage(mCurrentPosition, 0, true); return true; } }); item.setIcon(android.R.drawable.ic_menu_slideshow); } final SelectedImageGetter selectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return mAllImages.getImageAt(mCurrentPosition); } public Uri getCurrentImageUri() { return mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); } }; mImageMenuRunnable = MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL, true, ViewImage.this, mHandler, mDeletePhotoRunnable, new MenuHelper.MenuInvoker() { public void run(MenuHelper.MenuCallback cb) { setMode(MODE_NORMAL); cb.run(selectedImageGetter.getCurrentImageUri(), selectedImageGetter.getCurrentImage()); for (ImageViewTouchBase iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } setImage(mCurrentPosition); } }); if (true) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 1000, R.string.camerasettings); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent preferences = new Intent(); preferences.setClass(ViewImage.this, GallerySettings.class); startActivity(preferences); return true; } }); item.setAlphabeticShortcut('p'); item.setIcon(android.R.drawable.ic_menu_preferences); } // Hidden menu just so the shortcut will bring up the zoom controls menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.camerasettings) // the string resource is a placeholder .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { showOnScreenControls(); return true; } }) .setAlphabeticShortcut('z') .setVisible(false); return true; } protected Runnable mDeletePhotoRunnable = new Runnable() { public void run() { mAllImages.removeImageAt(mCurrentPosition); if (mAllImages.getCount() == 0) { finish(); } else { if (mCurrentPosition == mAllImages.getCount()) { mCurrentPosition -= 1; } } for (ImageViewTouchBase iv: mImageViews) { iv.setImageBitmapResetBase(null, true, true); } setImage(mCurrentPosition); } }; @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); setMode(MODE_NORMAL); if (mImageMenuRunnable != null) { mImageMenuRunnable.gettingReadyToOpen(menu, mAllImages.getImageAt(mCurrentPosition)); } return true; } @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean changed = mCurrentOrientation != newConfig.orientation; mCurrentOrientation = newConfig.orientation; if (changed) { if (mGetter != null) { // kill off any background image fetching mGetter.cancelCurrent(); mGetter.stop(); } makeGetter(); mFirst = true; // clear off the current set of images since we need to reload // them at the right size for (ImageViewTouchBase iv: mImageViews) { iv.clear(); } MenuHelper.requestOrientation(this, mPrefs); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { boolean b = super.onMenuItemSelected(featureId, item); if (mImageMenuRunnable != null) mImageMenuRunnable.aboutToCall(item, mAllImages.getImageAt(mCurrentPosition)); return b; } /* * Here's the loading strategy. For any given image, load the thumbnail * into memory and post a callback to display the resulting bitmap. * * Then proceed to load the full image bitmap. Three things can * happen at this point: * * 1. the image fails to load because the UI thread decided * to move on to a different image. This "cancellation" happens * by virtue of the UI thread closing the stream containing the * image being decoded. BitmapFactory.decodeStream returns null * in this case. * * 2. the image loaded successfully. At that point we post * a callback to the UI thread to actually show the bitmap. * * 3. when the post runs it checks to see if the image that was * loaded is still the one we want. The UI may have moved on * to some other image and if so we just drop the newly loaded * bitmap on the floor. */ interface ImageGetterCallback { public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb); public boolean wantsThumbnail(int pos, int offset); public boolean wantsFullImage(int pos, int offset); public int fullImageSizeToUse(int pos, int offset); public void completed(boolean wasCanceled); public int [] loadOrder(); } class ImageGetter { // The thread which does the work. private Thread mGetterThread; // The base position that's being retrieved. The actual images retrieved // are this base plus each of the offets. private int mCurrentPosition = -1; // The callback to invoke for each image. private ImageGetterCallback mCB; // This is the loader cancelable that gets set while we're loading an image. // If we change position we can cancel the current load using this. private ImageManager.IGetBitmap_cancelable mLoad; // True if we're canceling the current load. private boolean mCancelCurrent = false; // True when the therad should exit. private boolean mDone = false; // True when the loader thread is waiting for work. private boolean mReady = false; private void cancelCurrent() { synchronized (this) { if (!mReady) { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { if (Config.LOGV) Log.v(TAG, "canceling load object"); load.cancel(); } mCancelCurrent = false; } } } public ImageGetter() { mGetterThread = new Thread(new Runnable() { private Runnable callback(final int position, final int offset, final boolean isThumb, final Bitmap bitmap) { return new Runnable() { public void run() { // check for inflight callbacks that aren't applicable any longer // before delivering them if (!isCanceled() && position == mCurrentPosition) { mCB.imageLoaded(position, offset, bitmap, isThumb); } else { if (bitmap != null) bitmap.recycle(); } } }; } private Runnable completedCallback(final boolean wasCanceled) { return new Runnable() { public void run() { mCB.completed(wasCanceled); } }; } public void run() { int lastPosition = -1; while (!mDone) { synchronized (ImageGetter.this) { mReady = true; ImageGetter.this.notify(); if (mCurrentPosition == -1 || lastPosition == mCurrentPosition) { try { ImageGetter.this.wait(); } catch (InterruptedException ex) { continue; } } lastPosition = mCurrentPosition; mReady = false; } if (lastPosition != -1) { int imageCount = mAllImages.getCount(); int [] order = mCB.loadOrder(); for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (image == null || isCanceled()) { break; } if (mCB.wantsThumbnail(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting THUMBNAIL load at offset " + offset); Bitmap b = image.thumbBitmap(); mHandler.post(callback(lastPosition, offset, true, b)); } } } for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (mCB.wantsFullImage(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting FULL IMAGE load at offset " + offset); int sizeToUse = mCB.fullImageSizeToUse(lastPosition, offset); if (image != null && !isCanceled()) { mLoad = image.fullSizeBitmap_cancelable(sizeToUse); } if (mLoad != null) { long t1; if (Config.LOGV) t1 = System.currentTimeMillis(); // The return value could be null if the // bitmap is too big, or we cancelled it. Bitmap b = mLoad.get(); if (Config.LOGV && b != null) { long t2 = System.currentTimeMillis(); Log.v(TAG, "loading full image for " + image.fullSizeImageUri() + " with requested size " + sizeToUse + " took " + (t2-t1) + " and returned a bitmap with size " + b.getWidth() + " / " + b.getHeight()); } mLoad = null; if (b != null) { if (isCanceled()) { b.recycle(); } else { mHandler.post(callback(lastPosition, offset, false, b)); } } } } } } mHandler.post(completedCallback(isCanceled())); } } } }); mGetterThread.setName("ImageGettter"); mGetterThread.start(); } private boolean isCanceled() { synchronized (this) { return mCancelCurrent; } } public void setPosition(int position, ImageGetterCallback cb) { synchronized (this) { if (!mReady) { try { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { load.cancel(); } // if the thread is waiting before loading the full size // image then this will free it up ImageGetter.this.notify(); ImageGetter.this.wait(); mCancelCurrent = false; } catch (InterruptedException ex) { // not sure what to do here } } } mCurrentPosition = position; mCB = cb; synchronized (this) { ImageGetter.this.notify(); } } public void stop() { synchronized (this) { mDone = true; ImageGetter.this.notify(); } try { mGetterThread.join(); } catch (InterruptedException ex) { } } } private void setImage(int pos) { if (!mLayoutComplete) { return; } final boolean left = (pos == mCurrentPosition - 1); final boolean right = (pos == mCurrentPosition + 1); mCurrentPosition = pos; ImageViewTouchBase current = mImageViews[1]; current.mSuppMatrix.reset(); current.setImageMatrix(current.getImageViewMatrix()); if (false) { Log.v(TAG, "before..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } if (!mFirst) { if (left) { mImageViews[2].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[0]); } else if (right) { mImageViews[0].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[2]); @@ -973,578 +973,578 @@ public class ViewImage extends Activity implements View.OnClickListener public int [] loadOrder() { return sOrder_adjacents; } public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb) { ImageViewTouchBase ivt = mImageViews[1 + offset]; if (offset == 0) updateZoomButtonsEnabled(); ivt.setImageBitmapResetBase(bitmap, isThumb, isThumb); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { mGetter.setPosition(pos, cb); } showOnScreenControls(); } @Override public void onCreate(Bundle instanceState) { super.onCreate(instanceState); Intent intent = getIntent(); mCameraReviewMode = intent.getBooleanExtra("com.android.camera.ReviewMode", false); mFullScreenInNormalMode = intent.getBooleanExtra(MediaStore.EXTRA_FULL_SCREEN, true); mShowActionIcons = intent.getBooleanExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, false); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mCurrentOrientation = getResources().getConfiguration().orientation; setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.viewimage); mImageViews[0] = (ImageViewTouch) findViewById(R.id.image1); mImageViews[1] = (ImageViewTouch) findViewById(R.id.image2); mImageViews[2] = (ImageViewTouch) findViewById(R.id.image3); for(ImageViewTouch v : mImageViews) { v.setEnableTrackballScroll(!mShowActionIcons); } mScroller = (ScrollHandler)findViewById(R.id.scroller); makeGetter(); mAnimationIndex = -1; mSlideShowInAnimation = new Animation[] { makeInAnimation(R.anim.transition_in), makeInAnimation(R.anim.slide_in), makeInAnimation(R.anim.slide_in_vertical), }; mSlideShowOutAnimation = new Animation[] { makeOutAnimation(R.anim.transition_out), makeOutAnimation(R.anim.slide_out), makeOutAnimation(R.anim.slide_out_vertical), }; mSlideShowImageViews[0] = (ImageViewTouch) findViewById(R.id.image1_slideShow); mSlideShowImageViews[1] = (ImageViewTouch) findViewById(R.id.image2_slideShow); for (ImageViewTouch v : mSlideShowImageViews) { v.setImageBitmapResetBase(null, true, true); v.setVisibility(View.INVISIBLE); v.setEnableTrackballScroll(!mShowActionIcons); } mActionIconPanel = findViewById(R.id.action_icon_panel); { int[] pickIds = {R.id.attach, R.id.cancel}; int[] normalIds = {R.id.gallery, R.id.setas, R.id.share, R.id.discard}; int[] hideIds = pickIds; int[] connectIds = normalIds; if (isPickIntent()) { hideIds = normalIds; connectIds = pickIds; } for(int id : hideIds) { mActionIconPanel.findViewById(id).setVisibility(View.GONE); } for(int id : connectIds) { View view = mActionIconPanel.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } mShutterButton = findViewById(R.id.shutter_button); mShutterButton.setOnClickListener(this); Uri uri = getIntent().getData(); if (Config.LOGV) Log.v(TAG, "uri is " + uri); if (instanceState != null) { if (instanceState.containsKey("uri")) { uri = Uri.parse(instanceState.getString("uri")); } } if (uri == null) { finish(); return; } init(uri); Bundle b = getIntent().getExtras(); boolean slideShow = b != null ? b.getBoolean("slideshow", false) : false; if (slideShow) { setMode(MODE_SLIDESHOW); loadNextImage(mCurrentPosition, 0, true); } else { if (mFullScreenInNormalMode) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } } setupZoomButtonController(findViewById(R.id.rootLayout)); setupDismissOnScreenControlRunnable(); mNextImageView = findViewById(R.id.next_image); mPrevImageView = findViewById(R.id.prev_image); mNextImageView.setOnClickListener(this); mPrevImageView.setOnClickListener(this); if (mShowActionIcons) { mNextImageView.setFocusable(true); mPrevImageView.setFocusable(true); } setOrientation(); } private void setOrientation() { Intent intent = getIntent(); if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); if (orientation != getRequestedOrientation()) { setRequestedOrientation(orientation); } } else { MenuHelper.requestOrientation(this, mPrefs); } } private Animation makeInAnimation(int id) { Animation inAnimation = AnimationUtils.loadAnimation(this, id); return inAnimation; } private Animation makeOutAnimation(int id) { Animation outAnimation = AnimationUtils.loadAnimation(this, id); return outAnimation; } private void setMode(int mode) { if (mMode == mode) { return; } findViewById(R.id.slideShowContainer).setVisibility(mode == MODE_SLIDESHOW ? View.VISIBLE : View.GONE); findViewById(R.id.abs) .setVisibility(mode == MODE_NORMAL ? View.VISIBLE : View.GONE); Window win = getWindow(); mMode = mode; if (mode == MODE_SLIDESHOW) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (sSlideShowHidesStatusBar) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } for (ImageViewTouchBase ivt: mImageViews) { ivt.clear(); } mActionIconPanel.setVisibility(View.GONE); mShutterButton.setVisibility(View.GONE); if (false) { Log.v(TAG, "current is " + this.mSlideShowImageCurrent); this.mSlideShowImageViews[0].dump(); this.mSlideShowImageViews[0].dump(); } findViewById(R.id.slideShowContainer).getRootView().requestLayout(); mUseShuffleOrder = mPrefs.getBoolean("pref_gallery_slideshow_shuffle_key", false); mSlideShowLoop = mPrefs.getBoolean("pref_gallery_slideshow_repeat_key", false); try { mAnimationIndex = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_transition_key", "0")); } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mAnimationIndex = 0; } try { mSlideShowInterval = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_interval_key", "3")) * 1000; } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mSlideShowInterval = 3000; } if (Config.LOGV) { Log.v(TAG, "read prefs... shuffle: " + mUseShuffleOrder); Log.v(TAG, "read prefs... loop: " + mSlideShowLoop); Log.v(TAG, "read prefs... animidx: " + mAnimationIndex); Log.v(TAG, "read prefs... interval: " + mSlideShowInterval); } if (mUseShuffleOrder) { generateShuffleOrder(); } } else { if (Config.LOGV) Log.v(TAG, "slide show mode off, mCurrentPosition == " + mCurrentPosition); win.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (mFullScreenInNormalMode) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mGetter != null) mGetter.cancelCurrent(); if (sSlideShowHidesStatusBar) { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } ImageViewTouchBase dst = mImageViews[1]; dst.mLastXTouchPos = -1; dst.mLastYTouchPos = -1; for (ImageViewTouchBase ivt: mSlideShowImageViews) { ivt.clear(); } mShuffleOrder = null; // mGetter null is a proxy for being paused if (mGetter != null) { mFirst = true; // don't animate setImage(mCurrentPosition); } } // this line shouldn't be necessary but the view hierarchy doesn't // seem to realize that the window layout changed mScroller.requestLayout(); } private void generateShuffleOrder() { if (mShuffleOrder == null || mShuffleOrder.length != mAllImages.getCount()) { mShuffleOrder = new int[mAllImages.getCount()]; } for (int i = 0; i < mShuffleOrder.length; i++) { mShuffleOrder[i] = i; } for (int i = mShuffleOrder.length - 1; i > 0; i--) { int r = mRandom.nextInt(i); int tmp = mShuffleOrder[r]; mShuffleOrder[r] = mShuffleOrder[i]; mShuffleOrder[i] = tmp; } } private void loadNextImage(final int requestedPos, final long delay, final boolean firstCall) { if (firstCall && mUseShuffleOrder) { generateShuffleOrder(); } final long targetDisplayTime = System.currentTimeMillis() + delay; ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { } public boolean wantsThumbnail(int pos, int offset) { return true; } public boolean wantsFullImage(int pos, int offset) { return false; } public int [] loadOrder() { return sOrder_slideshow; } public int fullImageSizeToUse(int pos, int offset) { return 480; // TODO compute this } public void imageLoaded(final int pos, final int offset, final Bitmap bitmap, final boolean isThumb) { long timeRemaining = Math.max(0, targetDisplayTime - System.currentTimeMillis()); mHandler.postDelayed(new Runnable() { public void run() { if (mMode == MODE_NORMAL) { return; } ImageViewTouchBase oldView = mSlideShowImageViews[mSlideShowImageCurrent]; if (++mSlideShowImageCurrent == mSlideShowImageViews.length) { mSlideShowImageCurrent = 0; } ImageViewTouchBase newView = mSlideShowImageViews[mSlideShowImageCurrent]; newView.setVisibility(View.VISIBLE); newView.setImageBitmapResetBase(bitmap, isThumb, isThumb); newView.bringToFront(); int animation = 0; if (mAnimationIndex == -1) { int n = mRandom.nextInt(mSlideShowInAnimation.length); animation = n; } else { animation = mAnimationIndex; } Animation aIn = mSlideShowInAnimation[animation]; newView.setAnimation(aIn); newView.setVisibility(View.VISIBLE); aIn.startNow(); Animation aOut = mSlideShowOutAnimation[animation]; oldView.setVisibility(View.INVISIBLE); oldView.setAnimation(aOut); aOut.startNow(); mCurrentPosition = requestedPos; mHandler.post(new Runnable() { public void run() { if (mCurrentPosition == mLastSlideShowImage && !firstCall) { if (mSlideShowLoop) { if (mUseShuffleOrder) { generateShuffleOrder(); } } else { setMode(MODE_NORMAL); return; } } if (Config.LOGV) Log.v(TAG, "mCurrentPosition is now " + mCurrentPosition); loadNextImage((mCurrentPosition + 1) % mAllImages.getCount(), mSlideShowInterval, false); } }); } }, timeRemaining); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { int pos = requestedPos; if (mShuffleOrder != null) { pos = mShuffleOrder[pos]; } mGetter.setPosition(pos, cb); } } private void makeGetter() { mGetter = new ImageGetter(); } private boolean desiredSortOrder() { String sortOrder = mPrefs.getString("pref_gallery_sort_key", null); boolean sortAscending = false; if (sortOrder != null) { sortAscending = sortOrder.equals("ascending"); } if (mCameraReviewMode) { // Force left-arrow older pictures, right-arrow newer pictures. sortAscending = true; } return sortAscending; } private void init(Uri uri) { mSortAscending = desiredSortOrder(); int sort = mSortAscending ? ImageManager.SORT_ASCENDING : ImageManager.SORT_DESCENDING; mAllImages = ImageManager.makeImageList(uri, this, sort); uri = uri.buildUpon().query(null).build(); // TODO smarter/faster here please for (int i = 0; i < mAllImages.getCount(); i++) { ImageManager.IImage image = mAllImages.getImageAt(i); if (image.fullSizeImageUri().equals(uri)) { mCurrentPosition = i; mLastSlideShowImage = mCurrentPosition; break; } } } @Override public void onSaveInstanceState(Bundle b) { super.onSaveInstanceState(b); ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); if (image != null){ Uri uri = image.fullSizeImageUri(); String bucket = null; if(getIntent()!= null && getIntent().getData()!=null) bucket = getIntent().getData().getQueryParameter("bucketId"); if(bucket!=null) uri = uri.buildUpon().appendQueryParameter("bucketId", bucket).build(); b.putString("uri", uri.toString()); } if (mMode == MODE_SLIDESHOW) b.putBoolean("slideshow", true); } @Override public void onResume() { super.onResume(); // normally this will never be zero but if one "backs" into this // activity after removing the sdcard it could be zero. in that // case just "finish" since there's nothing useful that can happen. if (mAllImages.getCount() == 0) { finish(); } ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); if (desiredSortOrder() != mSortAscending) { init(image.fullSizeImageUri()); } if (mGetter == null) { makeGetter(); } mFirst = true; mScroller.setLayoutCompletedCallback(new Runnable() { public void run() { mLayoutComplete = true; setImage(mCurrentPosition); } }); setImage(mCurrentPosition); setOrientation(); } @Override public void onPause() { super.onPause(); mGetter.cancelCurrent(); mGetter.stop(); mGetter = null; setMode(MODE_NORMAL); mAllImages.deactivate(); mDismissOnScreenControlsRunnable.run(); if (mDismissOnScreenControlsRunnable != null) mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); for (ImageViewTouch iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } for (ImageViewTouch iv: mSlideShowImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } } @Override public void onStop() { super.onStop(); } public void onClick(View v) { switch (v.getId()) { case R.id.shutter_button: { if (mCameraReviewMode) { finish(); } else { MenuHelper.gotoStillImageCapture(this); } } break; case R.id.gallery: { MenuHelper.gotoCameraImageGallery(this); } break; case R.id.discard: { - MenuHelper.displayDeleteDialog(this, mDeletePhotoRunnable, true); + MenuHelper.deletePhoto(this, mDeletePhotoRunnable); } break; case R.id.share: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_STREAM, u); try { startActivity(Intent.createChooser(intent, getText(R.string.sendImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_image, Toast.LENGTH_SHORT).show(); } } break; case R.id.setas: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA, u); try { startActivity(Intent.createChooser(intent, getText(R.string.setImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } break; case R.id.next_image: { moveNextOrPrevious(1); } break; case R.id.prev_image: { moveNextOrPrevious(-1); } break; } } private void moveNextOrPrevious(int delta) { int nextImagePos = mCurrentPosition + delta; if ((0 <= nextImagePos) && (nextImagePos < mAllImages.getCount())) { setImage(nextImagePos); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case MenuHelper.RESULT_COMMON_MENU_CROP: if (resultCode == RESULT_OK) { // The CropImage activity passes back the Uri of the cropped image as // the Action rather than the Data. Uri dataUri = Uri.parse(data.getAction()); init(dataUri); // Clear mImageViews so we can reload the correct image in onResume(). for (ImageViewTouch iv: mImageViews) { iv.clear(); } } break; } } }
brunsky/WS171-packages-apps-Camera
e7b339c91b554539119abecaf53f552982f60477
auto import from //branches/cupcake_rel/...@141571
diff --git a/res/drawable/frame_thumbnail_default.png b/res/drawable/frame_thumbnail_default.png index a7498db..a531790 100644 Binary files a/res/drawable/frame_thumbnail_default.png and b/res/drawable/frame_thumbnail_default.png differ diff --git a/res/drawable/frame_thumbnail_pressed.png b/res/drawable/frame_thumbnail_pressed.png index ebc6855..3be8138 100644 Binary files a/res/drawable/frame_thumbnail_pressed.png and b/res/drawable/frame_thumbnail_pressed.png differ diff --git a/res/drawable/frame_thumbnail_selected.png b/res/drawable/frame_thumbnail_selected.png index 429a318..5884f9c 100644 Binary files a/res/drawable/frame_thumbnail_selected.png and b/res/drawable/frame_thumbnail_selected.png differ diff --git a/res/drawable/ic_btn_actionmenu_attach_default.png b/res/drawable/ic_btn_actionmenu_attach_default.png index 043691d..c8f7ec7 100644 Binary files a/res/drawable/ic_btn_actionmenu_attach_default.png and b/res/drawable/ic_btn_actionmenu_attach_default.png differ diff --git a/res/drawable/ic_btn_actionmenu_attach_pressed.png b/res/drawable/ic_btn_actionmenu_attach_pressed.png index b092ac1..7753e5b 100644 Binary files a/res/drawable/ic_btn_actionmenu_attach_pressed.png and b/res/drawable/ic_btn_actionmenu_attach_pressed.png differ diff --git a/res/drawable/ic_btn_actionmenu_attach_selected.png b/res/drawable/ic_btn_actionmenu_attach_selected.png index 52a2ef0..ca7e775 100644 Binary files a/res/drawable/ic_btn_actionmenu_attach_selected.png and b/res/drawable/ic_btn_actionmenu_attach_selected.png differ diff --git a/res/drawable/ic_btn_actionmenu_cancel_default.png b/res/drawable/ic_btn_actionmenu_cancel_default.png index cb8f7bc..ac7169a 100644 Binary files a/res/drawable/ic_btn_actionmenu_cancel_default.png and b/res/drawable/ic_btn_actionmenu_cancel_default.png differ diff --git a/res/drawable/ic_btn_actionmenu_cancel_pressed.png b/res/drawable/ic_btn_actionmenu_cancel_pressed.png index 02bdb49..ecb1a1f 100644 Binary files a/res/drawable/ic_btn_actionmenu_cancel_pressed.png and b/res/drawable/ic_btn_actionmenu_cancel_pressed.png differ diff --git a/res/drawable/ic_btn_actionmenu_cancel_selected.png b/res/drawable/ic_btn_actionmenu_cancel_selected.png index a0b6017..235ee88 100644 Binary files a/res/drawable/ic_btn_actionmenu_cancel_selected.png and b/res/drawable/ic_btn_actionmenu_cancel_selected.png differ diff --git a/res/drawable/ic_btn_actionmenu_delete_default.png b/res/drawable/ic_btn_actionmenu_delete_default.png index 7e25f0d..f3f655e 100644 Binary files a/res/drawable/ic_btn_actionmenu_delete_default.png and b/res/drawable/ic_btn_actionmenu_delete_default.png differ diff --git a/res/drawable/ic_btn_actionmenu_delete_pressed.png b/res/drawable/ic_btn_actionmenu_delete_pressed.png index 94087f6..14a21a8 100644 Binary files a/res/drawable/ic_btn_actionmenu_delete_pressed.png and b/res/drawable/ic_btn_actionmenu_delete_pressed.png differ diff --git a/res/drawable/ic_btn_actionmenu_delete_selected.png b/res/drawable/ic_btn_actionmenu_delete_selected.png index 780310b..2ddb0a6 100644 Binary files a/res/drawable/ic_btn_actionmenu_delete_selected.png and b/res/drawable/ic_btn_actionmenu_delete_selected.png differ diff --git a/res/drawable/ic_btn_actionmenu_gallery_default.png b/res/drawable/ic_btn_actionmenu_gallery_default.png index a2d38db..4d3456c 100644 Binary files a/res/drawable/ic_btn_actionmenu_gallery_default.png and b/res/drawable/ic_btn_actionmenu_gallery_default.png differ diff --git a/res/drawable/ic_btn_actionmenu_gallery_pressed.png b/res/drawable/ic_btn_actionmenu_gallery_pressed.png index a01b7f8..4c29587 100644 Binary files a/res/drawable/ic_btn_actionmenu_gallery_pressed.png and b/res/drawable/ic_btn_actionmenu_gallery_pressed.png differ diff --git a/res/drawable/ic_btn_actionmenu_gallery_selected.png b/res/drawable/ic_btn_actionmenu_gallery_selected.png index 400a63b..27349d4 100644 Binary files a/res/drawable/ic_btn_actionmenu_gallery_selected.png and b/res/drawable/ic_btn_actionmenu_gallery_selected.png differ diff --git a/res/drawable/ic_btn_actionmenu_play_default.png b/res/drawable/ic_btn_actionmenu_play_default.png index 17e0748..eba780b 100644 Binary files a/res/drawable/ic_btn_actionmenu_play_default.png and b/res/drawable/ic_btn_actionmenu_play_default.png differ diff --git a/res/drawable/ic_btn_actionmenu_play_pressed.png b/res/drawable/ic_btn_actionmenu_play_pressed.png index c671669..1caa2c2 100644 Binary files a/res/drawable/ic_btn_actionmenu_play_pressed.png and b/res/drawable/ic_btn_actionmenu_play_pressed.png differ diff --git a/res/drawable/ic_btn_actionmenu_play_selected.png b/res/drawable/ic_btn_actionmenu_play_selected.png index 35e1425..fea0ba0 100644 Binary files a/res/drawable/ic_btn_actionmenu_play_selected.png and b/res/drawable/ic_btn_actionmenu_play_selected.png differ diff --git a/res/drawable/ic_btn_actionmenu_set_as_default.png b/res/drawable/ic_btn_actionmenu_set_as_default.png index 0d341c7..048024f 100644 Binary files a/res/drawable/ic_btn_actionmenu_set_as_default.png and b/res/drawable/ic_btn_actionmenu_set_as_default.png differ diff --git a/res/drawable/ic_btn_actionmenu_set_as_pressed.png b/res/drawable/ic_btn_actionmenu_set_as_pressed.png index 58dc85c..67ae2aa 100644 Binary files a/res/drawable/ic_btn_actionmenu_set_as_pressed.png and b/res/drawable/ic_btn_actionmenu_set_as_pressed.png differ diff --git a/res/drawable/ic_btn_actionmenu_set_as_selected.png b/res/drawable/ic_btn_actionmenu_set_as_selected.png index 6281229..f2e5fce 100644 Binary files a/res/drawable/ic_btn_actionmenu_set_as_selected.png and b/res/drawable/ic_btn_actionmenu_set_as_selected.png differ diff --git a/res/drawable/ic_btn_actionmenu_share_default.png b/res/drawable/ic_btn_actionmenu_share_default.png index 19f6ef4..8e66365 100644 Binary files a/res/drawable/ic_btn_actionmenu_share_default.png and b/res/drawable/ic_btn_actionmenu_share_default.png differ diff --git a/res/drawable/ic_btn_actionmenu_share_grayout.png b/res/drawable/ic_btn_actionmenu_share_grayout.png index f41db23..4b62023 100755 Binary files a/res/drawable/ic_btn_actionmenu_share_grayout.png and b/res/drawable/ic_btn_actionmenu_share_grayout.png differ diff --git a/res/drawable/ic_btn_actionmenu_share_pressed.png b/res/drawable/ic_btn_actionmenu_share_pressed.png index 8583114..be71235 100644 Binary files a/res/drawable/ic_btn_actionmenu_share_pressed.png and b/res/drawable/ic_btn_actionmenu_share_pressed.png differ diff --git a/res/drawable/ic_btn_actionmenu_share_selected.png b/res/drawable/ic_btn_actionmenu_share_selected.png index fc9679b..fd4f886 100644 Binary files a/res/drawable/ic_btn_actionmenu_share_selected.png and b/res/drawable/ic_btn_actionmenu_share_selected.png differ diff --git a/res/drawable/ic_btn_camera_default_background.png b/res/drawable/ic_btn_camera_default_background.png index 5dac9c1..d58e2d2 100644 Binary files a/res/drawable/ic_btn_camera_default_background.png and b/res/drawable/ic_btn_camera_default_background.png differ diff --git a/res/drawable/ic_btn_camera_pressed_background.png b/res/drawable/ic_btn_camera_pressed_background.png index ebc6855..e0f7e12 100644 Binary files a/res/drawable/ic_btn_camera_pressed_background.png and b/res/drawable/ic_btn_camera_pressed_background.png differ diff --git a/res/drawable/ic_btn_camera_selected_background.png b/res/drawable/ic_btn_camera_selected_background.png index 429a318..3d7549b 100644 Binary files a/res/drawable/ic_btn_camera_selected_background.png and b/res/drawable/ic_btn_camera_selected_background.png differ diff --git a/res/drawable/ic_camera_indicator_photo.png b/res/drawable/ic_camera_indicator_photo.png index 3b0483b..d6c02da 100644 Binary files a/res/drawable/ic_camera_indicator_photo.png and b/res/drawable/ic_camera_indicator_photo.png differ diff --git a/res/drawable/ic_camera_indicator_video.png b/res/drawable/ic_camera_indicator_video.png index a4cb8d0..c160c66 100644 Binary files a/res/drawable/ic_camera_indicator_video.png and b/res/drawable/ic_camera_indicator_video.png differ diff --git a/res/drawable/ic_gps_active_camera.png b/res/drawable/ic_gps_active_camera.png new file mode 100755 index 0000000..9814772 Binary files /dev/null and b/res/drawable/ic_gps_active_camera.png differ diff --git a/res/drawable/ic_launcher_camera.png b/res/drawable/ic_launcher_camera.png index 9bb4c61..c2d7606 100644 Binary files a/res/drawable/ic_launcher_camera.png and b/res/drawable/ic_launcher_camera.png differ diff --git a/res/layout/camera.xml b/res/layout/camera.xml index 02d8430..767beaa 100644 --- a/res/layout/camera.xml +++ b/res/layout/camera.xml @@ -1,66 +1,79 @@ <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/camera" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal"> <com.android.camera.VideoPreview android:id="@+id/camera_preview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_centerInParent="true" /> - + <com.android.camera.ShutterButton android:id="@+id/shutter_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_camera_indicator_photo" android:background="@drawable/ic_btn_camera_background" android:clickable="true" android:focusable="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" - android:layout_marginRight="10dip" - android:layout_marginTop="10dip" + android:layout_marginRight="5dip" + android:layout_marginTop="5dip" android:scaleType="center" /> + <ImageView + android:id="@+id/gps_indicator" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:visibility="invisible" + android:clickable="false" + android:focusable="false" + android:layout_alignParentRight="true" + android:layout_alignParentTop="true" + android:layout_marginRight="18dip" + android:layout_marginTop="18dip" + android:src="@drawable/ic_gps_active_camera" /> + <ImageView android:id="@+id/focus_indicator" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_camera_indicator_auto_focus_green" android:layout_alignLeft="@id/shutter_button" android:layout_alignTop="@id/shutter_button" android:layout_marginLeft="39dip" android:layout_marginTop="16dip" android:scaleType="center" android:visibility="gone" /> - + <ImageView android:visibility="gone" android:id="@+id/last_picture_button" android:layout_width="72dip" android:layout_height="72dip" android:clickable="true" android:focusable="false" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" - android:layout_marginLeft="10dip" - android:layout_marginTop="10dip" /> + android:layout_marginLeft="5dip" + android:layout_marginTop="5dip" /> </RelativeLayout> diff --git a/res/layout/video_camera.xml b/res/layout/video_camera.xml index bafcd09..b8981cc 100644 --- a/res/layout/video_camera.xml +++ b/res/layout/video_camera.xml @@ -1,137 +1,130 @@ <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal"> <com.android.camera.VideoPreview android:id="@+id/camera_preview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_centerInParent="true" - /> - - <ImageView - android:id="@+id/video_frame" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:visibility="gone" /> - + <ImageView - android:id="@+id/blackout" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:visibility="invisible" + android:id="@+id/video_frame" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:visibility="gone" /> <com.android.camera.ShutterButton - android:id="@+id/shutter_button" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:src="@drawable/ic_camera_indicator_video" - android:background="@drawable/ic_btn_camera_background" - android:clickable="true" - android:focusable="true" - android:layout_alignParentRight="true" - android:layout_alignParentTop="true" - android:layout_marginRight="10dip" - android:layout_marginTop="10dip" - android:scaleType="center"/> + android:id="@+id/shutter_button" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:src="@drawable/ic_camera_indicator_video" + android:background="@drawable/ic_btn_camera_background" + android:clickable="true" + android:focusable="true" + android:layout_alignParentRight="true" + android:layout_alignParentTop="true" + android:layout_marginRight="5dip" + android:layout_marginTop="5dip" + android:scaleType="center" /> <!-- Note: In this TextView the paddingRight="2" attribute is required because otherwise the text's drop shadow will be clipped. --> <TextView - android:id="@+id/recording_time" - android:layout_width="90dip" - android:layout_height="wrap_content" - android:layout_toLeftOf="@id/shutter_button" - android:layout_alignTop="@id/shutter_button" - android:layout_marginTop="20dip" - android:layout_marginRight="6dip" - android:paddingRight="2dip" - android:shadowColor="#c0000000" - android:shadowDx="1" - android:shadowDy="1" - android:shadowRadius="1" - android:gravity="right" - android:textColor="@color/recording_time_elapsed_text" - android:textSize="20dip" - android:textStyle="bold" - android:visibility="gone"/> + android:id="@+id/recording_time" + android:layout_width="90dip" + android:layout_height="wrap_content" + android:layout_toLeftOf="@id/shutter_button" + android:layout_alignTop="@id/shutter_button" + android:layout_marginTop="20dip" + android:layout_marginRight="6dip" + android:paddingRight="2dip" + android:shadowColor="#c0000000" + android:shadowDx="1" + android:shadowDy="1" + android:shadowRadius="1" + android:gravity="right" + android:textColor="@color/recording_time_elapsed_text" + android:textSize="20dip" + android:textStyle="bold" + android:visibility="gone"/> - <LinearLayout - android:visibility="gone" - android:id="@+id/post_picture_panel" - android:layout_alignTop="@id/shutter_button" - android:layout_toLeftOf="@id/shutter_button" + <LinearLayout + android:visibility="gone" + android:id="@+id/post_picture_panel" + android:layout_alignTop="@id/shutter_button" + android:layout_toLeftOf="@id/shutter_button" android:layout_marginRight="38dip" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:orientation="horizontal"> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="horizontal"> <com.android.camera.ActionMenuButton - android:id="@+id/gallery" - android:drawableTop="@drawable/ic_menu_gallery" - android:text="@string/camera_gallery" - style="@style/OnscreenActionIcon" + android:id="@+id/gallery" + android:drawableTop="@drawable/ic_menu_gallery" + android:text="@string/camera_gallery" + style="@style/OnscreenActionIcon" + /> + <com.android.camera.ActionMenuButton + android:id="@+id/play" + android:drawableTop="@drawable/ic_menu_camera_play" + android:text="@string/camera_play" + style="@style/OnscreenActionIcon" /> <com.android.camera.ActionMenuButton - android:id="@+id/play" - android:drawableTop="@drawable/ic_menu_camera_play" - android:text="@string/camera_play" - style="@style/OnscreenActionIcon" - /> - <com.android.camera.ActionMenuButton - android:id="@+id/share" - android:drawableTop="@drawable/ic_menu_share" - android:text="@string/camera_share" - style="@style/OnscreenActionIcon" - /> - <com.android.camera.ActionMenuButton - android:id="@+id/discard" - android:drawableTop="@drawable/ic_menu_delete" - android:text="@string/camera_toss" - style="@style/OnscreenActionIcon" - /> - <com.android.camera.ActionMenuButton - android:id="@+id/attach" - android:drawableTop="@drawable/ic_menu_attach" - android:text="@string/camera_attach" - style="@style/OnscreenActionIcon" - /> - <com.android.camera.ActionMenuButton - android:id="@+id/cancel" - android:drawableTop="@drawable/ic_menu_cancel" - android:text="@string/camera_cancel" - style="@style/OnscreenActionIcon" - /> - </LinearLayout> + android:id="@+id/share" + android:drawableTop="@drawable/ic_menu_share" + android:text="@string/camera_share" + style="@style/OnscreenActionIcon" + /> + <com.android.camera.ActionMenuButton + android:id="@+id/discard" + android:drawableTop="@drawable/ic_menu_delete" + android:text="@string/camera_toss" + style="@style/OnscreenActionIcon" + /> + <com.android.camera.ActionMenuButton + android:id="@+id/attach" + android:drawableTop="@drawable/ic_menu_attach" + android:text="@string/camera_attach" + style="@style/OnscreenActionIcon" + /> + <com.android.camera.ActionMenuButton + android:id="@+id/cancel" + android:drawableTop="@drawable/ic_menu_cancel" + android:text="@string/camera_cancel" + style="@style/OnscreenActionIcon" + /> + </LinearLayout> <ImageView - android:visibility="visible" - android:id="@+id/last_picture_button" - android:layout_width="72dip" - android:layout_height="72dip" - android:clickable="true" - android:focusable="false" - android:layout_alignParentLeft="true" - android:layout_alignParentTop="true" - android:layout_marginLeft="10dip" - android:layout_marginTop="10dip" /> + android:visibility="visible" + android:id="@+id/last_picture_button" + android:layout_width="72dip" + android:layout_height="72dip" + android:clickable="true" + android:focusable="false" + android:layout_alignParentLeft="true" + android:layout_alignParentTop="true" + android:layout_marginLeft="5dip" + android:layout_marginTop="5dip"/> </RelativeLayout> diff --git a/res/raw/camera_click.ogg b/res/raw/camera_click.ogg deleted file mode 100644 index 0a769ff..0000000 Binary files a/res/raw/camera_click.ogg and /dev/null differ diff --git a/src/com/android/camera/Camera.java b/src/com/android/camera/Camera.java index 8cd1756..2300387 100644 --- a/src/com/android/camera/Camera.java +++ b/src/com/android/camera/Camera.java @@ -1,1788 +1,1612 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.File; -import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import android.app.Activity; -import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; -import android.content.res.AssetFileDescriptor; -import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; -import android.graphics.Canvas; import android.graphics.Matrix; -import android.graphics.Paint; -import android.graphics.PorterDuff; -import android.graphics.PorterDuffXfermode; -import android.graphics.RectF; -import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; -import android.graphics.drawable.LayerDrawable; -import android.graphics.drawable.TransitionDrawable; import android.hardware.Camera.PictureCallback; import android.hardware.Camera.Size; import android.location.Location; import android.location.LocationManager; import android.location.LocationProvider; import android.media.AudioManager; -import android.media.MediaPlayer; import android.media.ToneGenerator; import android.net.Uri; import android.os.Bundle; import android.os.Debug; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.text.format.DateFormat; import android.util.Config; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.OrientationEventListener; import android.view.SurfaceHolder; import android.view.View; import android.view.ViewGroup; -import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.Toast; public class Camera extends Activity implements View.OnClickListener, ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback { private static final String TAG = "camera"; private static final boolean DEBUG = false; private static final boolean DEBUG_TIME_OPERATIONS = DEBUG && false; private static final int CROP_MSG = 1; private static final int RESTART_PREVIEW = 3; private static final int CLEAR_SCREEN_DELAY = 4; private static final int SCREEN_DELAY = 2 * 60 * 1000; private static final int FOCUS_BEEP_VOLUME = 100; public static final int MENU_SWITCH_TO_VIDEO = 0; public static final int MENU_SWITCH_TO_CAMERA = 1; public static final int MENU_FLASH_SETTING = 2; public static final int MENU_FLASH_AUTO = 3; public static final int MENU_FLASH_ON = 4; public static final int MENU_FLASH_OFF = 5; public static final int MENU_SETTINGS = 6; public static final int MENU_GALLERY_PHOTOS = 7; public static final int MENU_GALLERY_VIDEOS = 8; public static final int MENU_SAVE_SELECT_PHOTOS = 30; public static final int MENU_SAVE_NEW_PHOTO = 31; public static final int MENU_SAVE_GALLERY_PHOTO = 34; public static final int MENU_SAVE_GALLERY_VIDEO_PHOTO = 35; public static final int MENU_SAVE_CAMERA_DONE = 36; public static final int MENU_SAVE_CAMERA_VIDEO_DONE = 37; private OrientationEventListener mOrientationListener; private int mLastOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; private SharedPreferences mPreferences; private static final int IDLE = 1; private static final int SNAPSHOT_IN_PROGRESS = 2; private static final int SNAPSHOT_COMPLETED = 3; private int mStatus = IDLE; private static final String sTempCropFilename = "crop-temp"; private android.hardware.Camera mCameraDevice; private android.hardware.Camera.Parameters mParameters; private VideoPreview mSurfaceView; private SurfaceHolder mSurfaceHolder = null; private int mOriginalViewFinderWidth, mOriginalViewFinderHeight; private int mViewFinderWidth, mViewFinderHeight; private boolean mPreviewing = false; - private MediaPlayer mClickSound; - private Capturer mCaptureObject; private ImageCapture mImageCapture = null; private boolean mPausing = false; private static final int FOCUS_NOT_STARTED = 0; private static final int FOCUSING = 1; private static final int FOCUSING_SNAP_ON_FINISH = 2; private static final int FOCUS_SUCCESS = 3; private static final int FOCUS_FAIL = 4; private int mFocusState = FOCUS_NOT_STARTED; private static ContentResolver mContentResolver; private boolean mDidRegister = false; private ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>(); - private ImageView mLastPictureButton; - private LayerDrawable mVignette; - private Animation mShowLastPictureButtonAnimation = new AlphaAnimation(0F, 1F); - private boolean mShouldShowLastPictureButton; - private TransitionDrawable mThumbnailTransition; - private Drawable[] mThumbnails; - private boolean mShouldTransitionThumbnails; - private Uri mLastPictureUri; - private Bitmap mLastPictureThumb; private LocationManager mLocationManager = null; private ShutterButton mShutterButton; private Animation mFocusBlinkAnimation; private View mFocusIndicator; + private ImageView mGpsIndicator; private ToneGenerator mFocusToneGenerator; private ShutterCallback mShutterCallback = new ShutterCallback(); private RawPictureCallback mRawPictureCallback = new RawPictureCallback(); private AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback(); private long mFocusStartTime; private long mFocusCallbackTime; private long mCaptureStartTime; private long mShutterCallbackTime; private long mRawPictureCallbackTime; private int mPicturesRemaining; + private boolean mRecordLocation; private boolean mKeepAndRestartPreview; - // mPostCaptureAlert is non-null only if isImageCaptureIntent() is true. + private boolean mIsImageCaptureIntent; + // mPostCaptureAlert, mLastPictureButton, mThumbController + // are non-null only if isImageCaptureIntent() is true. private View mPostCaptureAlert; - + private ImageView mLastPictureButton; + private ThumbnailController mThumbController; private Handler mHandler = new MainHandler(); private interface Capturer { Uri getLastCaptureUri(); void onSnap(); void dismissFreezeFrame(); } /** This Handler is used to post message back onto the main thread of the application */ private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case RESTART_PREVIEW: { if (mStatus == SNAPSHOT_IN_PROGRESS) { // We are still in the processing of taking the picture, wait. // This is strange. Why are we polling? // TODO remove polling mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, 100); } else if (mStatus == SNAPSHOT_COMPLETED){ mCaptureObject.dismissFreezeFrame(); hidePostCaptureAlert(); } break; } case CLEAR_SCREEN_DELAY: { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); break; } } } }; LocationListener [] mLocationListeners = new LocationListener[] { new LocationListener(LocationManager.GPS_PROVIDER), new LocationListener(LocationManager.NETWORK_PROVIDER) }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { // SD card available updateStorageHint(calculatePicturesRemaining()); } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED) || action.equals(Intent.ACTION_MEDIA_CHECKING)) { // SD card unavailable mPicturesRemaining = MenuHelper.NO_STORAGE_ERROR; updateStorageHint(mPicturesRemaining); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { Toast.makeText(Camera.this, getResources().getString(R.string.wait), 5000); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { updateStorageHint(); } } }; private class LocationListener implements android.location.LocationListener { Location mLastLocation; boolean mValid = false; String mProvider; public LocationListener(String provider) { mProvider = provider; mLastLocation = new Location(mProvider); } public void onLocationChanged(Location newLocation) { if (newLocation.getLatitude() == 0.0 && newLocation.getLongitude() == 0.0) { // Hack to filter out 0.0,0.0 locations return; } + // If GPS is available before start camera, we won't get status + // update so update GPS indicator when we receive data. + if (mRecordLocation + && LocationManager.GPS_PROVIDER.equals(mProvider)) { + mGpsIndicator.setVisibility(View.VISIBLE); + } mLastLocation.set(newLocation); mValid = true; } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { mValid = false; } public void onStatusChanged(String provider, int status, Bundle extras) { - if (status == LocationProvider.OUT_OF_SERVICE) { - mValid = false; + switch(status) { + case LocationProvider.OUT_OF_SERVICE: + case LocationProvider.TEMPORARILY_UNAVAILABLE: { + mValid = false; + if (mRecordLocation && + LocationManager.GPS_PROVIDER.equals(provider)) { + mGpsIndicator.setVisibility(View.INVISIBLE); + } + break; + } } } public Location current() { return mValid ? mLastLocation : null; } }; private boolean mImageSavingItem = false; private final class ShutterCallback implements android.hardware.Camera.ShutterCallback { public void onShutter() { if (DEBUG_TIME_OPERATIONS) { mShutterCallbackTime = System.currentTimeMillis(); Log.v(TAG, "Shutter lag was " + (mShutterCallbackTime - mCaptureStartTime) + " ms."); } // We are going to change the size of surface view and show captured // image. Set it to invisible now and set it back to visible in // surfaceChanged() so that users won't see the image is resized on // the screen. mSurfaceView.setVisibility(View.INVISIBLE); // Resize the SurfaceView to the aspect-ratio of the still image // and so that we can see the full image that was taken. Size pictureSize = mParameters.getPictureSize(); mSurfaceView.setAspectRatio(pictureSize.width, pictureSize.height); - - if (mClickSound != null) { - mClickSound.start(); - } } }; private final class RawPictureCallback implements PictureCallback { public void onPictureTaken(byte [] rawData, android.hardware.Camera camera) { if (Config.LOGV) Log.v(TAG, "got RawPictureCallback..."); mRawPictureCallbackTime = System.currentTimeMillis(); if (DEBUG_TIME_OPERATIONS) { Log.v(TAG, (mRawPictureCallbackTime - mShutterCallbackTime) + "ms elapsed between" + " ShutterCallback and RawPictureCallback."); } } }; private final class JpegPictureCallback implements PictureCallback { Location mLocation; public JpegPictureCallback(Location loc) { mLocation = loc; } public void onPictureTaken(byte [] jpegData, android.hardware.Camera camera) { if (mPausing) { return; } if (Config.LOGV) Log.v(TAG, "got JpegPictureCallback..."); if (DEBUG_TIME_OPERATIONS) { long mJpegPictureCallback = System.currentTimeMillis(); Log.v(TAG, (mJpegPictureCallback - mRawPictureCallbackTime) + "ms elapsed between" + " RawPictureCallback and JpegPictureCallback."); } if (jpegData != null) { mImageCapture.storeImage(jpegData, camera, mLocation); } mStatus = SNAPSHOT_COMPLETED; if (mKeepAndRestartPreview) { long delay = 1500 - (System.currentTimeMillis() - mRawPictureCallbackTime); mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, Math.max(delay, 0)); } } }; private final class AutoFocusCallback implements android.hardware.Camera.AutoFocusCallback { public void onAutoFocus(boolean focused, android.hardware.Camera camera) { if (DEBUG_TIME_OPERATIONS) { mFocusCallbackTime = System.currentTimeMillis(); Log.v(TAG, "Auto focus took " + (mFocusCallbackTime - mFocusStartTime) + " ms."); } if (mFocusState == FOCUSING_SNAP_ON_FINISH && mCaptureObject != null) { // Take the picture no matter focus succeeds or fails. // No need to play the AF sound if we're about to play the shutter sound. mCaptureObject.onSnap(); clearFocusState(); } else if (mFocusState == FOCUSING) { // User is half-pressing the focus key. Play the focus tone. // Do not take the picture now. ToneGenerator tg = mFocusToneGenerator; if (tg != null) tg.startTone(ToneGenerator.TONE_PROP_BEEP2); if (focused) { mFocusState = FOCUS_SUCCESS; } else { mFocusState = FOCUS_FAIL; } } else if (mFocusState == FOCUS_NOT_STARTED) { // User has released the focus key before focus completes. // Do nothing. } updateFocusIndicator(); } }; private class ImageCapture implements Capturer { private boolean mCancel = false; private boolean mCapturing = false; private Uri mLastContentUri; private ImageManager.IAddImage_cancelable mAddImageCancelable; Bitmap mCaptureOnlyBitmap; /** These member variables are used for various debug timings */ private long mThreadTimeStart; private long mThreadTimeEnd; private long mWallTimeStart; private long mWallTimeEnd; public ImageCapture() { } /** * This method sets whether or not we are capturing a picture. This method must be called * with the ImageCapture.this lock held. */ public void setCapturingLocked(boolean capturing) { mCapturing = capturing; } public void dismissFreezeFrame() { if (mStatus == SNAPSHOT_IN_PROGRESS) { // If we are still in the process of taking a picture, then just post a message. mHandler.sendEmptyMessage(RESTART_PREVIEW); } else { restartPreview(); } } private void startTiming() { mWallTimeStart = SystemClock.elapsedRealtime(); mThreadTimeStart = Debug.threadCpuTimeNanos(); } private void stopTiming() { mThreadTimeEnd = Debug.threadCpuTimeNanos(); mWallTimeEnd = SystemClock.elapsedRealtime(); } private void storeImage(byte[] data, Location loc) { try { if (DEBUG_TIME_OPERATIONS) { startTiming(); } long dateTaken = System.currentTimeMillis(); String name = createName(dateTaken) + ".jpg"; mLastContentUri = ImageManager.instance().addImage( Camera.this, mContentResolver, name, "", dateTaken, // location for the database goes here loc, 0, // the dsp will use the right orientation so don't "double set it" ImageManager.CAMERA_IMAGE_BUCKET_NAME, name); if (mLastContentUri == null) { // this means we got an error mCancel = true; } if (!mCancel) { mAddImageCancelable = ImageManager.instance().storeImage(mLastContentUri, Camera.this, mContentResolver, 0, null, data); mAddImageCancelable.get(); mAddImageCancelable = null; } if (DEBUG_TIME_OPERATIONS) { stopTiming(); Log.d(TAG, "Storing image took " + (mWallTimeEnd - mWallTimeStart) + " ms. " + "Thread time was " + ((mThreadTimeEnd - mThreadTimeStart) / 1000000) + " ms."); } } catch (Exception ex) { Log.e(TAG, "Exception while compressing image.", ex); } } public void storeImage(byte[] data, android.hardware.Camera camera, Location loc) { - boolean captureOnly = isImageCaptureIntent(); + boolean captureOnly = mIsImageCaptureIntent; if (!captureOnly) { storeImage(data, loc); sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", mLastContentUri)); setLastPictureThumb(data, mCaptureObject.getLastCaptureUri()); dismissFreezeFrame(); } else { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; if (DEBUG_TIME_OPERATIONS) { startTiming(); } mCaptureOnlyBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options); if (DEBUG_TIME_OPERATIONS) { stopTiming(); Log.d(TAG, "Decoded mCaptureOnly bitmap (" + mCaptureOnlyBitmap.getWidth() + "x" + mCaptureOnlyBitmap.getHeight() + " ) in " + (mWallTimeEnd - mWallTimeStart) + " ms. Thread time was " + ((mThreadTimeEnd - mThreadTimeStart) / 1000000) + " ms."); } showPostCaptureAlert(); cancelAutomaticPreviewRestart(); } mCapturing = false; if (mPausing) { closeCamera(); } } /* * Initiate the capture of an image. */ public void initiate(boolean captureOnly) { if (mCameraDevice == null) { return; } mCancel = false; mCapturing = true; capture(captureOnly); } public Uri getLastCaptureUri() { return mLastContentUri; } public Bitmap getLastBitmap() { return mCaptureOnlyBitmap; } private void capture(boolean captureOnly) { mPreviewing = false; mCaptureOnlyBitmap = null; final int latchedOrientation = ImageManager.roundOrientation(mLastOrientation + 90); - Boolean recordLocation = mPreferences.getBoolean("pref_camera_recordlocation_key", false); - Location loc = recordLocation ? getCurrentLocation() : null; + Location loc = mRecordLocation ? getCurrentLocation() : null; // Quality 75 has visible artifacts, and quality 90 looks great but the files begin to // get large. 85 is a good compromise between the two. mParameters.set("jpeg-quality", 85); mParameters.set("rotation", latchedOrientation); mParameters.remove("gps-latitude"); mParameters.remove("gps-longitude"); mParameters.remove("gps-altitude"); mParameters.remove("gps-timestamp"); if (loc != null) { double lat = loc.getLatitude(); double lon = loc.getLongitude(); boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d); if (hasLatLon) { String latString = String.valueOf(lat); String lonString = String.valueOf(lon); mParameters.set("gps-latitude", latString); mParameters.set("gps-longitude", lonString); if (loc.hasAltitude()) { mParameters.set("gps-altitude", String.valueOf(loc.getAltitude())); } else { // for NETWORK_PROVIDER location provider, we may have // no altitude information, but the driver needs it, so // we fake one. mParameters.set("gps-altitude", "0"); } if (loc.getTime() != 0) { // Location.getTime() is UTC in milliseconds. // gps-timestamp is UTC in seconds. long utcTimeSeconds = loc.getTime() / 1000; mParameters.set("gps-timestamp", String.valueOf(utcTimeSeconds)); } } else { loc = null; } } mCameraDevice.setParameters(mParameters); mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback, new JpegPictureCallback(loc)); - // Prepare the sound to play in shutter callback. - if (mClickSound != null) { - mClickSound.seekTo(0); - } } public void onSnap() { if (mPausing) { return; } if (DEBUG_TIME_OPERATIONS) mCaptureStartTime = System.currentTimeMillis(); // If we are already in the middle of taking a snapshot then we should just save // the image after we have returned from the camera service. if (mStatus == SNAPSHOT_IN_PROGRESS || mStatus == SNAPSHOT_COMPLETED) { mKeepAndRestartPreview = true; mHandler.sendEmptyMessage(RESTART_PREVIEW); return; } // Don't check the filesystem here, we can't afford the latency. Instead, check the // cached value which was calculated when the preview was restarted. if (mPicturesRemaining < 1) { updateStorageHint(mPicturesRemaining); return; } mStatus = SNAPSHOT_IN_PROGRESS; mKeepAndRestartPreview = true; - boolean getContentAction = isImageCaptureIntent(); + boolean getContentAction = mIsImageCaptureIntent; if (getContentAction) { mImageCapture.initiate(true); } else { mImageCapture.initiate(false); } } private void clearLastBitmap() { if (mCaptureOnlyBitmap != null) { mCaptureOnlyBitmap.recycle(); mCaptureOnlyBitmap = null; } } } private void setLastPictureThumb(byte[] data, Uri uri) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 16; - Bitmap lastPictureThumb = BitmapFactory.decodeByteArray(data, 0, data.length, options); - - setLastPictureThumb(lastPictureThumb, uri); - } - - private static Bitmap makeRoundedCorner(Bitmap thumb, int rx, int ry) { - if (thumb == null) return null; - int width = thumb.getWidth(); - int height = thumb.getHeight(); - - Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(result); - Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); - paint.setStyle(Paint.Style.FILL); - canvas.drawRoundRect(new RectF(0, 0, width, height), rx, ry, paint); - paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); - canvas.drawBitmap(thumb, 0, 0, paint); - return result; - } - - private void setLastPictureThumb(Bitmap lastPictureThumb, Uri uri) { - - final int PADDING_WIDTH = 6; - final int PADDING_HEIGHT = 6; - LayoutParams layoutParams = mLastPictureButton.getLayoutParams(); - // Make the mini-thumbnail size smaller than the button size so that the image corners - // don't peek out from the rounded corners of the frame_thumbnail graphic: - final int miniThumbWidth = layoutParams.width - 2 * PADDING_WIDTH; - final int miniThumbHeight = layoutParams.height - 2 * PADDING_HEIGHT; - mLastPictureThumb = ImageManager.extractMiniThumb( - lastPictureThumb, miniThumbWidth, miniThumbHeight); - lastPictureThumb = makeRoundedCorner(mLastPictureThumb, 3, 3); - - Drawable[] vignetteLayers = new Drawable[2]; - vignetteLayers[0] = getResources().getDrawable(R.drawable.frame_thumbnail); - if (mThumbnails == null) { - mThumbnails = new Drawable[2]; - mThumbnails[1] = new BitmapDrawable(lastPictureThumb); - vignetteLayers[1] = mThumbnails[1]; - } else { - mThumbnails[0] = mThumbnails[1]; - mThumbnails[1] = new BitmapDrawable(lastPictureThumb); - mThumbnailTransition = new TransitionDrawable(mThumbnails); - mShouldTransitionThumbnails = true; - vignetteLayers[1] = mThumbnailTransition; - } - - mVignette = new LayerDrawable(vignetteLayers); - mVignette.setLayerInset(1, PADDING_WIDTH, PADDING_HEIGHT, - PADDING_WIDTH, PADDING_HEIGHT); - mLastPictureButton.setImageDrawable(mVignette); - - if (mLastPictureButton.getVisibility() != View.VISIBLE) { - mShouldShowLastPictureButton = true; - } - mLastPictureUri = uri; + mThumbController.setData(uri, lastPictureThumb); } static private String createName(long dateTaken) { return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString(); } static public Matrix GetDisplayMatrix(Bitmap b, ImageView v) { Matrix m = new Matrix(); float bw = (float)b.getWidth(); float bh = (float)b.getHeight(); float vw = (float)v.getWidth(); float vh = (float)v.getHeight(); float scale, x, y; if (bw*vh > vw*bh) { scale = vh / bh; x = (vw - scale*bw)*0.5F; y = 0; } else { scale = vw / bw; x = 0; y = (vh - scale*bh)*0.5F; } m.setScale(scale, scale, 0.5F, 0.5F); m.postTranslate(x, y); return m; } /** Called with the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); // To reduce startup time, we open camera device in another thread. // We make sure the camera is opened at the end of onCreate. Thread openCameraThread = new Thread(new Runnable() { public void run() { mCameraDevice = android.hardware.Camera.open(); } }); openCameraThread.start(); // To reduce startup time, we run some service creation code in another thread. // We make sure the services are loaded at the end of onCreate(). Thread loadServiceThread = new Thread(new Runnable() { public void run() { mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mOrientationListener = new OrientationEventListener(Camera.this) { public void onOrientationChanged(int orientation) { // We keep the last known orientation. So if the user // first orient the camera then point the camera to // floor/sky, we still have the correct orientation. if (orientation != ORIENTATION_UNKNOWN) mLastOrientation = orientation; } }; } }); loadServiceThread.start(); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mContentResolver = getContentResolver(); Window win = getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.camera); mSurfaceView = (VideoPreview) findViewById(R.id.camera_preview); + mGpsIndicator = (ImageView) findViewById(R.id.gps_indicator); // don't set mSurfaceHolder here. We have it set ONLY within // surfaceCreated / surfaceDestroyed, other parts of the code // assume that when it is set, the surface is also set. SurfaceHolder holder = mSurfaceView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); - if (!isImageCaptureIntent()) { + mIsImageCaptureIntent = isImageCaptureIntent(); + + if (!mIsImageCaptureIntent) { mLastPictureButton = (ImageView) findViewById(R.id.last_picture_button); mLastPictureButton.setOnClickListener(this); - loadLastThumb(); + Drawable frame = getResources().getDrawable(R.drawable.frame_thumbnail); + mThumbController = new ThumbnailController(mLastPictureButton, + frame, mContentResolver); + mThumbController.loadData(ImageManager.getLastImageThumbPath()); } mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); - try { - mClickSound = new MediaPlayer(); - AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.camera_click); - - mClickSound.setDataSource(afd.getFileDescriptor(), - afd.getStartOffset(), - afd.getLength()); - - if (mClickSound != null) { - mClickSound.setAudioStreamType(AudioManager.STREAM_ALARM); - mClickSound.prepare(); - } - } catch (Exception ex) { - Log.w(TAG, "Couldn't create click sound", ex); - } - mFocusIndicator = findViewById(R.id.focus_indicator); mFocusBlinkAnimation = AnimationUtils.loadAnimation(this, R.anim.auto_focus_blink); mFocusBlinkAnimation.setRepeatCount(Animation.INFINITE); mFocusBlinkAnimation.setRepeatMode(Animation.REVERSE); // We load the post_picture_panel layout only if it is needed. - if (isImageCaptureIntent()) { + if (mIsImageCaptureIntent) { ViewGroup cameraView = (ViewGroup)findViewById(R.id.camera); getLayoutInflater().inflate(R.layout.post_picture_panel, cameraView); mPostCaptureAlert = findViewById(R.id.post_picture_panel); } // Make sure the services are loaded. try { openCameraThread.join(); loadServiceThread.join(); } catch (InterruptedException ex) { } ImageManager.ensureOSXCompatibleFolder(); } @Override public void onStart() { super.onStart(); Thread t = new Thread(new Runnable() { public void run() { final boolean storageOK = calculatePicturesRemaining() > 0; if (!storageOK) { mHandler.post(new Runnable() { public void run() { updateStorageHint(mPicturesRemaining); } }); } } }); t.start(); } public void onClick(View v) { switch (v.getId()) { case R.id.last_picture_button: viewLastImage(); break; case R.id.attach: doAttach(); break; case R.id.cancel: doCancel(); } } private void doAttach() { if (mPausing) { return; } Bitmap bitmap = mImageCapture.getLastBitmap(); String cropValue = null; Uri saveUri = null; Bundle myExtras = getIntent().getExtras(); if (myExtras != null) { saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); cropValue = myExtras.getString("crop"); } if (cropValue == null) { /* * First handle the no crop case -- just return the value. If the caller * specifies a "save uri" then write the data to it's stream. Otherwise, * pass back a scaled down version of the bitmap directly in the extras. */ if (saveUri != null) { OutputStream outputStream = null; try { outputStream = mContentResolver.openOutputStream(saveUri); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, outputStream); outputStream.close(); setResult(RESULT_OK); finish(); } catch (IOException ex) { // } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { } } } } else { float scale = .5F; Matrix m = new Matrix(); m.setScale(scale, scale); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true); setResult(RESULT_OK, new Intent("inline-data").putExtra("data", bitmap)); finish(); } } else { /* * Save the image to a temp file and invoke the cropper */ Uri tempUri = null; FileOutputStream tempStream = null; try { File path = getFileStreamPath(sTempCropFilename); path.delete(); tempStream = openFileOutput(sTempCropFilename, 0); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, tempStream); tempStream.close(); tempUri = Uri.fromFile(path); } catch (FileNotFoundException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } catch (IOException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } finally { if (tempStream != null) { try { tempStream.close(); } catch (IOException ex) { } } } Bundle newExtras = new Bundle(); if (cropValue.equals("circle")) newExtras.putString("circleCrop", "true"); if (saveUri != null) newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, saveUri); else newExtras.putBoolean("return-data", true); Intent cropIntent = new Intent(); cropIntent.setClass(Camera.this, CropImage.class); cropIntent.setData(tempUri); cropIntent.putExtras(newExtras); startActivityForResult(cropIntent, CROP_MSG); } } private void doCancel() { setResult(RESULT_CANCELED, new Intent()); finish(); } public void onShutterButtonFocus(ShutterButton button, boolean pressed) { if (mPausing) { return; } switch (button.getId()) { case R.id.shutter_button: doFocus(pressed); break; } } public void onShutterButtonClick(ShutterButton button) { if (mPausing) { return; } switch (button.getId()) { case R.id.shutter_button: doSnap(); break; } } private void updateStorageHint() { updateStorageHint(MenuHelper.calculatePicturesRemaining()); } private OnScreenHint mStorageHint; private void updateStorageHint(int remaining) { String noStorageText = null; if (remaining == MenuHelper.NO_STORAGE_ERROR) { String state = Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING) { noStorageText = getString(R.string.preparing_sd); } else { noStorageText = getString(R.string.no_storage); } } else if (remaining < 1) { noStorageText = getString(R.string.not_enough_space); } if (noStorageText != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, noStorageText); } else { mStorageHint.setText(noStorageText); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } @Override public void onResume() { super.onResume(); mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); mPausing = false; mOrientationListener.enable(); + mRecordLocation = mPreferences.getBoolean( + "pref_camera_recordlocation_key", false); + mGpsIndicator.setVisibility(View.INVISIBLE); // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); mDidRegister = true; mImageCapture = new ImageCapture(); restartPreview(); - if (mPreferences.getBoolean("pref_camera_recordlocation_key", false)) - startReceivingLocationUpdates(); + if (mRecordLocation) startReceivingLocationUpdates(); updateFocusIndicator(); try { mFocusToneGenerator = new ToneGenerator(AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME); } catch (RuntimeException e) { Log.w(TAG, "Exception caught while creating local tone generator: " + e); mFocusToneGenerator = null; } } - private ImageManager.DataLocation dataLocation() { + private static ImageManager.DataLocation dataLocation() { return ImageManager.DataLocation.EXTERNAL; } - private static final int BUFSIZE = 4096; - - // Stores the thumbnail and URI of last-picture-taken to SD card, so we can - // load it the next time the Camera app starts. - private void storeLastThumb() { - if (mLastPictureUri != null && mLastPictureThumb != null) { - try { - FileOutputStream f = new FileOutputStream(ImageManager.getLastThumbPath()); - try { - BufferedOutputStream b = new BufferedOutputStream(f, BUFSIZE); - try { - DataOutputStream d = new DataOutputStream(b); - try { - d.writeUTF(mLastPictureUri.toString()); - mLastPictureThumb.compress(Bitmap.CompressFormat.PNG, 100, d); - } finally { - d.close(); - b = null; - f = null; - } - } finally { - if (b != null) { - b.close(); - f = null; - } - } - } finally { - if (f != null) { - f.close(); - } - } - } catch (IOException e) { - } - } - } - - // Loads the thumbnail and URI of last-picture-taken from SD card. - private void loadLastThumb() { - try { - FileInputStream f = new FileInputStream(ImageManager.getLastThumbPath()); - try { - BufferedInputStream b = new BufferedInputStream(f, BUFSIZE); - try { - DataInputStream d = new DataInputStream(b); - try { - Uri lastUri = Uri.parse(d.readUTF()); - Bitmap lastThumb = BitmapFactory.decodeStream(d); - setLastPictureThumb(lastThumb, lastUri); - } finally { - d.close(); - b = null; - f = null; - } - } finally { - if (b != null) { - b.close(); - f = null; - } - } - } finally { - if (f != null) { - f.close(); - } - } - } catch (IOException e) { - } - } - @Override public void onStop() { keep(); stopPreview(); closeCamera(); mHandler.removeMessages(CLEAR_SCREEN_DELAY); super.onStop(); } @Override protected void onPause() { keep(); mPausing = true; mOrientationListener.disable(); stopPreview(); if (!mImageCapture.mCapturing) { closeCamera(); } if (mDidRegister) { unregisterReceiver(mReceiver); mDidRegister = false; } stopReceivingLocationUpdates(); if (mFocusToneGenerator != null) { mFocusToneGenerator.release(); mFocusToneGenerator = null; } - storeLastThumb(); + if (!mIsImageCaptureIntent) { + mThumbController.storeData(ImageManager.getLastImageThumbPath()); + } + if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } // If we are in an image capture intent and has taken // a picture, we just clear it in onPause. mImageCapture.clearLastBitmap(); mImageCapture = null; hidePostCaptureAlert(); super.onPause(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case CROP_MSG: { Intent intent = new Intent(); if (data != null) { Bundle extras = data.getExtras(); if (extras != null) { intent.putExtras(extras); } } setResult(resultCode, intent); finish(); File path = getFileStreamPath(sTempCropFilename); path.delete(); break; } } } private void autoFocus() { updateFocusIndicator(); if (mFocusState != FOCUSING && mFocusState != FOCUSING_SNAP_ON_FINISH) { if (mCameraDevice != null) { if (DEBUG_TIME_OPERATIONS) { mFocusStartTime = System.currentTimeMillis(); } mFocusState = FOCUSING; mCameraDevice.autoFocus(mAutoFocusCallback); } } } private void clearFocusState() { mFocusState = FOCUS_NOT_STARTED; } private void updateFocusIndicator() { mHandler.post(new Runnable() { public void run() { if (mFocusState == FOCUS_SUCCESS) { mFocusIndicator.setVisibility(View.VISIBLE); mFocusIndicator.clearAnimation(); } else if (mFocusState == FOCUS_FAIL) { mFocusIndicator.setVisibility(View.VISIBLE); mFocusIndicator.startAnimation(mFocusBlinkAnimation); } else { mFocusIndicator.setVisibility(View.GONE); mFocusIndicator.clearAnimation(); } } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mStatus == SNAPSHOT_IN_PROGRESS) { // ignore backs while we're taking a picture return true; } break; case KeyEvent.KEYCODE_FOCUS: if (event.getRepeatCount() == 0) { doFocus(true); } return true; case KeyEvent.KEYCODE_CAMERA: if (event.getRepeatCount() == 0) { doSnap(); } return true; case KeyEvent.KEYCODE_DPAD_CENTER: // If we get a dpad center event without any focused view, move the // focus to the shutter button and press it. if (event.getRepeatCount() == 0) { // Start auto-focus immediately to reduce shutter lag. After the shutter button // gets the focus, doFocus() will be called again but it is fine. doFocus(true); if (mShutterButton.isInTouchMode()) { mShutterButton.requestFocusFromTouch(); } else { mShutterButton.requestFocus(); } mShutterButton.setPressed(true); } return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_FOCUS: doFocus(false); return true; } return super.onKeyUp(keyCode, event); } private void doSnap() { // If the user has half-pressed the shutter and focus is completed, we // can take the photo right away. if ((mFocusState == FOCUS_SUCCESS || mFocusState == FOCUS_FAIL) || !mPreviewing) { // doesn't get set until the idler runs if (mCaptureObject != null) { mCaptureObject.onSnap(); } clearFocusState(); updateFocusIndicator(); } else if (mFocusState == FOCUSING) { // Half pressing the shutter (i.e. the focus button event) will // already have requested AF for us, so just request capture on // focus here. mFocusState = FOCUSING_SNAP_ON_FINISH; } else if (mFocusState == FOCUS_NOT_STARTED) { // Focus key down event is dropped for some reasons. Just ignore. } } private void doFocus(boolean pressed) { if (pressed) { // Focus key down. if (mPreviewing) { autoFocus(); } else if (mCaptureObject != null) { // Save and restart preview mCaptureObject.onSnap(); } } else { // Focus key up. if (mFocusState != FOCUSING_SNAP_ON_FINISH) { // User releases half-pressed focus key. clearFocusState(); updateFocusIndicator(); } } } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { mSurfaceView.setVisibility(View.VISIBLE); // if we're creating the surface, start the preview as well. boolean preview = holder.isCreating(); setViewFinder(w, h, preview); mCaptureObject = mImageCapture; } public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; } public void surfaceDestroyed(SurfaceHolder holder) { stopPreview(); mSurfaceHolder = null; } private void closeCamera() { if (mCameraDevice != null) { mCameraDevice.release(); mCameraDevice = null; mPreviewing = false; } } private boolean ensureCameraDevice() { if (mCameraDevice == null) { mCameraDevice = android.hardware.Camera.open(); } return mCameraDevice != null; } - private boolean isLastPictureValid() { - boolean isValid = true; - if (mLastPictureUri == null) return false; - try { - mContentResolver.openFileDescriptor(mLastPictureUri, "r").close(); - } - catch (Exception ex) { - isValid = false; - Log.e(TAG, ex.toString()); - } - return isValid; - } - private void updateLastImage() { ImageManager.IImageList list = ImageManager.instance().allImages( this, mContentResolver, dataLocation(), ImageManager.INCLUDE_IMAGES, ImageManager.SORT_ASCENDING, ImageManager.CAMERA_IMAGE_BUCKET_ID); int count = list.getCount(); if (count > 0) { ImageManager.IImage image = list.getImageAt(count-1); - mLastPictureUri = image.fullSizeImageUri(); - Log.v(TAG, "updateLastImage: count="+ count + - ", lastPictureUri="+mLastPictureUri); - setLastPictureThumb(image.miniThumbBitmap(), mLastPictureUri); + Uri uri = image.fullSizeImageUri(); + mThumbController.setData(uri, image.miniThumbBitmap()); } else { - mLastPictureUri = null; + mThumbController.setData(null, null); } list.deactivate(); } private void restartPreview() { VideoPreview surfaceView = mSurfaceView; // make sure the surfaceview fills the whole screen when previewing surfaceView.setAspectRatio(VideoPreview.DONT_CARE); setViewFinder(mOriginalViewFinderWidth, mOriginalViewFinderHeight, true); mStatus = IDLE; // Calculate this in advance of each shot so we don't add to shutter latency. It's true that // someone else could write to the SD card in the mean time and fill it, but that could have // happened between the shutter press and saving the JPEG too. // TODO: The best longterm solution is to write a reserve file of maximum JPEG size, always // let the user take a picture, and delete that file if needed to save the new photo. calculatePicturesRemaining(); - if (!isImageCaptureIntent() && !isLastPictureValid()) { + if (!mIsImageCaptureIntent && !mThumbController.isUriValid()) { updateLastImage(); } - if (mShouldShowLastPictureButton) { - mShouldShowLastPictureButton = false; - mLastPictureButton.setVisibility(View.VISIBLE); - Animation a = mShowLastPictureButtonAnimation; - a.setDuration(500); - mLastPictureButton.setAnimation(a); - } - - if (mShouldTransitionThumbnails) { - mShouldTransitionThumbnails = false; - mThumbnailTransition.startTransition(500); + if (!mIsImageCaptureIntent) { + mThumbController.updateDisplayIfNeeded(); } } private void setViewFinder(int w, int h, boolean startPreview) { if (mPausing) return; if (mPreviewing && w == mViewFinderWidth && h == mViewFinderHeight) { return; } if (!ensureCameraDevice()) return; if (mSurfaceHolder == null) return; if (isFinishing()) return; if (mPausing) return; // remember view finder size mViewFinderWidth = w; mViewFinderHeight = h; if (mOriginalViewFinderHeight == 0) { mOriginalViewFinderWidth = w; mOriginalViewFinderHeight = h; } if (startPreview == false) return; /* * start the preview if we're asked to... */ // we want to start the preview and we're previewing already, // stop the preview first (this will blank the screen). if (mPreviewing) stopPreview(); // this blanks the screen if the surface changed, no-op otherwise try { mCameraDevice.setPreviewDisplay(mSurfaceHolder); } catch (IOException exception) { mCameraDevice.release(); mCameraDevice = null; // TODO: add more exception handling logic here return; } // request the preview size, the hardware may not honor it, // if we depended on it we would have to query the size again mParameters = mCameraDevice.getParameters(); mParameters.setPreviewSize(w, h); try { mCameraDevice.setParameters(mParameters); } catch (IllegalArgumentException e) { // Ignore this error, it happens in the simulator. } final long wallTimeStart = SystemClock.elapsedRealtime(); final long threadTimeStart = Debug.threadCpuTimeNanos(); final Object watchDogSync = new Object(); Thread watchDog = new Thread(new Runnable() { public void run() { int next_warning = 1; while (true) { try { synchronized (watchDogSync) { watchDogSync.wait(1000); } } catch (InterruptedException ex) { // } - if (mPreviewing) - break; + if (mPreviewing) break; int delay = (int) (SystemClock.elapsedRealtime() - wallTimeStart) / 1000; if (delay >= next_warning) { if (delay < 120) { Log.e(TAG, "preview hasn't started yet in " + delay + " seconds"); } else { Log.e(TAG, "preview hasn't started yet in " + (delay / 60) + " minutes"); } if (next_warning < 60) { next_warning <<= 1; if (next_warning == 16) { next_warning = 15; } } else { next_warning += 60; } } } } }); watchDog.start(); if (Config.LOGV) Log.v(TAG, "calling mCameraDevice.startPreview"); try { mCameraDevice.startPreview(); } catch (Throwable e) { // TODO: change Throwable to IOException once android.hardware.Camera.startPreview // properly declares that it throws IOException. } mPreviewing = true; synchronized (watchDogSync) { watchDogSync.notify(); } long threadTimeEnd = Debug.threadCpuTimeNanos(); long wallTimeEnd = SystemClock.elapsedRealtime(); if ((wallTimeEnd - wallTimeStart) > 3000) { Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart) + " ms. Thread time was" + (threadTimeEnd - threadTimeStart) / 1000000 + " ms."); } } private void stopPreview() { if (mCameraDevice != null && mPreviewing) { mCameraDevice.stopPreview(); } mPreviewing = false; // If auto focus was in progress, it would have been canceled. clearFocusState(); } void gotoGallery() { MenuHelper.gotoCameraImageGallery(this); } private void viewLastImage() { - Uri targetUri = mLastPictureUri; - if (targetUri != null && isLastPictureValid()) { + if (mThumbController.isUriValid()) { + Uri targetUri = mThumbController.getUri(); targetUri = targetUri.buildUpon(). appendQueryParameter("bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build(); Intent intent = new Intent(Intent.ACTION_VIEW, targetUri); intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true); intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true); intent.putExtra("com.android.camera.ReviewMode", true); try { startActivity(intent); } catch (android.content.ActivityNotFoundException ex) { // ignore. } } else { Log.e(TAG, "Can't view last image."); } } void keep() { if (mCaptureObject != null) { mCaptureObject.dismissFreezeFrame(); } }; private ImageManager.IImage getImageForURI(Uri uri) { ImageManager.IImageList list = ImageManager.instance().allImages( this, mContentResolver, dataLocation(), ImageManager.INCLUDE_IMAGES, ImageManager.SORT_ASCENDING); ImageManager.IImage image = list.getImageForUri(uri); list.deactivate(); return image; } private void startReceivingLocationUpdates() { if (mLocationManager != null) { try { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 1000, 0F, mLocationListeners[1]); } catch (java.lang.SecurityException ex) { // ok } catch (IllegalArgumentException ex) { if (Config.LOGD) { Log.d(TAG, "provider does not exist " + ex.getMessage()); } } try { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 1000, 0F, mLocationListeners[0]); } catch (java.lang.SecurityException ex) { // ok } catch (IllegalArgumentException ex) { if (Config.LOGD) { Log.d(TAG, "provider does not exist " + ex.getMessage()); } } } } private void stopReceivingLocationUpdates() { if (mLocationManager != null) { for (int i = 0; i < mLocationListeners.length; i++) { try { mLocationManager.removeUpdates(mLocationListeners[i]); } catch (Exception ex) { // ok } } } } private Location getCurrentLocation() { - Location l = null; - // go in best to worst order for (int i = 0; i < mLocationListeners.length; i++) { - l = mLocationListeners[i].current(); - if (l != null) - break; + Location l = mLocationListeners[i].current(); + if (l != null) return l; } - - return l; + return null; } @Override public void onOptionsMenuClosed(Menu menu) { super.onOptionsMenuClosed(menu); if (mImageSavingItem) { // save the image if we presented the "advanced" menu // which happens if "menu" is pressed while in // SNAPSHOT_IN_PROGRESS or SNAPSHOT_COMPLETED modes keep(); mHandler.sendEmptyMessage(RESTART_PREVIEW); } } @Override public boolean onMenuOpened(int featureId, Menu menu) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { if (mStatus == SNAPSHOT_IN_PROGRESS) { cancelAutomaticPreviewRestart(); } } return super.onMenuOpened(featureId, menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); for (int i = 1; i <= MenuHelper.MENU_ITEM_MAX; i++) { if (i != MenuHelper.GENERIC_ITEM) { menu.setGroupVisible(i, false); } } if (mStatus == SNAPSHOT_IN_PROGRESS || mStatus == SNAPSHOT_COMPLETED) { menu.setGroupVisible(MenuHelper.IMAGE_SAVING_ITEM, true); mImageSavingItem = true; } else { menu.setGroupVisible(MenuHelper.IMAGE_MODE_ITEM, true); mImageSavingItem = false; } return true; } private void cancelAutomaticPreviewRestart() { mKeepAndRestartPreview = false; mHandler.removeMessages(RESTART_PREVIEW); } private boolean isImageCaptureIntent() { String action = getIntent().getAction(); return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)); } private void showPostCaptureAlert() { - if (isImageCaptureIntent()) { + if (mIsImageCaptureIntent) { mPostCaptureAlert.setVisibility(View.VISIBLE); int[] pickIds = {R.id.attach, R.id.cancel}; for(int id : pickIds) { View view = mPostCaptureAlert.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } } private void hidePostCaptureAlert() { - if (isImageCaptureIntent()) { + if (mIsImageCaptureIntent) { mPostCaptureAlert.setVisibility(View.INVISIBLE); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); - if (isImageCaptureIntent()) { + if (mIsImageCaptureIntent) { // No options menu for attach mode. return false; } else { addBaseMenuItems(menu); } return true; } SelectedImageGetter mSelectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return getImageForURI(getCurrentImageUri()); } public Uri getCurrentImageUri() { keep(); return mCaptureObject.getLastCaptureUri(); } }; private int calculatePicturesRemaining() { mPicturesRemaining = MenuHelper.calculatePicturesRemaining(); return mPicturesRemaining; } private void addBaseMenuItems(Menu menu) { MenuHelper.addSwitchModeMenuItem(menu, this, true); { MenuItem gallery = menu.add(MenuHelper.IMAGE_MODE_ITEM, MENU_GALLERY_PHOTOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } { MenuItem gallery = menu.add(MenuHelper.VIDEO_MODE_ITEM, MENU_GALLERY_VIDEOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } MenuItem item = menu.add(MenuHelper.GENERIC_ITEM, MENU_SETTINGS, 0, R.string.settings).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(); intent.setClass(Camera.this, CameraSettings.class); startActivity(intent); return true; } }); item.setIcon(android.R.drawable.ic_menu_preferences); } } diff --git a/src/com/android/camera/ImageManager.java b/src/com/android/camera/ImageManager.java index d7cfc2b..073b8db 100755 --- a/src/com/android/camera/ImageManager.java +++ b/src/com/android/camera/ImageManager.java @@ -3688,517 +3688,522 @@ public class ImageManager { static public Bitmap extractMiniThumb(Bitmap source, int width, int height, boolean recycle) { if (source == null) { return null; } float scale; if (source.getWidth() < source.getHeight()) { scale = width / (float)source.getWidth(); } else { scale = height / (float)source.getHeight(); } Matrix matrix = new Matrix(); matrix.setScale(scale, scale); Bitmap miniThumbnail = ImageLoader.transform(matrix, source, width, height, false); if (recycle && miniThumbnail != source) { source.recycle(); } return miniThumbnail; } // Rotates the bitmap by the specified degree. // If a new bitmap is created, the original bitmap is recycled. static Bitmap rotate(Bitmap b, int degrees) { if (degrees != 0 && b != null) { Matrix m = new Matrix(); m.setRotate(degrees, (float) b.getWidth() / 2, (float) b.getHeight() / 2); try { Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true); if (b != b2) { b.recycle(); b = b2; } } catch (OutOfMemoryError ex) { // We have no memory to rotate. Return the original bitmap. } } return b; } public static int roundOrientation(int orientationInput) { int orientation = orientationInput; if (orientation == -1) orientation = 0; orientation = orientation % 360; int retVal; if (orientation < (0*90) + 45) { retVal = 0; } else if (orientation < (1*90) + 45) { retVal = 90; } else if (orientation < (2*90) + 45) { retVal = 180; } else if (orientation < (3*90) + 45) { retVal = 270; } else { retVal = 0; } if (VERBOSE) Log.v(TAG, "map orientation " + orientationInput + " to " + retVal); return retVal; } /** * @return true if the mimetype is an image mimetype. */ public static boolean isImageMimeType(String mimeType) { return mimeType.startsWith("image/"); } /** * @return true if the mimetype is a video mimetype. */ public static boolean isVideoMimeType(String mimeType) { return mimeType.startsWith("video/"); } /** * @return true if the image is an image. */ public static boolean isImage(IImage image) { return isImageMimeType(image.getMimeType()); } /** * @return true if the image is a video. */ public static boolean isVideo(IImage image) { return isVideoMimeType(image.getMimeType()); } public Uri addImage( final Context ctx, final ContentResolver cr, final String imageName, final String description, final long dateTaken, final Location location, final int orientation, final String directory, final String filename) { ContentValues values = new ContentValues(7); values.put(Images.Media.TITLE, imageName); values.put(Images.Media.DISPLAY_NAME, imageName); values.put(Images.Media.DESCRIPTION, description); values.put(Images.Media.DATE_TAKEN, dateTaken); values.put(Images.Media.MIME_TYPE, "image/jpeg"); values.put(Images.Media.ORIENTATION, orientation); File parentFile = new File(directory); // Lowercase the path for hashing. This avoids duplicate buckets if the filepath // case is changed externally. // Keep the original case for display. String path = parentFile.toString().toLowerCase(); String name = parentFile.getName(); if (VERBOSE) Log.v(TAG, "addImage id is " + path.hashCode() + "; name " + name + "; path is " + path); if (location != null) { if (VERBOSE) { Log.v(TAG, "lat long " + location.getLatitude() + " / " + location.getLongitude()); } values.put(Images.Media.LATITUDE, location.getLatitude()); values.put(Images.Media.LONGITUDE, location.getLongitude()); } if (directory != null && filename != null) { String value = directory + "/" + filename; values.put("_data", value); } long t3 = System.currentTimeMillis(); Uri uri = cr.insert(sStorageURI, values); // The line above will create a filename that ends in .jpg // That filename is what will be handed to gmail when a user shares a photo. // Gmail gets the name of the picture attachment from the "DISPLAY_NAME" field. // Extract the filename and jam it into the display name. Cursor c = cr.query( uri, new String [] { ImageColumns._ID, Images.Media.DISPLAY_NAME, "_data" }, null, null, null); if (c.moveToFirst()) { String filePath = c.getString(2); if (filePath != null) { int pos = filePath.lastIndexOf("/"); if (pos >= 0) { filePath = filePath.substring(pos + 1); // pick off the filename c.updateString(1, filePath); c.commitUpdates(); } } } c.close(); return uri; } public IAddImage_cancelable storeImage( final Uri uri, final Context ctx, final ContentResolver cr, final int orientation, final Bitmap source, final byte [] jpegData) { class AddImageCancelable extends BaseCancelable implements IAddImage_cancelable { private IGetBoolean_cancelable mSaveImageCancelable; public boolean doCancelWork() { if (VERBOSE) { Log.v(TAG, "calling AddImageCancelable.cancel() " + mSaveImageCancelable); } if (mSaveImageCancelable != null) { mSaveImageCancelable.cancel(); } return true; } public void get() { if (source == null && jpegData == null) { throw new IllegalArgumentException("source cannot be null"); } try { long t1 = System.currentTimeMillis(); synchronized (this) { if (mCancel) { throw new CanceledException(); } } long id = ContentUris.parseId(uri); BaseImageList il = new ImageList(ctx, cr, sStorageURI, sThumbURI, SORT_ASCENDING, null); ImageManager.Image image = new Image(id, 0, cr, il, il.getCount(), 0); long t5 = System.currentTimeMillis(); Cursor c = cr.query( uri, new String [] { ImageColumns._ID, ImageColumns.MINI_THUMB_MAGIC, "_data" }, null, null, null); c.moveToPosition(0); synchronized (this) { checkCanceled(); mSaveImageCancelable = image.saveImageContents(source, jpegData, orientation, true, c); } if (mSaveImageCancelable.get()) { long t6 = System.currentTimeMillis(); if (VERBOSE) Log.v(TAG, "saveImageContents took " + (t6-t5)); if (VERBOSE) Log.v(TAG, "updating new picture with id " + id); c.updateLong(1, id); c.commitUpdates(); c.close(); long t7 = System.currentTimeMillis(); if (VERBOSE) Log.v(TAG, "commit updates to save mini thumb took " + (t7-t6)); } else { c.close(); throw new CanceledException(); } } catch (CanceledException ex) { if (VERBOSE) { Log.v(TAG, "caught CanceledException"); } if (uri != null) { if (VERBOSE) { Log.v(TAG, "canceled... cleaning up this uri: " + uri); } cr.delete(uri, null, null); } acknowledgeCancel(); } } } return new AddImageCancelable(); } static public IImageList makeImageList(Uri uri, Context ctx, int sort) { ContentResolver cr = ctx.getContentResolver(); String uriString = (uri != null) ? uri.toString() : ""; // TODO we need to figure out whether we're viewing // DRM images in a better way. Is there a constant // for content://drm somewhere?? IImageList imageList; if (uriString.startsWith("content://drm")) { imageList = ImageManager.instance().allImages( ctx, cr, ImageManager.DataLocation.ALL, ImageManager.INCLUDE_DRM_IMAGES, sort); } else if (!uriString.startsWith(MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString()) && !uriString.startsWith(MediaStore.Images.Media.INTERNAL_CONTENT_URI.toString())) { imageList = ImageManager.instance().new SingleImageList(cr, uri); } else { String bucketId = uri.getQueryParameter("bucketId"); if (VERBOSE) Log.v(TAG, "bucketId is " + bucketId); imageList = ImageManager.instance().allImages( ctx, cr, ImageManager.DataLocation.ALL, ImageManager.INCLUDE_IMAGES, sort, bucketId); } return imageList; } public IImageList emptyImageList() { return new IImageList() { public void checkThumbnails(ImageManager.IImageList.ThumbCheckCallback cb, int totalThumbnails) { } public void commitChanges() { } public void deactivate() { } public HashMap<String, String> getBucketIds() { return new HashMap<String,String>(); } public int getCount() { return 0; } public boolean isEmpty() { return true; } public IImage getImageAt(int i) { return null; } public IImage getImageForUri(Uri uri) { return null; } public boolean removeImage(IImage image) { return false; } public void removeImageAt(int i) { } public void removeOnChangeListener(ImageManager.IImageList.OnChange changeCallback) { } public void setOnChangeListener(ImageManager.IImageList.OnChange changeCallback, Handler h) { } }; } public IImageList allImages(Context ctx, ContentResolver cr, DataLocation location, int inclusion, int sort) { return allImages(ctx, cr, location, inclusion, sort, null, null); } public IImageList allImages(Context ctx, ContentResolver cr, DataLocation location, int inclusion, int sort, String bucketId) { return allImages(ctx, cr, location, inclusion, sort, bucketId, null); } public IImageList allImages(Context ctx, ContentResolver cr, DataLocation location, int inclusion, int sort, String bucketId, Uri specificImageUri) { if (VERBOSE) { Log.v(TAG, "allImages " + location + " " + ((inclusion&INCLUDE_IMAGES)!=0) + " + v=" + ((inclusion&INCLUDE_VIDEOS)!=0)); } if (cr == null) { return null; } else { // false ==> don't require write access boolean haveSdCard = hasStorage(false); if (true) { // use this code to merge videos and stills into the same list ArrayList<IImageList> l = new ArrayList<IImageList>(); if (VERBOSE) { Log.v(TAG, "initializing ... haveSdCard == " + haveSdCard + "; inclusion is " + String.format("%x", inclusion)); } if (specificImageUri != null) { try { if (specificImageUri.getScheme().equalsIgnoreCase("content")) l.add(new ImageList(ctx, cr, specificImageUri, sThumbURI, sort, bucketId)); else l.add(new SingleImageList(cr, specificImageUri)); } catch (UnsupportedOperationException ex) { } } else { if (haveSdCard && location != DataLocation.INTERNAL) { if ((inclusion & INCLUDE_IMAGES) != 0) { try { l.add(new ImageList(ctx, cr, sStorageURI, sThumbURI, sort, bucketId)); } catch (UnsupportedOperationException ex) { } } if ((inclusion & INCLUDE_VIDEOS) != 0) { try { l.add(new VideoList(ctx, cr, sVideoStorageURI, sVideoThumbURI, sort, bucketId)); } catch (UnsupportedOperationException ex) { } } } if (location == DataLocation.INTERNAL || location == DataLocation.ALL) { if ((inclusion & INCLUDE_IMAGES) != 0) { try { l.add(new ImageList(ctx, cr, Images.Media.INTERNAL_CONTENT_URI, Images.Thumbnails.INTERNAL_CONTENT_URI, sort, bucketId)); } catch (UnsupportedOperationException ex) { } } if ((inclusion & INCLUDE_DRM_IMAGES) != 0) { try { l.add(new DrmImageList(ctx, cr, DrmStore.Images.CONTENT_URI, sort, bucketId)); } catch (UnsupportedOperationException ex) { } } } } IImageList [] imageList = l.toArray(new IImageList[l.size()]); return new ImageListUber(imageList, sort); } else { if (haveSdCard && location != DataLocation.INTERNAL) { return new ImageList(ctx, cr, sStorageURI, sThumbURI, sort, bucketId); } else { return new ImageList(ctx, cr, Images.Media.INTERNAL_CONTENT_URI, Images.Thumbnails.INTERNAL_CONTENT_URI, sort, bucketId); } } } } // Create a temporary file to see whether a volume is really writeable. It's important not to // put it in the root directory which may have a limit on the number of files. static private boolean checkFsWritable() { String directoryName = Environment.getExternalStorageDirectory().toString() + "/DCIM"; File directory = new File(directoryName); if (!directory.isDirectory()) { if (!directory.mkdirs()) { return false; } } File f = new File(directoryName, ".probe"); try { // Remove stale file if any if (f.exists()) { f.delete(); } if (!f.createNewFile()) return false; f.delete(); return true; } catch (IOException ex) { return false; } } static public boolean hasStorage() { return hasStorage(true); } static public boolean hasStorage(boolean requireWriteAccess) { //TODO: After fix the bug, add "if (VERBOSE)" before logging errors. String state = Environment.getExternalStorageState(); Log.v(TAG, "storage state is " + state); if (Environment.MEDIA_MOUNTED.equals(state)) { if (requireWriteAccess) { boolean writable = checkFsWritable(); Log.v(TAG, "storage writable is " + writable); return writable; } else { return true; } } else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; } public static Cursor query(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { try { ContentResolver resolver = context.getContentResolver(); if (resolver == null) { return null; } return resolver.query(uri, projection, selection, selectionArgs, sortOrder); } catch (UnsupportedOperationException ex) { return null; } } public static boolean isMediaScannerScanning(Context context) { boolean result = false; Cursor cursor = query(context, MediaStore.getMediaScannerUri(), new String [] { MediaStore.MEDIA_SCANNER_VOLUME }, null, null, null); if (cursor != null) { if (cursor.getCount() == 1) { cursor.moveToFirst(); result = "external".equals(cursor.getString(0)); } cursor.close(); } if (VERBOSE) Log.v(TAG, ">>>>>>>>>>>>>>>>>>>>>>>>> isMediaScannerScanning returning " + result); return result; } /** * Create a video thumbnail for a video. May return null if the video is corrupt. * @param filePath * @return */ public static Bitmap createVideoThumbnail(String filePath) { Bitmap bitmap = null; MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY); retriever.setDataSource(filePath); bitmap = retriever.captureFrame(); } catch(IllegalArgumentException ex) { // Assume this is a corrupt video file } catch (RuntimeException ex) { // Assume this is a corrupt video file. } finally { try { retriever.release(); } catch (RuntimeException ex) { // Ignore failures while cleaning up. } } return bitmap; } - public static String getLastThumbPath() { + public static String getLastImageThumbPath() { return Environment.getExternalStorageDirectory().toString() + - "/DCIM/.thumbnails/camera_last_thumb"; + "/DCIM/.thumbnails/image_last_thumb"; + } + + public static String getLastVideoThumbPath() { + return Environment.getExternalStorageDirectory().toString() + + "/DCIM/.thumbnails/video_last_thumb"; } } diff --git a/src/com/android/camera/ThumbnailController.java b/src/com/android/camera/ThumbnailController.java new file mode 100644 index 0000000..c35c467 --- /dev/null +++ b/src/com/android/camera/ThumbnailController.java @@ -0,0 +1,233 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.camera; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.Closeable; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; + +import android.content.ContentResolver; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.PorterDuff; +import android.graphics.PorterDuffXfermode; +import android.graphics.RectF; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.LayerDrawable; +import android.graphics.drawable.TransitionDrawable; +import android.net.Uri; +import android.util.Log; +import android.view.View; +import android.view.ViewGroup.LayoutParams; +import android.view.animation.AlphaAnimation; +import android.view.animation.Animation; +import android.widget.ImageView; + +// A controller shows thumbnail picture on a button. The thumbnail picture +// corresponds to a URI of the original picture/video. The thumbnail bitmap +// and the URI can be saved to a file (and later loaded from it). +// +// public ThumbnailController(ImageView button) +// public void setData(Uri uri, Bitmap original) +// public void updateDisplayIfNeeded() +// public Uri getUri() +// public Bitmap getThumb() +// public boolean storeData(String filePath) +// public boolean loadData(String filePath) +// + +public class ThumbnailController { + private static final String TAG = "ThumbnailController"; + private ContentResolver mContentResolver; + private Uri mUri; + private Bitmap mThumb; + private ImageView mButton; + private Drawable mFrame; + private Drawable[] mThumbs; + private TransitionDrawable mThumbTransition; + private boolean mShouldAnimateThumb; + private Animation mShowButtonAnimation = new AlphaAnimation(0F, 1F); + private boolean mShouldAnimateButton; + + // The "frame" is a drawable we want to put on top of the thumbnail. + public ThumbnailController(ImageView button, Drawable frame, + ContentResolver contentResolver) { + mButton = button; + mFrame = frame; + mContentResolver = contentResolver; + mShowButtonAnimation.setDuration(500); + } + + public void setData(Uri uri, Bitmap original) { + // Make sure uri and original are consistently both null or both non-null. + if (uri == null || original == null) { + uri = null; + original = null; + } + mUri = uri; + updateThumb(original); + } + + public Uri getUri() { + return mUri; + } + + public Bitmap getThumb() { + return mThumb; + } + + private static final int BUFSIZE = 4096; + + // Stores the data from the specified file. + // Returns true for success. + public boolean storeData(String filePath) { + if (mUri == null) { + return false; + } + + FileOutputStream f = null; + BufferedOutputStream b = null; + DataOutputStream d = null; + try { + f = new FileOutputStream(filePath); + b = new BufferedOutputStream(f, BUFSIZE); + d = new DataOutputStream(b); + d.writeUTF(mUri.toString()); + mThumb.compress(Bitmap.CompressFormat.PNG, 100, d); + d.close(); + } catch (IOException e) { + return false; + } finally { + closeSilently(f); + closeSilently(b); + closeSilently(d); + } + return true; + } + + // Loads the data from the specified file. + // Returns true for success. + public boolean loadData(String filePath) { + FileInputStream f = null; + BufferedInputStream b = null; + DataInputStream d = null; + try { + f = new FileInputStream(filePath); + b = new BufferedInputStream(f, BUFSIZE); + d = new DataInputStream(b); + Uri uri = Uri.parse(d.readUTF()); + Bitmap thumb = BitmapFactory.decodeStream(d); + setData(uri, thumb); + d.close(); + } catch (IOException e) { + return false; + } finally { + closeSilently(f); + closeSilently(b); + closeSilently(d); + } + return true; + } + + private void closeSilently(Closeable c) { + if (c != null) { + try { + c.close(); + } catch (IOException e) { + // ignore + } + } + } + + public void updateDisplayIfNeeded() { + if (mUri == null) { + mButton.setVisibility(View.INVISIBLE); + return; + } + + if (mShouldAnimateButton) { + mButton.setVisibility(View.VISIBLE); + mButton.startAnimation(mShowButtonAnimation); + mShouldAnimateButton = false; + } + + if (mShouldAnimateThumb) { + mThumbTransition.startTransition(500); + mShouldAnimateThumb = false; + } + } + + private void updateThumb(Bitmap original) { + if (original == null) { + mThumb = null; + mThumbs = null; + return; + } + + // Make the mini-thumb size smaller than the button size so that the image corners + // don't peek out from the rounded corners of the frame_thumb graphic: + final int PADDING_WIDTH = 12; + final int PADDING_HEIGHT = 12; + LayoutParams layoutParams = mButton.getLayoutParams(); + final int miniThumbWidth = layoutParams.width - 2 * PADDING_WIDTH; + final int miniThumbHeight = layoutParams.height - 2 * PADDING_HEIGHT; + mThumb = ImageManager.extractMiniThumb( + original, miniThumbWidth, miniThumbHeight, false); + + Drawable[] vignetteLayers = new Drawable[2]; + vignetteLayers[0] = mFrame; + if (mThumbs == null) { + mThumbs = new Drawable[2]; + mThumbs[1] = new BitmapDrawable(mThumb); + vignetteLayers[1] = mThumbs[1]; + mShouldAnimateThumb = false; + } else { + mThumbs[0] = mThumbs[1]; + mThumbs[1] = new BitmapDrawable(mThumb); + mThumbTransition = new TransitionDrawable(mThumbs); + vignetteLayers[1] = mThumbTransition; + mShouldAnimateThumb = true; + } + + LayerDrawable mVignette = new LayerDrawable(vignetteLayers); + mVignette.setLayerInset(1, PADDING_WIDTH, PADDING_HEIGHT, + PADDING_WIDTH, PADDING_HEIGHT); + mButton.setImageDrawable(mVignette); + + if (mButton.getVisibility() != View.VISIBLE) { + mShouldAnimateButton = true; + } + } + + public boolean isUriValid() { + if (mUri == null) return false; + try { + mContentResolver.openFileDescriptor(mUri, "r").close(); + } catch (Exception ex) { + return false; + } + return true; + } +} diff --git a/src/com/android/camera/VideoCamera.java b/src/com/android/camera/VideoCamera.java index 0d6e74d..7f1b010 100644 --- a/src/com/android/camera/VideoCamera.java +++ b/src/com/android/camera/VideoCamera.java @@ -1,1211 +1,1184 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import android.app.Activity; -import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; +import android.database.Cursor; import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Canvas; -import android.graphics.Matrix; -import android.graphics.Paint; -import android.graphics.PorterDuff; -import android.graphics.PorterDuffXfermode; -import android.graphics.RectF; -import android.graphics.drawable.ColorDrawable; -import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; -import android.graphics.drawable.LayerDrawable; -import android.graphics.drawable.TransitionDrawable; import android.location.LocationManager; -import android.media.MediaMetadataRetriever; import android.media.MediaRecorder; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.StatFs; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.MediaStore.Video; import android.text.format.DateFormat; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.View; -import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.WindowManager; import android.view.MenuItem.OnMenuItemClickListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class VideoCamera extends Activity implements View.OnClickListener, ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback, MediaRecorder.OnErrorListener, MediaRecorder.OnInfoListener { private static final String TAG = "videocamera"; private static final boolean DEBUG = true; private static final boolean DEBUG_SUPPRESS_AUDIO_RECORDING = DEBUG && false; - private static final boolean DEBUG_DO_NOT_REUSE_MEDIA_RECORDER = DEBUG && true; - private static final boolean DEBUG_LOG_APP_LIFECYCLE = DEBUG && false; private static final int CLEAR_SCREEN_DELAY = 4; private static final int UPDATE_RECORD_TIME = 5; private static final int SCREEN_DELAY = 2 * 60 * 1000; private static final long NO_STORAGE_ERROR = -1L; private static final long CANNOT_STAT_ERROR = -2L; private static final long LOW_STORAGE_THRESHOLD = 512L * 1024L; private static final long SHARE_FILE_LENGTH_LIMIT = 3L * 1024L * 1024L; private static final int STORAGE_STATUS_OK = 0; private static final int STORAGE_STATUS_LOW = 1; private static final int STORAGE_STATUS_NONE = 2; public static final int MENU_SETTINGS = 6; public static final int MENU_GALLERY_PHOTOS = 7; public static final int MENU_GALLERY_VIDEOS = 8; public static final int MENU_SAVE_GALLERY_PHOTO = 34; public static final int MENU_SAVE_PLAY_VIDEO = 35; public static final int MENU_SAVE_SELECT_VIDEO = 36; public static final int MENU_SAVE_NEW_VIDEO = 37; SharedPreferences mPreferences; private static final float VIDEO_ASPECT_RATIO = 176.0f / 144.0f; VideoPreview mVideoPreview; SurfaceHolder mSurfaceHolder = null; - ImageView mBlackout = null; ImageView mVideoFrame; - Bitmap mVideoFrameBitmap; - private TransitionDrawable mThumbnailTransition; - private Drawable[] mThumbnails; - private boolean mShouldTransitionThumbnails; + + private boolean mIsVideoCaptureIntent; + // mLastPictureButton and mThumbController + // are non-null only if isVideoCaptureIntent() is true; private ImageView mLastPictureButton; - private Bitmap mLastPictureThumb; + private ThumbnailController mThumbController; private static final int MAX_RECORDING_DURATION_MS = 10 * 60 * 1000; private int mStorageStatus = STORAGE_STATUS_OK; private MediaRecorder mMediaRecorder; private boolean mMediaRecorderRecording = false; private long mRecordingStartTime; // The video file that the hardware camera is about to record into // (or is recording into.) private String mCameraVideoFilename; private FileDescriptor mCameraVideoFileDescriptor; // The video file that has already been recorded, and that is being // examined by the user. private String mCurrentVideoFilename; private long mCurrentVideoFileLength = 0L; private Uri mCurrentVideoUri; private ContentValues mCurrentVideoValues; boolean mPausing = false; static ContentResolver mContentResolver; int mCurrentZoomIndex = 0; private ShutterButton mShutterButton; private TextView mRecordingTimeView; private boolean mRecordingTimeCountsDown = false; ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>(); View mPostPictureAlert; LocationManager mLocationManager = null; private Handler mHandler = new MainHandler(); /** This Handler is used to post message back onto the main thread of the application */ private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case CLEAR_SCREEN_DELAY: { clearScreenOnFlag(); break; } case UPDATE_RECORD_TIME: { if (mMediaRecorderRecording) { long now = SystemClock.uptimeMillis(); long delta = now - mRecordingStartTime; // Starting a minute before reaching the max duration // limit, we'll countdown the remaining time instead. boolean countdown_remaining_time = (delta >= MAX_RECORDING_DURATION_MS - 60000); if (countdown_remaining_time) { delta = Math.max(0, MAX_RECORDING_DURATION_MS - delta); } long seconds = (delta + 500) / 1000; // round to nearest long minutes = seconds / 60; long hours = minutes / 60; long remainderMinutes = minutes - (hours * 60); long remainderSeconds = seconds - (minutes * 60); String secondsString = Long.toString(remainderSeconds); if (secondsString.length() < 2) { secondsString = "0" + secondsString; } String minutesString = Long.toString(remainderMinutes); if (minutesString.length() < 2) { minutesString = "0" + minutesString; } String text = minutesString + ":" + secondsString; if (hours > 0) { String hoursString = Long.toString(hours); if (hoursString.length() < 2) { hoursString = "0" + hoursString; } text = hoursString + ":" + text; } mRecordingTimeView.setText(text); if (mRecordingTimeCountsDown != countdown_remaining_time) { // Avoid setting the color on every update, do it only // when it needs changing. mRecordingTimeCountsDown = countdown_remaining_time; int color = getResources().getColor( countdown_remaining_time ? R.color.recording_time_remaining_text : R.color.recording_time_elapsed_text); mRecordingTimeView.setTextColor(color); } // Work around a limitation of the T-Mobile G1: The T-Mobile // hardware blitter can't pixel-accurately scale and clip at the same time, // and the SurfaceFlinger doesn't attempt to work around this limitation. // In order to avoid visual corruption we must manually refresh the entire // surface view when changing any overlapping view's contents. mVideoPreview.invalidate(); mHandler.sendEmptyMessageDelayed(UPDATE_RECORD_TIME, 1000); } break; } default: Log.v(TAG, "Unhandled message: " + msg.what); break; } } }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_EJECT)) { updateAndShowStorageHint(false); stopVideoRecording(); initializeVideo(); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { updateAndShowStorageHint(true); initializeVideo(); } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) { // SD card unavailable // handled in ACTION_MEDIA_EJECT } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { Toast.makeText(VideoCamera.this, getResources().getString(R.string.wait), 5000); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { updateAndShowStorageHint(true); } } }; static private String createName(long dateTaken) { return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString(); } /** Called with the activity is first created. */ @Override public void onCreate(Bundle icicle) { - if (DEBUG_LOG_APP_LIFECYCLE) { - Log.v(TAG, "onCreate " + this.hashCode()); - } super.onCreate(icicle); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mContentResolver = getContentResolver(); //setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.video_camera); mVideoPreview = (VideoPreview) findViewById(R.id.camera_preview); mVideoPreview.setAspectRatio(VIDEO_ASPECT_RATIO); // don't set mSurfaceHolder here. We have it set ONLY within // surfaceCreated / surfaceDestroyed, other parts of the code // assume that when it is set, the surface is also set. SurfaceHolder holder = mVideoPreview.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); - mBlackout = (ImageView) findViewById(R.id.blackout); - mBlackout.setBackgroundDrawable(new ColorDrawable(0xFF000000)); - mPostPictureAlert = findViewById(R.id.post_picture_panel); int[] ids = new int[]{R.id.play, R.id.share, R.id.discard, R.id.cancel, R.id.attach}; for (int id : ids) { findViewById(id).setOnClickListener(this); } mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); mRecordingTimeView = (TextView) findViewById(R.id.recording_time); mVideoFrame = (ImageView) findViewById(R.id.video_frame); - mLastPictureButton = (ImageView) findViewById(R.id.last_picture_button); - mLastPictureButton.setOnClickListener(this); + mIsVideoCaptureIntent = isVideoCaptureIntent(); + if (!mIsVideoCaptureIntent) { + mLastPictureButton = (ImageView) findViewById(R.id.last_picture_button); + mLastPictureButton.setOnClickListener(this); + Drawable frame = getResources().getDrawable(R.drawable.frame_thumbnail); + mThumbController = new ThumbnailController(mLastPictureButton, + frame, mContentResolver); + mThumbController.loadData(ImageManager.getLastVideoThumbPath()); + } } private void startShareVideoActivity() { if (mCurrentVideoFileLength > SHARE_FILE_LENGTH_LIMIT) { Toast.makeText(VideoCamera.this, R.string.too_large_to_attach, Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("video/3gpp"); intent.putExtra(Intent.EXTRA_STREAM, mCurrentVideoUri); try { startActivity(Intent.createChooser(intent, getText(R.string.sendVideo))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(VideoCamera.this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } public void onClick(View v) { switch (v.getId()) { case R.id.gallery: MenuHelper.gotoCameraVideoGallery(this); break; case R.id.attach: doReturnToCaller(true); break; case R.id.cancel: doReturnToCaller(false); break; case R.id.discard: { discardCurrentVideoAndStartPreview(); break; } case R.id.share: { startShareVideoActivity(); break; } case R.id.play: { doPlayCurrentVideo(); break; } case R.id.last_picture_button: { - stopPreviewAndShowAlert(); + stopVideoRecordingAndShowAlert(); break; } } } public void onShutterButtonFocus(ShutterButton button, boolean pressed) { // Do nothing (everything happens in onShutterButtonClick). } public void onShutterButtonClick(ShutterButton button) { switch (button.getId()) { case R.id.shutter_button: if (mMediaRecorderRecording) { - if (isVideoCaptureIntent()) { + if (mIsVideoCaptureIntent) { stopVideoRecordingAndShowAlert(); } else { - stopVideoRecordingAndShowThumbnail(); - doStartCaptureMode(); + stopVideoRecordingAndGetThumbnail(); + initializeVideo(); + } + } else if (isAlertVisible()) { + if (mIsVideoCaptureIntent) { + discardCurrentVideoAndStartPreview(); + } else { + hideAlertAndStartVideoRecording(); } - } else if (mVideoFrame.getVisibility() == View.VISIBLE) { - doStartCaptureMode(); - startVideoRecording(); } else { startVideoRecording(); } break; } } - private void doStartCaptureMode() { - if (isVideoCaptureIntent()) { - discardCurrentVideoAndStartPreview(); - } else { - hideVideoFrameAndStartPreview(); - } - } - private void doPlayCurrentVideo() { Log.e(TAG, "Playing current video: " + mCurrentVideoUri); Intent intent = new Intent(Intent.ACTION_VIEW, mCurrentVideoUri); try { startActivity(intent); } catch (android.content.ActivityNotFoundException ex) { Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex); } } private void discardCurrentVideoAndStartPreview() { deleteCurrentVideo(); - hideVideoFrameAndStartPreview(); + hideAlertAndStartPreview(); } private OnScreenHint mStorageHint; private void updateAndShowStorageHint(boolean mayHaveSd) { mStorageStatus = getStorageStatus(mayHaveSd); showStorageHint(); } private void showStorageHint() { String errorMessage = null; switch (mStorageStatus) { case STORAGE_STATUS_NONE: errorMessage = getString(R.string.no_storage); break; case STORAGE_STATUS_LOW: errorMessage = getString(R.string.spaceIsLow_content); } if (errorMessage != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, errorMessage); } else { mStorageHint.setText(errorMessage); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } private int getStorageStatus(boolean mayHaveSd) { long remaining = mayHaveSd ? getAvailableStorage() : NO_STORAGE_ERROR; if (remaining == NO_STORAGE_ERROR) { return STORAGE_STATUS_NONE; } return remaining < LOW_STORAGE_THRESHOLD ? STORAGE_STATUS_LOW : STORAGE_STATUS_OK; } @Override public void onResume() { - if (DEBUG_LOG_APP_LIFECYCLE) { - Log.v(TAG, "onResume " + this.hashCode()); - } super.onResume(); setScreenTimeoutLong(); mPausing = false; // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_EJECT); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); mStorageStatus = getStorageStatus(true); mHandler.postDelayed(new Runnable() { public void run() { showStorageHint(); } }, 200); - mBlackout.setVisibility(View.INVISIBLE); - if (mVideoFrameBitmap == null) { - initializeVideo(); - } else { - showVideoFrame(); - } + initializeVideo(); } @Override public void onStop() { - if (DEBUG_LOG_APP_LIFECYCLE) { - Log.v(TAG, "onStop " + this.hashCode()); - } - stopVideoRecording(); setScreenTimeoutSystemDefault(); super.onStop(); } @Override protected void onPause() { - if (DEBUG_LOG_APP_LIFECYCLE) { - Log.v(TAG, "onPause " + this.hashCode()); - } super.onPause(); - stopVideoRecording(); - hideVideoFrame(); + // This is similar to what mShutterButton.performClick() does, + // but not quite the same. + if (mMediaRecorderRecording) { + if (mIsVideoCaptureIntent) { + stopVideoRecordingAndShowAlert(); + } else { + stopVideoRecordingAndGetThumbnail(); + } + } else { + stopVideoRecording(); + } mPausing = true; unregisterReceiver(mReceiver); - mBlackout.setVisibility(View.VISIBLE); setScreenTimeoutSystemDefault(); + if (!mIsVideoCaptureIntent) { + mThumbController.storeData(ImageManager.getLastVideoThumbPath()); + } + if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { setScreenTimeoutLong(); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mMediaRecorderRecording) { mShutterButton.performClick(); return true; - } else if(isPostRecordingAlertVisible()) { - hideVideoFrameAndStartPreview(); + } else if(isAlertVisible()) { + hideAlertAndStartPreview(); return true; } break; case KeyEvent.KEYCODE_CAMERA: if (event.getRepeatCount() == 0) { mShutterButton.performClick(); return true; } break; case KeyEvent.KEYCODE_DPAD_CENTER: if (event.getRepeatCount() == 0) { mShutterButton.performClick(); return true; } break; case KeyEvent.KEYCODE_MENU: if (mMediaRecorderRecording) { mShutterButton.performClick(); return true; } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_CAMERA: mShutterButton.setPressed(false); return true; } return super.onKeyUp(keyCode, event); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { + if (mPausing) { + // We're pausing, the screen is off and we already stopped + // video recording. We don't want to start the camera again + // in this case in order to conserve power. + // The fact that surfaceChanged is called _after_ an onPause appears + // to be legitimate since in that case the lockscreen always returns + // to portrait orientation possibly triggering the notification. + return; + } + stopVideoRecording(); initializeVideo(); } public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; } public void surfaceDestroyed(SurfaceHolder holder) { mSurfaceHolder = null; } void gotoGallery() { MenuHelper.gotoCameraVideoGallery(this); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); for (int i = 1; i <= MenuHelper.MENU_ITEM_MAX; i++) { if (i != MenuHelper.GENERIC_ITEM) { menu.setGroupVisible(i, false); } } menu.setGroupVisible(MenuHelper.VIDEO_MODE_ITEM, true); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); - if (isVideoCaptureIntent()) { + if (mIsVideoCaptureIntent) { // No options menu for attach mode. return false; } else { addBaseMenuItems(menu); MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL & ~MenuHelper.INCLUDE_ROTATE_MENU, false, VideoCamera.this, mHandler, // Handler for deletion new Runnable() { public void run() { // What do we do here? // mContentResolver.delete(uri, null, null); } }, new MenuHelper.MenuInvoker() { public void run(final MenuHelper.MenuCallback cb) { } }); MenuItem gallery = menu.add(MenuHelper.IMAGE_SAVING_ITEM, MENU_SAVE_GALLERY_PHOTO, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); } return true; } private boolean isVideoCaptureIntent() { String action = getIntent().getAction(); return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action)); } private void doReturnToCaller(boolean success) { Intent resultIntent = new Intent(); int resultCode; if (success) { resultCode = RESULT_OK; resultIntent.setData(mCurrentVideoUri); } else { resultCode = RESULT_CANCELED; } setResult(resultCode, resultIntent); finish(); } /** * Returns * @return number of bytes available, or an ERROR code. */ private static long getAvailableStorage() { try { if (!ImageManager.hasStorage()) { return NO_STORAGE_ERROR; } else { String storageDirectory = Environment.getExternalStorageDirectory().toString(); StatFs stat = new StatFs(storageDirectory); return ((long)stat.getAvailableBlocks() * (long)stat.getBlockSize()); } } catch (Exception ex) { // if we can't stat the filesystem then we don't know how many // free bytes exist. It might be zero but just leave it // blank since we really don't know. return CANNOT_STAT_ERROR; } } private void cleanupEmptyFile() { if (mCameraVideoFilename != null) { File f = new File(mCameraVideoFilename); if (f.length() == 0 && f.delete()) { Log.v(TAG, "Empty video file deleted: " + mCameraVideoFilename); mCameraVideoFilename = null; } } } + // initializeVideo() starts preview and prepare media recorder. // Returns false if initializeVideo fails private boolean initializeVideo() { Log.v(TAG, "initializeVideo"); - boolean isCaptureIntent = isVideoCaptureIntent(); + + // We will call initializeVideo() again when the alert is hidden. + if (isAlertVisible()) return false; + Intent intent = getIntent(); Bundle myExtras = intent.getExtras(); - if (isCaptureIntent && myExtras != null) { + if (mIsVideoCaptureIntent && myExtras != null) { Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); if (saveUri != null) { try { mCameraVideoFileDescriptor = mContentResolver. openFileDescriptor(saveUri, "rw").getFileDescriptor(); mCurrentVideoUri = saveUri; } catch (java.io.FileNotFoundException ex) { // invalid uri Log.e(TAG, ex.toString()); } } } releaseMediaRecorder(); if (mSurfaceHolder == null) { Log.v(TAG, "SurfaceHolder is null"); return false; } mMediaRecorder = new MediaRecorder(); if (DEBUG_SUPPRESS_AUDIO_RECORDING) { Log.v(TAG, "DEBUG_SUPPRESS_AUDIO_RECORDING is true."); } else { mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); } mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mMediaRecorder.setMaxDuration(MAX_RECORDING_DURATION_MS); if (mStorageStatus != STORAGE_STATUS_OK) { mMediaRecorder.setOutputFile("/dev/null"); } else { // We try Uri in intent first. If it doesn't work, use our own instead. if (mCameraVideoFileDescriptor != null) { mMediaRecorder.setOutputFile(mCameraVideoFileDescriptor); } else { createVideoPath(); mMediaRecorder.setOutputFile(mCameraVideoFilename); } } boolean videoQualityHigh = getBooleanPreference(CameraSettings.KEY_VIDEO_QUALITY, CameraSettings.DEFAULT_VIDEO_QUALITY_VALUE); if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) { int extraVideoQuality = intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); videoQualityHigh = (extraVideoQuality > 0); } // Use the same frame rate for both, since internally // if the frame rate is too large, it can cause camera to become // unstable. We need to fix the MediaRecorder to disable the support // of setting frame rate for now. mMediaRecorder.setVideoFrameRate(20); if (videoQualityHigh) { mMediaRecorder.setVideoSize(352,288); } else { mMediaRecorder.setVideoSize(176,144); } mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); if (!DEBUG_SUPPRESS_AUDIO_RECORDING) { mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); } mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); long remaining = getAvailableStorage(); // remaining >= LOW_STORAGE_THRESHOLD at this point, reserve a quarter // of that to make it more likely that recording can complete successfully. try { mMediaRecorder.setMaxFileSize(remaining - LOW_STORAGE_THRESHOLD / 4); } catch (RuntimeException exception) { // We are going to ignore failure of setMaxFileSize here, as // a) The composer selected may simply not support it, or // b) The underlying media framework may not handle 64-bit range // on the size restriction. } try { mMediaRecorder.prepare(); } catch (IOException exception) { Log.e(TAG, "prepare failed for " + mCameraVideoFilename); releaseMediaRecorder(); // TODO: add more exception handling logic here return false; } mMediaRecorderRecording = false; + + if (!mIsVideoCaptureIntent && !mThumbController.isUriValid()) { + updateLastVideo(); + } + + if (!mIsVideoCaptureIntent) { + mThumbController.updateDisplayIfNeeded(); + } + return true; } private void releaseMediaRecorder() { Log.v(TAG, "Releasing media recorder."); if (mMediaRecorder != null) { cleanupEmptyFile(); mMediaRecorder.reset(); mMediaRecorder.release(); mMediaRecorder = null; } } - private void restartPreview() { - if (DEBUG_DO_NOT_REUSE_MEDIA_RECORDER) { - Log.v(TAG, "DEBUG_DO_NOT_REUSE_MEDIA_RECORDER recreating mMediaRecorder."); - initializeVideo(); - } else { - try { - mMediaRecorder.prepare(); - } catch (IOException exception) { - Log.e(TAG, "prepare failed for " + mCameraVideoFilename); - releaseMediaRecorder(); - // TODO: add more exception handling logic here - } - } - if (mShouldTransitionThumbnails) { - mShouldTransitionThumbnails = false; - mThumbnailTransition.startTransition(500); - } - } - private int getIntPreference(String key, int defaultValue) { String s = mPreferences.getString(key, ""); int result = defaultValue; try { result = Integer.parseInt(s); } catch (NumberFormatException e) { // Ignore, result is already the default value. } return result; } private boolean getBooleanPreference(String key, boolean defaultValue) { return getIntPreference(key, defaultValue ? 1 : 0) != 0; } private void createVideoPath() { long dateTaken = System.currentTimeMillis(); String title = createName(dateTaken); String displayName = title + ".3gp"; // Used when emailing. String cameraDirPath = ImageManager.CAMERA_IMAGE_BUCKET_NAME; File cameraDir = new File(cameraDirPath); cameraDir.mkdirs(); SimpleDateFormat dateFormat = new SimpleDateFormat( getString(R.string.video_file_name_format)); Date date = new Date(dateTaken); String filepart = dateFormat.format(date); String filename = cameraDirPath + "/" + filepart + ".3gp"; ContentValues values = new ContentValues(7); values.put(Video.Media.TITLE, title); values.put(Video.Media.DISPLAY_NAME, displayName); values.put(Video.Media.DESCRIPTION, ""); values.put(Video.Media.DATE_TAKEN, dateTaken); values.put(Video.Media.MIME_TYPE, "video/3gpp"); values.put(Video.Media.DATA, filename); mCameraVideoFilename = filename; Log.v(TAG, "Current camera video filename: " + mCameraVideoFilename); mCurrentVideoValues = values; } private void registerVideo() { if (mCameraVideoFileDescriptor == null) { Uri videoTable = Uri.parse("content://media/external/video/media"); mCurrentVideoUri = mContentResolver.insert(videoTable, mCurrentVideoValues); Log.v(TAG, "Current video URI: " + mCurrentVideoUri); } mCurrentVideoValues = null; } private void deleteCurrentVideo() { if (mCurrentVideoFilename != null) { deleteVideoFile(mCurrentVideoFilename); mCurrentVideoFilename = null; } if (mCurrentVideoUri != null) { mContentResolver.delete(mCurrentVideoUri, null, null); mCurrentVideoUri = null; } updateAndShowStorageHint(true); } private void deleteVideoFile(String fileName) { Log.v(TAG, "Deleting video " + fileName); File f = new File(fileName); if (! f.delete()) { Log.v(TAG, "Could not delete " + fileName); } } private void addBaseMenuItems(Menu menu) { MenuHelper.addSwitchModeMenuItem(menu, this, false); { MenuItem gallery = menu.add(MenuHelper.IMAGE_MODE_ITEM, MENU_GALLERY_PHOTOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } { MenuItem gallery = menu.add(MenuHelper.VIDEO_MODE_ITEM, MENU_GALLERY_VIDEOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } MenuItem item = menu.add(MenuHelper.GENERIC_ITEM, MENU_SETTINGS, 0, R.string.settings).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(); intent.setClass(VideoCamera.this, CameraSettings.class); startActivity(intent); return true; } }); item.setIcon(android.R.drawable.ic_menu_preferences); } // from MediaRecorder.OnErrorListener public void onError(MediaRecorder mr, int what, int extra) { if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) { // We may have run out of space on the sdcard. stopVideoRecording(); updateAndShowStorageHint(true); } } // from MediaRecorder.OnInfoListener public void onInfo(MediaRecorder mr, int what, int extra) { if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) { mShutterButton.performClick(); } else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) { mShutterButton.performClick(); updateAndShowStorageHint(true); } } /* * Make sure we're not recording music playing in the background, ask * the MediaPlaybackService to pause playback. */ private void pauseAudioPlayback() { // Shamelessly copied from MediaPlaybackService.java, which // should be public, but isn't. Intent i = new Intent("com.android.music.musicservicecommand"); i.putExtra("command", "pause"); sendBroadcast(i); } private void startVideoRecording() { Log.v(TAG, "startVideoRecording"); if (!mMediaRecorderRecording) { if (mStorageStatus != STORAGE_STATUS_OK) { Log.v(TAG, "Storage issue, ignore the start request"); return; } // Check mMediaRecorder to see whether it is initialized or not. if (mMediaRecorder == null && initializeVideo() == false ) { Log.e(TAG, "Initialize video (MediaRecorder) failed."); return; } pauseAudioPlayback(); try { mMediaRecorder.setOnErrorListener(this); mMediaRecorder.setOnInfoListener(this); mMediaRecorder.start(); // Recording is now started } catch (RuntimeException e) { Log.e(TAG, "Could not start media recorder. ", e); return; } mMediaRecorderRecording = true; mRecordingStartTime = SystemClock.uptimeMillis(); updateRecordingIndicator(true); mRecordingTimeView.setText(""); mRecordingTimeView.setVisibility(View.VISIBLE); mHandler.sendEmptyMessage(UPDATE_RECORD_TIME); setScreenTimeoutInfinite(); hideLastPictureButton(); - recycleVideoFrameBitmap(); } } private void updateRecordingIndicator(boolean showRecording) { int drawableId = showRecording ? R.drawable.ic_camera_bar_indicator_record : R.drawable.ic_camera_indicator_video; Drawable drawable = getResources().getDrawable(drawableId); mShutterButton.setImageDrawable(drawable); } - private void stopVideoRecordingAndShowThumbnail() { - Log.v(TAG, "stopVideoRecordingAndShowThumbnail"); - if (mMediaRecorderRecording) { - stopVideoRecording(); - acquireVideoFrame(); - setLastPictureThumb(mVideoFrameBitmap); - showLastPictureButton(); - } + private void stopVideoRecordingAndGetThumbnail() { + stopVideoRecording(); + acquireVideoThumb(); } private void stopVideoRecordingAndShowAlert() { - Log.v(TAG, "stopVideoRecordingAndShowAlert"); - if (mMediaRecorderRecording) { - stopVideoRecording(); - acquireVideoFrame(); - showVideoFrame(); - } - } - - private void stopPreviewAndShowAlert() { stopVideoRecording(); - showVideoFrame(); + showAlert(); } - private void showVideoFrame() { + private void showAlert() { int[] pickIds = {R.id.attach, R.id.cancel}; int[] normalIds = {R.id.gallery, R.id.share, R.id.discard}; int[] alwaysOnIds = {R.id.play}; int[] hideIds = pickIds; int[] connectIds = normalIds; - if (isVideoCaptureIntent()) { + if (mIsVideoCaptureIntent) { hideIds = normalIds; connectIds = pickIds; } for(int id : hideIds) { mPostPictureAlert.findViewById(id).setVisibility(View.GONE); } ActionMenuButton shareButton = (ActionMenuButton) mPostPictureAlert.findViewById(R.id.share); shareButton.setRestricted( mCurrentVideoFileLength > SHARE_FILE_LENGTH_LIMIT); connectAndFadeIn(connectIds); connectAndFadeIn(alwaysOnIds); hideLastPictureButton(); - mVideoFrame.setVisibility(View.VISIBLE); mPostPictureAlert.setVisibility(View.VISIBLE); + + // There are two cases we are here: + // (1) We are in a capture video intent, and we are reviewing the video + // we just taken. + // (2) The thumbnail button is clicked: we review the video associated + // with the thumbnail. + // For the second case, we copy the associated URI and filename to + // mCurrentVideoUri and mCurrentVideoFilename, so the video frame shown + // and the target for actions (play, delete, ...) will be correct. + + if (!mIsVideoCaptureIntent) { + mCurrentVideoUri = mThumbController.getUri(); + mCurrentVideoFilename = getDataPath(mCurrentVideoUri); + } + + String path = mCurrentVideoFilename; + if (path != null) { + Bitmap videoFrame = ImageManager.createVideoThumbnail(path); + mVideoFrame.setImageBitmap(videoFrame); + mVideoFrame.setVisibility(View.VISIBLE); + } } - private void hideVideoFrame() { + private void hideAlert() { mVideoFrame.setVisibility(View.INVISIBLE); mPostPictureAlert.setVisibility(View.INVISIBLE); showLastPictureButton(); } private void connectAndFadeIn(int[] connectIds) { for(int id : connectIds) { View view = mPostPictureAlert.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); - view.setAnimation(animation); + view.startAnimation(animation); } } - private boolean isPostRecordingAlertVisible() { + private boolean isAlertVisible() { return mPostPictureAlert.getVisibility() == View.VISIBLE; } private void stopVideoRecording() { Log.v(TAG, "stopVideoRecording"); boolean needToRegisterRecording = false; if (mMediaRecorderRecording || mMediaRecorder != null) { if (mMediaRecorderRecording && mMediaRecorder != null) { try { mMediaRecorder.setOnErrorListener(null); mMediaRecorder.setOnInfoListener(null); mMediaRecorder.stop(); } catch (RuntimeException e) { Log.e(TAG, "stop fail: " + e.getMessage()); } mCurrentVideoFilename = mCameraVideoFilename; try { mCurrentVideoFileLength = new File(mCurrentVideoFilename).length(); } catch (RuntimeException e) { Log.e(TAG, "get file length fail: " + e.getMessage()); mCurrentVideoFileLength = 0; } Log.v(TAG, "Setting current video filename: " + mCurrentVideoFilename); needToRegisterRecording = true; mMediaRecorderRecording = false; } releaseMediaRecorder(); updateRecordingIndicator(false); mRecordingTimeView.setVisibility(View.GONE); setScreenTimeoutLong(); } if (needToRegisterRecording && mStorageStatus == STORAGE_STATUS_OK) { registerVideo(); } mCameraVideoFilename = null; mCameraVideoFileDescriptor = null; } private void setScreenTimeoutSystemDefault() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); clearScreenOnFlag(); } private void setScreenTimeoutLong() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); setScreenOnFlag(); mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); } private void setScreenTimeoutInfinite() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); setScreenOnFlag(); } private void clearScreenOnFlag() { Window w = getWindow(); final int keepScreenOnFlag = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; if ((w.getAttributes().flags & keepScreenOnFlag) != 0) { w.clearFlags(keepScreenOnFlag); } } private void setScreenOnFlag() { Window w = getWindow(); final int keepScreenOnFlag = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; if ((w.getAttributes().flags & keepScreenOnFlag) == 0) { w.addFlags(keepScreenOnFlag); } } - private void hideVideoFrameAndStartPreview() { - hideVideoFrame(); - restartPreview(); + private void hideAlertAndStartPreview() { + hideAlert(); + initializeVideo(); } - private void acquireVideoFrame() { - recycleVideoFrameBitmap(); - mVideoFrameBitmap = ImageManager.createVideoThumbnail(mCurrentVideoFilename); - mVideoFrame.setImageBitmap(mVideoFrameBitmap); - Log.v(TAG, "acquireVideoFrame:" + mVideoFrameBitmap); + private void hideAlertAndStartVideoRecording() { + hideAlert(); + startVideoRecording(); } - //TODO: Refactor the code so that the following code is shared between - // VideoCamera.java and Camera.java - private static Bitmap makeRoundedCorner(Bitmap thumb, int rx, int ry) { - if (thumb == null) return null; - int width = thumb.getWidth(); - int height = thumb.getHeight(); - - Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(result); - Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); - paint.setStyle(Paint.Style.FILL); - canvas.drawRoundRect(new RectF(0, 0, width, height), rx, ry, paint); - paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); - canvas.drawBitmap(thumb, 0, 0, paint); - return result; + private void acquireVideoThumb() { + Bitmap videoFrame = ImageManager.createVideoThumbnail(mCurrentVideoFilename); + mThumbController.setData(mCurrentVideoUri, videoFrame); } - private void setLastPictureThumb(Bitmap videoFrame) { - - final int PADDING_WIDTH = 6; - final int PADDING_HEIGHT = 6; - LayoutParams layoutParams = mLastPictureButton.getLayoutParams(); - // Make the mini-thumbnail size smaller than the button size so that the image corners - // don't peek out from the rounded corners of the frame_thumbnail graphic: - final int miniThumbWidth = layoutParams.width - 2 * PADDING_WIDTH; - final int miniThumbHeight = layoutParams.height - 2 * PADDING_HEIGHT; - - Bitmap lastPictureThumb = ImageManager.extractMiniThumb(videoFrame, - miniThumbWidth, miniThumbHeight, false); - lastPictureThumb = makeRoundedCorner(lastPictureThumb, 3, 3); - - Drawable[] vignetteLayers = new Drawable[2]; - vignetteLayers[0] = getResources().getDrawable(R.drawable.frame_thumbnail); - if (mThumbnails == null) { - mThumbnails = new Drawable[2]; - mThumbnails[1] = new BitmapDrawable(lastPictureThumb); - vignetteLayers[1] = mThumbnails[1]; - } else { - mThumbnails[0] = mThumbnails[1]; - mThumbnails[1] = new BitmapDrawable(lastPictureThumb); - mThumbnailTransition = new TransitionDrawable(mThumbnails); - mShouldTransitionThumbnails = true; - vignetteLayers[1] = mThumbnailTransition; + private void showLastPictureButton() { + if (!mIsVideoCaptureIntent) { + mLastPictureButton.setVisibility(View.VISIBLE); } + } - LayerDrawable vignette = new LayerDrawable(vignetteLayers); - vignette.setLayerInset(1, PADDING_WIDTH, PADDING_HEIGHT, - PADDING_WIDTH, PADDING_HEIGHT); - mLastPictureButton.setImageDrawable(vignette); + private void hideLastPictureButton() { + if (!mIsVideoCaptureIntent) { + mLastPictureButton.setVisibility(View.INVISIBLE); + } } - private void showLastPictureButton() { - mLastPictureButton.setVisibility(View.VISIBLE); + private static ImageManager.DataLocation dataLocation() { + return ImageManager.DataLocation.EXTERNAL; } - private void hideLastPictureButton() { - mLastPictureButton.setVisibility(View.INVISIBLE); + private void updateLastVideo() { + ImageManager.IImageList list = ImageManager.instance().allImages( + this, + mContentResolver, + dataLocation(), + ImageManager.INCLUDE_VIDEOS, + ImageManager.SORT_ASCENDING, + ImageManager.CAMERA_IMAGE_BUCKET_ID); + int count = list.getCount(); + if (count > 0) { + ImageManager.IImage image = list.getImageAt(count-1); + Uri uri = image.fullSizeImageUri(); + mThumbController.setData(uri, image.miniThumbBitmap()); + } else { + mThumbController.setData(null, null); + } + list.deactivate(); } - private void recycleVideoFrameBitmap() { - if (mVideoFrameBitmap != null) { - mVideoFrame.setImageDrawable(null); - mVideoFrameBitmap.recycle(); - mVideoFrameBitmap = null; + private static final String[] DATA_PATH_PROJECTION = new String[] { + "_data" + }; + + private String getDataPath(Uri uri) { + Cursor c = null; + try { + c = mContentResolver.query(uri, DATA_PATH_PROJECTION, null, null, null); + if (c != null && c.moveToFirst()) { + return c.getString(0); + } else { + return null; + } + } finally { + if (c != null) c.close(); } } } diff --git a/src/com/android/camera/ViewImage.java b/src/com/android/camera/ViewImage.java index 2e777fd..1376172 100644 --- a/src/com/android/camera/ViewImage.java +++ b/src/com/android/camera/ViewImage.java @@ -1,715 +1,726 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.util.Random; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.util.AttributeSet; import android.util.Config; import android.util.Log; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import android.widget.Scroller; import android.widget.Toast; import android.widget.ZoomButtonsController; import com.android.camera.ImageManager.IImage; public class ViewImage extends Activity implements View.OnClickListener { private static final String TAG = "ViewImage"; private static final int TOUCH_AREA_WIDTH = 60; private ImageGetter mGetter; static final boolean sSlideShowHidesStatusBar = true; // Choices for what adjacents to load. static private final int[] sOrder_adjacents = new int[] { 0, 1, -1 }; static private final int[] sOrder_slideshow = new int[] { 0 }; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { } }; private Random mRandom = new Random(System.currentTimeMillis()); private int [] mShuffleOrder; private boolean mUseShuffleOrder = false; private boolean mSlideShowLoop = false; private static final int MODE_NORMAL = 1; private static final int MODE_SLIDESHOW = 2; private int mMode = MODE_NORMAL; private boolean mFullScreenInNormalMode; private boolean mShowActionIcons; private View mActionIconPanel; private View mShutterButton; private boolean mSortAscending = false; private int mSlideShowInterval; private int mLastSlideShowImage; private boolean mFirst = true; private int mCurrentPosition = 0; private boolean mLayoutComplete = false; // represents which style animation to use private int mAnimationIndex; private Animation [] mSlideShowInAnimation; private Animation [] mSlideShowOutAnimation; private SharedPreferences mPrefs; private View mNextImageView, mPrevImageView; private Animation mHideNextImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mHidePrevImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mShowNextImageViewAnimation = new AlphaAnimation(0F, 1F); private Animation mShowPrevImageViewAnimation = new AlphaAnimation(0F, 1F); static final int sPadding = 20; static final int sHysteresis = sPadding * 2; static final int sBaseScrollDuration = 1000; // ms private ImageManager.IImageList mAllImages; private int mSlideShowImageCurrent = 0; private ImageViewTouch [] mSlideShowImageViews = new ImageViewTouch[2]; private GestureDetector mGestureDetector; private ZoomButtonsController mZoomButtonsController; // Array of image views. The center view is the one the user is focused // on. The one at the zeroth position and the second position reflect // the images to the left/right of the center image. private ImageViewTouch[] mImageViews = new ImageViewTouch[3]; // Container for the three image views. This guy can be "scrolled" // to reveal the image prior to and after the center image. private ScrollHandler mScroller; private MenuHelper.MenuItemsResult mImageMenuRunnable; private Runnable mDismissOnScreenControlsRunnable; private boolean mCameraReviewMode; private int mCurrentOrientation; private void updateNextPrevControls() { boolean showPrev = mCurrentPosition > 0; boolean showNext = mCurrentPosition < mAllImages.getCount() - 1; boolean prevIsVisible = mPrevImageView.getVisibility() == View.VISIBLE; boolean nextIsVisible = mNextImageView.getVisibility() == View.VISIBLE; if (showPrev && !prevIsVisible) { Animation a = mShowPrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.VISIBLE); } else if (!showPrev && prevIsVisible) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.GONE); } if (showNext && !nextIsVisible) { Animation a = mShowNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.VISIBLE); } else if (!showNext && nextIsVisible) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.GONE); } } private void showOnScreenControls() { updateNextPrevControls(); updateZoomButtonsEnabled(); mZoomButtonsController.setVisible(true); scheduleDismissOnScreenControls(); } @Override public boolean dispatchTouchEvent(MotionEvent m) { boolean sup = super.dispatchTouchEvent(m); if (sup == false) { if (mMode == MODE_SLIDESHOW) { mSlideShowImageViews[mSlideShowImageCurrent].handleTouchEvent(m); } else if (mMode == MODE_NORMAL){ mImageViews[1].handleTouchEvent(m); } return true; } return true; } private void scheduleDismissOnScreenControls() { mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); mHandler.postDelayed(mDismissOnScreenControlsRunnable, 1500); } private void updateZoomButtonsEnabled() { ImageViewTouch imageView = mImageViews[1]; float scale = imageView.getScale(); mZoomButtonsController.setZoomInEnabled(scale < imageView.mMaxZoom); mZoomButtonsController.setZoomOutEnabled(scale > 1); } + @Override + protected void onDestroy() { + // This is necessary to make the ZoomButtonsController unregister + // its configuration change receiver. + if (mZoomButtonsController != null) { + mZoomButtonsController.setVisible(false); + } + + super.onDestroy(); + } + private void setupZoomButtonController(View rootView) { mGestureDetector = new GestureDetector(this, new MyGestureListener()); mZoomButtonsController = new ZoomButtonsController(rootView); mZoomButtonsController.setAutoDismissed(false); mZoomButtonsController.setOnZoomListener( new ZoomButtonsController.OnZoomListener() { public void onVisibilityChanged(boolean visible) { if (visible) { updateZoomButtonsEnabled(); } } public void onZoom(boolean zoomIn) { if (zoomIn) { mImageViews[1].zoomIn(); } else { mImageViews[1].zoomOut(); } showOnScreenControls(); } }); } private class MyGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { ImageViewTouch imageView = mImageViews[1]; if (imageView.getScale() > 1F) { imageView.postTranslate(-distanceX, -distanceY, sUseBounce); imageView.center(true, true, false); } showOnScreenControls(); return true; } @Override public boolean onSingleTapUp(MotionEvent e) { int viewWidth = mImageViews[1].getWidth(); int x = (int) e.getX(); int y = (int) e.getY(); if (x < TOUCH_AREA_WIDTH) { moveNextOrPrevious(-1); } else if (x > viewWidth - TOUCH_AREA_WIDTH) { moveNextOrPrevious(1); } setMode(MODE_NORMAL); showOnScreenControls(); return true; } } private void setupDismissOnScreenControlRunnable() { mDismissOnScreenControlsRunnable = new Runnable() { public void run() { if (!mShowActionIcons) { if (mNextImageView.getVisibility() == View.VISIBLE) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.INVISIBLE); } if (mPrevImageView.getVisibility() == View.VISIBLE) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.INVISIBLE); } mZoomButtonsController.setVisible(false); } } }; } private boolean isPickIntent() { String action = getIntent().getAction(); return (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)); } private static final boolean sUseBounce = false; private static final boolean sAnimateTransitions = false; public static class ImageViewTouch extends ImageViewTouchBase { private ViewImage mViewImage; private boolean mEnableTrackballScroll; public ImageViewTouch(Context context) { super(context); mViewImage = (ViewImage) context; } public ImageViewTouch(Context context, AttributeSet attrs) { super(context, attrs); mViewImage = (ViewImage) context; } public void setEnableTrackballScroll(boolean enable) { mEnableTrackballScroll = enable; } protected void postTranslate(float dx, float dy, boolean bounceOK) { super.postTranslate(dx, dy); if (dx != 0F || dy != 0F) { mViewImage.showOnScreenControls(); } if (!sUseBounce) { center(true, false, false); } } protected ScrollHandler scrollHandler() { return mViewImage.mScroller; } public boolean handleTouchEvent(MotionEvent m) { return mViewImage.mGestureDetector.onTouchEvent(m); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Don't respond to arrow keys if trackball scrolling is not enabled if (!mEnableTrackballScroll) { if ((keyCode >= KeyEvent.KEYCODE_DPAD_UP) && (keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT)) { return super.onKeyDown(keyCode, event); } } int current = mViewImage.mCurrentPosition; int nextImagePos = -2; // default no next image try { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: { if (mViewImage.isPickIntent()) { ImageManager.IImage img = mViewImage.mAllImages.getImageAt(mViewImage.mCurrentPosition); mViewImage.setResult(RESULT_OK, new Intent().setData(img.fullSizeImageUri())); mViewImage.finish(); } break; } case KeyEvent.KEYCODE_DPAD_LEFT: { panBy(sPanRate, 0); int maxOffset = (current == 0) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(true, maxOffset)) { nextImagePos = current - 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_RIGHT: { panBy(-sPanRate, 0); int maxOffset = (current == mViewImage.mAllImages.getCount() - 1) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(false, maxOffset)) { nextImagePos = current + 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_UP: { panBy(0, sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DPAD_DOWN: { panBy(0, -sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DEL: MenuHelper.displayDeleteDialog(mViewImage, mViewImage.mDeletePhotoRunnable, true); break; } } finally { if (nextImagePos >= 0 && nextImagePos < mViewImage.mAllImages.getCount()) { synchronized (mViewImage) { mViewImage.setMode(MODE_NORMAL); mViewImage.setImage(nextImagePos); } } else if (nextImagePos != -2) { center(true, true, false); } } return super.onKeyDown(keyCode, event); } protected boolean isShiftedToNextImage(boolean left, int maxOffset) { boolean retval; Bitmap bitmap = mBitmapDisplayed; Matrix m = getImageViewMatrix(); if (left) { float [] t1 = new float[] { 0, 0 }; m.mapPoints(t1); retval = t1[0] > maxOffset; } else { int width = bitmap != null ? bitmap.getWidth() : getWidth(); float [] t1 = new float[] { width, 0 }; m.mapPoints(t1); retval = t1[0] + maxOffset < getWidth(); } return retval; } protected void scrollX(int deltaX) { scrollHandler().scrollBy(deltaX, 0); } protected int getScrollOffset() { return scrollHandler().getScrollX(); } } static class ScrollHandler extends LinearLayout { private Runnable mFirstLayoutCompletedCallback = null; private Scroller mScrollerHelper; private int mWidth = -1; public ScrollHandler(Context context) { super(context); mScrollerHelper = new Scroller(context); } public ScrollHandler(Context context, AttributeSet attrs) { super(context, attrs); mScrollerHelper = new Scroller(context); } public void setLayoutCompletedCallback(Runnable r) { mFirstLayoutCompletedCallback = r; } public void startScrollTo(int newX, int newY) { int oldX = getScrollX(); int oldY = getScrollY(); int deltaX = newX - oldX; int deltaY = newY - oldY; if (mWidth == -1) { mWidth = findViewById(R.id.image2).getWidth(); } int viewWidth = mWidth; int duration = viewWidth > 0 ? sBaseScrollDuration * Math.abs(deltaX) / viewWidth : 0; mScrollerHelper.startScroll(oldX, oldY, deltaX, deltaY, duration); invalidate(); } @Override public void computeScroll() { if (mScrollerHelper.computeScrollOffset()) { scrollTo(mScrollerHelper.getCurrX(), mScrollerHelper.getCurrY()); postInvalidate(); // So we draw again } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int width = right - left; int x = 0; for (View v : new View[] { findViewById(R.id.image1), findViewById(R.id.image2), findViewById(R.id.image3) }) { v.layout(x, 0, x + width, bottom); x += (width + sPadding); } findViewById(R.id.padding1).layout(width, 0, width + sPadding, bottom); findViewById(R.id.padding2).layout(width+sPadding+width, 0, width+sPadding+width+sPadding, bottom); if (changed) { if (mFirstLayoutCompletedCallback != null) { mFirstLayoutCompletedCallback.run(); } } } } private void animateScrollTo(int xNew, int yNew) { mScroller.startScrollTo(xNew, yNew); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (! mCameraReviewMode) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.slide_show); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { setMode(MODE_SLIDESHOW); mLastSlideShowImage = mCurrentPosition; loadNextImage(mCurrentPosition, 0, true); return true; } }); item.setIcon(android.R.drawable.ic_menu_slideshow); } final SelectedImageGetter selectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return mAllImages.getImageAt(mCurrentPosition); } public Uri getCurrentImageUri() { return mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); } }; mImageMenuRunnable = MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL, true, ViewImage.this, mHandler, mDeletePhotoRunnable, new MenuHelper.MenuInvoker() { public void run(MenuHelper.MenuCallback cb) { setMode(MODE_NORMAL); cb.run(selectedImageGetter.getCurrentImageUri(), selectedImageGetter.getCurrentImage()); for (ImageViewTouchBase iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } setImage(mCurrentPosition); } }); if (true) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 1000, R.string.camerasettings); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent preferences = new Intent(); preferences.setClass(ViewImage.this, GallerySettings.class); startActivity(preferences); return true; } }); item.setAlphabeticShortcut('p'); item.setIcon(android.R.drawable.ic_menu_preferences); } // Hidden menu just so the shortcut will bring up the zoom controls menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.camerasettings) // the string resource is a placeholder .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { showOnScreenControls(); return true; } }) .setAlphabeticShortcut('z') .setVisible(false); return true; } protected Runnable mDeletePhotoRunnable = new Runnable() { public void run() { mAllImages.removeImageAt(mCurrentPosition); if (mAllImages.getCount() == 0) { finish(); } else { if (mCurrentPosition == mAllImages.getCount()) { mCurrentPosition -= 1; } } for (ImageViewTouchBase iv: mImageViews) { iv.setImageBitmapResetBase(null, true, true); } setImage(mCurrentPosition); } }; @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); setMode(MODE_NORMAL); if (mImageMenuRunnable != null) { mImageMenuRunnable.gettingReadyToOpen(menu, mAllImages.getImageAt(mCurrentPosition)); } return true; } @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean changed = mCurrentOrientation != newConfig.orientation; mCurrentOrientation = newConfig.orientation; if (changed) { if (mGetter != null) { // kill off any background image fetching mGetter.cancelCurrent(); mGetter.stop(); } makeGetter(); mFirst = true; // clear off the current set of images since we need to reload // them at the right size for (ImageViewTouchBase iv: mImageViews) { iv.clear(); } MenuHelper.requestOrientation(this, mPrefs); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { boolean b = super.onMenuItemSelected(featureId, item); if (mImageMenuRunnable != null) mImageMenuRunnable.aboutToCall(item, mAllImages.getImageAt(mCurrentPosition)); return b; } /* * Here's the loading strategy. For any given image, load the thumbnail * into memory and post a callback to display the resulting bitmap. * * Then proceed to load the full image bitmap. Three things can * happen at this point: * * 1. the image fails to load because the UI thread decided * to move on to a different image. This "cancellation" happens * by virtue of the UI thread closing the stream containing the * image being decoded. BitmapFactory.decodeStream returns null * in this case. * * 2. the image loaded successfully. At that point we post * a callback to the UI thread to actually show the bitmap. * * 3. when the post runs it checks to see if the image that was * loaded is still the one we want. The UI may have moved on * to some other image and if so we just drop the newly loaded * bitmap on the floor. */ interface ImageGetterCallback { public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb); public boolean wantsThumbnail(int pos, int offset); public boolean wantsFullImage(int pos, int offset); public int fullImageSizeToUse(int pos, int offset); public void completed(boolean wasCanceled); public int [] loadOrder(); } class ImageGetter { // The thread which does the work. private Thread mGetterThread; // The base position that's being retrieved. The actual images retrieved // are this base plus each of the offets. private int mCurrentPosition = -1; // The callback to invoke for each image. private ImageGetterCallback mCB; // This is the loader cancelable that gets set while we're loading an image. // If we change position we can cancel the current load using this. private ImageManager.IGetBitmap_cancelable mLoad; // True if we're canceling the current load. private boolean mCancelCurrent = false; // True when the therad should exit. private boolean mDone = false; // True when the loader thread is waiting for work. private boolean mReady = false; private void cancelCurrent() { synchronized (this) { if (!mReady) { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { if (Config.LOGV) Log.v(TAG, "canceling load object"); load.cancel(); } mCancelCurrent = false; } } } public ImageGetter() { mGetterThread = new Thread(new Runnable() { private Runnable callback(final int position, final int offset, final boolean isThumb, final Bitmap bitmap) { return new Runnable() { public void run() {
brunsky/WS171-packages-apps-Camera
9a379bd668227d3dcea30312025f304fd248f6e3
auto import from //branches/cupcake/...@137197
diff --git a/Android.mk b/Android.mk index d35d7cb..4ee7f34 100644 --- a/Android.mk +++ b/Android.mk @@ -1,16 +1,16 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := user development +LOCAL_MODULE_TAGS := user LOCAL_SRC_FILES := $(call all-java-files-under, src) LOCAL_PACKAGE_NAME := Camera LOCAL_CERTIFICATE := media LOCAL_STATIC_JAVA_LIBRARIES := googlelogin-client include $(BUILD_PACKAGE) # Use the following include to make our test apk. include $(call all-makefiles-under,$(LOCAL_PATH)) diff --git a/res/drawable/ic_btn_actionmenu_attach_default.png b/res/drawable/ic_btn_actionmenu_attach_default.png index 78d6e1b..f429206 100644 Binary files a/res/drawable/ic_btn_actionmenu_attach_default.png and b/res/drawable/ic_btn_actionmenu_attach_default.png differ diff --git a/res/drawable/ic_btn_actionmenu_attach_pressed.png b/res/drawable/ic_btn_actionmenu_attach_pressed.png index 01cbe46..ee083a7 100644 Binary files a/res/drawable/ic_btn_actionmenu_attach_pressed.png and b/res/drawable/ic_btn_actionmenu_attach_pressed.png differ diff --git a/res/drawable/ic_btn_actionmenu_attach_selected.png b/res/drawable/ic_btn_actionmenu_attach_selected.png index ee7af0b..582c3b9 100644 Binary files a/res/drawable/ic_btn_actionmenu_attach_selected.png and b/res/drawable/ic_btn_actionmenu_attach_selected.png differ diff --git a/src/com/android/camera/Camera.java b/src/com/android/camera/Camera.java index 56e048a..3564508 100644 --- a/src/com/android/camera/Camera.java +++ b/src/com/android/camera/Camera.java @@ -1,1871 +1,1748 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import android.app.Activity; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.res.AssetFileDescriptor; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.TransitionDrawable; import android.hardware.Camera.PictureCallback; import android.hardware.Camera.Size; import android.location.Location; import android.location.LocationManager; import android.location.LocationProvider; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.ToneGenerator; import android.net.Uri; import android.os.Bundle; import android.os.Debug; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.text.format.DateFormat; import android.util.Config; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.OrientationEventListener; import android.view.SurfaceHolder; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.Toast; public class Camera extends Activity implements View.OnClickListener, ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback { private static final String TAG = "camera"; private static final boolean DEBUG = false; private static final boolean DEBUG_TIME_OPERATIONS = DEBUG && false; private static final int CROP_MSG = 1; - private static final int KEEP = 2; private static final int RESTART_PREVIEW = 3; private static final int CLEAR_SCREEN_DELAY = 4; private static final int SCREEN_DELAY = 2 * 60 * 1000; private static final int FOCUS_BEEP_VOLUME = 100; public static final int MENU_SWITCH_TO_VIDEO = 0; public static final int MENU_SWITCH_TO_CAMERA = 1; public static final int MENU_FLASH_SETTING = 2; public static final int MENU_FLASH_AUTO = 3; public static final int MENU_FLASH_ON = 4; public static final int MENU_FLASH_OFF = 5; public static final int MENU_SETTINGS = 6; public static final int MENU_GALLERY_PHOTOS = 7; public static final int MENU_GALLERY_VIDEOS = 8; public static final int MENU_SAVE_SELECT_PHOTOS = 30; public static final int MENU_SAVE_NEW_PHOTO = 31; public static final int MENU_SAVE_GALLERY_PHOTO = 34; public static final int MENU_SAVE_GALLERY_VIDEO_PHOTO = 35; public static final int MENU_SAVE_CAMERA_DONE = 36; public static final int MENU_SAVE_CAMERA_VIDEO_DONE = 37; - private Toast mToast; private OrientationEventListener mOrientationListener; private int mLastOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; private SharedPreferences mPreferences; private static final int IDLE = 1; private static final int SNAPSHOT_IN_PROGRESS = 2; private static final int SNAPSHOT_COMPLETED = 3; private int mStatus = IDLE; private static final String sTempCropFilename = "crop-temp"; private android.hardware.Camera mCameraDevice; private android.hardware.Camera.Parameters mParameters; private VideoPreview mSurfaceView; private SurfaceHolder mSurfaceHolder = null; private View mBlackout = null; private int mOriginalViewFinderWidth, mOriginalViewFinderHeight; private int mViewFinderWidth, mViewFinderHeight; private boolean mPreviewing = false; private MediaPlayer mClickSound; private Capturer mCaptureObject; private ImageCapture mImageCapture = null; private boolean mPausing = false; private static final int FOCUS_NOT_STARTED = 0; private static final int FOCUSING = 1; private static final int FOCUSING_SNAP_ON_FINISH = 2; private static final int FOCUS_SUCCESS = 3; private static final int FOCUS_FAIL = 4; private int mFocusState = FOCUS_NOT_STARTED; private static ContentResolver mContentResolver; private boolean mDidRegister = false; private ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>(); - private boolean mMenuSelectionMade; - private ImageView mLastPictureButton; private LayerDrawable mVignette; private Animation mShowLastPictureButtonAnimation = new AlphaAnimation(0F, 1F); private boolean mShouldShowLastPictureButton; private TransitionDrawable mThumbnailTransition; private Drawable[] mThumbnails; private boolean mShouldTransitionThumbnails; private Uri mLastPictureUri; private Bitmap mLastPictureThumb; private LocationManager mLocationManager = null; private ShutterButton mShutterButton; private Animation mFocusBlinkAnimation; private View mFocusIndicator; private ToneGenerator mFocusToneGenerator; private ShutterCallback mShutterCallback = new ShutterCallback(); private RawPictureCallback mRawPictureCallback = new RawPictureCallback(); private AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback(); private long mFocusStartTime; private long mFocusCallbackTime; private long mCaptureStartTime; private long mShutterCallbackTime; private long mRawPictureCallbackTime; private int mPicturesRemaining; private boolean mKeepAndRestartPreview; // mPostCaptureAlert is non-null only if isImageCaptureIntent() is true. private View mPostCaptureAlert; private Handler mHandler = new MainHandler(); - private ProgressDialog mSavingProgress; private interface Capturer { Uri getLastCaptureUri(); void onSnap(); - void dismissFreezeFrame(boolean keep); - void cancelSave(); - void cancelAutoDismiss(); - void setDone(boolean wait); - } - - private void cancelSavingNotification() { - if (mToast != null) { - mToast.cancel(); - mToast = null; - } + void dismissFreezeFrame(); } /** This Handler is used to post message back onto the main thread of the application */ private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { - case KEEP: { - keep(); - if (mSavingProgress != null) { - mSavingProgress.cancel(); - mSavingProgress = null; - } - - mKeepAndRestartPreview = true; - - if (msg.obj != null) { - mHandler.post((Runnable)msg.obj); - } - break; - } - case RESTART_PREVIEW: { if (mStatus == SNAPSHOT_IN_PROGRESS) { // We are still in the processing of taking the picture, wait. // This is is strange. Why are we polling? // TODO remove polling mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, 100); } else if (mStatus == SNAPSHOT_COMPLETED){ - mCaptureObject.dismissFreezeFrame(true); + mCaptureObject.dismissFreezeFrame(); hidePostCaptureAlert(); } break; } case CLEAR_SCREEN_DELAY: { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); break; } } } }; LocationListener [] mLocationListeners = new LocationListener[] { new LocationListener(LocationManager.GPS_PROVIDER), new LocationListener(LocationManager.NETWORK_PROVIDER) }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { // SD card available updateStorageHint(calculatePicturesRemaining()); } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED) || action.equals(Intent.ACTION_MEDIA_CHECKING)) { // SD card unavailable mPicturesRemaining = MenuHelper.NO_STORAGE_ERROR; updateStorageHint(mPicturesRemaining); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { Toast.makeText(Camera.this, getResources().getString(R.string.wait), 5000); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { updateStorageHint(); } } }; private class LocationListener implements android.location.LocationListener { Location mLastLocation; boolean mValid = false; String mProvider; public LocationListener(String provider) { mProvider = provider; mLastLocation = new Location(mProvider); } public void onLocationChanged(Location newLocation) { if (newLocation.getLatitude() == 0.0 && newLocation.getLongitude() == 0.0) { // Hack to filter out 0.0,0.0 locations return; } mLastLocation.set(newLocation); mValid = true; } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { mValid = false; } public void onStatusChanged(String provider, int status, Bundle extras) { if (status == LocationProvider.OUT_OF_SERVICE) { mValid = false; } } public Location current() { return mValid ? mLastLocation : null; } }; private boolean mImageSavingItem = false; private final class ShutterCallback implements android.hardware.Camera.ShutterCallback { public void onShutter() { if (DEBUG_TIME_OPERATIONS) { mShutterCallbackTime = System.currentTimeMillis(); Log.v(TAG, "Shutter lag was " + (mShutterCallbackTime - mCaptureStartTime) + " ms."); } if (mClickSound != null) { mClickSound.start(); } mBlackout.setVisibility(View.VISIBLE); Size pictureSize = mParameters.getPictureSize(); // Resize the SurfaceView to the aspect-ratio of the still image // and so that we can see the full image that was taken. mSurfaceView.setAspectRatio(pictureSize.width, pictureSize.height); } }; private final class RawPictureCallback implements PictureCallback { public void onPictureTaken(byte [] rawData, android.hardware.Camera camera) { if (Config.LOGV) Log.v(TAG, "got RawPictureCallback..."); mRawPictureCallbackTime = System.currentTimeMillis(); if (DEBUG_TIME_OPERATIONS) { Log.v(TAG, (mRawPictureCallbackTime - mShutterCallbackTime) + "ms elapsed between" + " ShutterCallback and RawPictureCallback."); } mBlackout.setVisibility(View.GONE); } }; private final class JpegPictureCallback implements PictureCallback { Location mLocation; public JpegPictureCallback(Location loc) { mLocation = loc; } public void onPictureTaken(byte [] jpegData, android.hardware.Camera camera) { if (Config.LOGV) Log.v(TAG, "got JpegPictureCallback..."); if (DEBUG_TIME_OPERATIONS) { long mJpegPictureCallback = System.currentTimeMillis(); Log.v(TAG, (mJpegPictureCallback - mRawPictureCallbackTime) + "ms elapsed between" + " RawPictureCallback and JpegPictureCallback."); } mImageCapture.storeImage(jpegData, camera, mLocation); mStatus = SNAPSHOT_COMPLETED; if (mKeepAndRestartPreview) { long delay = 1500 - (System.currentTimeMillis() - mRawPictureCallbackTime); mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, Math.max(delay, 0)); } } }; private final class AutoFocusCallback implements android.hardware.Camera.AutoFocusCallback { public void onAutoFocus(boolean focused, android.hardware.Camera camera) { if (DEBUG_TIME_OPERATIONS) { mFocusCallbackTime = System.currentTimeMillis(); Log.v(TAG, "Auto focus took " + (mFocusCallbackTime - mFocusStartTime) + " ms."); } if (mFocusState == FOCUSING_SNAP_ON_FINISH && mCaptureObject != null) { // Take the picture no matter focus succeeds or fails. // No need to play the AF sound if we're about to play the shutter sound. mCaptureObject.onSnap(); clearFocusState(); } else if (mFocusState == FOCUSING) { // User is half-pressing the focus key. Play the focus tone. // Do not take the picture now. ToneGenerator tg = mFocusToneGenerator; if (tg != null) tg.startTone(ToneGenerator.TONE_PROP_BEEP2); if (focused) { mFocusState = FOCUS_SUCCESS; } else { mFocusState = FOCUS_FAIL; } } else if (mFocusState == FOCUS_NOT_STARTED) { // User has released the focus key before focus completes. // Do nothing. } updateFocusIndicator(); } }; private class ImageCapture implements Capturer { private boolean mCancel = false; private boolean mCapturing = false; private Uri mLastContentUri; private ImageManager.IAddImage_cancelable mAddImageCancelable; Bitmap mCaptureOnlyBitmap; /** These member variables are used for various debug timings */ private long mThreadTimeStart; private long mThreadTimeEnd; private long mWallTimeStart; private long mWallTimeEnd; public ImageCapture() { } /** * This method sets whether or not we are capturing a picture. This method must be called * with the ImageCapture.this lock held. */ public void setCapturingLocked(boolean capturing) { mCapturing = capturing; } - /* - * Tell the ImageCapture thread to exit when possible. - */ - public void setDone(boolean wait) { - } - - /* - * Tell the image capture thread to not "dismiss" the current - * capture when the current image is stored, etc. - */ - public void cancelAutoDismiss() { - } - - public void dismissFreezeFrame(boolean keep) { - if (keep) { - cancelSavingNotification(); - } else { - Toast.makeText(Camera.this, R.string.camera_tossing, Toast.LENGTH_SHORT).show(); - } - + public void dismissFreezeFrame() { if (mStatus == SNAPSHOT_IN_PROGRESS) { // If we are still in the process of taking a picture, then just post a message. mHandler.sendEmptyMessage(RESTART_PREVIEW); } else { restartPreview(); } } private void startTiming() { mWallTimeStart = SystemClock.elapsedRealtime(); mThreadTimeStart = Debug.threadCpuTimeNanos(); } private void stopTiming() { mThreadTimeEnd = Debug.threadCpuTimeNanos(); mWallTimeEnd = SystemClock.elapsedRealtime(); } private void storeImage(byte[] data, Location loc) { try { if (DEBUG_TIME_OPERATIONS) { startTiming(); } long dateTaken = System.currentTimeMillis(); String name = createName(dateTaken) + ".jpg"; mLastContentUri = ImageManager.instance().addImage( Camera.this, mContentResolver, name, "", dateTaken, // location for the database goes here loc, 0, // the dsp will use the right orientation so don't "double set it" ImageManager.CAMERA_IMAGE_BUCKET_NAME, name); if (mLastContentUri == null) { // this means we got an error mCancel = true; } if (!mCancel) { mAddImageCancelable = ImageManager.instance().storeImage(mLastContentUri, Camera.this, mContentResolver, 0, null, data); mAddImageCancelable.get(); mAddImageCancelable = null; } if (DEBUG_TIME_OPERATIONS) { stopTiming(); Log.d(TAG, "Storing image took " + (mWallTimeEnd - mWallTimeStart) + " ms. " + "Thread time was " + ((mThreadTimeEnd - mThreadTimeStart) / 1000000) + " ms."); } } catch (Exception ex) { Log.e(TAG, "Exception while compressing image.", ex); } } public void storeImage(byte[] data, android.hardware.Camera camera, Location loc) { boolean captureOnly = isImageCaptureIntent(); if (!captureOnly) { storeImage(data, loc); sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", mLastContentUri)); setLastPictureThumb(data, mCaptureObject.getLastCaptureUri()); - dismissFreezeFrame(true); + dismissFreezeFrame(); } else { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; if (DEBUG_TIME_OPERATIONS) { startTiming(); } mCaptureOnlyBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options); if (DEBUG_TIME_OPERATIONS) { stopTiming(); Log.d(TAG, "Decoded mCaptureOnly bitmap (" + mCaptureOnlyBitmap.getWidth() + "x" + mCaptureOnlyBitmap.getHeight() + " ) in " + (mWallTimeEnd - mWallTimeStart) + " ms. Thread time was " + ((mThreadTimeEnd - mThreadTimeStart) / 1000000) + " ms."); } showPostCaptureAlert(); cancelAutomaticPreviewRestart(); } mCapturing = false; if (mPausing) { closeCamera(); } } - /* - * Tells the image capture thread to abort the capture of the - * current image. - */ - public void cancelSave() { - if (!mCapturing) { - return; - } - - mCancel = true; - - if (mAddImageCancelable != null) { - mAddImageCancelable.cancel(); - } - dismissFreezeFrame(false); - } - /* * Initiate the capture of an image. */ public void initiate(boolean captureOnly) { if (mCameraDevice == null) { return; } mCancel = false; mCapturing = true; capture(captureOnly); } public Uri getLastCaptureUri() { return mLastContentUri; } public Bitmap getLastBitmap() { return mCaptureOnlyBitmap; } private void capture(boolean captureOnly) { mPreviewing = false; mCaptureOnlyBitmap = null; final int latchedOrientation = ImageManager.roundOrientation(mLastOrientation + 90); Boolean recordLocation = mPreferences.getBoolean("pref_camera_recordlocation_key", false); Location loc = recordLocation ? getCurrentLocation() : null; // Quality 75 has visible artifacts, and quality 90 looks great but the files begin to // get large. 85 is a good compromise between the two. mParameters.set("jpeg-quality", 85); mParameters.set("rotation", latchedOrientation); mParameters.remove("gps-latitude"); mParameters.remove("gps-longitude"); mParameters.remove("gps-altitude"); mParameters.remove("gps-timestamp"); if (loc != null) { double lat = loc.getLatitude(); double lon = loc.getLongitude(); boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d); if (hasLatLon) { String latString = String.valueOf(lat); String lonString = String.valueOf(lon); mParameters.set("gps-latitude", latString); mParameters.set("gps-longitude", lonString); if (loc.hasAltitude()) { mParameters.set("gps-altitude", String.valueOf(loc.getAltitude())); } else { // for NETWORK_PROVIDER location provider, we may have // no altitude information, but the driver needs it, so // we fake one. mParameters.set("gps-altitude", "0"); } if (loc.getTime() != 0) { // Location.getTime() is UTC in milliseconds. // gps-timestamp is UTC in seconds. long utcTimeSeconds = loc.getTime() / 1000; mParameters.set("gps-timestamp", String.valueOf(utcTimeSeconds)); } } else { loc = null; } } mCameraDevice.setParameters(mParameters); mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback, new JpegPictureCallback(loc)); // Prepare the sound to play in shutter callback. if (mClickSound != null) { mClickSound.seekTo(0); } } public void onSnap() { if (DEBUG_TIME_OPERATIONS) mCaptureStartTime = System.currentTimeMillis(); // If we are already in the middle of taking a snapshot then we should just save // the image after we have returned from the camera service. if (mStatus == SNAPSHOT_IN_PROGRESS || mStatus == SNAPSHOT_COMPLETED) { mKeepAndRestartPreview = true; mHandler.sendEmptyMessage(RESTART_PREVIEW); return; } // Don't check the filesystem here, we can't afford the latency. Instead, check the // cached value which was calculated when the preview was restarted. if (mPicturesRemaining < 1) { updateStorageHint(mPicturesRemaining); return; } mStatus = SNAPSHOT_IN_PROGRESS; mKeepAndRestartPreview = true; boolean getContentAction = isImageCaptureIntent(); if (getContentAction) { mImageCapture.initiate(true); } else { mImageCapture.initiate(false); } } + + private void clearLastBitmap() { + if (mCaptureOnlyBitmap != null) { + mCaptureOnlyBitmap.recycle(); + mCaptureOnlyBitmap = null; + } + } } private void setLastPictureThumb(byte[] data, Uri uri) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 16; Bitmap lastPictureThumb = BitmapFactory.decodeByteArray(data, 0, data.length, options); setLastPictureThumb(lastPictureThumb, uri); } private void setLastPictureThumb(Bitmap lastPictureThumb, Uri uri) { final int PADDING_WIDTH = 2; final int PADDING_HEIGHT = 2; LayoutParams layoutParams = mLastPictureButton.getLayoutParams(); // Make the mini-thumbnail size smaller than the button size so that the image corners // don't peek out from the rounded corners of the frame_thumbnail graphic: final int miniThumbWidth = layoutParams.width - 2 * PADDING_WIDTH; final int miniThumbHeight = layoutParams.height - 2 * PADDING_HEIGHT; lastPictureThumb = ImageManager.extractMiniThumb(lastPictureThumb, miniThumbWidth, miniThumbHeight); Drawable[] vignetteLayers = new Drawable[2]; vignetteLayers[1] = getResources().getDrawable(R.drawable.frame_thumbnail); if (mThumbnails == null) { mThumbnails = new Drawable[2]; mThumbnails[1] = new BitmapDrawable(lastPictureThumb); vignetteLayers[0] = mThumbnails[1]; } else { mThumbnails[0] = mThumbnails[1]; mThumbnails[1] = new BitmapDrawable(lastPictureThumb); mThumbnailTransition = new TransitionDrawable(mThumbnails); mShouldTransitionThumbnails = true; vignetteLayers[0] = mThumbnailTransition; } mVignette = new LayerDrawable(vignetteLayers); mVignette.setLayerInset(0, PADDING_WIDTH, PADDING_HEIGHT, PADDING_WIDTH, PADDING_HEIGHT); mLastPictureButton.setImageDrawable(mVignette); if (mLastPictureButton.getVisibility() != View.VISIBLE) { mShouldShowLastPictureButton = true; } mLastPictureThumb = lastPictureThumb; mLastPictureUri = uri; } static private String createName(long dateTaken) { return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString(); } static public Matrix GetDisplayMatrix(Bitmap b, ImageView v) { Matrix m = new Matrix(); float bw = (float)b.getWidth(); float bh = (float)b.getHeight(); float vw = (float)v.getWidth(); float vh = (float)v.getHeight(); float scale, x, y; if (bw*vh > vw*bh) { scale = vh / bh; x = (vw - scale*bw)*0.5F; y = 0; } else { scale = vw / bw; x = 0; y = (vh - scale*bh)*0.5F; } m.setScale(scale, scale, 0.5F, 0.5F); m.postTranslate(x, y); return m; } - private void postAfterKeep(final Runnable r) { - Resources res = getResources(); - - if (mSavingProgress != null) { - mSavingProgress = ProgressDialog.show(this, res.getString(R.string.savingImage), - res.getString(R.string.wait)); - } - - Message msg = mHandler.obtainMessage(KEEP); - msg.obj = r; - msg.sendToTarget(); - } - /** Called with the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); // To reduce startup time, we open camera device in another thread. // We make sure the camera is opened at the end of onCreate. Thread openCameraThread = new Thread(new Runnable() { public void run() { mCameraDevice = android.hardware.Camera.open(); } }); openCameraThread.start(); // To reduce startup time, we run some service creation code in another thread. // We make sure the services are loaded at the end of onCreate(). Thread loadServiceThread = new Thread(new Runnable() { public void run() { mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mOrientationListener = new OrientationEventListener(Camera.this) { public void onOrientationChanged(int orientation) { // We keep the last known orientation. So if the user // first orient the camera then point the camera to // floor/sky, we still have the correct orientation. if (orientation != ORIENTATION_UNKNOWN) mLastOrientation = orientation; } }; } }); loadServiceThread.start(); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mContentResolver = getContentResolver(); Window win = getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.camera); mSurfaceView = (VideoPreview) findViewById(R.id.camera_preview); // don't set mSurfaceHolder here. We have it set ONLY within // surfaceCreated / surfaceDestroyed, other parts of the code // assume that when it is set, the surface is also set. SurfaceHolder holder = mSurfaceView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mBlackout = findViewById(R.id.blackout); if (!isImageCaptureIntent()) { mLastPictureButton = (ImageView) findViewById(R.id.last_picture_button); mLastPictureButton.setOnClickListener(this); loadLastThumb(); } mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); try { mClickSound = new MediaPlayer(); AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.camera_click); mClickSound.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); if (mClickSound != null) { mClickSound.setAudioStreamType(AudioManager.STREAM_ALARM); mClickSound.prepare(); } } catch (Exception ex) { Log.w(TAG, "Couldn't create click sound", ex); } mFocusIndicator = findViewById(R.id.focus_indicator); mFocusBlinkAnimation = AnimationUtils.loadAnimation(this, R.anim.auto_focus_blink); mFocusBlinkAnimation.setRepeatCount(Animation.INFINITE); mFocusBlinkAnimation.setRepeatMode(Animation.REVERSE); // We load the post_picture_panel layout only if it is needed. if (isImageCaptureIntent()) { ViewGroup cameraView = (ViewGroup)findViewById(R.id.camera); getLayoutInflater().inflate(R.layout.post_picture_panel, cameraView); mPostCaptureAlert = findViewById(R.id.post_picture_panel); } // Make sure the services are loaded. try { openCameraThread.join(); loadServiceThread.join(); } catch (InterruptedException ex) { } ImageManager.ensureOSXCompatibleFolder(); } @Override public void onStart() { super.onStart(); Thread t = new Thread(new Runnable() { public void run() { final boolean storageOK = calculatePicturesRemaining() > 0; if (!storageOK) { mHandler.post(new Runnable() { public void run() { updateStorageHint(mPicturesRemaining); } }); } } }); t.start(); } public void onClick(View v) { switch (v.getId()) { case R.id.last_picture_button: viewLastImage(); break; case R.id.attach: doAttach(); break; case R.id.cancel: doCancel(); } } private void doAttach() { Bitmap bitmap = mImageCapture.getLastBitmap(); - mCaptureObject.setDone(true); String cropValue = null; Uri saveUri = null; Bundle myExtras = getIntent().getExtras(); if (myExtras != null) { saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); cropValue = myExtras.getString("crop"); } if (cropValue == null) { /* * First handle the no crop case -- just return the value. If the caller * specifies a "save uri" then write the data to it's stream. Otherwise, * pass back a scaled down version of the bitmap directly in the extras. */ if (saveUri != null) { OutputStream outputStream = null; try { outputStream = mContentResolver.openOutputStream(saveUri); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, outputStream); outputStream.close(); setResult(RESULT_OK); finish(); } catch (IOException ex) { // } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { } } } } else { float scale = .5F; Matrix m = new Matrix(); m.setScale(scale, scale); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true); setResult(RESULT_OK, new Intent("inline-data").putExtra("data", bitmap)); finish(); } } else { /* * Save the image to a temp file and invoke the cropper */ Uri tempUri = null; FileOutputStream tempStream = null; try { File path = getFileStreamPath(sTempCropFilename); path.delete(); tempStream = openFileOutput(sTempCropFilename, 0); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, tempStream); tempStream.close(); tempUri = Uri.fromFile(path); } catch (FileNotFoundException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } catch (IOException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } finally { if (tempStream != null) { try { tempStream.close(); } catch (IOException ex) { } } } Bundle newExtras = new Bundle(); if (cropValue.equals("circle")) newExtras.putString("circleCrop", "true"); if (saveUri != null) newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, saveUri); else newExtras.putBoolean("return-data", true); Intent cropIntent = new Intent(); cropIntent.setClass(Camera.this, CropImage.class); cropIntent.setData(tempUri); cropIntent.putExtras(newExtras); startActivityForResult(cropIntent, CROP_MSG); } } private void doCancel() { setResult(RESULT_CANCELED, new Intent()); finish(); } public void onShutterButtonFocus(ShutterButton button, boolean pressed) { switch (button.getId()) { case R.id.shutter_button: doFocus(pressed); break; } } public void onShutterButtonClick(ShutterButton button) { switch (button.getId()) { case R.id.shutter_button: doSnap(); break; } } private void updateStorageHint() { updateStorageHint(MenuHelper.calculatePicturesRemaining()); } private OnScreenHint mStorageHint; private void updateStorageHint(int remaining) { String noStorageText = null; if (remaining == MenuHelper.NO_STORAGE_ERROR) { String state = Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING) { noStorageText = getString(R.string.preparing_sd); } else { noStorageText = getString(R.string.no_storage); } } else if (remaining < 1) { noStorageText = getString(R.string.not_enough_space); } if (noStorageText != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, noStorageText); } else { mStorageHint.setText(noStorageText); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } @Override public void onResume() { super.onResume(); mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); mPausing = false; mOrientationListener.enable(); // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); mDidRegister = true; mImageCapture = new ImageCapture(); restartPreview(); if (mPreferences.getBoolean("pref_camera_recordlocation_key", false)) startReceivingLocationUpdates(); updateFocusIndicator(); try { mFocusToneGenerator = new ToneGenerator(AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME); } catch (RuntimeException e) { Log.w(TAG, "Exception caught while creating local tone generator: " + e); mFocusToneGenerator = null; } mBlackout.setVisibility(View.GONE); } private ImageManager.DataLocation dataLocation() { return ImageManager.DataLocation.EXTERNAL; } private static final int BUFSIZE = 4096; // Stores the thumbnail and URI of last-picture-taken to SD card, so we can // load it the next time the Camera app starts. private void storeLastThumb() { if (mLastPictureUri != null && mLastPictureThumb != null) { try { FileOutputStream f = new FileOutputStream(ImageManager.getLastThumbPath()); try { BufferedOutputStream b = new BufferedOutputStream(f, BUFSIZE); try { DataOutputStream d = new DataOutputStream(b); try { d.writeUTF(mLastPictureUri.toString()); mLastPictureThumb.compress(Bitmap.CompressFormat.PNG, 100, d); } finally { d.close(); b = null; f = null; } } finally { if (b != null) { b.close(); f = null; } } } finally { if (f != null) { f.close(); } } } catch (IOException e) { } } } // Loads the thumbnail and URI of last-picture-taken from SD card. private void loadLastThumb() { try { FileInputStream f = new FileInputStream(ImageManager.getLastThumbPath()); try { BufferedInputStream b = new BufferedInputStream(f, BUFSIZE); try { DataInputStream d = new DataInputStream(b); try { Uri lastUri = Uri.parse(d.readUTF()); Bitmap lastThumb = BitmapFactory.decodeStream(d); setLastPictureThumb(lastThumb, lastUri); } finally { d.close(); b = null; f = null; } } finally { if (b != null) { b.close(); f = null; } } } finally { if (f != null) { f.close(); } } } catch (IOException e) { } } @Override public void onStop() { keep(); stopPreview(); closeCamera(); mHandler.removeMessages(CLEAR_SCREEN_DELAY); super.onStop(); } @Override protected void onPause() { keep(); mPausing = true; mOrientationListener.disable(); stopPreview(); if (!mImageCapture.mCapturing) { closeCamera(); } if (mDidRegister) { unregisterReceiver(mReceiver); mDidRegister = false; } stopReceivingLocationUpdates(); if (mFocusToneGenerator != null) { mFocusToneGenerator.release(); mFocusToneGenerator = null; } storeLastThumb(); if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } + + // If we are in an image capture intent and has taken + // a picture, we just clear it in onPause. + mImageCapture.clearLastBitmap(); + mImageCapture = null; + hidePostCaptureAlert(); + super.onPause(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case CROP_MSG: { Intent intent = new Intent(); if (data != null) { Bundle extras = data.getExtras(); if (extras != null) { intent.putExtras(extras); } } setResult(resultCode, intent); finish(); File path = getFileStreamPath(sTempCropFilename); path.delete(); break; } } } private void autoFocus() { updateFocusIndicator(); if (mFocusState != FOCUSING && mFocusState != FOCUSING_SNAP_ON_FINISH) { if (mCameraDevice != null) { if (DEBUG_TIME_OPERATIONS) { mFocusStartTime = System.currentTimeMillis(); } mFocusState = FOCUSING; mCameraDevice.autoFocus(mAutoFocusCallback); } } } private void clearFocusState() { mFocusState = FOCUS_NOT_STARTED; } private void updateFocusIndicator() { mHandler.post(new Runnable() { public void run() { if (mFocusState == FOCUS_SUCCESS) { mFocusIndicator.setVisibility(View.VISIBLE); mFocusIndicator.clearAnimation(); } else if (mFocusState == FOCUS_FAIL) { mFocusIndicator.setVisibility(View.VISIBLE); mFocusIndicator.startAnimation(mFocusBlinkAnimation); } else { mFocusIndicator.setVisibility(View.GONE); mFocusIndicator.clearAnimation(); } } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mStatus == SNAPSHOT_IN_PROGRESS) { // ignore backs while we're taking a picture return true; } break; case KeyEvent.KEYCODE_FOCUS: if (event.getRepeatCount() == 0) { doFocus(true); } return true; case KeyEvent.KEYCODE_CAMERA: if (event.getRepeatCount() == 0) { doSnap(); } return true; case KeyEvent.KEYCODE_DPAD_CENTER: // If we get a dpad center event without any focused view, move the // focus to the shutter button and press it. if (event.getRepeatCount() == 0) { // Start auto-focus immediately to reduce shutter lag. After the shutter button // gets the focus, doFocus() will be called again but it is fine. doFocus(true); if (mShutterButton.isInTouchMode()) { mShutterButton.requestFocusFromTouch(); } else { mShutterButton.requestFocus(); } mShutterButton.setPressed(true); } return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_FOCUS: doFocus(false); return true; } return super.onKeyUp(keyCode, event); } private void doSnap() { // If the user has half-pressed the shutter and focus is completed, we // can take the photo right away. if ((mFocusState == FOCUS_SUCCESS || mFocusState == FOCUS_FAIL) || !mPreviewing) { // doesn't get set until the idler runs if (mCaptureObject != null) { mCaptureObject.onSnap(); } clearFocusState(); updateFocusIndicator(); } else { // Half pressing the shutter (i.e. the focus button event) will // already have requested AF for us, so just request capture on // focus here. mFocusState = FOCUSING_SNAP_ON_FINISH; } } private void doFocus(boolean pressed) { if (pressed) { // Focus key down. if (mPreviewing) { autoFocus(); } else if (mCaptureObject != null) { // Save and restart preview mCaptureObject.onSnap(); } } else { // Focus key up. if (mFocusState != FOCUSING_SNAP_ON_FINISH) { // User releases half-pressed focus key. clearFocusState(); updateFocusIndicator(); } } } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // if we're creating the surface, start the preview as well. boolean preview = holder.isCreating(); setViewFinder(w, h, preview); mCaptureObject = mImageCapture; } public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; } public void surfaceDestroyed(SurfaceHolder holder) { stopPreview(); mSurfaceHolder = null; } private void closeCamera() { if (mCameraDevice != null) { mCameraDevice.release(); mCameraDevice = null; mPreviewing = false; } } private boolean ensureCameraDevice() { if (mCameraDevice == null) { mCameraDevice = android.hardware.Camera.open(); } return mCameraDevice != null; } private boolean isLastPictureValid() { boolean isValid = true; if (mLastPictureUri == null) return false; try { mContentResolver.openFileDescriptor(mLastPictureUri, "r").close(); } catch (Exception ex) { isValid = false; Log.e(TAG, ex.toString()); } return isValid; } private void updateLastImage() { ImageManager.IImageList list = ImageManager.instance().allImages( this, mContentResolver, dataLocation(), ImageManager.INCLUDE_IMAGES, ImageManager.SORT_ASCENDING, ImageManager.CAMERA_IMAGE_BUCKET_ID); int count = list.getCount(); if (count > 0) { ImageManager.IImage image = list.getImageAt(count-1); mLastPictureUri = image.fullSizeImageUri(); Log.v(TAG, "updateLastImage: count="+ count + ", lastPictureUri="+mLastPictureUri); setLastPictureThumb(image.miniThumbBitmap(), mLastPictureUri); } else { mLastPictureUri = null; } list.deactivate(); } private void restartPreview() { VideoPreview surfaceView = mSurfaceView; // make sure the surfaceview fills the whole screen when previewing surfaceView.setAspectRatio(VideoPreview.DONT_CARE); setViewFinder(mOriginalViewFinderWidth, mOriginalViewFinderHeight, true); mStatus = IDLE; // Calculate this in advance of each shot so we don't add to shutter latency. It's true that // someone else could write to the SD card in the mean time and fill it, but that could have // happened between the shutter press and saving the JPEG too. // TODO: The best longterm solution is to write a reserve file of maximum JPEG size, always // let the user take a picture, and delete that file if needed to save the new photo. calculatePicturesRemaining(); if (!isImageCaptureIntent() && !isLastPictureValid()) { updateLastImage(); } if (mShouldShowLastPictureButton) { mShouldShowLastPictureButton = false; mLastPictureButton.setVisibility(View.VISIBLE); Animation a = mShowLastPictureButtonAnimation; a.setDuration(500); mLastPictureButton.setAnimation(a); } if (mShouldTransitionThumbnails) { mShouldTransitionThumbnails = false; mThumbnailTransition.startTransition(500); } } private void setViewFinder(int w, int h, boolean startPreview) { if (mPausing) return; if (mPreviewing && w == mViewFinderWidth && h == mViewFinderHeight) { return; } if (!ensureCameraDevice()) return; if (mSurfaceHolder == null) return; if (isFinishing()) return; if (mPausing) return; // remember view finder size mViewFinderWidth = w; mViewFinderHeight = h; if (mOriginalViewFinderHeight == 0) { mOriginalViewFinderWidth = w; mOriginalViewFinderHeight = h; } if (startPreview == false) return; /* * start the preview if we're asked to... */ // we want to start the preview and we're previewing already, // stop the preview first (this will blank the screen). if (mPreviewing) stopPreview(); // this blanks the screen if the surface changed, no-op otherwise try { mCameraDevice.setPreviewDisplay(mSurfaceHolder); } catch (IOException exception) { mCameraDevice.release(); mCameraDevice = null; // TODO: add more exception handling logic here return; } // request the preview size, the hardware may not honor it, // if we depended on it we would have to query the size again mParameters = mCameraDevice.getParameters(); mParameters.setPreviewSize(w, h); try { mCameraDevice.setParameters(mParameters); } catch (IllegalArgumentException e) { // Ignore this error, it happens in the simulator. } final long wallTimeStart = SystemClock.elapsedRealtime(); final long threadTimeStart = Debug.threadCpuTimeNanos(); final Object watchDogSync = new Object(); Thread watchDog = new Thread(new Runnable() { public void run() { int next_warning = 1; while (true) { try { synchronized (watchDogSync) { watchDogSync.wait(1000); } } catch (InterruptedException ex) { // } if (mPreviewing) break; int delay = (int) (SystemClock.elapsedRealtime() - wallTimeStart) / 1000; if (delay >= next_warning) { if (delay < 120) { Log.e(TAG, "preview hasn't started yet in " + delay + " seconds"); } else { Log.e(TAG, "preview hasn't started yet in " + (delay / 60) + " minutes"); } if (next_warning < 60) { next_warning <<= 1; if (next_warning == 16) { next_warning = 15; } } else { next_warning += 60; } } } } }); watchDog.start(); if (Config.LOGV) Log.v(TAG, "calling mCameraDevice.startPreview"); try { mCameraDevice.startPreview(); } catch (Throwable e) { // TODO: change Throwable to IOException once android.hardware.Camera.startPreview // properly declares that it throws IOException. } mPreviewing = true; synchronized (watchDogSync) { watchDogSync.notify(); } long threadTimeEnd = Debug.threadCpuTimeNanos(); long wallTimeEnd = SystemClock.elapsedRealtime(); if ((wallTimeEnd - wallTimeStart) > 3000) { Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart) + " ms. Thread time was" + (threadTimeEnd - threadTimeStart) / 1000000 + " ms."); } } private void stopPreview() { if (mCameraDevice != null && mPreviewing) { mCameraDevice.stopPreview(); } mPreviewing = false; } void gotoGallery() { MenuHelper.gotoCameraImageGallery(this); } private void viewLastImage() { Uri targetUri = mLastPictureUri; if (targetUri != null && isLastPictureValid()) { targetUri = targetUri.buildUpon(). appendQueryParameter("bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build(); Intent intent = new Intent(Intent.ACTION_VIEW, targetUri); intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true); intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true); intent.putExtra("com.android.camera.ReviewMode", true); try { startActivity(intent); } catch (android.content.ActivityNotFoundException ex) { // ignore. } } else { Log.e(TAG, "Can't view last image."); } } void keep() { - cancelSavingNotification(); if (mCaptureObject != null) { - mCaptureObject.dismissFreezeFrame(true); - } - }; - - void toss() { - cancelSavingNotification(); - if (mCaptureObject != null) { - mCaptureObject.cancelSave(); + mCaptureObject.dismissFreezeFrame(); } }; private ImageManager.IImage getImageForURI(Uri uri) { ImageManager.IImageList list = ImageManager.instance().allImages( this, mContentResolver, dataLocation(), ImageManager.INCLUDE_IMAGES, ImageManager.SORT_ASCENDING); ImageManager.IImage image = list.getImageForUri(uri); list.deactivate(); return image; } private void startReceivingLocationUpdates() { if (mLocationManager != null) { try { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 1000, 0F, mLocationListeners[1]); } catch (java.lang.SecurityException ex) { // ok } catch (IllegalArgumentException ex) { if (Config.LOGD) { Log.d(TAG, "provider does not exist " + ex.getMessage()); } } try { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 1000, 0F, mLocationListeners[0]); } catch (java.lang.SecurityException ex) { // ok } catch (IllegalArgumentException ex) { if (Config.LOGD) { Log.d(TAG, "provider does not exist " + ex.getMessage()); } } } } private void stopReceivingLocationUpdates() { if (mLocationManager != null) { for (int i = 0; i < mLocationListeners.length; i++) { try { mLocationManager.removeUpdates(mLocationListeners[i]); } catch (Exception ex) { // ok } } } } private Location getCurrentLocation() { Location l = null; // go in best to worst order for (int i = 0; i < mLocationListeners.length; i++) { l = mLocationListeners[i].current(); if (l != null) break; } return l; } @Override public void onOptionsMenuClosed(Menu menu) { super.onOptionsMenuClosed(menu); - if (mImageSavingItem && !mMenuSelectionMade) { + if (mImageSavingItem) { // save the image if we presented the "advanced" menu // which happens if "menu" is pressed while in // SNAPSHOT_IN_PROGRESS or SNAPSHOT_COMPLETED modes keep(); mHandler.sendEmptyMessage(RESTART_PREVIEW); } } @Override public boolean onMenuOpened(int featureId, Menu menu) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { if (mStatus == SNAPSHOT_IN_PROGRESS) { cancelAutomaticPreviewRestart(); - mMenuSelectionMade = false; } } return super.onMenuOpened(featureId, menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); - mMenuSelectionMade = false; - for (int i = 1; i <= MenuHelper.MENU_ITEM_MAX; i++) { if (i != MenuHelper.GENERIC_ITEM) { menu.setGroupVisible(i, false); } } if (mStatus == SNAPSHOT_IN_PROGRESS || mStatus == SNAPSHOT_COMPLETED) { menu.setGroupVisible(MenuHelper.IMAGE_SAVING_ITEM, true); mImageSavingItem = true; } else { menu.setGroupVisible(MenuHelper.IMAGE_MODE_ITEM, true); mImageSavingItem = false; } - if (mCaptureObject != null) - mCaptureObject.cancelAutoDismiss(); - return true; } private void cancelAutomaticPreviewRestart() { mKeepAndRestartPreview = false; mHandler.removeMessages(RESTART_PREVIEW); } private boolean isImageCaptureIntent() { String action = getIntent().getAction(); return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)); } private void showPostCaptureAlert() { if (isImageCaptureIntent()) { mPostCaptureAlert.setVisibility(View.VISIBLE); int[] pickIds = {R.id.attach, R.id.cancel}; for(int id : pickIds) { View view = mPostCaptureAlert.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } } private void hidePostCaptureAlert() { if (isImageCaptureIntent()) { mPostCaptureAlert.setVisibility(View.INVISIBLE); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (isImageCaptureIntent()) { // No options menu for attach mode. return false; } else { addBaseMenuItems(menu); - MenuHelper.addImageMenuItems( - menu, - MenuHelper.INCLUDE_ALL & ~MenuHelper.INCLUDE_ROTATE_MENU, - true, - Camera.this, - mHandler, - - // Handler for deletion - new Runnable() { - public void run() { - if (mCaptureObject != null) { - mCaptureObject.cancelSave(); - Uri uri = mCaptureObject.getLastCaptureUri(); - if (uri != null) { - mContentResolver.delete(uri, null, null); - } - } - } - }, - new MenuHelper.MenuInvoker() { - public void run(final MenuHelper.MenuCallback cb) { - mMenuSelectionMade = true; - postAfterKeep(new Runnable() { - public void run() { - cb.run(mSelectedImageGetter.getCurrentImageUri(), mSelectedImageGetter.getCurrentImage()); - if (mCaptureObject != null) - mCaptureObject.dismissFreezeFrame(true); - } - }); - } - }); - - MenuItem gallery = menu.add(MenuHelper.IMAGE_SAVING_ITEM, MENU_SAVE_GALLERY_PHOTO, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { - public boolean onMenuItemClick(MenuItem item) { - postAfterKeep(new Runnable() { - public void run() { - gotoGallery(); - } - }); - return true; - } - }); - gallery.setIcon(android.R.drawable.ic_menu_gallery); } return true; } SelectedImageGetter mSelectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return getImageForURI(getCurrentImageUri()); } public Uri getCurrentImageUri() { keep(); return mCaptureObject.getLastCaptureUri(); } }; private int calculatePicturesRemaining() { mPicturesRemaining = MenuHelper.calculatePicturesRemaining(); return mPicturesRemaining; } private void addBaseMenuItems(Menu menu) { MenuHelper.addSwitchModeMenuItem(menu, this, true); { MenuItem gallery = menu.add(MenuHelper.IMAGE_MODE_ITEM, MENU_GALLERY_PHOTOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } { MenuItem gallery = menu.add(MenuHelper.VIDEO_MODE_ITEM, MENU_GALLERY_VIDEOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } MenuItem item = menu.add(MenuHelper.GENERIC_ITEM, MENU_SETTINGS, 0, R.string.settings).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(); intent.setClass(Camera.this, CameraSettings.class); startActivity(intent); return true; } }); item.setIcon(android.R.drawable.ic_menu_preferences); } } diff --git a/src/com/android/camera/VideoCamera.java b/src/com/android/camera/VideoCamera.java index e9ffbe4..70b1646 100644 --- a/src/com/android/camera/VideoCamera.java +++ b/src/com/android/camera/VideoCamera.java @@ -1,1017 +1,1045 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.location.LocationManager; import android.media.MediaMetadataRetriever; import android.media.MediaRecorder; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.StatFs; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.MediaStore.Video; import android.text.format.DateFormat; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.MenuItem.OnMenuItemClickListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class VideoCamera extends Activity implements View.OnClickListener, ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback, MediaRecorder.OnErrorListener { private static final String TAG = "videocamera"; private static final boolean DEBUG = true; private static final boolean DEBUG_SUPPRESS_AUDIO_RECORDING = DEBUG && false; private static final boolean DEBUG_DO_NOT_REUSE_MEDIA_RECORDER = DEBUG && true; private static final boolean DEBUG_LOG_APP_LIFECYCLE = DEBUG && false; private static final int CLEAR_SCREEN_DELAY = 4; private static final int UPDATE_RECORD_TIME = 5; private static final int SCREEN_DELAY = 2 * 60 * 1000; private static final long NO_STORAGE_ERROR = -1L; private static final long CANNOT_STAT_ERROR = -2L; private static final long LOW_STORAGE_THRESHOLD = 512L * 1024L; + private static final int STORAGE_STATUS_OK = 0; + private static final int STORAGE_STATUS_LOW = 1; + private static final int STORAGE_STATUS_NONE = 2; + public static final int MENU_SETTINGS = 6; public static final int MENU_GALLERY_PHOTOS = 7; public static final int MENU_GALLERY_VIDEOS = 8; public static final int MENU_SAVE_GALLERY_PHOTO = 34; public static final int MENU_SAVE_PLAY_VIDEO = 35; public static final int MENU_SAVE_SELECT_VIDEO = 36; public static final int MENU_SAVE_NEW_VIDEO = 37; SharedPreferences mPreferences; private static final float VIDEO_ASPECT_RATIO = 176.0f / 144.0f; VideoPreview mVideoPreview; SurfaceHolder mSurfaceHolder = null; ImageView mBlackout = null; ImageView mVideoFrame; Bitmap mVideoFrameBitmap; + private int mStorageStatus = STORAGE_STATUS_OK; + private MediaRecorder mMediaRecorder; private boolean mMediaRecorderRecording = false; private long mRecordingStartTime; // The video file that the hardware camera is about to record into // (or is recording into.) private String mCameraVideoFilename; private FileDescriptor mCameraVideoFileDescriptor; // The video file that has already been recorded, and that is being // examined by the user. private String mCurrentVideoFilename; private Uri mCurrentVideoUri; private ContentValues mCurrentVideoValues; boolean mPausing = false; static ContentResolver mContentResolver; int mCurrentZoomIndex = 0; private ShutterButton mShutterButton; private TextView mRecordingTimeView; ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>(); View mPostPictureAlert; LocationManager mLocationManager = null; private Handler mHandler = new MainHandler(); /** This Handler is used to post message back onto the main thread of the application */ private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case CLEAR_SCREEN_DELAY: { clearScreenOnFlag(); break; } case UPDATE_RECORD_TIME: { if (mMediaRecorderRecording) { long now = SystemClock.uptimeMillis(); long delta = now - mRecordingStartTime; long seconds = delta / 1000; long minutes = seconds / 60; long hours = minutes / 60; long remainderMinutes = minutes - (hours * 60); long remainderSeconds = seconds - (minutes * 60); String secondsString = Long.toString(remainderSeconds); if (secondsString.length() < 2) { secondsString = "0" + secondsString; } String minutesString = Long.toString(remainderMinutes); if (minutesString.length() < 2) { minutesString = "0" + minutesString; } String text = minutesString + ":" + secondsString; if (hours > 0) { String hoursString = Long.toString(hours); if (hoursString.length() < 2) { hoursString = "0" + hoursString; } text = hoursString + ":" + text; } mRecordingTimeView.setText(text); // Work around a limitation of the T-Mobile G1: The T-Mobile // hardware blitter can't pixel-accurately scale and clip at the same time, // and the SurfaceFlinger doesn't attempt to work around this limitation. // In order to avoid visual corruption we must manually refresh the entire // surface view when changing any overlapping view's contents. mVideoPreview.invalidate(); mHandler.sendEmptyMessageDelayed(UPDATE_RECORD_TIME, 1000); } break; } default: Log.v(TAG, "Unhandled message: " + msg.what); break; } } }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_EJECT)) { - updateStorageHint(false); + updateAndShowStorageHint(false); stopVideoRecording(); initializeVideo(); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { - updateStorageHint(true); + updateAndShowStorageHint(true); initializeVideo(); } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) { // SD card unavailable - updateStorageHint(false); - releaseMediaRecorder(); + // handled in ACTION_MEDIA_EJECT } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { Toast.makeText(VideoCamera.this, getResources().getString(R.string.wait), 5000); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { - updateStorageHint(true); + updateAndShowStorageHint(true); } } }; static private String createName(long dateTaken) { return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString(); } /** Called with the activity is first created. */ @Override public void onCreate(Bundle icicle) { if (DEBUG_LOG_APP_LIFECYCLE) { Log.v(TAG, "onCreate " + this.hashCode()); } super.onCreate(icicle); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mContentResolver = getContentResolver(); //setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.video_camera); mVideoPreview = (VideoPreview) findViewById(R.id.camera_preview); mVideoPreview.setAspectRatio(VIDEO_ASPECT_RATIO); // don't set mSurfaceHolder here. We have it set ONLY within // surfaceCreated / surfaceDestroyed, other parts of the code // assume that when it is set, the surface is also set. SurfaceHolder holder = mVideoPreview.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mBlackout = (ImageView) findViewById(R.id.blackout); mBlackout.setBackgroundDrawable(new ColorDrawable(0xFF000000)); mPostPictureAlert = findViewById(R.id.post_picture_panel); int[] ids = new int[]{R.id.play, R.id.share, R.id.discard, R.id.cancel, R.id.attach}; for (int id : ids) { findViewById(id).setOnClickListener(this); } mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); mRecordingTimeView = (TextView) findViewById(R.id.recording_time); mVideoFrame = (ImageView) findViewById(R.id.video_frame); } public void onClick(View v) { switch (v.getId()) { case R.id.gallery: MenuHelper.gotoCameraVideoGallery(this); break; case R.id.attach: doReturnToCaller(true); break; case R.id.cancel: doReturnToCaller(false); break; case R.id.discard: { discardCurrentVideoAndStartPreview(); break; } case R.id.share: { Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("video/3gpp"); intent.putExtra(Intent.EXTRA_STREAM, mCurrentVideoUri); try { startActivity(Intent.createChooser(intent, getText(R.string.sendVideo))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(VideoCamera.this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } break; } case R.id.play: { doPlayCurrentVideo(); break; } } } public void onShutterButtonFocus(ShutterButton button, boolean pressed) { switch (button.getId()) { case R.id.shutter_button: if (pressed) { if (mMediaRecorderRecording) { stopVideoRecordingAndDisplayDialog(); } else if (mVideoFrame.getVisibility() == View.VISIBLE) { doStartCaptureMode(); } else { startVideoRecording(); } } break; } } public void onShutterButtonClick(ShutterButton button) { // Do nothing (everything happens in onShutterButtonFocus). } private void doStartCaptureMode() { if (isVideoCaptureIntent()) { discardCurrentVideoAndStartPreview(); } else { hideVideoFrameAndStartPreview(); } } private void doPlayCurrentVideo() { Log.e(TAG, "Playing current video: " + mCurrentVideoUri); Intent intent = new Intent(Intent.ACTION_VIEW, mCurrentVideoUri); try { startActivity(intent); } catch (android.content.ActivityNotFoundException ex) { Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex); } } private void discardCurrentVideoAndStartPreview() { deleteCurrentVideo(); hideVideoFrameAndStartPreview(); } private OnScreenHint mStorageHint; - private void updateStorageHint(boolean mayHaveSd) { - long remaining = mayHaveSd ? getAvailableStorage() : NO_STORAGE_ERROR; + private void updateAndShowStorageHint(boolean mayHaveSd) { + mStorageStatus = getStorageStatus(mayHaveSd); + showStorageHint(); + } + + private void showStorageHint() { String errorMessage = null; - if (remaining == NO_STORAGE_ERROR) { + switch (mStorageStatus) { + case STORAGE_STATUS_NONE: errorMessage = getString(R.string.no_storage); - } else if (remaining < LOW_STORAGE_THRESHOLD) { + break; + case STORAGE_STATUS_LOW: errorMessage = getString(R.string.spaceIsLow_content); } if (errorMessage != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, errorMessage); } else { mStorageHint.setText(errorMessage); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } + private int getStorageStatus(boolean mayHaveSd) { + long remaining = mayHaveSd ? getAvailableStorage() : NO_STORAGE_ERROR; + if (remaining == NO_STORAGE_ERROR) { + return STORAGE_STATUS_NONE; + } + return remaining < LOW_STORAGE_THRESHOLD + ? STORAGE_STATUS_LOW : STORAGE_STATUS_OK; + } + @Override public void onResume() { if (DEBUG_LOG_APP_LIFECYCLE) { Log.v(TAG, "onResume " + this.hashCode()); } super.onResume(); setScreenTimeoutLong(); mPausing = false; // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_EJECT); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); - updateStorageHint(true); + mStorageStatus = getStorageStatus(true); + + mHandler.postDelayed(new Runnable() { + public void run() { + showStorageHint(); + } + }, 200); mBlackout.setVisibility(View.INVISIBLE); if (mVideoFrameBitmap == null) { initializeVideo(); } else { showPostRecordingAlert(); } } @Override public void onStop() { if (DEBUG_LOG_APP_LIFECYCLE) { Log.v(TAG, "onStop " + this.hashCode()); } stopVideoRecording(); setScreenTimeoutSystemDefault(); super.onStop(); } @Override protected void onPause() { if (DEBUG_LOG_APP_LIFECYCLE) { Log.v(TAG, "onPause " + this.hashCode()); } super.onPause(); stopVideoRecording(); hidePostPictureAlert(); mPausing = true; unregisterReceiver(mReceiver); mBlackout.setVisibility(View.VISIBLE); setScreenTimeoutSystemDefault(); if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { setScreenTimeoutLong(); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mMediaRecorderRecording) { Log.v(TAG, "onKeyBack"); stopVideoRecordingAndDisplayDialog(); return true; } else if(isPostRecordingAlertVisible()) { hideVideoFrameAndStartPreview(); return true; } break; case KeyEvent.KEYCODE_CAMERA: if (event.getRepeatCount() == 0) { // If we get a dpad center event without any focused view, move the // focus to the shutter button and press it. if (mShutterButton.isInTouchMode()) { mShutterButton.requestFocusFromTouch(); } else { mShutterButton.requestFocus(); } mShutterButton.setPressed(true); return true; } return true; case KeyEvent.KEYCODE_DPAD_CENTER: if (event.getRepeatCount() == 0) { // If we get a dpad center event without any focused view, move the // focus to the shutter button and press it. if (mShutterButton.isInTouchMode()) { mShutterButton.requestFocusFromTouch(); } else { mShutterButton.requestFocus(); } mShutterButton.setPressed(true); } break; case KeyEvent.KEYCODE_MENU: if (mMediaRecorderRecording) { stopVideoRecordingAndDisplayDialog(); return true; } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_CAMERA: mShutterButton.setPressed(false); return true; } return super.onKeyUp(keyCode, event); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { stopVideoRecording(); initializeVideo(); } public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; } public void surfaceDestroyed(SurfaceHolder holder) { mSurfaceHolder = null; } void gotoGallery() { MenuHelper.gotoCameraVideoGallery(this); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); for (int i = 1; i <= MenuHelper.MENU_ITEM_MAX; i++) { if (i != MenuHelper.GENERIC_ITEM) { menu.setGroupVisible(i, false); } } menu.setGroupVisible(MenuHelper.VIDEO_MODE_ITEM, true); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (isVideoCaptureIntent()) { // No options menu for attach mode. return false; } else { addBaseMenuItems(menu); MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL & ~MenuHelper.INCLUDE_ROTATE_MENU, false, VideoCamera.this, mHandler, // Handler for deletion new Runnable() { public void run() { // What do we do here? // mContentResolver.delete(uri, null, null); } }, new MenuHelper.MenuInvoker() { public void run(final MenuHelper.MenuCallback cb) { } }); MenuItem gallery = menu.add(MenuHelper.IMAGE_SAVING_ITEM, MENU_SAVE_GALLERY_PHOTO, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); } return true; } private boolean isVideoCaptureIntent() { String action = getIntent().getAction(); return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action)); } private void doReturnToCaller(boolean success) { Intent resultIntent = new Intent(); int resultCode; if (success) { resultCode = RESULT_OK; resultIntent.setData(mCurrentVideoUri); } else { resultCode = RESULT_CANCELED; } setResult(resultCode, resultIntent); finish(); } /** * Returns * @return number of bytes available, or an ERROR code. */ private static long getAvailableStorage() { try { if (!ImageManager.hasStorage()) { return NO_STORAGE_ERROR; } else { String storageDirectory = Environment.getExternalStorageDirectory().toString(); StatFs stat = new StatFs(storageDirectory); return ((long)stat.getAvailableBlocks() * (long)stat.getBlockSize()); } } catch (Exception ex) { // if we can't stat the filesystem then we don't know how many // free bytes exist. It might be zero but just leave it // blank since we really don't know. return CANNOT_STAT_ERROR; } } private void cleanupEmptyFile() { if (mCameraVideoFilename != null) { File f = new File(mCameraVideoFilename); if (f.length() == 0 && f.delete()) { Log.v(TAG, "Empty video file deleted: " + mCameraVideoFilename); mCameraVideoFilename = null; } } } // Returns false if initializeVideo fails private boolean initializeVideo() { Log.v(TAG, "initializeVideo"); boolean isCaptureIntent = isVideoCaptureIntent(); Intent intent = getIntent(); Bundle myExtras = intent.getExtras(); if (isCaptureIntent && myExtras != null) { Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); if (saveUri != null) { try { mCameraVideoFileDescriptor = mContentResolver. openFileDescriptor(saveUri, "rw").getFileDescriptor(); mCurrentVideoUri = saveUri; } catch (java.io.FileNotFoundException ex) { // invalid uri Log.e(TAG, ex.toString()); } } } releaseMediaRecorder(); if (mSurfaceHolder == null) { Log.v(TAG, "SurfaceHolder is null"); return false; } mMediaRecorder = new MediaRecorder(); if (DEBUG_SUPPRESS_AUDIO_RECORDING) { Log.v(TAG, "DEBUG_SUPPRESS_AUDIO_RECORDING is true."); } else { mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); } mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); - if (mStorageHint != null) { + if (mStorageStatus != STORAGE_STATUS_OK) { mMediaRecorder.setOutputFile("/dev/null"); } else { // We try Uri in intent first. If it doesn't work, use our own instead. if (mCameraVideoFileDescriptor != null) { mMediaRecorder.setOutputFile(mCameraVideoFileDescriptor); } else { createVideoPath(); mMediaRecorder.setOutputFile(mCameraVideoFilename); } } boolean videoQualityHigh = getBooleanPreference(CameraSettings.KEY_VIDEO_QUALITY, CameraSettings.DEFAULT_VIDEO_QUALITY_VALUE); if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) { int extraVideoQuality = intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); videoQualityHigh = (extraVideoQuality > 0); } // Use the same frame rate for both, since internally // if the frame rate is too large, it can cause camera to become // unstable. We need to fix the MediaRecorder to disable the support // of setting frame rate for now. mMediaRecorder.setVideoFrameRate(20); if (videoQualityHigh) { mMediaRecorder.setVideoSize(352,288); } else { mMediaRecorder.setVideoSize(176,144); } mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); if (!DEBUG_SUPPRESS_AUDIO_RECORDING) { mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); } mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); try { mMediaRecorder.prepare(); } catch (IOException exception) { Log.e(TAG, "prepare failed for " + mCameraVideoFilename); releaseMediaRecorder(); // TODO: add more exception handling logic here return false; } mMediaRecorderRecording = false; return true; } private void releaseMediaRecorder() { Log.v(TAG, "Releasing media recorder."); if (mMediaRecorder != null) { cleanupEmptyFile(); mMediaRecorder.reset(); mMediaRecorder.release(); mMediaRecorder = null; } } private void restartPreview() { if (DEBUG_DO_NOT_REUSE_MEDIA_RECORDER) { Log.v(TAG, "DEBUG_DO_NOT_REUSE_MEDIA_RECORDER recreating mMediaRecorder."); initializeVideo(); } else { try { mMediaRecorder.prepare(); } catch (IOException exception) { Log.e(TAG, "prepare failed for " + mCameraVideoFilename); releaseMediaRecorder(); // TODO: add more exception handling logic here } } } private int getIntPreference(String key, int defaultValue) { String s = mPreferences.getString(key, ""); int result = defaultValue; try { result = Integer.parseInt(s); } catch (NumberFormatException e) { // Ignore, result is already the default value. } return result; } private boolean getBooleanPreference(String key, boolean defaultValue) { return getIntPreference(key, defaultValue ? 1 : 0) != 0; } private void createVideoPath() { long dateTaken = System.currentTimeMillis(); String title = createName(dateTaken); String displayName = title + ".3gp"; // Used when emailing. String cameraDirPath = ImageManager.CAMERA_IMAGE_BUCKET_NAME; File cameraDir = new File(cameraDirPath); cameraDir.mkdirs(); SimpleDateFormat dateFormat = new SimpleDateFormat( getString(R.string.video_file_name_format)); Date date = new Date(dateTaken); String filepart = dateFormat.format(date); String filename = cameraDirPath + "/" + filepart + ".3gp"; ContentValues values = new ContentValues(7); values.put(Video.Media.TITLE, title); values.put(Video.Media.DISPLAY_NAME, displayName); values.put(Video.Media.DESCRIPTION, ""); values.put(Video.Media.DATE_TAKEN, dateTaken); values.put(Video.Media.MIME_TYPE, "video/3gpp"); values.put(Video.Media.DATA, filename); mCameraVideoFilename = filename; Log.v(TAG, "Current camera video filename: " + mCameraVideoFilename); mCurrentVideoValues = values; } private void registerVideo() { if (mCameraVideoFileDescriptor == null) { Uri videoTable = Uri.parse("content://media/external/video/media"); mCurrentVideoUri = mContentResolver.insert(videoTable, mCurrentVideoValues); Log.v(TAG, "Current video URI: " + mCurrentVideoUri); } mCurrentVideoValues = null; } private void deleteCurrentVideo() { if (mCurrentVideoFilename != null) { deleteVideoFile(mCurrentVideoFilename); mCurrentVideoFilename = null; } if (mCurrentVideoUri != null) { mContentResolver.delete(mCurrentVideoUri, null, null); mCurrentVideoUri = null; } } private void deleteVideoFile(String fileName) { Log.v(TAG, "Deleting video " + fileName); File f = new File(fileName); if (! f.delete()) { Log.v(TAG, "Could not delete " + fileName); } } private void addBaseMenuItems(Menu menu) { MenuHelper.addSwitchModeMenuItem(menu, this, false); { MenuItem gallery = menu.add(MenuHelper.IMAGE_MODE_ITEM, MENU_GALLERY_PHOTOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } { MenuItem gallery = menu.add(MenuHelper.VIDEO_MODE_ITEM, MENU_GALLERY_VIDEOS, 0, R.string.camera_gallery_photos_text).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); } MenuItem item = menu.add(MenuHelper.GENERIC_ITEM, MENU_SETTINGS, 0, R.string.settings).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(); intent.setClass(VideoCamera.this, CameraSettings.class); startActivity(intent); return true; } }); item.setIcon(android.R.drawable.ic_menu_preferences); } // from MediaRecorder.OnErrorListener public void onError(MediaRecorder mr, int what, int extra) { if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) { // We may have run out of space on the sdcard. stopVideoRecording(); - updateStorageHint(true); + updateAndShowStorageHint(true); } } /* * Make sure we're not recording music playing in the background, ask * the MediaPlaybackService to pause playback. */ private void pauseAudioPlayback() { // Shamelessly copied from MediaPlaybackService.java, which // should be public, but isn't. Intent i = new Intent("com.android.music.musicservicecommand"); i.putExtra("command", "pause"); sendBroadcast(i); } private void startVideoRecording() { Log.v(TAG, "startVideoRecording"); if (!mMediaRecorderRecording) { - if (mStorageHint != null) { + if (mStorageStatus != STORAGE_STATUS_OK) { Log.v(TAG, "Storage issue, ignore the start request"); return; } // Check mMediaRecorder to see whether it is initialized or not. if (mMediaRecorder == null && initializeVideo() == false ) { Log.e(TAG, "Initialize video (MediaRecorder) failed."); return; } pauseAudioPlayback(); try { mMediaRecorder.setOnErrorListener(this); mMediaRecorder.start(); // Recording is now started } catch (RuntimeException e) { Log.e(TAG, "Could not start media recorder. ", e); return; } mMediaRecorderRecording = true; mRecordingStartTime = SystemClock.uptimeMillis(); updateRecordingIndicator(true); mRecordingTimeView.setText(""); mRecordingTimeView.setVisibility(View.VISIBLE); mHandler.sendEmptyMessage(UPDATE_RECORD_TIME); setScreenTimeoutInfinite(); } } private void updateRecordingIndicator(boolean showRecording) { int drawableId = showRecording ? R.drawable.ic_camera_bar_indicator_record : R.drawable.ic_camera_indicator_video; Drawable drawable = getResources().getDrawable(drawableId); mShutterButton.setImageDrawable(drawable); } private void stopVideoRecordingAndDisplayDialog() { Log.v(TAG, "stopVideoRecordingAndDisplayDialog"); if (mMediaRecorderRecording) { stopVideoRecording(); acquireAndShowVideoFrame(); showPostRecordingAlert(); } } private void showPostRecordingAlert() { int[] pickIds = {R.id.attach, R.id.cancel}; int[] normalIds = {R.id.gallery, R.id.share, R.id.discard}; int[] alwaysOnIds = {R.id.play}; int[] hideIds = pickIds; int[] connectIds = normalIds; if (isVideoCaptureIntent()) { hideIds = normalIds; connectIds = pickIds; } for(int id : hideIds) { mPostPictureAlert.findViewById(id).setVisibility(View.GONE); } connectAndFadeIn(connectIds); connectAndFadeIn(alwaysOnIds); mPostPictureAlert.setVisibility(View.VISIBLE); } private void connectAndFadeIn(int[] connectIds) { for(int id : connectIds) { View view = mPostPictureAlert.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } private void hidePostPictureAlert() { mPostPictureAlert.setVisibility(View.INVISIBLE); } private boolean isPostRecordingAlertVisible() { return mPostPictureAlert.getVisibility() == View.VISIBLE; } private void stopVideoRecording() { Log.v(TAG, "stopVideoRecording"); boolean needToRegisterRecording = false; if (mMediaRecorderRecording || mMediaRecorder != null) { if (mMediaRecorderRecording && mMediaRecorder != null) { try { mMediaRecorder.setOnErrorListener(null); mMediaRecorder.stop(); } catch (RuntimeException e) { Log.e(TAG, "stop fail: " + e.getMessage()); } mCurrentVideoFilename = mCameraVideoFilename; Log.v(TAG, "Setting current video filename: " + mCurrentVideoFilename); needToRegisterRecording = true; mMediaRecorderRecording = false; } releaseMediaRecorder(); updateRecordingIndicator(false); mRecordingTimeView.setVisibility(View.GONE); setScreenTimeoutLong(); } - if (needToRegisterRecording && mStorageHint == null) registerVideo(); + if (needToRegisterRecording && mStorageStatus == STORAGE_STATUS_OK) { + registerVideo(); + } mCameraVideoFilename = null; mCameraVideoFileDescriptor = null; } private void setScreenTimeoutSystemDefault() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); clearScreenOnFlag(); } private void setScreenTimeoutLong() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); setScreenOnFlag(); mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); } private void setScreenTimeoutInfinite() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); setScreenOnFlag(); } private void clearScreenOnFlag() { Window w = getWindow(); final int keepScreenOnFlag = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; if ((w.getAttributes().flags & keepScreenOnFlag) != 0) { w.clearFlags(keepScreenOnFlag); } } private void setScreenOnFlag() { Window w = getWindow(); final int keepScreenOnFlag = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; if ((w.getAttributes().flags & keepScreenOnFlag) == 0) { w.addFlags(keepScreenOnFlag); } } private void hideVideoFrameAndStartPreview() { hidePostPictureAlert(); hideVideoFrame(); restartPreview(); } private void acquireAndShowVideoFrame() { recycleVideoFrameBitmap(); mVideoFrameBitmap = ImageManager.createVideoThumbnail(mCurrentVideoFilename); mVideoFrame.setImageBitmap(mVideoFrameBitmap); mVideoFrame.setVisibility(View.VISIBLE); } private void hideVideoFrame() { recycleVideoFrameBitmap(); mVideoFrame.setVisibility(View.GONE); } private void recycleVideoFrameBitmap() { if (mVideoFrameBitmap != null) { mVideoFrame.setImageDrawable(null); mVideoFrameBitmap.recycle(); mVideoFrameBitmap = null; } } } diff --git a/src/com/android/camera/ViewImage.java b/src/com/android/camera/ViewImage.java index 254cd60..a5a3821 100644 --- a/src/com/android/camera/ViewImage.java +++ b/src/com/android/camera/ViewImage.java @@ -1,1680 +1,1563 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import java.util.Random; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.util.AttributeSet; import android.util.Config; import android.util.Log; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import android.widget.Scroller; import android.widget.Toast; import android.widget.ZoomButtonsController; -import android.widget.ZoomRingController; import com.android.camera.ImageManager.IImage; public class ViewImage extends Activity implements View.OnClickListener { static final String TAG = "ViewImage"; private ImageGetter mGetter; static final boolean sSlideShowHidesStatusBar = true; // Choices for what adjacents to load. static private final int[] sOrder_adjacents = new int[] { 0, 1, -1 }; static private final int[] sOrder_slideshow = new int[] { 0 }; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { } }; private Random mRandom = new Random(System.currentTimeMillis()); private int [] mShuffleOrder; private boolean mUseShuffleOrder = false; private boolean mSlideShowLoop = false; private static final int MODE_NORMAL = 1; private static final int MODE_SLIDESHOW = 2; private int mMode = MODE_NORMAL; private boolean mFullScreenInNormalMode; private boolean mShowActionIcons; private View mActionIconPanel; private View mShutterButton; private boolean mSortAscending = false; private int mSlideShowInterval; private int mLastSlideShowImage; private boolean mFirst = true; private int mCurrentPosition = 0; private boolean mLayoutComplete = false; // represents which style animation to use private int mAnimationIndex; private Animation [] mSlideShowInAnimation; private Animation [] mSlideShowOutAnimation; private SharedPreferences mPrefs; private View mNextImageView, mPrevImageView; private Animation mHideNextImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mHidePrevImageViewAnimation = new AlphaAnimation(1F, 0F); private Animation mShowNextImageViewAnimation = new AlphaAnimation(0F, 1F); private Animation mShowPrevImageViewAnimation = new AlphaAnimation(0F, 1F); static final int sPadding = 20; static final int sHysteresis = sPadding * 2; static final int sBaseScrollDuration = 1000; // ms private ImageManager.IImageList mAllImages; private int mSlideShowImageCurrent = 0; private ImageViewTouch [] mSlideShowImageViews = new ImageViewTouch[2]; // Array of image views. The center view is the one the user is focused // on. The one at the zeroth position and the second position reflect // the images to the left/right of the center image. private ImageViewTouch[] mImageViews = new ImageViewTouch[3]; // Container for the three image views. This guy can be "scrolled" // to reveal the image prior to and after the center image. private ScrollHandler mScroller; private MenuHelper.MenuItemsResult mImageMenuRunnable; private Runnable mDismissOnScreenControlsRunnable; private boolean mCameraReviewMode; private int mCurrentOrientation; public ViewImage() { } private void updateNextPrevControls() { boolean showPrev = mCurrentPosition > 0; boolean showNext = mCurrentPosition < mAllImages.getCount() - 1; boolean prevIsVisible = mPrevImageView.getVisibility() == View.VISIBLE; boolean nextIsVisible = mNextImageView.getVisibility() == View.VISIBLE; if (showPrev && !prevIsVisible) { Animation a = mShowPrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.VISIBLE); } else if (!showPrev && prevIsVisible) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.GONE); } if (showNext && !nextIsVisible) { Animation a = mShowNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.VISIBLE); } else if (!showNext && nextIsVisible) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.GONE); } } private void showOnScreenControls() { updateNextPrevControls(); scheduleDismissOnScreenControls(); } @Override public boolean dispatchTouchEvent(MotionEvent m) { boolean sup = super.dispatchTouchEvent(m); if (sup == false) { if (mMode == MODE_SLIDESHOW) { mSlideShowImageViews[mSlideShowImageCurrent].handleTouchEvent(m); } else if (mMode == MODE_NORMAL){ mImageViews[1].handleTouchEvent(m); } return true; } return true; } private void scheduleDismissOnScreenControls() { mHandler.removeCallbacks(mDismissOnScreenControlsRunnable); mHandler.postDelayed(mDismissOnScreenControlsRunnable, 1500); } public void setupDismissOnScreenControlRunnable() { mDismissOnScreenControlsRunnable = new Runnable() { public void run() { if (!mShowActionIcons) { if (mNextImageView.getVisibility() == View.VISIBLE) { Animation a = mHideNextImageViewAnimation; a.setDuration(500); a.startNow(); mNextImageView.setAnimation(a); mNextImageView.setVisibility(View.INVISIBLE); } if (mPrevImageView.getVisibility() == View.VISIBLE) { Animation a = mHidePrevImageViewAnimation; a.setDuration(500); a.startNow(); mPrevImageView.setAnimation(a); mPrevImageView.setVisibility(View.INVISIBLE); } } } }; } private boolean isPickIntent() { String action = getIntent().getAction(); return (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)); } private static final boolean sUseBounce = false; private static final boolean sAnimateTransitions = false; static public class ImageViewTouch extends ImageViewTouchBase { private ViewImage mViewImage; private boolean mEnableTrackballScroll; private GestureDetector mGestureDetector; private static int TOUCH_AREA_WIDTH = 60; - - // The zoom ring setup: - // We limit the thumb on the zoom ring in the range 0 to 5/3*PI. The - // last PI/3 of the ring is left as a region that the thumb can't go in. - // The 5/3*PI range is divided into 60 steps. Each step scales the image - // by mScaleRate. We make mScaleRate^60 = maxZoom(). - - // This is the max step value we can have for the zoom ring. - private static int MAX_STEP = 60; - // This is the angle we used to separate each step. - private static float STEP_ANGLE = (5 * (float) Math.PI / 3) / MAX_STEP; - // The scale rate for each step. - private float mScaleRate; - - // Returns current scale step (numbered from 0 to MAX_STEP). - private int getCurrentStep() { - float s = getScale(); - float b = mScaleRate; - int step = (int)Math.round(Math.log(s) / Math.log(b)); - return Math.max(0, Math.min(MAX_STEP, step)); - } - - // Limit the thumb on the zoom ring in the range 0 to 5/3*PI. (clockwise - // angle is negative, and we need to mod 2*PI for the API to work.) - private void setZoomRingBounds() { - mScaleRate = (float) Math.pow(maxZoom(), 1.0 / MAX_STEP); - float limit = (2 - 5 / 3F) * (float) Math.PI; - mZoomRingController.setThumbClockwiseBound(limit); - mZoomRingController.setThumbCounterclockwiseBound(0); - } private ZoomButtonsController mZoomButtonsController; - - // The zoom ring is set to visible by a double tap. - private ZoomRingController mZoomRingController; - private ZoomRingController.OnZoomListener mZoomListener = - new ZoomRingController.OnZoomListener() { - public void onCenter(int x, int y) { - } - - public void onBeginPan() { - } - - public boolean onPan(int deltaX, int deltaY) { - postTranslate(-deltaX, -deltaY, sUseBounce); - ImageViewTouch.this.center(true, true, false); - return true; - } - - public void onEndPan() { - } - - // The clockwise angle is negative, so we need to mod 2*PI - private float stepToAngle(int step) { - float angle = step * STEP_ANGLE; - angle = (float) Math.PI * 2 - angle; - return angle; - } - - private int angleToStep(double angle) { - angle = Math.PI * 2 - angle; - int step = (int)Math.round(angle / STEP_ANGLE); - return step; - } - - public void onVisibilityChanged(boolean visible) { - if (visible) { - int step = getCurrentStep(); - float angle = stepToAngle(step); - mZoomRingController.setThumbAngle(angle); - } - } - - public void onBeginDrag() { - setZoomRingBounds(); - } - - public void onEndDrag() { - } - - public boolean onDragZoom(int deltaZoomLevel, int centerX, - int centerY, float startAngle, float curAngle) { - setZoomRingBounds(); - int deltaStep = angleToStep(curAngle) - getCurrentStep(); - if ((deltaZoomLevel > 0) && (deltaStep < 0)) return false; - if ((deltaZoomLevel < 0) && (deltaStep > 0)) return false; - if ((deltaZoomLevel == 0) || (deltaStep == 0)) return false; - - float oldScale = getScale(); - - // First move centerX/centerY to the center of the view. - int deltaX = getWidth() / 2 - centerX; - int deltaY = getHeight() / 2 - centerY; - panBy(deltaX, deltaY); - - // Do zoom in/out. - if (deltaStep > 0) { - zoomIn((float) Math.pow(mScaleRate, deltaStep)); - } else if (deltaStep < 0) { - zoomOut((float) Math.pow(mScaleRate, -deltaStep)); - } - - // Reverse the first centering. - panBy(-deltaX, -deltaY); - - // Return true if the zoom succeeds. - return (oldScale != getScale()); - } - - public void onSimpleZoom(boolean zoomIn, int centerX, int centerY) { - // First move centerX/centerY to the center of the view. - int deltaX = getWidth() / 2 - centerX; - int deltaY = getHeight() / 2 - centerY; - panBy(deltaX, deltaY); - - if (zoomIn) { - zoomIn(); - } else { - zoomOut(); - } - - panBy(-deltaX, -deltaY); - } - }; public ImageViewTouch(Context context) { super(context); setup(context); } public ImageViewTouch(Context context, AttributeSet attrs) { super(context, attrs); setup(context); } private void setup(Context context) { mViewImage = (ViewImage) context; - mZoomRingController = new ZoomRingController(context, this); - mZoomRingController.setVibration(false); - mZoomRingController.setTickDelta(STEP_ANGLE); - mZoomRingController.setCallback(mZoomListener); mGestureDetector = new GestureDetector(getContext(), new MyGestureListener()); mGestureDetector.setOnDoubleTapListener(new MyDoubleTapListener()); mZoomButtonsController = new ZoomButtonsController(context, this); mZoomButtonsController.setOverviewVisible(false); mZoomButtonsController.setCallback(new ZoomButtonsController.OnZoomListener() { - public void onCenter(int x, int y) { - mZoomListener.onCenter(x, y); } public void onOverview() { } public void onVisibilityChanged(boolean visible) { - mZoomListener.onVisibilityChanged(visible); + if (visible) { + updateButtonsEnabled(); + } } public void onZoom(boolean zoomIn) { - mZoomListener.onSimpleZoom(zoomIn, getWidth()/2, getHeight()/2); + if (zoomIn) { + zoomIn(); + } else { + zoomOut(); + } + + updateButtonsEnabled(); + } + + private void updateButtonsEnabled() { + float scale = getScale(); + mZoomButtonsController.setZoomInEnabled(scale < mMaxZoom); + mZoomButtonsController.setZoomOutEnabled(scale > 1); } }); } public void setEnableTrackballScroll(boolean enable) { mEnableTrackballScroll = enable; } protected void postTranslate(float dx, float dy, boolean bounceOK) { super.postTranslate(dx, dy); if (dx != 0F || dy != 0F) mViewImage.showOnScreenControls(); if (!sUseBounce) { center(true, false, false); } } protected ScrollHandler scrollHandler() { return mViewImage.mScroller; } public boolean handleTouchEvent(MotionEvent m) { return mGestureDetector.onTouchEvent(m); } private class MyGestureListener extends GestureDetector.SimpleOnGestureListener { public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (getScale() > 1F) { postTranslate(-distanceX, -distanceY, sUseBounce); ImageViewTouch.this.center(true, true, false); } return true; } } private class MyDoubleTapListener implements GestureDetector.OnDoubleTapListener { // On single tap, we show the arrows. We also change to the // prev/next image if the user taps on the left/right region. public boolean onSingleTapConfirmed(MotionEvent e) { ViewImage viewImage = mViewImage; int viewWidth = getWidth(); int x = (int) e.getX(); int y = (int) e.getY(); if (x < TOUCH_AREA_WIDTH) { viewImage.moveNextOrPrevious(-1); } else if (x > viewWidth - TOUCH_AREA_WIDTH) { viewImage.moveNextOrPrevious(1); } viewImage.setMode(MODE_NORMAL); viewImage.showOnScreenControls(); return true; } - // On double tap, we show the zoom ring control. + // On double tap, we show the zoom controls. public boolean onDoubleTapEvent(MotionEvent e) { mViewImage.setMode(MODE_NORMAL); - mZoomRingController.handleDoubleTapEvent(e); mZoomButtonsController.handleDoubleTapEvent(e); return true; } public boolean onDoubleTap(MotionEvent e) { return false; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Don't respond to arrow keys if trackball scrolling is not enabled if (!mEnableTrackballScroll) { if ((keyCode >= KeyEvent.KEYCODE_DPAD_UP) && (keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT)) { return super.onKeyDown(keyCode, event); } } int current = mViewImage.mCurrentPosition; int nextImagePos = -2; // default no next image try { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: { if (mViewImage.isPickIntent()) { ImageManager.IImage img = mViewImage.mAllImages.getImageAt(mViewImage.mCurrentPosition); mViewImage.setResult(RESULT_OK, new Intent().setData(img.fullSizeImageUri())); mViewImage.finish(); } break; } case KeyEvent.KEYCODE_DPAD_LEFT: { panBy(sPanRate, 0); int maxOffset = (current == 0) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(true, maxOffset)) { nextImagePos = current - 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_RIGHT: { panBy(-sPanRate, 0); int maxOffset = (current == mViewImage.mAllImages.getCount()-1) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(false, maxOffset)) { nextImagePos = current + 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_UP: { panBy(0, sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DPAD_DOWN: { panBy(0, -sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DEL: MenuHelper.deletePhoto(mViewImage, mViewImage.mDeletePhotoRunnable); break; } } finally { if (nextImagePos >= 0 && nextImagePos < mViewImage.mAllImages.getCount()) { synchronized (mViewImage) { mViewImage.setMode(MODE_NORMAL); mViewImage.setImage(nextImagePos); } } else if (nextImagePos != -2) { center(true, true, false); } } return super.onKeyDown(keyCode, event); } protected boolean isShiftedToNextImage(boolean left, int maxOffset) { boolean retval; Bitmap bitmap = mBitmapDisplayed; Matrix m = getImageViewMatrix(); if (left) { float [] t1 = new float[] { 0, 0 }; m.mapPoints(t1); retval = t1[0] > maxOffset; } else { int width = bitmap != null ? bitmap.getWidth() : getWidth(); float [] t1 = new float[] { width, 0 }; m.mapPoints(t1); retval = t1[0] + maxOffset < getWidth(); } return retval; } protected void scrollX(int deltaX) { scrollHandler().scrollBy(deltaX, 0); } protected int getScrollOffset() { return scrollHandler().getScrollX(); } @Override protected void onDetachedFromWindow() { - mZoomRingController.setVisible(false); mZoomButtonsController.setVisible(false); } } static class ScrollHandler extends LinearLayout { private Runnable mFirstLayoutCompletedCallback = null; private Scroller mScrollerHelper; private int mWidth = -1; public ScrollHandler(Context context) { super(context); mScrollerHelper = new Scroller(context); } public ScrollHandler(Context context, AttributeSet attrs) { super(context, attrs); mScrollerHelper = new Scroller(context); } public void setLayoutCompletedCallback(Runnable r) { mFirstLayoutCompletedCallback = r; } public void startScrollTo(int newX, int newY) { int oldX = getScrollX(); int oldY = getScrollY(); int deltaX = newX - oldX; int deltaY = newY - oldY; if (mWidth == -1) { mWidth = findViewById(R.id.image2).getWidth(); } int viewWidth = mWidth; int duration = viewWidth > 0 ? sBaseScrollDuration * Math.abs(deltaX) / viewWidth : 0; mScrollerHelper.startScroll(oldX, oldY, deltaX, deltaY, duration); invalidate(); } @Override public void computeScroll() { if (mScrollerHelper.computeScrollOffset()) { scrollTo(mScrollerHelper.getCurrX(), mScrollerHelper.getCurrY()); postInvalidate(); // So we draw again } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int width = right - left; int x = 0; for (View v : new View[] { findViewById(R.id.image1), findViewById(R.id.image2), findViewById(R.id.image3) }) { v.layout(x, 0, x + width, bottom); x += (width + sPadding); } findViewById(R.id.padding1).layout(width, 0, width + sPadding, bottom); findViewById(R.id.padding2).layout(width+sPadding+width, 0, width+sPadding+width+sPadding, bottom); if (changed) { if (mFirstLayoutCompletedCallback != null) { mFirstLayoutCompletedCallback.run(); } } } } private void animateScrollTo(int xNew, int yNew) { mScroller.startScrollTo(xNew, yNew); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (! mCameraReviewMode) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.slide_show); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { setMode(MODE_SLIDESHOW); mLastSlideShowImage = mCurrentPosition; loadNextImage(mCurrentPosition, 0, true); return true; } }); item.setIcon(android.R.drawable.ic_menu_slideshow); } final SelectedImageGetter selectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return mAllImages.getImageAt(mCurrentPosition); } public Uri getCurrentImageUri() { return mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); } }; mImageMenuRunnable = MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL, true, ViewImage.this, mHandler, mDeletePhotoRunnable, new MenuHelper.MenuInvoker() { public void run(MenuHelper.MenuCallback cb) { setMode(MODE_NORMAL); cb.run(selectedImageGetter.getCurrentImageUri(), selectedImageGetter.getCurrentImage()); for (ImageViewTouchBase iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } setImage(mCurrentPosition); } }); if (true) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 1000, R.string.camerasettings); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent preferences = new Intent(); preferences.setClass(ViewImage.this, GallerySettings.class); startActivity(preferences); return true; } }); item.setAlphabeticShortcut('p'); item.setIcon(android.R.drawable.ic_menu_preferences); } // Hidden menu just so the shortcut will bring up the zoom controls menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.camerasettings) // the string resource is a placeholder .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { showOnScreenControls(); return true; } }) .setAlphabeticShortcut('z') .setVisible(false); return true; } protected Runnable mDeletePhotoRunnable = new Runnable() { public void run() { mAllImages.removeImageAt(mCurrentPosition); if (mAllImages.getCount() == 0) { finish(); } else { if (mCurrentPosition == mAllImages.getCount()) { mCurrentPosition -= 1; } } for (ImageViewTouchBase iv: mImageViews) { iv.setImageBitmapResetBase(null, true, true); } setImage(mCurrentPosition); } }; @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); setMode(MODE_NORMAL); if (mImageMenuRunnable != null) { mImageMenuRunnable.gettingReadyToOpen(menu, mAllImages.getImageAt(mCurrentPosition)); } return true; } @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean changed = mCurrentOrientation != newConfig.orientation; mCurrentOrientation = newConfig.orientation; if (changed) { if (mGetter != null) { // kill off any background image fetching mGetter.cancelCurrent(); mGetter.stop(); } makeGetter(); mFirst = true; // clear off the current set of images since we need to reload // them at the right size for (ImageViewTouchBase iv: mImageViews) { iv.clear(); } MenuHelper.requestOrientation(this, mPrefs); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { boolean b = super.onMenuItemSelected(featureId, item); if (mImageMenuRunnable != null) mImageMenuRunnable.aboutToCall(item, mAllImages.getImageAt(mCurrentPosition)); return b; } /* * Here's the loading strategy. For any given image, load the thumbnail * into memory and post a callback to display the resulting bitmap. * * Then proceed to load the full image bitmap. Three things can * happen at this point: * * 1. the image fails to load because the UI thread decided * to move on to a different image. This "cancellation" happens * by virtue of the UI thread closing the stream containing the * image being decoded. BitmapFactory.decodeStream returns null * in this case. * * 2. the image loaded successfully. At that point we post * a callback to the UI thread to actually show the bitmap. * * 3. when the post runs it checks to see if the image that was * loaded is still the one we want. The UI may have moved on * to some other image and if so we just drop the newly loaded * bitmap on the floor. */ interface ImageGetterCallback { public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb); public boolean wantsThumbnail(int pos, int offset); public boolean wantsFullImage(int pos, int offset); public int fullImageSizeToUse(int pos, int offset); public void completed(boolean wasCanceled); public int [] loadOrder(); } class ImageGetter { // The thread which does the work. private Thread mGetterThread; // The base position that's being retrieved. The actual images retrieved // are this base plus each of the offets. private int mCurrentPosition = -1; // The callback to invoke for each image. private ImageGetterCallback mCB; // This is the loader cancelable that gets set while we're loading an image. // If we change position we can cancel the current load using this. private ImageManager.IGetBitmap_cancelable mLoad; // True if we're canceling the current load. private boolean mCancelCurrent = false; // True when the therad should exit. private boolean mDone = false; // True when the loader thread is waiting for work. private boolean mReady = false; private void cancelCurrent() { synchronized (this) { if (!mReady) { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { if (Config.LOGV) Log.v(TAG, "canceling load object"); load.cancel(); } mCancelCurrent = false; } } } public ImageGetter() { mGetterThread = new Thread(new Runnable() { private Runnable callback(final int position, final int offset, final boolean isThumb, final Bitmap bitmap) { return new Runnable() { public void run() { // check for inflight callbacks that aren't applicable any longer // before delivering them if (!isCanceled() && position == mCurrentPosition) { mCB.imageLoaded(position, offset, bitmap, isThumb); } else { if (bitmap != null) bitmap.recycle(); } } }; } private Runnable completedCallback(final boolean wasCanceled) { return new Runnable() { public void run() { mCB.completed(wasCanceled); } }; } public void run() { int lastPosition = -1; while (!mDone) { synchronized (ImageGetter.this) { mReady = true; ImageGetter.this.notify(); if (mCurrentPosition == -1 || lastPosition == mCurrentPosition) { try { ImageGetter.this.wait(); } catch (InterruptedException ex) { continue; } } lastPosition = mCurrentPosition; mReady = false; } if (lastPosition != -1) { int imageCount = mAllImages.getCount(); int [] order = mCB.loadOrder(); for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (image == null || isCanceled()) { break; } if (mCB.wantsThumbnail(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting THUMBNAIL load at offset " + offset); Bitmap b = image.thumbBitmap(); mHandler.post(callback(lastPosition, offset, true, b)); } } } for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (mCB.wantsFullImage(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting FULL IMAGE load at offset " + offset); int sizeToUse = mCB.fullImageSizeToUse(lastPosition, offset); if (image != null && !isCanceled()) { mLoad = image.fullSizeBitmap_cancelable(sizeToUse); } if (mLoad != null) { long t1; if (Config.LOGV) t1 = System.currentTimeMillis(); // The return value could be null if the // bitmap is too big, or we cancelled it. Bitmap b = mLoad.get(); if (Config.LOGV && b != null) { long t2 = System.currentTimeMillis(); Log.v(TAG, "loading full image for " + image.fullSizeImageUri() + " with requested size " + sizeToUse + " took " + (t2-t1) + " and returned a bitmap with size " + b.getWidth() + " / " + b.getHeight()); } mLoad = null; if (b != null) { if (isCanceled()) { b.recycle(); } else { mHandler.post(callback(lastPosition, offset, false, b)); } } } } } } mHandler.post(completedCallback(isCanceled())); } } } }); mGetterThread.setName("ImageGettter"); mGetterThread.start(); } private boolean isCanceled() { synchronized (this) { return mCancelCurrent; } } public void setPosition(int position, ImageGetterCallback cb) { synchronized (this) { if (!mReady) { try { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { load.cancel(); } // if the thread is waiting before loading the full size // image then this will free it up ImageGetter.this.notify(); ImageGetter.this.wait(); mCancelCurrent = false; } catch (InterruptedException ex) { // not sure what to do here } } } mCurrentPosition = position; mCB = cb; synchronized (this) { ImageGetter.this.notify(); } } public void stop() { synchronized (this) { mDone = true; ImageGetter.this.notify(); } try { mGetterThread.join(); } catch (InterruptedException ex) { } } } private void setImage(int pos) { if (!mLayoutComplete) { return; } final boolean left = mCurrentPosition > pos; mCurrentPosition = pos; ImageViewTouchBase current = mImageViews[1]; current.mSuppMatrix.reset(); current.setImageMatrix(current.getImageViewMatrix()); if (false) { Log.v(TAG, "before..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } if (!mFirst) { if (left) { mImageViews[2].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[0]); } else { mImageViews[0].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[2]); } } if (false) { Log.v(TAG, "after copy..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } for (ImageViewTouchBase ivt: mImageViews) { ivt.mIsZooming = false; } int width = mImageViews[1].getWidth(); int from; int to = width + sPadding; if (mFirst) { from = to; mFirst = false; } else { from = left ? (width + sPadding) + mScroller.getScrollX() : mScroller.getScrollX() - (width + sPadding); } if (sAnimateTransitions) { mScroller.scrollTo(from, 0); animateScrollTo(to, 0); } else { mScroller.scrollTo(to, 0); } ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { if (!mShowActionIcons) { mImageViews[1].setFocusableInTouchMode(true); mImageViews[1].requestFocus(); } } public boolean wantsThumbnail(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; return ivt.mThumbBitmap == null; } public boolean wantsFullImage(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; if (ivt.mBitmapDisplayed != null && !ivt.mBitmapIsThumbnail) { return false; } if (offset != 0) { return false; } return true; } public int fullImageSizeToUse(int pos, int offset) { // TODO // this number should be bigger so that we can zoom. we may need to // get fancier and read in the fuller size image as the user starts // to zoom. use -1 to get the full full size image. // for now use 480 so we don't run out of memory final int imageViewSize = 480; return imageViewSize; } public int [] loadOrder() { return sOrder_adjacents; } public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb) { ImageViewTouchBase ivt = mImageViews[1 + offset]; ivt.setImageBitmapResetBase(bitmap, isThumb, isThumb); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { mGetter.setPosition(pos, cb); } showOnScreenControls(); } @Override public void onCreate(Bundle instanceState) { super.onCreate(instanceState); Intent intent = getIntent(); mCameraReviewMode = intent.getBooleanExtra("com.android.camera.ReviewMode", false); mFullScreenInNormalMode = intent.getBooleanExtra(MediaStore.EXTRA_FULL_SCREEN, true); mShowActionIcons = intent.getBooleanExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, false); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mCurrentOrientation = getResources().getConfiguration().orientation; setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.viewimage); mImageViews[0] = (ImageViewTouch) findViewById(R.id.image1); mImageViews[1] = (ImageViewTouch) findViewById(R.id.image2); mImageViews[2] = (ImageViewTouch) findViewById(R.id.image3); for(ImageViewTouch v : mImageViews) { v.setEnableTrackballScroll(!mShowActionIcons); } mScroller = (ScrollHandler)findViewById(R.id.scroller); makeGetter(); mAnimationIndex = -1; mSlideShowInAnimation = new Animation[] { makeInAnimation(R.anim.transition_in), makeInAnimation(R.anim.slide_in), makeInAnimation(R.anim.slide_in_vertical), }; mSlideShowOutAnimation = new Animation[] { makeOutAnimation(R.anim.transition_out), makeOutAnimation(R.anim.slide_out), makeOutAnimation(R.anim.slide_out_vertical), }; mSlideShowImageViews[0] = (ImageViewTouch) findViewById(R.id.image1_slideShow); mSlideShowImageViews[1] = (ImageViewTouch) findViewById(R.id.image2_slideShow); for (ImageViewTouch v : mSlideShowImageViews) { v.setImageBitmapResetBase(null, true, true); v.setVisibility(View.INVISIBLE); v.setEnableTrackballScroll(!mShowActionIcons); } mActionIconPanel = findViewById(R.id.action_icon_panel); { int[] pickIds = {R.id.attach, R.id.cancel}; int[] normalIds = {R.id.gallery, R.id.setas, R.id.share, R.id.discard}; int[] hideIds = pickIds; int[] connectIds = normalIds; if (isPickIntent()) { hideIds = normalIds; connectIds = pickIds; } for(int id : hideIds) { mActionIconPanel.findViewById(id).setVisibility(View.GONE); } for(int id : connectIds) { View view = mActionIconPanel.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } mShutterButton = findViewById(R.id.shutter_button); mShutterButton.setOnClickListener(this); Uri uri = getIntent().getData(); if (Config.LOGV) Log.v(TAG, "uri is " + uri); if (instanceState != null) { if (instanceState.containsKey("uri")) { uri = Uri.parse(instanceState.getString("uri")); } } if (uri == null) { finish(); return; } init(uri); Bundle b = getIntent().getExtras(); boolean slideShow = b != null ? b.getBoolean("slideshow", false) : false; if (slideShow) { setMode(MODE_SLIDESHOW); loadNextImage(mCurrentPosition, 0, true); } else { if (mFullScreenInNormalMode) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } } setupDismissOnScreenControlRunnable(); mNextImageView = findViewById(R.id.next_image); mPrevImageView = findViewById(R.id.prev_image); mNextImageView.setOnClickListener(this); mPrevImageView.setOnClickListener(this); if (mShowActionIcons) { mNextImageView.setFocusable(true); mPrevImageView.setFocusable(true); } setOrientation(); } private void setOrientation() { Intent intent = getIntent(); if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); if (orientation != getRequestedOrientation()) { setRequestedOrientation(orientation); } } else { MenuHelper.requestOrientation(this, mPrefs); } } private Animation makeInAnimation(int id) { Animation inAnimation = AnimationUtils.loadAnimation(this, id); return inAnimation; } private Animation makeOutAnimation(int id) { Animation outAnimation = AnimationUtils.loadAnimation(this, id); return outAnimation; } private void setMode(int mode) { if (mMode == mode) { return; } findViewById(R.id.slideShowContainer).setVisibility(mode == MODE_SLIDESHOW ? View.VISIBLE : View.GONE); findViewById(R.id.abs) .setVisibility(mode == MODE_NORMAL ? View.VISIBLE : View.GONE); Window win = getWindow(); mMode = mode; if (mode == MODE_SLIDESHOW) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (sSlideShowHidesStatusBar) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } for (ImageViewTouchBase ivt: mImageViews) { ivt.clear(); } mActionIconPanel.setVisibility(View.GONE); mShutterButton.setVisibility(View.GONE); if (false) { Log.v(TAG, "current is " + this.mSlideShowImageCurrent); this.mSlideShowImageViews[0].dump(); this.mSlideShowImageViews[0].dump(); } findViewById(R.id.slideShowContainer).getRootView().requestLayout(); mUseShuffleOrder = mPrefs.getBoolean("pref_gallery_slideshow_shuffle_key", false); mSlideShowLoop = mPrefs.getBoolean("pref_gallery_slideshow_repeat_key", false); try { mAnimationIndex = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_transition_key", "0")); } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mAnimationIndex = 0; } try { mSlideShowInterval = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_interval_key", "3")) * 1000; } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mSlideShowInterval = 3000; } if (Config.LOGV) { Log.v(TAG, "read prefs... shuffle: " + mUseShuffleOrder); Log.v(TAG, "read prefs... loop: " + mSlideShowLoop); Log.v(TAG, "read prefs... animidx: " + mAnimationIndex); Log.v(TAG, "read prefs... interval: " + mSlideShowInterval); } if (mUseShuffleOrder) { generateShuffleOrder(); } } else { if (Config.LOGV) Log.v(TAG, "slide show mode off, mCurrentPosition == " + mCurrentPosition); win.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (mFullScreenInNormalMode) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mGetter != null) mGetter.cancelCurrent(); if (sSlideShowHidesStatusBar) { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } ImageViewTouchBase dst = mImageViews[1]; dst.mLastXTouchPos = -1; dst.mLastYTouchPos = -1; for (ImageViewTouchBase ivt: mSlideShowImageViews) { ivt.clear(); } mShuffleOrder = null; // mGetter null is a proxy for being paused if (mGetter != null) { mFirst = true; // don't animate setImage(mCurrentPosition); } } // this line shouldn't be necessary but the view hierarchy doesn't // seem to realize that the window layout changed mScroller.requestLayout(); } private void generateShuffleOrder() { if (mShuffleOrder == null || mShuffleOrder.length != mAllImages.getCount()) { mShuffleOrder = new int[mAllImages.getCount()]; } for (int i = 0; i < mShuffleOrder.length; i++) { mShuffleOrder[i] = i; } for (int i = mShuffleOrder.length - 1; i > 0; i--) { int r = mRandom.nextInt(i); int tmp = mShuffleOrder[r]; mShuffleOrder[r] = mShuffleOrder[i]; mShuffleOrder[i] = tmp; } } private void loadNextImage(final int requestedPos, final long delay, final boolean firstCall) { if (firstCall && mUseShuffleOrder) { generateShuffleOrder(); } final long targetDisplayTime = System.currentTimeMillis() + delay; ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { } public boolean wantsThumbnail(int pos, int offset) { return true; } public boolean wantsFullImage(int pos, int offset) { return false; } public int [] loadOrder() { return sOrder_slideshow; } public int fullImageSizeToUse(int pos, int offset) { return 480; // TODO compute this } public void imageLoaded(final int pos, final int offset, final Bitmap bitmap, final boolean isThumb) { long timeRemaining = Math.max(0, targetDisplayTime - System.currentTimeMillis()); mHandler.postDelayed(new Runnable() { public void run() { if (mMode == MODE_NORMAL) { return; } ImageViewTouchBase oldView = mSlideShowImageViews[mSlideShowImageCurrent]; if (++mSlideShowImageCurrent == mSlideShowImageViews.length) { mSlideShowImageCurrent = 0; } ImageViewTouchBase newView = mSlideShowImageViews[mSlideShowImageCurrent]; newView.setVisibility(View.VISIBLE); newView.setImageBitmapResetBase(bitmap, isThumb, isThumb); newView.bringToFront(); int animation = 0; if (mAnimationIndex == -1) { int n = mRandom.nextInt(mSlideShowInAnimation.length); animation = n; } else { animation = mAnimationIndex; } Animation aIn = mSlideShowInAnimation[animation]; newView.setAnimation(aIn); newView.setVisibility(View.VISIBLE); aIn.startNow(); Animation aOut = mSlideShowOutAnimation[animation]; oldView.setVisibility(View.INVISIBLE); oldView.setAnimation(aOut); aOut.startNow(); mCurrentPosition = requestedPos; mHandler.post(new Runnable() { public void run() { if (mCurrentPosition == mLastSlideShowImage && !firstCall) { if (mSlideShowLoop) { if (mUseShuffleOrder) { generateShuffleOrder(); } } else { setMode(MODE_NORMAL); return; } } if (Config.LOGV) Log.v(TAG, "mCurrentPosition is now " + mCurrentPosition); loadNextImage((mCurrentPosition + 1) % mAllImages.getCount(), mSlideShowInterval, false); } }); } }, timeRemaining); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { int pos = requestedPos; if (mShuffleOrder != null) { pos = mShuffleOrder[pos]; } mGetter.setPosition(pos, cb); } } private void makeGetter() { mGetter = new ImageGetter(); } private boolean desiredSortOrder() { String sortOrder = mPrefs.getString("pref_gallery_sort_key", null); boolean sortAscending = false; if (sortOrder != null) { sortAscending = sortOrder.equals("ascending"); } if (mCameraReviewMode) { // Force left-arrow older pictures, right-arrow newer pictures. sortAscending = true; } return sortAscending; } private void init(Uri uri) { mSortAscending = desiredSortOrder(); int sort = mSortAscending ? ImageManager.SORT_ASCENDING : ImageManager.SORT_DESCENDING; mAllImages = ImageManager.makeImageList(uri, this, sort); uri = uri.buildUpon().query(null).build(); // TODO smarter/faster here please for (int i = 0; i < mAllImages.getCount(); i++) { ImageManager.IImage image = mAllImages.getImageAt(i); if (image.fullSizeImageUri().equals(uri)) { mCurrentPosition = i; mLastSlideShowImage = mCurrentPosition; break; } } } @Override public void onSaveInstanceState(Bundle b) { super.onSaveInstanceState(b); ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); if (image != null){ Uri uri = image.fullSizeImageUri(); String bucket = null; if(getIntent()!= null && getIntent().getData()!=null) bucket = getIntent().getData().getQueryParameter("bucketId"); if(bucket!=null) uri = uri.buildUpon().appendQueryParameter("bucketId", bucket).build(); b.putString("uri", uri.toString()); } if (mMode == MODE_SLIDESHOW) b.putBoolean("slideshow", true); } @Override public void onResume() { super.onResume(); // normally this will never be zero but if one "backs" into this // activity after removing the sdcard it could be zero. in that // case just "finish" since there's nothing useful that can happen. if (mAllImages.getCount() == 0) { finish(); } ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); if (desiredSortOrder() != mSortAscending) { init(image.fullSizeImageUri()); } if (mGetter == null) { makeGetter(); } mFirst = true; mScroller.setLayoutCompletedCallback(new Runnable() { public void run() { mLayoutComplete = true; setImage(mCurrentPosition); } }); setImage(mCurrentPosition); setOrientation(); // Show a tutorial for the new zoom interaction (the method ensure we only show it once) - ZoomRingController.showZoomTutorialOnce(this); + ZoomButtonsController.showZoomTutorialOnce(this); } @Override public void onPause() { super.onPause(); mGetter.cancelCurrent(); mGetter.stop(); mGetter = null; setMode(MODE_NORMAL); mAllImages.deactivate(); for (ImageViewTouch iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } for (ImageViewTouch iv: mSlideShowImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } - ZoomRingController.finishZoomTutorial(this, false); + ZoomButtonsController.finishZoomTutorial(this, false); } @Override public void onStop() { super.onStop(); } public void onClick(View v) { switch (v.getId()) { case R.id.shutter_button: { if (mCameraReviewMode) { finish(); } else { MenuHelper.gotoStillImageCapture(this); } } break; case R.id.gallery: { MenuHelper.gotoCameraImageGallery(this); } break; case R.id.discard: { if (mCameraReviewMode) { mDeletePhotoRunnable.run(); } else { MenuHelper.deletePhoto(this, mDeletePhotoRunnable); } } break; case R.id.share: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_STREAM, u); try { startActivity(Intent.createChooser(intent, getText(R.string.sendImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_image, Toast.LENGTH_SHORT).show(); } } break; case R.id.setas: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA, u); try { startActivity(Intent.createChooser(intent, getText(R.string.setImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } break; case R.id.next_image: { moveNextOrPrevious(1); } break; case R.id.prev_image: { moveNextOrPrevious(-1); } break; } } private void moveNextOrPrevious(int delta) { int nextImagePos = mCurrentPosition + delta; if ((0 <= nextImagePos) && (nextImagePos < mAllImages.getCount())) { setImage(nextImagePos); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case MenuHelper.RESULT_COMMON_MENU_CROP: if (resultCode == RESULT_OK) { // The CropImage activity passes back the Uri of the cropped image as // the Action rather than the Data. Uri dataUri = Uri.parse(data.getAction()); init(dataUri); } break; } } }
brunsky/WS171-packages-apps-Camera
d7e9d1916fbabaecd4be9dacb4472fa3ffe62ed4
auto import from //depot/cupcake/@136745
diff --git a/src/com/android/camera/Camera.java b/src/com/android/camera/Camera.java index 9717d5e..56e048a 100644 --- a/src/com/android/camera/Camera.java +++ b/src/com/android/camera/Camera.java @@ -109,1026 +109,1032 @@ public class Camera extends Activity implements View.OnClickListener, public static final int MENU_GALLERY_PHOTOS = 7; public static final int MENU_GALLERY_VIDEOS = 8; public static final int MENU_SAVE_SELECT_PHOTOS = 30; public static final int MENU_SAVE_NEW_PHOTO = 31; public static final int MENU_SAVE_GALLERY_PHOTO = 34; public static final int MENU_SAVE_GALLERY_VIDEO_PHOTO = 35; public static final int MENU_SAVE_CAMERA_DONE = 36; public static final int MENU_SAVE_CAMERA_VIDEO_DONE = 37; private Toast mToast; private OrientationEventListener mOrientationListener; private int mLastOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; private SharedPreferences mPreferences; private static final int IDLE = 1; private static final int SNAPSHOT_IN_PROGRESS = 2; private static final int SNAPSHOT_COMPLETED = 3; private int mStatus = IDLE; private static final String sTempCropFilename = "crop-temp"; private android.hardware.Camera mCameraDevice; private android.hardware.Camera.Parameters mParameters; private VideoPreview mSurfaceView; private SurfaceHolder mSurfaceHolder = null; private View mBlackout = null; private int mOriginalViewFinderWidth, mOriginalViewFinderHeight; private int mViewFinderWidth, mViewFinderHeight; private boolean mPreviewing = false; private MediaPlayer mClickSound; private Capturer mCaptureObject; private ImageCapture mImageCapture = null; private boolean mPausing = false; private static final int FOCUS_NOT_STARTED = 0; private static final int FOCUSING = 1; private static final int FOCUSING_SNAP_ON_FINISH = 2; private static final int FOCUS_SUCCESS = 3; private static final int FOCUS_FAIL = 4; private int mFocusState = FOCUS_NOT_STARTED; private static ContentResolver mContentResolver; private boolean mDidRegister = false; private ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>(); private boolean mMenuSelectionMade; private ImageView mLastPictureButton; private LayerDrawable mVignette; private Animation mShowLastPictureButtonAnimation = new AlphaAnimation(0F, 1F); private boolean mShouldShowLastPictureButton; private TransitionDrawable mThumbnailTransition; private Drawable[] mThumbnails; private boolean mShouldTransitionThumbnails; private Uri mLastPictureUri; private Bitmap mLastPictureThumb; private LocationManager mLocationManager = null; private ShutterButton mShutterButton; private Animation mFocusBlinkAnimation; private View mFocusIndicator; private ToneGenerator mFocusToneGenerator; private ShutterCallback mShutterCallback = new ShutterCallback(); private RawPictureCallback mRawPictureCallback = new RawPictureCallback(); private AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback(); private long mFocusStartTime; private long mFocusCallbackTime; private long mCaptureStartTime; private long mShutterCallbackTime; private long mRawPictureCallbackTime; private int mPicturesRemaining; private boolean mKeepAndRestartPreview; // mPostCaptureAlert is non-null only if isImageCaptureIntent() is true. private View mPostCaptureAlert; private Handler mHandler = new MainHandler(); private ProgressDialog mSavingProgress; private interface Capturer { Uri getLastCaptureUri(); void onSnap(); void dismissFreezeFrame(boolean keep); void cancelSave(); void cancelAutoDismiss(); void setDone(boolean wait); } private void cancelSavingNotification() { if (mToast != null) { mToast.cancel(); mToast = null; } } /** This Handler is used to post message back onto the main thread of the application */ private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case KEEP: { keep(); if (mSavingProgress != null) { mSavingProgress.cancel(); mSavingProgress = null; } mKeepAndRestartPreview = true; if (msg.obj != null) { mHandler.post((Runnable)msg.obj); } break; } case RESTART_PREVIEW: { if (mStatus == SNAPSHOT_IN_PROGRESS) { // We are still in the processing of taking the picture, wait. // This is is strange. Why are we polling? // TODO remove polling mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, 100); } else if (mStatus == SNAPSHOT_COMPLETED){ mCaptureObject.dismissFreezeFrame(true); hidePostCaptureAlert(); } break; } case CLEAR_SCREEN_DELAY: { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); break; } } } }; LocationListener [] mLocationListeners = new LocationListener[] { new LocationListener(LocationManager.GPS_PROVIDER), new LocationListener(LocationManager.NETWORK_PROVIDER) }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { // SD card available updateStorageHint(calculatePicturesRemaining()); } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED) || action.equals(Intent.ACTION_MEDIA_CHECKING)) { // SD card unavailable mPicturesRemaining = MenuHelper.NO_STORAGE_ERROR; updateStorageHint(mPicturesRemaining); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { Toast.makeText(Camera.this, getResources().getString(R.string.wait), 5000); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { updateStorageHint(); } } }; private class LocationListener implements android.location.LocationListener { Location mLastLocation; boolean mValid = false; String mProvider; public LocationListener(String provider) { mProvider = provider; mLastLocation = new Location(mProvider); } public void onLocationChanged(Location newLocation) { if (newLocation.getLatitude() == 0.0 && newLocation.getLongitude() == 0.0) { // Hack to filter out 0.0,0.0 locations return; } mLastLocation.set(newLocation); mValid = true; } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { mValid = false; } public void onStatusChanged(String provider, int status, Bundle extras) { if (status == LocationProvider.OUT_OF_SERVICE) { mValid = false; } } public Location current() { return mValid ? mLastLocation : null; } }; private boolean mImageSavingItem = false; private final class ShutterCallback implements android.hardware.Camera.ShutterCallback { public void onShutter() { if (DEBUG_TIME_OPERATIONS) { mShutterCallbackTime = System.currentTimeMillis(); Log.v(TAG, "Shutter lag was " + (mShutterCallbackTime - mCaptureStartTime) + " ms."); } if (mClickSound != null) { mClickSound.start(); } mBlackout.setVisibility(View.VISIBLE); Size pictureSize = mParameters.getPictureSize(); // Resize the SurfaceView to the aspect-ratio of the still image // and so that we can see the full image that was taken. mSurfaceView.setAspectRatio(pictureSize.width, pictureSize.height); } }; private final class RawPictureCallback implements PictureCallback { public void onPictureTaken(byte [] rawData, android.hardware.Camera camera) { if (Config.LOGV) Log.v(TAG, "got RawPictureCallback..."); mRawPictureCallbackTime = System.currentTimeMillis(); if (DEBUG_TIME_OPERATIONS) { Log.v(TAG, (mRawPictureCallbackTime - mShutterCallbackTime) + "ms elapsed between" + " ShutterCallback and RawPictureCallback."); } mBlackout.setVisibility(View.GONE); } }; private final class JpegPictureCallback implements PictureCallback { Location mLocation; public JpegPictureCallback(Location loc) { mLocation = loc; } public void onPictureTaken(byte [] jpegData, android.hardware.Camera camera) { if (Config.LOGV) Log.v(TAG, "got JpegPictureCallback..."); if (DEBUG_TIME_OPERATIONS) { long mJpegPictureCallback = System.currentTimeMillis(); Log.v(TAG, (mJpegPictureCallback - mRawPictureCallbackTime) + "ms elapsed between" + " RawPictureCallback and JpegPictureCallback."); } mImageCapture.storeImage(jpegData, camera, mLocation); mStatus = SNAPSHOT_COMPLETED; if (mKeepAndRestartPreview) { long delay = 1500 - (System.currentTimeMillis() - mRawPictureCallbackTime); mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, Math.max(delay, 0)); } } }; private final class AutoFocusCallback implements android.hardware.Camera.AutoFocusCallback { public void onAutoFocus(boolean focused, android.hardware.Camera camera) { if (DEBUG_TIME_OPERATIONS) { mFocusCallbackTime = System.currentTimeMillis(); Log.v(TAG, "Auto focus took " + (mFocusCallbackTime - mFocusStartTime) + " ms."); } if (mFocusState == FOCUSING_SNAP_ON_FINISH && mCaptureObject != null) { // Take the picture no matter focus succeeds or fails. // No need to play the AF sound if we're about to play the shutter sound. mCaptureObject.onSnap(); clearFocusState(); } else if (mFocusState == FOCUSING) { // User is half-pressing the focus key. Play the focus tone. // Do not take the picture now. ToneGenerator tg = mFocusToneGenerator; if (tg != null) tg.startTone(ToneGenerator.TONE_PROP_BEEP2); if (focused) { mFocusState = FOCUS_SUCCESS; } else { mFocusState = FOCUS_FAIL; } } else if (mFocusState == FOCUS_NOT_STARTED) { // User has released the focus key before focus completes. // Do nothing. } updateFocusIndicator(); } }; private class ImageCapture implements Capturer { private boolean mCancel = false; private boolean mCapturing = false; private Uri mLastContentUri; private ImageManager.IAddImage_cancelable mAddImageCancelable; Bitmap mCaptureOnlyBitmap; /** These member variables are used for various debug timings */ private long mThreadTimeStart; private long mThreadTimeEnd; private long mWallTimeStart; private long mWallTimeEnd; public ImageCapture() { } /** * This method sets whether or not we are capturing a picture. This method must be called * with the ImageCapture.this lock held. */ public void setCapturingLocked(boolean capturing) { mCapturing = capturing; } /* * Tell the ImageCapture thread to exit when possible. */ public void setDone(boolean wait) { } /* * Tell the image capture thread to not "dismiss" the current * capture when the current image is stored, etc. */ public void cancelAutoDismiss() { } public void dismissFreezeFrame(boolean keep) { if (keep) { cancelSavingNotification(); } else { Toast.makeText(Camera.this, R.string.camera_tossing, Toast.LENGTH_SHORT).show(); } if (mStatus == SNAPSHOT_IN_PROGRESS) { // If we are still in the process of taking a picture, then just post a message. mHandler.sendEmptyMessage(RESTART_PREVIEW); } else { restartPreview(); } } private void startTiming() { mWallTimeStart = SystemClock.elapsedRealtime(); mThreadTimeStart = Debug.threadCpuTimeNanos(); } private void stopTiming() { mThreadTimeEnd = Debug.threadCpuTimeNanos(); mWallTimeEnd = SystemClock.elapsedRealtime(); } private void storeImage(byte[] data, Location loc) { try { if (DEBUG_TIME_OPERATIONS) { startTiming(); } long dateTaken = System.currentTimeMillis(); String name = createName(dateTaken) + ".jpg"; mLastContentUri = ImageManager.instance().addImage( Camera.this, mContentResolver, name, "", dateTaken, // location for the database goes here loc, 0, // the dsp will use the right orientation so don't "double set it" ImageManager.CAMERA_IMAGE_BUCKET_NAME, name); if (mLastContentUri == null) { // this means we got an error mCancel = true; } if (!mCancel) { mAddImageCancelable = ImageManager.instance().storeImage(mLastContentUri, Camera.this, mContentResolver, 0, null, data); mAddImageCancelable.get(); mAddImageCancelable = null; } if (DEBUG_TIME_OPERATIONS) { stopTiming(); Log.d(TAG, "Storing image took " + (mWallTimeEnd - mWallTimeStart) + " ms. " + "Thread time was " + ((mThreadTimeEnd - mThreadTimeStart) / 1000000) + " ms."); } } catch (Exception ex) { Log.e(TAG, "Exception while compressing image.", ex); } } public void storeImage(byte[] data, android.hardware.Camera camera, Location loc) { boolean captureOnly = isImageCaptureIntent(); if (!captureOnly) { storeImage(data, loc); sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", mLastContentUri)); setLastPictureThumb(data, mCaptureObject.getLastCaptureUri()); dismissFreezeFrame(true); } else { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; if (DEBUG_TIME_OPERATIONS) { startTiming(); } mCaptureOnlyBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options); if (DEBUG_TIME_OPERATIONS) { stopTiming(); Log.d(TAG, "Decoded mCaptureOnly bitmap (" + mCaptureOnlyBitmap.getWidth() + "x" + mCaptureOnlyBitmap.getHeight() + " ) in " + (mWallTimeEnd - mWallTimeStart) + " ms. Thread time was " + ((mThreadTimeEnd - mThreadTimeStart) / 1000000) + " ms."); } showPostCaptureAlert(); cancelAutomaticPreviewRestart(); } mCapturing = false; if (mPausing) { closeCamera(); } } /* * Tells the image capture thread to abort the capture of the * current image. */ public void cancelSave() { if (!mCapturing) { return; } mCancel = true; if (mAddImageCancelable != null) { mAddImageCancelable.cancel(); } dismissFreezeFrame(false); } /* * Initiate the capture of an image. */ public void initiate(boolean captureOnly) { if (mCameraDevice == null) { return; } mCancel = false; mCapturing = true; capture(captureOnly); } public Uri getLastCaptureUri() { return mLastContentUri; } public Bitmap getLastBitmap() { return mCaptureOnlyBitmap; } private void capture(boolean captureOnly) { mPreviewing = false; mCaptureOnlyBitmap = null; final int latchedOrientation = ImageManager.roundOrientation(mLastOrientation + 90); Boolean recordLocation = mPreferences.getBoolean("pref_camera_recordlocation_key", false); Location loc = recordLocation ? getCurrentLocation() : null; // Quality 75 has visible artifacts, and quality 90 looks great but the files begin to // get large. 85 is a good compromise between the two. mParameters.set("jpeg-quality", 85); mParameters.set("rotation", latchedOrientation); mParameters.remove("gps-latitude"); mParameters.remove("gps-longitude"); mParameters.remove("gps-altitude"); mParameters.remove("gps-timestamp"); if (loc != null) { double lat = loc.getLatitude(); double lon = loc.getLongitude(); boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d); if (hasLatLon) { String latString = String.valueOf(lat); String lonString = String.valueOf(lon); mParameters.set("gps-latitude", latString); mParameters.set("gps-longitude", lonString); - if (loc.hasAltitude()) + if (loc.hasAltitude()) { mParameters.set("gps-altitude", String.valueOf(loc.getAltitude())); + } else { + // for NETWORK_PROVIDER location provider, we may have + // no altitude information, but the driver needs it, so + // we fake one. + mParameters.set("gps-altitude", "0"); + } if (loc.getTime() != 0) { // Location.getTime() is UTC in milliseconds. // gps-timestamp is UTC in seconds. long utcTimeSeconds = loc.getTime() / 1000; mParameters.set("gps-timestamp", String.valueOf(utcTimeSeconds)); } } else { loc = null; } } mCameraDevice.setParameters(mParameters); mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback, new JpegPictureCallback(loc)); // Prepare the sound to play in shutter callback. if (mClickSound != null) { mClickSound.seekTo(0); } } public void onSnap() { if (DEBUG_TIME_OPERATIONS) mCaptureStartTime = System.currentTimeMillis(); // If we are already in the middle of taking a snapshot then we should just save // the image after we have returned from the camera service. if (mStatus == SNAPSHOT_IN_PROGRESS || mStatus == SNAPSHOT_COMPLETED) { mKeepAndRestartPreview = true; mHandler.sendEmptyMessage(RESTART_PREVIEW); return; } // Don't check the filesystem here, we can't afford the latency. Instead, check the // cached value which was calculated when the preview was restarted. if (mPicturesRemaining < 1) { updateStorageHint(mPicturesRemaining); return; } mStatus = SNAPSHOT_IN_PROGRESS; mKeepAndRestartPreview = true; boolean getContentAction = isImageCaptureIntent(); if (getContentAction) { mImageCapture.initiate(true); } else { mImageCapture.initiate(false); } } } private void setLastPictureThumb(byte[] data, Uri uri) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 16; Bitmap lastPictureThumb = BitmapFactory.decodeByteArray(data, 0, data.length, options); setLastPictureThumb(lastPictureThumb, uri); } private void setLastPictureThumb(Bitmap lastPictureThumb, Uri uri) { final int PADDING_WIDTH = 2; final int PADDING_HEIGHT = 2; LayoutParams layoutParams = mLastPictureButton.getLayoutParams(); // Make the mini-thumbnail size smaller than the button size so that the image corners // don't peek out from the rounded corners of the frame_thumbnail graphic: final int miniThumbWidth = layoutParams.width - 2 * PADDING_WIDTH; final int miniThumbHeight = layoutParams.height - 2 * PADDING_HEIGHT; lastPictureThumb = ImageManager.extractMiniThumb(lastPictureThumb, miniThumbWidth, miniThumbHeight); Drawable[] vignetteLayers = new Drawable[2]; vignetteLayers[1] = getResources().getDrawable(R.drawable.frame_thumbnail); if (mThumbnails == null) { mThumbnails = new Drawable[2]; mThumbnails[1] = new BitmapDrawable(lastPictureThumb); vignetteLayers[0] = mThumbnails[1]; } else { mThumbnails[0] = mThumbnails[1]; mThumbnails[1] = new BitmapDrawable(lastPictureThumb); mThumbnailTransition = new TransitionDrawable(mThumbnails); mShouldTransitionThumbnails = true; vignetteLayers[0] = mThumbnailTransition; } mVignette = new LayerDrawable(vignetteLayers); mVignette.setLayerInset(0, PADDING_WIDTH, PADDING_HEIGHT, PADDING_WIDTH, PADDING_HEIGHT); mLastPictureButton.setImageDrawable(mVignette); if (mLastPictureButton.getVisibility() != View.VISIBLE) { mShouldShowLastPictureButton = true; } mLastPictureThumb = lastPictureThumb; mLastPictureUri = uri; } static private String createName(long dateTaken) { return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString(); } static public Matrix GetDisplayMatrix(Bitmap b, ImageView v) { Matrix m = new Matrix(); float bw = (float)b.getWidth(); float bh = (float)b.getHeight(); float vw = (float)v.getWidth(); float vh = (float)v.getHeight(); float scale, x, y; if (bw*vh > vw*bh) { scale = vh / bh; x = (vw - scale*bw)*0.5F; y = 0; } else { scale = vw / bw; x = 0; y = (vh - scale*bh)*0.5F; } m.setScale(scale, scale, 0.5F, 0.5F); m.postTranslate(x, y); return m; } private void postAfterKeep(final Runnable r) { Resources res = getResources(); if (mSavingProgress != null) { mSavingProgress = ProgressDialog.show(this, res.getString(R.string.savingImage), res.getString(R.string.wait)); } Message msg = mHandler.obtainMessage(KEEP); msg.obj = r; msg.sendToTarget(); } /** Called with the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); // To reduce startup time, we open camera device in another thread. // We make sure the camera is opened at the end of onCreate. Thread openCameraThread = new Thread(new Runnable() { public void run() { mCameraDevice = android.hardware.Camera.open(); } }); openCameraThread.start(); // To reduce startup time, we run some service creation code in another thread. // We make sure the services are loaded at the end of onCreate(). Thread loadServiceThread = new Thread(new Runnable() { public void run() { mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mOrientationListener = new OrientationEventListener(Camera.this) { public void onOrientationChanged(int orientation) { // We keep the last known orientation. So if the user // first orient the camera then point the camera to // floor/sky, we still have the correct orientation. if (orientation != ORIENTATION_UNKNOWN) mLastOrientation = orientation; } }; } }); loadServiceThread.start(); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mContentResolver = getContentResolver(); Window win = getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.camera); mSurfaceView = (VideoPreview) findViewById(R.id.camera_preview); // don't set mSurfaceHolder here. We have it set ONLY within // surfaceCreated / surfaceDestroyed, other parts of the code // assume that when it is set, the surface is also set. SurfaceHolder holder = mSurfaceView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mBlackout = findViewById(R.id.blackout); if (!isImageCaptureIntent()) { mLastPictureButton = (ImageView) findViewById(R.id.last_picture_button); mLastPictureButton.setOnClickListener(this); loadLastThumb(); } mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); try { mClickSound = new MediaPlayer(); AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.camera_click); mClickSound.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); if (mClickSound != null) { mClickSound.setAudioStreamType(AudioManager.STREAM_ALARM); mClickSound.prepare(); } } catch (Exception ex) { Log.w(TAG, "Couldn't create click sound", ex); } mFocusIndicator = findViewById(R.id.focus_indicator); mFocusBlinkAnimation = AnimationUtils.loadAnimation(this, R.anim.auto_focus_blink); mFocusBlinkAnimation.setRepeatCount(Animation.INFINITE); mFocusBlinkAnimation.setRepeatMode(Animation.REVERSE); // We load the post_picture_panel layout only if it is needed. if (isImageCaptureIntent()) { ViewGroup cameraView = (ViewGroup)findViewById(R.id.camera); getLayoutInflater().inflate(R.layout.post_picture_panel, cameraView); mPostCaptureAlert = findViewById(R.id.post_picture_panel); } // Make sure the services are loaded. try { openCameraThread.join(); loadServiceThread.join(); } catch (InterruptedException ex) { } ImageManager.ensureOSXCompatibleFolder(); } @Override public void onStart() { super.onStart(); Thread t = new Thread(new Runnable() { public void run() { final boolean storageOK = calculatePicturesRemaining() > 0; if (!storageOK) { mHandler.post(new Runnable() { public void run() { updateStorageHint(mPicturesRemaining); } }); } } }); t.start(); } public void onClick(View v) { switch (v.getId()) { case R.id.last_picture_button: viewLastImage(); break; case R.id.attach: doAttach(); break; case R.id.cancel: doCancel(); } } private void doAttach() { Bitmap bitmap = mImageCapture.getLastBitmap(); mCaptureObject.setDone(true); String cropValue = null; Uri saveUri = null; Bundle myExtras = getIntent().getExtras(); if (myExtras != null) { saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); cropValue = myExtras.getString("crop"); } if (cropValue == null) { /* * First handle the no crop case -- just return the value. If the caller * specifies a "save uri" then write the data to it's stream. Otherwise, * pass back a scaled down version of the bitmap directly in the extras. */ if (saveUri != null) { OutputStream outputStream = null; try { outputStream = mContentResolver.openOutputStream(saveUri); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, outputStream); outputStream.close(); setResult(RESULT_OK); finish(); } catch (IOException ex) { // } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { } } } } else { float scale = .5F; Matrix m = new Matrix(); m.setScale(scale, scale); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true); setResult(RESULT_OK, new Intent("inline-data").putExtra("data", bitmap)); finish(); } } else { /* * Save the image to a temp file and invoke the cropper */ Uri tempUri = null; FileOutputStream tempStream = null; try { File path = getFileStreamPath(sTempCropFilename); path.delete(); tempStream = openFileOutput(sTempCropFilename, 0); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, tempStream); tempStream.close(); tempUri = Uri.fromFile(path); } catch (FileNotFoundException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } catch (IOException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } finally { if (tempStream != null) { try { tempStream.close(); } catch (IOException ex) { } } } Bundle newExtras = new Bundle(); if (cropValue.equals("circle")) newExtras.putString("circleCrop", "true"); if (saveUri != null) newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, saveUri); else newExtras.putBoolean("return-data", true); Intent cropIntent = new Intent(); cropIntent.setClass(Camera.this, CropImage.class); cropIntent.setData(tempUri); cropIntent.putExtras(newExtras); startActivityForResult(cropIntent, CROP_MSG); } } private void doCancel() { setResult(RESULT_CANCELED, new Intent()); finish(); } public void onShutterButtonFocus(ShutterButton button, boolean pressed) { switch (button.getId()) { case R.id.shutter_button: doFocus(pressed); break; } } public void onShutterButtonClick(ShutterButton button) { switch (button.getId()) { case R.id.shutter_button: doSnap(); break; } } private void updateStorageHint() { updateStorageHint(MenuHelper.calculatePicturesRemaining()); } private OnScreenHint mStorageHint; private void updateStorageHint(int remaining) { String noStorageText = null; if (remaining == MenuHelper.NO_STORAGE_ERROR) { String state = Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING) { noStorageText = getString(R.string.preparing_sd); } else { noStorageText = getString(R.string.no_storage); } } else if (remaining < 1) { noStorageText = getString(R.string.not_enough_space); } if (noStorageText != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, noStorageText); } else { mStorageHint.setText(noStorageText); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } @Override public void onResume() { super.onResume(); mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); mPausing = false; mOrientationListener.enable(); // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); mDidRegister = true; mImageCapture = new ImageCapture(); restartPreview(); if (mPreferences.getBoolean("pref_camera_recordlocation_key", false)) startReceivingLocationUpdates(); updateFocusIndicator(); try { mFocusToneGenerator = new ToneGenerator(AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME); } catch (RuntimeException e) { Log.w(TAG, "Exception caught while creating local tone generator: " + e); mFocusToneGenerator = null; } mBlackout.setVisibility(View.GONE); } private ImageManager.DataLocation dataLocation() { return ImageManager.DataLocation.EXTERNAL; } private static final int BUFSIZE = 4096; // Stores the thumbnail and URI of last-picture-taken to SD card, so we can // load it the next time the Camera app starts. private void storeLastThumb() { if (mLastPictureUri != null && mLastPictureThumb != null) { try { FileOutputStream f = new FileOutputStream(ImageManager.getLastThumbPath()); try { BufferedOutputStream b = new BufferedOutputStream(f, BUFSIZE); try { DataOutputStream d = new DataOutputStream(b); try { d.writeUTF(mLastPictureUri.toString()); mLastPictureThumb.compress(Bitmap.CompressFormat.PNG, 100, d); } finally { d.close(); b = null; f = null; } } finally { if (b != null) { b.close(); f = null; } } } finally { if (f != null) { f.close(); } } } catch (IOException e) { } } } // Loads the thumbnail and URI of last-picture-taken from SD card. private void loadLastThumb() { try { FileInputStream f = new FileInputStream(ImageManager.getLastThumbPath()); try { BufferedInputStream b = new BufferedInputStream(f, BUFSIZE); try { DataInputStream d = new DataInputStream(b); try { Uri lastUri = Uri.parse(d.readUTF()); Bitmap lastThumb = BitmapFactory.decodeStream(d); diff --git a/src/com/android/camera/ViewImage.java b/src/com/android/camera/ViewImage.java index f6d0744..254cd60 100644 --- a/src/com/android/camera/ViewImage.java +++ b/src/com/android/camera/ViewImage.java @@ -423,1264 +423,1258 @@ public class ViewImage extends Activity implements View.OnClickListener float distanceX, float distanceY) { if (getScale() > 1F) { postTranslate(-distanceX, -distanceY, sUseBounce); ImageViewTouch.this.center(true, true, false); } return true; } } private class MyDoubleTapListener implements GestureDetector.OnDoubleTapListener { // On single tap, we show the arrows. We also change to the // prev/next image if the user taps on the left/right region. public boolean onSingleTapConfirmed(MotionEvent e) { ViewImage viewImage = mViewImage; int viewWidth = getWidth(); int x = (int) e.getX(); int y = (int) e.getY(); if (x < TOUCH_AREA_WIDTH) { viewImage.moveNextOrPrevious(-1); } else if (x > viewWidth - TOUCH_AREA_WIDTH) { viewImage.moveNextOrPrevious(1); } viewImage.setMode(MODE_NORMAL); viewImage.showOnScreenControls(); return true; } // On double tap, we show the zoom ring control. public boolean onDoubleTapEvent(MotionEvent e) { mViewImage.setMode(MODE_NORMAL); mZoomRingController.handleDoubleTapEvent(e); mZoomButtonsController.handleDoubleTapEvent(e); return true; } public boolean onDoubleTap(MotionEvent e) { return false; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Don't respond to arrow keys if trackball scrolling is not enabled if (!mEnableTrackballScroll) { if ((keyCode >= KeyEvent.KEYCODE_DPAD_UP) && (keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT)) { return super.onKeyDown(keyCode, event); } } int current = mViewImage.mCurrentPosition; int nextImagePos = -2; // default no next image try { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: { if (mViewImage.isPickIntent()) { ImageManager.IImage img = mViewImage.mAllImages.getImageAt(mViewImage.mCurrentPosition); mViewImage.setResult(RESULT_OK, new Intent().setData(img.fullSizeImageUri())); mViewImage.finish(); } break; } case KeyEvent.KEYCODE_DPAD_LEFT: { panBy(sPanRate, 0); int maxOffset = (current == 0) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(true, maxOffset)) { nextImagePos = current - 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_RIGHT: { panBy(-sPanRate, 0); int maxOffset = (current == mViewImage.mAllImages.getCount()-1) ? 0 : sHysteresis; if (getScale() <= 1F || isShiftedToNextImage(false, maxOffset)) { nextImagePos = current + 1; } else { center(true, false, true); } return true; } case KeyEvent.KEYCODE_DPAD_UP: { panBy(0, sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DPAD_DOWN: { panBy(0, -sPanRate); center(true, false, false); return true; } case KeyEvent.KEYCODE_DEL: MenuHelper.deletePhoto(mViewImage, mViewImage.mDeletePhotoRunnable); break; } } finally { if (nextImagePos >= 0 && nextImagePos < mViewImage.mAllImages.getCount()) { synchronized (mViewImage) { mViewImage.setMode(MODE_NORMAL); mViewImage.setImage(nextImagePos); } } else if (nextImagePos != -2) { center(true, true, false); } } return super.onKeyDown(keyCode, event); } protected boolean isShiftedToNextImage(boolean left, int maxOffset) { boolean retval; Bitmap bitmap = mBitmapDisplayed; Matrix m = getImageViewMatrix(); if (left) { float [] t1 = new float[] { 0, 0 }; m.mapPoints(t1); retval = t1[0] > maxOffset; } else { int width = bitmap != null ? bitmap.getWidth() : getWidth(); float [] t1 = new float[] { width, 0 }; m.mapPoints(t1); retval = t1[0] + maxOffset < getWidth(); } return retval; } protected void scrollX(int deltaX) { scrollHandler().scrollBy(deltaX, 0); } protected int getScrollOffset() { return scrollHandler().getScrollX(); } @Override protected void onDetachedFromWindow() { mZoomRingController.setVisible(false); mZoomButtonsController.setVisible(false); } } static class ScrollHandler extends LinearLayout { private Runnable mFirstLayoutCompletedCallback = null; private Scroller mScrollerHelper; private int mWidth = -1; public ScrollHandler(Context context) { super(context); mScrollerHelper = new Scroller(context); } public ScrollHandler(Context context, AttributeSet attrs) { super(context, attrs); mScrollerHelper = new Scroller(context); } public void setLayoutCompletedCallback(Runnable r) { mFirstLayoutCompletedCallback = r; } public void startScrollTo(int newX, int newY) { int oldX = getScrollX(); int oldY = getScrollY(); int deltaX = newX - oldX; int deltaY = newY - oldY; if (mWidth == -1) { mWidth = findViewById(R.id.image2).getWidth(); } int viewWidth = mWidth; int duration = viewWidth > 0 ? sBaseScrollDuration * Math.abs(deltaX) / viewWidth : 0; mScrollerHelper.startScroll(oldX, oldY, deltaX, deltaY, duration); invalidate(); } @Override public void computeScroll() { if (mScrollerHelper.computeScrollOffset()) { scrollTo(mScrollerHelper.getCurrX(), mScrollerHelper.getCurrY()); postInvalidate(); // So we draw again } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int width = right - left; int x = 0; for (View v : new View[] { findViewById(R.id.image1), findViewById(R.id.image2), findViewById(R.id.image3) }) { v.layout(x, 0, x + width, bottom); x += (width + sPadding); } findViewById(R.id.padding1).layout(width, 0, width + sPadding, bottom); findViewById(R.id.padding2).layout(width+sPadding+width, 0, width+sPadding+width+sPadding, bottom); if (changed) { if (mFirstLayoutCompletedCallback != null) { mFirstLayoutCompletedCallback.run(); } } } } private void animateScrollTo(int xNew, int yNew) { mScroller.startScrollTo(xNew, yNew); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (! mCameraReviewMode) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.slide_show); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { setMode(MODE_SLIDESHOW); mLastSlideShowImage = mCurrentPosition; loadNextImage(mCurrentPosition, 0, true); return true; } }); item.setIcon(android.R.drawable.ic_menu_slideshow); } final SelectedImageGetter selectedImageGetter = new SelectedImageGetter() { public ImageManager.IImage getCurrentImage() { return mAllImages.getImageAt(mCurrentPosition); } public Uri getCurrentImageUri() { return mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); } }; mImageMenuRunnable = MenuHelper.addImageMenuItems( menu, MenuHelper.INCLUDE_ALL, true, ViewImage.this, mHandler, mDeletePhotoRunnable, new MenuHelper.MenuInvoker() { public void run(MenuHelper.MenuCallback cb) { setMode(MODE_NORMAL); cb.run(selectedImageGetter.getCurrentImageUri(), selectedImageGetter.getCurrentImage()); for (ImageViewTouchBase iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } setImage(mCurrentPosition); } }); if (true) { MenuItem item = menu.add(Menu.CATEGORY_SECONDARY, 203, 1000, R.string.camerasettings); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent preferences = new Intent(); preferences.setClass(ViewImage.this, GallerySettings.class); startActivity(preferences); return true; } }); item.setAlphabeticShortcut('p'); item.setIcon(android.R.drawable.ic_menu_preferences); } // Hidden menu just so the shortcut will bring up the zoom controls menu.add(Menu.CATEGORY_SECONDARY, 203, 0, R.string.camerasettings) // the string resource is a placeholder .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { showOnScreenControls(); return true; } }) .setAlphabeticShortcut('z') .setVisible(false); return true; } protected Runnable mDeletePhotoRunnable = new Runnable() { public void run() { mAllImages.removeImageAt(mCurrentPosition); if (mAllImages.getCount() == 0) { finish(); } else { if (mCurrentPosition == mAllImages.getCount()) { mCurrentPosition -= 1; } } for (ImageViewTouchBase iv: mImageViews) { iv.setImageBitmapResetBase(null, true, true); } setImage(mCurrentPosition); } }; @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); setMode(MODE_NORMAL); if (mImageMenuRunnable != null) { mImageMenuRunnable.gettingReadyToOpen(menu, mAllImages.getImageAt(mCurrentPosition)); } return true; } @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean changed = mCurrentOrientation != newConfig.orientation; mCurrentOrientation = newConfig.orientation; if (changed) { if (mGetter != null) { // kill off any background image fetching mGetter.cancelCurrent(); mGetter.stop(); } makeGetter(); mFirst = true; // clear off the current set of images since we need to reload // them at the right size for (ImageViewTouchBase iv: mImageViews) { iv.clear(); } MenuHelper.requestOrientation(this, mPrefs); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { boolean b = super.onMenuItemSelected(featureId, item); if (mImageMenuRunnable != null) mImageMenuRunnable.aboutToCall(item, mAllImages.getImageAt(mCurrentPosition)); return b; } /* * Here's the loading strategy. For any given image, load the thumbnail * into memory and post a callback to display the resulting bitmap. * * Then proceed to load the full image bitmap. Three things can * happen at this point: * * 1. the image fails to load because the UI thread decided * to move on to a different image. This "cancellation" happens * by virtue of the UI thread closing the stream containing the * image being decoded. BitmapFactory.decodeStream returns null * in this case. * * 2. the image loaded successfully. At that point we post * a callback to the UI thread to actually show the bitmap. * * 3. when the post runs it checks to see if the image that was * loaded is still the one we want. The UI may have moved on * to some other image and if so we just drop the newly loaded * bitmap on the floor. */ interface ImageGetterCallback { public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb); public boolean wantsThumbnail(int pos, int offset); public boolean wantsFullImage(int pos, int offset); public int fullImageSizeToUse(int pos, int offset); public void completed(boolean wasCanceled); public int [] loadOrder(); } class ImageGetter { // The thread which does the work. private Thread mGetterThread; // The base position that's being retrieved. The actual images retrieved // are this base plus each of the offets. private int mCurrentPosition = -1; // The callback to invoke for each image. private ImageGetterCallback mCB; // This is the loader cancelable that gets set while we're loading an image. // If we change position we can cancel the current load using this. private ImageManager.IGetBitmap_cancelable mLoad; // True if we're canceling the current load. private boolean mCancelCurrent = false; // True when the therad should exit. private boolean mDone = false; // True when the loader thread is waiting for work. private boolean mReady = false; private void cancelCurrent() { synchronized (this) { if (!mReady) { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { if (Config.LOGV) Log.v(TAG, "canceling load object"); load.cancel(); } mCancelCurrent = false; } } } public ImageGetter() { mGetterThread = new Thread(new Runnable() { private Runnable callback(final int position, final int offset, final boolean isThumb, final Bitmap bitmap) { return new Runnable() { public void run() { // check for inflight callbacks that aren't applicable any longer // before delivering them if (!isCanceled() && position == mCurrentPosition) { mCB.imageLoaded(position, offset, bitmap, isThumb); } else { if (bitmap != null) bitmap.recycle(); } } }; } private Runnable completedCallback(final boolean wasCanceled) { return new Runnable() { public void run() { mCB.completed(wasCanceled); } }; } public void run() { int lastPosition = -1; while (!mDone) { synchronized (ImageGetter.this) { mReady = true; ImageGetter.this.notify(); if (mCurrentPosition == -1 || lastPosition == mCurrentPosition) { try { ImageGetter.this.wait(); } catch (InterruptedException ex) { continue; } } lastPosition = mCurrentPosition; mReady = false; } if (lastPosition != -1) { int imageCount = mAllImages.getCount(); int [] order = mCB.loadOrder(); for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (image == null || isCanceled()) { break; } if (mCB.wantsThumbnail(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting THUMBNAIL load at offset " + offset); Bitmap b = image.thumbBitmap(); mHandler.post(callback(lastPosition, offset, true, b)); } } } for (int i = 0; i < order.length; i++) { int offset = order[i]; int imageNumber = lastPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { ImageManager.IImage image = mAllImages.getImageAt(lastPosition + offset); if (mCB.wantsFullImage(lastPosition, offset)) { if (Config.LOGV) Log.v(TAG, "starting FULL IMAGE load at offset " + offset); int sizeToUse = mCB.fullImageSizeToUse(lastPosition, offset); if (image != null && !isCanceled()) { mLoad = image.fullSizeBitmap_cancelable(sizeToUse); } if (mLoad != null) { long t1; if (Config.LOGV) t1 = System.currentTimeMillis(); - Bitmap b = null; - try { - b = mLoad.get(); - } catch (OutOfMemoryError e) { - Log.e(TAG, "couldn't load full size bitmap for " + ""); - } + // The return value could be null if the + // bitmap is too big, or we cancelled it. + Bitmap b = mLoad.get(); + if (Config.LOGV && b != null) { long t2 = System.currentTimeMillis(); Log.v(TAG, "loading full image for " + image.fullSizeImageUri() + " with requested size " + sizeToUse + " took " + (t2-t1) + " and returned a bitmap with size " + b.getWidth() + " / " + b.getHeight()); } mLoad = null; if (b != null) { if (isCanceled()) { b.recycle(); } else { mHandler.post(callback(lastPosition, offset, false, b)); } } } } } } mHandler.post(completedCallback(isCanceled())); } } } }); mGetterThread.setName("ImageGettter"); mGetterThread.start(); } private boolean isCanceled() { synchronized (this) { return mCancelCurrent; } } public void setPosition(int position, ImageGetterCallback cb) { synchronized (this) { if (!mReady) { try { mCancelCurrent = true; ImageManager.IGetBitmap_cancelable load = mLoad; if (load != null) { load.cancel(); } // if the thread is waiting before loading the full size // image then this will free it up ImageGetter.this.notify(); ImageGetter.this.wait(); mCancelCurrent = false; } catch (InterruptedException ex) { // not sure what to do here } } } mCurrentPosition = position; mCB = cb; synchronized (this) { ImageGetter.this.notify(); } } public void stop() { synchronized (this) { mDone = true; ImageGetter.this.notify(); } try { mGetterThread.join(); } catch (InterruptedException ex) { } } } private void setImage(int pos) { if (!mLayoutComplete) { return; } final boolean left = mCurrentPosition > pos; mCurrentPosition = pos; ImageViewTouchBase current = mImageViews[1]; current.mSuppMatrix.reset(); current.setImageMatrix(current.getImageViewMatrix()); if (false) { Log.v(TAG, "before..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } if (!mFirst) { if (left) { mImageViews[2].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[0]); } else { mImageViews[0].copyFrom(mImageViews[1]); mImageViews[1].copyFrom(mImageViews[2]); } } if (false) { Log.v(TAG, "after copy..."); for (ImageViewTouchBase ivtb : mImageViews) ivtb.dump(); } for (ImageViewTouchBase ivt: mImageViews) { ivt.mIsZooming = false; } int width = mImageViews[1].getWidth(); int from; int to = width + sPadding; if (mFirst) { from = to; mFirst = false; } else { from = left ? (width + sPadding) + mScroller.getScrollX() : mScroller.getScrollX() - (width + sPadding); } if (sAnimateTransitions) { mScroller.scrollTo(from, 0); animateScrollTo(to, 0); } else { mScroller.scrollTo(to, 0); } ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { if (!mShowActionIcons) { mImageViews[1].setFocusableInTouchMode(true); mImageViews[1].requestFocus(); } } public boolean wantsThumbnail(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; return ivt.mThumbBitmap == null; } public boolean wantsFullImage(int pos, int offset) { ImageViewTouchBase ivt = mImageViews[1 + offset]; if (ivt.mBitmapDisplayed != null && !ivt.mBitmapIsThumbnail) { return false; } if (offset != 0) { return false; } return true; } public int fullImageSizeToUse(int pos, int offset) { // TODO // this number should be bigger so that we can zoom. we may need to // get fancier and read in the fuller size image as the user starts // to zoom. use -1 to get the full full size image. // for now use 480 so we don't run out of memory final int imageViewSize = 480; return imageViewSize; } public int [] loadOrder() { return sOrder_adjacents; } public void imageLoaded(int pos, int offset, Bitmap bitmap, boolean isThumb) { ImageViewTouchBase ivt = mImageViews[1 + offset]; ivt.setImageBitmapResetBase(bitmap, isThumb, isThumb); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { mGetter.setPosition(pos, cb); } showOnScreenControls(); } @Override public void onCreate(Bundle instanceState) { super.onCreate(instanceState); Intent intent = getIntent(); mCameraReviewMode = intent.getBooleanExtra("com.android.camera.ReviewMode", false); mFullScreenInNormalMode = intent.getBooleanExtra(MediaStore.EXTRA_FULL_SCREEN, true); mShowActionIcons = intent.getBooleanExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, false); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mCurrentOrientation = getResources().getConfiguration().orientation; setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.viewimage); mImageViews[0] = (ImageViewTouch) findViewById(R.id.image1); mImageViews[1] = (ImageViewTouch) findViewById(R.id.image2); mImageViews[2] = (ImageViewTouch) findViewById(R.id.image3); for(ImageViewTouch v : mImageViews) { v.setEnableTrackballScroll(!mShowActionIcons); } mScroller = (ScrollHandler)findViewById(R.id.scroller); makeGetter(); mAnimationIndex = -1; mSlideShowInAnimation = new Animation[] { makeInAnimation(R.anim.transition_in), makeInAnimation(R.anim.slide_in), makeInAnimation(R.anim.slide_in_vertical), }; mSlideShowOutAnimation = new Animation[] { makeOutAnimation(R.anim.transition_out), makeOutAnimation(R.anim.slide_out), makeOutAnimation(R.anim.slide_out_vertical), }; mSlideShowImageViews[0] = (ImageViewTouch) findViewById(R.id.image1_slideShow); mSlideShowImageViews[1] = (ImageViewTouch) findViewById(R.id.image2_slideShow); for (ImageViewTouch v : mSlideShowImageViews) { v.setImageBitmapResetBase(null, true, true); v.setVisibility(View.INVISIBLE); v.setEnableTrackballScroll(!mShowActionIcons); } mActionIconPanel = findViewById(R.id.action_icon_panel); { int[] pickIds = {R.id.attach, R.id.cancel}; int[] normalIds = {R.id.gallery, R.id.setas, R.id.share, R.id.discard}; int[] hideIds = pickIds; int[] connectIds = normalIds; if (isPickIntent()) { hideIds = normalIds; connectIds = pickIds; } for(int id : hideIds) { mActionIconPanel.findViewById(id).setVisibility(View.GONE); } for(int id : connectIds) { View view = mActionIconPanel.findViewById(id); view.setOnClickListener(this); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(500); view.setAnimation(animation); } } mShutterButton = findViewById(R.id.shutter_button); mShutterButton.setOnClickListener(this); Uri uri = getIntent().getData(); if (Config.LOGV) Log.v(TAG, "uri is " + uri); if (instanceState != null) { if (instanceState.containsKey("uri")) { uri = Uri.parse(instanceState.getString("uri")); } } if (uri == null) { finish(); return; } init(uri); Bundle b = getIntent().getExtras(); boolean slideShow = b != null ? b.getBoolean("slideshow", false) : false; if (slideShow) { setMode(MODE_SLIDESHOW); loadNextImage(mCurrentPosition, 0, true); } else { if (mFullScreenInNormalMode) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } } setupDismissOnScreenControlRunnable(); mNextImageView = findViewById(R.id.next_image); mPrevImageView = findViewById(R.id.prev_image); mNextImageView.setOnClickListener(this); mPrevImageView.setOnClickListener(this); if (mShowActionIcons) { mNextImageView.setFocusable(true); mPrevImageView.setFocusable(true); } setOrientation(); } private void setOrientation() { Intent intent = getIntent(); if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) { int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); if (orientation != getRequestedOrientation()) { setRequestedOrientation(orientation); } } else { MenuHelper.requestOrientation(this, mPrefs); } } private Animation makeInAnimation(int id) { Animation inAnimation = AnimationUtils.loadAnimation(this, id); return inAnimation; } private Animation makeOutAnimation(int id) { Animation outAnimation = AnimationUtils.loadAnimation(this, id); return outAnimation; } private void setMode(int mode) { if (mMode == mode) { return; } findViewById(R.id.slideShowContainer).setVisibility(mode == MODE_SLIDESHOW ? View.VISIBLE : View.GONE); findViewById(R.id.abs) .setVisibility(mode == MODE_NORMAL ? View.VISIBLE : View.GONE); Window win = getWindow(); mMode = mode; if (mode == MODE_SLIDESHOW) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (sSlideShowHidesStatusBar) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } for (ImageViewTouchBase ivt: mImageViews) { ivt.clear(); } mActionIconPanel.setVisibility(View.GONE); mShutterButton.setVisibility(View.GONE); if (false) { Log.v(TAG, "current is " + this.mSlideShowImageCurrent); this.mSlideShowImageViews[0].dump(); this.mSlideShowImageViews[0].dump(); } findViewById(R.id.slideShowContainer).getRootView().requestLayout(); mUseShuffleOrder = mPrefs.getBoolean("pref_gallery_slideshow_shuffle_key", false); mSlideShowLoop = mPrefs.getBoolean("pref_gallery_slideshow_repeat_key", false); try { mAnimationIndex = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_transition_key", "0")); } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mAnimationIndex = 0; } try { mSlideShowInterval = Integer.parseInt(mPrefs.getString("pref_gallery_slideshow_interval_key", "3")) * 1000; } catch (Exception ex) { Log.e(TAG, "couldn't parse preference: " + ex.toString()); mSlideShowInterval = 3000; } if (Config.LOGV) { Log.v(TAG, "read prefs... shuffle: " + mUseShuffleOrder); Log.v(TAG, "read prefs... loop: " + mSlideShowLoop); Log.v(TAG, "read prefs... animidx: " + mAnimationIndex); Log.v(TAG, "read prefs... interval: " + mSlideShowInterval); } if (mUseShuffleOrder) { generateShuffleOrder(); } } else { if (Config.LOGV) Log.v(TAG, "slide show mode off, mCurrentPosition == " + mCurrentPosition); win.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (mFullScreenInNormalMode) { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mGetter != null) mGetter.cancelCurrent(); if (sSlideShowHidesStatusBar) { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (mShowActionIcons) { mActionIconPanel.setVisibility(View.VISIBLE); mShutterButton.setVisibility(View.VISIBLE); } ImageViewTouchBase dst = mImageViews[1]; dst.mLastXTouchPos = -1; dst.mLastYTouchPos = -1; for (ImageViewTouchBase ivt: mSlideShowImageViews) { ivt.clear(); } mShuffleOrder = null; // mGetter null is a proxy for being paused if (mGetter != null) { mFirst = true; // don't animate setImage(mCurrentPosition); } } // this line shouldn't be necessary but the view hierarchy doesn't // seem to realize that the window layout changed mScroller.requestLayout(); } private void generateShuffleOrder() { if (mShuffleOrder == null || mShuffleOrder.length != mAllImages.getCount()) { mShuffleOrder = new int[mAllImages.getCount()]; } for (int i = 0; i < mShuffleOrder.length; i++) { mShuffleOrder[i] = i; } for (int i = mShuffleOrder.length - 1; i > 0; i--) { int r = mRandom.nextInt(i); int tmp = mShuffleOrder[r]; mShuffleOrder[r] = mShuffleOrder[i]; mShuffleOrder[i] = tmp; } } private void loadNextImage(final int requestedPos, final long delay, final boolean firstCall) { if (firstCall && mUseShuffleOrder) { generateShuffleOrder(); } final long targetDisplayTime = System.currentTimeMillis() + delay; ImageGetterCallback cb = new ImageGetterCallback() { public void completed(boolean wasCanceled) { } public boolean wantsThumbnail(int pos, int offset) { return true; } public boolean wantsFullImage(int pos, int offset) { return false; } public int [] loadOrder() { return sOrder_slideshow; } public int fullImageSizeToUse(int pos, int offset) { return 480; // TODO compute this } public void imageLoaded(final int pos, final int offset, final Bitmap bitmap, final boolean isThumb) { long timeRemaining = Math.max(0, targetDisplayTime - System.currentTimeMillis()); mHandler.postDelayed(new Runnable() { public void run() { if (mMode == MODE_NORMAL) { return; } ImageViewTouchBase oldView = mSlideShowImageViews[mSlideShowImageCurrent]; if (++mSlideShowImageCurrent == mSlideShowImageViews.length) { mSlideShowImageCurrent = 0; } ImageViewTouchBase newView = mSlideShowImageViews[mSlideShowImageCurrent]; newView.setVisibility(View.VISIBLE); newView.setImageBitmapResetBase(bitmap, isThumb, isThumb); newView.bringToFront(); int animation = 0; if (mAnimationIndex == -1) { int n = mRandom.nextInt(mSlideShowInAnimation.length); animation = n; } else { animation = mAnimationIndex; } Animation aIn = mSlideShowInAnimation[animation]; newView.setAnimation(aIn); newView.setVisibility(View.VISIBLE); aIn.startNow(); Animation aOut = mSlideShowOutAnimation[animation]; oldView.setVisibility(View.INVISIBLE); oldView.setAnimation(aOut); aOut.startNow(); mCurrentPosition = requestedPos; mHandler.post(new Runnable() { public void run() { if (mCurrentPosition == mLastSlideShowImage && !firstCall) { if (mSlideShowLoop) { if (mUseShuffleOrder) { generateShuffleOrder(); } } else { setMode(MODE_NORMAL); return; } } if (Config.LOGV) Log.v(TAG, "mCurrentPosition is now " + mCurrentPosition); loadNextImage((mCurrentPosition + 1) % mAllImages.getCount(), mSlideShowInterval, false); } }); } }, timeRemaining); } }; // Could be null if we're stopping a slide show in the course of pausing if (mGetter != null) { int pos = requestedPos; if (mShuffleOrder != null) { pos = mShuffleOrder[pos]; } mGetter.setPosition(pos, cb); } } private void makeGetter() { mGetter = new ImageGetter(); } private boolean desiredSortOrder() { String sortOrder = mPrefs.getString("pref_gallery_sort_key", null); boolean sortAscending = false; if (sortOrder != null) { sortAscending = sortOrder.equals("ascending"); } if (mCameraReviewMode) { // Force left-arrow older pictures, right-arrow newer pictures. sortAscending = true; } return sortAscending; } private void init(Uri uri) { mSortAscending = desiredSortOrder(); int sort = mSortAscending ? ImageManager.SORT_ASCENDING : ImageManager.SORT_DESCENDING; mAllImages = ImageManager.makeImageList(uri, this, sort); uri = uri.buildUpon().query(null).build(); // TODO smarter/faster here please for (int i = 0; i < mAllImages.getCount(); i++) { ImageManager.IImage image = mAllImages.getImageAt(i); if (image.fullSizeImageUri().equals(uri)) { mCurrentPosition = i; mLastSlideShowImage = mCurrentPosition; break; } } } @Override public void onSaveInstanceState(Bundle b) { super.onSaveInstanceState(b); ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); if (image != null){ Uri uri = image.fullSizeImageUri(); String bucket = null; if(getIntent()!= null && getIntent().getData()!=null) bucket = getIntent().getData().getQueryParameter("bucketId"); if(bucket!=null) uri = uri.buildUpon().appendQueryParameter("bucketId", bucket).build(); b.putString("uri", uri.toString()); } if (mMode == MODE_SLIDESHOW) b.putBoolean("slideshow", true); } @Override public void onResume() { super.onResume(); // normally this will never be zero but if one "backs" into this // activity after removing the sdcard it could be zero. in that // case just "finish" since there's nothing useful that can happen. if (mAllImages.getCount() == 0) { finish(); } ImageManager.IImage image = mAllImages.getImageAt(mCurrentPosition); if (desiredSortOrder() != mSortAscending) { init(image.fullSizeImageUri()); } if (mGetter == null) { makeGetter(); } - for (ImageViewTouchBase iv: mImageViews) { - iv.setImageBitmap(null, true); - } - mFirst = true; mScroller.setLayoutCompletedCallback(new Runnable() { public void run() { mLayoutComplete = true; setImage(mCurrentPosition); } }); setImage(mCurrentPosition); setOrientation(); // Show a tutorial for the new zoom interaction (the method ensure we only show it once) ZoomRingController.showZoomTutorialOnce(this); } @Override public void onPause() { super.onPause(); mGetter.cancelCurrent(); mGetter.stop(); mGetter = null; setMode(MODE_NORMAL); mAllImages.deactivate(); for (ImageViewTouch iv: mImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } for (ImageViewTouch iv: mSlideShowImageViews) { iv.recycleBitmaps(); iv.setImageBitmap(null, true); } ZoomRingController.finishZoomTutorial(this, false); } @Override public void onStop() { super.onStop(); } public void onClick(View v) { switch (v.getId()) { case R.id.shutter_button: { if (mCameraReviewMode) { finish(); } else { MenuHelper.gotoStillImageCapture(this); } } break; case R.id.gallery: { MenuHelper.gotoCameraImageGallery(this); } break; case R.id.discard: { if (mCameraReviewMode) { mDeletePhotoRunnable.run(); } else { MenuHelper.deletePhoto(this, mDeletePhotoRunnable); } } break; case R.id.share: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_STREAM, u); try { startActivity(Intent.createChooser(intent, getText(R.string.sendImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_image, Toast.LENGTH_SHORT).show(); } } break; case R.id.setas: { Uri u = mAllImages.getImageAt(mCurrentPosition).fullSizeImageUri(); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA, u); try { startActivity(Intent.createChooser(intent, getText(R.string.setImage))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(this, R.string.no_way_to_share_video, Toast.LENGTH_SHORT).show(); } } break; case R.id.next_image: { moveNextOrPrevious(1); } break; case R.id.prev_image: { moveNextOrPrevious(-1); } break; } } private void moveNextOrPrevious(int delta) { int nextImagePos = mCurrentPosition + delta; if ((0 <= nextImagePos) && (nextImagePos < mAllImages.getCount())) { setImage(nextImagePos); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case MenuHelper.RESULT_COMMON_MENU_CROP: if (resultCode == RESULT_OK) { // The CropImage activity passes back the Uri of the cropped image as // the Action rather than the Data. Uri dataUri = Uri.parse(data.getAction()); init(dataUri); } break; } } }
SmartITEngineering/smart-cms
5eab96d2a28eedfc74d1b8e779397421c8b54c6e
SMARTCMS-58: Add API for exposing field definitions as map
diff --git a/webservice-modules/smart-cms-client-api/src/main/java/com/smartitengineering/cms/client/api/ContentTypeFeedResource.java b/webservice-modules/smart-cms-client-api/src/main/java/com/smartitengineering/cms/client/api/ContentTypeFeedResource.java index 49e58d0..f61a08f 100644 --- a/webservice-modules/smart-cms-client-api/src/main/java/com/smartitengineering/cms/client/api/ContentTypeFeedResource.java +++ b/webservice-modules/smart-cms-client-api/src/main/java/com/smartitengineering/cms/client/api/ContentTypeFeedResource.java @@ -1,51 +1,54 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.client.api; import com.smartitengineering.cms.ws.common.domains.FieldDef; import com.smartitengineering.util.rest.client.Resource; import java.util.List; +import java.util.Map; import org.apache.abdera.model.Feed; /** * * @author imyousuf */ public interface ContentTypeFeedResource extends Resource<Feed> { ContentTypeResource getContentTypeResource(); List<FieldDef> getFieldDefs(); + + Map<String, FieldDef> getFieldDefsMap(); List<String> getStatuses(); String getDisplayName(); String getWorkspaceNamespace(); String getWorkspaceName(); String getContentTypeNamespace(); String getContentTypeName(); public ContentTypeSearchResultResource getChildren(); public ContentTypeSearchResultResource getInstances(); } diff --git a/webservice-modules/smart-cms-client-impl/src/main/java/com/smartitengineering/cms/client/impl/ContentTypeFeedResourceImpl.java b/webservice-modules/smart-cms-client-impl/src/main/java/com/smartitengineering/cms/client/impl/ContentTypeFeedResourceImpl.java index 464e25a..874093a 100644 --- a/webservice-modules/smart-cms-client-impl/src/main/java/com/smartitengineering/cms/client/impl/ContentTypeFeedResourceImpl.java +++ b/webservice-modules/smart-cms-client-impl/src/main/java/com/smartitengineering/cms/client/impl/ContentTypeFeedResourceImpl.java @@ -1,146 +1,157 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.client.impl; import com.smartitengineering.cms.client.api.ContentTypeFeedResource; import com.smartitengineering.cms.client.api.ContentTypeResource; import com.smartitengineering.cms.client.api.ContentTypeSearchResultResource; import com.smartitengineering.cms.ws.common.domains.FieldDef; import com.smartitengineering.cms.ws.common.utils.SimpleFeedExtensions; import com.smartitengineering.util.rest.atom.AbstractFeedClientResource; import com.smartitengineering.util.rest.atom.AtomClientUtil; import com.smartitengineering.util.rest.client.Resource; import com.smartitengineering.util.rest.client.ResourceLink; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import java.util.ArrayList; import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Link; import org.codehaus.jackson.map.ObjectMapper; /** * * @author imyousuf */ public class ContentTypeFeedResourceImpl extends AbstractFeedClientResource<Resource<? extends Feed>> implements ContentTypeFeedResource { public ContentTypeFeedResourceImpl(Resource referrer, ResourceLink resouceLink) throws IllegalArgumentException, UniformInterfaceException { super(referrer, resouceLink); } @Override protected void processClientConfig(ClientConfig clientConfig) { } @Override protected Resource<? extends Feed> instantiatePageableResource(ResourceLink link) { return null; } @Override public ContentTypeResource getContentTypeResource() { return new ContentTypeResourceImpl(this, getRelatedResourceUris().getFirst(Link.REL_ALTERNATE)); } @Override public List<FieldDef> getFieldDefs() { if (getLastReadStateOfEntity() == null || getLastReadStateOfEntity().getEntries() == null || getLastReadStateOfEntity(). getEntries().isEmpty()) { return Collections.emptyList(); } List<FieldDef> defs = new ArrayList<FieldDef>(getLastReadStateOfEntity().getEntries().size()); ObjectMapper mapper = new ObjectMapper(); for (Entry entry : getLastReadStateOfEntity().getEntries()) { if (logger.isDebugEnabled()) { logger.debug("FiedDef JSON Content: " + entry.getContent()); } try { defs.add(mapper.readValue(entry.getContent(), FieldDef.class)); } catch (Exception ex) { logger.error("Could not parse Field Def JSON", ex); } } return defs; } + public Map<String, FieldDef> getFieldDefsMap() { + List<FieldDef> defs = getFieldDefs(); + final Map<String, FieldDef> result = new LinkedHashMap<String, FieldDef>(); + for (FieldDef def : defs) { + result.put(def.getName(), def); + } + return result; + } + @Override public ContentTypeSearchResultResource getChildren() { return new ContentTypeSearchResultResourceImpl(this, AtomClientUtil.convertFromAtomLinkToResourceLink(getLastReadStateOfEntity(). getLink("children"))); } @Override public ContentTypeSearchResultResource getInstances() { return new ContentTypeSearchResultResourceImpl(this, AtomClientUtil.convertFromAtomLinkToResourceLink(getLastReadStateOfEntity(). getLink("instances"))); } @Override public String getDisplayName() { return getLastReadStateOfEntity().getTitle(); } @Override public String getWorkspaceNamespace() { return getLastReadStateOfEntity().getSimpleExtension(SimpleFeedExtensions.WORKSPACE_NAME_SPACE); } @Override public String getWorkspaceName() { return getLastReadStateOfEntity().getSimpleExtension(SimpleFeedExtensions.WORKSPACE_NAME); } @Override public String getContentTypeName() { return getLastReadStateOfEntity().getSimpleExtension(SimpleFeedExtensions.CONTENT_TYPE_NAME); } @Override public String getContentTypeNamespace() { return getLastReadStateOfEntity().getSimpleExtension(SimpleFeedExtensions.CONTENT_TYPE_NAME_SPACE); } @Override public List<String> getStatuses() { ArrayList<String> statuses = new ArrayList<String>(); try { ResourceLink link = getRelatedResourceUris().getFirst("statuses"); WebResource resource = getClient().resource(getUri().resolve(link.getUri())); resource.accept(link.getMimeType()); Feed statusFeed = resource.get(Feed.class); for (Entry entry : statusFeed.getEntries()) { statuses.add(entry.getContent()); } } catch (Exception ex) { logger.warn("Could not fetch statuses!", ex); } return statuses; } }
SmartITEngineering/smart-cms
64a80c3eca8d3c0fa511ef810be3caf0ca4d317a
Remove JavaDoc generation from code gen demo
diff --git a/code-generation/cms-codegenerator-demo/pom.xml b/code-generation/cms-codegenerator-demo/pom.xml index b7d2985..5f315ad 100644 --- a/code-generation/cms-codegenerator-demo/pom.xml +++ b/code-generation/cms-codegenerator-demo/pom.xml @@ -1,192 +1,188 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- * * This is a simple Content Management System (CMS) * Copyright (C) 2011 Imran M Yousuf ([email protected]) * 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/>. --> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <groupId>com.smartitengineering.smart-cms</groupId> <artifactId>cms-codegenerator-demo</artifactId> <parent> <groupId>com.smartitengineering.smart-cms</groupId> <artifactId>code-generation</artifactId> <version>0.1-SNAPSHOT</version> </parent> <version>0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>CMS Code Generator Demo</name> <dependencies> <dependency> <groupId>com.smartitengineering.smart-cms</groupId> <artifactId>content-repo-dao-impl</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>com.smartitengineering.smart-util</groupId> <artifactId>smart-bean-guice-util</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-jdk14</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-javadoc-plugin</artifactId> - </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> </plugin> <plugin> <groupId>com.smartitengineering.smart-cms</groupId> <artifactId>cms-tools-plugin</artifactId> <version>${project.version}</version> <configuration> <outputDirectory>${project.build.directory}/cms-tools/</outputDirectory> <solrHomeDirectory>../../solr/sample-conf/</solrHomeDirectory> <solrArtifact> <groupId>org.apache.solr</groupId> <artifactId>solr</artifactId> <version>${solr.version}</version> </solrArtifact> <eventHubArtifact> <groupId>com.smartitengineering.event</groupId> <artifactId>hub-hbase</artifactId> <version>${hub.version}</version> </eventHubArtifact> <!-- Other configurations and their default expressions --> <!-- <zooKeeperPort>2181</zooKeeperPort> <embeddedPort>40404</embeddedPort> <hbaseVersion>${hbase.version}</hbaseVersion> <hadoopVersion>${hadoop.version}</hadoopVersion> <jerseyVersion>${jersey.version}</jerseyVersion> --> </configuration> <executions> <execution> <id>start-cms-tool-suite</id> <phase>test-compile</phase> <goals> <goal>start</goal> </goals> <configuration> <!-- By default it is set to false, which means manual invokation would result a running CMS container --> <daemonMode>true</daemonMode> </configuration> </execution> <execution> <id>stop-cms-tool-suite</id> <phase>package</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>com.smartitengineering.smart-cms</groupId> <artifactId>maven-pojo-generator-plugin</artifactId> <version>${project.version}</version> <configuration> <outputDirectory>${project.build.directory}/generated-sources/cms-pojo/</outputDirectory> <workspaceId>p:q</workspaceId> </configuration> <executions> <execution> <id>generate-pojo-example</id> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> <configuration> <contentTypeResource>${basedir}/src/main/resources/content-type-example.xml</contentTypeResource> <packageForGuiceMasterModule>com.embarcadero.edn</packageForGuiceMasterModule> <typeFiles> <typeFile>content-type-example.xml</typeFile> </typeFiles> <transactionEnabled>true</transactionEnabled> </configuration> </execution> <execution> <id>generate-pojo-file</id> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> <configuration> <contentTypeResource>${basedir}/src/main/resources/content-type-def-with-composition.xml</contentTypeResource> <packageForGuiceMasterModule>test.di</packageForGuiceMasterModule> <typeFiles> <typeFile>content-type-def-with-composition.xml</typeFile> </typeFiles> </configuration> </execution> <execution> <id>generate-pojo-resource</id> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> <configuration> <contentTypeResource>${basedir}/src/main/resources/content-type-def-with-composition_1.xml</contentTypeResource> <packageForGuiceMasterModule>testa.di</packageForGuiceMasterModule> <typeFiles> <typeFile>content-type-def-with-composition_1.xml</typeFile> </typeFiles> </configuration> </execution> <execution> <id>generate-pojo-resources</id> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> <configuration> <contentTypes> <contentType>${basedir}/src/main/resources/content-type-def-with-composition_2.xml</contentType> <contentType>${basedir}/src/main/resources/content-type-def-with-composition_3.xml</contentType> </contentTypes> <typeFiles> <typeFile>content-type-def-with-composition_2.xml</typeFile> <typeFile>content-type-def-with-composition_3.xml</typeFile> </typeFiles> <packageForGuiceMasterModule>testb.di</packageForGuiceMasterModule> </configuration> </execution> </executions> </plugin> </plugins> </build> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <junit.version>4.8.2</junit.version> </properties> </project>
SmartITEngineering/smart-cms
82a9e2da04f28ae807df8e6ba58839a2e2335131
Add Workspace deletion from web service as well as client impl.
diff --git a/webservice-modules/smart-cms-client-api/src/main/java/com/smartitengineering/cms/client/api/WorkspaceContentResouce.java b/webservice-modules/smart-cms-client-api/src/main/java/com/smartitengineering/cms/client/api/WorkspaceContentResouce.java index 0ac797b..bfbf316 100644 --- a/webservice-modules/smart-cms-client-api/src/main/java/com/smartitengineering/cms/client/api/WorkspaceContentResouce.java +++ b/webservice-modules/smart-cms-client-api/src/main/java/com/smartitengineering/cms/client/api/WorkspaceContentResouce.java @@ -1,31 +1,33 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.client.api; import com.smartitengineering.cms.ws.common.domains.Workspace; import com.smartitengineering.util.rest.client.Resource; /** * * @author kaisar */ public interface WorkspaceContentResouce extends Resource<Workspace> { String WORKSPACE_CONTENT = "workspaceContent"; + + public void delete(); } diff --git a/webservice-modules/smart-cms-client-impl/src/main/java/com/smartitengineering/cms/client/impl/WorkspaceContentResourceImpl.java b/webservice-modules/smart-cms-client-impl/src/main/java/com/smartitengineering/cms/client/impl/WorkspaceContentResourceImpl.java index 780898d..f00dd17 100644 --- a/webservice-modules/smart-cms-client-impl/src/main/java/com/smartitengineering/cms/client/impl/WorkspaceContentResourceImpl.java +++ b/webservice-modules/smart-cms-client-impl/src/main/java/com/smartitengineering/cms/client/impl/WorkspaceContentResourceImpl.java @@ -1,59 +1,64 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.client.impl; import com.smartitengineering.cms.client.api.WorkspaceContentResouce; import com.smartitengineering.cms.ws.common.domains.Workspace; import com.smartitengineering.util.rest.client.AbstractClientResource; import com.smartitengineering.util.rest.client.Resource; import com.smartitengineering.util.rest.client.ResourceLink; +import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.config.ClientConfig; /** * * @author imyousuf */ public class WorkspaceContentResourceImpl extends AbstractClientResource<Workspace, WorkspaceContentResouce> implements WorkspaceContentResouce { public WorkspaceContentResourceImpl(Resource referrer, ResourceLink resouceLink) throws IllegalArgumentException, UniformInterfaceException { super(referrer, resouceLink); } @Override protected void processClientConfig(ClientConfig clientConfig) { } @Override protected WorkspaceContentResouce instantiatePageableResource(ResourceLink link) { return null; } @Override protected ResourceLink getNextUri() { return null; } @Override protected ResourceLink getPreviousUri() { return null; } + + public void delete() { + delete(ClientResponse.Status.OK); + } } diff --git a/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java b/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java index 2b3e074..580c80f 100644 --- a/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java +++ b/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java @@ -3090,537 +3090,725 @@ public class AppTest { lastReadStateOfEntity.getFieldsMap().get("directEnumFieldCopy").getValue().getValue()); String dynaField = lastReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue(); sleep(); final Content reReadStateOfEntity = client.resource(resourceImpl.getUri()).accept(MediaType.APPLICATION_JSON). header("Pragma", "no-cache").get(Content.class); Assert.assertFalse(dynaField.equals(reReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue())); } sleep(); } private WorkspaceFeedResource setupSequenceWorkspace() { RootResource resource = RootResourceImpl.getRoot(URI.create(ROOT_URI_STRING)); resource.get(); WorkspaceFeedResource feedResource; try { feedResource = resource.getTemplates().getWorkspaceResource("test", "sequences"); } catch (Exception ex) { feedResource = null; LOGGER.info("Exception getting feed resoruce", ex); } boolean valid = false; { try { final WorkspaceIdImpl workspaceId = new WorkspaceIdImpl("test", "sequences"); if (feedResource == null) { Workspace workspace = resource.createWorkspace(workspaceId); feedResource = resource.getTemplates().getWorkspaceResource(workspace.getId().getGlobalNamespace(), workspace.getId().getName()); } valid = true; } catch (Exception ex) { LOGGER.error("Error creating test workspace for templates", ex); } } Assert.assertTrue(valid); return feedResource; } @Test public void testCreateSequences() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Create Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.putSequence(workspace.getId(), TEST, PORT); Assert.assertNotNull(sequence); Assert.assertEquals(workspace.getId(), sequence.getWorkspace()); Assert.assertEquals(TEST, sequence.getName()); Assert.assertEquals(PORT, sequence.getCurrentValue()); sleep(); } @Test public void testGetSequence() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Get Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertNotNull(sequence); Assert.assertEquals(workspace.getId(), sequence.getWorkspace()); Assert.assertEquals(TEST, sequence.getName()); Assert.assertEquals(PORT, sequence.getCurrentValue()); Collection<Sequence> sequences = workspaceApi.getSequencesForWorkspace(workspace.getId()); Assert.assertNotNull(sequences); Assert.assertEquals(1, sequences.size()); sequence = sequences.iterator().next(); Assert.assertNotNull(sequence); Assert.assertEquals(workspace.getId(), sequence.getWorkspace()); Assert.assertEquals(TEST, sequence.getName()); Assert.assertEquals(PORT, sequence.getCurrentValue()); sleep(); } @Test public void testBasicSequenceModifications() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Basic Modify Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); long newVal = workspaceApi.modifySequenceValue(sequence, 1); Assert.assertEquals(PORT + 1, newVal); newVal = workspaceApi.modifySequenceValue(sequence, -2); Assert.assertEquals(PORT - 1, newVal); newVal = workspaceApi.modifySequenceValue(sequence, 1); Assert.assertEquals(PORT, newVal); sleep(); } @Test public void testSingleJVMMultiThreadedSequenceModifications() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Multithread modify Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); final Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); final ConcurrentHashSet<Long> vals = new ConcurrentHashSet<Long>(); Runnable runnable = new Runnable() { public void run() { for (int i = 0; i < 100; ++i) { long newVal = workspaceApi.modifySequenceValue(sequence, 1); Assert.assertTrue(vals.add(newVal)); } } }; long start = System.currentTimeMillis(); Collection<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < 10; ++i) { Thread thread = new Thread(runnable); thread.start(); threads.add(thread); } try { for (Thread thread : threads) { thread.join(); } } catch (Exception ex) { LOGGER.error("Could wait for thread to end!", ex); throw new IllegalArgumentException(ex); } long end = System.currentTimeMillis(); sleep(); Sequence lsequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertEquals(PORT + 1000, lsequence.getCurrentValue()); LOGGER.info("Duration for 1000 increments " + (end - start) + "ms"); } @Test public void testDeleteSequence() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Delete Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertNotNull(sequence); workspaceApi.deleteSequence(workspace.getId(), TEST); sequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertNull(sequence); sleep(); Collection<Sequence> sequences = workspaceApi.getSequencesForWorkspace(workspace.getId()); Assert.assertNotNull(sequences); Assert.assertEquals(0, sequences.size()); } @Test public void testCreateSequencesViaWebService() { WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceSequencesResource sequences = resource.getSequences(); Assert.assertNotNull(sequences); sequences.createSequence(TEST, PORT); sleep(); sequences.get(); Collection<WorkspaceSequenceResource> seqs = sequences.getSequences(); Assert.assertEquals(1, seqs.size()); WorkspaceSequenceResource seq = sequences.getSequenceByName(TEST); Assert.assertEquals(TEST, seq.getName()); Assert.assertEquals(PORT, seq.getCurrentValue()); } @Test public void testUpdateSequenceViaWebService() { WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceSequencesResource sequences = resource.getSequences(); Assert.assertNotNull(sequences); WorkspaceSequenceResource seq = sequences.getSequenceByName(TEST); Assert.assertNotNull(seq); long newVal = seq.update(1); Assert.assertEquals(TEST, seq.getName()); Assert.assertEquals(PORT + 1, newVal); sleep(); } @Test public void testDeleteSequenceViaWebService() { WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceSequencesResource sequences = resource.getSequences(); Assert.assertNotNull(sequences); WorkspaceSequenceResource seq = sequences.getSequenceByName(TEST); Assert.assertNotNull(seq); seq.delete(ClientResponse.Status.ACCEPTED); try { seq = sequences.getSequenceByName(TEST); } catch (Exception ex) { //Expected } sleep(); } @Test public void testDeleteWorkspace() { LOGGER.info("::::::::::::::::::::: TEST DELETE WORKSPACE ::::::::::::::::::::::"); final String WSForDeleteWith300plusContent = "wsfordeletewith350content"; final String WSForDeleteWith90Content = "wsfordeletewith90content"; final String WSForDeleteWithNoContent = "wsfordeletewithnocontent"; // create a workspace for delete WorkspaceId workspaceForDeleteWith300PlusContentId = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspace( WSForDeleteWith300plusContent); ResultScanner rs = null; //SmartContentAPI.getInstance().getWorkspaceApi().createWorkspace(workspaceForDeleteId); com.smartitengineering.cms.api.workspace.Workspace workSpaceForDeleteWith300PlusContent = SmartContentAPI. getInstance(). getWorkspaceApi().getWorkspace(workspaceForDeleteWith300PlusContentId); Assert.assertNotNull(workSpaceForDeleteWith300PlusContent); // create content type InputStream stream = getClass().getClassLoader().getResourceAsStream("content-type-for-delete.xml"); try { final ContentTypeLoader contentTypeLoader = SmartContentAPI.getInstance().getContentTypeLoader(); final Collection<WritableContentType> types; types = contentTypeLoader.parseContentTypes(workSpaceForDeleteWith300PlusContent.getId(), stream, com.smartitengineering.cms.api.common.MediaType.APPLICATION_XML); for (WritableContentType type : types) { type.put(); } stream.close(); } catch (Exception ex) { LOGGER.info("Can not create ContentType for delete", ex); Assert.fail(); } ContentTypeId contentTypeId = SmartContentAPI.getInstance().getContentTypeLoader().createContentTypeId( workspaceForDeleteWith300PlusContentId, "com.smartitengineering.smart-shopping.content", "ContentTypeForDelete"); ContentType contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); Assert.assertNotNull(contentType); // create content String statusKey = contentType.getStatuses().keySet().iterator().next(); ContentStatus contentStatus = contentType.getStatuses().get(statusKey); for (int i = 0; i < 350; i++) { MutableContent mutableContent = SmartContentAPI.getInstance().getContentLoader().createContent(contentType); mutableContent.setContentDefinition(contentType); mutableContent.setPrivate(false); mutableContent.setStatus(contentStatus); MutableField mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); mutableField.setName("name"); MutableFieldValue<String> mutableFieldValue = new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); mutableFieldValue.setValue("russel"); mutableField.setValue(mutableFieldValue); mutableContent.setField(mutableField); //Create new content WriteableContent writeableContent = SmartContentAPI.getInstance().getContentLoader().getWritableContent( mutableContent); writeableContent.createContentId(workspaceForDeleteWith300PlusContentId); try { //Save or update the content, will be decided by writeable content implementation writeableContent.put(); } catch (IOException ex) { LOGGER.error(ex.getMessage(), ex); Assert.fail(); } } sleep(); SmartContentAPI.getInstance().getWorkspaceApi().deleteWorkspace(workspaceForDeleteWith300PlusContentId); sleep(); try { Thread.sleep(50000); } catch (Exception ex) { } com.smartitengineering.cms.api.workspace.Workspace fetchedWorkspace = SmartContentAPI.getInstance(). getWorkspaceApi(). getWorkspace(workspaceForDeleteWith300PlusContentId); if (fetchedWorkspace == null) { LOGGER.info("Fetched workspace null"); } Assert.assertNull(fetchedWorkspace); contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); Assert.assertNull(contentType); // test contents exists or not try { HTable table = new HTable(TEST_UTIL.getConfiguration(), "cms_content"); Scan s = new Scan(); s.addColumn(Bytes.toBytes("self"), Bytes.toBytes("contentType")); rs = table.getScanner(s); LOGGER.info("WorkspaceForDelete Id: " + workspaceForDeleteWith300PlusContentId.toString()); for (Result rr = rs.next(); rr != null; rr = rs.next()) { String rowId = Bytes.toString(rr.getRow()); if (rowId.contains(workspaceForDeleteWith300PlusContentId.toString())) { LOGGER.info(rowId); Assert.fail(); } } } catch (Exception ex) { ex.printStackTrace(); } finally { rs.close(); } // test fields exists or not try { HTable table = new HTable(TEST_UTIL.getConfiguration(), "cms_fields"); Scan s = new Scan(); s.addColumn(Bytes.toBytes("self"), Bytes.toBytes("id")); rs = table.getScanner(s); LOGGER.info("WorkspaceForDelete Id: " + workspaceForDeleteWith300PlusContentId.toString()); for (Result rr = rs.next(); rr != null; rr = rs.next()) { String rowId = Bytes.toString(rr.getRow()); LOGGER.info("Fields: " + rowId); if (rowId.contains(workspaceForDeleteWith300PlusContentId.toString())) { LOGGER.info(rowId); Assert.fail(); } } } catch (Exception ex) { ex.printStackTrace(); } finally { rs.close(); } final WriteableContent writeableContentForDeleteTest; MutableContent mutableContent = SmartContentAPI.getInstance().getContentLoader().createContent(contentType); mutableContent.setContentDefinition(contentType); mutableContent.setPrivate(false); mutableContent.setStatus(contentStatus); MutableField mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); mutableField.setName("name"); MutableFieldValue<String> mutableFieldValue = new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); mutableFieldValue.setValue("russel"); mutableField.setValue(mutableFieldValue); mutableContent.setField(mutableField); //Create new content writeableContentForDeleteTest = SmartContentAPI.getInstance().getContentLoader().getWritableContent(mutableContent); writeableContentForDeleteTest.createContentId(workspaceForDeleteWith300PlusContentId); try { //Save or update the content, will be decided by writeable content implementation writeableContentForDeleteTest.put(); Assert.fail(); } catch (IOException ex) { LOGGER.info("should fail"); } // workspace with less than 100 content WorkspaceId workspaceForDeleteWith90ContentId = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspace( WSForDeleteWith90Content); com.smartitengineering.cms.api.workspace.Workspace workSpaceForDeleteWith90Content = SmartContentAPI.getInstance(). getWorkspaceApi().getWorkspace(workspaceForDeleteWith90ContentId); Assert.assertNotNull(workSpaceForDeleteWith90Content); stream = getClass().getClassLoader().getResourceAsStream("content-type-for-delete.xml"); try { final ContentTypeLoader contentTypeLoader = SmartContentAPI.getInstance().getContentTypeLoader(); final Collection<WritableContentType> types; types = contentTypeLoader.parseContentTypes(workSpaceForDeleteWith90Content.getId(), stream, com.smartitengineering.cms.api.common.MediaType.APPLICATION_XML); for (WritableContentType type : types) { type.put(); } } catch (Exception ex) { LOGGER.info("Can not create ContentType for delete", ex); Assert.fail(); } contentTypeId = SmartContentAPI.getInstance().getContentTypeLoader().createContentTypeId( workspaceForDeleteWith90ContentId, "com.smartitengineering.smart-shopping.content", "ContentTypeForDelete"); Assert.assertNotNull(contentTypeId); contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); Assert.assertNotNull(contentType); for (int i = 0; i < 90; i++) { mutableContent = SmartContentAPI.getInstance().getContentLoader().createContent(contentType); mutableContent.setContentDefinition(contentType); mutableContent.setPrivate(false); mutableContent.setStatus(contentStatus); mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); mutableField.setName("name"); mutableFieldValue = new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); mutableFieldValue.setValue("russel"); mutableField.setValue(mutableFieldValue); mutableContent.setField(mutableField); //Create new content WriteableContent writeableContent = SmartContentAPI.getInstance().getContentLoader().getWritableContent( mutableContent); writeableContent.createContentId(workspaceForDeleteWith90ContentId); try { //Save or update the content, will be decided by writeable content implementation writeableContent.put(); } catch (IOException ex) { LOGGER.error(ex.getMessage(), ex); Assert.fail(); } } sleep(); SmartContentAPI.getInstance().getWorkspaceApi().deleteWorkspace(workspaceForDeleteWith90ContentId); sleep(); try { Thread.sleep(50000); } catch (Exception ex) { } fetchedWorkspace = SmartContentAPI.getInstance(). getWorkspaceApi(). getWorkspace(workspaceForDeleteWith90ContentId); if (fetchedWorkspace == null) { LOGGER.info("Fetched workspace null"); } Assert.assertNull(fetchedWorkspace); contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); Assert.assertNull(contentType); // test contents exists or not try { HTable table = new HTable(TEST_UTIL.getConfiguration(), "cms_content"); Scan s = new Scan(); s.addColumn(Bytes.toBytes("self"), Bytes.toBytes("contentType")); rs = table.getScanner(s); LOGGER.info("WorkspaceForDelete Id: " + workspaceForDeleteWith90ContentId.toString()); for (Result rr = rs.next(); rr != null; rr = rs.next()) { String rowId = Bytes.toString(rr.getRow()); if (rowId.contains(workspaceForDeleteWith90ContentId.toString())) { LOGGER.info(rowId); Assert.fail(); } } } catch (Exception ex) { ex.printStackTrace(); } finally { rs.close(); } // test fields exists or not try { HTable table = new HTable(TEST_UTIL.getConfiguration(), "cms_fields"); Scan s = new Scan(); s.addColumn(Bytes.toBytes("self"), Bytes.toBytes("id")); rs = table.getScanner(s); LOGGER.info("WorkspaceForDelete Id: " + workspaceForDeleteWith90ContentId.toString()); for (Result rr = rs.next(); rr != null; rr = rs.next()) { String rowId = Bytes.toString(rr.getRow()); LOGGER.info("Fields: " + rowId); if (rowId.contains(workspaceForDeleteWith90ContentId.toString())) { LOGGER.info(rowId); Assert.fail(); } } } catch (Exception ex) { ex.printStackTrace(); } finally { rs.close(); } // workspace with no content WorkspaceId workspaceForDeleteWithNoContentId = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspace( WSForDeleteWithNoContent); com.smartitengineering.cms.api.workspace.Workspace workSpaceForDeleteWithNoContent = SmartContentAPI.getInstance(). getWorkspaceApi().getWorkspace(workspaceForDeleteWithNoContentId); Assert.assertNotNull(workSpaceForDeleteWithNoContent); SmartContentAPI.getInstance().getWorkspaceApi().deleteWorkspace(workspaceForDeleteWithNoContentId); sleep(); fetchedWorkspace = SmartContentAPI.getInstance(). getWorkspaceApi(). getWorkspace(workspaceForDeleteWithNoContentId); if (fetchedWorkspace == null) { LOGGER.info("Fetched workspace null"); } Assert.assertNull(fetchedWorkspace); } @Test public void testDeleteWorkspaceViaWebservice() { + LOGGER.info("::::::::::::::::::::: TEST DELETE WORKSPACE FROM WEBSERVICE ::::::::::::::::::::::"); + + final String WSForDeleteWith300plusContent = "wsfordeletewith350content"; + WorkspaceIdImpl workspaceId = new WorkspaceIdImpl(); + workspaceId.setName(WSForDeleteWith300plusContent); + workspaceId.setGlobalNamespace(WSForDeleteWith300plusContent); + WorkspaceContentResouce workspaceContentResourceForDelete = null; + try { + RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); + int size = resource.getWorkspaces().size(); + Workspace workspace = resource.createWorkspace(workspaceId); + Assert.assertNotNull(workspace); + resource.get(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Workspace size: " + resource.getWorkspaces().size()); + } + for (WorkspaceContentResouce workspaceContentResource : resource.getWorkspaces()) { + if (workspaceContentResource.get().getId().getName().equals(WSForDeleteWith300plusContent)) { + workspaceContentResourceForDelete = workspaceContentResource; + } + } + } + catch (Exception ex) { + LOGGER.error(ex.getMessage(), ex); + } + + ResultScanner rs = null; + com.smartitengineering.cms.api.impl.workspace.WorkspaceIdImpl workspaceForDeleteWith300PlusContentId = + new com.smartitengineering.cms.api.impl.workspace.WorkspaceIdImpl(); + workspaceForDeleteWith300PlusContentId.setName(WSForDeleteWith300plusContent); + workspaceForDeleteWith300PlusContentId.setGlobalNamespace(WSForDeleteWith300plusContent); + com.smartitengineering.cms.api.workspace.Workspace workSpaceForDeleteWith300PlusContent = SmartContentAPI. + getInstance().getWorkspaceApi().getWorkspace(workspaceForDeleteWith300PlusContentId); + Assert.assertNotNull(workSpaceForDeleteWith300PlusContent); + + // create content type + InputStream stream = getClass().getClassLoader().getResourceAsStream("content-type-for-delete.xml"); + + try { + final ContentTypeLoader contentTypeLoader = SmartContentAPI.getInstance().getContentTypeLoader(); + final Collection<WritableContentType> types; + types = contentTypeLoader.parseContentTypes(workSpaceForDeleteWith300PlusContent.getId(), stream, + com.smartitengineering.cms.api.common.MediaType.APPLICATION_XML); + for (WritableContentType type : types) { + type.put(); + } + stream.close(); + } + catch (Exception ex) { + LOGGER.info("Can not create ContentType for delete", ex); + Assert.fail(); + } + ContentTypeId contentTypeId = SmartContentAPI.getInstance().getContentTypeLoader().createContentTypeId( + workspaceForDeleteWith300PlusContentId, "com.smartitengineering.smart-shopping.content", "ContentTypeForDelete"); + + + ContentType contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); + Assert.assertNotNull(contentType); + + // create content + String statusKey = contentType.getStatuses().keySet().iterator().next(); + ContentStatus contentStatus = contentType.getStatuses().get(statusKey); + + for (int i = 0; i < 350; i++) { + MutableContent mutableContent = SmartContentAPI.getInstance().getContentLoader().createContent(contentType); + mutableContent.setContentDefinition(contentType); + mutableContent.setPrivate(false); + mutableContent.setStatus(contentStatus); + MutableField mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); + mutableField.setName("name"); + MutableFieldValue<String> mutableFieldValue = + new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); + mutableFieldValue.setValue("russel"); + mutableField.setValue(mutableFieldValue); + mutableContent.setField(mutableField); + //Create new content + WriteableContent writeableContent = SmartContentAPI.getInstance().getContentLoader().getWritableContent( + mutableContent); + writeableContent.createContentId(workspaceForDeleteWith300PlusContentId); + + try { + //Save or update the content, will be decided by writeable content implementation + writeableContent.put(); + } + catch (IOException ex) { + LOGGER.error(ex.getMessage(), ex); + Assert.fail(); + } + } + sleep(); + + // delete workspace via web service + LOGGER.info(""); + workspaceContentResourceForDelete.delete(); + + + sleep(); + try { + Thread.sleep(50000); + } + catch (Exception ex) { + } + com.smartitengineering.cms.api.workspace.Workspace fetchedWorkspace = SmartContentAPI.getInstance(). + getWorkspaceApi(). + getWorkspace(workspaceForDeleteWith300PlusContentId); + if (fetchedWorkspace == null) { + LOGGER.info("Fetched workspace null"); + } + Assert.assertNull(fetchedWorkspace); + + contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); + Assert.assertNull(contentType); + + // test contents exists or not + + try { + HTable table = new HTable(TEST_UTIL.getConfiguration(), "cms_content"); + Scan s = new Scan(); + s.addColumn(Bytes.toBytes("self"), Bytes.toBytes("contentType")); + rs = table.getScanner(s); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("WorkspaceForDelete Id: " + workspaceForDeleteWith300PlusContentId.toString()); + } + for (Result rr = rs.next(); rr != null; rr = rs.next()) { + String rowId = Bytes.toString(rr.getRow()); + if (rowId.contains(workspaceForDeleteWith300PlusContentId.toString())) { + LOGGER.info(rowId); + Assert.fail(); + } + } + + } + catch (Exception ex) { + ex.printStackTrace(); + } + finally { + rs.close(); + } + + // test fields exists or not + try { + HTable table = new HTable(TEST_UTIL.getConfiguration(), "cms_fields"); + Scan s = new Scan(); + s.addColumn(Bytes.toBytes("self"), Bytes.toBytes("id")); + rs = table.getScanner(s); + LOGGER.info("WorkspaceForDelete Id: " + workspaceForDeleteWith300PlusContentId.toString()); + for (Result rr = rs.next(); rr != null; rr = rs.next()) { + String rowId = Bytes.toString(rr.getRow()); + LOGGER.info("Fields: " + rowId); + if (rowId.contains(workspaceForDeleteWith300PlusContentId.toString())) { + LOGGER.info(rowId); + Assert.fail(); + } + } + } + catch (Exception ex) { + ex.printStackTrace(); + } + finally { + rs.close(); + } + + final WriteableContent writeableContentForDeleteTest; + MutableContent mutableContent = SmartContentAPI.getInstance().getContentLoader().createContent(contentType); + mutableContent.setContentDefinition(contentType); + mutableContent.setPrivate(false); + mutableContent.setStatus(contentStatus); + MutableField mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); + mutableField.setName("name"); + MutableFieldValue<String> mutableFieldValue = + new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); + mutableFieldValue.setValue("russel"); + mutableField.setValue(mutableFieldValue); + mutableContent.setField(mutableField); + //Create new content + writeableContentForDeleteTest = + SmartContentAPI.getInstance().getContentLoader().getWritableContent(mutableContent); + writeableContentForDeleteTest.createContentId(workspaceForDeleteWith300PlusContentId); + + try { + //Save or update the content, will be decided by writeable content implementation + writeableContentForDeleteTest.put(); + Assert.fail(); + } + catch (IOException ex) { + LOGGER.info("should fail"); + + } } protected void sleep() { try { Thread.sleep(SLEEP_DURATION); } catch (Exception ex) { LOGGER.error("Error sleeping", ex); } } public static class ConfigurationModule extends AbstractModule { @Override protected void configure() { bind(Configuration.class).toInstance(TEST_UTIL.getConfiguration()); ConnectionConfig config = new ConnectionConfig(); config.setBasicUri(""); config.setContextPath("/"); config.setHost("localhost"); config.setPort(PORT); bind(ConnectionConfig.class).toInstance(config); } } } diff --git a/webservice-modules/webservice-resources/src/main/java/com/smartitengineering/cms/ws/resources/workspace/WorkspaceResource.java b/webservice-modules/webservice-resources/src/main/java/com/smartitengineering/cms/ws/resources/workspace/WorkspaceResource.java index 539d0e6..e36b164 100644 --- a/webservice-modules/webservice-resources/src/main/java/com/smartitengineering/cms/ws/resources/workspace/WorkspaceResource.java +++ b/webservice-modules/webservice-resources/src/main/java/com/smartitengineering/cms/ws/resources/workspace/WorkspaceResource.java @@ -1,281 +1,292 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.ws.resources.workspace; import com.smartitengineering.cms.api.factory.SmartContentAPI; import com.smartitengineering.cms.api.workspace.Workspace; import com.smartitengineering.cms.api.factory.workspace.WorkspaceAPI; import com.smartitengineering.cms.ws.common.providers.TextURIListProvider; import com.smartitengineering.cms.ws.common.utils.SimpleFeedExtensions; import com.smartitengineering.cms.ws.common.utils.Utils; import com.smartitengineering.cms.ws.resources.content.ContentsResource; import com.smartitengineering.cms.ws.resources.content.searcher.ContentSearcherResource; import com.smartitengineering.cms.ws.resources.domains.Factory; import com.smartitengineering.cms.ws.resources.type.ContentTypesResource; import com.smartitengineering.util.rest.atom.server.AbstractResource; import java.net.URI; import java.util.Date; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; +import javax.ws.rs.DELETE; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.UriBuilder; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Link; import org.apache.commons.codec.digest.DigestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author imyousuf */ @Path("/w/{" + WorkspaceResource.PARAM_NAMESPACE + "}/{" + WorkspaceResource.PARAM_NAME + "}") public class WorkspaceResource extends AbstractResource { public static final int MAX_AGE = 1 * 60 * 60; public static final String PARAM_NAMESPACE = "ns"; public static final String PARAM_NAME = "wsName"; public static final String PATH_FRIENDLIES = "friendlies"; public static final String PATH_REPRESENTATIONS = "representations"; public static final String PATH_CONTENT_CO_PROCESSORS = "content-co-processors"; public static final String PATH_VARIATIONS = "variations"; public static final String PATH_VALIDATORS = "validators"; public static final String PATH_SEQUENCES = "sequences"; public static final String PATH_SEARCH = "search"; public static final String PATH_REINDEX = "reindex"; public static final String REL_FRIENDLIES = "friendlies"; public static final String REL_SEQUENCES = "sequences"; public static final String REL_REPRESENTATIONS = "representations"; public static final String REL_CONTENT_CO_PROCESSORS = "contentCoProcessors"; public static final String REL_VARIATIONS = "variations"; public static final String REL_VALIDATORS = "validators"; public static final String REL_CONTENT_TYPES = "content-types"; public static final String REL_CONTENTS = "contents"; public static final String REL_SEARCH = "search"; public static final String REL_REINDEX = "re-index-all"; public static final String REL_REINDEX_CONTENTS = "re-index-contents"; public static final String REL_REINDEX_TYPES = "re-index-types"; public static final String REL_WORKSPACE_CONTENT = "workspaceContent"; private final String namespace; private final String workspaceName; private final Workspace workspace; @HeaderParam(HttpHeaders.IF_MODIFIED_SINCE) private Date ifModifiedSince; @HeaderParam(HttpHeaders.IF_NONE_MATCH) private EntityTag entityTag; private final static transient Logger LOGGER = LoggerFactory.getLogger(WorkspaceResource.class); public WorkspaceResource(@PathParam(PARAM_NAMESPACE) String namespace, @PathParam(PARAM_NAME) String workspaceName) { this.namespace = namespace; this.workspaceName = workspaceName; final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); this.workspace = workspaceApi.getWorkspace(workspaceApi.createWorkspaceId(namespace, workspaceName)); if (this.workspace == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } @GET @Produces(MediaType.APPLICATION_JSON) public Response getWorkspaceContent() { if (ifModifiedSince == null || ifModifiedSince.before(workspace.getCreationDate())) { ResponseBuilder builder = Response.ok(Factory.getWorkspace(workspace)); builder.lastModified(workspace.getCreationDate()); CacheControl control = new CacheControl(); control.setMaxAge(MAX_AGE); builder.cacheControl(control); builder.header(HttpHeaders.VARY, HttpHeaders.ACCEPT); return builder.build(); } else { return Response.status(Response.Status.NOT_MODIFIED).build(); } } + @DELETE + public Response deleteWorkspace() { + ResponseBuilder responseBuilder = Response.status(Response.Status.OK); + if (workspace == null) { + return responseBuilder.status(Response.Status.NOT_FOUND).build(); + } + SmartContentAPI.getInstance().getWorkspaceApi().deleteWorkspace(workspace.getId()); + return responseBuilder.build(); + } + @Path(PATH_SEARCH) public ContentSearcherResource searchWithinWorkspace() { ContentSearcherResource resource = new ContentSearcherResource(getInjectables()); resource.setWorkspaceId(workspace.getId().toString().replaceAll(":", ",")); return resource; } @Path(PATH_REINDEX) public ReIndexResource reindexForWorkspace() { ReIndexResource resource = new ReIndexResource(getInjectables()); resource.setWorkspaceId(workspace.getId()); return resource; } @Path(PATH_REINDEX + "/" + ReIndexResource.CONTENTS) public ReIndexResource reindexForWorkspaceContents() { ReIndexResource resource = new ReIndexResource(getInjectables()); resource.setWorkspaceId(workspace.getId()); resource.setContentsOnly(true); return resource; } @Path(PATH_REINDEX + "/" + ReIndexResource.TYPES) public ReIndexResource reindexForWorkspaceTypes() { ReIndexResource resource = new ReIndexResource(getInjectables()); resource.setWorkspaceId(workspace.getId()); resource.setTypesOnly(true); return resource; } @GET @Produces(MediaType.APPLICATION_ATOM_XML) public Response getWorkspaceFeed() { final Date creationDate = workspace.getCreationDate(); final EntityTag tag = new EntityTag(DigestUtils.md5Hex(Utils.getFormattedDate(creationDate))); if ((ifModifiedSince == null || ifModifiedSince.before(creationDate)) && (entityTag == null || !entityTag.equals(tag))) { Feed feed = getFeed(workspace.getId().toString(), workspaceName, creationDate); feed.addLink(getLink( getAbsoluteURIBuilder().path(WorkspaceResource.class).path(PATH_FRIENDLIES).build(namespace, workspaceName), REL_FRIENDLIES, TextURIListProvider.TEXT_URI_LIST)); feed.addLink(getLink( getAbsoluteURIBuilder().path(WorkspaceResource.class).path(PATH_REPRESENTATIONS).build(namespace, workspaceName), REL_REPRESENTATIONS, MediaType.APPLICATION_ATOM_XML)); feed.addLink(getLink( getAbsoluteURIBuilder().path(WorkspaceResource.class).path(PATH_CONTENT_CO_PROCESSORS).build(namespace, workspaceName), REL_CONTENT_CO_PROCESSORS, MediaType.APPLICATION_ATOM_XML)); feed.addLink(getLink( getAbsoluteURIBuilder().path(WorkspaceResource.class).path(PATH_VARIATIONS).build(namespace, workspaceName), REL_VARIATIONS, MediaType.APPLICATION_ATOM_XML)); feed.addLink(getLink( getAbsoluteURIBuilder().path(WorkspaceResource.class).path(PATH_VALIDATORS).build(namespace, workspaceName), REL_VALIDATORS, MediaType.APPLICATION_ATOM_XML)); feed.addLink(getLink( getAbsoluteURIBuilder().path(WorkspaceResource.class).path(PATH_SEQUENCES).build(namespace, workspaceName), REL_SEQUENCES, MediaType.APPLICATION_ATOM_XML)); feed.addLink(getLink( getAbsoluteURIBuilder().path(WorkspaceResource.class).path(PATH_SEARCH).build(namespace, workspaceName), REL_SEARCH, com.smartitengineering.util.opensearch.jaxrs.MediaType.APPLICATION_OPENSEARCHDESCRIPTION_XML)); feed.addLink(getLink( getAbsoluteURIBuilder().path(WorkspaceResource.class).path(PATH_REINDEX).build(namespace, workspaceName), REL_REINDEX, MediaType.TEXT_PLAIN)); feed.addLink(getLink( getAbsoluteURIBuilder().path(WorkspaceResource.class).path(PATH_REINDEX).path(ReIndexResource.CONTENTS).build( namespace, workspaceName), REL_REINDEX_CONTENTS, MediaType.TEXT_PLAIN)); feed.addLink(getLink( getAbsoluteURIBuilder().path(WorkspaceResource.class).path(PATH_REINDEX).path(ReIndexResource.TYPES).build( namespace, workspaceName), REL_REINDEX_TYPES, MediaType.TEXT_PLAIN)); feed.addLink(getLink( getAbsoluteURIBuilder().path(ContentTypesResource.class).build(namespace, workspaceName), REL_CONTENT_TYPES, MediaType.APPLICATION_ATOM_XML)); feed.addLink(getLink(getAbsoluteURIBuilder().path(ContentsResource.class).build(namespace, workspaceName), REL_CONTENTS, MediaType.APPLICATION_ATOM_XML)); feed.addLink(getLink(getUriInfo().getRequestUri(), Link.REL_ALTERNATE, MediaType.APPLICATION_JSON)); feed.addSimpleExtension(SimpleFeedExtensions.WORKSPACE_NAME_SPACE, namespace); feed.addSimpleExtension(SimpleFeedExtensions.WORKSPACE_NAME, workspaceName); ResponseBuilder builder = Response.ok(feed); builder.lastModified(creationDate); CacheControl control = new CacheControl(); control.setMaxAge(MAX_AGE); builder.cacheControl(control); builder.tag(tag); builder.header(HttpHeaders.VARY, HttpHeaders.ACCEPT); return builder.build(); } else { return Response.status(Response.Status.NOT_MODIFIED).build(); } } @Path(PATH_FRIENDLIES) public WorkspaceFriendliesResource getFriendliesResource() { return new WorkspaceFriendliesResource(workspace, getInjectables()); } @Path(PATH_REPRESENTATIONS) public WorkspaceRepresentationsResource getRepresentationsResource(@QueryParam("count") @DefaultValue("10") int count) { return new WorkspaceRepresentationsResource(workspace, count, getInjectables()); } @Path(PATH_CONTENT_CO_PROCESSORS) public WorkspaceContentCoProcessorsResource getContentCoProcessorsResource( @QueryParam("count") @DefaultValue("10") int count) { return new WorkspaceContentCoProcessorsResource(workspace, count, getInjectables()); } @Path(PATH_VARIATIONS) public WorkspaceVariationsResource getVariationsResource(@QueryParam("count") @DefaultValue("10") int count) { return new WorkspaceVariationsResource(workspace, count, getInjectables()); } @Path(PATH_VALIDATORS) public WorkspaceValidatorsResource getValidatorsResource(@QueryParam("count") @DefaultValue("10") int count) { return new WorkspaceValidatorsResource(workspace, count, getInjectables()); } @Path(PATH_SEQUENCES) public WorkspaceSequencesResource getSequencesResource() { return new WorkspaceSequencesResource(workspace, getInjectables()); } @Path(PATH_REPRESENTATIONS + "/name/{name}") public WorkspaceRepresentationResource getRepresentationsResource(@PathParam("name") String name) { return new WorkspaceRepresentationResource(name, workspace, getInjectables()); } @Path(PATH_CONTENT_CO_PROCESSORS + "/name/{name}") public WorkspaceContentCoProcessorResource getContentCoProcessorResource(@PathParam("name") String name) { return new WorkspaceContentCoProcessorResource(name, workspace, getInjectables()); } @Path(PATH_VARIATIONS + "/name/{name}") public WorkspaceVariationResource getVariationResource(@PathParam("name") String name) { return new WorkspaceVariationResource(name, workspace, getInjectables()); } @Path(PATH_VALIDATORS + "/name/{name}") public WorkspaceValidatorResource getValidatorResource(@PathParam("name") String name) { return new WorkspaceValidatorResource(name, workspace, getInjectables()); } public static URI getWorkspaceURI(UriBuilder builder, String namespace, String name) { if (builder != null) { builder.path(WorkspaceResource.class); return builder.build(namespace, name); } return null; } public Workspace getWorkspace() { return workspace; } @Override protected String getAuthor() { return "Smart CMS"; } }
SmartITEngineering/smart-cms
b647b03b9b999b5581af70b295be929f7b585ccf
Improved test cases. Now there are three workpspaces that have 300 plus content, less than 100 content and no content used for workspace delete test.
diff --git a/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java b/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java index 7f3c7e5..2b3e074 100644 --- a/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java +++ b/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java @@ -2782,727 +2782,845 @@ public class AppTest { com.smartitengineering.cms.ws.common.domains.FieldDef wCompositedFieldDef = wDefs.get("compositedEnumField"); Assert.assertNotNull(wCompositedFieldDef); Assert.assertNotNull(((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField")); Assert.assertTrue( ((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField") instanceof EnumFieldDef); Assert.assertTrue(((EnumFieldDef) ((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField")). getChoices().contains("5")); Assert.assertTrue(((EnumFieldDef) ((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField")). getChoices().contains("6")); wCompositedFieldDef = ((CollectionFieldDef) wDefs.get("collectiveCompositedEnumField")).getItemDef(); Assert.assertNotNull(wCompositedFieldDef); Assert.assertNotNull(((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField")); Assert.assertTrue( ((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField") instanceof EnumFieldDef); Assert.assertTrue(((EnumFieldDef) ((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField")). getChoices().contains("7")); Assert.assertTrue(((EnumFieldDef) ((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField")). getChoices().contains("8")); } @Test public void testCreateContentWithEnumField() throws Exception { LOGGER.info("~~~~~~~~~~~~~~~~~~~~~~~~~~ ENUM CONTENT CREATION ~~~~~~~~~~~~~~~~~~~~~~~~~"); WorkspaceFeedResource feedResource = setupEnumWorkspace(); Properties properties = new Properties(); properties.load(getClass().getClassLoader().getResourceAsStream( "enum/form-value.properties")); Set<Object> formKeys = properties.keySet(); FormDataMultiPart multiPart = new FormDataMultiPart(); for (Object key : formKeys) { multiPart.field(key.toString(), properties.getProperty(key.toString())); } ClientResponse response = feedResource.getContents().post(MediaType.MULTIPART_FORM_DATA, multiPart, ClientResponse.Status.CREATED, ClientResponse.Status.ACCEPTED, ClientResponse.Status.OK); URI uri = response.getLocation(); ContentResourceImpl resourceImpl = new ContentResourceImpl(feedResource, uri); final Content lastReadStateOfEntity = resourceImpl.getLastReadStateOfEntity(); Assert.assertNotNull(lastReadStateOfEntity); Field field = lastReadStateOfEntity.getFieldsMap().get("directEnumField"); String val = field.getValue().getValue(); Assert.assertEquals("1", val); field = ((CompositeFieldValue) lastReadStateOfEntity.getFieldsMap().get("compositedEnumField").getValue()).getValues(). get("enumField"); val = field.getValue().getValue(); Assert.assertEquals("5", val); val = ((CollectionFieldValue) lastReadStateOfEntity.getFieldsMap().get("collectiveEnumField").getValue()).getValues(). iterator().next().getValue(); Assert.assertEquals("4", val); sleep(); for (int i = 1; i < 5; ++i) { try { properties = new Properties(); properties.load(getClass().getClassLoader().getResourceAsStream( "enum/form-invalid-value-" + i + ".properties")); formKeys = properties.keySet(); multiPart = new FormDataMultiPart(); for (Object key : formKeys) { multiPart.field(key.toString(), properties.getProperty(key.toString())); } feedResource.getContents().post(MediaType.MULTIPART_FORM_DATA, multiPart, ClientResponse.Status.CREATED, ClientResponse.Status.ACCEPTED, ClientResponse.Status.OK); Assert.fail("Invalid content should have failed " + i); } catch (Exception ex) { //Expected that creation fails } } } @Test public void testCreateContentCoProcessor() throws Exception { ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "Template"; template.setName("rep"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.JAVASCRIPT.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceContentCoProcessorsResource rsrcs = feedResource.getContentCoProcessors(); WorkspaceContentCoProcessorResource rsrc = rsrcs.createContentCoProcessor( template); Assert.assertEquals("rep", rsrc.get().getName()); Assert.assertEquals(temp, new String(rsrc.get().getTemplate())); Assert.assertEquals(TemplateType.JAVASCRIPT.toString(), rsrc.get().getTemplateType()); } @Test public void testUpdateContentCoProcessor() throws Exception { LOGGER.info(":::::::::::::: UPDATE CONTENT CO PROCESSOR RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "newTemplate"; final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.RUBY.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); Collection<WorkspaceContentCoProcessorResource> representationResources = feedResource.getContentCoProcessors(). getContentCoProcessorResources(); Assert.assertEquals(1, representationResources.size()); Iterator<WorkspaceContentCoProcessorResource> representationIterator = representationResources.iterator(); WorkspaceContentCoProcessorResource rsrc = representationIterator.next(); rsrc.update(template); Assert.assertEquals("rep", rsrc.get().getName()); Assert.assertEquals(temp, new String(rsrc.get().getTemplate())); Assert.assertEquals(TemplateType.RUBY.toString(), rsrc.get().getTemplateType()); resource.getWorkspaceFeeds(); WorkspaceContentCoProcessorResource secondRepresentationResource = resource.getWorkspaceFeeds().iterator().next(). getContentCoProcessors().getContentCoProcessorResources().iterator().next(); template.setTemplateType(TemplateType.JAVASCRIPT.name()); secondRepresentationResource.update(template); Assert.assertEquals(TemplateType.JAVASCRIPT.name(), secondRepresentationResource.get().getTemplateType()); try { rsrc.update(template); Assert.fail("Should not have been able to update!"); } catch (UniformInterfaceException ex) { //Exception expected rsrc.get(); rsrc.update(template); } sleep(); } @Test public void testDeleteContentCoProcessor() throws Exception { LOGGER.info(":::::::::::::: DELETE CONTENT CO PROCESSOR RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "Template2"; template.setName("rep2"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.JAVASCRIPT.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); final WorkspaceContentCoProcessorsResource procsResource = feedResource.getContentCoProcessors(); Collection<WorkspaceContentCoProcessorResource> rsrcs = procsResource.getContentCoProcessorResources(); Assert.assertEquals(1, rsrcs.size()); procsResource.createContentCoProcessor(template); Iterator<WorkspaceContentCoProcessorResource> representationIterator = rsrcs.iterator(); WorkspaceContentCoProcessorResource rsrc = representationIterator.next(); rsrc.delete(ClientResponse.Status.ACCEPTED); Collection<WorkspaceContentCoProcessorResource> secRsrcs = resource.getWorkspaceFeeds().iterator(). next().getContentCoProcessors().getContentCoProcessorResources(); Assert.assertEquals(1, secRsrcs.size()); sleep(); } @Test public void testCreateContentTypeWithContentCoProcessors() { WorkspaceFeedResource feedResource = setupEnumWorkspace(); com.smartitengineering.cms.api.impl.workspace.WorkspaceIdImpl id = new com.smartitengineering.cms.api.impl.workspace.WorkspaceIdImpl(); id.setGlobalNamespace(feedResource.getWorkspaceNamespace()); id.setName(feedResource.getWorkspaceName()); ContentTypeIdImpl idImpl = new ContentTypeIdImpl(); idImpl.setWorkspace(id); idImpl.setNamespace("enum"); idImpl.setName("ContentCoProcessorTest"); ContentType type = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(idImpl); final Map<ContentProcessingPhase, Collection<ContentCoProcessorDef>> contentCoProcessorDefs = type.getContentCoProcessorDefs(); Assert.assertNotNull(contentCoProcessorDefs); Assert.assertFalse(contentCoProcessorDefs.isEmpty()); Assert.assertNotNull(contentCoProcessorDefs.get(ContentProcessingPhase.READ)); Assert.assertNotNull(contentCoProcessorDefs.get(ContentProcessingPhase.WRITE)); Assert.assertFalse(contentCoProcessorDefs.get(ContentProcessingPhase.READ).isEmpty()); Assert.assertFalse(contentCoProcessorDefs.get(ContentProcessingPhase.WRITE).isEmpty()); Assert.assertEquals(2, contentCoProcessorDefs.get(ContentProcessingPhase.READ).size()); Assert.assertEquals(1, contentCoProcessorDefs.get(ContentProcessingPhase.WRITE).size()); final Iterator<ContentCoProcessorDef> readItr = contentCoProcessorDefs.get(ContentProcessingPhase.READ).iterator(); ContentCoProcessorDef def = readItr.next(); Assert.assertEquals("testr", def.getName()); Assert.assertNull(def.getMIMEType()); Assert.assertEquals(0, def.getPriority()); Assert.assertEquals(1, def.getParameters().size()); Assert.assertEquals("v", def.getParameters().get("k")); Assert.assertEquals("test", def.getResourceUri().getValue()); def = readItr.next(); Assert.assertEquals("testr1", def.getName()); Assert.assertNull(def.getMIMEType()); Assert.assertEquals(1, def.getPriority()); Assert.assertEquals(1, def.getParameters().size()); Assert.assertEquals("v1", def.getParameters().get("k1")); Assert.assertEquals("test1", def.getResourceUri().getValue()); def = contentCoProcessorDefs.get(ContentProcessingPhase.WRITE).iterator().next(); Assert.assertEquals("testw", def.getName()); Assert.assertNull(def.getMIMEType()); Assert.assertEquals(0, def.getPriority()); Assert.assertEquals(1, def.getParameters().size()); Assert.assertEquals("v2", def.getParameters().get("k2")); Assert.assertEquals("test2", def.getResourceUri().getValue()); sleep(); } private WorkspaceFeedResource setupContentCoProcessorExecWorkspace() { RootResource resource = RootResourceImpl.getRoot(URI.create(ROOT_URI_STRING)); resource.get(); WorkspaceFeedResource feedResource; try { feedResource = resource.getTemplates().getWorkspaceResource("test", "enums"); } catch (Exception ex) { feedResource = null; LOGGER.info("Exception getting feed resoruce", ex); } boolean valid = false; { try { final WorkspaceIdImpl workspaceId = new WorkspaceIdImpl("test", "enums"); if (feedResource == null) { Workspace workspace = resource.createWorkspace(workspaceId); feedResource = resource.getTemplates().getWorkspaceResource(workspace.getId().getGlobalNamespace(), workspace. getId().getName()); } String contentTypeXml = IOUtils.toString(getClass().getClassLoader().getResourceAsStream( "contentcoprocessors/content-type-def-with-enum-ext.xml")); feedResource.getContentTypes().createContentType(contentTypeXml); ResourceTemplateImpl template = new ResourceTemplateImpl(); template.setName("test"); template.setTemplate(IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream( "contentcoprocessors/coprocessor.groovy"))); template.setTemplateType("GROOVY"); template.setWorkspaceId(workspaceId); feedResource.getContentCoProcessors().createContentCoProcessor(template); valid = true; } catch (Exception ex) { LOGGER.error("Error creating test workspace for templates", ex); } } Assert.assertTrue(valid); return feedResource; } @Test public void testCreateContentWithContentCoProcessors() throws Exception { WorkspaceFeedResource feedResource = setupContentCoProcessorExecWorkspace(); ClientConfig config = new DefaultClientConfig(); config.getClasses().add(JacksonJsonProvider.class); config.getClasses().add(TextURIListProvider.class); config.getClasses().add(FeedProvider.class); Client client = Client.create(config); { final Properties properties = new Properties(); properties.load(getClass().getClassLoader().getResourceAsStream( "contentcoprocessors/form-value-write.properties")); Set<Object> formKeys = properties.keySet(); FormDataMultiPart multiPart = new FormDataMultiPart(); for (Object key : formKeys) { multiPart.field(key.toString(), properties.getProperty(key.toString())); } ClientResponse response = feedResource.getContents().post(MediaType.MULTIPART_FORM_DATA, multiPart, ClientResponse.Status.CREATED, ClientResponse.Status.ACCEPTED, ClientResponse.Status.OK); URI uri = response.getLocation(); ContentResourceImpl resourceImpl = new ContentResourceImpl(feedResource, uri); final Content lastReadStateOfEntity = resourceImpl.getLastReadStateOfEntity(); Assert.assertNotNull(lastReadStateOfEntity); Assert.assertNotNull(lastReadStateOfEntity.getFieldsMap().get("directEnumFieldCopy")); Assert.assertNotNull(lastReadStateOfEntity.getFieldsMap().get("dynaField")); Assert.assertEquals(lastReadStateOfEntity.getFieldsMap().get("directEnumField").getValue().getValue(), lastReadStateOfEntity.getFieldsMap().get("directEnumFieldCopy").getValue().getValue()); String dynaField = lastReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue(); sleep(); final Content reReadStateOfEntity = client.resource(resourceImpl.getUri()).accept(MediaType.APPLICATION_JSON). header("Pragma", "no-cache").get(Content.class); Assert.assertEquals(dynaField, reReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue()); } { final Properties properties = new Properties(); properties.load(getClass().getClassLoader().getResourceAsStream( "contentcoprocessors/form-value-read.properties")); Set<Object> formKeys = properties.keySet(); FormDataMultiPart multiPart = new FormDataMultiPart(); for (Object key : formKeys) { multiPart.field(key.toString(), properties.getProperty(key.toString())); } ClientResponse response = feedResource.getContents().post(MediaType.MULTIPART_FORM_DATA, multiPart, ClientResponse.Status.CREATED, ClientResponse.Status.ACCEPTED, ClientResponse.Status.OK); URI uri = response.getLocation(); ContentResourceImpl resourceImpl = new ContentResourceImpl(feedResource, uri); final Content lastReadStateOfEntity = resourceImpl.getLastReadStateOfEntity(); Assert.assertNotNull(lastReadStateOfEntity); Assert.assertNotNull(lastReadStateOfEntity.getFieldsMap().get("directEnumFieldCopy")); Assert.assertNotNull(lastReadStateOfEntity.getFieldsMap().get("dynaField")); Assert.assertEquals(lastReadStateOfEntity.getFieldsMap().get("directEnumField").getValue().getValue(), lastReadStateOfEntity.getFieldsMap().get("directEnumFieldCopy").getValue().getValue()); String dynaField = lastReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue(); sleep(); final Content reReadStateOfEntity = client.resource(resourceImpl.getUri()).accept(MediaType.APPLICATION_JSON). header("Pragma", "no-cache").get(Content.class); Assert.assertFalse(dynaField.equals(reReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue())); } sleep(); } private WorkspaceFeedResource setupSequenceWorkspace() { RootResource resource = RootResourceImpl.getRoot(URI.create(ROOT_URI_STRING)); resource.get(); WorkspaceFeedResource feedResource; try { feedResource = resource.getTemplates().getWorkspaceResource("test", "sequences"); } catch (Exception ex) { feedResource = null; LOGGER.info("Exception getting feed resoruce", ex); } boolean valid = false; { try { final WorkspaceIdImpl workspaceId = new WorkspaceIdImpl("test", "sequences"); if (feedResource == null) { Workspace workspace = resource.createWorkspace(workspaceId); feedResource = resource.getTemplates().getWorkspaceResource(workspace.getId().getGlobalNamespace(), workspace.getId().getName()); } valid = true; } catch (Exception ex) { LOGGER.error("Error creating test workspace for templates", ex); } } Assert.assertTrue(valid); return feedResource; } @Test public void testCreateSequences() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Create Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.putSequence(workspace.getId(), TEST, PORT); Assert.assertNotNull(sequence); Assert.assertEquals(workspace.getId(), sequence.getWorkspace()); Assert.assertEquals(TEST, sequence.getName()); Assert.assertEquals(PORT, sequence.getCurrentValue()); sleep(); } @Test public void testGetSequence() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Get Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertNotNull(sequence); Assert.assertEquals(workspace.getId(), sequence.getWorkspace()); Assert.assertEquals(TEST, sequence.getName()); Assert.assertEquals(PORT, sequence.getCurrentValue()); Collection<Sequence> sequences = workspaceApi.getSequencesForWorkspace(workspace.getId()); Assert.assertNotNull(sequences); Assert.assertEquals(1, sequences.size()); sequence = sequences.iterator().next(); Assert.assertNotNull(sequence); Assert.assertEquals(workspace.getId(), sequence.getWorkspace()); Assert.assertEquals(TEST, sequence.getName()); Assert.assertEquals(PORT, sequence.getCurrentValue()); sleep(); } @Test public void testBasicSequenceModifications() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Basic Modify Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); long newVal = workspaceApi.modifySequenceValue(sequence, 1); Assert.assertEquals(PORT + 1, newVal); newVal = workspaceApi.modifySequenceValue(sequence, -2); Assert.assertEquals(PORT - 1, newVal); newVal = workspaceApi.modifySequenceValue(sequence, 1); Assert.assertEquals(PORT, newVal); sleep(); } @Test public void testSingleJVMMultiThreadedSequenceModifications() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Multithread modify Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); final Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); final ConcurrentHashSet<Long> vals = new ConcurrentHashSet<Long>(); Runnable runnable = new Runnable() { public void run() { for (int i = 0; i < 100; ++i) { long newVal = workspaceApi.modifySequenceValue(sequence, 1); Assert.assertTrue(vals.add(newVal)); } } }; long start = System.currentTimeMillis(); Collection<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < 10; ++i) { Thread thread = new Thread(runnable); thread.start(); threads.add(thread); } try { for (Thread thread : threads) { thread.join(); } } catch (Exception ex) { LOGGER.error("Could wait for thread to end!", ex); throw new IllegalArgumentException(ex); } long end = System.currentTimeMillis(); sleep(); Sequence lsequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertEquals(PORT + 1000, lsequence.getCurrentValue()); LOGGER.info("Duration for 1000 increments " + (end - start) + "ms"); } @Test public void testDeleteSequence() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Delete Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertNotNull(sequence); workspaceApi.deleteSequence(workspace.getId(), TEST); sequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertNull(sequence); sleep(); Collection<Sequence> sequences = workspaceApi.getSequencesForWorkspace(workspace.getId()); Assert.assertNotNull(sequences); Assert.assertEquals(0, sequences.size()); } @Test public void testCreateSequencesViaWebService() { WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceSequencesResource sequences = resource.getSequences(); Assert.assertNotNull(sequences); sequences.createSequence(TEST, PORT); sleep(); sequences.get(); Collection<WorkspaceSequenceResource> seqs = sequences.getSequences(); Assert.assertEquals(1, seqs.size()); WorkspaceSequenceResource seq = sequences.getSequenceByName(TEST); Assert.assertEquals(TEST, seq.getName()); Assert.assertEquals(PORT, seq.getCurrentValue()); } @Test public void testUpdateSequenceViaWebService() { WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceSequencesResource sequences = resource.getSequences(); Assert.assertNotNull(sequences); WorkspaceSequenceResource seq = sequences.getSequenceByName(TEST); Assert.assertNotNull(seq); long newVal = seq.update(1); Assert.assertEquals(TEST, seq.getName()); Assert.assertEquals(PORT + 1, newVal); sleep(); } @Test public void testDeleteSequenceViaWebService() { WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceSequencesResource sequences = resource.getSequences(); Assert.assertNotNull(sequences); WorkspaceSequenceResource seq = sequences.getSequenceByName(TEST); Assert.assertNotNull(seq); seq.delete(ClientResponse.Status.ACCEPTED); try { seq = sequences.getSequenceByName(TEST); } catch (Exception ex) { //Expected } sleep(); } @Test public void testDeleteWorkspace() { LOGGER.info("::::::::::::::::::::: TEST DELETE WORKSPACE ::::::::::::::::::::::"); - // create a workspace for delete - WorkspaceId workspaceForDeleteId = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspace("wsfordelete"); + final String WSForDeleteWith300plusContent = "wsfordeletewith350content"; + final String WSForDeleteWith90Content = "wsfordeletewith90content"; + final String WSForDeleteWithNoContent = "wsfordeletewithnocontent"; - LOGGER.info("<<<<<<<<<<<<<<<<<<BEFORE INSERTING DELETE WORKSPACE CONTENT>>>>>>>>>>>>>>>>>>"); + // create a workspace for delete + WorkspaceId workspaceForDeleteWith300PlusContentId = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspace( + WSForDeleteWith300plusContent); ResultScanner rs = null; - - try { - HTable table = new HTable(TEST_UTIL.getConfiguration(), "cms_content"); - Scan s = new Scan(); - s.addColumn(Bytes.toBytes("self"), Bytes.toBytes("contentType")); - rs = table.getScanner(s); - LOGGER.info("WorkspaceForDelete Id: " + workspaceForDeleteId.toString()); - for (Result rr = rs.next(); rr != null; rr = rs.next()) { - String rowId = Bytes.toString(rr.getRow()); - if (rowId.contains(workspaceForDeleteId.toString())) { - LOGGER.info(rowId); - Assert.fail(); - } - LOGGER.info(rowId); - } - - } - catch (Exception ex) { - ex.printStackTrace(); - } - finally { - rs.close(); - } - - //SmartContentAPI.getInstance().getWorkspaceApi().createWorkspace(workspaceForDeleteId); - com.smartitengineering.cms.api.workspace.Workspace workSpaceForDelete = SmartContentAPI.getInstance(). - getWorkspaceApi().getWorkspace(workspaceForDeleteId); - Assert.assertNotNull(workSpaceForDelete); + com.smartitengineering.cms.api.workspace.Workspace workSpaceForDeleteWith300PlusContent = SmartContentAPI. + getInstance(). + getWorkspaceApi().getWorkspace(workspaceForDeleteWith300PlusContentId); + Assert.assertNotNull(workSpaceForDeleteWith300PlusContent); // create content type InputStream stream = getClass().getClassLoader().getResourceAsStream("content-type-for-delete.xml"); try { final ContentTypeLoader contentTypeLoader = SmartContentAPI.getInstance().getContentTypeLoader(); final Collection<WritableContentType> types; - types = contentTypeLoader.parseContentTypes(workSpaceForDelete.getId(), stream, + types = contentTypeLoader.parseContentTypes(workSpaceForDeleteWith300PlusContent.getId(), stream, com.smartitengineering.cms.api.common.MediaType.APPLICATION_XML); for (WritableContentType type : types) { type.put(); } + stream.close(); } catch (Exception ex) { LOGGER.info("Can not create ContentType for delete", ex); Assert.fail(); } ContentTypeId contentTypeId = SmartContentAPI.getInstance().getContentTypeLoader().createContentTypeId( - workspaceForDeleteId, "com.smartitengineering.smart-shopping.content", "ContentTypeForDelete"); + workspaceForDeleteWith300PlusContentId, "com.smartitengineering.smart-shopping.content", "ContentTypeForDelete"); ContentType contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); Assert.assertNotNull(contentType); // create content String statusKey = contentType.getStatuses().keySet().iterator().next(); ContentStatus contentStatus = contentType.getStatuses().get(statusKey); - WriteableContent writeableContent; - for (int i = 0; i < 150; i++) { - + for (int i = 0; i < 350; i++) { MutableContent mutableContent = SmartContentAPI.getInstance().getContentLoader().createContent(contentType); mutableContent.setContentDefinition(contentType); mutableContent.setPrivate(false); mutableContent.setStatus(contentStatus); MutableField mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); mutableField.setName("name"); MutableFieldValue<String> mutableFieldValue = new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); mutableFieldValue.setValue("russel"); mutableField.setValue(mutableFieldValue); mutableContent.setField(mutableField); //Create new content - writeableContent = SmartContentAPI.getInstance().getContentLoader().getWritableContent(mutableContent); - writeableContent.createContentId(workspaceForDeleteId); - + WriteableContent writeableContent = SmartContentAPI.getInstance().getContentLoader().getWritableContent( + mutableContent); + writeableContent.createContentId(workspaceForDeleteWith300PlusContentId); try { //Save or update the content, will be decided by writeable content implementation writeableContent.put(); } catch (IOException ex) { LOGGER.error(ex.getMessage(), ex); Assert.fail(); } } sleep(); - SmartContentAPI.getInstance().getWorkspaceApi().deleteWorkspace(workspaceForDeleteId); + SmartContentAPI.getInstance().getWorkspaceApi().deleteWorkspace(workspaceForDeleteWith300PlusContentId); sleep(); try { Thread.sleep(50000); } catch (Exception ex) { } com.smartitengineering.cms.api.workspace.Workspace fetchedWorkspace = SmartContentAPI.getInstance(). getWorkspaceApi(). - getWorkspace(workspaceForDeleteId); + getWorkspace(workspaceForDeleteWith300PlusContentId); if (fetchedWorkspace == null) { LOGGER.info("Fetched workspace null"); } Assert.assertNull(fetchedWorkspace); contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); Assert.assertNull(contentType); // test contents exists or not try { HTable table = new HTable(TEST_UTIL.getConfiguration(), "cms_content"); Scan s = new Scan(); s.addColumn(Bytes.toBytes("self"), Bytes.toBytes("contentType")); rs = table.getScanner(s); - LOGGER.info("WorkspaceForDelete Id: " + workspaceForDeleteId.toString()); + LOGGER.info("WorkspaceForDelete Id: " + workspaceForDeleteWith300PlusContentId.toString()); for (Result rr = rs.next(); rr != null; rr = rs.next()) { String rowId = Bytes.toString(rr.getRow()); - if (rowId.contains(workspaceForDeleteId.toString())) { + if (rowId.contains(workspaceForDeleteWith300PlusContentId.toString())) { LOGGER.info(rowId); Assert.fail(); } } } catch (Exception ex) { ex.printStackTrace(); } finally { rs.close(); } // test fields exists or not try { HTable table = new HTable(TEST_UTIL.getConfiguration(), "cms_fields"); Scan s = new Scan(); s.addColumn(Bytes.toBytes("self"), Bytes.toBytes("id")); rs = table.getScanner(s); - LOGGER.info("WorkspaceForDelete Id: " + workspaceForDeleteId.toString()); + LOGGER.info("WorkspaceForDelete Id: " + workspaceForDeleteWith300PlusContentId.toString()); for (Result rr = rs.next(); rr != null; rr = rs.next()) { String rowId = Bytes.toString(rr.getRow()); LOGGER.info("Fields: " + rowId); - if (rowId.contains(workspaceForDeleteId.toString())) { + if (rowId.contains(workspaceForDeleteWith300PlusContentId.toString())) { LOGGER.info(rowId); Assert.fail(); } } } catch (Exception ex) { ex.printStackTrace(); } finally { rs.close(); } final WriteableContent writeableContentForDeleteTest; MutableContent mutableContent = SmartContentAPI.getInstance().getContentLoader().createContent(contentType); mutableContent.setContentDefinition(contentType); mutableContent.setPrivate(false); mutableContent.setStatus(contentStatus); MutableField mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); mutableField.setName("name"); MutableFieldValue<String> mutableFieldValue = new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); mutableFieldValue.setValue("russel"); mutableField.setValue(mutableFieldValue); mutableContent.setField(mutableField); //Create new content writeableContentForDeleteTest = SmartContentAPI.getInstance().getContentLoader().getWritableContent(mutableContent); - writeableContentForDeleteTest.createContentId(workspaceForDeleteId); - + writeableContentForDeleteTest.createContentId(workspaceForDeleteWith300PlusContentId); try { //Save or update the content, will be decided by writeable content implementation writeableContentForDeleteTest.put(); Assert.fail(); } catch (IOException ex) { LOGGER.info("should fail"); } + // workspace with less than 100 content + + WorkspaceId workspaceForDeleteWith90ContentId = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspace( + WSForDeleteWith90Content); + + com.smartitengineering.cms.api.workspace.Workspace workSpaceForDeleteWith90Content = SmartContentAPI.getInstance(). + getWorkspaceApi().getWorkspace(workspaceForDeleteWith90ContentId); + Assert.assertNotNull(workSpaceForDeleteWith90Content); + + stream = getClass().getClassLoader().getResourceAsStream("content-type-for-delete.xml"); + + try { + final ContentTypeLoader contentTypeLoader = SmartContentAPI.getInstance().getContentTypeLoader(); + final Collection<WritableContentType> types; + types = contentTypeLoader.parseContentTypes(workSpaceForDeleteWith90Content.getId(), stream, + com.smartitengineering.cms.api.common.MediaType.APPLICATION_XML); + for (WritableContentType type : types) { + type.put(); + } + } + catch (Exception ex) { + LOGGER.info("Can not create ContentType for delete", ex); + Assert.fail(); + } + + contentTypeId = SmartContentAPI.getInstance().getContentTypeLoader().createContentTypeId( + workspaceForDeleteWith90ContentId, "com.smartitengineering.smart-shopping.content", "ContentTypeForDelete"); + Assert.assertNotNull(contentTypeId); + + contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); + Assert.assertNotNull(contentType); + + for (int i = 0; i < 90; i++) { + mutableContent = SmartContentAPI.getInstance().getContentLoader().createContent(contentType); + mutableContent.setContentDefinition(contentType); + mutableContent.setPrivate(false); + mutableContent.setStatus(contentStatus); + mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); + mutableField.setName("name"); + mutableFieldValue = new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); + mutableFieldValue.setValue("russel"); + mutableField.setValue(mutableFieldValue); + mutableContent.setField(mutableField); + //Create new content + WriteableContent writeableContent = SmartContentAPI.getInstance().getContentLoader().getWritableContent( + mutableContent); + writeableContent.createContentId(workspaceForDeleteWith90ContentId); + + try { + //Save or update the content, will be decided by writeable content implementation + writeableContent.put(); + } + catch (IOException ex) { + LOGGER.error(ex.getMessage(), ex); + Assert.fail(); + } + } + sleep(); + + SmartContentAPI.getInstance().getWorkspaceApi().deleteWorkspace(workspaceForDeleteWith90ContentId); + sleep(); + try { + Thread.sleep(50000); + } + catch (Exception ex) { + } + fetchedWorkspace = SmartContentAPI.getInstance(). + getWorkspaceApi(). + getWorkspace(workspaceForDeleteWith90ContentId); + if (fetchedWorkspace == null) { + LOGGER.info("Fetched workspace null"); + } + Assert.assertNull(fetchedWorkspace); + + contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); + Assert.assertNull(contentType); + + // test contents exists or not + + try { + HTable table = new HTable(TEST_UTIL.getConfiguration(), "cms_content"); + Scan s = new Scan(); + s.addColumn(Bytes.toBytes("self"), Bytes.toBytes("contentType")); + rs = table.getScanner(s); + LOGGER.info("WorkspaceForDelete Id: " + workspaceForDeleteWith90ContentId.toString()); + for (Result rr = rs.next(); rr != null; rr = rs.next()) { + String rowId = Bytes.toString(rr.getRow()); + if (rowId.contains(workspaceForDeleteWith90ContentId.toString())) { + LOGGER.info(rowId); + Assert.fail(); + } + } + + } + catch (Exception ex) { + ex.printStackTrace(); + } + finally { + rs.close(); + } + + // test fields exists or not + try { + HTable table = new HTable(TEST_UTIL.getConfiguration(), "cms_fields"); + Scan s = new Scan(); + s.addColumn(Bytes.toBytes("self"), Bytes.toBytes("id")); + rs = table.getScanner(s); + LOGGER.info("WorkspaceForDelete Id: " + workspaceForDeleteWith90ContentId.toString()); + for (Result rr = rs.next(); rr != null; rr = rs.next()) { + String rowId = Bytes.toString(rr.getRow()); + LOGGER.info("Fields: " + rowId); + if (rowId.contains(workspaceForDeleteWith90ContentId.toString())) { + LOGGER.info(rowId); + Assert.fail(); + } + } + } + catch (Exception ex) { + ex.printStackTrace(); + } + finally { + rs.close(); + } + + // workspace with no content + WorkspaceId workspaceForDeleteWithNoContentId = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspace( + WSForDeleteWithNoContent); + com.smartitengineering.cms.api.workspace.Workspace workSpaceForDeleteWithNoContent = SmartContentAPI.getInstance(). + getWorkspaceApi().getWorkspace(workspaceForDeleteWithNoContentId); + Assert.assertNotNull(workSpaceForDeleteWithNoContent); + + SmartContentAPI.getInstance().getWorkspaceApi().deleteWorkspace(workspaceForDeleteWithNoContentId); + sleep(); + fetchedWorkspace = SmartContentAPI.getInstance(). + getWorkspaceApi(). + getWorkspace(workspaceForDeleteWithNoContentId); + if (fetchedWorkspace == null) { + LOGGER.info("Fetched workspace null"); + } + Assert.assertNull(fetchedWorkspace); + } @Test public void testDeleteWorkspaceViaWebservice() { } protected void sleep() { try { Thread.sleep(SLEEP_DURATION); } catch (Exception ex) { LOGGER.error("Error sleeping", ex); } } public static class ConfigurationModule extends AbstractModule { @Override protected void configure() { bind(Configuration.class).toInstance(TEST_UTIL.getConfiguration()); ConnectionConfig config = new ConnectionConfig(); config.setBasicUri(""); config.setContextPath("/"); config.setHost("localhost"); config.setPort(PORT); bind(ConnectionConfig.class).toInstance(config); } } }
SmartITEngineering/smart-cms
859e7c01ce6265a622fef216c97c532cc5c466e3
Added blank check in query parameter and set the log as debug
diff --git a/spi-modules/content-spi-hbase-impl/src/main/java/com/smartitengineering/cms/spi/impl/workspace/WorkspaceServiceImpl.java b/spi-modules/content-spi-hbase-impl/src/main/java/com/smartitengineering/cms/spi/impl/workspace/WorkspaceServiceImpl.java index baf8b20..b6575ae 100644 --- a/spi-modules/content-spi-hbase-impl/src/main/java/com/smartitengineering/cms/spi/impl/workspace/WorkspaceServiceImpl.java +++ b/spi-modules/content-spi-hbase-impl/src/main/java/com/smartitengineering/cms/spi/impl/workspace/WorkspaceServiceImpl.java @@ -1,681 +1,687 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.spi.impl.workspace; import com.google.inject.Inject; import com.smartitengineering.cms.api.common.TemplateType; import com.smartitengineering.cms.api.content.ContentId; import com.smartitengineering.cms.api.factory.SmartContentAPI; import com.smartitengineering.cms.api.factory.content.WriteableContent; import com.smartitengineering.cms.api.factory.type.WritableContentType; import com.smartitengineering.cms.api.type.ContentType; import com.smartitengineering.cms.api.workspace.ContentCoProcessorTemplate; import com.smartitengineering.cms.api.workspace.RepresentationTemplate; import com.smartitengineering.cms.api.workspace.ResourceTemplate; import com.smartitengineering.cms.api.workspace.Sequence; import com.smartitengineering.cms.api.workspace.ValidatorTemplate; import com.smartitengineering.cms.api.workspace.VariationTemplate; import com.smartitengineering.cms.api.workspace.Workspace; import com.smartitengineering.cms.api.factory.workspace.WorkspaceAPI.ResourceSortCriteria; import com.smartitengineering.cms.api.type.ValidatorType; import com.smartitengineering.cms.api.workspace.SequenceId; import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.cms.spi.SmartContentSPI; import com.smartitengineering.cms.spi.impl.content.ContentPersistentService; import com.smartitengineering.cms.spi.impl.content.PersistentContent; import com.smartitengineering.cms.spi.impl.type.ContentTypePersistentService; import com.smartitengineering.cms.spi.impl.type.PersistentContentType; import com.smartitengineering.cms.spi.type.PersistentContentTypeReader; import com.smartitengineering.cms.spi.workspace.PersistableContentCoProcessorTemplate; import com.smartitengineering.cms.spi.workspace.PersistableRepresentationTemplate; import com.smartitengineering.cms.spi.workspace.PersistableResourceTemplate; import com.smartitengineering.cms.spi.workspace.PersistableSequence; import com.smartitengineering.cms.spi.workspace.PersistableValidatorTemplate; import com.smartitengineering.cms.spi.workspace.PersistableVariationTemplate; import com.smartitengineering.cms.spi.workspace.PersistableWorkspace; import com.smartitengineering.cms.spi.workspace.SequenceSearcher; import com.smartitengineering.cms.spi.workspace.WorkspaceService; import com.smartitengineering.dao.common.CommonReadDao; import com.smartitengineering.dao.common.CommonWriteDao; import com.smartitengineering.dao.common.queryparam.MatchMode; import com.smartitengineering.dao.common.queryparam.Order; import com.smartitengineering.dao.common.queryparam.QueryParameter; import com.smartitengineering.dao.common.queryparam.QueryParameterFactory; import com.smartitengineering.dao.impl.hbase.spi.RowCellIncrementor; import com.smartitengineering.util.bean.adapter.GenericAdapter; import java.util.*; import java.util.concurrent.ExecutorService; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author imyousuf */ public class WorkspaceServiceImpl extends AbstractWorkspaceService implements WorkspaceService { protected final transient Logger logger = LoggerFactory.getLogger(getClass()); public static final QueryParameter<Void> SELF_PARAM = QueryParameterFactory.getPropProjectionParam("workspace"); @Inject protected CommonReadDao<PersistentSequence, SequenceId> commonSeqReadDao; @Inject protected CommonWriteDao<PersistentSequence> commonSeqWriteDao; @Inject protected RowCellIncrementor<Sequence, PersistentSequence, SequenceId> sequenceModifier; @Inject protected SequenceSearcher sequenceSearcher; @Inject private GenericAdapter<Sequence, PersistentSequence> sequenceAdapter; @Inject private ExecutorService executorService; private static final Comparator<ResourceTemplate> TEMPLATE_DATE_COMPARATOR = new Comparator<ResourceTemplate>() { @Override public int compare(ResourceTemplate o1, ResourceTemplate o2) { return o1.getLastModifiedDate().compareTo(o2.getLastModifiedDate()); } }; private static final Comparator<ResourceTemplate> TEMPLATE_NAME_COMPARATOR = new Comparator<ResourceTemplate>() { @Override public int compare(ResourceTemplate o1, ResourceTemplate o2) { return o1.getName().compareTo(o2.getName()); } }; private static final Comparator<ValidatorTemplate> VALIDATOR_DATE_COMPARATOR = new Comparator<ValidatorTemplate>() { @Override public int compare(ValidatorTemplate o1, ValidatorTemplate o2) { return o1.getLastModifiedDate().compareTo(o2.getLastModifiedDate()); } }; private static final Comparator<ValidatorTemplate> VALIDATOR_NAME_COMPARATOR = new Comparator<ValidatorTemplate>() { @Override public int compare(ValidatorTemplate o1, ValidatorTemplate o2) { return o1.getName().compareTo(o2.getName()); } }; public PersistentContentTypeReader getContentTypeReader() { return contentTypeReader; } @Override public Workspace create(WorkspaceId workspaceId) throws IllegalArgumentException { PersistableWorkspace workspace = SmartContentSPI.getInstance().getPersistableDomainFactory(). createPersistentWorkspace(); workspace.setCreationDate(new Date()); workspace.setId(workspaceId); commonWriteDao.save(adapter.convert(workspace)); return workspace; } @Override public Workspace load(WorkspaceId workspaceId) { return adapter.convertInversely(getByIdWorkspaceOnly(workspaceId)); } @Override public Workspace delete(WorkspaceId workspaceId) { Workspace workspace = load(workspaceId); if (workspace == null) { throw new IllegalArgumentException("No workspace found with workspaceId " + workspaceId); } commonWriteDao.delete(adapter.convert(workspace)); return workspace; } @Override public void deleteWorkspaceWithDependencies(final WorkspaceId workspaceId) { // first collect sequences before workspace delete final Collection<Sequence> sequences = SmartContentAPI.getInstance().getWorkspaceApi().getSequencesForWorkspace( workspaceId); // delete it from persistent storage delete(workspaceId); executorService.submit(new Runnable() { public void run() { ContentPersistentService contentPersistentService = (ContentPersistentService) SmartContentSPI.getInstance(). getPersistentService(WriteableContent.class); String lastId = ""; List<QueryParameter> qps = new ArrayList<QueryParameter>(); qps.add(QueryParameterFactory.getStringLikePropertyParam("id", workspaceId.toString(), MatchMode.START)); qps.add(QueryParameterFactory.getMaxResultsParam(100)); qps.add(QueryParameterFactory.getOrderByParam("id", Order.ASC)); List<PersistentContent> contents = new ArrayList<PersistentContent>(); do { - logger.info("Last ID: " + lastId); - qps.add(QueryParameterFactory.getGreaterThanPropertyParam("id", lastId)); + if (logger.isDebugEnabled()) { + logger.debug("Last ID: " + lastId); + } + if (StringUtils.isNotBlank(lastId)) { + qps.add(QueryParameterFactory.getGreaterThanPropertyParam("id", lastId)); + } contents = contentPersistentService.getCommonReadDao().getList(qps); - logger.info("Contents size : " + contents.size()); + if (logger.isDebugEnabled()) { + logger.debug("Contents size : " + contents.size()); + } if (!contents.isEmpty()) { lastId = contents.get(contents.size() - 1).getId().toString(); } for (PersistentContent persistentContent : contents) { contentPersistentService.getCommonWriteDao().delete(persistentContent); } } while (!contents.isEmpty()); ContentTypePersistentService contentTypePersistentService = (ContentTypePersistentService) SmartContentSPI. getInstance().getPersistentService(WritableContentType.class); Set<PersistentContentType> persistentContentTypes = contentTypePersistentService.getCommonReadDao().getAll(); for (PersistentContentType persistentContentType : persistentContentTypes) { contentTypePersistentService.getCommonWriteDao().delete(persistentContentType); } // delete sequence for (Sequence sequence : sequences) { commonSeqWriteDao.delete(sequenceAdapter.convert(sequence)); } } }); } @Override public Collection<Workspace> getWorkspaces() { final List<PersistentWorkspace> list = commonReadDao.getList(SELF_PARAM, QueryParameterFactory. getStringLikePropertyParam("id", "", MatchMode.START)); if (list == null || list.isEmpty()) { return Collections.emptyList(); } return Collections.unmodifiableCollection(adapter.convertInversely( list.toArray(new PersistentWorkspace[list.size()]))); } @Override public Collection<ContentType> getContentDefintions(WorkspaceId workspaceId) { return Collections.unmodifiableCollection(getContentTypeReader().getByWorkspace(workspaceId)); } @Override public Collection<WorkspaceId> getFriendlies(WorkspaceId workspaceId) { final QueryParameter friendliesProp = QueryParameterFactory.getPropProjectionParam("friendlies"); final QueryParameter idParam = getIdParam(workspaceId); PersistentWorkspace workspace = commonReadDao.getSingle(idParam, SELF_PARAM, friendliesProp); return workspace.getFriendlies(); } @Override public void addFriend(WorkspaceId to, WorkspaceId... workspaceIds) { PersistentWorkspace workspace = getWorkspace(to); for (WorkspaceId id : workspaceIds) { workspace.addFriendly(id); } workspace.setFriendliesPopulated(true); commonWriteDao.update(workspace); } @Override public void removeFriend(WorkspaceId from, WorkspaceId workspaceId) { PersistentWorkspace workspace = getWorkspace(from); workspace.addFriendly(workspaceId); workspace.setFriendliesPopulated(true); commonWriteDao.delete(workspace); } protected PersistentWorkspace getWorkspace(WorkspaceId from) { PersistentWorkspace workspace = new PersistentWorkspace(); workspace.setWorkspace(load(from)); return workspace; } @Override public RepresentationTemplate putRepresentationTemplate(WorkspaceId workspaceId, String name, TemplateType templateType, byte[] data) { PersistentWorkspace workspace = getWorkspace(workspaceId); PersistableRepresentationTemplate template = SmartContentSPI.getInstance().getPersistableDomainFactory(). createPersistableRepresentationTemplate(); workspace.addRepresentationTemplate(template); template.setName(name); template.setTemplateType(templateType); template.setWorkspaceId(workspaceId); template.setTemplate(data); RepresentationTemplate oldTemplate = getRepresentationTemplate(workspaceId, name); updateFields(template, oldTemplate); workspace.setRepresentationPopulated(true); commonWriteDao.update(workspace); return template; } @Override public RepresentationTemplate getRepresentationTemplate(WorkspaceId workspaceId, String name) { List<QueryParameter> params = new ArrayList<QueryParameter>(); final String info = WorkspaceObjectConverter.REP_INFO; if (logger.isDebugEnabled()) { logger.debug("Sample column name " + new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.TEMPLATETYPE).toString()); } params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.TEMPLATETYPE).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.CREATED).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.LASTMODIFIED).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.ENTITY_TAG).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(WorkspaceObjectConverter.REP_DATA).append( ':').append(name).toString())); params.add(SELF_PARAM); params.add(getIdParam(workspaceId)); final List<PersistableRepresentationTemplate> list = commonReadDao.getSingle(params).getRepresentationTemplates(); if (list.isEmpty()) { return null; } return list.get(0); } @Override public VariationTemplate putVariationTemplate(WorkspaceId workspaceId, String name, TemplateType templateType, byte[] data) { PersistentWorkspace workspace = getWorkspace(workspaceId); PersistableVariationTemplate template = SmartContentSPI.getInstance().getPersistableDomainFactory(). createPersistableVariationTemplate(); workspace.addVariationTemplate(template); template.setName(name); template.setTemplateType(templateType); template.setWorkspaceId(workspaceId); template.setTemplate(data); VariationTemplate oldTemplate = getVariationTemplate(workspaceId, name); updateFields(template, oldTemplate); workspace.setVariationPopulated(true); commonWriteDao.update(workspace); return template; } @Override public VariationTemplate getVariationTemplate(WorkspaceId workspaceId, String name) { List<QueryParameter> params = new ArrayList<QueryParameter>(); final String info = WorkspaceObjectConverter.VAR_INFO; params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.TEMPLATETYPE).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.CREATED).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.LASTMODIFIED).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.ENTITY_TAG).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(WorkspaceObjectConverter.VAR_DATA).append( ':').append(name).toString())); params.add(SELF_PARAM); params.add(getIdParam(workspaceId)); final List<PersistableVariationTemplate> list = commonReadDao.getSingle(params).getVariationTemplates(); if (list.isEmpty()) { return null; } return list.get(0); } @Override public void deleteRepresentation(RepresentationTemplate template) { PersistentWorkspace workspace = getWorkspace(template.getWorkspaceId()); workspace.setRepresentationPopulated(true); PersistableRepresentationTemplate repTemplate = SmartContentSPI.getInstance().getPersistableDomainFactory(). createPersistableRepresentationTemplate(); repTemplate.setCreatedDate(template.getCreatedDate()); repTemplate.setLastModifiedDate(template.getLastModifiedDate()); repTemplate.setWorkspaceId(template.getWorkspaceId()); repTemplate.setName(template.getName()); repTemplate.setTemplate(template.getTemplate()); repTemplate.setTemplateType(template.getTemplateType()); workspace.addRepresentationTemplate(repTemplate); commonWriteDao.delete(workspace); } @Override public void deleteVariation(VariationTemplate template) { PersistentWorkspace workspace = getWorkspace(template.getWorkspaceId()); workspace.setVariationPopulated(true); PersistableVariationTemplate varTemplate = SmartContentSPI.getInstance().getPersistableDomainFactory(). createPersistableVariationTemplate(); varTemplate.setCreatedDate(template.getCreatedDate()); varTemplate.setLastModifiedDate(template.getLastModifiedDate()); varTemplate.setWorkspaceId(template.getWorkspaceId()); varTemplate.setName(template.getName()); varTemplate.setTemplate(template.getTemplate()); varTemplate.setTemplateType(template.getTemplateType()); workspace.addVariationTemplate(varTemplate); commonWriteDao.delete(workspace); } protected QueryParameter<String> getIdParam(WorkspaceId workspaceId) { return QueryParameterFactory.getStringLikePropertyParam("id", workspaceId.toString(), MatchMode.EXACT); } @Override public void removeAllFriendlies(WorkspaceId workspaceId) { PersistentWorkspace workspace = getWorkspace(workspaceId); workspace.setFriendliesPopulated(true); commonWriteDao.delete(workspace); } @Override public void removeAllRepresentationTemplates(WorkspaceId workspaceId) { PersistentWorkspace workspace = getWorkspace(workspaceId); workspace.setRepresentationPopulated(true); commonWriteDao.delete(workspace); } @Override public void removeAllVariationTemplates(WorkspaceId workspaceId) { PersistentWorkspace workspace = getWorkspace(workspaceId); workspace.setVariationPopulated(true); commonWriteDao.delete(workspace); } @Override public Collection<RepresentationTemplate> getRepresentationsWithoutData(WorkspaceId id, ResourceSortCriteria criteria) { List<QueryParameter> params = new ArrayList<QueryParameter>(); final String info = WorkspaceObjectConverter.REP_INFO; params.add(QueryParameterFactory.getPropProjectionParam(info)); params.add(getIdParam(id)); final PersistentWorkspace single = commonReadDao.getSingle(params); List<? extends RepresentationTemplate> templates = new ArrayList(single == null ? Collections.<RepresentationTemplate>emptyList() : single.getRepresentationTemplates()); if (templates.isEmpty()) { return Collections.emptyList(); } final Comparator<ResourceTemplate> comp; if (ResourceSortCriteria.BY_DATE.equals(criteria)) { comp = TEMPLATE_DATE_COMPARATOR; } else { comp = TEMPLATE_NAME_COMPARATOR; } Collections.sort(templates, comp); return Collections.unmodifiableCollection(templates); } @Override public Collection<VariationTemplate> getVariationsWithoutData(WorkspaceId id, ResourceSortCriteria criteria) { List<QueryParameter> params = new ArrayList<QueryParameter>(); final String info = WorkspaceObjectConverter.VAR_INFO; params.add(QueryParameterFactory.getPropProjectionParam(info)); params.add(getIdParam(id)); final PersistentWorkspace single = commonReadDao.getSingle(params); List<? extends VariationTemplate> templates = new ArrayList(single == null ? Collections.<VariationTemplate> emptyList() : single.getVariationTemplates()); if (templates.isEmpty()) { return Collections.emptyList(); } final Comparator<ResourceTemplate> comp; if (ResourceSortCriteria.BY_DATE.equals(criteria)) { comp = TEMPLATE_DATE_COMPARATOR; } else { comp = TEMPLATE_NAME_COMPARATOR; } Collections.sort(templates, comp); return Collections.unmodifiableCollection(templates); } private void updateFields(PersistableResourceTemplate template, ResourceTemplate oldTemplate) { final Date date = new Date(); if (oldTemplate != null) { template.setCreatedDate(oldTemplate.getCreatedDate()); } else { template.setCreatedDate(date); } template.setLastModifiedDate(date); template.setEntityTagValue(SmartContentAPI.getInstance().getWorkspaceApi().getEntityTagValueForResourceTemplate( template)); } private void updateFields(PersistableValidatorTemplate template, ValidatorTemplate oldTemplate) { final Date date = new Date(); if (oldTemplate != null) { template.setCreatedDate(oldTemplate.getCreatedDate()); } else { template.setCreatedDate(date); } template.setLastModifiedDate(date); template.setEntityTagValue(SmartContentAPI.getInstance().getWorkspaceApi().getEntityTagValueForValidatorTemplate( template)); } @Override public Collection<ContentId> getRootContents(WorkspaceId workspaceId) { final QueryParameter rootContentsProp = QueryParameterFactory.getPropProjectionParam("rootContents"); final QueryParameter idParam = getIdParam(workspaceId); PersistentWorkspace workspace = commonReadDao.getSingle(idParam, SELF_PARAM, rootContentsProp); return workspace.getRootContents(); } @Override public void addRootContent(WorkspaceId to, ContentId... contentIds) { PersistentWorkspace workspace = getWorkspace(to); for (ContentId id : contentIds) { workspace.addRootContent(id); } workspace.setRootContentsPopulated(true); commonWriteDao.update(workspace); } @Override public void removeRootContent(WorkspaceId from, ContentId contentId) { PersistentWorkspace workspace = getWorkspace(from); workspace.addRootContent(contentId); workspace.setRootContentsPopulated(true); commonWriteDao.delete(workspace); } @Override public void removeAllRootContents(WorkspaceId workspaceId) { PersistentWorkspace workspace = getWorkspace(workspaceId); workspace.setRootContentsPopulated(true); commonWriteDao.delete(workspace); } @Override public ValidatorTemplate getValidationTemplate(WorkspaceId workspaceId, String name) { List<QueryParameter> params = new ArrayList<QueryParameter>(); final String info = WorkspaceObjectConverter.VAL_INFO; params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.TEMPLATETYPE).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.CREATED).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.LASTMODIFIED).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.ENTITY_TAG).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(WorkspaceObjectConverter.VAL_DATA).append( ':').append(name).toString())); params.add(SELF_PARAM); params.add(getIdParam(workspaceId)); final PersistentWorkspace single = commonReadDao.getSingle(params); if (logger.isDebugEnabled()) { logger.debug("Workspace ID " + single.getId().toString()); logger.debug("Validators " + single.isValidatorsPopulated()); logger.debug("Validators " + single.getValidatorTemplates()); } final List<PersistableValidatorTemplate> list = single.getValidatorTemplates(); if (list.isEmpty()) { return null; } return list.get(0); } @Override public void deleteValidator(ValidatorTemplate template) { PersistentWorkspace workspace = getWorkspace(template.getWorkspaceId()); workspace.setValidatorsPopulated(true); PersistableValidatorTemplate valTemplate = SmartContentSPI.getInstance().getPersistableDomainFactory(). createPersistableValidatorTemplate(); valTemplate.setCreatedDate(template.getCreatedDate()); valTemplate.setLastModifiedDate(template.getLastModifiedDate()); valTemplate.setWorkspaceId(template.getWorkspaceId()); valTemplate.setName(template.getName()); valTemplate.setTemplate(template.getTemplate()); valTemplate.setTemplateType(template.getTemplateType()); workspace.addValidatorTemplate(valTemplate); commonWriteDao.delete(workspace); } @Override public ValidatorTemplate putValidatorTemplate(WorkspaceId workspaceId, String name, ValidatorType templateType, byte[] data) { PersistentWorkspace workspace = getWorkspace(workspaceId); PersistableValidatorTemplate template = SmartContentSPI.getInstance().getPersistableDomainFactory(). createPersistableValidatorTemplate(); workspace.addValidatorTemplate(template); template.setName(name); template.setTemplateType(templateType); template.setWorkspaceId(workspaceId); template.setTemplate(data); ValidatorTemplate oldTemplate = getValidationTemplate(workspaceId, name); updateFields(template, oldTemplate); workspace.setValidatorsPopulated(true); commonWriteDao.update(workspace); return template; } @Override public Collection<ValidatorTemplate> getValidatorsWithoutData(WorkspaceId id, ResourceSortCriteria criteria) { List<QueryParameter> params = new ArrayList<QueryParameter>(); final String info = WorkspaceObjectConverter.VAL_INFO; params.add(QueryParameterFactory.getPropProjectionParam(info)); params.add(getIdParam(id)); final PersistentWorkspace single = commonReadDao.getSingle(params); List<? extends ValidatorTemplate> templates = new ArrayList(single == null ? Collections.<ValidatorTemplate> emptyList() : single.getValidatorTemplates()); if (templates.isEmpty()) { return Collections.emptyList(); } final Comparator<ValidatorTemplate> comp; if (ResourceSortCriteria.BY_DATE.equals(criteria)) { comp = VALIDATOR_DATE_COMPARATOR; } else { comp = VALIDATOR_NAME_COMPARATOR; } Collections.sort(templates, comp); return Collections.unmodifiableCollection(templates); } @Override public void removeAllValidatorTemplates(WorkspaceId workspaceId) { PersistentWorkspace workspace = getWorkspace(workspaceId); workspace.setValidatorsPopulated(true); commonWriteDao.delete(workspace); } public ContentCoProcessorTemplate putContentCoProcessorTemplate(WorkspaceId workspaceId, String name, TemplateType templateType, byte[] data) { PersistentWorkspace workspace = getWorkspace(workspaceId); PersistableContentCoProcessorTemplate template = SmartContentSPI.getInstance().getPersistableDomainFactory(). createPersistableContentCoProcessorTemplate(); workspace.addContentCoProcessorTemplate(template); template.setName(name); template.setTemplateType(templateType); template.setWorkspaceId(workspaceId); template.setTemplate(data); ContentCoProcessorTemplate oldTemplate = getContentCoProcessorTemplate(workspaceId, name); updateFields(template, oldTemplate); workspace.setContentCoProcessorPopulated(true); commonWriteDao.update(workspace); return template; } public ContentCoProcessorTemplate getContentCoProcessorTemplate(WorkspaceId workspaceId, String name) { List<QueryParameter> params = new ArrayList<QueryParameter>(); final String info = WorkspaceObjectConverter.CCP_INFO; if (logger.isDebugEnabled()) { logger.debug("Sample column name " + new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.TEMPLATETYPE).toString()); } params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.TEMPLATETYPE).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.CREATED).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.LASTMODIFIED).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(info).append(':').append(name).append(':'). append(WorkspaceObjectConverter.ENTITY_TAG).toString())); params.add(QueryParameterFactory.getPropProjectionParam(new StringBuilder(WorkspaceObjectConverter.CCP_DATA).append( ':').append(name).toString())); params.add(SELF_PARAM); params.add(getIdParam(workspaceId)); final PersistentWorkspace singleWs = commonReadDao.getSingle(params); if (logger.isDebugEnabled()) { logger.debug("Loaded CCP " + singleWs.isContentCoProcessorPopulated()); } final List<PersistableContentCoProcessorTemplate> list = singleWs.getContentCoProcessorTemplates(); if (list.isEmpty()) { if (logger.isWarnEnabled()) { logger.warn("No content co processor with name " + name + " in " + workspaceId); } return null; } return list.get(0); } public void removeAllContentCoProcessorTemplates(WorkspaceId workspaceId) { PersistentWorkspace workspace = getWorkspace(workspaceId); workspace.setContentCoProcessorPopulated(true); commonWriteDao.delete(workspace); } public Collection<ContentCoProcessorTemplate> getContentCoProcessorsWithoutData(WorkspaceId id, ResourceSortCriteria criteria) { List<QueryParameter> params = new ArrayList<QueryParameter>(); final String info = WorkspaceObjectConverter.CCP_INFO; params.add(QueryParameterFactory.getPropProjectionParam(info)); params.add(getIdParam(id)); final PersistentWorkspace single = commonReadDao.getSingle(params); if (logger.isDebugEnabled()) { if (single == null) { logger.debug("Query result is null!"); } else { logger.debug("Loaded CCP " + single.isContentCoProcessorPopulated() + " " + single.getContentCoProcessorTemplates()); } } List<? extends ContentCoProcessorTemplate> templates = new ArrayList(single == null ? Collections.<ContentCoProcessorTemplate>emptyList() : single.getContentCoProcessorTemplates()); if (templates.isEmpty()) { return Collections.emptyList(); } final Comparator<ResourceTemplate> comp; if (ResourceSortCriteria.BY_DATE.equals(criteria)) { comp = TEMPLATE_DATE_COMPARATOR; } else { comp = TEMPLATE_NAME_COMPARATOR; } Collections.sort(templates, comp); return Collections.unmodifiableCollection(templates); } public void deleteContentCoProcessor(ContentCoProcessorTemplate template) { PersistentWorkspace workspace = getWorkspace(template.getWorkspaceId()); workspace.setContentCoProcessorPopulated(true); PersistableContentCoProcessorTemplate varTemplate = SmartContentSPI.getInstance().getPersistableDomainFactory(). createPersistableContentCoProcessorTemplate(); varTemplate.setCreatedDate(template.getCreatedDate()); varTemplate.setLastModifiedDate(template.getLastModifiedDate());
SmartITEngineering/smart-cms
779dbcb098e2fdc0af5ab513363100389485e3e7
Removed * imports
diff --git a/api-modules/content-api-factory/src/main/java/com/smartitengineering/cms/api/factory/workspace/WorkspaceAPI.java b/api-modules/content-api-factory/src/main/java/com/smartitengineering/cms/api/factory/workspace/WorkspaceAPI.java index 6a3431f..59ba0a0 100644 --- a/api-modules/content-api-factory/src/main/java/com/smartitengineering/cms/api/factory/workspace/WorkspaceAPI.java +++ b/api-modules/content-api-factory/src/main/java/com/smartitengineering/cms/api/factory/workspace/WorkspaceAPI.java @@ -1,218 +1,225 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.api.factory.workspace; import com.smartitengineering.cms.api.common.TemplateType; import com.smartitengineering.cms.api.content.ContentId; import com.smartitengineering.cms.api.content.template.ContentCoProcessor; import com.smartitengineering.cms.api.content.template.FieldValidator; import com.smartitengineering.cms.api.content.template.RepresentationGenerator; import com.smartitengineering.cms.api.content.template.VariationGenerator; import com.smartitengineering.cms.api.type.ValidatorType; -import com.smartitengineering.cms.api.workspace.*; +import com.smartitengineering.cms.api.workspace.ContentCoProcessorTemplate; +import com.smartitengineering.cms.api.workspace.RepresentationTemplate; +import com.smartitengineering.cms.api.workspace.ResourceTemplate; +import com.smartitengineering.cms.api.workspace.Sequence; +import com.smartitengineering.cms.api.workspace.SequenceId; +import com.smartitengineering.cms.api.workspace.ValidatorTemplate; +import com.smartitengineering.cms.api.workspace.VariationTemplate; +import com.smartitengineering.cms.api.workspace.Workspace; +import com.smartitengineering.cms.api.workspace.WorkspaceId; import java.io.IOException; import java.io.InputStream; import java.util.Collection; /** * * @author imyousuf */ public interface WorkspaceAPI { String getGlobalNamespace(); WorkspaceId createWorkspaceId(String globalNamespace, String name); WorkspaceId createWorkspaceId(String name); WorkspaceId createWorkspace(String name); WorkspaceId createWorkspace(String globalNamespace, String name); WorkspaceId createWorkspace(WorkspaceId workspaceId); RepresentationTemplate putRepresentationTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException; RepresentationTemplate putRepresentationTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data); RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name); void delete(RepresentationTemplate template); void delete(VariationTemplate template); VariationTemplate putVariationTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException; VariationTemplate putVariationTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data); VariationTemplate getVariationTemplate(WorkspaceId id, String name); void delete(ContentCoProcessorTemplate template); ContentCoProcessorTemplate putContentCoProcessorTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException; ContentCoProcessorTemplate putContentCoProcessorTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data); ContentCoProcessorTemplate getContentCoProcessorTemplate(WorkspaceId id, String name); ContentCoProcessor getContentCoProcessor(WorkspaceId id, String name); public ContentCoProcessorTemplate getContentCoProcessorTemplate(WorkspaceId id, String name, boolean searchInFriendlies); public RepresentationTemplate getRepresentationTemplate(WorkspaceId workspaceId, String name, boolean searchInFriendlies); public ValidatorTemplate getValidatorTemplate(WorkspaceId id, String name, boolean searchInFriendlies); public VariationTemplate getVariationTemplate(WorkspaceId workspaceId, String name, boolean searchInFriendlies); RepresentationGenerator getRepresentationGenerator(WorkspaceId id, String name); VariationGenerator getVariationGenerator(WorkspaceId id, String name); FieldValidator getFieldValidator(WorkspaceId id, String name); ContentCoProcessor getContentCoProcessor(ContentCoProcessorTemplate template); RepresentationGenerator getRepresentationGenerator(RepresentationTemplate template); VariationGenerator getVariationGenerator(VariationTemplate template); FieldValidator getFieldValidator(ValidatorTemplate template); ContentCoProcessor getContentCoProcessor(WorkspaceId id, String name, boolean searchInFriendlies); RepresentationGenerator getRepresentationGenerator(WorkspaceId id, String name, boolean searchInFriendlies); VariationGenerator getVariationGenerator(WorkspaceId id, String name, boolean searchInFriendlies); FieldValidator getFieldValidator(WorkspaceId id, String name, boolean searchInFriendlies); WorkspaceId getWorkspaceIdIfExists(String name); WorkspaceId getWorkspaceIdIfExists(WorkspaceId workspaceId); Workspace getWorkspace(WorkspaceId workspaceId); Collection<Workspace> getWorkspaces(); public Collection<WorkspaceId> getFriendlies(WorkspaceId workspaceId); public void addFriend(WorkspaceId to, WorkspaceId... workspaceIds); public void removeFriend(WorkspaceId from, WorkspaceId workspaceId); public void removeAllFriendlies(WorkspaceId workspaceId); public void removeAllRepresentationTemplates(WorkspaceId workspaceId); public void removeAllVariationTemplates(WorkspaceId workspaceId); public void removeAllContentCoProcessorTemplates(WorkspaceId workspaceId); enum ResourceSortCriteria { BY_NAME, - BY_DATE, - } + BY_DATE,} public Collection<String> getRepresentationNames(WorkspaceId id); public Collection<String> getVariationNames(WorkspaceId id); public Collection<String> getRepresentationNames(WorkspaceId id, String startPoint, int count); public Collection<String> getVariationNames(WorkspaceId id, String startPoint, int count); public Collection<String> getRepresentationNames(WorkspaceId id, ResourceSortCriteria criteria); public Collection<String> getVariationNames(WorkspaceId id, ResourceSortCriteria criteria); public Collection<String> getContentCoProcessorNames(WorkspaceId id); public Collection<String> getContentCoProcessorNames(WorkspaceId id, String startPoint, int count); public Collection<String> getContentCoProcessorNames(WorkspaceId id, ResourceSortCriteria criteria); public Collection<String> getContentCoProcessorNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count); public Collection<String> getRepresentationNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count); public Collection<String> getVariationNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count); public String getEntityTagValueForResourceTemplate(ResourceTemplate resourceTemplate); public Collection<ContentId> getRootContents(WorkspaceId workspaceId); public void addRootContent(WorkspaceId to, ContentId... contentIds); public void removeRootContent(WorkspaceId from, ContentId contentId); public void removeAllRootContents(WorkspaceId workspaceId); ValidatorTemplate putValidatorTemplate(WorkspaceId to, String name, ValidatorType templateType, InputStream stream) throws IOException; ValidatorTemplate putValidatorTemplate(WorkspaceId to, String name, ValidatorType templateType, byte[] data); void delete(ValidatorTemplate template); public ValidatorTemplate getValidatorTemplate(WorkspaceId workspaceId, String name); public void removeAllValidatorTemplates(WorkspaceId workspaceId); public Collection<String> getValidatorNames(WorkspaceId id); public Collection<String> getValidatorNames(WorkspaceId id, String startPoint, int count); public Collection<String> getValidatorNames(WorkspaceId id, ResourceSortCriteria criteria); public Collection<String> getValidatorNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count); public String getEntityTagValueForValidatorTemplate(ValidatorTemplate validatorTemplate); public Sequence putSequence(WorkspaceId workspaceId, String name, long initialValue); public long modifySequenceValue(Sequence sequence, long delta); public Sequence getSequence(WorkspaceId workspaceId, String name); public void deleteSequence(WorkspaceId workspaceId, String name); public Collection<Sequence> getSequencesForWorkspace(WorkspaceId workspaceId); public void reIndex(WorkspaceId workspaceId); public void reIndex(SequenceId seqId); public SequenceId createSequenceId(WorkspaceId workspaceId, String name); public void deleteWorkspace(WorkspaceId workspaceId); } diff --git a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java index ab226a8..8847f41 100644 --- a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java +++ b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java @@ -1,424 +1,435 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.api.impl.content; -import com.smartitengineering.cms.api.content.*; +import com.smartitengineering.cms.api.content.Content; +import com.smartitengineering.cms.api.content.ContentId; +import com.smartitengineering.cms.api.content.Field; +import com.smartitengineering.cms.api.content.Representation; +import com.smartitengineering.cms.api.content.FieldValue; import com.smartitengineering.cms.api.content.template.ContentCoProcessor; import com.smartitengineering.cms.api.event.Event; import com.smartitengineering.cms.api.event.Event.EventType; import com.smartitengineering.cms.api.event.Event.Type; import com.smartitengineering.cms.api.factory.SmartContentAPI; import com.smartitengineering.cms.api.factory.content.WriteableContent; import com.smartitengineering.cms.api.impl.AbstractPersistableDomain; import com.smartitengineering.cms.api.type.ContentCoProcessorDef; import com.smartitengineering.cms.api.type.ContentStatus; import com.smartitengineering.cms.api.type.ContentType; import com.smartitengineering.cms.api.type.ContentType.ContentProcessingPhase; import com.smartitengineering.cms.api.type.FieldDef; import com.smartitengineering.cms.api.workspace.Workspace; import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.cms.spi.SmartContentSPI; import com.smartitengineering.cms.spi.content.PersistableContent; import java.io.IOException; import java.net.URI; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.LinkedHashMap; +import java.util.Map; import org.apache.commons.lang.ObjectUtils; /** * * @author kaisar */ public class ContentImpl extends AbstractPersistableDomain<WriteableContent, ContentId> implements PersistableContent { private ContentId contentId; private ContentId parentId; private ContentType contentDef; private ContentStatus contentStatus; private Date creationDate; private Date lastModifiedDate; private Map<String, Field> map; private Map<String, Field> cachedFieldMap; private String entityTagValue; private boolean privateContent; private boolean supressChecking; public ContentImpl() { super(LOCK_KEY_PREFIX); } public boolean isSupressChecking() { return supressChecking; } public void setSupressChecking(boolean supressChecking) { this.supressChecking = supressChecking; } @Override public void put() throws IOException { final boolean attainedLockLocally; if (isPersisted() && !isLockOwned()) { lock(); attainedLockLocally = true; } else { attainedLockLocally = false; } try { triggerContentCoProcessors(ContentType.ContentProcessingPhase.WRITE); if (!isValid()) { getLogger().info("Content not in valid state!"); //First get contents indexed before attempting to use this validity! //Uncomment the following line once indexing is ensured in testing throw new IOException("Content is not in valid state!"); } super.put(); } finally { if (attainedLockLocally) { unlock(); } } } protected void triggerContentCoProcessors(final ContentProcessingPhase phase) { //Trigger content co processors if (contentDef != null && contentId != null) { Collection<ContentCoProcessorDef> defs = contentDef.getContentCoProcessorDefs().get( phase); if (defs != null && !defs.isEmpty()) { List<ContentCoProcessorDef> list = new ArrayList<ContentCoProcessorDef>(defs); Collections.sort(list, new Comparator<ContentCoProcessorDef>() { public int compare(ContentCoProcessorDef o1, ContentCoProcessorDef o2) { return o1.getPriority() - o2.getPriority(); } }); for (ContentCoProcessorDef def : list) { ContentCoProcessor processor = SmartContentAPI.getInstance().getWorkspaceApi().getContentCoProcessor(contentId. getWorkspaceId(), def.getResourceUri().getValue()); if (processor != null) { processor.processContent(this, def.getParameters()); } } } } } @Override public void setParentId(ContentId contentId) { if (contentDef == null) { throw new IllegalArgumentException("Content Type Definition must be set before setting parent content ID"); } if (contentId != null && SmartContentAPI.getInstance().getContentLoader().loadContent(contentId) == null) { throw new IllegalArgumentException("Parent must exist for it to be set!"); } this.parentId = contentId; } @Override public void setContentDefinition(ContentType contentType) { this.contentDef = contentType; } @Override public void setField(Field field) { getMap().put(field.getName(), field); cachedFieldMap = null; } @Override public void setStatus(ContentStatus contentStatus) { this.contentStatus = contentStatus; } @Override public ContentId getContentId() { return this.contentId; } @Override public ContentId getParentId() { return this.parentId; } @Override public Content getParent() { if (parentId != null) { return SmartContentAPI.getInstance().getContentLoader().loadContent(parentId); } else { return null; } } @Override public ContentType getContentDefinition() { return this.contentDef; } @Override public Map<String, Field> getFields() { final Content parent = getParent(); final ContentType def = getContentDefinition(); if (cachedFieldMap == null) { Map<String, Field> fields = new LinkedHashMap<String, Field>(); if (parent != null && def != null) { Map<String, Field> parentFields = parent.getFields(); for (String fieldName : parentFields.keySet()) { FieldDef myDef = def.getOwnFieldDefs().get(fieldName); FieldDef thatDef = parent.getContentDefinition().getOwnFieldDefs().get(fieldName); if (myDef != null && thatDef != null && ObjectUtils.equals(myDef, thatDef) && myDef.getValueDef().getType(). equals(thatDef.getValueDef().getType())) { fields.put(fieldName, parent.getField(fieldName)); } } } fields.putAll(getMap()); cachedFieldMap = fields; } return Collections.unmodifiableMap(cachedFieldMap); } public Map<String, Field> getMap() { if (map == null) { map = new LinkedHashMap<String, Field>(SmartContentSPI.getInstance().getContentReader().getFieldsForContent( contentId)); triggerContentCoProcessors(ContentType.ContentProcessingPhase.READ); } return map; } @Override public Map<String, Field> getOwnFields() { return Collections.unmodifiableMap(getMap()); } @Override public Field getField(String fieldName) { return getFields().get(fieldName); } @Override public ContentStatus getStatus() { return this.contentStatus; } @Override public Representation getRepresentation(String repName) { return SmartContentSPI.getInstance().getRepresentationProvider().getRepresentation(repName, getContentDefinition(), this); } @Override public Date getCreationDate() { return this.creationDate; } @Override public Date getLastModifiedDate() { return this.lastModifiedDate; } @Override public boolean isPersisted() { return creationDate != null; } @Override public ContentId getKeySpecimen() { return contentId; } @Override public void removeField(String fieldName) { getMap().remove(fieldName); } @Override public void setContentId(ContentId contentId) { this.contentId = contentId; } @Override public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } @Override public void setLastModifiedDate(Date lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } @Override protected void create() throws IOException { if (contentId != null) { if (contentId.getWorkspaceId() == null || contentId.getId() == null) { throw new IOException("Workspace ID or ID of content within wokrspace can not be null"); } Workspace workspace = SmartContentAPI.getInstance().getWorkspaceApi().getWorkspace(contentId.getWorkspaceId()); if (workspace == null) { throw new IOException("Non existance workspace Id " + contentId.getWorkspaceId()); } } if (contentId == null && contentDef != null && contentDef.getContentTypeID() != null) { createContentId(contentDef.getContentTypeID().getWorkspace()); } else if (contentId == null && (contentDef == null || contentDef.getContentTypeID() == null)) { throw new IOException("Content ID and Content Type Definition is not set!"); } super.create(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.CREATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public void delete() throws IOException { super.delete(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.DELETE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override protected void update() throws IOException { super.update(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.UPDATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!Content.class.isAssignableFrom(obj.getClass())) { return false; } final Content other = (Content) obj; if (this.contentId != other.getContentId() && (this.contentId == null || !this.contentId.equals(other.getContentId()))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.contentId != null ? this.contentId.hashCode() : 0); return hash; } @Override public void createContentId(WorkspaceId workspace) { if (workspace == null) { throw new IllegalArgumentException("Workspace ID can not be null!"); } setContentId(SmartContentAPI.getInstance().getContentLoader().generateContentId(workspace)); } @Override public void setEntityTagValue(String eTagValue) { this.entityTagValue = eTagValue; } @Override public String getEntityTagValue() { return this.entityTagValue; } @Override public boolean isValid() { boolean validContent = supressChecking || SmartContentAPI.getInstance().getContentLoader().isValidContent(this); if (getLogger().isDebugEnabled()) { getLogger().debug("!!! Checking Content " + validContent); } return validContent; } @Override public URI getUri() { return SmartContentSPI.getInstance().getUriProvider().getContentUri(contentId); } @Override public String getEncodedUriString() { if (getUri() == null) { return null; } else { return getUri().toASCIIString(); } } @Override public void setPrivate(boolean privateContent) { this.privateContent = privateContent; } @Override public boolean isPrivate() { return this.privateContent; } @Override public ContentImpl clone() { ContentImpl contentImpl = new ContentImpl(); contentImpl.contentDef = contentDef; contentImpl.contentId = contentId; contentImpl.parentId = parentId; contentImpl.privateContent = privateContent; contentImpl.contentStatus = contentStatus; contentImpl.nextPerformToWaitForLock = nextPerformToWaitForLock; contentImpl.supressChecking = supressChecking; contentImpl.entityTagValue = entityTagValue; if (creationDate != null) { contentImpl.creationDate = new Date(creationDate.getTime()); } if (lastModifiedDate != null) { contentImpl.lastModifiedDate = new Date(lastModifiedDate.getTime()); } contentImpl.map = map; if (map != null) { contentImpl.map = new LinkedHashMap<String, Field>(); cloneFields(map, contentImpl.map); } if (cachedFieldMap != null) { contentImpl.cachedFieldMap = new LinkedHashMap<String, Field>(); cloneFields(cachedFieldMap, contentImpl.cachedFieldMap); } return contentImpl; } protected void cloneFields(Map<String, Field> fieldMap, Map<String, Field> destMap) { for (Map.Entry<String, Field> oneField : fieldMap.entrySet()) { FieldImpl fieldImpl = new FieldImpl(); final Field value = oneField.getValue(); fieldImpl.setContent(value.getContent()); fieldImpl.setFieldDef(value.getFieldDef()); fieldImpl.setName(value.getName()); final FieldValue fieldVal = value.getValue(); fieldImpl.setValue(fieldVal); destMap.put(oneField.getKey(), fieldImpl); } } } diff --git a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/workspace/WorkspaceAPIImpl.java b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/workspace/WorkspaceAPIImpl.java index f019166..255dded 100644 --- a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/workspace/WorkspaceAPIImpl.java +++ b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/workspace/WorkspaceAPIImpl.java @@ -1,953 +1,956 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.api.impl.workspace; import com.google.inject.Inject; import com.google.inject.name.Named; import com.smartitengineering.cms.api.common.CacheableResource; -import com.smartitengineering.cms.api.common.SearchResult; import com.smartitengineering.cms.api.common.TemplateType; -import com.smartitengineering.cms.api.content.Content; import com.smartitengineering.cms.api.content.ContentId; -import com.smartitengineering.cms.api.content.Filter; import com.smartitengineering.cms.api.content.template.ContentCoProcessor; import com.smartitengineering.cms.api.content.template.FieldValidator; import com.smartitengineering.cms.api.content.template.RepresentationGenerator; import com.smartitengineering.cms.api.content.template.VariationGenerator; import com.smartitengineering.cms.api.event.Event; import com.smartitengineering.cms.api.event.Event.EventType; import com.smartitengineering.cms.api.event.Event.Type; import com.smartitengineering.cms.api.exception.InvalidTemplateException; import com.smartitengineering.cms.api.factory.SmartContentAPI; -import com.smartitengineering.cms.api.factory.content.WriteableContent; -import com.smartitengineering.cms.api.factory.type.WritableContentType; import com.smartitengineering.cms.api.factory.workspace.WorkspaceAPI; -import com.smartitengineering.cms.api.impl.content.FilterImpl; -import com.smartitengineering.cms.api.impl.type.ContentTypeImpl; -import com.smartitengineering.cms.api.type.ContentType; import com.smartitengineering.cms.api.type.ValidatorType; -import com.smartitengineering.cms.api.workspace.*; +import com.smartitengineering.cms.api.workspace.ContentCoProcessorTemplate; +import com.smartitengineering.cms.api.workspace.RepresentationTemplate; +import com.smartitengineering.cms.api.workspace.ResourceTemplate; +import com.smartitengineering.cms.api.workspace.Sequence; +import com.smartitengineering.cms.api.workspace.SequenceId; +import com.smartitengineering.cms.api.workspace.ValidatorTemplate; +import com.smartitengineering.cms.api.workspace.VariationTemplate; +import com.smartitengineering.cms.api.workspace.Workspace; +import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.cms.spi.SmartContentSPI; import com.smartitengineering.cms.spi.content.template.ContentCoProcessorGenerator; import com.smartitengineering.cms.spi.content.template.TypeFieldValidator; import com.smartitengineering.cms.spi.content.template.TypeRepresentationGenerator; import com.smartitengineering.cms.spi.content.template.TypeVariationGenerator; -import com.smartitengineering.cms.spi.persistence.PersistentService; import com.smartitengineering.dao.common.cache.CacheServiceProvider; import com.smartitengineering.dao.common.cache.Lock; import com.smartitengineering.dao.common.cache.Mutex; import com.smartitengineering.dao.common.cache.impl.CacheAPIFactory; import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.AbstractMap.SimpleEntry; -import java.util.*; import java.util.Map.Entry; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author imyousuf */ public class WorkspaceAPIImpl implements WorkspaceAPI { private String globalNamespace; private final transient Logger logger = LoggerFactory.getLogger(getClass()); @Inject private Map<TemplateType, ContentCoProcessorGenerator> contentCoProcessorGenerators; @Inject private Map<TemplateType, TypeRepresentationGenerator> representationGenerators; @Inject private Map<TemplateType, TypeVariationGenerator> variationGenerators; @Inject private Map<ValidatorType, TypeFieldValidator> validatorGenerators; @Inject private CacheServiceProvider<WorkspaceResourceCacheKey, CacheableResource> resourcesCache; protected final Mutex<WorkspaceResourceCacheKey> mutex = CacheAPIFactory.<WorkspaceResourceCacheKey>getMutex(); public CacheServiceProvider<WorkspaceResourceCacheKey, CacheableResource> getResourcesCache() { return resourcesCache; } public void setResourcesCache(CacheServiceProvider<WorkspaceResourceCacheKey, CacheableResource> resourcesCache) { this.resourcesCache = resourcesCache; } public Map<TemplateType, ContentCoProcessorGenerator> getContentCoProcessorGenerators() { return contentCoProcessorGenerators; } public void setContentCoProcessorGenerators( Map<TemplateType, ContentCoProcessorGenerator> contentCoProcessorGenerators) { this.contentCoProcessorGenerators = contentCoProcessorGenerators; } public Map<TemplateType, TypeRepresentationGenerator> getRepresentationGenerators() { return representationGenerators; } public void setRepresentationGenerators(Map<TemplateType, TypeRepresentationGenerator> representationGenerators) { this.representationGenerators = representationGenerators; } public Map<ValidatorType, TypeFieldValidator> getValidatorGenerators() { return validatorGenerators; } public void setValidatorGenerators(Map<ValidatorType, TypeFieldValidator> validatorGenerators) { this.validatorGenerators = validatorGenerators; } public Map<TemplateType, TypeVariationGenerator> getVariationGenerators() { return variationGenerators; } public void setVariationGenerators(Map<TemplateType, TypeVariationGenerator> variationGenerators) { this.variationGenerators = variationGenerators; } @Inject public void setGlobalNamespace(@Named("globalNamespace") String globalNamespace) { this.globalNamespace = globalNamespace; } @Override public String getGlobalNamespace() { return globalNamespace; } @Override public WorkspaceId createWorkspace(String name) { WorkspaceId workspaceIdImpl = createWorkspaceId(name); return createWorkspace(workspaceIdImpl); } @Override public WorkspaceId createWorkspace(String globalNamespace, String name) { return createWorkspace(createWorkspaceId(globalNamespace, name)); } @Override public WorkspaceId createWorkspace(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().create(workspaceId); Event<Workspace> event = SmartContentAPI.getInstance().getEventRegistrar().<Workspace>createEvent( EventType.UPDATE, Type.WORKSPACE, getWorkspace(workspaceId)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); return workspaceId; } @Override public WorkspaceId createWorkspaceId(String name) { return createWorkspaceId(null, name); } @Override public WorkspaceId createWorkspaceId(final String namespace, String name) { final WorkspaceIdImpl workspaceIdImpl = new WorkspaceIdImpl(); workspaceIdImpl.setGlobalNamespace(StringUtils.isBlank(namespace) ? getGlobalNamespace() : namespace); workspaceIdImpl.setName(name); return workspaceIdImpl; } @Override public WorkspaceId getWorkspaceIdIfExists(String name) { final WorkspaceId createdWorkspaceId = createWorkspaceId(name); return getWorkspaceIdIfExists(createdWorkspaceId); } @Override public WorkspaceId getWorkspaceIdIfExists(WorkspaceId workspaceId) { Workspace workspace = getWorkspace(workspaceId); if (workspace != null) { return workspaceId; } return null; } @Override public Workspace getWorkspace(WorkspaceId workspaceId) { return SmartContentSPI.getInstance().getWorkspaceService().load(workspaceId); } @Override public Collection<Workspace> getWorkspaces() { return SmartContentSPI.getInstance().getWorkspaceService().getWorkspaces(); } @Override public RepresentationTemplate putRepresentationTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException { return putRepresentationTemplate(to, name, templateType, IOUtils.toByteArray(stream)); } @Override public RepresentationTemplate putRepresentationTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data) { final RepresentationTemplate putRepresentationTemplate = SmartContentSPI.getInstance().getWorkspaceService(). putRepresentationTemplate(to, name, templateType, data); Event<RepresentationTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<RepresentationTemplate> createEvent(EventType.UPDATE, Type.REPRESENTATION_TEMPLATE, putRepresentationTemplate); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); if (resourcesCache != null) { WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(to, WorkspaceResourceCacheKey.WorkspaceResourceType.REPRESENTATION_GEN, name); resourcesCache.expireFromCache(key); } return putRepresentationTemplate; } @Override public VariationTemplate putVariationTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException { return putVariationTemplate(to, name, templateType, IOUtils.toByteArray(stream)); } @Override public VariationTemplate putVariationTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data) { final VariationTemplate putVariationTemplate = SmartContentSPI.getInstance().getWorkspaceService(). putVariationTemplate(to, name, templateType, data); Event<VariationTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<VariationTemplate> createEvent(EventType.UPDATE, Type.VARIATION_TEMPLATE, putVariationTemplate); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); if (resourcesCache != null) { WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(to, WorkspaceResourceCacheKey.WorkspaceResourceType.VARIATION_GEN, name); resourcesCache.expireFromCache(key); } return putVariationTemplate; } @Override public void delete(RepresentationTemplate template) { SmartContentSPI.getInstance().getWorkspaceService().deleteRepresentation(template); Event<RepresentationTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<RepresentationTemplate> createEvent(EventType.DELETE, Type.REPRESENTATION_TEMPLATE, template); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void delete(VariationTemplate template) { SmartContentSPI.getInstance().getWorkspaceService().deleteVariation(template); Event<VariationTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<VariationTemplate> createEvent(EventType.DELETE, Type.VARIATION_TEMPLATE, template); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public Collection<WorkspaceId> getFriendlies(WorkspaceId workspaceId) { return SmartContentSPI.getInstance().getWorkspaceService().getFriendlies(workspaceId); } @Override public void addFriend(WorkspaceId to, WorkspaceId... workspaceIds) { SmartContentSPI.getInstance().getWorkspaceService().addFriend(to, workspaceIds); for (WorkspaceId friend : workspaceIds) { Event<Entry<WorkspaceId, WorkspaceId>> event = SmartContentAPI.getInstance().getEventRegistrar().<Entry<WorkspaceId, WorkspaceId>> createEvent(EventType.CREATE, Type.FRIENDLY, new SimpleEntry<WorkspaceId, WorkspaceId>(to, friend)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } } @Override public void removeFriend(WorkspaceId from, WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeFriend(from, workspaceId); Event<Entry<WorkspaceId, WorkspaceId>> event = SmartContentAPI.getInstance().getEventRegistrar().<Entry<WorkspaceId, WorkspaceId>> createEvent(EventType.DELETE, Type.FRIENDLY, new SimpleEntry<WorkspaceId, WorkspaceId>(from, workspaceId)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void removeAllFriendlies(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllFriendlies(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_FRIENDLIES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void removeAllRepresentationTemplates(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllRepresentationTemplates(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_REPRESENTATION_TEMPLATES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void removeAllVariationTemplates(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllVariationTemplates(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_VARIATION_TEMPLATES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public Collection<String> getRepresentationNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count) { if (count == 0 || startPoint == null) { return Collections.emptyList(); } List<String> list = new ArrayList<String>(getRepresentationNames(id, criteria)); return cutList(list, startPoint, count); } @Override public Collection<String> getVariationNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count) { if (count == 0 || startPoint == null) { return Collections.emptyList(); } List<String> list = new ArrayList<String>(getVariationNames(id, criteria)); return cutList(list, startPoint, count); } @Override public Collection<String> getRepresentationNames(WorkspaceId id, ResourceSortCriteria criteria) { final Collection<? extends ResourceTemplate> repsWithoutData = SmartContentSPI.getInstance(). getWorkspaceService().getRepresentationsWithoutData(id, criteria); return getResourceNames(repsWithoutData); } @Override public Collection<String> getVariationNames(WorkspaceId id, ResourceSortCriteria criteria) { final Collection<? extends ResourceTemplate> variationsWithoutData = SmartContentSPI.getInstance(). getWorkspaceService().getVariationsWithoutData(id, criteria); return getResourceNames(variationsWithoutData); } protected Collection<String> getResourceNames(Collection<? extends ResourceTemplate> templates) { ArrayList<String> list = new ArrayList<String>(templates.size()); for (ResourceTemplate template : templates) { list.add(template.getName()); } return list; } protected Collection<String> getValidatorNames(Collection<ValidatorTemplate> templates) { ArrayList<String> list = new ArrayList<String>(templates.size()); for (ValidatorTemplate template : templates) { list.add(template.getName()); } return list; } @Override public Collection<String> getRepresentationNames(WorkspaceId id) { return getRepresentationNames(id, ResourceSortCriteria.BY_NAME); } @Override public Collection<String> getVariationNames(WorkspaceId id) { return getVariationNames(id, ResourceSortCriteria.BY_NAME); } @Override public Collection<String> getRepresentationNames(WorkspaceId id, String startPoint, int count) { return getRepresentationNames(id, ResourceSortCriteria.BY_NAME, startPoint, count); } @Override public Collection<String> getVariationNames(WorkspaceId id, String startPoint, int count) { return getVariationNames(id, ResourceSortCriteria.BY_NAME, startPoint, count); } @Override public RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getRepresentationTemplate(id, name); } @Override public VariationTemplate getVariationTemplate(WorkspaceId id, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getVariationTemplate(id, name); } @Override public String getEntityTagValueForResourceTemplate(ResourceTemplate template) { final String toString = new StringBuilder(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(template. getLastModifiedDate())).append(':').append(Arrays.toString(template.getTemplate())).append(':').append(template. getTemplateType().name()).toString(); final String etag = DigestUtils.md5Hex(toString); if (logger.isDebugEnabled()) { logger.debug("Generated etag " + etag + " for " + template.getClass().getName() + " with name " + template.getName()); } return etag; } @Override public Collection<ContentId> getRootContents(WorkspaceId workspaceId) { return SmartContentSPI.getInstance().getWorkspaceService().getRootContents(workspaceId); } @Override public void addRootContent(WorkspaceId to, ContentId... contentIds) { SmartContentSPI.getInstance().getWorkspaceService().addRootContent(to, contentIds); for (ContentId rootContent : contentIds) { Event<Entry<WorkspaceId, ContentId>> event = SmartContentAPI.getInstance().getEventRegistrar().<Entry<WorkspaceId, ContentId>> createEvent(EventType.CREATE, Type.ROOT_CONTENT, new SimpleEntry<WorkspaceId, ContentId>(to, rootContent)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } } @Override public void removeRootContent(WorkspaceId from, ContentId contentId) { SmartContentSPI.getInstance().getWorkspaceService().removeRootContent(from, contentId); Event<Entry<WorkspaceId, ContentId>> event = SmartContentAPI.getInstance().getEventRegistrar().<Entry<WorkspaceId, ContentId>> createEvent(EventType.DELETE, Type.ROOT_CONTENT, new SimpleEntry<WorkspaceId, ContentId>(from, contentId)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void removeAllRootContents(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllRootContents(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_ROOT_CONTENTS, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public ValidatorTemplate getValidatorTemplate(WorkspaceId workspaceId, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getValidationTemplate(workspaceId, name); } @Override public void delete(ValidatorTemplate template) { SmartContentSPI.getInstance().getWorkspaceService().deleteValidator(template); Event<ValidatorTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<ValidatorTemplate> createEvent(EventType.DELETE, Type.VALIDATION_TEMPLATE, template); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public ValidatorTemplate putValidatorTemplate(WorkspaceId to, String name, ValidatorType templateType, InputStream stream) throws IOException { return putValidatorTemplate(to, name, templateType, IOUtils.toByteArray(stream)); } @Override public ValidatorTemplate putValidatorTemplate(WorkspaceId to, String name, ValidatorType templateType, byte[] data) { final ValidatorTemplate validatorTemplate = SmartContentSPI.getInstance().getWorkspaceService().putValidatorTemplate( to, name, templateType, data); Event<ValidatorTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<ValidatorTemplate> createEvent(EventType.UPDATE, Type.VALIDATION_TEMPLATE, validatorTemplate); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); if (resourcesCache != null) { WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(to, WorkspaceResourceCacheKey.WorkspaceResourceType.VALIDATION_SCR, name); resourcesCache.expireFromCache(key); } return validatorTemplate; } @Override public String getEntityTagValueForValidatorTemplate(ValidatorTemplate template) { final String toString = new StringBuilder(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(template. getLastModifiedDate())).append(':').append(Arrays.toString(template.getTemplate())).append(':').append(template. getTemplateType().name()).toString(); final String etag = DigestUtils.md5Hex(toString); if (logger.isDebugEnabled()) { logger.debug("Generated etag " + etag + " for " + template.getClass().getName() + " with name " + template.getName()); } return etag; } @Override public Collection<String> getValidatorNames(WorkspaceId id) { return getVariationNames(id, ResourceSortCriteria.BY_NAME); } @Override public Collection<String> getValidatorNames(WorkspaceId id, String startPoint, int count) { return getVariationNames(id, ResourceSortCriteria.BY_NAME, startPoint, count); } @Override public Collection<String> getValidatorNames(WorkspaceId id, ResourceSortCriteria criteria) { final Collection<ValidatorTemplate> variationsWithoutData = SmartContentSPI.getInstance().getWorkspaceService(). getValidatorsWithoutData(id, criteria); return getValidatorNames(variationsWithoutData); } @Override public Collection<String> getValidatorNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count) { if (count == 0 || startPoint == null) { return Collections.emptyList(); } List<String> list = new ArrayList<String>(getValidatorNames(id, criteria)); return cutList(list, startPoint, count); } @Override public void removeAllValidatorTemplates(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllValidatorTemplates(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_VALIDATION_TEMPLATES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } protected Collection<String> cutList(List<String> list, String startPoint, int count) { if (logger.isDebugEnabled()) { logger.debug("All names " + list); } int index = Collections.binarySearch(list, startPoint); if (logger.isDebugEnabled()) { logger.debug("Index " + index); } if (index < 0) { index = index * - 1; } if (count > 0 && index + 1 >= list.size() && StringUtils.isNotBlank(startPoint)) { logger.debug("Index is equal to size and count is greater than 0"); return Collections.emptyList(); } if (count < 0 && index <= 0) { logger.debug("Index is zero to size and count is smaller than 0"); return Collections.emptyList(); } final int fromIndex; final int toIndex; if (count > 0) { fromIndex = StringUtils.isBlank(startPoint) ? 0 : index + 1; toIndex = (fromIndex + count >= list.size()) ? list.size() : fromIndex + count; } else { toIndex = index; fromIndex = (toIndex + count >= 0) ? toIndex + count : 0; } if (logger.isDebugEnabled()) { logger.debug("Sublisting starts at " + fromIndex + " and ends before " + toIndex); } final List<String> result = list.subList(fromIndex, toIndex); if (logger.isDebugEnabled()) { logger.debug("Returning " + result); } return result; } public void delete(ContentCoProcessorTemplate template) { SmartContentSPI.getInstance().getWorkspaceService().deleteContentCoProcessor(template); Event<ContentCoProcessorTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<ContentCoProcessorTemplate> createEvent(EventType.DELETE, Type.CONTENT_CO_PROCESSOR_TEMPLATE, template); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } public ContentCoProcessorTemplate putContentCoProcessorTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException { return putContentCoProcessorTemplate(to, name, templateType, IOUtils.toByteArray(stream)); } public ContentCoProcessorTemplate putContentCoProcessorTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data) { if (templateType.equals(TemplateType.JASPER) || templateType.equals(TemplateType.VELOCITY)) { throw new IllegalArgumentException("TemplateType not supported for content type co processor"); } final ContentCoProcessorTemplate temp = SmartContentSPI.getInstance().getWorkspaceService(). putContentCoProcessorTemplate(to, name, templateType, data); Event<ContentCoProcessorTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<ContentCoProcessorTemplate> createEvent(EventType.UPDATE, Type.CONTENT_CO_PROCESSOR_TEMPLATE, temp); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); if (resourcesCache != null) { WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(to, WorkspaceResourceCacheKey.WorkspaceResourceType.CONTENT_CO_PROCESSOR_GEN, name); resourcesCache.expireFromCache(key); } return temp; } public ContentCoProcessorTemplate getContentCoProcessorTemplate(WorkspaceId id, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getContentCoProcessorTemplate(id, name); } public void removeAllContentCoProcessorTemplates(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllContentCoProcessorTemplates(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_CONTENT_CO_PROCESSOR_TEMPLATES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } public ContentCoProcessor getContentCoProcessor(WorkspaceId id, String name) { return getContentCoProcessor(id, name, true); } public ContentCoProcessor getContentCoProcessor(final WorkspaceId id, final String name, final boolean searchInFriendlies) { if (id == null || StringUtils.isBlank(name)) { logger.warn("Null workspace id or blank name!"); return null; } WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(id, WorkspaceResourceCacheKey.WorkspaceResourceType.CONTENT_CO_PROCESSOR_GEN, name); CacheThroughReader<ContentCoProcessor> reader = new CacheThroughReader<ContentCoProcessor>(key, new Lookup<ContentCoProcessor>() { public ContentCoProcessor get() { ContentCoProcessorTemplate template = getContentCoProcessorTemplate(id, name, searchInFriendlies); return getContentCoProcessor(template); } }); return reader.read(); } public FieldValidator getFieldValidator(WorkspaceId id, String name) { return getFieldValidator(id, name, true); } public FieldValidator getFieldValidator(final WorkspaceId id, final String name, final boolean searchInFriendlies) { if (id == null || StringUtils.isBlank(name)) { logger.warn("Null workspace id or blank name!"); return null; } WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(id, WorkspaceResourceCacheKey.WorkspaceResourceType.VALIDATION_SCR, name); CacheThroughReader<FieldValidator> reader = new CacheThroughReader<FieldValidator>(key, new Lookup<FieldValidator>() { public FieldValidator get() { ValidatorTemplate template = getValidatorTemplate(id, name, searchInFriendlies); if (template == null) { logger.info("Validator template is null, returning true!"); return null; } return getFieldValidator(template); } }); return reader.read(); } public RepresentationGenerator getRepresentationGenerator(WorkspaceId id, String name) { return getRepresentationGenerator(id, name, true); } public RepresentationGenerator getRepresentationGenerator(final WorkspaceId workspaceId, final String name, final boolean searchInFriendlies) { if (workspaceId == null || StringUtils.isBlank(name)) { logger.warn("Null workspace id or blank name!"); return null; } WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(workspaceId, WorkspaceResourceCacheKey.WorkspaceResourceType.REPRESENTATION_GEN, name); CacheThroughReader<RepresentationGenerator> reader = new CacheThroughReader<RepresentationGenerator>(key, new Lookup<RepresentationGenerator>() { public RepresentationGenerator get() { RepresentationTemplate representationTemplate = getRepresentationTemplate(workspaceId, name, searchInFriendlies); return getRepresentationGenerator(representationTemplate); } }); return reader.read(); } public VariationGenerator getVariationGenerator(WorkspaceId id, String name) { return getVariationGenerator(id, name, true); } public VariationGenerator getVariationGenerator(final WorkspaceId workspaceId, final String name, final boolean searchInFriendlies) { if (workspaceId == null || StringUtils.isBlank(name)) { logger.warn("Null workspace id or blank name!"); return null; } WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(workspaceId, WorkspaceResourceCacheKey.WorkspaceResourceType.VARIATION_GEN, name); CacheThroughReader<VariationGenerator> reader = new CacheThroughReader<VariationGenerator>(key, new Lookup<VariationGenerator>() { public VariationGenerator get() { VariationTemplate variationTemplate = getVariationTemplate(workspaceId, name, searchInFriendlies); return getVariationGenerator(variationTemplate); } }); return reader.read(); } public Collection<String> getContentCoProcessorNames(WorkspaceId id, ResourceSortCriteria criteria) { final Collection<ContentCoProcessorTemplate> procsWithoutData = SmartContentSPI.getInstance(). getWorkspaceService().getContentCoProcessorsWithoutData(id, criteria); return getResourceNames(procsWithoutData); } public Collection<String> getContentCoProcessorNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count) { if (count == 0 || startPoint == null) { return Collections.emptyList(); } List<String> list = new ArrayList<String>(getContentCoProcessorNames(id, criteria)); return cutList(list, startPoint, count); } public Collection<String> getContentCoProcessorNames(WorkspaceId id) { return getContentCoProcessorNames(id, ResourceSortCriteria.BY_NAME); } public Collection<String> getContentCoProcessorNames(WorkspaceId id, String startPoint, int count) { return getContentCoProcessorNames(id, ResourceSortCriteria.BY_NAME, startPoint, count); } public ContentCoProcessorTemplate getContentCoProcessorTemplate(WorkspaceId id, String name, boolean searchInFriendlies) { ContentCoProcessorTemplate template = getContentCoProcessorTemplate(id, name); if (searchInFriendlies && template == null) { //Lookup friendlies Collection<WorkspaceId> friends = SmartContentAPI.getInstance().getWorkspaceApi().getFriendlies(id); if (friends != null && !friends.isEmpty()) { Iterator<WorkspaceId> friendsIterator = friends.iterator(); while (template == null && friendsIterator.hasNext()) { template = SmartContentAPI.getInstance().getWorkspaceApi().getContentCoProcessorTemplate( friendsIterator.next(), name); } } } return template; } public RepresentationTemplate getRepresentationTemplate(WorkspaceId workspaceId, String name, boolean searchInFriendlies) { RepresentationTemplate representationTemplate = SmartContentAPI.getInstance().getWorkspaceApi().getRepresentationTemplate(workspaceId, name); if (searchInFriendlies && representationTemplate == null) { //Lookup friendlies Collection<WorkspaceId> friends = SmartContentAPI.getInstance().getWorkspaceApi().getFriendlies(workspaceId); if (friends != null && !friends.isEmpty()) { Iterator<WorkspaceId> friendsIterator = friends.iterator(); while (representationTemplate == null && friendsIterator.hasNext()) { representationTemplate = SmartContentAPI.getInstance().getWorkspaceApi().getRepresentationTemplate(friendsIterator. next(), name); } } } return representationTemplate; } public ValidatorTemplate getValidatorTemplate(WorkspaceId id, String name, boolean searchInFriendlies) { ValidatorTemplate template = SmartContentAPI.getInstance().getWorkspaceApi().getValidatorTemplate(id, name); if (searchInFriendlies && template == null) { //Lookup friendlies Collection<WorkspaceId> friends = SmartContentAPI.getInstance().getWorkspaceApi().getFriendlies(id); if (friends != null && !friends.isEmpty()) { Iterator<WorkspaceId> friendsIterator = friends.iterator(); while (template == null && friendsIterator.hasNext()) { template = SmartContentAPI.getInstance().getWorkspaceApi().getValidatorTemplate(friendsIterator.next(), name); } } } return template; } public VariationTemplate getVariationTemplate(WorkspaceId workspaceId, String name, boolean searchInFriendlies) { VariationTemplate variationTemplate = SmartContentAPI.getInstance().getWorkspaceApi().getVariationTemplate(workspaceId, name); if (searchInFriendlies && variationTemplate == null) { //Lookup friendlies Collection<WorkspaceId> friends = SmartContentAPI.getInstance().getWorkspaceApi().getFriendlies(workspaceId); if (friends != null && !friends.isEmpty()) { Iterator<WorkspaceId> friendsIterator = friends.iterator(); while (variationTemplate == null && friendsIterator.hasNext()) { variationTemplate = SmartContentAPI.getInstance().getWorkspaceApi().getVariationTemplate( friendsIterator.next(), name); } } } return variationTemplate; } public ContentCoProcessor getContentCoProcessor(ContentCoProcessorTemplate template) { if (template == null) { return null; } ContentCoProcessorGenerator generator = contentCoProcessorGenerators.get(template.getTemplateType()); try { return generator.getGenerator(template); } catch (Exception ex) { logger.warn("Could not retrieve processor", ex); return null; } } public RepresentationGenerator getRepresentationGenerator(RepresentationTemplate representationTemplate) { if (representationTemplate == null) { return null; } TypeRepresentationGenerator generator = representationGenerators.get(representationTemplate.getTemplateType()); if (generator == null) { return null; } try { return generator.getGenerator(representationTemplate); } catch (Exception ex) { logger.warn("Could not generate representation generator", ex); return null; } } public VariationGenerator getVariationGenerator(VariationTemplate variationTemplate) { if (variationTemplate == null) { return null; } TypeVariationGenerator generator = variationGenerators.get(variationTemplate.getTemplateType()); if (generator == null) { return null; } try { return generator.getGenerator(variationTemplate); } catch (Exception ex) { logger.warn("Could not generate variation generator", ex); return null; } } public FieldValidator getFieldValidator(ValidatorTemplate template) { TypeFieldValidator generator = validatorGenerators.get(template.getTemplateType()); if (generator == null) { logger.info("Validator generator is null, returning true!"); return null; } try { return generator.getValidator(template); } catch (InvalidTemplateException ex) { logger.error("Not a valid validator template!"); return null; } } public Sequence putSequence(WorkspaceId workspaceId, String name, long initialValue) { final Sequence created = SmartContentSPI.getInstance().getWorkspaceService().create(workspaceId, name, initialValue); Event<Sequence> event = SmartContentAPI.getInstance().getEventRegistrar().<Sequence>createEvent(EventType.CREATE, Type.SEQUENCE, created); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); return created; } public long modifySequenceValue(Sequence sequence, long delta) { final long newSequence = SmartContentSPI.getInstance().getWorkspaceService().modifySequenceValue(sequence, delta); return newSequence; } public Sequence getSequence(WorkspaceId workspaceId, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getSequence(workspaceId, name); } public void deleteSequence(WorkspaceId workspaceId, String name) { Sequence sequence = getSequence(workspaceId, name); if (sequence != null) { SmartContentSPI.getInstance().getWorkspaceService().deleteSequence(workspaceId, name); } Event<Sequence> event = SmartContentAPI.getInstance().getEventRegistrar().<Sequence>createEvent(EventType.DELETE, Type.SEQUENCE, sequence); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } public SequenceId createSequenceId(WorkspaceId workspaceId, String name) { SequenceIdImpl impl = new SequenceIdImpl(); impl.setName(name); impl.setWorkspaceId(workspaceId); return impl; } public Collection<Sequence> getSequencesForWorkspace(WorkspaceId workspaceId) { return SmartContentSPI.getInstance().getWorkspaceService().getSequencesForWorkspace(workspaceId); } public void reIndex(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().reIndex(workspaceId); } public void reIndex(SequenceId seqId) { SmartContentSPI.getInstance().getWorkspaceService().reIndex(seqId); } public void deleteWorkspace(final WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().deleteWorkspaceWithDependencies(workspaceId); } - + public interface Lookup<T> { T get(); } public class CacheThroughReader<T extends CacheableResource> { private final Lookup<T> lookup; private final WorkspaceResourceCacheKey key; public CacheThroughReader(WorkspaceResourceCacheKey key, Lookup<T> lookup) { this.lookup = lookup; this.key = key; } public T read() { if (resourcesCache == null) { logger.info("Avoiding cache through read as cache is null!"); return lookup.get(); } final Lock<WorkspaceResourceCacheKey> lock; try { lock = mutex.acquire(key); } catch (Exception ex) { logger.warn("Error retrieving lock", ex); throw new IllegalStateException(ex); } try { CacheableResource cachedResource = resourcesCache.retrieveFromCache(key); if (cachedResource != null) { return (T) cachedResource; } else { T result = lookup.get(); resourcesCache.putToCache(key, result); return result; } } catch (Exception ex) { logger.warn("Error in doing cache through read", ex); return null; } finally { mutex.release(lock); } } } }
SmartITEngineering/smart-cms
288087ae518134ca0789bf0b1241873058221c29
Add sleep
diff --git a/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java b/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java index ec5da7c..1401680 100644 --- a/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java +++ b/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java @@ -2708,579 +2708,580 @@ public class AppTest { } feedResource.getContents().post(MediaType.MULTIPART_FORM_DATA, multiPart, ClientResponse.Status.CREATED, ClientResponse.Status.ACCEPTED, ClientResponse.Status.OK); Assert.fail("Invalid content should have failed " + i); } catch (Exception ex) { //Expected that creation fails } } } @Test public void testCreateContentCoProcessor() throws Exception { ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "Template"; template.setName("rep"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.JAVASCRIPT.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceContentCoProcessorsResource rsrcs = feedResource.getContentCoProcessors(); WorkspaceContentCoProcessorResource rsrc = rsrcs.createContentCoProcessor( template); Assert.assertEquals("rep", rsrc.get().getName()); Assert.assertEquals(temp, new String(rsrc.get().getTemplate())); Assert.assertEquals(TemplateType.JAVASCRIPT.toString(), rsrc.get().getTemplateType()); } @Test public void testUpdateContentCoProcessor() throws Exception { LOGGER.info(":::::::::::::: UPDATE CONTENT CO PROCESSOR RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "newTemplate"; final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.RUBY.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); Collection<WorkspaceContentCoProcessorResource> representationResources = feedResource.getContentCoProcessors(). getContentCoProcessorResources(); Assert.assertEquals(1, representationResources.size()); Iterator<WorkspaceContentCoProcessorResource> representationIterator = representationResources.iterator(); WorkspaceContentCoProcessorResource rsrc = representationIterator.next(); rsrc.update(template); Assert.assertEquals("rep", rsrc.get().getName()); Assert.assertEquals(temp, new String(rsrc.get().getTemplate())); Assert.assertEquals(TemplateType.RUBY.toString(), rsrc.get().getTemplateType()); resource.getWorkspaceFeeds(); WorkspaceContentCoProcessorResource secondRepresentationResource = resource.getWorkspaceFeeds().iterator().next(). getContentCoProcessors().getContentCoProcessorResources().iterator().next(); template.setTemplateType(TemplateType.JAVASCRIPT.name()); secondRepresentationResource.update(template); Assert.assertEquals(TemplateType.JAVASCRIPT.name(), secondRepresentationResource.get().getTemplateType()); try { rsrc.update(template); Assert.fail("Should not have been able to update!"); } catch (UniformInterfaceException ex) { //Exception expected rsrc.get(); rsrc.update(template); } sleep(); } @Test public void testDeleteContentCoProcessor() throws Exception { LOGGER.info(":::::::::::::: DELETE CONTENT CO PROCESSOR RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "Template2"; template.setName("rep2"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.JAVASCRIPT.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); final WorkspaceContentCoProcessorsResource procsResource = feedResource.getContentCoProcessors(); Collection<WorkspaceContentCoProcessorResource> rsrcs = procsResource.getContentCoProcessorResources(); Assert.assertEquals(1, rsrcs.size()); procsResource.createContentCoProcessor(template); Iterator<WorkspaceContentCoProcessorResource> representationIterator = rsrcs.iterator(); WorkspaceContentCoProcessorResource rsrc = representationIterator.next(); rsrc.delete(ClientResponse.Status.ACCEPTED); Collection<WorkspaceContentCoProcessorResource> secRsrcs = resource.getWorkspaceFeeds().iterator(). next().getContentCoProcessors().getContentCoProcessorResources(); Assert.assertEquals(1, secRsrcs.size()); sleep(); } @Test public void testCreateContentTypeWithContentCoProcessors() { WorkspaceFeedResource feedResource = setupEnumWorkspace(); com.smartitengineering.cms.api.impl.workspace.WorkspaceIdImpl id = new com.smartitengineering.cms.api.impl.workspace.WorkspaceIdImpl(); id.setGlobalNamespace(feedResource.getWorkspaceNamespace()); id.setName(feedResource.getWorkspaceName()); ContentTypeIdImpl idImpl = new ContentTypeIdImpl(); idImpl.setWorkspace(id); idImpl.setNamespace("enum"); idImpl.setName("ContentCoProcessorTest"); ContentType type = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(idImpl); final Map<ContentProcessingPhase, Collection<ContentCoProcessorDef>> contentCoProcessorDefs = type.getContentCoProcessorDefs(); Assert.assertNotNull(contentCoProcessorDefs); Assert.assertFalse(contentCoProcessorDefs.isEmpty()); Assert.assertNotNull(contentCoProcessorDefs.get(ContentProcessingPhase.READ)); Assert.assertNotNull(contentCoProcessorDefs.get(ContentProcessingPhase.WRITE)); Assert.assertFalse(contentCoProcessorDefs.get(ContentProcessingPhase.READ).isEmpty()); Assert.assertFalse(contentCoProcessorDefs.get(ContentProcessingPhase.WRITE).isEmpty()); Assert.assertEquals(2, contentCoProcessorDefs.get(ContentProcessingPhase.READ).size()); Assert.assertEquals(1, contentCoProcessorDefs.get(ContentProcessingPhase.WRITE).size()); final Iterator<ContentCoProcessorDef> readItr = contentCoProcessorDefs.get(ContentProcessingPhase.READ).iterator(); ContentCoProcessorDef def = readItr.next(); Assert.assertEquals("testr", def.getName()); Assert.assertNull(def.getMIMEType()); Assert.assertEquals(0, def.getPriority()); Assert.assertEquals(1, def.getParameters().size()); Assert.assertEquals("v", def.getParameters().get("k")); Assert.assertEquals("test", def.getResourceUri().getValue()); def = readItr.next(); Assert.assertEquals("testr1", def.getName()); Assert.assertNull(def.getMIMEType()); Assert.assertEquals(1, def.getPriority()); Assert.assertEquals(1, def.getParameters().size()); Assert.assertEquals("v1", def.getParameters().get("k1")); Assert.assertEquals("test1", def.getResourceUri().getValue()); def = contentCoProcessorDefs.get(ContentProcessingPhase.WRITE).iterator().next(); Assert.assertEquals("testw", def.getName()); Assert.assertNull(def.getMIMEType()); Assert.assertEquals(0, def.getPriority()); Assert.assertEquals(1, def.getParameters().size()); Assert.assertEquals("v2", def.getParameters().get("k2")); Assert.assertEquals("test2", def.getResourceUri().getValue()); sleep(); } private WorkspaceFeedResource setupContentCoProcessorExecWorkspace() { RootResource resource = RootResourceImpl.getRoot(URI.create(ROOT_URI_STRING)); resource.get(); WorkspaceFeedResource feedResource; try { feedResource = resource.getTemplates().getWorkspaceResource("test", "enums"); } catch (Exception ex) { feedResource = null; LOGGER.info("Exception getting feed resoruce", ex); } boolean valid = false; { try { final WorkspaceIdImpl workspaceId = new WorkspaceIdImpl("test", "enums"); if (feedResource == null) { Workspace workspace = resource.createWorkspace(workspaceId); feedResource = resource.getTemplates().getWorkspaceResource(workspace.getId().getGlobalNamespace(), workspace. getId().getName()); } String contentTypeXml = IOUtils.toString(getClass().getClassLoader().getResourceAsStream( "contentcoprocessors/content-type-def-with-enum-ext.xml")); feedResource.getContentTypes().createContentType(contentTypeXml); ResourceTemplateImpl template = new ResourceTemplateImpl(); template.setName("test"); template.setTemplate(IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream( "contentcoprocessors/coprocessor.groovy"))); template.setTemplateType("GROOVY"); template.setWorkspaceId(workspaceId); feedResource.getContentCoProcessors().createContentCoProcessor(template); valid = true; } catch (Exception ex) { LOGGER.error("Error creating test workspace for templates", ex); } } Assert.assertTrue(valid); return feedResource; } @Test public void testCreateContentWithContentCoProcessors() throws Exception { WorkspaceFeedResource feedResource = setupContentCoProcessorExecWorkspace(); ClientConfig config = new DefaultClientConfig(); config.getClasses().add(JacksonJsonProvider.class); config.getClasses().add(TextURIListProvider.class); config.getClasses().add(FeedProvider.class); Client client = Client.create(config); { final Properties properties = new Properties(); properties.load(getClass().getClassLoader().getResourceAsStream( "contentcoprocessors/form-value-write.properties")); Set<Object> formKeys = properties.keySet(); FormDataMultiPart multiPart = new FormDataMultiPart(); for (Object key : formKeys) { multiPart.field(key.toString(), properties.getProperty(key.toString())); } ClientResponse response = feedResource.getContents().post(MediaType.MULTIPART_FORM_DATA, multiPart, ClientResponse.Status.CREATED, ClientResponse.Status.ACCEPTED, ClientResponse.Status.OK); URI uri = response.getLocation(); ContentResourceImpl resourceImpl = new ContentResourceImpl(feedResource, uri); final Content lastReadStateOfEntity = resourceImpl.getLastReadStateOfEntity(); Assert.assertNotNull(lastReadStateOfEntity); Assert.assertNotNull(lastReadStateOfEntity.getFieldsMap().get("directEnumFieldCopy")); Assert.assertNotNull(lastReadStateOfEntity.getFieldsMap().get("dynaField")); Assert.assertEquals(lastReadStateOfEntity.getFieldsMap().get("directEnumField").getValue().getValue(), lastReadStateOfEntity.getFieldsMap().get("directEnumFieldCopy").getValue().getValue()); String dynaField = lastReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue(); sleep(); final Content reReadStateOfEntity = client.resource(resourceImpl.getUri()).accept(MediaType.APPLICATION_JSON). header("Pragma", "no-cache").get(Content.class); Assert.assertEquals(dynaField, reReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue()); } { final Properties properties = new Properties(); properties.load(getClass().getClassLoader().getResourceAsStream( "contentcoprocessors/form-value-read.properties")); Set<Object> formKeys = properties.keySet(); FormDataMultiPart multiPart = new FormDataMultiPart(); for (Object key : formKeys) { multiPart.field(key.toString(), properties.getProperty(key.toString())); } ClientResponse response = feedResource.getContents().post(MediaType.MULTIPART_FORM_DATA, multiPart, ClientResponse.Status.CREATED, ClientResponse.Status.ACCEPTED, ClientResponse.Status.OK); URI uri = response.getLocation(); ContentResourceImpl resourceImpl = new ContentResourceImpl(feedResource, uri); final Content lastReadStateOfEntity = resourceImpl.getLastReadStateOfEntity(); Assert.assertNotNull(lastReadStateOfEntity); Assert.assertNotNull(lastReadStateOfEntity.getFieldsMap().get("directEnumFieldCopy")); Assert.assertNotNull(lastReadStateOfEntity.getFieldsMap().get("dynaField")); Assert.assertEquals(lastReadStateOfEntity.getFieldsMap().get("directEnumField").getValue().getValue(), lastReadStateOfEntity.getFieldsMap().get("directEnumFieldCopy").getValue().getValue()); String dynaField = lastReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue(); sleep(); final Content reReadStateOfEntity = client.resource(resourceImpl.getUri()).accept(MediaType.APPLICATION_JSON). header("Pragma", "no-cache").get(Content.class); Assert.assertFalse(dynaField.equals(reReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue())); } sleep(); } private WorkspaceFeedResource setupSequenceWorkspace() { RootResource resource = RootResourceImpl.getRoot(URI.create(ROOT_URI_STRING)); resource.get(); WorkspaceFeedResource feedResource; try { feedResource = resource.getTemplates().getWorkspaceResource("test", "sequences"); } catch (Exception ex) { feedResource = null; LOGGER.info("Exception getting feed resoruce", ex); } boolean valid = false; { try { final WorkspaceIdImpl workspaceId = new WorkspaceIdImpl("test", "sequences"); if (feedResource == null) { Workspace workspace = resource.createWorkspace(workspaceId); feedResource = resource.getTemplates().getWorkspaceResource(workspace.getId().getGlobalNamespace(), workspace. getId().getName()); } valid = true; } catch (Exception ex) { LOGGER.error("Error creating test workspace for templates", ex); } } Assert.assertTrue(valid); return feedResource; } @Test public void testCreateSequences() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Create Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.putSequence(workspace.getId(), TEST, PORT); Assert.assertNotNull(sequence); Assert.assertEquals(workspace.getId(), sequence.getWorkspace()); Assert.assertEquals(TEST, sequence.getName()); Assert.assertEquals(PORT, sequence.getCurrentValue()); sleep(); } @Test public void testGetSequence() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Get Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertNotNull(sequence); Assert.assertEquals(workspace.getId(), sequence.getWorkspace()); Assert.assertEquals(TEST, sequence.getName()); Assert.assertEquals(PORT, sequence.getCurrentValue()); Collection<Sequence> sequences = workspaceApi.getSequencesForWorkspace(workspace.getId()); Assert.assertNotNull(sequences); Assert.assertEquals(1, sequences.size()); sequence = sequences.iterator().next(); Assert.assertNotNull(sequence); Assert.assertEquals(workspace.getId(), sequence.getWorkspace()); Assert.assertEquals(TEST, sequence.getName()); Assert.assertEquals(PORT, sequence.getCurrentValue()); sleep(); } @Test public void testBasicSequenceModifications() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Basic Modify Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); long newVal = workspaceApi.modifySequenceValue(sequence, 1); Assert.assertEquals(PORT + 1, newVal); newVal = workspaceApi.modifySequenceValue(sequence, -2); Assert.assertEquals(PORT - 1, newVal); newVal = workspaceApi.modifySequenceValue(sequence, 1); Assert.assertEquals(PORT, newVal); sleep(); } @Test public void testSingleJVMMultiThreadedSequenceModifications() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Multithread modify Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); final Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); final ConcurrentHashSet<Long> vals = new ConcurrentHashSet<Long>(); Runnable runnable = new Runnable() { public void run() { for (int i = 0; i < 100; ++i) { long newVal = workspaceApi.modifySequenceValue(sequence, 1); Assert.assertTrue(vals.add(newVal)); } } }; long start = System.currentTimeMillis(); Collection<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < 10; ++i) { Thread thread = new Thread(runnable); thread.start(); threads.add(thread); } try { for (Thread thread : threads) { thread.join(); } } catch (Exception ex) { LOGGER.error("Could wait for thread to end!", ex); throw new IllegalArgumentException(ex); } long end = System.currentTimeMillis(); sleep(); Sequence lsequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertEquals(PORT + 1000, lsequence.getCurrentValue()); LOGGER.info("Duration for 1000 increments " + (end - start) + "ms"); } @Test public void testDeleteSequence() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Delete Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertNotNull(sequence); workspaceApi.deleteSequence(workspace.getId(), TEST); sequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertNull(sequence); sleep(); Collection<Sequence> sequences = workspaceApi.getSequencesForWorkspace(workspace.getId()); Assert.assertNotNull(sequences); Assert.assertEquals(0, sequences.size()); } @Test public void testCreateSequencesViaWebService() { WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceSequencesResource sequences = resource.getSequences(); Assert.assertNotNull(sequences); sequences.createSequence(TEST, PORT); sleep(); sequences.get(); Collection<WorkspaceSequenceResource> seqs = sequences.getSequences(); Assert.assertEquals(1, seqs.size()); WorkspaceSequenceResource seq = sequences.getSequenceByName(TEST); Assert.assertEquals(TEST, seq.getName()); Assert.assertEquals(PORT, seq.getCurrentValue()); } @Test public void testUpdateSequenceViaWebService() { WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceSequencesResource sequences = resource.getSequences(); Assert.assertNotNull(sequences); WorkspaceSequenceResource seq = sequences.getSequenceByName(TEST); Assert.assertNotNull(seq); long newVal = seq.update(1); Assert.assertEquals(TEST, seq.getName()); Assert.assertEquals(PORT + 1, newVal); sleep(); } @Test public void testDeleteSequenceViaWebService() { WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceSequencesResource sequences = resource.getSequences(); Assert.assertNotNull(sequences); WorkspaceSequenceResource seq = sequences.getSequenceByName(TEST); Assert.assertNotNull(seq); seq.delete(ClientResponse.Status.ACCEPTED); try { seq = sequences.getSequenceByName(TEST); } catch (Exception ex) { //Expected } sleep(); } @Test public void testDeleteWorkspace() { LOGGER.info("::::::::::::::::::::: TEST DELETE WORKSPACE ::::::::::::::::::::::"); // create a workspace for delete WorkspaceId workspaceForDeleteId = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspace("wsfordelete"); //SmartContentAPI.getInstance().getWorkspaceApi().createWorkspace(workspaceForDeleteId); com.smartitengineering.cms.api.workspace.Workspace workSpaceForDelete = SmartContentAPI.getInstance(). getWorkspaceApi().getWorkspace(workspaceForDeleteId); Assert.assertNotNull(workSpaceForDelete); // create content type InputStream stream = getClass().getClassLoader().getResourceAsStream("content-type-for-delete.xml"); try { final ContentTypeLoader contentTypeLoader = SmartContentAPI.getInstance().getContentTypeLoader(); final Collection<WritableContentType> types; types = contentTypeLoader.parseContentTypes(workSpaceForDelete.getId(), stream, com.smartitengineering.cms.api.common.MediaType.APPLICATION_XML); for (WritableContentType type : types) { type.put(); } } catch (Exception ex) { LOGGER.info("Can not create ContentType for delete", ex); Assert.fail(); } ContentTypeId contentTypeId = SmartContentAPI.getInstance().getContentTypeLoader().createContentTypeId( workspaceForDeleteId, "com.smartitengineering.smart-shopping.content", "ContentTypeForDelete"); ContentType contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); Assert.assertNotNull(contentType); // create content String statusKey = contentType.getStatuses().keySet().iterator().next(); ContentStatus contentStatus = contentType.getStatuses().get(statusKey); final WriteableContent writeableContent; MutableContent mutableContent = SmartContentAPI.getInstance().getContentLoader().createContent(contentType); mutableContent.setContentDefinition(contentType); mutableContent.setPrivate(false); mutableContent.setStatus(contentStatus); MutableField mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); mutableField.setName("name"); MutableFieldValue<String> mutableFieldValue = new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); mutableFieldValue.setValue("russel"); mutableField.setValue(mutableFieldValue); mutableContent.setField(mutableField); //Create new content writeableContent = SmartContentAPI.getInstance().getContentLoader().getWritableContent(mutableContent); writeableContent.createContentId(workspaceForDeleteId); try { //Save or update the content, will be decided by writeable content implementation writeableContent.put(); } catch (IOException ex) { LOGGER.error(ex.getMessage(), ex); Assert.fail(); } SmartContentAPI.getInstance().getWorkspaceApi().deleteWorkspace(workspaceForDeleteId); + sleep(); com.smartitengineering.cms.api.workspace.Workspace fetchedWorkspace = SmartContentAPI.getInstance().getWorkspaceApi(). getWorkspace(workspaceForDeleteId); if (fetchedWorkspace == null) { LOGGER.info("Fetched workspace null"); } Assert.assertNull(fetchedWorkspace); contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); Assert.assertNull(contentType); final WriteableContent writeableContentForDeleteTest; mutableContent = SmartContentAPI.getInstance().getContentLoader().createContent(contentType); mutableContent.setContentDefinition(contentType); mutableContent.setPrivate(false); mutableContent.setStatus(contentStatus); mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); mutableField.setName("name"); mutableFieldValue = new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); mutableFieldValue.setValue("russel"); mutableField.setValue(mutableFieldValue); mutableContent.setField(mutableField); //Create new content writeableContentForDeleteTest = SmartContentAPI.getInstance().getContentLoader().getWritableContent(mutableContent); writeableContentForDeleteTest.createContentId(workspaceForDeleteId); try { //Save or update the content, will be decided by writeable content implementation writeableContentForDeleteTest.put(); Assert.fail(); } catch (IOException ex) { LOGGER.info("should fail"); } } @Test public void testDeleteWorkspaceViaWebservice() { } protected void sleep() { try { Thread.sleep(SLEEP_DURATION); } catch (Exception ex) { LOGGER.error("Error sleeping", ex); } } public static class ConfigurationModule extends AbstractModule { @Override protected void configure() { bind(Configuration.class).toInstance(TEST_UTIL.getConfiguration()); ConnectionConfig config = new ConnectionConfig(); config.setBasicUri(""); config.setContextPath("/"); config.setHost("localhost"); config.setPort(PORT); bind(ConnectionConfig.class).toInstance(config); } } }
SmartITEngineering/smart-cms
a0014dd497dfdcf051f7ec3c3fbb17a216640867
Deleteing dependencies of workspace in different thread
diff --git a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/workspace/WorkspaceAPIImpl.java b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/workspace/WorkspaceAPIImpl.java index 42d8e0b..e7fdeaf 100644 --- a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/workspace/WorkspaceAPIImpl.java +++ b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/workspace/WorkspaceAPIImpl.java @@ -1,973 +1,995 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.api.impl.workspace; import com.google.inject.Inject; import com.google.inject.name.Named; import com.smartitengineering.cms.api.common.CacheableResource; +import com.smartitengineering.cms.api.common.SearchResult; import com.smartitengineering.cms.api.common.TemplateType; +import com.smartitengineering.cms.api.content.Content; import com.smartitengineering.cms.api.content.ContentId; +import com.smartitengineering.cms.api.content.Filter; import com.smartitengineering.cms.api.content.template.ContentCoProcessor; import com.smartitengineering.cms.api.content.template.FieldValidator; import com.smartitengineering.cms.api.content.template.RepresentationGenerator; import com.smartitengineering.cms.api.content.template.VariationGenerator; import com.smartitengineering.cms.api.event.Event; import com.smartitengineering.cms.api.event.Event.EventType; import com.smartitengineering.cms.api.event.Event.Type; import com.smartitengineering.cms.api.exception.InvalidTemplateException; import com.smartitengineering.cms.api.factory.SmartContentAPI; import com.smartitengineering.cms.api.factory.type.WritableContentType; import com.smartitengineering.cms.api.factory.workspace.WorkspaceAPI; +import com.smartitengineering.cms.api.impl.content.FilterImpl; import com.smartitengineering.cms.api.type.ContentType; import com.smartitengineering.cms.api.type.ValidatorType; import com.smartitengineering.cms.api.workspace.*; import com.smartitengineering.cms.spi.SmartContentSPI; import com.smartitengineering.cms.spi.content.template.ContentCoProcessorGenerator; import com.smartitengineering.cms.spi.content.template.TypeFieldValidator; import com.smartitengineering.cms.spi.content.template.TypeRepresentationGenerator; import com.smartitengineering.cms.spi.content.template.TypeVariationGenerator; import com.smartitengineering.dao.common.cache.CacheServiceProvider; import com.smartitengineering.dao.common.cache.Lock; import com.smartitengineering.dao.common.cache.Mutex; import com.smartitengineering.dao.common.cache.impl.CacheAPIFactory; import java.io.IOException; import java.io.InputStream; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.Map.Entry; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author imyousuf */ public class WorkspaceAPIImpl implements WorkspaceAPI { private String globalNamespace; private final transient Logger logger = LoggerFactory.getLogger(getClass()); @Inject private Map<TemplateType, ContentCoProcessorGenerator> contentCoProcessorGenerators; @Inject private Map<TemplateType, TypeRepresentationGenerator> representationGenerators; @Inject private Map<TemplateType, TypeVariationGenerator> variationGenerators; @Inject private Map<ValidatorType, TypeFieldValidator> validatorGenerators; @Inject private CacheServiceProvider<WorkspaceResourceCacheKey, CacheableResource> resourcesCache; protected final Mutex<WorkspaceResourceCacheKey> mutex = CacheAPIFactory.<WorkspaceResourceCacheKey>getMutex(); public CacheServiceProvider<WorkspaceResourceCacheKey, CacheableResource> getResourcesCache() { return resourcesCache; } public void setResourcesCache(CacheServiceProvider<WorkspaceResourceCacheKey, CacheableResource> resourcesCache) { this.resourcesCache = resourcesCache; } public Map<TemplateType, ContentCoProcessorGenerator> getContentCoProcessorGenerators() { return contentCoProcessorGenerators; } public void setContentCoProcessorGenerators( Map<TemplateType, ContentCoProcessorGenerator> contentCoProcessorGenerators) { this.contentCoProcessorGenerators = contentCoProcessorGenerators; } public Map<TemplateType, TypeRepresentationGenerator> getRepresentationGenerators() { return representationGenerators; } public void setRepresentationGenerators(Map<TemplateType, TypeRepresentationGenerator> representationGenerators) { this.representationGenerators = representationGenerators; } public Map<ValidatorType, TypeFieldValidator> getValidatorGenerators() { return validatorGenerators; } public void setValidatorGenerators(Map<ValidatorType, TypeFieldValidator> validatorGenerators) { this.validatorGenerators = validatorGenerators; } public Map<TemplateType, TypeVariationGenerator> getVariationGenerators() { return variationGenerators; } public void setVariationGenerators(Map<TemplateType, TypeVariationGenerator> variationGenerators) { this.variationGenerators = variationGenerators; } @Inject public void setGlobalNamespace(@Named("globalNamespace") String globalNamespace) { this.globalNamespace = globalNamespace; } @Override public String getGlobalNamespace() { return globalNamespace; } @Override public WorkspaceId createWorkspace(String name) { WorkspaceId workspaceIdImpl = createWorkspaceId(name); return createWorkspace(workspaceIdImpl); } @Override public WorkspaceId createWorkspace(String globalNamespace, String name) { return createWorkspace(createWorkspaceId(globalNamespace, name)); } @Override public WorkspaceId createWorkspace(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().create(workspaceId); Event<Workspace> event = SmartContentAPI.getInstance().getEventRegistrar().<Workspace>createEvent( EventType.UPDATE, Type.WORKSPACE, getWorkspace(workspaceId)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); return workspaceId; } @Override public WorkspaceId createWorkspaceId(String name) { return createWorkspaceId(null, name); } @Override public WorkspaceId createWorkspaceId(final String namespace, String name) { final WorkspaceIdImpl workspaceIdImpl = new WorkspaceIdImpl(); workspaceIdImpl.setGlobalNamespace(StringUtils.isBlank(namespace) ? getGlobalNamespace() : namespace); workspaceIdImpl.setName(name); return workspaceIdImpl; } @Override public WorkspaceId getWorkspaceIdIfExists(String name) { final WorkspaceId createdWorkspaceId = createWorkspaceId(name); return getWorkspaceIdIfExists(createdWorkspaceId); } @Override public WorkspaceId getWorkspaceIdIfExists(WorkspaceId workspaceId) { Workspace workspace = getWorkspace(workspaceId); if (workspace != null) { return workspaceId; } return null; } @Override public Workspace getWorkspace(WorkspaceId workspaceId) { return SmartContentSPI.getInstance().getWorkspaceService().load(workspaceId); } @Override public Collection<Workspace> getWorkspaces() { return SmartContentSPI.getInstance().getWorkspaceService().getWorkspaces(); } @Override public RepresentationTemplate putRepresentationTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException { return putRepresentationTemplate(to, name, templateType, IOUtils.toByteArray(stream)); } @Override public RepresentationTemplate putRepresentationTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data) { final RepresentationTemplate putRepresentationTemplate = SmartContentSPI.getInstance().getWorkspaceService(). putRepresentationTemplate(to, name, templateType, data); Event<RepresentationTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<RepresentationTemplate> createEvent(EventType.UPDATE, Type.REPRESENTATION_TEMPLATE, putRepresentationTemplate); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); if (resourcesCache != null) { WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(to, WorkspaceResourceCacheKey.WorkspaceResourceType.REPRESENTATION_GEN, name); resourcesCache.expireFromCache(key); } return putRepresentationTemplate; } @Override public VariationTemplate putVariationTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException { return putVariationTemplate(to, name, templateType, IOUtils.toByteArray(stream)); } @Override public VariationTemplate putVariationTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data) { final VariationTemplate putVariationTemplate = SmartContentSPI.getInstance().getWorkspaceService(). putVariationTemplate(to, name, templateType, data); Event<VariationTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<VariationTemplate> createEvent(EventType.UPDATE, Type.VARIATION_TEMPLATE, putVariationTemplate); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); if (resourcesCache != null) { WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(to, WorkspaceResourceCacheKey.WorkspaceResourceType.VARIATION_GEN, name); resourcesCache.expireFromCache(key); } return putVariationTemplate; } @Override public void delete(RepresentationTemplate template) { SmartContentSPI.getInstance().getWorkspaceService().deleteRepresentation(template); Event<RepresentationTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<RepresentationTemplate> createEvent(EventType.DELETE, Type.REPRESENTATION_TEMPLATE, template); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void delete(VariationTemplate template) { SmartContentSPI.getInstance().getWorkspaceService().deleteVariation(template); Event<VariationTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<VariationTemplate> createEvent(EventType.DELETE, Type.VARIATION_TEMPLATE, template); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public Collection<WorkspaceId> getFriendlies(WorkspaceId workspaceId) { return SmartContentSPI.getInstance().getWorkspaceService().getFriendlies(workspaceId); } @Override public void addFriend(WorkspaceId to, WorkspaceId... workspaceIds) { SmartContentSPI.getInstance().getWorkspaceService().addFriend(to, workspaceIds); for (WorkspaceId friend : workspaceIds) { Event<Entry<WorkspaceId, WorkspaceId>> event = SmartContentAPI.getInstance().getEventRegistrar().<Entry<WorkspaceId, WorkspaceId>> createEvent(EventType.CREATE, Type.FRIENDLY, new SimpleEntry<WorkspaceId, WorkspaceId>(to, friend)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } } @Override public void removeFriend(WorkspaceId from, WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeFriend(from, workspaceId); Event<Entry<WorkspaceId, WorkspaceId>> event = SmartContentAPI.getInstance().getEventRegistrar().<Entry<WorkspaceId, WorkspaceId>> createEvent(EventType.DELETE, Type.FRIENDLY, new SimpleEntry<WorkspaceId, WorkspaceId>(from, workspaceId)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void removeAllFriendlies(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllFriendlies(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_FRIENDLIES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void removeAllRepresentationTemplates(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllRepresentationTemplates(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_REPRESENTATION_TEMPLATES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void removeAllVariationTemplates(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllVariationTemplates(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_VARIATION_TEMPLATES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public Collection<String> getRepresentationNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count) { if (count == 0 || startPoint == null) { return Collections.emptyList(); } List<String> list = new ArrayList<String>(getRepresentationNames(id, criteria)); return cutList(list, startPoint, count); } @Override public Collection<String> getVariationNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count) { if (count == 0 || startPoint == null) { return Collections.emptyList(); } List<String> list = new ArrayList<String>(getVariationNames(id, criteria)); return cutList(list, startPoint, count); } @Override public Collection<String> getRepresentationNames(WorkspaceId id, ResourceSortCriteria criteria) { final Collection<? extends ResourceTemplate> repsWithoutData = SmartContentSPI.getInstance(). getWorkspaceService().getRepresentationsWithoutData(id, criteria); return getResourceNames(repsWithoutData); } @Override public Collection<String> getVariationNames(WorkspaceId id, ResourceSortCriteria criteria) { final Collection<? extends ResourceTemplate> variationsWithoutData = SmartContentSPI.getInstance(). getWorkspaceService().getVariationsWithoutData(id, criteria); return getResourceNames(variationsWithoutData); } protected Collection<String> getResourceNames(Collection<? extends ResourceTemplate> templates) { ArrayList<String> list = new ArrayList<String>(templates.size()); for (ResourceTemplate template : templates) { list.add(template.getName()); } return list; } protected Collection<String> getValidatorNames(Collection<ValidatorTemplate> templates) { ArrayList<String> list = new ArrayList<String>(templates.size()); for (ValidatorTemplate template : templates) { list.add(template.getName()); } return list; } @Override public Collection<String> getRepresentationNames(WorkspaceId id) { return getRepresentationNames(id, ResourceSortCriteria.BY_NAME); } @Override public Collection<String> getVariationNames(WorkspaceId id) { return getVariationNames(id, ResourceSortCriteria.BY_NAME); } @Override public Collection<String> getRepresentationNames(WorkspaceId id, String startPoint, int count) { return getRepresentationNames(id, ResourceSortCriteria.BY_NAME, startPoint, count); } @Override public Collection<String> getVariationNames(WorkspaceId id, String startPoint, int count) { return getVariationNames(id, ResourceSortCriteria.BY_NAME, startPoint, count); } @Override public RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getRepresentationTemplate(id, name); } @Override public VariationTemplate getVariationTemplate(WorkspaceId id, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getVariationTemplate(id, name); } @Override public String getEntityTagValueForResourceTemplate(ResourceTemplate template) { final String toString = new StringBuilder(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(template. getLastModifiedDate())).append(':').append(Arrays.toString(template.getTemplate())).append(':').append(template. getTemplateType().name()).toString(); final String etag = DigestUtils.md5Hex(toString); if (logger.isDebugEnabled()) { logger.debug("Generated etag " + etag + " for " + template.getClass().getName() + " with name " + template.getName()); } return etag; } @Override public Collection<ContentId> getRootContents(WorkspaceId workspaceId) { return SmartContentSPI.getInstance().getWorkspaceService().getRootContents(workspaceId); } @Override public void addRootContent(WorkspaceId to, ContentId... contentIds) { SmartContentSPI.getInstance().getWorkspaceService().addRootContent(to, contentIds); for (ContentId rootContent : contentIds) { Event<Entry<WorkspaceId, ContentId>> event = SmartContentAPI.getInstance().getEventRegistrar().<Entry<WorkspaceId, ContentId>> createEvent(EventType.CREATE, Type.ROOT_CONTENT, new SimpleEntry<WorkspaceId, ContentId>(to, rootContent)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } } @Override public void removeRootContent(WorkspaceId from, ContentId contentId) { SmartContentSPI.getInstance().getWorkspaceService().removeRootContent(from, contentId); Event<Entry<WorkspaceId, ContentId>> event = SmartContentAPI.getInstance().getEventRegistrar().<Entry<WorkspaceId, ContentId>> createEvent(EventType.DELETE, Type.ROOT_CONTENT, new SimpleEntry<WorkspaceId, ContentId>(from, contentId)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void removeAllRootContents(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllRootContents(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_ROOT_CONTENTS, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public ValidatorTemplate getValidatorTemplate(WorkspaceId workspaceId, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getValidationTemplate(workspaceId, name); } @Override public void delete(ValidatorTemplate template) { SmartContentSPI.getInstance().getWorkspaceService().deleteValidator(template); Event<ValidatorTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<ValidatorTemplate> createEvent(EventType.DELETE, Type.VALIDATION_TEMPLATE, template); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public ValidatorTemplate putValidatorTemplate(WorkspaceId to, String name, ValidatorType templateType, InputStream stream) throws IOException { return putValidatorTemplate(to, name, templateType, IOUtils.toByteArray(stream)); } @Override public ValidatorTemplate putValidatorTemplate(WorkspaceId to, String name, ValidatorType templateType, byte[] data) { final ValidatorTemplate validatorTemplate = SmartContentSPI.getInstance().getWorkspaceService().putValidatorTemplate( to, name, templateType, data); Event<ValidatorTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<ValidatorTemplate> createEvent(EventType.UPDATE, Type.VALIDATION_TEMPLATE, validatorTemplate); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); if (resourcesCache != null) { WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(to, WorkspaceResourceCacheKey.WorkspaceResourceType.VALIDATION_SCR, name); resourcesCache.expireFromCache(key); } return validatorTemplate; } @Override public String getEntityTagValueForValidatorTemplate(ValidatorTemplate template) { final String toString = new StringBuilder(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(template. getLastModifiedDate())).append(':').append(Arrays.toString(template.getTemplate())).append(':').append(template. getTemplateType().name()).toString(); final String etag = DigestUtils.md5Hex(toString); if (logger.isDebugEnabled()) { logger.debug("Generated etag " + etag + " for " + template.getClass().getName() + " with name " + template.getName()); } return etag; } @Override public Collection<String> getValidatorNames(WorkspaceId id) { return getVariationNames(id, ResourceSortCriteria.BY_NAME); } @Override public Collection<String> getValidatorNames(WorkspaceId id, String startPoint, int count) { return getVariationNames(id, ResourceSortCriteria.BY_NAME, startPoint, count); } @Override public Collection<String> getValidatorNames(WorkspaceId id, ResourceSortCriteria criteria) { final Collection<ValidatorTemplate> variationsWithoutData = SmartContentSPI.getInstance().getWorkspaceService(). getValidatorsWithoutData(id, criteria); return getValidatorNames(variationsWithoutData); } @Override public Collection<String> getValidatorNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count) { if (count == 0 || startPoint == null) { return Collections.emptyList(); } List<String> list = new ArrayList<String>(getValidatorNames(id, criteria)); return cutList(list, startPoint, count); } @Override public void removeAllValidatorTemplates(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllValidatorTemplates(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_VALIDATION_TEMPLATES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } protected Collection<String> cutList(List<String> list, String startPoint, int count) { if (logger.isDebugEnabled()) { logger.debug("All names " + list); } int index = Collections.binarySearch(list, startPoint); if (logger.isDebugEnabled()) { logger.debug("Index " + index); } if (index < 0) { index = index * - 1; } if (count > 0 && index + 1 >= list.size() && StringUtils.isNotBlank(startPoint)) { logger.debug("Index is equal to size and count is greater than 0"); return Collections.emptyList(); } if (count < 0 && index <= 0) { logger.debug("Index is zero to size and count is smaller than 0"); return Collections.emptyList(); } final int fromIndex; final int toIndex; if (count > 0) { fromIndex = StringUtils.isBlank(startPoint) ? 0 : index + 1; toIndex = (fromIndex + count >= list.size()) ? list.size() : fromIndex + count; } else { toIndex = index; fromIndex = (toIndex + count >= 0) ? toIndex + count : 0; } if (logger.isDebugEnabled()) { logger.debug("Sublisting starts at " + fromIndex + " and ends before " + toIndex); } final List<String> result = list.subList(fromIndex, toIndex); if (logger.isDebugEnabled()) { logger.debug("Returning " + result); } return result; } public void delete(ContentCoProcessorTemplate template) { SmartContentSPI.getInstance().getWorkspaceService().deleteContentCoProcessor(template); Event<ContentCoProcessorTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<ContentCoProcessorTemplate> createEvent(EventType.DELETE, Type.CONTENT_CO_PROCESSOR_TEMPLATE, template); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } public ContentCoProcessorTemplate putContentCoProcessorTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException { return putContentCoProcessorTemplate(to, name, templateType, IOUtils.toByteArray(stream)); } public ContentCoProcessorTemplate putContentCoProcessorTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data) { if (templateType.equals(TemplateType.JASPER) || templateType.equals(TemplateType.VELOCITY)) { throw new IllegalArgumentException("TemplateType not supported for content type co processor"); } final ContentCoProcessorTemplate temp = SmartContentSPI.getInstance().getWorkspaceService(). putContentCoProcessorTemplate(to, name, templateType, data); Event<ContentCoProcessorTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<ContentCoProcessorTemplate> createEvent(EventType.UPDATE, Type.CONTENT_CO_PROCESSOR_TEMPLATE, temp); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); if (resourcesCache != null) { WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(to, WorkspaceResourceCacheKey.WorkspaceResourceType.CONTENT_CO_PROCESSOR_GEN, name); resourcesCache.expireFromCache(key); } return temp; } public ContentCoProcessorTemplate getContentCoProcessorTemplate(WorkspaceId id, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getContentCoProcessorTemplate(id, name); } public void removeAllContentCoProcessorTemplates(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllContentCoProcessorTemplates(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_CONTENT_CO_PROCESSOR_TEMPLATES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } public ContentCoProcessor getContentCoProcessor(WorkspaceId id, String name) { return getContentCoProcessor(id, name, true); } public ContentCoProcessor getContentCoProcessor(final WorkspaceId id, final String name, final boolean searchInFriendlies) { if (id == null || StringUtils.isBlank(name)) { logger.warn("Null workspace id or blank name!"); return null; } WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(id, WorkspaceResourceCacheKey.WorkspaceResourceType.CONTENT_CO_PROCESSOR_GEN, name); CacheThroughReader<ContentCoProcessor> reader = new CacheThroughReader<ContentCoProcessor>(key, new Lookup<ContentCoProcessor>() { public ContentCoProcessor get() { ContentCoProcessorTemplate template = getContentCoProcessorTemplate(id, name, searchInFriendlies); return getContentCoProcessor(template); } }); return reader.read(); } public FieldValidator getFieldValidator(WorkspaceId id, String name) { return getFieldValidator(id, name, true); } public FieldValidator getFieldValidator(final WorkspaceId id, final String name, final boolean searchInFriendlies) { if (id == null || StringUtils.isBlank(name)) { logger.warn("Null workspace id or blank name!"); return null; } WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(id, WorkspaceResourceCacheKey.WorkspaceResourceType.VALIDATION_SCR, name); CacheThroughReader<FieldValidator> reader = new CacheThroughReader<FieldValidator>(key, new Lookup<FieldValidator>() { public FieldValidator get() { ValidatorTemplate template = getValidatorTemplate(id, name, searchInFriendlies); if (template == null) { logger.info("Validator template is null, returning true!"); return null; } return getFieldValidator(template); } }); return reader.read(); } public RepresentationGenerator getRepresentationGenerator(WorkspaceId id, String name) { return getRepresentationGenerator(id, name, true); } public RepresentationGenerator getRepresentationGenerator(final WorkspaceId workspaceId, final String name, final boolean searchInFriendlies) { if (workspaceId == null || StringUtils.isBlank(name)) { logger.warn("Null workspace id or blank name!"); return null; } WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(workspaceId, WorkspaceResourceCacheKey.WorkspaceResourceType.REPRESENTATION_GEN, name); CacheThroughReader<RepresentationGenerator> reader = new CacheThroughReader<RepresentationGenerator>(key, new Lookup<RepresentationGenerator>() { public RepresentationGenerator get() { RepresentationTemplate representationTemplate = getRepresentationTemplate(workspaceId, name, searchInFriendlies); return getRepresentationGenerator(representationTemplate); } }); return reader.read(); } public VariationGenerator getVariationGenerator(WorkspaceId id, String name) { return getVariationGenerator(id, name, true); } public VariationGenerator getVariationGenerator(final WorkspaceId workspaceId, final String name, final boolean searchInFriendlies) { if (workspaceId == null || StringUtils.isBlank(name)) { logger.warn("Null workspace id or blank name!"); return null; } WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(workspaceId, WorkspaceResourceCacheKey.WorkspaceResourceType.VARIATION_GEN, name); CacheThroughReader<VariationGenerator> reader = new CacheThroughReader<VariationGenerator>(key, new Lookup<VariationGenerator>() { public VariationGenerator get() { VariationTemplate variationTemplate = getVariationTemplate(workspaceId, name, searchInFriendlies); return getVariationGenerator(variationTemplate); } }); return reader.read(); } public Collection<String> getContentCoProcessorNames(WorkspaceId id, ResourceSortCriteria criteria) { final Collection<ContentCoProcessorTemplate> procsWithoutData = SmartContentSPI.getInstance(). getWorkspaceService().getContentCoProcessorsWithoutData(id, criteria); return getResourceNames(procsWithoutData); } public Collection<String> getContentCoProcessorNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count) { if (count == 0 || startPoint == null) { return Collections.emptyList(); } List<String> list = new ArrayList<String>(getContentCoProcessorNames(id, criteria)); return cutList(list, startPoint, count); } public Collection<String> getContentCoProcessorNames(WorkspaceId id) { return getContentCoProcessorNames(id, ResourceSortCriteria.BY_NAME); } public Collection<String> getContentCoProcessorNames(WorkspaceId id, String startPoint, int count) { return getContentCoProcessorNames(id, ResourceSortCriteria.BY_NAME, startPoint, count); } public ContentCoProcessorTemplate getContentCoProcessorTemplate(WorkspaceId id, String name, boolean searchInFriendlies) { ContentCoProcessorTemplate template = getContentCoProcessorTemplate(id, name); if (searchInFriendlies && template == null) { //Lookup friendlies Collection<WorkspaceId> friends = SmartContentAPI.getInstance().getWorkspaceApi().getFriendlies(id); if (friends != null && !friends.isEmpty()) { Iterator<WorkspaceId> friendsIterator = friends.iterator(); while (template == null && friendsIterator.hasNext()) { template = SmartContentAPI.getInstance().getWorkspaceApi().getContentCoProcessorTemplate( friendsIterator.next(), name); } } } return template; } public RepresentationTemplate getRepresentationTemplate(WorkspaceId workspaceId, String name, boolean searchInFriendlies) { RepresentationTemplate representationTemplate = SmartContentAPI.getInstance().getWorkspaceApi().getRepresentationTemplate(workspaceId, name); if (searchInFriendlies && representationTemplate == null) { //Lookup friendlies Collection<WorkspaceId> friends = SmartContentAPI.getInstance().getWorkspaceApi().getFriendlies(workspaceId); if (friends != null && !friends.isEmpty()) { Iterator<WorkspaceId> friendsIterator = friends.iterator(); while (representationTemplate == null && friendsIterator.hasNext()) { representationTemplate = SmartContentAPI.getInstance().getWorkspaceApi().getRepresentationTemplate(friendsIterator. next(), name); } } } return representationTemplate; } public ValidatorTemplate getValidatorTemplate(WorkspaceId id, String name, boolean searchInFriendlies) { ValidatorTemplate template = SmartContentAPI.getInstance().getWorkspaceApi().getValidatorTemplate(id, name); if (searchInFriendlies && template == null) { //Lookup friendlies Collection<WorkspaceId> friends = SmartContentAPI.getInstance().getWorkspaceApi().getFriendlies(id); if (friends != null && !friends.isEmpty()) { Iterator<WorkspaceId> friendsIterator = friends.iterator(); while (template == null && friendsIterator.hasNext()) { template = SmartContentAPI.getInstance().getWorkspaceApi().getValidatorTemplate(friendsIterator.next(), name); } } } return template; } public VariationTemplate getVariationTemplate(WorkspaceId workspaceId, String name, boolean searchInFriendlies) { VariationTemplate variationTemplate = SmartContentAPI.getInstance().getWorkspaceApi().getVariationTemplate(workspaceId, name); if (searchInFriendlies && variationTemplate == null) { //Lookup friendlies Collection<WorkspaceId> friends = SmartContentAPI.getInstance().getWorkspaceApi().getFriendlies(workspaceId); if (friends != null && !friends.isEmpty()) { Iterator<WorkspaceId> friendsIterator = friends.iterator(); while (variationTemplate == null && friendsIterator.hasNext()) { variationTemplate = SmartContentAPI.getInstance().getWorkspaceApi().getVariationTemplate( friendsIterator.next(), name); } } } return variationTemplate; } public ContentCoProcessor getContentCoProcessor(ContentCoProcessorTemplate template) { if (template == null) { return null; } ContentCoProcessorGenerator generator = contentCoProcessorGenerators.get(template.getTemplateType()); try { return generator.getGenerator(template); } catch (Exception ex) { logger.warn("Could not retrieve processor", ex); return null; } } public RepresentationGenerator getRepresentationGenerator(RepresentationTemplate representationTemplate) { if (representationTemplate == null) { return null; } TypeRepresentationGenerator generator = representationGenerators.get(representationTemplate.getTemplateType()); if (generator == null) { return null; } try { return generator.getGenerator(representationTemplate); } catch (Exception ex) { logger.warn("Could not generate representation generator", ex); return null; } } public VariationGenerator getVariationGenerator(VariationTemplate variationTemplate) { if (variationTemplate == null) { return null; } TypeVariationGenerator generator = variationGenerators.get(variationTemplate.getTemplateType()); if (generator == null) { return null; } try { return generator.getGenerator(variationTemplate); } catch (Exception ex) { logger.warn("Could not generate variation generator", ex); return null; } } public FieldValidator getFieldValidator(ValidatorTemplate template) { TypeFieldValidator generator = validatorGenerators.get(template.getTemplateType()); if (generator == null) { logger.info("Validator generator is null, returning true!"); return null; } try { return generator.getValidator(template); } catch (InvalidTemplateException ex) { logger.error("Not a valid validator template!"); return null; } } public Sequence putSequence(WorkspaceId workspaceId, String name, long initialValue) { final Sequence created = SmartContentSPI.getInstance().getWorkspaceService().create(workspaceId, name, initialValue); Event<Sequence> event = SmartContentAPI.getInstance().getEventRegistrar().<Sequence>createEvent(EventType.CREATE, Type.SEQUENCE, created); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); return created; } public long modifySequenceValue(Sequence sequence, long delta) { final long newSequence = SmartContentSPI.getInstance().getWorkspaceService().modifySequenceValue(sequence, delta); return newSequence; } public Sequence getSequence(WorkspaceId workspaceId, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getSequence(workspaceId, name); } public void deleteSequence(WorkspaceId workspaceId, String name) { Sequence sequence = getSequence(workspaceId, name); if (sequence != null) { SmartContentSPI.getInstance().getWorkspaceService().deleteSequence(workspaceId, name); } Event<Sequence> event = SmartContentAPI.getInstance().getEventRegistrar().<Sequence>createEvent(EventType.DELETE, Type.SEQUENCE, sequence); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } public SequenceId createSequenceId(WorkspaceId workspaceId, String name) { SequenceIdImpl impl = new SequenceIdImpl(); impl.setName(name); impl.setWorkspaceId(workspaceId); return impl; } public Collection<Sequence> getSequencesForWorkspace(WorkspaceId workspaceId) { return SmartContentSPI.getInstance().getWorkspaceService().getSequencesForWorkspace(workspaceId); } public void reIndex(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().reIndex(workspaceId); } public void reIndex(SequenceId seqId) { SmartContentSPI.getInstance().getWorkspaceService().reIndex(seqId); } - public void deleteWorkspace(WorkspaceId workspaceId) { - Workspace workspace = SmartContentAPI.getInstance().getWorkspaceApi().getWorkspace(workspaceId); + public void deleteWorkspace(final WorkspaceId workspaceId) { + final Workspace workspace = SmartContentAPI.getInstance().getWorkspaceApi().getWorkspace(workspaceId); if (workspace == null) { throw new RuntimeException("Workspace not found"); } - Collection<ContentType> contentTypes = workspace.getContentDefintions(); - for (ContentType contentType : contentTypes) { - WritableContentType writableContentType = SmartContentAPI.getInstance().getContentTypeLoader(). - getWritableContentType(contentType); - try { - writableContentType.delete(); - } - catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - } - - SmartContentAPI.getInstance().getWorkspaceApi().removeAllContentCoProcessorTemplates(workspaceId); - SmartContentAPI.getInstance().getWorkspaceApi().removeAllFriendlies(workspaceId); - SmartContentAPI.getInstance().getWorkspaceApi().removeAllRepresentationTemplates(workspaceId); - SmartContentAPI.getInstance().getWorkspaceApi().removeAllRootContents(workspaceId); - SmartContentAPI.getInstance().getWorkspaceApi().removeAllValidatorTemplates(workspaceId); - SmartContentAPI.getInstance().getWorkspaceApi().removeAllVariationTemplates(workspaceId); - - Collection<ContentId> contentIds = workspace.getRootContents(); - for (ContentId contentId : contentIds) { - SmartContentAPI.getInstance().getWorkspaceApi().removeRootContent(workspaceId, contentId); - } logger.info("Deleting workspace from persister"); SmartContentSPI.getInstance().getWorkspaceService().delete(workspaceId); + + ExecutorService threadExecutor = Executors.newCachedThreadPool(); + threadExecutor.execute(new Runnable() { + + public void run() { + Collection<ContentType> contentTypes = workspace.getContentDefintions(); + for (ContentType contentType : contentTypes) { + WritableContentType writableContentType = SmartContentAPI.getInstance().getContentTypeLoader(). + getWritableContentType(contentType); + try { + writableContentType.delete(); + } + catch (Exception ex) { + logger.error(ex.getMessage(), ex); + } + } + + SmartContentAPI.getInstance().getWorkspaceApi().removeAllContentCoProcessorTemplates(workspaceId); + SmartContentAPI.getInstance().getWorkspaceApi().removeAllFriendlies(workspaceId); + SmartContentAPI.getInstance().getWorkspaceApi().removeAllRepresentationTemplates(workspaceId); + SmartContentAPI.getInstance().getWorkspaceApi().removeAllRootContents(workspaceId); + SmartContentAPI.getInstance().getWorkspaceApi().removeAllValidatorTemplates(workspaceId); + SmartContentAPI.getInstance().getWorkspaceApi().removeAllVariationTemplates(workspaceId); + + Filter filter = new FilterImpl(); + filter.setWorkspaceId(workspaceId); + + SearchResult<Content> contents = SmartContentAPI.getInstance().getContentLoader().search(filter); + + for (Content content : contents.getResult()) { + try { + SmartContentAPI.getInstance().getContentLoader().getWritableContent(content).delete(); + } + catch (Exception ex) { + logger.error(ex.getMessage(), ex); + } + } + } + }); } public interface Lookup<T> { T get(); } public class CacheThroughReader<T extends CacheableResource> { private final Lookup<T> lookup; private final WorkspaceResourceCacheKey key; public CacheThroughReader(WorkspaceResourceCacheKey key, Lookup<T> lookup) { this.lookup = lookup; this.key = key; } public T read() { if (resourcesCache == null) { logger.info("Avoiding cache through read as cache is null!"); return lookup.get(); } final Lock<WorkspaceResourceCacheKey> lock; try { lock = mutex.acquire(key); } catch (Exception ex) { logger.warn("Error retrieving lock", ex); throw new IllegalStateException(ex); } try { CacheableResource cachedResource = resourcesCache.retrieveFromCache(key); if (cachedResource != null) { return (T) cachedResource; } else { T result = lookup.get(); resourcesCache.putToCache(key, result); return result; } } catch (Exception ex) { logger.warn("Error in doing cache through read", ex); return null; } finally { mutex.release(lock); } } } }
SmartITEngineering/smart-cms
a67349383552753ffe2f0602e97f015d7cf8c553
Implemented workspace deletion with test case
diff --git a/api-modules/content-api-factory/src/main/java/com/smartitengineering/cms/api/factory/workspace/WorkspaceAPI.java b/api-modules/content-api-factory/src/main/java/com/smartitengineering/cms/api/factory/workspace/WorkspaceAPI.java index 6c3f57d..6a3431f 100644 --- a/api-modules/content-api-factory/src/main/java/com/smartitengineering/cms/api/factory/workspace/WorkspaceAPI.java +++ b/api-modules/content-api-factory/src/main/java/com/smartitengineering/cms/api/factory/workspace/WorkspaceAPI.java @@ -1,223 +1,218 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.api.factory.workspace; import com.smartitengineering.cms.api.common.TemplateType; import com.smartitengineering.cms.api.content.ContentId; import com.smartitengineering.cms.api.content.template.ContentCoProcessor; import com.smartitengineering.cms.api.content.template.FieldValidator; import com.smartitengineering.cms.api.content.template.RepresentationGenerator; import com.smartitengineering.cms.api.content.template.VariationGenerator; import com.smartitengineering.cms.api.type.ValidatorType; -import com.smartitengineering.cms.api.workspace.ContentCoProcessorTemplate; -import com.smartitengineering.cms.api.workspace.RepresentationTemplate; -import com.smartitengineering.cms.api.workspace.ResourceTemplate; -import com.smartitengineering.cms.api.workspace.Sequence; -import com.smartitengineering.cms.api.workspace.SequenceId; -import com.smartitengineering.cms.api.workspace.ValidatorTemplate; -import com.smartitengineering.cms.api.workspace.VariationTemplate; -import com.smartitengineering.cms.api.workspace.Workspace; -import com.smartitengineering.cms.api.workspace.WorkspaceId; +import com.smartitengineering.cms.api.workspace.*; import java.io.IOException; import java.io.InputStream; import java.util.Collection; /** * * @author imyousuf */ public interface WorkspaceAPI { String getGlobalNamespace(); WorkspaceId createWorkspaceId(String globalNamespace, String name); WorkspaceId createWorkspaceId(String name); WorkspaceId createWorkspace(String name); WorkspaceId createWorkspace(String globalNamespace, String name); WorkspaceId createWorkspace(WorkspaceId workspaceId); RepresentationTemplate putRepresentationTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException; RepresentationTemplate putRepresentationTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data); RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name); void delete(RepresentationTemplate template); void delete(VariationTemplate template); VariationTemplate putVariationTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException; VariationTemplate putVariationTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data); VariationTemplate getVariationTemplate(WorkspaceId id, String name); void delete(ContentCoProcessorTemplate template); ContentCoProcessorTemplate putContentCoProcessorTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException; ContentCoProcessorTemplate putContentCoProcessorTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data); ContentCoProcessorTemplate getContentCoProcessorTemplate(WorkspaceId id, String name); ContentCoProcessor getContentCoProcessor(WorkspaceId id, String name); public ContentCoProcessorTemplate getContentCoProcessorTemplate(WorkspaceId id, String name, boolean searchInFriendlies); public RepresentationTemplate getRepresentationTemplate(WorkspaceId workspaceId, String name, boolean searchInFriendlies); public ValidatorTemplate getValidatorTemplate(WorkspaceId id, String name, boolean searchInFriendlies); public VariationTemplate getVariationTemplate(WorkspaceId workspaceId, String name, boolean searchInFriendlies); RepresentationGenerator getRepresentationGenerator(WorkspaceId id, String name); VariationGenerator getVariationGenerator(WorkspaceId id, String name); FieldValidator getFieldValidator(WorkspaceId id, String name); ContentCoProcessor getContentCoProcessor(ContentCoProcessorTemplate template); RepresentationGenerator getRepresentationGenerator(RepresentationTemplate template); VariationGenerator getVariationGenerator(VariationTemplate template); FieldValidator getFieldValidator(ValidatorTemplate template); ContentCoProcessor getContentCoProcessor(WorkspaceId id, String name, boolean searchInFriendlies); RepresentationGenerator getRepresentationGenerator(WorkspaceId id, String name, boolean searchInFriendlies); VariationGenerator getVariationGenerator(WorkspaceId id, String name, boolean searchInFriendlies); FieldValidator getFieldValidator(WorkspaceId id, String name, boolean searchInFriendlies); WorkspaceId getWorkspaceIdIfExists(String name); WorkspaceId getWorkspaceIdIfExists(WorkspaceId workspaceId); Workspace getWorkspace(WorkspaceId workspaceId); Collection<Workspace> getWorkspaces(); public Collection<WorkspaceId> getFriendlies(WorkspaceId workspaceId); public void addFriend(WorkspaceId to, WorkspaceId... workspaceIds); public void removeFriend(WorkspaceId from, WorkspaceId workspaceId); public void removeAllFriendlies(WorkspaceId workspaceId); public void removeAllRepresentationTemplates(WorkspaceId workspaceId); public void removeAllVariationTemplates(WorkspaceId workspaceId); public void removeAllContentCoProcessorTemplates(WorkspaceId workspaceId); enum ResourceSortCriteria { BY_NAME, - BY_DATE,} + BY_DATE, + } public Collection<String> getRepresentationNames(WorkspaceId id); public Collection<String> getVariationNames(WorkspaceId id); public Collection<String> getRepresentationNames(WorkspaceId id, String startPoint, int count); public Collection<String> getVariationNames(WorkspaceId id, String startPoint, int count); public Collection<String> getRepresentationNames(WorkspaceId id, ResourceSortCriteria criteria); public Collection<String> getVariationNames(WorkspaceId id, ResourceSortCriteria criteria); public Collection<String> getContentCoProcessorNames(WorkspaceId id); public Collection<String> getContentCoProcessorNames(WorkspaceId id, String startPoint, int count); public Collection<String> getContentCoProcessorNames(WorkspaceId id, ResourceSortCriteria criteria); public Collection<String> getContentCoProcessorNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count); public Collection<String> getRepresentationNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count); public Collection<String> getVariationNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count); public String getEntityTagValueForResourceTemplate(ResourceTemplate resourceTemplate); public Collection<ContentId> getRootContents(WorkspaceId workspaceId); public void addRootContent(WorkspaceId to, ContentId... contentIds); public void removeRootContent(WorkspaceId from, ContentId contentId); public void removeAllRootContents(WorkspaceId workspaceId); ValidatorTemplate putValidatorTemplate(WorkspaceId to, String name, ValidatorType templateType, InputStream stream) throws IOException; ValidatorTemplate putValidatorTemplate(WorkspaceId to, String name, ValidatorType templateType, byte[] data); void delete(ValidatorTemplate template); public ValidatorTemplate getValidatorTemplate(WorkspaceId workspaceId, String name); public void removeAllValidatorTemplates(WorkspaceId workspaceId); public Collection<String> getValidatorNames(WorkspaceId id); public Collection<String> getValidatorNames(WorkspaceId id, String startPoint, int count); public Collection<String> getValidatorNames(WorkspaceId id, ResourceSortCriteria criteria); public Collection<String> getValidatorNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count); public String getEntityTagValueForValidatorTemplate(ValidatorTemplate validatorTemplate); public Sequence putSequence(WorkspaceId workspaceId, String name, long initialValue); public long modifySequenceValue(Sequence sequence, long delta); public Sequence getSequence(WorkspaceId workspaceId, String name); public void deleteSequence(WorkspaceId workspaceId, String name); public Collection<Sequence> getSequencesForWorkspace(WorkspaceId workspaceId); public void reIndex(WorkspaceId workspaceId); public void reIndex(SequenceId seqId); public SequenceId createSequenceId(WorkspaceId workspaceId, String name); + + public void deleteWorkspace(WorkspaceId workspaceId); } diff --git a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java index badc5e4..ab226a8 100644 --- a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java +++ b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java @@ -1,435 +1,424 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.api.impl.content; -import com.smartitengineering.cms.api.content.FieldValue; -import com.smartitengineering.cms.api.type.ContentType.ContentProcessingPhase; -import com.smartitengineering.cms.api.workspace.WorkspaceId; -import com.smartitengineering.cms.api.content.Content; -import com.smartitengineering.cms.api.content.ContentId; -import com.smartitengineering.cms.api.content.Field; -import com.smartitengineering.cms.api.content.Representation; +import com.smartitengineering.cms.api.content.*; import com.smartitengineering.cms.api.content.template.ContentCoProcessor; import com.smartitengineering.cms.api.event.Event; import com.smartitengineering.cms.api.event.Event.EventType; import com.smartitengineering.cms.api.event.Event.Type; import com.smartitengineering.cms.api.factory.SmartContentAPI; import com.smartitengineering.cms.api.factory.content.WriteableContent; import com.smartitengineering.cms.api.impl.AbstractPersistableDomain; import com.smartitengineering.cms.api.type.ContentCoProcessorDef; import com.smartitengineering.cms.api.type.ContentStatus; import com.smartitengineering.cms.api.type.ContentType; +import com.smartitengineering.cms.api.type.ContentType.ContentProcessingPhase; import com.smartitengineering.cms.api.type.FieldDef; import com.smartitengineering.cms.api.workspace.Workspace; +import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.cms.spi.SmartContentSPI; import com.smartitengineering.cms.spi.content.PersistableContent; import java.io.IOException; import java.net.URI; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import org.apache.commons.lang.ObjectUtils; /** * * @author kaisar */ public class ContentImpl extends AbstractPersistableDomain<WriteableContent, ContentId> implements PersistableContent { private ContentId contentId; private ContentId parentId; private ContentType contentDef; private ContentStatus contentStatus; private Date creationDate; private Date lastModifiedDate; private Map<String, Field> map; private Map<String, Field> cachedFieldMap; private String entityTagValue; private boolean privateContent; private boolean supressChecking; public ContentImpl() { super(LOCK_KEY_PREFIX); } public boolean isSupressChecking() { return supressChecking; } public void setSupressChecking(boolean supressChecking) { this.supressChecking = supressChecking; } @Override public void put() throws IOException { final boolean attainedLockLocally; if (isPersisted() && !isLockOwned()) { lock(); attainedLockLocally = true; } else { attainedLockLocally = false; } try { triggerContentCoProcessors(ContentType.ContentProcessingPhase.WRITE); if (!isValid()) { getLogger().info("Content not in valid state!"); //First get contents indexed before attempting to use this validity! //Uncomment the following line once indexing is ensured in testing throw new IOException("Content is not in valid state!"); } super.put(); } finally { if (attainedLockLocally) { unlock(); } } } protected void triggerContentCoProcessors(final ContentProcessingPhase phase) { //Trigger content co processors if (contentDef != null && contentId != null) { Collection<ContentCoProcessorDef> defs = contentDef.getContentCoProcessorDefs().get( phase); if (defs != null && !defs.isEmpty()) { List<ContentCoProcessorDef> list = new ArrayList<ContentCoProcessorDef>(defs); Collections.sort(list, new Comparator<ContentCoProcessorDef>() { public int compare(ContentCoProcessorDef o1, ContentCoProcessorDef o2) { return o1.getPriority() - o2.getPriority(); } }); for (ContentCoProcessorDef def : list) { ContentCoProcessor processor = SmartContentAPI.getInstance().getWorkspaceApi().getContentCoProcessor(contentId. getWorkspaceId(), def.getResourceUri().getValue()); if (processor != null) { processor.processContent(this, def.getParameters()); } } } } } @Override public void setParentId(ContentId contentId) { if (contentDef == null) { throw new IllegalArgumentException("Content Type Definition must be set before setting parent content ID"); } if (contentId != null && SmartContentAPI.getInstance().getContentLoader().loadContent(contentId) == null) { throw new IllegalArgumentException("Parent must exist for it to be set!"); } this.parentId = contentId; } @Override public void setContentDefinition(ContentType contentType) { this.contentDef = contentType; } @Override public void setField(Field field) { getMap().put(field.getName(), field); cachedFieldMap = null; } @Override public void setStatus(ContentStatus contentStatus) { this.contentStatus = contentStatus; } @Override public ContentId getContentId() { return this.contentId; } @Override public ContentId getParentId() { return this.parentId; } @Override public Content getParent() { if (parentId != null) { return SmartContentAPI.getInstance().getContentLoader().loadContent(parentId); } else { return null; } } @Override public ContentType getContentDefinition() { return this.contentDef; } @Override public Map<String, Field> getFields() { final Content parent = getParent(); final ContentType def = getContentDefinition(); if (cachedFieldMap == null) { Map<String, Field> fields = new LinkedHashMap<String, Field>(); if (parent != null && def != null) { Map<String, Field> parentFields = parent.getFields(); for (String fieldName : parentFields.keySet()) { FieldDef myDef = def.getOwnFieldDefs().get(fieldName); FieldDef thatDef = parent.getContentDefinition().getOwnFieldDefs().get(fieldName); if (myDef != null && thatDef != null && ObjectUtils.equals(myDef, thatDef) && myDef.getValueDef().getType(). equals(thatDef.getValueDef().getType())) { fields.put(fieldName, parent.getField(fieldName)); } } } fields.putAll(getMap()); cachedFieldMap = fields; } return Collections.unmodifiableMap(cachedFieldMap); } public Map<String, Field> getMap() { if (map == null) { map = new LinkedHashMap<String, Field>(SmartContentSPI.getInstance().getContentReader().getFieldsForContent( contentId)); triggerContentCoProcessors(ContentType.ContentProcessingPhase.READ); } return map; } @Override public Map<String, Field> getOwnFields() { return Collections.unmodifiableMap(getMap()); } @Override public Field getField(String fieldName) { return getFields().get(fieldName); } @Override public ContentStatus getStatus() { return this.contentStatus; } @Override public Representation getRepresentation(String repName) { return SmartContentSPI.getInstance().getRepresentationProvider().getRepresentation(repName, getContentDefinition(), this); } @Override public Date getCreationDate() { return this.creationDate; } @Override public Date getLastModifiedDate() { return this.lastModifiedDate; } @Override public boolean isPersisted() { return creationDate != null; } @Override public ContentId getKeySpecimen() { return contentId; } @Override public void removeField(String fieldName) { getMap().remove(fieldName); } @Override public void setContentId(ContentId contentId) { this.contentId = contentId; } @Override public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } @Override public void setLastModifiedDate(Date lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } @Override protected void create() throws IOException { if (contentId != null) { if (contentId.getWorkspaceId() == null || contentId.getId() == null) { throw new IOException("Workspace ID or ID of content within wokrspace can not be null"); } Workspace workspace = SmartContentAPI.getInstance().getWorkspaceApi().getWorkspace(contentId.getWorkspaceId()); if (workspace == null) { throw new IOException("Non existance workspace Id " + contentId.getWorkspaceId()); } } if (contentId == null && contentDef != null && contentDef.getContentTypeID() != null) { createContentId(contentDef.getContentTypeID().getWorkspace()); } else if (contentId == null && (contentDef == null || contentDef.getContentTypeID() == null)) { throw new IOException("Content ID and Content Type Definition is not set!"); } super.create(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.CREATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public void delete() throws IOException { super.delete(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.DELETE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override protected void update() throws IOException { super.update(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.UPDATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!Content.class.isAssignableFrom(obj.getClass())) { return false; } final Content other = (Content) obj; if (this.contentId != other.getContentId() && (this.contentId == null || !this.contentId.equals(other.getContentId()))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.contentId != null ? this.contentId.hashCode() : 0); return hash; } @Override public void createContentId(WorkspaceId workspace) { if (workspace == null) { throw new IllegalArgumentException("Workspace ID can not be null!"); } setContentId(SmartContentAPI.getInstance().getContentLoader().generateContentId(workspace)); } @Override public void setEntityTagValue(String eTagValue) { this.entityTagValue = eTagValue; } @Override public String getEntityTagValue() { return this.entityTagValue; } @Override public boolean isValid() { boolean validContent = supressChecking || SmartContentAPI.getInstance().getContentLoader().isValidContent(this); if (getLogger().isDebugEnabled()) { getLogger().debug("!!! Checking Content " + validContent); } return validContent; } @Override public URI getUri() { return SmartContentSPI.getInstance().getUriProvider().getContentUri(contentId); } @Override public String getEncodedUriString() { if (getUri() == null) { return null; } else { return getUri().toASCIIString(); } } @Override public void setPrivate(boolean privateContent) { this.privateContent = privateContent; } @Override public boolean isPrivate() { return this.privateContent; } @Override public ContentImpl clone() { ContentImpl contentImpl = new ContentImpl(); contentImpl.contentDef = contentDef; contentImpl.contentId = contentId; contentImpl.parentId = parentId; contentImpl.privateContent = privateContent; contentImpl.contentStatus = contentStatus; contentImpl.nextPerformToWaitForLock = nextPerformToWaitForLock; contentImpl.supressChecking = supressChecking; contentImpl.entityTagValue = entityTagValue; if (creationDate != null) { contentImpl.creationDate = new Date(creationDate.getTime()); } if (lastModifiedDate != null) { contentImpl.lastModifiedDate = new Date(lastModifiedDate.getTime()); } contentImpl.map = map; if (map != null) { contentImpl.map = new LinkedHashMap<String, Field>(); cloneFields(map, contentImpl.map); } if (cachedFieldMap != null) { contentImpl.cachedFieldMap = new LinkedHashMap<String, Field>(); cloneFields(cachedFieldMap, contentImpl.cachedFieldMap); } return contentImpl; } protected void cloneFields(Map<String, Field> fieldMap, Map<String, Field> destMap) { for (Map.Entry<String, Field> oneField : fieldMap.entrySet()) { FieldImpl fieldImpl = new FieldImpl(); final Field value = oneField.getValue(); fieldImpl.setContent(value.getContent()); fieldImpl.setFieldDef(value.getFieldDef()); fieldImpl.setName(value.getName()); final FieldValue fieldVal = value.getValue(); fieldImpl.setValue(fieldVal); destMap.put(oneField.getKey(), fieldImpl); } } } diff --git a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/workspace/WorkspaceAPIImpl.java b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/workspace/WorkspaceAPIImpl.java index f9d77bc..42d8e0b 100644 --- a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/workspace/WorkspaceAPIImpl.java +++ b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/workspace/WorkspaceAPIImpl.java @@ -1,952 +1,973 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.api.impl.workspace; import com.google.inject.Inject; import com.google.inject.name.Named; import com.smartitengineering.cms.api.common.CacheableResource; import com.smartitengineering.cms.api.common.TemplateType; import com.smartitengineering.cms.api.content.ContentId; import com.smartitengineering.cms.api.content.template.ContentCoProcessor; import com.smartitengineering.cms.api.content.template.FieldValidator; import com.smartitengineering.cms.api.content.template.RepresentationGenerator; import com.smartitengineering.cms.api.content.template.VariationGenerator; -import com.smartitengineering.cms.api.exception.InvalidTemplateException; -import com.smartitengineering.cms.api.workspace.Sequence; -import com.smartitengineering.cms.api.workspace.SequenceId; -import com.smartitengineering.cms.spi.content.template.ContentCoProcessorGenerator; import com.smartitengineering.cms.api.event.Event; import com.smartitengineering.cms.api.event.Event.EventType; import com.smartitengineering.cms.api.event.Event.Type; +import com.smartitengineering.cms.api.exception.InvalidTemplateException; import com.smartitengineering.cms.api.factory.SmartContentAPI; -import com.smartitengineering.cms.api.workspace.ContentCoProcessorTemplate; -import com.smartitengineering.cms.api.workspace.RepresentationTemplate; -import com.smartitengineering.cms.api.workspace.ResourceTemplate; -import com.smartitengineering.cms.api.workspace.ValidatorTemplate; -import com.smartitengineering.cms.api.workspace.VariationTemplate; -import com.smartitengineering.cms.api.workspace.Workspace; +import com.smartitengineering.cms.api.factory.type.WritableContentType; import com.smartitengineering.cms.api.factory.workspace.WorkspaceAPI; +import com.smartitengineering.cms.api.type.ContentType; import com.smartitengineering.cms.api.type.ValidatorType; -import com.smartitengineering.cms.api.workspace.WorkspaceId; +import com.smartitengineering.cms.api.workspace.*; import com.smartitengineering.cms.spi.SmartContentSPI; +import com.smartitengineering.cms.spi.content.template.ContentCoProcessorGenerator; import com.smartitengineering.cms.spi.content.template.TypeFieldValidator; import com.smartitengineering.cms.spi.content.template.TypeRepresentationGenerator; import com.smartitengineering.cms.spi.content.template.TypeVariationGenerator; import com.smartitengineering.dao.common.cache.CacheServiceProvider; import com.smartitengineering.dao.common.cache.Lock; import com.smartitengineering.dao.common.cache.Mutex; import com.smartitengineering.dao.common.cache.impl.CacheAPIFactory; import java.io.IOException; import java.io.InputStream; import java.util.AbstractMap.SimpleEntry; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author imyousuf */ public class WorkspaceAPIImpl implements WorkspaceAPI { private String globalNamespace; private final transient Logger logger = LoggerFactory.getLogger(getClass()); @Inject private Map<TemplateType, ContentCoProcessorGenerator> contentCoProcessorGenerators; @Inject private Map<TemplateType, TypeRepresentationGenerator> representationGenerators; @Inject private Map<TemplateType, TypeVariationGenerator> variationGenerators; @Inject private Map<ValidatorType, TypeFieldValidator> validatorGenerators; @Inject private CacheServiceProvider<WorkspaceResourceCacheKey, CacheableResource> resourcesCache; protected final Mutex<WorkspaceResourceCacheKey> mutex = CacheAPIFactory.<WorkspaceResourceCacheKey>getMutex(); public CacheServiceProvider<WorkspaceResourceCacheKey, CacheableResource> getResourcesCache() { return resourcesCache; } public void setResourcesCache(CacheServiceProvider<WorkspaceResourceCacheKey, CacheableResource> resourcesCache) { this.resourcesCache = resourcesCache; } public Map<TemplateType, ContentCoProcessorGenerator> getContentCoProcessorGenerators() { return contentCoProcessorGenerators; } public void setContentCoProcessorGenerators( Map<TemplateType, ContentCoProcessorGenerator> contentCoProcessorGenerators) { this.contentCoProcessorGenerators = contentCoProcessorGenerators; } public Map<TemplateType, TypeRepresentationGenerator> getRepresentationGenerators() { return representationGenerators; } public void setRepresentationGenerators(Map<TemplateType, TypeRepresentationGenerator> representationGenerators) { this.representationGenerators = representationGenerators; } public Map<ValidatorType, TypeFieldValidator> getValidatorGenerators() { return validatorGenerators; } public void setValidatorGenerators(Map<ValidatorType, TypeFieldValidator> validatorGenerators) { this.validatorGenerators = validatorGenerators; } public Map<TemplateType, TypeVariationGenerator> getVariationGenerators() { return variationGenerators; } public void setVariationGenerators(Map<TemplateType, TypeVariationGenerator> variationGenerators) { this.variationGenerators = variationGenerators; } @Inject public void setGlobalNamespace(@Named("globalNamespace") String globalNamespace) { this.globalNamespace = globalNamespace; } @Override public String getGlobalNamespace() { return globalNamespace; } @Override public WorkspaceId createWorkspace(String name) { WorkspaceId workspaceIdImpl = createWorkspaceId(name); return createWorkspace(workspaceIdImpl); } @Override public WorkspaceId createWorkspace(String globalNamespace, String name) { return createWorkspace(createWorkspaceId(globalNamespace, name)); } @Override public WorkspaceId createWorkspace(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().create(workspaceId); Event<Workspace> event = SmartContentAPI.getInstance().getEventRegistrar().<Workspace>createEvent( EventType.UPDATE, Type.WORKSPACE, getWorkspace(workspaceId)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); return workspaceId; } @Override public WorkspaceId createWorkspaceId(String name) { return createWorkspaceId(null, name); } @Override public WorkspaceId createWorkspaceId(final String namespace, String name) { final WorkspaceIdImpl workspaceIdImpl = new WorkspaceIdImpl(); workspaceIdImpl.setGlobalNamespace(StringUtils.isBlank(namespace) ? getGlobalNamespace() : namespace); workspaceIdImpl.setName(name); return workspaceIdImpl; } @Override public WorkspaceId getWorkspaceIdIfExists(String name) { final WorkspaceId createdWorkspaceId = createWorkspaceId(name); return getWorkspaceIdIfExists(createdWorkspaceId); } @Override public WorkspaceId getWorkspaceIdIfExists(WorkspaceId workspaceId) { Workspace workspace = getWorkspace(workspaceId); if (workspace != null) { return workspaceId; } return null; } @Override public Workspace getWorkspace(WorkspaceId workspaceId) { return SmartContentSPI.getInstance().getWorkspaceService().load(workspaceId); } @Override public Collection<Workspace> getWorkspaces() { return SmartContentSPI.getInstance().getWorkspaceService().getWorkspaces(); } @Override public RepresentationTemplate putRepresentationTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException { return putRepresentationTemplate(to, name, templateType, IOUtils.toByteArray(stream)); } @Override public RepresentationTemplate putRepresentationTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data) { final RepresentationTemplate putRepresentationTemplate = SmartContentSPI.getInstance().getWorkspaceService(). putRepresentationTemplate(to, name, templateType, data); Event<RepresentationTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<RepresentationTemplate> createEvent(EventType.UPDATE, Type.REPRESENTATION_TEMPLATE, putRepresentationTemplate); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); if (resourcesCache != null) { WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(to, WorkspaceResourceCacheKey.WorkspaceResourceType.REPRESENTATION_GEN, name); resourcesCache.expireFromCache(key); } return putRepresentationTemplate; } @Override public VariationTemplate putVariationTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException { return putVariationTemplate(to, name, templateType, IOUtils.toByteArray(stream)); } @Override public VariationTemplate putVariationTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data) { final VariationTemplate putVariationTemplate = SmartContentSPI.getInstance().getWorkspaceService(). putVariationTemplate(to, name, templateType, data); Event<VariationTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<VariationTemplate> createEvent(EventType.UPDATE, Type.VARIATION_TEMPLATE, putVariationTemplate); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); if (resourcesCache != null) { WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(to, WorkspaceResourceCacheKey.WorkspaceResourceType.VARIATION_GEN, name); resourcesCache.expireFromCache(key); } return putVariationTemplate; } @Override public void delete(RepresentationTemplate template) { SmartContentSPI.getInstance().getWorkspaceService().deleteRepresentation(template); Event<RepresentationTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<RepresentationTemplate> createEvent(EventType.DELETE, Type.REPRESENTATION_TEMPLATE, template); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void delete(VariationTemplate template) { SmartContentSPI.getInstance().getWorkspaceService().deleteVariation(template); Event<VariationTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<VariationTemplate> createEvent(EventType.DELETE, Type.VARIATION_TEMPLATE, template); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public Collection<WorkspaceId> getFriendlies(WorkspaceId workspaceId) { return SmartContentSPI.getInstance().getWorkspaceService().getFriendlies(workspaceId); } @Override public void addFriend(WorkspaceId to, WorkspaceId... workspaceIds) { SmartContentSPI.getInstance().getWorkspaceService().addFriend(to, workspaceIds); for (WorkspaceId friend : workspaceIds) { Event<Entry<WorkspaceId, WorkspaceId>> event = SmartContentAPI.getInstance().getEventRegistrar().<Entry<WorkspaceId, WorkspaceId>> createEvent(EventType.CREATE, Type.FRIENDLY, new SimpleEntry<WorkspaceId, WorkspaceId>(to, friend)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } } @Override public void removeFriend(WorkspaceId from, WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeFriend(from, workspaceId); Event<Entry<WorkspaceId, WorkspaceId>> event = SmartContentAPI.getInstance().getEventRegistrar().<Entry<WorkspaceId, WorkspaceId>> createEvent(EventType.DELETE, Type.FRIENDLY, new SimpleEntry<WorkspaceId, WorkspaceId>(from, workspaceId)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void removeAllFriendlies(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllFriendlies(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_FRIENDLIES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void removeAllRepresentationTemplates(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllRepresentationTemplates(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_REPRESENTATION_TEMPLATES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void removeAllVariationTemplates(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllVariationTemplates(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_VARIATION_TEMPLATES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public Collection<String> getRepresentationNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count) { if (count == 0 || startPoint == null) { return Collections.emptyList(); } List<String> list = new ArrayList<String>(getRepresentationNames(id, criteria)); return cutList(list, startPoint, count); } @Override public Collection<String> getVariationNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count) { if (count == 0 || startPoint == null) { return Collections.emptyList(); } List<String> list = new ArrayList<String>(getVariationNames(id, criteria)); return cutList(list, startPoint, count); } @Override public Collection<String> getRepresentationNames(WorkspaceId id, ResourceSortCriteria criteria) { final Collection<? extends ResourceTemplate> repsWithoutData = SmartContentSPI.getInstance(). getWorkspaceService().getRepresentationsWithoutData(id, criteria); return getResourceNames(repsWithoutData); } @Override public Collection<String> getVariationNames(WorkspaceId id, ResourceSortCriteria criteria) { final Collection<? extends ResourceTemplate> variationsWithoutData = SmartContentSPI.getInstance(). getWorkspaceService().getVariationsWithoutData(id, criteria); return getResourceNames(variationsWithoutData); } protected Collection<String> getResourceNames(Collection<? extends ResourceTemplate> templates) { ArrayList<String> list = new ArrayList<String>(templates.size()); for (ResourceTemplate template : templates) { list.add(template.getName()); } return list; } protected Collection<String> getValidatorNames(Collection<ValidatorTemplate> templates) { ArrayList<String> list = new ArrayList<String>(templates.size()); for (ValidatorTemplate template : templates) { list.add(template.getName()); } return list; } @Override public Collection<String> getRepresentationNames(WorkspaceId id) { return getRepresentationNames(id, ResourceSortCriteria.BY_NAME); } @Override public Collection<String> getVariationNames(WorkspaceId id) { return getVariationNames(id, ResourceSortCriteria.BY_NAME); } @Override public Collection<String> getRepresentationNames(WorkspaceId id, String startPoint, int count) { return getRepresentationNames(id, ResourceSortCriteria.BY_NAME, startPoint, count); } @Override public Collection<String> getVariationNames(WorkspaceId id, String startPoint, int count) { return getVariationNames(id, ResourceSortCriteria.BY_NAME, startPoint, count); } @Override public RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getRepresentationTemplate(id, name); } @Override public VariationTemplate getVariationTemplate(WorkspaceId id, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getVariationTemplate(id, name); } @Override public String getEntityTagValueForResourceTemplate(ResourceTemplate template) { final String toString = new StringBuilder(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(template. getLastModifiedDate())).append(':').append(Arrays.toString(template.getTemplate())).append(':').append(template. getTemplateType().name()).toString(); final String etag = DigestUtils.md5Hex(toString); if (logger.isDebugEnabled()) { logger.debug("Generated etag " + etag + " for " + template.getClass().getName() + " with name " + template.getName()); } return etag; } @Override public Collection<ContentId> getRootContents(WorkspaceId workspaceId) { return SmartContentSPI.getInstance().getWorkspaceService().getRootContents(workspaceId); } @Override public void addRootContent(WorkspaceId to, ContentId... contentIds) { SmartContentSPI.getInstance().getWorkspaceService().addRootContent(to, contentIds); for (ContentId rootContent : contentIds) { Event<Entry<WorkspaceId, ContentId>> event = SmartContentAPI.getInstance().getEventRegistrar().<Entry<WorkspaceId, ContentId>> createEvent(EventType.CREATE, Type.ROOT_CONTENT, new SimpleEntry<WorkspaceId, ContentId>(to, rootContent)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } } @Override public void removeRootContent(WorkspaceId from, ContentId contentId) { SmartContentSPI.getInstance().getWorkspaceService().removeRootContent(from, contentId); Event<Entry<WorkspaceId, ContentId>> event = SmartContentAPI.getInstance().getEventRegistrar().<Entry<WorkspaceId, ContentId>> createEvent(EventType.DELETE, Type.ROOT_CONTENT, new SimpleEntry<WorkspaceId, ContentId>(from, contentId)); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public void removeAllRootContents(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllRootContents(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_ROOT_CONTENTS, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public ValidatorTemplate getValidatorTemplate(WorkspaceId workspaceId, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getValidationTemplate(workspaceId, name); } @Override public void delete(ValidatorTemplate template) { SmartContentSPI.getInstance().getWorkspaceService().deleteValidator(template); Event<ValidatorTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<ValidatorTemplate> createEvent(EventType.DELETE, Type.VALIDATION_TEMPLATE, template); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } @Override public ValidatorTemplate putValidatorTemplate(WorkspaceId to, String name, ValidatorType templateType, InputStream stream) throws IOException { return putValidatorTemplate(to, name, templateType, IOUtils.toByteArray(stream)); } @Override public ValidatorTemplate putValidatorTemplate(WorkspaceId to, String name, ValidatorType templateType, byte[] data) { final ValidatorTemplate validatorTemplate = SmartContentSPI.getInstance().getWorkspaceService().putValidatorTemplate( to, name, templateType, data); Event<ValidatorTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<ValidatorTemplate> createEvent(EventType.UPDATE, Type.VALIDATION_TEMPLATE, validatorTemplate); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); if (resourcesCache != null) { WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(to, WorkspaceResourceCacheKey.WorkspaceResourceType.VALIDATION_SCR, name); resourcesCache.expireFromCache(key); } return validatorTemplate; } @Override public String getEntityTagValueForValidatorTemplate(ValidatorTemplate template) { final String toString = new StringBuilder(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(template. getLastModifiedDate())).append(':').append(Arrays.toString(template.getTemplate())).append(':').append(template. getTemplateType().name()).toString(); final String etag = DigestUtils.md5Hex(toString); if (logger.isDebugEnabled()) { logger.debug("Generated etag " + etag + " for " + template.getClass().getName() + " with name " + template.getName()); } return etag; } @Override public Collection<String> getValidatorNames(WorkspaceId id) { return getVariationNames(id, ResourceSortCriteria.BY_NAME); } @Override public Collection<String> getValidatorNames(WorkspaceId id, String startPoint, int count) { return getVariationNames(id, ResourceSortCriteria.BY_NAME, startPoint, count); } @Override public Collection<String> getValidatorNames(WorkspaceId id, ResourceSortCriteria criteria) { final Collection<ValidatorTemplate> variationsWithoutData = SmartContentSPI.getInstance().getWorkspaceService(). getValidatorsWithoutData(id, criteria); return getValidatorNames(variationsWithoutData); } @Override public Collection<String> getValidatorNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count) { if (count == 0 || startPoint == null) { return Collections.emptyList(); } List<String> list = new ArrayList<String>(getValidatorNames(id, criteria)); return cutList(list, startPoint, count); } @Override public void removeAllValidatorTemplates(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllValidatorTemplates(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_VALIDATION_TEMPLATES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } protected Collection<String> cutList(List<String> list, String startPoint, int count) { if (logger.isDebugEnabled()) { logger.debug("All names " + list); } int index = Collections.binarySearch(list, startPoint); if (logger.isDebugEnabled()) { logger.debug("Index " + index); } if (index < 0) { index = index * - 1; } if (count > 0 && index + 1 >= list.size() && StringUtils.isNotBlank(startPoint)) { logger.debug("Index is equal to size and count is greater than 0"); return Collections.emptyList(); } if (count < 0 && index <= 0) { logger.debug("Index is zero to size and count is smaller than 0"); return Collections.emptyList(); } final int fromIndex; final int toIndex; if (count > 0) { fromIndex = StringUtils.isBlank(startPoint) ? 0 : index + 1; toIndex = (fromIndex + count >= list.size()) ? list.size() : fromIndex + count; } else { toIndex = index; fromIndex = (toIndex + count >= 0) ? toIndex + count : 0; } if (logger.isDebugEnabled()) { logger.debug("Sublisting starts at " + fromIndex + " and ends before " + toIndex); } final List<String> result = list.subList(fromIndex, toIndex); if (logger.isDebugEnabled()) { logger.debug("Returning " + result); } return result; } public void delete(ContentCoProcessorTemplate template) { SmartContentSPI.getInstance().getWorkspaceService().deleteContentCoProcessor(template); Event<ContentCoProcessorTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<ContentCoProcessorTemplate> createEvent(EventType.DELETE, Type.CONTENT_CO_PROCESSOR_TEMPLATE, template); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } public ContentCoProcessorTemplate putContentCoProcessorTemplate(WorkspaceId to, String name, TemplateType templateType, InputStream stream) throws IOException { return putContentCoProcessorTemplate(to, name, templateType, IOUtils.toByteArray(stream)); } public ContentCoProcessorTemplate putContentCoProcessorTemplate(WorkspaceId to, String name, TemplateType templateType, byte[] data) { if (templateType.equals(TemplateType.JASPER) || templateType.equals(TemplateType.VELOCITY)) { throw new IllegalArgumentException("TemplateType not supported for content type co processor"); } final ContentCoProcessorTemplate temp = SmartContentSPI.getInstance().getWorkspaceService(). putContentCoProcessorTemplate(to, name, templateType, data); Event<ContentCoProcessorTemplate> event = SmartContentAPI.getInstance().getEventRegistrar().<ContentCoProcessorTemplate> createEvent(EventType.UPDATE, Type.CONTENT_CO_PROCESSOR_TEMPLATE, temp); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); if (resourcesCache != null) { WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(to, WorkspaceResourceCacheKey.WorkspaceResourceType.CONTENT_CO_PROCESSOR_GEN, name); resourcesCache.expireFromCache(key); } return temp; } public ContentCoProcessorTemplate getContentCoProcessorTemplate(WorkspaceId id, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getContentCoProcessorTemplate(id, name); } public void removeAllContentCoProcessorTemplates(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().removeAllContentCoProcessorTemplates(workspaceId); Event<WorkspaceId> event = SmartContentAPI.getInstance().getEventRegistrar().<WorkspaceId> createEvent(EventType.DELETE, Type.ALL_CONTENT_CO_PROCESSOR_TEMPLATES, workspaceId); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } public ContentCoProcessor getContentCoProcessor(WorkspaceId id, String name) { return getContentCoProcessor(id, name, true); } public ContentCoProcessor getContentCoProcessor(final WorkspaceId id, final String name, final boolean searchInFriendlies) { if (id == null || StringUtils.isBlank(name)) { logger.warn("Null workspace id or blank name!"); return null; } WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(id, WorkspaceResourceCacheKey.WorkspaceResourceType.CONTENT_CO_PROCESSOR_GEN, name); CacheThroughReader<ContentCoProcessor> reader = new CacheThroughReader<ContentCoProcessor>(key, new Lookup<ContentCoProcessor>() { public ContentCoProcessor get() { ContentCoProcessorTemplate template = getContentCoProcessorTemplate(id, name, searchInFriendlies); return getContentCoProcessor(template); } }); return reader.read(); } public FieldValidator getFieldValidator(WorkspaceId id, String name) { return getFieldValidator(id, name, true); } public FieldValidator getFieldValidator(final WorkspaceId id, final String name, final boolean searchInFriendlies) { if (id == null || StringUtils.isBlank(name)) { logger.warn("Null workspace id or blank name!"); return null; } WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(id, WorkspaceResourceCacheKey.WorkspaceResourceType.VALIDATION_SCR, name); CacheThroughReader<FieldValidator> reader = new CacheThroughReader<FieldValidator>(key, new Lookup<FieldValidator>() { public FieldValidator get() { ValidatorTemplate template = getValidatorTemplate(id, name, searchInFriendlies); if (template == null) { logger.info("Validator template is null, returning true!"); return null; } return getFieldValidator(template); } }); return reader.read(); } public RepresentationGenerator getRepresentationGenerator(WorkspaceId id, String name) { return getRepresentationGenerator(id, name, true); } public RepresentationGenerator getRepresentationGenerator(final WorkspaceId workspaceId, final String name, final boolean searchInFriendlies) { if (workspaceId == null || StringUtils.isBlank(name)) { logger.warn("Null workspace id or blank name!"); return null; } WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(workspaceId, WorkspaceResourceCacheKey.WorkspaceResourceType.REPRESENTATION_GEN, name); CacheThroughReader<RepresentationGenerator> reader = new CacheThroughReader<RepresentationGenerator>(key, new Lookup<RepresentationGenerator>() { public RepresentationGenerator get() { RepresentationTemplate representationTemplate = getRepresentationTemplate(workspaceId, name, searchInFriendlies); return getRepresentationGenerator(representationTemplate); } }); return reader.read(); } public VariationGenerator getVariationGenerator(WorkspaceId id, String name) { return getVariationGenerator(id, name, true); } public VariationGenerator getVariationGenerator(final WorkspaceId workspaceId, final String name, final boolean searchInFriendlies) { if (workspaceId == null || StringUtils.isBlank(name)) { logger.warn("Null workspace id or blank name!"); return null; } WorkspaceResourceCacheKey key = new WorkspaceResourceCacheKey(workspaceId, WorkspaceResourceCacheKey.WorkspaceResourceType.VARIATION_GEN, name); CacheThroughReader<VariationGenerator> reader = new CacheThroughReader<VariationGenerator>(key, new Lookup<VariationGenerator>() { public VariationGenerator get() { VariationTemplate variationTemplate = getVariationTemplate(workspaceId, name, searchInFriendlies); return getVariationGenerator(variationTemplate); } }); return reader.read(); } public Collection<String> getContentCoProcessorNames(WorkspaceId id, ResourceSortCriteria criteria) { final Collection<ContentCoProcessorTemplate> procsWithoutData = SmartContentSPI.getInstance(). getWorkspaceService().getContentCoProcessorsWithoutData(id, criteria); return getResourceNames(procsWithoutData); } public Collection<String> getContentCoProcessorNames(WorkspaceId id, ResourceSortCriteria criteria, String startPoint, int count) { if (count == 0 || startPoint == null) { return Collections.emptyList(); } List<String> list = new ArrayList<String>(getContentCoProcessorNames(id, criteria)); return cutList(list, startPoint, count); } public Collection<String> getContentCoProcessorNames(WorkspaceId id) { return getContentCoProcessorNames(id, ResourceSortCriteria.BY_NAME); } public Collection<String> getContentCoProcessorNames(WorkspaceId id, String startPoint, int count) { return getContentCoProcessorNames(id, ResourceSortCriteria.BY_NAME, startPoint, count); } public ContentCoProcessorTemplate getContentCoProcessorTemplate(WorkspaceId id, String name, boolean searchInFriendlies) { ContentCoProcessorTemplate template = getContentCoProcessorTemplate(id, name); if (searchInFriendlies && template == null) { //Lookup friendlies Collection<WorkspaceId> friends = SmartContentAPI.getInstance().getWorkspaceApi().getFriendlies(id); if (friends != null && !friends.isEmpty()) { Iterator<WorkspaceId> friendsIterator = friends.iterator(); while (template == null && friendsIterator.hasNext()) { template = SmartContentAPI.getInstance().getWorkspaceApi().getContentCoProcessorTemplate( friendsIterator.next(), name); } } } return template; } public RepresentationTemplate getRepresentationTemplate(WorkspaceId workspaceId, String name, boolean searchInFriendlies) { RepresentationTemplate representationTemplate = SmartContentAPI.getInstance().getWorkspaceApi().getRepresentationTemplate(workspaceId, name); if (searchInFriendlies && representationTemplate == null) { //Lookup friendlies Collection<WorkspaceId> friends = SmartContentAPI.getInstance().getWorkspaceApi().getFriendlies(workspaceId); if (friends != null && !friends.isEmpty()) { Iterator<WorkspaceId> friendsIterator = friends.iterator(); while (representationTemplate == null && friendsIterator.hasNext()) { representationTemplate = SmartContentAPI.getInstance().getWorkspaceApi().getRepresentationTemplate(friendsIterator. next(), name); } } } return representationTemplate; } public ValidatorTemplate getValidatorTemplate(WorkspaceId id, String name, boolean searchInFriendlies) { ValidatorTemplate template = SmartContentAPI.getInstance().getWorkspaceApi().getValidatorTemplate(id, name); if (searchInFriendlies && template == null) { //Lookup friendlies Collection<WorkspaceId> friends = SmartContentAPI.getInstance().getWorkspaceApi().getFriendlies(id); if (friends != null && !friends.isEmpty()) { Iterator<WorkspaceId> friendsIterator = friends.iterator(); while (template == null && friendsIterator.hasNext()) { template = SmartContentAPI.getInstance().getWorkspaceApi().getValidatorTemplate(friendsIterator.next(), name); } } } return template; } public VariationTemplate getVariationTemplate(WorkspaceId workspaceId, String name, boolean searchInFriendlies) { VariationTemplate variationTemplate = SmartContentAPI.getInstance().getWorkspaceApi().getVariationTemplate(workspaceId, name); if (searchInFriendlies && variationTemplate == null) { //Lookup friendlies Collection<WorkspaceId> friends = SmartContentAPI.getInstance().getWorkspaceApi().getFriendlies(workspaceId); if (friends != null && !friends.isEmpty()) { Iterator<WorkspaceId> friendsIterator = friends.iterator(); while (variationTemplate == null && friendsIterator.hasNext()) { variationTemplate = SmartContentAPI.getInstance().getWorkspaceApi().getVariationTemplate( friendsIterator.next(), name); } } } return variationTemplate; } public ContentCoProcessor getContentCoProcessor(ContentCoProcessorTemplate template) { if (template == null) { return null; } ContentCoProcessorGenerator generator = contentCoProcessorGenerators.get(template.getTemplateType()); try { return generator.getGenerator(template); } catch (Exception ex) { logger.warn("Could not retrieve processor", ex); return null; } } public RepresentationGenerator getRepresentationGenerator(RepresentationTemplate representationTemplate) { if (representationTemplate == null) { return null; } TypeRepresentationGenerator generator = representationGenerators.get(representationTemplate.getTemplateType()); if (generator == null) { return null; } try { return generator.getGenerator(representationTemplate); } catch (Exception ex) { logger.warn("Could not generate representation generator", ex); return null; } } public VariationGenerator getVariationGenerator(VariationTemplate variationTemplate) { if (variationTemplate == null) { return null; } TypeVariationGenerator generator = variationGenerators.get(variationTemplate.getTemplateType()); if (generator == null) { return null; } try { return generator.getGenerator(variationTemplate); } catch (Exception ex) { logger.warn("Could not generate variation generator", ex); return null; } } public FieldValidator getFieldValidator(ValidatorTemplate template) { TypeFieldValidator generator = validatorGenerators.get(template.getTemplateType()); if (generator == null) { logger.info("Validator generator is null, returning true!"); return null; } try { return generator.getValidator(template); } catch (InvalidTemplateException ex) { logger.error("Not a valid validator template!"); return null; } } public Sequence putSequence(WorkspaceId workspaceId, String name, long initialValue) { final Sequence created = SmartContentSPI.getInstance().getWorkspaceService().create(workspaceId, name, initialValue); Event<Sequence> event = SmartContentAPI.getInstance().getEventRegistrar().<Sequence>createEvent(EventType.CREATE, Type.SEQUENCE, created); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); return created; } public long modifySequenceValue(Sequence sequence, long delta) { final long newSequence = SmartContentSPI.getInstance().getWorkspaceService().modifySequenceValue(sequence, delta); return newSequence; } public Sequence getSequence(WorkspaceId workspaceId, String name) { return SmartContentSPI.getInstance().getWorkspaceService().getSequence(workspaceId, name); } public void deleteSequence(WorkspaceId workspaceId, String name) { Sequence sequence = getSequence(workspaceId, name); if (sequence != null) { SmartContentSPI.getInstance().getWorkspaceService().deleteSequence(workspaceId, name); } Event<Sequence> event = SmartContentAPI.getInstance().getEventRegistrar().<Sequence>createEvent(EventType.DELETE, Type.SEQUENCE, sequence); SmartContentAPI.getInstance().getEventRegistrar().notifyEventAsynchronously(event); } public SequenceId createSequenceId(WorkspaceId workspaceId, String name) { SequenceIdImpl impl = new SequenceIdImpl(); impl.setName(name); impl.setWorkspaceId(workspaceId); return impl; } public Collection<Sequence> getSequencesForWorkspace(WorkspaceId workspaceId) { return SmartContentSPI.getInstance().getWorkspaceService().getSequencesForWorkspace(workspaceId); } public void reIndex(WorkspaceId workspaceId) { SmartContentSPI.getInstance().getWorkspaceService().reIndex(workspaceId); } public void reIndex(SequenceId seqId) { SmartContentSPI.getInstance().getWorkspaceService().reIndex(seqId); } + public void deleteWorkspace(WorkspaceId workspaceId) { + Workspace workspace = SmartContentAPI.getInstance().getWorkspaceApi().getWorkspace(workspaceId); + if (workspace == null) { + throw new RuntimeException("Workspace not found"); + } + + Collection<ContentType> contentTypes = workspace.getContentDefintions(); + for (ContentType contentType : contentTypes) { + WritableContentType writableContentType = SmartContentAPI.getInstance().getContentTypeLoader(). + getWritableContentType(contentType); + try { + writableContentType.delete(); + } + catch (Exception ex) { + logger.error(ex.getMessage(), ex); + } + } + + SmartContentAPI.getInstance().getWorkspaceApi().removeAllContentCoProcessorTemplates(workspaceId); + SmartContentAPI.getInstance().getWorkspaceApi().removeAllFriendlies(workspaceId); + SmartContentAPI.getInstance().getWorkspaceApi().removeAllRepresentationTemplates(workspaceId); + SmartContentAPI.getInstance().getWorkspaceApi().removeAllRootContents(workspaceId); + SmartContentAPI.getInstance().getWorkspaceApi().removeAllValidatorTemplates(workspaceId); + SmartContentAPI.getInstance().getWorkspaceApi().removeAllVariationTemplates(workspaceId); + + Collection<ContentId> contentIds = workspace.getRootContents(); + for (ContentId contentId : contentIds) { + SmartContentAPI.getInstance().getWorkspaceApi().removeRootContent(workspaceId, contentId); + } + logger.info("Deleting workspace from persister"); + SmartContentSPI.getInstance().getWorkspaceService().delete(workspaceId); + } + public interface Lookup<T> { T get(); } public class CacheThroughReader<T extends CacheableResource> { private final Lookup<T> lookup; private final WorkspaceResourceCacheKey key; public CacheThroughReader(WorkspaceResourceCacheKey key, Lookup<T> lookup) { this.lookup = lookup; this.key = key; } public T read() { if (resourcesCache == null) { logger.info("Avoiding cache through read as cache is null!"); return lookup.get(); } final Lock<WorkspaceResourceCacheKey> lock; try { lock = mutex.acquire(key); } catch (Exception ex) { logger.warn("Error retrieving lock", ex); throw new IllegalStateException(ex); } try { CacheableResource cachedResource = resourcesCache.retrieveFromCache(key); if (cachedResource != null) { return (T) cachedResource; } else { T result = lookup.get(); resourcesCache.putToCache(key, result); return result; } } catch (Exception ex) { logger.warn("Error in doing cache through read", ex); return null; } finally { mutex.release(lock); } } } } diff --git a/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java b/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java index a573c0e..ec5da7c 100644 --- a/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java +++ b/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java @@ -1,632 +1,624 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.client.impl; import com.google.inject.AbstractModule; import com.smartitengineering.cms.api.common.TemplateType; -import com.smartitengineering.cms.api.content.ContentId; import com.smartitengineering.cms.api.content.MutableContent; import com.smartitengineering.cms.api.content.MutableField; import com.smartitengineering.cms.api.content.MutableFieldValue; import com.smartitengineering.cms.api.event.Event; import com.smartitengineering.cms.api.event.Event.EventType; import com.smartitengineering.cms.api.event.EventListener; import com.smartitengineering.cms.api.factory.SmartContentAPI; -import com.smartitengineering.cms.api.factory.content.ContentLoader; import com.smartitengineering.cms.api.factory.content.WriteableContent; +import com.smartitengineering.cms.api.factory.type.ContentTypeLoader; import com.smartitengineering.cms.api.factory.type.WritableContentType; import com.smartitengineering.cms.api.factory.workspace.WorkspaceAPI; -import com.smartitengineering.cms.api.impl.content.ContentImpl; -import com.smartitengineering.cms.api.impl.type.ContentStatusImpl; import com.smartitengineering.cms.api.impl.type.ContentTypeIdImpl; -import com.smartitengineering.cms.api.impl.type.ContentTypeImpl; import com.smartitengineering.cms.api.type.*; import com.smartitengineering.cms.api.type.ContentType.ContentProcessingPhase; import com.smartitengineering.cms.api.workspace.Sequence; import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.cms.binder.guice.Initializer; import com.smartitengineering.cms.client.api.ContainerResource; import com.smartitengineering.cms.client.api.ContentResource; import com.smartitengineering.cms.client.api.ContentSearcherResource; import com.smartitengineering.cms.client.api.ContentTypeFeedResource; import com.smartitengineering.cms.client.api.ContentTypeResource; import com.smartitengineering.cms.client.api.ContentTypesResource; import com.smartitengineering.cms.client.api.ContentsResource; import com.smartitengineering.cms.client.api.FieldResource; import com.smartitengineering.cms.client.api.RootResource; import com.smartitengineering.cms.client.api.UriTemplateResource; import com.smartitengineering.cms.client.api.WorkspaceContentCoProcessorResource; import com.smartitengineering.cms.client.api.WorkspaceContentCoProcessorsResource; import com.smartitengineering.cms.client.api.WorkspaceContentResouce; import com.smartitengineering.cms.client.api.WorkspaceFeedResource; import com.smartitengineering.cms.client.api.WorkspaceFriendsResource; import com.smartitengineering.cms.client.api.WorkspaceRepresentationResource; import com.smartitengineering.cms.client.api.WorkspaceRepresentationsResource; import com.smartitengineering.cms.client.api.WorkspaceSequenceResource; import com.smartitengineering.cms.client.api.WorkspaceSequencesResource; import com.smartitengineering.cms.client.api.WorkspaceValidatorResource; import com.smartitengineering.cms.client.api.WorkspaceValidatorsResource; import com.smartitengineering.cms.client.api.WorkspaceVariationResource; import com.smartitengineering.cms.client.api.WorkspaceVariationsResource; -import com.smartitengineering.cms.spi.impl.content.ContentAdapterHelper; import com.smartitengineering.cms.ws.common.domains.CollectionFieldDef; import com.smartitengineering.cms.ws.common.domains.CollectionFieldValue; import com.smartitengineering.cms.ws.common.domains.CompositeFieldDef; import com.smartitengineering.cms.ws.common.domains.CompositeFieldValue; import com.smartitengineering.cms.ws.common.domains.Content; import com.smartitengineering.cms.ws.common.domains.EnumFieldDef; import com.smartitengineering.cms.ws.common.domains.Field; import com.smartitengineering.cms.ws.common.domains.FieldImpl; import com.smartitengineering.cms.ws.common.domains.FieldValue; import com.smartitengineering.cms.ws.common.domains.FieldValueImpl; import com.smartitengineering.cms.ws.common.domains.OtherFieldValueImpl; import com.smartitengineering.cms.ws.common.domains.ResourceTemplateImpl; import com.smartitengineering.cms.ws.common.domains.Workspace; import com.smartitengineering.cms.ws.common.domains.WorkspaceImpl.WorkspaceIdImpl; import com.smartitengineering.cms.ws.common.providers.JacksonJsonProvider; import com.smartitengineering.cms.ws.common.providers.TextURIListProvider; import com.smartitengineering.dao.hbase.ddl.HBaseTableGenerator; import com.smartitengineering.dao.hbase.ddl.config.json.ConfigurationJsonParser; -import com.smartitengineering.util.bean.adapter.GenericAdapter; -import com.smartitengineering.util.bean.adapter.GenericAdapterImpl; import com.smartitengineering.util.bean.guice.GuiceUtil; import com.smartitengineering.util.rest.client.ApplicationWideClientFactoryImpl; import com.smartitengineering.util.rest.client.ClientUtil; import com.smartitengineering.util.rest.client.ConnectionConfig; import com.smartitengineering.util.rest.client.ResourceLink; import com.smartitengineering.util.rest.client.jersey.cache.CacheableClient; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.atom.abdera.impl.provider.entity.FeedProvider; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.sun.jersey.multipart.FormDataMultiPart; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Feed; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.mutable.MutableInt; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster; import org.codehaus.jackson.map.ObjectMapper; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.util.ConcurrentHashSet; import org.eclipse.jetty.webapp.WebAppClassLoader; import org.eclipse.jetty.webapp.WebAppContext; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Unit test for simple App. */ public class AppTest { public static final int SLEEP_DURATION = 3000; private static final int PORT = 10080; public static final String DEFAULT_NS = "com.smartitengineering"; public static final String ROOT_URI_STRING = "http://localhost:" + PORT + "/cms/"; public static final String TEST = "test"; public static final String TEST_NS = "testNS"; private static final MiniZooKeeperCluster ZOO_KEEPER_CLUSTER = new MiniZooKeeperCluster(); private static HBaseTestingUtility TEST_UTIL; private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class); private static Server jettyServer; @BeforeClass public static void globalSetup() throws Exception { /* * Start HBase and initialize tables */ //-Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); try { ZOO_KEEPER_CLUSTER.setClientPort(2181); File file = new File("./target/zk-server/"); file.mkdirs(); ZOO_KEEPER_CLUSTER.startup(file); TEST_UTIL = new HBaseTestingUtility(); TEST_UTIL.setZkCluster(ZOO_KEEPER_CLUSTER); TEST_UTIL.startMiniCluster(); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } new HBaseTableGenerator(ConfigurationJsonParser.getConfigurations(AppTest.class.getClassLoader().getResourceAsStream( "com/smartitengineering/cms/spi/impl/schema.json")), TEST_UTIL.getConfiguration(), true).generateTables(); /* * Ensure DIs done */ Properties properties = new Properties(); properties.setProperty(GuiceUtil.CONTEXT_NAME_PROP, "com.smartitengineering.dao.impl.hbase,com.smartitengineering.user.client"); properties.setProperty(GuiceUtil.IGNORE_MISSING_DEP_PROP, Boolean.TRUE.toString()); properties.setProperty(GuiceUtil.MODULES_LIST_PROP, ConfigurationModule.class.getName()); GuiceUtil.getInstance(properties).register(); Initializer.init(); /* * Start web application container */ jettyServer = new Server(PORT); HandlerList handlerList = new HandlerList(); /* * The following is for solr for later, when this is to be used it */ System.setProperty("solr.solr.home", "./target/sample-conf/"); Handler solr = new WebAppContext("./target/solr/", "/solr"); handlerList.addHandler(solr); WebAppContext hub = new WebAppContext("./target/hub/", "/hub"); final WebAppClassLoader webAppClassLoader = new WebAppClassLoader(hub); hub.setClassLoader(webAppClassLoader); handlerList.addHandler(hub); final String webapp = "./src/test/webapp/"; if (!new File(webapp).exists()) { throw new IllegalStateException("WebApp file/dir does not exist!"); } WebAppContext webAppHandler = new WebAppContext(webapp, "/cms"); handlerList.addHandler(webAppHandler); jettyServer.setHandler(handlerList); jettyServer.setSendDateHeader(true); jettyServer.start(); /* * Setup client properties */ System.setProperty(ApplicationWideClientFactoryImpl.TRACE, "true"); Client client = CacheableClient.create(); client.resource("http://localhost:10080/hub/api/channels/test").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).put( "{\"name\":\"test\"}"); LOGGER.info("Created test channel!"); } @AfterClass public static void globalTearDown() throws Exception { try { jettyServer.stop(); } catch (Exception ex) { LOGGER.warn(ex.getMessage(), ex); } try { TEST_UTIL.shutdownMiniCluster(); } catch (Exception ex) { LOGGER.warn(ex.getMessage(), ex); } try { ZOO_KEEPER_CLUSTER.shutdown(); } catch (Exception ex) { LOGGER.warn(ex.getMessage(), ex); } } @Test public void testStartup() throws URISyntaxException { RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Assert.assertNotNull(resource); Assert.assertEquals(0, resource.getWorkspaces().size()); } @Test public void testCreationAndRetrievalWithNameOnly() throws URISyntaxException { RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); final MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add("name", TEST); ClientResponse response = resource.post(MediaType.APPLICATION_FORM_URLENCODED, map, ClientResponse.Status.CREATED); ResourceLink link = ClientUtil.createResourceLink(WorkspaceContentResouce.WORKSPACE_CONTENT, response.getLocation(), MediaType.APPLICATION_JSON); WorkspaceContentResouce workspaceContentResource = new WorkspaceContentResourceImpl(resource, link); Assert.assertNotNull(workspaceContentResource.getLastReadStateOfEntity()); Workspace workspace = workspaceContentResource.getLastReadStateOfEntity(); Assert.assertEquals(TEST, workspace.getId().getName()); Assert.assertEquals(DEFAULT_NS, workspace.getId().getGlobalNamespace()); Collection<WorkspaceContentResouce> resources = resource.getWorkspaces(); Assert.assertEquals(1, resource.getWorkspaces().size()); workspaceContentResource = resources.iterator().next(); workspace = workspaceContentResource.getLastReadStateOfEntity(); Assert.assertEquals(TEST, workspace.getId().getName()); Assert.assertEquals(DEFAULT_NS, workspace.getId().getGlobalNamespace()); } @Test public void testCreationAndRetrievalWithNamespace() throws URISyntaxException { RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); final MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add("name", TEST); map.add("namespace", TEST_NS); ClientResponse response = resource.post(MediaType.APPLICATION_FORM_URLENCODED, map, ClientResponse.Status.CREATED); ResourceLink link = ClientUtil.createResourceLink(WorkspaceContentResouce.WORKSPACE_CONTENT, response.getLocation(), MediaType.APPLICATION_JSON); WorkspaceContentResouce workspaceContentResource = new WorkspaceContentResourceImpl(resource, link); Assert.assertNotNull(workspaceContentResource.getLastReadStateOfEntity()); Workspace workspace = workspaceContentResource.getLastReadStateOfEntity(); Assert.assertEquals(TEST, workspace.getId().getName()); Assert.assertEquals(TEST_NS, workspace.getId().getGlobalNamespace()); Collection<WorkspaceContentResouce> resources = resource.getWorkspaces(); Assert.assertEquals(2, resource.getWorkspaces().size()); workspaceContentResource = resources.iterator().next(); workspace = workspaceContentResource.getLastReadStateOfEntity(); Assert.assertEquals(TEST, workspace.getId().getName()); Assert.assertEquals(TEST_NS, workspace.getId().getGlobalNamespace()); } @Test public void testConditionalRootResourceGet() throws Exception { final String uri = ROOT_URI_STRING; testConditionalGetUsingLastModified(uri); } @Test public void testConditionalWorkspaceContentResourceGet() throws Exception { final String uri = ROOT_URI_STRING; RootResource resource = RootResourceImpl.getRoot(new URI(uri)); Collection<WorkspaceContentResouce> resouces = resource.getWorkspaces(); for (WorkspaceContentResouce contentResouce : resouces) { testConditionalGetUsingLastModified(contentResouce.getUri().toString()); } } @Test public void testCreateWorkspace() throws Exception { WorkspaceIdImpl workspaceId = new WorkspaceIdImpl(); workspaceId.setName("this is a test"); workspaceId.setGlobalNamespace("a test namespace"); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); int size = resource.getWorkspaces().size(); Workspace workspace = resource.createWorkspace(workspaceId); Assert.assertEquals(workspaceId.getName(), workspace.getId().getName()); Assert.assertEquals(workspaceId.getGlobalNamespace(), workspace.getId().getGlobalNamespace()); Feed feed = resource.get(); Assert.assertNotNull(feed); Assert.assertEquals(size + 1, resource.getWorkspaces().size()); } @Test public void testWorkspaceExists() throws Exception { final RootResource root = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); root.get(); final Iterator<WorkspaceFeedResource> iterator = root.getWorkspaceFeeds().iterator(); WorkspaceFeedResource feedResource = iterator.next(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(new StringBuilder("Total no of workspace created in test : ").append(root.getWorkspaceFeeds().size()). toString()); } Assert.assertNotNull(feedResource); feedResource = iterator.next(); Assert.assertNotNull(feedResource); feedResource = iterator.next(); Assert.assertNotNull(feedResource); Assert.assertEquals(3, root.getWorkspaceFeeds().size()); } @Test public void testAddFriend() throws Exception { final RootResource rootResource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); rootResource.get(); final Iterator<WorkspaceFeedResource> iterator = rootResource.getWorkspaceFeeds().iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceFriendsResource friendsResource = feedResource.getFriends(); friendsResource.addFriend(new URI(ROOT_URI_STRING + "w/com.smartitengineering/test")); friendsResource.get(); Collection<URI> frdUri = friendsResource.getLastReadStateOfEntity(); Iterator<URI> frdUris = frdUri.iterator(); Assert.assertEquals(1, frdUri.size()); Assert.assertEquals(ROOT_URI_STRING + "w/com.smartitengineering/test", frdUris.next().toASCIIString()); friendsResource.addFriend(URI.create("/cms/w/a%20test%20namespace/this%20is%20a%20test")); friendsResource.addFriend(new URI("cms/w/testNS/test")); WorkspaceFriendsResource newFriendsResource = feedResource.getFriends(); Collection<URI> collection = newFriendsResource.get(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(new StringBuilder("Total no of friend workspace after adding a friend are : ").append( collection.size()). toString()); } Assert.assertEquals(3, collection.size()); frdUris = collection.iterator(); String friendWorkspace = frdUris.next().toASCIIString(); Assert.assertEquals(ROOT_URI_STRING + "w/a%20test%20namespace/this%20is%20a%20test", friendWorkspace); LOGGER.debug(new StringBuilder("First friend workspace is : ").append(friendWorkspace).toString()); friendWorkspace = frdUris.next().toASCIIString(); Assert.assertEquals(ROOT_URI_STRING + "w/com.smartitengineering/test", friendWorkspace); LOGGER.debug(new StringBuilder("Second friend workspace is : ").append(friendWorkspace).toString()); friendWorkspace = frdUris.next().toASCIIString(); Assert.assertEquals(ROOT_URI_STRING + "w/testNS/test", friendWorkspace); LOGGER.debug(new StringBuilder("Third friend workspace is : ").append(friendWorkspace).toString()); } @Test public void testDeleteFriend() throws Exception { final RootResource rootResource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); rootResource.get(); final Iterator<WorkspaceFeedResource> iterator = rootResource.getWorkspaceFeeds().iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceFriendsResource friendsResource = feedResource.getFriends(); friendsResource.deleteFriend(new URI(ROOT_URI_STRING + "w/com.smartitengineering/test")); friendsResource.get(); Collection<URI> frdUri = friendsResource.getLastReadStateOfEntity(); Iterator<URI> frdUris = frdUri.iterator(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(new StringBuilder("Total no of friend workspace after deleting a friend is : ").append(frdUri.size()). toString()); } // Assert.assertEquals(2, frdUri.size()); // String friendWorkspace = frdUris.next().toASCIIString(); // Assert.assertEquals(ROOT_URI_STRING + "w/a%20test%20namespace/this%20is%20a%20test", friendWorkspace); // LOGGER.debug(new StringBuilder("First friend workspace is : ").append(friendWorkspace).toString()); // friendWorkspace = frdUris.next().toASCIIString(); // Assert.assertEquals(ROOT_URI_STRING + "w/testNS/test", friendWorkspace); // LOGGER.debug(new StringBuilder("Second friend workspace is : ").append(friendWorkspace).toString()); } @Test public void testReplaceAllFriends() throws Exception { Collection<URI> uris = new ArrayList<URI>(); final RootResource rootResource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); final MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add("name", "additional"); map.add("namespace", "atest2"); rootResource.post(MediaType.APPLICATION_FORM_URLENCODED, map, ClientResponse.Status.CREATED); rootResource.get(); final Iterator<WorkspaceFeedResource> iterator = rootResource.getWorkspaceFeeds().iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceFriendsResource friendsResource = feedResource.getFriends(); uris.add(new URI(ROOT_URI_STRING + "w/atest2/additional")); uris.add(new URI(ROOT_URI_STRING + "w/com.smartitengineering/test")); friendsResource.replaceAllFriends(uris); friendsResource.get(); Collection<URI> frdUri = friendsResource.getLastReadStateOfEntity(); Iterator<URI> frdUris = frdUri.iterator(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(new StringBuilder("Total no of friend workspace after replace all friends are : ").append( frdUri.size()).toString()); } Assert.assertEquals(2, frdUri.size()); final String friendWS1 = frdUris.next().toASCIIString(); Assert.assertEquals(ROOT_URI_STRING + "w/atest2/additional", friendWS1); LOGGER.debug(new StringBuilder("First friend after replacing is : ").append(friendWS1).toString()); final String friendWS2 = frdUris.next().toASCIIString(); Assert.assertEquals(ROOT_URI_STRING + "w/com.smartitengineering/test", friendWS2); LOGGER.debug(new StringBuilder("Second friend after replacing is : ").append(friendWS2).toString()); } @Test public void testDeleteAllFriends() throws Exception { final RootResource rootResource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); rootResource.get(); final Iterator<WorkspaceFeedResource> iterator = rootResource.getWorkspaceFeeds().iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceFriendsResource friendsResource = feedResource.getFriends(); friendsResource.deleteAllFriends(); friendsResource.get(); Collection<URI> frdUri = friendsResource.getLastReadStateOfEntity(); Assert.assertNull(frdUri); } @Test public void testCreateRepresentation() throws Exception { ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "Template"; template.setName("rep"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.JAVASCRIPT.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceRepresentationsResource representationsResource = feedResource.getRepresentations(); WorkspaceRepresentationResource representationResource = representationsResource.createRepresentations(template); Assert.assertEquals("rep", representationResource.get().getName()); Assert.assertEquals(temp, new String(representationResource.get().getTemplate())); Assert.assertEquals(TemplateType.JAVASCRIPT.toString(), representationResource.get().getTemplateType()); } @Test public void testCreateVariation() throws Exception { ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "variationTemplate"; template.setName("variation"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.VELOCITY.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceVariationsResource variationsResource = feedResource.getVariations(); WorkspaceVariationResource variationResource = variationsResource.createVariation(template); Assert.assertEquals("variation", variationResource.get().getName()); Assert.assertEquals(temp, new String(variationResource.get().getTemplate())); Assert.assertEquals(TemplateType.VELOCITY.toString(), variationResource.get().getTemplateType()); } @Test public void testUpdateRepresentation() throws Exception { LOGGER.info(":::::::::::::: UPDATE REPRESENTATION RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "newTemplate"; final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.RUBY.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); Collection<WorkspaceRepresentationResource> representationResources = feedResource.getRepresentations(). getRepresentationsResources(); Assert.assertEquals(1, representationResources.size()); Iterator<WorkspaceRepresentationResource> representationIterator = representationResources.iterator(); WorkspaceRepresentationResource representationResource = representationIterator.next(); representationResource.update(template); Assert.assertEquals("rep", representationResource.get().getName()); Assert.assertEquals(temp, new String(representationResource.get().getTemplate())); Assert.assertEquals(TemplateType.RUBY.toString(), representationResource.get().getTemplateType()); resource.getWorkspaceFeeds(); WorkspaceRepresentationResource secondRepresentationResource = resource.getWorkspaceFeeds().iterator().next(). getRepresentations().getRepresentationsResources().iterator().next(); template.setTemplateType(TemplateType.VELOCITY.name()); secondRepresentationResource.update(template); Assert.assertEquals(TemplateType.VELOCITY.name(), secondRepresentationResource.get().getTemplateType()); try { representationResource.update(template); Assert.fail("Should not have been able to update!"); } catch (UniformInterfaceException ex) { //Exception expected representationResource.get(); representationResource.update(template); } } @Test public void testUpdateVariation() throws Exception { LOGGER.info(":::::::::::::: UPDATE VARIATION RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "newTemplate"; final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.RUBY.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); Collection<WorkspaceVariationResource> variationResources = feedResource.getVariations().getVariationResources(); Assert.assertEquals(1, variationResources.size()); Iterator<WorkspaceVariationResource> VariationIterator = variationResources.iterator(); WorkspaceVariationResource variationResource = VariationIterator.next(); variationResource.update(template); Assert.assertEquals("variation", variationResource.get().getName()); Assert.assertEquals(temp, new String(variationResource.get().getTemplate())); Assert.assertEquals(TemplateType.RUBY.toString(), variationResource.get().getTemplateType()); resource.getWorkspaceFeeds(); WorkspaceVariationResource secondVariationResource = resource.getWorkspaceFeeds().iterator().next(). getVariations().getVariationResources().iterator().next(); template.setTemplateType(TemplateType.VELOCITY.name()); secondVariationResource.update(template); Assert.assertEquals(TemplateType.VELOCITY.name(), secondVariationResource.get().getTemplateType()); try { variationResource.update(template); Assert.fail("Should not have been able to update!"); } catch (UniformInterfaceException ex) { //Exception expected variationResource.get(); variationResource.update(template); } } @Test public void testDeleteRepresentation() throws Exception { LOGGER.info(":::::::::::::: DELETE REPRESENTATION RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "Template2"; template.setName("rep2"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.JAVASCRIPT.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); final WorkspaceRepresentationsResource representationsResource = feedResource.getRepresentations(); Collection<WorkspaceRepresentationResource> representationResources = representationsResource. getRepresentationsResources(); Assert.assertEquals(1, representationResources.size()); representationsResource.createRepresentations(template); Iterator<WorkspaceRepresentationResource> representationIterator = representationResources.iterator(); WorkspaceRepresentationResource representationResource = representationIterator.next(); representationResource.delete(ClientResponse.Status.ACCEPTED); Collection<WorkspaceRepresentationResource> secondRepresentationResources = resource.getWorkspaceFeeds().iterator(). next().getRepresentations().getRepresentationsResources(); Assert.assertEquals(1, secondRepresentationResources.size()); } @Test public void testDeleteVariation() throws Exception { LOGGER.info(":::::::::::::: DELETE VARIATION RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "Template2"; template.setName("aaavar2"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.VELOCITY.name()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); final WorkspaceVariationsResource variationsResource = feedResource.getVariations(); Collection<WorkspaceVariationResource> variationResources = variationsResource.getVariationResources(); Assert.assertEquals(1, variationResources.size()); variationsResource.createVariation(template); variationsResource.get(); variationResources = variationsResource.getVariationResources(); Iterator<WorkspaceVariationResource> variationIterator = variationResources.iterator(); WorkspaceVariationResource variationResource = variationIterator.next(); @@ -2650,535 +2642,645 @@ public class AppTest { Assert.assertNotNull(wCollectiveFieldDef); Assert.assertNotNull(((CollectionFieldDef) wCollectiveFieldDef).getItemDef()); Assert.assertTrue(((CollectionFieldDef) wCollectiveFieldDef).getItemDef() instanceof EnumFieldDef); Assert.assertTrue( ((EnumFieldDef) ((CollectionFieldDef) wCollectiveFieldDef).getItemDef()).getChoices().contains("3")); Assert.assertTrue( ((EnumFieldDef) ((CollectionFieldDef) wCollectiveFieldDef).getItemDef()).getChoices().contains("4")); com.smartitengineering.cms.ws.common.domains.FieldDef wCompositedFieldDef = wDefs.get("compositedEnumField"); Assert.assertNotNull(wCompositedFieldDef); Assert.assertNotNull(((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField")); Assert.assertTrue( ((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField") instanceof EnumFieldDef); Assert.assertTrue(((EnumFieldDef) ((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField")). getChoices().contains("5")); Assert.assertTrue(((EnumFieldDef) ((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField")). getChoices().contains("6")); wCompositedFieldDef = ((CollectionFieldDef) wDefs.get("collectiveCompositedEnumField")).getItemDef(); Assert.assertNotNull(wCompositedFieldDef); Assert.assertNotNull(((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField")); Assert.assertTrue( ((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField") instanceof EnumFieldDef); Assert.assertTrue(((EnumFieldDef) ((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField")). getChoices().contains("7")); Assert.assertTrue(((EnumFieldDef) ((CompositeFieldDef) wCompositedFieldDef).getComposedFields().get("enumField")). getChoices().contains("8")); } @Test public void testCreateContentWithEnumField() throws Exception { LOGGER.info("~~~~~~~~~~~~~~~~~~~~~~~~~~ ENUM CONTENT CREATION ~~~~~~~~~~~~~~~~~~~~~~~~~"); WorkspaceFeedResource feedResource = setupEnumWorkspace(); Properties properties = new Properties(); properties.load(getClass().getClassLoader().getResourceAsStream( "enum/form-value.properties")); Set<Object> formKeys = properties.keySet(); FormDataMultiPart multiPart = new FormDataMultiPart(); for (Object key : formKeys) { multiPart.field(key.toString(), properties.getProperty(key.toString())); } ClientResponse response = feedResource.getContents().post(MediaType.MULTIPART_FORM_DATA, multiPart, ClientResponse.Status.CREATED, ClientResponse.Status.ACCEPTED, ClientResponse.Status.OK); URI uri = response.getLocation(); ContentResourceImpl resourceImpl = new ContentResourceImpl(feedResource, uri); final Content lastReadStateOfEntity = resourceImpl.getLastReadStateOfEntity(); Assert.assertNotNull(lastReadStateOfEntity); Field field = lastReadStateOfEntity.getFieldsMap().get("directEnumField"); String val = field.getValue().getValue(); Assert.assertEquals("1", val); field = ((CompositeFieldValue) lastReadStateOfEntity.getFieldsMap().get("compositedEnumField").getValue()).getValues(). get("enumField"); val = field.getValue().getValue(); Assert.assertEquals("5", val); val = ((CollectionFieldValue) lastReadStateOfEntity.getFieldsMap().get("collectiveEnumField").getValue()).getValues(). iterator().next().getValue(); Assert.assertEquals("4", val); sleep(); for (int i = 1; i < 5; ++i) { try { properties = new Properties(); properties.load(getClass().getClassLoader().getResourceAsStream( "enum/form-invalid-value-" + i + ".properties")); formKeys = properties.keySet(); multiPart = new FormDataMultiPart(); for (Object key : formKeys) { multiPart.field(key.toString(), properties.getProperty(key.toString())); } feedResource.getContents().post(MediaType.MULTIPART_FORM_DATA, multiPart, ClientResponse.Status.CREATED, ClientResponse.Status.ACCEPTED, ClientResponse.Status.OK); Assert.fail("Invalid content should have failed " + i); } catch (Exception ex) { //Expected that creation fails } } } @Test public void testCreateContentCoProcessor() throws Exception { ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "Template"; template.setName("rep"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.JAVASCRIPT.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceContentCoProcessorsResource rsrcs = feedResource.getContentCoProcessors(); WorkspaceContentCoProcessorResource rsrc = rsrcs.createContentCoProcessor( template); Assert.assertEquals("rep", rsrc.get().getName()); Assert.assertEquals(temp, new String(rsrc.get().getTemplate())); Assert.assertEquals(TemplateType.JAVASCRIPT.toString(), rsrc.get().getTemplateType()); } @Test public void testUpdateContentCoProcessor() throws Exception { LOGGER.info(":::::::::::::: UPDATE CONTENT CO PROCESSOR RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "newTemplate"; final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.RUBY.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); Collection<WorkspaceContentCoProcessorResource> representationResources = feedResource.getContentCoProcessors(). getContentCoProcessorResources(); Assert.assertEquals(1, representationResources.size()); Iterator<WorkspaceContentCoProcessorResource> representationIterator = representationResources.iterator(); WorkspaceContentCoProcessorResource rsrc = representationIterator.next(); rsrc.update(template); Assert.assertEquals("rep", rsrc.get().getName()); Assert.assertEquals(temp, new String(rsrc.get().getTemplate())); Assert.assertEquals(TemplateType.RUBY.toString(), rsrc.get().getTemplateType()); resource.getWorkspaceFeeds(); WorkspaceContentCoProcessorResource secondRepresentationResource = resource.getWorkspaceFeeds().iterator().next(). getContentCoProcessors().getContentCoProcessorResources().iterator().next(); template.setTemplateType(TemplateType.JAVASCRIPT.name()); secondRepresentationResource.update(template); Assert.assertEquals(TemplateType.JAVASCRIPT.name(), secondRepresentationResource.get().getTemplateType()); try { rsrc.update(template); Assert.fail("Should not have been able to update!"); } catch (UniformInterfaceException ex) { //Exception expected rsrc.get(); rsrc.update(template); } sleep(); } @Test public void testDeleteContentCoProcessor() throws Exception { LOGGER.info(":::::::::::::: DELETE CONTENT CO PROCESSOR RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "Template2"; template.setName("rep2"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.JAVASCRIPT.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); final WorkspaceContentCoProcessorsResource procsResource = feedResource.getContentCoProcessors(); Collection<WorkspaceContentCoProcessorResource> rsrcs = procsResource.getContentCoProcessorResources(); Assert.assertEquals(1, rsrcs.size()); procsResource.createContentCoProcessor(template); Iterator<WorkspaceContentCoProcessorResource> representationIterator = rsrcs.iterator(); WorkspaceContentCoProcessorResource rsrc = representationIterator.next(); rsrc.delete(ClientResponse.Status.ACCEPTED); Collection<WorkspaceContentCoProcessorResource> secRsrcs = resource.getWorkspaceFeeds().iterator(). next().getContentCoProcessors().getContentCoProcessorResources(); Assert.assertEquals(1, secRsrcs.size()); sleep(); } @Test public void testCreateContentTypeWithContentCoProcessors() { WorkspaceFeedResource feedResource = setupEnumWorkspace(); com.smartitengineering.cms.api.impl.workspace.WorkspaceIdImpl id = new com.smartitengineering.cms.api.impl.workspace.WorkspaceIdImpl(); id.setGlobalNamespace(feedResource.getWorkspaceNamespace()); id.setName(feedResource.getWorkspaceName()); ContentTypeIdImpl idImpl = new ContentTypeIdImpl(); idImpl.setWorkspace(id); idImpl.setNamespace("enum"); idImpl.setName("ContentCoProcessorTest"); ContentType type = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(idImpl); final Map<ContentProcessingPhase, Collection<ContentCoProcessorDef>> contentCoProcessorDefs = type.getContentCoProcessorDefs(); Assert.assertNotNull(contentCoProcessorDefs); Assert.assertFalse(contentCoProcessorDefs.isEmpty()); Assert.assertNotNull(contentCoProcessorDefs.get(ContentProcessingPhase.READ)); Assert.assertNotNull(contentCoProcessorDefs.get(ContentProcessingPhase.WRITE)); Assert.assertFalse(contentCoProcessorDefs.get(ContentProcessingPhase.READ).isEmpty()); Assert.assertFalse(contentCoProcessorDefs.get(ContentProcessingPhase.WRITE).isEmpty()); Assert.assertEquals(2, contentCoProcessorDefs.get(ContentProcessingPhase.READ).size()); Assert.assertEquals(1, contentCoProcessorDefs.get(ContentProcessingPhase.WRITE).size()); final Iterator<ContentCoProcessorDef> readItr = contentCoProcessorDefs.get(ContentProcessingPhase.READ).iterator(); ContentCoProcessorDef def = readItr.next(); Assert.assertEquals("testr", def.getName()); Assert.assertNull(def.getMIMEType()); Assert.assertEquals(0, def.getPriority()); Assert.assertEquals(1, def.getParameters().size()); Assert.assertEquals("v", def.getParameters().get("k")); Assert.assertEquals("test", def.getResourceUri().getValue()); def = readItr.next(); Assert.assertEquals("testr1", def.getName()); Assert.assertNull(def.getMIMEType()); Assert.assertEquals(1, def.getPriority()); Assert.assertEquals(1, def.getParameters().size()); Assert.assertEquals("v1", def.getParameters().get("k1")); Assert.assertEquals("test1", def.getResourceUri().getValue()); def = contentCoProcessorDefs.get(ContentProcessingPhase.WRITE).iterator().next(); Assert.assertEquals("testw", def.getName()); Assert.assertNull(def.getMIMEType()); Assert.assertEquals(0, def.getPriority()); Assert.assertEquals(1, def.getParameters().size()); Assert.assertEquals("v2", def.getParameters().get("k2")); Assert.assertEquals("test2", def.getResourceUri().getValue()); sleep(); } private WorkspaceFeedResource setupContentCoProcessorExecWorkspace() { RootResource resource = RootResourceImpl.getRoot(URI.create(ROOT_URI_STRING)); resource.get(); WorkspaceFeedResource feedResource; try { feedResource = resource.getTemplates().getWorkspaceResource("test", "enums"); } catch (Exception ex) { feedResource = null; LOGGER.info("Exception getting feed resoruce", ex); } boolean valid = false; { try { final WorkspaceIdImpl workspaceId = new WorkspaceIdImpl("test", "enums"); if (feedResource == null) { Workspace workspace = resource.createWorkspace(workspaceId); feedResource = resource.getTemplates().getWorkspaceResource(workspace.getId().getGlobalNamespace(), workspace. getId().getName()); } String contentTypeXml = IOUtils.toString(getClass().getClassLoader().getResourceAsStream( "contentcoprocessors/content-type-def-with-enum-ext.xml")); feedResource.getContentTypes().createContentType(contentTypeXml); ResourceTemplateImpl template = new ResourceTemplateImpl(); template.setName("test"); template.setTemplate(IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream( "contentcoprocessors/coprocessor.groovy"))); template.setTemplateType("GROOVY"); template.setWorkspaceId(workspaceId); feedResource.getContentCoProcessors().createContentCoProcessor(template); valid = true; } catch (Exception ex) { LOGGER.error("Error creating test workspace for templates", ex); } } Assert.assertTrue(valid); return feedResource; } @Test public void testCreateContentWithContentCoProcessors() throws Exception { WorkspaceFeedResource feedResource = setupContentCoProcessorExecWorkspace(); ClientConfig config = new DefaultClientConfig(); config.getClasses().add(JacksonJsonProvider.class); config.getClasses().add(TextURIListProvider.class); config.getClasses().add(FeedProvider.class); Client client = Client.create(config); { final Properties properties = new Properties(); properties.load(getClass().getClassLoader().getResourceAsStream( "contentcoprocessors/form-value-write.properties")); Set<Object> formKeys = properties.keySet(); FormDataMultiPart multiPart = new FormDataMultiPart(); for (Object key : formKeys) { multiPart.field(key.toString(), properties.getProperty(key.toString())); } ClientResponse response = feedResource.getContents().post(MediaType.MULTIPART_FORM_DATA, multiPart, ClientResponse.Status.CREATED, ClientResponse.Status.ACCEPTED, ClientResponse.Status.OK); URI uri = response.getLocation(); ContentResourceImpl resourceImpl = new ContentResourceImpl(feedResource, uri); final Content lastReadStateOfEntity = resourceImpl.getLastReadStateOfEntity(); Assert.assertNotNull(lastReadStateOfEntity); Assert.assertNotNull(lastReadStateOfEntity.getFieldsMap().get("directEnumFieldCopy")); Assert.assertNotNull(lastReadStateOfEntity.getFieldsMap().get("dynaField")); Assert.assertEquals(lastReadStateOfEntity.getFieldsMap().get("directEnumField").getValue().getValue(), lastReadStateOfEntity.getFieldsMap().get("directEnumFieldCopy").getValue().getValue()); String dynaField = lastReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue(); sleep(); final Content reReadStateOfEntity = client.resource(resourceImpl.getUri()).accept(MediaType.APPLICATION_JSON). header("Pragma", "no-cache").get(Content.class); Assert.assertEquals(dynaField, reReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue()); } { final Properties properties = new Properties(); properties.load(getClass().getClassLoader().getResourceAsStream( "contentcoprocessors/form-value-read.properties")); Set<Object> formKeys = properties.keySet(); FormDataMultiPart multiPart = new FormDataMultiPart(); for (Object key : formKeys) { multiPart.field(key.toString(), properties.getProperty(key.toString())); } ClientResponse response = feedResource.getContents().post(MediaType.MULTIPART_FORM_DATA, multiPart, ClientResponse.Status.CREATED, ClientResponse.Status.ACCEPTED, ClientResponse.Status.OK); URI uri = response.getLocation(); ContentResourceImpl resourceImpl = new ContentResourceImpl(feedResource, uri); final Content lastReadStateOfEntity = resourceImpl.getLastReadStateOfEntity(); Assert.assertNotNull(lastReadStateOfEntity); Assert.assertNotNull(lastReadStateOfEntity.getFieldsMap().get("directEnumFieldCopy")); Assert.assertNotNull(lastReadStateOfEntity.getFieldsMap().get("dynaField")); Assert.assertEquals(lastReadStateOfEntity.getFieldsMap().get("directEnumField").getValue().getValue(), lastReadStateOfEntity.getFieldsMap().get("directEnumFieldCopy").getValue().getValue()); String dynaField = lastReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue(); sleep(); final Content reReadStateOfEntity = client.resource(resourceImpl.getUri()).accept(MediaType.APPLICATION_JSON). header("Pragma", "no-cache").get(Content.class); Assert.assertFalse(dynaField.equals(reReadStateOfEntity.getFieldsMap().get("dynaField").getValue().getValue())); } sleep(); } private WorkspaceFeedResource setupSequenceWorkspace() { RootResource resource = RootResourceImpl.getRoot(URI.create(ROOT_URI_STRING)); resource.get(); WorkspaceFeedResource feedResource; try { feedResource = resource.getTemplates().getWorkspaceResource("test", "sequences"); } catch (Exception ex) { feedResource = null; LOGGER.info("Exception getting feed resoruce", ex); } boolean valid = false; { try { final WorkspaceIdImpl workspaceId = new WorkspaceIdImpl("test", "sequences"); if (feedResource == null) { Workspace workspace = resource.createWorkspace(workspaceId); feedResource = resource.getTemplates().getWorkspaceResource(workspace.getId().getGlobalNamespace(), workspace. getId().getName()); } valid = true; } catch (Exception ex) { LOGGER.error("Error creating test workspace for templates", ex); } } Assert.assertTrue(valid); return feedResource; } @Test public void testCreateSequences() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Create Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.putSequence(workspace.getId(), TEST, PORT); Assert.assertNotNull(sequence); Assert.assertEquals(workspace.getId(), sequence.getWorkspace()); Assert.assertEquals(TEST, sequence.getName()); Assert.assertEquals(PORT, sequence.getCurrentValue()); sleep(); } @Test public void testGetSequence() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Get Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertNotNull(sequence); Assert.assertEquals(workspace.getId(), sequence.getWorkspace()); Assert.assertEquals(TEST, sequence.getName()); Assert.assertEquals(PORT, sequence.getCurrentValue()); Collection<Sequence> sequences = workspaceApi.getSequencesForWorkspace(workspace.getId()); Assert.assertNotNull(sequences); Assert.assertEquals(1, sequences.size()); sequence = sequences.iterator().next(); Assert.assertNotNull(sequence); Assert.assertEquals(workspace.getId(), sequence.getWorkspace()); Assert.assertEquals(TEST, sequence.getName()); Assert.assertEquals(PORT, sequence.getCurrentValue()); sleep(); } @Test public void testBasicSequenceModifications() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Basic Modify Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); long newVal = workspaceApi.modifySequenceValue(sequence, 1); Assert.assertEquals(PORT + 1, newVal); newVal = workspaceApi.modifySequenceValue(sequence, -2); Assert.assertEquals(PORT - 1, newVal); newVal = workspaceApi.modifySequenceValue(sequence, 1); Assert.assertEquals(PORT, newVal); sleep(); } @Test public void testSingleJVMMultiThreadedSequenceModifications() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Multithread modify Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); final Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); final ConcurrentHashSet<Long> vals = new ConcurrentHashSet<Long>(); Runnable runnable = new Runnable() { public void run() { for (int i = 0; i < 100; ++i) { long newVal = workspaceApi.modifySequenceValue(sequence, 1); Assert.assertTrue(vals.add(newVal)); } } }; long start = System.currentTimeMillis(); Collection<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < 10; ++i) { Thread thread = new Thread(runnable); thread.start(); threads.add(thread); } try { for (Thread thread : threads) { thread.join(); } } catch (Exception ex) { LOGGER.error("Could wait for thread to end!", ex); throw new IllegalArgumentException(ex); } long end = System.currentTimeMillis(); sleep(); Sequence lsequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertEquals(PORT + 1000, lsequence.getCurrentValue()); LOGGER.info("Duration for 1000 increments " + (end - start) + "ms"); } @Test public void testDeleteSequence() { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Delete Sequence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi(); com.smartitengineering.cms.api.workspace.Workspace workspace = workspaceApi.createWorkspaceId(resource. getWorkspaceNamespace(), resource.getWorkspaceName()).getWorkspace(); Sequence sequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertNotNull(sequence); workspaceApi.deleteSequence(workspace.getId(), TEST); sequence = workspaceApi.getSequence(workspace.getId(), TEST); Assert.assertNull(sequence); sleep(); Collection<Sequence> sequences = workspaceApi.getSequencesForWorkspace(workspace.getId()); Assert.assertNotNull(sequences); Assert.assertEquals(0, sequences.size()); } @Test public void testCreateSequencesViaWebService() { WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceSequencesResource sequences = resource.getSequences(); Assert.assertNotNull(sequences); sequences.createSequence(TEST, PORT); sleep(); sequences.get(); Collection<WorkspaceSequenceResource> seqs = sequences.getSequences(); Assert.assertEquals(1, seqs.size()); WorkspaceSequenceResource seq = sequences.getSequenceByName(TEST); Assert.assertEquals(TEST, seq.getName()); Assert.assertEquals(PORT, seq.getCurrentValue()); } @Test public void testUpdateSequenceViaWebService() { WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceSequencesResource sequences = resource.getSequences(); Assert.assertNotNull(sequences); WorkspaceSequenceResource seq = sequences.getSequenceByName(TEST); Assert.assertNotNull(seq); long newVal = seq.update(1); Assert.assertEquals(TEST, seq.getName()); Assert.assertEquals(PORT + 1, newVal); sleep(); } @Test public void testDeleteSequenceViaWebService() { WorkspaceFeedResource resource = setupSequenceWorkspace(); final WorkspaceSequencesResource sequences = resource.getSequences(); Assert.assertNotNull(sequences); WorkspaceSequenceResource seq = sequences.getSequenceByName(TEST); Assert.assertNotNull(seq); seq.delete(ClientResponse.Status.ACCEPTED); try { seq = sequences.getSequenceByName(TEST); } catch (Exception ex) { //Expected } sleep(); } + @Test + public void testDeleteWorkspace() { + LOGGER.info("::::::::::::::::::::: TEST DELETE WORKSPACE ::::::::::::::::::::::"); + + // create a workspace for delete + WorkspaceId workspaceForDeleteId = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspace("wsfordelete"); + //SmartContentAPI.getInstance().getWorkspaceApi().createWorkspace(workspaceForDeleteId); + com.smartitengineering.cms.api.workspace.Workspace workSpaceForDelete = SmartContentAPI.getInstance(). + getWorkspaceApi().getWorkspace(workspaceForDeleteId); + Assert.assertNotNull(workSpaceForDelete); + + // create content type + InputStream stream = getClass().getClassLoader().getResourceAsStream("content-type-for-delete.xml"); + + try { + final ContentTypeLoader contentTypeLoader = SmartContentAPI.getInstance().getContentTypeLoader(); + final Collection<WritableContentType> types; + types = contentTypeLoader.parseContentTypes(workSpaceForDelete.getId(), stream, + com.smartitengineering.cms.api.common.MediaType.APPLICATION_XML); + for (WritableContentType type : types) { + type.put(); + } + } + catch (Exception ex) { + LOGGER.info("Can not create ContentType for delete", ex); + Assert.fail(); + } + ContentTypeId contentTypeId = SmartContentAPI.getInstance().getContentTypeLoader().createContentTypeId( + workspaceForDeleteId, "com.smartitengineering.smart-shopping.content", "ContentTypeForDelete"); + + + ContentType contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); + Assert.assertNotNull(contentType); + + // create content + String statusKey = contentType.getStatuses().keySet().iterator().next(); + ContentStatus contentStatus = contentType.getStatuses().get(statusKey); + + final WriteableContent writeableContent; + + MutableContent mutableContent = SmartContentAPI.getInstance().getContentLoader().createContent(contentType); + mutableContent.setContentDefinition(contentType); + mutableContent.setPrivate(false); + mutableContent.setStatus(contentStatus); + MutableField mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); + mutableField.setName("name"); + MutableFieldValue<String> mutableFieldValue = + new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); + mutableFieldValue.setValue("russel"); + mutableField.setValue(mutableFieldValue); + mutableContent.setField(mutableField); + //Create new content + writeableContent = SmartContentAPI.getInstance().getContentLoader().getWritableContent(mutableContent); + writeableContent.createContentId(workspaceForDeleteId); + + + try { + //Save or update the content, will be decided by writeable content implementation + writeableContent.put(); + } + catch (IOException ex) { + LOGGER.error(ex.getMessage(), ex); + Assert.fail(); + } + + SmartContentAPI.getInstance().getWorkspaceApi().deleteWorkspace(workspaceForDeleteId); + com.smartitengineering.cms.api.workspace.Workspace fetchedWorkspace = SmartContentAPI.getInstance().getWorkspaceApi(). + getWorkspace(workspaceForDeleteId); + if (fetchedWorkspace == null) { + LOGGER.info("Fetched workspace null"); + } + Assert.assertNull(fetchedWorkspace); + + contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); + Assert.assertNull(contentType); + + + + final WriteableContent writeableContentForDeleteTest; + mutableContent = SmartContentAPI.getInstance().getContentLoader().createContent(contentType); + mutableContent.setContentDefinition(contentType); + mutableContent.setPrivate(false); + mutableContent.setStatus(contentStatus); + mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); + mutableField.setName("name"); + mutableFieldValue = new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); + mutableFieldValue.setValue("russel"); + mutableField.setValue(mutableFieldValue); + mutableContent.setField(mutableField); + //Create new content + writeableContentForDeleteTest = SmartContentAPI.getInstance().getContentLoader().getWritableContent(mutableContent); + writeableContentForDeleteTest.createContentId(workspaceForDeleteId); + + + try { + //Save or update the content, will be decided by writeable content implementation + writeableContentForDeleteTest.put(); + Assert.fail(); + } + catch (IOException ex) { + LOGGER.info("should fail"); + + } + + } + + @Test + public void testDeleteWorkspaceViaWebservice() { + } + protected void sleep() { try { Thread.sleep(SLEEP_DURATION); } catch (Exception ex) { LOGGER.error("Error sleeping", ex); } } public static class ConfigurationModule extends AbstractModule { @Override protected void configure() { bind(Configuration.class).toInstance(TEST_UTIL.getConfiguration()); ConnectionConfig config = new ConnectionConfig(); config.setBasicUri(""); config.setContextPath("/"); config.setHost("localhost"); config.setPort(PORT); bind(ConnectionConfig.class).toInstance(config); } } } diff --git a/webservice-modules/smart-cms-client-impl/src/test/resources/content-type-for-delete.xml b/webservice-modules/smart-cms-client-impl/src/test/resources/content-type-for-delete.xml new file mode 100644 index 0000000..d9e1ac6 --- /dev/null +++ b/webservice-modules/smart-cms-client-impl/src/test/resources/content-type-for-delete.xml @@ -0,0 +1,73 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * + * This is a simple Content Management System (CMS) + * Copyright (C) 2009 Imran M Yousuf ([email protected]) + * + * 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/>. +--> +<!-- + Document : content-type-def-product.xml + Created on : September 25, 2009, 5:20 PM + Author : imyousuf + Description: + A sample content type definition in context of smart shopping +--> +<contentTypes xmlns="http://www.smartitengineering.com/smart-cms/content/content-type-schema" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.smartitengineering.com/smart-cms/content/content-type-schema http://github.com/smart-it/smart-cms/raw/master/content-api-impl/src/main/resources/com/smartitengineering/cms/content/content-type-schema.xsd"> + + <contentType namespace="com.smartitengineering.smart-shopping.content"> + <name>ContentTypeForDelete</name> + <primaryField>name</primaryField> + <fields> + <field> + <name>name</name> + <value> + <string> + <mimeType>text/plain</mimeType> + </string> + </value> + <required>true</required> + <variations> + <variation> + <name>avar</name> + <mimeType>some/type</mimeType> + <uri> + <external>http://some/uri</external> + </uri> + </variation> + <variation> + <name>anothervar</name> + <mimeType>some/type</mimeType> + <uri> + <internal> + <name>internalvar</name> + </internal> + </uri> + </variation> + </variations> + <search> + <index>true</index> + <store>false</store> + <boost>a</boost> + </search> + </field> + </fields> + <status> + <statusName>draft</statusName> + <statusName>published</statusName> + </status> + </contentType> +</contentTypes>
SmartITEngineering/smart-cms
2c18a7cd858d908025dc775253cebf99a2b1195b
Remove JavaDoc from build plugins to reduce Jenkins build time
diff --git a/pom.xml b/pom.xml index 309a055..4e080bc 100644 --- a/pom.xml +++ b/pom.xml @@ -1,152 +1,148 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- * * This is a simple Content Management System (CMS) * Copyright (C) 2009 Imran M Yousuf ([email protected]) * 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/>. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.smartitengineering</groupId> <artifactId>smart-core</artifactId> <version>0.1.11-SNAPSHOT</version> </parent> <groupId>com.smartitengineering</groupId> <artifactId>smart-cms</artifactId> <packaging>pom</packaging> <version>0.1-SNAPSHOT</version> <name>Smart CMS</name> <inceptionYear>2009</inceptionYear> <description> This project basically aims to create an abstraction layer using Smart DAO for saving contents. That is persisting customizable beans and making the customized beans searchable is its main feature. Since it will heavily depend on Smart DAO for now the project will be discussed with Smart DAO groups. </description> <url>http://smart-cms.kenai.com</url> <organization> <name>Smart IT Engineering</name> <url>http://www.smartitengineering.com</url> </organization> <issueManagement> <system>Google Code Issue Tracker</system> <url>http://kenai.com/bugzilla/buglist.cgi?product=smart-cms</url> </issueManagement> <licenses> <license> <name>GPL v3</name> <distribution>repo and manual</distribution> <url>http://www.gnu.org/licenses/gpl-3.0-standalone.html</url> </license> </licenses> <developers> <developer> <id>imyousuf</id> <name>Imran M Yousuf</name> <email>[email protected]</email> <organization>Smart IT Engineering</organization> <timezone>GMT +0600</timezone> <roles> <role>Project Owner</role> <role>Developer</role> <role>Maintainer</role> </roles> </developer> <developer> <id>modhu7</id> <name>Subrata Sen Gupta</name> <email>[email protected]</email> <organization>Smart IT Engineering</organization> <timezone>GMT +0600</timezone> <roles> <role>Project Owner</role> <role>Developer</role> </roles> </developer> <developer> <id>kaisar</id> <name>Md. Kaisar Ali</name> <email>[email protected]</email> <organization>Smart IT Engineering</organization> <timezone>GMT +0600</timezone> <roles> <role>Developer</role> </roles> </developer> </developers> <scm> <connection>scm:git:git://github.com/SmartITEngineering/smart-cms.git</connection> <developerConnection>scm:git:[email protected]:SmartITEngineering/smart-cms.git</developerConnection> </scm> <build> <pluginManagement> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>javancss-maven-plugin</artifactId> <inherited>true</inherited> <configuration> <includes> <include>**/*.java</include> </includes> </configuration> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-javadoc-plugin</artifactId> - </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <inherited>true</inherited> <configuration> <excludePackageNames>test:testa:testb:testc:com.embarcadero.edn:enumeration</excludePackageNames> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>javancss-maven-plugin</artifactId> </plugin> </plugins> </reporting> <modules> <module>api-modules</module> <module>spi-modules</module> <module>webservice-modules</module> <module>code-generation</module> </modules> </project>
SmartITEngineering/smart-cms
614cd6b9e3988fa138cc146deb3ed72ebb7b2377
Fix WorkspaceId injection for RepositoryDAOImpl
diff --git a/code-generation/maven-pojo-generator-plugin/src/main/java/com/smartitengineering/cms/maven/dto/generator/plugin/PojoGeneratorMojo.java b/code-generation/maven-pojo-generator-plugin/src/main/java/com/smartitengineering/cms/maven/dto/generator/plugin/PojoGeneratorMojo.java index 7054693..1fb2dbe 100644 --- a/code-generation/maven-pojo-generator-plugin/src/main/java/com/smartitengineering/cms/maven/dto/generator/plugin/PojoGeneratorMojo.java +++ b/code-generation/maven-pojo-generator-plugin/src/main/java/com/smartitengineering/cms/maven/dto/generator/plugin/PojoGeneratorMojo.java @@ -1,870 +1,865 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2011 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.maven.dto.generator.plugin; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.PrivateModule; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.MapBinder; import com.google.inject.name.Names; import com.smartitengineering.cms.api.content.CompositeFieldValue; import com.smartitengineering.cms.api.content.Content; import com.smartitengineering.cms.api.content.ContentId; import com.smartitengineering.cms.api.content.Field; import com.smartitengineering.cms.api.content.FieldValue; import com.smartitengineering.cms.api.content.MutableCompositeFieldValue; import com.smartitengineering.cms.api.content.MutableField; import com.smartitengineering.cms.api.content.MutableFieldValue; import com.smartitengineering.cms.api.factory.SmartContentAPI; import com.smartitengineering.cms.api.factory.content.ContentLoader; import com.smartitengineering.cms.api.factory.content.WriteableContent; import com.smartitengineering.cms.api.impl.type.ContentTypeImpl; import com.smartitengineering.cms.api.impl.workspace.WorkspaceIdImpl; import com.smartitengineering.cms.api.type.CollectionDataType; import com.smartitengineering.cms.api.type.CompositeDataType; import com.smartitengineering.cms.api.type.ContentDataType; import com.smartitengineering.cms.api.type.ContentType; import com.smartitengineering.cms.api.type.ContentType.DefinitionType; import com.smartitengineering.cms.api.type.ContentTypeId; import com.smartitengineering.cms.api.type.EnumDataType; import com.smartitengineering.cms.api.type.FieldDef; import com.smartitengineering.cms.api.type.FieldValueType; import com.smartitengineering.cms.api.type.MutableContentType; import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.cms.repo.dao.impl.AbstractRepoAdapterHelper; import com.smartitengineering.cms.repo.dao.impl.AbstractRepositoryDomain; import com.smartitengineering.cms.repo.dao.impl.ExtendedReadDao; import com.smartitengineering.cms.repo.dao.impl.Initializer; import com.smartitengineering.cms.repo.dao.impl.RepositoryDaoImpl; import com.smartitengineering.cms.repo.dao.impl.tx.CommonTxDao; import com.smartitengineering.cms.repo.dao.impl.tx.TransactionImplModule; import com.smartitengineering.cms.repo.dao.impl.tx.Transactionable; import com.smartitengineering.cms.type.xml.XMLParserIntrospector; import com.smartitengineering.cms.type.xml.XmlParser; import com.smartitengineering.dao.common.CommonDao; import com.smartitengineering.dao.common.CommonReadDao; import com.smartitengineering.dao.common.CommonWriteDao; import com.smartitengineering.domain.PersistentDTO; import com.smartitengineering.util.bean.adapter.AbstractAdapterHelper; import com.smartitengineering.util.bean.adapter.GenericAdapter; import com.smartitengineering.util.bean.adapter.GenericAdapterImpl; import com.sun.codemodel.ClassType; import com.sun.codemodel.JBlock; import com.sun.codemodel.JClass; import com.sun.codemodel.JClassAlreadyExistsException; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JConditional; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JExpr; import com.sun.codemodel.JExpression; import com.sun.codemodel.JFieldVar; import com.sun.codemodel.JForLoop; import com.sun.codemodel.JInvocation; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JType; import com.sun.codemodel.JVar; import com.sun.codemodel.JWhileLoop; import nu.xom.Element; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.maven.project.MavenProject; /** * Goal which touches a timestamp file. Configure any one of contentTypesResourceConfig, contentTypeResourceConfig and * contentTypeResource. Not configuring any one of them or more than one would result runtime exception. * * @goal generate * * @phase generate-sources */ public class PojoGeneratorMojo extends AbstractMojo { /** * Location of the file. * @parameter expression="${generated.sources.directory}" * @required */ private File outputDirectory; /** * A collection of content types for generating POJOs for beans in multiple workspaces. Content types could either be * a file or a classpath resource. If either is missing it would result a classpath exception * @parameter */ private List<String> contentTypes; /** * A content type file * @parameter */ private File contentTypeResource; /** * Default package for aggregating modules * @parameter * @required */ private String packageForGuiceMasterModule; /** * The workspace id for the specified content type resource. It will be used to DI in the adapter and DAO Impl * @parameter * @required */ private String workspaceId; /** * The Maven project instance for the executing project. * * @parameter expression="${project}" * @required */ private MavenProject project; /** * The content type files from classpath to use for initialization * * @parameter */ private List<String> typeFiles; /** * Whether transaction is enabled for this piece of generated code or not. By default its false to be backward * compatible. * @parameter expression="false" */ private boolean transactionEnabled; /** * Whether a transaction with isolated=false is allowed or not. By default its not allowed. * @parameter expression="false" */ private boolean nonIsolatedTransactionAllowed; public void execute() throws MojoExecutionException { File f = outputDirectory; if (!f.exists()) { f.mkdirs(); } if ((contentTypes == null || contentTypes.isEmpty()) && contentTypeResource == null) { throw new MojoExecutionException("Parameters not specified properly. Any one and only one of " + "contentTypesResourceConfig, contentTypeResourceConfig and contentTypeResource must be specified!"); } if (StringUtils.isBlank(packageForGuiceMasterModule)) { throw new MojoExecutionException("Parameter 'packageForGuiceMasterModule' can not be blank"); } JCodeModel codeModel = new JCodeModel(); Set<MutableContentType> types = new LinkedHashSet<MutableContentType>(); if (StringUtils.isBlank(workspaceId) || workspaceId.split(":").length != 2) { throw new MojoExecutionException("Workspace ID not specified or is not in format 'namespace:name'"); } final String wIds[] = workspaceId.split(":"); if (contentTypeResource != null) { if (!contentTypeResource.exists() || !contentTypeResource.isFile()) { throw new MojoExecutionException("'contentTypeResource' file either does not exist or is not a file: " + (contentTypeResource == null ? null : contentTypeResource.getAbsolutePath())); } final WorkspaceIdImpl dummyIdImpl = new WorkspaceIdImpl(); dummyIdImpl.setGlobalNamespace(wIds[0]); dummyIdImpl.setName(wIds[1]); types.addAll(parseContentType(dummyIdImpl, contentTypeResource)); } else { for (String contentTypeRsrc : contentTypes) { final String value = contentTypeRsrc; if (StringUtils.isBlank(value)) { throw new MojoExecutionException("'contentTypesResourceConfig' can not have empty resource config"); } File file = new File(value); if (file.exists() && file.isFile()) { WorkspaceIdImpl idImpl = new WorkspaceIdImpl(); idImpl.setGlobalNamespace(wIds[0]); idImpl.setName(wIds[1]); types.addAll(parseContentType(idImpl, file)); } else { throw new MojoExecutionException("'contentTypesResourceConfig' can not have a resource config that is neither" + "a file nor a classpath resoruce: " + value); } } } try { generateCode(codeModel, types); codeModel.build(outputDirectory); project.addCompileSourceRoot(outputDirectory.getAbsolutePath()); } catch (Exception ex) { throw new MojoExecutionException(ex.getMessage(), ex); } } protected void generateIoCClasses(JCodeModel codeModel, Set<MutableContentType> types, Map<ContentTypeId, JDefinedClass> classes, Map<ContentTypeId, JDefinedClass> helpers, Map<ContentTypeId, JDefinedClass> modules) throws JClassAlreadyExistsException { // Create helpers and google guice module for concrete type definitions JClass privateModuleClass = codeModel.ref(PrivateModule.class); // Initialize common classes for Google Guice bindings JClass typeLiteral = codeModel.ref(TypeLiteral.class); JClass commonDao = codeModel.ref(CommonDao.class); JClass commonReadDao = codeModel.ref(CommonReadDao.class); JClass extendedReadDao = codeModel.ref(ExtendedReadDao.class); JClass commonWriteDao = codeModel.ref(CommonWriteDao.class); JClass commonDaoImpl = codeModel.ref(RepositoryDaoImpl.class); JClass commonTxDao = codeModel.ref(CommonTxDao.class); JClass transactionableAnn = codeModel.ref(Transactionable.class); JClass genericAdapter = codeModel.ref(GenericAdapter.class).narrow(Content.class); JClass classRef = codeModel.ref(Class.class); JClass genericAdapterImpl = codeModel.ref(GenericAdapterImpl.class).narrow(Content.class); JClass abstractHelper = codeModel.ref(AbstractAdapterHelper.class).narrow(Content.class); JClass singletonScope = codeModel.ref(Singleton.class); - JClass workspaceIdClass = codeModel.ref(WorkspaceId.class); - JClass apiClass = codeModel.ref(SmartContentAPI.class); String[] wId = workspaceId.split(":"); for (MutableContentType type : types) { if (type.getDefinitionType().equals(DefinitionType.CONCRETE_TYPE)) { final ContentTypeId contentTypeID = type.getContentTypeID(); JDefinedClass definedClass = classes.get(contentTypeID); final JDefinedClass helperClass = generateHelper(type, codeModel, classes, types); helpers.put(contentTypeID, helperClass); { final String moduleClassName = new StringBuilder(contentTypeID.getNamespace()).append(".guice.").append(contentTypeID. getName()).append("Module").toString(); final JDefinedClass moduleClass = codeModel._class(moduleClassName); modules.put(contentTypeID, moduleClass); moduleClass._extends(privateModuleClass); JMethod configureMethod = moduleClass.method(JMod.PUBLIC, JCodeModel.boxToPrimitive.get(Void.class), "configure"); JBlock block = configureMethod.body(); final JDefinedClass commonDaoType; final JDefinedClass daoImplType; final JDefinedClass txDaoImplType; final JDefinedClass readDaoType; final JDefinedClass writeDaoType; { final JClass narrowedCommonDaoTypeLiteral = typeLiteral.narrow(commonDao.narrow(definedClass).narrow( String.class)); commonDaoType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append( "CommonDaoType").toString()); commonDaoType._extends(narrowedCommonDaoTypeLiteral); } { final JClass narrowedReadTypeLiteral = typeLiteral.narrow(commonReadDao.narrow(definedClass).narrow( String.class)); readDaoType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append("ReadDaoType"). toString()); readDaoType._extends(narrowedReadTypeLiteral); block.add(JExpr.invoke("bind").arg(JExpr._new(readDaoType)).invoke("to").arg(JExpr._new(commonDaoType)). invoke("in").arg(singletonScope.dotclass())); block.add(JExpr.invoke("binder").invoke("expose").arg(JExpr._new(readDaoType))); } { final JClass narrowedWriteTypeLiteral = typeLiteral.narrow(commonWriteDao.narrow(definedClass)); writeDaoType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append("WriteDaoType"). toString()); writeDaoType._extends(narrowedWriteTypeLiteral); block.add(JExpr.invoke("bind").arg(JExpr._new(writeDaoType)).invoke("to").arg(JExpr._new(commonDaoType)). invoke("in").arg(singletonScope.dotclass())); block.add(JExpr.invoke("binder").invoke("expose").arg(JExpr._new(writeDaoType))); } { final JClass narrowedDaoImplTypeLiteral = typeLiteral.narrow(commonDaoImpl.narrow(definedClass)); final JClass narrowedCommonTxDaoTypeLiteral = typeLiteral.narrow(commonTxDao.narrow(definedClass)); final JClass beanClass = classRef.narrow(definedClass); JDefinedClass classType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append( "ClassType").toString()); classType._extends(typeLiteral.narrow(beanClass)); daoImplType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append("DaoImplType"). toString()); daoImplType._extends(narrowedDaoImplTypeLiteral); txDaoImplType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append( "CommonTxDaoType").toString()); txDaoImplType._extends(narrowedCommonTxDaoTypeLiteral); block.add(JExpr.invoke("bind").arg(JExpr._new(classType)).invoke("toInstance").arg(definedClass.dotclass())); if (transactionEnabled) { block.add(JExpr.invoke("bind").arg(JExpr._new(commonDaoType)).invoke("to").arg(JExpr._new(txDaoImplType))); block.add(JExpr.invoke("bind").arg(JExpr._new(readDaoType)).invoke("annotatedWith").arg(transactionableAnn. dotclass()).invoke("to").arg(JExpr._new(daoImplType))); block.add(JExpr.invoke("bind").arg(JExpr._new(writeDaoType)).invoke("annotatedWith").arg(transactionableAnn. dotclass()).invoke("to").arg(JExpr._new(daoImplType))); } else { block.add(JExpr.invoke("bind").arg(JExpr._new(commonDaoType)).invoke("to").arg(JExpr._new(daoImplType))); } block.add(JExpr.invoke("binder").invoke("expose").arg(JExpr._new(commonDaoType))); } { final JClass narrowedReadTypeLiteral = typeLiteral.narrow(extendedReadDao.narrow(definedClass).narrow( String.class)); final JDefinedClass extReadDaoType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()). append("ExtReadDaoType").toString()); extReadDaoType._extends(narrowedReadTypeLiteral); block.add(JExpr.invoke("bind").arg(JExpr._new(extReadDaoType)).invoke("to").arg(JExpr._new(daoImplType)). invoke("in").arg(singletonScope.dotclass())); block.add(JExpr.invoke("binder").invoke("expose").arg(JExpr._new(extReadDaoType))); } { JClass lGenericAdapter = genericAdapter.narrow(definedClass); JClass lGenericAdapterImpl = genericAdapterImpl.narrow(definedClass); JClass lAbstractHelper = abstractHelper.narrow(definedClass); final JDefinedClass adapterHelperType = moduleClass._class(new StringBuilder( type.getContentTypeID().getName()).append("AdapterType").toString()); adapterHelperType._extends(typeLiteral.narrow(lGenericAdapter)); final JDefinedClass adapterImplType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()). append("AdapterImplType").toString()); adapterImplType._extends(typeLiteral.narrow(lGenericAdapterImpl)); final JDefinedClass abstractHelperType = moduleClass._class(new StringBuilder(type.getContentTypeID(). getName()).append("AdapterHelperType").toString()); abstractHelperType._extends(typeLiteral.narrow(lAbstractHelper)); final JDefinedClass helperType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()). append("AdapterHelperImplType").toString()); helperType._extends(typeLiteral.narrow(helperClass)); block.add(JExpr.invoke("bind").arg(JExpr._new(adapterHelperType)).invoke("to").arg(JExpr._new( adapterImplType)).invoke("in").arg(singletonScope.dotclass())); block.add(JExpr.invoke("bind").arg(JExpr._new(abstractHelperType)).invoke("to").arg(JExpr._new(helperType)). invoke("in").arg(singletonScope.dotclass())); - final JInvocation workspaceApiInvocation = apiClass.staticInvoke("getInstance").invoke("getWorkspaceApi"). - invoke("createWorkspaceId"); - final JInvocation _new = workspaceApiInvocation.arg(wId[0]).arg(wId[1]); - block.add(JExpr.invoke("bind").arg(workspaceIdClass.dotclass()).invoke("toInstance").arg(_new)); + } //String TypeLiteral final JDefinedClass stringType; { final JClass narrowedReadTypeLiteral = typeLiteral.narrow(String.class); stringType = moduleClass._class("StringType"); stringType._extends(narrowedReadTypeLiteral); } //Traverse fields to make their DIs { Collection<FieldDef> defs = getAllFields(type, types).values(); generateAssociationIoCForFields(defs, codeModel, stringType, typeLiteral, moduleClass, block, types, classes, type.getContentTypeID().getName(), new HashSet<ContentTypeId>()); } } } } generateMasterModule(modules, codeModel, wId); } protected Set<FieldDef> getAllComposedFields(CompositeDataType compositeDataType, Set<? extends ContentType> types) { Set<FieldDef> compositeFields = new LinkedHashSet<FieldDef>(); if (compositeDataType.getEmbeddedContentType() != null) { ContentType currentType = getType(types, compositeDataType.getEmbeddedContentType().getTypeDef()); if (currentType != null) { compositeFields.addAll(getAllFields(currentType, types).values()); } } compositeFields.addAll(compositeDataType.getOwnComposition()); return compositeFields; } protected Map<String, FieldDef> getAllFields(ContentType currentType, Set<? extends ContentType> types) { Map<String, FieldDef> defs = new LinkedHashMap<String, FieldDef>(); boolean hasMore = true; while (hasMore) { Map<String, FieldDef> ownFields = currentType.getOwnFieldDefs(); for (Entry<String, FieldDef> ownField : ownFields.entrySet()) { if (!defs.containsKey(ownField.getKey())) { defs.put(ownField.getKey(), ownField.getValue()); } } if (currentType.getParent() != null) { final ContentTypeId parent = currentType.getParent(); currentType = getType(types, parent); hasMore = currentType != null; } else { hasMore = false; } } return defs; } protected ContentType getType(Set<? extends ContentType> types, final ContentTypeId id) { for (ContentType type : types) { if (type.getContentTypeID().equals(id)) { return type; } } return null; } protected JFieldVar initializeDao(ContentTypeId typeId, JDefinedClass helperClass, JCodeModel model, Map<ContentTypeId, JDefinedClass> classes) { final JDefinedClass typeDef = classes.get(typeId); final String varClassName = typeDef.name(); String readDaoName = new StringBuilder(new StringBuilder().append( ("" + varClassName.charAt(0)).toLowerCase()).append(varClassName.substring(1)).toString()).append( "ReadDaos").toString(); JFieldVar readDaoVar = helperClass.fields().get(readDaoName); if (readDaoVar == null) { readDaoVar = helperClass.field(JMod.PRIVATE, model.ref(Map.class).narrow(String.class).narrow(model.ref( CommonReadDao.class).narrow(typeDef.wildcard()).narrow( String.class)), readDaoName); readDaoVar.annotate(Inject.class); } return readDaoVar; } protected Collection<MutableContentType> parseContentType(final WorkspaceId id, File file) throws MojoExecutionException { try { final XmlParser parser = new XmlParser(id, new FileInputStream(file), new XMLParserIntrospector() { public MutableContentType createMutableContentType() { return new ContentTypeImpl(); } public void processMutableContentType(MutableContentType type, Element element) { } }); return parser.parse(); } catch (Exception ex) { throw new MojoExecutionException(ex.getMessage(), ex); } } protected void generateCode(JCodeModel codeModel, Set<MutableContentType> types) throws Exception { Map<ContentTypeId, JDefinedClass> classes = new LinkedHashMap<ContentTypeId, JDefinedClass>(); Map<ContentTypeId, JDefinedClass> helpers = new LinkedHashMap<ContentTypeId, JDefinedClass>(); Map<ContentTypeId, JDefinedClass> modules = new LinkedHashMap<ContentTypeId, JDefinedClass>(); // Create the classes for (MutableContentType type : types) { final ContentTypeId contentTypeID = type.getContentTypeID(); classes.put(contentTypeID, generateClassForType(type, codeModel)); } // Set parent content types as appropriate for (MutableContentType type : types) { final JDefinedClass typeClass = classes.get(type.getContentTypeID()); if (type.getParent() != null) { final JClass parentClass = classes.get(type.getParent()); typeClass._extends(parentClass); } } // Create members and their accessors for (MutableContentType type : types) { generateFields(type.getOwnFieldDefs().values(), classes.get(type.getContentTypeID()), classes, codeModel); } generateIoCClasses(codeModel, types, classes, helpers, modules); } protected JDefinedClass generateHelper(final ContentType contentType, JCodeModel codeModel, Map<ContentTypeId, JDefinedClass> classes, Set<? extends ContentType> types) throws JClassAlreadyExistsException { ContentTypeId contentTypeID = contentType.getContentTypeID(); final JDefinedClass definedClass = classes.get(contentTypeID); final JClass parentClass = codeModel.ref(AbstractRepoAdapterHelper.class); final JDefinedClass helperClass; final String helperClassName = new StringBuilder(contentTypeID.getNamespace()).append(".helpers.").append(contentTypeID. getName()).append("Helper").toString(); helperClass = codeModel._class(helperClassName); helperClass._extends(parentClass.narrow(definedClass)); ContentType currentType = contentType; Map<String, FieldDef> defs = getAllFields(currentType, types); { JMethod forwardConversion = helperClass.method(JMod.PROTECTED, JCodeModel.boxToPrimitive.get(Void.class), "mergeContentIntoBean"); JVar content = forwardConversion.param(Content.class, "fromBean"); JVar toBean = forwardConversion.param(definedClass, "toBean"); JBlock block = forwardConversion.body(); generateForwardBlocks(defs.values(), block, content, toBean, codeModel, definedClass, helperClass, classes, types, ""); } { JMethod reverseConversion = helperClass.method(JMod.PROTECTED, JCodeModel.boxToPrimitive.get(Void.class), "mergeBeanIntoContent"); JVar fromBean = reverseConversion.param(definedClass, "fromBean"); JVar wContent = reverseConversion.param(WriteableContent.class, "toBean"); JBlock block = reverseConversion.body(); JInvocation staticInvoke = codeModel.ref(SmartContentAPI.class).staticInvoke("getInstance"); block._if(staticInvoke.eq(JExpr._null()))._then()._throw(JExpr._new(codeModel.ref(IllegalStateException.class)). arg("Smart Content API can not be null!")); JVar contentLoader = block.decl(JMod.FINAL, codeModel.ref(ContentLoader.class), "contentLoader", staticInvoke.invoke("getContentLoader")); JVar fieldDefs = block.decl(codeModel.ref(Map.class).narrow(String.class).narrow(FieldDef.class), "fieldDefs", wContent.invoke("getContentDefinition").invoke("getFieldDefs")); generateReverseBlocks(defs.values(), block, fromBean, wContent, contentLoader, fieldDefs, codeModel, definedClass, classes, types, ""); } { JMethod instanceCreation = helperClass.method(JMod.PROTECTED, definedClass, "newTInstance"); JBlock block = instanceCreation.body(); block._return(JExpr._new(definedClass)); } return helperClass; } protected JDefinedClass generateClassForType(MutableContentType type, JCodeModel codeModel) throws JClassAlreadyExistsException { ContentTypeId typeId = type.getContentTypeID(); int mod = JMod.PUBLIC; final DefinitionType defType = type.getDefinitionType(); if (defType.equals(ContentType.DefinitionType.ABSTRACT_COMPONENT)) { // Extend nothing mod = mod | JMod.ABSTRACT; } else if (defType.equals(ContentType.DefinitionType.ABSTRACT_TYPE)) { mod = mod | JMod.ABSTRACT; } JDefinedClass definedClass = codeModel._class(mod, new StringBuilder(typeId.getNamespace()).append('.').append(typeId. getName()).toString(), ClassType.CLASS); if (defType.equals(ContentType.DefinitionType.ABSTRACT_TYPE) || defType.equals( ContentType.DefinitionType.CONCRETE_TYPE)) { JClass clazz = codeModel.ref(AbstractRepositoryDomain.class); definedClass._extends(clazz.narrow(definedClass)); } return definedClass; } protected void generateFields(Collection<FieldDef> fields, JDefinedClass definedClass, Map<ContentTypeId, JDefinedClass> classes, JCodeModel codeModel) throws JClassAlreadyExistsException, ClassNotFoundException { for (FieldDef def : fields) { final Class fieldClass; final JType jType; final String name = def.getName(); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); switch (def.getValueDef().getType()) { case BOOLEAN: fieldClass = Boolean.class; jType = null; break; case STRING: fieldClass = String.class; jType = null; break; case CONTENT: ContentDataType contentDataType = (ContentDataType) def.getValueDef(); fieldClass = null; final ContentTypeId typeDef = contentDataType.getTypeDef(); jType = classes.get(typeDef); break; case DATE_TIME: fieldClass = Date.class; jType = null; break; case INTEGER: fieldClass = Integer.class; jType = null; break; case DOUBLE: fieldClass = Double.class; jType = null; break; case LONG: fieldClass = Long.class; jType = null; break; case OTHER: fieldClass = byte[].class; jType = null; break; case ENUM: { JDefinedClass enumClass = definedClass._enum(JMod.PUBLIC | JMod.STATIC, getterSetterSuffix); EnumDataType enumDataType = (EnumDataType) def.getValueDef(); Collection<String> choices = enumDataType.getChoices(); for (String choice : choices) { enumClass.enumConstant(choice); } fieldClass = null; jType = enumClass; break; } case COLLECTION: fieldClass = null; final JClass itemType; CollectionDataType collectionDataType = (CollectionDataType) def.getValueDef(); switch (collectionDataType.getItemDataType().getType()) { case BOOLEAN: itemType = codeModel.ref(Boolean.class); break; case STRING: itemType = codeModel.ref(String.class); break; case CONTENT: itemType = classes.get(((ContentDataType) collectionDataType.getItemDataType()).getTypeDef()); break; case DATE_TIME: itemType = codeModel.ref(Date.class); break; case INTEGER: itemType = codeModel.ref(Integer.class); break; case DOUBLE: itemType = codeModel.ref(Double.class); break; case LONG: itemType = codeModel.ref(Long.class); break; case OTHER: itemType = codeModel.ref(byte[].class); break; case ENUM: { JDefinedClass enumClass = definedClass._enum(JMod.PUBLIC | JMod.STATIC, getterSetterSuffix); EnumDataType enumDataType = (EnumDataType) collectionDataType.getItemDataType(); Collection<String> choices = enumDataType.getChoices(); for (String choice : choices) { enumClass.enumConstant(choice); } itemType = enumClass; break; } case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) collectionDataType.getItemDataType(); ContentDataType composedOfContent = compositeDataType.getEmbeddedContentType(); final JDefinedClass composedOfClass; if (composedOfContent != null) { composedOfClass = classes.get(composedOfContent.getTypeDef()); } else { composedOfClass = null; } if (compositeDataType.getOwnComposition() != null && !compositeDataType.getOwnComposition().isEmpty()) { JDefinedClass compositeFieldClass = definedClass._class(JMod.STATIC | JMod.PUBLIC, getterSetterSuffix); if (composedOfContent != null) { compositeFieldClass._extends(composedOfClass); } generateFields(compositeDataType.getOwnComposition(), compositeFieldClass, classes, codeModel); itemType = compositeFieldClass; } else if (composedOfContent != null) { itemType = composedOfClass; } else { itemType = codeModel.ref(Object.class); } break; } default: itemType = codeModel.ref(Object.class); } jType = codeModel.ref(Collection.class).narrow(itemType); break; case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) def.getValueDef(); ContentDataType composedOfContent = compositeDataType.getEmbeddedContentType(); if (compositeDataType.getOwnComposition() != null && !compositeDataType.getOwnComposition().isEmpty()) { fieldClass = null; JDefinedClass compositeFieldClass = definedClass._class(JMod.STATIC | JMod.PUBLIC, getterSetterSuffix); if (composedOfContent != null) { compositeFieldClass._extends(classes.get(composedOfContent.getTypeDef())); } generateFields(compositeDataType.getOwnComposition(), compositeFieldClass, classes, codeModel); jType = compositeFieldClass; } else if (composedOfContent != null) { fieldClass = null; jType = classes.get(composedOfContent.getTypeDef()); } else { fieldClass = Object.class; jType = null; } break; } default: fieldClass = Object.class; jType = null; } final String getterName = new StringBuilder("get").append(getterSetterSuffix).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); final JFieldVar fieldVar; final JMethod getterMethod; final JMethod setterMethod; final JVar paramVar; final JFieldVar propConstant = definedClass.field(JMod.PUBLIC | JMod.FINAL | JMod.STATIC, String.class, new StringBuilder("PROPERTY").append('_').append(name. toUpperCase()).toString(), JExpr.lit(name)); if (jType == null) { fieldVar = definedClass.field(JMod.PROTECTED, fieldClass, name); getterMethod = definedClass.method(JMod.PUBLIC, fieldClass, getterName); setterMethod = definedClass.method(JMod.PUBLIC, JCodeModel.boxToPrimitive.get(Void.class), setterName); paramVar = setterMethod.param(fieldClass, name); } else { fieldVar = definedClass.field(JMod.PROTECTED, jType, name); getterMethod = definedClass.method(JMod.PUBLIC, jType, getterName); setterMethod = definedClass.method(JMod.PUBLIC, JCodeModel.boxToPrimitive.get(Void.class), setterName); paramVar = setterMethod.param(jType, name); } final JBlock getterBlock = getterMethod.body(); getterBlock._return(fieldVar); JBlock setterBlock = setterMethod.body(); setterBlock.assign(JExpr._this().ref(fieldVar), paramVar); } } protected void generateForwardBlocks(Collection<FieldDef> values, JBlock block, JVar from, JVar toBean, JCodeModel model, JDefinedClass currentClass, JDefinedClass helperClass, Map<ContentTypeId, JDefinedClass> classes, Set<? extends ContentType> types, String prefix) { final JClass contentIdRef = model.ref(ContentId.class); for (FieldDef def : values) { final String name = def.getName(); final String varName = getVarName(prefix, name); final String fieldVar = new StringBuilder(varName).append("Field").toString(); JVar field = block.decl(model.ref(Field.class), fieldVar, from.invoke("getField").arg(name)); JConditional conditional = block._if(field.ne(JExpr._null())); JBlock valBlock = conditional._then(); switch (def.getValueDef().getType()) { case BOOLEAN: setField(valBlock, model, field, name, toBean, Boolean.class, prefix); break; case STRING: setField(valBlock, model, field, name, toBean, String.class, prefix); break; case ENUM: { final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); final String fieldValVar = getVarName(prefix, new StringBuilder(name).append("Val").toString()); JClass enumClass = ((JClass) currentClass.fields().get(name).type()); JVar fieldVal = block.decl(model.ref(FieldValue.class).narrow(String.class), fieldValVar, field.invoke( "getValue")); JConditional valCond = block._if(fieldVal.ne(JExpr._null())); JBlock setBlock = valCond._then(); setBlock.add(toBean.invoke(setterName).arg(enumClass.staticInvoke("valueOf").arg(fieldVal.invoke("getValue")))); break; } case DATE_TIME: setField(valBlock, model, field, name, toBean, Date.class, prefix); break; case INTEGER: setField(valBlock, model, field, name, toBean, Integer.class, prefix); break; case DOUBLE: setField(valBlock, model, field, name, toBean, Double.class, prefix); break; case LONG: setField(valBlock, model, field, name, toBean, Long.class, prefix); break; case OTHER: setField(valBlock, model, field, name, toBean, byte[].class, prefix); break; case CONTENT: { ContentDataType contentDataType = (ContentDataType) def.getValueDef(); final JDefinedClass typeDef = classes.get(contentDataType.getTypeDef()); if (typeDef != null) { JFieldVar readDaoVar = initializeDao(contentDataType.getTypeDef(), helperClass, model, classes); if (readDaoVar != null) { final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); final String fieldValVar = new StringBuilder(varName).append("Val").toString(); JVar fieldVal = valBlock.decl(model.ref(FieldValue.class).narrow(contentIdRef), fieldValVar, field.invoke("getValue")); JConditional valCond = valBlock._if(fieldVal.ne(JExpr._null())); JBlock setBlock = valCond._then(); final JVar contentIdVal = setBlock.decl(contentIdRef, getVarName(prefix, "contentIdVal"), fieldVal.invoke( "getValue")); JConditional idValCond = setBlock._if(contentIdVal.ne(JExpr._null())); JBlock typeDaoBlock = idValCond._then(); String readDaoName = new StringBuilder(new StringBuilder().append( ("" + typeDef.name().charAt(0)).toLowerCase()).append(typeDef.name().substring(1)).toString()).append( "ReadDao").toString(); JVar typeDao = typeDaoBlock.decl(model.ref(CommonReadDao.class).narrow(typeDef.wildcard()).narrow( String.class), readDaoName, readDaoVar.invoke("get").arg(contentIdVal.invoke("getContent").invoke( "getContentDefinition").invoke("toString"))); JConditional daoValCond = typeDaoBlock._if(typeDao.ne(JExpr._null())); daoValCond._then().add(toBean.invoke(setterName).arg(typeDao.invoke("getById").arg( contentIdVal.invoke("toString")))); } } break; } case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) def.getValueDef(); Set<FieldDef> compositeFields = getAllComposedFields(compositeDataType, types); JClass compFieldVal = model.ref(FieldValue.class).narrow(model.ref(Collection.class).narrow(Field.class)); final JVar fieldVal = valBlock.decl(compFieldVal, new StringBuilder(varName).append("FieldVal").toString(), field.invoke("getValue")); JDefinedClass compositeDefinition = findClass(compositeDataType, currentClass, classes, name); JDefinedClass newCompositeDefintion = findConcreteClass(compositeDefinition, classes); if (compositeDefinition != null && newCompositeDefintion != null) { JBlock validCompVal = valBlock._if(fieldVal.ne(JExpr._null()))._then(); final JVar compositeToBean = validCompVal.decl(compositeDefinition, varName, JExpr._new( newCompositeDefintion)); final JClass ref = model.ref(CompositeFieldValue.class); JVar compositeFromBean = validCompVal.decl(ref, new StringBuilder(varName).append("Val").toString(), JExpr. cast(ref, fieldVal)); String compPrefix = new StringBuilder(varName).append('_').toString(); generateForwardBlocks(compositeFields, validCompVal, compositeFromBean, compositeToBean, model, compositeDefinition, helperClass, classes, types, compPrefix); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); validCompVal.add(toBean.invoke(setterName).arg(compositeToBean)); } break; } case COLLECTION: CollectionDataType collectionDataType = (CollectionDataType) def.getValueDef(); switch (collectionDataType.getItemDataType().getType()) { case BOOLEAN: setCollectionField(valBlock, model, field, Boolean.class, name, toBean, prefix); break; case STRING: setCollectionField(valBlock, model, field, String.class, name, toBean, prefix); break; case ENUM: { JClass itClass = (JClass) ((JClass) currentClass.fields().get(name).type()).getTypeParameters().get(0); JVar resultVal = valBlock.decl(model.ref(Collection.class).narrow(itClass), getVarName(prefix, "beanList"), JExpr._new(model.ref(ArrayList.class).narrow(itClass))); final JClass narrowedCollection = model.ref(Collection.class).narrow(FieldValue.class); JVar fieldVal = valBlock.decl(model.ref(FieldValue.class).narrow(narrowedCollection), getVarName(prefix, "fieldVal"), field.invoke("getValue")); JConditional collectionValCond = valBlock._if(fieldVal.ne(JExpr._null())); JBlock validValBlock = collectionValCond._then(); JVar collectionVal = validValBlock.decl(narrowedCollection, getVarName(prefix, "collectionVal"), fieldVal. invoke( "getValue")); JConditional validCollectionCond = validValBlock._if(collectionVal.ne(JExpr._null()).cand(collectionVal. invoke( "isEmpty").not())); JBlock iterateBlock = validCollectionCond._then(); JVar iterator = iterateBlock.decl(model.ref(Iterator.class).narrow(FieldValue.class), getVarName(prefix, "iterator"), collectionVal.invoke("iterator")); JWhileLoop loop = iterateBlock._while(iterator.invoke("hasNext")); JBlock loopBlock = loop.body(); JVar val = loopBlock.decl(model.ref(FieldValue.class).narrow(String.class), getVarName(prefix, "val"), iterator.invoke("next")); JConditional singleValCond = loopBlock._if(val.ne(JExpr._null())); singleValCond._then().add(resultVal.invoke("add").arg(itClass.staticInvoke("valueOf").arg(val.invoke( "getValue")))); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. @@ -937,662 +932,668 @@ public class PojoGeneratorMojo extends AbstractMojo { } break; } case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) collectionDataType.getItemDataType(); Set<FieldDef> compositeFields = new LinkedHashSet<FieldDef>(); if (compositeDataType.getEmbeddedContentType() != null) { ContentType currentType = getType(types, compositeDataType.getEmbeddedContentType().getTypeDef()); if (currentType != null) { compositeFields.addAll(getAllFields(currentType, types).values()); } } compositeFields.addAll(compositeDataType.getOwnComposition()); JDefinedClass compositeDefinition = findClass(compositeDataType, currentClass, classes, name); JDefinedClass newCompositeDefintion = findConcreteClass(compositeDefinition, classes); if (compositeDefinition != null && newCompositeDefintion != null) { JVar resultVal = valBlock.decl(model.ref(Collection.class).narrow(newCompositeDefintion), getVarName(prefix, "beanList"), JExpr._new(model.ref(ArrayList.class).narrow(newCompositeDefintion))); final JClass narrowedCollection = model.ref(Collection.class).narrow(FieldValue.class); JVar fieldVal = valBlock.decl(model.ref(FieldValue.class).narrow(narrowedCollection), getVarName(prefix, "fieldVal"), field.invoke("getValue")); JConditional collectionValCond = valBlock._if(fieldVal.ne(JExpr._null())); JBlock validValBlock = collectionValCond._then(); JVar collectionVal = validValBlock.decl(narrowedCollection, getVarName(prefix, "collectionVal"), fieldVal.invoke("getValue")); JConditional validCollectionCond = validValBlock._if(collectionVal.ne(JExpr._null()).cand(collectionVal. invoke("isEmpty").not())); JBlock iterateBlock = validCollectionCond._then(); JVar iterator = iterateBlock.decl(model.ref(Iterator.class).narrow(FieldValue.class), getVarName(prefix, "iterator"), collectionVal.invoke("iterator")); JWhileLoop loop = iterateBlock._while(iterator.invoke("hasNext")); JBlock loopBlock = loop.body(); JVar val = loopBlock.decl(model.ref(FieldValue.class).narrow(model.ref(Collection.class).narrow( Field.class)), getVarName(prefix, "val"), iterator.invoke("next")); final JBlock _then = loopBlock; JBlock validCompVal = _then._if(val.ne(JExpr._null()))._then(); final JVar compositeToBean = validCompVal.decl(compositeDefinition, varName, JExpr._new( newCompositeDefintion)); final JClass ref = model.ref(CompositeFieldValue.class); JVar compositeFromBean = validCompVal.decl(ref, new StringBuilder(varName).append("Val").toString(), JExpr.cast(ref, val)); String compPrefix = new StringBuilder(varName).append('_').toString(); generateForwardBlocks(compositeFields, validCompVal, compositeFromBean, compositeToBean, model, compositeDefinition, helperClass, classes, types, compPrefix); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); validCompVal.add(resultVal.invoke("add").arg(compositeToBean)); valBlock.add(toBean.invoke(setterName).arg(resultVal)); } } } break; default: } } } protected void setCollectionField(JBlock valBlock, JCodeModel model, JVar field, final Class narrowClass, final String name, JVar toBean, String prefix) { final JVar collectionVal = addToCollection(valBlock, model, field, narrowClass, prefix); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); valBlock.add(toBean.invoke(setterName).arg(collectionVal)); } protected String getVarName(String prefix, String literal) { return new StringBuilder(prefix).append(literal).toString(); } protected JVar addToCollection(JBlock valBlock, JCodeModel model, JVar field, final Class narrowClass, String prefix) { JVar resultVal = valBlock.decl(model.ref(Collection.class).narrow(narrowClass), getVarName(prefix, "beanList"), JExpr._new(model.ref(ArrayList.class).narrow(narrowClass))); final JClass narrowedCollection = model.ref(Collection.class).narrow(FieldValue.class); JVar fieldVal = valBlock.decl(model.ref(FieldValue.class).narrow(narrowedCollection), getVarName(prefix, "fieldVal"), field.invoke("getValue")); JConditional collectionValCond = valBlock._if(fieldVal.ne(JExpr._null())); JBlock validValBlock = collectionValCond._then(); JVar collectionVal = validValBlock.decl(narrowedCollection, getVarName(prefix, "collectionVal"), fieldVal.invoke( "getValue")); JConditional validCollectionCond = validValBlock._if(collectionVal.ne(JExpr._null()).cand(collectionVal.invoke( "isEmpty").not())); JBlock iterateBlock = validCollectionCond._then(); JVar iterator = iterateBlock.decl(model.ref(Iterator.class).narrow(FieldValue.class), getVarName(prefix, "iterator"), collectionVal.invoke("iterator")); JWhileLoop loop = iterateBlock._while(iterator.invoke("hasNext")); JBlock loopBlock = loop.body(); JVar val = loopBlock.decl(model.ref(FieldValue.class).narrow(narrowClass), getVarName(prefix, "val"), iterator. invoke("next")); JConditional singleValCond = loopBlock._if(val.ne(JExpr._null())); singleValCond._then().add(resultVal.invoke("add").arg(val.invoke("getValue"))); return resultVal; } protected void setField(JBlock block, JCodeModel model, JVar field, final String name, JVar toBean, Class valType, String prefix) { final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); final String fieldValVar = getVarName(prefix, new StringBuilder(name).append("Val").toString()); JVar fieldVal = block.decl(model.ref(FieldValue.class).narrow(valType), fieldValVar, field.invoke("getValue")); JConditional valCond = block._if(fieldVal.ne(JExpr._null())); JBlock setBlock = valCond._then(); setBlock.add(toBean.invoke(setterName).arg(fieldVal.invoke("getValue"))); } protected void addField(JBlock block, JCodeModel model, JVar field, final String name, JVar toBean, Class valType, String prefix) { final String setterName = "add"; final String fieldValVar = getVarName(prefix, new StringBuilder(name).append("Val").toString()); JVar fieldVal = block.decl(model.ref(FieldValue.class).narrow(valType), fieldValVar, field.invoke("getValue")); JConditional valCond = block._if(fieldVal.ne(JExpr._null())); JBlock setBlock = valCond._then(); setBlock.add(toBean.invoke(setterName).arg(fieldVal.invoke("getValue"))); } protected JDefinedClass findClass(CompositeDataType compositeDataType, JDefinedClass currentClass, Map<ContentTypeId, JDefinedClass> classes, String fieldName) { final String getterSetterSuffix = new StringBuilder().append(("" + fieldName.charAt(0)).toUpperCase()).append(fieldName. substring(1)).toString(); JDefinedClass jType = null; ContentDataType composedOfContent = compositeDataType.getEmbeddedContentType(); if (compositeDataType.getOwnComposition() != null && !compositeDataType.getOwnComposition().isEmpty()) { Iterator<JDefinedClass> compositeFieldClasses = currentClass.classes(); while (compositeFieldClasses.hasNext()) { JDefinedClass innerClass = compositeFieldClasses.next(); if (innerClass.name().equals(getterSetterSuffix)) { jType = innerClass; } } } else if (composedOfContent != null) { jType = classes.get(composedOfContent.getTypeDef()); } return jType; } protected JDefinedClass findConcreteClass(JDefinedClass compositeDefinition, Map<ContentTypeId, JDefinedClass> classes) { if (compositeDefinition.isAbstract()) { for (JDefinedClass clazz : classes.values()) { if (!clazz.isAbstract() && compositeDefinition.isAssignableFrom(clazz)) { return clazz; } else { JDefinedClass inInnerClass = findConcreteInInnerClass(compositeDefinition, clazz); if (inInnerClass != null) { return inInnerClass; } } } return null; } else { return compositeDefinition; } } protected JDefinedClass findConcreteInInnerClass(JDefinedClass compositeDefinition, JDefinedClass clazz) { final Iterator<JDefinedClass> classes = clazz.classes(); while (classes.hasNext()) { JDefinedClass innerClass = classes.next(); if (compositeDefinition.isAssignableFrom(innerClass)) { return innerClass; } else { JDefinedClass inInnerClass = findConcreteInInnerClass(compositeDefinition, innerClass); if (inInnerClass != null) { return inInnerClass; } } } return null; } protected void generateReverseBlocks(Collection<FieldDef> values, JBlock block, JVar fromBean, JVar wContent, JVar contentLoader, JVar fieldDefs, JCodeModel model, JDefinedClass currentClass, Map<ContentTypeId, JDefinedClass> classes, Set<? extends ContentType> types, String prefix) { for (FieldDef def : values) { final String name = def.getName(); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String getterName = new StringBuilder("get").append(getterSetterSuffix).toString(); switch (def.getValueDef().getType()) { case BOOLEAN: { final String methodName = "createBooleanFieldValue"; final Class valClass = Boolean.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case STRING: { final String methodName = "createStringFieldValue"; final Class valClass = String.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case ENUM: { final String methodName = "createStringFieldValue"; final Class valClass = String.class; JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(valClass), getVarName(prefix, "fieldVal"), contentLoader.invoke(methodName)); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(fromBean.invoke(getterName).invoke("name"))); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); break; } case DATE_TIME: { final String methodName = "createDateTimeFieldValue"; final Class valClass = Date.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case INTEGER: { final String methodName = "createIntegerFieldValue"; final Class valClass = Number.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case DOUBLE: { final String methodName = "createDoubleFieldValue"; final Class valClass = Number.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case LONG: { final String methodName = "createLongFieldValue"; final Class valClass = Number.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case OTHER: { final String methodName = "createOtherFieldValue"; final Class valClass = byte[].class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case CONTENT: { JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null()).cand(fromBean.invoke(getterName).invoke("getId").ne(JExpr._null()))))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()). arg(fieldDefs.invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(ContentId.class), getVarName(prefix, "fieldVal"), contentLoader.invoke("createContentFieldValue")); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(JExpr._super().invoke("getContentId").arg(fromBean. invoke(getterName).invoke("getId")).arg(fromBean.invoke(getterName).invoke("getWorkspaceId")))); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); break; } case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) def.getValueDef(); JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null())))._then(); JDefinedClass clazz = findClass(compositeDataType, currentClass, classes, name); JVar input = nonNullBlock.decl(clazz, getVarName(prefix, "compositeField"), fromBean.invoke(getterName)); final JInvocation defArg = fieldDefs.invoke("get").arg(name); JVar fieldDef = nonNullBlock.decl(model.ref(FieldDef.class), getVarName(prefix, "def"), defArg); JVar compositeFieldDefs = nonNullBlock.decl( model.ref(Map.class).narrow(String.class).narrow(FieldDef.class), getVarName(prefix, "compositeFieldDefs"), JExpr.invoke(JExpr.cast(model.ref(CompositeDataType.class), fieldDef.invoke("getValueDef")), "getComposedFieldDefs")); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDef)); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableCompositeFieldValue.class), getVarName(prefix, "fieldVal"), contentLoader.invoke("createCompositeFieldValue")); Collection<FieldDef> defs = getAllComposedFields(compositeDataType, types); generateReverseBlocks(defs, nonNullBlock, input, mutableFieldValue, contentLoader, compositeFieldDefs, model, clazz, classes, types, new StringBuilder(prefix).append(name).append('_').toString()); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); break; } case COLLECTION: CollectionDataType collectionDataType = (CollectionDataType) def.getValueDef(); switch (collectionDataType.getItemDataType().getType()) { case BOOLEAN: { final String methodName = "createBooleanFieldValue"; final Class valClass = Boolean.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case STRING: { final String methodName = "createStringFieldValue"; final Class valClass = String.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case ENUM: { final String methodName = "createStringFieldValue"; final Class valClass = String.class; JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get"). arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(model.ref( Collection.class). narrow(model.ref(FieldValue.class))), getVarName(prefix, "fieldVals"), contentLoader.invoke( "createCollectionFieldValue")); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); JVar collection = nonNullBlock.decl(model.ref(Collection.class).narrow(model.ref(FieldValue.class)), getVarName( prefix, "collectionVar"), JExpr._new(model.ref(ArrayList.class).narrow(FieldValue.class))); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(collection)); final JForLoop forLoop = nonNullBlock._for(); JType itClass = ((JClass) currentClass.fields().get(name).type()).getTypeParameters().get(0); JVar iterator_item = forLoop.init(model.ref(Iterator.class).narrow(itClass), getVarName(prefix, "i"), fromBean.invoke(getterName).invoke("iterator")); forLoop.test(iterator_item.invoke("hasNext")); final JBlock forBody = forLoop.body(); JVar mutableItemFieldValue = forBody.decl(model.ref(MutableFieldValue.class).narrow(valClass), getVarName(prefix, "fieldVal"), contentLoader.invoke(methodName)); forBody.add(mutableItemFieldValue.invoke("setValue").arg(iterator_item.invoke("next").invoke("name"))); forBody.add(collection.invoke("add").arg(mutableItemFieldValue)); break; } case DATE_TIME: { final String methodName = "createDateTimeFieldValue"; final Class valClass = Date.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case INTEGER: { final String methodName = "createIntegerFieldValue"; final Class valClass = Number.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case DOUBLE: { final String methodName = "createDoubleFieldValue"; final Class valClass = Number.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case LONG: { final String methodName = "createLongFieldValue"; final Class valClass = Number.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case OTHER: { final String methodName = "createOtherFieldValue"; final Class valClass = byte[].class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case CONTENT: { JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get"). arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(model.ref( Collection.class).narrow(model.ref(FieldValue.class))), getVarName(prefix, "fieldVals"), contentLoader.invoke("createCollectionFieldValue")); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); JVar collection = nonNullBlock.decl(model.ref(Collection.class).narrow(model.ref(FieldValue.class)), getVarName(prefix, "collectionVar"), JExpr._new(model.ref( ArrayList.class).narrow(FieldValue.class))); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(collection)); final JForLoop forLoop = nonNullBlock._for(); final JClass narrowedDomain = model.ref(AbstractRepositoryDomain.class).narrow(model.ref( PersistentDTO.class).narrow(model.ref(PersistentDTO.class).wildcard()).narrow(String.class).narrow( Long.class).wildcard()); JVar iterator_item = forLoop.init(model.ref(Iterator.class).narrow(narrowedDomain.wildcard()), getVarName( prefix, "i"), fromBean.invoke(getterName).invoke("iterator")); forLoop.test(iterator_item.invoke("hasNext")); final JBlock forBody = forLoop.body(); JVar nextVal = forBody.decl(narrowedDomain, getVarName(prefix, "domain"), iterator_item.invoke( "next")); JVar mutableItemFieldValue = forBody.decl(model.ref(MutableFieldValue.class).narrow(ContentId.class), getVarName(prefix, "fieldVal"), contentLoader.invoke("createContentFieldValue")); forBody.add(mutableItemFieldValue.invoke("setValue").arg(JExpr._super().invoke("getContentId").arg(nextVal. invoke("getId")).arg(nextVal.invoke("getWorkspaceId")))); forBody.add(collection.invoke("add").arg(mutableItemFieldValue)); break; } case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) collectionDataType.getItemDataType(); JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get"). arg(name).ne(JExpr._null())))._then(); JDefinedClass clazz = findClass(compositeDataType, currentClass, classes, name); final JInvocation defArg = fieldDefs.invoke("get").arg(name); JVar fieldDef = nonNullBlock.decl(model.ref(FieldDef.class), getVarName(prefix, "def"), defArg); JVar compositeFieldDefs = nonNullBlock.decl(model.ref(Map.class).narrow(String.class).narrow( FieldDef.class), getVarName(prefix, "compositeFieldDefs"), JExpr.invoke(JExpr.cast(model.ref(CompositeDataType.class), JExpr.invoke(JExpr.cast(model.ref( CollectionDataType.class), fieldDef.invoke("getValueDef")), "getItemDataType")), "getComposedFieldDefs")); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg( fieldDef)); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(model.ref( Collection.class).narrow(model.ref(FieldValue.class))), getVarName(prefix, "fieldVals"), contentLoader.invoke("createCollectionFieldValue")); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); JVar collection = nonNullBlock.decl(model.ref(Collection.class).narrow(model.ref(FieldValue.class)), getVarName(prefix, "collectionVar"), JExpr._new(model.ref( ArrayList.class).narrow(FieldValue.class))); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(collection)); final JForLoop forLoop = nonNullBlock._for(); final JClass narrowedDomain = clazz; JVar iterator_item = forLoop.init(model.ref(Iterator.class).narrow(narrowedDomain), getVarName( prefix, "i"), fromBean.invoke(getterName).invoke("iterator")); forLoop.test(iterator_item.invoke("hasNext")); final JBlock forBody = forLoop.body(); JVar nextVal = forBody.decl(narrowedDomain, getVarName(prefix, "domain"), iterator_item.invoke( "next")); JVar mutableItemFieldValue = forBody.decl(model.ref(MutableCompositeFieldValue.class), getVarName(prefix, "fieldVal"), contentLoader.invoke("createCompositeFieldValue")); Collection<FieldDef> defs = getAllComposedFields(compositeDataType, types); generateReverseBlocks(defs, forBody, nextVal, mutableItemFieldValue, contentLoader, compositeFieldDefs, model, clazz, classes, types, new StringBuilder(prefix).append(name).append('_').toString()); forBody.add(collection.invoke("add").arg(mutableItemFieldValue)); } } break; default: } } } protected void setSimpleField(JBlock block, JVar fromBean, JVar wContent, final String getterName, JVar fieldDefs, final String name, JCodeModel model, JVar contentLoader, final Class valClass, final String methodName, String prefix) { JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(valClass), getVarName(prefix, "fieldVal"), contentLoader.invoke(methodName)); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(fromBean.invoke(getterName))); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); } protected void setSimpleMultiField(JBlock block, JVar fromBean, JVar wContent, final String getterName, JVar fieldDefs, final String name, JCodeModel model, JVar contentLoader, final Class valClass, final String methodName, String prefix) { JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(model.ref(Collection.class). narrow(model.ref(FieldValue.class))), getVarName(prefix, "fieldVals"), contentLoader.invoke( "createCollectionFieldValue")); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); JVar collection = nonNullBlock.decl(model.ref(Collection.class).narrow(model.ref(FieldValue.class)), getVarName( prefix, "collectionVar"), JExpr._new(model.ref(ArrayList.class).narrow(FieldValue.class))); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(collection)); final JForLoop forLoop = nonNullBlock._for(); JVar iterator_item = forLoop.init(model.ref(Iterator.class).narrow(model.ref(valClass).wildcard()), getVarName( prefix, "i"), fromBean.invoke(getterName).invoke("iterator")); forLoop.test(iterator_item.invoke("hasNext")); final JBlock forBody = forLoop.body(); JVar mutableItemFieldValue = forBody.decl(model.ref(MutableFieldValue.class).narrow(valClass), getVarName(prefix, "fieldVal"), contentLoader.invoke(methodName)); forBody.add(mutableItemFieldValue.invoke("setValue").arg(iterator_item.invoke("next"))); forBody.add(collection.invoke("add").arg(mutableItemFieldValue)); } protected void generateMasterModule(Map<ContentTypeId, JDefinedClass> modules, JCodeModel codeModel, String[] wId) throws JClassAlreadyExistsException { final String moduleClassName = new StringBuilder(packageForGuiceMasterModule).append(".MasterModule").toString(); final JDefinedClass moduleClass = codeModel._class(moduleClassName); moduleClass._extends(codeModel.ref(AbstractModule.class)); JMethod configureMethod = moduleClass.method(JMod.PUBLIC, JCodeModel.boxToPrimitive.get(Void.class), "configure"); JClass namesClass = codeModel.ref(Names.class); JBlock block = configureMethod.body(); - if (typeFiles != null && !typeFiles.isEmpty()) { - final JClass stringClassType = codeModel.ref(String.class); - final JClass systemClass = codeModel.ref(System.class); - JExpression stringClass = stringClassType.dotclass(); - JVar workspaceNamespace = block.decl(stringClassType, "workspaceNamespace", - systemClass.staticInvoke("getProperty").arg( - "com.smartitengineering.cms.repo.workspace.namespace").arg(wId[0])); - JVar workspaceName = block.decl(stringClassType, "workspaceName", systemClass.staticInvoke("getProperty").arg( - "com.smartitengineering.cms.repo.workspace.name").arg(wId[1])); - block.add(JExpr.invoke("bind").arg(stringClass).invoke("annotatedWith").arg(namesClass.staticInvoke("named"). - arg("cmsWorkspaceNamespace")).invoke("toInstance").arg(workspaceNamespace)); - block.add(JExpr.invoke("bind").arg(stringClass).invoke("annotatedWith").arg(namesClass.staticInvoke("named"). - arg("cmsWorkspaceName")).invoke("toInstance").arg(workspaceName)); + final JClass systemClass = codeModel.ref(System.class); + final JClass stringClassType = codeModel.ref(String.class); + JExpression stringClass = stringClassType.dotclass(); + JVar workspaceNamespace = block.decl(stringClassType, "workspaceNamespace", + systemClass.staticInvoke("getProperty").arg( + "com.smartitengineering.cms.repo.workspace.namespace").arg(wId[0])); + JVar workspaceName = block.decl(stringClassType, "workspaceName", systemClass.staticInvoke("getProperty").arg( + "com.smartitengineering.cms.repo.workspace.name").arg(wId[1])); + block.add(JExpr.invoke("bind").arg(stringClass).invoke("annotatedWith").arg(namesClass.staticInvoke("named"). + arg("cmsWorkspaceNamespace")).invoke("toInstance").arg(workspaceNamespace)); + block.add(JExpr.invoke("bind").arg(stringClass).invoke("annotatedWith").arg(namesClass.staticInvoke("named"). + arg("cmsWorkspaceName")).invoke("toInstance").arg(workspaceName)); + if (typeFiles != null && !typeFiles.isEmpty()) { { JClass typeLiteral = codeModel.ref(TypeLiteral.class); final JClass narrowedTypesLiteral = typeLiteral.narrow(codeModel.ref(List.class).narrow(String.class)); final JDefinedClass stringListType = moduleClass._class("InitializationContentTypes"); stringListType._extends(narrowedTypesLiteral); JVar typesList = block.decl(codeModel.ref(List.class).narrow(String.class), "contentTypes", JExpr._new(codeModel.ref(ArrayList.class).narrow(String.class))); for (String typeFile : typeFiles) { block.add(typesList.invoke("add").arg(typeFile)); } block.add(JExpr.invoke("bind").arg(JExpr._new(stringListType)).invoke( "annotatedWith").arg(namesClass.staticInvoke("named").arg("contentTypePath")).invoke("toInstance").arg( typesList)); JVar initVar = block.decl(codeModel.ref(Initializer.class), "initializer", JExpr._new(codeModel.ref(Initializer.class)).arg(workspaceNamespace).arg(workspaceName). arg(typesList)); block.add(initVar.invoke("init")); } } + JClass workspaceIdClass = codeModel.ref(WorkspaceId.class); + JClass apiClass = codeModel.ref(SmartContentAPI.class); + final JInvocation workspaceApiInvocation = apiClass.staticInvoke("getInstance").invoke("getWorkspaceApi"). + invoke("createWorkspaceId"); + final JInvocation _new = workspaceApiInvocation.arg(workspaceNamespace).arg(workspaceName); + block.add(JExpr.invoke("bind").arg(workspaceIdClass.dotclass()).invoke("toInstance").arg(_new)); for (JDefinedClass clazz : modules.values()) { block.invoke("install").arg(JExpr._new(clazz)); } if (transactionEnabled) { JClass booleanClass = codeModel.ref(Boolean.class); JClass bigBoolClass = codeModel.ref(Boolean.class); JClass txImplModuleClass = codeModel.ref(TransactionImplModule.class); block.add(JExpr.invoke("bind").arg(booleanClass.dotclass()).invoke("annotatedWith").arg(namesClass.staticInvoke( "named").arg("nonIsolatedLookupEnabled")).invoke("toInstance").arg(bigBoolClass.staticInvoke("parseBoolean"). arg(String.valueOf(nonIsolatedTransactionAllowed)))); block.invoke("install").arg(JExpr._new(txImplModuleClass)); } } private void generateAssociationIoCForFields(Collection<FieldDef> defs, JCodeModel model, JDefinedClass stringType, JClass typeLiteral, JDefinedClass moduleClass, JBlock block, Set<MutableContentType> types, Map<ContentTypeId, JDefinedClass> classes, String namePrefix, final Set<ContentTypeId> idsConfigdFor) throws JClassAlreadyExistsException { for (FieldDef def : defs) { final ContentDataType contentDataType; final String probablePrefix = new StringBuilder(namePrefix).append(def.getName().substring(0, 1).toUpperCase()). append(def.getName().substring(1)).toString(); switch (def.getValueDef().getType()) { case CONTENT: contentDataType = (ContentDataType) def.getValueDef(); break; case COLLECTION: CollectionDataType collectionDataType = (CollectionDataType) def.getValueDef(); if (collectionDataType.getItemDataType().getType().equals(FieldValueType.CONTENT)) { contentDataType = (ContentDataType) collectionDataType.getItemDataType(); } else if (collectionDataType.getItemDataType().getType().equals(FieldValueType.COMPOSITE)) { CompositeDataType compositeDataType = (CompositeDataType) collectionDataType.getItemDataType(); generateAssociationIoCForFields(getAllComposedFields(compositeDataType, types), model, stringType, typeLiteral, moduleClass, block, types, classes, probablePrefix, idsConfigdFor); contentDataType = null; } else { contentDataType = null; } break; case COMPOSITE: CompositeDataType compositeDataType = (CompositeDataType) def.getValueDef(); generateAssociationIoCForFields(getAllComposedFields(compositeDataType, types), model, stringType, typeLiteral, moduleClass, block, types, classes, probablePrefix, idsConfigdFor); default: contentDataType = null; break; } if (contentDataType != null && !idsConfigdFor.contains(contentDataType.getTypeDef())) { idsConfigdFor.add(contentDataType.getTypeDef()); JBlock mapBindingBlock = block.block(); JDefinedClass definedClass = classes.get(contentDataType.getTypeDef()); final JClass assocType = model.ref(CommonReadDao.class).narrow(definedClass.wildcard()).narrow(String.class); final JClass narrowedReadTypeLiteral = typeLiteral.narrow(assocType); final JDefinedClass assocDaoTypeLit = moduleClass._class(new StringBuilder(probablePrefix).append("DaoType"). toString()); assocDaoTypeLit._extends(narrowedReadTypeLiteral); JVar mapBinderVar = mapBindingBlock.decl(model.ref(MapBinder.class).narrow(String.class).narrow(assocType), "mapBinder", model.ref(MapBinder.class).staticInvoke("newMapBinder"). arg(JExpr._this().invoke("binder")).arg(JExpr._new(stringType)).arg(JExpr._new(assocDaoTypeLit))); Collection<ContentType> concreteInstances = findConcreteInstanceOf(contentDataType.getTypeDef(), types); for (ContentType concreteInstance : concreteInstances) { JDefinedClass concClass = classes.get(concreteInstance.getContentTypeID()); if (concClass == null) { continue; } final JClass concType = model.ref(CommonReadDao.class).narrow(concClass).narrow(String.class); final JClass narrowedConcReadTypeLiteral = typeLiteral.narrow(concType); final String name = concreteInstance.getContentTypeID().getName(); final JDefinedClass concDaoTypeLit = moduleClass._class(new StringBuilder(probablePrefix).append(name. substring(0, 1).toUpperCase()).append(name.substring(1)).append("DaoType"). toString()); concDaoTypeLit._extends(narrowedConcReadTypeLiteral); mapBindingBlock.add(mapBinderVar.invoke("addBinding").arg(JExpr.lit(concreteInstance.getContentTypeID(). toString())).invoke("to").arg(JExpr._new(concDaoTypeLit))); } } } } private Collection<ContentType> findConcreteInstanceOf(final ContentTypeId typeDef, final Collection<? extends ContentType> types) { if (types == null || typeDef == null || types.isEmpty()) { return Collections.emptyList(); } final List<ContentType> instanceOfTypes = new ArrayList<ContentType>(); final Map<ContentTypeId, ContentType> typeMap = new HashMap<ContentTypeId, ContentType>(); for (ContentType type : types) { typeMap.put(type.getContentTypeID(), type); } for (ContentType type : types) { if (type.getDefinitionType().equals(DefinitionType.CONCRETE_TYPE)) { boolean isInstanceOf = isInstanceOf(type, typeDef, typeMap); if (isInstanceOf) { instanceOfTypes.add(type); } } } return instanceOfTypes; } private boolean isInstanceOf(ContentType type, final ContentTypeId typeDef, Map<ContentTypeId, ContentType> types) { boolean isInstanceOf = false; if (type.getContentTypeID().equals(typeDef)) { isInstanceOf = true; } if (!isInstanceOf) { ContentTypeId parentId = type.getParent(); if (!isInstanceOf && parentId != null && types.get(parentId) != null) { isInstanceOf = isInstanceOf(types.get(parentId), typeDef, types); } } return isInstanceOf; } }
SmartITEngineering/smart-cms
04c603ee1555cf790dbf928d8c7b01aef29f9d76
Error message correction
diff --git a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java index 6c35019..badc5e4 100644 --- a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java +++ b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java @@ -1,435 +1,435 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.api.impl.content; import com.smartitengineering.cms.api.content.FieldValue; import com.smartitengineering.cms.api.type.ContentType.ContentProcessingPhase; import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.cms.api.content.Content; import com.smartitengineering.cms.api.content.ContentId; import com.smartitengineering.cms.api.content.Field; import com.smartitengineering.cms.api.content.Representation; import com.smartitengineering.cms.api.content.template.ContentCoProcessor; import com.smartitengineering.cms.api.event.Event; import com.smartitengineering.cms.api.event.Event.EventType; import com.smartitengineering.cms.api.event.Event.Type; import com.smartitengineering.cms.api.factory.SmartContentAPI; import com.smartitengineering.cms.api.factory.content.WriteableContent; import com.smartitengineering.cms.api.impl.AbstractPersistableDomain; import com.smartitengineering.cms.api.type.ContentCoProcessorDef; import com.smartitengineering.cms.api.type.ContentStatus; import com.smartitengineering.cms.api.type.ContentType; import com.smartitengineering.cms.api.type.FieldDef; import com.smartitengineering.cms.api.workspace.Workspace; import com.smartitengineering.cms.spi.SmartContentSPI; import com.smartitengineering.cms.spi.content.PersistableContent; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.ObjectUtils; /** * * @author kaisar */ public class ContentImpl extends AbstractPersistableDomain<WriteableContent, ContentId> implements PersistableContent { private ContentId contentId; private ContentId parentId; private ContentType contentDef; private ContentStatus contentStatus; private Date creationDate; private Date lastModifiedDate; private Map<String, Field> map; private Map<String, Field> cachedFieldMap; private String entityTagValue; private boolean privateContent; private boolean supressChecking; public ContentImpl() { super(LOCK_KEY_PREFIX); } public boolean isSupressChecking() { return supressChecking; } public void setSupressChecking(boolean supressChecking) { this.supressChecking = supressChecking; } @Override public void put() throws IOException { final boolean attainedLockLocally; if (isPersisted() && !isLockOwned()) { lock(); attainedLockLocally = true; } else { attainedLockLocally = false; } try { triggerContentCoProcessors(ContentType.ContentProcessingPhase.WRITE); if (!isValid()) { getLogger().info("Content not in valid state!"); //First get contents indexed before attempting to use this validity! //Uncomment the following line once indexing is ensured in testing throw new IOException("Content is not in valid state!"); } super.put(); } finally { if (attainedLockLocally) { unlock(); } } } protected void triggerContentCoProcessors(final ContentProcessingPhase phase) { //Trigger content co processors if (contentDef != null && contentId != null) { Collection<ContentCoProcessorDef> defs = contentDef.getContentCoProcessorDefs().get( phase); if (defs != null && !defs.isEmpty()) { List<ContentCoProcessorDef> list = new ArrayList<ContentCoProcessorDef>(defs); Collections.sort(list, new Comparator<ContentCoProcessorDef>() { public int compare(ContentCoProcessorDef o1, ContentCoProcessorDef o2) { return o1.getPriority() - o2.getPriority(); } }); for (ContentCoProcessorDef def : list) { ContentCoProcessor processor = SmartContentAPI.getInstance().getWorkspaceApi().getContentCoProcessor(contentId. getWorkspaceId(), def.getResourceUri().getValue()); if (processor != null) { processor.processContent(this, def.getParameters()); } } } } } @Override public void setParentId(ContentId contentId) { if (contentDef == null) { throw new IllegalArgumentException("Content Type Definition must be set before setting parent content ID"); } if (contentId != null && SmartContentAPI.getInstance().getContentLoader().loadContent(contentId) == null) { throw new IllegalArgumentException("Parent must exist for it to be set!"); } this.parentId = contentId; } @Override public void setContentDefinition(ContentType contentType) { this.contentDef = contentType; } @Override public void setField(Field field) { getMap().put(field.getName(), field); cachedFieldMap = null; } @Override public void setStatus(ContentStatus contentStatus) { this.contentStatus = contentStatus; } @Override public ContentId getContentId() { return this.contentId; } @Override public ContentId getParentId() { return this.parentId; } @Override public Content getParent() { if (parentId != null) { return SmartContentAPI.getInstance().getContentLoader().loadContent(parentId); } else { return null; } } @Override public ContentType getContentDefinition() { return this.contentDef; } @Override public Map<String, Field> getFields() { final Content parent = getParent(); final ContentType def = getContentDefinition(); if (cachedFieldMap == null) { Map<String, Field> fields = new LinkedHashMap<String, Field>(); if (parent != null && def != null) { Map<String, Field> parentFields = parent.getFields(); for (String fieldName : parentFields.keySet()) { FieldDef myDef = def.getOwnFieldDefs().get(fieldName); FieldDef thatDef = parent.getContentDefinition().getOwnFieldDefs().get(fieldName); if (myDef != null && thatDef != null && ObjectUtils.equals(myDef, thatDef) && myDef.getValueDef().getType(). equals(thatDef.getValueDef().getType())) { fields.put(fieldName, parent.getField(fieldName)); } } } fields.putAll(getMap()); cachedFieldMap = fields; } return Collections.unmodifiableMap(cachedFieldMap); } public Map<String, Field> getMap() { if (map == null) { map = new LinkedHashMap<String, Field>(SmartContentSPI.getInstance().getContentReader().getFieldsForContent( contentId)); triggerContentCoProcessors(ContentType.ContentProcessingPhase.READ); } return map; } @Override public Map<String, Field> getOwnFields() { return Collections.unmodifiableMap(getMap()); } @Override public Field getField(String fieldName) { return getFields().get(fieldName); } @Override public ContentStatus getStatus() { return this.contentStatus; } @Override public Representation getRepresentation(String repName) { return SmartContentSPI.getInstance().getRepresentationProvider().getRepresentation(repName, getContentDefinition(), this); } @Override public Date getCreationDate() { return this.creationDate; } @Override public Date getLastModifiedDate() { return this.lastModifiedDate; } @Override public boolean isPersisted() { return creationDate != null; } @Override public ContentId getKeySpecimen() { return contentId; } @Override public void removeField(String fieldName) { getMap().remove(fieldName); } @Override public void setContentId(ContentId contentId) { this.contentId = contentId; } @Override public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } @Override public void setLastModifiedDate(Date lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } @Override protected void create() throws IOException { if (contentId != null) { if (contentId.getWorkspaceId() == null || contentId.getId() == null) { - throw new IOException("Workspace Id and Id is null though Content Id is not null"); + throw new IOException("Workspace ID or ID of content within wokrspace can not be null"); } Workspace workspace = SmartContentAPI.getInstance().getWorkspaceApi().getWorkspace(contentId.getWorkspaceId()); if (workspace == null) { throw new IOException("Non existance workspace Id " + contentId.getWorkspaceId()); } } if (contentId == null && contentDef != null && contentDef.getContentTypeID() != null) { createContentId(contentDef.getContentTypeID().getWorkspace()); } else if (contentId == null && (contentDef == null || contentDef.getContentTypeID() == null)) { throw new IOException("Content ID and Content Type Definition is not set!"); } super.create(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.CREATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public void delete() throws IOException { super.delete(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.DELETE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override protected void update() throws IOException { super.update(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.UPDATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!Content.class.isAssignableFrom(obj.getClass())) { return false; } final Content other = (Content) obj; if (this.contentId != other.getContentId() && (this.contentId == null || !this.contentId.equals(other.getContentId()))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.contentId != null ? this.contentId.hashCode() : 0); return hash; } @Override public void createContentId(WorkspaceId workspace) { if (workspace == null) { throw new IllegalArgumentException("Workspace ID can not be null!"); } setContentId(SmartContentAPI.getInstance().getContentLoader().generateContentId(workspace)); } @Override public void setEntityTagValue(String eTagValue) { this.entityTagValue = eTagValue; } @Override public String getEntityTagValue() { return this.entityTagValue; } @Override public boolean isValid() { boolean validContent = supressChecking || SmartContentAPI.getInstance().getContentLoader().isValidContent(this); if (getLogger().isDebugEnabled()) { getLogger().debug("!!! Checking Content " + validContent); } return validContent; } @Override public URI getUri() { return SmartContentSPI.getInstance().getUriProvider().getContentUri(contentId); } @Override public String getEncodedUriString() { if (getUri() == null) { return null; } else { return getUri().toASCIIString(); } } @Override public void setPrivate(boolean privateContent) { this.privateContent = privateContent; } @Override public boolean isPrivate() { return this.privateContent; } @Override public ContentImpl clone() { ContentImpl contentImpl = new ContentImpl(); contentImpl.contentDef = contentDef; contentImpl.contentId = contentId; contentImpl.parentId = parentId; contentImpl.privateContent = privateContent; contentImpl.contentStatus = contentStatus; contentImpl.nextPerformToWaitForLock = nextPerformToWaitForLock; contentImpl.supressChecking = supressChecking; contentImpl.entityTagValue = entityTagValue; if (creationDate != null) { contentImpl.creationDate = new Date(creationDate.getTime()); } if (lastModifiedDate != null) { contentImpl.lastModifiedDate = new Date(lastModifiedDate.getTime()); } contentImpl.map = map; if (map != null) { contentImpl.map = new LinkedHashMap<String, Field>(); cloneFields(map, contentImpl.map); } if (cachedFieldMap != null) { contentImpl.cachedFieldMap = new LinkedHashMap<String, Field>(); cloneFields(cachedFieldMap, contentImpl.cachedFieldMap); } return contentImpl; } protected void cloneFields(Map<String, Field> fieldMap, Map<String, Field> destMap) { for (Map.Entry<String, Field> oneField : fieldMap.entrySet()) { FieldImpl fieldImpl = new FieldImpl(); final Field value = oneField.getValue(); fieldImpl.setContent(value.getContent()); fieldImpl.setFieldDef(value.getFieldDef()); fieldImpl.setName(value.getName()); final FieldValue fieldVal = value.getValue(); fieldImpl.setValue(fieldVal); destMap.put(oneField.getKey(), fieldImpl); } } }
SmartITEngineering/smart-cms
4ff95301675bc12bbc59adaab29ca6c23dc23a30
Content creation should throw exception if workspace id and id of content is null in ContentId object
diff --git a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java index bee1535..6c35019 100644 --- a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java +++ b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java @@ -1,435 +1,435 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.api.impl.content; import com.smartitengineering.cms.api.content.FieldValue; import com.smartitengineering.cms.api.type.ContentType.ContentProcessingPhase; import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.cms.api.content.Content; import com.smartitengineering.cms.api.content.ContentId; import com.smartitengineering.cms.api.content.Field; import com.smartitengineering.cms.api.content.Representation; import com.smartitengineering.cms.api.content.template.ContentCoProcessor; import com.smartitengineering.cms.api.event.Event; import com.smartitengineering.cms.api.event.Event.EventType; import com.smartitengineering.cms.api.event.Event.Type; import com.smartitengineering.cms.api.factory.SmartContentAPI; import com.smartitengineering.cms.api.factory.content.WriteableContent; import com.smartitengineering.cms.api.impl.AbstractPersistableDomain; import com.smartitengineering.cms.api.type.ContentCoProcessorDef; import com.smartitengineering.cms.api.type.ContentStatus; import com.smartitengineering.cms.api.type.ContentType; import com.smartitengineering.cms.api.type.FieldDef; import com.smartitengineering.cms.api.workspace.Workspace; import com.smartitengineering.cms.spi.SmartContentSPI; import com.smartitengineering.cms.spi.content.PersistableContent; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.ObjectUtils; /** * * @author kaisar */ public class ContentImpl extends AbstractPersistableDomain<WriteableContent, ContentId> implements PersistableContent { private ContentId contentId; private ContentId parentId; private ContentType contentDef; private ContentStatus contentStatus; private Date creationDate; private Date lastModifiedDate; private Map<String, Field> map; private Map<String, Field> cachedFieldMap; private String entityTagValue; private boolean privateContent; private boolean supressChecking; public ContentImpl() { super(LOCK_KEY_PREFIX); } public boolean isSupressChecking() { return supressChecking; } public void setSupressChecking(boolean supressChecking) { this.supressChecking = supressChecking; } @Override public void put() throws IOException { final boolean attainedLockLocally; if (isPersisted() && !isLockOwned()) { lock(); attainedLockLocally = true; } else { attainedLockLocally = false; } try { triggerContentCoProcessors(ContentType.ContentProcessingPhase.WRITE); if (!isValid()) { getLogger().info("Content not in valid state!"); //First get contents indexed before attempting to use this validity! //Uncomment the following line once indexing is ensured in testing throw new IOException("Content is not in valid state!"); } super.put(); } finally { if (attainedLockLocally) { unlock(); } } } protected void triggerContentCoProcessors(final ContentProcessingPhase phase) { //Trigger content co processors if (contentDef != null && contentId != null) { Collection<ContentCoProcessorDef> defs = contentDef.getContentCoProcessorDefs().get( phase); if (defs != null && !defs.isEmpty()) { List<ContentCoProcessorDef> list = new ArrayList<ContentCoProcessorDef>(defs); Collections.sort(list, new Comparator<ContentCoProcessorDef>() { public int compare(ContentCoProcessorDef o1, ContentCoProcessorDef o2) { return o1.getPriority() - o2.getPriority(); } }); for (ContentCoProcessorDef def : list) { ContentCoProcessor processor = SmartContentAPI.getInstance().getWorkspaceApi().getContentCoProcessor(contentId. getWorkspaceId(), def.getResourceUri().getValue()); if (processor != null) { processor.processContent(this, def.getParameters()); } } } } } @Override public void setParentId(ContentId contentId) { if (contentDef == null) { throw new IllegalArgumentException("Content Type Definition must be set before setting parent content ID"); } if (contentId != null && SmartContentAPI.getInstance().getContentLoader().loadContent(contentId) == null) { throw new IllegalArgumentException("Parent must exist for it to be set!"); } this.parentId = contentId; } @Override public void setContentDefinition(ContentType contentType) { this.contentDef = contentType; } @Override public void setField(Field field) { getMap().put(field.getName(), field); cachedFieldMap = null; } @Override public void setStatus(ContentStatus contentStatus) { this.contentStatus = contentStatus; } @Override public ContentId getContentId() { return this.contentId; } @Override public ContentId getParentId() { return this.parentId; } @Override public Content getParent() { if (parentId != null) { return SmartContentAPI.getInstance().getContentLoader().loadContent(parentId); } else { return null; } } @Override public ContentType getContentDefinition() { return this.contentDef; } @Override public Map<String, Field> getFields() { final Content parent = getParent(); final ContentType def = getContentDefinition(); if (cachedFieldMap == null) { Map<String, Field> fields = new LinkedHashMap<String, Field>(); if (parent != null && def != null) { Map<String, Field> parentFields = parent.getFields(); for (String fieldName : parentFields.keySet()) { FieldDef myDef = def.getOwnFieldDefs().get(fieldName); FieldDef thatDef = parent.getContentDefinition().getOwnFieldDefs().get(fieldName); if (myDef != null && thatDef != null && ObjectUtils.equals(myDef, thatDef) && myDef.getValueDef().getType(). equals(thatDef.getValueDef().getType())) { fields.put(fieldName, parent.getField(fieldName)); } } } fields.putAll(getMap()); cachedFieldMap = fields; } return Collections.unmodifiableMap(cachedFieldMap); } public Map<String, Field> getMap() { if (map == null) { map = new LinkedHashMap<String, Field>(SmartContentSPI.getInstance().getContentReader().getFieldsForContent( contentId)); triggerContentCoProcessors(ContentType.ContentProcessingPhase.READ); } return map; } @Override public Map<String, Field> getOwnFields() { return Collections.unmodifiableMap(getMap()); } @Override public Field getField(String fieldName) { return getFields().get(fieldName); } @Override public ContentStatus getStatus() { return this.contentStatus; } @Override public Representation getRepresentation(String repName) { return SmartContentSPI.getInstance().getRepresentationProvider().getRepresentation(repName, getContentDefinition(), this); } @Override public Date getCreationDate() { return this.creationDate; } @Override public Date getLastModifiedDate() { return this.lastModifiedDate; } @Override public boolean isPersisted() { return creationDate != null; } @Override public ContentId getKeySpecimen() { return contentId; } @Override public void removeField(String fieldName) { getMap().remove(fieldName); } @Override public void setContentId(ContentId contentId) { this.contentId = contentId; } @Override public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } @Override public void setLastModifiedDate(Date lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } @Override protected void create() throws IOException { if (contentId != null) { - if (contentId.getWorkspaceId() == null && contentId.getId() == null) { + if (contentId.getWorkspaceId() == null || contentId.getId() == null) { throw new IOException("Workspace Id and Id is null though Content Id is not null"); } Workspace workspace = SmartContentAPI.getInstance().getWorkspaceApi().getWorkspace(contentId.getWorkspaceId()); if (workspace == null) { throw new IOException("Non existance workspace Id " + contentId.getWorkspaceId()); } } if (contentId == null && contentDef != null && contentDef.getContentTypeID() != null) { createContentId(contentDef.getContentTypeID().getWorkspace()); } else if (contentId == null && (contentDef == null || contentDef.getContentTypeID() == null)) { throw new IOException("Content ID and Content Type Definition is not set!"); } super.create(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.CREATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public void delete() throws IOException { super.delete(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.DELETE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override protected void update() throws IOException { super.update(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.UPDATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!Content.class.isAssignableFrom(obj.getClass())) { return false; } final Content other = (Content) obj; if (this.contentId != other.getContentId() && (this.contentId == null || !this.contentId.equals(other.getContentId()))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.contentId != null ? this.contentId.hashCode() : 0); return hash; } @Override public void createContentId(WorkspaceId workspace) { if (workspace == null) { throw new IllegalArgumentException("Workspace ID can not be null!"); } setContentId(SmartContentAPI.getInstance().getContentLoader().generateContentId(workspace)); } @Override public void setEntityTagValue(String eTagValue) { this.entityTagValue = eTagValue; } @Override public String getEntityTagValue() { return this.entityTagValue; } @Override public boolean isValid() { boolean validContent = supressChecking || SmartContentAPI.getInstance().getContentLoader().isValidContent(this); if (getLogger().isDebugEnabled()) { getLogger().debug("!!! Checking Content " + validContent); } return validContent; } @Override public URI getUri() { return SmartContentSPI.getInstance().getUriProvider().getContentUri(contentId); } @Override public String getEncodedUriString() { if (getUri() == null) { return null; } else { return getUri().toASCIIString(); } } @Override public void setPrivate(boolean privateContent) { this.privateContent = privateContent; } @Override public boolean isPrivate() { return this.privateContent; } @Override public ContentImpl clone() { ContentImpl contentImpl = new ContentImpl(); contentImpl.contentDef = contentDef; contentImpl.contentId = contentId; contentImpl.parentId = parentId; contentImpl.privateContent = privateContent; contentImpl.contentStatus = contentStatus; contentImpl.nextPerformToWaitForLock = nextPerformToWaitForLock; contentImpl.supressChecking = supressChecking; contentImpl.entityTagValue = entityTagValue; if (creationDate != null) { contentImpl.creationDate = new Date(creationDate.getTime()); } if (lastModifiedDate != null) { contentImpl.lastModifiedDate = new Date(lastModifiedDate.getTime()); } contentImpl.map = map; if (map != null) { contentImpl.map = new LinkedHashMap<String, Field>(); cloneFields(map, contentImpl.map); } if (cachedFieldMap != null) { contentImpl.cachedFieldMap = new LinkedHashMap<String, Field>(); cloneFields(cachedFieldMap, contentImpl.cachedFieldMap); } return contentImpl; } protected void cloneFields(Map<String, Field> fieldMap, Map<String, Field> destMap) { for (Map.Entry<String, Field> oneField : fieldMap.entrySet()) { FieldImpl fieldImpl = new FieldImpl(); final Field value = oneField.getValue(); fieldImpl.setContent(value.getContent()); fieldImpl.setFieldDef(value.getFieldDef()); fieldImpl.setName(value.getName()); final FieldValue fieldVal = value.getValue(); fieldImpl.setValue(fieldVal); destMap.put(oneField.getKey(), fieldImpl); } } }
SmartITEngineering/smart-cms
226a524cb167d62e2e2a50ee8f9bc23df630a09e
Fix a bug
diff --git a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java index 9adde16..bee1535 100644 --- a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java +++ b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java @@ -1,438 +1,435 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.api.impl.content; import com.smartitengineering.cms.api.content.FieldValue; import com.smartitengineering.cms.api.type.ContentType.ContentProcessingPhase; import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.cms.api.content.Content; import com.smartitengineering.cms.api.content.ContentId; import com.smartitengineering.cms.api.content.Field; import com.smartitengineering.cms.api.content.Representation; import com.smartitengineering.cms.api.content.template.ContentCoProcessor; import com.smartitengineering.cms.api.event.Event; import com.smartitengineering.cms.api.event.Event.EventType; import com.smartitengineering.cms.api.event.Event.Type; import com.smartitengineering.cms.api.factory.SmartContentAPI; import com.smartitengineering.cms.api.factory.content.WriteableContent; import com.smartitengineering.cms.api.impl.AbstractPersistableDomain; import com.smartitengineering.cms.api.type.ContentCoProcessorDef; import com.smartitengineering.cms.api.type.ContentStatus; import com.smartitengineering.cms.api.type.ContentType; import com.smartitengineering.cms.api.type.FieldDef; import com.smartitengineering.cms.api.workspace.Workspace; import com.smartitengineering.cms.spi.SmartContentSPI; import com.smartitengineering.cms.spi.content.PersistableContent; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.ObjectUtils; /** * * @author kaisar */ public class ContentImpl extends AbstractPersistableDomain<WriteableContent, ContentId> implements PersistableContent { private ContentId contentId; private ContentId parentId; private ContentType contentDef; private ContentStatus contentStatus; private Date creationDate; private Date lastModifiedDate; private Map<String, Field> map; private Map<String, Field> cachedFieldMap; private String entityTagValue; private boolean privateContent; private boolean supressChecking; public ContentImpl() { super(LOCK_KEY_PREFIX); } public boolean isSupressChecking() { return supressChecking; } public void setSupressChecking(boolean supressChecking) { this.supressChecking = supressChecking; } @Override public void put() throws IOException { final boolean attainedLockLocally; if (isPersisted() && !isLockOwned()) { lock(); attainedLockLocally = true; } else { attainedLockLocally = false; } try { triggerContentCoProcessors(ContentType.ContentProcessingPhase.WRITE); if (!isValid()) { getLogger().info("Content not in valid state!"); //First get contents indexed before attempting to use this validity! //Uncomment the following line once indexing is ensured in testing throw new IOException("Content is not in valid state!"); } super.put(); } finally { if (attainedLockLocally) { unlock(); } } } protected void triggerContentCoProcessors(final ContentProcessingPhase phase) { //Trigger content co processors if (contentDef != null && contentId != null) { Collection<ContentCoProcessorDef> defs = contentDef.getContentCoProcessorDefs().get( phase); if (defs != null && !defs.isEmpty()) { List<ContentCoProcessorDef> list = new ArrayList<ContentCoProcessorDef>(defs); Collections.sort(list, new Comparator<ContentCoProcessorDef>() { public int compare(ContentCoProcessorDef o1, ContentCoProcessorDef o2) { return o1.getPriority() - o2.getPriority(); } }); for (ContentCoProcessorDef def : list) { ContentCoProcessor processor = SmartContentAPI.getInstance().getWorkspaceApi().getContentCoProcessor(contentId. getWorkspaceId(), def.getResourceUri().getValue()); if (processor != null) { processor.processContent(this, def.getParameters()); } } } } } @Override public void setParentId(ContentId contentId) { if (contentDef == null) { throw new IllegalArgumentException("Content Type Definition must be set before setting parent content ID"); } if (contentId != null && SmartContentAPI.getInstance().getContentLoader().loadContent(contentId) == null) { throw new IllegalArgumentException("Parent must exist for it to be set!"); } this.parentId = contentId; } @Override public void setContentDefinition(ContentType contentType) { this.contentDef = contentType; } @Override public void setField(Field field) { getMap().put(field.getName(), field); cachedFieldMap = null; } @Override public void setStatus(ContentStatus contentStatus) { this.contentStatus = contentStatus; } @Override public ContentId getContentId() { return this.contentId; } @Override public ContentId getParentId() { return this.parentId; } @Override public Content getParent() { if (parentId != null) { return SmartContentAPI.getInstance().getContentLoader().loadContent(parentId); } else { return null; } } @Override public ContentType getContentDefinition() { return this.contentDef; } @Override public Map<String, Field> getFields() { final Content parent = getParent(); final ContentType def = getContentDefinition(); if (cachedFieldMap == null) { Map<String, Field> fields = new LinkedHashMap<String, Field>(); if (parent != null && def != null) { Map<String, Field> parentFields = parent.getFields(); for (String fieldName : parentFields.keySet()) { FieldDef myDef = def.getOwnFieldDefs().get(fieldName); FieldDef thatDef = parent.getContentDefinition().getOwnFieldDefs().get(fieldName); if (myDef != null && thatDef != null && ObjectUtils.equals(myDef, thatDef) && myDef.getValueDef().getType(). equals(thatDef.getValueDef().getType())) { fields.put(fieldName, parent.getField(fieldName)); } } } fields.putAll(getMap()); cachedFieldMap = fields; } return Collections.unmodifiableMap(cachedFieldMap); } public Map<String, Field> getMap() { if (map == null) { map = new LinkedHashMap<String, Field>(SmartContentSPI.getInstance().getContentReader().getFieldsForContent( contentId)); triggerContentCoProcessors(ContentType.ContentProcessingPhase.READ); } return map; } @Override public Map<String, Field> getOwnFields() { return Collections.unmodifiableMap(getMap()); } @Override public Field getField(String fieldName) { return getFields().get(fieldName); } @Override public ContentStatus getStatus() { return this.contentStatus; } @Override public Representation getRepresentation(String repName) { return SmartContentSPI.getInstance().getRepresentationProvider().getRepresentation(repName, getContentDefinition(), this); } @Override public Date getCreationDate() { return this.creationDate; } @Override public Date getLastModifiedDate() { return this.lastModifiedDate; } @Override public boolean isPersisted() { return creationDate != null; } @Override public ContentId getKeySpecimen() { return contentId; } @Override public void removeField(String fieldName) { getMap().remove(fieldName); } @Override public void setContentId(ContentId contentId) { this.contentId = contentId; } @Override public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } @Override public void setLastModifiedDate(Date lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } @Override protected void create() throws IOException { if (contentId != null) { if (contentId.getWorkspaceId() == null && contentId.getId() == null) { throw new IOException("Workspace Id and Id is null though Content Id is not null"); } Workspace workspace = SmartContentAPI.getInstance().getWorkspaceApi().getWorkspace(contentId.getWorkspaceId()); if (workspace == null) { throw new IOException("Non existance workspace Id " + contentId.getWorkspaceId()); } - else { - throw new IOException("Invalid workspace null"); - } } if (contentId == null && contentDef != null && contentDef.getContentTypeID() != null) { createContentId(contentDef.getContentTypeID().getWorkspace()); } else if (contentId == null && (contentDef == null || contentDef.getContentTypeID() == null)) { throw new IOException("Content ID and Content Type Definition is not set!"); } super.create(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.CREATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public void delete() throws IOException { super.delete(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.DELETE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override protected void update() throws IOException { super.update(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.UPDATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!Content.class.isAssignableFrom(obj.getClass())) { return false; } final Content other = (Content) obj; if (this.contentId != other.getContentId() && (this.contentId == null || !this.contentId.equals(other.getContentId()))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.contentId != null ? this.contentId.hashCode() : 0); return hash; } @Override public void createContentId(WorkspaceId workspace) { if (workspace == null) { throw new IllegalArgumentException("Workspace ID can not be null!"); } setContentId(SmartContentAPI.getInstance().getContentLoader().generateContentId(workspace)); } @Override public void setEntityTagValue(String eTagValue) { this.entityTagValue = eTagValue; } @Override public String getEntityTagValue() { return this.entityTagValue; } @Override public boolean isValid() { boolean validContent = supressChecking || SmartContentAPI.getInstance().getContentLoader().isValidContent(this); if (getLogger().isDebugEnabled()) { getLogger().debug("!!! Checking Content " + validContent); } return validContent; } @Override public URI getUri() { return SmartContentSPI.getInstance().getUriProvider().getContentUri(contentId); } @Override public String getEncodedUriString() { if (getUri() == null) { return null; } else { return getUri().toASCIIString(); } } @Override public void setPrivate(boolean privateContent) { this.privateContent = privateContent; } @Override public boolean isPrivate() { return this.privateContent; } @Override public ContentImpl clone() { ContentImpl contentImpl = new ContentImpl(); contentImpl.contentDef = contentDef; contentImpl.contentId = contentId; contentImpl.parentId = parentId; contentImpl.privateContent = privateContent; contentImpl.contentStatus = contentStatus; contentImpl.nextPerformToWaitForLock = nextPerformToWaitForLock; contentImpl.supressChecking = supressChecking; contentImpl.entityTagValue = entityTagValue; if (creationDate != null) { contentImpl.creationDate = new Date(creationDate.getTime()); } if (lastModifiedDate != null) { contentImpl.lastModifiedDate = new Date(lastModifiedDate.getTime()); } contentImpl.map = map; if (map != null) { contentImpl.map = new LinkedHashMap<String, Field>(); cloneFields(map, contentImpl.map); } if (cachedFieldMap != null) { contentImpl.cachedFieldMap = new LinkedHashMap<String, Field>(); cloneFields(cachedFieldMap, contentImpl.cachedFieldMap); } return contentImpl; } protected void cloneFields(Map<String, Field> fieldMap, Map<String, Field> destMap) { for (Map.Entry<String, Field> oneField : fieldMap.entrySet()) { FieldImpl fieldImpl = new FieldImpl(); final Field value = oneField.getValue(); fieldImpl.setContent(value.getContent()); fieldImpl.setFieldDef(value.getFieldDef()); fieldImpl.setName(value.getName()); final FieldValue fieldVal = value.getValue(); fieldImpl.setValue(fieldVal); destMap.put(oneField.getKey(), fieldImpl); } } }
SmartITEngineering/smart-cms
9704f6f5aa9b0dafcad66aab164272ac9c5d2374
Refactor code
diff --git a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java index 6ae812c..9adde16 100644 --- a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java +++ b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java @@ -1,441 +1,438 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.api.impl.content; import com.smartitengineering.cms.api.content.FieldValue; import com.smartitengineering.cms.api.type.ContentType.ContentProcessingPhase; import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.cms.api.content.Content; import com.smartitengineering.cms.api.content.ContentId; import com.smartitengineering.cms.api.content.Field; import com.smartitengineering.cms.api.content.Representation; import com.smartitengineering.cms.api.content.template.ContentCoProcessor; import com.smartitengineering.cms.api.event.Event; import com.smartitengineering.cms.api.event.Event.EventType; import com.smartitengineering.cms.api.event.Event.Type; import com.smartitengineering.cms.api.factory.SmartContentAPI; import com.smartitengineering.cms.api.factory.content.WriteableContent; import com.smartitengineering.cms.api.impl.AbstractPersistableDomain; import com.smartitengineering.cms.api.type.ContentCoProcessorDef; import com.smartitengineering.cms.api.type.ContentStatus; import com.smartitengineering.cms.api.type.ContentType; import com.smartitengineering.cms.api.type.FieldDef; import com.smartitengineering.cms.api.workspace.Workspace; import com.smartitengineering.cms.spi.SmartContentSPI; import com.smartitengineering.cms.spi.content.PersistableContent; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.ObjectUtils; /** * * @author kaisar */ public class ContentImpl extends AbstractPersistableDomain<WriteableContent, ContentId> implements PersistableContent { private ContentId contentId; private ContentId parentId; private ContentType contentDef; private ContentStatus contentStatus; private Date creationDate; private Date lastModifiedDate; private Map<String, Field> map; private Map<String, Field> cachedFieldMap; private String entityTagValue; private boolean privateContent; private boolean supressChecking; public ContentImpl() { super(LOCK_KEY_PREFIX); } public boolean isSupressChecking() { return supressChecking; } public void setSupressChecking(boolean supressChecking) { this.supressChecking = supressChecking; } @Override public void put() throws IOException { final boolean attainedLockLocally; if (isPersisted() && !isLockOwned()) { lock(); attainedLockLocally = true; } else { attainedLockLocally = false; } try { triggerContentCoProcessors(ContentType.ContentProcessingPhase.WRITE); if (!isValid()) { getLogger().info("Content not in valid state!"); //First get contents indexed before attempting to use this validity! //Uncomment the following line once indexing is ensured in testing throw new IOException("Content is not in valid state!"); } super.put(); } finally { if (attainedLockLocally) { unlock(); } } } protected void triggerContentCoProcessors(final ContentProcessingPhase phase) { //Trigger content co processors if (contentDef != null && contentId != null) { Collection<ContentCoProcessorDef> defs = contentDef.getContentCoProcessorDefs().get( phase); if (defs != null && !defs.isEmpty()) { List<ContentCoProcessorDef> list = new ArrayList<ContentCoProcessorDef>(defs); Collections.sort(list, new Comparator<ContentCoProcessorDef>() { public int compare(ContentCoProcessorDef o1, ContentCoProcessorDef o2) { return o1.getPriority() - o2.getPriority(); } }); for (ContentCoProcessorDef def : list) { ContentCoProcessor processor = SmartContentAPI.getInstance().getWorkspaceApi().getContentCoProcessor(contentId. getWorkspaceId(), def.getResourceUri().getValue()); if (processor != null) { processor.processContent(this, def.getParameters()); } } } } } @Override public void setParentId(ContentId contentId) { if (contentDef == null) { throw new IllegalArgumentException("Content Type Definition must be set before setting parent content ID"); } if (contentId != null && SmartContentAPI.getInstance().getContentLoader().loadContent(contentId) == null) { throw new IllegalArgumentException("Parent must exist for it to be set!"); } this.parentId = contentId; } @Override public void setContentDefinition(ContentType contentType) { this.contentDef = contentType; } @Override public void setField(Field field) { getMap().put(field.getName(), field); cachedFieldMap = null; } @Override public void setStatus(ContentStatus contentStatus) { this.contentStatus = contentStatus; } @Override public ContentId getContentId() { return this.contentId; } @Override public ContentId getParentId() { return this.parentId; } @Override public Content getParent() { if (parentId != null) { return SmartContentAPI.getInstance().getContentLoader().loadContent(parentId); } else { return null; } } @Override public ContentType getContentDefinition() { return this.contentDef; } @Override public Map<String, Field> getFields() { final Content parent = getParent(); final ContentType def = getContentDefinition(); if (cachedFieldMap == null) { Map<String, Field> fields = new LinkedHashMap<String, Field>(); if (parent != null && def != null) { Map<String, Field> parentFields = parent.getFields(); for (String fieldName : parentFields.keySet()) { FieldDef myDef = def.getOwnFieldDefs().get(fieldName); FieldDef thatDef = parent.getContentDefinition().getOwnFieldDefs().get(fieldName); if (myDef != null && thatDef != null && ObjectUtils.equals(myDef, thatDef) && myDef.getValueDef().getType(). equals(thatDef.getValueDef().getType())) { fields.put(fieldName, parent.getField(fieldName)); } } } fields.putAll(getMap()); cachedFieldMap = fields; } return Collections.unmodifiableMap(cachedFieldMap); } public Map<String, Field> getMap() { if (map == null) { map = new LinkedHashMap<String, Field>(SmartContentSPI.getInstance().getContentReader().getFieldsForContent( contentId)); triggerContentCoProcessors(ContentType.ContentProcessingPhase.READ); } return map; } @Override public Map<String, Field> getOwnFields() { return Collections.unmodifiableMap(getMap()); } @Override public Field getField(String fieldName) { return getFields().get(fieldName); } @Override public ContentStatus getStatus() { return this.contentStatus; } @Override public Representation getRepresentation(String repName) { return SmartContentSPI.getInstance().getRepresentationProvider().getRepresentation(repName, getContentDefinition(), this); } @Override public Date getCreationDate() { return this.creationDate; } @Override public Date getLastModifiedDate() { return this.lastModifiedDate; } @Override public boolean isPersisted() { return creationDate != null; } @Override public ContentId getKeySpecimen() { return contentId; } @Override public void removeField(String fieldName) { getMap().remove(fieldName); } @Override public void setContentId(ContentId contentId) { this.contentId = contentId; } @Override public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } @Override public void setLastModifiedDate(Date lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } @Override protected void create() throws IOException { - System.out.println("Inside create method"); if (contentId != null) { if (contentId.getWorkspaceId() == null && contentId.getId() == null) { throw new IOException("Workspace Id and Id is null though Content Id is not null"); } - if (contentId.getWorkspaceId() != null) { - Workspace workspace = SmartContentAPI.getInstance().getWorkspaceApi().getWorkspace(contentId.getWorkspaceId()); - if (workspace == null) { - throw new IOException("Non existance workspace Id " + contentId.getWorkspaceId()); - } + Workspace workspace = SmartContentAPI.getInstance().getWorkspaceApi().getWorkspace(contentId.getWorkspaceId()); + if (workspace == null) { + throw new IOException("Non existance workspace Id " + contentId.getWorkspaceId()); } else { throw new IOException("Invalid workspace null"); } } if (contentId == null && contentDef != null && contentDef.getContentTypeID() != null) { createContentId(contentDef.getContentTypeID().getWorkspace()); } else if (contentId == null && (contentDef == null || contentDef.getContentTypeID() == null)) { throw new IOException("Content ID and Content Type Definition is not set!"); } super.create(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.CREATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public void delete() throws IOException { super.delete(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.DELETE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override protected void update() throws IOException { super.update(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.UPDATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!Content.class.isAssignableFrom(obj.getClass())) { return false; } final Content other = (Content) obj; if (this.contentId != other.getContentId() && (this.contentId == null || !this.contentId.equals(other.getContentId()))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.contentId != null ? this.contentId.hashCode() : 0); return hash; } @Override public void createContentId(WorkspaceId workspace) { if (workspace == null) { throw new IllegalArgumentException("Workspace ID can not be null!"); } setContentId(SmartContentAPI.getInstance().getContentLoader().generateContentId(workspace)); } @Override public void setEntityTagValue(String eTagValue) { this.entityTagValue = eTagValue; } @Override public String getEntityTagValue() { return this.entityTagValue; } @Override public boolean isValid() { boolean validContent = supressChecking || SmartContentAPI.getInstance().getContentLoader().isValidContent(this); if (getLogger().isDebugEnabled()) { getLogger().debug("!!! Checking Content " + validContent); } return validContent; } @Override public URI getUri() { return SmartContentSPI.getInstance().getUriProvider().getContentUri(contentId); } @Override public String getEncodedUriString() { if (getUri() == null) { return null; } else { return getUri().toASCIIString(); } } @Override public void setPrivate(boolean privateContent) { this.privateContent = privateContent; } @Override public boolean isPrivate() { return this.privateContent; } @Override public ContentImpl clone() { ContentImpl contentImpl = new ContentImpl(); contentImpl.contentDef = contentDef; contentImpl.contentId = contentId; contentImpl.parentId = parentId; contentImpl.privateContent = privateContent; contentImpl.contentStatus = contentStatus; contentImpl.nextPerformToWaitForLock = nextPerformToWaitForLock; contentImpl.supressChecking = supressChecking; contentImpl.entityTagValue = entityTagValue; if (creationDate != null) { contentImpl.creationDate = new Date(creationDate.getTime()); } if (lastModifiedDate != null) { contentImpl.lastModifiedDate = new Date(lastModifiedDate.getTime()); } contentImpl.map = map; if (map != null) { contentImpl.map = new LinkedHashMap<String, Field>(); cloneFields(map, contentImpl.map); } if (cachedFieldMap != null) { contentImpl.cachedFieldMap = new LinkedHashMap<String, Field>(); cloneFields(cachedFieldMap, contentImpl.cachedFieldMap); } return contentImpl; } protected void cloneFields(Map<String, Field> fieldMap, Map<String, Field> destMap) { for (Map.Entry<String, Field> oneField : fieldMap.entrySet()) { FieldImpl fieldImpl = new FieldImpl(); final Field value = oneField.getValue(); fieldImpl.setContent(value.getContent()); fieldImpl.setFieldDef(value.getFieldDef()); fieldImpl.setName(value.getName()); final FieldValue fieldVal = value.getValue(); fieldImpl.setValue(fieldVal); destMap.put(oneField.getKey(), fieldImpl); } } } diff --git a/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java b/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java index 1d31218..a573c0e 100644 --- a/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java +++ b/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java @@ -1022,1053 +1022,1053 @@ public class AppTest { LOGGER.debug("Content Type Name : " + getContentType.getContentTypeID().getName()); } Assert.assertEquals(servedContentType.getContentTypeID().getName(), getContentType.getContentTypeID().getName()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Type Namespace : " + getContentType.getContentTypeID().getNamespace()); } Assert.assertEquals(servedContentType.getContentTypeID().getNamespace(), getContentType.getContentTypeID(). getNamespace()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Type Global Namespace : " + getContentType.getContentTypeID().getWorkspace(). getGlobalNamespace()); } Assert.assertEquals(servedContentType.getContentTypeID().getWorkspace().getGlobalNamespace(), getContentType. getContentTypeID().getWorkspace().getGlobalNamespace()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Type ID Global Name : " + getContentType.getContentTypeID().getWorkspace().getName()); } Assert.assertEquals(servedContentType.getContentTypeID().getWorkspace().getName(), getContentType.getContentTypeID(). getWorkspace().getName()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Type Display Name : " + getContentType.getDisplayName()); } Assert.assertEquals(servedContentType.getDisplayName(), getContentType.getDisplayName()); if (getContentType.getParent() != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Type Parent's Name : " + getContentType.getParent().getName()); } Assert.assertEquals(servedContentType.getParent().getName(), getContentType.getParent().getName()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Type Parent's Namespace : " + getContentType.getParent().getNamespace()); } Assert.assertEquals(servedContentType.getParent().getNamespace(), getContentType.getParent().getNamespace()); Assert.assertEquals(servedContentType.getParent().getWorkspace().getGlobalNamespace(), getContentType.getParent(). getWorkspace().getGlobalNamespace()); Assert.assertEquals(servedContentType.getParent().getWorkspace().getName(), getContentType.getParent(). getWorkspace().getName()); } Assert.assertEquals(servedContentType.getStatuses().size(), getContentType.getStatuses().size()); Set statusKeys = servedContentType.getStatuses().keySet(); for (Iterator ite = statusKeys.iterator(); ite.hasNext();) { String key = (String) ite.next(); ContentStatus servedContentStatus = servedContentType.getStatuses().get(key); ContentStatus getContentStatus = getContentType.getStatuses().get(key); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Status : " + getContentStatus.getName()); } Assert.assertEquals(servedContentStatus.getName(), getContentStatus.getName()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Size of Representations Defs : " + getContentType.getRepresentationDefs()); } Assert.assertEquals(servedContentType.getRepresentations().size(), getContentType.getRepresentations().size()); Assert.assertEquals(servedContentType.getRepresentationDefs().size(), getContentType.getRepresentationDefs().size()); Map<String, RepresentationDef> servedRepresentationDefs = servedContentType.getRepresentationDefs(); Set keys = servedRepresentationDefs.keySet(); for (Iterator ite = keys.iterator(); ite.hasNext();) { String key = (String) ite.next(); RepresentationDef servedRepresentationDef = servedContentType.getRepresentationDefs().get(key); RepresentationDef getRepresentationDef = getContentType.getRepresentationDefs().get(key); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Representation MimeType : " + getRepresentationDef.getMIMEType()); } Assert.assertEquals(servedRepresentationDef.getMIMEType(), getRepresentationDef.getMIMEType()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Representation Name : " + getRepresentationDef.getName()); } Assert.assertEquals(servedRepresentationDef.getName(), getRepresentationDef.getName()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Representation URI : " + getRepresentationDef.getResourceUri().getValue()); } Assert.assertEquals(servedRepresentationDef.getResourceUri().getValue(), getRepresentationDef.getResourceUri(). getValue()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Representation URI Type : " + getRepresentationDef.getResourceUri().getType().name()); } Assert.assertEquals(servedRepresentationDef.getResourceUri().getType().name(), getRepresentationDef. getResourceUri().getType().name()); } Assert.assertEquals(servedContentType.getFieldDefs().size(), getContentType.getFieldDefs().size()); Map<String, FieldDef> servedFieldDefs = servedContentType.getFieldDefs(); Set fieldKeys = servedFieldDefs.keySet(); for (Iterator ite = fieldKeys.iterator(); ite.hasNext();) { String key = (String) ite.next(); FieldDef servedFieldDef = servedContentType.getFieldDefs().get(key); FieldDef getFieldDef = getContentType.getFieldDefs().get(key); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Field Name : " + getFieldDef.getName()); } Assert.assertEquals(servedFieldDef.getName(), getFieldDef.getName()); if (servedFieldDef.getCustomValidators() != null && !servedFieldDef.getCustomValidators().isEmpty()) { if (servedFieldDef.getCustomValidators().iterator().next().getUri() != null) { Assert.assertEquals(servedFieldDef.getCustomValidators().iterator().next().getUri().getType().name(), getFieldDef.getCustomValidators().iterator().next().getUri().getType().name()); Assert.assertEquals(servedFieldDef.getCustomValidators().iterator().next().getUri().getValue(), getFieldDef. getCustomValidators().iterator().next().getUri().getValue()); } } if (getFieldDef.getSearchDefinition() != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Field Search Def : " + getFieldDef.getSearchDefinition().toString()); } Assert.assertEquals(getFieldDef.getSearchDefinition().toString(), getFieldDef.getSearchDefinition().toString()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Field value Name : " + getFieldDef.getValueDef().getType().name()); } Assert.assertEquals(servedFieldDef.getValueDef().getType().name(), getFieldDef.getValueDef().getType().name()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Field isUpdateable : " + getFieldDef.isFieldStandaloneUpdateAble()); } Assert.assertEquals(servedFieldDef.isFieldStandaloneUpdateAble(), getFieldDef.isFieldStandaloneUpdateAble()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Field isRequired : " + getFieldDef.isRequired()); } Assert.assertEquals(servedFieldDef.isRequired(), getFieldDef.isRequired()); Collection<VariationDef> servedVariationDefs = servedFieldDef.getVariations().values(); Collection<VariationDef> getVariationDefs = getFieldDef.getVariations().values(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Size of Variation Def : " + getFieldDef.getVariations().size()); } Assert.assertEquals(servedVariationDefs.size(), getVariationDefs.size()); Iterator<VariationDef> iterator3 = getVariationDefs.iterator(); for (VariationDef servedVariationDef : servedVariationDefs) { VariationDef getVariationDef = iterator3.next(); Assert.assertEquals(servedVariationDef.getMIMEType(), getVariationDef.getMIMEType()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Variation Name : " + getVariationDef.getName()); } Assert.assertEquals(servedVariationDef.getName(), getVariationDef.getName()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Variation URI Type : " + getVariationDef.getResourceUri().getType().name()); } Assert.assertEquals(servedVariationDef.getResourceUri().getType().name(), getVariationDef.getResourceUri(). getType().name()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Variation URI : " + getVariationDef.getResourceUri().getValue()); } Assert.assertEquals(servedVariationDef.getResourceUri().getValue(), getVariationDef.getResourceUri().getValue()); } } } } @Test public void testCreateInvlidContent() throws Exception { LOGGER.info(":::::::::::::: CREATE INVALID CONTENT RESOURCE TEST ::::::::::::::"); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("InvalidContent.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); try { feedResource.getContents().createContentResource(content); Assert.fail("Should not be able to create!"); } catch (UniformInterfaceException ex) { Assert.assertEquals(400, ex.getResponse().getStatus()); } } @Test public void testCreateContent() throws Exception { LOGGER.info(":::::::::::::: CREATE DUMMY CONTENT RESOURCE TEST ::::::::::::::"); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); sleep(); sleep(); LOGGER.info(":::::::::::::: CREATE CONTENT RESOURCE TEST ::::::::::::::"); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); ContentResource contentResource = feedResource.getContents().createContentResource(content); Content content1 = contentResource.get(); Assert.assertNotNull(content1); Assert.assertEquals(content.getParentContentUri(), content1.getParentContentUri()); Assert.assertEquals(content.getStatus(), content1.getStatus()); Assert.assertEquals(content.getFields().size(), content1.getFields().size()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Parent Container Uri : " + content1.getParentContentUri()); LOGGER.debug("Status : " + content1.getStatus()); LOGGER.debug("Number of Fields : " + content1.getFields().size()); } Collection<Field> fields = content.getFields(); Collections.reverse((List<Field>) fields); Iterator<Field> iterator1 = fields.iterator(); Field field = iterator1.next(); final Iterator<Field> iterator2 = content1.getFields().iterator(); Field field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertNotNull(field1.getFieldRawContentUri()); Assert.assertNotNull(field1.getFieldUri()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertTrue(field.getValue().getValue().endsWith(field1.getValue().getValue())); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); CollectionFieldValue collectionFieldValue = (CollectionFieldValue) field.getValue(); CollectionFieldValue collectionFieldValue1 = (CollectionFieldValue) field1.getValue(); Assert.assertEquals(collectionFieldValue.getType().toUpperCase(), collectionFieldValue1.getType()); Assert.assertEquals(collectionFieldValue.getValues().size(), collectionFieldValue1.getValues().size()); Iterator<FieldValue> collectionIterator1 = collectionFieldValue.getValues().iterator(); Iterator<FieldValue> collectionIterator2 = collectionFieldValue1.getValues().iterator(); while (collectionIterator1.hasNext()) { String value1 = collectionIterator1.next().getValue(); String value2 = collectionIterator2.next().getValue(); Assert.assertEquals(value1, value2); } field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); sleep(); } @Test public void testUriTemplates() throws URISyntaxException { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TEST TEMPLATES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); final String workspaceNS, workspaceId, typeNS, typeId; RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); WorkspaceFeedResource feedResource = resource.getWorkspaceFeeds().iterator().next(); workspaceNS = "atest2"; workspaceId = "additional"; typeNS = "com.smartitengineering.smart-shopping.content"; typeId = "Publisher"; UriTemplateResource templateResource = resource.getTemplates(); LOGGER.info("Testing getting workspace"); Assert.assertNotNull(templateResource.getWorkspaceResource(workspaceNS, workspaceId)); LOGGER.info("Testing getting content type"); Assert.assertNotNull(templateResource.getContentTypeResource(workspaceNS, workspaceId, typeNS, typeId)); LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% END TEST TEMPLATES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); } @Test public void testContentListener() throws Exception { final MutableInt createCount = new MutableInt(0); final MutableInt updateCount = new MutableInt(0); final MutableInt deleteCount = new MutableInt(0); SmartContentAPI.getInstance().getEventRegistrar().addListener(new EventListener() { @Override public boolean accepts(Event event) { return event.getEventSourceType().equals(Event.Type.CONTENT) && event.getEventType().equals(EventType.CREATE); } @Override public void notify(Event event) { createCount.add(1); } }); SmartContentAPI.getInstance().getEventRegistrar().addListener(new EventListener() { @Override public boolean accepts(Event event) { return event.getEventSourceType().equals(Event.Type.CONTENT) && event.getEventType().equals(EventType.UPDATE); } @Override public void notify(Event event) { updateCount.add(1); } }); SmartContentAPI.getInstance().getEventRegistrar().addListener(new EventListener() { @Override public boolean accepts(Event event) { return event.getEventSourceType().equals(Event.Type.CONTENT) && event.getEventType().equals(EventType.DELETE); } @Override public void notify(Event event) { deleteCount.add(1); } }); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource authorResource = feedResourceTest.getContents().createContentResource(contentTest); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(authorResource.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); sleep(); ContentResource contentResource = feedResource.getContents().createContentResource(content); Assert.assertEquals(2, createCount.intValue()); contentResource.update(content); Assert.assertEquals(1, updateCount.intValue()); authorResource.delete(); contentResource.get(); contentResource.delete(); Assert.assertEquals(2, deleteCount.intValue()); sleep(); } @Test public void testAddContainerContent() throws Exception { LOGGER.info(":::::::::::::: CREATE CONTENT IN CONTAINER RESOURCE TEST ::::::::::::::"); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); sleep(); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Update-Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); ContentResource contentResource = feedResource.getContents().createContentResource(content); Content content1 = contentResource.get(); Assert.assertNotNull(content1); Assert.assertEquals(content.getParentContentUri(), content1.getParentContentUri()); Assert.assertEquals(content.getStatus(), content1.getStatus()); Assert.assertEquals(content.getFields().size(), content1.getFields().size()); Collection<Field> fields = content.getFields(); Collections.reverse((List<Field>) fields); final Field field = fields.iterator().next(); final Field field1 = content1.getFields().iterator().next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType(), field.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field.getValue().getValue()); feedResource.get(); ContainerResource containerResource = feedResource.getContents().getContainer().iterator().next(); containerResource.createContainer(contentResource.getUri()); Assert.assertEquals(1, containerResource.getContainerContents().size()); Assert.assertEquals(contentResource.getUri().toASCIIString(), containerResource.getContainerContents().iterator(). next().getUri().toASCIIString()); } @Test public void testCreateContentWithInvalidWorkspace() throws Exception { LOGGER.info(":::::::::::::: CREATE CONTENT WITH INVALID WORKSPACE ::::::::::::::"); WorkspaceId workspaceId = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspaceId("atest2", "additional"); - WorkspaceId workspaceId1 = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspaceId("invalidws", - "invalidws"); + WorkspaceId invalidWorkspaceId = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspaceId("invalidws", + "invalidws"); - String NAME_SPACE = "com.smartitengineering.smart-shopping.content"; + String nameSpace = "com.smartitengineering.smart-shopping.content"; String name = "Publisher"; ContentTypeId contentTypeId = SmartContentAPI.getInstance().getContentTypeLoader().createContentTypeId(workspaceId, - NAME_SPACE, + nameSpace, name); ContentType contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); String statusKey = contentType.getStatuses().keySet().iterator().next(); ContentStatus contentStatus = contentType.getStatuses().get(statusKey); final WriteableContent writeableContent; - MutableContent mutableContent = new ContentImpl(); + MutableContent mutableContent = SmartContentAPI.getInstance().getContentLoader().createContent(contentType); mutableContent.setContentDefinition(contentType); mutableContent.setPrivate(false); mutableContent.setStatus(contentStatus); MutableField mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); mutableField.setName("name"); MutableFieldValue<String> mutableFieldValue = new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); mutableFieldValue.setValue("russel"); mutableField.setValue(mutableFieldValue); mutableContent.setField(mutableField); //Create new content writeableContent = SmartContentAPI.getInstance().getContentLoader().getWritableContent(mutableContent); - writeableContent.createContentId(workspaceId1); + writeableContent.createContentId(invalidWorkspaceId); try { //Save or update the content, will be decided by writeable content implementation writeableContent.put(); Assert.fail(); } catch (IOException ex) { LOGGER.info("Should fail", ex); } } @Test public void testUpdateCointainerContent() throws Exception { LOGGER.info(":::::::::::::: UPDATE CONTAINER CONTENT RESOURCE TEST ::::::::::::::"); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); sleep(); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); Collection<URI> contentUri = new ArrayList<URI>(); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); ContentResource contentResource = feedResource.getContents().createContentResource(content); feedResource.get(); ContainerResource containerResource = feedResource.getContents().getContainer().iterator().next(); contentUri.add(contentResource.getUri()); containerResource.updateContainer(contentUri); Assert.assertEquals(1, containerResource.getContainerContents().size()); Assert.assertEquals(contentResource.getUri().toASCIIString(), containerResource.getContainerContents().iterator(). next().getUri().toASCIIString()); } @Test public void testDeleteContainerContent() throws Exception { LOGGER.info(":::::::::::::: UPDATE CONTAINER CONTENT RESOURCE TEST ::::::::::::::"); RootResource rootResource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = rootResource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); feedResource.get(); ContainerResource containerResource = feedResource.getContents().getContainer().iterator().next(); containerResource.delete(ClientResponse.Status.ACCEPTED); Assert.assertEquals(0, containerResource.getContainerContents().size()); } @Test public void testUpdateContent() throws Exception { LOGGER.info(":::::::::::::: UPDATE CONTENT RESOURCE TEST ::::::::::::::"); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); sleep(); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); ContentResource contentResource = feedResource.getContents().createContentResource(content); Content content1 = contentResource.get(); Assert.assertNotNull(content1); Assert.assertEquals(content.getParentContentUri(), content1.getParentContentUri()); Assert.assertEquals(content.getStatus(), content1.getStatus()); Assert.assertEquals(content.getFields().size(), content1.getFields().size()); LOGGER.info("::: TEST SEARCHING FROM WORKSPACE RESOURCE"); ContentSearcherResource contentSearcherResource = feedResource.searchContent("count=3"); Assert.assertEquals(3, contentSearcherResource.get().getEntries().size()); LOGGER.info("::: TEST SEARCHING FROM CONTENT RESOURCE"); ContentsResource contentsResource = feedResource.getContents(); ContentSearcherResource contentSearcherResource1 = contentsResource.searchContent("count=6"); Assert.assertEquals(6, contentSearcherResource1.get().getEntries().size()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Parent Container Uri : " + content1.getParentContentUri()); LOGGER.debug("Status : " + content1.getStatus()); LOGGER.debug("Number of Fields : " + content1.getFields().size()); } Collection<Field> fields = content.getFields(); Collections.reverse((List<Field>) fields); Iterator<Field> iterator1 = fields.iterator(); Field field = iterator1.next(); final Iterator<Field> iterator2 = content1.getFields().iterator(); Field field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertNotNull(field1.getFieldRawContentUri()); Assert.assertNotNull(field1.getFieldUri()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertTrue(field.getValue().getValue().endsWith(field1.getValue().getValue())); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); CollectionFieldValue collectionFieldValue = (CollectionFieldValue) field.getValue(); CollectionFieldValue collectionFieldValue1 = (CollectionFieldValue) field1.getValue(); Assert.assertEquals(collectionFieldValue.getType().toUpperCase(), collectionFieldValue1.getType()); Assert.assertEquals(collectionFieldValue.getValues().size(), collectionFieldValue1.getValues().size()); Iterator<FieldValue> collectionIterator1 = collectionFieldValue.getValues().iterator(); Iterator<FieldValue> collectionIterator2 = collectionFieldValue1.getValues().iterator(); while (collectionIterator1.hasNext()) { String value1 = collectionIterator1.next().getValue(); String value2 = collectionIterator2.next().getValue(); Assert.assertEquals(value1, value2); } field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); LOGGER.info(":::::::::::::: Updating Content Resource ::::::::::::::"); ObjectMapper updateMapper = new ObjectMapper(); String updateJSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Update-Content.json")); InputStream updateStream = IOUtils.toInputStream(updateJSON); Content updateContent = updateMapper.readValue(updateStream, Content.class); updateContent.getFields().add(valueImpl); updateContent.getFields().add(authorField); Assert.assertNotNull(updateContent); RootResource updateResource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> updateWorkspaceFeedResources = updateResource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> updateIterator = updateWorkspaceFeedResources.iterator(); WorkspaceFeedResource updateFeedResource = updateIterator.next(); ContentResource updateContentResource = updateFeedResource.getContents().createContentResource(updateContent); Content updateContent1 = updateContentResource.get(); Assert.assertNotNull(updateContent1); Assert.assertEquals(updateContent.getParentContentUri(), updateContent1.getParentContentUri()); Assert.assertEquals(updateContent.getStatus(), updateContent1.getStatus()); Assert.assertEquals(updateContent.getFields().size(), updateContent1.getFields().size()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Parent Container Uri : " + updateContent1.getParentContentUri()); LOGGER.debug("Status : " + updateContent1.getStatus()); LOGGER.debug("Number of Fields : " + updateContent1.getFields().size()); } Collection<Field> updateFields = updateContent.getFields(); Collections.reverse((List<Field>) updateFields); Iterator<Field> updateIterator1 = updateFields.iterator(); Field updateField = updateIterator1.next(); final Iterator<Field> updateIterator2 = updateContent1.getFields().iterator(); Field updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertNotNull(updateField1.getFieldRawContentUri()); Assert.assertNotNull(updateField1.getFieldUri()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertTrue(updateField.getValue().getValue().endsWith(updateField1.getValue().getValue())); updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); CollectionFieldValue updateCollectionFieldValue = (CollectionFieldValue) updateField.getValue(); CollectionFieldValue updateCollectionFieldValue1 = (CollectionFieldValue) updateField1.getValue(); Assert.assertEquals(updateCollectionFieldValue.getType().toUpperCase(), updateCollectionFieldValue1.getType()); Assert.assertEquals(updateCollectionFieldValue.getValues().size(), updateCollectionFieldValue1.getValues().size()); Iterator<FieldValue> updateCollectionIterator1 = updateCollectionFieldValue.getValues().iterator(); Iterator<FieldValue> updateCollectionIterator2 = updateCollectionFieldValue1.getValues().iterator(); while (updateCollectionIterator1.hasNext()) { String value1 = updateCollectionIterator1.next().getValue(); String value2 = updateCollectionIterator2.next().getValue(); Assert.assertEquals(value1, value2); } updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); sleep(); } @Test public void testContentRepresentation() throws Exception { LOGGER.info(":::::::::::::: CONTENT REPRESENTATION RESOURCE TEST ::::::::::::::"); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); LOGGER.info("Author for representation created!"); sleep(); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); ContentResource contentResource = feedResource.getContents().createContentResource(content); Collection<String> urls = contentResource.getRepresentationUrls(); Iterator<String> iterator1 = urls.iterator(); while (iterator1.hasNext()) { String next = iterator1.next(); String type = contentResource.getRepresentation(next); Assert.assertEquals("some/type", type); } sleep(); } @Test public void testFieldVariation() throws Exception { ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); sleep(); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); ContentResource contentResource = feedResource.getContents().createContentResource(content); Iterator<FieldResource> iterator2 = contentResource.getFields().iterator(); while (iterator2.hasNext()) { FieldResource next = iterator2.next(); Collection<String> variations = next.getVariationUrls(); Iterator<String> iterator1 = variations.iterator(); while (iterator1.hasNext()) { String url = iterator1.next(); String variation = next.getVariation(url); Assert.assertEquals("some/type", variation); } } } @Test public void testSearch() throws Exception { LOGGER.info(":::::::::::::: SEARCH CONTENT RESOURCE TEST ::::::::::::::"); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); sleep(); String query = "typeId=atest2:additional:com.smartitengineering.smart-shopping.content:Author&status=published&status=draft&disjunction=true"; ContentSearcherResource searchContent = resource.searchContent(query); Assert.assertEquals(5, searchContent.get().getEntries().size()); IRI href = searchContent.get().getLink("next").getHref(); query = "typeId=atest2:additional:com.smartitengineering.smart-shopping.content:Author&status=published&status=draft&disjunction=true&count=10"; searchContent = resource.searchContent(query); Assert.assertEquals(10, searchContent.get().getEntries().size()); } @Test public void testDeleteContent() throws Exception { LOGGER.info(":::::::::::::: DELETE CONTENT RESOURCE TEST ::::::::::::::"); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); sleep(); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); feedResource.getContents().createContentResource(content).delete(ClientResponse.Status.OK); feedResource.get(); Assert.assertEquals(0, feedResource.getContents().getContentResources().size()); } @Test public void testDeleteContentType() throws Exception { LOGGER.info(":::::::::::::: DELETE CONTENT_TYPE RESOURCE TEST ::::::::::::::"); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next();
SmartITEngineering/smart-cms
3f8a12a9edea17f30f5aac6cb31ad321fa0a6cd0
Implement transaction related injection code generation
diff --git a/code-generation/cms-codegenerator-demo/pom.xml b/code-generation/cms-codegenerator-demo/pom.xml index 7db0a57..b7d2985 100644 --- a/code-generation/cms-codegenerator-demo/pom.xml +++ b/code-generation/cms-codegenerator-demo/pom.xml @@ -1,191 +1,192 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- * * This is a simple Content Management System (CMS) * Copyright (C) 2011 Imran M Yousuf ([email protected]) * 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/>. --> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <groupId>com.smartitengineering.smart-cms</groupId> <artifactId>cms-codegenerator-demo</artifactId> <parent> <groupId>com.smartitengineering.smart-cms</groupId> <artifactId>code-generation</artifactId> <version>0.1-SNAPSHOT</version> </parent> <version>0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>CMS Code Generator Demo</name> <dependencies> <dependency> <groupId>com.smartitengineering.smart-cms</groupId> <artifactId>content-repo-dao-impl</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>com.smartitengineering.smart-util</groupId> <artifactId>smart-bean-guice-util</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-jdk14</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> </plugin> <plugin> <groupId>com.smartitengineering.smart-cms</groupId> <artifactId>cms-tools-plugin</artifactId> <version>${project.version}</version> <configuration> <outputDirectory>${project.build.directory}/cms-tools/</outputDirectory> <solrHomeDirectory>../../solr/sample-conf/</solrHomeDirectory> <solrArtifact> <groupId>org.apache.solr</groupId> <artifactId>solr</artifactId> <version>${solr.version}</version> </solrArtifact> <eventHubArtifact> <groupId>com.smartitengineering.event</groupId> <artifactId>hub-hbase</artifactId> <version>${hub.version}</version> </eventHubArtifact> <!-- Other configurations and their default expressions --> <!-- <zooKeeperPort>2181</zooKeeperPort> <embeddedPort>40404</embeddedPort> <hbaseVersion>${hbase.version}</hbaseVersion> <hadoopVersion>${hadoop.version}</hadoopVersion> <jerseyVersion>${jersey.version}</jerseyVersion> --> </configuration> <executions> <execution> <id>start-cms-tool-suite</id> <phase>test-compile</phase> <goals> <goal>start</goal> </goals> <configuration> <!-- By default it is set to false, which means manual invokation would result a running CMS container --> <daemonMode>true</daemonMode> </configuration> </execution> <execution> <id>stop-cms-tool-suite</id> <phase>package</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>com.smartitengineering.smart-cms</groupId> <artifactId>maven-pojo-generator-plugin</artifactId> <version>${project.version}</version> <configuration> <outputDirectory>${project.build.directory}/generated-sources/cms-pojo/</outputDirectory> <workspaceId>p:q</workspaceId> </configuration> <executions> <execution> <id>generate-pojo-example</id> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> <configuration> <contentTypeResource>${basedir}/src/main/resources/content-type-example.xml</contentTypeResource> <packageForGuiceMasterModule>com.embarcadero.edn</packageForGuiceMasterModule> <typeFiles> <typeFile>content-type-example.xml</typeFile> </typeFiles> + <transactionEnabled>true</transactionEnabled> </configuration> </execution> <execution> <id>generate-pojo-file</id> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> <configuration> <contentTypeResource>${basedir}/src/main/resources/content-type-def-with-composition.xml</contentTypeResource> <packageForGuiceMasterModule>test.di</packageForGuiceMasterModule> <typeFiles> <typeFile>content-type-def-with-composition.xml</typeFile> </typeFiles> </configuration> </execution> <execution> <id>generate-pojo-resource</id> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> <configuration> <contentTypeResource>${basedir}/src/main/resources/content-type-def-with-composition_1.xml</contentTypeResource> <packageForGuiceMasterModule>testa.di</packageForGuiceMasterModule> <typeFiles> <typeFile>content-type-def-with-composition_1.xml</typeFile> </typeFiles> </configuration> </execution> <execution> <id>generate-pojo-resources</id> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> <configuration> <contentTypes> <contentType>${basedir}/src/main/resources/content-type-def-with-composition_2.xml</contentType> <contentType>${basedir}/src/main/resources/content-type-def-with-composition_3.xml</contentType> </contentTypes> <typeFiles> <typeFile>content-type-def-with-composition_2.xml</typeFile> <typeFile>content-type-def-with-composition_3.xml</typeFile> </typeFiles> <packageForGuiceMasterModule>testb.di</packageForGuiceMasterModule> </configuration> </execution> </executions> </plugin> </plugins> </build> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <junit.version>4.8.2</junit.version> </properties> </project> diff --git a/code-generation/maven-pojo-generator-plugin/src/main/java/com/smartitengineering/cms/maven/dto/generator/plugin/PojoGeneratorMojo.java b/code-generation/maven-pojo-generator-plugin/src/main/java/com/smartitengineering/cms/maven/dto/generator/plugin/PojoGeneratorMojo.java index 01119c1..7054693 100644 --- a/code-generation/maven-pojo-generator-plugin/src/main/java/com/smartitengineering/cms/maven/dto/generator/plugin/PojoGeneratorMojo.java +++ b/code-generation/maven-pojo-generator-plugin/src/main/java/com/smartitengineering/cms/maven/dto/generator/plugin/PojoGeneratorMojo.java @@ -1,813 +1,846 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2011 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.maven.dto.generator.plugin; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.PrivateModule; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.MapBinder; import com.google.inject.name.Names; import com.smartitengineering.cms.api.content.CompositeFieldValue; import com.smartitengineering.cms.api.content.Content; import com.smartitengineering.cms.api.content.ContentId; import com.smartitengineering.cms.api.content.Field; import com.smartitengineering.cms.api.content.FieldValue; import com.smartitengineering.cms.api.content.MutableCompositeFieldValue; import com.smartitengineering.cms.api.content.MutableField; import com.smartitengineering.cms.api.content.MutableFieldValue; import com.smartitengineering.cms.api.factory.SmartContentAPI; import com.smartitengineering.cms.api.factory.content.ContentLoader; import com.smartitengineering.cms.api.factory.content.WriteableContent; import com.smartitengineering.cms.api.impl.type.ContentTypeImpl; import com.smartitengineering.cms.api.impl.workspace.WorkspaceIdImpl; import com.smartitengineering.cms.api.type.CollectionDataType; import com.smartitengineering.cms.api.type.CompositeDataType; import com.smartitengineering.cms.api.type.ContentDataType; import com.smartitengineering.cms.api.type.ContentType; import com.smartitengineering.cms.api.type.ContentType.DefinitionType; import com.smartitengineering.cms.api.type.ContentTypeId; import com.smartitengineering.cms.api.type.EnumDataType; import com.smartitengineering.cms.api.type.FieldDef; import com.smartitengineering.cms.api.type.FieldValueType; import com.smartitengineering.cms.api.type.MutableContentType; import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.cms.repo.dao.impl.AbstractRepoAdapterHelper; import com.smartitengineering.cms.repo.dao.impl.AbstractRepositoryDomain; import com.smartitengineering.cms.repo.dao.impl.ExtendedReadDao; import com.smartitengineering.cms.repo.dao.impl.Initializer; import com.smartitengineering.cms.repo.dao.impl.RepositoryDaoImpl; +import com.smartitengineering.cms.repo.dao.impl.tx.CommonTxDao; +import com.smartitengineering.cms.repo.dao.impl.tx.TransactionImplModule; +import com.smartitengineering.cms.repo.dao.impl.tx.Transactionable; import com.smartitengineering.cms.type.xml.XMLParserIntrospector; import com.smartitengineering.cms.type.xml.XmlParser; import com.smartitengineering.dao.common.CommonDao; import com.smartitengineering.dao.common.CommonReadDao; import com.smartitengineering.dao.common.CommonWriteDao; import com.smartitengineering.domain.PersistentDTO; import com.smartitengineering.util.bean.adapter.AbstractAdapterHelper; import com.smartitengineering.util.bean.adapter.GenericAdapter; import com.smartitengineering.util.bean.adapter.GenericAdapterImpl; import com.sun.codemodel.ClassType; import com.sun.codemodel.JBlock; import com.sun.codemodel.JClass; import com.sun.codemodel.JClassAlreadyExistsException; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JConditional; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JExpr; import com.sun.codemodel.JExpression; import com.sun.codemodel.JFieldVar; import com.sun.codemodel.JForLoop; import com.sun.codemodel.JInvocation; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JType; import com.sun.codemodel.JVar; import com.sun.codemodel.JWhileLoop; import nu.xom.Element; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.maven.project.MavenProject; /** * Goal which touches a timestamp file. Configure any one of contentTypesResourceConfig, contentTypeResourceConfig and * contentTypeResource. Not configuring any one of them or more than one would result runtime exception. * * @goal generate * * @phase generate-sources */ public class PojoGeneratorMojo extends AbstractMojo { /** * Location of the file. * @parameter expression="${generated.sources.directory}" * @required */ private File outputDirectory; /** * A collection of content types for generating POJOs for beans in multiple workspaces. Content types could either be * a file or a classpath resource. If either is missing it would result a classpath exception * @parameter */ private List<String> contentTypes; /** * A content type file * @parameter */ private File contentTypeResource; /** * Default package for aggregating modules * @parameter * @required */ private String packageForGuiceMasterModule; /** * The workspace id for the specified content type resource. It will be used to DI in the adapter and DAO Impl * @parameter * @required */ private String workspaceId; /** * The Maven project instance for the executing project. * * @parameter expression="${project}" * @required */ private MavenProject project; /** * The content type files from classpath to use for initialization * * @parameter */ private List<String> typeFiles; + /** + * Whether transaction is enabled for this piece of generated code or not. By default its false to be backward + * compatible. + * @parameter expression="false" + */ + private boolean transactionEnabled; + /** + * Whether a transaction with isolated=false is allowed or not. By default its not allowed. + * @parameter expression="false" + */ + private boolean nonIsolatedTransactionAllowed; public void execute() throws MojoExecutionException { File f = outputDirectory; if (!f.exists()) { f.mkdirs(); } if ((contentTypes == null || contentTypes.isEmpty()) && contentTypeResource == null) { throw new MojoExecutionException("Parameters not specified properly. Any one and only one of " + "contentTypesResourceConfig, contentTypeResourceConfig and contentTypeResource must be specified!"); } if (StringUtils.isBlank(packageForGuiceMasterModule)) { throw new MojoExecutionException("Parameter 'packageForGuiceMasterModule' can not be blank"); } JCodeModel codeModel = new JCodeModel(); Set<MutableContentType> types = new LinkedHashSet<MutableContentType>(); if (StringUtils.isBlank(workspaceId) || workspaceId.split(":").length != 2) { throw new MojoExecutionException("Workspace ID not specified or is not in format 'namespace:name'"); } final String wIds[] = workspaceId.split(":"); if (contentTypeResource != null) { if (!contentTypeResource.exists() || !contentTypeResource.isFile()) { throw new MojoExecutionException("'contentTypeResource' file either does not exist or is not a file: " + (contentTypeResource == null ? null : contentTypeResource.getAbsolutePath())); } final WorkspaceIdImpl dummyIdImpl = new WorkspaceIdImpl(); dummyIdImpl.setGlobalNamespace(wIds[0]); dummyIdImpl.setName(wIds[1]); types.addAll(parseContentType(dummyIdImpl, contentTypeResource)); } else { for (String contentTypeRsrc : contentTypes) { final String value = contentTypeRsrc; if (StringUtils.isBlank(value)) { throw new MojoExecutionException("'contentTypesResourceConfig' can not have empty resource config"); } File file = new File(value); if (file.exists() && file.isFile()) { WorkspaceIdImpl idImpl = new WorkspaceIdImpl(); idImpl.setGlobalNamespace(wIds[0]); idImpl.setName(wIds[1]); types.addAll(parseContentType(idImpl, file)); } else { throw new MojoExecutionException("'contentTypesResourceConfig' can not have a resource config that is neither" + "a file nor a classpath resoruce: " + value); } } } try { generateCode(codeModel, types); codeModel.build(outputDirectory); project.addCompileSourceRoot(outputDirectory.getAbsolutePath()); } catch (Exception ex) { throw new MojoExecutionException(ex.getMessage(), ex); } } protected void generateIoCClasses(JCodeModel codeModel, Set<MutableContentType> types, Map<ContentTypeId, JDefinedClass> classes, Map<ContentTypeId, JDefinedClass> helpers, Map<ContentTypeId, JDefinedClass> modules) throws JClassAlreadyExistsException { // Create helpers and google guice module for concrete type definitions JClass privateModuleClass = codeModel.ref(PrivateModule.class); // Initialize common classes for Google Guice bindings JClass typeLiteral = codeModel.ref(TypeLiteral.class); JClass commonDao = codeModel.ref(CommonDao.class); JClass commonReadDao = codeModel.ref(CommonReadDao.class); JClass extendedReadDao = codeModel.ref(ExtendedReadDao.class); JClass commonWriteDao = codeModel.ref(CommonWriteDao.class); JClass commonDaoImpl = codeModel.ref(RepositoryDaoImpl.class); + JClass commonTxDao = codeModel.ref(CommonTxDao.class); + JClass transactionableAnn = codeModel.ref(Transactionable.class); JClass genericAdapter = codeModel.ref(GenericAdapter.class).narrow(Content.class); JClass classRef = codeModel.ref(Class.class); JClass genericAdapterImpl = codeModel.ref(GenericAdapterImpl.class).narrow(Content.class); JClass abstractHelper = codeModel.ref(AbstractAdapterHelper.class).narrow(Content.class); JClass singletonScope = codeModel.ref(Singleton.class); JClass workspaceIdClass = codeModel.ref(WorkspaceId.class); JClass apiClass = codeModel.ref(SmartContentAPI.class); String[] wId = workspaceId.split(":"); for (MutableContentType type : types) { if (type.getDefinitionType().equals(DefinitionType.CONCRETE_TYPE)) { final ContentTypeId contentTypeID = type.getContentTypeID(); JDefinedClass definedClass = classes.get(contentTypeID); final JDefinedClass helperClass = generateHelper(type, codeModel, classes, types); helpers.put(contentTypeID, helperClass); { final String moduleClassName = new StringBuilder(contentTypeID.getNamespace()).append(".guice.").append(contentTypeID. getName()).append("Module").toString(); final JDefinedClass moduleClass = codeModel._class(moduleClassName); modules.put(contentTypeID, moduleClass); moduleClass._extends(privateModuleClass); JMethod configureMethod = moduleClass.method(JMod.PUBLIC, JCodeModel.boxToPrimitive.get(Void.class), "configure"); JBlock block = configureMethod.body(); final JDefinedClass commonDaoType; final JDefinedClass daoImplType; + final JDefinedClass txDaoImplType; + final JDefinedClass readDaoType; + final JDefinedClass writeDaoType; { final JClass narrowedCommonDaoTypeLiteral = typeLiteral.narrow(commonDao.narrow(definedClass).narrow( String.class)); commonDaoType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append( "CommonDaoType").toString()); commonDaoType._extends(narrowedCommonDaoTypeLiteral); - final JClass beanClass = classRef.narrow(definedClass.wildcard()); - JDefinedClass classType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append( - "ClassType").toString()); - classType._extends(typeLiteral.narrow(beanClass)); - block.add(JExpr.invoke("bind").arg(JExpr._new(classType)).invoke("toInstance").arg(definedClass.dotclass())); - final JClass narrowedDaoImplTypeLiteral = typeLiteral.narrow(commonDaoImpl.narrow(definedClass)); - daoImplType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append("DaoImplType"). - toString()); - daoImplType._extends(narrowedDaoImplTypeLiteral); - block.add(JExpr.invoke("bind").arg(JExpr._new(commonDaoType)).invoke("to").arg(JExpr._new(daoImplType)). - invoke("in").arg(singletonScope.dotclass())); - block.add(JExpr.invoke("binder").invoke("expose").arg(JExpr._new(commonDaoType))); } { final JClass narrowedReadTypeLiteral = typeLiteral.narrow(commonReadDao.narrow(definedClass).narrow( String.class)); - final JDefinedClass readDaoType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()). - append("ReadDaoType").toString()); + readDaoType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append("ReadDaoType"). + toString()); readDaoType._extends(narrowedReadTypeLiteral); block.add(JExpr.invoke("bind").arg(JExpr._new(readDaoType)).invoke("to").arg(JExpr._new(commonDaoType)). invoke("in").arg(singletonScope.dotclass())); block.add(JExpr.invoke("binder").invoke("expose").arg(JExpr._new(readDaoType))); } - { - final JClass narrowedReadTypeLiteral = typeLiteral.narrow(extendedReadDao.narrow(definedClass).narrow( - String.class)); - final JDefinedClass readDaoType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()). - append("ExtReadDaoType").toString()); - readDaoType._extends(narrowedReadTypeLiteral); - block.add(JExpr.invoke("bind").arg(JExpr._new(readDaoType)).invoke("to").arg(JExpr._new(daoImplType)). - invoke("in").arg(singletonScope.dotclass())); - block.add(JExpr.invoke("binder").invoke("expose").arg(JExpr._new(readDaoType))); - } { final JClass narrowedWriteTypeLiteral = typeLiteral.narrow(commonWriteDao.narrow(definedClass)); - final JDefinedClass writeDaoType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()). - append("WriteDaoType").toString()); + writeDaoType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append("WriteDaoType"). + toString()); writeDaoType._extends(narrowedWriteTypeLiteral); block.add(JExpr.invoke("bind").arg(JExpr._new(writeDaoType)).invoke("to").arg(JExpr._new(commonDaoType)). invoke("in").arg(singletonScope.dotclass())); block.add(JExpr.invoke("binder").invoke("expose").arg(JExpr._new(writeDaoType))); } + { + final JClass narrowedDaoImplTypeLiteral = typeLiteral.narrow(commonDaoImpl.narrow(definedClass)); + final JClass narrowedCommonTxDaoTypeLiteral = typeLiteral.narrow(commonTxDao.narrow(definedClass)); + final JClass beanClass = classRef.narrow(definedClass); + JDefinedClass classType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append( + "ClassType").toString()); + classType._extends(typeLiteral.narrow(beanClass)); + daoImplType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append("DaoImplType"). + toString()); + daoImplType._extends(narrowedDaoImplTypeLiteral); + txDaoImplType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()).append( + "CommonTxDaoType").toString()); + txDaoImplType._extends(narrowedCommonTxDaoTypeLiteral); + block.add(JExpr.invoke("bind").arg(JExpr._new(classType)).invoke("toInstance").arg(definedClass.dotclass())); + if (transactionEnabled) { + block.add(JExpr.invoke("bind").arg(JExpr._new(commonDaoType)).invoke("to").arg(JExpr._new(txDaoImplType))); + block.add(JExpr.invoke("bind").arg(JExpr._new(readDaoType)).invoke("annotatedWith").arg(transactionableAnn. + dotclass()).invoke("to").arg(JExpr._new(daoImplType))); + block.add(JExpr.invoke("bind").arg(JExpr._new(writeDaoType)).invoke("annotatedWith").arg(transactionableAnn. + dotclass()).invoke("to").arg(JExpr._new(daoImplType))); + } + else { + block.add(JExpr.invoke("bind").arg(JExpr._new(commonDaoType)).invoke("to").arg(JExpr._new(daoImplType))); + } + block.add(JExpr.invoke("binder").invoke("expose").arg(JExpr._new(commonDaoType))); + } + { + final JClass narrowedReadTypeLiteral = typeLiteral.narrow(extendedReadDao.narrow(definedClass).narrow( + String.class)); + final JDefinedClass extReadDaoType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()). + append("ExtReadDaoType").toString()); + extReadDaoType._extends(narrowedReadTypeLiteral); + block.add(JExpr.invoke("bind").arg(JExpr._new(extReadDaoType)).invoke("to").arg(JExpr._new(daoImplType)). + invoke("in").arg(singletonScope.dotclass())); + block.add(JExpr.invoke("binder").invoke("expose").arg(JExpr._new(extReadDaoType))); + } { JClass lGenericAdapter = genericAdapter.narrow(definedClass); JClass lGenericAdapterImpl = genericAdapterImpl.narrow(definedClass); JClass lAbstractHelper = abstractHelper.narrow(definedClass); final JDefinedClass adapterHelperType = moduleClass._class(new StringBuilder( type.getContentTypeID().getName()).append("AdapterType").toString()); adapterHelperType._extends(typeLiteral.narrow(lGenericAdapter)); final JDefinedClass adapterImplType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()). append("AdapterImplType").toString()); adapterImplType._extends(typeLiteral.narrow(lGenericAdapterImpl)); final JDefinedClass abstractHelperType = moduleClass._class(new StringBuilder(type.getContentTypeID(). getName()).append("AdapterHelperType").toString()); abstractHelperType._extends(typeLiteral.narrow(lAbstractHelper)); final JDefinedClass helperType = moduleClass._class(new StringBuilder(type.getContentTypeID().getName()). append("AdapterHelperImplType").toString()); helperType._extends(typeLiteral.narrow(helperClass)); block.add(JExpr.invoke("bind").arg(JExpr._new(adapterHelperType)).invoke("to").arg(JExpr._new( adapterImplType)).invoke("in").arg(singletonScope.dotclass())); block.add(JExpr.invoke("bind").arg(JExpr._new(abstractHelperType)).invoke("to").arg(JExpr._new(helperType)). invoke("in").arg(singletonScope.dotclass())); final JInvocation workspaceApiInvocation = apiClass.staticInvoke("getInstance").invoke("getWorkspaceApi"). invoke("createWorkspaceId"); final JInvocation _new = workspaceApiInvocation.arg(wId[0]).arg(wId[1]); block.add(JExpr.invoke("bind").arg(workspaceIdClass.dotclass()).invoke("toInstance").arg(_new)); } //String TypeLiteral final JDefinedClass stringType; { final JClass narrowedReadTypeLiteral = typeLiteral.narrow(String.class); stringType = moduleClass._class("StringType"); stringType._extends(narrowedReadTypeLiteral); } //Traverse fields to make their DIs { Collection<FieldDef> defs = getAllFields(type, types).values(); generateAssociationIoCForFields(defs, codeModel, stringType, typeLiteral, moduleClass, block, types, classes, type.getContentTypeID().getName(), new HashSet<ContentTypeId>()); } } } } generateMasterModule(modules, codeModel, wId); } protected Set<FieldDef> getAllComposedFields(CompositeDataType compositeDataType, Set<? extends ContentType> types) { Set<FieldDef> compositeFields = new LinkedHashSet<FieldDef>(); if (compositeDataType.getEmbeddedContentType() != null) { ContentType currentType = getType(types, compositeDataType.getEmbeddedContentType().getTypeDef()); if (currentType != null) { compositeFields.addAll(getAllFields(currentType, types).values()); } } compositeFields.addAll(compositeDataType.getOwnComposition()); return compositeFields; } protected Map<String, FieldDef> getAllFields(ContentType currentType, Set<? extends ContentType> types) { Map<String, FieldDef> defs = new LinkedHashMap<String, FieldDef>(); boolean hasMore = true; while (hasMore) { Map<String, FieldDef> ownFields = currentType.getOwnFieldDefs(); for (Entry<String, FieldDef> ownField : ownFields.entrySet()) { if (!defs.containsKey(ownField.getKey())) { defs.put(ownField.getKey(), ownField.getValue()); } } if (currentType.getParent() != null) { final ContentTypeId parent = currentType.getParent(); currentType = getType(types, parent); hasMore = currentType != null; } else { hasMore = false; } } return defs; } protected ContentType getType(Set<? extends ContentType> types, final ContentTypeId id) { for (ContentType type : types) { if (type.getContentTypeID().equals(id)) { return type; } } return null; } protected JFieldVar initializeDao(ContentTypeId typeId, JDefinedClass helperClass, JCodeModel model, Map<ContentTypeId, JDefinedClass> classes) { final JDefinedClass typeDef = classes.get(typeId); final String varClassName = typeDef.name(); String readDaoName = new StringBuilder(new StringBuilder().append( ("" + varClassName.charAt(0)).toLowerCase()).append(varClassName.substring(1)).toString()).append( "ReadDaos").toString(); JFieldVar readDaoVar = helperClass.fields().get(readDaoName); if (readDaoVar == null) { readDaoVar = helperClass.field(JMod.PRIVATE, model.ref(Map.class).narrow(String.class).narrow(model.ref( CommonReadDao.class).narrow(typeDef.wildcard()).narrow( String.class)), readDaoName); readDaoVar.annotate(Inject.class); } return readDaoVar; } protected Collection<MutableContentType> parseContentType(final WorkspaceId id, File file) throws MojoExecutionException { try { final XmlParser parser = new XmlParser(id, new FileInputStream(file), new XMLParserIntrospector() { public MutableContentType createMutableContentType() { return new ContentTypeImpl(); } public void processMutableContentType(MutableContentType type, Element element) { } }); return parser.parse(); } catch (Exception ex) { throw new MojoExecutionException(ex.getMessage(), ex); } } protected void generateCode(JCodeModel codeModel, Set<MutableContentType> types) throws Exception { Map<ContentTypeId, JDefinedClass> classes = new LinkedHashMap<ContentTypeId, JDefinedClass>(); Map<ContentTypeId, JDefinedClass> helpers = new LinkedHashMap<ContentTypeId, JDefinedClass>(); Map<ContentTypeId, JDefinedClass> modules = new LinkedHashMap<ContentTypeId, JDefinedClass>(); // Create the classes for (MutableContentType type : types) { final ContentTypeId contentTypeID = type.getContentTypeID(); classes.put(contentTypeID, generateClassForType(type, codeModel)); } // Set parent content types as appropriate for (MutableContentType type : types) { final JDefinedClass typeClass = classes.get(type.getContentTypeID()); if (type.getParent() != null) { final JClass parentClass = classes.get(type.getParent()); typeClass._extends(parentClass); } } // Create members and their accessors for (MutableContentType type : types) { generateFields(type.getOwnFieldDefs().values(), classes.get(type.getContentTypeID()), classes, codeModel); } generateIoCClasses(codeModel, types, classes, helpers, modules); } protected JDefinedClass generateHelper(final ContentType contentType, JCodeModel codeModel, Map<ContentTypeId, JDefinedClass> classes, Set<? extends ContentType> types) throws JClassAlreadyExistsException { ContentTypeId contentTypeID = contentType.getContentTypeID(); final JDefinedClass definedClass = classes.get(contentTypeID); final JClass parentClass = codeModel.ref(AbstractRepoAdapterHelper.class); final JDefinedClass helperClass; final String helperClassName = new StringBuilder(contentTypeID.getNamespace()).append(".helpers.").append(contentTypeID. getName()).append("Helper").toString(); helperClass = codeModel._class(helperClassName); helperClass._extends(parentClass.narrow(definedClass)); ContentType currentType = contentType; Map<String, FieldDef> defs = getAllFields(currentType, types); { JMethod forwardConversion = helperClass.method(JMod.PROTECTED, JCodeModel.boxToPrimitive.get(Void.class), "mergeContentIntoBean"); JVar content = forwardConversion.param(Content.class, "fromBean"); JVar toBean = forwardConversion.param(definedClass, "toBean"); JBlock block = forwardConversion.body(); generateForwardBlocks(defs.values(), block, content, toBean, codeModel, definedClass, helperClass, classes, types, ""); } { JMethod reverseConversion = helperClass.method(JMod.PROTECTED, JCodeModel.boxToPrimitive.get(Void.class), "mergeBeanIntoContent"); JVar fromBean = reverseConversion.param(definedClass, "fromBean"); JVar wContent = reverseConversion.param(WriteableContent.class, "toBean"); JBlock block = reverseConversion.body(); JInvocation staticInvoke = codeModel.ref(SmartContentAPI.class).staticInvoke("getInstance"); block._if(staticInvoke.eq(JExpr._null()))._then()._throw(JExpr._new(codeModel.ref(IllegalStateException.class)). arg("Smart Content API can not be null!")); JVar contentLoader = block.decl(JMod.FINAL, codeModel.ref(ContentLoader.class), "contentLoader", staticInvoke.invoke("getContentLoader")); JVar fieldDefs = block.decl(codeModel.ref(Map.class).narrow(String.class).narrow(FieldDef.class), "fieldDefs", wContent.invoke("getContentDefinition").invoke("getFieldDefs")); generateReverseBlocks(defs.values(), block, fromBean, wContent, contentLoader, fieldDefs, codeModel, definedClass, classes, types, ""); } { JMethod instanceCreation = helperClass.method(JMod.PROTECTED, definedClass, "newTInstance"); JBlock block = instanceCreation.body(); block._return(JExpr._new(definedClass)); } return helperClass; } protected JDefinedClass generateClassForType(MutableContentType type, JCodeModel codeModel) throws JClassAlreadyExistsException { ContentTypeId typeId = type.getContentTypeID(); int mod = JMod.PUBLIC; final DefinitionType defType = type.getDefinitionType(); if (defType.equals(ContentType.DefinitionType.ABSTRACT_COMPONENT)) { // Extend nothing mod = mod | JMod.ABSTRACT; } else if (defType.equals(ContentType.DefinitionType.ABSTRACT_TYPE)) { mod = mod | JMod.ABSTRACT; } JDefinedClass definedClass = codeModel._class(mod, new StringBuilder(typeId.getNamespace()).append('.').append(typeId. getName()).toString(), ClassType.CLASS); if (defType.equals(ContentType.DefinitionType.ABSTRACT_TYPE) || defType.equals( ContentType.DefinitionType.CONCRETE_TYPE)) { JClass clazz = codeModel.ref(AbstractRepositoryDomain.class); definedClass._extends(clazz.narrow(definedClass)); } return definedClass; } protected void generateFields(Collection<FieldDef> fields, JDefinedClass definedClass, Map<ContentTypeId, JDefinedClass> classes, JCodeModel codeModel) throws JClassAlreadyExistsException, ClassNotFoundException { for (FieldDef def : fields) { final Class fieldClass; final JType jType; final String name = def.getName(); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); switch (def.getValueDef().getType()) { case BOOLEAN: fieldClass = Boolean.class; jType = null; break; case STRING: fieldClass = String.class; jType = null; break; case CONTENT: ContentDataType contentDataType = (ContentDataType) def.getValueDef(); fieldClass = null; final ContentTypeId typeDef = contentDataType.getTypeDef(); jType = classes.get(typeDef); break; case DATE_TIME: fieldClass = Date.class; jType = null; break; case INTEGER: fieldClass = Integer.class; jType = null; break; case DOUBLE: fieldClass = Double.class; jType = null; break; case LONG: fieldClass = Long.class; jType = null; break; case OTHER: fieldClass = byte[].class; jType = null; break; case ENUM: { JDefinedClass enumClass = definedClass._enum(JMod.PUBLIC | JMod.STATIC, getterSetterSuffix); EnumDataType enumDataType = (EnumDataType) def.getValueDef(); Collection<String> choices = enumDataType.getChoices(); for (String choice : choices) { enumClass.enumConstant(choice); } fieldClass = null; jType = enumClass; break; } case COLLECTION: fieldClass = null; final JClass itemType; CollectionDataType collectionDataType = (CollectionDataType) def.getValueDef(); switch (collectionDataType.getItemDataType().getType()) { case BOOLEAN: itemType = codeModel.ref(Boolean.class); break; case STRING: itemType = codeModel.ref(String.class); break; case CONTENT: itemType = classes.get(((ContentDataType) collectionDataType.getItemDataType()).getTypeDef()); break; case DATE_TIME: itemType = codeModel.ref(Date.class); break; case INTEGER: itemType = codeModel.ref(Integer.class); break; case DOUBLE: itemType = codeModel.ref(Double.class); break; case LONG: itemType = codeModel.ref(Long.class); break; case OTHER: itemType = codeModel.ref(byte[].class); break; case ENUM: { JDefinedClass enumClass = definedClass._enum(JMod.PUBLIC | JMod.STATIC, getterSetterSuffix); EnumDataType enumDataType = (EnumDataType) collectionDataType.getItemDataType(); Collection<String> choices = enumDataType.getChoices(); for (String choice : choices) { enumClass.enumConstant(choice); } itemType = enumClass; break; } case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) collectionDataType.getItemDataType(); ContentDataType composedOfContent = compositeDataType.getEmbeddedContentType(); final JDefinedClass composedOfClass; if (composedOfContent != null) { composedOfClass = classes.get(composedOfContent.getTypeDef()); } else { composedOfClass = null; } if (compositeDataType.getOwnComposition() != null && !compositeDataType.getOwnComposition().isEmpty()) { JDefinedClass compositeFieldClass = definedClass._class(JMod.STATIC | JMod.PUBLIC, getterSetterSuffix); if (composedOfContent != null) { compositeFieldClass._extends(composedOfClass); } generateFields(compositeDataType.getOwnComposition(), compositeFieldClass, classes, codeModel); itemType = compositeFieldClass; } else if (composedOfContent != null) { itemType = composedOfClass; } else { itemType = codeModel.ref(Object.class); } break; } default: itemType = codeModel.ref(Object.class); } jType = codeModel.ref(Collection.class).narrow(itemType); break; case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) def.getValueDef(); ContentDataType composedOfContent = compositeDataType.getEmbeddedContentType(); if (compositeDataType.getOwnComposition() != null && !compositeDataType.getOwnComposition().isEmpty()) { fieldClass = null; JDefinedClass compositeFieldClass = definedClass._class(JMod.STATIC | JMod.PUBLIC, getterSetterSuffix); if (composedOfContent != null) { compositeFieldClass._extends(classes.get(composedOfContent.getTypeDef())); } generateFields(compositeDataType.getOwnComposition(), compositeFieldClass, classes, codeModel); jType = compositeFieldClass; } else if (composedOfContent != null) { fieldClass = null; jType = classes.get(composedOfContent.getTypeDef()); } else { fieldClass = Object.class; jType = null; } break; } default: fieldClass = Object.class; jType = null; } final String getterName = new StringBuilder("get").append(getterSetterSuffix).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); final JFieldVar fieldVar; final JMethod getterMethod; final JMethod setterMethod; final JVar paramVar; final JFieldVar propConstant = definedClass.field(JMod.PUBLIC | JMod.FINAL | JMod.STATIC, String.class, new StringBuilder("PROPERTY").append('_').append(name. toUpperCase()).toString(), JExpr.lit(name)); if (jType == null) { fieldVar = definedClass.field(JMod.PROTECTED, fieldClass, name); getterMethod = definedClass.method(JMod.PUBLIC, fieldClass, getterName); setterMethod = definedClass.method(JMod.PUBLIC, JCodeModel.boxToPrimitive.get(Void.class), setterName); paramVar = setterMethod.param(fieldClass, name); } else { fieldVar = definedClass.field(JMod.PROTECTED, jType, name); getterMethod = definedClass.method(JMod.PUBLIC, jType, getterName); setterMethod = definedClass.method(JMod.PUBLIC, JCodeModel.boxToPrimitive.get(Void.class), setterName); paramVar = setterMethod.param(jType, name); } final JBlock getterBlock = getterMethod.body(); getterBlock._return(fieldVar); JBlock setterBlock = setterMethod.body(); setterBlock.assign(JExpr._this().ref(fieldVar), paramVar); } } protected void generateForwardBlocks(Collection<FieldDef> values, JBlock block, JVar from, JVar toBean, JCodeModel model, JDefinedClass currentClass, JDefinedClass helperClass, Map<ContentTypeId, JDefinedClass> classes, Set<? extends ContentType> types, String prefix) { final JClass contentIdRef = model.ref(ContentId.class); for (FieldDef def : values) { final String name = def.getName(); final String varName = getVarName(prefix, name); final String fieldVar = new StringBuilder(varName).append("Field").toString(); JVar field = block.decl(model.ref(Field.class), fieldVar, from.invoke("getField").arg(name)); JConditional conditional = block._if(field.ne(JExpr._null())); JBlock valBlock = conditional._then(); switch (def.getValueDef().getType()) { case BOOLEAN: setField(valBlock, model, field, name, toBean, Boolean.class, prefix); break; case STRING: setField(valBlock, model, field, name, toBean, String.class, prefix); break; case ENUM: { final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); final String fieldValVar = getVarName(prefix, new StringBuilder(name).append("Val").toString()); JClass enumClass = ((JClass) currentClass.fields().get(name).type()); JVar fieldVal = block.decl(model.ref(FieldValue.class).narrow(String.class), fieldValVar, field.invoke( "getValue")); JConditional valCond = block._if(fieldVal.ne(JExpr._null())); JBlock setBlock = valCond._then(); setBlock.add(toBean.invoke(setterName).arg(enumClass.staticInvoke("valueOf").arg(fieldVal.invoke("getValue")))); break; } case DATE_TIME: setField(valBlock, model, field, name, toBean, Date.class, prefix); break; case INTEGER: setField(valBlock, model, field, name, toBean, Integer.class, prefix); break; case DOUBLE: setField(valBlock, model, field, name, toBean, Double.class, prefix); break; case LONG: setField(valBlock, model, field, name, toBean, Long.class, prefix); break; case OTHER: setField(valBlock, model, field, name, toBean, byte[].class, prefix); break; case CONTENT: { ContentDataType contentDataType = (ContentDataType) def.getValueDef(); final JDefinedClass typeDef = classes.get(contentDataType.getTypeDef()); if (typeDef != null) { JFieldVar readDaoVar = initializeDao(contentDataType.getTypeDef(), helperClass, model, classes); if (readDaoVar != null) { final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); final String fieldValVar = new StringBuilder(varName).append("Val").toString(); JVar fieldVal = valBlock.decl(model.ref(FieldValue.class).narrow(contentIdRef), fieldValVar, field.invoke("getValue")); JConditional valCond = valBlock._if(fieldVal.ne(JExpr._null())); JBlock setBlock = valCond._then(); final JVar contentIdVal = setBlock.decl(contentIdRef, getVarName(prefix, "contentIdVal"), fieldVal.invoke( "getValue")); JConditional idValCond = setBlock._if(contentIdVal.ne(JExpr._null())); JBlock typeDaoBlock = idValCond._then(); String readDaoName = new StringBuilder(new StringBuilder().append( ("" + typeDef.name().charAt(0)).toLowerCase()).append(typeDef.name().substring(1)).toString()).append( "ReadDao").toString(); JVar typeDao = typeDaoBlock.decl(model.ref(CommonReadDao.class).narrow(typeDef.wildcard()).narrow( String.class), readDaoName, readDaoVar.invoke("get").arg(contentIdVal.invoke("getContent").invoke( "getContentDefinition").invoke("toString"))); JConditional daoValCond = typeDaoBlock._if(typeDao.ne(JExpr._null())); daoValCond._then().add(toBean.invoke(setterName).arg(typeDao.invoke("getById").arg( contentIdVal.invoke("toString")))); } } break; } case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) def.getValueDef(); Set<FieldDef> compositeFields = getAllComposedFields(compositeDataType, types); JClass compFieldVal = model.ref(FieldValue.class).narrow(model.ref(Collection.class).narrow(Field.class)); final JVar fieldVal = valBlock.decl(compFieldVal, new StringBuilder(varName).append("FieldVal").toString(), field.invoke("getValue")); JDefinedClass compositeDefinition = findClass(compositeDataType, currentClass, classes, name); JDefinedClass newCompositeDefintion = findConcreteClass(compositeDefinition, classes); if (compositeDefinition != null && newCompositeDefintion != null) { JBlock validCompVal = valBlock._if(fieldVal.ne(JExpr._null()))._then(); final JVar compositeToBean = validCompVal.decl(compositeDefinition, varName, JExpr._new( newCompositeDefintion)); final JClass ref = model.ref(CompositeFieldValue.class); JVar compositeFromBean = validCompVal.decl(ref, new StringBuilder(varName).append("Val").toString(), JExpr. cast(ref, fieldVal)); String compPrefix = new StringBuilder(varName).append('_').toString(); generateForwardBlocks(compositeFields, validCompVal, compositeFromBean, compositeToBean, model, compositeDefinition, helperClass, classes, types, compPrefix); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); validCompVal.add(toBean.invoke(setterName).arg(compositeToBean)); } break; } case COLLECTION: CollectionDataType collectionDataType = (CollectionDataType) def.getValueDef(); switch (collectionDataType.getItemDataType().getType()) { case BOOLEAN: setCollectionField(valBlock, model, field, Boolean.class, name, toBean, prefix); break; case STRING: setCollectionField(valBlock, model, field, String.class, name, toBean, prefix); break; case ENUM: { JClass itClass = (JClass) ((JClass) currentClass.fields().get(name).type()).getTypeParameters().get(0); JVar resultVal = valBlock.decl(model.ref(Collection.class).narrow(itClass), getVarName(prefix, "beanList"), @@ -902,655 +935,664 @@ public class PojoGeneratorMojo extends AbstractMojo { valBlock.add(toBean.invoke(setterName).arg(resultVal)); } } break; } case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) collectionDataType.getItemDataType(); Set<FieldDef> compositeFields = new LinkedHashSet<FieldDef>(); if (compositeDataType.getEmbeddedContentType() != null) { ContentType currentType = getType(types, compositeDataType.getEmbeddedContentType().getTypeDef()); if (currentType != null) { compositeFields.addAll(getAllFields(currentType, types).values()); } } compositeFields.addAll(compositeDataType.getOwnComposition()); JDefinedClass compositeDefinition = findClass(compositeDataType, currentClass, classes, name); JDefinedClass newCompositeDefintion = findConcreteClass(compositeDefinition, classes); if (compositeDefinition != null && newCompositeDefintion != null) { JVar resultVal = valBlock.decl(model.ref(Collection.class).narrow(newCompositeDefintion), getVarName(prefix, "beanList"), JExpr._new(model.ref(ArrayList.class).narrow(newCompositeDefintion))); final JClass narrowedCollection = model.ref(Collection.class).narrow(FieldValue.class); JVar fieldVal = valBlock.decl(model.ref(FieldValue.class).narrow(narrowedCollection), getVarName(prefix, "fieldVal"), field.invoke("getValue")); JConditional collectionValCond = valBlock._if(fieldVal.ne(JExpr._null())); JBlock validValBlock = collectionValCond._then(); JVar collectionVal = validValBlock.decl(narrowedCollection, getVarName(prefix, "collectionVal"), fieldVal.invoke("getValue")); JConditional validCollectionCond = validValBlock._if(collectionVal.ne(JExpr._null()).cand(collectionVal. invoke("isEmpty").not())); JBlock iterateBlock = validCollectionCond._then(); JVar iterator = iterateBlock.decl(model.ref(Iterator.class).narrow(FieldValue.class), getVarName(prefix, "iterator"), collectionVal.invoke("iterator")); JWhileLoop loop = iterateBlock._while(iterator.invoke("hasNext")); JBlock loopBlock = loop.body(); JVar val = loopBlock.decl(model.ref(FieldValue.class).narrow(model.ref(Collection.class).narrow( Field.class)), getVarName(prefix, "val"), iterator.invoke("next")); final JBlock _then = loopBlock; JBlock validCompVal = _then._if(val.ne(JExpr._null()))._then(); final JVar compositeToBean = validCompVal.decl(compositeDefinition, varName, JExpr._new( newCompositeDefintion)); final JClass ref = model.ref(CompositeFieldValue.class); JVar compositeFromBean = validCompVal.decl(ref, new StringBuilder(varName).append("Val").toString(), JExpr.cast(ref, val)); String compPrefix = new StringBuilder(varName).append('_').toString(); generateForwardBlocks(compositeFields, validCompVal, compositeFromBean, compositeToBean, model, compositeDefinition, helperClass, classes, types, compPrefix); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); validCompVal.add(resultVal.invoke("add").arg(compositeToBean)); valBlock.add(toBean.invoke(setterName).arg(resultVal)); } } } break; default: } } } protected void setCollectionField(JBlock valBlock, JCodeModel model, JVar field, final Class narrowClass, final String name, JVar toBean, String prefix) { final JVar collectionVal = addToCollection(valBlock, model, field, narrowClass, prefix); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); valBlock.add(toBean.invoke(setterName).arg(collectionVal)); } protected String getVarName(String prefix, String literal) { return new StringBuilder(prefix).append(literal).toString(); } protected JVar addToCollection(JBlock valBlock, JCodeModel model, JVar field, final Class narrowClass, String prefix) { JVar resultVal = valBlock.decl(model.ref(Collection.class).narrow(narrowClass), getVarName(prefix, "beanList"), JExpr._new(model.ref(ArrayList.class).narrow(narrowClass))); final JClass narrowedCollection = model.ref(Collection.class).narrow(FieldValue.class); JVar fieldVal = valBlock.decl(model.ref(FieldValue.class).narrow(narrowedCollection), getVarName(prefix, "fieldVal"), field.invoke("getValue")); JConditional collectionValCond = valBlock._if(fieldVal.ne(JExpr._null())); JBlock validValBlock = collectionValCond._then(); JVar collectionVal = validValBlock.decl(narrowedCollection, getVarName(prefix, "collectionVal"), fieldVal.invoke( "getValue")); JConditional validCollectionCond = validValBlock._if(collectionVal.ne(JExpr._null()).cand(collectionVal.invoke( "isEmpty").not())); JBlock iterateBlock = validCollectionCond._then(); JVar iterator = iterateBlock.decl(model.ref(Iterator.class).narrow(FieldValue.class), getVarName(prefix, "iterator"), collectionVal.invoke("iterator")); JWhileLoop loop = iterateBlock._while(iterator.invoke("hasNext")); JBlock loopBlock = loop.body(); JVar val = loopBlock.decl(model.ref(FieldValue.class).narrow(narrowClass), getVarName(prefix, "val"), iterator. invoke("next")); JConditional singleValCond = loopBlock._if(val.ne(JExpr._null())); singleValCond._then().add(resultVal.invoke("add").arg(val.invoke("getValue"))); return resultVal; } protected void setField(JBlock block, JCodeModel model, JVar field, final String name, JVar toBean, Class valType, String prefix) { final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); final String fieldValVar = getVarName(prefix, new StringBuilder(name).append("Val").toString()); JVar fieldVal = block.decl(model.ref(FieldValue.class).narrow(valType), fieldValVar, field.invoke("getValue")); JConditional valCond = block._if(fieldVal.ne(JExpr._null())); JBlock setBlock = valCond._then(); setBlock.add(toBean.invoke(setterName).arg(fieldVal.invoke("getValue"))); } protected void addField(JBlock block, JCodeModel model, JVar field, final String name, JVar toBean, Class valType, String prefix) { final String setterName = "add"; final String fieldValVar = getVarName(prefix, new StringBuilder(name).append("Val").toString()); JVar fieldVal = block.decl(model.ref(FieldValue.class).narrow(valType), fieldValVar, field.invoke("getValue")); JConditional valCond = block._if(fieldVal.ne(JExpr._null())); JBlock setBlock = valCond._then(); setBlock.add(toBean.invoke(setterName).arg(fieldVal.invoke("getValue"))); } protected JDefinedClass findClass(CompositeDataType compositeDataType, JDefinedClass currentClass, Map<ContentTypeId, JDefinedClass> classes, String fieldName) { final String getterSetterSuffix = new StringBuilder().append(("" + fieldName.charAt(0)).toUpperCase()).append(fieldName. substring(1)).toString(); JDefinedClass jType = null; ContentDataType composedOfContent = compositeDataType.getEmbeddedContentType(); if (compositeDataType.getOwnComposition() != null && !compositeDataType.getOwnComposition().isEmpty()) { Iterator<JDefinedClass> compositeFieldClasses = currentClass.classes(); while (compositeFieldClasses.hasNext()) { JDefinedClass innerClass = compositeFieldClasses.next(); if (innerClass.name().equals(getterSetterSuffix)) { jType = innerClass; } } } else if (composedOfContent != null) { jType = classes.get(composedOfContent.getTypeDef()); } return jType; } protected JDefinedClass findConcreteClass(JDefinedClass compositeDefinition, Map<ContentTypeId, JDefinedClass> classes) { if (compositeDefinition.isAbstract()) { for (JDefinedClass clazz : classes.values()) { if (!clazz.isAbstract() && compositeDefinition.isAssignableFrom(clazz)) { return clazz; } else { JDefinedClass inInnerClass = findConcreteInInnerClass(compositeDefinition, clazz); if (inInnerClass != null) { return inInnerClass; } } } return null; } else { return compositeDefinition; } } protected JDefinedClass findConcreteInInnerClass(JDefinedClass compositeDefinition, JDefinedClass clazz) { final Iterator<JDefinedClass> classes = clazz.classes(); while (classes.hasNext()) { JDefinedClass innerClass = classes.next(); if (compositeDefinition.isAssignableFrom(innerClass)) { return innerClass; } else { JDefinedClass inInnerClass = findConcreteInInnerClass(compositeDefinition, innerClass); if (inInnerClass != null) { return inInnerClass; } } } return null; } protected void generateReverseBlocks(Collection<FieldDef> values, JBlock block, JVar fromBean, JVar wContent, JVar contentLoader, JVar fieldDefs, JCodeModel model, JDefinedClass currentClass, Map<ContentTypeId, JDefinedClass> classes, Set<? extends ContentType> types, String prefix) { for (FieldDef def : values) { final String name = def.getName(); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String getterName = new StringBuilder("get").append(getterSetterSuffix).toString(); switch (def.getValueDef().getType()) { case BOOLEAN: { final String methodName = "createBooleanFieldValue"; final Class valClass = Boolean.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case STRING: { final String methodName = "createStringFieldValue"; final Class valClass = String.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case ENUM: { final String methodName = "createStringFieldValue"; final Class valClass = String.class; JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(valClass), getVarName(prefix, "fieldVal"), contentLoader.invoke(methodName)); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(fromBean.invoke(getterName).invoke("name"))); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); break; } case DATE_TIME: { final String methodName = "createDateTimeFieldValue"; final Class valClass = Date.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case INTEGER: { final String methodName = "createIntegerFieldValue"; final Class valClass = Number.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case DOUBLE: { final String methodName = "createDoubleFieldValue"; final Class valClass = Number.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case LONG: { final String methodName = "createLongFieldValue"; final Class valClass = Number.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case OTHER: { final String methodName = "createOtherFieldValue"; final Class valClass = byte[].class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case CONTENT: { JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null()).cand(fromBean.invoke(getterName).invoke("getId").ne(JExpr._null()))))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()). arg(fieldDefs.invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(ContentId.class), getVarName(prefix, "fieldVal"), contentLoader.invoke("createContentFieldValue")); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(JExpr._super().invoke("getContentId").arg(fromBean. invoke(getterName).invoke("getId")).arg(fromBean.invoke(getterName).invoke("getWorkspaceId")))); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); break; } case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) def.getValueDef(); JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null())))._then(); JDefinedClass clazz = findClass(compositeDataType, currentClass, classes, name); JVar input = nonNullBlock.decl(clazz, getVarName(prefix, "compositeField"), fromBean.invoke(getterName)); final JInvocation defArg = fieldDefs.invoke("get").arg(name); JVar fieldDef = nonNullBlock.decl(model.ref(FieldDef.class), getVarName(prefix, "def"), defArg); JVar compositeFieldDefs = nonNullBlock.decl( model.ref(Map.class).narrow(String.class).narrow(FieldDef.class), getVarName(prefix, "compositeFieldDefs"), JExpr.invoke(JExpr.cast(model.ref(CompositeDataType.class), fieldDef.invoke("getValueDef")), "getComposedFieldDefs")); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDef)); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableCompositeFieldValue.class), getVarName(prefix, "fieldVal"), contentLoader.invoke("createCompositeFieldValue")); Collection<FieldDef> defs = getAllComposedFields(compositeDataType, types); generateReverseBlocks(defs, nonNullBlock, input, mutableFieldValue, contentLoader, compositeFieldDefs, model, clazz, classes, types, new StringBuilder(prefix).append(name).append('_').toString()); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); break; } case COLLECTION: CollectionDataType collectionDataType = (CollectionDataType) def.getValueDef(); switch (collectionDataType.getItemDataType().getType()) { case BOOLEAN: { final String methodName = "createBooleanFieldValue"; final Class valClass = Boolean.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case STRING: { final String methodName = "createStringFieldValue"; final Class valClass = String.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case ENUM: { final String methodName = "createStringFieldValue"; final Class valClass = String.class; JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get"). arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(model.ref( Collection.class). narrow(model.ref(FieldValue.class))), getVarName(prefix, "fieldVals"), contentLoader.invoke( "createCollectionFieldValue")); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); JVar collection = nonNullBlock.decl(model.ref(Collection.class).narrow(model.ref(FieldValue.class)), getVarName( prefix, "collectionVar"), JExpr._new(model.ref(ArrayList.class).narrow(FieldValue.class))); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(collection)); final JForLoop forLoop = nonNullBlock._for(); JType itClass = ((JClass) currentClass.fields().get(name).type()).getTypeParameters().get(0); JVar iterator_item = forLoop.init(model.ref(Iterator.class).narrow(itClass), getVarName(prefix, "i"), fromBean.invoke(getterName).invoke("iterator")); forLoop.test(iterator_item.invoke("hasNext")); final JBlock forBody = forLoop.body(); JVar mutableItemFieldValue = forBody.decl(model.ref(MutableFieldValue.class).narrow(valClass), getVarName(prefix, "fieldVal"), contentLoader.invoke(methodName)); forBody.add(mutableItemFieldValue.invoke("setValue").arg(iterator_item.invoke("next").invoke("name"))); forBody.add(collection.invoke("add").arg(mutableItemFieldValue)); break; } case DATE_TIME: { final String methodName = "createDateTimeFieldValue"; final Class valClass = Date.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case INTEGER: { final String methodName = "createIntegerFieldValue"; final Class valClass = Number.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case DOUBLE: { final String methodName = "createDoubleFieldValue"; final Class valClass = Number.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case LONG: { final String methodName = "createLongFieldValue"; final Class valClass = Number.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case OTHER: { final String methodName = "createOtherFieldValue"; final Class valClass = byte[].class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case CONTENT: { JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get"). arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(model.ref( Collection.class).narrow(model.ref(FieldValue.class))), getVarName(prefix, "fieldVals"), contentLoader.invoke("createCollectionFieldValue")); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); JVar collection = nonNullBlock.decl(model.ref(Collection.class).narrow(model.ref(FieldValue.class)), getVarName(prefix, "collectionVar"), JExpr._new(model.ref( ArrayList.class).narrow(FieldValue.class))); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(collection)); final JForLoop forLoop = nonNullBlock._for(); final JClass narrowedDomain = model.ref(AbstractRepositoryDomain.class).narrow(model.ref( PersistentDTO.class).narrow(model.ref(PersistentDTO.class).wildcard()).narrow(String.class).narrow( Long.class).wildcard()); JVar iterator_item = forLoop.init(model.ref(Iterator.class).narrow(narrowedDomain.wildcard()), getVarName( prefix, "i"), fromBean.invoke(getterName).invoke("iterator")); forLoop.test(iterator_item.invoke("hasNext")); final JBlock forBody = forLoop.body(); JVar nextVal = forBody.decl(narrowedDomain, getVarName(prefix, "domain"), iterator_item.invoke( "next")); JVar mutableItemFieldValue = forBody.decl(model.ref(MutableFieldValue.class).narrow(ContentId.class), getVarName(prefix, "fieldVal"), contentLoader.invoke("createContentFieldValue")); forBody.add(mutableItemFieldValue.invoke("setValue").arg(JExpr._super().invoke("getContentId").arg(nextVal. invoke("getId")).arg(nextVal.invoke("getWorkspaceId")))); forBody.add(collection.invoke("add").arg(mutableItemFieldValue)); break; } case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) collectionDataType.getItemDataType(); JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get"). arg(name).ne(JExpr._null())))._then(); JDefinedClass clazz = findClass(compositeDataType, currentClass, classes, name); final JInvocation defArg = fieldDefs.invoke("get").arg(name); JVar fieldDef = nonNullBlock.decl(model.ref(FieldDef.class), getVarName(prefix, "def"), defArg); JVar compositeFieldDefs = nonNullBlock.decl(model.ref(Map.class).narrow(String.class).narrow( FieldDef.class), getVarName(prefix, "compositeFieldDefs"), JExpr.invoke(JExpr.cast(model.ref(CompositeDataType.class), JExpr.invoke(JExpr.cast(model.ref( CollectionDataType.class), fieldDef.invoke("getValueDef")), "getItemDataType")), "getComposedFieldDefs")); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg( fieldDef)); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(model.ref( Collection.class).narrow(model.ref(FieldValue.class))), getVarName(prefix, "fieldVals"), contentLoader.invoke("createCollectionFieldValue")); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); JVar collection = nonNullBlock.decl(model.ref(Collection.class).narrow(model.ref(FieldValue.class)), getVarName(prefix, "collectionVar"), JExpr._new(model.ref( ArrayList.class).narrow(FieldValue.class))); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(collection)); final JForLoop forLoop = nonNullBlock._for(); final JClass narrowedDomain = clazz; JVar iterator_item = forLoop.init(model.ref(Iterator.class).narrow(narrowedDomain), getVarName( prefix, "i"), fromBean.invoke(getterName).invoke("iterator")); forLoop.test(iterator_item.invoke("hasNext")); final JBlock forBody = forLoop.body(); JVar nextVal = forBody.decl(narrowedDomain, getVarName(prefix, "domain"), iterator_item.invoke( "next")); JVar mutableItemFieldValue = forBody.decl(model.ref(MutableCompositeFieldValue.class), getVarName(prefix, "fieldVal"), contentLoader.invoke("createCompositeFieldValue")); Collection<FieldDef> defs = getAllComposedFields(compositeDataType, types); generateReverseBlocks(defs, forBody, nextVal, mutableItemFieldValue, contentLoader, compositeFieldDefs, model, clazz, classes, types, new StringBuilder(prefix).append(name).append('_').toString()); forBody.add(collection.invoke("add").arg(mutableItemFieldValue)); } } break; default: } } } protected void setSimpleField(JBlock block, JVar fromBean, JVar wContent, final String getterName, JVar fieldDefs, final String name, JCodeModel model, JVar contentLoader, final Class valClass, final String methodName, String prefix) { JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(valClass), getVarName(prefix, "fieldVal"), contentLoader.invoke(methodName)); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(fromBean.invoke(getterName))); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); } protected void setSimpleMultiField(JBlock block, JVar fromBean, JVar wContent, final String getterName, JVar fieldDefs, final String name, JCodeModel model, JVar contentLoader, final Class valClass, final String methodName, String prefix) { JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(model.ref(Collection.class). narrow(model.ref(FieldValue.class))), getVarName(prefix, "fieldVals"), contentLoader.invoke( "createCollectionFieldValue")); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); JVar collection = nonNullBlock.decl(model.ref(Collection.class).narrow(model.ref(FieldValue.class)), getVarName( prefix, "collectionVar"), JExpr._new(model.ref(ArrayList.class).narrow(FieldValue.class))); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(collection)); final JForLoop forLoop = nonNullBlock._for(); JVar iterator_item = forLoop.init(model.ref(Iterator.class).narrow(model.ref(valClass).wildcard()), getVarName( prefix, "i"), fromBean.invoke(getterName).invoke("iterator")); forLoop.test(iterator_item.invoke("hasNext")); final JBlock forBody = forLoop.body(); JVar mutableItemFieldValue = forBody.decl(model.ref(MutableFieldValue.class).narrow(valClass), getVarName(prefix, "fieldVal"), contentLoader.invoke(methodName)); forBody.add(mutableItemFieldValue.invoke("setValue").arg(iterator_item.invoke("next"))); forBody.add(collection.invoke("add").arg(mutableItemFieldValue)); } protected void generateMasterModule(Map<ContentTypeId, JDefinedClass> modules, JCodeModel codeModel, String[] wId) throws JClassAlreadyExistsException { final String moduleClassName = new StringBuilder(packageForGuiceMasterModule).append(".MasterModule").toString(); final JDefinedClass moduleClass = codeModel._class(moduleClassName); moduleClass._extends(codeModel.ref(AbstractModule.class)); JMethod configureMethod = moduleClass.method(JMod.PUBLIC, JCodeModel.boxToPrimitive.get(Void.class), "configure"); + JClass namesClass = codeModel.ref(Names.class); JBlock block = configureMethod.body(); if (typeFiles != null && !typeFiles.isEmpty()) { - JClass namesClass = codeModel.ref(Names.class); final JClass stringClassType = codeModel.ref(String.class); final JClass systemClass = codeModel.ref(System.class); JExpression stringClass = stringClassType.dotclass(); JVar workspaceNamespace = block.decl(stringClassType, "workspaceNamespace", systemClass.staticInvoke("getProperty").arg( "com.smartitengineering.cms.repo.workspace.namespace").arg(wId[0])); JVar workspaceName = block.decl(stringClassType, "workspaceName", systemClass.staticInvoke("getProperty").arg( "com.smartitengineering.cms.repo.workspace.name").arg(wId[1])); block.add(JExpr.invoke("bind").arg(stringClass).invoke("annotatedWith").arg(namesClass.staticInvoke("named"). arg("cmsWorkspaceNamespace")).invoke("toInstance").arg(workspaceNamespace)); block.add(JExpr.invoke("bind").arg(stringClass).invoke("annotatedWith").arg(namesClass.staticInvoke("named"). arg("cmsWorkspaceName")).invoke("toInstance").arg(workspaceName)); { JClass typeLiteral = codeModel.ref(TypeLiteral.class); final JClass narrowedTypesLiteral = typeLiteral.narrow(codeModel.ref(List.class).narrow(String.class)); final JDefinedClass stringListType = moduleClass._class("InitializationContentTypes"); stringListType._extends(narrowedTypesLiteral); JVar typesList = block.decl(codeModel.ref(List.class).narrow(String.class), "contentTypes", JExpr._new(codeModel.ref(ArrayList.class).narrow(String.class))); for (String typeFile : typeFiles) { block.add(typesList.invoke("add").arg(typeFile)); } block.add(JExpr.invoke("bind").arg(JExpr._new(stringListType)).invoke( "annotatedWith").arg(namesClass.staticInvoke("named").arg("contentTypePath")).invoke("toInstance").arg( typesList)); JVar initVar = block.decl(codeModel.ref(Initializer.class), "initializer", JExpr._new(codeModel.ref(Initializer.class)).arg(workspaceNamespace).arg(workspaceName). arg(typesList)); block.add(initVar.invoke("init")); } } for (JDefinedClass clazz : modules.values()) { block.invoke("install").arg(JExpr._new(clazz)); } + if (transactionEnabled) { + JClass booleanClass = codeModel.ref(Boolean.class); + JClass bigBoolClass = codeModel.ref(Boolean.class); + JClass txImplModuleClass = codeModel.ref(TransactionImplModule.class); + block.add(JExpr.invoke("bind").arg(booleanClass.dotclass()).invoke("annotatedWith").arg(namesClass.staticInvoke( + "named").arg("nonIsolatedLookupEnabled")).invoke("toInstance").arg(bigBoolClass.staticInvoke("parseBoolean"). + arg(String.valueOf(nonIsolatedTransactionAllowed)))); + block.invoke("install").arg(JExpr._new(txImplModuleClass)); + } } private void generateAssociationIoCForFields(Collection<FieldDef> defs, JCodeModel model, JDefinedClass stringType, JClass typeLiteral, JDefinedClass moduleClass, JBlock block, Set<MutableContentType> types, Map<ContentTypeId, JDefinedClass> classes, String namePrefix, final Set<ContentTypeId> idsConfigdFor) throws JClassAlreadyExistsException { for (FieldDef def : defs) { final ContentDataType contentDataType; final String probablePrefix = new StringBuilder(namePrefix).append(def.getName().substring(0, 1).toUpperCase()). append(def.getName().substring(1)).toString(); switch (def.getValueDef().getType()) { case CONTENT: contentDataType = (ContentDataType) def.getValueDef(); break; case COLLECTION: CollectionDataType collectionDataType = (CollectionDataType) def.getValueDef(); if (collectionDataType.getItemDataType().getType().equals(FieldValueType.CONTENT)) { contentDataType = (ContentDataType) collectionDataType.getItemDataType(); } else if (collectionDataType.getItemDataType().getType().equals(FieldValueType.COMPOSITE)) { CompositeDataType compositeDataType = (CompositeDataType) collectionDataType.getItemDataType(); generateAssociationIoCForFields(getAllComposedFields(compositeDataType, types), model, stringType, typeLiteral, moduleClass, block, types, classes, probablePrefix, idsConfigdFor); contentDataType = null; } else { contentDataType = null; } break; case COMPOSITE: CompositeDataType compositeDataType = (CompositeDataType) def.getValueDef(); generateAssociationIoCForFields(getAllComposedFields(compositeDataType, types), model, stringType, typeLiteral, moduleClass, block, types, classes, probablePrefix, idsConfigdFor); default: contentDataType = null; break; } if (contentDataType != null && !idsConfigdFor.contains(contentDataType.getTypeDef())) { idsConfigdFor.add(contentDataType.getTypeDef()); JBlock mapBindingBlock = block.block(); JDefinedClass definedClass = classes.get(contentDataType.getTypeDef()); final JClass assocType = model.ref(CommonReadDao.class).narrow(definedClass.wildcard()).narrow(String.class); final JClass narrowedReadTypeLiteral = typeLiteral.narrow(assocType); final JDefinedClass assocDaoTypeLit = moduleClass._class(new StringBuilder(probablePrefix).append("DaoType"). toString()); assocDaoTypeLit._extends(narrowedReadTypeLiteral); JVar mapBinderVar = mapBindingBlock.decl(model.ref(MapBinder.class).narrow(String.class).narrow(assocType), "mapBinder", model.ref(MapBinder.class).staticInvoke("newMapBinder"). arg(JExpr._this().invoke("binder")).arg(JExpr._new(stringType)).arg(JExpr._new(assocDaoTypeLit))); Collection<ContentType> concreteInstances = findConcreteInstanceOf(contentDataType.getTypeDef(), types); for (ContentType concreteInstance : concreteInstances) { JDefinedClass concClass = classes.get(concreteInstance.getContentTypeID()); if (concClass == null) { continue; } final JClass concType = model.ref(CommonReadDao.class).narrow(concClass).narrow(String.class); final JClass narrowedConcReadTypeLiteral = typeLiteral.narrow(concType); final String name = concreteInstance.getContentTypeID().getName(); final JDefinedClass concDaoTypeLit = moduleClass._class(new StringBuilder(probablePrefix).append(name. substring(0, 1).toUpperCase()).append(name.substring(1)).append("DaoType"). toString()); concDaoTypeLit._extends(narrowedConcReadTypeLiteral); mapBindingBlock.add(mapBinderVar.invoke("addBinding").arg(JExpr.lit(concreteInstance.getContentTypeID(). toString())).invoke("to").arg(JExpr._new(concDaoTypeLit))); } } } } private Collection<ContentType> findConcreteInstanceOf(final ContentTypeId typeDef, final Collection<? extends ContentType> types) { if (types == null || typeDef == null || types.isEmpty()) { return Collections.emptyList(); } final List<ContentType> instanceOfTypes = new ArrayList<ContentType>(); final Map<ContentTypeId, ContentType> typeMap = new HashMap<ContentTypeId, ContentType>(); for (ContentType type : types) { typeMap.put(type.getContentTypeID(), type); } for (ContentType type : types) { if (type.getDefinitionType().equals(DefinitionType.CONCRETE_TYPE)) { boolean isInstanceOf = isInstanceOf(type, typeDef, typeMap); if (isInstanceOf) { instanceOfTypes.add(type); } } } return instanceOfTypes; } private boolean isInstanceOf(ContentType type, final ContentTypeId typeDef, Map<ContentTypeId, ContentType> types) { boolean isInstanceOf = false; if (type.getContentTypeID().equals(typeDef)) { isInstanceOf = true; } if (!isInstanceOf) { ContentTypeId parentId = type.getParent(); if (!isInstanceOf && parentId != null && types.get(parentId) != null) { isInstanceOf = isInstanceOf(types.get(parentId), typeDef, types); } } return isInstanceOf; } }
SmartITEngineering/smart-cms
a02ac475fd28cbabcda02d3d83167e82822807ee
Add singleton annotation on DAO Impls and re-use class injection
diff --git a/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/RepositoryDaoImpl.java b/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/RepositoryDaoImpl.java index f08d0e7..5fe15ad 100644 --- a/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/RepositoryDaoImpl.java +++ b/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/RepositoryDaoImpl.java @@ -1,543 +1,545 @@ package com.smartitengineering.cms.repo.dao.impl; import com.google.inject.Inject; +import com.google.inject.Singleton; import com.smartitengineering.cms.api.common.SearchResult; import com.smartitengineering.cms.api.content.Content; import com.smartitengineering.cms.api.content.ContentId; import com.smartitengineering.cms.api.content.Filter; import com.smartitengineering.cms.api.factory.SmartContentAPI; import com.smartitengineering.cms.api.factory.content.WriteableContent; import com.smartitengineering.cms.api.type.CollectionDataType; import com.smartitengineering.cms.api.type.CompositeDataType; import com.smartitengineering.cms.api.type.ContentDataType; import com.smartitengineering.cms.api.type.ContentTypeId; import com.smartitengineering.cms.api.type.DataType; import com.smartitengineering.cms.api.type.FieldDef; import com.smartitengineering.cms.api.type.FieldValueType; import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.dao.common.CommonDao; import com.smartitengineering.dao.common.queryparam.BasicCompoundQueryParameter; import com.smartitengineering.dao.common.queryparam.BiOperandQueryParameter; import com.smartitengineering.dao.common.queryparam.CompositionQueryParameter; import com.smartitengineering.dao.common.queryparam.MatchMode; import com.smartitengineering.dao.common.queryparam.OperatorType; import com.smartitengineering.dao.common.queryparam.Order; import com.smartitengineering.dao.common.queryparam.QueryParameter; import com.smartitengineering.dao.common.queryparam.QueryParameterCastHelper; import com.smartitengineering.dao.common.queryparam.QueryParameterFactory; import com.smartitengineering.dao.common.queryparam.QueryParameterWithPropertyName; import com.smartitengineering.dao.common.queryparam.SimpleNameValueQueryParameter; import com.smartitengineering.dao.common.queryparam.StringLikeQueryParameter; import com.smartitengineering.dao.common.queryparam.UniOperandQueryParameter; import com.smartitengineering.dao.common.queryparam.ValueOnlyQueryParameter; import com.smartitengineering.domain.PersistentDTO; import com.smartitengineering.util.bean.adapter.GenericAdapter; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author imyousuf */ +@Singleton public class RepositoryDaoImpl<T extends AbstractRepositoryDomain<? extends PersistentDTO>> implements CommonDao<T, String>, ExtendedReadDao<T, String> { @Inject private WorkspaceId defaultContainerWorkspace; @Inject private GenericAdapter<Content, T> adapter; - protected final Class<? extends T> beanClass; + protected final Class<T> beanClass; private ContentTypeId contentTypeId; protected transient final Logger logger = LoggerFactory.getLogger(getClass()); private static final String SOLR_DATE_FORMAT = DateFormatUtils.ISO_DATETIME_FORMAT.getPattern() + "'Z'"; @Inject - public RepositoryDaoImpl(Class<? extends T> entityClass) { + public RepositoryDaoImpl(Class<T> entityClass) { beanClass = entityClass; } protected ContentTypeId getContentTypeId() { if (contentTypeId == null) { String typeNS = beanClass.getPackage().getName(); String typeName = beanClass.getSimpleName(); contentTypeId = SmartContentAPI.getInstance().getContentTypeLoader().createContentTypeId(defaultContainerWorkspace, typeNS, typeName); } return contentTypeId; } protected Filter getDefaultFilter() { Filter filter = SmartContentAPI.getInstance().getContentLoader().craeteFilter(); filter.addContentTypeToFilter(getContentTypeId()); filter.setWorkspaceId(defaultContainerWorkspace); filter.setFriendliesIncluded(true); return filter; } protected final Class<? extends T> initializeEntityClassFromGenerics() { Class<? extends T> extractedEntityClass = null; try { Type paramType = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; if (paramType instanceof ParameterizedType) { paramType = ((ParameterizedType) paramType).getRawType(); } Class<T> pesistenceRegistryClass = paramType instanceof Class ? (Class<T>) paramType : null; if (logger.isDebugEnabled()) { logger.debug("Entity class predicted to: " + pesistenceRegistryClass.toString()); } extractedEntityClass = pesistenceRegistryClass; } catch (Exception ex) { logger.warn("Could not predict entity class ", ex); } return extractedEntityClass; } protected ContentId getContentId(String id) { final ContentId cId; if (id.contains(":")) { String[] idTokens = id.split(":"); if (idTokens.length != 3) { final byte[] bytesUtf8 = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(idTokens[0]); cId = SmartContentAPI.getInstance().getContentLoader().createContentId(defaultContainerWorkspace, bytesUtf8); } else { final byte[] bytesUtf8 = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(idTokens[2]); cId = SmartContentAPI.getInstance().getContentLoader().createContentId(SmartContentAPI.getInstance(). getWorkspaceApi().createWorkspaceId(idTokens[0], idTokens[1]), bytesUtf8); } } else { final byte[] bytesUtf8 = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(id); cId = SmartContentAPI.getInstance().getContentLoader().createContentId(defaultContainerWorkspace, bytesUtf8); } if (logger.isDebugEnabled()) { logger.debug("Attempting to read content with passed ID " + id + " and reading " + cId); } return cId; } public Set<T> getByIds(List<String> ids) { Set<T> cs = new LinkedHashSet<T>(); for (String id : ids) { T bean = getById(id); if (bean != null) { cs.add(bean); } } return cs; } public T getById(String id) { ContentId contentId = getContentId(id); Content content = SmartContentAPI.getInstance().getContentLoader().loadContent(contentId); if (content == null) { return null; } else { return adapter.convert(content); } } public Set<T> getAll() { return new LinkedHashSet<T>(searchCms(getDefaultFilter(), true)); } public T getSingle(List<QueryParameter> queries) { Filter filter = getDefaultFilter(); processQueryParams(filter, queries); filter.setMaxContents(1); List<T> result = searchCms(filter, false); if (!result.isEmpty()) { return result.get(0); } return null; } public List<T> getList(List<QueryParameter> queries) { return searchCms(processQueryParams(getDefaultFilter(), queries), false); } protected long countResults(Filter filter) { filter.setStartFrom(0); filter.setMaxContents(0); SearchResult<Content> searchResult = SmartContentAPI.getInstance().getContentLoader().search(filter); return searchResult.getTotalResultsCount(); } protected List<T> searchCms(Filter filter, boolean getAll) { if (getAll) { filter.setStartFrom(0); filter.setMaxContents(10); } SearchResult<Content> searchResult = SmartContentAPI.getInstance().getContentLoader().search(filter); final List<T> result; result = new ArrayList<T>(); Collection<Content> collectionResult = searchResult.getResult(); if (collectionResult != null && !collectionResult.isEmpty()) { result.addAll(adapter.convert(collectionResult.toArray(new Content[collectionResult.size()]))); } if (getAll) { long totalResult = searchResult.getTotalResultsCount(); long cTotal = result.size(); if (totalResult > 10) { while (cTotal < totalResult) { filter.setStartFrom((int) cTotal); filter.setMaxContents(20); searchResult = SmartContentAPI.getInstance().getContentLoader().search(filter); collectionResult = searchResult.getResult(); if (collectionResult != null && !collectionResult.isEmpty()) { result.addAll(adapter.convert(collectionResult.toArray(new Content[collectionResult.size()]))); cTotal += collectionResult.size(); } else { break; } } } } return result; } protected Filter processQueryParams(Filter filter, List<QueryParameter> queries) { filter.setFieldParamsEscaped(true); List<QueryParameter> cQueries = new ArrayList<QueryParameter>(queries); Iterator<QueryParameter> pIterator = cQueries.iterator(); while (pIterator.hasNext()) { QueryParameter parameter = pIterator.next(); switch (parameter.getParameterType()) { case PARAMETER_TYPE_MAX_RESULT: { ValueOnlyQueryParameter<Integer> param = QueryParameterCastHelper.VALUE_PARAM_HELPER.cast(parameter); filter.setMaxContents(param.getValue()); pIterator.remove(); break; } case PARAMETER_TYPE_FIRST_RESULT: { ValueOnlyQueryParameter<Integer> param = QueryParameterCastHelper.VALUE_PARAM_HELPER.cast(parameter); filter.setStartFrom(param.getValue()); pIterator.remove(); break; } } } List<QueryParameter> params = processQueryParams(cQueries, "", getContentTypeId().getContentType().getFieldDefs()); filter.addFieldFilter(params.toArray(new QueryParameter[params.size()])); return filter; } protected List<QueryParameter> processQueryParams(final Collection<QueryParameter> queries, final String prefix, final Map<String, FieldDef> defs) { final List<QueryParameter> params = new ArrayList<QueryParameter>(); for (QueryParameter parameter : queries) { switch (parameter.getParameterType()) { case PARAMETER_TYPE_CONJUNCTION: { BasicCompoundQueryParameter compoundQueryParameter = (BasicCompoundQueryParameter) parameter; final List<QueryParameter> conParams = processQueryParams(compoundQueryParameter.getNestedParameters(), prefix, defs); if (!conParams.isEmpty()) { params.add( QueryParameterFactory.getConjunctionParam(conParams.toArray(new QueryParameter[conParams.size()]))); } break; } case PARAMETER_TYPE_DISJUNCTION: { BasicCompoundQueryParameter compoundQueryParameter = (BasicCompoundQueryParameter) parameter; final List<QueryParameter> disParams = processQueryParams(compoundQueryParameter.getNestedParameters(), prefix, defs); if (!disParams.isEmpty()) { params.add( QueryParameterFactory.getDisjunctionParam(disParams.toArray(new QueryParameter[disParams.size()]))); } break; } case PARAMETER_TYPE_PROPERTY: { QueryParameterWithPropertyName para = (QueryParameterWithPropertyName) parameter; FieldDef def = defs.get(para.getPropertyName()); final QueryParameter fieldQuery = addQueryForProperty(parameter, def, prefix); if (fieldQuery != null) { params.add(fieldQuery); } break; } case PARAMETER_TYPE_NESTED_PROPERTY: { CompositionQueryParameter para = QueryParameterCastHelper.COMPOSITION_PARAM_FOR_NESTED_TYPE.cast(parameter); FieldDef def = defs.get(para.getPropertyName()); final DataType type; if (def.getValueDef().getType().equals(FieldValueType.COLLECTION)) { type = ((CollectionDataType) def.getValueDef()).getItemDataType(); } else { type = def.getValueDef(); } if (type.getType().equals(FieldValueType.CONTENT)) { ContentDataType dataType = (ContentDataType) type; final StringBuilder prefixBldr = new StringBuilder(); if (StringUtils.isNotBlank(prefix)) { prefixBldr.append(prefix).append('_'); } final String fieldName = SmartContentAPI.getInstance().getContentTypeLoader(). getSearchFieldNameWithoutTypeSpecifics(def); if (StringUtils.isNotBlank(fieldName)) { params.addAll(processQueryParams(para.getNestedParameters(), prefixBldr.append(fieldName).toString(), dataType.getTypeDef().getContentType().getFieldDefs())); } } else if (type.getType().equals(FieldValueType.COMPOSITE)) { CompositeDataType dataType = (CompositeDataType) type; params.addAll(processQueryParams(para.getNestedParameters(), prefix, dataType.getComposedFieldDefs())); } break; } case PARAMETER_TYPE_ORDER_BY: { SimpleNameValueQueryParameter<Order> orderBy = QueryParameterCastHelper.SIMPLE_PARAM_HELPER.cast(parameter); final FieldDef def = defs.get(orderBy.getPropertyName()); if (def != null) { String fieldName = SmartContentAPI.getInstance().getContentTypeLoader().getSearchFieldName(def); if (StringUtils.isNotBlank(fieldName)) { params.add(QueryParameterFactory.getOrderByParam(new StringBuilder(prefix).append(fieldName). toString(), orderBy.getValue())); } } break; } } } return params; } protected QueryParameter addQueryForProperty(QueryParameter parameter, FieldDef def, final String prefix) { if (def != null) { String fieldName = SmartContentAPI.getInstance().getContentTypeLoader().getSearchFieldName(def); if (StringUtils.isNotBlank(fieldName)) { String searchFieldName = new StringBuilder(prefix).append(fieldName).toString(); final String query; if (parameter instanceof StringLikeQueryParameter) { StringLikeQueryParameter queryParameter = (StringLikeQueryParameter) parameter; MatchMode mode = queryParameter.getMatchMode(); if (mode == null) { mode = MatchMode.START; } switch (mode) { case START: { query = new StringBuilder(formatInSolrFormat(queryParameter.getValue())).append('*').toString(); break; } case EXACT: { query = queryParameter.getValue(); break; } case END: { query = new StringBuilder('*').append(formatInSolrFormat(queryParameter.getValue())).toString(); break; } default: case ANYWHERE: { query = new StringBuilder('*').append(formatInSolrFormat(queryParameter.getValue())).append('*').toString(); break; } } } else { query = generateQuery(parameter); } if (StringUtils.isNotBlank(query)) { final QueryParameter<String> stringLikePropertyParam = QueryParameterFactory.getStringLikePropertyParam(searchFieldName, query); return stringLikePropertyParam; } } } return null; } protected <T> String generateQuery(QueryParameter<T> creationDateFilter) { StringBuilder query = new StringBuilder(); String dateQuery = ""; switch (creationDateFilter.getParameterType()) { case PARAMETER_TYPE_PROPERTY: if (creationDateFilter instanceof UniOperandQueryParameter) { UniOperandQueryParameter<T> param = (UniOperandQueryParameter<T>) creationDateFilter; switch (param.getOperatorType()) { case OPERATOR_EQUAL: dateQuery = formatInSolrFormat(param.getValue()); break; case OPERATOR_LESSER: query.insert(0, "NOT "); dateQuery = "[" + formatInSolrFormat(param.getValue()) + " TO *]"; // dateQuery = "-[" + param.getValue() + " TO *]"; break; case OPERATOR_GREATER_EQUAL: dateQuery = "[" + formatInSolrFormat(param.getValue()) + " TO *]"; break; case OPERATOR_GREATER: query.insert(0, "NOT "); dateQuery = "[* TO " + formatInSolrFormat(param.getValue()) + "]"; // dateQuery = "-[* TO " + param.getValue() + "]"; break; case OPERATOR_LESSER_EQUAL: dateQuery = "[* TO " + formatInSolrFormat(param.getValue()) + "]"; break; default: dateQuery = "[* TO *]"; } } if (creationDateFilter instanceof BiOperandQueryParameter) { BiOperandQueryParameter<T> param = (BiOperandQueryParameter<T>) creationDateFilter; if (param.getOperatorType().equals(OperatorType.OPERATOR_BETWEEN)) { dateQuery = "[" + formatInSolrFormat(param.getFirstValue()) + " TO " + formatInSolrFormat(param. getSecondValue()) + "]"; } } break; default: UniOperandQueryParameter<Date> param = (UniOperandQueryParameter<Date>) creationDateFilter; dateQuery = param.getPropertyName() + ": [* TO *]"; break; } query.append(dateQuery); return query.toString(); } protected <T> String formatInSolrFormat(T value) { if (value instanceof Date) { return formatInSolrFormat((Date) value); } if (value instanceof Integer) { return formatInSolrFormat((Integer) value); } if (value instanceof Long) { return formatInSolrFormat((Long) value); } if (value instanceof Double) { return formatInSolrFormat((Double) value); } if (value instanceof Boolean) { return formatInSolrFormat((Boolean) value); } if (value instanceof String) { return formatInSolrFormat((String) value); } return null; } protected String formatInSolrFormat(Date value) { return DateFormatUtils.formatUTC(value, SOLR_DATE_FORMAT); } protected String formatInSolrFormat(Integer value) { return String.valueOf(value); } protected String formatInSolrFormat(Long value) { return String.valueOf(value); } protected String formatInSolrFormat(Double value) { return String.valueOf(value); } protected String formatInSolrFormat(Boolean value) { return String.valueOf(value); } protected String formatInSolrFormat(String value) { return SmartContentAPI.getInstance().getContentLoader().escapeStringForSearch(value); } public <OtherTemplate> OtherTemplate getOther(List<QueryParameter> query) { throw new UnsupportedOperationException("Not supported yet."); } public <OtherTemplate> List<OtherTemplate> getOtherList(List<QueryParameter> query) { throw new UnsupportedOperationException("Not supported yet."); } public T getSingle(QueryParameter... query) { return getSingle(Arrays.asList(query)); } public List<T> getList(QueryParameter... query) { return getList(Arrays.asList(query)); } public <OtherTemplate> OtherTemplate getOther(QueryParameter... query) { return this.<OtherTemplate>getOther(Arrays.asList(query)); } public <OtherTemplate> List<OtherTemplate> getOtherList(QueryParameter... query) { return this.<OtherTemplate>getOtherList(Arrays.asList(query)); } public void save(T... states) { for (T state : states) { Content content = adapter.convertInversely(state); if (content != null) { WriteableContent wContent = SmartContentAPI.getInstance().getContentLoader().getWritableContent(content); try { wContent.put(); } catch (Exception ex) { logger.warn("Could not save content ", ex); throw new RuntimeException(ex); } } } } public void update(T... states) { for (T state : states) { Content content = adapter.convertInversely(state); if (content != null) { WriteableContent wContent = SmartContentAPI.getInstance().getContentLoader().getWritableContent(content); try { wContent.put(); } catch (Exception ex) { logger.warn("Could not save content ", ex); throw new RuntimeException(ex); } } } } public void delete(T... states) { for (T state : states) { Content content = adapter.convertInversely(state); if (content != null) { WriteableContent wContent = SmartContentAPI.getInstance().getContentLoader().getWritableContent(content); try { wContent.delete(); } catch (Exception ex) { logger.warn("Could not save content ", ex); throw new RuntimeException(ex); } } } } public long count(QueryParameter... params) { return countResults(processQueryParams(getDefaultFilter(), Arrays.asList(params))); } } diff --git a/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/CommonTxDao.java b/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/CommonTxDao.java index 316a506..b2fb703 100644 --- a/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/CommonTxDao.java +++ b/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/CommonTxDao.java @@ -1,187 +1,189 @@ package com.smartitengineering.cms.repo.dao.impl.tx; import com.google.inject.Inject; +import com.google.inject.Singleton; import com.smartitengineering.cms.repo.dao.impl.AbstractRepositoryDomain; import com.smartitengineering.cms.repo.dao.tx.Transaction; import com.smartitengineering.cms.repo.dao.tx.TransactionManager; import com.smartitengineering.dao.common.CommonDao; import com.smartitengineering.dao.common.CommonReadDao; import com.smartitengineering.dao.common.CommonWriteDao; import com.smartitengineering.dao.common.queryparam.QueryParameter; import com.smartitengineering.domain.PersistentDTO; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * Implements the Common CMS Content Repo Trasnactionable DAO. * @author imyousuf */ +@Singleton public class CommonTxDao<T extends AbstractRepositoryDomain<? extends PersistentDTO>> implements CommonDao<T, String> { private final CommonReadDao<T, String> readDao; private final CommonWriteDao<T> writeDao; private final TransactionService txService; private final TransactionManager txManager; private final TransactionInMemoryCache memCache; private final Class<T> entityClass; @Inject public CommonTxDao(@Transactionable CommonReadDao<T, String> readDao, @Transactionable CommonWriteDao<T> writeDao, TransactionService txService, TransactionManager txManager, TransactionInMemoryCache memCache, Class<T> entityClass) { this.readDao = readDao; this.writeDao = writeDao; this.txService = txService; this.txManager = txManager; this.memCache = memCache; this.entityClass = entityClass; } public Set<T> getByIds(List<String> ids) { LinkedHashSet<T> set = new LinkedHashSet<T>(); if (ids != null) { for (String id : ids) { T dto = this.getById(id); set.add(dto); } } return set; } public T getById(String id) { if (isWithinTransaction()) { Transaction tx = txManager.getCurrentTransaction(); T txDto = null; Pair<TransactionStoreKey, TransactionStoreValue> pair; if (tx.isIsolatedTransaction()) { pair = memCache.getValueForIsolatedTransaction(tx.getId(), entityClass.getName(), id); } else { pair = memCache.getValueForNonIsolatedTransaction(entityClass.getName(), id); } // It means the value is either deleted earlier in the transaction or has to been saved. if (pair != null && (pair.getValue().getOpState() == null || OpState.DELETE.equals(pair.getValue().getOpState()))) { return null; } if (pair == null) { return this.readDao.getById(id); } else { txDto = pair.getValue().<T>getCurrentState(); return txDto; } } else { return this.readDao.getById(id); } } public T getSingle(QueryParameter... query) { return this.getSingle(Arrays.asList(query)); } public T getSingle(List<QueryParameter> query) { T dto = readDao.getSingle(query); if (isWithinTransaction()) { if (dto != null) { return this.getById(dto.getId()); } else { return null; } } else { return dto; } } public Set<T> getAll() { return this.readDao.getAll(); } public List<T> getList(List<QueryParameter> query) { return this.readDao.getList(query); } public <OtherTemplate> OtherTemplate getOther(List<QueryParameter> query) { return this.readDao.<OtherTemplate>getOther(query); } public <OtherTemplate> List<OtherTemplate> getOtherList(List<QueryParameter> query) { return this.readDao.<OtherTemplate>getOtherList(query); } public List<T> getList(QueryParameter... query) { return this.readDao.getList(query); } public <OtherTemplate> OtherTemplate getOther(QueryParameter... query) { return this.readDao.<OtherTemplate>getOther(query); } public <OtherTemplate> List<OtherTemplate> getOtherList(QueryParameter... query) { return this.readDao.<OtherTemplate>getOtherList(query); } public void save(T... states) { if (states == null) { return; } if (isWithinTransaction()) { for (T state : states) { this.txService.save(getTxElement(state)); } } else { this.writeDao.save(states); } } public void update(T... states) { if (states == null) { return; } if (isWithinTransaction()) { for (T state : states) { this.txService.update(getTxElement(state)); } } else { this.writeDao.update(states); } } public void delete(T... states) { if (states == null) { return; } if (isWithinTransaction()) { for (T state : states) { this.txService.delete(getTxElement(state)); } } else { this.writeDao.delete(states); } } private boolean isWithinTransaction() { return txManager.getCurrentTransaction() != null; } private TransactionElement<T> getTxElement(T dto) { Transaction tx = txManager.getCurrentTransaction(); if (tx == null) { return null; } TransactionElement<T> element = new TransactionElement<T>(); element.setDto(dto); element.setObjectType(dto.getClass()); element.setReadDao(readDao); element.setWriteDao(writeDao); element.setTxId(tx.getId()); return element; } }
SmartITEngineering/smart-cms
98619c47c500394a2c48c2a4d0dd5cf5af6902e5
Add generics during invocation to work around JavaC bug on Jenkins
diff --git a/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/CommonTxDao.java b/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/CommonTxDao.java index fc6f3c0..316a506 100644 --- a/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/CommonTxDao.java +++ b/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/CommonTxDao.java @@ -1,187 +1,187 @@ package com.smartitengineering.cms.repo.dao.impl.tx; import com.google.inject.Inject; import com.smartitengineering.cms.repo.dao.impl.AbstractRepositoryDomain; import com.smartitengineering.cms.repo.dao.tx.Transaction; import com.smartitengineering.cms.repo.dao.tx.TransactionManager; import com.smartitengineering.dao.common.CommonDao; import com.smartitengineering.dao.common.CommonReadDao; import com.smartitengineering.dao.common.CommonWriteDao; import com.smartitengineering.dao.common.queryparam.QueryParameter; import com.smartitengineering.domain.PersistentDTO; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * Implements the Common CMS Content Repo Trasnactionable DAO. * @author imyousuf */ public class CommonTxDao<T extends AbstractRepositoryDomain<? extends PersistentDTO>> implements CommonDao<T, String> { private final CommonReadDao<T, String> readDao; private final CommonWriteDao<T> writeDao; private final TransactionService txService; private final TransactionManager txManager; private final TransactionInMemoryCache memCache; private final Class<T> entityClass; @Inject public CommonTxDao(@Transactionable CommonReadDao<T, String> readDao, @Transactionable CommonWriteDao<T> writeDao, TransactionService txService, TransactionManager txManager, TransactionInMemoryCache memCache, Class<T> entityClass) { this.readDao = readDao; this.writeDao = writeDao; this.txService = txService; this.txManager = txManager; this.memCache = memCache; this.entityClass = entityClass; } public Set<T> getByIds(List<String> ids) { LinkedHashSet<T> set = new LinkedHashSet<T>(); if (ids != null) { for (String id : ids) { T dto = this.getById(id); set.add(dto); } } return set; } public T getById(String id) { if (isWithinTransaction()) { Transaction tx = txManager.getCurrentTransaction(); T txDto = null; Pair<TransactionStoreKey, TransactionStoreValue> pair; if (tx.isIsolatedTransaction()) { pair = memCache.getValueForIsolatedTransaction(tx.getId(), entityClass.getName(), id); } else { pair = memCache.getValueForNonIsolatedTransaction(entityClass.getName(), id); } // It means the value is either deleted earlier in the transaction or has to been saved. if (pair != null && (pair.getValue().getOpState() == null || OpState.DELETE.equals(pair.getValue().getOpState()))) { return null; } if (pair == null) { return this.readDao.getById(id); } else { - txDto = pair.getValue().getCurrentState(); + txDto = pair.getValue().<T>getCurrentState(); return txDto; } } else { return this.readDao.getById(id); } } public T getSingle(QueryParameter... query) { return this.getSingle(Arrays.asList(query)); } public T getSingle(List<QueryParameter> query) { T dto = readDao.getSingle(query); if (isWithinTransaction()) { if (dto != null) { return this.getById(dto.getId()); } else { return null; } } else { return dto; } } public Set<T> getAll() { return this.readDao.getAll(); } public List<T> getList(List<QueryParameter> query) { return this.readDao.getList(query); } public <OtherTemplate> OtherTemplate getOther(List<QueryParameter> query) { return this.readDao.<OtherTemplate>getOther(query); } public <OtherTemplate> List<OtherTemplate> getOtherList(List<QueryParameter> query) { return this.readDao.<OtherTemplate>getOtherList(query); } public List<T> getList(QueryParameter... query) { return this.readDao.getList(query); } public <OtherTemplate> OtherTemplate getOther(QueryParameter... query) { return this.readDao.<OtherTemplate>getOther(query); } public <OtherTemplate> List<OtherTemplate> getOtherList(QueryParameter... query) { return this.readDao.<OtherTemplate>getOtherList(query); } public void save(T... states) { if (states == null) { return; } if (isWithinTransaction()) { for (T state : states) { this.txService.save(getTxElement(state)); } } else { this.writeDao.save(states); } } public void update(T... states) { if (states == null) { return; } if (isWithinTransaction()) { for (T state : states) { this.txService.update(getTxElement(state)); } } else { this.writeDao.update(states); } } public void delete(T... states) { if (states == null) { return; } if (isWithinTransaction()) { for (T state : states) { this.txService.delete(getTxElement(state)); } } else { this.writeDao.delete(states); } } private boolean isWithinTransaction() { return txManager.getCurrentTransaction() != null; } private TransactionElement<T> getTxElement(T dto) { Transaction tx = txManager.getCurrentTransaction(); if (tx == null) { return null; } TransactionElement<T> element = new TransactionElement<T>(); element.setDto(dto); element.setObjectType(dto.getClass()); element.setReadDao(readDao); element.setWriteDao(writeDao); element.setTxId(tx.getId()); return element; } }
SmartITEngineering/smart-cms
fd1b47a2e90785e9d3932053ecd5c146da1eb4db
Existence of workspace is checked when creating content with test case
diff --git a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java index c5cdb40..6ae812c 100644 --- a/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java +++ b/api-modules/content-api-impl/src/main/java/com/smartitengineering/cms/api/impl/content/ContentImpl.java @@ -1,425 +1,441 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.api.impl.content; import com.smartitengineering.cms.api.content.FieldValue; import com.smartitengineering.cms.api.type.ContentType.ContentProcessingPhase; import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.cms.api.content.Content; import com.smartitengineering.cms.api.content.ContentId; import com.smartitengineering.cms.api.content.Field; import com.smartitengineering.cms.api.content.Representation; import com.smartitengineering.cms.api.content.template.ContentCoProcessor; import com.smartitengineering.cms.api.event.Event; import com.smartitengineering.cms.api.event.Event.EventType; import com.smartitengineering.cms.api.event.Event.Type; import com.smartitengineering.cms.api.factory.SmartContentAPI; import com.smartitengineering.cms.api.factory.content.WriteableContent; import com.smartitengineering.cms.api.impl.AbstractPersistableDomain; import com.smartitengineering.cms.api.type.ContentCoProcessorDef; import com.smartitengineering.cms.api.type.ContentStatus; import com.smartitengineering.cms.api.type.ContentType; import com.smartitengineering.cms.api.type.FieldDef; +import com.smartitengineering.cms.api.workspace.Workspace; import com.smartitengineering.cms.spi.SmartContentSPI; import com.smartitengineering.cms.spi.content.PersistableContent; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.ObjectUtils; /** * * @author kaisar */ public class ContentImpl extends AbstractPersistableDomain<WriteableContent, ContentId> implements PersistableContent { private ContentId contentId; private ContentId parentId; private ContentType contentDef; private ContentStatus contentStatus; private Date creationDate; private Date lastModifiedDate; private Map<String, Field> map; private Map<String, Field> cachedFieldMap; private String entityTagValue; private boolean privateContent; private boolean supressChecking; public ContentImpl() { super(LOCK_KEY_PREFIX); } public boolean isSupressChecking() { return supressChecking; } public void setSupressChecking(boolean supressChecking) { this.supressChecking = supressChecking; } @Override public void put() throws IOException { final boolean attainedLockLocally; if (isPersisted() && !isLockOwned()) { lock(); attainedLockLocally = true; } else { attainedLockLocally = false; } try { triggerContentCoProcessors(ContentType.ContentProcessingPhase.WRITE); if (!isValid()) { getLogger().info("Content not in valid state!"); //First get contents indexed before attempting to use this validity! //Uncomment the following line once indexing is ensured in testing throw new IOException("Content is not in valid state!"); } super.put(); } finally { if (attainedLockLocally) { unlock(); } } } protected void triggerContentCoProcessors(final ContentProcessingPhase phase) { //Trigger content co processors if (contentDef != null && contentId != null) { Collection<ContentCoProcessorDef> defs = contentDef.getContentCoProcessorDefs().get( phase); if (defs != null && !defs.isEmpty()) { List<ContentCoProcessorDef> list = new ArrayList<ContentCoProcessorDef>(defs); Collections.sort(list, new Comparator<ContentCoProcessorDef>() { public int compare(ContentCoProcessorDef o1, ContentCoProcessorDef o2) { return o1.getPriority() - o2.getPriority(); } }); for (ContentCoProcessorDef def : list) { ContentCoProcessor processor = SmartContentAPI.getInstance().getWorkspaceApi().getContentCoProcessor(contentId. getWorkspaceId(), def.getResourceUri().getValue()); if (processor != null) { processor.processContent(this, def.getParameters()); } } } } } @Override public void setParentId(ContentId contentId) { if (contentDef == null) { throw new IllegalArgumentException("Content Type Definition must be set before setting parent content ID"); } if (contentId != null && SmartContentAPI.getInstance().getContentLoader().loadContent(contentId) == null) { throw new IllegalArgumentException("Parent must exist for it to be set!"); } this.parentId = contentId; } @Override public void setContentDefinition(ContentType contentType) { this.contentDef = contentType; } @Override public void setField(Field field) { getMap().put(field.getName(), field); cachedFieldMap = null; } @Override public void setStatus(ContentStatus contentStatus) { this.contentStatus = contentStatus; } @Override public ContentId getContentId() { return this.contentId; } @Override public ContentId getParentId() { return this.parentId; } @Override public Content getParent() { if (parentId != null) { return SmartContentAPI.getInstance().getContentLoader().loadContent(parentId); } else { return null; } } @Override public ContentType getContentDefinition() { return this.contentDef; } @Override public Map<String, Field> getFields() { final Content parent = getParent(); final ContentType def = getContentDefinition(); if (cachedFieldMap == null) { Map<String, Field> fields = new LinkedHashMap<String, Field>(); if (parent != null && def != null) { Map<String, Field> parentFields = parent.getFields(); for (String fieldName : parentFields.keySet()) { FieldDef myDef = def.getOwnFieldDefs().get(fieldName); FieldDef thatDef = parent.getContentDefinition().getOwnFieldDefs().get(fieldName); if (myDef != null && thatDef != null && ObjectUtils.equals(myDef, thatDef) && myDef.getValueDef().getType(). equals(thatDef.getValueDef().getType())) { fields.put(fieldName, parent.getField(fieldName)); } } } fields.putAll(getMap()); cachedFieldMap = fields; } return Collections.unmodifiableMap(cachedFieldMap); } public Map<String, Field> getMap() { if (map == null) { map = new LinkedHashMap<String, Field>(SmartContentSPI.getInstance().getContentReader().getFieldsForContent( contentId)); triggerContentCoProcessors(ContentType.ContentProcessingPhase.READ); } return map; } @Override public Map<String, Field> getOwnFields() { return Collections.unmodifiableMap(getMap()); } @Override public Field getField(String fieldName) { return getFields().get(fieldName); } @Override public ContentStatus getStatus() { return this.contentStatus; } @Override public Representation getRepresentation(String repName) { return SmartContentSPI.getInstance().getRepresentationProvider().getRepresentation(repName, getContentDefinition(), this); } @Override public Date getCreationDate() { return this.creationDate; } @Override public Date getLastModifiedDate() { return this.lastModifiedDate; } @Override public boolean isPersisted() { return creationDate != null; } @Override public ContentId getKeySpecimen() { return contentId; } @Override public void removeField(String fieldName) { getMap().remove(fieldName); } @Override public void setContentId(ContentId contentId) { this.contentId = contentId; } @Override public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } @Override public void setLastModifiedDate(Date lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } @Override protected void create() throws IOException { + System.out.println("Inside create method"); + if (contentId != null) { + if (contentId.getWorkspaceId() == null && contentId.getId() == null) { + throw new IOException("Workspace Id and Id is null though Content Id is not null"); + } + if (contentId.getWorkspaceId() != null) { + Workspace workspace = SmartContentAPI.getInstance().getWorkspaceApi().getWorkspace(contentId.getWorkspaceId()); + if (workspace == null) { + throw new IOException("Non existance workspace Id " + contentId.getWorkspaceId()); + } + } + else { + throw new IOException("Invalid workspace null"); + } + } if (contentId == null && contentDef != null && contentDef.getContentTypeID() != null) { createContentId(contentDef.getContentTypeID().getWorkspace()); } else if (contentId == null && (contentDef == null || contentDef.getContentTypeID() == null)) { throw new IOException("Content ID and Content Type Definition is not set!"); } super.create(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.CREATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public void delete() throws IOException { super.delete(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.DELETE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override protected void update() throws IOException { super.update(); Event<Content> contentEvent = SmartContentAPI.getInstance().getEventRegistrar().<Content>createEvent( EventType.UPDATE, Type.CONTENT, this); SmartContentAPI.getInstance().getEventRegistrar().notifyEvent(contentEvent); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!Content.class.isAssignableFrom(obj.getClass())) { return false; } final Content other = (Content) obj; if (this.contentId != other.getContentId() && (this.contentId == null || !this.contentId.equals(other.getContentId()))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.contentId != null ? this.contentId.hashCode() : 0); return hash; } @Override public void createContentId(WorkspaceId workspace) { if (workspace == null) { throw new IllegalArgumentException("Workspace ID can not be null!"); } setContentId(SmartContentAPI.getInstance().getContentLoader().generateContentId(workspace)); } @Override public void setEntityTagValue(String eTagValue) { this.entityTagValue = eTagValue; } @Override public String getEntityTagValue() { return this.entityTagValue; } @Override public boolean isValid() { boolean validContent = supressChecking || SmartContentAPI.getInstance().getContentLoader().isValidContent(this); if (getLogger().isDebugEnabled()) { getLogger().debug("!!! Checking Content " + validContent); } return validContent; } @Override public URI getUri() { return SmartContentSPI.getInstance().getUriProvider().getContentUri(contentId); } @Override public String getEncodedUriString() { if (getUri() == null) { return null; } else { return getUri().toASCIIString(); } } @Override public void setPrivate(boolean privateContent) { this.privateContent = privateContent; } @Override public boolean isPrivate() { return this.privateContent; } @Override public ContentImpl clone() { ContentImpl contentImpl = new ContentImpl(); contentImpl.contentDef = contentDef; contentImpl.contentId = contentId; contentImpl.parentId = parentId; contentImpl.privateContent = privateContent; contentImpl.contentStatus = contentStatus; contentImpl.nextPerformToWaitForLock = nextPerformToWaitForLock; contentImpl.supressChecking = supressChecking; contentImpl.entityTagValue = entityTagValue; if (creationDate != null) { contentImpl.creationDate = new Date(creationDate.getTime()); } if (lastModifiedDate != null) { contentImpl.lastModifiedDate = new Date(lastModifiedDate.getTime()); } contentImpl.map = map; if (map != null) { contentImpl.map = new LinkedHashMap<String, Field>(); cloneFields(map, contentImpl.map); } if (cachedFieldMap != null) { contentImpl.cachedFieldMap = new LinkedHashMap<String, Field>(); cloneFields(cachedFieldMap, contentImpl.cachedFieldMap); } return contentImpl; } protected void cloneFields(Map<String, Field> fieldMap, Map<String, Field> destMap) { for (Map.Entry<String, Field> oneField : fieldMap.entrySet()) { FieldImpl fieldImpl = new FieldImpl(); final Field value = oneField.getValue(); fieldImpl.setContent(value.getContent()); fieldImpl.setFieldDef(value.getFieldDef()); fieldImpl.setName(value.getName()); final FieldValue fieldVal = value.getValue(); fieldImpl.setValue(fieldVal); destMap.put(oneField.getKey(), fieldImpl); } } } diff --git a/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java b/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java index bf37b60..1d31218 100644 --- a/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java +++ b/webservice-modules/smart-cms-client-impl/src/test/java/com/smartitengineering/cms/client/impl/AppTest.java @@ -1,630 +1,632 @@ /* * * This is a simple Content Management System (CMS) * Copyright (C) 2010 Imran M Yousuf ([email protected]) * * 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/>. */ package com.smartitengineering.cms.client.impl; import com.google.inject.AbstractModule; import com.smartitengineering.cms.api.common.TemplateType; +import com.smartitengineering.cms.api.content.ContentId; +import com.smartitengineering.cms.api.content.MutableContent; +import com.smartitengineering.cms.api.content.MutableField; +import com.smartitengineering.cms.api.content.MutableFieldValue; import com.smartitengineering.cms.api.event.Event; import com.smartitengineering.cms.api.event.Event.EventType; import com.smartitengineering.cms.api.event.EventListener; import com.smartitengineering.cms.api.factory.SmartContentAPI; +import com.smartitengineering.cms.api.factory.content.ContentLoader; +import com.smartitengineering.cms.api.factory.content.WriteableContent; import com.smartitengineering.cms.api.factory.type.WritableContentType; import com.smartitengineering.cms.api.factory.workspace.WorkspaceAPI; +import com.smartitengineering.cms.api.impl.content.ContentImpl; +import com.smartitengineering.cms.api.impl.type.ContentStatusImpl; import com.smartitengineering.cms.api.impl.type.ContentTypeIdImpl; -import com.smartitengineering.cms.api.type.CollectionDataType; -import com.smartitengineering.cms.api.type.CompositeDataType; -import com.smartitengineering.cms.api.type.ContentCoProcessorDef; -import com.smartitengineering.cms.api.type.ContentStatus; -import com.smartitengineering.cms.api.type.ContentType; +import com.smartitengineering.cms.api.impl.type.ContentTypeImpl; +import com.smartitengineering.cms.api.type.*; import com.smartitengineering.cms.api.type.ContentType.ContentProcessingPhase; -import com.smartitengineering.cms.api.type.ContentTypeId; -import com.smartitengineering.cms.api.type.EnumDataType; -import com.smartitengineering.cms.api.type.FieldDef; -import com.smartitengineering.cms.api.type.FieldValueType; -import com.smartitengineering.cms.api.type.RepresentationDef; -import com.smartitengineering.cms.api.type.ValidatorType; -import com.smartitengineering.cms.api.type.VariationDef; import com.smartitengineering.cms.api.workspace.Sequence; import com.smartitengineering.cms.api.workspace.WorkspaceId; import com.smartitengineering.cms.binder.guice.Initializer; import com.smartitengineering.cms.client.api.ContainerResource; import com.smartitengineering.cms.client.api.ContentResource; import com.smartitengineering.cms.client.api.ContentSearcherResource; import com.smartitengineering.cms.client.api.ContentTypeFeedResource; import com.smartitengineering.cms.client.api.ContentTypeResource; import com.smartitengineering.cms.client.api.ContentTypesResource; import com.smartitengineering.cms.client.api.ContentsResource; import com.smartitengineering.cms.client.api.FieldResource; import com.smartitengineering.cms.client.api.RootResource; import com.smartitengineering.cms.client.api.UriTemplateResource; import com.smartitengineering.cms.client.api.WorkspaceContentCoProcessorResource; import com.smartitengineering.cms.client.api.WorkspaceContentCoProcessorsResource; import com.smartitengineering.cms.client.api.WorkspaceContentResouce; import com.smartitengineering.cms.client.api.WorkspaceFeedResource; import com.smartitengineering.cms.client.api.WorkspaceFriendsResource; import com.smartitengineering.cms.client.api.WorkspaceRepresentationResource; import com.smartitengineering.cms.client.api.WorkspaceRepresentationsResource; import com.smartitengineering.cms.client.api.WorkspaceSequenceResource; import com.smartitengineering.cms.client.api.WorkspaceSequencesResource; import com.smartitengineering.cms.client.api.WorkspaceValidatorResource; import com.smartitengineering.cms.client.api.WorkspaceValidatorsResource; import com.smartitengineering.cms.client.api.WorkspaceVariationResource; import com.smartitengineering.cms.client.api.WorkspaceVariationsResource; +import com.smartitengineering.cms.spi.impl.content.ContentAdapterHelper; import com.smartitengineering.cms.ws.common.domains.CollectionFieldDef; import com.smartitengineering.cms.ws.common.domains.CollectionFieldValue; import com.smartitengineering.cms.ws.common.domains.CompositeFieldDef; import com.smartitengineering.cms.ws.common.domains.CompositeFieldValue; import com.smartitengineering.cms.ws.common.domains.Content; import com.smartitengineering.cms.ws.common.domains.EnumFieldDef; import com.smartitengineering.cms.ws.common.domains.Field; import com.smartitengineering.cms.ws.common.domains.FieldImpl; import com.smartitengineering.cms.ws.common.domains.FieldValue; import com.smartitengineering.cms.ws.common.domains.FieldValueImpl; import com.smartitengineering.cms.ws.common.domains.OtherFieldValueImpl; import com.smartitengineering.cms.ws.common.domains.ResourceTemplateImpl; import com.smartitengineering.cms.ws.common.domains.Workspace; import com.smartitengineering.cms.ws.common.domains.WorkspaceImpl.WorkspaceIdImpl; import com.smartitengineering.cms.ws.common.providers.JacksonJsonProvider; import com.smartitengineering.cms.ws.common.providers.TextURIListProvider; import com.smartitengineering.dao.hbase.ddl.HBaseTableGenerator; import com.smartitengineering.dao.hbase.ddl.config.json.ConfigurationJsonParser; +import com.smartitengineering.util.bean.adapter.GenericAdapter; +import com.smartitengineering.util.bean.adapter.GenericAdapterImpl; import com.smartitengineering.util.bean.guice.GuiceUtil; import com.smartitengineering.util.rest.client.ApplicationWideClientFactoryImpl; import com.smartitengineering.util.rest.client.ClientUtil; import com.smartitengineering.util.rest.client.ConnectionConfig; import com.smartitengineering.util.rest.client.ResourceLink; import com.smartitengineering.util.rest.client.jersey.cache.CacheableClient; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.atom.abdera.impl.provider.entity.FeedProvider; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.sun.jersey.multipart.FormDataMultiPart; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Feed; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.mutable.MutableInt; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster; import org.codehaus.jackson.map.ObjectMapper; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.util.ConcurrentHashSet; import org.eclipse.jetty.webapp.WebAppClassLoader; import org.eclipse.jetty.webapp.WebAppContext; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Unit test for simple App. */ public class AppTest { public static final int SLEEP_DURATION = 3000; private static final int PORT = 10080; public static final String DEFAULT_NS = "com.smartitengineering"; public static final String ROOT_URI_STRING = "http://localhost:" + PORT + "/cms/"; public static final String TEST = "test"; public static final String TEST_NS = "testNS"; private static final MiniZooKeeperCluster ZOO_KEEPER_CLUSTER = new MiniZooKeeperCluster(); private static HBaseTestingUtility TEST_UTIL; private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class); private static Server jettyServer; @BeforeClass public static void globalSetup() throws Exception { /* * Start HBase and initialize tables */ //-Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); try { ZOO_KEEPER_CLUSTER.setClientPort(2181); File file = new File("./target/zk-server/"); file.mkdirs(); ZOO_KEEPER_CLUSTER.startup(file); TEST_UTIL = new HBaseTestingUtility(); TEST_UTIL.setZkCluster(ZOO_KEEPER_CLUSTER); TEST_UTIL.startMiniCluster(); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } new HBaseTableGenerator(ConfigurationJsonParser.getConfigurations(AppTest.class.getClassLoader().getResourceAsStream( "com/smartitengineering/cms/spi/impl/schema.json")), TEST_UTIL.getConfiguration(), true).generateTables(); /* * Ensure DIs done */ Properties properties = new Properties(); properties.setProperty(GuiceUtil.CONTEXT_NAME_PROP, "com.smartitengineering.dao.impl.hbase,com.smartitengineering.user.client"); properties.setProperty(GuiceUtil.IGNORE_MISSING_DEP_PROP, Boolean.TRUE.toString()); properties.setProperty(GuiceUtil.MODULES_LIST_PROP, ConfigurationModule.class.getName()); GuiceUtil.getInstance(properties).register(); Initializer.init(); /* * Start web application container */ jettyServer = new Server(PORT); HandlerList handlerList = new HandlerList(); /* * The following is for solr for later, when this is to be used it */ System.setProperty("solr.solr.home", "./target/sample-conf/"); Handler solr = new WebAppContext("./target/solr/", "/solr"); handlerList.addHandler(solr); WebAppContext hub = new WebAppContext("./target/hub/", "/hub"); final WebAppClassLoader webAppClassLoader = new WebAppClassLoader(hub); hub.setClassLoader(webAppClassLoader); handlerList.addHandler(hub); final String webapp = "./src/test/webapp/"; if (!new File(webapp).exists()) { throw new IllegalStateException("WebApp file/dir does not exist!"); } WebAppContext webAppHandler = new WebAppContext(webapp, "/cms"); handlerList.addHandler(webAppHandler); jettyServer.setHandler(handlerList); jettyServer.setSendDateHeader(true); jettyServer.start(); /* * Setup client properties */ System.setProperty(ApplicationWideClientFactoryImpl.TRACE, "true"); Client client = CacheableClient.create(); client.resource("http://localhost:10080/hub/api/channels/test").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).put( "{\"name\":\"test\"}"); LOGGER.info("Created test channel!"); } @AfterClass public static void globalTearDown() throws Exception { try { jettyServer.stop(); } catch (Exception ex) { LOGGER.warn(ex.getMessage(), ex); } try { TEST_UTIL.shutdownMiniCluster(); } catch (Exception ex) { LOGGER.warn(ex.getMessage(), ex); } try { ZOO_KEEPER_CLUSTER.shutdown(); } catch (Exception ex) { LOGGER.warn(ex.getMessage(), ex); } } @Test public void testStartup() throws URISyntaxException { RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Assert.assertNotNull(resource); Assert.assertEquals(0, resource.getWorkspaces().size()); } @Test public void testCreationAndRetrievalWithNameOnly() throws URISyntaxException { RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); final MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add("name", TEST); ClientResponse response = resource.post(MediaType.APPLICATION_FORM_URLENCODED, map, ClientResponse.Status.CREATED); ResourceLink link = ClientUtil.createResourceLink(WorkspaceContentResouce.WORKSPACE_CONTENT, response.getLocation(), MediaType.APPLICATION_JSON); WorkspaceContentResouce workspaceContentResource = new WorkspaceContentResourceImpl(resource, link); Assert.assertNotNull(workspaceContentResource.getLastReadStateOfEntity()); Workspace workspace = workspaceContentResource.getLastReadStateOfEntity(); Assert.assertEquals(TEST, workspace.getId().getName()); Assert.assertEquals(DEFAULT_NS, workspace.getId().getGlobalNamespace()); Collection<WorkspaceContentResouce> resources = resource.getWorkspaces(); Assert.assertEquals(1, resource.getWorkspaces().size()); workspaceContentResource = resources.iterator().next(); workspace = workspaceContentResource.getLastReadStateOfEntity(); Assert.assertEquals(TEST, workspace.getId().getName()); Assert.assertEquals(DEFAULT_NS, workspace.getId().getGlobalNamespace()); } @Test public void testCreationAndRetrievalWithNamespace() throws URISyntaxException { RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); final MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add("name", TEST); map.add("namespace", TEST_NS); ClientResponse response = resource.post(MediaType.APPLICATION_FORM_URLENCODED, map, ClientResponse.Status.CREATED); ResourceLink link = ClientUtil.createResourceLink(WorkspaceContentResouce.WORKSPACE_CONTENT, response.getLocation(), MediaType.APPLICATION_JSON); WorkspaceContentResouce workspaceContentResource = new WorkspaceContentResourceImpl(resource, link); Assert.assertNotNull(workspaceContentResource.getLastReadStateOfEntity()); Workspace workspace = workspaceContentResource.getLastReadStateOfEntity(); Assert.assertEquals(TEST, workspace.getId().getName()); Assert.assertEquals(TEST_NS, workspace.getId().getGlobalNamespace()); Collection<WorkspaceContentResouce> resources = resource.getWorkspaces(); Assert.assertEquals(2, resource.getWorkspaces().size()); workspaceContentResource = resources.iterator().next(); workspace = workspaceContentResource.getLastReadStateOfEntity(); Assert.assertEquals(TEST, workspace.getId().getName()); Assert.assertEquals(TEST_NS, workspace.getId().getGlobalNamespace()); } @Test public void testConditionalRootResourceGet() throws Exception { final String uri = ROOT_URI_STRING; testConditionalGetUsingLastModified(uri); } @Test public void testConditionalWorkspaceContentResourceGet() throws Exception { final String uri = ROOT_URI_STRING; RootResource resource = RootResourceImpl.getRoot(new URI(uri)); Collection<WorkspaceContentResouce> resouces = resource.getWorkspaces(); for (WorkspaceContentResouce contentResouce : resouces) { testConditionalGetUsingLastModified(contentResouce.getUri().toString()); } } @Test public void testCreateWorkspace() throws Exception { WorkspaceIdImpl workspaceId = new WorkspaceIdImpl(); workspaceId.setName("this is a test"); workspaceId.setGlobalNamespace("a test namespace"); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); int size = resource.getWorkspaces().size(); Workspace workspace = resource.createWorkspace(workspaceId); Assert.assertEquals(workspaceId.getName(), workspace.getId().getName()); Assert.assertEquals(workspaceId.getGlobalNamespace(), workspace.getId().getGlobalNamespace()); Feed feed = resource.get(); Assert.assertNotNull(feed); Assert.assertEquals(size + 1, resource.getWorkspaces().size()); } @Test public void testWorkspaceExists() throws Exception { final RootResource root = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); root.get(); final Iterator<WorkspaceFeedResource> iterator = root.getWorkspaceFeeds().iterator(); WorkspaceFeedResource feedResource = iterator.next(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(new StringBuilder("Total no of workspace created in test : ").append(root.getWorkspaceFeeds().size()). toString()); } Assert.assertNotNull(feedResource); feedResource = iterator.next(); Assert.assertNotNull(feedResource); feedResource = iterator.next(); Assert.assertNotNull(feedResource); Assert.assertEquals(3, root.getWorkspaceFeeds().size()); } @Test public void testAddFriend() throws Exception { final RootResource rootResource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); rootResource.get(); final Iterator<WorkspaceFeedResource> iterator = rootResource.getWorkspaceFeeds().iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceFriendsResource friendsResource = feedResource.getFriends(); friendsResource.addFriend(new URI(ROOT_URI_STRING + "w/com.smartitengineering/test")); friendsResource.get(); Collection<URI> frdUri = friendsResource.getLastReadStateOfEntity(); Iterator<URI> frdUris = frdUri.iterator(); Assert.assertEquals(1, frdUri.size()); Assert.assertEquals(ROOT_URI_STRING + "w/com.smartitengineering/test", frdUris.next().toASCIIString()); friendsResource.addFriend(URI.create("/cms/w/a%20test%20namespace/this%20is%20a%20test")); friendsResource.addFriend(new URI("cms/w/testNS/test")); WorkspaceFriendsResource newFriendsResource = feedResource.getFriends(); Collection<URI> collection = newFriendsResource.get(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(new StringBuilder("Total no of friend workspace after adding a friend are : ").append( collection.size()). toString()); } Assert.assertEquals(3, collection.size()); frdUris = collection.iterator(); String friendWorkspace = frdUris.next().toASCIIString(); Assert.assertEquals(ROOT_URI_STRING + "w/a%20test%20namespace/this%20is%20a%20test", friendWorkspace); LOGGER.debug(new StringBuilder("First friend workspace is : ").append(friendWorkspace).toString()); friendWorkspace = frdUris.next().toASCIIString(); Assert.assertEquals(ROOT_URI_STRING + "w/com.smartitengineering/test", friendWorkspace); LOGGER.debug(new StringBuilder("Second friend workspace is : ").append(friendWorkspace).toString()); friendWorkspace = frdUris.next().toASCIIString(); Assert.assertEquals(ROOT_URI_STRING + "w/testNS/test", friendWorkspace); LOGGER.debug(new StringBuilder("Third friend workspace is : ").append(friendWorkspace).toString()); } @Test public void testDeleteFriend() throws Exception { final RootResource rootResource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); rootResource.get(); final Iterator<WorkspaceFeedResource> iterator = rootResource.getWorkspaceFeeds().iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceFriendsResource friendsResource = feedResource.getFriends(); friendsResource.deleteFriend(new URI(ROOT_URI_STRING + "w/com.smartitengineering/test")); friendsResource.get(); Collection<URI> frdUri = friendsResource.getLastReadStateOfEntity(); Iterator<URI> frdUris = frdUri.iterator(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(new StringBuilder("Total no of friend workspace after deleting a friend is : ").append(frdUri.size()). toString()); } // Assert.assertEquals(2, frdUri.size()); // String friendWorkspace = frdUris.next().toASCIIString(); // Assert.assertEquals(ROOT_URI_STRING + "w/a%20test%20namespace/this%20is%20a%20test", friendWorkspace); // LOGGER.debug(new StringBuilder("First friend workspace is : ").append(friendWorkspace).toString()); // friendWorkspace = frdUris.next().toASCIIString(); // Assert.assertEquals(ROOT_URI_STRING + "w/testNS/test", friendWorkspace); // LOGGER.debug(new StringBuilder("Second friend workspace is : ").append(friendWorkspace).toString()); } @Test public void testReplaceAllFriends() throws Exception { Collection<URI> uris = new ArrayList<URI>(); final RootResource rootResource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); final MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add("name", "additional"); map.add("namespace", "atest2"); rootResource.post(MediaType.APPLICATION_FORM_URLENCODED, map, ClientResponse.Status.CREATED); rootResource.get(); final Iterator<WorkspaceFeedResource> iterator = rootResource.getWorkspaceFeeds().iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceFriendsResource friendsResource = feedResource.getFriends(); uris.add(new URI(ROOT_URI_STRING + "w/atest2/additional")); uris.add(new URI(ROOT_URI_STRING + "w/com.smartitengineering/test")); friendsResource.replaceAllFriends(uris); friendsResource.get(); Collection<URI> frdUri = friendsResource.getLastReadStateOfEntity(); Iterator<URI> frdUris = frdUri.iterator(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(new StringBuilder("Total no of friend workspace after replace all friends are : ").append( frdUri.size()).toString()); } Assert.assertEquals(2, frdUri.size()); final String friendWS1 = frdUris.next().toASCIIString(); Assert.assertEquals(ROOT_URI_STRING + "w/atest2/additional", friendWS1); LOGGER.debug(new StringBuilder("First friend after replacing is : ").append(friendWS1).toString()); final String friendWS2 = frdUris.next().toASCIIString(); Assert.assertEquals(ROOT_URI_STRING + "w/com.smartitengineering/test", friendWS2); LOGGER.debug(new StringBuilder("Second friend after replacing is : ").append(friendWS2).toString()); } @Test public void testDeleteAllFriends() throws Exception { final RootResource rootResource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); rootResource.get(); final Iterator<WorkspaceFeedResource> iterator = rootResource.getWorkspaceFeeds().iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceFriendsResource friendsResource = feedResource.getFriends(); friendsResource.deleteAllFriends(); friendsResource.get(); Collection<URI> frdUri = friendsResource.getLastReadStateOfEntity(); Assert.assertNull(frdUri); } @Test public void testCreateRepresentation() throws Exception { ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "Template"; template.setName("rep"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.JAVASCRIPT.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceRepresentationsResource representationsResource = feedResource.getRepresentations(); WorkspaceRepresentationResource representationResource = representationsResource.createRepresentations(template); Assert.assertEquals("rep", representationResource.get().getName()); Assert.assertEquals(temp, new String(representationResource.get().getTemplate())); Assert.assertEquals(TemplateType.JAVASCRIPT.toString(), representationResource.get().getTemplateType()); } @Test public void testCreateVariation() throws Exception { ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "variationTemplate"; template.setName("variation"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.VELOCITY.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); WorkspaceVariationsResource variationsResource = feedResource.getVariations(); WorkspaceVariationResource variationResource = variationsResource.createVariation(template); Assert.assertEquals("variation", variationResource.get().getName()); Assert.assertEquals(temp, new String(variationResource.get().getTemplate())); Assert.assertEquals(TemplateType.VELOCITY.toString(), variationResource.get().getTemplateType()); } @Test public void testUpdateRepresentation() throws Exception { LOGGER.info(":::::::::::::: UPDATE REPRESENTATION RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "newTemplate"; final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.RUBY.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); Collection<WorkspaceRepresentationResource> representationResources = feedResource.getRepresentations(). getRepresentationsResources(); Assert.assertEquals(1, representationResources.size()); Iterator<WorkspaceRepresentationResource> representationIterator = representationResources.iterator(); WorkspaceRepresentationResource representationResource = representationIterator.next(); representationResource.update(template); Assert.assertEquals("rep", representationResource.get().getName()); Assert.assertEquals(temp, new String(representationResource.get().getTemplate())); Assert.assertEquals(TemplateType.RUBY.toString(), representationResource.get().getTemplateType()); resource.getWorkspaceFeeds(); WorkspaceRepresentationResource secondRepresentationResource = resource.getWorkspaceFeeds().iterator().next(). getRepresentations().getRepresentationsResources().iterator().next(); template.setTemplateType(TemplateType.VELOCITY.name()); secondRepresentationResource.update(template); Assert.assertEquals(TemplateType.VELOCITY.name(), secondRepresentationResource.get().getTemplateType()); try { representationResource.update(template); Assert.fail("Should not have been able to update!"); } catch (UniformInterfaceException ex) { //Exception expected representationResource.get(); representationResource.update(template); } } @Test public void testUpdateVariation() throws Exception { LOGGER.info(":::::::::::::: UPDATE VARIATION RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "newTemplate"; final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.RUBY.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); Collection<WorkspaceVariationResource> variationResources = feedResource.getVariations().getVariationResources(); Assert.assertEquals(1, variationResources.size()); Iterator<WorkspaceVariationResource> VariationIterator = variationResources.iterator(); WorkspaceVariationResource variationResource = VariationIterator.next(); variationResource.update(template); Assert.assertEquals("variation", variationResource.get().getName()); Assert.assertEquals(temp, new String(variationResource.get().getTemplate())); Assert.assertEquals(TemplateType.RUBY.toString(), variationResource.get().getTemplateType()); resource.getWorkspaceFeeds(); WorkspaceVariationResource secondVariationResource = resource.getWorkspaceFeeds().iterator().next(). getVariations().getVariationResources().iterator().next(); template.setTemplateType(TemplateType.VELOCITY.name()); secondVariationResource.update(template); Assert.assertEquals(TemplateType.VELOCITY.name(), secondVariationResource.get().getTemplateType()); try { variationResource.update(template); Assert.fail("Should not have been able to update!"); } catch (UniformInterfaceException ex) { //Exception expected variationResource.get(); variationResource.update(template); } } @Test public void testDeleteRepresentation() throws Exception { LOGGER.info(":::::::::::::: DELETE REPRESENTATION RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "Template2"; template.setName("rep2"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.JAVASCRIPT.toString()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); final WorkspaceRepresentationsResource representationsResource = feedResource.getRepresentations(); Collection<WorkspaceRepresentationResource> representationResources = representationsResource. getRepresentationsResources(); Assert.assertEquals(1, representationResources.size()); representationsResource.createRepresentations(template); Iterator<WorkspaceRepresentationResource> representationIterator = representationResources.iterator(); WorkspaceRepresentationResource representationResource = representationIterator.next(); representationResource.delete(ClientResponse.Status.ACCEPTED); Collection<WorkspaceRepresentationResource> secondRepresentationResources = resource.getWorkspaceFeeds().iterator(). next().getRepresentations().getRepresentationsResources(); Assert.assertEquals(1, secondRepresentationResources.size()); } @Test public void testDeleteVariation() throws Exception { LOGGER.info(":::::::::::::: DELETE VARIATION RESOURCE TEST ::::::::::::::"); ResourceTemplateImpl template = new ResourceTemplateImpl(); String temp = "Template2"; template.setName("aaavar2"); final byte[] bytes = temp.getBytes(); template.setTemplate(bytes); template.setTemplateType(TemplateType.VELOCITY.name()); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); final WorkspaceVariationsResource variationsResource = feedResource.getVariations(); Collection<WorkspaceVariationResource> variationResources = variationsResource.getVariationResources(); Assert.assertEquals(1, variationResources.size()); variationsResource.createVariation(template); variationsResource.get(); variationResources = variationsResource.getVariationResources(); Iterator<WorkspaceVariationResource> variationIterator = variationResources.iterator(); WorkspaceVariationResource variationResource = variationIterator.next(); @@ -1014,1024 +1016,1071 @@ public class AppTest { Iterator<WritableContentType> iterator1 = contentTypes.iterator(); Iterator<ContentType> iterator2 = HBaseContentTypes.iterator(); for (int i = 0; i < 3; i++) { ContentType servedContentType = iterator1.next(); ContentType getContentType = iterator2.next(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Type Name : " + getContentType.getContentTypeID().getName()); } Assert.assertEquals(servedContentType.getContentTypeID().getName(), getContentType.getContentTypeID().getName()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Type Namespace : " + getContentType.getContentTypeID().getNamespace()); } Assert.assertEquals(servedContentType.getContentTypeID().getNamespace(), getContentType.getContentTypeID(). getNamespace()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Type Global Namespace : " + getContentType.getContentTypeID().getWorkspace(). getGlobalNamespace()); } Assert.assertEquals(servedContentType.getContentTypeID().getWorkspace().getGlobalNamespace(), getContentType. getContentTypeID().getWorkspace().getGlobalNamespace()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Type ID Global Name : " + getContentType.getContentTypeID().getWorkspace().getName()); } Assert.assertEquals(servedContentType.getContentTypeID().getWorkspace().getName(), getContentType.getContentTypeID(). getWorkspace().getName()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Type Display Name : " + getContentType.getDisplayName()); } Assert.assertEquals(servedContentType.getDisplayName(), getContentType.getDisplayName()); if (getContentType.getParent() != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Type Parent's Name : " + getContentType.getParent().getName()); } Assert.assertEquals(servedContentType.getParent().getName(), getContentType.getParent().getName()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Type Parent's Namespace : " + getContentType.getParent().getNamespace()); } Assert.assertEquals(servedContentType.getParent().getNamespace(), getContentType.getParent().getNamespace()); Assert.assertEquals(servedContentType.getParent().getWorkspace().getGlobalNamespace(), getContentType.getParent(). getWorkspace().getGlobalNamespace()); Assert.assertEquals(servedContentType.getParent().getWorkspace().getName(), getContentType.getParent(). getWorkspace().getName()); } Assert.assertEquals(servedContentType.getStatuses().size(), getContentType.getStatuses().size()); Set statusKeys = servedContentType.getStatuses().keySet(); for (Iterator ite = statusKeys.iterator(); ite.hasNext();) { String key = (String) ite.next(); ContentStatus servedContentStatus = servedContentType.getStatuses().get(key); ContentStatus getContentStatus = getContentType.getStatuses().get(key); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content Status : " + getContentStatus.getName()); } Assert.assertEquals(servedContentStatus.getName(), getContentStatus.getName()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Size of Representations Defs : " + getContentType.getRepresentationDefs()); } Assert.assertEquals(servedContentType.getRepresentations().size(), getContentType.getRepresentations().size()); Assert.assertEquals(servedContentType.getRepresentationDefs().size(), getContentType.getRepresentationDefs().size()); Map<String, RepresentationDef> servedRepresentationDefs = servedContentType.getRepresentationDefs(); Set keys = servedRepresentationDefs.keySet(); for (Iterator ite = keys.iterator(); ite.hasNext();) { String key = (String) ite.next(); RepresentationDef servedRepresentationDef = servedContentType.getRepresentationDefs().get(key); RepresentationDef getRepresentationDef = getContentType.getRepresentationDefs().get(key); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Representation MimeType : " + getRepresentationDef.getMIMEType()); } Assert.assertEquals(servedRepresentationDef.getMIMEType(), getRepresentationDef.getMIMEType()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Representation Name : " + getRepresentationDef.getName()); } Assert.assertEquals(servedRepresentationDef.getName(), getRepresentationDef.getName()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Representation URI : " + getRepresentationDef.getResourceUri().getValue()); } Assert.assertEquals(servedRepresentationDef.getResourceUri().getValue(), getRepresentationDef.getResourceUri(). getValue()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Representation URI Type : " + getRepresentationDef.getResourceUri().getType().name()); } Assert.assertEquals(servedRepresentationDef.getResourceUri().getType().name(), getRepresentationDef. getResourceUri().getType().name()); } Assert.assertEquals(servedContentType.getFieldDefs().size(), getContentType.getFieldDefs().size()); Map<String, FieldDef> servedFieldDefs = servedContentType.getFieldDefs(); Set fieldKeys = servedFieldDefs.keySet(); for (Iterator ite = fieldKeys.iterator(); ite.hasNext();) { String key = (String) ite.next(); FieldDef servedFieldDef = servedContentType.getFieldDefs().get(key); FieldDef getFieldDef = getContentType.getFieldDefs().get(key); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Field Name : " + getFieldDef.getName()); } Assert.assertEquals(servedFieldDef.getName(), getFieldDef.getName()); if (servedFieldDef.getCustomValidators() != null && !servedFieldDef.getCustomValidators().isEmpty()) { if (servedFieldDef.getCustomValidators().iterator().next().getUri() != null) { Assert.assertEquals(servedFieldDef.getCustomValidators().iterator().next().getUri().getType().name(), getFieldDef.getCustomValidators().iterator().next().getUri().getType().name()); Assert.assertEquals(servedFieldDef.getCustomValidators().iterator().next().getUri().getValue(), getFieldDef. getCustomValidators().iterator().next().getUri().getValue()); } } if (getFieldDef.getSearchDefinition() != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Field Search Def : " + getFieldDef.getSearchDefinition().toString()); } Assert.assertEquals(getFieldDef.getSearchDefinition().toString(), getFieldDef.getSearchDefinition().toString()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Field value Name : " + getFieldDef.getValueDef().getType().name()); } Assert.assertEquals(servedFieldDef.getValueDef().getType().name(), getFieldDef.getValueDef().getType().name()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Field isUpdateable : " + getFieldDef.isFieldStandaloneUpdateAble()); } Assert.assertEquals(servedFieldDef.isFieldStandaloneUpdateAble(), getFieldDef.isFieldStandaloneUpdateAble()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Field isRequired : " + getFieldDef.isRequired()); } Assert.assertEquals(servedFieldDef.isRequired(), getFieldDef.isRequired()); Collection<VariationDef> servedVariationDefs = servedFieldDef.getVariations().values(); Collection<VariationDef> getVariationDefs = getFieldDef.getVariations().values(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Size of Variation Def : " + getFieldDef.getVariations().size()); } Assert.assertEquals(servedVariationDefs.size(), getVariationDefs.size()); Iterator<VariationDef> iterator3 = getVariationDefs.iterator(); for (VariationDef servedVariationDef : servedVariationDefs) { VariationDef getVariationDef = iterator3.next(); Assert.assertEquals(servedVariationDef.getMIMEType(), getVariationDef.getMIMEType()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Variation Name : " + getVariationDef.getName()); } Assert.assertEquals(servedVariationDef.getName(), getVariationDef.getName()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Variation URI Type : " + getVariationDef.getResourceUri().getType().name()); } Assert.assertEquals(servedVariationDef.getResourceUri().getType().name(), getVariationDef.getResourceUri(). getType().name()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Variation URI : " + getVariationDef.getResourceUri().getValue()); } Assert.assertEquals(servedVariationDef.getResourceUri().getValue(), getVariationDef.getResourceUri().getValue()); } } } } @Test public void testCreateInvlidContent() throws Exception { LOGGER.info(":::::::::::::: CREATE INVALID CONTENT RESOURCE TEST ::::::::::::::"); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("InvalidContent.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); try { feedResource.getContents().createContentResource(content); Assert.fail("Should not be able to create!"); } catch (UniformInterfaceException ex) { Assert.assertEquals(400, ex.getResponse().getStatus()); } } @Test public void testCreateContent() throws Exception { LOGGER.info(":::::::::::::: CREATE DUMMY CONTENT RESOURCE TEST ::::::::::::::"); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); sleep(); sleep(); LOGGER.info(":::::::::::::: CREATE CONTENT RESOURCE TEST ::::::::::::::"); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); ContentResource contentResource = feedResource.getContents().createContentResource(content); Content content1 = contentResource.get(); Assert.assertNotNull(content1); Assert.assertEquals(content.getParentContentUri(), content1.getParentContentUri()); Assert.assertEquals(content.getStatus(), content1.getStatus()); Assert.assertEquals(content.getFields().size(), content1.getFields().size()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Parent Container Uri : " + content1.getParentContentUri()); LOGGER.debug("Status : " + content1.getStatus()); LOGGER.debug("Number of Fields : " + content1.getFields().size()); } Collection<Field> fields = content.getFields(); Collections.reverse((List<Field>) fields); Iterator<Field> iterator1 = fields.iterator(); Field field = iterator1.next(); final Iterator<Field> iterator2 = content1.getFields().iterator(); Field field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertNotNull(field1.getFieldRawContentUri()); Assert.assertNotNull(field1.getFieldUri()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertTrue(field.getValue().getValue().endsWith(field1.getValue().getValue())); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); CollectionFieldValue collectionFieldValue = (CollectionFieldValue) field.getValue(); CollectionFieldValue collectionFieldValue1 = (CollectionFieldValue) field1.getValue(); Assert.assertEquals(collectionFieldValue.getType().toUpperCase(), collectionFieldValue1.getType()); Assert.assertEquals(collectionFieldValue.getValues().size(), collectionFieldValue1.getValues().size()); Iterator<FieldValue> collectionIterator1 = collectionFieldValue.getValues().iterator(); Iterator<FieldValue> collectionIterator2 = collectionFieldValue1.getValues().iterator(); while (collectionIterator1.hasNext()) { String value1 = collectionIterator1.next().getValue(); String value2 = collectionIterator2.next().getValue(); Assert.assertEquals(value1, value2); } field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); sleep(); } @Test public void testUriTemplates() throws URISyntaxException { LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TEST TEMPLATES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); final String workspaceNS, workspaceId, typeNS, typeId; RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); WorkspaceFeedResource feedResource = resource.getWorkspaceFeeds().iterator().next(); workspaceNS = "atest2"; workspaceId = "additional"; typeNS = "com.smartitengineering.smart-shopping.content"; typeId = "Publisher"; UriTemplateResource templateResource = resource.getTemplates(); LOGGER.info("Testing getting workspace"); Assert.assertNotNull(templateResource.getWorkspaceResource(workspaceNS, workspaceId)); LOGGER.info("Testing getting content type"); Assert.assertNotNull(templateResource.getContentTypeResource(workspaceNS, workspaceId, typeNS, typeId)); LOGGER.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% END TEST TEMPLATES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); } @Test public void testContentListener() throws Exception { final MutableInt createCount = new MutableInt(0); final MutableInt updateCount = new MutableInt(0); final MutableInt deleteCount = new MutableInt(0); SmartContentAPI.getInstance().getEventRegistrar().addListener(new EventListener() { @Override public boolean accepts(Event event) { return event.getEventSourceType().equals(Event.Type.CONTENT) && event.getEventType().equals(EventType.CREATE); } @Override public void notify(Event event) { createCount.add(1); } }); SmartContentAPI.getInstance().getEventRegistrar().addListener(new EventListener() { @Override public boolean accepts(Event event) { return event.getEventSourceType().equals(Event.Type.CONTENT) && event.getEventType().equals(EventType.UPDATE); } @Override public void notify(Event event) { updateCount.add(1); } }); SmartContentAPI.getInstance().getEventRegistrar().addListener(new EventListener() { @Override public boolean accepts(Event event) { return event.getEventSourceType().equals(Event.Type.CONTENT) && event.getEventType().equals(EventType.DELETE); } @Override public void notify(Event event) { deleteCount.add(1); } }); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource authorResource = feedResourceTest.getContents().createContentResource(contentTest); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(authorResource.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); sleep(); ContentResource contentResource = feedResource.getContents().createContentResource(content); Assert.assertEquals(2, createCount.intValue()); contentResource.update(content); Assert.assertEquals(1, updateCount.intValue()); authorResource.delete(); contentResource.get(); contentResource.delete(); Assert.assertEquals(2, deleteCount.intValue()); sleep(); } @Test public void testAddContainerContent() throws Exception { LOGGER.info(":::::::::::::: CREATE CONTENT IN CONTAINER RESOURCE TEST ::::::::::::::"); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); sleep(); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Update-Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); ContentResource contentResource = feedResource.getContents().createContentResource(content); Content content1 = contentResource.get(); Assert.assertNotNull(content1); Assert.assertEquals(content.getParentContentUri(), content1.getParentContentUri()); Assert.assertEquals(content.getStatus(), content1.getStatus()); Assert.assertEquals(content.getFields().size(), content1.getFields().size()); Collection<Field> fields = content.getFields(); Collections.reverse((List<Field>) fields); final Field field = fields.iterator().next(); final Field field1 = content1.getFields().iterator().next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType(), field.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field.getValue().getValue()); feedResource.get(); ContainerResource containerResource = feedResource.getContents().getContainer().iterator().next(); containerResource.createContainer(contentResource.getUri()); Assert.assertEquals(1, containerResource.getContainerContents().size()); Assert.assertEquals(contentResource.getUri().toASCIIString(), containerResource.getContainerContents().iterator(). next().getUri().toASCIIString()); } + @Test + public void testCreateContentWithInvalidWorkspace() throws Exception { + LOGGER.info(":::::::::::::: CREATE CONTENT WITH INVALID WORKSPACE ::::::::::::::"); + + WorkspaceId workspaceId = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspaceId("atest2", "additional"); + + WorkspaceId workspaceId1 = SmartContentAPI.getInstance().getWorkspaceApi().createWorkspaceId("invalidws", + "invalidws"); + + String NAME_SPACE = "com.smartitengineering.smart-shopping.content"; + String name = "Publisher"; + ContentTypeId contentTypeId = SmartContentAPI.getInstance().getContentTypeLoader().createContentTypeId(workspaceId, + NAME_SPACE, + name); + ContentType contentType = SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(contentTypeId); + + String statusKey = contentType.getStatuses().keySet().iterator().next(); + ContentStatus contentStatus = contentType.getStatuses().get(statusKey); + + final WriteableContent writeableContent; + + MutableContent mutableContent = new ContentImpl(); + mutableContent.setContentDefinition(contentType); + mutableContent.setPrivate(false); + mutableContent.setStatus(contentStatus); + MutableField mutableField = new com.smartitengineering.cms.api.impl.content.FieldImpl(); + mutableField.setName("name"); + MutableFieldValue<String> mutableFieldValue = + new com.smartitengineering.cms.api.impl.content.FieldValueImpl<String>(); + mutableFieldValue.setValue("russel"); + mutableField.setValue(mutableFieldValue); + mutableContent.setField(mutableField); + //Create new content + writeableContent = SmartContentAPI.getInstance().getContentLoader().getWritableContent(mutableContent); + writeableContent.createContentId(workspaceId1); + + + try { + //Save or update the content, will be decided by writeable content implementation + writeableContent.put(); + Assert.fail(); + } + catch (IOException ex) { + LOGGER.info("Should fail", ex); + } + } + @Test public void testUpdateCointainerContent() throws Exception { LOGGER.info(":::::::::::::: UPDATE CONTAINER CONTENT RESOURCE TEST ::::::::::::::"); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); sleep(); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); Collection<URI> contentUri = new ArrayList<URI>(); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); ContentResource contentResource = feedResource.getContents().createContentResource(content); feedResource.get(); ContainerResource containerResource = feedResource.getContents().getContainer().iterator().next(); contentUri.add(contentResource.getUri()); containerResource.updateContainer(contentUri); Assert.assertEquals(1, containerResource.getContainerContents().size()); Assert.assertEquals(contentResource.getUri().toASCIIString(), containerResource.getContainerContents().iterator(). next().getUri().toASCIIString()); } @Test public void testDeleteContainerContent() throws Exception { LOGGER.info(":::::::::::::: UPDATE CONTAINER CONTENT RESOURCE TEST ::::::::::::::"); RootResource rootResource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = rootResource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); feedResource.get(); ContainerResource containerResource = feedResource.getContents().getContainer().iterator().next(); containerResource.delete(ClientResponse.Status.ACCEPTED); Assert.assertEquals(0, containerResource.getContainerContents().size()); } @Test public void testUpdateContent() throws Exception { LOGGER.info(":::::::::::::: UPDATE CONTENT RESOURCE TEST ::::::::::::::"); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); sleep(); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); ContentResource contentResource = feedResource.getContents().createContentResource(content); Content content1 = contentResource.get(); Assert.assertNotNull(content1); Assert.assertEquals(content.getParentContentUri(), content1.getParentContentUri()); Assert.assertEquals(content.getStatus(), content1.getStatus()); Assert.assertEquals(content.getFields().size(), content1.getFields().size()); LOGGER.info("::: TEST SEARCHING FROM WORKSPACE RESOURCE"); ContentSearcherResource contentSearcherResource = feedResource.searchContent("count=3"); Assert.assertEquals(3, contentSearcherResource.get().getEntries().size()); LOGGER.info("::: TEST SEARCHING FROM CONTENT RESOURCE"); ContentsResource contentsResource = feedResource.getContents(); ContentSearcherResource contentSearcherResource1 = contentsResource.searchContent("count=6"); Assert.assertEquals(6, contentSearcherResource1.get().getEntries().size()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Parent Container Uri : " + content1.getParentContentUri()); LOGGER.debug("Status : " + content1.getStatus()); LOGGER.debug("Number of Fields : " + content1.getFields().size()); } Collection<Field> fields = content.getFields(); Collections.reverse((List<Field>) fields); Iterator<Field> iterator1 = fields.iterator(); Field field = iterator1.next(); final Iterator<Field> iterator2 = content1.getFields().iterator(); Field field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertNotNull(field1.getFieldRawContentUri()); Assert.assertNotNull(field1.getFieldUri()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertTrue(field.getValue().getValue().endsWith(field1.getValue().getValue())); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); CollectionFieldValue collectionFieldValue = (CollectionFieldValue) field.getValue(); CollectionFieldValue collectionFieldValue1 = (CollectionFieldValue) field1.getValue(); Assert.assertEquals(collectionFieldValue.getType().toUpperCase(), collectionFieldValue1.getType()); Assert.assertEquals(collectionFieldValue.getValues().size(), collectionFieldValue1.getValues().size()); Iterator<FieldValue> collectionIterator1 = collectionFieldValue.getValues().iterator(); Iterator<FieldValue> collectionIterator2 = collectionFieldValue1.getValues().iterator(); while (collectionIterator1.hasNext()) { String value1 = collectionIterator1.next().getValue(); String value2 = collectionIterator2.next().getValue(); Assert.assertEquals(value1, value2); } field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); field = iterator1.next(); field1 = iterator2.next(); Assert.assertEquals(field.getName(), field1.getName()); Assert.assertEquals(field.getValue().getType().toUpperCase(), field1.getValue().getType()); Assert.assertEquals(field.getValue().getValue(), field1.getValue().getValue()); LOGGER.info(":::::::::::::: Updating Content Resource ::::::::::::::"); ObjectMapper updateMapper = new ObjectMapper(); String updateJSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Update-Content.json")); InputStream updateStream = IOUtils.toInputStream(updateJSON); Content updateContent = updateMapper.readValue(updateStream, Content.class); updateContent.getFields().add(valueImpl); updateContent.getFields().add(authorField); Assert.assertNotNull(updateContent); RootResource updateResource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> updateWorkspaceFeedResources = updateResource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> updateIterator = updateWorkspaceFeedResources.iterator(); WorkspaceFeedResource updateFeedResource = updateIterator.next(); ContentResource updateContentResource = updateFeedResource.getContents().createContentResource(updateContent); Content updateContent1 = updateContentResource.get(); Assert.assertNotNull(updateContent1); Assert.assertEquals(updateContent.getParentContentUri(), updateContent1.getParentContentUri()); Assert.assertEquals(updateContent.getStatus(), updateContent1.getStatus()); Assert.assertEquals(updateContent.getFields().size(), updateContent1.getFields().size()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Parent Container Uri : " + updateContent1.getParentContentUri()); LOGGER.debug("Status : " + updateContent1.getStatus()); LOGGER.debug("Number of Fields : " + updateContent1.getFields().size()); } Collection<Field> updateFields = updateContent.getFields(); Collections.reverse((List<Field>) updateFields); Iterator<Field> updateIterator1 = updateFields.iterator(); Field updateField = updateIterator1.next(); final Iterator<Field> updateIterator2 = updateContent1.getFields().iterator(); Field updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertNotNull(updateField1.getFieldRawContentUri()); Assert.assertNotNull(updateField1.getFieldUri()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertTrue(updateField.getValue().getValue().endsWith(updateField1.getValue().getValue())); updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); CollectionFieldValue updateCollectionFieldValue = (CollectionFieldValue) updateField.getValue(); CollectionFieldValue updateCollectionFieldValue1 = (CollectionFieldValue) updateField1.getValue(); Assert.assertEquals(updateCollectionFieldValue.getType().toUpperCase(), updateCollectionFieldValue1.getType()); Assert.assertEquals(updateCollectionFieldValue.getValues().size(), updateCollectionFieldValue1.getValues().size()); Iterator<FieldValue> updateCollectionIterator1 = updateCollectionFieldValue.getValues().iterator(); Iterator<FieldValue> updateCollectionIterator2 = updateCollectionFieldValue1.getValues().iterator(); while (updateCollectionIterator1.hasNext()) { String value1 = updateCollectionIterator1.next().getValue(); String value2 = updateCollectionIterator2.next().getValue(); Assert.assertEquals(value1, value2); } updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); updateField = updateIterator1.next(); updateField1 = updateIterator2.next(); Assert.assertEquals(updateField.getName(), updateField1.getName()); Assert.assertEquals(updateField.getValue().getType().toUpperCase(), updateField1.getValue().getType()); Assert.assertEquals(updateField.getValue().getValue(), updateField1.getValue().getValue()); sleep(); } @Test public void testContentRepresentation() throws Exception { LOGGER.info(":::::::::::::: CONTENT REPRESENTATION RESOURCE TEST ::::::::::::::"); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); LOGGER.info("Author for representation created!"); sleep(); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); ContentResource contentResource = feedResource.getContents().createContentResource(content); Collection<String> urls = contentResource.getRepresentationUrls(); Iterator<String> iterator1 = urls.iterator(); while (iterator1.hasNext()) { String next = iterator1.next(); String type = contentResource.getRepresentation(next); Assert.assertEquals("some/type", type); } sleep(); } @Test public void testFieldVariation() throws Exception { ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); sleep(); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); ContentResource contentResource = feedResource.getContents().createContentResource(content); Iterator<FieldResource> iterator2 = contentResource.getFields().iterator(); while (iterator2.hasNext()) { FieldResource next = iterator2.next(); Collection<String> variations = next.getVariationUrls(); Iterator<String> iterator1 = variations.iterator(); while (iterator1.hasNext()) { String url = iterator1.next(); String variation = next.getVariation(url); Assert.assertEquals("some/type", variation); } } } @Test public void testSearch() throws Exception { LOGGER.info(":::::::::::::: SEARCH CONTENT RESOURCE TEST ::::::::::::::"); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); sleep(); String query = "typeId=atest2:additional:com.smartitengineering.smart-shopping.content:Author&status=published&status=draft&disjunction=true"; ContentSearcherResource searchContent = resource.searchContent(query); Assert.assertEquals(5, searchContent.get().getEntries().size()); IRI href = searchContent.get().getLink("next").getHref(); query = "typeId=atest2:additional:com.smartitengineering.smart-shopping.content:Author&status=published&status=draft&disjunction=true&count=10"; searchContent = resource.searchContent(query); Assert.assertEquals(10, searchContent.get().getEntries().size()); } @Test public void testDeleteContent() throws Exception { LOGGER.info(":::::::::::::: DELETE CONTENT RESOURCE TEST ::::::::::::::"); ObjectMapper mapper1 = new ObjectMapper(); String JSON1 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("DummyContent.json")); InputStream stream1 = IOUtils.toInputStream(JSON1); Content contentTest = mapper1.readValue(stream1, Content.class); Assert.assertNotNull(contentTest); RootResource resource1 = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources1 = resource1.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iteratorTest = workspaceFeedResources1.iterator(); WorkspaceFeedResource feedResourceTest = iteratorTest.next(); ContentResource contentResourceTest = feedResourceTest.getContents().createContentResource(contentTest); sleep(); FieldValueImpl value = new FieldValueImpl(); value.setType("content"); value.setValue(contentResourceTest.getUri().toASCIIString()); FieldImpl authorField = new FieldImpl(); authorField.setName("Authors"); authorField.setValue(value); String valueString = "otherValue"; byte[] otherValue = valueString.getBytes(); OtherFieldValueImpl otherFieldValueImpl = new OtherFieldValueImpl(); otherFieldValueImpl.setMimeType("jpeg/image"); otherFieldValueImpl.setType("other"); otherFieldValueImpl.setValue(Base64.encodeBase64String(otherValue)); FieldImpl valueImpl = new FieldImpl(); valueImpl.setName("b"); valueImpl.setValue(otherFieldValueImpl); ObjectMapper mapper = new ObjectMapper(); String JSON = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("Content.json")); InputStream stream = IOUtils.toInputStream(JSON); Content content = mapper.readValue(stream, Content.class); content.getFields().add(valueImpl); content.getFields().add(authorField); Assert.assertNotNull(content); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); feedResource.getContents().createContentResource(content).delete(ClientResponse.Status.OK); feedResource.get(); Assert.assertEquals(0, feedResource.getContents().getContentResources().size()); } @Test public void testDeleteContentType() throws Exception { LOGGER.info(":::::::::::::: DELETE CONTENT_TYPE RESOURCE TEST ::::::::::::::"); RootResource resource = RootResourceImpl.getRoot(new URI(ROOT_URI_STRING)); Collection<WorkspaceFeedResource> workspaceFeedResources = resource.getWorkspaceFeeds(); Iterator<WorkspaceFeedResource> iterator = workspaceFeedResources.iterator(); WorkspaceFeedResource feedResource = iterator.next(); ContentTypesResource contentTypesResource = feedResource.getContentTypes(); Collection<ContentTypeResource> collection = contentTypesResource.getContentTypes(); Assert.assertEquals(4, collection.size()); ContentTypeResource contentTypeResource = collection.iterator().next(); Assert.assertNotNull(contentTypeResource.get()); contentTypeResource.delete(ClientResponse.Status.OK); try { contentTypeResource.get(); } catch (UniformInterfaceException exception) { Assert.assertEquals(404, exception.getResponse().getStatus()); }
SmartITEngineering/smart-cms
29e1ddc5ed491cdbb95e2ddfec484e6b7ea5916a
Add System Property support to override workspace id
diff --git a/code-generation/maven-pojo-generator-plugin/src/main/java/com/smartitengineering/cms/maven/dto/generator/plugin/PojoGeneratorMojo.java b/code-generation/maven-pojo-generator-plugin/src/main/java/com/smartitengineering/cms/maven/dto/generator/plugin/PojoGeneratorMojo.java index e49d6a4..01119c1 100644 --- a/code-generation/maven-pojo-generator-plugin/src/main/java/com/smartitengineering/cms/maven/dto/generator/plugin/PojoGeneratorMojo.java +++ b/code-generation/maven-pojo-generator-plugin/src/main/java/com/smartitengineering/cms/maven/dto/generator/plugin/PojoGeneratorMojo.java @@ -905,644 +905,652 @@ public class PojoGeneratorMojo extends AbstractMojo { break; } case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) collectionDataType.getItemDataType(); Set<FieldDef> compositeFields = new LinkedHashSet<FieldDef>(); if (compositeDataType.getEmbeddedContentType() != null) { ContentType currentType = getType(types, compositeDataType.getEmbeddedContentType().getTypeDef()); if (currentType != null) { compositeFields.addAll(getAllFields(currentType, types).values()); } } compositeFields.addAll(compositeDataType.getOwnComposition()); JDefinedClass compositeDefinition = findClass(compositeDataType, currentClass, classes, name); JDefinedClass newCompositeDefintion = findConcreteClass(compositeDefinition, classes); if (compositeDefinition != null && newCompositeDefintion != null) { JVar resultVal = valBlock.decl(model.ref(Collection.class).narrow(newCompositeDefintion), getVarName(prefix, "beanList"), JExpr._new(model.ref(ArrayList.class).narrow(newCompositeDefintion))); final JClass narrowedCollection = model.ref(Collection.class).narrow(FieldValue.class); JVar fieldVal = valBlock.decl(model.ref(FieldValue.class).narrow(narrowedCollection), getVarName(prefix, "fieldVal"), field.invoke("getValue")); JConditional collectionValCond = valBlock._if(fieldVal.ne(JExpr._null())); JBlock validValBlock = collectionValCond._then(); JVar collectionVal = validValBlock.decl(narrowedCollection, getVarName(prefix, "collectionVal"), fieldVal.invoke("getValue")); JConditional validCollectionCond = validValBlock._if(collectionVal.ne(JExpr._null()).cand(collectionVal. invoke("isEmpty").not())); JBlock iterateBlock = validCollectionCond._then(); JVar iterator = iterateBlock.decl(model.ref(Iterator.class).narrow(FieldValue.class), getVarName(prefix, "iterator"), collectionVal.invoke("iterator")); JWhileLoop loop = iterateBlock._while(iterator.invoke("hasNext")); JBlock loopBlock = loop.body(); JVar val = loopBlock.decl(model.ref(FieldValue.class).narrow(model.ref(Collection.class).narrow( Field.class)), getVarName(prefix, "val"), iterator.invoke("next")); final JBlock _then = loopBlock; JBlock validCompVal = _then._if(val.ne(JExpr._null()))._then(); final JVar compositeToBean = validCompVal.decl(compositeDefinition, varName, JExpr._new( newCompositeDefintion)); final JClass ref = model.ref(CompositeFieldValue.class); JVar compositeFromBean = validCompVal.decl(ref, new StringBuilder(varName).append("Val").toString(), JExpr.cast(ref, val)); String compPrefix = new StringBuilder(varName).append('_').toString(); generateForwardBlocks(compositeFields, validCompVal, compositeFromBean, compositeToBean, model, compositeDefinition, helperClass, classes, types, compPrefix); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); validCompVal.add(resultVal.invoke("add").arg(compositeToBean)); valBlock.add(toBean.invoke(setterName).arg(resultVal)); } } } break; default: } } } protected void setCollectionField(JBlock valBlock, JCodeModel model, JVar field, final Class narrowClass, final String name, JVar toBean, String prefix) { final JVar collectionVal = addToCollection(valBlock, model, field, narrowClass, prefix); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); valBlock.add(toBean.invoke(setterName).arg(collectionVal)); } protected String getVarName(String prefix, String literal) { return new StringBuilder(prefix).append(literal).toString(); } protected JVar addToCollection(JBlock valBlock, JCodeModel model, JVar field, final Class narrowClass, String prefix) { JVar resultVal = valBlock.decl(model.ref(Collection.class).narrow(narrowClass), getVarName(prefix, "beanList"), JExpr._new(model.ref(ArrayList.class).narrow(narrowClass))); final JClass narrowedCollection = model.ref(Collection.class).narrow(FieldValue.class); JVar fieldVal = valBlock.decl(model.ref(FieldValue.class).narrow(narrowedCollection), getVarName(prefix, "fieldVal"), field.invoke("getValue")); JConditional collectionValCond = valBlock._if(fieldVal.ne(JExpr._null())); JBlock validValBlock = collectionValCond._then(); JVar collectionVal = validValBlock.decl(narrowedCollection, getVarName(prefix, "collectionVal"), fieldVal.invoke( "getValue")); JConditional validCollectionCond = validValBlock._if(collectionVal.ne(JExpr._null()).cand(collectionVal.invoke( "isEmpty").not())); JBlock iterateBlock = validCollectionCond._then(); JVar iterator = iterateBlock.decl(model.ref(Iterator.class).narrow(FieldValue.class), getVarName(prefix, "iterator"), collectionVal.invoke("iterator")); JWhileLoop loop = iterateBlock._while(iterator.invoke("hasNext")); JBlock loopBlock = loop.body(); JVar val = loopBlock.decl(model.ref(FieldValue.class).narrow(narrowClass), getVarName(prefix, "val"), iterator. invoke("next")); JConditional singleValCond = loopBlock._if(val.ne(JExpr._null())); singleValCond._then().add(resultVal.invoke("add").arg(val.invoke("getValue"))); return resultVal; } protected void setField(JBlock block, JCodeModel model, JVar field, final String name, JVar toBean, Class valType, String prefix) { final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String setterName = new StringBuilder("set").append(getterSetterSuffix).toString(); final String fieldValVar = getVarName(prefix, new StringBuilder(name).append("Val").toString()); JVar fieldVal = block.decl(model.ref(FieldValue.class).narrow(valType), fieldValVar, field.invoke("getValue")); JConditional valCond = block._if(fieldVal.ne(JExpr._null())); JBlock setBlock = valCond._then(); setBlock.add(toBean.invoke(setterName).arg(fieldVal.invoke("getValue"))); } protected void addField(JBlock block, JCodeModel model, JVar field, final String name, JVar toBean, Class valType, String prefix) { final String setterName = "add"; final String fieldValVar = getVarName(prefix, new StringBuilder(name).append("Val").toString()); JVar fieldVal = block.decl(model.ref(FieldValue.class).narrow(valType), fieldValVar, field.invoke("getValue")); JConditional valCond = block._if(fieldVal.ne(JExpr._null())); JBlock setBlock = valCond._then(); setBlock.add(toBean.invoke(setterName).arg(fieldVal.invoke("getValue"))); } protected JDefinedClass findClass(CompositeDataType compositeDataType, JDefinedClass currentClass, Map<ContentTypeId, JDefinedClass> classes, String fieldName) { final String getterSetterSuffix = new StringBuilder().append(("" + fieldName.charAt(0)).toUpperCase()).append(fieldName. substring(1)).toString(); JDefinedClass jType = null; ContentDataType composedOfContent = compositeDataType.getEmbeddedContentType(); if (compositeDataType.getOwnComposition() != null && !compositeDataType.getOwnComposition().isEmpty()) { Iterator<JDefinedClass> compositeFieldClasses = currentClass.classes(); while (compositeFieldClasses.hasNext()) { JDefinedClass innerClass = compositeFieldClasses.next(); if (innerClass.name().equals(getterSetterSuffix)) { jType = innerClass; } } } else if (composedOfContent != null) { jType = classes.get(composedOfContent.getTypeDef()); } return jType; } protected JDefinedClass findConcreteClass(JDefinedClass compositeDefinition, Map<ContentTypeId, JDefinedClass> classes) { if (compositeDefinition.isAbstract()) { for (JDefinedClass clazz : classes.values()) { if (!clazz.isAbstract() && compositeDefinition.isAssignableFrom(clazz)) { return clazz; } else { JDefinedClass inInnerClass = findConcreteInInnerClass(compositeDefinition, clazz); if (inInnerClass != null) { return inInnerClass; } } } return null; } else { return compositeDefinition; } } protected JDefinedClass findConcreteInInnerClass(JDefinedClass compositeDefinition, JDefinedClass clazz) { final Iterator<JDefinedClass> classes = clazz.classes(); while (classes.hasNext()) { JDefinedClass innerClass = classes.next(); if (compositeDefinition.isAssignableFrom(innerClass)) { return innerClass; } else { JDefinedClass inInnerClass = findConcreteInInnerClass(compositeDefinition, innerClass); if (inInnerClass != null) { return inInnerClass; } } } return null; } protected void generateReverseBlocks(Collection<FieldDef> values, JBlock block, JVar fromBean, JVar wContent, JVar contentLoader, JVar fieldDefs, JCodeModel model, JDefinedClass currentClass, Map<ContentTypeId, JDefinedClass> classes, Set<? extends ContentType> types, String prefix) { for (FieldDef def : values) { final String name = def.getName(); final String getterSetterSuffix = new StringBuilder().append(("" + name.charAt(0)).toUpperCase()).append(name. substring(1)).toString(); final String getterName = new StringBuilder("get").append(getterSetterSuffix).toString(); switch (def.getValueDef().getType()) { case BOOLEAN: { final String methodName = "createBooleanFieldValue"; final Class valClass = Boolean.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case STRING: { final String methodName = "createStringFieldValue"; final Class valClass = String.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case ENUM: { final String methodName = "createStringFieldValue"; final Class valClass = String.class; JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(valClass), getVarName(prefix, "fieldVal"), contentLoader.invoke(methodName)); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(fromBean.invoke(getterName).invoke("name"))); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); break; } case DATE_TIME: { final String methodName = "createDateTimeFieldValue"; final Class valClass = Date.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case INTEGER: { final String methodName = "createIntegerFieldValue"; final Class valClass = Number.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case DOUBLE: { final String methodName = "createDoubleFieldValue"; final Class valClass = Number.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case LONG: { final String methodName = "createLongFieldValue"; final Class valClass = Number.class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case OTHER: { final String methodName = "createOtherFieldValue"; final Class valClass = byte[].class; setSimpleField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case CONTENT: { JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null()).cand(fromBean.invoke(getterName).invoke("getId").ne(JExpr._null()))))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()). arg(fieldDefs.invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(ContentId.class), getVarName(prefix, "fieldVal"), contentLoader.invoke("createContentFieldValue")); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(JExpr._super().invoke("getContentId").arg(fromBean. invoke(getterName).invoke("getId")).arg(fromBean.invoke(getterName).invoke("getWorkspaceId")))); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); break; } case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) def.getValueDef(); JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null())))._then(); JDefinedClass clazz = findClass(compositeDataType, currentClass, classes, name); JVar input = nonNullBlock.decl(clazz, getVarName(prefix, "compositeField"), fromBean.invoke(getterName)); final JInvocation defArg = fieldDefs.invoke("get").arg(name); JVar fieldDef = nonNullBlock.decl(model.ref(FieldDef.class), getVarName(prefix, "def"), defArg); JVar compositeFieldDefs = nonNullBlock.decl( model.ref(Map.class).narrow(String.class).narrow(FieldDef.class), getVarName(prefix, "compositeFieldDefs"), JExpr.invoke(JExpr.cast(model.ref(CompositeDataType.class), fieldDef.invoke("getValueDef")), "getComposedFieldDefs")); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDef)); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableCompositeFieldValue.class), getVarName(prefix, "fieldVal"), contentLoader.invoke("createCompositeFieldValue")); Collection<FieldDef> defs = getAllComposedFields(compositeDataType, types); generateReverseBlocks(defs, nonNullBlock, input, mutableFieldValue, contentLoader, compositeFieldDefs, model, clazz, classes, types, new StringBuilder(prefix).append(name).append('_').toString()); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); break; } case COLLECTION: CollectionDataType collectionDataType = (CollectionDataType) def.getValueDef(); switch (collectionDataType.getItemDataType().getType()) { case BOOLEAN: { final String methodName = "createBooleanFieldValue"; final Class valClass = Boolean.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case STRING: { final String methodName = "createStringFieldValue"; final Class valClass = String.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case ENUM: { final String methodName = "createStringFieldValue"; final Class valClass = String.class; JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get"). arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(model.ref( Collection.class). narrow(model.ref(FieldValue.class))), getVarName(prefix, "fieldVals"), contentLoader.invoke( "createCollectionFieldValue")); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); JVar collection = nonNullBlock.decl(model.ref(Collection.class).narrow(model.ref(FieldValue.class)), getVarName( prefix, "collectionVar"), JExpr._new(model.ref(ArrayList.class).narrow(FieldValue.class))); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(collection)); final JForLoop forLoop = nonNullBlock._for(); JType itClass = ((JClass) currentClass.fields().get(name).type()).getTypeParameters().get(0); JVar iterator_item = forLoop.init(model.ref(Iterator.class).narrow(itClass), getVarName(prefix, "i"), fromBean.invoke(getterName).invoke("iterator")); forLoop.test(iterator_item.invoke("hasNext")); final JBlock forBody = forLoop.body(); JVar mutableItemFieldValue = forBody.decl(model.ref(MutableFieldValue.class).narrow(valClass), getVarName(prefix, "fieldVal"), contentLoader.invoke(methodName)); forBody.add(mutableItemFieldValue.invoke("setValue").arg(iterator_item.invoke("next").invoke("name"))); forBody.add(collection.invoke("add").arg(mutableItemFieldValue)); break; } case DATE_TIME: { final String methodName = "createDateTimeFieldValue"; final Class valClass = Date.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case INTEGER: { final String methodName = "createIntegerFieldValue"; final Class valClass = Number.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case DOUBLE: { final String methodName = "createDoubleFieldValue"; final Class valClass = Number.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case LONG: { final String methodName = "createLongFieldValue"; final Class valClass = Number.class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case OTHER: { final String methodName = "createOtherFieldValue"; final Class valClass = byte[].class; setSimpleMultiField(block, fromBean, wContent, getterName, fieldDefs, name, model, contentLoader, valClass, methodName, prefix); break; } case CONTENT: { JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get"). arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(model.ref( Collection.class).narrow(model.ref(FieldValue.class))), getVarName(prefix, "fieldVals"), contentLoader.invoke("createCollectionFieldValue")); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); JVar collection = nonNullBlock.decl(model.ref(Collection.class).narrow(model.ref(FieldValue.class)), getVarName(prefix, "collectionVar"), JExpr._new(model.ref( ArrayList.class).narrow(FieldValue.class))); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(collection)); final JForLoop forLoop = nonNullBlock._for(); final JClass narrowedDomain = model.ref(AbstractRepositoryDomain.class).narrow(model.ref( PersistentDTO.class).narrow(model.ref(PersistentDTO.class).wildcard()).narrow(String.class).narrow( Long.class).wildcard()); JVar iterator_item = forLoop.init(model.ref(Iterator.class).narrow(narrowedDomain.wildcard()), getVarName( prefix, "i"), fromBean.invoke(getterName).invoke("iterator")); forLoop.test(iterator_item.invoke("hasNext")); final JBlock forBody = forLoop.body(); JVar nextVal = forBody.decl(narrowedDomain, getVarName(prefix, "domain"), iterator_item.invoke( "next")); JVar mutableItemFieldValue = forBody.decl(model.ref(MutableFieldValue.class).narrow(ContentId.class), getVarName(prefix, "fieldVal"), contentLoader.invoke("createContentFieldValue")); forBody.add(mutableItemFieldValue.invoke("setValue").arg(JExpr._super().invoke("getContentId").arg(nextVal. invoke("getId")).arg(nextVal.invoke("getWorkspaceId")))); forBody.add(collection.invoke("add").arg(mutableItemFieldValue)); break; } case COMPOSITE: { CompositeDataType compositeDataType = (CompositeDataType) collectionDataType.getItemDataType(); JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get"). arg(name).ne(JExpr._null())))._then(); JDefinedClass clazz = findClass(compositeDataType, currentClass, classes, name); final JInvocation defArg = fieldDefs.invoke("get").arg(name); JVar fieldDef = nonNullBlock.decl(model.ref(FieldDef.class), getVarName(prefix, "def"), defArg); JVar compositeFieldDefs = nonNullBlock.decl(model.ref(Map.class).narrow(String.class).narrow( FieldDef.class), getVarName(prefix, "compositeFieldDefs"), JExpr.invoke(JExpr.cast(model.ref(CompositeDataType.class), JExpr.invoke(JExpr.cast(model.ref( CollectionDataType.class), fieldDef.invoke("getValueDef")), "getItemDataType")), "getComposedFieldDefs")); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg( fieldDef)); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(model.ref( Collection.class).narrow(model.ref(FieldValue.class))), getVarName(prefix, "fieldVals"), contentLoader.invoke("createCollectionFieldValue")); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); JVar collection = nonNullBlock.decl(model.ref(Collection.class).narrow(model.ref(FieldValue.class)), getVarName(prefix, "collectionVar"), JExpr._new(model.ref( ArrayList.class).narrow(FieldValue.class))); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(collection)); final JForLoop forLoop = nonNullBlock._for(); final JClass narrowedDomain = clazz; JVar iterator_item = forLoop.init(model.ref(Iterator.class).narrow(narrowedDomain), getVarName( prefix, "i"), fromBean.invoke(getterName).invoke("iterator")); forLoop.test(iterator_item.invoke("hasNext")); final JBlock forBody = forLoop.body(); JVar nextVal = forBody.decl(narrowedDomain, getVarName(prefix, "domain"), iterator_item.invoke( "next")); JVar mutableItemFieldValue = forBody.decl(model.ref(MutableCompositeFieldValue.class), getVarName(prefix, "fieldVal"), contentLoader.invoke("createCompositeFieldValue")); Collection<FieldDef> defs = getAllComposedFields(compositeDataType, types); generateReverseBlocks(defs, forBody, nextVal, mutableItemFieldValue, contentLoader, compositeFieldDefs, model, clazz, classes, types, new StringBuilder(prefix).append(name).append('_').toString()); forBody.add(collection.invoke("add").arg(mutableItemFieldValue)); } } break; default: } } } protected void setSimpleField(JBlock block, JVar fromBean, JVar wContent, final String getterName, JVar fieldDefs, final String name, JCodeModel model, JVar contentLoader, final Class valClass, final String methodName, String prefix) { JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(valClass), getVarName(prefix, "fieldVal"), contentLoader.invoke(methodName)); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(fromBean.invoke(getterName))); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); } protected void setSimpleMultiField(JBlock block, JVar fromBean, JVar wContent, final String getterName, JVar fieldDefs, final String name, JCodeModel model, JVar contentLoader, final Class valClass, final String methodName, String prefix) { JBlock nonNullBlock = block._if(fromBean.invoke(getterName).ne(JExpr._null()).cand(fieldDefs.invoke("get").arg( name).ne(JExpr._null())))._then(); JVar mutableField = nonNullBlock.decl(model.ref(MutableField.class), getVarName(prefix, "mutableField"), contentLoader.invoke("createMutableField").arg(JExpr._null()).arg(fieldDefs. invoke("get").arg(name))); JVar mutableFieldValue = nonNullBlock.decl(model.ref(MutableFieldValue.class).narrow(model.ref(Collection.class). narrow(model.ref(FieldValue.class))), getVarName(prefix, "fieldVals"), contentLoader.invoke( "createCollectionFieldValue")); nonNullBlock.add(mutableField.invoke("setValue").arg(mutableFieldValue)); nonNullBlock.add(wContent.invoke("setField").arg(mutableField)); JVar collection = nonNullBlock.decl(model.ref(Collection.class).narrow(model.ref(FieldValue.class)), getVarName( prefix, "collectionVar"), JExpr._new(model.ref(ArrayList.class).narrow(FieldValue.class))); nonNullBlock.add(mutableFieldValue.invoke("setValue").arg(collection)); final JForLoop forLoop = nonNullBlock._for(); JVar iterator_item = forLoop.init(model.ref(Iterator.class).narrow(model.ref(valClass).wildcard()), getVarName( prefix, "i"), fromBean.invoke(getterName).invoke("iterator")); forLoop.test(iterator_item.invoke("hasNext")); final JBlock forBody = forLoop.body(); JVar mutableItemFieldValue = forBody.decl(model.ref(MutableFieldValue.class).narrow(valClass), getVarName(prefix, "fieldVal"), contentLoader.invoke(methodName)); forBody.add(mutableItemFieldValue.invoke("setValue").arg(iterator_item.invoke("next"))); forBody.add(collection.invoke("add").arg(mutableItemFieldValue)); } protected void generateMasterModule(Map<ContentTypeId, JDefinedClass> modules, JCodeModel codeModel, String[] wId) throws JClassAlreadyExistsException { final String moduleClassName = new StringBuilder(packageForGuiceMasterModule).append(".MasterModule").toString(); final JDefinedClass moduleClass = codeModel._class(moduleClassName); moduleClass._extends(codeModel.ref(AbstractModule.class)); JMethod configureMethod = moduleClass.method(JMod.PUBLIC, JCodeModel.boxToPrimitive.get(Void.class), "configure"); JBlock block = configureMethod.body(); if (typeFiles != null && !typeFiles.isEmpty()) { JClass namesClass = codeModel.ref(Names.class); - JExpression stringClass = codeModel.ref(String.class).dotclass(); + final JClass stringClassType = codeModel.ref(String.class); + final JClass systemClass = codeModel.ref(System.class); + JExpression stringClass = stringClassType.dotclass(); + JVar workspaceNamespace = block.decl(stringClassType, "workspaceNamespace", + systemClass.staticInvoke("getProperty").arg( + "com.smartitengineering.cms.repo.workspace.namespace").arg(wId[0])); + JVar workspaceName = block.decl(stringClassType, "workspaceName", systemClass.staticInvoke("getProperty").arg( + "com.smartitengineering.cms.repo.workspace.name").arg(wId[1])); block.add(JExpr.invoke("bind").arg(stringClass).invoke("annotatedWith").arg(namesClass.staticInvoke("named"). - arg("cmsWorkspaceNamespace")).invoke("toInstance").arg(wId[0])); + arg("cmsWorkspaceNamespace")).invoke("toInstance").arg(workspaceNamespace)); block.add(JExpr.invoke("bind").arg(stringClass).invoke("annotatedWith").arg(namesClass.staticInvoke("named"). - arg("cmsWorkspaceName")).invoke("toInstance").arg(wId[1])); + arg("cmsWorkspaceName")).invoke("toInstance").arg(workspaceName)); { JClass typeLiteral = codeModel.ref(TypeLiteral.class); final JClass narrowedTypesLiteral = typeLiteral.narrow(codeModel.ref(List.class).narrow(String.class)); final JDefinedClass stringListType = moduleClass._class("InitializationContentTypes"); stringListType._extends(narrowedTypesLiteral); JVar typesList = block.decl(codeModel.ref(List.class).narrow(String.class), "contentTypes", JExpr._new(codeModel.ref(ArrayList.class).narrow(String.class))); for (String typeFile : typeFiles) { block.add(typesList.invoke("add").arg(typeFile)); } block.add(JExpr.invoke("bind").arg(JExpr._new(stringListType)).invoke( "annotatedWith").arg(namesClass.staticInvoke("named").arg("contentTypePath")).invoke("toInstance").arg( typesList)); JVar initVar = block.decl(codeModel.ref(Initializer.class), "initializer", - JExpr._new(codeModel.ref(Initializer.class)).arg(wId[0]).arg(wId[1]).arg(typesList)); + JExpr._new(codeModel.ref(Initializer.class)).arg(workspaceNamespace).arg(workspaceName). + arg(typesList)); block.add(initVar.invoke("init")); } } for (JDefinedClass clazz : modules.values()) { block.invoke("install").arg(JExpr._new(clazz)); } } private void generateAssociationIoCForFields(Collection<FieldDef> defs, JCodeModel model, JDefinedClass stringType, JClass typeLiteral, JDefinedClass moduleClass, JBlock block, Set<MutableContentType> types, Map<ContentTypeId, JDefinedClass> classes, String namePrefix, final Set<ContentTypeId> idsConfigdFor) throws JClassAlreadyExistsException { for (FieldDef def : defs) { final ContentDataType contentDataType; final String probablePrefix = new StringBuilder(namePrefix).append(def.getName().substring(0, 1).toUpperCase()). append(def.getName().substring(1)).toString(); switch (def.getValueDef().getType()) { case CONTENT: contentDataType = (ContentDataType) def.getValueDef(); break; case COLLECTION: CollectionDataType collectionDataType = (CollectionDataType) def.getValueDef(); if (collectionDataType.getItemDataType().getType().equals(FieldValueType.CONTENT)) { contentDataType = (ContentDataType) collectionDataType.getItemDataType(); } else if (collectionDataType.getItemDataType().getType().equals(FieldValueType.COMPOSITE)) { CompositeDataType compositeDataType = (CompositeDataType) collectionDataType.getItemDataType(); generateAssociationIoCForFields(getAllComposedFields(compositeDataType, types), model, stringType, typeLiteral, moduleClass, block, types, classes, probablePrefix, idsConfigdFor); contentDataType = null; } else { contentDataType = null; } break; case COMPOSITE: CompositeDataType compositeDataType = (CompositeDataType) def.getValueDef(); generateAssociationIoCForFields(getAllComposedFields(compositeDataType, types), model, stringType, typeLiteral, moduleClass, block, types, classes, probablePrefix, idsConfigdFor); default: contentDataType = null; break; } if (contentDataType != null && !idsConfigdFor.contains(contentDataType.getTypeDef())) { idsConfigdFor.add(contentDataType.getTypeDef()); JBlock mapBindingBlock = block.block(); JDefinedClass definedClass = classes.get(contentDataType.getTypeDef()); final JClass assocType = model.ref(CommonReadDao.class).narrow(definedClass.wildcard()).narrow(String.class); final JClass narrowedReadTypeLiteral = typeLiteral.narrow(assocType); final JDefinedClass assocDaoTypeLit = moduleClass._class(new StringBuilder(probablePrefix).append("DaoType"). toString()); assocDaoTypeLit._extends(narrowedReadTypeLiteral); JVar mapBinderVar = mapBindingBlock.decl(model.ref(MapBinder.class).narrow(String.class).narrow(assocType), "mapBinder", model.ref(MapBinder.class).staticInvoke("newMapBinder"). arg(JExpr._this().invoke("binder")).arg(JExpr._new(stringType)).arg(JExpr._new(assocDaoTypeLit))); Collection<ContentType> concreteInstances = findConcreteInstanceOf(contentDataType.getTypeDef(), types); for (ContentType concreteInstance : concreteInstances) { JDefinedClass concClass = classes.get(concreteInstance.getContentTypeID()); if (concClass == null) { continue; } final JClass concType = model.ref(CommonReadDao.class).narrow(concClass).narrow(String.class); final JClass narrowedConcReadTypeLiteral = typeLiteral.narrow(concType); final String name = concreteInstance.getContentTypeID().getName(); final JDefinedClass concDaoTypeLit = moduleClass._class(new StringBuilder(probablePrefix).append(name. substring(0, 1).toUpperCase()).append(name.substring(1)).append("DaoType"). toString()); concDaoTypeLit._extends(narrowedConcReadTypeLiteral); mapBindingBlock.add(mapBinderVar.invoke("addBinding").arg(JExpr.lit(concreteInstance.getContentTypeID(). toString())).invoke("to").arg(JExpr._new(concDaoTypeLit))); } } } } private Collection<ContentType> findConcreteInstanceOf(final ContentTypeId typeDef, final Collection<? extends ContentType> types) { if (types == null || typeDef == null || types.isEmpty()) { return Collections.emptyList(); } final List<ContentType> instanceOfTypes = new ArrayList<ContentType>(); final Map<ContentTypeId, ContentType> typeMap = new HashMap<ContentTypeId, ContentType>(); for (ContentType type : types) { typeMap.put(type.getContentTypeID(), type); } for (ContentType type : types) { if (type.getDefinitionType().equals(DefinitionType.CONCRETE_TYPE)) { boolean isInstanceOf = isInstanceOf(type, typeDef, typeMap); if (isInstanceOf) { instanceOfTypes.add(type); } } } return instanceOfTypes; } private boolean isInstanceOf(ContentType type, final ContentTypeId typeDef, Map<ContentTypeId, ContentType> types) { boolean isInstanceOf = false; if (type.getContentTypeID().equals(typeDef)) { isInstanceOf = true; } if (!isInstanceOf) { ContentTypeId parentId = type.getParent(); if (!isInstanceOf && parentId != null && types.get(parentId) != null) { isInstanceOf = isInstanceOf(types.get(parentId), typeDef, types); } } return isInstanceOf; } }
SmartITEngineering/smart-cms
d7f7e2745f378b227bb735966e6dcb3c2eba8f36
Add @Transactional annotation interceptor
diff --git a/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionImplModule.java b/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionImplModule.java index 558987d..f274986 100644 --- a/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionImplModule.java +++ b/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionImplModule.java @@ -1,24 +1,29 @@ package com.smartitengineering.cms.repo.dao.impl.tx; import com.google.inject.AbstractModule; import com.google.inject.Singleton; import com.google.inject.assistedinject.FactoryModuleBuilder; +import com.google.inject.matcher.Matchers; import com.smartitengineering.cms.repo.dao.tx.Transaction; import com.smartitengineering.cms.repo.dao.tx.TransactionManager; +import com.smartitengineering.cms.repo.dao.tx.Transactional; /** * * @author imyousuf */ public class TransactionImplModule extends AbstractModule { @Override protected void configure() { bind(TransactionInMemoryCache.class).to(TransactionInMemoryCacheImpl.class).in(Singleton.class); bind(TransactionService.class).to(TransactionServiceImpl.class).in(Singleton.class); bind(TransactionManager.class).to(TransactionManagerImpl.class).in(Singleton.class); install(new FactoryModuleBuilder().implement(TransactionStoreKey.class, TransactionStoreKeyImpl.class).implement( TransactionStoreValue.class, TransactionStoreValueImpl.class).implement(Transaction.class, TransactionImpl.class). build(TransactionFactory.class)); + TransactionalInterceptor interceptor = new TransactionalInterceptor(); + super.requestInjection(interceptor); + bindInterceptor(Matchers.any(), Matchers.annotatedWith(Transactional.class), interceptor); } } diff --git a/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionManagerImpl.java b/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionManagerImpl.java index 7f44422..341036a 100644 --- a/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionManagerImpl.java +++ b/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionManagerImpl.java @@ -1,73 +1,74 @@ package com.smartitengineering.cms.repo.dao.impl.tx; import com.google.inject.Inject; import com.google.inject.Singleton; import com.smartitengineering.cms.repo.dao.tx.Transaction; import com.smartitengineering.cms.repo.dao.tx.TransactionCompletionEvent; import com.smartitengineering.cms.repo.dao.tx.TransactionCompletionListener; import com.smartitengineering.cms.repo.dao.tx.TransactionManager; import java.util.ArrayDeque; import java.util.Deque; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author imyousuf */ @Singleton class TransactionManagerImpl implements TransactionManager, TransactionCompletionListener { private final ThreadLocal<Deque<Transaction>> transactions = new ThreadLocal<Deque<Transaction>>(); private final TransactionFactory factory; private final TransactionInMemoryCache memCache; private static final Logger LOGGER = LoggerFactory.getLogger(TransactionManagerImpl.class); @Inject public TransactionManagerImpl(TransactionFactory factory, TransactionInMemoryCache memCache) { this.factory = factory; this.memCache = memCache; } public Transaction beginTransaction() { return beginTransaction(true); } public Transaction beginTransaction(boolean isolatedTransaction) { Deque<Transaction> stack = transactions.get(); if (stack == null) { stack = new ArrayDeque<Transaction>(); transactions.set(stack); } final Transaction tx = this.factory.createTransaction(isolatedTransaction); tx.addTransactionCompletionListener(this); stack.push(tx); return getCurrentTransaction(); } public Transaction getCurrentTransaction() { Deque<Transaction> stack = transactions.get(); if (stack != null) { return stack.peek(); } else { return null; } } public void transactionComplete(TransactionCompletionEvent event) { Deque<Transaction> stack = transactions.get(); - if (stack != null) { - if (stack.peek().equals(event.getTransaction())) { + if (stack != null && !stack.isEmpty()) { + final Transaction peek = stack.peek(); + if (peek.equals(event.getTransaction())) { stack.pop(); } else { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Removing a transaction (" + event.getTransaction().getId() + ") that is not the 'peek'"); } stack.remove(event.getTransaction()); } } memCache.removeTransactionReferences(event.getTransaction().getId()); } } diff --git a/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionalInterceptor.java b/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionalInterceptor.java new file mode 100644 index 0000000..49f352b --- /dev/null +++ b/code-generation/content-repo-dao-impl/src/main/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionalInterceptor.java @@ -0,0 +1,52 @@ +package com.smartitengineering.cms.repo.dao.impl.tx; + +import com.google.inject.Inject; +import com.smartitengineering.cms.repo.dao.tx.Transaction; +import com.smartitengineering.cms.repo.dao.tx.TransactionManager; +import com.smartitengineering.cms.repo.dao.tx.Transactional; +import java.lang.reflect.Method; +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +/** + * Implements AOP wrapper around {@link Transactional transact annotation}. + * @author imyousuf + */ +public class TransactionalInterceptor implements MethodInterceptor { + + @Inject + private TransactionManager manager; + + public Object invoke(MethodInvocation invocation) throws Throwable { + final Method method = invocation.getMethod(); + if(method == null) { + return null; + } + Transactional txa = method.getAnnotation(Transactional.class); + if (txa == null) { + return invocation.proceed(); + } + Transaction tx = manager.getCurrentTransaction(); + final boolean transactionStarted; + if (tx == null || !txa.propagationRequired()) { + tx = manager.beginTransaction(txa.isolated()); + transactionStarted = true; + } + else { + transactionStarted = false; + } + try { + Object obj = invocation.proceed(); + if (transactionStarted) { + tx.commit(); + } + return obj; + } + catch (Exception ex) { + if (transactionStarted) { + tx.rollback(); + } + throw ex; + } + } +} diff --git a/code-generation/content-repo-dao-impl/src/test/java/com/smartitengineering/cms/repo/dao/impl/tx/ImplicitTransactionTest.java b/code-generation/content-repo-dao-impl/src/test/java/com/smartitengineering/cms/repo/dao/impl/tx/ImplicitTransactionTest.java new file mode 100644 index 0000000..c05306d --- /dev/null +++ b/code-generation/content-repo-dao-impl/src/test/java/com/smartitengineering/cms/repo/dao/impl/tx/ImplicitTransactionTest.java @@ -0,0 +1,144 @@ +package com.smartitengineering.cms.repo.dao.impl.tx; + +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Inject; +import com.google.inject.Injector; +import com.google.inject.TypeLiteral; +import com.smartitengineering.cms.repo.dao.tx.TransactionException; +import com.smartitengineering.cms.repo.dao.tx.TransactionManager; +import com.smartitengineering.cms.repo.dao.tx.Transactional; +import com.smartitengineering.dao.common.CommonDao; +import com.smartitengineering.dao.common.CommonReadDao; +import com.smartitengineering.dao.common.CommonWriteDao; +import org.jmock.Expectations; +import org.jmock.Mockery; +import org.junit.Before; +import org.junit.Test; + +/** + * + * @author imyousuf + */ +public class ImplicitTransactionTest { + + private static class Services { + + private final CommonDao<DemoDomain, String> cmnDao; + private final CommonReadDao<DemoDomain, String> readDao; + private final CommonWriteDao<DemoDomain> writeDao; + + @Inject + public Services(CommonDao<DemoDomain, String> cmnDao, + CommonReadDao<DemoDomain, String> readDao, + CommonWriteDao<DemoDomain> writeDao) { + this.cmnDao = cmnDao; + this.readDao = readDao; + this.writeDao = writeDao; + } + + @Transactional + public void testCommit(DemoDomain d1) { + writeDao.save(d1); + } + + @Transactional + public void testRollback(DemoDomain d1) { + writeDao.save(d1); + throw new NullPointerException(); + } + + @Transactional + public void testHardRollback(DemoDomain d1, DemoDomain d2, DemoDomain d3) { + System.out.println("----------------------START---------------------------"); + writeDao.save(d1); + System.out.println("1"); + writeDao.delete(d2); + System.out.println("2"); + writeDao.update(d3); + System.out.println("3"); + System.out.println("----------------------DONE---------------------------"); + } + } + private Mockery mockery; + private CommonReadDao<DemoDomain, String> readDao; + private CommonWriteDao<DemoDomain> writeDao; + private Injector injector; + private Services services; + private TransactionManager manager; + + @Before + public void setup() { + mockery = new Mockery(); + readDao = mockery.mock(CommonReadDao.class); + writeDao = mockery.mock(CommonWriteDao.class); + injector = Guice.createInjector(new DemoDomainMasterModule(new AbstractModule() { + + @Override + protected void configure() { + bind(new TypeLiteral<Class<DemoDomain>>() { + }).toInstance(DemoDomain.class); + bind(new TypeLiteral<CommonWriteDao<DemoDomain>>() { + }).annotatedWith(Transactionable.class).toInstance(writeDao); + bind(new TypeLiteral<CommonReadDao<DemoDomain, String>>() { + }).annotatedWith(Transactionable.class).toInstance(readDao); + bind(Services.class); + } + })); + services = injector.getInstance(Services.class); + manager = injector.getInstance(TransactionManager.class); + } + + @Test + public void testImplicitCommit() { + final DemoDomain d1 = new DemoDomain(); + mockery.checking(new Expectations() { + + { + exactly(1).of(writeDao).save(d1); + } + }); + services.testCommit(d1); + mockery.assertIsSatisfied(); + } + + @Test(expected = NullPointerException.class) + public void testImplicitRollback() { + final DemoDomain d1 = new DemoDomain(); + services.testRollback(d1); + } + + @Test(expected = TransactionException.class) + public void testImplicitHardRollback() { + final DemoDomain d1 = new DemoDomain(); + d1.setId("1"); + final DemoDomain d2 = new DemoDomain(); + d2.setId("2"); + final DemoDomain d3 = new DemoDomain(); + d3.setId("3"); + mockery.checking(new Expectations() { + + { + exactly(1).of(readDao).getById("2"); + will(returnValue(d2)); + exactly(1).of(readDao).getById("3"); + will(returnValue(d3)); + exactly(1).of(writeDao).save(d1); + exactly(1).of(writeDao).delete(d2); + exactly(1).of(writeDao).update(d3); + will(throwException(new TransactionException())); + exactly(1).of(writeDao).save(d2); + exactly(1).of(writeDao).delete(d1); + } + }); + try { + services.testHardRollback(d1, d2, d3); + } + catch(RuntimeException ex) { + throw ex; + } + finally { + mockery.assertIsSatisfied(); + } + } +} diff --git a/code-generation/content-repo-dao-impl/src/test/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionalInterceptorTest.java b/code-generation/content-repo-dao-impl/src/test/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionalInterceptorTest.java new file mode 100644 index 0000000..bf1785f --- /dev/null +++ b/code-generation/content-repo-dao-impl/src/test/java/com/smartitengineering/cms/repo/dao/impl/tx/TransactionalInterceptorTest.java @@ -0,0 +1,288 @@ +package com.smartitengineering.cms.repo.dao.impl.tx; + +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.smartitengineering.cms.repo.dao.tx.Transaction; +import com.smartitengineering.cms.repo.dao.tx.TransactionException; +import com.smartitengineering.cms.repo.dao.tx.TransactionManager; +import com.smartitengineering.cms.repo.dao.tx.Transactional; +import java.lang.reflect.Method; +import org.aopalliance.intercept.MethodInvocation; +import org.jmock.Expectations; +import org.jmock.Mockery; +import org.jmock.Sequence; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * + * @author imyousuf + */ +public class TransactionalInterceptorTest { + + public static class TransactionalSampleUse { + + @Transactional(propagationRequired = false) + public void singleTransactionWithoutPropagation() { + } + + @Transactional(isolated = true) + public void singleTransactionWithIsolation() { + } + + @Transactional(isolated = false) + public void singleTransactionWithNonIsolation() { + } + + @Transactional + public void nestedTransactionWithNonPropagation() { + singleTransactionWithoutPropagation(); + } + + @Transactional + public void nestedTransactionWithPropagation() { + singleTransactionWithIsolation(); + } + + public void nonTransactional() { + } + } + private final Method propagtedIsolatedTransaction; + private final Method propagtedNonIsolatedTransaction; + private final Method propagtedIsolatedNestedTransaction; + private final Method nonPropagtedIsolatedNestedTransaction; + private final Method nonTransaction; + private final TransactionalSampleUse sampleService; + private Mockery mockery; + private TransactionManager mockManager; + private Injector injector; + private TransactionalInterceptor interceptor; + + public TransactionalInterceptorTest() { + try { + propagtedIsolatedTransaction = TransactionalSampleUse.class.getDeclaredMethod("singleTransactionWithIsolation"); + propagtedNonIsolatedTransaction = TransactionalSampleUse.class.getDeclaredMethod( + "singleTransactionWithNonIsolation"); + propagtedIsolatedNestedTransaction = TransactionalSampleUse.class.getDeclaredMethod( + "nestedTransactionWithPropagation"); + nonPropagtedIsolatedNestedTransaction = TransactionalSampleUse.class.getDeclaredMethod( + "singleTransactionWithoutPropagation"); + nonTransaction = TransactionalSampleUse.class.getDeclaredMethod("nonTransactional"); + sampleService = new TransactionalSampleUse(); + } + catch (Exception ex) { + throw new RuntimeException(ex); + } + } + + @Before + public void setup() { + mockery = new Mockery(); + mockManager = mockery.mock(TransactionManager.class); + injector = Guice.createInjector(new AbstractModule() { + + @Override + protected void configure() { + bind(TransactionManager.class).toInstance(mockManager); + bind(TransactionalInterceptor.class); + } + }); + interceptor = injector.getInstance(TransactionalInterceptor.class); + } + + @Test + public void testNullMethod() throws Throwable { + final MethodInvocation invocation = mockery.mock(MethodInvocation.class); + mockery.checking(new Expectations() { + + { + exactly(1).of(invocation).getMethod(); + will(returnValue(null)); + } + }); + interceptor.invoke(invocation); + mockery.assertIsSatisfied(); + } + + @Test + public void testNullAnnotation() throws Throwable { + final MethodInvocation invocation = mockery.mock(MethodInvocation.class); + mockery.checking(new Expectations() { + + { + exactly(1).of(invocation).getMethod(); + will(returnValue(nonTransaction)); + exactly(1).of(invocation).proceed(); + will(returnValue(sampleService)); + } + }); + Assert.assertSame(sampleService, interceptor.invoke(invocation)); + mockery.assertIsSatisfied(); + } + + @Test + public void testNewTransactionWithSuccess() throws Throwable { + final MethodInvocation invocation = mockery.mock(MethodInvocation.class); + mockery.checking(new Expectations() { + + { + Sequence seq = mockery.sequence("newTx"); + exactly(1).of(invocation).getMethod(); + will(returnValue(propagtedIsolatedTransaction)); + inSequence(seq); + exactly(1).of(mockManager).getCurrentTransaction(); + will(returnValue(null)); + inSequence(seq); + Transaction tx = mockery.mock(Transaction.class); + exactly(1).of(mockManager).beginTransaction(true); + will(returnValue(tx)); + inSequence(seq); + exactly(1).of(invocation).proceed(); + will(returnValue(sampleService)); + inSequence(seq); + exactly(1).of(tx).commit(); + inSequence(seq); + } + }); + Assert.assertSame(sampleService, interceptor.invoke(invocation)); + mockery.assertIsSatisfied(); + } + + @Test(expected = TransactionException.class) + public void testNewTransactionWithError() throws Throwable { + final MethodInvocation invocation = mockery.mock(MethodInvocation.class); + mockery.checking(new Expectations() { + + { + Sequence seq = mockery.sequence("newTxWithError"); + exactly(1).of(invocation).getMethod(); + will(returnValue(propagtedIsolatedTransaction)); + inSequence(seq); + exactly(1).of(mockManager).getCurrentTransaction(); + will(returnValue(null)); + inSequence(seq); + Transaction tx = mockery.mock(Transaction.class); + exactly(1).of(mockManager).beginTransaction(true); + will(returnValue(tx)); + inSequence(seq); + exactly(1).of(invocation).proceed(); + will(throwException(new TransactionException(new NullPointerException()))); + inSequence(seq); + exactly(1).of(tx).rollback(); + inSequence(seq); + } + }); + try { + interceptor.invoke(invocation); + } + finally { + mockery.assertIsSatisfied(); + } + } + + @Test + public void testNewNonIsolatedTransactionWithSuccess() throws Throwable { + final MethodInvocation invocation = mockery.mock(MethodInvocation.class); + mockery.checking(new Expectations() { + + { + Sequence seq = mockery.sequence("newTx"); + exactly(1).of(invocation).getMethod(); + will(returnValue(propagtedNonIsolatedTransaction)); + inSequence(seq); + exactly(1).of(mockManager).getCurrentTransaction(); + will(returnValue(null)); + inSequence(seq); + Transaction tx = mockery.mock(Transaction.class); + exactly(1).of(mockManager).beginTransaction(false); + will(returnValue(tx)); + inSequence(seq); + exactly(1).of(invocation).proceed(); + will(returnValue(sampleService)); + inSequence(seq); + exactly(1).of(tx).commit(); + inSequence(seq); + } + }); + Assert.assertSame(sampleService, interceptor.invoke(invocation)); + mockery.assertIsSatisfied(); + } + + @Test + public void testNestedTransactionWithoutPropagationWithSuccess() throws Throwable { + final MethodInvocation invocation = mockery.mock(MethodInvocation.class); + mockery.checking(new Expectations() { + + { + Sequence seq = mockery.sequence("newTx"); + Transaction tx = mockery.mock(Transaction.class, "tx0"); + exactly(1).of(mockManager).beginTransaction(true); + will(returnValue(tx)); + inSequence(seq); + exactly(1).of(invocation).getMethod(); + will(returnValue(nonPropagtedIsolatedNestedTransaction)); + inSequence(seq); + exactly(1).of(mockManager).getCurrentTransaction(); + will(returnValue(tx)); + inSequence(seq); + Transaction tx1 = mockery.mock(Transaction.class, "tx1"); + exactly(1).of(mockManager).beginTransaction(true); + will(returnValue(tx1)); + inSequence(seq); + exactly(1).of(invocation).proceed(); + will(returnValue(sampleService)); + inSequence(seq); + exactly(1).of(tx1).commit(); + inSequence(seq); + exactly(1).of(tx).commit(); + inSequence(seq); + } + }); + TransactionManager manager = injector.getInstance(TransactionManager.class); + Transaction tx = manager.beginTransaction(true); + try { + Assert.assertSame(sampleService, interceptor.invoke(invocation)); + } + finally { + tx.commit(); + } + mockery.assertIsSatisfied(); + } + + @Test + public void testNestedTransactionWithPropagationWithSuccess() throws Throwable { + final MethodInvocation invocation = mockery.mock(MethodInvocation.class); + mockery.checking(new Expectations() { + + { + Sequence seq = mockery.sequence("newTx"); + Transaction tx = mockery.mock(Transaction.class, "tx0"); + exactly(1).of(mockManager).beginTransaction(true); + will(returnValue(tx)); + inSequence(seq); + exactly(1).of(invocation).getMethod(); + will(returnValue(propagtedIsolatedNestedTransaction)); + inSequence(seq); + exactly(1).of(mockManager).getCurrentTransaction(); + will(returnValue(tx)); + inSequence(seq); + exactly(1).of(invocation).proceed(); + will(returnValue(sampleService)); + inSequence(seq); + exactly(1).of(tx).commit(); + inSequence(seq); + } + }); + TransactionManager manager = injector.getInstance(TransactionManager.class); + Transaction tx = manager.beginTransaction(true); + try { + Assert.assertSame(sampleService, interceptor.invoke(invocation)); + } + finally { + tx.commit(); + } + mockery.assertIsSatisfied(); + } +}