diff --git a/Gemfile b/Gemfile index d5c8c35d0..078289fe5 100644 --- a/Gemfile +++ b/Gemfile @@ -6,6 +6,7 @@ unless RUBY_PLATFORM =~ /w32/ gem 'iconv' end +gem 'grack', path:'./lib/grack' gem 'gitlab', path: 'lib/gitlab-cli' gem 'rest-client' gem "mysql2", "= 0.3.18" @@ -42,6 +43,9 @@ group :development, :test do gem 'pry-byebug' end gem 'pry-stack_explorer' + if RUBY_PLATFORM =~ /darwin/ + gem 'puma' + end end gem 'rspec-rails', '~> 3.0' diff --git a/app/assets/javascripts/system_messages.js.coffee b/app/assets/javascripts/system_messages.js.coffee new file mode 100644 index 000000000..761567942 --- /dev/null +++ b/app/assets/javascripts/system_messages.js.coffee @@ -0,0 +1,3 @@ +# Place all the behaviors and hooks related to the matching controller here. +# All this logic will automatically be available in application.js. +# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/ diff --git a/app/assets/stylesheets/system_messages.css.scss b/app/assets/stylesheets/system_messages.css.scss new file mode 100644 index 000000000..a9947d45a --- /dev/null +++ b/app/assets/stylesheets/system_messages.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the SystemMessages controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/app/controllers/account_controller.rb b/app/controllers/account_controller.rb index 181f76b22..af501fdf9 100644 --- a/app/controllers/account_controller.rb +++ b/app/controllers/account_controller.rb @@ -25,21 +25,33 @@ class AccountController < ApplicationController # Login request and validation def login if request.get? + @login = params[:login] || true if User.current.logged? - redirect_to home_url + redirect_to user_path(User.current) + else + render :layout => 'login' end else authenticate_user end end + # 服务协议 + def agreement + render :layout => 'static_base' + end + + def about_us + render :layout => 'static_base' + end + # Log out current user and redirect to welcome page def logout if User.current.anonymous? - redirect_to home_url + redirect_to signin_path elsif request.post? logout_user - redirect_to home_url + redirect_to signin_path end # display the logout form end @@ -50,16 +62,16 @@ class AccountController < ApplicationController # Lets user choose a new password def lost_password - (redirect_to(home_url); return) unless Setting.lost_password? + (redirect_to(signin_path); return) unless Setting.lost_password? if params[:token] @token = Token.find_token("recovery", params[:token].to_s) if @token.nil? || @token.expired? - redirect_to home_url + redirect_to signin_path return end @user = @token.user unless @user && @user.active? - redirect_to home_url + redirect_to signin_path return end if request.post? @@ -71,7 +83,7 @@ class AccountController < ApplicationController return end end - render :template => "account/password_recovery" + render :template => "account/password_recovery" return else if request.post? @@ -79,6 +91,7 @@ class AccountController < ApplicationController # user not found or not active unless user && user.active? flash.now[:error] = l(:notice_account_unknown_email) + render :layout => 'static_base' return end # user cannot change its password @@ -91,16 +104,17 @@ class AccountController < ApplicationController if token.save Mailer.run.lost_password(token) flash[:notice] = l(:notice_account_lost_email_sent) - redirect_to signin_url + redirect_to lost_password_path return end end + render :layout => 'static_base' end end # User self-registration def register - (redirect_to(home_url); return) unless Setting.self_registration? || session[:auth_source_registration] + (redirect_to(signin_path); return) unless Setting.self_registration? || session[:auth_source_registration] if request.get? session[:auth_source_registration] = nil @user = User.new(:language => current_language.to_s) @@ -128,10 +142,12 @@ class AccountController < ApplicationController end when '3' #register_automatically(@user) - unless @user.new_record? + if !@user.new_record? self.logged_user = @user flash[:notice] = l(:notice_account_activated) redirect_to my_account_url + else + redirect_to signin_path end else #register_manually_by_administrator(@user) @@ -175,11 +191,11 @@ class AccountController < ApplicationController # Token based account activation def activate - (redirect_to(home_url); return) unless Setting.self_registration? && params[:token].present? + (redirect_to(signin_path); return) unless Setting.self_registration? && params[:token].present? token = Token.find_token('register', params[:token].to_s) - (redirect_to(home_url); return) unless token and !token.expired? + (redirect_to(signin_path); return) unless token and !token.expired? user = token.user - (redirect_to(home_url); return) unless user.registered? + (redirect_to(signin_path); return) unless user.registered? user.activate if user.save token.destroy @@ -266,7 +282,7 @@ class AccountController < ApplicationController user = User.find_or_initialize_by_identity_url(identity_url) if user.new_record? # Self-registration off - (redirect_to(home_url); return) unless Setting.self_registration? + (redirect_to(signin_path); return) unless Setting.self_registration? # Create on the fly user.login = registration['nickname'] unless registration['nickname'].nil? @@ -353,12 +369,15 @@ class AccountController < ApplicationController def invalid_credentials logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}" - flash.now[:error] = l(:notice_account_invalid_creditentials) + flash[:error] = l(:notice_account_invalid_creditentials) + # render :layout => 'login' + redirect_to signin_path(:login=>true) end def invalid_credentials_new logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}" - flash.now[:error] = l(:notice_account_invalid_creditentials_new) + flash[:error] = l(:notice_account_invalid_creditentials_new) + render signin_path(:login=>true) end # Register a user for email activation. diff --git a/app/controllers/admin_controller.rb b/app/controllers/admin_controller.rb index a44b58789..5666934b6 100644 --- a/app/controllers/admin_controller.rb +++ b/app/controllers/admin_controller.rb @@ -79,6 +79,11 @@ class AdminController < ApplicationController end end + # 系统消息 + def messages + @admin_messages = SystemMessage.new + end + def plugins @plugins = Redmine::Plugin.all end @@ -395,4 +400,78 @@ class AdminController < ApplicationController end + #留言列表 + def leave_messages + @jour = JournalsForMessage.find_by_sql("SELECT * FROM journals_for_messages AS j1 + WHERE j1.jour_type IN ('Course','Principal') AND (j1.m_parent_id IS NULL OR (j1.m_parent_id IN (SELECT id FROM journals_for_messages WHERE jour_type IN ('Course','Principal')))) order by created_on desc") + @jour = paginateHelper @jour,30 + @page = (params['page'] || 1).to_i - 1 + respond_to do |format| + format.html + end + end + + #帖子 + def messages_list + @memo = Memo.reorder("created_at desc") + @memo = paginateHelper @memo,30 + @page = (params['page'] || 1).to_i - 1 + respond_to do |format| + format.html + end + end + + #课程讨论区的帖子 + def course_messages + @course_ms=Message.joins("join boards on messages.board_id=boards.id where boards.course_id is not NULL").reorder('created_on desc') + @course_ms = paginateHelper @course_ms,30 + @page = (params['page'] || 1).to_i - 1 + respond_to do |format| + format.html + end + end + + #项目讨论区的帖子 + def project_messages + @project_ms=Message.joins("join boards on messages.board_id=boards.id where boards.project_id != -1").reorder('created_on desc') + @project_ms = paginateHelper @project_ms,30 + @page = (params['page'] || 1).to_i - 1 + respond_to do |format| + format.html + end + end + + #通知 + def notices + @news = News.where('course_id is not NULL').order('created_on desc') + @news = paginateHelper @news,30 + @page = (params['page'] || 1).to_i - 1 + respond_to do |format| + format.html + end + end + + #最近登录用户列表 + def latest_login_users + scope = User.order('last_login_on desc') + scope = scope.where("last_login_on>= '#{params[:startdate]} 00:00:00'") if params[:startdate].present? + scope =scope.where("last_login_on <= '#{params[:enddate]} 23:59:59'") if params[:enddate].present? + @user = scope + @user = paginateHelper @user,30 + @page = (params['page'] || 1).to_i - 1 + respond_to do |format| + format.html + end + end + + #作业 + def homework + @homework = HomeworkCommon.order('end_time desc') + @homework = paginateHelper @homework,30 + @page = (params['page'] || 1).to_i - 1 + respond_to do |format| + format.html + end + end + end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 10e5e6f06..a6554075f 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -557,12 +557,13 @@ class ApplicationController < ActionController::Base end def redirect_back_or_default(default, options={}) - back_url = params[:back_url].to_s + back_url = '' #params[:back_url].to_s if back_url.present? begin uri = URI.parse(back_url) # do not redirect user to another host or to the login or register page if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)}) + back_url = back_url.gsub(%r{\/users\/(\d+)},"/users/"+default.id.to_s) if default.is_a?(:User) redirect_to(back_url) return end diff --git a/app/controllers/boards_controller.rb b/app/controllers/boards_controller.rb index 6ff4d2f97..434ea4470 100644 --- a/app/controllers/boards_controller.rb +++ b/app/controllers/boards_controller.rb @@ -67,7 +67,29 @@ class BoardsController < ApplicationController end - def show + def show + # 讨论区消息状态更新(已读和未读) + if @project + query_forge_messages = @board.messages + query_forge_messages.each do |query_forge_message| + query = query_forge_message.forge_messages + query.each do |forge_message| + if User.current.id == forge_message.user_id + forge_message.update_attributes(:viewed => true) + end + end + end + elsif @course + query_course_messages = @board.messages + query_course_messages.each do |query_course_message| + query = query_course_message.course_messages + query.each do |course_message| + if User.current.id == course_message.user_id + course_message.update_attributes(:viewed => true) + end + end + end + end respond_to do |format| format.js format.html { @@ -79,8 +101,9 @@ class BoardsController < ApplicationController @topic_count = @board ? @board.topics.count : 0 if @project @topic_pages = Paginator.new @topic_count, per_page_option, params['page'] + #现在发布帖子的时候置顶功能已经没有了。所以取消这个置顶排序 #{Message.table_name}.sticky DESC, @topics = @board.topics. - reorder("#{Message.table_name}.sticky DESC, #{Message.table_name}.created_on desc"). + reorder("#{Message.table_name}.created_on desc"). includes(:last_reply). limit(@topic_pages.per_page). offset(@topic_pages.offset). diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb index c10f8bc84..8a64918ae 100644 --- a/app/controllers/comments_controller.rb +++ b/app/controllers/comments_controller.rb @@ -19,7 +19,7 @@ class CommentsController < ApplicationController default_search_scope :news include ApplicationHelper model_object News - before_filter :find_model_object + before_filter :find_model_object before_filter :find_project_from_association before_filter :authorize @@ -34,24 +34,41 @@ class CommentsController < ApplicationController ids = params[:asset_id].split(',') update_kindeditor_assets_owner ids,@comment.id,OwnerTypeHelper::COMMENT end - # ض̬ļ¼add start - if( @comment.id && @news.course ) - if(@news.author_id != User.current.id) - notify = ActivityNotify.new() - notify.activity_container_id = @news.course.id - notify.activity_container_type = 'Course' - notify.activity_id = @comment.id - notify.activity_type = 'Comment' - notify.notify_to = @news.author_id - notify.is_read = 0 - notify.save() - end - end - # ض̬ļ¼add end + # # ������ض�̬�ļ�¼add start + # if( @comment.id && @news.course ) + # if(@news.author_id != User.current.id) + # notify = ActivityNotify.new() + # notify.activity_container_id = @news.course.id + # notify.activity_container_type = 'Course' + # notify.activity_id = @comment.id + # notify.activity_type = 'Comment' + # notify.notify_to = @news.author_id + # notify.is_read = 0 + # notify.save() + # end + # end + # # ������ض�̬�ļ�¼add end flash[:notice] = l(:label_comment_added) + course_activity = CourseActivity.where("course_act_type='News' and course_act_id =#{@news.id}").first + if course_activity + course_activity.updated_at = Time.now + course_activity.save + end + user_activity = UserActivity.where("act_type='News' and act_id =#{@news.id}").first + if user_activity + user_activity.updated_at = Time.now + user_activity.save + end end - redirect_to news_url(@news) + if params[:user_activity_id] + @user_activity_id = params[:user_activity_id] + respond_to do |format| + format.js + end + else + redirect_to news_url(@news) + end end def destroy @@ -69,6 +86,6 @@ class CommentsController < ApplicationController @comment = nil @news end - - + + end diff --git a/app/controllers/courses_controller.rb b/app/controllers/courses_controller.rb index 1623979f0..e12d4886a 100644 --- a/app/controllers/courses_controller.rb +++ b/app/controllers/courses_controller.rb @@ -8,7 +8,7 @@ class CoursesController < ApplicationController helper :attachments helper :activity_notifys - before_filter :auth_login1, :only => [:show, :feedback] + before_filter :auth_login1, :only => [:show, :course_activity, :feedback] menu_item :overview menu_item :feedback, :only => :feedback menu_item :homework, :only => :homework @@ -39,9 +39,14 @@ class CoursesController < ApplicationController else @state = 5 #未登录 end - respond_to do |format| - format.js { render :partial => 'set_join', :locals => {:user => user, :course => course, :object_id => params[:object_id]} } - end + # if @state == 1 || @state == 3 + # respond_to course_path(course.id) + # else + respond_to do |format| + format.js { render :partial => 'set_join', :locals => {:user => user, :course => course, :object_id => params[:object_id]} } + end + #end + rescue Exception => e @state = 4 #已经加入了课程 respond_to do |format| @@ -101,74 +106,18 @@ class CoursesController < ApplicationController # 课程搜索 # add by nwb def search - courses_all = Course.all_course - name = params[:name] - if name.blank? - @courses = [] - @courses_all = [] - @course_count = 0 - @course_pages = Paginator.new @course_count, per_page_option, params['page'] + if params[:name].empty? + courses = Course.visible + @courses = paginateHelper courses,10 else - @courses = courses_all.visible - if params[:name].present? - @courses_all = @courses.like(params[:name]) - else - @courses_all = @courses; - end - @course_count = @courses_all.count - @course_pages = Paginator.new @course_count, per_page_option, params['page'] - - # 课程的动态数 - @course_activity_count=Hash.new - @courses_all.each do |course| - @course_activity_count[course.id]=0 - end - - case params[:course_sort_type] - when '0' - @courses = @courses_all.order("created_at desc") - @s_type = 0 - @courses = @courses.offset(@course_pages.offset).limit(@course_pages.per_page) - - @course_activity_count=get_course_activity @courses,@course_activity_count - - when '1' - @courses = @courses_all.order("course_ac_para desc") - @s_type = 1 - @courses = @courses.offset(@course_pages.offset).limit(@course_pages.per_page) - - @course_activity_count=get_course_activity @courses,@course_activity_count - - when '2' - @courses = @courses_all.order("watchers_count desc") - @s_type = 2 - @courses = @courses.offset(@course_pages.offset).limit(@course_pages.per_page) - - @course_activity_count=get_course_activity @courses,@course_activity_count - - when '3' - @course_activity_count=get_course_activity @courses_all,@course_activity_count_array - @courses=handle_course @courses_all,@course_activity_count - @s_type = 3 - @courses = @courses[@course_pages.offset, @course_pages.per_page] - - else - @s_type = 0 - @courses = @courses_all.order("created_at desc") - @courses = @courses.offset(@course_pages.offset).limit(@course_pages.per_page) - - @course_activity_count=get_course_activity @courses,@course_activity_count - - end + courses = Course.visible.where("LOWER(name) like '%#{params[:name].to_s.downcase}%'") + @courses = paginateHelper courses,10 end - + @name = params[:name] + @type = 'courses' respond_to do |format| format.html { render :layout => 'course_base' - scope = Course - unless params[:closed] - scope = scope.active - end } format.atom { courses = Course.visible.order('created_on DESC').limit(Setting.feeds_limit.to_i).all @@ -519,13 +468,17 @@ class CoursesController < ApplicationController end def new - @course_type = params[:course_type] ||= params[:course] - @issue_custom_fields = IssueCustomField.sorted.all - @trackers = Tracker.sorted.all - @course = Course.new - @course.safe_attributes = params[:course] - # month = Time.now.month - render :layout => 'new_base' + if User.current.login? + @course_type = params[:course_type] ||= params[:course] + @issue_custom_fields = IssueCustomField.sorted.all + @trackers = Tracker.sorted.all + @course = Course.new + @course.safe_attributes = params[:course] + # month = Time.now.month + render :layout => 'new_base' + else + redirect_to signin_url + end end def desc_sort_course_by_avtivity(activity_count, courses) @@ -657,94 +610,37 @@ class CoursesController < ApplicationController end end + def course_activity + redirect_to course_url(@course, type: params[:type], page: params[:page]) + end + def show - if params[:jump] && redirect_to_course_menu_item(@course, params[:jump]) - return - end - @users_by_role = @course.users_by_role - if(User.find_by_id(CourseInfos.find_by_course_id(@course.id).try(:user_id))) - @user = User.find_by_id(CourseInfos.find_by_course_id(@course.id).user_id) - end - @key = User.current.rss_key - #新增内容 - @days = Setting.activity_days_default.to_i - if params[:from] - begin; @date_to = params[:from].to_date + 1; rescue; end - end - has = { - "show_course_files" => true, - "show_course_news" => true, - "show_course_messages" => true, - #"show_course_journals_for_messages" => true, - # "show_bids" => true, - # "show_homeworks" => true, - "show_polls" => true - } - @date_to ||= Date.today + 1 - @date_from = (@date_to - @days) > @course.created_at.to_date ? (@date_to - @days) : @course.created_at.to_date - @author = (params[:user_id].blank? ? nil : User.active.find(params[:user_id])) - if @author.nil? - # 显示老师和助教的活动 - # @authors = searchTeacherAndAssistant(@course) - @authors = course_all_member(@course) - events = [] - key = "course_events_#{@course.id}".to_sym - if Rails.env.production? && Setting.course_cahce_enabled? - events = Rails.cache.read(key) || [] - end - if events.empty? - @authors.each do |author| - @activity = Redmine::Activity::Fetcher.new(User.current, :course => @course, - :with_subprojects => false, - :author => author.user) - - @activity.scope_select {|t| has["show_#{t}"]} - # modify by nwb - # 添加私密性判断 - if User.current.member_of_course?(@course)|| User.current.admin? - events += @activity.events(@days, @course.created_at) - else - events += @activity.events(@days, @course.created_at, :is_public => 1) - end - end - Rails.cache.write(key, events) if Rails.env.production? && Setting.course_cahce_enabled? + course_activities = @course.course_activities + @canShowRealName = User.current.member_of_course? @course + @page = params[:page] ? params[:page].to_i + 1 : 0 + if params[:type].present? + case params[:type] + when "homework" + @course_activities = course_activities.where("course_act_type = 'HomeworkCommon'").order('updated_at desc').limit(10).offset(@page * 10) + when "news" + @course_activities = course_activities.where("course_act_type = 'News'").order('updated_at desc').limit(10).offset(@page * 10) + when "message" + @course_activities = course_activities.where("course_act_type = 'Message'").order('updated_at desc').limit(10).offset(@page * 10) + when "poll" + @course_activities = course_activities.where("course_act_type = 'Poll'").order('updated_at desc').limit(10).offset(@page * 10) + when "attachment" + @course_activities = course_activities.where("course_act_type = 'Attachment'").order('updated_at desc').limit(10).offset(@page * 10) + when "journalsForMessage" + @course_activities = course_activities.where("course_act_type = 'JournalsForMessage'").order('updated_at desc').limit(10).offset(@page * 10) + else + @course_activities = course_activities.order('updated_at desc').limit(10).offset(@page * 10) end else - # @author = @course.teacher - @activity = Redmine::Activity::Fetcher.new(User.current, :course => @course, - :with_subprojects => false, - :author => @author) - - @activity.scope_select {|t| has["show_#{t}"]} - # modify by nwb - # 添加私密性判断 - if User.current.member_of_course?(@course)|| User.current.admin? - events = @activity.events(@days, @course.created_at) - else - events = @activity.events(@days, @course.created_at, :is_public => 1) - end - end - - # 无新动态时,显示老动态 - if events.count == 0 - if User.current.member_of_course?(@course)|| User.current.admin? - events = @activity.events - else - events = @activity.events(:is_public => 1) - end - end - @sort_by = %w(category date title author).include?(params[:sort_by]) ? params[:sort_by] : 'category' - if(User.find_by_id(CourseInfos.find_by_course_id(@course.id).try(:user_id))) - @user = User.find_by_id(CourseInfos.find_by_course_id(@course.id).user_id) + @course_activities = course_activities.order('updated_at desc').limit(10).offset(@page * 10) end - - sorted_events = sort_activity_events_course(events) - events = paginateHelper sorted_events,10 - @events_by_day = events.group_by {|event| User.current.time_to_date(event.event_datetime)} - # documents - - + @type = params[:type] respond_to do |format| + format.js format.html{render :layout => 'base_courses'} format.api end @@ -761,6 +657,11 @@ class CoursesController < ApplicationController end def feedback + @course.journals_for_messages.each do |messages| + query = messages.course_messages.where("user_id = ?", User.current.id) + query.update_all(:viewed => true); + end + if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course))) page = params[:page] # Find the page of the requested reply diff --git a/app/controllers/files_controller.rb b/app/controllers/files_controller.rb index 19c1214e2..057d962c8 100644 --- a/app/controllers/files_controller.rb +++ b/app/controllers/files_controller.rb @@ -134,8 +134,12 @@ class FilesController < ApplicationController if sort == "" sort = "created_on DESC" end + if keywords != "%%" resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' AND filename LIKE :like ", like: "%#{keywords}%"). reorder(sort) + else + resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' "). reorder(sort) + end #resultSet = Attachment.find_by_sql("SELECT `attachments`.* FROM `attachments` LEFT OUTER JOIN `homework_attaches` ON `attachments`.container_type = 'HomeworkAttach' AND `attachments`.container_id = `homework_attaches`.id LEFT OUTER JOIN `homework_for_courses` ON `homework_attaches`.bid_id = `homework_for_courses`.bid_id LEFT OUTER JOIN `homework_for_courses` AS H_C ON `attachments`.container_type = 'Bid' AND `attachments`.container_id = H_C.bid_id WHERE (`homework_for_courses`.course_id = 117 OR H_C.course_id = 117 OR (`attachments`.container_type = 'Course' AND `attachments`.container_id = 117)) AND `attachments`.filename LIKE '%#{keywords}%'").reorder("created_on DESC") end @@ -176,12 +180,6 @@ class FilesController < ApplicationController def index @flag = params[:flag] || false - #sort_init 'filename', 'asc' - sort_init 'created_on', 'desc' - sort_update 'created_on' => "#{Attachment.table_name}.created_on", - 'filename' => "#{Attachment.table_name}.filename", - 'size' => "#{Attachment.table_name}.filesize", - 'downloads' => "#{Attachment.table_name}.downloads" sort = "" @sort = "" @order = "" @@ -553,7 +551,7 @@ class FilesController < ApplicationController q = "%#{@q.strip}%" @result = find_course_attache q,@course,sort @result = visable_attachemnts @result - @result = @result.select{|attachment| attachment.tag_list.include?(@tag_name)} + @result = @result.select{|attachment| attachment.tag_list.include?(@tag_name)} unless @tag_name.blank? @searched_attach = paginateHelper @result,10 @tag_list = get_course_tag_list @course diff --git a/app/controllers/forums_controller.rb b/app/controllers/forums_controller.rb index 2b44d51de..efbb4ffab 100644 --- a/app/controllers/forums_controller.rb +++ b/app/controllers/forums_controller.rb @@ -7,7 +7,7 @@ class ForumsController < ApplicationController before_filter :find_forum_if_available before_filter :authenticate_user_edit, :only => [:edit, :update] before_filter :authenticate_user_destroy, :only => [:destroy] - before_filter :require_login, :only => [:new, :create] + before_filter :require_login, :only => [:new, :create,:destroy,:update,:edit] helper :sort include SortHelper @@ -97,7 +97,24 @@ class ForumsController < ApplicationController def index @offset, @limit = api_offset_and_limit({:limit => 10}) - @forums_all = Forum.reorder("sticky DESC") + if(params[:reorder_complex]) + @type="reorder_complex" + @str=params[:reorder_complex] + @forums_all = Forum.reorder("topic_count #{params[:reorder_complex]},updated_at #{params[:reorder_complex]}") + elsif(params[:reorder_popu]) + @type="reorder_popu" + @str=params[:reorder_popu] + @forums_all = Forum.reorder("topic_count #{params[:reorder_popu]}") + elsif(params[:reorder_time]) + @type="reorder_time" + @str=params[:reorder_time] + @forums_all = Forum.reorder("updated_at #{params[:reorder_time]}") + else + params[:reorder_complex] = "desc" + @type="reorder_complex" + @str=params[:reorder_complex] + @forums_all = Forum.reorder("topic_count desc,updated_at desc") + end @forums_count = @forums_all.count @forums_pages = Paginator.new @forums_count, @limit, params['page'] @@ -106,6 +123,7 @@ class ForumsController < ApplicationController #@forums = Forum.all respond_to do |format| format.html # index.html.erb + format.js format.json { render json: @forums } end end @@ -113,11 +131,25 @@ class ForumsController < ApplicationController # GET /forums/1 # GET /forums/1.json def show - sort_init 'updated_at', 'desc' - sort_update 'created_at' => "#{Memo.table_name}.created_at", - 'replies' => "#{Memo.table_name}.replies_count", - 'updated_at' => "COALESCE (last_replies_memos.created_at, #{Memo.table_name}.created_at)" - + # sort_init 'updated_at', 'desc' + # sort_update 'created_at' => "#{Memo.table_name}.created_at", + # 'replies' => "#{Memo.table_name}.replies_count", + # 'updated_at' => "COALESCE (last_replies_memos.created_at, #{Memo.table_name}.created_at)" + order = "" + @order_str = "" + if(params[:reorder_complex]) + order = " last_replies_memos.created_at #{params[:reorder_complex]}, #{Memo.table_name}.created_at #{params[:reorder_complex]}" + @order_str = "reorder_complex="+params[:reorder_complex] + elsif(params[:reorder_popu]) + order = "replies_count #{params[:reorder_popu]}" + @order_str = "reorder_popu="+params[:reorder_popu] + elsif(params[:reorder_time]) + order = "#{Memo.table_name}.updated_at #{params[:reorder_time]}" + @order_str = "reorder_time="+params[:reorder_time] + else + order = "last_replies_memos.created_at desc, #{Memo.table_name}.created_at desc" + @order_str = "reorder_complex=desc" + end @memo = Memo.new(:forum => @forum) @topic_count = @forum.topics.count @topic_pages = Paginator.new @topic_count, per_page_option, params['page'] @@ -126,19 +158,15 @@ class ForumsController < ApplicationController includes(:last_reply). limit(@topic_pages.per_page). offset(@topic_pages.offset). - order(sort_clause). + reorder(order). preload(:author, {:last_reply => :author}). all @memos - # @offset, @limit = api_offset_and_limit({:limit => 10}) - # @forum = Forum.find(params[:id]) - # @memos_all = @forum.topics - # @topic_count = @memos_all.count - # @topic_pages = Paginator.new @topic_count, @limit, params['page'] - - # @offset ||= @topic_pages.offset - # @memos = @memos_all.offset(@offset).limit(@limit).all + @my_topic_count = Memo.where("forum_id = #{@forum.id} and author_id = #{User.current.id} and parent_id is null").count + @my_replies_count = Memo.where("forum_id = #{@forum.id} and author_id = #{User.current.id} and parent_id is not null").count + @errors = params[:errors] respond_to do |format| + format.js format.html { render :layout => 'base_forums' }# show.html.erb @@ -172,20 +200,23 @@ class ForumsController < ApplicationController # Author lizanle # Description after save后需要进行资源记录的更新 # owner_type = 2 对应的是 forum + @save_flag=true if params[:asset_id] ids = params[:asset_id].split(',') update_kindeditor_assets_owner ids ,@forum.id,OwnerTypeHelper::FORUM end #end respond_to do |format| - + format.js format.html { redirect_to @forum, notice: l(:label_forum_create_succ) } format.json { render json: @forum, status: :created, location: @forum } end else + @save_flag=false respond_to do |format| flash.now[:error] = "#{l :label_forum_create_fail}: #{@forum.errors.full_messages[0]}" + format.js format.html { render action: "new" } format.json { render json: @forum.errors, status: :unprocessable_entity } end @@ -199,10 +230,12 @@ class ForumsController < ApplicationController respond_to do |format| if @forum.update_attributes(params[:forum]) + format.js {render :text=> true} format.html { redirect_to @forum, notice: l(:label_forum_update_succ) } format.json { head :no_content } else flash.now[:error] = "#{l :label_forum_update_fail}: #{@forum.errors.full_messages[0]}" + format.js { render :text=> false} format.html { render action: "edit" } format.json { render json: @forum.errors, status: :unprocessable_entity } end @@ -261,6 +294,52 @@ class ForumsController < ApplicationController end end + #检查forum的名字 + def check_forum_name + forum_name_exist = true + if params[:forum_id] + forum_name_exist = Forum.where("name = '#{params[:forum_name]}' and id != #{params[:forum_id]}").count >= 1 ? true : false + else + forum_name_exist = Forum.where("name = '#{params[:forum_name]}' ").count >= 1 ? true : false + end + render :text => forum_name_exist + end + + #添加论坛tag + def add_forum_tag + @forum = Forum.find(params[:id]) + unless @forum.nil? + @forum.tag_list.add(params[:tag_str].split(',')) + @forum.save + end + respond_to do |format| + format.js {render :delete_forum_tag} + end + end + + #删除forum的tag + def delete_forum_tag + @tag_id = (ActsAsTaggableOn::Tag.find_by_name(params[:tag_name])).id + #forum的taggable_type = 5 + @taggings = ActsAsTaggableOn::Tagging.find_by_tag_id_and_taggable_id_and_taggable_type(@tag_id,params[:id],'Forum') + + unless @taggings.nil? + @taggings.delete + end + + # 是否还有其他记录 引用了 tag_id + @tagging = ActsAsTaggableOn::Tagging.find_by_tag_id(@tag_id) + # 如果taggings表中记录已经不存在 ,那么检查tags表 作删除动作 + if @tagging.nil? + @tag = ActsAsTaggableOn::Tag.find_by_id(@tag_id) + @tag.delete unless @tag.nil? + end + @forum = Forum.find(params[:id]) + respond_to do |format| + format.js + end + end + private def find_forum_if_available diff --git a/app/controllers/git_usage_controller.rb b/app/controllers/git_usage_controller.rb deleted file mode 100644 index 56aaa56f1..000000000 --- a/app/controllers/git_usage_controller.rb +++ /dev/null @@ -1,12 +0,0 @@ -#added by baiyu -class GitUsageController < ApplicationController - layout "new_base" - def ch_usage - - end - - def en_usage - - end -end -#end \ No newline at end of file diff --git a/app/controllers/homework_common_controller.rb b/app/controllers/homework_common_controller.rb index e3424707f..9e3a4b836 100644 --- a/app/controllers/homework_common_controller.rb +++ b/app/controllers/homework_common_controller.rb @@ -3,282 +3,86 @@ class HomeworkCommonController < ApplicationController require 'json' require "base64" layout "base_courses" - before_filter :find_course, :only => [:index,:new,:create,:next_step] - before_filter :find_homework, :only => [:edit,:update,:alert_anonymous_comment,:start_anonymous_comment,:stop_anonymous_comment,:destroy] - before_filter :teacher_of_course, :only => [:new, :create, :edit, :update, :destroy, :start_anonymous_comment, :stop_anonymous_comment, :alert_anonymous_comment] + + include StudentWorkHelper + before_filter :find_course, :only => [:index,:new,:create] + before_filter :find_homework, :only => [:edit,:update,:alert_anonymous_comment,:start_anonymous_comment,:stop_anonymous_comment,:destroy,:start_evaluation_set,:set_evaluation_attr] + before_filter :teacher_of_course, :only => [:new, :create, :edit, :update, :destroy, :start_anonymous_comment, :stop_anonymous_comment, :alert_anonymous_comment,:start_evaluation_set,:set_evaluation_attr] before_filter :member_of_course, :only => [:index] def index - homeworks = @course.homework_commons.order("created_at desc") + @new_homework = HomeworkCommon.new + @new_homework.homework_detail_manual = HomeworkDetailManual.new + @new_homework.course = @course + @page = params[:page] ? params[:page].to_i + 1 : 0 + @homeworks = @course.homework_commons.order("created_at desc").limit(10).offset(@page * 10) @is_teacher = User.current.logged? && (User.current.admin? || User.current.allowed_to?(:as_teacher,@course)) @is_student = User.current.logged? && (User.current.admin? || (User.current.member_of_course?(@course) && !@is_teacher)) - @homeworks = paginateHelper homeworks,20 + @is_new = params[:is_new] respond_to do |format| + format.js format.html end end + #新建作业,在个人作业列表创建作业 def new - # @homework_type = "1" - # - # @homework = HomeworkCommon.new - # @homework.safe_attributes = params[:homework_common] - # @homework.late_penalty = 0 - # @homework.end_time = (Time.now + 3600 * 24).strftime('%Y-%m-%d') - # @homework.publish_time = Time.now.strftime('%Y-%m-%d') - # - # if @homework_type == "1" - # #匿评作业相关属性 - # @homework_detail_manual = HomeworkDetailManual.new - # @homework_detail_manual.ta_proportion = 0.6 - # @homework_detail_manual.absence_penalty = 0 - # @homework_detail_manual.evaluation_num = 3 - # @homework_detail_manual.evaluation_start = Time.now.strftime('%Y-%m-%d') - # @homework_detail_manual.evaluation_end = (Time.now + 3600 * 24).strftime('%Y-%m-%d') - # @homework.homework_detail_manual = @homework_detail_manual - # elsif @homework_type == "2" - # #编程作业相关属性 - # @homework_detail_programing = HomeworkDetailPrograming.new - # @homework.homework_detail_programing = @homework_detail_programing - # end - respond_to do |format| - format.html - end - end - - #新建作业下一步 - def next_step - @homework_type = params[:homework_common_type] - - @homework = HomeworkCommon.new - @homework.safe_attributes = params[:homework_common] - @homework.late_penalty = 0 - @homework.end_time = (Time.now + 3600 * 24).strftime('%Y-%m-%d') - @homework.publish_time = Time.now.strftime('%Y-%m-%d') - - if @homework_type == "1" - #匿评作业相关属性 - @homework_detail_manual = HomeworkDetailManual.new - @homework_detail_manual.ta_proportion = 0.6 - @homework_detail_manual.absence_penalty = 0 - @homework_detail_manual.evaluation_num = 3 - @homework_detail_manual.evaluation_start = Time.now.strftime('%Y-%m-%d') - @homework_detail_manual.evaluation_end = (Time.now + 3600 * 24).strftime('%Y-%m-%d') - @homework.homework_detail_manual = @homework_detail_manual - elsif @homework_type == "2" - #编程作业相关属性 - @homework_detail_programing = HomeworkDetailPrograming.new - @homework.homework_detail_programing = @homework_detail_programing - end - - - respond_to do |format| - format.html - end + render_404 end + #新建作业,在个人作业列表创建作业 def create - if params[:homework_common] - homework = HomeworkCommon.new - homework.name = params[:homework_common][:name] - homework.description = params[:homework_common][:description] - homework.end_time = params[:homework_common][:end_time] - homework.publish_time = params[:homework_common][:publish_time] - homework.homework_type = params[:homework_common][:homework_type] - homework.late_penalty = params[:late_penalty] - homework.user_id = User.current.id - homework.course_id = @course.id - - homework.save_attachments(params[:attachments]) - render_attachment_warning_if_needed(homework) - - if homework.homework_type == 2 - homework_detail_programing = HomeworkDetailPrograming.new - homework_detail_programing.language = params[:language] - homework_detail_programing.standard_code = params[:standard_code] - homework_detail_programing.ta_proportion = params[:ta_proportion] || 0.6 - question = {title:homework.name,content:homework.description} - question[:input] = [] - question[:output] = [] - if params[:input] && params[:output] && params[:result] - params[:input].each do |k,v| - if params[:output].include? k - homework_test = HomeworkTest.new - homework_test.input = v - homework_test.output = params[:output][k] - homework_test.result = params[:result][k] - homework.homework_tests << homework_test - question[:input] << homework_test.input - question[:output] << homework_test.output - end - end - end - - # uri = URI('http://test.gitlab.trustie.net/api/questions.json') - # req = Net::HTTP::Post.new(uri, initheader = {'Content-Type' =>'application/json'}) - # req.body = question.to_json - # res = Net::HTTP.start(uri.hostname, uri.port) do |http| - # http.request(req) - # end - - uri = URI('http://192.168.80.21:8080/api/questions.json') - body = question.to_json - res = Net::HTTP.new(uri.host, uri.port).start do |client| - request = Net::HTTP::Post.new(uri.path) - request.body = body - request["Content-Type"] = "application/json" - client.request(request) - end - result = JSON.parse(res.body) - homework_detail_programing.question_id = result["id"] if result["status"] && result["status"] == 0 - - homework.homework_detail_programing = homework_detail_programing - else - #匿评作业相关属性 - homework_detail_manual = HomeworkDetailManual.new - homework_detail_manual.ta_proportion = params[:ta_proportion] || 0.6 - homework_detail_manual.comment_status = 1 - homework_detail_manual.evaluation_start = params[:evaluation_start] - homework_detail_manual.evaluation_end = params[:evaluation_end] - homework_detail_manual.evaluation_num = params[:evaluation_num] - homework_detail_manual.absence_penalty = params[:absence_penalty] - homework.homework_detail_manual = homework_detail_manual - end - - if homework.save - homework_detail_programing.save if homework_detail_programing - homework_detail_manual.save if homework_detail_manual - respond_to do |format| - format.html { - flash[:notice] = l(:notice_successful_create) - redirect_to homework_common_index_path(:course => @course.id) - } - end - return - end - end - - respond_to do |format| - format.html { - flash[:notice] = l(:notice_failed_create) - redirect_to new_homework_common_path(:course => @course.id) - } - end + redirect_to user_homeworks_user_path(User.current.id) end def edit + @user = User.current + @is_in_course = params[:is_in_course].to_i respond_to do |format| - format.html + format.html{render :layout => 'new_base_user'} end end def update - @homework.name = params[:homework_common][:name] - @homework.description = params[:homework_common][:description] - @homework.end_time = params[:homework_common][:end_time] - @homework.publish_time = params[:homework_common][:publish_time] - @homework.homework_type = params[:homework_common][:homework_type] if params[:homework_common][:homework_type] - unless @homework.late_penalty == params[:late_penalty] - @homework.student_works.where("created_at > '#{@homework.end_time} 23:59:59'").each do |student_work| - student_work.late_penalty = params[:late_penalty] - student_work.save - end - @homework.late_penalty = params[:late_penalty] - end - # @homework.course_id = @course.id + if params[:homework_common] + @homework.name = params[:homework_common][:name] + @homework.description = params[:homework_common][:description] + @homework.end_time = params[:homework_common][:end_time] || Time.now + @homework.course_id = params[:course_id] - #匿评作业相关属性 - if @homework.homework_type == 1 && @homework_detail_manual - @homework_detail_manual.ta_proportion = params[:ta_proportion] || 0.6 - @homework_detail_manual.evaluation_start = params[:evaluation_start] - @homework_detail_manual.evaluation_end = params[:evaluation_end] - @homework_detail_manual.evaluation_num = params[:evaluation_num] - unless @homework_detail_manual.absence_penalty == params[:absence_penalty] - if @homework_detail_manual.comment_status == 3 #当前作业处于匿评结束状态,修改缺评扣分才会修改每个作品应扣分的值 - work_ids = "(" + @homework.student_works.map(&:id).join(",") + ")" - @homework.student_works.each do |student_work| - absence_penalty_count = student_work.user.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count - student_work.user.student_works_scores.where("student_work_id IN #{work_ids}").count - student_work.absence_penalty = absence_penalty_count > 0 ? absence_penalty_count * @homework_detail_manual.absence_penalty : 0 - student_work.save - end - end - @homework_detail_manual.absence_penalty = params[:absence_penalty] - end - elsif @homework.homework_type == 0 #普通作业,缺评扣分为0分,每个作品的缺评扣分改为0分,防止某些作业在结束匿评之后改为普通作业 - @homework.student_works.where("absence_penalty != 0").each do |student_work| - student_work.late_penalty = 0 - student_work.save - end - @homework_detail_manual.absence_penalty = 0 if @homework_detail_manual - end + homework_detail_manual = @homework.homework_detail_manual || HomeworkDetailManual.new + homework_detail_manual.evaluation_start = params[:evaluation_start].blank? ? @homework.end_time + 7 : params[:evaluation_start] + homework_detail_manual.evaluation_end = params[:evaluation_end].blank? ? homework_detail_manual.evaluation_start + 7 : params[:evaluation_end] - if @homework.homework_type == 2 && @homework_detail_programing #编程作业 - @homework_detail_programing.language = params[:language] - @homework_detail_programing.standard_code = params[:standard_code] - @homework_detail_programing.ta_proportion = params[:ta_proportion] || 0.6 - homework_tests = @homework.homework_tests - #需要删除的测试 - ids = homework_tests.map(&:id) - params[:input].keys.map(&:to_i) - ids.each do |id| - homework_test = HomeworkTest.find id - homework_test.destroy if homework_test - end - if params[:input] && params[:output] - params[:input].each do |k,v| - if params[:output].include? k - homework_test = HomeworkTest.find_by_id k - if homework_test #已存在的测试,修改 - homework_test.input = v - homework_test.output = params[:output][k] - else #不存在的测试,增加 - homework_test = HomeworkTest.new - homework_test.input = v - homework_test.output = params[:output][k] - homework_test.homework_common = @homework + @homework.save_attachments(params[:attachments]) + render_attachment_warning_if_needed(@homework) + + #编程作业相关属性 + if @homework.homework_type == 2 + @homework.homework_detail_programing ||= HomeworkDetailPrograming.new + @homework_detail_programing = @homework.homework_detail_programing + @homework_detail_programing.language = params[:language_type].to_i + + @homework.homework_tests.delete_all + inputs = params[:program][:input] + if Array === inputs + inputs.each_with_index do |val, i| + @homework.homework_tests << HomeworkTest.new( + input: val, + output: params[:program][:output][i] + ) end - homework_test.save end - end end - #发送修改作业的请求 - question = {title:@homework.name,content:@homework.description} - question[:input] = [] - question[:output] = [] - @homework.homework_tests.each do |test| - question[:input] << test.input - question[:output] << test.output - end - uri = URI("http://192.168.80.21:8080/api/questions/#{@homework_detail_programing.question_id}.json") - body = question.to_json - res = Net::HTTP.new(uri.host, uri.port).start do |client| - request = Net::HTTP::Put.new(uri.path) - request.body = body - request["Content-Type"] = "application/json" - client.request(request) - end - result = JSON.parse(res.body) - end - - @homework.save_attachments(params[:attachments]) - render_attachment_warning_if_needed(@homework) - - if @homework.save - @homework_detail_manual.save if @homework_detail_manual - @homework_detail_programing.save if @homework_detail_programing - respond_to do |format| - format.html { - flash[:notice] = l(:notice_successful_edit) + if @homework.save + @homework_detail_manual.save if @homework_detail_manual + @homework_detail_programing.save if @homework_detail_programing + if params[:is_in_course] == "1" redirect_to homework_common_index_path(:course => @course.id) - } - end - return - else - respond_to do |format| - format.html { - flash[:notice] = l(:notice_failed_edit) - redirect_to edit_homework_common_path(@homework) - } + else + redirect_to user_homeworks_user_path(User.current.id) + end end end end @@ -286,7 +90,13 @@ class HomeworkCommonController < ApplicationController def destroy if @homework.destroy respond_to do |format| - format.html {redirect_to homework_common_index_path(:course => @course.id)} + format.html { + if params[:is_in_course] == "1" + redirect_to homework_common_index_path(:course => @course.id) + else + redirect_to user_homeworks_user_path(User.current.id) + end + } end end end @@ -294,11 +104,11 @@ class HomeworkCommonController < ApplicationController #开启匿评 #statue 1:启动成功,2:启动失败,作业总数大于等于2份时才能启动匿评,3:已开启匿评,请务重复开启,4:没有开启匿评的权限 def start_anonymous_comment - @statue =4 and return unless User.current.admin? || User.current.allowed_to?(:as_teacher,@course) + @statue = 4 and return unless User.current.admin? || User.current.allowed_to?(:as_teacher,@course) @statue = 5 and return if Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d") if @homework_detail_manual.comment_status == 1 student_works = @homework.student_works - if student_works && student_works.size >=2 + if student_works && student_works.size >= 2 student_works.each_with_index do |work, index| user = work.user n = @homework_detail_manual.evaluation_num @@ -311,6 +121,9 @@ class HomeworkCommonController < ApplicationController end @homework_detail_manual.update_column('comment_status', 2) @statue = 1 + # 匿评开启消息邮件通知 + send_message_anonymous_comment(@homework, m_status = 2) + Mailer.send_mail_anonymous_comment_open(@homework).deliver else @statue = 2 end @@ -322,19 +135,29 @@ class HomeworkCommonController < ApplicationController #关闭匿评 def stop_anonymous_comment @homework_detail_manual.update_column('comment_status', 3) - + #计算缺评扣分 work_ids = "(" + @homework.student_works.map(&:id).join(",") + ")" @homework.student_works.each do |student_work| absence_penalty_count = student_work.user.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count - student_work.user.student_works_scores.where("student_work_id IN #{work_ids}").count student_work.absence_penalty = absence_penalty_count > 0 ? absence_penalty_count * @homework_detail_manual.absence_penalty : 0 student_work.save end - + # 匿评关闭消息邮件通知 + send_message_anonymous_comment(@homework, m_status = 3) + Mailer.send_mail_anonymous_comment_close(@homework).deliver respond_to do |format| format.js end end + # 开启/关闭匿评消息通知 + def send_message_anonymous_comment(homework, m_status ) + # status 标记匿评状态 1为关闭 0为开启 + course = homework.course + course.members.each do |m| + @homework.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => false, :status => m_status) + end + end #提示 def alert_anonymous_comment @cur_size = 0 @@ -365,11 +188,33 @@ class HomeworkCommonController < ApplicationController client.request(request) end result = JSON.parse(res.body) + @err_msg = result["compile_error_msg"] result["results"].each do |re| @result = re["status"] end end + #启动匿评参数设置 + def start_evaluation_set + + end + + #设置匿评参数 + def set_evaluation_attr + if @homework_detail_manual + unless params[:evaluation_start].to_s == @homework_detail_manual.evaluation_start.to_s + @homework_detail_manual.evaluation_start = params[:evaluation_start] + end + + unless @homework_detail_manual.evaluation_end.to_s == params[:evaluation_end].to_s + @homework_detail_manual.evaluation_end = params[:evaluation_end] + end + + @homework_detail_manual.evaluation_num = params[:evaluation_num] + @homework_detail_manual.save + end + end + private #获取课程 def find_course @@ -400,4 +245,4 @@ class HomeworkCommonController < ApplicationController student_works += student_works student_works[index + 1 .. index + n] end -end \ No newline at end of file +end diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index 539d84e65..923414583 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -20,11 +20,11 @@ class IssuesController < ApplicationController default_search_scope :issues before_filter :authorize1, :only => [:show] - before_filter :find_issue, :only => [:show, :edit, :update] + before_filter :find_issue, :only => [:show, :edit, :update,:add_journal] before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :destroy] before_filter :find_project, :only => [:new, :create, :update_form] #before_filter :authorize, :except => [:index, :show] - before_filter :authorize, :except => [:index] + before_filter :authorize, :except => [:index,:add_journal] before_filter :find_optional_project, :only => [:index] before_filter :check_for_default_issue_status, :only => [:new, :create] @@ -66,14 +66,14 @@ class IssuesController < ApplicationController if @query.valid? case params[:format] - when 'csv', 'pdf' - @limit = 10#Setting.issues_export_limit.to_i - when 'atom' - @limit = 10#Setting.feeds_limit.to_i - when 'xml', 'json' - @offset, @limit = api_offset_and_limit({:limit => 10}) - else - @limit = 10#per_page_option + when 'csv', 'pdf' + @limit = 10#Setting.issues_export_limit.to_i + when 'atom' + @limit = 10#Setting.feeds_limit.to_i + when 'xml', 'json' + @offset, @limit = api_offset_and_limit({:limit => 10}) + else + @limit = 10#per_page_option end @assign_to_id = params[:assigned_to_id] @author_id = params[:author_id] @@ -84,9 +84,9 @@ class IssuesController < ApplicationController @issue_pages = Paginator.new @issue_count, @limit, params['page'] @offset ||= @issue_pages.offset @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version], - :order => sort_clause, - :offset => @offset, - :limit => @limit) + :order => sort_clause, + :offset => @offset, + :limit => @limit) @issue_count_by_group = @query.issue_count_by_group respond_to do |format| format.js @@ -112,7 +112,19 @@ class IssuesController < ApplicationController end def show - + # 当前用户查看指派给他的缺陷消息,则设置消息为已读 + query = ForgeMessage.where("forge_message_type =? and user_id =? and forge_message_id =?", "Issue", User.current, @issue).first + query.update_attribute(:viewed, true) unless query.nil? + # 缺陷状态更新 + query_journals = @issue.journals + query_journals.each do |query_journal| + query_journal.forge_messages.each do |f| + if User.current.id == f.user_id + f.update_attributes(:viewed => true) + end + end + end + # end @journals = @issue.journals.includes(:user, :details).reorder("#{Journal.table_name}.id ASC").all @journals.each_with_index {|j,i| j.indice = i+1} @journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project) @@ -131,16 +143,16 @@ class IssuesController < ApplicationController @available_watchers = (@issue.project.users.sort + @issue.watcher_users).uniq respond_to do |format|`` - format.html { - retrieve_previous_and_next_issue_ids - render :template => 'issues/show', :layout => @project_base_tag#by young - } - format.api - format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' } - format.pdf { - pdf = issue_to_pdf(@issue, :journals => @journals) - send_data(pdf, :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") - } + format.html { + retrieve_previous_and_next_issue_ids + render :template => 'issues/show', :layout => @project_base_tag#by young + } + format.api + format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' } + format.pdf { + pdf = issue_to_pdf(@issue, :journals => @journals) + send_data(pdf, :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") + } end end @@ -207,7 +219,6 @@ class IssuesController < ApplicationController end if saved - #修改界面增加跟踪者 watcherlist = @issue.watcher_users select_users = [] @@ -237,9 +248,7 @@ class IssuesController < ApplicationController JournalReply.add_reply(@issue.current_journal.id, reply_id, User.current.id) end flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record? - respond_to do |format| - format.html { redirect_to issue_url(@issue.id) } format.api { render_api_ok } end @@ -310,8 +319,8 @@ class IssuesController < ApplicationController issue.reload if @copy issue = issue.copy({}, - :attachments => params[:copy_attachments].present?, - :subtasks => params[:copy_subtasks].present? + :attachments => params[:copy_attachments].present?, + :subtasks => params[:copy_subtasks].present? ) end journal = issue.init_journal(User.current, params[:notes]) @@ -341,21 +350,21 @@ class IssuesController < ApplicationController @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f if @hours > 0 case params[:todo] - when 'destroy' - # nothing to do - when 'nullify' - TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues]) - when 'reassign' - reassign_to = @project.issues.find_by_id(params[:reassign_to_id]) - if reassign_to.nil? - flash.now[:error] = l(:error_issue_not_found_in_project) - return + when 'destroy' + # nothing to do + when 'nullify' + TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues]) + when 'reassign' + reassign_to = @project.issues.find_by_id(params[:reassign_to_id]) + if reassign_to.nil? + flash.now[:error] = l(:error_issue_not_found_in_project) + return + else + TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues]) + end else - TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues]) - end - else - # display the destroy form if it's a user request - return unless api_request? + # display the destroy form if it's a user request + return unless api_request? end end @issues.each do |issue| @@ -371,6 +380,23 @@ class IssuesController < ApplicationController end end + def add_journal + if User.current.logged? + jour = Journal.new + jour.user_id = User.current.id + jour.notes = params[:notes] + jour.journalized = @issue + jour.save + user_activity = UserActivity.where("act_type='Issue' and act_id =#{@issue.id}").first + user_activity.updated_at = jour.created_on + user_activity.save + @user_activity_id = params[:user_activity_id] + respond_to do |format| + format.js + end + end + end + private def find_project @@ -411,14 +437,14 @@ class IssuesController < ApplicationController issue_attributes = params[:issue] if issue_attributes && params[:conflict_resolution] case params[:conflict_resolution] - when 'overwrite' - issue_attributes = issue_attributes.dup - issue_attributes.delete(:lock_version) - when 'add_notes' - issue_attributes = issue_attributes.slice(:notes) - when 'cancel' - redirect_to issue_url(@issue) - return false + when 'overwrite' + issue_attributes = issue_attributes.dup + issue_attributes.delete(:lock_version) + when 'add_notes' + issue_attributes = issue_attributes.slice(:notes) + when 'cancel' + redirect_to issue_url(@issue) + return false end end @issue.safe_attributes = issue_attributes diff --git a/app/controllers/journals_controller.rb b/app/controllers/journals_controller.rb index 6cebfef7a..a38bd4096 100644 --- a/app/controllers/journals_controller.rb +++ b/app/controllers/journals_controller.rb @@ -36,8 +36,7 @@ class JournalsController < ApplicationController sort_update(@query.sortable_columns) if @query.valid? - @journals = @query.journals(:order => "#{Journal.table_name}.created_on DESC", - :limit => 25) + @journals = @query.journals(:order => "#{Journal.table_name}.created_on DESC", :limit => 25) end @title = (@project ? @project.name : Setting.app_title) + ": " + (@query.new_record? ? l(:label_changes_details) : @query.name) render :layout => false, :content_type => 'application/atom+xml' @@ -72,9 +71,9 @@ class JournalsController < ApplicationController end # Replaces pre blocks with [...] text = text.to_s.strip.gsub(%r{
((.|\s)*?)
}m, '[...]') - @content = "> #{ll(Setting.default_language, :text_user_wrote, user)}\n> " - @content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n" - # @content = "
" << @content + @content = "#{ll(Setting.default_language, :text_user_wrote, user)}\n" + @content << text.gsub(/(\r?\n|\r\n?)/, "\n ") + "\n" + @content = "
" << @content << "
\n\n
" @id = user.id rescue ActiveRecord::RecordNotFound render_404 diff --git a/app/controllers/memos_controller.rb b/app/controllers/memos_controller.rb index 68f6f6473..4181090a5 100644 --- a/app/controllers/memos_controller.rb +++ b/app/controllers/memos_controller.rb @@ -11,7 +11,7 @@ class MemosController < ApplicationController include AttachmentsHelper include ApplicationHelper - layout 'base_memos' + # layout 'base_memos' def quote @subject = @memo.subject @@ -73,41 +73,14 @@ class MemosController < ApplicationController end end #end - format.html { redirect_to back_memo_url, notice: "#{l :label_memo_create_succ}" } - format.json { render json: @memo, status: :created, location: @memo } + format.html { redirect_to back_memo_url, notice: "#{l :label_memo_create_succ}" } + format.json { render json: @memo, status: :created, location: @memo } else flash.now[:error] = "#{l :label_memo_create_fail}: #{@memo.errors.full_messages[0]}" - # back_error_page = @memo.parent_id.nil? ? forum_path(@forum) : forum_memo_path(@forum, @memo.parent_id) - pre_count = REPLIES_PER_PAGE - - @memo_new = @memo.dup - @memo = @memo.root # 取出楼主,防止输入帖子id让回复作为主贴显示 - unless @memo.new_record? - @memo.update_column(:viewed_count, (@memo.viewed_count.to_i + 1)) - end - - - page = params[:page] - if params[:r] && page.nil? - offset = @memo.children.where("#{Memo.table_name}.id < ?", params[:r].to_i).count - page = 1 + offset / pre_count - else - - end - @reply_count = @memo.children.count - @reply_pages = Paginator.new @reply_count, pre_count, page - @replies = @memo.children. - includes(:author, :attachments). - reorder("#{Memo.table_name}.created_at DESC"). - limit(@reply_pages.per_page). - offset(@reply_pages.offset). - all - if @memo.new_record? - format.html { render :new,:layout=>'base'} - else - format.html { render action: :show } + format.js + format.html { redirect_to( forum_path(Forum.find(params[:forum_id]),:errors=>@memo.errors.full_messages[0])) } format.json { render json: @memo.errors, status: :unprocessable_entity } - end + #end end end @@ -115,8 +88,25 @@ class MemosController < ApplicationController REPLIES_PER_PAGE = 20 unless const_defined?(:REPLIES_PER_PAGE) def show - pre_count = REPLIES_PER_PAGE + # 更新贴吧帖子留言对应的memo_messages的viewed字段 + unless @memo.children.blank? + @memo.children.each do |child| + child.memo_messages.each do |memo_message| + if User.current.id == memo_message.user_id + memo_message.update_attributes(:viewed => true) + end + end + end + end + query_memo_messages = @memo.memo_messages + query_memo_messages.each do |query_memo_message| + if User.current.id == query_memo_message.user_id + query_memo_message.update_attributes(:viewed => true) + end + end + + pre_count = REPLIES_PER_PAGE @memo = @memo.root # 取出楼主,防止输入帖子id让回复作为主贴显示 @memo.update_column(:viewed_count, (@memo.viewed_count.to_i + 1)) @@ -138,21 +128,27 @@ class MemosController < ApplicationController @memo_new = Memo.new - + @my_topic_count = Memo.where("forum_id = #{@memo.forum_id} and author_id = #{User.current.id} and parent_id is null").count + @my_replies_count = Memo.where("forum_id = #{@memo.forum_id} and author_id = #{User.current.id} and parent_id is not null").count # @memo = Memo.find_by_id(params[:id]) # @forum = Forum.find(params[:forum_id]) # @replies = @memo.replies # @mome_new = Memo.new respond_to do |format| - format.html # show.html.erb + format.html {render :layout=> 'base_forums'}#:layout=> 'base_forums', format.json { render json: @memo } format.xml { render xml: @memo } end end def edit + @my_topic_count = Memo.where("forum_id = #{@memo.forum_id} and author_id = #{User.current.id} and parent_id is null").count + @my_replies_count = Memo.where("forum_id = #{@memo.forum_id} and author_id = #{User.current.id} and parent_id is not null").count @replying = false + respond_to do |format| + format.html {render :layout=>'base_forums'} + end end def update @@ -160,7 +156,8 @@ class MemosController < ApplicationController if( #@memo.update_column(:subject, params[:memo][:subject]) && @memo.update_column(:content, params[:memo][:content]) && @memo.update_column(:sticky, params[:memo][:sticky]) && - @memo.update_column(:lock, params[:memo][:lock])) + @memo.update_column(:lock, params[:memo][:lock]) && + @memo.update_column(:subject,params[:memo][:subject])) @memo.save_attachments(params[:attachments] || (params[:memo] && params[:memo][:uploads])) @memo.save # @memo.root.update_attribute(:updated_at, @memo.updated_at) @@ -211,7 +208,7 @@ class MemosController < ApplicationController end def back_memo_url - forum_memo_path(@forum, (@memo.parent_id.nil? ? @memo : @memo.parent_id)) + forum_memo_path(@forum, (@memo.root.nil? ? @memo : @memo.root)) end def back_memo_or_forum_url diff --git a/app/controllers/messages_controller.rb b/app/controllers/messages_controller.rb index a242587fb..4f3f3ec0d 100644 --- a/app/controllers/messages_controller.rb +++ b/app/controllers/messages_controller.rb @@ -89,72 +89,54 @@ class MessagesController < ApplicationController # Create a new topic def new - @message = Message.new - @message.author = User.current - @message.board = @board - @message.safe_attributes = params[:message] - if request.post? - @message.save_attachments(params[:attachments]) - if @message.save - # 更新kindeditor上传的图片资源所有者 - if params[:asset_id] - ids = params[:asset_id].split(',') - update_kindeditor_assets_owner ids,@message.id,OwnerTypeHelper::MESSAGE - end - # 与我相关动态的记录add start - if(@board && @board.course) #项目的先不管 - teachers = searchTeacherAndAssistant(@board.course) - for teacher in teachers - if(teacher.user_id != User.current.id) - notify = ActivityNotify.new() - if(@board.course) - notify.activity_container_id = @board.course_id - notify.activity_container_type = 'Course' - else - notify.activity_container_id = @board.project_id - notify.activity_container_type = 'Project' - end - notify.activity_id = @message.id - notify.activity_type = 'Message' - notify.notify_to = teacher.user_id - notify.is_read = 0 - notify.save() - end + if User.current.logged? + @message = Message.new + @message.author = User.current + @message.board = @board + @message.safe_attributes = params[:message] + if request.post? + @message.save_attachments(params[:attachments]) + if @message.save + # 更新kindeditor上传的图片资源所有者 + if params[:asset_id] + ids = params[:asset_id].split(',') + update_kindeditor_assets_owner ids,@message.id,OwnerTypeHelper::MESSAGE end - end - # 与我相关动态的记录add end - call_hook(:controller_messages_new_after_save, { :params => params, :message => @message}) - render_attachment_warning_if_needed(@message) - if params[:is_board] - if @project - redirect_to project_boards_path(@project) - elsif @course - redirect_to course_boards_path(@course) + call_hook(:controller_messages_new_after_save, { :params => params, :message => @message}) + render_attachment_warning_if_needed(@message) + if params[:is_board] + if @project + redirect_to project_boards_path(@project) + elsif @course + redirect_to course_boards_path(@course) + end + else + redirect_to board_message_url(@board, @message) end else - redirect_to board_message_url(@board, @message) + if params[:is_board] + if @project + redirect_to project_boards_path(@project, :flag => true) + elsif @course + redirect_to course_boards_path(@course, :flag => true) + end + else + layout_file = @project ? 'base_projects' : 'base_courses' + render :action => 'new', :layout => layout_file + end + end else - if params[:is_board] - if @project - redirect_to project_boards_path(@project, :flag => true) - elsif @course - redirect_to course_boards_path(@course, :flag => true) - end - else - layout_file = @project ? 'base_projects' : 'base_courses' - render :action => 'new', :layout => layout_file + respond_to do |format| + format.html { + layout_file = @project ? 'base_projects' : 'base_courses' + render :layout => layout_file + } end - end else - respond_to do |format| - format.html { - layout_file = @project ? 'base_projects' : 'base_courses' - render :layout => layout_file - } - end + redirect_to signin_path end end @@ -177,7 +159,19 @@ class MessagesController < ApplicationController @reply.board = @board @reply.safe_attributes = params[:reply] @reply.content = @quote + @reply.content + @reply.subject = "RE: #{@topic.subject}" unless params[:reply][:subject] + # @reply.reply_id = params[:id] @topic.children << @reply + course_activity = CourseActivity.where("course_act_type='Message' and course_act_id =#{@topic.id}").first + if course_activity + course_activity.updated_at = Time.now + course_activity.save + end + user_activity = UserActivity.where("act_type='Message' and act_id =#{@topic.id}").first + if user_activity + user_activity.updated_at = Time.now + user_activity.save + end #@topic.update_attribute(:updated_on, Time.now) if !@reply.new_record? if params[:asset_id] @@ -185,41 +179,18 @@ class MessagesController < ApplicationController update_kindeditor_assets_owner ids,@reply.id,OwnerTypeHelper::MESSAGE end - # 与我相关动态的记录add start - if(@board && @board.course) #项目的先不管 - notifyto_arr = {} - notifyto_arr[@topic.author_id] = @topic.author_id - if( params[:parent_topic] != nil && params[:parent_topic] != '') - parent_topic = Message.find(params[:parent_topic]) - notifyto_arr[parent_topic.author_id] = parent_topic.author_id - end - notifyto_arr.each do |k,user_id| - if(user_id != User.current.id) - notify = ActivityNotify.new() - if(@board.course) - notify.activity_container_id = @board.course_id - notify.activity_container_type = 'Course' - else - notify.activity_container_id = @board.project_id - notify.activity_container_type = 'Project' - end - notify.activity_id = @reply.id - notify.activity_type = 'Message' - notify.notify_to = user_id - notify.is_read = 0 - notify.save() - end - end - end - # 与我相关动态的记录add end - call_hook(:controller_messages_reply_after_save, { :params => params, :message => @reply}) attachments = Attachment.attach_files(@reply, params[:attachments]) render_attachment_warning_if_needed(@reply) else #render file: 'messages#show', layout: 'base_courses' end - if params[:is_board] + if params[:user_activity_id] + @user_activity_id = params[:user_activity_id] + respond_to do |format| + format.js + end + elsif params[:is_board] if @project redirect_to project_boards_path(@project) elsif @course diff --git a/app/controllers/my_controller.rb b/app/controllers/my_controller.rb index 103030d51..9728ddf11 100644 --- a/app/controllers/my_controller.rb +++ b/app/controllers/my_controller.rb @@ -137,7 +137,7 @@ class MyController < ApplicationController @se.identity = params[:identity].to_i if params[:identity] @se.technical_title = params[:technical_title] if params[:technical_title] @se.student_id = params[:no] if params[:no] - @se.brief_introduction = params[:brief_introduction] + # @se.brief_introduction = params[:brief_introduction] @se.description = params[:description] if @user.save && @se.save @@ -157,7 +157,7 @@ class MyController < ApplicationController File.delete(diskfile1) if File.exist?(diskfile1) end - render :layout=>'base_users_new' + render :layout=>'new_base_user' end # Destroys user's account @@ -174,7 +174,7 @@ class MyController < ApplicationController logout_user flash.now[:notice] = l(:notice_account_deleted) end - redirect_to home_url + redirect_to signin_path end end diff --git a/app/controllers/news_controller.rb b/app/controllers/news_controller.rb index 185e7128e..5d83c1320 100644 --- a/app/controllers/news_controller.rb +++ b/app/controllers/news_controller.rb @@ -72,7 +72,7 @@ class NewsController < ApplicationController @news_count = scope.count @q = params[:subject] - if params[:subject].nil? + if params[:subject].nil? || params[:subject].blank? scope_order = scope.all(:include => [:author, :course], :order => "#{News.table_name}.created_on DESC") else @@ -99,6 +99,33 @@ class NewsController < ApplicationController end def show + # 更新news对应的forge_messages的消息viewed字段 + if @project + query_message_news = @news.forge_messages + else + query_message_news = @news.course_messages + end + query_message_news.each do |query| + if User.current.id == query.user_id + query.update_attributes(:viewed => true) + end + end + # 更新项目新闻的评阅的消息viewed字段 + current_message_comments = @news.comments + current_message_comments.each do |current_message_comment| + if @project + query_message_comment = current_message_comment.forge_messages + else + query_message_comment = current_message_comment.course_messages + end + query_message_comment.each do |query| + if User.current.id == query.user_id + query.update_attributes(:viewed => true) + end + end + end + # end + cs = CoursesService.new result = cs.show_course_news params,User.current @news = result[:news] @@ -148,19 +175,19 @@ class NewsController < ApplicationController update_kindeditor_assets_owner ids,@news.id,OwnerTypeHelper::NEWS end # ������ض�̬�ļ�¼add start - teachers = searchTeacherAndAssistant(@course) - for teacher in teachers - if(teacher.user_id != User.current.id) - notify = ActivityNotify.new() - notify.activity_container_id = @course.id - notify.activity_container_type = 'Course' - notify.activity_id = @news.id - notify.activity_type = 'News' - notify.notify_to = teacher.user_id - notify.is_read = 0 - notify.save() - end - end + # teachers = searchTeacherAndAssistant(@course) + # for teacher in teachers + # if(teacher.user_id != User.current.id) + # notify = ActivityNotify.new() + # notify.activity_container_id = @course.id + # notify.activity_container_type = 'Course' + # notify.activity_id = @news.id + # notify.activity_type = 'News' + # notify.notify_to = teacher.user_id + # notify.is_read = 0 + # notify.save() + # end + # end # ������ض�̬�ļ�¼add end render_attachment_warning_if_needed(@news) flash[:notice] = l(:notice_successful_create) diff --git a/app/controllers/poll_controller.rb b/app/controllers/poll_controller.rb index dda5b81b2..a8f2a11f1 100644 --- a/app/controllers/poll_controller.rb +++ b/app/controllers/poll_controller.rb @@ -1,3 +1,4 @@ +#encoding utf-8 class PollController < ApplicationController before_filter :find_poll_and_course, :only => [:edit,:update,:destroy,:show,:statistics_result,:create_poll_question,:commit_poll,:commit_answer,:publish_poll,:republish_poll,:poll_result,:close_poll,:export_poll] before_filter :find_container, :only => [:new,:create, :index] @@ -27,6 +28,13 @@ class PollController < ApplicationController render_403 return end + # 问卷消息状态更新 + query_course_poll = @poll.course_messages + query_course_poll.each do |query| + if User.current.id == query.user_id + query.update_attributes(:viewed => true) + end + end #已提交问卷的用户不能再访问该界面 if has_commit_poll?(@poll.id,User.current.id) && (!User.current.admin?) redirect_to poll_index_url(:polls_type => "Course", :polls_group_id => @course.id) @@ -410,6 +418,70 @@ class PollController < ApplicationController end end + # 将其他地方的问卷导出来 + def other_poll + # 查作者是我,或者作者是当前课程的老师,且不在当前课程内的问卷 进行导入 + tea_ids = '(' + tea_ids << Course.find(params[:polls_group_id]).tea_id.to_s << ','<< User.current.id.to_s << ')' + @polls = Poll.where("user_id in #{tea_ids} and polls_type = 'course' and polls_group_id != #{params[:polls_group_id]}") + @polls_group_id = params[:polls_group_id] + respond_to do |format| + format.js + end + end + + # 将问卷导入本课程 + def import_other_poll + course_id = params[:course_id] + @course = Course.find(course_id) + params[:polls].each_with_index do |p,i| + poll = Poll.find(p) + option = { + :polls_name => poll.polls_name || l(:label_poll_new), + :polls_type => 'Course', + :polls_group_id => course_id, + :polls_status => 1, + :user_id => User.current.id, + :published_at => Time.now, + :closed_at => Time.now, + :show_result => 1, + :polls_description => poll.polls_description + } + @poll = Poll.create option + + poll.poll_questions.each do | q| + #question_title = params[:poll_questions_title].nil? || params[:poll_questions_title].empty? ? l(:label_enter_single_title) : params[:poll_questions_title] + option = { + :is_necessary => q[:is_necessary], + :question_title => q[:question_title], + :question_type => q[:question_type] || 1, + :question_number => q[:question_number] + } + @poll_questions = @poll.poll_questions.new option + + for i in 1..q.poll_answers.count + answer = q.poll_answers[i-1].nil? ? l(:label_new_answer) : q.poll_answers[i-1][:answer_text] + question_option = { + :answer_position => i, + :answer_text => answer + } + @poll_questions.poll_answers.new question_option + end + end + @poll.save + end + @is_teacher = User.current.allowed_to?(:as_teacher,@course) + if @is_teacher + polls = Poll.where("polls_type = 'Course' and polls_group_id = #{@course.id}") + else + polls = Poll.where("polls_type = 'Course' and polls_group_id = #{@course.id} and polls_status = 2") + end + @polls = paginateHelper polls,20 #分页 + respond_to do |format| + format.js + end + end + private def find_poll_and_course @poll = Poll.find params[:id] diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 09ae5ad79..90974b376 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -33,7 +33,7 @@ class ProjectsController < ApplicationController before_filter :require_admin, :only => [ :copy, :archive, :unarchive, :destroy, :calendar] before_filter :file, :statistics #:watcherlist # 除非项目内人员,不可查看成员, TODO: 完了写报表里去 - before_filter :memberAccess, only: :member + # before_filter :memberAccess, only: :member # accept_rss_auth :index accept_api_auth :index, :show, :create, :update, :destroy @@ -86,8 +86,15 @@ class ProjectsController < ApplicationController @project_pages = Project.project_entities.visible.like(params[:name]).page(params[:page]).per(10) else @project_pages = Project.project_entities.visible.page(params[:page] ).per(10) + @project_pages = Project.project_entities.visible.page(params[:page] ).per(10) end @projects = @project_pages.order("created_on desc") + @limit = 10#per_page_option + + @project_count = Project.project_entities.visible.like(params[:name]).page(params[:page]).count + @project_pages = Paginator.new @project_count, @limit, params['page'] + @name = params[:name] + @type = 'projects' respond_to do |format| format.html { render :layout => 'base' @@ -155,7 +162,7 @@ class ProjectsController < ApplicationController @trackers = Tracker.sorted.all @project = Project.new @project.safe_attributes = params[:project] - render :layout => 'base' + render :layout => 'new_base' else redirect_to signin_url end @@ -181,7 +188,8 @@ class ProjectsController < ApplicationController @project.safe_attributes = params[:project] @project.organization_id = params[:organization_id] @project.user_id = User.current.id - @project.project_new_type = 1 + @project.project_new_type = params[:project_new_type] + params[:project][:is_public] ? @project.is_public = 1 : @project.is_public = 0 if validate_parent_id && @project.save @project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id') # Add current user as a project member if he is not admin @@ -209,10 +217,11 @@ class ProjectsController < ApplicationController end } format.api { render :action => 'show', :status => :created, :location => url_for(:controller => 'projects', :action => 'show', :id => @project.id) } + format.js end else respond_to do |format| - format.html { render :action => 'new', :layout => 'base'}#Added by young + format.html { render :action => 'new', :layout => 'new_base'}#Added by young format.api { render_validation_errors(@project) } end end @@ -251,7 +260,8 @@ class ProjectsController < ApplicationController # Author lizanle # Description 项目动态展示方法,删除了不必要的代码 def show - + # 更新消息为已读 + update_message_status(User.current, @project) if params[:jump] && redirect_to_project_menu_item(@project, params[:jump]) return end @@ -315,6 +325,12 @@ class ProjectsController < ApplicationController end def settings + # 修改查看消息状态 + applied_messages = ForgeMessage.where("user_id =? and project_id =? and forge_message_type =? and viewed =?", User.current.id, @project, "AppliedProject", 0) + applied_messages.each do |applied_message| + applied_message.update_attributes(:viewed => true) + end + # end @issue_custom_fields = IssueCustomField.sorted.all @issue_category ||= IssueCategory.new @member ||= @project.members.new @@ -335,7 +351,7 @@ class ProjectsController < ApplicationController if params[:repository] == "pswd_is_null" html << l(:label_password_not_null) end - flash[:error] = html if !html.to_s.blank? + flash.now[:error] = html if !html.to_s.blank? end scm = params[:repository_scm] || (Redmine::Scm::Base.all & Setting.enabled_scm).first @repository = Repository.factory(scm) @@ -344,24 +360,60 @@ class ProjectsController < ApplicationController end + # 项目邀请用户加入实现过程 # 两种情况:1、系统外用户;2、系统内用户 (通过邮件判定) def send_mail_to_member + # 该邮箱未注册过 if !params[:mail].blank? && User.find_by_mail(params[:mail].to_s).nil? - email = params[:mail] - Mailer.run.send_invite_in_project(email, @project, User.current) - @is_zhuce = false - flash[:notice] = l(:notice_email_sent, :value => email) + if !User.where("login =?", params[:mail]).first.nil? + # 用户名唯一,用户修改邮箱,未修改用户名,用户名等同邮箱的情况,默认改用户已经注册 + user = User.find_by_login(params[:mail].to_s) + if !user.member_of?(@project) + # 如果已经邀请过该用户,则不重复发送 + if InviteList.where("project_id =? and mail =?", @project.id, params[:mail].to_s).first.nil? + email = params[:mail] + Mailer.request_member_to_project(email, @project, User.current).deliver + flash[:notice] = l(:notice_email_sent, :value => email) + else + flash[:error] = l(:notice_email_invited) + end + else + flash[:error] = l(:label_member_of_project, :value => email) + end + else + email = params[:mail] + first_name = params[:first_name] + last_name = params[:last_name] + gender = params[:gender] + Mailer.send_invite_in_project(email, @project, User.current, first_name, last_name, gender).deliver + @is_zhuce = false + flash[:notice] = l(:notice_email_sent, :value => email) + end + + # 邮箱地址已被注册 elsif !User.find_by_mail(params[:mail].to_s).nil? user = User.find_by_mail(params[:mail].to_s) if !user.member_of?(@project) - email = params[:mail] - Mailer.run.request_member_to_project(email, @project, User.current) - flash[:notice] = l(:notice_email_sent, :value => email) + # 如果已经邀请过该用户,则不重复发送 + invite_list = InviteList.where("project_id =? and mail =?", @project.id, params[:mail].to_s).first + if invite_list.nil? + email = params[:mail] + Mailer.request_member_to_project(email, @project, User.current).deliver + flash[:notice] = l(:notice_email_sent, :value => email) + else + # 已经发送过了,则隔3小时才能再次发送 + if Time.now - invite_list.created_at > 10800 + email = params[:mail] + Mailer.request_member_to_project(email, @project, User.current).deliver + flash[:notice] = l(:notice_email_sent, :value => email) + else + flash[:error] = l(:notice_email_invited) + end + end else flash[:error] = l(:label_member_of_project, :value => email) end else - flash[:error] = l(:notice_registed_error, :value => email) @is_zhuce = true end respond_to do |format| @@ -369,56 +421,26 @@ class ProjectsController < ApplicationController end end - # dts测试工具 - def dts_dep - render_403 unless User.current.admin? - @dts = Dts.all - end - - # dts云部署 - def yun_dep - render_403 unless User.current.admin? - end - - # 软件知识库 - def soft_knowledge - render_403 unless User.current.admin? - end - - # 在线开发平台 - def online_dev - render_403 unless User.current.admin? - end - - # 软件资源库 - def soft_file - render_403 unless User.current.admin? - end - - # 软件服务 - def soft_service - render_403 unless User.current.admin? - end - - #发送邮件邀请新用户 + # 发送邮件邀请新用户页面对应方法 def invite_members_by_mail if User.current.member_of?(@project) || User.current.admin? - @inviter_lists = InviteList.where(project_id:@project.id).all - @inviters = [] - @waiters = [] - unless @inviter_lists.blank? - @inviter_lists.each do|inviter_list| - unless inviter_list.user.nil? - if inviter_list.user.member_of?(@project) - @inviters << inviter_list.user - @inviters_count = @inviters.size - else - @waiters << inviter_list.user - @waiters_count = @waiters.size - end - end - end - end + @inviter_lists = InviteList.where(project_id:@project.id).order("created_at desc") + + # @inviters = [] + # @waiters = [] + # unless @inviter_lists.blank? + # @inviter_lists.each do|inviter_list| + # unless inviter_list.user.nil? + # if inviter_list.user.member_of?(@project) + # @inviters << inviter_list.user + # @inviters_count = @inviters.size + # else + # @waiters << inviter_list.user + # @waiters_count = @waiters.size + # end + # end + # end + # end @is_zhuce = false respond_to do |format| format.html @@ -430,16 +452,16 @@ class ProjectsController < ApplicationController end # 邀请Trustie注册用户 - def invite_members - if User.current.member_of?(@project) || User.current.admin? - @member ||= @project.members.new - respond_to do |format| - format.html - end - else - render_403 - end - end + # def invite_members + # if User.current.member_of?(@project) || User.current.admin? + # @member ||= @project.members.new + # respond_to do |format| + # format.html + # end + # else + # render_403 + # end + # end def edit end @@ -447,6 +469,11 @@ class ProjectsController < ApplicationController # by young # include CoursesHelper def member + # 消息"同意加入项目" + if params[:message_id] + message_invite(params[:message_id], params[:key]) + end + update_message_status(User.current, @project) # params[:login]为邮箱邀请用户加入,主要功能: # 1、自动注册 # 2、加入项目、创建角色 @@ -468,6 +495,10 @@ class ProjectsController < ApplicationController flash[:notice] = l(:label_mail_invite_success) end end + # 私有项目非项目成员无法访问成员列表 + unless @project.is_public? + return render_403 unless User.current.member_of?(@project) + end ## 有角色参数的才是课程,没有的就是项目 @render_file = 'project_member_list' # 判断是否课程 @@ -498,6 +529,24 @@ class ProjectsController < ApplicationController @members = paginateHelper @members end + def update_message_status(user, project) + project_invite_messages = ForgeMessage.where("user_id =? and project_id =? and forge_message_type =?", user, project, "ProjectInvite") + project_invite_messages.each do |project_invite_message| + project_invite_message.update_attribute(:viewed, true) + end + end + + def message_invite(message_id, key) + forge_message = ForgeMessage.find(message_id) + if key == forge_message.secret_key + # 情况:用户收到邀请邮件还没看,但是管理员已经把该用户添加进项目 + if Member.where("user_id =? and project_id =?",forge_message.user_id, forge_message.project_id).first.nil? + Member.create(:role_ids => [4], :user_id => forge_message.user_id, :project_id => forge_message.project_id) + UserGrade.create(:user_id => forge_message.user_id, :project_id => forge_message.project_id) + end + end + end + #判断指定用户是否为课程教师 def isCourseTeacher(id) result = false @@ -610,14 +659,10 @@ class ProjectsController < ApplicationController # Delete @project def destroy @project_to_destroy = @project - if api_request? || params[:confirm] - @project_to_destroy.destroy - respond_to do |format| - format.html { redirect_to admin_projects_url } - format.api { render_api_ok } - end - else - render :layout => "base_projects" + @project_to_destroy.destroy + respond_to do |format| + format.html { redirect_to admin_projects_url } + format.api { render_api_ok } end # hide project in layout @project = nil diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index 7219f4c08..024d5fdde 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -136,7 +136,7 @@ update logger.info "the value of create repository"+@root_path+": "+@repository_name+": "+@project_path+": "+@repo_name attrs = pickup_extra_info if((@repository_tag!="")&¶ms[:repository_scm]=="Git") - params[:repository][:url]=@project_path + params[:repository][:url]=@project_path end ###xianbo @repository = Repository.factory(params[:repository_scm]) diff --git a/app/controllers/softapplications_controller.rb b/app/controllers/softapplications_controller.rb index e47cfc2ff..bedb2541f 100644 --- a/app/controllers/softapplications_controller.rb +++ b/app/controllers/softapplications_controller.rb @@ -207,7 +207,7 @@ class SoftapplicationsController < ApplicationController @softapplication.destroy respond_to do |format| - format.html { redirect_to home_url } + format.html { redirect_to signin_path } format.json { head :no_content } end end diff --git a/app/controllers/student_work_controller.rb b/app/controllers/student_work_controller.rb index 3e1e0ba29..17f179492 100644 --- a/app/controllers/student_work_controller.rb +++ b/app/controllers/student_work_controller.rb @@ -3,16 +3,81 @@ class StudentWorkController < ApplicationController include StudentWorkHelper require 'bigdecimal' require "base64" - before_filter :find_homework, :only => [:new, :index, :create, :student_work_absence_penalty, :absence_penalty_list, :evaluation_list] + before_filter :find_homework, :only => [:new, :index, :create, :student_work_absence_penalty, :absence_penalty_list, :evaluation_list, :program_test,:set_score_rule] before_filter :find_work, :only => [:edit, :update, :show, :destroy, :add_score, :praise_student_work] before_filter :member_of_course, :only => [:index, :new, :create, :show, :add_score, :praise_student_work] before_filter :author_of_work, :only => [:edit, :update, :destroy] - before_filter :teacher_of_course, :only => [:student_work_absence_penalty, :absence_penalty_list, :evaluation_list] - protect_from_forgery :except => :set_program_score + before_filter :teacher_of_course, :only => [:student_work_absence_penalty, :absence_penalty_list, :evaluation_list, :set_score_rule] + + ### + def program_test + is_test = params[:is_test] == 'true' + resultObj = {status: 0, results: [], error_msg: '', time: Time.now.strftime('%Y-%m-%d %T')} + + student_work = find_or_save_student_work(is_test) + + unless student_work + resultObj[:status] = 100 + else + if @homework.homework_type == 2 && @homework.homework_detail_programing + result = test_realtime(student_work, params[:src]) + logger.debug result + resultObj[:status] = result["status"] + resultObj[:results] = result["results"] + resultObj[:error_msg] = result["error_msg"] + results = result["results"] + if result["status"].to_i == -2 #编译错误 + results = [result["error_msg"]] + end + student_work_test = student_work.student_work_tests.build(status: result["status"], results: results, + src: params[:src]) + unless student_work.save + resultObj[:status] = 200 + else + resultObj[:status] = result["status"].to_i + resultObj[:time] = student_work_test.created_at.to_s(:db) + resultObj[:index] = student_work.student_work_tests.count + end + + end + end + + render :json => resultObj + end def index + # 作业消息状态更新 + @homework.course_messages.each do |homework_message| + if User.current.id == homework_message.user_id && homework_message.viewed == 0 + homework_message.update_attributes(:viewed => true) if homework_message.viewed == 0 + end + end + # 作品打分消息状态更新 + studentworks_scores = CourseMessage.where("user_id =? and course_id =? and course_message_type =? and viewed =?", User.current.id, @homework.course, "StudentWorksScore", 0) + studentworks_scores.each do |studentworks_score| + studentworks_score.update_attributes(:viewed => true) if studentworks_score.viewed == 0 + end + # 作品评论消息状态更新 + journals_for_teacher = CourseMessage.where("user_id =? and course_id =? and course_message_type =? and viewed =?", User.current.id, @homework.course, "JournalsForMessage", 0) + journals_for_teacher.each do |journal_for_teacher| + journal_for_teacher.update_attributes(:viewed => true) + end + # 作品留言 + # 消息end + #设置作业对应的forge_messages表的viewed字段 + query_student_work = @homework.course_messages + query_student_work.each do |query| + if User.current.id == query.user_id + query.update_attributes(:viewed => true) + end + end + ################################################################################################################## @order,@b_sort,@name,@group = params[:order] || "score",params[:sort] || "desc",params[:name] || "",params[:group] - @is_teacher = User.current.allowed_to?(:as_teacher,@course) + @homework_commons = @course.homework_commons.order("created_at desc") + @is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin? + @is_evaluation = @homework.homework_detail_manual && @homework.homework_detail_manual.comment_status == 2 && !@is_teacher #是不是匿评 + @show_all = false + course_group = CourseGroup.find_by_id(@group) if @group if course_group group_students = course_group.users @@ -21,71 +86,51 @@ class StudentWorkController < ApplicationController else student_in_group = '(' + group_students.map{|user| user.id}.join(',') + ')' end - #老师 || 非匿评作业 || 匿评结束 显示所有的作品 - @show_all = @is_teacher || @homework.homework_type != 1 || @homework.homework_detail_manual.comment_status == 3 || User.current.admin? - if @show_all - if @homework.homework_type == 1 || @is_teacher || User.current.admin? #超级管理员 || 老师 || 匿评结束 显示所有的作品 - if @order == "name" - @stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").joins(:user).where("users.id in #{student_in_group}").order("users.lastname #{@b_sort}, users.firstname #{@b_sort}"),@name - else - @stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}"),@name - end - else #剩余情况: 学生 && 非匿评作业 如果未提交作品,只能看到自己的,提交了作品,能看到所有作品 - my_work = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:user_id => User.current.id) - if my_work.empty? - @stundet_works = [] - else - if @order == "name" - @stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").joins(:user).where("users.id in #{student_in_group}").order("users.lastname #{@b_sort}, users.firstname #{@b_sort}"),@name - else - @stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}"),@name - end - end - end - else #学生 - if @homework.homework_detail_manual.comment_status == 1 #未开启匿评,只显示我的作品 - @stundet_works = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:user_id => User.current.id) - elsif @homework.homework_detail_manual.comment_status == 2 #匿评列表,显示匿评作品和我的作品 - @is_evaluation = true - my_work = @homework.student_works.where(:user_id => User.current.id) - @stundet_works = my_work + User.current.student_works_evaluation_distributions.map(&:student_work).select { |work| work.homework_common_id == @homework.id} + if @is_teacher || @homework.homework_detail_manual.nil? #老师 || 超级管理员 显示所有列表 + @stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}"),@name + @show_all = true + elsif @homework.homework_detail_manual.comment_status == 1 #学生 && 未开启匿评 只看到自己的 + @stundet_works = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:user_id => User.current.id) + elsif @homework.homework_detail_manual.comment_status == 2 #学生 && 开启匿评 看到匿评列表 + my_work = @homework.student_works.where(:user_id => User.current.id) + @stundet_works = my_work + User.current.student_works_evaluation_distributions.map(&:student_work).select { |work| work.homework_common_id == @homework.id} + elsif @homework.homework_detail_manual.comment_status == 3 #学生 && 关闭匿评 未提交作品之前列表为空,提交了作品看到所有的 + my_work = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:user_id => User.current.id) + if my_work.empty? + @stundet_works = [] + else + @stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}"),@name + @show_all = true end + else + @stundet_works = [] end else - #老师 || 非匿评作业 || 匿评结束 显示所有的作品 - @show_all = @is_teacher || @homework.homework_type != 1 || @homework.homework_detail_manual.comment_status == 3 || User.current.admin? - if @show_all - if @homework.homework_type == 1 || @is_teacher || User.current.admin? #超级管理员 || 老师 || 匿评结束 显示所有的作品 - if @order == "name" - @stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").joins(:user).order("users.lastname #{@b_sort}, users.firstname #{@b_sort}"),@name - else - @stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").order("#{@order} #{@b_sort}"),@name - end - else #剩余情况: 学生 && 非匿评作业 如果未提交作品,只能看到自己的,提交了作品,能看到所有作品 - my_work = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:user_id => User.current.id) - if my_work.empty? - @stundet_works = [] - else - if @order == "name" - @stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").joins(:user).order("users.lastname #{@b_sort}, users.firstname #{@b_sort}"),@name - else - @stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").order("#{@order} #{@b_sort}"),@name - end - end - end - else #学生 - if @homework.homework_detail_manual.comment_status == 1 #未开启匿评,只显示我的作品 - @stundet_works = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:user_id => User.current.id) - elsif @homework.homework_detail_manual.comment_status == 2 #匿评列表,显示匿评作品和我的作品 - @is_evaluation = true - my_work = @homework.student_works.where(:user_id => User.current.id) - @stundet_works = my_work + User.current.student_works_evaluation_distributions.map(&:student_work).select { |work| work.homework_common_id == @homework.id} + if @is_teacher || @homework.homework_detail_manual.nil? #老师 || 超级管理员 显示所有列表 + @stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").order("#{@order} #{@b_sort}"),@name + @show_all = true + elsif @homework.homework_detail_manual.comment_status == 1 #学生 && 未开启匿评 只看到自己的 + @stundet_works = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:user_id => User.current.id) + elsif @homework.homework_detail_manual.comment_status == 2 #学生 && 开启匿评 看到匿评列表 + my_work = @homework.student_works.where(:user_id => User.current.id) + @stundet_works = my_work + User.current.student_works_evaluation_distributions.map(&:student_work).select { |work| work.homework_common_id == @homework.id} + elsif @homework.homework_detail_manual.comment_status == 3 #学生 && 关闭匿评 未提交作品之前列表为空,提交了作品看到所有的 + my_work = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:user_id => User.current.id) + if my_work.empty? + @stundet_works = [] + else + @stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").order("#{@order} #{@b_sort}"),@name + @show_all = true end + else + @stundet_works = [] end end - @homework_commons = @course.homework_commons.order("created_at desc") + @score = @b_sort == "desc" ? "asc" : "desc" + respond_to do |format| + format.js format.html format.xls { send_data(homework_to_xls(@stundet_works), :type => "text/excel;charset=utf-8; header=present", @@ -95,49 +140,48 @@ class StudentWorkController < ApplicationController end def new - student_work = @homework.student_works.where("user_id = ?",User.current.id).first - if student_work.nil? - @stundet_work = StudentWork.new - respond_to do |format| - format.html - end - else - render_403 + if @homework.homework_type==2 + redirect_to new_user_commit_homework_users_path(homework_id: @homework.id) + return + end + @user = User.current + @student_work = @homework.student_works.where("user_id = ?",User.current.id).first + if @student_work.nil? + @student_work = StudentWork.new + end + respond_to do |format| + format.html{ render :layout => "new_base_user"} end end def create if params[:student_work] - stundet_work = StudentWork.new - stundet_work.name = params[:student_work][:name] - stundet_work.description = params[:student_work][:description] - stundet_work.project_id = params[:student_work][:project_id] - stundet_work.homework_common_id = @homework.id - stundet_work.user_id = User.current.id - stundet_work.save_attachments(params[:attachments]) + student_work = StudentWork.find(params[:student_work_id]) if params[:student_work_id] + student_work ||= StudentWork.new + student_work.name = params[:student_work][:name] + student_work.description = params[:student_work][:description] + student_work.project_id = params[:student_work][:project_id] + student_work.homework_common_id = @homework.id + student_work.user_id = User.current.id + student_work.save_attachments(params[:attachments]) + render_attachment_warning_if_needed(student_work) + #提交作品时,计算是否迟交 if Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") < Time.parse(Time.now.to_s).strftime("%Y-%m-%d") - stundet_work.late_penalty = @homework.late_penalty - else - stundet_work.late_penalty = 0 + student_work.late_penalty = @homework.late_penalty + else + student_work.late_penalty = 0 end - render_attachment_warning_if_needed(stundet_work) - - if stundet_work.save - if @homework.homework_type == 2 && @homework.homework_detail_programing #编程作业,学生提交作品后计算系统得分 - url = "http://192.168.80.21:8080/api/questions/#{@homework.homework_detail_programing.question_id}/solutions.json" - solutions = { - student_work_id:stundet_work.id, - src:Base64.encode64(stundet_work.description), - language:@homework.homework_detail_programing.language - } - uri = URI(url) - body = solutions.to_json - res = Net::HTTP.new(uri.host, uri.port).start do |client| - request = Net::HTTP::Post.new(uri.path) - request.body = body - request["Content-Type"] = "application/json" - client.request(request) - end + + if student_work.save + course_activity = CourseActivity.where("course_act_type='HomeworkCommon' and course_act_id =#{@homework.id}").first + if course_activity + course_activity.updated_at = Time.now + course_activity.save + end + user_activity = UserActivity.where("act_type='HomeworkCommon' and act_id =#{@homework.id}").first + if user_activity + user_activity.updated_at = Time.now + user_activity.save end respond_to do |format| format.html { @@ -157,11 +201,12 @@ class StudentWorkController < ApplicationController end def edit + @user = User.current if !User.current.admin? && @homework.homework_type == 2 #编程作业不能修改作业 render_403 else respond_to do |format| - format.html + format.html{ render :layout => "new_base_user"} end end end @@ -190,16 +235,15 @@ class StudentWorkController < ApplicationController def show @score = student_work_score @work,User.current - @is_teacher = User.current.allowed_to?(:as_teacher,@course) + @is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin? + @student_work_scores = @work.student_works_scores.order("updated_at desc") respond_to do |format| format.js end end def destroy - if @homework.homework_type == 2 #编程作业,作品提交后不可以删除 - render_403 - elsif @work.destroy + if @work.destroy respond_to do |format| format.html { redirect_to student_work_index_url(:homework => @homework.id) @@ -210,10 +254,11 @@ class StudentWorkController < ApplicationController #添加评分,已评分则为修改评分 def add_score + @is_last = params[:is_last] == "true" render_403 and return if User.current == @work.user #不可以匿评自己的作品 - @is_teacher = User.current.allowed_to?(:as_teacher,@course) + @is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin? #老师、教辅可以随时评分,学生只能在匿评作业的匿评阶段进行评分 - render_403 and return unless @is_teacher || (@homework.homework_type == 1 && @homework.homework_detail_manual.comment_status == 2) + render_403 and return unless @is_teacher || @homework.homework_detail_manual.comment_status == 2 @score = student_work_score @work,User.current if @score @score.comment = params[:new_form][:user_message] if params[:new_form] && params[:new_form][:user_message] && params[:new_form][:user_message] != "" @@ -226,6 +271,7 @@ class StudentWorkController < ApplicationController end @is_new = false else + @is_last_a = @work.student_works_scores.empty? @score = StudentWorksScore.new @score.score = params[:score] if params[:score] @score.comment = params[:new_form][:user_message] if params[:new_form] && params[:new_form][:user_message] && params[:new_form][:user_message] != "" @@ -247,35 +293,11 @@ class StudentWorkController < ApplicationController case @score.reviewer_role when 1 #教师评分:最后一个教师评分为最终评分 @work.teacher_score = @score.score - @work.final_score = @score.score when 2 #教辅评分 教辅评分显示平均分 @work.teaching_asistant_score = @work.student_works_scores.where(:reviewer_role => 2).average(:score).try(:round, 2).to_f - if @work.teacher_score.nil? - if @work.student_score.nil? - @work.final_score = @work.teaching_asistant_score - else - ta_proportion = @homework.homework_detail_manual.ta_proportion if @homework.homework_detail_manual - ta_proportion = @homework.homework_detail_programing.ta_proportion if @homework.homework_detail_programing - final_ta_score = BigDecimal.new("#{@work.teaching_asistant_score}") * BigDecimal.new("#{ta_proportion}") - final_s_score = BigDecimal.new("#{@work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}")) - final_score = final_ta_score + final_s_score - @work.final_score = format("%.2f",final_score.to_f) - end - end when 3 #学生评分 学生评分显示平均分 @work.student_score = @work.student_works_scores.where(:reviewer_role => 3).average(:score).try(:round, 2).to_f - if @work.teacher_score.nil? - if @work.teaching_asistant_score.nil? - @work.final_score = @work.student_score - else - final_ta_score = BigDecimal.new("#{@work.teaching_asistant_score}") * BigDecimal.new("#{@homework.homework_detail_manual.ta_proportion}") - final_s_score = BigDecimal.new("#{@work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{@homework.homework_detail_manual.ta_proportion}")) - final_score = final_ta_score + final_s_score - @work.final_score = format("%.2f",final_score.to_f) - end - end end - if @work.save respond_to do |format| format.js @@ -287,6 +309,7 @@ class StudentWorkController < ApplicationController #添加评分的回复 def add_score_reply @score = StudentWorksScore.find params[:score_id] + @is_last = params[:is_last] == "true" @jour = @score.journals_for_messages.new(:user_id => User.current.id,:notes =>params[:message], :reply_id => 0) if @jour.save @status = 1 @@ -379,44 +402,53 @@ class StudentWorkController < ApplicationController end end - #设置编程作业得分 - def set_program_score - stundet_work = StudentWork.find_by_id params[:student_work_id] - @course = stundet_work.homework_common.course - student_score_count = 0 - if stundet_work && params[:results] && params[:results].class.to_s == "Array" - homework_common = stundet_work.homework_common - params[:results].each do |result| - homework_test = homework_common.homework_tests.where("input = '#{result[:input]}' AND output = '#{result[:output]}'").first - if homework_test - student_work_test = StudentWorkTest.new - student_work_test.student_work = stundet_work - student_work_test.homework_test = homework_test - student_work_test.result = result[:status] - if student_work_test.result == 0 - student_score_count += 1 - end - student_work_test.error_msg = params[:compile_error_msg] - student_work_test.save! - end + #设置评分规则 + def set_score_rule + homework_detail_manual = @homework.homework_detail_manual + homework_detail_programing = @homework.homework_detail_programing + + unless @homework.late_penalty.to_s == params[:late_penalty].to_s + @homework.late_penalty = params[:late_penalty] + @homework.student_works.where("created_at > '#{@homework.end_time} 23:59:59'").each do |student_work| + student_work.late_penalty = @homework.late_penalty + student_work.save end - unless homework_common.homework_tests.empty? - stundet_work.student_score = student_score_count * 100.0 / homework_common.homework_tests.count - if stundet_work.teacher_score.nil? - if stundet_work.teaching_asistant_score.nil? - stundet_work.final_score = stundet_work.student_score - else - final_ta_score = BigDecimal.new("#{stundet_work.teaching_asistant_score}") * BigDecimal.new("#{homework_common.homework_detail_programing.ta_proportion}") - final_s_score = BigDecimal.new("#{stundet_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{homework_common.homework_detail_programing.ta_proportion}")) - final_score = final_ta_score + final_s_score - stundet_work.final_score = format("%.1f",final_score.to_f) - end + @homework.save + end + + unless homework_detail_manual.absence_penalty.to_s == params[:absence_penalty].to_s + homework_detail_manual.absence_penalty = params[:absence_penalty] + if homework_detail_manual.comment_status == 3 #当前作业处于匿评结束状态,修改缺评扣分才会修改每个作品应扣分的值 + work_ids = "(" + @homework.student_works.map(&:id).join(",") + ")" + @homework.student_works.each do |student_work| + absence_penalty_count = student_work.user.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count - student_work.user.student_works_scores.where("student_work_id IN #{work_ids}").count + student_work.absence_penalty = absence_penalty_count > 0 ? absence_penalty_count * homework_detail_manual.absence_penalty : 0 + student_work.save end + end + + homework_detail_manual.save if homework_detail_manual + end + + teacher_priority = params[:teacher_priority] ? 1 : 0 + if homework_detail_manual.ta_proportion.to_s != params[:ta_proportion].to_s || @homework.teacher_priority.to_s != teacher_priority.to_s || (homework_detail_programing && homework_detail_programing.ta_proportion.to_s != params[:sy_proportion].to_s) + homework_detail_manual.ta_proportion = params[:ta_proportion] + homework_detail_programing.ta_proportion = params[:sy_proportion] if homework_detail_programing + @homework.teacher_priority = teacher_priority - stundet_work.save! + @homework.save + homework_detail_manual.save if homework_detail_manual + homework_detail_programing.save if homework_detail_programing + + @homework.student_works.each do |student_work| + set_final_score @homework,student_work + student_work.save end end + respond_to do |format| + format.html{redirect_to student_work_index_url(:homework => @homework.id)} + end end private @@ -449,15 +481,19 @@ class StudentWorkController < ApplicationController end def teacher_of_course - render_403 unless User.current.allowed_to?(:as_teacher,@course) + render_403 unless User.current.allowed_to?(:as_teacher,@course) || User.current.admin? end #根据条件过滤作业结果 def search_homework_member homeworks,name - name = name.downcase - select_homework = homeworks.select{ |homework| - homework.user[:login].to_s.downcase.include?(name) || homework.user.user_extensions[:student_id].to_s.downcase.include?(name) || (homework.user[:lastname].to_s.downcase + homework.user[:firstname].to_s.downcase).include?(name) - } + if name == "" + select_homework = homeworks + else + name = name.downcase + select_homework = homeworks.select{ |homework| + homework.user[:login].to_s.downcase.include?(name) || homework.user.user_extensions[:student_id].to_s.downcase.include?(name) || (homework.user[:lastname].to_s.downcase + homework.user[:firstname].to_s.downcase).include?(name) + } + end select_homework end @@ -468,25 +504,7 @@ class StudentWorkController < ApplicationController sheet1 = book.create_worksheet :name => "homework" blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10 sheet1.row(0).default_format = blue - if @homework.homework_type == 0 #普通作业 - sheet1.row(0).concat([l(:excel_user_id),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_mail),l(:excel_homework_name), - l(:excel_t_score),l(:excel_ta_score),l(:excel_f_score),l(:excel_commit_time)]) - count_row = 1 - items.each do |homework| - sheet1[count_row,0]=homework.user.id - sheet1[count_row,1] = homework.user.lastname.to_s + homework.user.firstname.to_s - sheet1[count_row,2] = homework.user.login - sheet1[count_row,3] = homework.user.user_extensions.student_id - sheet1[count_row,4] = homework.user.mail - sheet1[count_row,5] = homework.name - sheet1[count_row,6] = homework.teacher_score.nil? ? l(:label_without_score) : format("%.2f",homework.teacher_score) - sheet1[count_row,7] = homework.teaching_asistant_score.nil? ? l(:label_without_score) : format("%.2f",homework.teaching_asistant_score) - # sheet1[count_row,8] = homework.student_score.nil? ? l(:label_without_score) : format("%.2f",homework.student_score) - sheet1[count_row,8] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : format("%.2f",homework.score) : l(:label_without_score) - sheet1[count_row,9] = format_time(homework.created_at) - count_row += 1 - end - elsif @homework.homework_type == 1 #匿评作业 + if @homework.homework_type == 1 #匿评作业 sheet1.row(0).concat([l(:excel_user_id),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_mail),l(:excel_homework_name), l(:excel_t_score),l(:excel_ta_score), l(:excel_n_score),l(:excel_f_score),l(:excel_commit_time)]) count_row = 1 @@ -506,7 +524,7 @@ class StudentWorkController < ApplicationController end elsif @homework.homework_type == 2 #编程作业 sheet1.row(0).concat([l(:excel_user_id),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_mail),l(:excel_homework_name), - l(:excel_t_score),l(:excel_ta_score), l(:excel_s_score),l(:excel_f_score),l(:excel_commit_time)]) + l(:excel_t_score),l(:excel_ta_score), l(:excel_s_score),l(:excel_n_score),l(:excel_f_score),l(:excel_commit_time)]) count_row = 1 items.each do |homework| sheet1[count_row,0]=homework.user.id @@ -517,9 +535,10 @@ class StudentWorkController < ApplicationController sheet1[count_row,5] = homework.name sheet1[count_row,6] = homework.teacher_score.nil? ? l(:label_without_score) : format("%.2f",homework.teacher_score) sheet1[count_row,7] = homework.teaching_asistant_score.nil? ? l(:label_without_score) : format("%.2f",homework.teaching_asistant_score) - sheet1[count_row,8] = homework.student_score.nil? ? l(:label_without_score) : format("%.2f",homework.student_score) - sheet1[count_row,9] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : format("%.2f",homework.score) : l(:label_without_score) - sheet1[count_row,10] = format_time(homework.created_at) + sheet1[count_row,8] = homework.system_score.nil? ? l(:label_without_score) : format("%.2f",homework.system_score) + sheet1[count_row,9] = homework.student_score.nil? ? l(:label_without_score) : format("%.2f",homework.student_score) + sheet1[count_row,10] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : format("%.2f",homework.score) : l(:label_without_score) + sheet1[count_row,11] = format_time(homework.created_at) count_row += 1 end end @@ -577,4 +596,145 @@ class StudentWorkController < ApplicationController book.write xls_report xls_report.string end + + def find_or_save_student_work(is_test) + student_work = StudentWork.where(homework_common_id: @homework.id, user_id: User.current.id).first + if student_work.nil? + @homework.student_works.build( + name: params[:title], + description: params[:src], + user_id: User.current.id, + is_test: is_test + ) + unless @homework.save + logger.debug @homework.errors.full_messages + else + student_work = StudentWork.where(homework_common_id: @homework.id, user_id: User.current.id).first + end + end + student_work + end + + + def test_realtime(student_work, src) + url = "#{Redmine::Configuration['judge_server']}api/realtime_test.json" + + factor = [] + @homework.homework_tests.each do |test| + factor << {input: test.input, output: test.output} + end + solutions = { + src:src, + language:@homework.homework_detail_programing.language, + factor: factor + } + uri = URI(url) + body = solutions.to_json + res = Net::HTTP.new(uri.host, uri.port).start do |client| + request = Net::HTTP::Post.new(uri.path) + request.body = body + request["Content-Type"] = "application/json" + client.request(request) + end + JSON.parse(res.body) + end + + #成绩计算 + def set_final_score homework,student_work + if homework && homework.homework_detail_manual + if homework.homework_type == 1 #匿评作业 + if homework.teacher_priority == 1 #教师优先 + if student_work.teacher_score + student_work.final_score = student_work.teacher_score + else + if student_work.teaching_asistant_score.nil? + student_work.final_score = student_work.student_score + elsif student_work.student_score.nil? + student_work.final_score = student_work.teaching_asistant_score + else + ta_proportion = homework.homework_detail_manual.ta_proportion + final_ta_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{ta_proportion}") + final_s_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}")) + final_score = final_ta_score + final_s_score + student_work.final_score = format("%.2f",final_score.to_f) + end + end + else #不考虑教师评分 + if student_work.teaching_asistant_score.nil? + student_work.final_score = student_work.student_score + elsif student_work.student_score.nil? + student_work.final_score = student_work.teaching_asistant_score + else + ta_proportion = homework.homework_detail_manual.ta_proportion + final_ta_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{ta_proportion}") + final_s_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}")) + final_score = final_ta_score + final_s_score + student_work.final_score = format("%.2f",final_score.to_f) + end + end + elsif homework.homework_type == 2 && homework.homework_detail_programing #编程作业-----设定:系统评分必定不为空 + if homework.teacher_priority == 1 #教师优先 + if student_work.teacher_score + student_work.final_score = student_work.teacher_score + else + if student_work.teaching_asistant_score.nil? #教辅未评分 + if student_work.student_score.nil? + student_work.final_score = student_work.system_score + else + ta_proportion = homework.homework_detail_programing.ta_proportion + homework.homework_detail_manual.ta_proportion / 2 + final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}") + final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}")) + final_score = final_sy_score + final_st_score + student_work.final_score = format("%.2f",final_score.to_f) + end + elsif student_work.student_score.nil? #学生未评分 + if student_work.teaching_asistant_score.nil? + student_work.final_score = student_work.system_score + else + ta_proportion = homework.homework_detail_programing.ta_proportion + (1.0 - homework.homework_detail_manual.ta_proportion - homework.homework_detail_programing.ta_proportion) / 2 + final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}") + final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}")) + final_score = final_sy_score + final_ts_score + student_work.final_score = format("%.2f",final_score.to_f) + end + else + final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}") + final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}") + final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}") - BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}")) + final_score = final_sy_score + final_ts_score + final_st_score + student_work.final_score = format("%.2f",final_score.to_f) + end + end + else #不考虑教师评分 + if student_work.teaching_asistant_score.nil? #教辅未评分 + if student_work.student_score.nil? + student_work.final_score = student_work.system_score + else + ta_proportion = homework.homework_detail_programing.ta_proportion + homework.homework_detail_manual.ta_proportion / 2 + final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}") + final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}")) + final_score = final_sy_score + final_st_score + student_work.final_score = format("%.2f",final_score.to_f) + end + elsif student_work.student_score.nil? #学生未评分 + if student_work.teaching_asistant_score.nil? + student_work.final_score = student_work.system_score + else + ta_proportion = homework.homework_detail_programing.ta_proportion + (1.0 - homework.homework_detail_manual.ta_proportion - homework.homework_detail_programing.ta_proportion) / 2 + final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}") + final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}")) + final_score = final_sy_score + final_ts_score + student_work.final_score = format("%.2f",final_score.to_f) + end + else + final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}") + final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}") + final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}") - BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}")) + final_score = final_sy_score + final_ts_score + final_st_score + student_work.final_score = format("%.2f",final_score.to_f) + end + end + end + end + end end \ No newline at end of file diff --git a/app/controllers/system_messages_controller.rb b/app/controllers/system_messages_controller.rb new file mode 100644 index 000000000..684378e8a --- /dev/null +++ b/app/controllers/system_messages_controller.rb @@ -0,0 +1,95 @@ +class SystemMessagesController < ApplicationController + # before_filter :message_author, :only => [:show] + # + # def message_author + # if(!User.current.logged? && !token.nil?) + # + # User.current =try_to_autologin1 + # end + # if @system_messages + # render_403 :message => :notice_not_authorized_message + # else + # deny_access + # end + # end + + def index + @system_messages = SystemMessage.all + end + + # def show + # @system_messages = SystemMessage.find(params[:id]) + # end + + # GET /products/new + # def new + # @product = Product.new + # end + + # GET /products/1/edit + # def edit + # end + + # POST /products + # POST /products.json + def create + unless User.current.admin? + render_403 + return + end + @system_messages = SystemMessage.new + @system_messages.description = params[:system_message][:description] + @system_messages.subject = params[:system_message][:subject] + @system_messages.user_id = User.current.id + respond_to do |format| + if @system_messages.save + format.html {redirect_to user_system_messages_path(User.current)} + flash[:notice] = l(:notice_successful_message) + else + if params[:system_messages][:description].empty? + flash[:error] = l(:label_content_blank_fail) + else + flash[:error] = l(:label_admin_message_fail) + end + format.html {redirect_to admin_messages_path} + end + end + end + + # PATCH/PUT /products/1 + # PATCH/PUT /products/1.json + # def update + # respond_to do |format| + # if @product.update(product_params) + # format.html { redirect_to @product, notice: 'Product was successfully updated.' } + # format.json { render :show, status: :ok, location: @product } + # else + # format.html { render :edit } + # format.json { render json: @product.errors, status: :unprocessable_entity } + # end + # end + # end + + # DELETE /products/1 + # DELETE /products/1.json + # def destroy + # @system_messages.destroy + # respond_to do |format| + # format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' } + # format.json { head :no_content } + # end + # end + + # private + # # Use callbacks to share common setup or constraints between actions. + # def set_product + # @product = Product.find(params[:id]) + # end + # + # # Never trust parameters from the scary internet, only allow the white list through. + # def message_params + # params.require(:admin_system_messages).permit(:content) + # end + + +end diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb index 253faa2b1..cb61177f5 100644 --- a/app/controllers/tags_controller.rb +++ b/app/controllers/tags_controller.rb @@ -15,6 +15,7 @@ class TagsController < ApplicationController include ContestsHelper include ActsAsTaggableOn::TagsHelper include TagsHelper + include FilesHelper helper :projects helper :courses helper :tags @@ -230,6 +231,103 @@ class TagsController < ApplicationController end end + #更新某个tag名称 + def update_tag_name + @tag_name = params[:tagName] + @rename_tag_name = params[:renameName] + @taggable_id = params[:taggableId] + @taggable_type = numbers_to_object_type(params[:taggableType]) + @course_id = params[:courseId] + + @rename_tag = (ActsAsTaggableOn::Tag.find_by_name(@rename_tag_name)) #查找重命名后的tag + @tag_id = (ActsAsTaggableOn::Tag.find_by_name(@tag_name)).id #重命名前的tag_id + @taggings = ActsAsTaggableOn::Tagging.find_by_tag_id_and_taggable_id_and_taggable_type(@tag_id,@taggable_id,@taggable_type) unless @taggable_id.blank? + @obj = get_object(@taggable_id,params[:taggableType]) unless @taggable_id.blank? + if @taggable_id.blank? #如果没有传tag_id,那么直接更新tag_name就好了。但是要防止 重命名后的tag存在。 + if @course_id + course = Course.find @course_id + if course + course.attachments.each do |attachment| + taggings = ActsAsTaggableOn::Tagging.find_by_tag_id_and_taggable_id_and_taggable_type(@tag_id,attachment.id,attachment.class) + if taggings + taggings.delete + attachment.tag_list.add(@rename_tag_name.split(",")) + attachment.save + end + end + end + end + else + if(@rename_tag.nil?) #这次命名的是新的tag + + # 是否还有其他记录 引用了 tag_id + @tagging = ActsAsTaggableOn::Tagging.where("tag_id = #{@tag_id}") + # 如果taggings表中记录为 1 ,那么改变@tag_id对应的tag的名字 + if @tagging.count == 1 + @tag = ActsAsTaggableOn::Tag.find_by_id(@tag_id) + @tag.update_attributes({:name=>@rename_tag_name}) + else #如果tagging表中的记录大于1,那么就要新增tag记录 + + unless @obj.nil? + @obj.tag_list.add(@rename_tag_name.split(",")) + @obj.save + end + #删除原来的对应的taggings的记录 + unless @taggings.nil? + @taggings.delete + end + end + else #这是已有的tag + # 更改taggings记录里的tag_id + unless @taggings.nil? + @taggings.update_attributes({:tag_id=>@rename_tag.id}) + end + end + end + + @obj_flag = params[:taggableType] + if @obj && @obj_flag == '6' && @obj.container.kind_of?(Course) + @course = @obj.container + @tag_list = @tag_list = get_course_tag_list @course + elsif @course_id + @course = Course.find(@course_id) + @tag_list = get_course_tag_list @course + + #这里要引用FilesController里的逻辑了。将资源库当前的文件列表刷新一遍。 + @flag = params[:flag] || false + sort = "" + @sort = "" + @order = "" + @is_remote = false + @isproject = false + + sort = "#{Attachment.table_name}.created_on desc" + + @containers = [ Course.includes(:attachments).reorder(sort).find(@course.id)] + + show_attachments @containers + elsif @obj && @obj_flag == '5' + @forum = @obj + end + respond_to do |format| + format.js + end + end + + def show_attachments obj + @attachments = [] + obj.each do |container| + @attachments += container.attachments + end + @all_attachments = User.current.admin? ? @attachments : visable_attachemnts(@attachments) + @limit = 10 + @feedback_count = @all_attachments.count + @feedback_pages = Paginator.new @feedback_count, @limit, params['page'] + @offset ||= @feedback_pages.offset + #@curse_attachments_all = @all_attachments[@offset, @limit] + @obj_attachments = paginateHelper @all_attachments,10 + end + def tag_save @select_tag_name = params[:tag_for_save][:tag_name] @tags = params[:tag_for_save][:name] diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 0c5b441d4..055c59f06 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,3 +1,4 @@ +#encoding: utf-8 # Redmine - project management software # Copyright (C) 2006-2013 Jean-Philippe Lang # @@ -14,6 +15,7 @@ # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + class UsersController < ApplicationController layout :setting_layout @@ -25,29 +27,20 @@ class UsersController < ApplicationController menu_item :user_course, :only => :user_courses menu_item :user_homework, :only => :user_homeworks menu_item :user_project, :only => [:user_projects, :watch_projects] - # menu_item :requirement_focus, :only => :watch_bids menu_item :requirement_focus, :only => :watch_contests menu_item :user_newfeedback, :only => :user_newfeedback + menu_item :user_messages, :only => :user_messages - #Ended by young - - # edit - # before_filter :can_show_course, :only => [:user_courses,:user_homeworks] - before_filter :require_admin, :except => [:show, :index, :search, :tag_save, :tag_saveEx,:user_projects, :user_newfeedback, :user_comments, :watch_contests, :info, - :user_watchlist, :user_fanslist,:update, :user_courses, :user_homeworks, :watch_projects, :show_score, :topic_score_index, :project_score_index, - :activity_score_index, :influence_score_index, :score_index,:show_new_score, :topic_new_score_index, :project_new_score_index, - :activity_new_score_index, :influence_new_score_index, :score_new_index,:update_score,:user_activities,:user_projects_index, - :user_courses4show,:user_projects4show,:user_course_activities,:user_project_activities,:user_feedback4show,:user_visitorlist] - #edit has been deleted by huang, 2013-9-23 before_filter :find_user, :only => [:user_fanslist, :user_watchlist, :show, :edit, :update, :destroy, :edit_membership, :user_courses, - :user_homeworks, :destroy_membership, :user_activities, :user_projects, :user_newfeedback, :user_comments, - :watch_contests, :info, :watch_projects, :show_score, :topic_score_index, :project_score_index, - :activity_score_index, :influence_score_index, :score_index,:show_new_score, :topic_new_score_index, :project_new_score_index, - :activity_new_score_index, :influence_new_score_index, :score_new_index,:user_projects_index, - :user_courses4show,:user_projects4show,:user_course_activities,:user_project_activities,:user_feedback4show,:user_visitorlist] + :user_homeworks, :destroy_membership, :user_activities, :user_projects, :user_newfeedback, :user_comments, + :watch_contests, :info, :watch_projects, :show_score, :topic_score_index, :project_score_index, + :activity_score_index, :influence_score_index, :score_index,:show_new_score, :topic_new_score_index, :project_new_score_index, + :activity_new_score_index, :influence_new_score_index, :score_new_index,:user_projects_index,:user_resource, + :user_courses4show,:user_projects4show,:user_course_activities,:user_project_activities,:user_feedback4show,:user_visitorlist,:user_messages,:edit_brief_introduction, + :user_import_homeworks,:user_search_homeworks,:user_import_resource, :user_system_messages] before_filter :auth_user_extension, only: :show #before_filter :rest_user_score, only: :show #before_filter :select_entry, only: :user_projects @@ -69,7 +62,10 @@ class UsersController < ApplicationController include WordsHelper include GitlabHelper include UserScoreHelper + + include PollHelper helper :user_score + helper :journals # added by liuping 关注 @@ -95,6 +91,117 @@ class UsersController < ApplicationController end end + # 用户消息 + # 说明: homework 发布作业;message:讨论区; news:新闻; poll:问卷;works_reviewers:作品评阅;works_reply:作品回复 + # issue:问题;journal:缺陷状态更新; forum:公共贴吧: user_feedback: 用户留言; new_reply:新闻回复(comment) + def user_messages + if !User.current.logged? + redirect_to signin_url + return + elsif @user != User.current && !User.current.admin? + return render_403 + end + # 初始化/更新 点击按钮时间 + # 24小时内显示系统消息 + update_onclick_time + # 全部设为已读 + if params[:viewed] == "all" + update_message_viewed(@user) + end + # @new_message_count = forge_querys.count + forum_querys.count + course_querys.count + user_querys.count + case params[:type] + when nil + @message_alls = [] + messages = MessageAll.where("(user_id =? and message_type !=?) or message_type =?" ,@user, "SystemMessage", "SystemMessage").order("created_at desc") + messages.each do |message_all| + @message_alls << message_all.message + end + when 'unviewed' + @message_alls = [] + messages = MessageAll.where("user_id =?", @user).order("created_at desc") + messages.each do |message_all| + # 在点击或者刷新消息列表后未读的消息存放在数组 + if message_all.message_type != "SystemMessage" && message_all.message.viewed == 0 + @message_alls << message_all.message + end + end + + #课程相关消息 + when 'homework' + @message_alls = CourseMessage.where("course_message_type in ('HomeworkCommon','StudentWorksScore','JournalsForMessage') and user_id =?", @user).order("created_at desc") + when 'course_message' + @message_alls = CourseMessage.where("course_message_type =? and user_id =?", "Message", @user).order("created_at desc") + when 'course_news' + # 课程通知包含发布的通知和回复的通知 + @message_alls = CourseMessage.where("course_message_type =? or course_message_type =?", "News", "Comment").where("user_id =?", @user).order("created_at desc") + when 'poll' + @message_alls = CourseMessage.where("course_message_type =? and user_id =?", "Poll", @user).order("created_at desc") + + #项目相关消息 + when 'issue' + @message_alls = ForgeMessage.where("forge_message_type =? or forge_message_type =?" , "Issue", "Journal").where("user_id=?", @user).order("created_at desc") + when 'forge_message' + @message_alls = ForgeMessage.where("forge_message_type =? and user_id =?", "Message", @user).order("created_at desc") + when 'forge_news' + @message_alls = ForgeMessage.where("forge_message_type in (?,?) and user_id =?", "News", "Comment", @user).order("created_at desc") + when 'apply' + @message_alls = ForgeMessage.where("forge_message_type in ('ProjectInvite', 'AppliedProject') and user_id =?", @user).order("created_at desc") + + #贴吧消息 + when 'forum' + @message_alls = MemoMessage.where("memo_type =? and user_id =?", "Memo", @user).order("created_at desc") + + #用户留言 + when 'user_feedback' + @message_alls = UserFeedbackMessage.where("journals_for_message_type =? and user_id =?", "JournalsForMessage", @user).order("created_at desc") + else + render_404 + return + end + @message_alls = paginateHelper @message_alls,25 + respond_to do |format| + format.html{render :layout=>'new_base_user'} + end + end + + # 初始化/更新 点击按钮时间 + def update_onclick_time + # 记录当前点击按钮的时间 + # 考虑到用户未退出刷新消息页面 + message_time = OnclickTime.where("user_id =?", User.current).first + if message_time.nil? + message_new_time = OnclickTime.new + message_new_time.user_id = User.current.id + message_new_time.onclick_time = Time.now + message_new_time.save + else + message_time.update_attributes(:onclick_time => Time.now) + end + end + + # 消息设置为已读 + def update_message_viewed(user) + course_querys = CourseMessage.where("user_id =? and viewed =?", user, 0) + forge_querys = ForgeMessage.where("user_id =? and viewed =?", user, 0) + user_querys = UserFeedbackMessage.where("user_id =? and viewed =?", user, 0) + forum_querys = MemoMessage.where("user_id =? and viewed =?", user, 0) + if User.current.id == @user.id + course_querys.update_all(:viewed => true) + forge_querys.update_all(:viewed => true) + user_querys.update_all(:viewed => true) + forum_querys.update_all(:viewed => true) + end + end + + # 系统消息 + def user_system_messages + @sytem_messages = SystemMessage.order("created_at desc").all + @sytem_messages = paginateHelper @sytem_messages, 10 + respond_to do |format| + format.html{render :layout=>'new_base_user'} + end + end + def user_projects_index if User.current.admin? memberships = @user.memberships.all(conditions: "projects.project_type = #{Project::ProjectType_project}").first @@ -118,7 +225,7 @@ class UsersController < ApplicationController return end end - projects = @user.projects.visible.order("updated_on desc") + projects = @user.projects.visible.select("projects.*,(SELECT MAX(created_at) FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS a").order("a desc") if(params[:status] == '1') projects = projects.where("projects.user_id = ?",@user.id) elsif(params[:status] == '2') @@ -142,7 +249,7 @@ class UsersController < ApplicationController end # end - ##added by fq +##added by fq def watch_bids # cond = 'bids.reward_type <> 1' # @bids = Bid.watched_by(@user).where('reward_type = ?', 1) # added by huang @@ -205,7 +312,7 @@ class UsersController < ApplicationController unless User.current.admin? if !@user.active? || (@user != User.current && @memberships.empty? && events.empty?) render_404 - return + return end end @@ -216,26 +323,294 @@ class UsersController < ApplicationController end # end - # added by huang + #用户作业列表 def user_homeworks - # @membership = @user.memberships.all(:conditions => Project.visible_condition(User.current)) - # @memberships = [] - # @membership.each do |membership| - # if membership.project.project_type == 1 - # @memberships << membership - # end - # end - # @bid = [] - # @memberships.each do |membership| - # @bid += membership.project.homeworks - # end - # @bid = @bid.group_by {|bid| bid.courses.first.id} - # unless User.current.admin? - # if !@user.active? - # render_404 - # return - # end - # end + if User.current == @user + @page = params[:page] ? params[:page].to_i + 1 : 0 + user_course_ids = @user.courses.empty? ? "(-1)" :"(" + @user.courses.visible.map{|course| course.id}.join(",") + ")" + @homework_commons = HomeworkCommon.where("course_id in #{user_course_ids}").order("created_at desc").limit(10).offset(@page * 10) + @is_teacher = User.current.user_extensions && User.current.user_extensions.identity == 0 && User.current.allowed_to?(:add_course, nil, :global => true) + @is_in_course = params[:is_in_course].to_i || 0 + respond_to do |format| + format.js + format.html {render :layout => 'new_base_user'} + end + else + render_403 + end + end + + #导入作业 + def user_import_homeworks + @select_course = params[:select_course] ? 1 : 0 + @user_homeworks = HomeworkCommon.where(:user_id => @user.id).order("created_at desc") + respond_to do |format| + format.js + end + end + + #用户主页过滤作业 + def user_search_homeworks + @user_homeworks = HomeworkCommon.where("user_id = '#{@user.id}' and lower(name) like '%#{params[:name].to_s.downcase}%'").order("created_at desc") + respond_to do |format| + format.js + end + end + + #导入作业,确定按钮 + def user_select_homework + homework = HomeworkCommon.find_by_id params[:checkMenu] + homework_detail_programing = homework.homework_detail_programing + @homework = HomeworkCommon.new + @select_course = params[:select_course] || 0 + if homework + @homework.name = homework.name + @homework.description = homework.description + @homework.end_time = homework.end_time + @homework.homework_type = homework.homework_type + @homework.course_id = homework.course_id + homework.attachments.each do |attachment| + att = attachment.copy + att.container_id = nil + att.container_type = nil + att.copy_from = attachment.id + att.save + @homework.attachments << att + end + + if homework_detail_programing + @homework.homework_detail_programing = HomeworkDetailPrograming.new + @homework_detail_programing = @homework.homework_detail_programing + @homework_detail_programing.ta_proportion = homework_detail_programing.ta_proportion + @homework_detail_programing.language = homework_detail_programing.language + homework.homework_tests.each_with_index do |homework_test| + @homework.homework_tests << HomeworkTest.new( + input: homework_test.input, + output: homework_test.output + ) + end + end + end + respond_to do |format| + format.js + end + end + + def new_user_commit_homework + if User.current.logged? + @user = User.current + @homework = HomeworkCommon.find(params[:homework_id]) + @is_test = params[:is_test] == 'true' + @student_work = StudentWork.where(homework_common_id: @homework.id, user_id: User.current.id).first + if @student_work.nil? + @student_work = StudentWork.new + end + respond_to do |format| + format.js + format.html {render :layout => 'new_base_user'} + end + else + render_403 + end + end + + #修改编程作业 + def edit_user_commit_homework + if User.current.logged? + + respond_to do |format| + format.js + format.html {render :layout => 'new_base_user'} + end + else + render_403 + end + end + + def user_commit_homework + homework = HomeworkCommon.find(params[:homework]) + student_work = StudentWork.where(homework_common_id: homework.id, user_id: User.current.id).first + if student_work + + #提交作品时,计算是否迟交 + if Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") < Time.parse(Time.now.to_s).strftime("%Y-%m-%d") + student_work.late_penalty = 1 + else + student_work.late_penalty = 0 + end + + student_work.save + flash[:notice] = l(:notice_successful_create) + redirect_to student_work_index_url(:homework => params[:homework]) + else + render_403 + end + end + + def user_new_homework + if User.current.logged? + if params[:homework_common] + homework = HomeworkCommon.new + homework.name = params[:homework_common][:name] + homework.description = params[:homework_common][:description] + homework.end_time = params[:homework_common][:end_time] || Time.now + homework.publish_time = Time.now + homework.homework_type = params[:homework_type].to_i || 1 + homework.late_penalty = 10 + homework.teacher_priority = 1 + homework.user_id = User.current.id + homework.course_id = params[:course_id] + + homework.save_attachments(params[:attachments]) + render_attachment_warning_if_needed(homework) + + homework_detail_manual = HomeworkDetailManual.new + homework_detail_manual.ta_proportion = homework.homework_type == 1 ? 0.6 : 0.3 + homework_detail_manual.comment_status = 1 + homework_detail_manual.evaluation_start = params[:evaluation_start].blank? ? homework.end_time + 7 : params[:evaluation_start] + homework_detail_manual.evaluation_end = params[:evaluation_end].blank? ? homework_detail_manual.evaluation_start + 7 : params[:evaluation_end] + homework_detail_manual.evaluation_num = params[:evaluation_num] || 3 + homework_detail_manual.absence_penalty = 5 + homework.homework_detail_manual = homework_detail_manual + + #编程作业相关属性 + if homework.homework_type == 2 + homework_detail_programing = HomeworkDetailPrograming.new + homework.homework_detail_programing = homework_detail_programing + homework_detail_programing.ta_proportion = 0.5 + homework_detail_programing.language = params[:language_type].to_i + + inputs = params[:program][:input] + if Array === inputs + inputs.each_with_index do |val, i| + homework.homework_tests << HomeworkTest.new( + input: val, + output: params[:program][:output][i] + ) + end + end + + end + + if homework.save + homework_detail_manual.save if homework_detail_manual + homework_detail_programing.save if homework_detail_programing + + if params[:is_in_course] == "1" + redirect_to homework_common_index_path(:course => homework.course_id) + else + redirect_to user_homeworks_user_path(User.current.id) + end + + end + end + else + render_403 + end + end + + #用户从资源库导入资源到作业 + def user_import_resource + @user = User.current + user_course_ids = @user.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源 + @attachments = Attachment.where("(author_id = #{params[:id]} and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) "+ + "or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))").order("created_on desc") + @type = params[:type] + @homework_id = params[:homework_id] + @limit = 7 + @is_remote = true + @atta_count = @attachments.count + @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1 + @offset ||= @atta_pages.offset + #@curse_attachments_all = @all_attachments[@offset, @limit] + @attachments = paginateHelper @attachments,7 + respond_to do |format| + format.js + end + end + + #引入资源列表根据类型过滤 + def user_resource_type + if User.current.id.to_i != params[:id].to_i + render_403 + return + end + if(params[:type].blank? || params[:type] == "1") #全部 + user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源 + @attachments = Attachment.where("(author_id = #{params[:id]} and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) "+ + "or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))").order("created_on desc") + elsif params[:type] == "2" #课程资源 + user_course_ids = User.current.courses.map { |c| c.id} + @attachments = Attachment.where("(author_id = #{params[:id]} and container_type = 'Course') or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')})) ").order("created_on desc") + elsif params[:type] == "3" #项目资源 + @attachments = Attachment.where("author_id = #{params[:id]} and container_type = 'Project'").order("created_on desc") + elsif params[:type] == "4" #附件 + @attachments = Attachment.where("author_id = #{params[:id]} and container_type in('Issue','Document','Message','News','StudentWorkScore','HomewCommon')").order("created_on desc") + elsif params[:type] == "5" #用户资源 + @attachments = Attachment.where("author_id = #{params[:id]} and container_type = 'Principal'").order("created_on desc") + end + @type = params[:type] + @limit = 7 + @is_remote = true + @atta_count = @attachments.count + @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1 + @offset ||= @atta_pages.offset + #@curse_attachments_all = @all_attachments[@offset, @limit] + @attachments = paginateHelper @attachments,7 + respond_to do |format| + format.js + end + end + + + #引入资源列表根据关键词过滤 + def user_ref_resource_search + search = params[:search].to_s.strip.downcase + if(params[:type].blank? || params[:type] == "1") #全部 + user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源 取交集并查询 + @attachments = Attachment.where("((author_id = #{params[:id]} and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) "+ + " or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))) and (filename like '%#{search}%') ").order("created_on desc") + elsif params[:type] == "2" #课程资源 + user_course_ids = User.current.courses.map { |c| c.id} + @attachments = Attachment.where("(author_id = #{params[:id]} and container_type = 'Course') or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')})) and (filename like '%#{search}%') ").order("created_on desc") + elsif params[:type] == "3" #项目资源 + @attachments = Attachment.where("author_id = #{params[:id]} and container_type = 'Project' and (filename like '%#{search}%')").order("created_on desc") + elsif params[:type] == "4" #附件 + @attachments = Attachment.where("author_id = #{params[:id]} and container_type in('Project','Issue','Document','Message','News','StudentWorkScore','HomewCommon') and (filename like '%#{search}%')").order("created_on desc") + elsif params[:type] == "5" #用户资源 + @attachments = Attachment.where("author_id = #{params[:id]} and container_type = 'Principal' and (filename like '%#{search}%')").order("created_on desc") + end + @type = params[:type] + @limit = 7 + @is_remote = true + @atta_count = @attachments.count + @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1 + @offset ||= @atta_pages.offset + #@curse_attachments_all = @all_attachments[@offset, @limit] + @attachments = paginateHelper @attachments,7 + respond_to do |format| + format.js + end + end + + #将资源批量引入 + def import_resources_to_homework + @attachments = [] + unless params[:checkbox1].nil? || params[:checkbox1].blank? + params[:checkbox1].each do |id| + atta = Attachment.find(id) + att_copy = atta.copy + att_copy.container_id = nil + att_copy.container_type = nil + att_copy.author_id = User.current.id + att_copy.copy_from = atta.id + att_copy.save + @attachments << att_copy + end + end + respond_to do |format| + format.js + end end @@ -248,7 +623,7 @@ class UsersController < ApplicationController return end end - courses = @user.courses.visible.order("created_at desc") + courses = @user.courses.visible.select("courses.*,(SELECT MAX(created_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS a").order("a desc") if(params[:status] == '1') courses = courses.where("endup_time >= ? or endup_time is null or endup_time=''",Time.now) elsif(params[:status] == '2') @@ -261,14 +636,28 @@ class UsersController < ApplicationController # modified by fq def user_newfeedback + unless User.current.logged? + redirect_to signin_url + return + end + # 自己访问自己的页面才更新消息状态 + if User.current == @user + journals_messages = UserFeedbackMessage.where("user_id =? and journals_for_message_type =? and viewed =?", User.current.id, "JournalsForMessage", 0) + journals_messages.each do |journals_message| + journals_message.update_attributes(:viewed => true) + end + end + # end jours = @user.journals_for_messages.where('m_parent_id IS NULL').order('created_on DESC') - jours.update_all(:is_readed => true, :status => false) - jours.each do |journal| - fetch_user_leaveWord_reply(journal).update_all(:is_readed => true, :status => false) + if User.current == @user + jours.update_all(:is_readed => true, :status => false) + jours.each do |journal| + fetch_user_leaveWord_reply(journal).update_all(:is_readed => true, :status => false) + end end @jour = paginateHelper jours,10 @state = false - render :layout=>'base_users_new' + render :layout=>'new_base_user' end def user_comments @@ -283,16 +672,16 @@ class UsersController < ApplicationController sort_update %w(login firstname lastname mail admin created_on last_login_on) case params[:format] - when 'xml', 'json' - @offset, @limit = api_offset_and_limit({:limit => 15}) - else - @limit = 15 + when 'xml', 'json' + @offset, @limit = api_offset_and_limit({:limit => 15}) + else + @limit = 15 end # retrieve all users # 先内连一下statuses 保证排序之后数量一致 scope = User.visible. - joins("INNER JOIN user_statuses ON users.id = user_statuses.user_id") + joins("INNER JOIN user_statuses ON users.id = user_statuses.user_id") # unknow scope = scope.in_group(params[:group_id]) if params[:group_id].present? @@ -303,29 +692,29 @@ class UsersController < ApplicationController # users classify case params[:user_sort_type] - when '0' - # 创建时间排序 - @s_type = 0 - @users = scope.reorder('users.created_on DESC') - when '1' - # 活跃度排序, 就是所谓的得分情况 - @s_type = 1 - @users = scope. - joins("LEFT JOIN option_numbers ON users.id = option_numbers.user_id and option_numbers.score_type = 1"). - reorder('option_numbers.total_score DESC') - when '2' - # 粉丝数排序 - @s_type = 2 - @users = scope. - #joins("INNER JOIN user_statuses ON users.id = user_statuses.user_id"). - reorder('user_statuses.watchers_count DESC') + when '0' + # 创建时间排序 + @s_type = 0 + @users = scope.reorder('users.created_on DESC') + when '1' + # 活跃度排序, 就是所谓的得分情况 + @s_type = 1 + @users = scope. + joins("LEFT JOIN option_numbers ON users.id = option_numbers.user_id and option_numbers.score_type = 1"). + reorder('option_numbers.total_score DESC') + when '2' + # 粉丝数排序 + @s_type = 2 + @users = scope. + #joins("INNER JOIN user_statuses ON users.id = user_statuses.user_id"). + reorder('user_statuses.watchers_count DESC') - else - # 默认活跃度排序 - @s_type = 1 - @users = scope. - joins("LEFT JOIN option_numbers ON users.id = option_numbers.user_id and option_numbers.score_type = 1"). - reorder('option_numbers.total_score DESC') + else + # 默认活跃度排序 + @s_type = 1 + @users = scope. + joins("LEFT JOIN option_numbers ON users.id = option_numbers.user_id and option_numbers.score_type = 1"). + reorder('option_numbers.total_score DESC') end # limit and offset @@ -345,20 +734,20 @@ class UsersController < ApplicationController sort_init 'login', 'asc' sort_update %w(login firstname lastname mail admin created_on last_login_on) (redirect_to user_url, :notice => l(:label_sumbit_empty);return) if params[:name].blank? - case params[:format] + case params[:format] when 'xml', 'json' @offset, @limit = api_offset_and_limit({:limit => 15}) else @limit = 15#per_page_option - end - # - #@status = params[:status] || 1 - #has = { - # "show_changesets" => true - #} - # scope = User.logged.status(@status) - # @search_by = params[:search_by] ? params[:search_by][:id] : 0 - # scope = scope.like(params[:name],@search_by) if params[:name].present? + end + # + #@status = params[:status] || 1 + #has = { + # "show_changesets" => true + #} + # scope = User.logged.status(@status) + # @search_by = params[:search_by] ? params[:search_by][:id] : 0 + # scope = scope.like(params[:name],@search_by) if params[:name].present? @search_by = params[:search_by] ? params[:search_by] : 0 us = UsersService.new @@ -376,6 +765,8 @@ class UsersController < ApplicationController end @users = scope.offset(@offset).limit(limit).all.reverse end + @name = params[:name] + @type = 'users' respond_to do |format| format.html { @groups = Group.all.sort @@ -385,40 +776,16 @@ class UsersController < ApplicationController end end + #显示更多用户课程 def user_courses4show - query = Course.joins("join members m on #{Course.table_name}.id=m.course_id") - query = query.where("m.user_id = ?",@user.id).order("#{Course.table_name}.id desc") - if User.current == @user #看自己 - else - if @user.user_extensions!=nil && @user.user_extensions.identity == 0 #看老师 - query = query.joins("join member_roles r on m.id = r.member_id") - query = query.where("r.role_id in(3,7,9)") - end - query = query.where(Course.table_name+".is_public = 1") - end - - if params[:lastid]!=nil && !params[:lastid].empty? - query = query.where(" #{Course.table_name}.id < ?",params[:lastid],) - end - @list = query.limit(8) - - render :layout=>nil + @page = params[:page].to_i + 1 + @courses = @user.courses.visible.select("courses.*,(SELECT MAX(created_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS a").order("a desc").limit(5).offset(@page * 5) end - def user_projects4show - query = Project.joins("join members m on #{Project.table_name}.id=m.project_id") - query = query.where("m.user_id = ? and #{Project.table_name}.project_type=?",@user.id,Project::ProjectType_project) - if User.current == @user #看自己 - else - query = query.where(Project.table_name+".is_public = 1") - # TODO or exists (select 1 from project c2,members m2 where c2.id=m2.course_id and c2.id=#{Project.table_name}.id and m2.user_id= User.current.id) - end - - if params[:lastid]!=nil && !params[:lastid].empty? - query = query.where("( (#{Project.table_name}.updated_on=? and #{Project.table_name}.id < ?) or #{Project.table_name}.updated_onnil + #显示更多用户项目 + def user_projects4show + @page = params[:page].to_i + 1 + @projects = @user.projects.visible.select("projects.*,(SELECT MAX(created_at) FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS a").order("a desc").limit(5).offset(@page * 5) end def user_course_activities @@ -496,7 +863,39 @@ class UsersController < ApplicationController end def show - render :layout=>'base_users_new' + @page = params[:page] ? params[:page].to_i + 1 : 0 + user_project_ids = @user.projects.visible.empty? ? "(-1)" : "(" + @user.projects.visible.map{|project| project.id}.join(",") + ")" + user_course_ids = @user.courses.visible.empty? ? "(-1)" : "(" + @user.courses.visible.map{|course| course.id}.join(",") + ")" + course_types = "('Message','News','HomeworkCommon','Poll')" + project_types = "('Message','Issue')" + if params[:type].present? + case params[:type] + when "course_homework" + @user_activities = UserActivity.where("container_type = 'Course' and container_id in #{user_course_ids} and act_type = 'HomeworkCommon'").order('updated_at desc').limit(10).offset(@page * 10) + when "course_news" + @user_activities = UserActivity.where("container_type = 'Course' and container_id in #{user_course_ids} and act_type = 'News'").order('updated_at desc').limit(10).offset(@page * 10) + when "course_message" + @user_activities = UserActivity.where("container_type = 'Course' and container_id in #{user_course_ids} and act_type = 'Message'").order('updated_at desc').limit(10).offset(@page * 10) + when "course_poll" + @user_activities = UserActivity.where("container_type = 'Course' and container_id in #{user_course_ids} and act_type = 'Poll'").order('updated_at desc').limit(10).offset(@page * 10) + when "project_issue" + @user_activities = UserActivity.where("container_type = 'Project' and container_id in #{user_project_ids} and act_type = 'Issue'").order('updated_at desc').limit(10).offset(@page * 10) + when "project_message" + @user_activities = UserActivity.where("container_type = 'Project' and container_id in #{user_project_ids} and act_type = 'Message'").order('updated_at desc').limit(10).offset(@page * 10) + when "current_user" + @user_activities = UserActivity.where("user_id = #{@user.id} and ((container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types}) or (container_type = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types}))").order('updated_at desc').limit(10).offset(@page * 10) + else + @user_activities = UserActivity.where("(container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types}) or (container_type = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types})").order('updated_at desc').limit(10).offset(@page * 10) + end + else + @user_activities = UserActivity.where("(container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types}) or (container_type = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types})").order('updated_at desc').limit(10).offset(@page * 10) + end + # @user_activities = paginateHelper @user_activities,500 + @type = params[:type] + respond_to do |format| + format.js + format.html {render :layout => 'new_base_user'} + end end def show_old @@ -505,124 +904,124 @@ class UsersController < ApplicationController # Author lizanle # Description type 1 :所有动态包括我关注的人 type 2:我的动态 type 3:关于我的回复 case params[:type] - when "1" - if @user == User.current - activity = Activity.where('user_id = ?', User.current.id).order('id desc') - @activity_count = activity.count - @activity_pages = Paginator.new @activity_count, pre_count, params['page'] - @activity = activity.offset(@activity_pages.offset).limit(@activity_pages.per_page).all - @state = 1 - end - when "2" - message = [] - if @user == User.current - message = JournalsForMessage.reference_message(@user.id) - message += Journal.reference_message(@user.id) - end - @activity_count = message.size - @info_pages = Paginator.new @activity_count, pre_count, params['page'] - messages = message.sort {|x,y| y.created_on <=> x.created_on } - @message = messages[@info_pages.offset, @info_pages.per_page] - @state = 2 - else - # Time 2015-02-04 10:50:49 - # Author lizanle - # Description 所有动态 - where_condition = nil; - # where_condition = "act_type <> 'JournalsForMessage'" - user_ids = [] - if @user == User.current - watcher = User.watched_by(@user) - watcher.push(User.current) - user_ids = watcher.map{|x| x.id} - else - user_ids << @user.id - end - activity = Activity.where(where_condition).where(user_id: user_ids).order('id desc') - - permission = !User.current.admin? - if permission - #Issue - act_ids = activity.where(act_type: 'Issue').select('act_id').map{|x| x.act_id} - project_ids = Issue.where(id: act_ids).select('distinct project_id').map{|x| x.project_id} - p_ids = [] - Project.where(id: project_ids).each do |x| - p_ids << x.id unless x.visible?(User.current) - end - ids = [] - ids << Issue.where(id: act_ids, project_id: p_ids).map{|x| x.id} - - #HomeworkCommon - act_ids = activity.where(act_type: 'HomeworkCommon').select('act_id').map{|x| x.act_id} - course_ids = HomeworkCommon.where(id: act_ids).select('distinct course_id').map{|x| x.course_id} - c_ids = [] - Course.where(id: course_ids).each do |x| - c_ids << x.id unless x.is_public !=0 && User.current.member_of_course?(x) - end - ids << HomeworkCommon.where(id: act_ids, course_id: c_ids).map{|x| x.id} - - #Journal - act_ids = activity.where(act_type: 'Journal').select('act_id').map{|x| x.act_id} - project_ids = Journal.where(id:act_ids, journalized_type: 'Project').select('distinct journalized_id').map{|x| x.journalized_id} - p_ids = [] - Project.where(id: project_ids).each do |x| - p_ids << x.id unless x.visible?(User.current) + when "1" + if @user == User.current + activity = Activity.where('user_id = ?', User.current.id).order('id desc') + @activity_count = activity.count + @activity_pages = Paginator.new @activity_count, pre_count, params['page'] + @activity = activity.offset(@activity_pages.offset).limit(@activity_pages.per_page).all + @state = 1 end - ids << Journal.where(id: act_ids, journalized_id: p_ids, journalized_type: 'Project').map{|x| x.id} - - #News - act_ids = activity.where(act_type: 'News').select('act_id').map{|x| x.act_id} - project_ids = News.where(id: act_ids).select('distinct project_id').map{|x| x.project_id} - p_ids = [] - Project.where(id: project_ids).each do |x| - p_ids << x.id unless x.visible?(User.current) + when "2" + message = [] + if @user == User.current + message = JournalsForMessage.reference_message(@user.id) + message += Journal.reference_message(@user.id) end - ids << News.where(id: act_ids, project_id: p_ids).map{|x| x.id} - - project_ids = News.where(id: act_ids).select('distinct course_id').map{|x| x.course_id} - c_ids = [] - Course.where(id: project_ids).each do |x| - c_ids << x.id unless x.is_public !=0 && User.current.member_of_course?(x) - end - ids << News.where(id: act_ids, course_id: p_ids).map{|x| x.id} - - #Message - act_ids = activity.where(act_type: 'Message').select('act_id').map{|x| x.act_id} - board_ids = Message.where(id: act_ids).select('distinct board_id').map{|x| x.board_id} - project_ids = Board.where(id: board_ids).select('distinct project_id').map{|x| x.project_id} - p_ids = [] - Project.where(id: project_ids).each do |x| - p_ids << x.id unless x.visible?(User.current) + @activity_count = message.size + @info_pages = Paginator.new @activity_count, pre_count, params['page'] + messages = message.sort {|x,y| y.created_on <=> x.created_on } + @message = messages[@info_pages.offset, @info_pages.per_page] + @state = 2 + else + # Time 2015-02-04 10:50:49 + # Author lizanle + # Description 所有动态 + where_condition = nil; + # where_condition = "act_type <> 'JournalsForMessage'" + user_ids = [] + if @user == User.current + watcher = User.watched_by(@user) + watcher.push(User.current) + user_ids = watcher.map{|x| x.id} + else + user_ids << @user.id end - ids << Message.where(id: act_ids, board_id: p_ids).map{|x| x.id} + activity = Activity.where(where_condition).where(user_id: user_ids).order('id desc') + + permission = !User.current.admin? + if permission + #Issue + act_ids = activity.where(act_type: 'Issue').select('act_id').map{|x| x.act_id} + project_ids = Issue.where(id: act_ids).select('distinct project_id').map{|x| x.project_id} + p_ids = [] + Project.where(id: project_ids).each do |x| + p_ids << x.id unless x.visible?(User.current) + end + ids = [] + ids << Issue.where(id: act_ids, project_id: p_ids).map{|x| x.id} + + #HomeworkCommon + act_ids = activity.where(act_type: 'HomeworkCommon').select('act_id').map{|x| x.act_id} + course_ids = HomeworkCommon.where(id: act_ids).select('distinct course_id').map{|x| x.course_id} + c_ids = [] + Course.where(id: course_ids).each do |x| + c_ids << x.id unless x.is_public !=0 && User.current.member_of_course?(x) + end + ids << HomeworkCommon.where(id: act_ids, course_id: c_ids).map{|x| x.id} + + #Journal + act_ids = activity.where(act_type: 'Journal').select('act_id').map{|x| x.act_id} + project_ids = Journal.where(id:act_ids, journalized_type: 'Project').select('distinct journalized_id').map{|x| x.journalized_id} + p_ids = [] + Project.where(id: project_ids).each do |x| + p_ids << x.id unless x.visible?(User.current) + end + ids << Journal.where(id: act_ids, journalized_id: p_ids, journalized_type: 'Project').map{|x| x.id} + + #News + act_ids = activity.where(act_type: 'News').select('act_id').map{|x| x.act_id} + project_ids = News.where(id: act_ids).select('distinct project_id').map{|x| x.project_id} + p_ids = [] + Project.where(id: project_ids).each do |x| + p_ids << x.id unless x.visible?(User.current) + end + ids << News.where(id: act_ids, project_id: p_ids).map{|x| x.id} - project_ids = Board.where(id: board_ids).select('distinct course_id').map{|x| x.course_id} - c_ids = [] - Course.where(id: project_ids).each do |x| - c_ids << x.id unless x.is_public !=0 && User.current.member_of_course?(x) - end - ids << Message.where(id: act_ids, board_id: c_ids).map{|x| x.id} + project_ids = News.where(id: act_ids).select('distinct course_id').map{|x| x.course_id} + c_ids = [] + Course.where(id: project_ids).each do |x| + c_ids << x.id unless x.is_public !=0 && User.current.member_of_course?(x) + end + ids << News.where(id: act_ids, course_id: p_ids).map{|x| x.id} + + #Message + act_ids = activity.where(act_type: 'Message').select('act_id').map{|x| x.act_id} + board_ids = Message.where(id: act_ids).select('distinct board_id').map{|x| x.board_id} + project_ids = Board.where(id: board_ids).select('distinct project_id').map{|x| x.project_id} + p_ids = [] + Project.where(id: project_ids).each do |x| + p_ids << x.id unless x.visible?(User.current) + end + ids << Message.where(id: act_ids, board_id: p_ids).map{|x| x.id} - logger.debug "filter ids #{ids}" + project_ids = Board.where(id: board_ids).select('distinct course_id').map{|x| x.course_id} + c_ids = [] + Course.where(id: project_ids).each do |x| + c_ids << x.id unless x.is_public !=0 && User.current.member_of_course?(x) + end + ids << Message.where(id: act_ids, board_id: c_ids).map{|x| x.id} - activity = activity.where('act_id not in (?)', ids.flatten ).order('id desc') unless ids.flatten.empty? - end + logger.debug "filter ids #{ids}" - # activity = activity.reject { |e| - # e.act.nil? || - # (!User.current.admin? && !e.act.nil? - # (((e.act_type == "Issue") && !e.act.project.visible?(User.current)) || - # (e.act_type == "Bid" && !e.act.courses.first.nil? && e.act.courses.first.is_public == 0 && !User.current.member_of_course?(e.act.courses.first)) || - # (e.act_type == "Journal" && e.act.respond_to?("Project") && !e.act.project.visible?(User.current)) || - # (e.act_type == "News" && ((!e.act.project.nil? && !e.act.project.visible?(User.current)) || (!e.act.course.nil? && e.act.course.is_public == 0 && !User.current.member_of_course?(e.act.course)))) || - # (e.act_type == "Message" && !e.act.board.nil? && ((!e.act.board.project.nil? && !e.act.board.project.visible?(User.current)) || (!e.act.board.course.nil? && e.act.board.course.is_public == 0 && !User.current.member_of_course?(e.act.board.course)))))) - # } - # + activity = activity.where('act_id not in (?)', ids.flatten ).order('id desc') unless ids.flatten.empty? + end - @activity_count = activity.count - @activity_pages = Paginator.new @activity_count, pre_count, params['page'] - @activity = activity.slice(@activity_pages.offset,@activity_pages.per_page) - @state = 0 + # activity = activity.reject { |e| + # e.act.nil? || + # (!User.current.admin? && !e.act.nil? + # (((e.act_type == "Issue") && !e.act.project.visible?(User.current)) || + # (e.act_type == "Bid" && !e.act.courses.first.nil? && e.act.courses.first.is_public == 0 && !User.current.member_of_course?(e.act.courses.first)) || + # (e.act_type == "Journal" && e.act.respond_to?("Project") && !e.act.project.visible?(User.current)) || + # (e.act_type == "News" && ((!e.act.project.nil? && !e.act.project.visible?(User.current)) || (!e.act.course.nil? && e.act.course.is_public == 0 && !User.current.member_of_course?(e.act.course)))) || + # (e.act_type == "Message" && !e.act.board.nil? && ((!e.act.board.project.nil? && !e.act.board.project.visible?(User.current)) || (!e.act.board.course.nil? && e.act.board.course.is_public == 0 && !User.current.member_of_course?(e.act.board.course)))))) + # } + # + + @activity_count = activity.count + @activity_pages = Paginator.new @activity_count, pre_count, params['page'] + @activity = activity.slice(@activity_pages.offset,@activity_pages.per_page) + @state = 0 end if params[:user].present? @@ -650,7 +1049,7 @@ class UsersController < ApplicationController if !@user.active? #|| (@user != User.current && @memberships.empty? && events.empty?) # redirect_to home_path render_404 - return + return end end @@ -682,7 +1081,7 @@ class UsersController < ApplicationController unless User.current.admin? if !@user.active? render_404 - return + return end end @@ -740,7 +1139,7 @@ class UsersController < ApplicationController unless @user.id.nil? #后台注册的用户默认权限为男性开发员 ue = UserExtensions.create(:identity => 3, - :gender => 0, + :gender => 0, :user_id => @user.id) ue.save end @@ -805,6 +1204,328 @@ class UsersController < ApplicationController end end + # 上传用户资源 + def user_resource_create + @user = User.find(params[:id]) + #@user.save_attachments(params[:attachments],User.current) + # Container_type为Principal + Attachment.attach_filesex(@user, params[:attachments], params[:attachment_type]) + if(params[:type].blank?|| params[:type] == "1") #全部 + if User.current.id.to_i == params[:id].to_i + user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源 + @attachments = Attachment.where("(author_id = #{params[:id]} and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) "+ + "or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))").order("created_on desc") + else + user_course_ids = User.find(params[:id]).courses.visible.map { |c| c.id} #Ta的资源库的话,应该是他上传的公开资源 加上 他加入的所有我可见课程里的公开资源 + @attachments = Attachment.where("(author_id = #{params[:id]} and is_public = 1 " + + "and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) " + + "or (container_type = 'Course' and is_public = 1 and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))").order("created_on desc") + end + elsif params[:type] == "2" #课程资源 + if User.current.id.to_i == params[:id].to_i + user_course_ids = User.current.courses.map { |c| c.id} + @attachments = Attachment.where("(author_id = #{params[:id]} and container_type = 'Course') or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')})) ").order("created_on desc") + else + user_course_ids = User.find(params[:id]).courses.visible.map { |c| c.id} #如果课程私有资源,那么要看这个资源的课程是不是在 这个user的所有我可见的课程中 + @attachments = Attachment.where("(author_id = #{params[:id]} and is_public = 1 and container_type = 'Course')"+ + "or (container_type = 'Course' and is_public = 1 and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))").order("created_on desc") + end + elsif params[:type] == "3" #项目资源 + if User.current.id.to_i == params[:id].to_i + @attachments = Attachment.where("author_id = #{params[:id]} and container_type = 'Project'").order("created_on desc") + else + @attachments = Attachment.where("author_id = #{params[:id]} and is_public = 1 and container_type = 'Project' ").order("created_on desc") + end + elsif params[:type] == "4" #附件 + if User.current.id.to_i == params[:id].to_i + @attachments = Attachment.where("author_id = #{params[:id]} and container_type in('Issue','Document','Message','News','StudentWorkScore','HomewCommon')").order("created_on desc") + else + @attachments = Attachment.where("author_id = #{params[:id]} and is_public = 1 and container_type in('Issue','Document','Message','News','StudentWorkScore','HomewCommon')").order("created_on desc") + end + elsif params[:type] == "5" #附件 + if User.current.id.to_i == params[:id].to_i + @attachments = Attachment.where("author_id = #{params[:id]} and container_type ='Principal'").order("created_on desc") + else + @attachments = Attachment.where("author_id = #{params[:id]} and is_public = 1 and container_type ='Principal'").order("created_on desc") + end + end + @type = params[:type] || 1 + @limit = 25 + @is_remote = true + @atta_count = @attachments.count + @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1 + @offset ||= @atta_pages.offset + #@curse_attachments_all = @all_attachments[@offset, @limit] + @attachments = paginateHelper @attachments,25 + respond_to do |format| + format.js + end + end + + # 删除用户资源,分为批量删除 和 单个删除,只能删除自己上传的资源 + def user_resource_delete + if params[:resource_id].present? + Attachment.where("author_id = #{User.current.id}").delete(params[:resource_id]) + elsif params[:checkbox1].present? + params[:checkbox1].each do |id| + Attachment.where("author_id = #{User.current.id}").delete(id) + end + end + + if(params[:type].blank? || params[:type] == "1") #全部 + if User.current.id.to_i == params[:id].to_i + user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源 + @attachments = Attachment.where("(author_id = #{params[:id]} and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) "+ + "or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))").order("created_on desc") + else + user_course_ids = User.find(params[:id]).courses.visible.map { |c| c.id} #Ta的资源库的话,应该是他上传的公开资源 加上 他加入的所有我可见课程里的公开资源 + @attachments = Attachment.where("(author_id = #{params[:id]} and is_public = 1 " + + "and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) " + + "or (container_type = 'Course' and is_public = 1 and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))").order("created_on desc") + end + elsif params[:type] == "2" #课程资源 + if User.current.id.to_i == params[:id].to_i + user_course_ids = User.current.courses.map { |c| c.id} + @attachments = Attachment.where("(author_id = #{params[:id]} and container_type = 'Course') or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')})) ").order("created_on desc") + else + user_course_ids = User.find(params[:id]).courses.visible.map { |c| c.id} #如果课程私有资源,那么要看这个资源的课程是不是在 这个user的所有我可见的课程中 + @attachments = Attachment.where("(author_id = #{params[:id]} and is_public = 1 and container_type = 'Course')"+ + "or (container_type = 'Course' and is_public = 1 and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))").order("created_on desc") + end + elsif params[:type] == "3" #项目资源 + if User.current.id.to_i == params[:id].to_i + @attachments = Attachment.where("author_id = #{params[:id]} and container_type = 'Project'").order("created_on desc") + else + @attachments = Attachment.where("author_id = #{params[:id]} and is_public = 1 and container_type = 'Project' ").order("created_on desc") + end + elsif params[:type] == "4" #附件 + if User.current.id.to_i == params[:id].to_i + @attachments = Attachment.where("author_id = #{params[:id]} and container_type in('Issue','Document','Message','News','StudentWorkScore','HomewCommon')").order("created_on desc") + else + @attachments = Attachment.where("author_id = #{params[:id]} and is_public = 1 and container_type in('Issue','Document','Message','News','StudentWorkScore','HomewCommon')").order("created_on desc") + end + elsif params[:type] == "5" #用户资源 + if User.current.id.to_i == params[:id].to_i + @attachments = Attachment.where("author_id = #{params[:id]} and container_type ='Principal'").order("created_on desc") + else + @attachments = Attachment.where("author_id = #{params[:id]} and is_public = 1 and container_type ='Principal'").order("created_on desc") + end + end + @type = params[:type] + @limit = 25 + @is_remote = true + @atta_count = @attachments.count + @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1 + @offset ||= @atta_pages.offset + #@curse_attachments_all = @all_attachments[@offset, @limit] + @attachments = paginateHelper @attachments,25 + respond_to do |format| + format.js + end + end + + #根据id或者名称搜索教师或者助教为当前用户的课程 + def search_user_course + @user = User.current + if !params[:search].nil? + @course = @user.courses.where(" #{Course.table_name}.id = #{params[:search].to_i } or #{Course.table_name}.name like '%#{params[:search.to_s]}%'") + .select { |course| @user.allowed_to?(:as_teacher,course)} + else + @course = @user.courses + .select { |course| @user.allowed_to?(:as_teacher,course)} + end + #这里仅仅是传递需要发送的资源id + @send_id = params[:send_id] + @send_ids = params[:checkbox1] || params[:send_ids] + respond_to do |format| + format.js + end + end + + # 根据id或者名称搜索当前用户所在的项目 + def search_user_project + @user = User.current + if !params[:search].nil? + @projects = @user.projects.where(" #{Project.table_name}.id = #{params[:search].to_i } or #{Project.table_name}.name like '%#{params[:search.to_s]}%'") + else + @projects = @user.projects + end + #这里仅仅是传递需要发送的资源id + @send_id = params[:send_id] + @send_ids = params[:checkbox1] || params[:send_ids] #搜索的时候 和 直接 用表格提交的时候的send_ids + respond_to do |format| + format.js + end + end + + # 将资源发送到对应的课程,分为发送单个,或者批量发送 + def add_exist_file_to_course + @flag = true + if params[:send_id].present? + send_id = params[:send_id] + ori = Attachment.find_by_id(send_id) + course_ids = params[:course_ids] + if course_ids.nil? + @flag = false + end + unless course_ids.nil? + course_ids.each do |id| + next if ori.blank? + attach_copied_obj = ori.copy + attach_copied_obj.tag_list.add(ori.tag_list) # tag关联 + attach_copied_obj.container = Course.find(id) + attach_copied_obj.created_on = Time.now + attach_copied_obj.author_id = User.current.id + if attach_copied_obj.attachtype == nil + attach_copied_obj.attachtype = 4 + end + attach_copied_obj.save + @save_message = attach_copied_obj.errors.full_messages + end + end + elsif params[:send_ids].present? + send_ids = params[:send_ids].split(" ") + course_ids = params[:course_ids] + if course_ids.nil? + @flag = false + end + send_ids.each do |send_id| + ori = Attachment.find_by_id(send_id) + + unless course_ids.nil? + course_ids.each do |id| + next if ori.blank? + attach_copied_obj = ori.copy + attach_copied_obj.tag_list.add(ori.tag_list) # tag关联 + attach_copied_obj.container = Course.find(id) + attach_copied_obj.created_on = Time.now + attach_copied_obj.author_id = User.current.id + if attach_copied_obj.attachtype == nil + attach_copied_obj.attachtype = 4 + end + attach_copied_obj.save + @save_message = attach_copied_obj.errors.full_messages + end + end + end + else + @flag = false + end + user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源 + @attachments = Attachment.where("(author_id = #{params[:id]} and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) "+ + "or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))").order("created_on desc") + @type = params[:type] + @limit = 25 + @user = User.current + @is_remote = true + @atta_count = @attachments.count + @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1 + @offset ||= @atta_pages.offset + #@curse_attachments_all = @all_attachments[@offset, @limit] + @attachments = paginateHelper @attachments,25 + respond_to do |format| + format.js + end + end + + # 添加资源到对应的项目 + def add_exist_file_to_project + @flag = true + if params[:send_id].present? + send_id = params[:send_id] + project_ids = params[:projects_ids] + if project_ids.nil? + @flag = false + end + ori = Attachment.find_by_id(send_id) + unless project_ids.nil? + project_ids.each do |project_id| + next if ori.blank? + attach_copied_obj = ori.copy + attach_copied_obj.tag_list.add(ori.tag_list) # tag关联 + attach_copied_obj.container = Project.find(project_id) + attach_copied_obj.created_on = Time.now + attach_copied_obj.author_id = User.current.id + if attach_copied_obj.attachtype == nil + attach_copied_obj.attachtype = 1 + end + attach_copied_obj.save + end + end + elsif params[:send_ids].present? + send_ids = params[:send_ids].split(" ") + project_ids = params[:projects_ids] + if project_ids.nil? + @flag = false + end + send_ids.each do |send_id| + + ori = Attachment.find_by_id(send_id) + unless project_ids.nil? + project_ids.each do |project_id| + next if ori.blank? + attach_copied_obj = ori.copy + attach_copied_obj.tag_list.add(ori.tag_list) # tag关联 + attach_copied_obj.container = Project.find(project_id) + attach_copied_obj.created_on = Time.now + attach_copied_obj.author_id = User.current.id + if attach_copied_obj.attachtype == nil + attach_copied_obj.attachtype = 1 + end + attach_copied_obj.save + end + end + end + else + @flag=true + end + user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源 + @attachments = Attachment.where("(author_id = #{params[:id]} and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) "+ + "or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))").order("created_on desc") + @type = params[:type] + @limit = 25 + @user = User.current + @is_remote = true + @atta_count = @attachments.count + @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1 + @offset ||= @atta_pages.offset + #@curse_attachments_all = @all_attachments[@offset, @limit] + @attachments = paginateHelper @attachments,25 + respond_to do |format| + format.js + end + end + + # 资源预览 + def resource_preview + preview_id = params[:resource_id] + @file = Attachment.find(preview_id) + @preview_able = false; + if %w(pdf pptx doc docx xls xlsx).any?{|x| @file.filename.downcase.end_with?(x)} + @preview_able = true; + end + respond_to do |format| + format.js + end + end + + # 重命名资源 + def rename_resource + @attachment = Attachment.find(params[:res_id]) if params[:res_id].present? + if @attachment != nil + @attachment.filename = params[:res_name] + @flag = @attachment.save + end + # respond_to do |format| + # format.js + # end + if @flag + render :text=> download_named_attachment_path(@attachment.id, @attachment.filename) + else + render :text=>'fail' + end + end + def destroy @user.destroy respond_to do |format| @@ -825,7 +1546,7 @@ class UsersController < ApplicationController def destroy_membership @membership = Member.find(params[:membership_id]) if @membership.deletable? - @membership.destroy + @membership.destroy end respond_to do |format| format.html { redirect_to edit_user_url(@user, :tab => 'memberships') } @@ -840,31 +1561,31 @@ class UsersController < ApplicationController @obj_flag = params[:tag_for_save][:object_flag] case @obj_flag - when '1' then - @obj = User.find_by_id(@obj_id) - when '2' then - @obj = Project.find_by_id(@obj_id) - when '3' then - @obj = Issue.find_by_id(@obj_id) - when '4' then - # @obj = Bid.find_by_id(@obj_id) - when '5' then - @obj = Forum.find_by_id(@obj_id) - when '6' - @obj = Attachment.find_by_id(@obj_id) - when '7' then - @obj = Contest.find_by_id(@obj_id) - when '8' - @obj = OpenSourceProject.find_by_id(@obj_id) - when '9' - @obj = Course.find_by_id(@obj_id) - else - @obj = nil + when '1' then + @obj = User.find_by_id(@obj_id) + when '2' then + @obj = Project.find_by_id(@obj_id) + when '3' then + @obj = Issue.find_by_id(@obj_id) + when '4' then + # @obj = Bid.find_by_id(@obj_id) + when '5' then + @obj = Forum.find_by_id(@obj_id) + when '6' + @obj = Attachment.find_by_id(@obj_id) + when '7' then + @obj = Contest.find_by_id(@obj_id) + when '8' + @obj = OpenSourceProject.find_by_id(@obj_id) + when '9' + @obj = Course.find_by_id(@obj_id) + else + @obj = nil end unless @obj.nil? @obj.tag_list.add(@tags.split(",")) else - return + return end if @obj.save logger.debug "#{__FILE__}:#{__LINE__} ===> #{@obj.to_json}" @@ -926,8 +1647,8 @@ class UsersController < ApplicationController @obj_count = query.count(); @obj_pages = Paginator.new @obj_count,limit,params['page'] @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all(); - - render :template=>'users/user_fanslist',:layout=>'base_users_new' + @action = 'watch' + render :template=>'users/user_fanslist',:layout=>'new_base_user' end ###add by huang def user_fanslist @@ -937,7 +1658,7 @@ class UsersController < ApplicationController @obj_pages = Paginator.new @obj_count,limit,params['page'] @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all(); @action = 'fans' - render :layout=>'base_users_new' + render :layout=>'new_base_user' end def user_visitorlist limit = 10; @@ -955,55 +1676,143 @@ class UsersController < ApplicationController def update_extensions(user_extensions) user_extensions = params[:user_extensions] unless user_extensions.nil? - user_extensions = UserExtensions.find_by_id(user_extensions.user_id) + user_extensions = UserExtensions.find_by_id(user_extensions.user_id) - # user_extensions. + # user_extensions. end end -# added by bai - def topic_score_index - - end - - def project_score_index - - end - - def activity_score_index - - end - - def influence_score_index - - end - - def score_index - - end -# end - def topic_new_score_index - - end - - def project_new_score_index - - end - - def activity_new_score_index - + def update_score + @user = User.find(params[:id]) end - def influence_new_score_index - + #修改个人简介 + def edit_brief_introduction + if @user && @user.extensions + @user.extensions.update_column("brief_introduction",params[:brief_introduction]) + end + respond_to do |format| + format.js + end end - def score_new_index - + # 资源库 分为全部 课程资源 项目资源 附件 + def user_resource + #确定container_type + # @user = User.find(params[:id]) + # 别人的资源库是没有权限去看的 + if User.current.id.to_i != params[:id].to_i + render_403 + return + end + if(params[:type].blank? || params[:type] == "1") #全部 + if User.current.id.to_i == params[:id].to_i + user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源 + @attachments = Attachment.where("(author_id = #{params[:id]} and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) "+ + "or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))").order("created_on desc") + else + user_course_ids = User.find(params[:id]).courses.visible.map { |c| c.id} #Ta的资源库的话,应该是他上传的公开资源 加上 他加入的所有我可见课程里的公开资源 + @attachments = Attachment.where("(author_id = #{params[:id]} and is_public = 1 " + + "and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) " + + "or (container_type = 'Course' and is_public = 1 and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))").order("created_on desc") + end + elsif params[:type] == "2" #课程资源 + if User.current.id.to_i == params[:id].to_i + user_course_ids = User.current.courses.map { |c| c.id} + @attachments = Attachment.where("(author_id = #{params[:id]} and container_type = 'Course') or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')})) ").order("created_on desc") + else + user_course_ids = User.find(params[:id]).courses.visible.map { |c| c.id} #如果课程私有资源,那么要看这个资源的课程是不是在 这个user的所有我可见的课程中 + @attachments = Attachment.where("(author_id = #{params[:id]} and is_public = 1 and container_type = 'Course')"+ + "or (container_type = 'Course' and is_public = 1 and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))").order("created_on desc") + end + elsif params[:type] == "3" #项目资源 + if User.current.id.to_i == params[:id].to_i + @attachments = Attachment.where("author_id = #{params[:id]} and container_type = 'Project'").order("created_on desc") + else + @attachments = Attachment.where("author_id = #{params[:id]} and is_public = 1 and container_type = 'Project' ").order("created_on desc") + end + elsif params[:type] == "4" #附件 + if User.current.id.to_i == params[:id].to_i + @attachments = Attachment.where("author_id = #{params[:id]} and container_type in('Issue','Document','Message','News','StudentWorkScore','HomewCommon')").order("created_on desc") + else + @attachments = Attachment.where("author_id = #{params[:id]} and is_public = 1 and container_type in('Issue','Document','Message','News','StudentWorkScore','HomewCommon')").order("created_on desc") + end + elsif params[:type] == "5" #用户资源 + if User.current.id.to_i == params[:id].to_i + @attachments = Attachment.where("author_id = #{params[:id]} and container_type = 'Principal'").order("created_on desc") + else + @attachments = Attachment.where("author_id = #{params[:id]} and is_public = 1 and container_type = 'Principal'").order("created_on desc") + end + end + @type = params[:type] + @limit = 25 + @is_remote = true + @atta_count = @attachments.count + @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1 + @offset ||= @atta_pages.offset + #@curse_attachments_all = @all_attachments[@offset, @limit] + @attachments = paginateHelper @attachments,25 + respond_to do |format| + format.js + format.html {render :layout => 'new_base_user'} + end end - def update_score - @user = User.find(params[:id]) + # 根据资源关键字进行搜索 + def resource_search + search = params[:search].to_s.strip.downcase + if(params[:type].nil? || params[:type] == "1") #全部 + if User.current.id.to_i == params[:id].to_i + user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源 取交集并查询 + @attachments = Attachment.where("((author_id = #{params[:id]} and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) "+ + " or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))) and (filename like '%#{search}%') ").order("created_on desc") + else + user_course_ids = User.find(params[:id]).courses.visible.map { |c| c.id} #如果课程私有资源,那么要看这个资源的课程是不是在 这个user的所有我可见的课程中 + @attachments = Attachment.where("((author_id = #{params[:id]} and is_public = 1 and container_type in" + + " ('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon'))"+ + " or (container_type = 'Course' and is_public = 1 and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')})) )" + + " and (filename like '%#{search}%') ").order("created_on desc") + end + elsif params[:type] == "2" #课程资源 + if User.current.id.to_i == params[:id].to_i + user_course_ids = User.current.courses.map { |c| c.id} + @attachments = Attachment.where("(author_id = #{params[:id]} and container_type = 'Course') or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')})) and (filename like '%#{search}%') ").order("created_on desc") + else + user_course_ids = User.find(params[:id]).courses.visible.map { |c| c.id} #如果课程私有资源,那么要看这个资源的课程是不是在 这个user的所有我可见的课程中 + @attachments = Attachment.where("((author_id = #{params[:id]} and is_public = 1 and container_type = 'Course') "+ + "or (container_type = 'Course' and is_public = 1 and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')})) )"+ + " and (filename like '%#{search}%') ").order("created_on desc") + end + elsif params[:type] == "3" #项目资源 + if User.current.id.to_i == params[:id].to_i + @attachments = Attachment.where("author_id = #{params[:id]} and container_type = 'Project' and (filename like '%#{search}%')").order("created_on desc") + else + @attachments = Attachment.where("author_id = #{params[:id]} and is_public = 1 and container_type = 'Project' and (filename like '%#{search}%') ").order("created_on desc") + end + elsif params[:type] == "4" #附件 + if User.current.id.to_i == params[:id].to_i + @attachments = Attachment.where("author_id = #{params[:id]} and container_type in('Project','Issue','Document','Message','News','StudentWorkScore','HomewCommon') and (filename like '%#{search}%')").order("created_on desc") + else + @attachments = Attachment.where("author_id = #{params[:id]} and is_public = 1 and container_type in('Issue','Document','Message','News','StudentWorkScore','HomewCommon') and (filename like '%#{search}%')").order("created_on desc") + end + elsif params[:type] == "5" #用户资源 + if User.current.id.to_i == params[:id].to_i + @attachments = Attachment.where("author_id = #{params[:id]} and container_type = 'Principal' and (filename like '%#{search}%')").order("created_on desc") + else + @attachments = Attachment.where("author_id = #{params[:id]} and is_public = 1 and container_type = 'Principal' and (filename like '%#{search}%')").order("created_on desc") + end + end + @type = params[:type] + @limit = 25 + @is_remote = true + @atta_count = @attachments.count + @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1 + @offset ||= @atta_pages.offset + #@curse_attachments_all = @all_attachments[@offset, @limit] + @attachments = paginateHelper @attachments,25 + respond_to do |format| + format.js + end end private @@ -1019,7 +1828,7 @@ class UsersController < ApplicationController render_404 end - def setting_layout(default_base='base_users') + def setting_layout(default_base='base_users_new') User.current.admin? ? default_base : default_base end @@ -1069,4 +1878,7 @@ class UsersController < ApplicationController impl.save end end + + + end diff --git a/app/controllers/watchers_controller.rb b/app/controllers/watchers_controller.rb index 35e1d5ba4..6e7f0adc6 100644 --- a/app/controllers/watchers_controller.rb +++ b/app/controllers/watchers_controller.rb @@ -22,9 +22,26 @@ class WatchersController < ApplicationController def watch s = WatchesService.new watchables = s.watch params.merge(:current_user_id => User.current.id) + if params[:action_name] == 'watch' + limit = 10; + query = User.watched_by(params[:target_id]); + @obj_count = query.count(); + @obj_pages = Paginator.new @obj_count,limit,params['page'] + @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all(); + @action = 'watch' + elsif params[:action_name] == 'fans' + limit = 10; + query = User.find(params[:target_id]).watcher_users; + @obj_count = query.count(); + @obj_pages = Paginator.new @obj_count,limit,params['page'] + @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all(); + @action = 'fans' + else + + end respond_to do |format| format.html { redirect_to_referer_or {render :text => (true ? 'Watcher added.' : 'Watcher removed.'), :layout => true}} - format.js { render :partial => 'set_watcher', :locals => {:user => User.current, :watched => watchables,:params=>params,:opt=>'add'} } + format.js { render :partial => 'set_watcher', :locals => {:user => User.current, :watched => watchables,:params=>params,:opt=>'add',:list => @list,:action_name=>params[:action_name],:page=>params[:page],:count=>@obj_count} } end rescue Exception => e if e.message == "404" @@ -38,9 +55,25 @@ class WatchersController < ApplicationController def unwatch s = WatchesService.new watchables = s.unwatch params.merge(:current_user_id => User.current.id) + if params[:action_name] == 'watch' + limit = 10; + query = User.watched_by(params[:target_id]); + @obj_count = query.count(); + @obj_pages = Paginator.new @obj_count,limit,params['page'] + @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all(); + @action = 'watch' + elsif params[:action_name] == 'fans' + limit = 10; + query = User.find(params[:target_id]).watcher_users; + @obj_count = query.count(); + @obj_pages = Paginator.new @obj_count,limit,params['page'] + @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all(); + @action = 'fans' + else + end respond_to do |format| format.html { redirect_to_referer_or {render :text => (false ? 'Watcher added.' : 'Watcher removed.'), :layout => true}} - format.js { render :partial => 'set_watcher', :locals => {:user => User.current, :watched => watchables,:params=>params,:opt=>'delete'} } + format.js { render :partial => 'set_watcher', :locals => {:user => User.current, :watched => watchables,:params=>params,:opt=>'delete',:list=>@list,:action_name=>params[:action_name],:page=>params[:page],:count=>@obj_count} } end rescue Exception => e if e.message == "404" diff --git a/app/controllers/welcome_controller.rb b/app/controllers/welcome_controller.rb index 6b14db9bb..784066378 100644 --- a/app/controllers/welcome_controller.rb +++ b/app/controllers/welcome_controller.rb @@ -27,7 +27,8 @@ class WelcomeController < ApplicationController def index # 企业版定制: params[:project]为传过来的参数 - + redirect_to signin_path + return unless params[:organization].nil? @organization = Organization.find params[:organization] # @organization_projects = Project.joins(:project_status).joins("LEFT JOIN project_scores ON projects.id = project_scores.project_id").where("projects.organization_id = ?", @organization.id).order("score DESC").limit(10).all @@ -95,11 +96,14 @@ class WelcomeController < ApplicationController @projects = Project.all_public.active render :layout => false, :content_type => 'text/plain' end - + def course - @course_page = FirstPage.find_by_page_type('course') - @school_id = params[:school_id] || User.current.user_extensions.school.try(:id) || 117 - @logoLink ||= logolink() + redirect_to signin_path + return + # + # @course_page = FirstPage.find_by_page_type('course') + # @school_id = params[:school_id] || User.current.user_extensions.school.try(:id) || 117 + # @logoLink ||= logolink() end def logolink() @@ -139,8 +143,11 @@ class WelcomeController < ApplicationController def contest - @contest_page = FirstPage.find_by_page_type('contest') - @contest_notifications = Contestnotification.order("created_at desc").limit(5) + redirect_to signin_path + return + + # @contest_page = FirstPage.find_by_page_type('contest') + # @contest_notifications = Contestnotification.order("created_at desc").limit(5) end def search @@ -171,7 +178,7 @@ class WelcomeController < ApplicationController redirect_to users_search_url(:name => search_condition, :search_by => search_by, :role => :student) else #redirect_to home_path, :alert => l(:label_sumbit_empty) - (redirect_to home_url, :notice => l(:label_sumbit_empty);return) #if params[:name].blank? + (redirect_to signin_path, :notice => l(:label_sumbit_empty);return) #if params[:name].blank? end } end @@ -180,28 +187,28 @@ class WelcomeController < ApplicationController private # 判断网站的入口,是课程 course 则跳过index去渲染 course 方法 def entry_select - url = request.original_url.gsub('/','') - if url.include?(Setting.url_course.gsub('/','')) - if @first_page.show_course == 1 - course - render :course - else - render_404 - end - - return 0 - elsif url.include?(Setting.url_contest.gsub('/','')) - if @first_page.show_contest == 1 - contest - render :contest - else - render_404 - end - - return 0 - elsif url.include?(Setting.url_user.gsub('/','')) - #redirect_to(:controller => "users", :action => "index") - end + # url = request.original_url.gsub('/','') + # if url.include?(Setting.url_course.gsub('/','')) + # if @first_page.show_course == 1 + # course + # render :course + # else + # render_404 + # end + # + # return 0 + # elsif url.include?(Setting.url_contest.gsub('/','')) + # if @first_page.show_contest == 1 + # contest + # render :contest + # else + # render_404 + # end + # + # return 0 + # elsif url.include?(Setting.url_user.gsub('/','')) + # #redirect_to(:controller => "users", :action => "index") + # end end diff --git a/app/controllers/wiki_controller.rb b/app/controllers/wiki_controller.rb index f74fbb04d..da6d48b8d 100644 --- a/app/controllers/wiki_controller.rb +++ b/app/controllers/wiki_controller.rb @@ -264,7 +264,7 @@ class WikiController < ApplicationController end @page.destroy respond_to do |format| - format.html { redirect_to project_wiki_index_url(@project) } + format.html {redirect_to edit_project_wiki_page_url @project, @page.title} format.api { render_api_ok } end end diff --git a/app/controllers/words_controller.rb b/app/controllers/words_controller.rb index fc723d5d5..a59f507df 100644 --- a/app/controllers/words_controller.rb +++ b/app/controllers/words_controller.rb @@ -53,7 +53,19 @@ class WordsController < ApplicationController :notes => content, :is_readed => false} @jfm = add_reply_adapter options - + @save_succ = true if @jfm.errors.empty? + if @save_succ + course_activity = CourseActivity.where("course_act_type='JournalsForMessage' and course_act_id =#{parent_id}").first + if course_activity + course_activity.updated_at = Time.now + course_activity.save + end + user_activity = UserActivity.where("act_type='JournalsForMessage' and act_id =#{parent_id}").first + if user_activity + user_activity.updated_at = Time.now + user_activity.save + end + end respond_to do |format| # format.html { # if @jfm.errors.empty? @@ -63,27 +75,31 @@ class WordsController < ApplicationController # end # render 'test/index' # } - format.js{ - @save_succ = true if @jfm.errors.empty? + format.js { + @user_activity_id = params[:user_activity_id] if + @activity = JournalsForMessage.find(parent_id) } end + end def destroy - @journal_destroyed = JournalsForMessage.delete_message(params[:object_id]) - if @journal_destroyed.jour_type == "Bid" - @bid = Bid.find(@journal_destroyed.jour_id) - @jours_count = @bid.journals_for_messages.where('m_parent_id IS NULL').count - elsif @journal_destroyed.jour_type == "Course" - @course = Course.find @journal_destroyed.jour_id - @jours_count = @course.journals_for_messages.where('m_parent_id IS NULL').count - elsif @journal_destroyed.jour_type == "Principal" - @user = User.find(@journal_destroyed.jour_id) - @jours_count = @user.journals_for_messages.where('m_parent_id IS NULL').count - @is_user = true - end - respond_to do |format| - format.js + @journal_destroyed = JournalsForMessage.find params[:object_id] + if @journal_destroyed.destroy + if @journal_destroyed.jour_type == "Bid" + @bid = Bid.find(@journal_destroyed.jour_id) + @jours_count = @bid.journals_for_messages.where('m_parent_id IS NULL').count + elsif @journal_destroyed.jour_type == "Course" + @course = Course.find @journal_destroyed.jour_id + @jours_count = @course.journals_for_messages.where('m_parent_id IS NULL').count + elsif @journal_destroyed.jour_type == "Principal" + @user = User.find(@journal_destroyed.jour_id) + @jours_count = @user.journals_for_messages.where('m_parent_id IS NULL').count + @is_user = true + end + respond_to do |format| + format.js + end end end @@ -200,11 +216,15 @@ class WordsController < ApplicationController #给用户留言 def leave_user_message - @user = User.find(params[:id]) - if params[:new_form][:user_message].size>0 && User.current.logged? && @user - @user.add_jour(User.current, params[:new_form][:user_message]) + if User.current.logged? + @user = User.find(params[:id]) + if params[:new_form][:user_message].size>0 && User.current.logged? && @user + @user.add_jour(User.current, params[:new_form][:user_message]) + end + redirect_to feedback_path(@user) + else + render_403 end - redirect_to feedback_path(@user) end # add by nwb diff --git a/app/controllers/zipdown_controller.rb b/app/controllers/zipdown_controller.rb index 53b40942a..1a01ac97b 100644 --- a/app/controllers/zipdown_controller.rb +++ b/app/controllers/zipdown_controller.rb @@ -1,4 +1,4 @@ -require 'zip' +require 'zip' class ZipdownController < ApplicationController #查找项目(课程) before_filter :find_project_by_bid_id, :only => [:assort] @@ -7,7 +7,7 @@ class ZipdownController < ApplicationController SAVE_FOLDER = "#{Rails.root}/files" OUTPUT_FOLDER = "#{Rails.root}/files/archiveZip" - #统一下载功能 + #统一下载功能 def download if User.current.logged? begin diff --git a/app/helpers/api_helper.rb b/app/helpers/api_helper.rb index f26f5c19b..f73cc87e6 100644 --- a/app/helpers/api_helper.rb +++ b/app/helpers/api_helper.rb @@ -75,7 +75,7 @@ module ApiHelper # 学生获取课程作业的状态 def get_homework_status homework homework_status = "" - if !homework.nil? + if homework if homework.homework_type == 1 && homework.homework_detail_manual case homework.homework_detail_manual.comment_status when 1 diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 165e22071..41e016562 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -760,7 +760,8 @@ module ApplicationHelper options = args.extract_options! text = distance_of_time_in_words(Time.now, time) if @project - link_to(text, {:controller => 'activities', :action => 'index', :id => @project, :from => User.current.time_to_date(time)},options.reverse_merge(:title => format_time(time))) + content_tag('acronym', text, options.reverse_merge(:title => format_time(time))) + # link_to(text, {:controller => 'activities', :action => 'index', :id => @project, :from => User.current.time_to_date(time)},options.reverse_merge(:title => format_time(time))) else content_tag('acronym', text, options.reverse_merge(:title => format_time(time))) end @@ -1812,7 +1813,7 @@ module ApplicationHelper #获取用户未过期的课程 def get_user_course user courses_doing = [] - user.courses.each do |course| + user.courses.select("courses.*,(SELECT MAX(created_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS a").order("a desc").each do |course| if !course_endTime_timeout?(course) courses_doing.push course end @@ -1852,7 +1853,8 @@ module ApplicationHelper candown = true elsif attachment.container.class.to_s=="StudentWork" candown = true - + elsif attachment.container.class.to_s == "User" + candown = (attachment.is_public == 1 || attachment.is_public == true || attachment.author_id == User.current.id) elsif attachment.container_type == "Bid" && attachment.container && attachment.container.courses course = attachment.container.courses.first candown = User.current.member_of_course?(attachment.container.courses.first) || (course.is_public == 1 && attachment.is_public == 1) @@ -2253,6 +2255,21 @@ module ApplicationHelper technical_title end + def get_user_roll user + technical_title = "" + case user.user_extensions.identity.to_s + when "0" + technical_title = get_technical_title user + when "1" + technical_title = l(:label_account_identity_student) + when "2" + technical_title = l(:label_account_identity_enterprise) + when "3" + technical_title = l(:label_account_identity_developer) + end + technical_title + end + def ie8? request.env["HTTP_USER_AGENT"] =~ /MSIE 8.0/ @@ -2280,25 +2297,19 @@ module ApplicationHelper #获取匿评相关连接代码 def homework_anonymous_comment homework - if homework.homework_type == 1 && homework.homework_detail_manual #匿评作业 - if Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d") - link = "启动匿评".html_safe - elsif homework.student_works.count >= 2 #作业份数大于2 - case homework.homework_detail_manual.comment_status - when 1 - link = link_to '启动匿评', alert_anonymous_comment_homework_common_path(homework), id: "#{homework.id}_start_anonymous_comment", remote: true, disable_with: '加载中...',:class => 'fr mr10 work_edit' - when 2 - link = link_to '关闭匿评', alert_anonymous_comment_homework_common_path(homework), id: "#{homework.id}_stop_anonymous_comment", remote: true,:class => 'fr mr10 work_edit' - when 3 - link = "匿评结束".html_safe - end - else - link = "启动匿评".html_safe + if Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d") + link = link_to "启动匿评","javascript:void(0)", :class => "postOptionLink", :title => "作业截止日期之前不可以启动匿评" + elsif homework.student_works.count >= 2 && homework.homework_detail_manual#作业份数大于2 + case homework.homework_detail_manual.comment_status + when 1 + link = link_to '启动匿评', alert_anonymous_comment_homework_common_path(homework), id: "#{homework.id}_start_anonymous_comment", remote: true, disable_with: '加载中...',:class => 'postOptionLink' + when 2 + link = link_to '关闭匿评', alert_anonymous_comment_homework_common_path(homework), id: "#{homework.id}_stop_anonymous_comment", remote: true,:class => 'postOptionLink' + when 3 + # link = link_to "匿评结束","javascript:void(0)", :class => "postOptionLink", :title => "匿评结束" end - elsif homework.homework_type == 2 && homework.homework_detail_programing #编程作业作业 - link = "编程作业".html_safe else - link = "启动匿评".html_safe + link = link_to "启动匿评","javascript:void(0)", :class => "postOptionLink", :title => "学生提交作业数大于等于2时才可以启动匿评" end link end @@ -2306,20 +2317,58 @@ module ApplicationHelper def student_new_homework homework work = cur_user_works_for_homework homework if work.nil? - link_to l(:label_commit_homework), new_student_work_path(:homework => homework.id),:class => 'fr mr10 work_edit' + link_to "提交作品", new_student_work_path(:homework => homework.id),:class => 'fr mr10 work_edit' else if homework.homework_type == 1 && homework.homework_detail_manual && homework.homework_detail_manual.comment_status != 1 #匿评作业,且作业状态不是在开启匿评之前 - "#{l(:label_edit_homework)}".html_safe - elsif homework.homework_type == 2 #编程作业不能修改作品 - "作品已交".html_safe + link_to "作品已交", "javascript:void(0);", :class => 'fr mr10 pr_join_span c_white', :title => "开启匿评后不可修改作品" + elsif homework.homework_type == 2 #编程作业修改作品 + if homework.homework_detail_manual && homework.homework_detail_manual.comment_status != 1 + link_to "作品已交", "javascript:void(0);", :class => 'fr mr10 pr_join_span c_white', :title => "开启匿评后不可修改作品" + else + link_to "修改作品", new_student_work_path(:homework => homework.id),:class => 'fr mr10 work_edit' + end else - link_to l(:label_edit_homework), edit_student_work_path(work.id),:class => 'fr mr10 work_edit' + link_to "修改作品", edit_student_work_path(work.id),:class => 'fr mr10 work_edit' + end + end + end + #动态列表中,确定学生是该提交还是进列表 + def student_work_activity_submit_status(opt={}) + default_opt = {class: 'c_blue'}.merge(opt) + + is_teacher = User.current.user_extensions && User.current.user_extensions.identity == 0 && User.current.allowed_to?(:add_course, nil, :global => true) + + homework = default_opt[:homework] + work = cur_user_works_for_homework homework + if work.nil? && !is_teacher + link_to "提交("+homework.student_works.count.to_s+")", new_student_work_path(:homework => homework.id,:host=> Setting.host_course), :class=> default_opt[:class] + else + link_to "提交("+homework.student_works.count.to_s+")", student_work_index_path(:homework => homework.id,:host=> Setting.host_course), :class=> default_opt[:class] + end + end + + #根据传入作业确定显示为编辑作品还是新建作品,或者显示作品数量 + def user_for_homework_common homework,is_teacher + if is_teacher #老师显示作品数量 + link_to "提交(#{homework.student_works.count})",student_work_index_path(:homework => homework.id),:class => "c_blue" + else #学生显示提交作品、修改作品等按钮 + work = cur_user_works_for_homework homework + if work.nil? + link_to "提交作品", new_student_work_path(:homework => homework.id),:class => 'c_blue' + else + if homework.homework_detail_manual && homework.homework_detail_manual.comment_status != 1 #匿评作业,且作业状态不是在开启匿评之前 + link_to "作品已交", "javascript:void(0)", :class => 'c_blue', :title => "开启匿评后不可修改作品" + elsif homework.homework_type == 2 #编程作业不能修改作品 + link_to "修改作品", new_student_work_path(:homework => homework.id),:class => 'c_blue' + else + link_to "修改作品", edit_student_work_path(work.id),:class => 'c_blue' + end end end end def student_anonymous_comment homework - if homework.homework_type == 1 && homework.homework_detail_manual + if homework.homework_detail_manual case homework.homework_detail_manual.comment_status when 1 "未开启匿评".html_safe @@ -2328,10 +2377,6 @@ module ApplicationHelper when 3 "匿评已结束".html_safe end - elsif homework.homework_type == 0 - "未启用匿评".html_safe - elsif homework.homework_type == 2 - " 编程作业  ".html_safe end end @@ -2378,4 +2423,108 @@ module ApplicationHelper end notice.html_safe end + + #老师C语言的标准代码 + def c_stantard_code_teacher + "// 老师您好!这是一个C语言的样例程序 +// 程序功能:输入两个整数,输出两者之和 +// 测试集合:老师可以给出多组测试集,例如: +// 输入1和2,输出3 +// 输入3和4,输出7 +// ... ... +// 系统将根据您给出的测试集对学生代码进行自动评分 + +// 特别提醒:程序采用命令行传参方式,输入通过argv传入 +// 否则您的作业标准代码将不能通过测试 + +#include //引用必须头文件 +int main(int argc, char** argv) { + int a = atoi(argv[1]); //将第一个输入转成整型 + int b = atoi(argv[2]); //将第二个输入转换为整型 + + printf(\"%d\",a+b); //输出a+b + return 0; +}".html_safe + end + + #老师C++语言的标准代码 + def c_stantard_code_teacher_ + "// 老师您好!这是一个C++语言的样例程序 +// 程序功能:输入两个整数,输出两者之和 +// 测试集合:老师可以给出多组测试集,例如: +// 输入1和2,输出3 +// 输入3和4,输出7 +// ... ... +// 系统将根据您给出的测试集对学生代码进行自动评分 + +// 特别提醒:程序采用命令行传参方式,输入通过argv传入 +// 否则您的作业标准代码将不能通过测试 + +#include //引用必须头文件 +#include +using namespace std; +int main(int argc, char** argv){ + int a = atoi(argv[1]); //将第一个输入转成整型 + int b = atoi(argv[2]); //将第二个输入转换为整型 + cout< //引用必须头文件 +int main(int argc, char** argv) { + int a = atoi(argv[1]); //将第一个输入转成整型 + int b = atoi(argv[2]); //将第二个输入转换为整型 + + printf(\"%d\",a+b); //输出a+b + return 0; +}".html_safe + end + + #学生C++语言的标准代码 + def c_stantard_code_student_ + "// 同学好!这是一个C++语言的样例程序 +// 程序功能:输入两个整数,输出两者之和 +// 测试集合:老师可以给出多组测试集,例如: +// 输入1和2,输出3 +// 输入3和4,输出7 +// ... ... +// 系统将根据您给出的测试集对学生代码进行自动评分 + +// 特别提醒:程序采用命令行传参方式,输入通过argv传入 +// 否则您的作业标准代码将不能通过测试 + +#include //引用必须头文件 +#include +using namespace std; +int main(int argc, char** argv){ + int a = atoi(argv[1]); //将第一个输入转成整型 + int b = atoi(argv[2]); //将第二个输入转换为整型 + cout< activity.course_act.id) + when "News" + title = "通知公告 " + activity.course_act.title + url = course_news_index_path(activity.course) + when "Attachment" + title = "课件 " + activity.course_act.filename + url = course_files_path(activity.course) + when "Message" + title = "课程讨论区 " + activity.course_act.subject + url = course_boards_path(activity.course,:parent_id => activity.course_act.parent_id ? activity.course_act.parent_id : activity.course_act.id, :topic_id => activity.course_act.id) + when "JournalsForMessage" + title = "留言 " + activity.course_act.notes + url = course_feedback_path(activity.course) + when "Poll" + title = "问卷 " + activity.course_act.polls_name + url = poll_path(activity.course_act_id) + end + end + link_to title.gsub(/<(?!img)[^>]*>/,'').html_safe, url, :class => "problem_tit c_dblue fl fb" + end + + #课程动态的描述 + def course_activity_desc activity + desc = "" + if activity.course_act + case activity.course_act_type + when "Course" + desc = "" + when "HomeworkCommon" + desc = activity.course_act.description + when "News" + desc = activity.course_act.description + when "Attachment" + desc = "" + when "Message" + desc = activity.course_act.content + when "JournalsForMessage" + desc = "" + when "Poll" + desc = activity.course_act.polls_description + end + end + desc.html_safe + end end diff --git a/app/helpers/homework_common_helper.rb b/app/helpers/homework_common_helper.rb index 49384cca4..a03c4ccd7 100644 --- a/app/helpers/homework_common_helper.rb +++ b/app/helpers/homework_common_helper.rb @@ -1,4 +1,5 @@ # encoding: utf-8 +include UsersHelper module HomeworkCommonHelper #迟交扣分下拉框 def late_penalty_option @@ -66,4 +67,31 @@ module HomeworkCommonHelper link end + #将状态转换为错误信息 + def status_to_err_msg status + case status.to_i + when -1 + '编译出错' + when -2 + '输入和输出不匹配' + when -3 + '输入和输出不匹配' + when 1 + '运行出错' + when 2 + '超时' + when 3 + '内存超出' + when 4 + '输出超出' + when 5 + '禁用函数' + when 6 + '其他错误' + when 0 + '成功' + else + '未知错误' + end + end end \ No newline at end of file diff --git a/app/helpers/issues_helper.rb b/app/helpers/issues_helper.rb index a26d2661a..412c3f889 100644 --- a/app/helpers/issues_helper.rb +++ b/app/helpers/issues_helper.rb @@ -380,6 +380,22 @@ module IssuesHelper value = content_tag("i", h(value)) if value end end + # 缺陷更新结果在消息中显示样式 + if no_html == "message" + label = content_tag(:span, label, :class => "issue_update_message") + old_value = content_tag("span", h(old_value)) if detail.old_value + old_value = content_tag("del", old_value) if detail.old_value and detail.value.blank? + if detail.property == 'attachment' && !value.blank? && atta = Attachment.find_by_id(detail.prop_key) + # Link to the attachment if it has not been removed + if options[:token].nil? + value = atta.filename + else + value = atta.filename + end + else + value = content_tag(:span, h(value), :class => "issue_update_message_value") if value + end + end if detail.property == 'attr' && detail.prop_key == 'description' s = l(:text_journal_changed_no_detail, :label => label) diff --git a/app/helpers/journals_helper.rb b/app/helpers/journals_helper.rb index 0eee08b6b..3591a0168 100644 --- a/app/helpers/journals_helper.rb +++ b/app/helpers/journals_helper.rb @@ -116,10 +116,10 @@ module JournalsHelper end end #content << content_tag('div', links.join(' ').html_safe, :class => 'contextual', :style => 'margin-top:-25px;') unless links.empty? - content << textilizable(journal, :notes) + content << textAreailizable(journal, :notes) css_classes = "wiki" css_classes << " editable" if editable - content_tag('div', content.html_safe, :id => "journal-#{journal.id}-notes", :class => css_classes ,:style => "width:510px") + content_tag('div', content.html_safe, :id => "journal-#{journal.id}-notes", :class => css_classes) end def link_to_in_place_notes_editor(text, field_id, url, options={}) diff --git a/app/helpers/poll_helper.rb b/app/helpers/poll_helper.rb index 3156f1b3a..84e12f3b1 100644 --- a/app/helpers/poll_helper.rb +++ b/app/helpers/poll_helper.rb @@ -47,7 +47,7 @@ module PollHelper true end end - + #统计答题百分比,统计结果保留两位小数 def statistics_result_percentage(e, t) e = e.to_f @@ -74,4 +74,13 @@ module PollHelper end end + #带勾选框的问卷列表 + def poll_check_box_tags(name,polls,current_poll) + s = '' + polls.each do |poll| + s << "
" + end + s.html_safe + end + end \ No newline at end of file diff --git a/app/helpers/projects_helper.rb b/app/helpers/projects_helper.rb index 12925b0b1..41f25d1a3 100644 --- a/app/helpers/projects_helper.rb +++ b/app/helpers/projects_helper.rb @@ -18,6 +18,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. include AvatarHelper +include StudentWorkHelper module ProjectsHelper def link_to_version(version, options = {}) return '' unless version && version.is_a?(Version) @@ -75,6 +76,47 @@ module ProjectsHelper return result end + # 项目类型 + def project_type_select + type = [] + option1 = [] + option1 << l(:label_development_team) + option1 << l(:label_development_team) + option2 = [] + option2 << l(:label_research_group) + option2 << l(:label_research_group) + option3 = [] + option3 << l(:label_friend_organization) + option3 << l(:label_friend_organization) + type << option1 + type << option2 + type << option3 + type + end + + # 项目类型描述 + def project_newtype_descrption + case params + when 1 + value = l(:label_type_des_development) + when 2 + value = l(:label_type_des_research) + when 3 + value = l(:label_type_des_friend) + end + end + +# 被邀请成员的状态 + def status_for_ivitied(ivite_list, project) + if ivite_list.user.member_of?(project) + value = "已经加入了项目!" + elsif ivite_list.user.active? + value = "邀请已发送,等待用户加入!" + else + value = "邀请已发送,等待用户激活账号!" + end + end + # Added by young def course_settings_tabs tabs = [{:name => 'info', :action => :edit_project, :partial => 'projects/edit', :label => :label_information_plural, :course=>'1'}, diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index c77eba0c5..710b7488f 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -19,7 +19,7 @@ module RepositoriesHelper if Rails.env.development? - ROOT_PATH="/tmp/" if Rails.env.development? + ROOT_PATH="/private/tmp/" else ROOT_PATH="/home/pdl/redmine-2.3.2-0/apache2/" end diff --git a/app/helpers/student_work_helper.rb b/app/helpers/student_work_helper.rb index f24d5078f..e1cf3464e 100644 --- a/app/helpers/student_work_helper.rb +++ b/app/helpers/student_work_helper.rb @@ -1,16 +1,17 @@ # encoding: utf-8 +include UserScoreHelper + module StudentWorkHelper + #获取当前用户的项目列表 def user_projects_option - cond = Project.visible_condition(User.current) + " AND projects.project_type <> 1" - memberships = User.current.memberships.all(:conditions => cond) - projects = memberships.map(&:project) + projects = User.current.projects.visible not_have_project = [] - not_have_project << Setting.please_chose + not_have_project << "请选择关联项目" not_have_project << 0 type = [] type << not_have_project projects.each do |project| - if project != nil + if project option = [] option << project.name option << project.id @@ -98,4 +99,31 @@ module StudentWorkHelper end result end + + #教辅评分比例下拉框 + def ta_proportion_option + type = [] + i = 0 + while i <= 100 + option = [] + option << i.to_s + "%" + option << i.to_f / 100 + type << option + i += 10 + end + type + end + + def ta_proportion_option_to num + type = [] + i = 0 + while i <= num + option = [] + option << i.to_s + "%" + option << i.to_f / 100 + type << option + i += 10 + end + type + end end \ No newline at end of file diff --git a/app/helpers/system_messages_helper.rb b/app/helpers/system_messages_helper.rb new file mode 100644 index 000000000..fef238676 --- /dev/null +++ b/app/helpers/system_messages_helper.rb @@ -0,0 +1,2 @@ +module SystemMessagesHelper +end diff --git a/app/helpers/tags_helper.rb b/app/helpers/tags_helper.rb index 284ee8c43..2e8b98a2d 100644 --- a/app/helpers/tags_helper.rb +++ b/app/helpers/tags_helper.rb @@ -1,5 +1,6 @@ module TagsHelper include StoresHelper + include CoursesHelper # 通过 id和type获取对象 def get_object(obj_id,obj_type) @obj = nil @@ -62,6 +63,27 @@ module TagsHelper end +#判断课程course中是否包含课件attachment,course中引用了attachment也算作包含 +def course_contains_attachment? course,attachment + course.attachments.each do |att| + if att.id == attachment.id || (!att.copy_from.nil? && !attachment.copy_from.nil? && att.copy_from == attachment.copy_from) || att.copy_from == attachment.id || att.id == attachment.copy_from + return true + end + end + false +end + +#判断用户是否拥有不包含当前资源的课程,需用户在该课程中角色为教师且该课程属于当前学期或下一学期 +def has_course? user,file + result = false + user.courses.each do |course| + if !course_contains_attachment?(course,file) && is_course_teacher(User.current,course) && course_in_current_or_next_term(course) + return true + end + end + result +end + # 判断用户是否是贴吧的管理员 # add by chenmin def is_forum_manager?(user_id,forum_id) diff --git a/app/helpers/user_score_helper.rb b/app/helpers/user_score_helper.rb index 41f76a792..c82255d00 100644 --- a/app/helpers/user_score_helper.rb +++ b/app/helpers/user_score_helper.rb @@ -27,7 +27,7 @@ module UserScoreHelper issue_c = issue_c + Journal.where("user_id = ?", user.id).count ############################ memos = Memo.where('author_id = ? AND parent_id IS NOT NULL', user.id) - + memos.each do |m| if Memo.find(m.parent_id).author.id != user.id issue_c = issue_c + 1 @@ -35,18 +35,18 @@ module UserScoreHelper issue_c = issue_c - 1 end end - - + + pmemos = Memo.where('author_id = ? AND parent_id IS NULL', user.id) pmemos.each do |pm| issue_c = issue_c + pm.replies_count end ############################ - + issue_c = issue_c + JournalsForMessage.where('user_id = ? AND reply_id IS NOT NULL AND reply_id <> ?', user.id, user.id).count + JournalsForMessage.where('reply_id = ? AND user_id <> ?', user.id, user.id).count - - - + + + return issue_c end @@ -58,14 +58,14 @@ module UserScoreHelper def calculate_skill_count(user) - + praise_count_l0 = 0 praise_count_l1 = 0 praise_count_l2 = 0 tread_count_l0 = 0 tread_count_l1 = 0 tread_count_l2 = 0 - issues = Issue.where('author_id = ?', user.id) + issues = Issue.where('author_id = ?', user.id) issues.each do |i| pts = PraiseTread.where('praise_tread_object_id = ?', i.id) pts.each do |p| @@ -75,7 +75,7 @@ module UserScoreHelper if p.praise_or_tread == 1 praise_count_l0 = praise_count_l0 + 1 else - tread_count_l0 = tread_count_l0 + 1 + tread_count_l0 = tread_count_l0 + 1 end end if templevel.to_i == 1 @@ -97,7 +97,7 @@ module UserScoreHelper - + bids = Bid.where('author_id = ?', user.id) bids.each do |b| ptcs = PraiseTread.where('praise_tread_object_id = ?', b.id) @@ -108,7 +108,7 @@ module UserScoreHelper if p.praise_or_tread == 1 praise_count_l0 = praise_count_l0 + 1 else - tread_count_l0 = tread_count_l0 + 1 + tread_count_l0 = tread_count_l0 + 1 end end if templevel.to_i == 1 @@ -127,7 +127,7 @@ module UserScoreHelper end end end - + contests = Contest.where('author_id = ?', user.id) contests.each do |c| ptcs = PraiseTread.where('praise_tread_object_id = ?', c.id) @@ -138,7 +138,7 @@ module UserScoreHelper if p.praise_or_tread == 1 praise_count_l0 = praise_count_l0 + 1 else - tread_count_l0 = tread_count_l0 + 1 + tread_count_l0 = tread_count_l0 + 1 end end if templevel.to_i == 1 @@ -154,12 +154,12 @@ module UserScoreHelper else tread_count_l2 + tread_count_l2 + 1 end - end - end + end + end end - - - + + + # case level # when 0 skill_score = praise_count - 0.5 * tread_count # when 1 skill_score = 2 * praise_count - 1.5 * tread_count @@ -170,9 +170,9 @@ module UserScoreHelper skill_score = 2 * praise_count_l0.to_f + 3 * praise_count_l1.to_f + 4 * praise_count_l2.to_f - 1 * tread_count_l0.to_f - 1.5 * tread_count_l1.to_f - 2 * tread_count_l2.to_f - + tread_user_count = PraiseTread.where('praise_or_tread = ? AND user_id = ?', 0, user.id).count - + skill_score = skill_score.to_f - tread_user_count.to_f @@ -182,17 +182,17 @@ module UserScoreHelper return skill_score - - - + + + end - + def calculate_level(user) commit_count = user.changesets.count max_praise_num = 0 - - - issues = Issue.where('author_id = ?', user.id) + + + issues = Issue.where('author_id = ?', user.id) issues.each do |i| ptcs = PraiseTreadCache.where('object_id = ?', i.id) ptcs.each do |p| @@ -201,7 +201,7 @@ module UserScoreHelper end end end - + bids = Bid.where('author_id = ?', user.id) bids.each do |b| ptcs = PraiseTreadCache.where('object_id = ?', b.id) @@ -211,7 +211,7 @@ module UserScoreHelper end end end - + contests = Contest.where('author_id = ?', user.id) contests.each do |c| ptcs = PraiseTreadCache.where('object_id = ?', c.id) @@ -219,12 +219,12 @@ module UserScoreHelper if p.praise_num.to_i > max_praise_num.to_i max_praise_num = p.praise_num end - end + end end - - + + best_answer_num = 0 - + isManager = 0 members = Member.where('user_id = ?', user.id) members.each do |m| @@ -238,21 +238,21 @@ module UserScoreHelper end - + level = 0 - + if max_praise_num > 4 level = 1 end if commit_count > 0 and commit_count < 101 level = 1 - end + end if commit_count > 100 or isManager == 1 level = 2 end - + return level - + end def calculate_activity_count(user) @@ -282,23 +282,23 @@ module UserScoreHelper def calculate_issue(user) commit_count = user.changesets.count - + issue_details_count = 0 issues = Issue.where('assigned_to_id = ?', user.id) - + change_count = 0 issues.each do |issue| js = issue.journals js.each do |j| change_count = change_count + j.details.where("prop_key = ?", "done_ratio").count end - - + + issue_details_count = change_count + issue_details_count end - + return (commit_count + issue_details_count) - + end @@ -306,9 +306,9 @@ module UserScoreHelper attachments = Attachment.where("container_type IS NOT NULL AND container_type <> 'Issue' AND author_id = ?", user.id).count return attachments - + end - + def calculate_user_score(user) collaboration = calculate_collaboration_count(user) influence = calculate_influence_count(user) @@ -322,7 +322,7 @@ module UserScoreHelper UserScore.new(:collaboration => collaboration, :influence => influence, :skill => skill, :activity => activity, :file => file, :issue => issue, :level => level) end - + def update_user_score(user) collaboration = calculate_collaboration_count(user) influence = calculate_influence_count(user) @@ -331,7 +331,7 @@ module UserScoreHelper issue = calculate_issue(user) ##activity = calculate_activity_count(user) - + level = calculate_level(user) user.user_score.update_attributes(:collaboration => collaboration, :influence => influence, :skill => skill, :activity => activity, :file => file, :issue => issue, :level => level) @@ -423,7 +423,7 @@ module UserScoreHelper #更新分数 def update_score(option_number) - option_number.total_score = collaboration(option_number) + influence(option_number) + skill(option_number) + active(option_number) + option_number.total_score = collaboration(option_number) + influence(option_number) + skill(option_number) + project_active(option_number) if option_number.total_score < 0 option_number.total_score = 0 end @@ -433,7 +433,7 @@ module UserScoreHelper #协同得分 def collaboration(option_number) - option_number.messages_for_issues + option_number.issues_status + option_number.replay_for_message + option_number.replay_for_memo + option_number.memo * 2 + option_number.messages_for_issues + option_number.issues_status + option_number.replay_for_message + option_number.replay_for_memo end #影响力得分 def influence(option_number) @@ -444,8 +444,8 @@ module UserScoreHelper option_number.praise_by_one * 4 + option_number.praise_by_two * 6 + option_number.praise_by_three * 8 - option_number.tread * 2 - option_number.tread_by_one * 2 - option_number.tread_by_two * 4 - option_number.tread_by_three * 6 end #项目贡献得分 - def active(option_number) - option_number.changeset * 4 + option_number.document * 4 + option_number.attachment * 4 + option_number.issue_done_ratio * 2 + option_number.post_issue * 4 + option_number.memo * 2 + def project_active(option_number) + option_number.changeset * 4 + option_number.document * 4 + option_number.attachment * 4 + option_number.issue_done_ratio * 2 + option_number.post_issue * 4 end #更新发帖数 diff --git a/app/helpers/users_helper.rb b/app/helpers/users_helper.rb index 5553990e6..f6b083b4d 100644 --- a/app/helpers/users_helper.rb +++ b/app/helpers/users_helper.rb @@ -29,6 +29,63 @@ module UsersHelper ["#{l(:status_locked)} (#{user_count_by_status[3].to_i})", '3']], selected.to_s) end + def get_resource_type type + case type + when 'Course' + '课程资源' + when 'Project' + '项目资源' + when 'Issue' + '缺陷附件' + when 'Message' + '讨论区附件' + when 'Document' + '文档附件' + when 'News' + '通知附件' + when 'HomewCommon' + '作业附件' + when 'StudentWorkScore' + '批改附件' + when 'Principal' + '用户资源' + end + end + + def title_for_message type + case type + when nil + '消息' + when 'unviewed' + '未读消息' + when 'apply' + '用户申请' + when 'system_messages' + '系统消息' + when 'homework' + '作业消息' + when 'course_message' + '课程讨论' + when 'course_news' + '课程通知' + when 'issue' + '项目任务' + when 'forum' + '贴吧帖子' + when 'user_feedback' + '用户留言' + end + end + + # 统计未读消息数 + def unviewed_message(user) + course_count = CourseMessage.where("user_id =? and viewed =?", user, 0).count + forge_count = ForgeMessage.where("user_id =? and viewed =?", user, 0).count + user_feedback_count = UserFeedbackMessage.where("user_id =? and viewed =?", user, 0).count + user_memo_count = MemoMessage.where("user_id =? and viewed =?", user, 0).count + messages_count = course_count + forge_count + user_feedback_count + user_memo_count + end + def user_mail_notification_options(user) user.valid_notification_options.collect {|o| [l(o.last), o.first]} end @@ -48,7 +105,7 @@ module UsersHelper def user_settings_tabs tabs = [{:name => 'general', :partial => 'users/general', :label => :label_general}, {:name => 'memberships', :partial => 'users/memberships', :label => :label_project_plural} - ] + ] if Group.all.any? tabs.insert 1, {:name => 'groups', :partial => 'users/groups', :label => :label_group_plural} end @@ -60,7 +117,7 @@ module UsersHelper def get_users_by_tag(tag_name) User.tagged_with(tag_name).order('updated_on desc') end - + # added by fq # - + # TODO: 待删 # def show_activity(state) # content = ''.html_safe @@ -91,19 +148,19 @@ module UsersHelper # end # content_tag('div', content, :class => "pagination") # end - + #TODO: 待删 def watch_projects(state) content = ''.html_safe case state - when 0 - s = content_tag('span', l(:label_project_take), :class => "current-page") - content << content_tag('li', s) - content << content_tag('li', link_to(l(:label_has_watched_project), {:controller => 'users', :action => 'watch_projects', :type => 1})) - when 1 - s = content_tag('span', l(:label_has_watched_project), :class => "current-page") - content << content_tag('li', link_to(l(:label_project_take), {:controller => 'users', :action => 'user_projects'})) - content << content_tag('li', s, :class => "current-page") + when 0 + s = content_tag('span', l(:label_project_take), :class => "current-page") + content << content_tag('li', s) + content << content_tag('li', link_to(l(:label_has_watched_project), {:controller => 'users', :action => 'watch_projects', :type => 1})) + when 1 + s = content_tag('span', l(:label_has_watched_project), :class => "current-page") + content << content_tag('li', link_to(l(:label_project_take), {:controller => 'users', :action => 'user_projects'})) + content << content_tag('li', s, :class => "current-page") end content_tag('div', content, :class => "pagination") end @@ -111,59 +168,59 @@ module UsersHelper def user_course(state) content = ''.html_safe if @user != User.current - if @user.user_extensions.identity == 0 + if @user.user_extensions.identity == 0 case state - when 0 - s = content_tag('span', '他执教的课程', :class => "current-page") - content << content_tag('li', s) - content << content_tag('li', link_to('他发布的作业', {:controller => 'users', :action => 'user_courses', :type => 1})) - content_tag('div', content, :class => "pagination") - when 1 - s = content_tag('span', '他发布的作业', :class => "current-page") - content << content_tag('li', link_to('他执教的课程', {:controller => 'users', :action => 'user_courses'})) - content << content_tag('li', s, :class => "current-page") - content_tag('div', content, :class => "pagination") + when 0 + s = content_tag('span', '他执教的课程', :class => "current-page") + content << content_tag('li', s) + content << content_tag('li', link_to('他发布的作业', {:controller => 'users', :action => 'user_courses', :type => 1})) + content_tag('div', content, :class => "pagination") + when 1 + s = content_tag('span', '他发布的作业', :class => "current-page") + content << content_tag('li', link_to('他执教的课程', {:controller => 'users', :action => 'user_courses'})) + content << content_tag('li', s, :class => "current-page") + content_tag('div', content, :class => "pagination") end - else + else case state - when 0 - s = content_tag('span', '他的课程', :class => "current-page") - content << content_tag('li', s) - content << content_tag('li', link_to('他的作业', {:controller => 'users', :action => 'user_courses', :type => 1})) - content_tag('div', content, :class => "pagination") - when 1 - s = content_tag('span', '他的作业', :class => "current-page") - content << content_tag('li', link_to('他的课程', {:controller => 'users', :action => 'user_courses', :type => 0})) - content << content_tag('li', s, :class => "current-page") - content_tag('div', content, :class => "pagination") + when 0 + s = content_tag('span', '他的课程', :class => "current-page") + content << content_tag('li', s) + content << content_tag('li', link_to('他的作业', {:controller => 'users', :action => 'user_courses', :type => 1})) + content_tag('div', content, :class => "pagination") + when 1 + s = content_tag('span', '他的作业', :class => "current-page") + content << content_tag('li', link_to('他的课程', {:controller => 'users', :action => 'user_courses', :type => 0})) + content << content_tag('li', s, :class => "current-page") + content_tag('div', content, :class => "pagination") end end else - if @user.user_extensions.identity == 0 + if @user.user_extensions.identity == 0 case state - when 0 - s = content_tag('span', l(:label_teaching_course), :class => "current-page") - content << content_tag('li', s) - content << content_tag('li', link_to(l(:label_release_homework), {:controller => 'users', :action => 'user_courses', :type => 1})) - content_tag('div', content, :class => "pagination") - when 1 - s = content_tag('span', l(:label_release_homework), :class => "current-page") - content << content_tag('li', link_to(l(:label_teaching_course), {:controller => 'users', :action => 'user_courses'})) - content << content_tag('li', s, :class => "current-page") - content_tag('div', content, :class => "pagination") + when 0 + s = content_tag('span', l(:label_teaching_course), :class => "current-page") + content << content_tag('li', s) + content << content_tag('li', link_to(l(:label_release_homework), {:controller => 'users', :action => 'user_courses', :type => 1})) + content_tag('div', content, :class => "pagination") + when 1 + s = content_tag('span', l(:label_release_homework), :class => "current-page") + content << content_tag('li', link_to(l(:label_teaching_course), {:controller => 'users', :action => 'user_courses'})) + content << content_tag('li', s, :class => "current-page") + content_tag('div', content, :class => "pagination") end - else + else case state - when 0 - s = content_tag('span', l(:label_my_course), :class => "current-page") - content << content_tag('li', s) - content << content_tag('li', link_to('我的作业', {:controller => 'users', :action => 'user_courses', :type => 1})) - content_tag('div', content, :class => "pagination") - when 1 - s = content_tag('span', '我的作业', :class => "current-page") - content << content_tag('li', link_to(l(:label_my_course), {:controller => 'users', :action => 'user_courses', :type => 0})) - content << content_tag('li', s, :class => "current-page") - content_tag('div', content, :class => "pagination") + when 0 + s = content_tag('span', l(:label_my_course), :class => "current-page") + content << content_tag('li', s) + content << content_tag('li', link_to('我的作业', {:controller => 'users', :action => 'user_courses', :type => 1})) + content_tag('div', content, :class => "pagination") + when 1 + s = content_tag('span', '我的作业', :class => "current-page") + content << content_tag('li', link_to(l(:label_my_course), {:controller => 'users', :action => 'user_courses', :type => 0})) + content << content_tag('li', s, :class => "current-page") + content_tag('div', content, :class => "pagination") end end end @@ -173,42 +230,42 @@ module UsersHelper def sort_user(state, project_type) content = ''.html_safe case state - when 0 - content << content_tag('li', link_to(l(:label_sort_by_active), users_path(params.merge({:user_sort_type => '1', :project_type => project_type}) ))) - content << content_tag('li', link_to(l(:label_sort_by_influence), users_path(params.merge({:user_sort_type => '2', :project_type => project_type}) ))) - content << content_tag('li', link_to(l(:label_sort_by_time), users_path(params.merge({:user_sort_type => '0', :project_type => project_type}) ), :class=>"selected") ) - when 1 - content << content_tag('li', link_to(l(:label_sort_by_active), users_path(params.merge({:user_sort_type => '1', :project_type => project_type}) ), :class=>"selected") ) - content << content_tag('li', link_to(l(:label_sort_by_influence), users_path(params.merge({:user_sort_type => '2', :project_type => project_type}) ))) - content << content_tag('li', link_to(l(:label_sort_by_time), users_path(params.merge({:user_sort_type => '0', :project_type => project_type}) ))) - when 2 - content << content_tag('li', link_to(l(:label_sort_by_active), users_path(params.merge({:user_sort_type => '1', :project_type => project_type}) ))) - content << content_tag('li', link_to(l(:label_sort_by_influence), users_path(params.merge({:user_sort_type => '2', :project_type => project_type}) ), :class=>"selected") ) - content << content_tag('li', link_to(l(:label_sort_by_time), users_path(params.merge({:user_sort_type => '0', :project_type => project_type}) ))) + when 0 + content << content_tag('li', link_to(l(:label_sort_by_active), users_path(params.merge({:user_sort_type => '1', :project_type => project_type}) ))) + content << content_tag('li', link_to(l(:label_sort_by_influence), users_path(params.merge({:user_sort_type => '2', :project_type => project_type}) ))) + content << content_tag('li', link_to(l(:label_sort_by_time), users_path(params.merge({:user_sort_type => '0', :project_type => project_type}) ), :class=>"selected") ) + when 1 + content << content_tag('li', link_to(l(:label_sort_by_active), users_path(params.merge({:user_sort_type => '1', :project_type => project_type}) ), :class=>"selected") ) + content << content_tag('li', link_to(l(:label_sort_by_influence), users_path(params.merge({:user_sort_type => '2', :project_type => project_type}) ))) + content << content_tag('li', link_to(l(:label_sort_by_time), users_path(params.merge({:user_sort_type => '0', :project_type => project_type}) ))) + when 2 + content << content_tag('li', link_to(l(:label_sort_by_active), users_path(params.merge({:user_sort_type => '1', :project_type => project_type}) ))) + content << content_tag('li', link_to(l(:label_sort_by_influence), users_path(params.merge({:user_sort_type => '2', :project_type => project_type}) ), :class=>"selected") ) + content << content_tag('li', link_to(l(:label_sort_by_time), users_path(params.merge({:user_sort_type => '0', :project_type => project_type}) ))) end content = content_tag('ul', content) content_tag('div', content, :class => "tabs") - end - + end + def sort_user_enterprise(state, project_type) content = ''.html_safe case state - when 0 - content << content_tag('li', link_to(l(:label_sort_by_active), users_path(:user_sort_type => '1', :project_type => project_type))) - content << content_tag('li', link_to(l(:label_sort_by_influence), users_path(:user_sort_type => '2', :project_type => project_type))) - content << content_tag('li', link_to(l(:label_sort_by_time), users_path(:user_sort_type => '0', :project_type => project_type), :class=>"selected"), :class=>"selected") - when 1 - content << content_tag('li', link_to(l(:label_sort_by_active), users_path(:user_sort_type => '1', :project_type => project_type), :class=>"selected"), :class=>"selected") - content << content_tag('li', link_to(l(:label_sort_by_influence), users_path(:user_sort_type => '2', :project_type => project_type))) - content << content_tag('li', link_to(l(:label_sort_by_time), users_path(:user_sort_type => '0', :project_type => project_type))) - when 2 - content << content_tag('li', link_to(l(:label_sort_by_active), users_path(:user_sort_type => '1', :project_type => project_type))) - content << content_tag('li', link_to(l(:label_sort_by_influence), users_path(:user_sort_type => '2', :project_type => project_type), :class=>"selected"), :class=>"selected") - content << content_tag('li', link_to(l(:label_sort_by_time), users_path(:user_sort_type => '0', :project_type => project_type))) + when 0 + content << content_tag('li', link_to(l(:label_sort_by_active), users_path(:user_sort_type => '1', :project_type => project_type))) + content << content_tag('li', link_to(l(:label_sort_by_influence), users_path(:user_sort_type => '2', :project_type => project_type))) + content << content_tag('li', link_to(l(:label_sort_by_time), users_path(:user_sort_type => '0', :project_type => project_type), :class=>"selected"), :class=>"selected") + when 1 + content << content_tag('li', link_to(l(:label_sort_by_active), users_path(:user_sort_type => '1', :project_type => project_type), :class=>"selected"), :class=>"selected") + content << content_tag('li', link_to(l(:label_sort_by_influence), users_path(:user_sort_type => '2', :project_type => project_type))) + content << content_tag('li', link_to(l(:label_sort_by_time), users_path(:user_sort_type => '0', :project_type => project_type))) + when 2 + content << content_tag('li', link_to(l(:label_sort_by_active), users_path(:user_sort_type => '1', :project_type => project_type))) + content << content_tag('li', link_to(l(:label_sort_by_influence), users_path(:user_sort_type => '2', :project_type => project_type), :class=>"selected"), :class=>"selected") + content << content_tag('li', link_to(l(:label_sort_by_time), users_path(:user_sort_type => '0', :project_type => project_type))) end content = content_tag('ul', content) content_tag('div', content, :class => "tabs_enterprise") - end + end def gender_avatar_uri user img_uri = '/images/sidebar/female.png' @@ -233,7 +290,7 @@ module UsersHelper # people_ids += (members_to_user_ids(tmp)) unless tmp.nil? # end # people_ids.include?(login_user.id) or (login_user == user) or login_user.admin? - + false end @@ -267,7 +324,7 @@ module UsersHelper membership.collect { |e| memberships.push(e) } - ## 判断课程是否过期 [需封装] + ## 判断课程是否过期 [需封装] memberships_doing = [] memberships_done = [] memberships.map { |e| @@ -321,6 +378,7 @@ module UsersHelper list = obj.watcher_users.order("#{Watcher.table_name}.id desc").limit(10).all return [count,list]; end + def get_visitor_users(obj) query = Visitor.where("master_id=?",obj.id) count = query.count @@ -332,33 +390,45 @@ module UsersHelper end def get_create_course_count(user) - if user == User.current - user.courses.count - else - user.courses.where("is_public = 1").count - end + user.courses.visible.where("tea_id = ?",user.id).count end + + #获取加入课程数 def get_join_course_count(user) - user.coursememberships.count - get_create_course_count(user) + user.courses.visible.count - get_create_course_count(user) end + + #发布作业数 def get_homework_commons_count(user) HomeworkCommon.where("user_id = ?",user.id).count end + + #资源数 def get_projectandcourse_attachment_count(user) Attachment.where("author_id = ? and container_type in ('Project','Course')",user.id).count end + + #创建项目数 def get_create_project_count(user) - Project.where("user_id = ? and project_type = ?",user.id,Project::ProjectType_project).count + user.projects.visible.where("projects.user_id=#{user.id}").count end + + #加入项目数 def get_join_project_count(user) - user.memberships.count(conditions: "projects.project_type = #{Project::ProjectType_project}") - get_create_project_count(user) + user.projects.visible.count - get_create_project_count(user) end + + #创建缺陷数 def get_create_issue_count(user) Issue.where("author_id = ?",user.id).count end + + #解决缺陷数 def get_resolve_issue_count(user) Issue.where("assigned_to_id = ? and status_id=3",user.id).count end + + #参与匿评数 def get_anonymous_evaluation_count(user) StudentWorksScore.where("user_id = ? and reviewer_role=3",user.id).count end @@ -388,6 +458,19 @@ module UsersHelper end return str.html_safe end + + # journal.details 记录每个动作的新旧值 + def get_issue_des_update(journal) + no_html = "message" + arr = details_to_strings(journal.details, no_html) + unless journal.notes.blank? + arr << journal.notes + end + str = '' + arr.each { |item| str = str+item } + return str + end + def get_activity_act_showname(activity) case activity.act_type when "HomeworkCommon" @@ -418,6 +501,7 @@ module UsersHelper return activity.act_type end end + def get_activity_act_createtime(activity) case activity.act_type when "HomeworkCommon" @@ -428,6 +512,7 @@ module UsersHelper return activity.act.created_on end end + def get_activity_container_url e if !e.visible? return "javascript:;" @@ -438,6 +523,7 @@ module UsersHelper end return url_for(:controller => 'projects', :action=>"show", :id=>e.id, :host=>Setting.host_name) end + def get_activity_url(activity,e) if !e.visible? return "javascript:;" @@ -466,6 +552,7 @@ module UsersHelper return 'javascript:;' end end + def get_activity_opt(activity,e) case activity.act_type when "HomeworkCommon" @@ -488,4 +575,20 @@ module UsersHelper end end + #获取指定用户作为老师的课程 + def get_as_teacher_courses user + type = [] + option = [] + option << "请选择发布作业的课程" + option << -1 + type << option + user.courses.visible.select("courses.*,(SELECT MAX(created_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS a").order("a desc").select{|c| user.allowed_to?(:as_teacher,c)}.each do |course| + option = [] + option << course.name+"("+course.time.to_s+course.term+")" + option << course.id + type << option + end + type + end + end diff --git a/app/models/applied_project.rb b/app/models/applied_project.rb index accbc90e2..fb8bf90af 100644 --- a/app/models/applied_project.rb +++ b/app/models/applied_project.rb @@ -1,8 +1,21 @@ class AppliedProject < ActiveRecord::Base attr_accessible :project_id, :user_id - belongs_to :user - belongs_to :project + belongs_to :user + belongs_to :project + has_many :forge_messages, :class_name => 'ForgeMessage', :as => :forge_message, :dependent => :destroy + + after_create :send_appliled_message + + def send_appliled_message + # if MessageAll.where("message_type = '#{self.class.to_s}' and message_id = '#{self.id}'").first.nil? + self.project.members.each do |m| + if m.roles.first.to_s.include?("Manager") + self.forge_messages << ForgeMessage.new(:user_id => m.user_id, :project_id => self.project_id, :viewed => false) + end + end + # end + end #删除用户申请 def self.deleteappiled(userid, projectid) @@ -11,5 +24,4 @@ class AppliedProject < ActiveRecord::Base applied.destroy end end - end diff --git a/app/models/attachment.rb b/app/models/attachment.rb index f999e27d6..f7fb9b1aa 100644 --- a/app/models/attachment.rb +++ b/app/models/attachment.rb @@ -27,6 +27,8 @@ class Attachment < ActiveRecord::Base belongs_to :attachmentstype, :foreign_key => "attachtype",:primary_key => "id" # 被ForgeActivity虚拟关联 has_many :forge_acts, :class_name => 'ForgeActivity',:as =>:forge_act ,:dependent => :destroy + # 课程动态 + has_many :course_acts, :class_name => 'CourseActivity',:as =>:course_act ,:dependent => :destroy # end include UserScoreHelper @@ -71,8 +73,8 @@ class Attachment < ActiveRecord::Base cattr_accessor :thumbnails_storage_path @@thumbnails_storage_path = File.join(Rails.root, "tmp", "thumbnails") - before_save :files_to_final_location - after_create :office_conver, :be_user_score,:act_as_forge_activity# user_score + before_save :files_to_final_location,:act_as_course_activity + after_create :office_conver, :be_user_score,:act_as_forge_activity after_update :office_conver, :be_user_score after_destroy :delete_from_disk,:down_user_score @@ -552,4 +554,10 @@ class Attachment < ActiveRecord::Base end end + #课程动态公共表记录 + def act_as_course_activity + if self.container_type == "Course" && self.course_acts.empty? + self.course_acts << CourseActivity.new(:user_id => self.author_id,:course_id => self.container_id) + end + end end diff --git a/app/models/comment.rb b/app/models/comment.rb index a4842a23f..bb31eb894 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -21,6 +21,10 @@ class Comment < ActiveRecord::Base has_many_kindeditor_assets :assets, :dependent => :destroy has_many :ActivityNotifies,:as => :activity, :dependent => :destroy + # 课程/项目 消息 + has_many :course_messages, :class_name =>'CourseMessage', :as => :course_message, :dependent => :destroy + has_many :forge_messages, :class_name => 'ForgeMessage', :as => :forge_message, :dependent => :destroy + #end acts_as_event :datetime => :updated_on, :description => :comments, :type => 'news', @@ -31,7 +35,19 @@ class Comment < ActiveRecord::Base belongs_to :author, :class_name => 'User', :foreign_key => 'author_id' validates_presence_of :commented, :author, :comments safe_attributes 'comments' - after_create :send_mail + after_create :send_mail, :act_as_system_message + + def act_as_system_message + if self.commented.course + if self.author_id != self.commented.author_id + self.course_messages << CourseMessage.new(:user_id => self.commented.author_id, :course_id => self.commented.course.id, :viewed => false) + end + else # 项目相关 + if self.author_id != self.commented.author_id + self.forge_messages << ForgeMessage.new(:user_id => self.commented.author_id, :project_id => self.commented.project.id, :viewed => false) + end + end + end def send_mail if self.commented.is_a?(News) && Setting.notified_events.include?('news_comment_added') diff --git a/app/models/course.rb b/app/models/course.rb index 6d71ad967..501d958e4 100644 --- a/app/models/course.rb +++ b/app/models/course.rb @@ -33,6 +33,12 @@ class Course < ActiveRecord::Base has_many :student_works, :through => :homework_commons, :dependent => :destroy has_many :course_groups, :dependent => :destroy + # 课程动态 + has_many :course_acts, :class_name => 'CourseActivity',:as =>:course_act ,:dependent => :destroy + + has_many :course_activities + # 课程消息 + has_many :course_messages, :class_name =>'CourseMessage', :as => :course_message, :dependent => :destroy acts_as_taggable acts_as_nested_set :order => 'name', :dependent => :destroy @@ -44,7 +50,7 @@ class Course < ActiveRecord::Base validates_format_of :name,:with =>/^[^ ]+[a-zA-Z0-9_\u4e00-\u9fa5\s\S]+$/ validates_length_of :description, :maximum => 10000 before_save :self_validate - after_create :create_board_sync + after_create :create_board_sync, :act_as_course_activity before_destroy :delete_all_members safe_attributes 'extra', @@ -310,6 +316,11 @@ class Course < ActiveRecord::Base end end + #课程动态公共表记录 + def act_as_course_activity + self.course_acts << CourseActivity.new(:user_id => self.tea_id,:course_id => self.id) + end + #项目与课程分离后,很多课程的名称等信息为空,这些数据信息存储在项目表中!!就是数据兼容的问题 #def name # read_attribute('name') || Project.find_by_identifier(self.extra).try(:name) diff --git a/app/models/course_activity.rb b/app/models/course_activity.rb new file mode 100644 index 000000000..4e74142ad --- /dev/null +++ b/app/models/course_activity.rb @@ -0,0 +1,37 @@ +class CourseActivity < ActiveRecord::Base + attr_accessible :user_id, :course_act_id,:course_act_type,:course_id + # 虚拟关联 + belongs_to :course_act ,:polymorphic => true + belongs_to :course + belongs_to :user + has_many :user_acts, :class_name => 'UserAcivity',:as =>:act + after_save :add_user_activity + before_destroy :destroy_user_activity + + #在个人动态里面增加当前动态 + def add_user_activity + user_activity = UserActivity.where("act_type = '#{self.course_act_type.to_s}' and act_id = '#{self.course_act_id}'").first + if user_activity + user_activity.save + else + if self.course_act_type == 'Message' && !self.course_act.parent_id.nil? + user_activity = UserActivity.where("act_type = 'Message' and act_id = #{self.course_act.parent.id}").first + user_activity.created_at = self.created_at + user_activity.save + else + user_activity = UserActivity.new + user_activity.act_id = self.course_act_id + user_activity.act_type = self.course_act_type + user_activity.container_type = "Course" + user_activity.container_id = self.course_id + user_activity.user_id = self.user_id + user_activity.save + end + end + end + + def destroy_user_activity + user_activity = UserActivity.where("act_type = '#{self.course_act_type.to_s}' and act_id = '#{self.course_act_id}'") + user_activity.destroy_all + end +end diff --git a/app/models/course_message.rb b/app/models/course_message.rb new file mode 100644 index 000000000..65e91141c --- /dev/null +++ b/app/models/course_message.rb @@ -0,0 +1,25 @@ +class CourseMessage < ActiveRecord::Base + # status说明: status在课程不同的类型,区分不同的功能 + # HomeworkCommon:status: + # nil:发布了作业; 1:作业截止时间到了提醒!;2:开启匿评; 3:关闭匿评; 4:匿评开始失败 + attr_accessible :course_id, :course_message_id, :course_message_type, :user_id, :viewed, :content, :status + + # 多态 虚拟关联 + belongs_to :course_message ,:polymorphic => true + belongs_to :course + belongs_to :user + has_many :message_alls, :class_name => 'MessageAll',:as =>:message, :dependent => :destroy + + validates :user_id,presence: true + validates :course_id,presence: true + validates :course_message_id,presence: true + validates :course_message_type, presence: true + validates_length_of :content, :maximum => 100 + after_create :add_user_message + + def add_user_message + if MessageAll.where("message_type = '#{self.class.to_s}' and message_id = '#{self.id}'").first.nil? + self.message_alls << MessageAll.new(:user_id => self.user_id) + end + end +end diff --git a/app/models/forge_activity.rb b/app/models/forge_activity.rb index 6b75552c0..c4f13c6d0 100644 --- a/app/models/forge_activity.rb +++ b/app/models/forge_activity.rb @@ -19,5 +19,34 @@ class ForgeActivity < ActiveRecord::Base validates :project_id,presence: true validates :forge_act_id,presence: true validates :forge_act_type, presence: true + has_many :user_acts, :class_name => 'UserAcivity',:as =>:act + after_save :add_user_activity + before_destroy :destroy_user_activity + #在个人动态里面增加当前动态 + def add_user_activity + user_activity = UserActivity.where("act_type = '#{self.forge_act_type.to_s}' and act_id = '#{self.forge_act_id}'").first + if user_activity + user_activity.save + else + if self.forge_act_type == 'Message' && !self.forge_act.parent_id.nil? + user_activity = UserActivity.where("act_type = 'Message' and act_id = #{self.forge_act.parent.id}").first + user_activity.created_at = self.created_at + user_activity.save + else + user_activity = UserActivity.new + user_activity.act_id = self.forge_act_id + user_activity.act_type = self.forge_act_type + user_activity.container_type = "Project" + user_activity.container_id = self.project_id + user_activity.user_id = self.user_id + user_activity.save + end + end + end + + def destroy_user_activity + user_activity = UserActivity.where("act_type = '#{self.forge_act_type.to_s}' and act_id = '#{self.forge_act_id}'") + user_activity.destroy_all + end end diff --git a/app/models/forge_message.rb b/app/models/forge_message.rb new file mode 100644 index 000000000..8bf754719 --- /dev/null +++ b/app/models/forge_message.rb @@ -0,0 +1,22 @@ +class ForgeMessage < ActiveRecord::Base + # status在不同的类中,作用不同 + # Isseu: satus nil:发布了缺陷;:1:缺陷计划完成日志到了提醒 + attr_accessible :forge_message_id, :forge_message_type, :project_id, :user_id, :viewed, :secret_key, :status + + belongs_to :forge_message ,:polymorphic => true + belongs_to :project + belongs_to :user + has_many :message_alls, :class_name => 'MessageAll',:as =>:message, :dependent => :destroy + + validates :user_id,presence: true + validates :project_id,presence: true + validates :forge_message_id,presence: true + validates :forge_message_type, presence: true + after_create :add_user_message + + def add_user_message + if MessageAll.where("message_type = '#{self.class.to_s}' and message_id = '#{self.id}'").first.nil? + self.message_alls << MessageAll.new(:user_id => self.user_id) + end + end +end diff --git a/app/models/forum.rb b/app/models/forum.rb index 2af1abf9e..9fa1b7dfd 100644 --- a/app/models/forum.rb +++ b/app/models/forum.rb @@ -14,7 +14,7 @@ class Forum < ActiveRecord::Base 'sticky', 'locked' validates_presence_of :name, :creator_id, :description - validates_length_of :name, maximum: 50 + validates_length_of :name, maximum: 160 #validates_length_of :description, maximum: 255 validates :name, :uniqueness => true after_destroy :delete_kindeditor_assets @@ -39,6 +39,7 @@ class Forum < ActiveRecord::Base logger.debug "send mail for forum add." Mailer.run.forum_add(self) if Setting.notified_events.include?('forum_add') end + # Updates topic_count, memo_count and last_memo_id attributes for +board_id+ def self.reset_counters!(forum_id) forum_id = forum_id.to_i diff --git a/app/models/homework_common.rb b/app/models/homework_common.rb index 291c14563..796080645 100644 --- a/app/models/homework_common.rb +++ b/app/models/homework_common.rb @@ -10,20 +10,43 @@ class HomeworkCommon < ActiveRecord::Base has_one :homework_detail_manual, :dependent => :destroy has_one :homework_detail_programing, :dependent => :destroy has_many :homework_tests, :dependent => :destroy - has_many :student_works, :dependent => :destroy + has_many :student_works, :dependent => :destroy, :conditions => "is_test=0" has_many :student_works_evaluation_distributions, :through => :student_works #一个作业的分配的匿评列表 has_many :acts, :class_name => 'Activity', :as => :act, :dependent => :destroy #用户活动 + # 课程动态 + has_many :course_acts, :class_name => 'CourseActivity',:as =>:course_act ,:dependent => :destroy + # 课程消息 + has_many :course_messages, :class_name =>'CourseMessage', :as => :course_message, :dependent => :destroy acts_as_attachable acts_as_event :title => Proc.new {|o| "#{l(:label_course_homework)} ##{o.id}: #{o.name}" }, :description => :description, :author => :author, :url => Proc.new {|o| {:controller => 'student_work', :action => 'index', :homework => o.id}} - after_create :act_as_activity, :send_mail + after_create :act_as_activity, :send_mail, :act_as_course_activity, :act_as_course_message after_destroy :delete_kindeditor_assets def act_as_activity self.acts << Activity.new(:user_id => self.user_id) end + + #课程动态公共表记录 + def act_as_course_activity + if self.course + self.course_acts << CourseActivity.new(:user_id => self.user_id,:course_id => self.course_id) + end + end + + #课程作业消息记录 + def act_as_course_message + if self.course + self.course.members.each do |m| + # if m.user_id != self.user_id + self.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => self.course_id, :viewed => false) + # end + end + end + end + #删除对应的图片 def delete_kindeditor_assets delete_kindeditor_assets_from_disk self.id,OwnerTypeHelper::HOMEWORKCOMMON @@ -33,4 +56,10 @@ class HomeworkCommon < ActiveRecord::Base Mailer.run.homework_added(self) end + def is_program_homework? + self.homework_type == 2 && self.homework_detail_programing + end + + delegate :language_name, :language, :to => :homework_detail_programing + end diff --git a/app/models/homework_detail_programing.rb b/app/models/homework_detail_programing.rb index 4c7134806..0c445d672 100644 --- a/app/models/homework_detail_programing.rb +++ b/app/models/homework_detail_programing.rb @@ -2,4 +2,8 @@ class HomeworkDetailPrograming < ActiveRecord::Base attr_accessible :language, :standard_code, :homework_common_id belongs_to :homework_common + + def language_name + %W(C C++ Python Java).at(self.language.to_i - 1) + end end diff --git a/app/models/homework_test.rb b/app/models/homework_test.rb index 4ed290ecd..b4d8a4262 100644 --- a/app/models/homework_test.rb +++ b/app/models/homework_test.rb @@ -1,6 +1,5 @@ class HomeworkTest < ActiveRecord::Base - attr_accessible :input, :output, :homework_common_id + attr_accessible :input, :output, :homework_common_id,:result,:error_msg belongs_to :homework_common - has_many :student_work_test end diff --git a/app/models/invite_list.rb b/app/models/invite_list.rb index 4868fc3d7..66efc8609 100644 --- a/app/models/invite_list.rb +++ b/app/models/invite_list.rb @@ -1,5 +1,5 @@ class InviteList < ActiveRecord::Base - attr_accessible :project_id, :user_id + attr_accessible :project_id, :user_id, :mail belongs_to :user belongs_to :project diff --git a/app/models/issue.rb b/app/models/issue.rb index c2670a0cc..2a6da44c5 100644 --- a/app/models/issue.rb +++ b/app/models/issue.rb @@ -49,6 +49,8 @@ class Issue < ActiveRecord::Base has_many :forge_acts, :class_name => 'ForgeActivity',:as =>:forge_act ,:dependent => :destroy # end has_many :praise_tread, as: :praise_tread_object, dependent: :destroy + # ForgeMessage虚拟关联(多态) + has_many :forge_messages, :class_name => 'ForgeMessage',:as =>:forge_message ,:dependent => :destroy acts_as_nested_set :scope => 'root_id', :dependent => :destroy @@ -80,7 +82,7 @@ class Issue < ActiveRecord::Base attr_reader :current_journal # fq - after_create :act_as_activity,:be_user_score_new_issue,:act_as_forge_activity + after_create :act_as_activity,:be_user_score_new_issue,:act_as_forge_activity, :act_as_forge_message after_update :be_user_score after_destroy :down_user_score # after_create :be_user_score @@ -138,6 +140,28 @@ class Issue < ActiveRecord::Base :project_id => self.project_id) end # end + + # 发布缺陷forge_messages中添加记录 + def act_as_forge_message + # 指派给自己的缺陷不提示消息 + unless self.author_id == self.assigned_to_id + self.forge_messages << ForgeMessage.new(:user_id => self.assigned_to_id, :project_id => self.project_id, :viewed => false) + end + if self.tracker_id == 5 + self.project.members.each do |m| + if m.roles.first.to_s.include?("Manager") && m.user_id != self.author_id && m.user_id != self.assigned_to_id + self.forge_messages << ForgeMessage.new(:user_id => m.user_id, :project_id => self.project_id, :viewed => false) + end + end + end + end + + # 更新缺陷 + #def act_as_forge_message_update + # unless self.author_id == self.assigned_to_id + # self.forge_messages << ForgeMessage.new(:user_id => self.assigned_to_id, :project_id => self.project_id, :viewed => false) + # end + #end # Returns a SQL conditions string used to find all issues visible by the specified user @@ -235,9 +259,10 @@ class Issue < ActiveRecord::Base base_reload(*args) end - def to_param - @to_param ||= "#{id}_#{self.project.name}(#{self.project.issues.index(self).to_i+1}-#{self.project.issues.count})"#.parameterize - end + # 之所以注释是以为最终以id形式显示,另外如果项目名称带点号或者纯数字会出现问题 + # def to_param + # @to_param ||= "#{id}_#{self.project.name}(#{self.project.issues.index(self).to_i+1}-#{self.project.issues.count})"#.parameterize + # end # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields def available_custom_fields @@ -991,7 +1016,7 @@ class Issue < ActiveRecord::Base if leaf.start_date # Only move subtask if it starts at the same date as the parent # or if it starts before the given date - if start_date == leaf.start_date || date > leaf.start_date + if start_date == leaf.start_date || date > leaf.start_date leaf.reschedule_on!(date) end else @@ -1374,6 +1399,7 @@ class Issue < ActiveRecord::Base def attachment_added(obj) if @current_journal && @current_journal.user_id == obj.author_id && JournalDetail.find_all_by_value(obj.filename).count == 0 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename) + end end @@ -1382,6 +1408,9 @@ class Issue < ActiveRecord::Base if @current_journal && !obj.new_record? @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :old_value => obj.filename) @current_journal.save + user_activity = UserActivity.where("act_type='Issue' and act_id =#{@current_journal.journalized_id}").first + user_activity.updated_at = Time.now + user_activity.save end end @@ -1488,6 +1517,9 @@ class Issue < ActiveRecord::Base } end @current_journal.save + user_activity = UserActivity.where("act_type='Issue' and act_id =#{@current_journal.journalized_id}").first + user_activity.updated_at = Time.now + user_activity.save # reset current journal init_journal @current_journal.user, @current_journal.notes end diff --git a/app/models/journal.rb b/app/models/journal.rb index 3b660132e..9ffc5d405 100644 --- a/app/models/journal.rb +++ b/app/models/journal.rb @@ -29,6 +29,8 @@ class Journal < ActiveRecord::Base has_many :acts, :class_name => 'Activity', :as => :act, :dependent => :destroy # 被ForgeActivity虚拟关联 has_many :forge_acts, :class_name => 'ForgeActivity',:as =>:forge_act ,:dependent => :destroy + # 被ForgeMessage虚拟关联 + has_many :forge_messages, :class_name => 'ForgeMessage',:as =>:forge_message ,:dependent => :destroy # end attr_accessor :indice @@ -48,7 +50,7 @@ class Journal < ActiveRecord::Base before_create :split_private_notes # fq - after_save :act_as_activity,:be_user_score,:act_as_forge_activity + after_save :act_as_activity,:be_user_score,:act_as_forge_activity, :act_as_forge_message # end #after_destroy :down_user_score #before_save :be_user_score @@ -163,10 +165,25 @@ class Journal < ActiveRecord::Base # Description 公共表中需要保存一份该记录 def act_as_forge_activity self.forge_acts << ForgeActivity.new(:user_id => self.user_id, - :project_id => self.issue.project.id) + :project_id => self.issue.project.id) end + # 缺陷状态更改,消息提醒 + def act_as_forge_message + receivers = [] + # 直接回复 + if self.user_id != self.issue.author_id + receivers << self.issue.author_id + end + if self.user_id != self.issue.assigned_to_id && self.issue.assigned_to_id != self.issue.author_id # 指派人不是自己的话,则给指派人发送 + receivers << self.issue.assigned_to_id + end + receivers.each do |r| + self.forge_messages << ForgeMessage.new(:user_id => r, :project_id => self.issue.project_id, :viewed => false) + end + end + # 更新用户分数 -by zjc def be_user_score #新建了缺陷留言且留言不为空,不为空白 diff --git a/app/models/journal_reply.rb b/app/models/journal_reply.rb index 814231776..16055608a 100644 --- a/app/models/journal_reply.rb +++ b/app/models/journal_reply.rb @@ -5,8 +5,34 @@ class JournalReply < ActiveRecord::Base belongs_to :user belongs_to :journal + after_create :send_journal_messages def self.add_reply(journal_id, reply_id, user_id) self.create(:journal_id => journal_id, :reply_id => reply_id, :user_id => user_id) end + + def send_journal_messages + journal = self.journal + replier = User.find(self.reply_id) + receivers = [] + # 被回复的人发送消息 + if journal.user_id != self.reply_id && self.reply_id != journal.issue.author_id && self.reply_id != journal.issue.assigned_to_id + receivers << replier + end + if journal.user_id != journal.issue.author_id && self.reply_id != journal.issue.author_id + receivers << self.journal.issue.author + end + # journal_forge_messages = ForgeMessage.new + receivers.each do |r| + journal.forge_messages << ForgeMessage.new(:user_id =>r.id, :project_id => journal.issue.project_id, :viewed => false) + end + + # if self.user_id != self.journal_reply.user_id + # receivers << self.journal_reply.user_id + # end + # # 给缺陷发布者发送 + # if self.user_id != self.issue.author_id && self.journal_reply.user_id != self.issue.author_id + # receivers << self.issue.author_id + # end + end end diff --git a/app/models/journals_for_message.rb b/app/models/journals_for_message.rb index b15c9b2d1..dde34abfd 100644 --- a/app/models/journals_for_message.rb +++ b/app/models/journals_for_message.rb @@ -56,9 +56,14 @@ class JournalsForMessage < ActiveRecord::Base acts_as_attachable has_many :acts, :class_name => 'Activity', :as => :act, :dependent => :destroy + # 课程动态 + has_many :course_acts, :class_name => 'CourseActivity',:as =>:course_act ,:dependent => :destroy + # 消息关联 + has_many :course_messages, :class_name => 'CourseMessage',:as =>:course_message ,:dependent => :destroy + has_many :user_feedback_messages, :class_name => 'UserFeedbackMessage', :as =>:journals_for_message, :dependent => :destroy validates :notes, presence: true, if: :is_homework_jour? - after_create :act_as_activity #huang + after_create :act_as_activity, :act_as_course_activity, :act_as_course_message, :act_as_user_feedback_message after_create :reset_counters! after_destroy :reset_counters! after_save :be_user_score @@ -177,4 +182,77 @@ class JournalsForMessage < ActiveRecord::Base def delete_kindeditor_assets delete_kindeditor_assets_from_disk self.id,7 end + + #课程动态公共表记录 + def act_as_course_activity + if self.jour_type == 'Course' && self.m_parent_id.nil? + self.course_acts << CourseActivity.new(:user_id => self.user_id,:course_id => self.jour_id) + end + end + + # 课程/作品回复 留言消息通知 + def act_as_course_message + if self.jour_type == 'StudentWorksScore' + if self.user_id != self.jour.user_id + self.course_messages << CourseMessage.new(:user_id => self.jour.user_id,:course_id => self.jour.student_work.homework_common.course.id, :viewed => false) + end + end + # 课程留言 + if self.jour_type == 'Course' + receivers = [] + teachers = [] + # 获取课程的老师 + self.jour.members.each do |m| + if m.user.allowed_to?(:as_teacher, self.jour) + teachers << m + end + end + if self.reply_id == 0 # 主留言,即不是回复某条留言 + teachers.each do |teacher| + if teacher.user_id != self.user_id + receivers << teacher.user_id + end + end + else # 留言回复 + reply_to = User.find(self.reply_id) + if self.user_id != self.reply_id # 添加我回复的那个人 + receivers << reply_to.id + end + # 给老师发送。 过滤条件:老师自己给自己发;回复对象为老师则排除改老师 + teachers.each do |teacher| + if teacher.user_id != self.user_id && self.reply_id != teacher.user_id + receivers << teacher.user_id + end + end + end + receivers.each do |r| + self.course_messages << CourseMessage.new(:user_id => r, :course_id => self.jour.id, :viewed => false) + end + end + end + + # 用户留言消息通知 + def act_as_user_feedback_message + # 主留言 + if self.jour_type == 'Principal' + receivers = [] + if self.reply_id == 0 + if self.user_id != self.jour_id # 过滤自己给自己的留言消息 + receivers << self.jour + end + else # 留言回复 + reply_to = User.find(self.reply_id) + if self.user_id != self.reply_id # 添加我回复的那个人 + receivers << reply_to + end + if self.user_id != self.parent.jour_id && self.reply_id != self.parent.jour_id # 给东家发信息,如果回复的对象是东家则不发 + receivers << self.parent.jour + end + end + receivers.each do |r| + self.user_feedback_messages << UserFeedbackMessage.new(:user_id => r.id, :journals_for_message_id => self.id, :journals_for_message_type => "Principal", :viewed => false) + end + + end + end end diff --git a/app/models/mailer.rb b/app/models/mailer.rb index a25aff6bb..d797f1ce1 100644 --- a/app/models/mailer.rb +++ b/app/models/mailer.rb @@ -34,8 +34,10 @@ class Mailer < ActionMailer::Base end def method_missing(name, *args, &block) if Setting.delayjob_enabled? && Object.const_defined?('Delayed') + # with delayed_job @target.delay.send(name, *args, &block) else + # without delayed_job @target.send(name, *args, &block).deliver end end @@ -45,10 +47,67 @@ class Mailer < ActionMailer::Base MailerProxy.new(self) end + # 作业匿评开启 + def send_mail_anonymous_comment_open(homework_common) + course = homework_common.course + recipients ||= [] + course.members.each do |member| + user = User.find(member.user_id) + @subject = "#{l(:mail_homework)}#{homework_common.name} #{l(:mail_anonymous_comment_open)}" + @token = Token.get_token_from_user(user, 'autologin') + @anonymous_comment_close_url = url_for(student_work_index_url(:homework => homework_common.id, :token => @token.value)) + @anonymous_comment_close_name = homework_common.name + @author = homework_common.user + #收件人邮箱 + recipients << user.mail + end + mail :to => recipients, + :subject => @subject + end + + # 作业匿评关闭 + def send_mail_anonymous_comment_close(homework_common) + course = homework_common.course + recipients ||= [] + course.members.each do |member| + user = User.find(member.user_id) + @subject = "#{l(:mail_homework)}#{homework_common.name} #{l(:mail_anonymous_comment_close)}" + @token = Token.get_token_from_user(user, 'autologin') + @anonymous_comment_close_url = url_for(student_work_index_url(:homework => homework_common.id, :token => @token.value)) + @anonymous_comment_close_name = homework_common.name + @author = homework_common.user + #收件人邮箱 + recipients << user.mail + end + mail :to => recipients, + :subject => @subject + end + + # 匿评失败给老师发送邮件通知 + def send_mail_anonymous_comment_fail(homework_common) + course = homework_common.course + recipients ||= [] + # 只给该课程的老师发送邮件提醒 + course.members.each do |member| + if member.user.allowed_to?(:as_teacher,course) + user = User.find(member.user_id) + @subject = "[#{l(:mail_homework)} #{homework_common.name}] #{l(:mail_anonymous_comment_failed)}" + @token = Token.get_token_from_user(user, 'autologin') + @anonymous_comment_fail_url = url_for(student_work_index_url(:homework => homework_common.id, :token => @token.value)) + @anonymous_comment_fail_name = homework_common.name + @author = homework_common.user + #收件人邮箱 + recipients << user.mail + end + end + mail :to => recipients, + :subject => @subject + end + # author: alan - # 发送邀请未注册用户加入项目邮件 + # 邀请未注册用户加入项目 # 功能: 在加入项目的同时自动注册用户 - def send_invite_in_project(email, project, invitor) + def send_invite_in_project(email, project, invitor, first_name, last_name, gender) @email = email @subject = "#{invitor.name} #{l(:label_invite_project)} #{project.name} " @password = newpass(6) @@ -57,8 +116,8 @@ class Mailer < ActionMailer::Base login = login.sub(/%40/,'@') us = UsersService.new # 自动激活用户 - user = us.register_auto(login, @email, @password) - InviteList.create(:user_id => user.id, :project_id => project.id) + user = us.register_auto(login, email, @password, first_name, last_name, gender) + InviteList.create(:user_id => user.id, :project_id => project.id, :mail =>email) User.current = user unless User.current.nil? @user = user @token = Token.get_token_from_user(user, 'autologin') @@ -74,15 +133,23 @@ class Mailer < ActionMailer::Base @project_name = "#{project.name}" @user = user @project = project - inviter_lists = InviteList.where(project_id:@project.id, user_id:@user.id).all - if inviter_lists.blank? - InviteList.create(:user_id => user.id, :project_id => project.id) + if InviteList.where("project_id= ? and user_id =? and mail =?", project.id, @user.id, email).first.nil? + InviteList.create(:user_id => user.id, :project_id => project.id, :mail => email) end @token = Token.get_token_from_user(user, 'autologin') @project_url = url_for(:controller => 'projects', :action => 'member', :id => project.id, :user_id => user.id, :mail => true, :token => @token.value) + # 发送消息邀请 + send_message_request_member(user,project) + # end mail :to => email, :subject => @subject end + # 邀请信息消息 注:forge_message_id 为邀请人ID(特殊情况) + def send_message_request_member(user, project) + key = newpass(6).to_s + ForgeMessage.create(:user_id => user.id, :project_id => project.id, :forge_message_type => "ProjectInvite",:forge_message_id => User.current.id, :viewed => false, :secret_key =>key) + end + # author: alan # 根据用户选择发送个人日报或周报 # 发送内容: 项目【缺陷,讨论区,新闻】,课程【通知,留言,新闻】, 贴吧, 个人留言 @@ -201,11 +268,26 @@ class Mailer < ActionMailer::Base has_content = [@issues,@issues_journals,@course_messages,@project_messages,@course_news,@course_news_comments,@project_news,@project_news_comments,@project_attachments, @course_journal_messages,@user_journal_messages,@project_journal_messages,@forums,@memos,@attachments,@bids,@wiki_contents].any? {|o| !o.empty?} + mylogger.debug "Sent activity mail : #{user.mail} - #{has_content}" #有内容才发,没有不发 mail :to => user.mail,:subject => subject if has_content end + # 作业截止时间邮件提醒 + def homework_endtime__added(homework_common, user_id) + user = User.find(user_id) + @subject = "#{l(:mail_homework)}#{homework_common.name} #{l(:mail_homework_endtime)} " + @token = Token.get_token_from_user(user, 'autologin') + @homework_endtime_url = url_for(student_work_index_url(:homework => homework_common.id, :token => @token.value)) + @homework_endtime_name = homework_common.name + @author = homework_common.user + #收件人邮箱 + recipient = user.mail + mail :to => recipient, + :subject => @subject + end + # 公共讨论区发帖、回帖添加邮件发送信息 def forum_message_added(memo) @memo = memo diff --git a/app/models/member.rb b/app/models/member.rb index c2bf4e7d5..ed7ee81e6 100644 --- a/app/models/member.rb +++ b/app/models/member.rb @@ -30,6 +30,9 @@ class Member < ActiveRecord::Base validate :validate_role before_destroy :set_issue_category_nil + # 删除项目成员一并删除该成员的邀请记录 + after_destroy :delete_ivite_list + def role @@ -98,6 +101,16 @@ class Member < ActiveRecord::Base end end + # 删除成员一并删除该成员的邀请信息 + def delete_ivite_list + member_invite_lists = InviteList.where("user_id =? and project_id =?", self.user_id, self.project_id) + unless member_invite_lists.nil? + member_invite_lists.each do |member_invite_list| + member_invite_list.destroy + end + end + end + # Find or initilize a Member with an id, attributes, and for a Principal def self.edit_membership(id, new_attributes, principal=nil) @membership = id.present? ? Member.find(id) : Member.new(:principal => principal) diff --git a/app/models/memo.rb b/app/models/memo.rb index e0abaa19f..33b24db50 100644 --- a/app/models/memo.rb +++ b/app/models/memo.rb @@ -16,6 +16,9 @@ class Memo < ActiveRecord::Base acts_as_attachable has_many :user_score_details, :class_name => 'UserScoreDetails',:as => :score_changeable_obj has_many :praise_tread, as: :praise_tread_object, dependent: :destroy + # 消息 + has_many :memo_messages, :class_name =>'MemoMessage', :dependent => :destroy + # end belongs_to :last_reply, :class_name => 'Memo', :foreign_key => 'last_reply_id' # acts_as_searchable :column => ['subject', 'content'], # #:include => { :forum => :p} @@ -44,7 +47,7 @@ class Memo < ActiveRecord::Base "parent_id", "replies_count" - after_create :add_author_as_watcher, :reset_counters!, :send_mail + after_create :add_author_as_watcher, :reset_counters!, :send_mail, :send_message # after_update :update_memos_forum after_destroy :reset_counters!,:delete_kindeditor_assets#,:down_user_score -- 公共区发帖暂不计入得分 # after_create :send_notification @@ -59,6 +62,32 @@ class Memo < ActiveRecord::Base Mailer.run.forum_message_added(self) if Setting.notified_events.include?('forum_message_added') end + # 公共贴吧消息记录 + # 原则:贴吧创始人;发帖人,wanglingchun(特殊用户) + def send_message + receivers = [] + u = User.find(6) + receivers << u + # 主贴 + if self.parent_id.nil? + if self.author_id != self.forum.creator_id # 发帖人不是吧主 + receivers << self.forum.creator + end + else # 回帖 + # 添加吧主 + if self.author_id != self.forum.creator_id + receivers << self.forum.creator + end + # 添加发帖人 + if self.author_id != self.parent.author_id && self.parent.author_id != self.forum.creator_id + receivers << self.parent.author + end + end + receivers.each do |r| + self.memo_messages << MemoMessage.new(:user_id => r.id, :forum_id => self.forum_id, :memo_id => self.id, :memo_type => "Memo", :viewed => false) + end + end + def cannot_reply_to_locked_topic errors.add :base, l(:label_memo_locked) if root.locked? && self != root end diff --git a/app/models/memo_message.rb b/app/models/memo_message.rb new file mode 100644 index 000000000..ce3896389 --- /dev/null +++ b/app/models/memo_message.rb @@ -0,0 +1,19 @@ +class MemoMessage < ActiveRecord::Base + attr_accessible :forum_id, :memo_id, :memo_type, :user_id, :viewed + + belongs_to :memo + belongs_to :user + has_many :message_alls, :class_name => 'MessageAll',:as =>:message, :dependent => :destroy + + validates :user_id,presence: true + validates :forum_id,presence: true + validates :memo_id,presence: true + validates :memo_type, presence: true + after_create :add_user_message + + def add_user_message + if MessageAll.where("message_type = '#{self.class.to_s}' and message_id = '#{self.id}'").first.nil? + self.message_alls << MessageAll.new(:user_id => self.user_id) + end + end +end diff --git a/app/models/message.rb b/app/models/message.rb index 15d358789..7af59815b 100644 --- a/app/models/message.rb +++ b/app/models/message.rb @@ -32,7 +32,13 @@ class Message < ActiveRecord::Base has_many :acts, :class_name => 'Activity', :as => :act, :dependent => :destroy # 被ForgeActivity虚拟关联 has_many :forge_acts, :class_name => 'ForgeActivity',:as =>:forge_act ,:dependent => :destroy + # 课程动态 + has_many :course_acts, :class_name => 'CourseActivity',:as =>:course_act ,:dependent => :destroy # end + # 课程/项目 消息 + has_many :course_messages, :class_name =>'CourseMessage', :as => :course_message, :dependent => :destroy + has_many :forge_messages, :class_name => 'ForgeMessage', :as => :forge_message, :dependent => :destroy + #end has_many :ActivityNotifies,:as => :activity, :dependent => :destroy @@ -68,7 +74,7 @@ class Message < ActiveRecord::Base after_update :update_messages_board after_destroy :reset_counters!,:down_user_score,:delete_kindeditor_assets - after_create :act_as_activity,:be_user_score,:act_as_forge_activity, :send_mail + after_create :act_as_activity,:act_as_course_activity,:be_user_score,:act_as_forge_activity, :act_as_system_message, :send_mail #before_save :be_user_score scope :visible, lambda {|*args| @@ -80,7 +86,7 @@ class Message < ActiveRecord::Base } - safe_attributes 'subject', 'content' + safe_attributes 'subject', 'content', 'reply_id' safe_attributes 'board_id','locked', 'sticky', :if => lambda {|message, user| if message.project @@ -185,11 +191,56 @@ class Message < ActiveRecord::Base :project_id => self.board.project.id) end end + + #课程动态公共表记录 + def act_as_course_activity + if self.course && self.parent_id.nil? + self.course_acts << CourseActivity.new(:user_id => self.author_id,:course_id => self.board.course_id) + end + end + + # 课程讨论区添加消息: + # 老师发帖所有人都能收到消息 + # 学生发帖,有人回复则给该学生消息,没回复则不给其它人发送消息 + # 帖子被回复的可以收到消息通知 + # 项目讨论区添加消息: + # 主贴项目成员都能收到 + # 回帖:帖子的发布人收到 + def act_as_system_message + if self.course + if self.parent_id.nil? # 主贴 + self.course.members.each do |m| + if self.author.allowed_to?(:as_teacher, self.course) && m.user_id != self.author_id # 老师 自己的帖子不给自己发送消息 + self.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => self.board.course_id, :viewed => false) + end + end + else # 回帖 + self.course.members.each do |m| + if m.user_id == Message.find(self.parent_id).author_id && m.user_id != self.author_id # 只针对主贴回复,回复自己的帖子不发消息 + self.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => self.board.course_id, :viewed => false) + end + end + end + else # 项目相关 + if self.parent_id.nil? # 主贴 + self.project.members.each do |m| + if m.user_id != self.author_id + self.forge_messages << ForgeMessage.new(:user_id => m.user_id, :project_id => self.board.project_id, :viewed => false) + end + end + else # 回帖 + self.project.members.each do |m| + if m.user_id == Message.find(self.parent_id).author_id && m.user_id != self.author_id # 只针对主贴回复,回复自己的帖子不发消息 + self.forge_messages << ForgeMessage.new(:user_id => m.user_id, :project_id => self.board.project_id, :viewed => false) + end + end + end + end + end #更新用户分数 -by zjc def be_user_score #新建message且无parent的为发帖 - if self.parent_id.nil? && !self.board.project.nil? UserScore.joint(:post_message, self.author,nil,self, { message_id: self.id }) update_memo_number(self.author,1) diff --git a/app/models/message_all.rb b/app/models/message_all.rb new file mode 100644 index 000000000..6e0276875 --- /dev/null +++ b/app/models/message_all.rb @@ -0,0 +1,5 @@ +class MessageAll < ActiveRecord::Base + attr_accessible :message_id, :message_type, :user_id + # 虚拟关联---项目消息表/课程消息表/用户留言消息表/贴吧消息表 + belongs_to :message ,:polymorphic => true +end diff --git a/app/models/news.rb b/app/models/news.rb index 7d33d760e..a9e9d1d18 100644 --- a/app/models/news.rb +++ b/app/models/news.rb @@ -23,12 +23,18 @@ class News < ActiveRecord::Base #added by nwb belongs_to :course belongs_to :author, :class_name => 'User', :foreign_key => 'author_id' - has_many :comments, :as => :commented, :dependent => :delete_all, :order => "created_on" + has_many :comments, :as => :commented, :dependent => :destroy, :order => "created_on" # fq has_many :acts, :class_name => 'Activity', :as => :act, :dependent => :destroy # 被ForgeActivity虚拟关联 has_many :forge_acts, :class_name => 'ForgeActivity',:as =>:forge_act ,:dependent => :destroy + # 课程动态 + has_many :course_acts, :class_name => 'CourseActivity',:as =>:course_act ,:dependent => :destroy # end + # 课程/项目消息关联 + has_many :course_messages, :class_name =>'CourseMessage', :as => :course_message, :dependent => :destroy + has_many :forge_messages, :class_name => 'ForgeMessage', :as => :forge_message, :dependent => :destroy + #end has_many :ActivityNotifies,:as => :activity, :dependent => :destroy @@ -49,7 +55,7 @@ class News < ActiveRecord::Base :author_key => :author_id acts_as_watchable - after_create :act_as_activity,:act_as_forge_activity,:add_author_as_watcher, :send_mail + after_create :act_as_activity,:act_as_forge_activity, :act_as_course_activity,:act_as_system_message, :add_author_as_watcher, :send_mail after_destroy :delete_kindeditor_assets @@ -115,12 +121,39 @@ class News < ActiveRecord::Base # Description 公用表中也要记录 def act_as_forge_activity # 如果是project为空,那么是课程相关的,不需要保存 - if !self.project.nil? + if self.project self.forge_acts << ForgeActivity.new(:user_id => self.author_id, :project_id => self.project.id) end end + #课程动态公共表记录 + def act_as_course_activity + if self.course + self.course_acts << CourseActivity.new(:user_id => self.author_id,:course_id => self.course_id) + end + end + + #课程/项目通知 消息发送 + #消息发送原则:除了消息的发布者,课程的其它成员都能收到消息提醒 + def act_as_system_message + if self.course + self.course.members.each do |m| + if m.user_id != self.author_id + self.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => self.course_id, :viewed => false) + end + end + else + if !self.project.nil? + self.project.members.each do |m| + if m.user_id != self.author_id + self.forge_messages << ForgeMessage.new(:user_id => m.user_id, :project_id => self.project_id, :viewed => false) + end + end + end + end + end + # Time 2015-03-31 13:50:54 # Author lizanle # Description 删除news后删除对应的资源 @@ -132,4 +165,4 @@ class News < ActiveRecord::Base Mailer.run.news_added(self) if Setting.notified_events.include?('news_added') end -end +end \ No newline at end of file diff --git a/app/models/onclick_time.rb b/app/models/onclick_time.rb new file mode 100644 index 000000000..c62a9274c --- /dev/null +++ b/app/models/onclick_time.rb @@ -0,0 +1,5 @@ +class OnclickTime < ActiveRecord::Base + attr_accessible :onclick_time, :user_id + + belongs_to :user +end diff --git a/app/models/poll.rb b/app/models/poll.rb index 64e9df79a..67bb9f5a8 100644 --- a/app/models/poll.rb +++ b/app/models/poll.rb @@ -8,7 +8,12 @@ class Poll < ActiveRecord::Base has_many :users, :through => :poll_users #该文件被哪些用户提交答案过 # 添加课程的poll动态 has_many :acts, :class_name => 'Activity', :as => :act, :dependent => :destroy - after_create :act_as_activity + # 课程动态 + has_many :course_acts, :class_name => 'CourseActivity',:as =>:course_act ,:dependent => :destroy + after_create :act_as_activity, :act_as_course_activity + # 课程消息 + has_many :course_messages, :class_name =>'CourseMessage', :as => :course_message, :dependent => :destroy + after_save :act_as_course_message, :act_as_activity, :act_as_course_activity acts_as_event :title => Proc.new {|o| "#{l(:label_course_poll)}: #{o.polls_name}" }, :description => :polls_description, @@ -27,4 +32,30 @@ class Poll < ActiveRecord::Base self.acts << Activity.new(:user_id => self.user_id) end + #课程动态公共表记录 + def act_as_course_activity + if self.polls_type == "Course" + if self.polls_status == 2 #问卷是发布状态 + self.course_acts << CourseActivity.new(:user_id => self.user_id,:course_id => self.polls_group_id) + elsif self.polls_status == 1 #问卷是新建状态 + self.course_acts.destroy_all + end + end + end + + # 发布问卷,出了发布者外,其他人都能收到消息通知 + def act_as_course_message + if self.polls_type == "Course" + if self.polls_status == 2 #问卷是发布状态 + Course.find(self.polls_group_id).members.each do |m| + if m.user_id != self.user_id + self.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => self.polls_group_id, :viewed => false) + end + end + elsif self.polls_status == 1 #问卷是新建状态 + self.course_messages.destroy_all + end + end + end + end diff --git a/app/models/project.rb b/app/models/project.rb index df32bfcbd..8fe02b29f 100644 --- a/app/models/project.rb +++ b/app/models/project.rb @@ -66,8 +66,8 @@ class Project < ActiveRecord::Base # has_many :students_for_courses, :dependent => :destroy has_many :student, :through => :students_for_courses, :source => :user has_one :course_extra, :class_name => 'Course', :foreign_key => :extra,:primary_key => :identifier, :dependent => :destroy - has_many :applied_projects - has_many :invite_lists + has_many :applied_projects, :dependent => :destroy + has_many :invite_lists, :dependent => :destroy has_one :dts # end @@ -91,6 +91,8 @@ class Project < ActiveRecord::Base has_many :tags, :through => :project_tags, :class_name => 'Tag' has_many :project_tags, :class_name => 'ProjectTags' + # 关联虚拟表 + has_many :forge_messages, :class_name =>'ForgeMessage', :as => :forge_message, :dependent => :destroy belongs_to :organization diff --git a/app/models/query.rb b/app/models/query.rb index 19bd1bed5..65c78e71f 100644 --- a/app/models/query.rb +++ b/app/models/query.rb @@ -492,26 +492,29 @@ class Query < ActiveRecord::Base def project_statement project_clauses = [] - if project && !project.descendants.active.empty? - ids = [project.id] - if has_filter?("subproject_id") - case operator_for("subproject_id") - when '=' - # include the selected subprojects - ids += values_for("subproject_id").each(&:to_i) - when '!*' - # main project only - else - # all subprojects - ids += project.descendants.collect(&:id) - end - elsif Setting.display_subprojects_issues? - ids += project.descendants.collect(&:id) - end - project_clauses << "#{Project.table_name}.id IN (%s)" % ids.join(',') - elsif project - project_clauses << "#{Project.table_name}.id = %d" % project.id + # unless project.descendants.blank? + # if project && project.descendants && project.descendants.active && !project.descendants.active.empty? + # ids = [project.id] + # if has_filter?("subproject_id") + # case operator_for("subproject_id") + # when '=' + # # include the selected subprojects + # ids += values_for("subproject_id").each(&:to_i) + # when '!*' + # # main project only + # else + # # all subprojects + # ids += project.descendants.collect(&:id) + # end + # elsif Setting.display_subprojects_issues? + # ids += project.descendants.collect(&:id) + # end + # project_clauses << "#{Project.table_name}.id IN (%s)" % ids.join(',') + # elsif project + if project + project_clauses << "#{Project.table_name}.id = %d" % project.id end + # end project_clauses.any? ? project_clauses.join(' AND ') : nil end diff --git a/app/models/student_work.rb b/app/models/student_work.rb index b95c11c11..cd4d81a32 100644 --- a/app/models/student_work.rb +++ b/app/models/student_work.rb @@ -1,19 +1,139 @@ #学生提交作品表 class StudentWork < ActiveRecord::Base - attr_accessible :name, :description, :homework_common_id, :user_id, :final_score, :teacher_score, :student_score, :teaching_asistant_score, :project_id + attr_accessible :name, :description, :homework_common_id, :user_id, :final_score, :teacher_score, :student_score, :teaching_asistant_score, :project_id, :is_test belongs_to :homework_common belongs_to :user has_many :student_works_evaluation_distributions, :dependent => :destroy has_many :student_works_scores, :dependent => :destroy belongs_to :project - has_many :student_work_test + has_many :student_work_tests, order: 'id desc' before_destroy :delete_praise + before_save :set_program_score, :set_src acts_as_attachable def delete_praise PraiseTread.where("praise_tread_object_id = #{self.id} AND praise_tread_object_type = 'StudentWork'").destroy_all end + + def last_test + student_work_tests.order('id desc').first + end + + private + def set_program_score + if homework_common.is_program_homework? #编程作业,学生提交作品后计算系统得分 + #根据最后一次测试计算得分 + unless last_test + self.system_score = 0 + else + self.system_score = last_test.test_score + end + end + set_final_score self.homework_common,self + end + def set_src + self.description = last_test.src if last_test + end + + #成绩计算 + def set_final_score homework,student_work + if homework && homework.homework_detail_manual + if homework.homework_type == 1 #匿评作业 + if homework.teacher_priority == 1 #教师优先 + if student_work.teacher_score + student_work.final_score = student_work.teacher_score + else + if student_work.teaching_asistant_score.nil? + student_work.final_score = student_work.student_score + elsif student_work.student_score.nil? + student_work.final_score = student_work.teaching_asistant_score + else + ta_proportion = homework.homework_detail_manual.ta_proportion + final_ta_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{ta_proportion}") + final_s_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}")) + final_score = final_ta_score + final_s_score + student_work.final_score = format("%.2f",final_score.to_f) + end + end + else #不考虑教师评分 + if student_work.teaching_asistant_score.nil? + student_work.final_score = student_work.student_score + elsif student_work.student_score.nil? + student_work.final_score = student_work.teaching_asistant_score + else + ta_proportion = homework.homework_detail_manual.ta_proportion + final_ta_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{ta_proportion}") + final_s_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}")) + final_score = final_ta_score + final_s_score + student_work.final_score = format("%.2f",final_score.to_f) + end + end + elsif homework.homework_type == 2 && homework.homework_detail_programing #编程作业-----设定:系统评分必定不为空 + if homework.teacher_priority == 1 #教师优先 + if student_work.teacher_score + student_work.final_score = student_work.teacher_score + else + if student_work.teaching_asistant_score.nil? #教辅未评分 + if student_work.student_score.nil? + student_work.final_score = student_work.system_score + else + ta_proportion = homework.homework_detail_programing.ta_proportion + homework.homework_detail_manual.ta_proportion / 2 + final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}") + final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}")) + final_score = final_sy_score + final_st_score + student_work.final_score = format("%.2f",final_score.to_f) + end + elsif student_work.student_score.nil? #学生未评分 + if student_work.teaching_asistant_score.nil? + student_work.final_score = student_work.system_score + else + ta_proportion = homework.homework_detail_programing.ta_proportion + (1.0 - homework.homework_detail_manual.ta_proportion - homework.homework_detail_programing.ta_proportion) / 2 + final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}") + final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}")) + final_score = final_sy_score + final_ts_score + student_work.final_score = format("%.2f",final_score.to_f) + end + else + final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}") + final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}") + final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}") - BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}")) + final_score = final_sy_score + final_ts_score + final_st_score + student_work.final_score = format("%.2f",final_score.to_f) + end + end + else #不考虑教师评分 + if student_work.teaching_asistant_score.nil? #教辅未评分 + if student_work.student_score.nil? + student_work.final_score = student_work.system_score + else + ta_proportion = homework.homework_detail_programing.ta_proportion + homework.homework_detail_manual.ta_proportion / 2 + final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}") + final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}")) + final_score = final_sy_score + final_st_score + student_work.final_score = format("%.2f",final_score.to_f) + end + elsif student_work.student_score.nil? #学生未评分 + if student_work.teaching_asistant_score.nil? + student_work.final_score = student_work.system_score + else + ta_proportion = homework.homework_detail_programing.ta_proportion + (1.0 - homework.homework_detail_manual.ta_proportion - homework.homework_detail_programing.ta_proportion) / 2 + final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}") + final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}")) + final_score = final_sy_score + final_ts_score + student_work.final_score = format("%.2f",final_score.to_f) + end + else + final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}") + final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}") + final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}") - BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}")) + final_score = final_sy_score + final_ts_score + final_st_score + student_work.final_score = format("%.2f",final_score.to_f) + end + end + end + end + end end diff --git a/app/models/student_work_test.rb b/app/models/student_work_test.rb index 413528b82..0246ecabf 100644 --- a/app/models/student_work_test.rb +++ b/app/models/student_work_test.rb @@ -1,12 +1,12 @@ # encoding: utf-8 class StudentWorkTest < ActiveRecord::Base - attr_accessible :student_work_id, :homework_test_id, :result, :error_msg - - belongs_to :homework_test + attr_accessible :student_work_id, :results, :status, :src belongs_to :student_work + serialize :results, Array + def status_to_s - case self.result.to_i + case self.status.to_i when -1 '编译出错' when -2 @@ -33,10 +33,20 @@ class StudentWorkTest < ActiveRecord::Base end def test_score - if self.result.to_i == 0 - format("%.1f",100.0 / self.student_work.homework_common.homework_tests.count) - else + if self.status.to_i == 0 + 100 + elsif self.results.empty? 0 + else + get_success_count * 100 / self.results.count end end + + private + def get_success_count + self.results.inject(0) do |sum, result| + sum += (result["status"] && result["status"].to_i == 0 ? 1 : 0) + end || 0 + end + end diff --git a/app/models/student_works_score.rb b/app/models/student_works_score.rb index 8fa14f8de..aa38c5dcd 100644 --- a/app/models/student_works_score.rb +++ b/app/models/student_works_score.rb @@ -1,3 +1,4 @@ +#encoding=UTF-8 class StudentWorksScore < ActiveRecord::Base #reviewer_role: 1:教师评分;2:教辅评分;3:学生匿评 attr_accessible :student_work_id, :user_id, :score, :comment, :reviewer_role @@ -5,6 +6,35 @@ class StudentWorksScore < ActiveRecord::Base belongs_to :user belongs_to :student_work has_many :journals_for_messages, :as => :jour, :dependent => :destroy + has_many :course_messages, :class_name =>'CourseMessage', :as => :course_message, :dependent => :destroy acts_as_attachable + + after_save :act_as_course_message + + # 评阅作品消息提示 + def act_as_course_message + if self.student_work && self.student_work.user && self.student_work.homework_common.course + receiver = self.student_work.user + # 判断是第一次评阅还是更新 status:0 新建;1 更新 + if self.created_at == self.updated_at + if self.comment.nil? + self.course_messages << CourseMessage.new(:user_id => receiver.id, :course_id => self.student_work.homework_common.course.id, + :viewed => false, :content => "作业评分:#{self.score}", :status=> false) + else + self.course_messages << CourseMessage.new(:user_id => receiver.id, :course_id => self.student_work.homework_common.course.id, + :viewed => false, :content => "作业评分:#{self.score}    评语:#{self.comment}", :status=> false) + end + else # 更新 + if self.comment.nil? + self.course_messages << CourseMessage.new(:user_id => receiver.id, :course_id => self.student_work.homework_common.course.id, + :viewed => false, :content => "作业评分:#{self.score}", :status=> true) + else + self.course_messages << CourseMessage.new(:user_id => receiver.id, :course_id => self.student_work.homework_common.course.id, + :viewed => false, :content => "作业评分:#{self.score}    评语:#{self.comment}", :status=> true) + end + end + end + end + end diff --git a/app/models/system_message.rb b/app/models/system_message.rb new file mode 100644 index 000000000..a05610da7 --- /dev/null +++ b/app/models/system_message.rb @@ -0,0 +1,19 @@ +class SystemMessage < ActiveRecord::Base + attr_accessible :content, :id, :user_id, :description, :subject + belongs_to :user + + validates :subject, presence: true + # validates :description, presence: true + validates_length_of :description, maximum: 10000 + + has_many :message_alls, :class_name => 'MessageAll',:as =>:message, :dependent => :destroy + + # 系统消息放置总消息列表 + after_create :add_system_message + + def add_system_message + if MessageAll.where("message_type = '#{self.class.to_s}' and message_id = '#{self.id}'").first.nil? + self.message_alls << MessageAll.new(:user_id => self.user_id) + end + end +end diff --git a/app/models/user.rb b/app/models/user.rb index 11dc5e953..fd565cbdf 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -109,7 +109,6 @@ class User < Principal has_many :contests, :foreign_key => 'author_id', :dependent => :destroy has_many :softapplications, :foreign_key => 'user_id', :dependent => :destroy has_many :journals_for_messages, :as => :jour, :dependent => :destroy - has_many :new_jours, :as => :jour, :class_name => 'JournalsForMessage', :conditions => "status=1" has_many :journal_replies, :dependent => :destroy has_many :activities, :dependent => :destroy has_many :students_for_courses @@ -128,10 +127,20 @@ class User < Principal has_many :messages, :foreign_key => 'author_id' has_one :user_score, :dependent => :destroy has_many :documents # 项目中关联的文档再次与人关联 -# end - +# 关联消息表 + has_many :forge_messages + has_many :course_messages + has_many :memo_messages + has_many :user_feedback_messages + has_one :onclick_time + has_many :system_messages + +# 虚拟转换 + has_many :new_jours, :as => :jour, :class_name => 'JournalsForMessage', :conditions => "status=1" + has_many :issue_assigns, :class_name => 'ForgeMessage', :conditions => 'viewed=0 and forge_message_type="Issue"' + has_many :status_updates, :class_name => 'ForgeMessage', :conditions => 'viewed=0 and forge_message_type="Journal"' # 邮件邀请状态 - # has_many :invite_lists + has_many :invite_lists, :dependent => :destroy # end ######added by nie @@ -150,7 +159,8 @@ class User < Principal nil } - + acts_as_attachable :view_permission => :view_files, + :delete_permission => :manage_files acts_as_customizable ############################added by william acts_as_taggable @@ -197,13 +207,14 @@ class User < Principal validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true validate :validate_password_length # validates_email_realness_of :mail - before_create :set_mail_notification + before_create :set_mail_notification, :sync_gitlab_user before_save :update_hashed_password before_destroy :remove_references_before_destroy # added by fq - after_create :act_as_activity + after_create :act_as_activity, :add_onclick_time # end - before_create :sync_gitlab_user + # 更新邮箱用户或用户名的同事,同步更新邀请信息 + after_update :update_invite_list scope :in_group, lambda {|group| group_id = group.is_a?(Group) ? group.id : group.to_i @@ -236,10 +247,51 @@ class User < Principal # ====================================================================== + # 查询用户未读过的记录 + # 用户留言记录 + def count_new_jour + count = self.new_jours.count + # count = self.journals_for_messages(:conditions => ["status=? and is_readed = ? " ,1, 0]).count + end + + # 查询指派给我的缺陷记录 + def count_new_issue_assign_to + self.issue_assigns + end + + # 新消息统计 + def count_new_message + if OnclickTime.where("user_id =?", User.current).first.nil? + message_new_time = OnclickTime.new + message_new_time.user_id = User.current.id + # 第一次初始化点击铃铛时间 + message_new_time.onclick_time = User.current.last_login_on.nil? ? Time.now : User.current.last_login_on + message_new_time.save + end + course_count = CourseMessage.where("user_id =? and viewed =? and created_at >?", User.current.id, 0, User.current.onclick_time.onclick_time).count + forge_count = ForgeMessage.where("user_id =? and viewed =? and created_at >?", User.current.id, 0, User.current.onclick_time.onclick_time).count + user_feedback_count = UserFeedbackMessage.where("user_id =? and viewed =? and created_at >?", User.current.id, 0, User.current.onclick_time.onclick_time).count + user_memo_count = MemoMessage.where("user_id =? and viewed =? and created_at >?", User.current.id, 0, User.current.onclick_time.onclick_time).count + system_messages_count = SystemMessage.where("created_at >?", User.current.onclick_time.onclick_time).count + messages_count = course_count + forge_count + user_feedback_count + user_memo_count + system_messages_count + end + + # 查询指派给我的缺陷记录 + def issue_status_update + self.status_updates + end + # end + def extensions self.user_extensions ||= UserExtensions.new end + # User现在可以作为一个Container_type,而Attachment的Container方法会有一个Container.try(:project), + # 所以这里定义一个空方法,保证不报错 + def project + + end + def user_score_attr self.user_score ||= UserScore.new end @@ -259,7 +311,7 @@ class User < Principal ###添加留言 fq def add_jour(user, notes, reference_user_id = 0, options = {}) if options.count == 0 - self.journals_for_messages << JournalsForMessage.new(:user_id => user.id, :notes => notes, :reply_id => reference_user_id, :status => true) + self.journals_for_messages << JournalsForMessage.new(:user_id => user.id, :notes => notes, :reply_id => reference_user_id, :status => true, :is_readed => false) else jfm = self.journals_for_messages.build(options) jfm.save @@ -293,10 +345,6 @@ class User < Principal end ## end - def count_new_jour - count = self.new_jours.count - end - #added by nie def count_new_journal_reply count = self.journal_reply.count @@ -419,7 +467,7 @@ class User < Principal end def nickname(formatter = nil) - login + login.nil? || (login && login.empty?) ? "AnonymousUser" : login end def name(formatter = nil) @@ -958,6 +1006,23 @@ class User < Principal self.acts << Activity.new(:user_id => self.id) end + # 注册用户的时候消息默认点击时间为用户创建时间 + def add_onclick_time + if OnclickTime.where("user_id =?" , self.id).first.nil? + OnclickTime.create(:user_id => self.id, :onclick_time => self.created_on) + end + end + + # 更新邮箱的同事,更新invite_lists表中的邮箱信息 + def update_invite_list + invite_lists = InviteList.where("user_id =?",self.id).all + unless invite_lists.blank? + invite_lists.each do |invite_list| + invite_list.update_attribute(:mail, self.mail) + end + end + end + # Removes references that are not handled by associations # Things that are not deleted are reassociated with the anonymous user def remove_references_before_destroy diff --git a/app/models/user_activity.rb b/app/models/user_activity.rb new file mode 100644 index 000000000..1af1dc017 --- /dev/null +++ b/app/models/user_activity.rb @@ -0,0 +1,7 @@ +class UserActivity < ActiveRecord::Base + attr_accessible :act_type,:act_id,:container_type,:container_id + # 虚拟关联---项目动态表/课程动态表 + belongs_to :act ,:polymorphic => true + # 虚拟关联---项目/课程 + belongs_to :container ,:polymorphic => true +end diff --git a/app/models/user_feedback_message.rb b/app/models/user_feedback_message.rb new file mode 100644 index 000000000..db7d3a384 --- /dev/null +++ b/app/models/user_feedback_message.rb @@ -0,0 +1,18 @@ +class UserFeedbackMessage < ActiveRecord::Base + attr_accessible :journals_for_message_id, :journals_for_message_type, :user_id, :viewed + + belongs_to :journals_for_message + belongs_to :user + has_many :message_alls, :class_name => 'MessageAll',:as =>:message, :dependent => :destroy + + validates :user_id,presence: true + validates :journals_for_message_id,presence: true + validates :journals_for_message_type, presence: true + after_save :add_user_message + + def add_user_message + if MessageAll.where("message_type = '#{self.class.to_s}' and message_id = '#{self.id}'").first.nil? + self.message_alls << MessageAll.new(:user_id => self.user_id) + end + end +end diff --git a/app/services/users_service.rb b/app/services/users_service.rb index 7e8e775ed..236dbc731 100644 --- a/app/services/users_service.rb +++ b/app/services/users_service.rb @@ -47,12 +47,16 @@ class UsersService end # 自动注册功能 FOR:邮件邀请 - def register_auto(login,mail,password) + def register_auto(login, mail, password, first_name, last_name, gender) + mail_notification = "day" @user = User.new @user.admin = false @user.register @user.login = login @user.mail = mail + @user.firstname = first_name + @user.lastname = last_name + @user.mail_notification = mail_notification password_confirmation = password should_confirmation_password = true if !password.blank? && !password_confirmation.blank? && should_confirmation_password @@ -65,6 +69,7 @@ class UsersService @user = automatically_register_lock(@user) if @user.id != nil ue = @user.user_extensions ||= UserExtensions.new + ue.gender = gender ue.user_id = @user.id ue.save end diff --git a/app/views/account/about_us.html.erb b/app/views/account/about_us.html.erb new file mode 100644 index 000000000..f990cd64c --- /dev/null +++ b/app/views/account/about_us.html.erb @@ -0,0 +1,50 @@ +<%= stylesheet_link_tag 'new_user'%> +
+

关于我们

+
+

+ Trustie是一个面向高校创新实践的在线协作社区,是在中国高校推行大规模开放在线研究(Massive Open Online Research, MOORE)的支撑平台,也简称Trustie平台。老师、学生和科研人员可以在此开展各种在线协同学习、协同作业、协同开发等活动。 +

+

+ MOORE是国防科学技术大学杨学军院士提出的一个面向高校科研教学活动的新型创新实践概念,为全面支持高校人才培养和科学研究提供了一种新思路。MOORE是对大规模在线开放课程(Massive Open Online Course, MOOC)的拓展,是课堂教学与创新实践深度结合的全新模式,可以看作MOOC2.0。 +

+

+ 2005年开始,Trustie研制团队围绕网络时代的软件开发效率和质量这一核心问题展开研究,经过十年的磨砺与攻关,逐步揭示出以大众化协同开发、开放式资源共享、持续性可信评估为核心的互联网大规模协同机理,提出了全新的软件开发群体化方法。2008年起,研制团队开始探索如何将这种协同机理引入软件人才培养。MOORE概念的提出为研制团队的人才培养实践提供了新的发展方向和应用模式,使Trustie技术和工具能够更直接、更有效地与高校人才培养对接,形成了今天已被大量师生接受的在线人才培养平台。 +

+

+ 研制团队认为MOORE的创新人才培养模式(如图1左图)是将互联网大规模协同机理与高校创新实践活动相结合的全新人才培养方法和模式,研制团队并基于本平台的架构形成了对MOORE核心机理的三方面认识(如图1右图)。 +

+
+ +

图1 基于MOORE的创新人才培养模式与核心机理

+
+

+ 目前,Trustie平台已经初步展现出大规模开放在线研究的生态系统蓝图,其核心是在线教学实践平台和在线协同研究平台,如图2。Trustie在线教学实践平台是支持教师和学生围绕课堂学习开展实践的平台(如图2),Trustie在线协同研究平台是支持开发小组围绕实践任务或研究工作开展分布式协作的平台(如图2)。两个核心平台为一名"新手"大学生成长为具有一定创新能力的"创客"提供了从学习到研究的一个渐进式成长环境(如图2)。 +

+

+ 特别是,根据师生的实际需要,Trustie平台提供了私有模式和公开模式,支持针对未公开成果实施有效知识产权保护为前提的交流分享(如图2)。随着越来越多的高校、课程和研究小组的加入,MOORE创新实践模式的生态效益将不断显现出来。 +

+
+ +

图2 基于MOORE的支撑平台和生态系统

+
+

+ 研制团队特别感谢高校老师和学生的积极反馈、无私创意。平台的很多实用便捷的功能都是老师们积极参与和设计的结果,汇聚了大量师生的宝贵贡献,是研制团队和用户群体共同成长的结果。 +

+

+ Trustie平台的基本思路是将开源模式与中国高校人才培养活动相结合,但其本质上是一种O2O(Online To Offline)的创新人才培养模式,只有在以下两个方面同步推进,才能在持续解决实际需求的过程中快速发展:
+     (1)构建实践平台,激活创新能力:成为支持不同规模的团队进行协同研究和协同开发的实践平台,支持各类可公开的课程实验任务、教研室科研任务的在线协同,能够有效提升和评估学生的创新能力、协作能力和实践能力。
+     (2)引入开源理念,形成创客文化:将互联网开源软件运动中的自由、对等、共享、创新的理念引入高校,使"自主创意并亲自动手实现创意"的创客精神深入人才培养活动,在学生群体中形成大胆创意、大胆实践的创新文化。 +

+

+ 研制团队认为,Trustie平台是一种"互联网+"思维在高校教育领域的大型探索性实践。作为一种互联网应用,Trustie平台自身的开发也采取了互联网模式:Trustie研制团队采用了"网构化软件开发模式",坚持"每周一更"的快速上线、快速体验模式,以最大程度上贴近用户实际需求提升。欢迎高校师生一同投身创新实践,共同见证MOORE创新生态的早日形成。 +

+
+ + + +
+ + + + diff --git a/app/views/account/agreement.html.erb b/app/views/account/agreement.html.erb new file mode 100644 index 000000000..921f66350 --- /dev/null +++ b/app/views/account/agreement.html.erb @@ -0,0 +1,51 @@ +<%= stylesheet_link_tag 'new_user'%> + +
+

Trustie服务协议

+
+

尊敬的用户,您好!
+欢迎使用Trustie平台,在您使用Trustie平台前,请您认真阅读并遵守《Trustie服务协议》(以下简称"本协议"),请您务必审慎阅读、充分理解协议的各条款内容。
+当您在注册过程中点击查看"看过并同意本服务协议",按照注册流程成功注册为Trustie平台的用户即表示您已充分阅读、理解并完全接受本协议中的全部条款。您承诺接受并遵守本协议的约定,届时您不应以未阅读本协议的内容等理由,主张本协议无效或本协议中的某些条款无效,或要求撤销本协议。

+

一、Trustie平台权利和义务

+

1、尊重用户隐私:尊重用户隐私,保障用户隐私安全是Trustie平台的一项基本政策;
+2、管理平台用户:Trustie平台依据国家法律、地方法律和国际法律等的标准以及本行业的规则来管理平台注册用户;
+3、处理用户反馈:Trustie平台的相关人员会及时处理用户反馈的问题并给予及时回复。

+

二、用户权利和义务

+

用户在使用Trustie平台的过程中,必须遵守如下原则:
+1、遵守中国的有关法律和法规;
+2、使用网络服务不作非法用途;
+3、不干扰和混乱网络服务;
+4、遵守所有使用网络服务的网络协议、规定、程序和惯例;
+5、不传输任何非法的、骚扰性的、中伤他人的、辱骂性的、恐吓性的、伤害性的、庸俗的,淫秽等信息资料;
+6、不传输任何教唆他人构成犯罪行为的资料;
+7、用户不得故意或者过失损害Trustie平台合法权利和利益。及时回复。

+

三、关于责任

+

鉴于网络服务的特殊性,用户同意Trustie团队有权在事先通知的情况下,变更、中断、升级部分网络服务。Trustie团队不担保网络服务不会中断,但承诺在用户可承受的时间内快速恢复服务,同时确保用户数据的安全性和可靠性。

+

四、服务条款的修改

+

Trustie团队保留在必要时对本协议修改的权利,一旦发生变动,这些条款可由Trustie团队及时更新,且毋须另行通知,修改后的条款一旦在网页上公布即有效代替原来的服务条款。您可随时查阅最新版服务条款。

+

本协议最终解释权归Trustie团队所有。

+
+ + +
+ + + diff --git a/app/views/account/login.html.erb b/app/views/account/login.html.erb index bb289eb03..ed43f455a 100644 --- a/app/views/account/login.html.erb +++ b/app/views/account/login.html.erb @@ -1,98 +1,286 @@ -<% @nav_dispaly_home_path_label = 1 - @nav_dispaly_main_course_label = 1 - @nav_dispaly_main_project_label = 1 - @nav_dispaly_main_contest_label = 1 %> -<% @nav_dispaly_forum_label = 1%> -<%= call_hook :view_account_login_top %> - - - - - - -
-<%= form_tag(signin_path) do %> -<%= back_url_hidden_field_tag %> - - - - - - - - - -<% if Setting.openid? %> - - - - -<% end %> - - - - - - - -
- - - <%= text_field_tag 'username', params[:username], :tabindex => '1' , :value => "#{l(:label_login_prompt)}", - :onfocus => "clearInfo('username','#{l(:label_login_prompt)}')", - :onblur => "showInfo('username','#{l(:label_login_prompt)}')", - :style => "resize: none;font-size: 12px;color: #818283;"%> -
- - - <%= password_field_tag 'password', nil, :tabindex => '2' %> -
- - - <%= text_field_tag "openid_url", nil, :tabindex => '3' %> -
- <% if Setting.autologin? %> - - <% end %> -
- - - <% if Setting.lost_password? %> - <%= link_to l(:label_password_lost), lost_password_path %> - <% end %> - - - -
-<% end %> -
-<%= call_hook :view_account_login_bottom %> - -<% if params[:username].present? %> -<%= javascript_tag "$('#password').focus();" %> -<% else %> -<%= javascript_tag "$('#username').focus();" %> -<% end %> +<%= stylesheet_link_tag 'new_user'%> +<%= stylesheet_link_tag 'leftside'%> + + +
+
+
+ +
  欢迎加入Trustie高校创新实践社区!老师、学生和科研人员可以在此开展各种在线协同学习、协同作业、协同开发等活动。

  Trustie是在中国推行大规模开放在线研究模式(MOORE)的支撑平台。
+
+
+
+
+
+
    +
  • 登录
  • +
  • +
+
+
<%= flash.empty? || flash[:error].nil? ? "" : flash[:error].html_safe %>
+
+
+ + <%= form_tag(signin_path,:id=>'main_login_form',:method=>'post') do %> + <%= back_url_hidden_field_tag %> +
+ <%= text_field_tag 'username', params[:username], :tabindex => '1' , + :class=>'loginSignBox',:placeholder=>'请输入邮箱地址或昵称', :onkeypress => "user_name_keypress(event);"%> + +
+ <% if Setting.openid? %> +
+ <%= text_field_tag "openid_url", nil, :tabindex => '3',:placeholder=>'请输入OpenId URL' %> +
+ <% end %> +
+ + <%= password_field_tag 'password', nil, :tabindex => '2',:class=>'loginSignBox' ,:placeholder=>'请输密码', :onkeypress => "user_name_keypress(event);"%> +
+
+ <% if Setting.autologin? %> +
+ <%= check_box_tag 'autologin', 1, true, :tabindex => 4 %> +
+ <%= l(:label_stay_logged_in) %> + <% end %> + + <% if Setting.lost_password? %> + 忘记密码? + <% end %> +
+ <% end %> +
+ 登录 +
+ +
+ +
+
+
+
    +
  • 注册<%= link_to l(:label_login_with_open_id_option), signin_url if Setting.openid? %> +
  • +
+
+
+ <%= form_for :user, :url => register_path,:method=>'post',:html=>{:id=>'main_reg_form'} do |f| %> + <%= error_messages_for 'user' %> +
+ + <%= f.text_field :mail,:size => 25, :class=>'loginSignBox' ,:placeholder=>"请输入邮箱地址"%> + +
+
+ + <%= f.password_field :password, :size => 25,:placeholder=>"请输入密码",:class=>'loginSignBox' %> + +
+
+ + <%= f.password_field :password_confirmation, :size => 25,:placeholder=>"请再次输入密码",:class=>'loginSignBox' %> + +
+
+ + <%= f.text_field :login, :size => 25,:placeholder=>"请输入用户昵称",:class=>'loginSignBox'%> + +
+
+
+ +
+ 我已阅读并接受Trustie服务协议条款
+
+ 注册 + +
+ <% end %> +
+
+
+
+
+
diff --git a/app/views/account/lost_password.html.erb b/app/views/account/lost_password.html.erb index 3c6c57f52..5bf93fd14 100644 --- a/app/views/account/lost_password.html.erb +++ b/app/views/account/lost_password.html.erb @@ -1,16 +1,26 @@ -<% @nav_dispaly_home_path_label = 1 - @nav_dispaly_main_course_label = 1 - @nav_dispaly_main_project_label = 1 - @nav_dispaly_main_contest_label = 1 %> -<% @nav_dispaly_forum_label = 1%> -

<%=l(:label_password_forget)%>

+<%= stylesheet_link_tag 'new_user'%> -<%= form_tag(lost_password_path) do %> -
-

- - <%= text_field_tag 'mail', nil, :size => 40, :placeholder => '请输入注册邮箱'%> - <%= submit_tag l(:button_submit) %> -

-
-<% end %> +
+
+

忘记密码

+
+ <%= form_tag(lost_password_path) do %> +

通过注册邮箱链接重设密码

+ + <%= text_field_tag 'mail', nil, :size => 40, :placeholder => '请输入注册邮箱',:class=>'NomalInput mb20'%> + <% if flash[:error] %> +

<%= flash[:error]%>

+ + <% elsif flash[:notice] %> +

<%= flash[:notice]%>

+ + <% end %> + + <% end %> +
+ + +
+
+ + diff --git a/app/views/account/password_recovery.html.erb b/app/views/account/password_recovery.html.erb index 568d4d4bb..5cd438336 100644 --- a/app/views/account/password_recovery.html.erb +++ b/app/views/account/password_recovery.html.erb @@ -1,20 +1,19 @@ -

<%=l(:label_password_lost)%>

- <%= error_messages_for 'user' %> +
+
+

重置密码

+
+ <%= form_tag(lost_password_path) do %> + <%= hidden_field_tag 'token', @token.value %> + + <%= password_field_tag 'new_password', nil, :size => 25,:placeholder=>'新密码',:style=>"width:308px; height:38px; border:1px solid #98a1a6; outline:none; color:#888888; font-size:14px; " %> +

至少需要 6 个字符

+ + <%= password_field_tag 'new_password_confirmation', nil, :size => 25,:placeholder=>'确定密码',:style=>"width:308px; height:38px; border:1px solid #98a1a6; outline:none; color:#888888; font-size:14px;margin-bottom:20px; " %> + + <% end %> +
-<%= form_tag(lost_password_path) do %> - <%= hidden_field_tag 'token', @token.value %> -
-

- - <%= password_field_tag 'new_password', nil, :size => 25 %> - <%= l(:text_caracters_minimum, :count => Setting.password_min_length) %> -

-

- - <%= password_field_tag 'new_password_confirmation', nil, :size => 25 %> -

-
-

<%= submit_tag l(:button_save) %>

-<% end %> +
+
diff --git a/app/views/admin/_tab_messages.erb b/app/views/admin/_tab_messages.erb new file mode 100644 index 000000000..ec04246ba --- /dev/null +++ b/app/views/admin/_tab_messages.erb @@ -0,0 +1,8 @@ +
+
    +
  • <%= link_to l(:label_forum), {:action => 'messages_list'}, class: "#{current_page?(messages_list_path)? 'selected' : nil }" %>
  • +
  • <%= link_to l(:label_borad_course), {:action => 'course_messages'}, class: "#{current_page?(course_messages_path)? 'selected' : nil }" %>
  • +
  • <%= link_to l(:label_borad_project), {:action => 'project_messages'}, class: "#{current_page?(project_messages_path)? 'selected' : nil }" %>
  • + +
+
\ No newline at end of file diff --git a/app/views/admin/course_messages.html.erb b/app/views/admin/course_messages.html.erb new file mode 100644 index 000000000..c9e69357f --- /dev/null +++ b/app/views/admin/course_messages.html.erb @@ -0,0 +1,69 @@ +

+ <%=l(:label_message_plural)%> +

+ +<%= render 'tab_messages' %> +

<%=l(:label_borad_course) %>

+
+ + + + + + + + + + + + + <% @count=@page*30%> + <% for course in @course_ms -%> + + <% @count=@count + 1 %> + "> + + + + + + + + + <% end %> + +
+ 序号 + + 来源(课程ID) + + 作者 + + 时间 + + 标题 + + 回复数 +
+ <%= @count %> + + <%= Board.where('id=?',course.board_id).first.course_id %> + <%= course.try(:author)%><% else %><%=course.try(:author).try(:realname) %><% end %>'> + <% if course.try(:author).try(:realname) == ' '%> + <%= link_to(course.try(:author), user_path(course.author)) %> + <% else %> + <%= link_to(course.try(:author).try(:realname), user_path(course.author)) %> + <% end %> + + <%= format_date(course.created_on) %> + + <%= link_to(course.subject, course_boards_path(Board.where('id=?',course.board_id).first.course_id)) %> + + <%= link_to(course.replies_count, course_boards_path(Board.where('id=?',course.board_id).first.course_id)) %> +
+
+ + +<% html_title(l(:label_message_plural)) -%> diff --git a/app/views/admin/homework.html.erb b/app/views/admin/homework.html.erb new file mode 100644 index 000000000..7260d68ff --- /dev/null +++ b/app/views/admin/homework.html.erb @@ -0,0 +1,66 @@ +

+ <%=l(:label_user_homework)%> +

+ +
+ + + + + + + + + + + + + <%@count=@page*30 %> + <% for homework in @homework do %> + <% @count+=1 %> + + + + + + + + + <% end %> + +
+ 序号 + + 作业名称 + + 课程名称 + + 作者 + + 提交作品数 + + 提交截止日期 +
+ <%=@count %> + + <%=link_to(homework.name, student_work_index_path(:homework => homework.id))%> + + <%= link_to(homework.course.name, course_path(homework.course.id)) %> + <%= homework.try(:user)%><% else %><%=homework.try(:user).try(:realname) %><% end %>'> + <% if homework.try(:user).try(:realname) == ' '%> + <%= link_to(homework.try(:user), user_path(homework.user_id)) %> + <% else %> + <%= link_to(homework.try(:user).try(:realname), user_path(homework.user_id)) %> + <% end %> + + <%=link_to(StudentWork.where('homework_common_id=?',homework.id).count, student_work_index_path(:homework => homework.id))%> + + <%=format_date(homework.end_time) %> +
+
+ + + +<% html_title(l(:label_user_homework)) -%> diff --git a/app/views/admin/latest_login_users.html.erb b/app/views/admin/latest_login_users.html.erb new file mode 100644 index 000000000..28ef8091e --- /dev/null +++ b/app/views/admin/latest_login_users.html.erb @@ -0,0 +1,98 @@ +<%= stylesheet_link_tag 'jquery/jquery-ui-1.9.2', :media => 'all' %> +

+ <%=l(:label_latest_login_user_list)%> +

+ +<%= form_tag({}, :method => :get) do %> +
+ + <%= l(:label_filter_plural) %> + + + <%= text_field_tag 'startdate', params[:startdate], :size => 15, :onchange=>"$('#ui-datepicker-div').hide()", :style=>"float:left"%> + <%= calendar_for('startdate')%>    + + <%= text_field_tag 'enddate', params[:enddate], :size => 15, :onchange =>"$('#ui-datepicker-div').hide()", :style=>"float:left"%> + <%= calendar_for('enddate')%>   + <%= submit_tag l(:button_apply), :class => "small", :name => nil %> + <%= link_to l(:button_clear), {:controller => 'admin', :action => 'latest_login_users'}, :class => 'icon icon-reload' %> +
+<% end %> +  + + +
+ + + + + + + + + + + + + <% @count=@page * 30 %> + <% for user in @user do %> + + <% @count +=1 %> + + + + + + + + <% end %> + +
+ 序号 + + 登录时间 + + 用户id + + 用户姓名 + + 用户昵称 + + 用户身份 +
+ <%=@count %> + + <%=format_time(user.last_login_on) %> + + <%=user.id %> + <%= user.login%><% else %><%=user.try(:realname) %><% end %>'> + <% if user.try(:realname) == ' '%> + <%= link_to(user.login, user_path(user)) %> + <% else %> + <%= link_to(user.try(:realname), user_path(user)) %> + <% end %> + + <%=link_to(user.login, user_path(user)) %> + + <%if user.user_extensions%> + <% case user.user_extensions.identity %> + <% when 0 %> + <%='老师' %> + <% when 1 %> + <%='学生' %> + <% when 2 %> + <%='企业' %> + <% when 3 %> + <%='开发者' %> + <% else %> + <%='未知身份' %> + <% end %> + <% end%> +
+
+ + + +<% html_title(l(:label_latest_login_user_list)) -%> diff --git a/app/views/admin/leave_messages.html.erb b/app/views/admin/leave_messages.html.erb new file mode 100644 index 000000000..dee8b7443 --- /dev/null +++ b/app/views/admin/leave_messages.html.erb @@ -0,0 +1,96 @@ +

+ <%=l(:label_leave_message_list)%> +

+ + +
+ + + + + + + + + + + + + + <% @count = @page * 30 %> + <% for journal in @jour -%> + <% @count=@count + 1 %> + "> + + + + + + + + + <% end %> + +
+ 序号 + + 类型 + + 来源(课程或用户ID) + + 留言人 + + 留言时间 + + 留言内容 + + 回复数 +
+ <%= @count %> + + <%case journal.jour_type %> + <% when 'Principal' %> + <%='用户主页' %> + <% when 'Course' %> + <%='课程' %> + <% end %> + + <%= journal.jour_id %> + <%= journal.try(:user)%><% else %><%=journal.try(:user).try(:realname) %><% end %>'> + <% if journal.try(:user).try(:realname) == ' '%> + <%= link_to(journal.try(:user), user_path(journal.user)) %> + <% else %> + <%= link_to(journal.try(:user).try(:realname), user_path(journal.user)) %> + <% end %> + + <%= format_date(journal.created_on) %> + + <%case journal.jour_type %> + <% when 'Principal' %> + <%= link_to(journal.notes.html_safe, feedback_path(journal.jour_id)) %> + <% when 'Course' %> + <%= link_to(journal.notes.html_safe, course_feedback_path(journal.jour_id)) %> + <% end %> + + <% if(journal.m_reply_count) %> + <%case journal.jour_type %> + <% when 'Principal' %> + <%= link_to(journal.m_reply_count, feedback_path(journal.jour_id)) %> + <% when 'Course' %> + <%= link_to(journal.m_reply_count, course_feedback_path(journal.jour_id)) %> + <% end %> + <% else %> + <%case journal.jour_type %> + <% when 'Principal' %> + <%= link_to(0, feedback_path(journal.jour_id)) %> + <% when 'Course' %> + <%= link_to(0, course_feedback_path(journal.jour_id)) %> + <% end %> + <% end %> +
+
+ + +<% html_title(l(:label_leave_message_list)) -%> diff --git a/app/views/admin/messages.html.erb b/app/views/admin/messages.html.erb new file mode 100644 index 000000000..f87741dd9 --- /dev/null +++ b/app/views/admin/messages.html.erb @@ -0,0 +1,64 @@ +<%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg' %> +

+ <%=l(:label_system_message)%> +


+
+ <%= form_for(@admin_messages, :html => {:id =>'system_messages-form'}) do |f| %> +
  • + + +

    +
  • +
  • + + <%= f.kindeditor :description,:width=>'87.5%',:editor_id=>'system_message_editor' %> +

    +
  • +
    +

    +
    +
    + <%= link_to l(:label_submit), "javascript:void(0)", :class => "btn_message_free", :onclick => "system_message_editor.sync();submit_message();" %> +
    + <% end %> +
    + + diff --git a/app/views/admin/messages_list.html.erb b/app/views/admin/messages_list.html.erb new file mode 100644 index 000000000..ca84baa24 --- /dev/null +++ b/app/views/admin/messages_list.html.erb @@ -0,0 +1,71 @@ +

    + <%=l(:label_message_plural)%> +

    + +<%= render 'tab_messages' %> +

    <%=l(:label_forum) %>

    +
    + + + + + + + + + + + + + <% @count=@page * 30%> + <% for memo in @memo -%> + <% @count=@count + 1 %> + "> + + + + + + + + <% end %> + +
    + 序号 + + 来源(贴吧ID) + + 作者 + + 时间 + + 标题 + + 回复数 +
    + <%= @count %> + + <%= memo.forum_id %> + <%= memo.try(:author)%><% else %><%=memo.try(:author).try(:realname) %><% end %>'> + <% if memo.try(:author).try(:realname) == ' '%> + <%= link_to(memo.try(:author), user_path(memo.author)) %> + <% else %> + <%= link_to(memo.try(:author).try(:realname), user_path(memo.author)) %> + <% end %> + + <%= format_date(memo.created_at) %> + + <% if memo.parent_id.nil? || memo.subject.starts_with?('RE:')%> + <%= link_to(memo.subject, forum_memo_path(memo.forum, memo)) %> + <% else %> + <%= link_to("RE:"+memo.subject, forum_memo_path(memo.forum, memo)) %> + <% end %> + + <%= link_to(memo.replies_count, forum_memo_path(memo.forum, memo)) %> +
    +
    + + +<% html_title(l(:label_message_plural)) -%> diff --git a/app/views/admin/notices.html.erb b/app/views/admin/notices.html.erb new file mode 100644 index 000000000..f03a7b97a --- /dev/null +++ b/app/views/admin/notices.html.erb @@ -0,0 +1,78 @@ +

    + <%=l(:label_notification_list)%> +

    + +
    + + + + + + + + + + + + + + + <% @count=@page * 30%> + <% for news in @news -%> + <% @count=@count + 1 %> + "> + + + + + + + + + + <% end %> + +
    + 序号 + + 课程id + + 课程名称 + + 主讲老师 + + 作者 + + 时间 + + 标题 + + 回复数 +
    + <%= @count %> + + <%=news.course_id %> + + <%=link_to(news.course.name, course_path(news.course)) %> + + <%=link_to(news.course.try(:teacher).try(:realname), user_path(news.course.teacher)) %> + <%= news.try(:author)%><% else %><%=news.try(:author).try(:realname) %><% end %>'> + <% if news.try(:author).try(:realname) == ' '%> + <%= link_to(news.try(:author), user_path(news.author)) %> + <% else %> + <%= link_to(news.try(:author).try(:realname), user_path(news.author)) %> + <% end %> + + <%= format_date(news.created_on) %> + + <%= link_to(news.title, news_path(news)) %> + + <%= link_to(news.comments_count, news_path(news)) %> +
    +
    + + + +<% html_title(l(:label_notification_list)) -%> diff --git a/app/views/admin/project_messages.html.erb b/app/views/admin/project_messages.html.erb new file mode 100644 index 000000000..a5639eba7 --- /dev/null +++ b/app/views/admin/project_messages.html.erb @@ -0,0 +1,70 @@ +

    + <%=l(:label_message_plural)%> +

    + +<%= render 'tab_messages' %> +

    <%=l(:label_borad_project) %>

    +
    + + + + + + + + + + + + + <% @count=@page * 30 %> + <% for project in @project_ms -%> + + <% @count=@count + 1 %> + "> + + + + + + + + + <% end %> + +
    + 序号 + + 来源(项目ID) + + 作者 + + 时间 + + 标题 + + 回复数 +
    + <%= @count %> + + <%= Board.where('id=?',project.board_id).first.project_id %> + <%= project.try(:author)%><% else %><%=project.try(:author).try(:realname) %><% end %>'> + <% if project.try(:author).try(:realname) == ' '%> + <%= link_to(project.try(:author), user_path(project.author)) %> + <% else %> + <%= link_to(project.try(:author).try(:realname), user_path(project.author)) %> + <% end %> + + <%= format_date(project.created_on) %> + + <%= link_to(project.subject, project_boards_path(Board.where('id=?',project.board_id).first.project_id)) %> + + <%= link_to(project.replies_count, project_boards_path(Board.where('id=?',project.board_id).first.project_id)) %> +
    +
    + + + +<% html_title(l(:label_message_plural)) -%> diff --git a/app/views/admin/projects.html.erb b/app/views/admin/projects.html.erb index f5b7955bf..3f6ee36f0 100644 --- a/app/views/admin/projects.html.erb +++ b/app/views/admin/projects.html.erb @@ -65,7 +65,7 @@ <%= link_to(l(:button_archive), { :controller => 'projects', :action => 'archive', :id => project, :status => params[:status] }, :data => {:confirm => l(:text_are_you_sure)}, :method => :post, :class => 'icon icon-lock') unless project.archived? %> <%= link_to(l(:button_unarchive), { :controller => 'projects', :action => 'unarchive', :id => project, :status => params[:status] }, :method => :post, :class => 'icon icon-unlock') if project.archived? && (project.parent.nil? || !project.parent.archived?) %> <%= link_to(l(:button_copy), { :controller => 'projects', :action => 'copy', :id => project }, :class => 'icon icon-copy') %> - <%= link_to(l(:button_delete), project_path(project), :method => :delete, :class => 'icon icon-del') %> + <%= link_to(l(:button_delete), project_path(project), :method => :delete, :class => 'icon icon-del', :onClick=>"delcfm()" ) %> <% end %> @@ -74,3 +74,11 @@ <% html_title(l(:label_project_plural)) -%> + + \ No newline at end of file diff --git a/app/views/attachments/_new_form.html.erb b/app/views/attachments/_new_form.html.erb index 38b471897..47f6fd202 100644 --- a/app/views/attachments/_new_form.html.erb +++ b/app/views/attachments/_new_form.html.erb @@ -23,6 +23,7 @@ <% end %> <% end %> +
    <% project = project %> <%= button_tag l(:button_browse), :type=>"button", :onclick=>"_file.click()",:onmouseover => 'this.focus()',:class => 'sub_btn', :style => ie8? ? 'display:none' : '' %> diff --git a/app/views/attachments/_project_file_links.html.erb b/app/views/attachments/_project_file_links.html.erb index b644fb9fa..3b76689f5 100644 --- a/app/views/attachments/_project_file_links.html.erb +++ b/app/views/attachments/_project_file_links.html.erb @@ -37,7 +37,7 @@ <% if options[:length] %> <%= link_to_short_attachment attachment, :class => ' link_file_board', :download => true,:length => options[:length] -%> <% else %> - + <%= link_to_short_attachment attachment, :class => ' link_file_board', :download => true -%> <% end %> <%if is_float%> diff --git a/app/views/attachments/file.html.erb b/app/views/attachments/file.html.erb index 75fa1858c..0ce174545 100644 --- a/app/views/attachments/file.html.erb +++ b/app/views/attachments/file.html.erb @@ -1,26 +1,38 @@ -

    <%=h @attachment.filename %>

    +
    +
    +
    +
    +
    +

    <%=h @attachment.filename %>

    -
    -

    <%= h("#{@attachment.description} - ") unless @attachment.description.blank? %> - <%= link_to_user(@attachment.author) %>, <%= format_time(@attachment.created_on) %>

    -

    <%= link_to_attachment @attachment, :text => l(:button_download), :download => true -%> - (<%= number_to_human_size @attachment.filesize %>)    - - <% if @attachment!=nil &&(@attachment.container_type == 'Document' || @attachment.container_type == 'WikiPage') && - User.current.allowed_to?({:controller => 'code_review', :action => 'update_diff_view'}, @attachment.project) %> - <%= l(:review_assignments)+":" %><%= link = link_to(l(:button_add), {:controller => 'code_review', - :action => 'assign', :action_type => 'attachment', - :id=>@attachment.project, - :change_id => '', :attachment_id => @attachment.id, - }, :class => 'icon icon-add') %> - <% end %> -

    -
    -  -<%= render :partial => 'common/file', :locals => {:content => @content, :filename => @attachment.filename} %> +
    +

    <%= h("#{@attachment.description} - ") unless @attachment.description.blank? %> + <%= link_to_user(@attachment.author) %>, <%= format_time(@attachment.created_on) %>

    +

    <%= link_to_attachment @attachment, :text => l(:button_download), :download => true -%> + (<%= number_to_human_size @attachment.filesize %>)    + + <% if @attachment!=nil &&(@attachment.container_type == 'Document' || @attachment.container_type == 'WikiPage') && + User.current.allowed_to?({:controller => 'code_review', :action => 'update_diff_view'}, @attachment.project) %> + <%= l(:review_assignments)+":" %><%= link = link_to(l(:button_add), {:controller => 'code_review', + :action => 'assign', :action_type => 'attachment', + :id=>@attachment.project, + :change_id => '', :attachment_id => @attachment.id, + }, :class => 'icon icon-add') %> + <% end %> +

    +
    +   + <%= render :partial => 'common/file', :locals => {:content => @content, :filename => @attachment.filename} %> + + <% html_title @attachment.filename %> -<% html_title @attachment.filename %> + <% content_for :header_tags do -%> + <%= stylesheet_link_tag "scm" -%> + <% end -%> +
    +
    +
    +
    +
    +
    -<% content_for :header_tags do -%> - <%= stylesheet_link_tag "scm" -%> -<% end -%> diff --git a/app/views/avatar/_new_avatar_form.html.erb b/app/views/avatar/_new_avatar_form.html.erb index 64abfbc30..2593bf1f5 100644 --- a/app/views/avatar/_new_avatar_form.html.erb +++ b/app/views/avatar/_new_avatar_form.html.erb @@ -2,10 +2,10 @@ <%= image_tag(url_to_avatar(source), id: "avatar_image", :width =>"60", :height =>"60",:alt=>"上传图片")%> <%#= link_to l(:button_delete_file),{:controller => :avatar,:action => :delete_image,:remote=>true,:source_type=> source.class,:source_id=>source.id},:confirm => l(:text_are_you_sure), :method => :post, :class => "upbtn fl" %> -<%= l(:button_upload_photo) %> +<%= l(:button_upload_photo) %> <%= file_field_tag 'avatar[image]', - :id => nil, - :class => 'upload_file', + :id => 'upload_course_logo', + :class => 'undis upload_file', :size => "1", :multiple => true, :data => { diff --git a/app/views/bids/edit.html.erb b/app/views/bids/edit.html.erb index da3d19267..554702d97 100644 --- a/app/views/bids/edit.html.erb +++ b/app/views/bids/edit.html.erb @@ -1,4 +1,5 @@ -<%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg' %> +<%= javascript_include_tag "/assets/kindeditor/kindeditor",'prettify','/assets/kindeditor/pasteimg' %> +<%= stylesheet_link_tag 'prettify'%> <%= labelled_form_for @bid,:html => { :multipart => true } do |f| %> <%= render :partial => 'new_homework_form', :locals => { :bid => @bid, :bid_id => "edit_bid_#{@bid.id}",:f=>f,:edit_mode => true} %> <% end %> diff --git a/app/views/boards/_course_show.html.erb b/app/views/boards/_course_show.html.erb index b8bbf3d63..db174f30e 100644 --- a/app/views/boards/_course_show.html.erb +++ b/app/views/boards/_course_show.html.erb @@ -37,7 +37,7 @@ <% @topics.each do |topic| %>
    <%= link_to image_tag(url_to_avatar(topic.author), :width=>"42",:height=>"42"), user_path(topic.author),:class =>'talkmain_pic fl' %> -
    +
    <% author = topic.author.to_s %>
    <%= link_to User.current.member_of_course?(@board.course) ? "#{topic.author.show_name}(#{topic.author.login})" : "#{topic.author}" , user_path(topic.author), @@ -48,7 +48,7 @@

      <%= h(topic.subject) %>

    <% if topic.course_editable_by?(User.current) %> - <%= l(:button_edit) %> <% end %> @@ -99,7 +99,7 @@ // } }); -
    +
    <%= topic.content.html_safe %> @@ -120,7 +120,7 @@ <%= l(:label_activity_time)%>:  <%= format_time topic.created_on %>
    - <%= l(:button_reply) %> + <%= l(:button_reply) %>
    @@ -165,13 +165,13 @@
    <%= link_to User.current.member_of_course?(@board.course) ? "#{message.author.show_name}(#{message.author.login})" : "#{message.author}", user_path(message.author),:class => 'fl c_orange f14 ' %>
    -
    +
    <%= textAreailizable message,:content,:attachments => message.attachments %>

    - <%= format_time(message.created_on) %> + <%= format_time(message.created_on) %> <%= link_to( l(:button_delete), @@ -179,13 +179,13 @@ :method => :post, :data => {:confirm => l(:text_are_you_sure)}, :title => l(:button_delete), - :class => ' c_dblue fr f14' + :class => ' linkBlue fr f12' ) if message.course_destroyable_by?(User.current) %> <%= link_to( l(:button_reply), 'javascript:;', :nhname =>'showbtn_child_reply', - :class => ' c_dblue fr f14', + :class => ' linkBlue fr f12', :style => 'margin-right: 10px;', 'data-topic-id' =>message.id, :title => l(:button_reply)) if !topic.locked? && authorize_for('messages', 'reply') %> diff --git a/app/views/boards/_form.html.erb b/app/views/boards/_form.html.erb index 47ae0672d..a4f58dcc3 100644 --- a/app/views/boards/_form.html.erb +++ b/app/views/boards/_form.html.erb @@ -1,7 +1,7 @@ <%= error_messages_for @board %>
    -

    +

    <%= f.text_field :name, :required => true %>

    diff --git a/app/views/boards/_project_show.html.erb b/app/views/boards/_project_show.html.erb index bc69e2666..4f022261f 100644 --- a/app/views/boards/_project_show.html.erb +++ b/app/views/boards/_project_show.html.erb @@ -51,9 +51,9 @@ :data => {:confirm => l(:text_are_you_sure)}, :class => 'talk_edit fr', :style => ' margin-right: 10px;') if topic.destroyable_by?(User.current) %> - <% if topic.sticky? %> - <%= l(:label_board_sticky)%> - <% end %> + <%# if topic.sticky? %> + + <%# end %>

    -
    +
    <%= topic.content.html_safe %> @@ -150,7 +150,7 @@
    <%= link_to_user_header message.author,false,:class => 'fl c_orange f14 ' %>
    -
    +
    <%= textAreailizable message,:content,:attachments => message.attachments %>
    diff --git a/app/views/boards/show.html.erb b/app/views/boards/show.html.erb index 5520f526d..a9c0e9101 100644 --- a/app/views/boards/show.html.erb +++ b/app/views/boards/show.html.erb @@ -1,12 +1,5 @@ + <% if activity %> + <% act = activity.course_act %> + <% case activity.course_act_type.to_s %> + <% when 'HomeworkCommon' %> + <%= render :partial => 'users/course_homework', :locals => {:activity => act, :user_activity_id => activity.id} %> + <% when 'News' %> + <%= render :partial => 'users/course_news', :locals => {:activity => act, :user_activity_id => activity.id} %> + <% when 'Message' %> + <%= render :partial => 'users/course_message', :locals => {:activity => act, :user_activity_id => activity.id} %> + <% when 'Poll' %> + <%= render :partial => 'users/course_poll', :locals => {:activity => act, :user_activity_id => activity.id} %> + <% when 'JournalsForMessage' %> + <%= render :partial => 'users/course_journalsformessage', :locals => {:activity => act, :user_activity_id => activity.id} %> + <% when 'Attachment' %> + <%= render :partial => 'users/course_attachment', :locals => {:activity => act, :user_activity_id => activity.id} %> + <% when 'Course' %> + <%= render :partial => 'users/course_create', :locals => {:activity => act, :user_activity_id => activity.id} %> + <% end %> + <% end %> + <% end %> +<% end %> + +<% if course_activities.count == 10 %> +
    展开更多<%= link_to "", course_activity_path(@course.id, :type => type, :page => page), :id => "more_course_activities_link", :remote => "true", :class => "none" %>
    +<% end %> + + \ No newline at end of file diff --git a/app/views/courses/_courses_jours.html.erb b/app/views/courses/_courses_jours.html.erb index cedc05f4b..12dd67c91 100644 --- a/app/views/courses/_courses_jours.html.erb +++ b/app/views/courses/_courses_jours.html.erb @@ -10,10 +10,13 @@ div.respond-form .reply_btn{margin-left:565px;margin-top:5px;} div.recall_con{width:570px;} div.recall_con .reply_btn{margin-left:525px;margin-top:5px;} + /*.ke-container{height: 80px !important;}*/ -<%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg' %> -
    - <%# reply_allow = JournalsForMessage.create_by_user? User.current %> +<%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg',"init_KindEditor" %> + +

    <%= l(:label_leave_message) %>

    <% if !User.current.logged?%> @@ -23,21 +26,15 @@
    <% else %> - <%= form_for('new_form', :method => :post, - :url => {:controller => 'words', :action => 'leave_course_message'},:html => {:id=>'leave_message_form'}) do |f|%> - <%= hidden_field_tag :asset_id,params[:asset_id],:required => false,:style => 'display:none' %> - <%#= f.kindeditor 'course_message',:height => '140px;',:editor_id => 'leave_message_editor',:input_html=>{:id => "leave_meassge",:style => "resize: none;", - :placeholder => "#{l(:label_welcome_my_respond)}",:maxlength => 250}%> - -

    - <% end %> -
    -
    -
    - 取  消 - - <%= l(:button_leave_meassge)%> - +
    + <%= form_for('new_form',:url => {:controller => 'words', :action => 'leave_course_message'},:method => "post") do |f|%> + <%= hidden_field_tag :asset_id,params[:asset_id],:required => false,:style => 'display:none' %> + +

    +
    + 取消 + 留言 + <% end%>
    <% end %>
    @@ -54,106 +51,6 @@ diff --git a/app/views/courses/_join_private_course.html.erb b/app/views/courses/_join_private_course.html.erb index 934a4eb33..4cc8b9fbf 100644 --- a/app/views/courses/_join_private_course.html.erb +++ b/app/views/courses/_join_private_course.html.erb @@ -57,6 +57,8 @@ :id => 'new-watcher-form') do %>
    • + + 课 程 ID: diff --git a/app/views/courses/_new_groups_name.html.erb b/app/views/courses/_new_groups_name.html.erb index fc2c5a62d..6ffbb6dd2 100644 --- a/app/views/courses/_new_groups_name.html.erb +++ b/app/views/courses/_new_groups_name.html.erb @@ -21,7 +21,7 @@ 删除班级 <% end%> - + 编辑班级 <% end %> diff --git a/app/views/courses/_set_join.js.erb b/app/views/courses/_set_join.js.erb index f880ce945..5476e7ff0 100644 --- a/app/views/courses/_set_join.js.erb +++ b/app/views/courses/_set_join.js.erb @@ -1,17 +1,19 @@ <% if object_id%> $("#join_in_course_header").html("<%= escape_javascript(join_in_course_header(course, user)) %>"); - $("#try_join_course_link").replaceWith(" 'index',:course=>course.id, :host=>Setting.host_course)%>' target='_blank' class='blue_n_btn fr mt20'>提交作品"); <% end %> <% if @state %> <% if @state == 0 %> alert("加入成功"); hideModal($("#popbox02")); + $("#try_join_course_link").replaceWith(" 'index',:course=>course.id, :host=>Setting.host_course)%>' target='_blank' class='blue_n_btn fr mt20'>提交作品"); + window.location.href= "http://"+"<%= Setting.host_name%>"+"/courses/" + "<%= course.id%>" <% elsif @state == 1 %> alert("密码错误"); <% elsif @state == 2 %> alert("课程已过期\n请联系课程管理员重启课程。(在配置课程处)"); <% elsif @state == 3 %> alert("您已经加入了课程"); + window.location.href= "http://"+"<%= Setting.host_name%>"+"/courses/" + "<%= course.id%>" <% elsif @state == 4 %> alert("您加入的课程不存在"); <% elsif @state == 5 %> diff --git a/app/views/courses/new.html.erb b/app/views/courses/new.html.erb index 75979d9f3..d2c17917e 100644 --- a/app/views/courses/new.html.erb +++ b/app/views/courses/new.html.erb @@ -5,6 +5,8 @@
        <%= labelled_form_for @course do |f| %>
      • + + @@ -50,7 +52,7 @@
      • 提交 - 取消 + <%= link_to "取消",user_activities_path(User.current.id),:class => "blue_btn grey_btn fl c_white"%>
      • <% end%> diff --git a/app/views/courses/search.html.erb b/app/views/courses/search.html.erb index 98b056487..e7f344df2 100644 --- a/app/views/courses/search.html.erb +++ b/app/views/courses/search.html.erb @@ -20,12 +20,12 @@ <% end %> <% end %> - + @@ -39,17 +39,17 @@ <% end %>
    -<% if @courses.size == 0 %> -<%= render :partial => 'layouts/no_content'%> +<% if @courses && !@courses.empty? %> +
    + <%= render_course_hierarchy(@courses)%> +
    <% else %> -
    - <%= render_course_hierarchy(@courses)%> -
    + <%= render :partial => 'layouts/no_content'%> <% end %> diff --git a/app/views/courses/settings.html.erb b/app/views/courses/settings.html.erb index 4ca8d3d43..a462db79d 100644 --- a/app/views/courses/settings.html.erb +++ b/app/views/courses/settings.html.erb @@ -20,6 +20,8 @@
  • + + diff --git a/app/views/courses/show.html.erb b/app/views/courses/show.html.erb index 654c25a42..78f44aa31 100644 --- a/app/views/courses/show.html.erb +++ b/app/views/courses/show.html.erb @@ -1,129 +1,31 @@ -
    -<% if @controller_name=='ActivityNotifys' %> - <%= l(:label_activity)%> -

    与我相关 - -

    - -<% else %> -

    <%= l(:label_activity)%>

    - <% if User.current.logged? %> - 与我相关 - - - <% end %> -<% end %> -
    - -<% if @events_by_day != nil && @events_by_day.size >0 %> - <% @events_by_day.keys.sort.reverse.each do |day| %> - <% sort_activity_events(@events_by_day[day]).each do |e, in_group| -%> -
    - - <%= image_tag(url_to_avatar(e.event_author), :width => "42", :height => "42") %> - -
    - <%= link_to_user_header(e.event_author,false,:class => 'problem_name c_orange fl') if e.respond_to?(:event_author) %> - <%= link_to_user_header("(#{e.event_author})", @canShowRealName,:class => 'problem_name c_orange fl') if @canShowRealName && e.respond_to?(:event_author) %> -   - <%= l(:label_new_activity) %>: - <% - link = (e.event_type.eql?("attachment")&&e.container.kind_of?(Course)) ? course_files_path(e.container) : - (e.event_type.eql?("bid") ? homework_course_path(@course) : - (e.event_type.eql?("message") || e.event_type.eql?("reply") ? - course_boards_path(@course,:topic_id => e.id,:parent_id=>(e.parent_id ? e.parent_id : e.id)) : e.event_url)) - %> - <%= link_to "#{eventToLanguageCourse(e.event_type, @course)} "<< format_activity_title(e.event_title), link, - :class => "problem_tit c_dblue fl fb",'data-type'=>e.event_type, - 'data-notify-id'=>(e.respond_to?('get_notify_id') ? e.get_notify_id : ''),:nhname=>"nh_act_link", - 'data-href'=>(course_activity_notifys_path(@course)+"/chang_read_flag?an_id="+(e.respond_to?('get_notify_id') ? e.get_notify_id : '').to_s)%> - <%if @controller_name=='ActivityNotifys' && e.get_notify_is_read!=1%> - - <%end%> -
    -

    <%= e.event_description.html_safe %> -
    -

    - <%= l :label_activity_time %> : <%= format_activity_day(day) %> <%= format_time(e.event_datetime, false) %> -

    - <%= link_to_attachments_course(e) if e.class.to_s == "News" %> -
    -
    -
    - <% end%> - <% end%> -<% elsif @controller_name=='ActivityNotifys' %> -

    <%= l(:label_no_data) %>

    -<% end%> -<% if @obj_pages.next_page.nil? && @controller_name!='ActivityNotifys' %> -
    - - <%= image_tag(url_to_avatar(@user), :width => "42", :height => "42") %> - -
    - <%= link_to_user_header(@user,false,:class => 'problem_name c_orange fl') %> - <%= link_to_user_header("(#{@user})", @canShowRealName,:class => 'problem_name c_orange fl') if @canShowRealName %> - <%= l(:label_user_create_project) %>: - <%= link_to @course.name,course_path(@course),:class => "problem_tit c_dblue fl fb"%> -
    -

    -
    - <%= l :label_create_time %> : <%= format_time(@course.created_at) %> -

    -
    -
    -
    -<% end%> -
      - <%= pagination_links_full @obj_pages, @obj_count, :per_page_links => false, :remote => false, :flag => true%> -
    -
    - + + +
    +
    +
    课程动态
    +
      +
    • +
        +
      • +
          +
        • <%= link_to "全部动态", {:controller => "courses", :action => "show", :type => nil}, :class =>"homepagePostTypeAll postTypeGrey"%>
        • +
        • <%= link_to "作业动态", {:controller => "courses", :action => "show", :type => "homework"}, :class => "homepagePostTypeAssignment postTypeGrey"%>
        • +
        • <%= link_to "通知动态", {:controller => "courses", :action => "show", :type => "news"}, :class => "homepagePostTypeNotice postTypeGrey"%>
        • +
        • <%= link_to "资源库动态", {:controller => "courses", :action => "show", :type => "attachment"}, :class => "homepagePostTypeResource resourcesGrey"%>
        • +
        • <%= link_to "论坛动态", {:controller => "courses", :action => "show", :type => "message"}, :class => "homepagePostTypeForum postTypeGrey"%>
        • +
        • <%= link_to "留言动态", {:controller => "courses", :action => "show", :type => "journalsForMessage"}, :class => "homepagePostTypeMessage postTypeGrey"%>
        • +
        • <%= link_to "问卷动态", {:controller => "courses", :action => "show", :type => "poll"}, :class => "homepagePostTypeQuiz postTypeGrey"%>
        • +
        +
      • +
      +
    • +
    +
    + <%= render :partial => 'courses/course_activity', :locals => {:course_activities => @course_activities,:page => 0,:type => @type} %> +
    \ No newline at end of file diff --git a/app/views/courses/show.js.erb b/app/views/courses/show.js.erb new file mode 100644 index 000000000..3f82dcf3a --- /dev/null +++ b/app/views/courses/show.js.erb @@ -0,0 +1 @@ +$("#show_more_course_activities").replaceWith("<%= escape_javascript( render :partial => 'courses/course_activity',:locals => {:course_activities => @course_activities, :page => @page,:type => @type} )%>"); diff --git a/app/views/courses/show_old.html.erb b/app/views/courses/show_old.html.erb new file mode 100644 index 000000000..608d41f9d --- /dev/null +++ b/app/views/courses/show_old.html.erb @@ -0,0 +1,83 @@ +
    +

    <%= l(:label_activity)%>

    +
    + +<%@course_activities.each do |activity|%> +
    + + <%= image_tag(url_to_avatar(activity.user), :width => "42", :height => "42") %> + +
    + <%= link_to_user_header(activity.user,false,:class => 'problem_name c_orange fl') %> +   + <%= activity.course_act_type == "Course" ? "创建了课程" : l(:label_new_activity) %>: + <%#= link_to "#{eventToLanguageCourse(e.event_type, @course)} "<< format_activity_title(e.event_title), link, + :class => "problem_tit c_dblue fl fb",'data-type'=>e.event_type, + 'data-notify-id'=>(e.respond_to?('get_notify_id') ? e.get_notify_id : ''),:nhname=>"nh_act_link", + 'data-href'=>(course_activity_notifys_path(@course)+"/chang_read_flag?an_id="+(e.respond_to?('get_notify_id') ? e.get_notify_id : '').to_s)%> + <%#if @controller_name=='ActivityNotifys' && e.get_notify_is_read!=1%> + + <%#end%> + <%= link_to course_activity_link activity%> +
    +

    + <%= course_activity_desc activity%> +
    +

    + <%= activity.course_act_type == "Course" ? l(:label_create_time) : l(:label_activity_time) %> : <%= format_time(activity.created_at) %> +

    + <%= link_to_attachments_course(activity.course_act) if activity.course_act_type.to_s == "News" %> +
    +
    +
    +<% end%> + +
      + <%= pagination_links_full @obj_pages, @obj_count, :per_page_links => false, :remote => false, :flag => true%> +
    +
    + + diff --git a/app/views/files/_course_list.html.erb b/app/views/files/_course_list.html.erb index 353d19dab..9e88cb2fd 100644 --- a/app/views/files/_course_list.html.erb +++ b/app/views/files/_course_list.html.erb @@ -3,13 +3,13 @@

    共有 <%= all_attachments.count%> 个资源

    <% if order == "asc" %> - 按 <%= link_to "时间",params.merge(:sort=>"created_on:desc"),:class => "f_b c_grey",:remote => @is_remote %><%= render partial: 'arrow_show',locals: { sort: sort,order:order,current:"created_on"} %> /  - <%= link_to "下载次数",params.merge(:sort=>"downloads:desc"),:class => "f_b c_grey",:remote => @is_remote %><%= render partial: 'arrow_show',locals: { sort: sort,order:order,current:"downloads"} %> /  - <%= link_to "引用次数",params.merge(:sort=>"quotes:desc"),:class => "f_b c_grey",:remote => @is_remote %><%= render partial: 'arrow_show',locals: { sort: sort,order:order,current:"quotes"} %> 排序 + 按 <%= link_to "时间",params.merge(:sort=>"created_on:desc"),:class => "f_b c_grey",:remote => @is_remote %><%= render partial: 'files/arrow_show',locals: { sort: sort,order:order,current:"created_on"} %> /  + <%= link_to "下载次数",params.merge(:sort=>"downloads:desc"),:class => "f_b c_grey",:remote => @is_remote %><%= render partial: 'files/arrow_show',locals: { sort: sort,order:order,current:"downloads"} %> /  + <%= link_to "引用次数",params.merge(:sort=>"quotes:desc"),:class => "f_b c_grey",:remote => @is_remote %><%= render partial: 'files/arrow_show',locals: { sort: sort,order:order,current:"quotes"} %> 排序 <% else %> - 按 <%= link_to "时间",params.merge(:sort=>"created_on:asc"),:class => "f_b c_grey" ,:remote => @is_remote %><%= render partial: 'arrow_show',locals: { sort: sort,order:order,current:"created_on"} %> /  - <%= link_to "下载次数",params.merge(:sort=>"downloads:asc"),:class => "f_b c_grey",:remote => @is_remote %><%= render partial: 'arrow_show',locals: { sort: sort,order:order,current:"downloads"} %>  /  - <%= link_to "引用次数",params.merge(:sort=>"quotes:asc"),:class => "f_b c_grey",:remote => @is_remote %><%= render partial: 'arrow_show',locals: { sort: sort,order:order,current:"quotes"} %> 排序 + 按 <%= link_to "时间",params.merge(:sort=>"created_on:asc"),:class => "f_b c_grey" ,:remote => @is_remote %><%= render partial: 'files/arrow_show',locals: { sort: sort,order:order,current:"created_on"} %> /  + <%= link_to "下载次数",params.merge(:sort=>"downloads:asc"),:class => "f_b c_grey",:remote => @is_remote %><%= render partial: 'files/arrow_show',locals: { sort: sort,order:order,current:"downloads"} %>  /  + <%= link_to "引用次数",params.merge(:sort=>"quotes:asc"),:class => "f_b c_grey",:remote => @is_remote %><%= render partial: 'files/arrow_show',locals: { sort: sort,order:order,current:"quotes"} %> 排序 <% end %>

  • @@ -55,6 +55,7 @@
    + <%= render :partial => 'tags/tag_new', :locals => {:obj => file, :object_flag => "6",:tag_name => @tag_name} %> <%= render :partial => 'tags/tag_add', :locals => {:obj => file, :object_flag => "6",:tag_name => @tag_name} %>
    diff --git a/app/views/files/_project_file_list.html.erb b/app/views/files/_project_file_list.html.erb index 9f9e86cff..6dc5b6753 100644 --- a/app/views/files/_project_file_list.html.erb +++ b/app/views/files/_project_file_list.html.erb @@ -44,6 +44,7 @@
    + <%= render :partial => 'tags/tag_new', :locals => {:obj => file, :object_flag => "6"} %> <%= render :partial => 'tags/tag_add', :locals => {:obj => file, :object_flag => "6"} %>
    diff --git a/app/views/files/_tag_yun.html.erb b/app/views/files/_tag_yun.html.erb index 9db34ece4..bdf581baa 100644 --- a/app/views/files/_tag_yun.html.erb +++ b/app/views/files/_tag_yun.html.erb @@ -1,9 +1,17 @@ + + 全部 <% unless tag_list.nil?%> <% tag_list.each do |k,v|%> <% if tag_name && tag_name == k%> - <%= k%>×<%= v%> + + <%= k%>(<%= v%>) <% else%> - <%= k%>×<%= v%> + + <%= k%>(<%= v%>) <% end%> <% end%> <% end%> \ No newline at end of file diff --git a/app/views/files/create.js.erb b/app/views/files/create.js.erb index a1c278a7a..81810344e 100644 --- a/app/views/files/create.js.erb +++ b/app/views/files/create.js.erb @@ -24,6 +24,8 @@ $('#upload_file_div').slideToggle('slow'); <% if @project %> closeModal(); $("#resource_list").html('<%= j(render partial: "project_file_new" ,locals: {project: @project}) %>'); + $("#project_files_count_info").html("<%= @all_attachments.count%>"); + $("#project_files_count_nav").html("(<%= @all_attachments.count%>)") // 添加文件上传成功提示 <% unless params[:attachments].nil? %> var div = $('
    文件上传成功!
    '); diff --git a/app/views/files/index.html.erb b/app/views/files/index.html.erb index aefa1a5a9..656baaf63 100644 --- a/app/views/files/index.html.erb +++ b/app/views/files/index.html.erb @@ -223,6 +223,87 @@ }); } + <% if @course %> + var tagNameHtml; //当前双击的链接的父节点的html + var tagName; //标签的值 + var parentCssBorder; //当前双击的链接的父节点 + var ele; //当前双击的链接 + var tagId; //标签的id + var taggableType; //被标签的类型 + //这里renameTag有两种情况,一种是改变某个资源的tag名称。如果其他资源也有这个tag。则新增一个改变后的tag名 + //第二种是改变某个tag名称。其他所有的资源如果拥有这个tag。那么对应的tag名也要改掉。 + //目前这两种依据 的来源就是 是否 传了参数 id。如果有id。就指定了资源id,就是第一种情况。如果没有id。就是第二种情况 + function rename_tag(domEle,name,id,type){ + isdb = true; //这是双击 + //clearTimeout(clickFunction); + if(domEle.children().get(0) != undefined ){ //已经是编辑框的情况下不要动 + return; + } + tagNameHtml = domEle.parent().html() + tagName = name; + parentCssBorder = domEle.parent().css("border"); + ele = domEle; + tagId = id; + taggableType = type; + width = parseInt(domEle.css('width').replace('px','')) >=100 ? parseInt(domEle.css('width').replace('px','')) : 100 + domEle.html(''); + domEle.parent().css("border","1px solid #ffffff"); + $("#renameTagName").focus(); + } + //监听所有的单击事件 + $(function(){ + $("#renameTagName").live("blur",function(){ + updateTagName(); + }).live("keypress",function(e){ + if (e.keyCode == '13') { + updateTagName(); + } + }); + }); + + //执行修改TAGName方法 + function updateTagName(){ + if(isdb){ + isdb = false; + if($("#renameTagName").val() == tagName){ //如果值一样,则恢复原来的状态 + ele.parent().css("border",""); + ele.parent().html(tagNameHtml); + + } + else{ + $.post( + '<%= update_tag_name_path %>', + {"taggableId": tagId, "taggableType": taggableType, "tagName": tagName, "renameName": $("#renameTagName").val().trim(),"courseId":<%= @course.id%>} + ); + } + } + } +// $(document.body).click(function(e){ +// isdb = false; //这是单击 +// node = document.elementFromPoint(e.clientX, e.clientY); +// if(node.tagName == "INPUT"){ //如果是输入框的聚焦,那么就不要进行下去了 +// isdb = true; //为了防止在编辑的时候又去单击其他tag去过滤。导致tag过滤不可用 +// return; +// } +// if($("#renameTagName")[0] != undefined ){//存在renameTagName,则处于编辑状态 +// if($("#renameTagName").val().trim() == tagName){ //如果值一样,则恢复原来的状态 +// ele.parent().css("border",""); +// ele.parent().html(tagNameHtml); +// +// }else{ //否则就要更新tag名称了 +//// if(confirm("是否将标签改为 "+ $("#renameTagName").val().trim())){ 去掉询问 +// $.post( +// '<%= update_tag_name_path %>', +// {"taggableId": tagId, "taggableType": taggableType, "tagName": tagName, "renameName": $("#renameTagName").val().trim(),"courseId":<%= @course.id%>} +// ) +//// }else{ +//// ele.parent().css("border",""); +//// ele.parent().html(tagNameHtml); +//// } +// } +// } +// }); + <%end %> diff --git a/app/views/forums/_file_form.html.erb b/app/views/forums/_file_form.html.erb new file mode 100644 index 000000000..560afc6d9 --- /dev/null +++ b/app/views/forums/_file_form.html.erb @@ -0,0 +1,79 @@ + +
    + +<% if defined?(container) && container && container.saved_attachments %> + <% container.attachments.each_with_index do |attachment, i| %> + + <%= text_field_tag("attachments[p#{i}][filename]", attachment.filename, :class => 'filename readonly', :readonly => 'readonly') %><%= text_field_tag("attachments[p#{i}][description]", attachment.description, :maxlength => 254, :placeholder => l(:label_optional_description), :class => 'description', :style => "display: inline-block;") %><%= l(:field_is_public) %>: + <%= check_box_tag("attachments[p#{i}][is_public_checkbox]", attachment.is_public, attachment.is_public == 1 ? true : false, :class => 'is_public') %> + <%= if attachment.id.nil? + #待补充代码 + else + link_to(' '.html_safe, attachment_path(attachment, :attachment_id => "p#{i}", :format => 'js'), :method => 'delete', :remote => true, :class => 'remove-upload') + end + %> + <%#= render :partial => 'tags/tag', :locals => {:obj => attachment, :object_flag => "6"} %> + + <%= hidden_field_tag "attachments[p#{i}][token]", "#{attachment.token}" %> + +
    + <% end %> + <% container.saved_attachments.each_with_index do |attachment, i| %> + + <%= text_field_tag("attachments[p#{i}][filename]", attachment.filename, :class => 'filename readonly', :readonly => 'readonly') %> + <%= text_field_tag("attachments[p#{i}][description]", attachment.description, :maxlength => 254, :placeholder => l(:label_optional_description), :class => 'description', :style => "display: inline-block;") %> + <%= l(:field_is_public) %>: + <%= check_box_tag("attachments[p#{i}][is_public_checkbox]", attachment.is_public, attachment.is_public == 1 ? true : false, :class => 'is_public') %> + <%= if attachment.id.nil? + #待补充代码 + else + link_to(' '.html_safe, attachment_path(attachment, :attachment_id => "p#{i}", :format => 'js'), :method => 'delete', :remote => true, :class => 'remove-upload') + end + %> + <%#= render :partial => 'tags/tag', :locals => {:obj => attachment, :object_flag => "6"} %> + + <%= hidden_field_tag "attachments[p#{i}][token]", "#{attachment.token}" %> + +
    + <% end %> +<% end %> +
    + <% project = project %> +
    + + <%#= button_tag "浏览", :type=>"button", :onclick=>"CompatibleSend();" %> + + <%#= button_tag "文件浏览", :type=>"button", :onclick=>"$('#_file').click();",:onmouseover => 'this.focus()',:class => 'AnnexBtn fl mt3' %> + 上传附件 + <%= file_field_tag 'attachments[dummy][file]', + :id => '_file', + :class => 'file_selector', + :multiple => true, + :onchange => 'addInputFiles(this);', + :style => ie8? ? '' : 'display:none', + :data => { + :max_file_size => Setting.attachment_max_size.to_i.kilobytes, + :max_file_size_message => l(:error_attachment_too_big, :max_size => number_to_human_size(Setting.attachment_max_size.to_i.kilobytes)), + :max_concurrent_uploads => Redmine::Configuration['max_concurrent_ajax_uploads'].to_i, + :upload_path => uploads_path(:format => 'js', :project => project), + :description_placeholder => l(:label_optional_description), + :field_is_public => l(:field_is_public), + :are_you_sure => l(:text_are_you_sure), + :file_count => l(:label_file_count), + :delete_all_files => l(:text_are_you_sure_all) + } %> + + + + + <%#= number_to_human_size(Setting.attachment_max_size.to_i.kilobytes) %> + + + + <% content_for :header_tags do %> + <%= javascript_include_tag 'attachments' %> + <% end %> +
    \ No newline at end of file diff --git a/app/views/forums/_form_edit_mode.html.erb b/app/views/forums/_form_edit_mode.html.erb index a9bb05f79..ade5a24c4 100644 --- a/app/views/forums/_form_edit_mode.html.erb +++ b/app/views/forums/_form_edit_mode.html.erb @@ -1,49 +1,26 @@ - - -
    - <%= labelled_form_for(@forum) do |f| %> - <% if @forum.errors.any? %> - - <% end %> -
    -
    - <%= f.text_field :name, :required => true, :style => 'width: 100%;', :class => 'create-share', :maxlength => 50%> -
    -
    - <% if User.current.logged? && User.current.admin? %> - <% if @forum.safe_attribute? 'sticky' %> - <%= f.check_box :sticky %> - <%= label_tag 'message_sticky', l(:label_board_sticky) %> - <% end %> - <% if @forum.safe_attribute? 'locked' %> - <%= f.check_box :locked %> - <%= label_tag 'message_locked', l(:label_board_locked) %> - <% end %> +
    + <%= labelled_form_for(@forum) do |f| %> + +
    + +
    +
    + +
    +
    + + +
    +
    <% end %>
    -
    -

    - <%= f.kindeditor :description, :required => true,:owner_id => @forum.id,:owner_type => 2 %> -

    - -

    - (<%= l(:label_forums_max_length) %>) -

    -
    -
    - <%= submit_tag l(:button_submit) %> - <%= link_to l(:button_back), forums_path ,:style => 'font-size: 14px; padding: 0px 3px;' %> -
    - <% end %> -
    +
    \ No newline at end of file diff --git a/app/views/forums/_forum_form.html.erb b/app/views/forums/_forum_form.html.erb new file mode 100644 index 000000000..9888b674e --- /dev/null +++ b/app/views/forums/_forum_form.html.erb @@ -0,0 +1,15 @@ + +
    + +
    +
    + +
    +
    + + +
    +
    \ No newline at end of file diff --git a/app/views/forums/_forum_list.html.erb b/app/views/forums/_forum_list.html.erb index ac27235eb..ec9f4f7de 100644 --- a/app/views/forums/_forum_list.html.erb +++ b/app/views/forums/_forum_list.html.erb @@ -1,57 +1,38 @@ - -
    + <% if forums.any? %> <% forums.each do |forum| %> -
    -
    - <%= forum.creator.nil? ? (link_to image_tag(url_to_avatar(forum.creator), :class => "avatar")) : (link_to image_tag(url_to_avatar(forum.creator), :class => "avatar"), user_path(forum.creator)) %> -
    -
    - - - - - - - - - - -
    -

    - <%= link_to h(forum.name), forum_path(forum) %> -

    -
    -

    - <%= textAreailizable forum.description%> -

    -
    -

    - <%= authoring forum.created_at, forum.creator %> -

    -
    -
    -
    - - - - - - - - - -
    - <%= link_to (forum.memo_count), forum_path(forum) %> - - <%= link_to (forum.topic_count), forum_path(forum) %> -
    回答帖子
    -
    -
    +
    +
    + <%= link_to image_tag(url_to_avatar(forum.creator),:width=>75,:height => 75 ),user_path( forum.creator) %> +
    +
    +
    + <%=forum.name.gsub(/(\r\n)/,'
    ').html_safe %>
    + <%#= link_to forum.name.gsub(/(\r\n|\s+)/,'
    '), forum_path(forum),:class=>"f16 linkBlue" %> +
    +
    <%= textAreailizable forum.description%>
    + + +
    +
    +
    + + <%= link_to ( forum.topic_count), forum_path(forum),:class=>"linkGrey5 fb" %> +
    +
    帖子
    +
    +
    +
    +
    + + <%= link_to (forum.memo_count), forum_path(forum),:class=>"linkGrey5 fb" %> +
    +
    回答
    +
    +
    +
    <% end %> - + <% else %> -<% end %> -
    \ No newline at end of file + <%= render :partial => "layouts/no_content" %> +<% end %> \ No newline at end of file diff --git a/app/views/forums/_forum_tag_list.html.erb b/app/views/forums/_forum_tag_list.html.erb new file mode 100644 index 000000000..b074cbca3 --- /dev/null +++ b/app/views/forums/_forum_tag_list.html.erb @@ -0,0 +1,8 @@ +<% forum.tag_list.each do |tag|%> + +<% end %> \ No newline at end of file diff --git a/app/views/forums/_post_banner.html.erb b/app/views/forums/_post_banner.html.erb new file mode 100644 index 000000000..797b43245 --- /dev/null +++ b/app/views/forums/_post_banner.html.erb @@ -0,0 +1,33 @@ + + +
    综合 + <% if order_type=='reorder_complex' && order_str == 'desc' %> + + <% elsif order_type=='reorder_complex' && order_str == 'asc' %> + + <% else %> + + <% end %> +
    +
    人气 + <% if order_type=='reorder_popu' && order_str == 'desc' %> + + <% elsif order_type=='reorder_popu' && order_str == 'asc' %> + + <% else %> + + <% end %> +
    +
    时间 + <% if order_type=='reorder_time' && order_str == 'desc' %> + + <% elsif order_type=='reorder_time' && order_str == 'asc' %> + + <% else %> + + <% end %> +
    + +
    \ No newline at end of file diff --git a/app/views/forums/_show_topics.html.erb b/app/views/forums/_show_topics.html.erb index f8679cefa..bb8a91b69 100644 --- a/app/views/forums/_show_topics.html.erb +++ b/app/views/forums/_show_topics.html.erb @@ -1,47 +1,32 @@ - -
    共有 <%=link_to @forum.memos.count %> 个贴子
    <% if memos.any? %> <% memos.each do |topic| %> - - - - - -
    - <%= link_to image_tag(url_to_avatar(topic.author), :class => "avatar"), user_path(topic.author) if topic.author%> - - - - - - - - - - - - -
    <%= link_to h(topic.subject), forum_memo_path(topic.forum, topic) %> - - - - - - - -
    <%= link_to (topic.replies_count), forum_memo_path(topic.forum, topic) %>
    回答
    <%= authoring topic.created_at, topic.author %> - - <% author = topic.last_reply.try(:author)%> - <% if author%> - 最后回复:<%=link_to_user author %> - <% end%> - -
    -
    -
    +
    +
    + + <%= link_to image_tag(url_to_avatar(topic.author), :width => 50,:height => 50,:alt => '贴吧图片'), user_path(topic.author) if topic.author%> +
    +
    + +
    <%= topic.content.html_safe%> + +
    + <% author = topic.last_reply.try(:author)%> + <% if author%> +
    最后回复:<%= author.name%>
    +
    <%= format_date(topic.last_reply.created_at)%>
    + <% end%> + +
    +
    + + <%= link_to (topic.replies_count), forum_memo_path(topic.forum, topic),:target =>'_blank',:class=>'linkGrey2' %> + <%= get_praise_num(topic)%> +
    +
    +
    <% end %> - + <% else %>

    <%= l(:label_no_data) %>

    <% end %> diff --git a/app/views/forums/create.js.erb b/app/views/forums/create.js.erb new file mode 100644 index 000000000..be99d724a --- /dev/null +++ b/app/views/forums/create.js.erb @@ -0,0 +1,6 @@ +<%if @save_flag%> +$('#new_forum_div').slideToggle();$('#create_btn').parent().slideToggle(); +$('#reorder_time').click(); +<%else%> + $("#error").html("<%= @forum.errors.full_messages[0]%>").show(); +<%end %> \ No newline at end of file diff --git a/app/views/forums/delete_forum_tag.js.erb b/app/views/forums/delete_forum_tag.js.erb new file mode 100644 index 000000000..5080b3bdd --- /dev/null +++ b/app/views/forums/delete_forum_tag.js.erb @@ -0,0 +1,2 @@ +$("#forum_tag_list").html("<%= escape_javascript( render :partial=>'forum_tag_list',:locals=>{:forum=>@forum}) %>"); +$('#add_tag01').hide(); \ No newline at end of file diff --git a/app/views/forums/edit.html.erb b/app/views/forums/edit.html.erb index 0a40120c7..1fcbc6cab 100644 --- a/app/views/forums/edit.html.erb +++ b/app/views/forums/edit.html.erb @@ -1,4 +1,78 @@ - -

    编辑讨论区

    -<%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg' %> + +<%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg' ,'new_user' %> + <%= render 'form_edit_mode' %> + \ No newline at end of file diff --git a/app/views/forums/index.html.erb b/app/views/forums/index.html.erb index 18ac7f752..c2997ac25 100644 --- a/app/views/forums/index.html.erb +++ b/app/views/forums/index.html.erb @@ -1,48 +1,177 @@ -<% @nav_dispaly_home_path_label = 1 - @nav_dispaly_main_course_label = 1 - @nav_dispaly_main_project_label = 1 - @nav_dispaly_main_contest_label = 1 %> - -
    - - - - - - - - - - - -
    公共贴吧 - - <%= l(:label_user_location) %> : - - - <% if User.current.logged? %> - <%= link_to( l(:label_forum_new), new_forum_path, :class => 'icon icon-add') %> - <% end %> - - -
    - - <%= link_to request.host()+"/forums", forums_path %> - - - <%= link_to l(:field_homepage), home_path %> > - <%= link_to "公共贴吧", forums_path %> -
    -
    -<% if @forums.size > 0 %> - <%= render :partial => 'forums/forum_list', :locals => {:forums => @forums} %> -<% else %> - <%= render :partial => "layouts/no_content" %> -<% end %> +<%= javascript_include_tag 'new_user' %> +<%= stylesheet_link_tag 'public'%> + + +
    +
    +
    + +
    + <%= render :partial => 'post_banner' ,:locals => {:order_type=>@type,:order_str=>@str}%> + + + + + + +
    +
    + <%= render :partial => 'forum_list',:locals => {:forums=>@forums}%> +
    +
      + <%= pagination_links_full @forums_pages, @forums_count ,:per_page_links => true,:remote =>true,:flag=>true%> +
    +
    +
    +
    +
    diff --git a/app/views/forums/index.js.erb b/app/views/forums/index.js.erb new file mode 100644 index 000000000..642c3c20a --- /dev/null +++ b/app/views/forums/index.js.erb @@ -0,0 +1,4 @@ +//$("#postBanner").html("<%#= render :partial => 'post_banner' ,:locals => {:order_type=>@type,:order_str=>@str }%>"); +$("#forum_list").html("<%= escape_javascript(render :partial => 'forum_list',:locals => {:forums=>@forums}) %>"); +//这里出现一个问题竟然是单双引号引起的。注意!! +$("#pages").html('<%= pagination_links_full @forums_pages, @forums_count,:per_page_links => false,:remote =>true,:flag=>true%>'); \ No newline at end of file diff --git a/app/views/forums/show.html.erb b/app/views/forums/show.html.erb index 24aa74c23..714d364a4 100644 --- a/app/views/forums/show.html.erb +++ b/app/views/forums/show.html.erb @@ -1,42 +1,144 @@ - -
    -

    - <%=l(:label_memo_new)%> -

    - <% if User.current.logged? %> - <%= labelled_form_for(@memo, :url => create_memo_forum_path(@forum), :html => {:multipart => true} ) do |f| %> -
    - <%= hidden_field_tag :asset_id,params[:asset_id],:required => false,:style => 'display:none' %> -

    - <%= f.text_field :subject, :required => true, :maxlength => 50%> -

    -

    - <%= f.kindeditor :content, :required => true %> -

    - -

    - (<%= l(:label_memos_max_length) %>) -

    -

    - <%= l(:label_attachment_plural) %> -
    - <%= render :partial => 'attachments/form', :locals => {:container => @memo} %> -

    -
    - <%= f.submit :value => l(:label_memo_create) %> - <%= link_to l(:button_cancel), "#", :onclick => '$("#add-memo").hide(); return false;' %> -
    - <% end %> - <% end %> +<%= javascript_include_tag 'new_user','/assets/kindeditor/pasteimg','/assets/kindeditor/kindeditor' %> + +
    + + +
    + <%= render :partial => 'show_topics',:locals => {:memos=>@memos}%> +
    +
      + <%= pagination_links_full @topic_pages, @topic_count ,:per_page_links => true, :remote => true, :flag => true %> +
    + + + + + + + + + + +
    - - - <%= link_to(image_tag('edit.png')+l(:label_forum_edit),{:action => 'edit', :id => @forum}, :method => 'get', :title => l(:button_edit)) if @forum.editable_by?(User.current) %> - <%= link_to(image_tag('delete.png')+'删除讨论区', {:action => 'destroy', :id => @forum}, :method => :delete, :data => {:confirm => l(:text_are_you_sure)}, :title => l(:button_delete) - ) if @forum.destroyable_by?(User.current) %> - - - <%= link_to l(:label_memo_new_from_forum), new_forum_memo_path(@forum), :class => 'icon icon-add', - :onclick => 'showAndScrollTo("add-memo", "memo_subject"); return false;' if User.current.logged? %> - -<%= render :partial => 'forums/show_topics', :locals => {:memos => @memos} %> +
    \ No newline at end of file diff --git a/app/views/forums/show.js.erb b/app/views/forums/show.js.erb new file mode 100644 index 000000000..9e36215ac --- /dev/null +++ b/app/views/forums/show.js.erb @@ -0,0 +1,2 @@ +$("#topics_list").html("<%= escape_javascript(render :partial => 'show_topics',:locals => {:memos=>@memos})%>") +$("#pages").html('<%= pagination_links_full @topic_pages, @topic_count,:per_page_links => false,:remote =>true%>'); \ No newline at end of file diff --git a/app/views/git_usage/ch_usage.html.erb b/app/views/git_usage/ch_usage.html.erb deleted file mode 100644 index 330ab9b5e..000000000 --- a/app/views/git_usage/ch_usage.html.erb +++ /dev/null @@ -1,352 +0,0 @@ - - - - - - - -无标题文档 - - - - - - - - -
    Git使用说明
    - - - - - -
    我们将使用 git 这个分布式版本控制系统来提交代码,下面就来介绍一下代码的提交方法。
    - - - - - -

     

    -

    Windows

    - - - - - - - - - - -
    1、安装
     

    Step1:

    -

    http://code.google.com/p/msysgit下载msysgit, 我们使用的版本是Git-1.7.4-preview20110204.exe

    - - - - -
    安装时,选择Checkout as-is, commit as-is,这样Git 就不会修改换行风格了. 其他用缺省设置即可。
    - - - - - - - - - - -
     

    Step2:

    -

    http://code.google.com/p/tortoisegit/下载TortoiseGit,我们使用的版本是Tortoisegit-1.6.5.0-32bit.msi

    安装时, 选择TortoisePLink。
    - - - - -
    这两个软件安装完成后, 就可以开始使用了。
    - - - - -
     
    - - - - -

    Step3:

    -

    在目录中右键单击TortoiseGit 再选Create Branch…就可以创建分支了。

    -

     

    - - - - - - - - - - - - - - - - -
    2、配置
     

    在桌面上点击鼠标右键,选择TortoiseGit的Settings进行设置

    Name和Email是用来设置自己的用户名和联系方式的(user.name和user.email必须填写,这些将在版本库提交时用到, 其中的name和email要和<%= Setting.host_name %>上的登陆名和邮箱保持一致 - ,方便代码贡献统计 )。

    接着可以定制上下文菜单:

    -

    我们在Context Menu里勾选的是 CloneSyncCommit

    -

    在Set Extend Menu Item里勾选的是Import Svn IgnoreShow ReflogBrowse ReferencesStash ApplySubmodule Sync

    - - - - -
     
    - - - - -
    3、日常用法
    - - - - -
     
    - - - - - - - -

    Step1:

    -

    创建版本库(两种途径)

    -

    (a)在文件夹中按右键, 选择Git Create repository here 就可以创建库了,在出现的窗口中, 不勾选选项, 直接按OK。

    -

    完成上述操作后,可以看到工作区中出现了隐藏目录 .git。这个隐藏的 .git目录就是git版本库(repository)。

    -

     

    -

    (b)从远程服务器上克隆一个已存在的版本库到本地:在目录中单击右键,选择Git Clone... 然后在URL里填入要clone的文件的地址。

     
    - - - - -

    Step2:

    -

    添加文件和文件夹

    -

    在文件夹中按右键, 选Git Commit -> "master"… ,接着填写Message, 勾选Whole Project 选项, 这样Commit 的时候可以将整个项目的信息全部Commit 上去, 可以实现不需要打Tag 就能Checkout 出每次Commit 的内容.

    -

    比如:

    -

    在工作区添加file1.txt,commit以后接着修改file1.txt,再创建一个文件夹dir1, 并且放置一个file2.txt 在dir1 目
    - 录中, 再次commit 时, 就可以将dir1 和file2.txt 一起加入了.

    - - - - -
     
    - - - - -

    Step3:

    -

    创建分支

    -

    在目录中单击右键,选择TortoiseGit 里的create Branch…就可以创建分支了。

    -

    勾选Switch to new branch, 就可以跳转到建立好的分支上。

    -

    比如:

    -

    添加一个file3.txt 后, commit 修改。接着通过Switch/Checkout….可以切换回master 分支。

    - - - - -
     
    - - - - -

    Step4:

    -

    看分支情况及修改log

    -

    在目录中单击右键,选择TortoiseGit 里的Show log, 可以看分支情况和修改log。 勾选All Branches 可以看到所有分支的情况.

    -

    在Message 列中, 绿色 - 的是分支, 红色 - 的是当前工作分支

    - - - - -
     
    - - - - -

    Step5:

    -

    比较版本差异

    -

    通过按Shift , 可以选中两个版本, 接着再按鼠标右键, 选中Compare revisions, 就可以比较两个revision 了。

    - - - - -
     
    - - - - -

    Step6:

    -

    合并分支

    -

    首先切换到master 分支, 接着点击鼠标右键选择TortoiseGit 里的Merge,就可以实现将分支合并到主版本。

    - - - - -
     
    - - - - -

    Step7:

    -

    其他操作

    -

    (a) Stash

    -

    Git 提供了一个暂存修改的功能, 称为Stash。 在一些程序进行了修改, 但还不
    - 想commit 成revision 时, 就可以将这些修改Stash 起来, 等到后面需要时再将它
    - 们Pop 出来。

    -

    (b) 忽略文件

    -

    一些编辑器在修改文件后会产生bak 文件, 一般不希望这些备份文件也加入
    - 库中, 可以选中一个.bak 文件, 然后选择Add to ignore list 中的*.bak, 这样bak 文
    - 件以后就不会被commit 了。

    - - - - - - - -

     

    -

    Tips:

    在碰到不熟悉的命令时,可以通过 git help命令查看git的用户手册,命令如下:

    - - - - -

    $git help <command>

    - - - - -
     
    - - - - - -
    Linux
    - - - - - - - - - - -
    1、安装
    如果你用的是Linux,你可以用你的本地包管理系统(native package management system)来安装。

    $ yum install git-core

    -

    在redhat等系统下用yum

    -

    $apt-get install git-core

    -

    在debian,ubuntu等系统下用apt-get

    - - - - - - - - - - - -
     
    2、配置

    $git config --global user.name “your_name”

    -

    $git config --global user.email “your_email” 

    -

    Name和Email是用来设置自己的用户名和联系方式的(user.name和user.email必须填写,这些将在版本库提交时用到, - 其中的name和email要和<%= Setting.host_name %>上的登陆名和密码保持一致 -,方便代码贡献统计 )。

    - - - - - - - - - - -
     
    3、代码提交方法

    cd file1

    -

    $ git add file1

    -

    $ git init

    -

    $ git commit -a

    -

    $ git remote add [name] [版本库里给的URL(去掉http)]

    -

    $ git push [name] master

    -

    输入password后即可上传。

    -

     

    - - - - -
    ——Trustie团队
    -

     

    -

     

    -

     

    -

     

    -

     

    - - - - \ No newline at end of file diff --git a/app/views/git_usage/en_usage.html.erb b/app/views/git_usage/en_usage.html.erb deleted file mode 100644 index 237895d23..000000000 --- a/app/views/git_usage/en_usage.html.erb +++ /dev/null @@ -1,346 +0,0 @@ - - - - - - -无标题文档 - - - - - - - - -
    Git User Guide
    - - - - - -
    We will use git which is a distributed version control and source code management system to submit our code, here is the submission method.
    - - - - - - - - - - - - - - -
    - - - -
     
    - - - - -
    Windows
    - - - - -
    1. Installation

    Step1:

    Download msysgit from http://code.google.com/p/msysgit, the version we have used is

    -

    Git-1.7.4-preview20110204.exe.

    Please tick "Checkout as-is" and "commit as-is" options during installation so git does not modify the line feed style. Other options you can use the default settings.

    - - - - -
     
    - - - - -

    Step2:

    -

    Download TortoiseGit from http://code.google.com/p/tortoisegit/, the version we have used is

    -

    Tortoisegit-1.6.5.0-32bit.msi.

    -

    Please tick "TortoisePLink" option during installation.

    -

    You can start using Git when you complete the installation.

    - - - - -
     
    - - - - -

    Step3:

    -

    You can create a branch with method that right-click the "TortoiseGit" in the directory and check the "Create Branch… " option.

    - - - - -
     
    - - - - -
    2. Configuration
    - - - - -

    Right-click on the desktop and select the "Settings" in the "TortoiseGit"

    -

    User name and email are used to set your own user name and contact information( user.name and user.email must be completed because these will be used when submitting the repository, the name and email must be the same with login name and email you registed in the <%= Setting.host_name %> - ).

    -

    Then you can customize the "Context Menu":

    -

    Please check the "Clone","Sync" and "Commit" options in the "Context Menu",

    -

    check the "Import Svn Ignore", "Show Reflog", "Browse References", "Stash Apply" and "Submodule Sync" in the "Set Extend Menu Item".

    - - - - -
     
    - - - - -
    3. Simple usage
    - - - - -

    Step1:

    -

    Create a new repository by two ways, here we go

    -

    (a) You can create a repository by right-click in the folder and select "Git Create repository here". Uncheck any options in the new window, instead of it please click "OK".

    -

    After completed these operation, you can see there is a hidden directory ( .git ) in the workspace and this hidden directory is the git repository.

    -

    (b) Clone a exist version from the remote server to local: right-click in the folder and select " Git Clone.." and fill in the URL where you had clone from.

    - - - - -
     
    - - - - -

    Step2:

    -

    Add the new file and folder

    -

    Right-click in the folder and select Git Commit -> "master"… , then fill in the "Message" and check the " Whole Project " option so that the whole information of the project can commit.

    -

    For example:

    -

    Create a new file in the workspace named "file1.txt", commit it, and then creat a new folder in the workspace named "dir1", after that create a new file again, but this file is in the folder dir1, named "file2.txt". After that select "Git Commit", then file1 and dir1 can be joined together.

    - - - - -
     
    - - - - -

    Step3:

    -

    Create a new Branch

    -

    You can create a new branch by right-click in the folder and select TortoiseGit -> " create Branch… ".

    -

    You will switch to the new branch when you check "Switch to new branch" option.

    -

    For example:

    -

    Create a new file in the workspace named "file3.txt", commit it. And you can switch to the "master" by select the "Switch/Checkout..." in the "TortoiseGit".

    - - - - -
     
    - - - - -

    Step4:

    -

    View and modify the log

    -

    You can view the situation of the branch by right-click in the folder and select TortoiseGit -> " Show log". Even you can also modify the log in it. And you can view all the branch's situation by check the " All Branches " option.

    -

    In the "Message" colume, branch is - green - and the current branch is red - .

    - - - - -
     
    - - - - -

    Step5:

    -

    Compare the version

    -

    You can select two version in the same time by press "shift", and you can compare the different between two version by right-click the " Compare revisions ".

    - - - - -
     
    - - - - -

    Step6:

    -

    Merge the branch

    -

    First, you should switch to the "master", then righr-click on it and select TortoiseGit -> "Merge" so that the branch can merge into the main version.

    - - - - -
     
    - - - - -

    Step7:

    -

    Other operations

    -

    (a) Stash

    -

    Git provides a function named Stash to temporarily store the revised programs. When you revise some programs but still do not want to commit them, you can stash these revised programs and pop them if you need them then.

    -

    (b) Ignore Files

    -

    The editor will generate some .bak files after editing. If you do not want to add these .bak files to the repository you can select the ".bak" file and check the "*.bak" in the " Add to ignore list". Then the .bak files will not be commited.
    -

    -


    -

    - - - - -
     
    - - - - -

    Tips:

    -

    You can read the user manual by enter " git help " command when you are confused, command as follows:

    - - - - -
    $git help <command>
    - - - - -
     
    - - - - - -
    Linux
    - - - - - - - -
    1.Installation

    If you are useing Linux, you can install git through native package management system.

    -

    $ yum install git-core

    -

    if you are using redhat, you should type "yum".

    -

    $apt-get install git-core

    -

    if you are using debian or ubuntu, you should type "apt-get".

    - - - - - - - - - - -
     
    2. Configuration

    $git config --global user.name “your_name”M

    -

    $git config --global user.email “your_email” 

    -

    User name and email are used to set your own user name and contact information( user.name and user.email must be completed because these will be used when submitting the repository, - the name and email must be the same with login name and email you registed in the <%= Setting.host_name %> -).

    - - - - - - - - - - -
     
    3. How to commit

    cd file1

    -

    $ git add file1

    -

    $ git init

    -

    $ git commit -a

    -

    $ git remote add [name] [The URL which we give you in our website(with out http)]

    -

    $ git push [name] master

    -

    The last step is enter your password.

    -

     

    - - - - -
    —— By Trustie Team
    -

     

    -

     

    -

     

    -

     

    -

     

    -

     

    -

     

    -

     

    - - - diff --git a/app/views/homework_common/_homework_detail_manual_form.html.erb b/app/views/homework_common/_homework_detail_manual_form.html.erb deleted file mode 100644 index ffec93e73..000000000 --- a/app/views/homework_common/_homework_detail_manual_form.html.erb +++ /dev/null @@ -1,109 +0,0 @@ -
      -
    • - - -

      -
    • -
      -
    • - -
      - <% if edit_mode %> - <%= f.kindeditor :description,:editor_id => 'homework_description_editor',:owner_id => homework.id,:owner_type =>OwnerTypeHelper::HOMEWORKCOMMON %> - <% else %> - <%= hidden_field_tag :asset_id,params[:asset_id],:required => false,:style => 'display:none' %> - <%= f.kindeditor :description,:editor_id => 'homework_description_editor' %> - <% end %> -
      -
    • -
      -
    • - - <%= render :partial => 'attachments/new_form', :locals => {:container => homework} %> -
    • -
      -
    • - - - <%= calendar_for('homework_end_time')%> -
      -
    • - -
      -
    -
    -

    基本规则设置(总分为100分)

    -
    -
      -
    • - - <%= select_tag :late_penalty,options_for_select(late_penalty_option,homework.late_penalty), {:class => "fl mb10 h26 w70"} %> -  分 -
      -
    • -
    • - - <%= f.check_box :homework_type, :class => "mb10 mt5 fl" %> -
      -
    • -
    • - - <%= select_tag :ta_proportion,options_for_select(ta_proportion_option,homework.homework_detail_manual.ta_proportion), {:class => "fl mb10 h26 w70"} %> - × 教辅评分 -   +   - - × 匿评得分 - = 学生得分 -
      -
    • -
    • - - 如果教师对学生作品进行了评分,则教师评分为学生最终得分。 -
      -
    • -
    -
    - -
    -

    学生互评设置

    -
    -
      -
    • - - - <%= calendar_for('evaluation_start_time')%> -
      -
    • -
    • - - - <%= calendar_for('evaluation_end_time')%> -
      -
    • -
    • - - -

      每个学生将收到 3 份待匿评作品

      -
      -
    • - -
    • - - <%= select_tag :absence_penalty,options_for_select(absence_penalty_option,homework.homework_detail_manual.absence_penalty), {:class => "fl mb10 h26 w70"} %> -  分 -

      学生漏评1个作品将扣 <%= homework.homework_detail_manual.absence_penalty%> 

      -
      -
    • -
    -
    \ No newline at end of file diff --git a/app/views/homework_common/_homework_detail_programing_form.html.erb b/app/views/homework_common/_homework_detail_programing_form.html.erb deleted file mode 100644 index 5e53c4b15..000000000 --- a/app/views/homework_common/_homework_detail_programing_form.html.erb +++ /dev/null @@ -1,145 +0,0 @@ -
      -
    • - - -

      -
    • -
      -
    • - -
      - <% if edit_mode %> - <%= f.kindeditor :description,:editor_id => 'homework_description_editor',:owner_id => homework.id,:owner_type =>OwnerTypeHelper::HOMEWORKCOMMON %> - <% else %> - <%= hidden_field_tag :asset_id,params[:asset_id],:required => false,:style => 'display:none' %> - <%= f.kindeditor :description,:editor_id => 'homework_description_editor' %> - <% end %> -
      -
    • -
      -
    • - - <%= render :partial => 'attachments/new_form', :locals => {:container => homework} %> -
    • -
      -
    • - - - <%= calendar_for('homework_end_time')%> -
      -
    • - - -
    • - - <%= select_tag :late_penalty,options_for_select(late_penalty_option,homework.late_penalty), {:class => "fl mb10 h26 w70"} %> -  分 -
      -
    • -
    - -
    -
    -

    编程评测设置

    -
    -
      -
    • - - <%= select_tag :language,options_for_select(programing_languages_options,homework.homework_detail_programing.language.to_i), {:class => "fl mb10 h26 w70"} %> -
      -
    • - -
    • - - <%= select_tag :ta_proportion,options_for_select(ta_proportion_option,homework.homework_detail_programing.ta_proportion), {:class => "fl mb10 h26 w70"} %> - × 教辅评分 -   +   - - × 系统评分 - = 学生得分 -
      -
    • -
    • - - 如果教师对学生作品进行了评分,则教师评分为学生最终得分。 -
      -
    • - -
    • - - -
      -
    • - - <% if edit_mode %> - <% homework.homework_tests.each do |homework_test|%> -
      -
    • - - -
    • -
    • - - -
    • -
    • - - - 测试 - -
    • -
      -
      - <% end%> - <% else %> -
      -
    • - - -
    • -
    • - - -
    • -
    • - - - 测试 - -
    • -
      -
      - <% end %> -
    -
    - - \ No newline at end of file diff --git a/app/views/homework_common/_set_evalutation_att.html.erb b/app/views/homework_common/_set_evalutation_att.html.erb new file mode 100644 index 000000000..01d9351ee --- /dev/null +++ b/app/views/homework_common/_set_evalutation_att.html.erb @@ -0,0 +1,53 @@ +
    + <%= form_for('new_form',:url => {:controller => 'homework_common',:action => 'set_evaluation_attr',:homework => @homework.id},:method => "post",:remote => true) do |f|%> + 匿评设置 +
    + +
    + 开启匿评 +
    + + <%= calendar_for('evaluation_start_time')%> +
    +
    +

    +
    +
    + +
    + 关闭匿评 +
    + + <%= calendar_for('evaluation_end_time')%> +
    +
    +

    +
    +
    + +
    + 匿评人数 + +
    +

    +
    +
    + +
    + 禁用匿评 + + 禁用后将无法进行学生互评 +
    +
    + +
    +
    + 确定 +
    +
    + 取消 +
    +
    +
    + <% end%> +
    \ No newline at end of file diff --git a/app/views/homework_common/alert_anonymous_comment.js.erb b/app/views/homework_common/alert_anonymous_comment.js.erb index 2b3248dc2..1c354aa45 100644 --- a/app/views/homework_common/alert_anonymous_comment.js.erb +++ b/app/views/homework_common/alert_anonymous_comment.js.erb @@ -3,5 +3,4 @@ showModal('ajax-modal', '500px'); $('#ajax-modal').siblings().remove(); $('#ajax-modal').before("" + ""); -$('#ajax-modal').parent().css("top","").css("left",""); -$('#ajax-modal').parent().addClass("anonymos"); \ No newline at end of file +$('#ajax-modal').parent().css("top","30%").css("left","30%").css("position","fixed"); \ No newline at end of file diff --git a/app/views/homework_common/edit.html.erb b/app/views/homework_common/edit.html.erb index 5b65b5982..5fc11728b 100644 --- a/app/views/homework_common/edit.html.erb +++ b/app/views/homework_common/edit.html.erb @@ -1,24 +1,24 @@ -<%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg' %> -<%= error_messages_for 'homework_common' %> - -
    -

    - <%= l(:label_course_homework_edit)%> -

    + +
    +
    编辑作业
    -
    - <%if @homework.homework_type == 2%> - <%= form_for @homework do |f| %> - <%= render :partial => 'homework_common/homework_detail_programing_form', :locals => { :homework => @homework,:f => f,:edit_mode => true } %> - 提交 - <%= link_to '取消',homework_common_index_path(:course => @course.id),:class => 'grey_btn fl'%> - <% end%> - <% else %> - <%= form_for @homework do |f| %> - <%= render :partial => 'homework_common/homework_detail_manual_form', :locals => { :homework => @homework,:f => f,:edit_mode => true } %> - 提交 - <%= link_to '取消',homework_common_index_path(:course => @course.id),:class => 'grey_btn fl'%> - <% end%> - <% end%> -
    + + +
    + <%= form_for @homework do |f| %> + +
    + <%= render :partial => 'users/user_homework_form', :locals => { :homework => @homework,:f => f,:edit_mode => true } %> +
    + <% end%> +
    diff --git a/app/views/homework_common/index.html.erb b/app/views/homework_common/index.html.erb index 4a804ae60..0c3dd6d8e 100644 --- a/app/views/homework_common/index.html.erb +++ b/app/views/homework_common/index.html.erb @@ -1,133 +1,55 @@ -
    -

    - <%= l(:label_homework)%> -

    -
    -
    -

    - <%= l(:label_totle)%> - <%= @obj_count%> - <%= l(:label_homework_count)%> -

    - <%= link_to( l(:label_course_homework_new), new_homework_common_path(:course => @course.id), :class => 'problem_new_btn fl c_dorange') if @is_teacher %> -
    -
    -<% @homeworks.each do |homework|%> -
    - <%= link_to(image_tag(url_to_avatar(homework.user), :width => "42", :height => "42"), user_path(homework.user), :class => "problem_pic fl") %> -
    - <%= link_to(homework.user.lastname+homework.user.firstname, user_path(homework.user),:class => 'problem_name fl',:target => "_blank") %> - <%= l(:label_user_create_project_homework) %>: - <%= link_to(homework.name, student_work_index_path(:homework => homework.id), :class => 'problem_tit fl fb c_dblue',:target => "_blank") %> -
    -

    - <%= l(:lebel_homework_commit)%> - ( <%= link_to homework.student_works.count, student_work_index_path(:homework => homework.id), :class => 'c_red'%> ) -

    - <% if @is_teacher%> - <%= homework_anonymous_comment(homework)%> - <%= link_to(l(:label_bid_respond_delete), homework_common_path(homework),:method => 'delete', :confirm => l(:text_are_you_sure), :class => "fr mr10 work_edit") %> - <%= link_to(l(:button_edit),edit_homework_common_path(homework), :class => "fr mr10 work_edit") %> - <% elsif @is_student%> - <%= student_anonymous_comment homework %> - <%= student_new_homework homework %> - <% end %> -
    - -
    -
    - <%= homework.description.html_safe %> -
    -
    -
    + + -
    - 开发语言: -
    - <% if homework.homework_detail_programing.language.to_i == 1%> - C - <% elsif homework.homework_detail_programing.language.to_i == 2%> - C++ - <% end%> -
    -
    -
    - <% end%> +
    +
    +
    作业
    +
    +
    - <% unless homework.attachments.empty?%> -
    - 附件: -
    - <%= render :partial => 'student_work/work_attachments', :locals => {:attachments => homework.attachments} %> -
    + <% if @is_teacher%> + +
    + <%= labelled_form_for @new_homework,:url => user_new_homework_users_path,:method => "post" do |f| %> +
    + <%= render :partial => 'users/user_homework_form', :locals => { :homework => @new_homework,:f => f,:edit_mode => false,:select_course => false } %> +
    -
    <% end%> +
    + <% end%> -
    - 扣分标准: -
    - <% if homework.homework_type == 1%> - <%= scoring_rules homework.late_penalty,homework.id,@is_teacher,homework.homework_detail_manual.absence_penalty%> - <% else%> - <%= scoring_rules homework.late_penalty,homework.id,@is_teacher%> - <% end%> -
    -
    -
    - - <%= l(:label_end_time)%>:<%= homework.end_time%> - <% if betweentime(homework.end_time) < 0 %> - - <%= l(:label_commit_limit)%> - - <% else %> - -
    -
    - <% end %> -
    -
    -
    -<% end%> + <%= render :partial => 'users/user_homework_list', :locals => {:homework_commons => @homeworks,:page => 0,:is_in_course => 1,:course_id => @course.id} %> +
    +
    -
      - <%= pagination_links_full @obj_pages, @obj_count, :per_page_links => false, :remote => false, :flag => true%> -
    -
    \ No newline at end of file diff --git a/app/views/homework_common/index.js.erb b/app/views/homework_common/index.js.erb new file mode 100644 index 000000000..7a038eb5c --- /dev/null +++ b/app/views/homework_common/index.js.erb @@ -0,0 +1 @@ +$("#user_show_more_homework").replaceWith("<%= escape_javascript( render :partial => 'users/user_homework_list',:locals => {:homework_commons => @homeworks, :page => @page, :is_in_course => 1,:course_id => @course.id} )%>"); \ No newline at end of file diff --git a/app/views/homework_common/new.html.erb b/app/views/homework_common/new.html.erb deleted file mode 100644 index cdc2ceca0..000000000 --- a/app/views/homework_common/new.html.erb +++ /dev/null @@ -1,27 +0,0 @@ -
    -

    - <%= l(:label_course_homework_new)%> -

    -
    -
    - <%= form_for("new_homework_common",:url => next_step_homework_common_index_path) do |f|%> - -

    - 请选择将要发布的作业类型 -

    - - - 人工评分的作业(支持匿名互评、灵活设置评分比例) - -
    - - - 自动评测的编程作业(支持C/C++程序的自动评分) - -
    - - 下一步 - - <% end%> -
    -
    diff --git a/app/views/homework_common/next_step.html.erb b/app/views/homework_common/next_step.html.erb deleted file mode 100644 index e84d0f87a..000000000 --- a/app/views/homework_common/next_step.html.erb +++ /dev/null @@ -1,30 +0,0 @@ -<%= javascript_include_tag "/assets/kindeditor/kindeditor" %> -<%= error_messages_for 'homework_common' %> -
    -

    - <%= l(:label_course_homework_new)%> -

    -
    -<% if @homework_type == "1"%> -
    - <%= labelled_form_for @homework,:url => {:controller => 'homework_common',:action => 'create'} do |f| %> - <%= hidden_field_tag "course",@course.id%> - <%= render :partial => 'homework_common/homework_detail_manual_form', :locals => { :homework => @homework,:f => f,:edit_mode => false } %> - 提交 - <%#= link_to "上一步", new_homework_common_path(:course => @course.id), :class => "orange_btn_homework fl"%> - <%= link_to '取消',homework_common_index_path(:course => @course.id),:class => 'grey_btn fl'%> - <% end%> -
    -<% elsif @homework_type == "2"%> -
    - <%= labelled_form_for @homework,:url => {:controller => 'homework_common',:action => 'create'} do |f| %> - <%= hidden_field_tag "course",@course.id%> - <%= hidden_field_tag "homework_common[homework_type]","2"%> - <%= render :partial => 'homework_common/homework_detail_programing_form', :locals => { :homework => @homework,:f => f,:edit_mode => false } %> - 提交 - <%#= link_to "上一步", new_homework_common_path(:course => @course.id), :class => "orange_btn_homework fl"%> - <%= link_to '取消',homework_common_index_path(:course => @course.id),:class => 'grey_btn fl'%> - <% end%> -
    -
    -<% end%> \ No newline at end of file diff --git a/app/views/homework_common/programing_test.js.erb b/app/views/homework_common/programing_test.js.erb index 74ec9439a..d1643329b 100644 --- a/app/views/homework_common/programing_test.js.erb +++ b/app/views/homework_common/programing_test.js.erb @@ -1,2 +1,12 @@ -$("#test_send_<%= @index%>").replaceWith(" fl ml5 mt1' onclick='programing_test(<%= @index%>)' id='test_send_<%= @index%>'><%= @result == 0 ? '正确' : '错误'%>"); -$("#test_result_<%= @index%>").val("<%= @result%>"); \ No newline at end of file +$("#test_send_<%= @index%>").replaceWith(" fl ml5 mt1 programing_test' onclick='programing_test(<%= @index%>)' id='test_send_<%= @index%>'><%= @result == 0 ? '正确' : '错误'%>"); +$("#test_result_<%= @index%>").val("<%= @result%>"); +<% if @err_msg || @result != 0%> + $("#homework_work_test_show").show(); + $("#homework_work_test_desc").text("<%= escape_javascript(@err_msg || status_to_err_msg(@result))%>"); + <% if @err_msg%> + $("#homework_test_error_msg").val("<%= escape_javascript(@err_msg)%>"); + <% end%> +<% else%> + $("#homework_work_test_show").hide(); + $("#homework_test_error_msg").val(""); +<% end%> \ No newline at end of file diff --git a/app/views/homework_common/set_evaluation_attr.js.erb b/app/views/homework_common/set_evaluation_attr.js.erb new file mode 100644 index 000000000..d6ab73df5 --- /dev/null +++ b/app/views/homework_common/set_evaluation_attr.js.erb @@ -0,0 +1 @@ +clickCanel(); \ No newline at end of file diff --git a/app/views/homework_common/start_anonymous_comment.js.erb b/app/views/homework_common/start_anonymous_comment.js.erb index 5f27a5b82..b0424bf7a 100644 --- a/app/views/homework_common/start_anonymous_comment.js.erb +++ b/app/views/homework_common/start_anonymous_comment.js.erb @@ -1,6 +1,6 @@ <% if @statue == 1%> alert('启动成功'); -$("#<%= @homework.id %>_start_anonymous_comment").replaceWith('<%= escape_javascript(link_to "关闭匿评", alert_anonymous_comment_homework_common_path(@homework), remote: true, id:"#{@homework.id}_stop_anonymous_comment",:class => "fr mr10 work_edit")%>'); +$("#<%= @homework.id %>_start_anonymous_comment").replaceWith('<%= escape_javascript(link_to "关闭匿评", alert_anonymous_comment_homework_common_path(@homework), remote: true, id:"#{@homework.id}_stop_anonymous_comment",:class => "postOptionLink")%>'); <% elsif @statue == 2 %> alert('启动失败\n作业总数大于等于2份时才能启动匿评'); <% elsif @statue == 3%> diff --git a/app/views/homework_common/start_evaluation_set.js.erb b/app/views/homework_common/start_evaluation_set.js.erb new file mode 100644 index 000000000..9d494f908 --- /dev/null +++ b/app/views/homework_common/start_evaluation_set.js.erb @@ -0,0 +1,6 @@ +$('#ajax-modal').html('<%= escape_javascript(render :partial => 'homework_common/set_evalutation_att') %>'); +showModal('ajax-modal', '350px'); +$('#ajax-modal').siblings().remove(); +$('#ajax-modal').before("" + +""); +$('#ajax-modal').parent().css("top","25%").css("left","35%").css("position","fixed"); \ No newline at end of file diff --git a/app/views/homework_common/stop_anonymous_comment.js.erb b/app/views/homework_common/stop_anonymous_comment.js.erb index 9a6131c64..4725d5731 100644 --- a/app/views/homework_common/stop_anonymous_comment.js.erb +++ b/app/views/homework_common/stop_anonymous_comment.js.erb @@ -1,2 +1,2 @@ -$("#<%= @homework.id %>_stop_anonymous_comment").replaceWith('匿评结束'); +$("#<%= @homework.id %>_stop_anonymous_comment").replaceWith(''); alert('关闭成功'); \ No newline at end of file diff --git a/app/views/issues/_action_menu.html.erb b/app/views/issues/_action_menu.html.erb index 2643c93e7..ae2a848e0 100644 --- a/app/views/issues/_action_menu.html.erb +++ b/app/views/issues/_action_menu.html.erb @@ -3,4 +3,4 @@ <%= link_to l(:button_copy), project_copy_issue_path(@project, @issue), :class => 'talk_edit fr' if User.current.allowed_to?(:add_issues, @project) %> <%= link_to l(:button_delete), issue_path(@issue.id), :data => {:confirm => issues_destroy_confirmation_message(@issue)}, :method => :delete, :class => 'talk_edit fr' if User.current.allowed_to?(:delete_issues, @project) %> <%= link_to l(:button_edit), edit_issue_path(@issue.id), :onclick => 'showAndScrollTo("all_attributes"); return false;', :class => 'talk_edit fr', :accesskey => accesskey(:edit) if @issue.editable? && User.current.allowed_to?(:edit_issues, @project) %> -<%= link_to l(:label_user_newfeedback), edit_issue_path(@issue.id), :onclick => 'showAndScrollTo("update", "issue_notes"); return false;', :class => 'talk_edit fr', :accesskey => accesskey(:edit) if @issue.editable? && User.current.allowed_to?(:add_issue_notes, @project) %> +<%= link_to l(:label_user_newfeedback), edit_issue_path(@issue.id), :onclick => 'showAndScrollTo("update", "issue_journal_kind_reply"); return false;', :class => 'talk_edit fr', :accesskey => accesskey(:edit) if @issue.editable? && User.current.allowed_to?(:add_issue_notes, @project) %> diff --git a/app/views/issues/_attributes.html.erb b/app/views/issues/_attributes.html.erb index 68bd9f82c..54cb85212 100644 --- a/app/views/issues/_attributes.html.erb +++ b/app/views/issues/_attributes.html.erb @@ -6,12 +6,11 @@
  • <% if @issue.safe_attribute?('status_id') && @allowed_statuses.present? %> - <%= f.select :status_id, - (@allowed_statuses.collect { |p| [p.name, p.id] }), - {:no_label => true}, - # ajax 刷新 - #:onchange => "updateIssueFrom('#{escape_javascript project_issue_form_path(@project, :id => @issue, :format => 'js')}')", - :class => "w150" %> + <%= f.select :status_id, (@allowed_statuses.collect { |p| [p.name, p.id] }), + {:no_label => true}, + # ajax 刷新 + #:onchange => "updateIssueFrom('#{escape_javascript project_issue_form_path(@project, :id => @issue, :format => 'js')}')", + :class => "w150" %> <% else %> <%= h(@issue.status.name) %> <% end %> @@ -20,10 +19,9 @@
  • <% if @issue.safe_attribute? 'priority_id' %> - <%= f.select :priority_id, - (@priorities.collect { |p| [p.name, p.id] }), - {:required => true, :no_label => true}, :disabled => !@issue.leaf?, - :class => "w150" %> + <%= f.select :priority_id, (@priorities.collect { |p| [p.name, p.id] }), + {:required => true, :no_label => true}, :disabled => !@issue.leaf?, + :class => "w150" %> <% end %>
  • @@ -32,8 +30,8 @@ <% if @issue.safe_attribute? 'assigned_to_id' %> <%= f.select :assigned_to_id, principals_options_for_select(@issue.assignable_users, @issue.assigned_to), - {:required => @issue.required_attribute?('assigned_to_id'), :no_label => true}, - :class => "w150" %> + {:required => @issue.required_attribute?('assigned_to_id'), :no_label => true}, + :class => "w150" %> <% end %>
    @@ -41,8 +39,8 @@ <% if @issue.safe_attribute?('fixed_version_id') && @issue.assignable_versions.any? %> <%= f.select :fixed_version_id, version_options_for_select(@issue.assignable_versions, @issue.fixed_version), - {:include_blank => true, :required => @issue.required_attribute?('fixed_version_id'), :no_label => true}, - :class => "w150" %> + {:include_blank => true, :required => @issue.required_attribute?('fixed_version_id'), :no_label => true}, + :class => "w150" %> <%#= link_to(image_tag('add.png', :style => 'vertical-align: middle;'), new_project_version_path(@issue.project), :remote => true, @@ -60,11 +58,7 @@
  • <% if @issue.safe_attribute? 'start_date' %> - <%= f.text_field :start_date, - :size => 22, - :disabled => !@issue.leaf?, - :no_label => true, - :required => @issue.required_attribute?('start_date') %> + <%= f.text_field :start_date, :size => 22, :disabled => !@issue.leaf?, :no_label => true, :required => @issue.required_attribute?('start_date') %> <%= calendar_for('issue_start_date', 'start_date') if @issue.leaf? %> <% end %>
  • @@ -72,10 +66,7 @@
  • <% if @issue.safe_attribute? 'due_date' %> - <%= f.text_field :due_date, :size => 22, - :disabled => !@issue.leaf?, - :no_label => true, - :required => @issue.required_attribute?('due_date') %> + <%= f.text_field :due_date, :size => 22, :disabled => !@issue.leaf?, :no_label => true, :required => @issue.required_attribute?('due_date') %> <%= calendar_for('issue_due_date', 'start_date') if @issue.leaf? %> <% end %>
  • @@ -83,10 +74,7 @@
  • <% if @issue.safe_attribute? 'estimated_hours' %> - <%= f.text_field :estimated_hours, :size => 22, - :disabled => !@issue.leaf?, - :no_label => true, - :required => @issue.required_attribute?('estimated_hours') %> + <%= f.text_field :estimated_hours, :size => 22, :disabled => !@issue.leaf?, :no_label => true, :required => @issue.required_attribute?('estimated_hours') %> <%= l(:field_hours) %> <% end %>
  • @@ -94,9 +82,9 @@
  • <% if @issue.safe_attribute?('done_ratio') && @issue.leaf? && Issue.use_field_for_done_ratio? %> <%= f.select :done_ratio, ((0..10).to_a.collect { |r| ["#{r*10} %", r*10] }), - {:required => @issue.required_attribute?('done_ratio'), :no_label => true}, - :onchange => "PrecentChange(this.value)", - :class => "w150" %> + {:required => @issue.required_attribute?('done_ratio'), :no_label => true}, + :onchange => "PrecentChange(this.value)", + :class => "w150" %> <% end %>
  • diff --git a/app/views/issues/_attributes_show.html.erb b/app/views/issues/_attributes_show.html.erb new file mode 100644 index 000000000..7b9e2bedf --- /dev/null +++ b/app/views/issues/_attributes_show.html.erb @@ -0,0 +1,52 @@ + +
    + <%= issue_fields_rows do |rows| %> +
      +
    •  状态  : 

      <%= @issue.status.name %>

      +
    • +
      + <% unless @issue.disabled_core_fields.include?('assigned_to_id') %> +
    •  指派给  : 

      <%= @issue.assigned_to ? link_to_isuue_user(@issue.assigned_to) : "--" %> +
    • + <% end %> +
      +
    +
      +
    •  优先级  : 

      <%= @issue.priority.name %> +
    • +
      + <% unless @issue.disabled_core_fields.include?('done_ratio') %> +
    •  % 完成  : 

      <%= @issue.done_ratio %>% +
    • + <% end %> +
      +
    +
      + <% unless @issue.disabled_core_fields.include?('start_date') %> +
    •  开始  : 

      <%= format_date(@issue.start_date) %>

      +
    • + <% end %> +
      + <% unless @issue.disabled_core_fields.include?('estimated_hours') %> +
    •  周期  : 

      <%= l_hours(@issue.estimated_hours) %> +
    • + <% end %> +
      +
    +
      + <% unless @issue.disabled_core_fields.include?('due_date') %> +
    •  计划完成  : 

      <%= format_date(@issue.due_date)? format_date(@issue.due_date) : "--" %> +
    • + <% end %> +
      + <% unless @issue.disabled_core_fields.include?('fixed_version_id') %> +
    •  目标版本  : 

      <%= (@issue.fixed_version ? link_to_version(@issue.fixed_version, :class => "pro_info_p") : "--") %> +
    • + <% end %> +
      +
    + <% end %> + <%#= render_custom_fields_rows(@issue) %> + <%#= call_hook(:view_issues_show_details_bottom, :issue => @issue) %> +
    + \ No newline at end of file diff --git a/app/views/issues/_edit.html.erb b/app/views/issues/_edit.html.erb index 1f3f984b4..f6b41f36d 100644 --- a/app/views/issues/_edit.html.erb +++ b/app/views/issues/_edit.html.erb @@ -1,3 +1,4 @@ +<%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg' %> <%= labelled_form_for @issue, :html => {:id => 'issue-form', :multipart => true} do |f| %> <%= error_messages_for 'issue', 'time_entry' %> <%= render :partial => 'conflict' if @conflict %> @@ -6,24 +7,20 @@ - <% end %> - - <% if @journals.present? %>
    <%= render :partial => 'history', :locals => {:issue => @issue, :journals => @journals} %>
    <% end %> -
    +
    + +
    回复 - <%= f.text_area :notes, :style => "width:99%;", :rows => "5", :no_label => true %> + <%= f.kindeditor :notes, :style => "width:99%;",:height=>'100px', :cssData =>"blockquote { padding:0px}", :rows => "5", :no_label => true, :editor_id=>'issue_journal_kind_reply' %>
    diff --git a/app/views/issues/_form.html.erb b/app/views/issues/_form.html.erb index 41fca87eb..0d5c876f1 100644 --- a/app/views/issues/_form.html.erb +++ b/app/views/issues/_form.html.erb @@ -28,11 +28,7 @@
  • <% if @issue.safe_attribute? 'subject' %> - <%= f.text_field :subject, - :class => "w576", - :maxlength => 255, - :style => "font-size:small", - :no_label => true %> + <%= f.text_field :subject, :class => "w576", :maxlength => 255, :style => "font-size:small", :no_label => true %> <%= javascript_tag do %> observeAutocompleteField('issue_subject', @@ -53,13 +49,7 @@ <%= f.label_for_field :description, :required => @issue.required_attribute?('description'), :no_label => true, :class => "label" %> <%#= link_to_function image_tag('edit.png'), '$(this).hide(); $("#issue_description_and_toolbar").show()' unless @issue.new_record? %> <%#= content_tag 'span', :id => "issue_description_and_toolbar" do %> - <%= f.kindeditor :description,:editor_id => "issue_desc_editor", - # :rows => (@issue.description.blank? ? 10 : [[10, @issue.description.length / 50].max, 100].min), - # :accesskey => accesskey(:edit), - # :class => "w583", - :width=>'87%', - :resizeType => 0, - :no_label => true %> + <%= f.kindeditor :description,:editor_id => "issue_desc_editor", :width=>'87%', :resizeType => 0, :no_label => true %> <%# end %> <%#= wikitoolbar_for 'issue_description' %> <% end %> @@ -68,13 +58,13 @@
  • - <% if @copy_from && @copy_from.attachments.any? %> -

    + <%# if @copy_from && @copy_from.attachments.any? %> + -

    - <% end %> + + <%# end %> <% if @copy_from && !@copy_from.leaf? %>

    diff --git a/app/views/issues/_form_custom_fields.html.erb b/app/views/issues/_form_custom_fields.html.erb index 4da98eb13..c97244902 100644 --- a/app/views/issues/_form_custom_fields.html.erb +++ b/app/views/issues/_form_custom_fields.html.erb @@ -1,13 +1,13 @@

    -
    -<% i = 0 %> -<% split_on = (@issue.custom_field_values.size / 2.0).ceil - 1 %> -<% @issue.editable_custom_field_values.each do |value| %> -

    <%= custom_field_tag_with_label :issue, value, :required => @issue.required_attribute?(value.custom_field_id) %>

    -<% if i == split_on -%> -
    -<% end -%> -<% i += 1 -%> -<% end -%> -
    +
    + <% i = 0 %> + <% split_on = (@issue.custom_field_values.size / 2.0).ceil - 1 %> + <% @issue.editable_custom_field_values.each do |value| %> +

    <%= custom_field_tag_with_label :issue, value, :required => @issue.required_attribute?(value.custom_field_id) %>

    + <% if i == split_on -%> +
    + <% end -%> + <% i += 1 -%> + <% end -%> +
    diff --git a/app/views/issues/_history.html.erb b/app/views/issues/_history.html.erb index 68e991594..8befaf37e 100644 --- a/app/views/issues/_history.html.erb +++ b/app/views/issues/_history.html.erb @@ -12,9 +12,9 @@

    <% if journal.details.any? %> <% details_to_strings(journal.details).each do |string| %> -

    <%= string %>

    +

    <%= string.html_safe %>

    <% end %> - <% end %> + <% end %>

  • diff --git a/app/views/issues/add_journal.js.erb b/app/views/issues/add_journal.js.erb new file mode 100644 index 000000000..7c56aea6e --- /dev/null +++ b/app/views/issues/add_journal.js.erb @@ -0,0 +1,3 @@ +$("#user_activity_<%= @user_activity_id%>").replaceWith("<%= escape_javascript(render :partial => 'users/project_issue', :locals => {:activity => @issue,:user_activity_id =>@user_activity_id,:first_user_activity =>@first_user_activity,:page => @page}) %>"); + +init_activity_KindEditor_data(<%= @user_activity_id%>,"","87%"); \ No newline at end of file diff --git a/app/views/issues/show.html.erb b/app/views/issues/show.html.erb index 8c12d62e0..76e178120 100644 --- a/app/views/issues/show.html.erb +++ b/app/views/issues/show.html.erb @@ -6,12 +6,13 @@
    <%= link_to "#{@issue.project.name}"+">", project_issues_path(@issue.project) %> - <%= "#" + @issue.project_index %> + <%= "#" + @issue.id.to_s %>
    <%= link_to image_tag(url_to_avatar(@issue.author), :width => 46, :height => 46), user_path(@issue.author), :class => "ping_dispic" %>
    +

    @@ -20,104 +21,53 @@


    -

    <%= @issue.author %> - <%# if @issue.created_on != @issue.updated_on %> - 添加于 <%= format_time(@issue.created_on).html_safe %> - <%# else %> - <%#= format_time(@issue.updated_on).html_safe %> - <%# end %> + 由<%= @issue.author %>添加于 <%= format_time(@issue.created_on).html_safe %>

    + 'action_menu' %>
    -
    - <% if @issue.description? || @issue.attachments.any? -%> + <% if @issue.description? || @issue.attachments.any? -%> +
    <% if @issue.description? %> <%#= link_to l(:button_quote), quoted_issue_path(@issue.id), :remote => true, :method => 'post', :class => 'icon icon-comment' if authorize_for('issues', 'edit') %> <%= textAreailizable @issue, :description, :attachments => @issue.attachments %> <% end %> -
    - + <% end -%> + +
    + + + <%= link_to_attachment_project @issue, :thumbnails => true %>
    <%= call_hook(:view_issues_show_description_bottom, :issue => @issue) %> -
    -
    - -
    - <%= issue_fields_rows do |rows| %> -
      -
    •  状态  : 

      <%= @issue.status.name %>

      -
    • -
      - <% unless @issue.disabled_core_fields.include?('assigned_to_id') %> -
    •  指派给  : 

      <%= @issue.assigned_to ? link_to_isuue_user(@issue.assigned_to) : "--" %> -
    • - <% end %> -
      -
    -
      -
    •  优先级  : 

      <%= @issue.priority.name %> -
    • -
      - <% unless @issue.disabled_core_fields.include?('done_ratio') %> -
    •  % 完成  : 

      <%= @issue.done_ratio %>% -
    • - <% end %> -
      -
    +
    +
    + + + <%= render :partial => 'attributes_show' %> + + + <%# 该应用是对issue主题内容的引用,对应:to => 'journals#new %> + + +
    +
    -
      - <% unless @issue.disabled_core_fields.include?('start_date') %> -
    •  开始  : 

      <%= format_date(@issue.start_date) %>

      -
    • - <% end %> -
      - <% unless @issue.disabled_core_fields.include?('estimated_hours') %> -
    •  周期  : 

      <%= l_hours(@issue.estimated_hours) %> -
    • - <% end %> -
      -
    -
      - <% unless @issue.disabled_core_fields.include?('due_date') %> -
    •  计划完成  : 

      <%= format_date(@issue.due_date)? format_date(@issue.due_date) : "--" %> -
    • - <% end %> -
      - <% unless @issue.disabled_core_fields.include?('fixed_version_id') %> -
    •  目标版本  : 

      <%= (@issue.fixed_version ? link_to_version(@issue.fixed_version, :class => "pro_info_p") : "--") %> -
    • - <% end %> -
      -
    - <% end %> - <%#= render_custom_fields_rows(@issue) %> - <%#= call_hook(:view_issues_show_details_bottom, :issue => @issue) %> -
    - -
    - <%= link_to l(:button_quote), quoted_issue_path(@issue.id), :remote => true, :method => 'post', :class => 'talk_edit fr' if authorize_for('issues', 'edit') %> -
    -
    + <% if @issue.editable? %>
    <%= render :partial => 'edit' %>

    - - - - + <%#--引用时不能修改,剥离出引用内容--%> + <%= l(:button_submit) %> <% end %> - <%#= submit_tag l(:button_submit) %> <%#= preview_link preview_edit_issue_path(:project_id => @project, :id => @issue), 'issue-form' ,'preview',{:class => "blue_btn fr mr10"}%>
    @@ -128,6 +78,7 @@ <%= render :partial => 'changesets', :locals => {:changesets => @changesets} %>
    <% end %> +
    <% other_formats_links do |f| %> <%= f.link_to 'Atom', :url => {:key => User.current.rss_key} %> diff --git a/app/views/journals/diff.html.erb b/app/views/journals/diff.html.erb index 190459b71..b842d87d0 100644 --- a/app/views/journals/diff.html.erb +++ b/app/views/journals/diff.html.erb @@ -1,8 +1,8 @@

    <%=h @issue.tracker %> #<%= @issue.id %>

    由<%= @journal.user %> 更新于 <%= format_time @journal.created_on %>

    -
    - <%= simple_format_without_paragraph @diff.to_html %> +
    + <%= @diff.to_html.gsub("<","<").gsub(">",">").gsub(""","\"").gsub("&gt;", ">").gsub("&lt;", "<").gsub("&quot;", "\"").html_safe %>

    <%= link_to l(:button_back), issue_path(@issue), :onclick => 'history.back(); return false;' %>

    diff --git a/app/views/journals/new.js.erb b/app/views/journals/new.js.erb index ae2574595..9c5d87079 100644 --- a/app/views/journals/new.js.erb +++ b/app/views/journals/new.js.erb @@ -1,10 +1,11 @@ -$('#issue_notes').val("<%= raw escape_javascript(@content) %>"); +issue_journal_kind_reply.html("<%= raw escape_javascript(@content) %>"); <% # when quoting a private journal, check the private checkbox - if @journal && @journal.private_notes? + if @journal && @journal.private_notes? %> $('#issue_private_notes').attr('checked', true); <% end %> +//quote_issue_journal() showAndScrollTo("update", "notes"); $('#notes').scrollTop = $('#notes').scrollHeight - $('#notes').clientHeight; diff --git a/app/views/layouts/_base_feedback.html.erb b/app/views/layouts/_base_feedback.html.erb index 07f852914..9fe25ce95 100644 --- a/app/views/layouts/_base_feedback.html.erb +++ b/app/views/layouts/_base_feedback.html.erb @@ -1,9 +1,9 @@ @@ -39,7 +39,7 @@ minStatue : true, skin : 'blue', durationTime : 1000 - } + }; var options = $.extend(defaults, options); this.each(function(){ @@ -56,13 +56,13 @@ if(options.minStatue == "true"){ $(".show_btn").css("float", options.float); sideContent.css('width', 0); - show_btn.css('width', 25); + show_btn.css('width', 29); } //close closeBtn.bind("click",function(){ sideContent.animate({width: '0px'},"fast"); - show_btn.stop(true, true).delay(300).animate({ width: '25px'},"fast"); + show_btn.stop(true, true).delay(300).animate({ width: '29px'},"fast"); cookiesave('minStatue','true','','',''); }); //show @@ -83,14 +83,10 @@ $(function(){ $("#button1").click(function(){ myTips("<%= l(:label_feedback_success) %>","success"); }); - }); function f_submit() { -// var subject = $("#memo_subject").val(); -// var content = $("#memo_content_1").val(); -// $("#memo_subject").val(subject+":"+ content.substr(0,18)+"..."); $("#new_memo").submit(); } @@ -169,15 +165,15 @@ function cookieget(n)
    <% get_memo %> - <% if @public_forum %> - <%= form_for(@new_memo, :url => create_feedback_forum_path(@public_forum)) do |f| %> - <%= f.text_area :subject,:id=>"subject", :class => "opnionText", :placeholder => l(:label_feedback_tips) %> - <%= f.hidden_field :content,:id => 'hidden', :required => true , :value => l(:label_feedback_value) %> - <%#= f.submit :value => l(:label_memo_create), :class => "opnionButton", :id => "button1" %> - - <%= l(:label_submit)%> - <% end %> - <% end %> + <% if @public_forum %> + <%= form_for(@new_memo, :url => create_feedback_forum_path(@public_forum)) do |f| %> + <%= f.text_area :subject,:id=>"subject", :class => "opnionText", :placeholder => l(:label_feedback_tips) %> + <%= f.hidden_field :content,:id => 'hidden', :required => true , :value => l(:label_feedback_value) %> + <%#= f.submit :value => l(:label_memo_create), :class => "opnionButton", :id => "button1" %> + + <%= l(:label_submit)%> + <% end %> + <% end %>
    -
    <%= l(:label_submit)%>
    +
    diff --git a/app/views/layouts/_base_footer_public.html.erb b/app/views/layouts/_base_footer_public.html.erb new file mode 100644 index 000000000..dba26f1f6 --- /dev/null +++ b/app/views/layouts/_base_footer_public.html.erb @@ -0,0 +1,46 @@ + +
    \ No newline at end of file diff --git a/app/views/layouts/_base_header.html.erb b/app/views/layouts/_base_header.html.erb index c4f61d73c..8dbacb523 100644 --- a/app/views/layouts/_base_header.html.erb +++ b/app/views/layouts/_base_header.html.erb @@ -18,7 +18,7 @@
    <% end -%> diff --git a/app/views/layouts/_base_header_new.html.erb b/app/views/layouts/_base_header_new.html.erb index 71cf8ab02..163f3a3ff 100644 --- a/app/views/layouts/_base_header_new.html.erb +++ b/app/views/layouts/_base_header_new.html.erb @@ -9,65 +9,60 @@ + + <% end %> <%= render_menu :account_menu -%> diff --git a/app/views/layouts/_footer.html.erb b/app/views/layouts/_footer.html.erb new file mode 100644 index 000000000..752853c60 --- /dev/null +++ b/app/views/layouts/_footer.html.erb @@ -0,0 +1,39 @@ + \ No newline at end of file diff --git a/app/views/layouts/_logined_header.html.erb b/app/views/layouts/_logined_header.html.erb new file mode 100644 index 000000000..c750ff3b5 --- /dev/null +++ b/app/views/layouts/_logined_header.html.erb @@ -0,0 +1,130 @@ + + + diff --git a/app/views/layouts/_new_feedback.html.erb b/app/views/layouts/_new_feedback.html.erb index 3b8098ed5..136e49b37 100644 --- a/app/views/layouts/_new_feedback.html.erb +++ b/app/views/layouts/_new_feedback.html.erb @@ -21,14 +21,16 @@ <% end %>
    -
    -
    在线客服
    +
    + <%= l(:label_submit)%> + +
    diff --git a/app/views/layouts/_new_header.html.erb b/app/views/layouts/_new_header.html.erb index a756009f0..9252e23b9 100644 --- a/app/views/layouts/_new_header.html.erb +++ b/app/views/layouts/_new_header.html.erb @@ -26,7 +26,7 @@
  • <%=link_to l(:label_my_course), {:controller => 'users', :action => 'user_courses', id: User.current.id},target:"_blank", :class => "parent" %>
      - <% user_course.reverse.each do |course| %> + <% user_course.each do |course| %>
    • <%= link_to course.name, {:controller => 'courses',:action => 'show',:id => course.id},target:"_blank" %>
    • @@ -40,7 +40,7 @@
    • <%= link_to l(:label_my_projects), {:controller => 'users', :action => 'user_projects', id: User.current.id, host: Setting.host_name},target:"_blank", :class => "parent" %>
        - <% User.current.projects.reverse.each do |project| %> + <% User.current.projects.select("projects.*,(SELECT MAX(created_at) FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS a").order("a desc").each do |project| %>
      • <%= link_to project.name, {:controller => 'projects', :action => 'show',id: project.id, host: Setting.host_name }, target:"_blank" %>
      • @@ -53,6 +53,9 @@
    • + + + <% end -%> <%= header_render_menu :account_menu -%>
    diff --git a/app/views/layouts/_unlogin_header.html.erb b/app/views/layouts/_unlogin_header.html.erb new file mode 100644 index 000000000..e674a769f --- /dev/null +++ b/app/views/layouts/_unlogin_header.html.erb @@ -0,0 +1,95 @@ + + + diff --git a/app/views/layouts/_user_brief_introduction.html.erb b/app/views/layouts/_user_brief_introduction.html.erb new file mode 100644 index 000000000..3b0500fed --- /dev/null +++ b/app/views/layouts/_user_brief_introduction.html.erb @@ -0,0 +1,8 @@ +<% if user.user_extensions && user.user_extensions.brief_introduction && !user.user_extensions.brief_introduction.empty? %> + <%= user.user_extensions.brief_introduction %>  +<% else%> + 这位童鞋很懒,什么也没有留下~  +<% end %> +<% if User.current == user%> + <%= link_to image_tag("../images/signature_edit.png",width:"12px", height: "12px"), "javascript:void(0);", :onclick => "show_edit_user_introduction();"%> +<% end%> \ No newline at end of file diff --git a/app/views/layouts/_user_courses.html.erb b/app/views/layouts/_user_courses.html.erb new file mode 100644 index 000000000..a71dd099f --- /dev/null +++ b/app/views/layouts/_user_courses.html.erb @@ -0,0 +1,12 @@ +<% courses.each do |course|%> +
  • + <%= link_to course.name, course_path(course.id,:host=>Setting.host_course), :class => "coursesLineGrey hidden #{course_endTime_timeout?(course) ? 'c_dark_grey' : ''}", :title => course.name+"("+course.time.to_s+course.term+")"%> +
  • +<% end %> + +<% if courses.size == 5%> +
  • + + +
  • +<% end%> \ No newline at end of file diff --git a/app/views/layouts/_user_courses_list.html.erb b/app/views/layouts/_user_courses_list.html.erb index a5cd6f273..ce9282ee7 100644 --- a/app/views/layouts/_user_courses_list.html.erb +++ b/app/views/layouts/_user_courses_list.html.erb @@ -4,7 +4,7 @@
      <% course_index = 0 %> - <% User.current.courses.reverse.each do |course| %> + <% User.current.courses.each do |course| %> <% if !course_endTime_timeout?(course) %> <%= render :partial => 'layouts/user_homework_list', :locals => {:course => course,:course_index => course_index} %> <% course_index += 1 %> diff --git a/app/views/layouts/_user_project_list.html.erb b/app/views/layouts/_user_project_list.html.erb index 4df61b01b..924bfa9d4 100644 --- a/app/views/layouts/_user_project_list.html.erb +++ b/app/views/layouts/_user_project_list.html.erb @@ -2,7 +2,7 @@
    • <%= link_to l(:label_my_projects), {:controller => 'users', :action => 'user_projects', id: User.current.id, host: Setting.host_name} %>
        - <% User.current.projects.reverse.each do |project| %> + <% User.current.projects.select("projects.*,(SELECT MAX(created_at) FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS a").order("a desc").each do |project| %>
      • <%= link_to project.name, {:controller => 'projects', :action => 'show',id: project.id, host: Setting.host_name } %>
      • diff --git a/app/views/layouts/_user_projects.html.erb b/app/views/layouts/_user_projects.html.erb new file mode 100644 index 000000000..da078c963 --- /dev/null +++ b/app/views/layouts/_user_projects.html.erb @@ -0,0 +1,11 @@ +<% projects.each do |project|%> +
      • + <%= link_to project.name, project_path(project.id,:host=>Setting.host_name), :class => "coursesLineGrey hidden", :title => project.name%> +
      • +<% end %> +<% if projects.size == 5%> +
      • + + +
      • +<% end%> \ No newline at end of file diff --git a/app/views/layouts/_user_watch_btn.html.erb b/app/views/layouts/_user_watch_btn.html.erb index 578319b68..aeb8ee08f 100644 --- a/app/views/layouts/_user_watch_btn.html.erb +++ b/app/views/layouts/_user_watch_btn.html.erb @@ -1,11 +1,11 @@ <% if User.current.logged?%> <% if User.current == target%> - 编辑资料 - <%else%> + <%= link_to("编辑资料", my_account_path, :class => "fl UsersEditBtn")%> + <% else%> <%if(target.watched_by?(User.current))%> - 取消关注 + <%= link_to "取消关注",watch_path(:object_type=> 'user',:object_id=>target.id,:target_id=>target.id),:class => "UsersApBtn", :method => "delete",:remote => "true", :title => "取消关注"%> <% else %> - 添加关注 + <%= link_to "添加关注",watch_path(:object_type=> 'user',:object_id=>target.id,:target_id=>target.id),:class => "UsersAttBtn", :method => "post",:remote => "true", :title => "添加关注"%> <% end %> <% end%> <% end %> \ No newline at end of file diff --git a/app/views/layouts/base.html.erb b/app/views/layouts/base.html.erb index 483cabac5..489820f0c 100644 --- a/app/views/layouts/base.html.erb +++ b/app/views/layouts/base.html.erb @@ -8,28 +8,39 @@ <%= csrf_meta_tag %> <%= favicon %> -<%= stylesheet_link_tag 'jquery/jquery-ui-1.9.2', 'application', 'nyan', :media => 'all' %> +<%= stylesheet_link_tag 'jquery/jquery-ui-1.9.2', 'application','prettify', 'nyan', :media => 'all' %> <%= stylesheet_link_tag 'rtl', :media => 'all' if l(:direction) == 'rtl' %> <%= javascript_heads %> <%= javascript_include_tag "jquery.leanModal.min" %> -<%= javascript_include_tag 'seems_rateable/jRating', 'seems_rateable/rateable'%> +<%= javascript_include_tag 'seems_rateable/jRating','prettify', 'seems_rateable/rateable'%> <%= heads_for_theme %> <%= call_hook :view_layouts_base_html_head %> <%= yield :header_tags -%> + <%= stylesheet_link_tag 'base','header', :media => 'all'%> - + + +
        + +
        +
        -<%=render :partial => 'layouts/base_header'%>
        <%= render_flash_messages %> <%= yield %> <%= call_hook :view_layouts_base_content %>
        - <%=render :partial => 'layouts/base_footer'%> + <%#=render :partial => 'layouts/base_footer'%>
        @@ -41,6 +52,9 @@
        +
        +<%= render :partial => 'layouts/footer' %> +
        <%= call_hook :view_layouts_base_body_bottom %> diff --git a/app/views/layouts/base_courses.html.erb b/app/views/layouts/base_courses.html.erb index 7a32cb67d..7499b7f33 100644 --- a/app/views/layouts/base_courses.html.erb +++ b/app/views/layouts/base_courses.html.erb @@ -1,5 +1,5 @@ -<% course_model %> -<% teacher_num = teacherCount(@course) %> +<%# course_model %> +<% teacher_num = searchTeacherAndAssistant(@course).count %> <% student_num = studentCount(@course) %> <% course_file_num = visable_attachemnts_incourse(@course).count%> <% is_teacher = User.current.logged? && (User.current.admin? || User.current.allowed_to?(:as_teacher,@course)) %> @@ -17,47 +17,22 @@ <%= javascript_heads %> <%= heads_for_theme %> <%= call_hook :view_layouts_base_html_head %> - <%= stylesheet_link_tag 'public', 'leftside', 'jquery/jquery-ui-1.9.2', 'courses'%> - <%= javascript_include_tag "course","header","attachments" %> + <%= stylesheet_link_tag 'jquery/jquery-ui-1.9.2','public', 'leftside','prettify', 'courses','header'%> + <%= javascript_include_tag "course","header","attachments",'prettify' %> <%= yield :header_tags -%> - + + +
        - <%= render :partial => 'layouts/new_header' %> -
        - -
        -
        -

        - - <%= l(:label_courses_community)%> - -

        -

        - <%= l(:label_user_location) %> : - <%= link_to l(:field_homepage), home_path %> - > - - <%=l(:label_courses_management_platform)%> - - > - <%= link_to @course.name, course_path(@course) %> -

        -
        - -
        -
        @@ -72,7 +47,7 @@ <% if is_teacher%> <%= link_to "#{l(:button_configure)}".html_safe, {:controller => 'courses', :action => 'settings', :id => @course}, :class => "pr_join_a" %> <%= set_course_time @course%> - <%= link_to "#{l(:button_copy)}".html_safe, copy_course_course_path(@course.id), :class => "pr_join_a" %> + <%#= link_to "#{l(:button_copy)}".html_safe, copy_course_course_path(@course.id), :class => "pr_join_a" %> <% else%>
        <%= join_in_course_header(@course, User.current) %>
        <% end%> @@ -82,12 +57,12 @@
        <%= @course.name %> - <% if @course.is_public == 0%> + + <% if @course.is_public == 0%> <%= l(:field_is_private)%> - <% end %> - + <% end %>
        @@ -113,12 +88,12 @@
        - <%= render_flash_messages %> <%= yield %> - <%= call_hook :view_layouts_base_content %> + <%#= render_flash_messages %> + <%#= call_hook :view_layouts_base_content %>
        -
        +
        -
        - - <%= render :partial => 'layouts/new_footer' %> -
        + +
        + <%= render :partial => 'layouts/footer' %> +
        + <%= render :partial => 'layouts/new_feedback' %>
      <%= l(:label_send_email)%> <% end %> + <%# 邀请用户的状态 %> + <% unless @inviter_lists.blank? %> +
      +
      +
      项目成员邀请状态列表
      +
      +
      + <% @inviter_lists.each do |inviter_list| %> + + + <% if inviter_list.user != nil %> + + + + + + + <% end %> + +
      + <% if inviter_list.user.active? %> + <%=link_to inviter_list.user.name, user_path(inviter_list.user), :class => "c_eblue" %> + <% else %> + <%= inviter_list.user.name %> + <% end %> + <%= status_for_ivitied(inviter_list, @project) %>
      + <% end %> +
      +
      + <% end %> + + <% unless @inviter_lists.blank? %>
      <% unless @inviters_count.nil? %> diff --git a/app/views/projects/new.html.erb b/app/views/projects/new.html.erb index 98612b733..66d933adc 100644 --- a/app/views/projects/new.html.erb +++ b/app/views/projects/new.html.erb @@ -1,23 +1,112 @@ <% @nav_dispaly_project_label = 1 @nav_dispaly_forum_label = 1 %> +<%= error_messages_for 'project' %> +
      +

      <%= l(:label_project_new)%>

      +
      +
      +
        + <%= labelled_form_for @project do |f| %> +
      • + + + + + +
      • +
        +
      • + + <%= select_tag :project_new_type, options_for_select([["开发模式", "1"], ["研讨模式", "2"], ["圈子模式", "3"]]) %> + <%=l(:label_type_des_development) %> +
      • +
        +
      • + + +
        +
      • +
      • +

        + <%= f.text_field :identifier, :required => true, :size => 60, :style => "width:488px;", :disabled => @project.identifier_frozen?, :maxlength => Project::IDENTIFIER_MAX_LENGTH, + value:"#{User.current.id.to_s + '_' +Time.now.to_s.gsub(' ','_').gsub(':','').gsub('+','')}" %> + <% unless @project.identifier_frozen? %> + + <%= l(:text_length_between, :min => 1, :max => Project::IDENTIFIER_MAX_LENGTH) %> + <%= l(:text_project_identifier_info).html_safe %> + + <% end %>

        +
      • +
      • + + + (打钩为公开,不打钩则不公开,若不公开,仅项目成员可见该项目。) +
        +
      • +
      • +

        + <%= f.text_field :project_type, :value => 0 %> +

        +
      • +
      • + <%= render :partial => 'form_new', :locals => { :f => f } %> +
      • +
      • + 提交 + <%= link_to "取消",user_activities_path(User.current.id),:class => "blue_btn grey_btn fl c_white"%> +
        +
      • + <% end%> +
      +
      +
      -<%= labelled_form_for @project do |f| %> -
      - <%=l(:label_project_new)%> - - -
      -

      - <%=raw l(:label_project_new_description)%> -

      - <%= render :partial => 'form', :locals => { :f => f } %> - - <%= submit_tag l(:button_create), :class => "enterprise"%> - -
      - <%#= submit_tag l(:button_create_and_continue), :name => 'continue' %> - <%= javascript_tag "$('#project_name').focus();" %> -
      -<% end %> +<% html_title(l(:label_project_new)) -%> + + -<% html_title(l(:label_project_new)) -%> \ No newline at end of file diff --git a/app/views/projects/search.html.erb b/app/views/projects/search.html.erb index b77b3fda6..fbb046171 100644 --- a/app/views/projects/search.html.erb +++ b/app/views/projects/search.html.erb @@ -17,13 +17,13 @@ <% end %> <% end %> - + <%= link_to request.host() + "/projects", :controller => 'projects', :action => 'course', :project_type => 1 %> @@ -44,14 +44,14 @@ <%= link_to(l(:label_project_new), {:controller => 'projects', :action => 'new', :course => 0, :project_type => @project_type}, :class => 'icon icon-add') if User.current.allowed_to?(:add_project, nil, :global => true) %> <% end %> - + - + <%#= text_field_tag 'name', params[:name], :size => 30, :onkeyup => "regexName();" %> + <%#= hidden_field_tag 'project_type', params[:project_type] %> + <%#= submit_tag l(:label_search), :class => "enterprise", :name => nil %> <!–修改项目搜索按钮的样式 –> + <!– + <%#= l(:label_search)%> + –>
      - + --> @@ -104,9 +104,13 @@
    <% end %> + - -<%= paginate @project_pages %> +<%#= paginate @project_pages %> diff --git a/app/views/projects/settings.html.erb b/app/views/projects/settings.html.erb index e70e20cef..3fc9a89d6 100644 --- a/app/views/projects/settings.html.erb +++ b/app/views/projects/settings.html.erb @@ -2,13 +2,15 @@ $(function(){ <%if @select_tab%> <%if @select_tab == "modules"%> - project_setting(2); + project_setting(2); + <% elsif @select_tab == "members"%> + project_setting(3); <% elsif @select_tab == "versions"%> - project_setting(4); - $("#pro_st_edit_ban").toggle(); + project_setting(4); + $("#pro_st_edit_ban").toggle(); <% elsif @select_tab == "repositories" %> - project_setting(6); - $("#pro_st_edit_ku").toggle(); + project_setting(6); + $("#pro_st_edit_ku").toggle(); <%else%> <% end%> <% end%> diff --git a/app/views/projects/settings/_new_edit.html.erb b/app/views/projects/settings/_new_edit.html.erb index a8998ece5..b38871a60 100644 --- a/app/views/projects/settings/_new_edit.html.erb +++ b/app/views/projects/settings/_new_edit.html.erb @@ -5,9 +5,8 @@ <%= render :partial=>"avatar/new_avatar_form",:locals=> {source:@project} %>
    -
  • - + @@ -15,25 +14,15 @@
  • - +
  • -
  • - - <%= select_tag :organization_id,options_for_select(project_organizations_id_option,@project.organization_id),{} %> -
  • -
  • >
  • -
  • - - > -
    -
  • 保存 <% end %> diff --git a/app/views/projects/settings/_new_members.html.erb b/app/views/projects/settings/_new_members.html.erb index d91cd0475..e82062e9b 100644 --- a/app/views/projects/settings/_new_members.html.erb +++ b/app/views/projects/settings/_new_members.html.erb @@ -46,7 +46,7 @@ ) do |f| %> <% roles.each do |role| %>
      - <%= check_box_tag 'membership[role_ids][]', role.id, member.roles.include?(role), + <%= radio_button_tag 'membership[role_ids][]', role.id, member.roles.include?(role), :disabled => member.member_roles.detect { |mr| mr.role_id == role.id && !mr.inherited_from.nil? } %> <% if User.current.language == "zh" %> @@ -64,11 +64,11 @@ <% end %> <%= hidden_field_tag 'membership[role_ids][]', '' %> -
      - + @@ -138,7 +138,7 @@ <% roles.each do |role| %>
    • - <%= check_box_tag 'membership[role_ids][]', role.id %> + <%= radio_button_tag 'membership[role_ids][]', role.id %> <% if User.current.language == "zh" %> <% if role.id == 3 %> @@ -154,7 +154,7 @@ <% end %>
    - + 新增成员
    diff --git a/app/views/projects/settings/_new_repositories.html.erb b/app/views/projects/settings/_new_repositories.html.erb index ca771a487..410bd8c32 100644 --- a/app/views/projects/settings/_new_repositories.html.erb +++ b/app/views/projects/settings/_new_repositories.html.erb @@ -59,18 +59,19 @@
    -<%= labelled_form_for :repository, @repository, :url =>project_repositories_path(@project),:html => {:id => 'repository-form',:method=>"post"} do |f| %> +<%= labelled_form_for :repository, @repository, :url =>project_repositories_path(@project),:html => {:id => 'repository-form',:method=>"post",:autocomplete=>'off'} do |f| %>
    • <%= select_tag('repository_scm', - options_for_select(["Git"],@repository.class.name.demodulize), - :data => {:remote => true, :method => 'get'})%> - <% if @repository && ! @repository.class.scm_available %> - <%= l(:text_scm_command_not_available) %> - <% end %> + options_for_select(["Git"],@repository.class.name.demodulize), + :data => {:remote => true, :method => 'get'})%> + <% if @repository && ! @repository.class.scm_available %> + <%= l(:text_scm_command_not_available) %> + <% end %>
    • + <% unless judge_main_repository(@project) %>
    • @@ -78,6 +79,8 @@
    • <% end %>
    • + + <%= f.text_field :identifier, :disabled =>@repository.nil? || @repository.identifier_frozen? ? true:false,:label=>"", :no_label => true %> <% unless @repository.identifier_frozen? %> @@ -86,7 +89,7 @@
    • - <%= f.password_field :upassword, :label=> "", :no_label => true %> + <%= f.password_field :upassword, :label=> "", :no_label => true%> <%= l(:label_upassword_info)%>
    • @@ -94,4 +97,4 @@ <%=l(:button_save)%> <%=l(:button_cancel)%>
    -<% end %> \ No newline at end of file +<% end %> diff --git a/app/views/projects/settings/_new_versions.html.erb b/app/views/projects/settings/_new_versions.html.erb index feb08bac5..557025eaa 100644 --- a/app/views/projects/settings/_new_versions.html.erb +++ b/app/views/projects/settings/_new_versions.html.erb @@ -13,8 +13,8 @@ <%= l(:field_effective_date) %> <%= l(:field_description) %> <%= l(:field_status) %> - <%= l(:field_sharing) %> - <%= l(:label_wiki_page) %> + + <% for version in @project.shared_versions.sort %> @@ -25,13 +25,13 @@ <%= format_date(version.effective_date) %> <%=h version.description %> <%= l("version_status_#{version.status}") %> - <%=h format_version_sharing(version.sharing) %> - - <%= link_to_if_authorized(h(truncate(version.wiki_page_title,:length=>20)), {:controller => 'wiki', - :action => 'show', - :project_id => version.project, + + + <%#= link_to_if_authorized(h(truncate(version.wiki_page_title,:length=>20)), {:controller => 'wiki', +# :action => 'show', +# :project_id => version.project, :id => Wiki.titleize(version.wiki_page_title)},:class=>"c_blue02") || h(version.wiki_page_title) unless version.wiki_page_title.blank? || version.project.wiki.nil? %> - + <% if version.project == @project && User.current.allowed_to?(:manage_versions, @project) %> <%= link_to l(:button_edit), edit_version_path(version), :class => 'c_purple' %> @@ -68,20 +68,20 @@ <%= f.select :status, Version::VERSION_STATUSES.collect {|s| [l("version_status_#{s}"), s]} %> -
  • - - <%= f.text_field :wiki_page_title, :size =>60, :label => :label_wiki_page, :disabled => @project.wiki.nil? %> -
  • + + + +
  • <%= f.text_field :effective_date, :size => 10, :readonly => true,:class=>" fl" %> <%= calendar_for('version_effective_date') %>
  • -
  • - - <%= f.select :sharing, @project.versions.build.allowed_sharings.collect {|v| [format_version_sharing(v), v]} %> -
  • + + + + <%=l(:button_save)%> diff --git a/app/views/projects/show.html.erb b/app/views/projects/show.html.erb index f1b3d9b7b..22317dc91 100644 --- a/app/views/projects/show.html.erb +++ b/app/views/projects/show.html.erb @@ -24,7 +24,7 @@ <% if e.forge_act_type == "Issue" %>
    <%= image_tag(url_to_avatar(act.author), :width => "42", :height => "42") %> -
    +
    <%= h(e.project) if @project.nil? || @project.id != e.project_id %> <%= link_to act.author, user_path(act.author), :class => "problem_name c_orange fl" %> <%= l(:label_new_activity) %> : @@ -34,7 +34,7 @@ :id => act.id}, :class => "problem_tit fl fb " %>
    -

    <%= textAreailizable act,:description %>
    +

    <%= act.description.html_safe %>
    <%= l :label_activity_time %> :<%= format_activity_day(act.created_on) %> <%= format_time(act.created_on, false) %>

    @@ -51,7 +51,7 @@ <%= link_to format_activity_title("#{act.issue.tracker} ##{act.issue.project_issues_index}: #{act.issue.subject}"), {:controller => 'issues', :action => 'show', :id => act.issue.id, :anchor => "change-#{act.id}"}, :class => "problem_tit fl fb" %>
    -

    <%= textilizable act,:notes %>
    +

    <%= act.notes.html_safe %>
    <%= l :label_activity_time %> :<%= format_activity_day(act.created_on) %> <%= format_time(act.created_on, false) %>

    @@ -60,7 +60,7 @@ <% elsif e.forge_act_type == "Message" %>
    <%= image_tag(url_to_avatar(e.user), :width => "42", :height => "42") %> -
    +
    <%= h(e.project) if @project.nil? || @project.id != e.project_id %> <%= link_to h(e.user), user_path(e.user_id), :class => "problem_name c_orange fl" %> <%= l(:label_new_activity) %> : @@ -79,7 +79,7 @@ <% elsif e.forge_act_type == "News" %>
    <%= image_tag(url_to_avatar(e.user), :width => "42", :height => "42") %> -
    +
    <%= h(e.project) if @project.nil? || @project.id != e.project_id %> <%= link_to h(e.user), user_path(e.user_id), :class => "problem_name c_orange fl" %> <%= l(:label_new_activity) %> : diff --git a/app/views/projects/soft_file.html.erb b/app/views/projects/soft_file.html.erb deleted file mode 100644 index 9e486dd78..000000000 --- a/app/views/projects/soft_file.html.erb +++ /dev/null @@ -1,46 +0,0 @@ -
    -

    <%= l(:label_project_soft_file) %>

    -
    - - - -
    -
    -

    软件资源库部署中...

    -
    -
    0%
    -
    - -
    -
    -
    -
    - - \ No newline at end of file diff --git a/app/views/projects/soft_knowledge.html.erb b/app/views/projects/soft_knowledge.html.erb deleted file mode 100644 index bcb745357..000000000 --- a/app/views/projects/soft_knowledge.html.erb +++ /dev/null @@ -1,46 +0,0 @@ -
    -

    <%= l(:label_project_soft_knowledge) %>

    -
    - - - -
    -
    -

    云化部署中...

    -
    -
    0%
    -
    - -
    -
    -
    -
    - - \ No newline at end of file diff --git a/app/views/projects/soft_service.html.erb b/app/views/projects/soft_service.html.erb deleted file mode 100644 index 43376b915..000000000 --- a/app/views/projects/soft_service.html.erb +++ /dev/null @@ -1,46 +0,0 @@ -
    -

    <%= l(:label_project_soft_service) %>

    -
    - - - -
    -
    -

    云化部署中...

    -
    -
    0%
    -
    - -
    -
    -
    -
    - - \ No newline at end of file diff --git a/app/views/projects/yun_dep.html.erb b/app/views/projects/yun_dep.html.erb deleted file mode 100644 index 7a774f4e4..000000000 --- a/app/views/projects/yun_dep.html.erb +++ /dev/null @@ -1,47 +0,0 @@ -
    -

    <%= l(:label_project_dts_yun) %>

    -
    - - - -
    -
    -

    云化部署中....

    -
    -
    -
    - -
    -
    -
    -
    - - \ No newline at end of file diff --git a/app/views/repositories/show.html.erb b/app/views/repositories/show.html.erb index 474ac638f..28a260178 100644 --- a/app/views/repositories/show.html.erb +++ b/app/views/repositories/show.html.erb @@ -29,78 +29,6 @@

    - -
    -
    -
    -

    项目代码请设置好正确的编码方式(utf-8),否则中文会出现乱码。

    -

    通过cmd命令提示符进入代码对应文件夹的根目录,假设当前用户的登录名为user,版本库名称为demo,需要操作的版本库分支为branch。 - 如果是首次提交代码,执行如下命令:

    -
    -
    -

    git init

    - -

    git add *

    - -

    git commit -m "first commit"

    - -

    git remote add origin - http://user_demo@repository.trustie.net/user/demo.git -

    - -

    git config http.postBuffer 524288000 #设置本地post缓存为500MB

    - -

    git push -u origin branch:branch

    -
    - -
    -

    已经有本地库,还没有配置远程地址,打开命令行执行如下:

    -
    -
    -

    git remote add origin http://user_demo@repository.trustie.net/user/demo.git

    - -

    git add .

    - -

    git commit -m "first commit"

    - -

    git config http.postBuffer 524288000 #设置本地post缓存为500MB

    - -

    git push -u origin branch:branch

    -
    - -
    -

    已有远程地址,创建一个远程分支,并切换到该分支,打开命令行执行如下:

    -
    -
    -

    git clone http://user_demo@repository.trustie.net/user/demo.git

    - -

    git push

    - -

    git checkout -b branch_name

    - -

    git push origin branch_name

    -
    - -
    -

    从网上获取别人的开源版本库,转交到trustie网站上,打开命令行执行如下:

    -
    -
    -

    git remote add trustie - http://user_demo@repository.trustie.net/user/demo.git -

    - -

    git add .

    - -

    git commit -m "first commit"

    - -

    git config http.postBuffer 524288000 #设置本地post缓存为500MB

    - -

    git push -u trustie branch:branch

    - -

    李海提供

    -
    -
    - <% if !@entries.nil? && authorize_for('repositories', 'browse') %> <%= render :partial => 'dir_list' %> <% end %> @@ -148,10 +76,7 @@ <% end %> -

    查看如何提交代码: - <%= link_to(l(:label_how_commit_code_chinese), ch_usage_path, :class => "c_blue") %> - <%= link_to('English', en_usage_path, :class => "c_blue") %> - +

    点击查看如何提交代码

    <% content_for :header_tags do %> diff --git a/app/views/student_work/_add_score_reply.html.erb b/app/views/student_work/_add_score_reply.html.erb index 2866b2da6..417d3d2c1 100644 --- a/app/views/student_work/_add_score_reply.html.erb +++ b/app/views/student_work/_add_score_reply.html.erb @@ -1,4 +1,5 @@ <%= form_for('', :remote => true, :method => :post,:url => add_score_reply_student_work_index_path(:score_id => score.id)) do |f|%> <%= f.text_area 'message', :class => 'ping_text', :placeholder => l(:text_caracters_maximum,:count=>250),:maxlength => 250 %> + 回复 <% end%> \ No newline at end of file diff --git a/app/views/student_work/_evaluation_student_work.html.erb b/app/views/student_work/_evaluation_student_work.html.erb index 9569718fb..368c636df 100644 --- a/app/views/student_work/_evaluation_student_work.html.erb +++ b/app/views/student_work/_evaluation_student_work.html.erb @@ -48,8 +48,10 @@  <%= student_work.final_score%> 分。 迟交扣分  <%= student_work.late_penalty%> 分, - 缺评扣分 -  <%= student_work.absence_penalty%> 分, + <% if student_work.homework_common.homework_type == 1%> + 缺评扣分 +  <%= student_work.absence_penalty%> 分, + <% end%> 最终成绩为  <%= format("%.1f",score)%> 分。
    diff --git a/app/views/student_work/_evaluation_student_work_title.html.erb b/app/views/student_work/_evaluation_student_work_title.html.erb deleted file mode 100644 index f19438f78..000000000 --- a/app/views/student_work/_evaluation_student_work_title.html.erb +++ /dev/null @@ -1,47 +0,0 @@ -
  • - 学号 -
  • -
  • - <%= link_to "姓名",@show_all ? student_work_index_path(:homework => @homework.id,:order => "name", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "f14 f_b c_dark fl"%> - <% if @show_all && @order == "name"%> - <%= link_to "",student_work_index_path(:homework => @homework.id,:order => "name", :sort => @score, :name => @name, :group => @group) ,:class => @score == 'desc' ? 'st_up' : 'st_down'%> - <% end%> -
  • -
  • - 作品名称 -
  • -
  • - <%= link_to "时间",@show_all ? student_work_index_path(:homework => @homework.id,:order => "created_at", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "f14 f_b c_dark fl"%> - <% if @show_all && @order == "created_at"%> - <%= link_to "",student_work_index_path(:homework => @homework.id,:order => "created_at", :sort => @score, :name => @name, :group => @group) ,:class => @score == 'desc' ? 'st_up' : 'st_down'%> - <% end%> -
  • -
  • - <%= link_to "教师",@show_all ? student_work_index_path(:homework => @homework.id,:order => "teacher_score", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "f14 f_b c_dark fl"%> - <% if @show_all && @order == "teacher_score"%> - <%= link_to "", student_work_index_path(:homework => @homework.id,:order => "teacher_score", :sort => @score, :name => @name, :group => @group) ,:class => @score == 'desc' ? 'st_up' : 'st_down'%> - <% end%> -
  • -
  • - <%= link_to "教辅",@show_all ? student_work_index_path(:homework => @homework.id,:order => "teaching_asistant_score", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "f14 f_b c_dark fl"%> - <% if @show_all && @order == "teaching_asistant_score"%> - <%= link_to "", student_work_index_path(:homework => @homework.id,:order => "teaching_asistant_score", :sort => @score, :name => @name, :group => @group) ,:class => @score == 'desc' ? 'st_up' : 'st_down'%> - - <% end%> -
  • -
  • - <% if @homework.homework_type == 1%> - <%= link_to "匿评",@show_all ? student_work_index_path(:homework => @homework.id,:order => "student_score", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "f14 f_b c_dark fl"%> - <% elsif @homework.homework_type == 2%> - <%= link_to "系统",@show_all ? student_work_index_path(:homework => @homework.id,:order => "student_score", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "f14 f_b c_dark fl"%> - <% end %> - <% if @show_all && @order == "student_score"%> - <%= link_to "", student_work_index_path(:homework => @homework.id,:order => "student_score", :sort => @score, :name => @name, :group => @group) ,:class => @score == 'desc' ? 'st_up' : 'st_down'%> - <% end%> -
  • -
  • - <%= link_to "成绩",@show_all ? student_work_index_path(:homework => @homework.id,:order => "score", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "f14 f_b c_dark fl"%> - <% if @show_all && @order == "score"%> - <%= link_to "", student_work_index_path(:homework => @homework.id,:order => "score", :sort => @score, :name => @name, :group => @group) ,:class => @score == 'desc' ? 'st_up' : 'st_down'%> - <% end%> -
  • \ No newline at end of file diff --git a/app/views/student_work/_evaluation_title.html.erb b/app/views/student_work/_evaluation_title.html.erb new file mode 100644 index 000000000..cfd9632c2 --- /dev/null +++ b/app/views/student_work/_evaluation_title.html.erb @@ -0,0 +1,15 @@ +
      +
    • + 作品名称 + 姓名 + 学号 +
    • + +
    • + 时间 +
    • + +
    • + 我的评分 +
    • +
    \ No newline at end of file diff --git a/app/views/student_work/_evaluation_un_title.html.erb b/app/views/student_work/_evaluation_un_title.html.erb new file mode 100644 index 000000000..9a21e109b --- /dev/null +++ b/app/views/student_work/_evaluation_un_title.html.erb @@ -0,0 +1,51 @@ +
      +
    • + 作品名称 + 姓名 + 学号 +
    • + +
    • + <%= link_to "时间",@show_all ? student_work_index_path(:homework => @homework.id,:order => "created_at", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "c_dark f14 fb fl ml50" ,:remote => true%> + <% if @show_all && @order == "created_at"%> + <%= link_to "", student_work_index_path(:homework => @homework.id,:order => "created_at", :sort => @score, :name => @name, :group => @group) ,:class => "#{@score == 'desc' ? 'st_up' : 'st_down'} mt10",:remote => true%> + <% end%> +
    • + +
    • + <%= link_to "教师",@show_all ? student_work_index_path(:homework => @homework.id,:order => "teacher_score", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "c_dark f14 fb fl ml10" ,:remote => true%> + <% if @show_all && @order == "teacher_score"%> + <%= link_to "", student_work_index_path(:homework => @homework.id,:order => "teacher_score", :sort => @score, :name => @name, :group => @group) ,:class => "#{@score == 'desc' ? 'st_up' : 'st_down'} mt10" ,:remote => true%> + <% end%> +
    • + +
    • + <%= link_to "教辅",@show_all ? student_work_index_path(:homework => @homework.id,:order => "teaching_asistant_score", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "c_dark f14 fb fl ml10",:remote => true%> + <% if @show_all && @order == "teaching_asistant_score"%> + <%= link_to "", student_work_index_path(:homework => @homework.id,:order => "teaching_asistant_score", :sort => @score, :name => @name, :group => @group) ,:class => "#{@score == 'desc' ? 'st_up' : 'st_down'} mt10",:remote => true%> + <% end%> +
    • + + <% if @homework.homework_type == 2%> +
    • + <%= link_to "系统",@show_all ? student_work_index_path(:homework => @homework.id,:order => "system_score", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "c_dark f14 fb fl ml10",:remote => true%> + <% if @show_all && @order == "system_score"%> + <%= link_to "", student_work_index_path(:homework => @homework.id,:order => "system_score", :sort => @score, :name => @name, :group => @group) ,:class => "#{@score == 'desc' ? 'st_up' : 'st_down'} mt10",:remote => true%> + <% end%> +
    • + <% end%> + +
    • + <%= link_to "匿评",@show_all ? student_work_index_path(:homework => @homework.id,:order => "student_score", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "c_dark f14 fb fl ml10",:remote => true%> + <% if @show_all && @order == "student_score"%> + <%= link_to "", student_work_index_path(:homework => @homework.id,:order => "student_score", :sort => @score, :name => @name, :group => @group) ,:class => "#{@score == 'desc' ? 'st_up' : 'st_down'} mt10",:remote => true%> + <% end%> +
    • + +
    • + <%= link_to "成绩",@show_all ? student_work_index_path(:homework => @homework.id,:order => "score", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "c_dark f14 fb fl ml10",:remote => true%> + <% if @show_all && @order == "score"%> + <%= link_to "", student_work_index_path(:homework => @homework.id,:order => "score", :sort => @score, :name => @name, :group => @group) ,:class => "#{@score == 'desc' ? 'st_up' : 'st_down'} mt10",:remote => true%> + <% end%> +
    • +
    \ No newline at end of file diff --git a/app/views/student_work/_evaluation_un_work.html.erb b/app/views/student_work/_evaluation_un_work.html.erb new file mode 100644 index 000000000..94fcfcee2 --- /dev/null +++ b/app/views/student_work/_evaluation_un_work.html.erb @@ -0,0 +1,83 @@ + +
      +
    • +
        +
      • + <%= link_to(image_tag(url_to_avatar(student_work.user),:width =>"40",:height => "40"),user_activities_path(User.current.id))%> +
      • +
        +
      • + <% student_work_name = student_work.name.nil? || student_work.name.empty? ? student_work.user.show_name + '的作品' : student_work.name%> +
        + <%= link_to student_work_name,"javascript:void(0)" ,:title => student_work_name, :class => "linkGrey f14 StudentName break_word #{@homework.homework_type == 2 ? '' : 'width165'}"%> +
        +
      • +
      • +
          +
        • + <%= student_work.user.show_name%> +
        • +
        • + <%= student_work.user.user_extensions.nil? ? "--" : student_work.user.user_extensions.student_id%> +
        • +
        +
      • +
        +
      +
    • +
    • + <% if student_work.created_at && @homework.end_time%> + <%= Time.parse(format_time(student_work.created_at)).strftime("%m-%d %H:%M")%>  + <% if Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") < Time.parse(student_work.created_at.to_s).strftime("%Y-%m-%d") %> + [迟交] + <% end %> + <% end %> +
    • +
    • + <%= student_work.teacher_score.nil? ? "--" : format("%.1f",student_work.teacher_score)%> +
    • +
    • + <%= student_work.teaching_asistant_score.nil? ? "--" : format("%.1f",student_work.teaching_asistant_score)%> +
    • + + <% if @homework.homework_type == 2%> + +
    • + <%= student_work.system_score.nil? ? "--" : format("%.1f",student_work.system_score)%> +
    • + <% end%> + +
    • + <%= student_work.student_score.nil? ? "--" : format("%.1f",student_work.student_score)%> + <% unless student_work.student_score.nil?%> + + (<%= student_work.student_works_scores.where(:reviewer_role => 3).count%>) + +
      + 现共有 +  <%= student_work.student_works_scores.where(:reviewer_role => 3).count%>  + 名学生进行了匿评,平均分为 +  <%= format("%.1f",student_work.student_score)%> 分。 +
      + <% end%> +
    • + + + <% score = student_work.respond_to?("score") ? student_work.score : (student_work.final_score || 0) - student_work.absence_penalty - student_work.late_penalty%> +
    • + <%= score.nil? ? "--" : format("%.1f",score)%> + <% unless score.nil?%> +
      + 作品最终评分为 +  <%= student_work.final_score%> 分。 + 迟交扣分 +  <%= student_work.late_penalty%> 分, + 缺评扣分 +  <%= student_work.absence_penalty%> 分, + 最终成绩为 +  <%= format("%.1f",score)%> 分。 +
      + <% end%> +
    • +
    + diff --git a/app/views/student_work/_evaluation_work.html.erb b/app/views/student_work/_evaluation_work.html.erb index be07269c3..63cb7ea99 100644 --- a/app/views/student_work/_evaluation_work.html.erb +++ b/app/views/student_work/_evaluation_work.html.erb @@ -1,29 +1,62 @@ -
      " id="student_work_<%= student_work.id%>"> +
        <% is_my_work = student_work.user == User.current%> -
      • - <% if is_my_work%> - - <%= student_work.user.user_extensions.nil? ? "--" : student_work.user.user_extensions.student_id%> - - <% else%> - -- - <% end%> +
      • +
          + <% if is_my_work%> +
        • + <%= image_tag(url_to_avatar(student_work.user),width:"40", height: "40") %> +
        • +
        • + <% student_work_name = student_work.name.nil? || student_work.name.empty? ? student_work.user.show_name + '的作品' : student_work.name%> +
          + <%= link_to student_work_name, student_work_path(student_work),:remote => true,:title => student_work_name, :class => "linkGrey f14 StudentName break_word width285"%> +
          +
        • +
        • +
            +
          • + <%= student_work.user.show_name%> +
          • +
          • + <%= student_work.user.user_extensions.nil? ? "--" : student_work.user.user_extensions.student_id%> +
          • +
          +
        • + <% else%> +
        • + <%= image_tag(url_to_avatar(""),width:"40", height: "40") %> +
        • +
        • +
          + <%= link_to "匿名的作品", student_work_path(student_work),:remote => true,:title => student_work_name, :class => "linkGrey f14 StudentName break_word width285"%> +
          +
        • +
        • +
            +
          • + 匿名 +
          • +
          • + -- +
          • +
          +
        • + <% end%> + +
      • -
      • - <% if is_my_work%> - <%= link_to student_work.user.show_name,user_path(student_work.user),:title => student_work.user.show_name, :class => "c_blue02" %> - <% else%> - <%= link_to "匿名","javascript:void(0)", :class => "c_blue02"%> - <% end%> -
      • -
      • - <% student_work_name = student_work.name.nil? || student_work.name.empty? ? '匿名的作品' : student_work.name%> - <%= link_to student_work_name, student_work_path(student_work),:remote => true, :title => student_work.name, :class => "c_blue02"%> +
      • + <%= Time.parse(format_time(student_work.created_at)).strftime("%m-%d %H:%M")%>  + <% if Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") < Time.parse(student_work.created_at.to_s).strftime("%Y-%m-%d") %> + [迟交] + <% end %>
      • + + <% my_score = student_work_score(student_work,User.current) %> -
      • - <%= my_score.nil? ? "--" : format("%.2f",my_score.score)%> +
      • + <%= my_score.nil? ? "--" : format("%.1f",my_score.score)%>
      • -
        -
      \ No newline at end of file +
    + diff --git a/app/views/student_work/_evaluation_work_title.html.erb b/app/views/student_work/_evaluation_work_title.html.erb deleted file mode 100644 index 0be6228bb..000000000 --- a/app/views/student_work/_evaluation_work_title.html.erb +++ /dev/null @@ -1,12 +0,0 @@ -
  • - 学号 -
  • -
  • - 学生姓名 -
  • -
  • - 作品名称 -
  • -
  • - <%= link_to "我的评分","javascript:void(0)",:class => "c_dark f14 fb fl"%> -
  • \ No newline at end of file diff --git a/app/views/student_work/_jour_replay.html.erb b/app/views/student_work/_jour_replay.html.erb index 77fb476bf..4b594d7f4 100644 --- a/app/views/student_work/_jour_replay.html.erb +++ b/app/views/student_work/_jour_replay.html.erb @@ -6,9 +6,9 @@ <% if jour.user==User.current || User.current.admin? %> <%= link_to(l(:label_bid_respond_delete), destroy_score_reply_student_work_index_path(:jour_id => jour.id), - :remote => true, :confirm => l(:text_are_you_sure), :title => l(:button_delete), :class => "fr c_purple") %> + :remote => true, :confirm => l(:text_are_you_sure), :title => l(:button_delete), :class => "fr linkBlue mr5") %> <% end %> - + <%=format_time jour.created_on %>
    diff --git a/app/views/student_work/_new_project.html.erb b/app/views/student_work/_new_project.html.erb new file mode 100644 index 000000000..3d9214c7d --- /dev/null +++ b/app/views/student_work/_new_project.html.erb @@ -0,0 +1,31 @@ +
    + <%= labelled_form_for(Project.new,:remote => "true") do |f| %> +

    新建项目

    +
    +
    +
    + + +

    +
    +
    + +

    + +
    + +
    + +
    + + 确定 + + 取消 +
    +
    + <% end%> +
    +
    diff --git a/app/views/student_work/_programing_work_show.html.erb b/app/views/student_work/_programing_work_show.html.erb index b259e20a5..b5ff8f064 100644 --- a/app/views/student_work/_programing_work_show.html.erb +++ b/app/views/student_work/_programing_work_show.html.erb @@ -1,78 +1,102 @@
    -
    +
    • - - 上交时间: - + 上交时间: <%=format_time @work.created_at %>
    • - <% if @work.user != User.current%> - + + <% if @work.user == User.current && @homework.homework_detail_manual.comment_status == 1 %> + +
    • + <%= link_to("", student_work_path(@work),:method => 'delete', :confirm => l(:text_are_you_sure), :class => "pic_del") %> +
    • +
    • + <%= link_to "",new_student_work_path(:homework => @homework.id),:class => "pic_edit"%> +
    • + <% end%> + <% if @homework.homework_detail_manual.comment_status == 3 && @work.user != User.current%> +
    • <%= render :partial => 'student_work_praise' %>
    • <% end%>
      +
    • - - 编程代码: - -
      - <%= text_format @work.description%> + 编程代码: +
      + <%= text_format(@work.description) if @work.description%>
    • <% if @is_teacher%> -
    • 测试结果: - - - - - - - - <%@homework.homework_tests.each do |test|%> - "> - - - <% student_work_test = StudentWorkTest.where(:homework_test_id => test.id,:student_work_id => @work.id).first%> - - - - <% end%> - <% student_work_test = @work.student_work_test.first%> - <% if student_work_test && student_work_test.error_msg && !student_work_test.error_msg.empty?%> - - - - <% end%> - - -
      输入输出测试结果
      <%= student_work_test.nil? ? "正在编译" : student_work_test.status_to_s%>
      - <%= student_work_test.error_msg%> -
      -
      +
    • + + 测试结果: + +
      + <% @work.student_work_tests.each_with_index do |test, index| %> +
      +

      + 第<%= @work.student_work_tests.count - index%>次测试 +

      + + <%= test.created_at.to_s(:db) %> + +
      +
      + <% if test.status.to_i == -2 %> +
      + <%= test.results.first %> +
      + <% else %> +
      +
        + <% test.results.each_with_index do |x, i| %> +
      • + 测试<%=i+1%> + <% if x["status"].to_i != 0 %> + 测试错误! + 您的输出: + <%=x["result"]%> + 正确输出: + <%=x["output"]%> +
        + <% else %> + 测试正确! +
        + <% end %> +
      • + <% end %> +
      +
      + <% end %> + <% end %> +
    • - -
      - <%= render :partial => 'add_score',:locals => {:work => @work,:score => @score}%> -
      <% end%> + +
    • + <% if @is_teacher || (@homework.homework_detail_manual.comment_status == 2 && @work.user != User.current )%> + +
      + <%= render :partial => 'add_score',:locals => {:work => @work,:score => @score}%> +
      + <% end%> +
      +
    -
    - <%@work.student_works_scores.order("updated_at desc").each do |score|%> +
    + <%@student_work_scores.each do |score|%>
    - <%= render :partial => 'student_work_score',:locals => {:score => score}%> + <%= render :partial => 'student_work_score',:locals => {:score => score,:is_last => score == @student_work_scores.last}%>
    <% end%> -
    - 收起 +
    + + 收起
    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/app/views/student_work/_set_score_rule.html.erb b/app/views/student_work/_set_score_rule.html.erb new file mode 100644 index 000000000..7deed7fb8 --- /dev/null +++ b/app/views/student_work/_set_score_rule.html.erb @@ -0,0 +1,63 @@ +<%= form_for('new_form',:url => {:controller => 'student_work',:action => 'set_score_rule',:homework => homework.id},:method => "post") do |f|%> +
    + 评分设置 +
    + 迟交扣分 + +
    +
    + 缺评扣分 + +
    + + <% if homework.homework_type == 2%> +
    + 系统评分 + <%= select_tag :sy_proportion,options_for_select(ta_proportion_option,homework.homework_detail_programing.ta_proportion), {:class => "markPercentage"} %> +
    + + + <% else%> + + <% end%> + +
    + 教辅评分 + <%= select_tag :ta_proportion,options_for_select(ta_proportion_option_to(100-(homework.homework_detail_programing ? homework.homework_detail_programing.ta_proportion * 100 : 0).to_i),homework.homework_detail_manual.ta_proportion), {:class => "markPercentage"} %> +
    +
    + 学生匿评 + +
    +
    + 教师优先 + /> + 教师评分为最终评分 +
    +
    +
    + 确定 +
    +
    + 取消 +
    +
    +
    +
    +<% end%> diff --git a/app/views/student_work/_show.html.erb b/app/views/student_work/_show.html.erb index f6580659e..2aa14be71 100644 --- a/app/views/student_work/_show.html.erb +++ b/app/views/student_work/_show.html.erb @@ -1,72 +1,74 @@
    -
    -
      -
    • - 上交时间: - <%=format_time @work.created_at %> -
    • +
      +
        +
      • + 上交时间: + <%=format_time @work.created_at %> +
      • - <% if !@is_teacher && @work.user == User.current && (@homework.homework_type != 1 || @homework.homework_detail_manual.comment_status == 1) %> - -
      • - <%= link_to("", student_work_path(@work),:method => 'delete', :confirm => l(:text_are_you_sure), :class => "pic_del") %> -
      • -
      • - <%= link_to "",edit_student_work_path(@work),:class => "pic_edit"%> -
      • - <% end%> - <% if (@homework.homework_type != 1 || @homework.homework_detail_manual.comment_status == 3) && @work.user != User.current%> - -
      • - <%= render :partial => 'student_work_praise' %> -
      • - <% end%> -
        - - - - - - <% if @work.project%> -
      • - 关联项目: - <%= link_to( @work.project.name, project_path(@work.project.id), :class => "c_blue02" )%> -
      • - <% end%> -
      • - 内容: -
        - <%= text_format(@work.description) if @work.description%> -
        + <% if @work.user == User.current && @homework.homework_detail_manual.comment_status == 1 %> + +
      • + <%= link_to("", student_work_path(@work),:method => 'delete', :confirm => l(:text_are_you_sure), :class => "pic_del") %> +
      • +
      • + <%= link_to "",edit_student_work_path(@work),:class => "pic_edit"%> +
      • + <% end%> + <% if @homework.homework_detail_manual.comment_status == 3 && @work.user != User.current%> + +
      • + <%= render :partial => 'student_work_praise' %> +
      • + <% end%>
        - -
      • - 附件: - <% if @work.attachments.empty?%> - 尚未提交附件 - <% else%> -
        - <%= render :partial => 'work_attachments', :locals => {:attachments => @work.attachments} %> -
        + + + + <% if @work.project%> +
      • + 关联项目: + <%= link_to( @work.project.name, project_path(@work.project.id), :class => "linkBlue" )%> +
      • <% end%> - -
        - <% if @is_teacher || (@homework.homework_type == 1 && @homework.homework_detail_manual.comment_status == 2 && @work.user != User.current )%> - -
        - <%= render :partial => 'add_score',:locals => {:work => @work,:score => @score}%> +
      • + 内容: +
        + <%= text_format(@work.description) if @work.description%>
        - <% end%> -
      +
      + +
    • + 附件: + <% if @work.attachments.empty?%> + 尚未提交附件 + <% else%> +
      + <%= render :partial => 'work_attachments', :locals => {:attachments => @work.attachments} %> +
      + <% end%> +
      +
    • +
    • + <% if @is_teacher || (@homework.homework_detail_manual.comment_status == 2 && @work.user != User.current )%> + +
      + <%= render :partial => 'add_score',:locals => {:work => @work,:score => @score}%> +
      + <% end%> +
      +
    • +
    -
    - <%@work.student_works_scores.order("updated_at desc").each do |score|%> -
    - <%= render :partial => 'student_work_score',:locals => {:score => score}%> -
    - <% end%> -
    -收起 -
    -
    \ No newline at end of file +
    + <%@student_work_scores.each do |score|%> +
    + <%= render :partial => 'student_work_score',:locals => {:score => score,:is_last => score == @student_work_scores.last}%> +
    + <% end%> +
    + + 收起 +
    +
    \ No newline at end of file diff --git a/app/views/student_work/_student_work_list.html.erb b/app/views/student_work/_student_work_list.html.erb new file mode 100644 index 000000000..197fecac9 --- /dev/null +++ b/app/views/student_work/_student_work_list.html.erb @@ -0,0 +1,36 @@ +
    + + 作品 + + (<%= @stundet_works.count%>) + + + <%if @is_teacher || @homework.homework_detail_manual.comment_status == 3%> +
    + + +
    + <%= select_tag(:student_work_in_group,options_for_select(course_group_list(@course),@group), {:class => "classSplit"}) unless course_group_list(@course).empty? %> + <% end%> +
    +
    + +
    + <% if @is_evaluation && !@stundet_works.empty?%> + <%= render :partial => "evaluation_title"%> + <% else%> + <%= render :partial => "evaluation_un_title"%> + <% end%> +
    +
    + +<% @stundet_works.each do |student_work|%> + <% if @is_evaluation%> + <%= render :partial => "evaluation_work", :locals => {:student_work => student_work}%> + <% else%> + <%= render :partial => "evaluation_un_work", :locals => {:student_work => student_work}%> + <% end%> +
    +
    +
    +<% end%> \ No newline at end of file diff --git a/app/views/student_work/_student_work_score.html.erb b/app/views/student_work/_student_work_score.html.erb index 8d10853f8..c800ae8d0 100644 --- a/app/views/student_work/_student_work_score.html.erb +++ b/app/views/student_work/_student_work_score.html.erb @@ -1,24 +1,31 @@ -
      +
        <% show_real_name = @is_teacher || score.user == User.current || score.user.allowed_to?(:as_teacher,@course) %> <%= link_to image_tag(url_to_avatar(show_real_name ? score.user : ""), :width => "34", :height => "34"), show_real_name ? user_path(score.user) : "javascript:void(0)",:class => "ping_pic fl" %> -
        - <%= link_to show_real_name ? score.user.show_name : "匿名", show_real_name ? user_path(score.user) : "javascript:void(0)", :title => show_real_name ? score.user.show_name : "匿评用户", :class => "c_blue fl" %> - (<%= student_work_score_role score%>) +
        + <%= link_to show_real_name ? score.user.show_name : "匿名", show_real_name ? user_path(score.user) : "javascript:void(0)", :title => show_real_name ? score.user.show_name : "匿评用户", :class => "linkBlue fl" %> + + (<%= student_work_score_role score%>) + 评分: - <%= score.score%>分 - 回复 - - <%=format_time score.updated_at %> - + + <%= score.score%>分 + + 回复 + + <%=format_time score.updated_at %> +
        +

        <%= score.comment%>

        + <%= render :partial => 'work_attachments', :locals => {:attachments => score.attachments} %>
        +
        - <%= render :partial => 'add_score_reply',:locals => {:score => score}%> + <%= render :partial => 'add_score_reply',:locals => {:score => score,:is_last => is_last}%>
        @@ -27,6 +34,6 @@ <%= render :partial => 'jour_replay',:locals => {:jour => jour}%> <% end%>
        +
        -
        -
      \ No newline at end of file +
    diff --git a/app/views/student_work/_student_work_title.html.erb b/app/views/student_work/_student_work_title.html.erb deleted file mode 100644 index 24e6a1b37..000000000 --- a/app/views/student_work/_student_work_title.html.erb +++ /dev/null @@ -1,37 +0,0 @@ -
  • - 学号 -
  • -
  • - <%= link_to "姓名",@show_all ? student_work_index_path(:homework => @homework.id,:order => "name", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "f14 f_b c_dark fl"%> - <% if @show_all && @order == "name"%> - <%= link_to "",student_work_index_path(:homework => @homework.id,:order => "name", :sort => @score, :name => @name, :group => @group) ,:class => @score == 'desc' ? 'st_up' : 'st_down'%> - <% end%> -
  • -
  • - 作品名称 -
  • -
  • - <%= link_to "时间",@show_all ? student_work_index_path(:homework => @homework.id,:order => "created_at", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "f14 f_b c_dark fl"%> - <% if @show_all && @order == "created_at"%> - <%= link_to "",student_work_index_path(:homework => @homework.id,:order => "created_at", :sort => @score, :name => @name, :group => @group) ,:class => @score == 'desc' ? 'st_up' : 'st_down'%> - <% end%> -
  • -
  • - <%= link_to "教师",@show_all ? student_work_index_path(:homework => @homework.id,:order => "teacher_score", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "f14 f_b c_dark fl"%> - <% if @show_all && @order == "teacher_score"%> - <%= link_to "", student_work_index_path(:homework => @homework.id,:order => "teacher_score", :sort => @score, :name => @name, :group => @group) ,:class => @score == 'desc' ? 'st_up' : 'st_down'%> - <% end%> -
  • -
  • - <%= link_to "教辅",@show_all ? student_work_index_path(:homework => @homework.id,:order => "teaching_asistant_score", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "f14 f_b c_dark fl"%> - <% if @show_all && @order == "teaching_asistant_score"%> - <%= link_to "", student_work_index_path(:homework => @homework.id,:order => "teaching_asistant_score", :sort => @score, :name => @name, :group => @group) ,:class => @score == 'desc' ? 'st_up' : 'st_down'%> - - <% end%> -
  • -
  • - <%= link_to "成绩",@show_all ? student_work_index_path(:homework => @homework.id,:order => "score", :sort => @score, :name => @name, :group => @group) : "javascript:void(0)",:class => "f14 f_b c_dark fl"%> - <% if @show_all && @order == "score"%> - <%= link_to "", student_work_index_path(:homework => @homework.id,:order => "score", :sort => @score, :name => @name, :group => @group) ,:class => @score == 'desc' ? 'st_up' : 'st_down'%> - <% end%> -
  • \ No newline at end of file diff --git a/app/views/student_work/_work_attachments.html.erb b/app/views/student_work/_work_attachments.html.erb index f303897bc..a75f68f70 100644 --- a/app/views/student_work/_work_attachments.html.erb +++ b/app/views/student_work/_work_attachments.html.erb @@ -1,8 +1,8 @@ <% attachments.each_with_index do |attachment,i| %>
    - <%= link_to_short_attachment attachment, :class => 'link_file', :download => true -%> - <%= link_to(' '.html_safe, attachment_path(attachment, :format => 'js'), :method => 'delete', :remote => true, :title => '删除', :class => 'remove-upload', :confirm => l(:text_are_you_sure)) if attachment.id && User.current == attachment.author %> - (<%= number_to_human_size attachment.filesize %>) + <%= link_to_short_attachment attachment, :class => 'link_file_a fl', :download => true -%> + <%= link_to(' '.html_safe, attachment_path(attachment, :format => 'js'), :method => 'delete', :remote => true, :title => '删除', :class => 'remove-upload fl', :confirm => l(:text_are_you_sure)) if attachment.id && User.current == attachment.author %> + (<%= number_to_human_size attachment.filesize %>)
    <% end -%> diff --git a/app/views/student_work/add_score.js.erb b/app/views/student_work/add_score.js.erb index 1de92b51a..762aa4a8a 100644 --- a/app/views/student_work/add_score.js.erb +++ b/app/views/student_work/add_score.js.erb @@ -2,39 +2,15 @@ $("#add_student_score_<%= @work.id%>").html("<%= escape_javascript(render :parti $('#score_<%= @work.id%>').peSlider({range: 'min'}); <% if @is_new%> - $("#score_list_<%= @work.id%>").prepend("
    <%= escape_javascript(render :partial => 'student_work_score', :locals => {:score => @score}) %>
    "); + $("#score_list_<%= @work.id%>").prepend("
    <%= escape_javascript(render :partial => 'student_work_score', :locals => {:score => @score,:is_last => @is_last_a}) %>
    "); <% else %> - $("#work_score_<%= @score.id%>").html("<%= escape_javascript(render :partial => 'student_work_score', :locals => {:score => @score}) %>"); + $("#work_score_<%= @score.id%>").html("<%= escape_javascript(render :partial => 'student_work_score', :locals => {:score => @score,:is_last => @is_last}) %>"); <% end%> $("#score_list_<%= @work.id%>").removeAttr("style"); <% if @is_teacher %> - <% if @homework.homework_type == 1%> - $("#student_work_<%= @work.id%>").replaceWith("<%= escape_javascript(render :partial => 'evaluation_student_work',:locals => {:student_work => @work}) %>"); - <% elsif @homework.homework_type == 2%> - $("#student_work_<%= @work.id%>").replaceWith("<%= escape_javascript(render :partial => 'evaluation_student_work',:locals => {:student_work => @work}) %>"); - <% else%> - $("#student_work_<%= @work.id%>").replaceWith("<%= escape_javascript(render :partial => 'student_work',:locals => {:student_work => @work}) %>"); - <% end%> + $("#student_work_<%= @work.id%>").replaceWith("<%= escape_javascript(render :partial => 'evaluation_un_work',:locals => {:student_work => @work}) %>"); <% else %> $("#student_work_<%= @work.id%>").replaceWith("<%= escape_javascript(render :partial => 'evaluation_work',:locals => {:student_work => @work}) %>"); <% end%> - - -$(function(){ - //匿评评分提示 - $(".student_score_info").bind("mouseover",function(e){ - $(this).find("div").show(); - }); - $(".student_score_info").bind("mouseout",function(e){ - $(this).find("div").hide(); - }); - //最终成绩提示 - $(".student_final_scor_info").bind("mouseover",function(e){ - $(this).find("div").show(); - }); - $(".student_final_scor_info").bind("mouseout",function(e){ - $(this).find("div").hide(); - }); -}); diff --git a/app/views/student_work/add_score_reply.js.erb b/app/views/student_work/add_score_reply.js.erb index 28704630f..f21870cd5 100644 --- a/app/views/student_work/add_score_reply.js.erb +++ b/app/views/student_work/add_score_reply.js.erb @@ -1,4 +1,4 @@ -$("#add_score_reply_<%= @score.id%>").html("<%= escape_javascript(render :partial => 'add_score_reply', :locals => {:score => @score}) %>"); +$("#add_score_reply_<%= @score.id%>").html("<%= escape_javascript(render :partial => 'add_score_reply', :locals => {:score => @score,:is_last => @is_last}) %>"); <% if @status && @status == 1%> $("#replay_histroy_<%= @score.id%>").prepend("<%= escape_javascript(render :partial => 'jour_replay', :locals => {:jour => @jour}) %>"); $("#add_score_reply_<%= @score.id%>").hide(); diff --git a/app/views/student_work/edit.html.erb b/app/views/student_work/edit.html.erb index 6e36447d2..25a65f039 100644 --- a/app/views/student_work/edit.html.erb +++ b/app/views/student_work/edit.html.erb @@ -1,52 +1,62 @@ -
    -

    编辑作品

    +
    +
    编辑作品
    -
    -
    -
    - <%= labelled_form_for @work,:html => { :multipart => true } do |f|%> -
    -

    - - - 项目信息 - - -

    -

    -

    -
    +
    -

    - - <%= f.select :project,options_for_select(user_projects_option,@work.project_id), {},{:class => "bo02 mb10"} %> -

    -
    +
    -

    - - -

    -

    -
    -

    - - <%= render :partial => 'attachments/new_form',:locals => {:container => @work} %> -

    -
    -

    - 提交作品 - <%= link_to "返  回".html_safe, student_work_index_path(:homework => @homework), :class => "blue_btn grey_btn fl c_white"%> +

    +
    +
    + <%= @homework.name%>(作业名称) +
    + + 截止时间:<%= @homework.end_time%> + +
    + + <%= link_to @homework.user.show_name, user_activities_path(@homework.user_id), :class => "c_blue"%> + +
    +
    + <%= @homework.description.html_safe %> +
    +
    +
    +
    + +
    + <%= labelled_form_for @work,:html => { :multipart => true } do |f|%> +
    + 提示:作品名称和描述中不要出现真实的姓名信息 +
    -

    -
    - <% end%> -
    -
    +
    + +
    +

    +
    +
    + + +
    +

    +
    + +
    + <%= render :partial => 'users/user_homework_attachment', :locals => {:container => @work, :has_program=>false} %> +
    + +
    + 确定 + + <%= link_to "取消", student_work_index_path(:homework => @homework), :class => "fr mr10 mt3"%> +
    +
    + <% end%> +
    -
    -
    diff --git a/app/views/student_work/index.html.erb b/app/views/student_work/index.html.erb index 3783d67d3..9c48d310b 100644 --- a/app/views/student_work/index.html.erb +++ b/app/views/student_work/index.html.erb @@ -1,5 +1,12 @@ -
    - -
    + //设置评分规则 + function set_score_rule(){ + $('#ajax-modal').html('<%= escape_javascript(render :partial => 'student_work/set_score_rule',:locals => {:homework => @homework}) %>'); + showModal('ajax-modal', '350px'); + $('#ajax-modal').siblings().remove(); + $('#ajax-modal').before("" + + ""); + $('#ajax-modal').parent().css("top","25%").css("left","35%").css("position","fixed"); + } - -
    -
    -
    -
      -
    • 全部作品
    • -
    • 作业信息
    • -
    -
    -
    + -
    -
    -
    - - <%= link_to "所有作品(#{@stundet_works.count})".html_safe,student_work_index_path(:homework => @homework.id), :class => "fl"%> - - <% if @show_all%> - - <%= select_tag(:late_penalty,options_for_select(course_group_list(@course),@group), {:class => "fl h22 w100 ml10"}) if(@is_teacher && course_group_list(@course).count > 0) %> - 搜索 - <%= link_to("缺评情况",student_work_absence_penalty_student_work_index_path(:homework => @homework.id), :class => "student_work_search fl", :target => "_blank") if((@is_teacher || User.current.admin?) && @homework.homework_type == 1) %> - <% end%> +
    +
    +
    + + <% if @is_teacher%> -
    - <% unless @homework.homework_type == 2%> - <% if @homework.student_works.empty?%> - <%= link_to "附件", "javascript:void(0)", class: "down_btn fr zip_download_alert", :onclick => "alert('没有学生提交作业,无法下载附件')" %> - <% else%> - <%= link_to "附件", zipdown_assort_path(obj_class: @homework.class, obj_id: @homework, format: :json), - remote: true, class: "down_btn fr zip_download_alert", :id => "download_homework_attachments" %> - <% end%> -
    - 使用 - winzip - 工具进行解压可能会导致 - 下载文件乱码 - ,建议您使用 - winrar - 工具进行解压 -
    - <% end%> - <%= link_to("匿评", evaluation_list_student_work_index_path(:homework => @homework.id, :format => 'xls'),:class=>'down_btn fr') if @homework.homework_type == 1%> - <%= link_to("缺评", absence_penalty_list_student_work_index_path(:homework => @homework.id, :format => 'xls'),:class=>'down_btn fr') if @homework.homework_type == 1%> - <%= link_to l(:label_list), student_work_index_path(:homework => @homework.id,:order => @order, :sort => @b_sort, :name => @name, :format => 'xls'),:class=>'down_btn fr'%> - 导出全部: +
    +
      +
    • + +
        +
      • + <%= link_to "导出作业成绩", student_work_index_path(:homework => @homework.id,:order => @order, :sort => @b_sort, :name => @name, :group => @group, :format => 'xls'),:class=>'hworkExport postTypeGrey', :id => "export_student_work"%> +
      • +
      • + <% if @homework.student_works.empty?%> + <%= link_to "导出作业附件", "javascript:void(0)", class: "hworkExport resourcesGrey", :onclick => "alert('没有学生提交作业,无法下载附件')" %> + <% else%> + <%= link_to "导出作业附件", zipdown_assort_path(obj_class: @homework.class, obj_id: @homework, format: :json), + remote: true, class: "hworkExport resourcesGrey", :id => "download_homework_attachments" %> + <% end%> +
      • +
      • + <%= link_to("导出缺评情况", absence_penalty_list_student_work_index_path(:homework => @homework.id, :format => 'xls'),:class=>'hworkExport resourcesGrey')%> +
      • +
      • + <%= link_to("导出匿评情况", evaluation_list_student_work_index_path(:homework => @homework.id, :format => 'xls'),:class=>'hworkExport resourcesGrey')%> +
      • +
      • + 评分设置 +
      • +
      +
    • +
    <% end%>
    -
    -
    - - <% if @is_evaluation%> -
      - <%= render :partial => 'evaluation_work_title'%> -
    -
    - <% @stundet_works.each do |student_work|%> - <%= render :partial => "evaluation_work",:locals => {:student_work => student_work}%> -
    - <% end%> - <% else %> - <% if @homework.homework_type == 1 || @homework.homework_type == 2%> -
      - <%= render :partial => 'evaluation_student_work_title'%> -
    -
    - <% @stundet_works.each do |student_work|%> - <%= render :partial => "evaluation_student_work",:locals => {:student_work => student_work}%> -
    - <% end%> - <% else%> -
      - <%= render :partial => 'student_work_title'%> -
    -
    - <% @stundet_works.each do |student_work|%> - <%= render :partial => "student_work",:locals => {:student_work => student_work}%> -
    - <% end%> - <% end%> - <% end%> -
    -
    - -
    -
    - <%= link_to(image_tag(url_to_avatar(@homework.user), :width => "42", :height => "42"), user_path(@homework.user), :class => "problem_pic fl") %> -
    -

    - <%= @homework.name%> -

    - <% if @is_teacher%> - <%= homework_anonymous_comment(@homework)%> - <%= link_to(l(:button_edit),edit_homework_common_path(@homework), :class => "fr mr10 work_edit") %> - <% else%> - <%= student_anonymous_comment @homework %> - <%= student_new_homework @homework %> - <% end %> -
    +
    -
    - <%= @homework.description.html_safe %> +
    +
    +
    + <%= render :partial => "student_work/student_work_list"%>
    -
    +
    +
    - <% if @homework.homework_type == 2 && @homework.homework_detail_programing%> - <% if @is_teacher%> - - - "> - - - - <% homework.homework_tests.each do |test|%> - "> - - - - <% end%> - -
    - 输入 - - 输出 -
    - <%=test.input%> - - <%= test.output%> -
    -
    - <% end%> - -
    - 开发语言: -
    - <% if @homework.homework_detail_programing.language.to_i == 1%> - C - <% elsif @homework.homework_detail_programing.language.to_i == 2%> - C++ - <% end%> -
    -
    -
    - <% end%> - -
    - <% unless @homework.attachments.empty?%> - 附件: -
    - <%= render :partial => 'student_work/work_attachments', :locals => {:attachments => @homework.attachments} %> -
    - <% end%> -
    -
    - -
    - 扣分标准: -
    - <% if @homework.homework_type == 1%> - <%= scoring_rules @homework.late_penalty,@homework.id,@is_teacher,@homework.homework_detail_manual.absence_penalty%> - <% else%> - <%= scoring_rules @homework.late_penalty,@homework.id,@is_teacher%> - <% end%> -
    -
    - -
    - 截止时间:<%= @homework.end_time%> -
    - <% if betweentime(@homework.end_time) < 0 %> - - <%= l(:label_commit_limit)%> - - <% else %> - -
    -
    - <% end %> -
    -
    -
    -
    -
    - - -
    -
    +
    +
    +
    +
    \ No newline at end of file diff --git a/app/views/student_work/index.js.erb b/app/views/student_work/index.js.erb new file mode 100644 index 000000000..73b94260d --- /dev/null +++ b/app/views/student_work/index.js.erb @@ -0,0 +1,2 @@ +$("#homework_student_work_list").html("<%= escape_javascript(render :partial => 'student_work/student_work_list') %>"); +$("#export_student_work").replaceWith("<%= escape_javascript( link_to "导出作业成绩", student_work_index_path(:homework => @homework.id,:order => @order, :sort => @b_sort, :group => @group, :name => @name, :format => 'xls'),:class=>'hworkExport postTypeGrey', :id => 'export_student_work') %>"); \ No newline at end of file diff --git a/app/views/student_work/new.html.erb b/app/views/student_work/new.html.erb index eda09114e..c7f1d45c4 100644 --- a/app/views/student_work/new.html.erb +++ b/app/views/student_work/new.html.erb @@ -1,79 +1,104 @@ + -
    -

    创建作品

    + +
    +
    提交作品
    -
    -
    -
    - <%= form_for(@stundet_work, - :html => { :multipart => true }, - :url => {:controller => 'student_work', - :action => 'create', - :homework => @homework.id - }) do |f|%> -
    - <% if @homework.homework_type == 1%> -
    - 提示:匿评作业提交的作品,作品名称和描述中不能出现真实的姓名信息 -
    - <% end%> -

    - - <%= f.text_field "name", :required => true, :size => 60, :class => "bo fl", :maxlength => 200, :placeholder => "作品名称", :onkeyup => "regexStudentWorkName();" %> - <% if @homework.homework_type != 2%> - - 项目信息 - - - <% end%> -

    -

    -

    -
    -

    - - <%= f.select :project_id,options_for_select(user_projects_option), {},{:class => "bo02 mb10"} %> -

    -
    -

    - - <%= f.text_area "description", :class => "w620 hwork_txt ", :placeholder => "作品描述不能为空", :onkeyup => "regexStudentWorkDescription();"%> -

    -

    -

    -
    - <% if @homework.homework_type != 2%> -

    - - <%= render :partial => 'attachments/new_form' %> -

    -
    - <% end%> -

    - 提交作品 - <%= link_to "返  回".html_safe, student_work_index_path(:homework => @homework), :class => "blue_btn grey_btn fl c_white"%> -

    -

    -
    - <% end%> +
    + +
    + +
    +
    +
    + <%= @homework.name%>(作业名称) +
    + + 截止时间:<%= @homework.end_time%> + +
    + + <%= link_to @homework.user.show_name, user_activities_path(@homework.user_id), :class => "c_blue"%> + +
    +
    + <%= @homework.description.html_safe %> +
    -
    -
    -
    \ No newline at end of file +
    +
    + +
    + <%= form_for(@student_work, + :html => { :multipart => true }, + :url => {:controller => 'student_work', + :action => 'create', + :homework => @homework.id + }) do |f|%> +
    + 提示:作品名称和描述中不要出现真实的姓名信息 +
    +
    + +
    + <%= f.text_field "name", :required => true, :size => 60, :class => "InputBox W700", :maxlength => 200, :placeholder => "请简洁的概括作品的功能或特性", :onkeyup => "regexStudentWorkName();" %> +
    +

    +
    +
    + <%= f.text_area "description", :class => "InputBox W700 H150", :placeholder => "请介绍你的作品", :onkeyup => "regexStudentWorkDescription();"%> + +
    +

    +
    + +
    + <%= render :partial => 'users/user_homework_attachment', :locals => {:container => @student_work, :has_program=>false} %> +
    + + +
    + +
    + <%= select_tag :project_id, options_for_select(user_projects_option, @student_work.project_id), {:class => "InputBox W680 fl"} %> + <%#=link_to "", new_project_path, :class => "ml5 mt5 SetUpIcon fl", :title => "快速创建"%> + +
    +
    + +
    + 确定 + + <%= link_to "取消", user_homeworks_user_path(User.current.id), :class => "fr mr10 mt3"%> +
    +
    + <% end%> +
    +
    \ No newline at end of file diff --git a/app/views/student_work/show.js.erb b/app/views/student_work/show.js.erb index 1c8874c2f..e6b99c146 100644 --- a/app/views/student_work/show.js.erb +++ b/app/views/student_work/show.js.erb @@ -1,11 +1,11 @@ -if($("#about_hwork_<%= @work.id%>").children().length > 0) - {$("#about_hwork_<%= @work.id%>").html("");} -else - { - <% if @homework.homework_type == 2%> - $("#about_hwork_<%= @work.id%>").html("<%= escape_javascript(render :partial => 'programing_work_show') %>"); - <% else%> - $("#about_hwork_<%= @work.id%>").html("<%= escape_javascript(render :partial => 'show') %>"); - <% end%> - $('#score_<%= @work.id%>').peSlider({range: 'min'}); - } \ No newline at end of file +if($("#about_hwork_<%= @work.id%>").children().length > 0){ + $("#about_hwork_<%= @work.id%>").html(""); +} +else{ + <% if @homework.homework_type == 2%> + $("#about_hwork_<%= @work.id%>").html("<%= escape_javascript(render :partial => 'programing_work_show') %>"); + <% else%> + $("#about_hwork_<%= @work.id%>").html("<%= escape_javascript(render :partial => 'show') %>"); + <% end%> + $('#score_<%= @work.id%>').peSlider({range: 'min'}); +} \ No newline at end of file diff --git a/app/views/system_messages/index.html.erb b/app/views/system_messages/index.html.erb new file mode 100644 index 000000000..4ed40757b --- /dev/null +++ b/app/views/system_messages/index.html.erb @@ -0,0 +1,3 @@ +<% @system_messages.each do |sm| %> +
    • <%= sm.content %>
    +<% end %> diff --git a/app/views/tags/_tag_list.html.erb b/app/views/tags/_tag_list.html.erb index b512f1ef3..14b6a0597 100644 --- a/app/views/tags/_tag_list.html.erb +++ b/app/views/tags/_tag_list.html.erb @@ -2,7 +2,8 @@ <% if @tags.size > 0 %> <% @tags.each do |tag| %> - <%= link_to tag, :controller => "tags", :action => "index", :q => tag, :object_flag => object_flag, :obj_id => obj.id %> + <%#= link_to tag, :controller => "tags", :action => "index", :q => tag, :object_flag => object_flag, :obj_id => obj.id %> + <%= tag %> <% case object_flag %> <% when '10' %> diff --git a/app/views/tags/_tag_user_new_name.html.erb b/app/views/tags/_tag_user_new_name.html.erb new file mode 100644 index 000000000..95730c22c --- /dev/null +++ b/app/views/tags/_tag_user_new_name.html.erb @@ -0,0 +1,30 @@ +<% @tags = obj.reload.tag_list %> +<% if non_list_all && @tags.size > 0 %> + +<% else %> + + <% if @tags.size > 0 %> + <% @tags.each do |tag| %> + + <%= link_to tag, :controller => "tags", :action => "index", :q => tag, :object_flag => object_flag, :obj_id => obj.id, :class => 'pt5' %> + + <%= link_to('x', remove_tag_path(:tag_name => tag,:taggable_id => obj.id, :taggable_type => object_flag), :remote => true, :confirm => l(:text_are_you_sure) ) if User.current.eql?(obj) %> + + + <% end %> + <% end %> +<% end %> + +<% if User.current.logged?%> + <%= l(:label_add_tag)%> + +<% end%> + + diff --git a/app/views/tags/_user_tag.html.erb b/app/views/tags/_user_tag.html.erb new file mode 100644 index 000000000..d04fb50a6 --- /dev/null +++ b/app/views/tags/_user_tag.html.erb @@ -0,0 +1,5 @@ +
    +
    + <%= render :partial => "tags/tag_user_new_name",:locals => {:obj => obj,:non_list_all => false ,:object_flag => object_flag} %> +
    +
    diff --git a/app/views/tags/remove_tag.js.erb b/app/views/tags/remove_tag.js.erb index cd56fef1a..4c4409c1c 100644 --- a/app/views/tags/remove_tag.js.erb +++ b/app/views/tags/remove_tag.js.erb @@ -2,6 +2,9 @@ <% if @object_flag == '3'%> $('#tags_show_issue').html('<%= escape_javascript(render :partial => 'tags/tag_name', :locals => {:obj => @obj,:non_list_all => false,:object_flag => @object_flag}) %>'); +<% elsif @object_flag == '1'%> +$('#tags_show').html('<%= escape_javascript(render :partial => 'tags/tag_user_new_name', + :locals => {:obj => @obj,:non_list_all => false,:object_flag => @object_flag}) %>'); <% elsif @object_flag == '2'%> $('#tags_show').html('<%= escape_javascript(render :partial => 'tags/tag_project_new_name', :locals => {:obj => @obj,:non_list_all => false,:object_flag => @object_flag}) %>'); diff --git a/app/views/tags/tag_save.js.erb b/app/views/tags/tag_save.js.erb index 992c472ed..f6ada82eb 100644 --- a/app/views/tags/tag_save.js.erb +++ b/app/views/tags/tag_save.js.erb @@ -4,6 +4,10 @@ $('#tags_show_issue').html('<%= escape_javascript(render :partial => 'tags/tag_n :locals => {:obj => @obj,:non_list_all => false,:object_flag => @obj_flag}) %>'); //$('#put-tag-form-issue').hide(); $('#name-issue').val(""); +<% elsif @obj_flag == '1'%> +$('#tags_show').html('<%= escape_javascript(render :partial => 'tags/tag_user_new_name', + :locals => {:obj => @obj,:non_list_all => false,:object_flag => @obj_flag}) %>'); +$('#tags_name3').val(""); <% elsif @obj_flag == '2'%> $('#tags_show').html('<%= escape_javascript(render :partial => 'tags/tag_project_new_name', :locals => {:obj => @obj,:non_list_all => false,:object_flag => @obj_flag}) %>'); @@ -16,8 +20,9 @@ $('#tags_name2').val(""); $("#files_tag").html("<%= escape_javascript(render :partial => "files/tag_yun", :locals => {:tag_list => @tag_list,:course => @course,:tag_name => @select_tag_name}) %>"); <%else%> $("#tags_show-<%=@obj.class%>-<%=@obj.id%>").empty(); - $("#tags_show-<%=@obj.class%>-<%=@obj.id%>").html('<%= escape_javascript(render :partial => 'tags/course_attachment_tag_name', - :locals => {:obj => @obj,:non_list_all => false,:object_flag => @obj_flag}) %>'); + $("#tags_show-<%=@obj.class%>-<%=@obj.id%>").replaceWith('<%= escape_javascript(render :partial => 'tags/tag_new', :locals => {:obj => @obj, :object_flag => "6"}) %>'); +//render :partial => 'tags/course_attachment_tag_name', +//:locals => {:obj => @obj,:non_list_all => false,:object_flag => @obj_flag}) <%end%> $("#tags_name_<%=@obj.id%>").val(""); diff --git a/app/views/tags/update_tag_name.js.erb b/app/views/tags/update_tag_name.js.erb new file mode 100644 index 000000000..ec81e7cbc --- /dev/null +++ b/app/views/tags/update_tag_name.js.erb @@ -0,0 +1,50 @@ +//本js使用的新的tag显示方法 +<% if @obj_flag == '3'%> +$('#tags_show_issue').html('<%= escape_javascript(render :partial => 'tags/tag_name', + :locals => {:obj => @obj,:non_list_all => false,:object_flag => @obj_flag}) %>'); +//$('#put-tag-form-issue').hide(); +$('#name-issue').val(""); +<% elsif @obj_flag == '1'%> +$('#tags_show').html('<%= escape_javascript(render :partial => 'tags/tag_user_new_name', + :locals => {:obj => @obj,:non_list_all => false,:object_flag => @obj_flag}) %>'); +$('#tags_name3').val(""); +<% elsif @obj_flag == '2'%> +$('#tags_show').html('<%= escape_javascript(render :partial => 'tags/tag_project_new_name', + :locals => {:obj => @obj,:non_list_all => false,:object_flag => @obj_flag}) %>'); +$('#tags_name2').val(""); +<% elsif @obj_flag == '6'%> +<%if @course%> + <% if @obj %> + $("#tags_show-<%=@obj.class%>-<%=@obj.id%>").empty(); + $("#tags_show-<%=@obj.class%>-<%=@obj.id%>").html('<%= escape_javascript(render :partial => 'tags/tag_list', + :locals => {:obj => @obj,:object_flag => @obj_flag,:select_tag_name => @select_tag_name}) %>'); + $("#tags_name_<%=@obj.id%>").val(""); + $("#add_tag_<%=@obj.id%>").hide(); + <% else %> + $("#course_list").html("<%= escape_javascript(render :partial => 'files/course_list', + :locals => {course: @course,all_attachments: @all_attachments,sort:@sort,order:@order,curse_attachments:@obj_attachments}) %>"); + <% end %> +$("#files_tag").html("<%= escape_javascript(render :partial => "files/tag_yun", :locals => {:tag_list => @tag_list,:course => @course,:tag_name => @select_tag_name}) %>"); +<%else%> +$("#tags_show-<%=@obj.class%>-<%=@obj.id%>").empty(); +$("#tags_show-<%=@obj.class%>-<%=@obj.id%>").html('<%= escape_javascript(render :partial => 'tags/course_attachment_tag_name', + :locals => {:obj => @obj,:non_list_all => false,:object_flag => @obj_flag}) %>'); +$("#tags_name_<%=@obj.id%>").val(""); +$("#add_tag_<%=@obj.id%>").hide(); +<%end%> + + +<% elsif @obj_flag == '9'%> +$('#tags_show').html('<%= escape_javascript(render :partial => 'tags/new_tag_name', + :locals => {:obj => @obj,:non_list_all => false,:object_flag => @obj_flag}) %>'); +$('#tags_name').val(""); +<% elsif @obj_flag == '10'%> +//$("#put-tag-form-<%#=@obj.class%>-<%#=@obj.id%>").hide(); +<% elsif @obj_flag == '5'%> + $('#forum_tag_list').html('<%= escape_javascript(render :partial=>'forums/forum_tag_list',:locals=>{:forum=>@forum})%>') +<% else%> +$('#tags_show').html('<%= escape_javascript(render :partial => 'tags/tag_name', + :locals => {:obj => @obj,:non_list_all => false,:object_flag => @obj_flag}) %>'); +$('#tags_name').val(""); +//$('#put-tag-form').hide(); +<% end %> \ No newline at end of file diff --git a/app/views/users/_activity_new_score_index.html.erb b/app/views/users/_activity_new_score_index.html.erb index 8140fd756..605219476 100644 --- a/app/views/users/_activity_new_score_index.html.erb +++ b/app/views/users/_activity_new_score_index.html.erb @@ -1,4 +1,3 @@ -
        <%= l('userscore.skill.tramples')%> * (-2) = <%= option_num.tread %> * (-2) = <%= option_num.tread * (-2) %>
        <%= l('userscore.skill.like.level1')%> * 4 = <%= option_num.praise_by_one %> * 4 = <%= option_num.praise_by_one * 4 %>
        <%= l('userscore.skill.like.level2')%> * 6 = <%= option_num.praise_by_two %> * 6 = <%= option_num.praise_by_two * 6 %>
    diff --git a/app/views/users/_attachment_list.html.erb b/app/views/users/_attachment_list.html.erb new file mode 100644 index 000000000..33e944498 --- /dev/null +++ b/app/views/users/_attachment_list.html.erb @@ -0,0 +1,30 @@ + + + + + 选择文件 +<%= file_field_tag 'attachments[dummy][file]', + :id => '_file', + :class => ie8? ? '':'file_selector', + :multiple => true, + :onchange => 'addInputFiles(this);', + :style => ie8? ? '': 'display:none', + :data => { + :max_file_size => Setting.attachment_max_size.to_i.kilobytes, + :max_file_size_message => l(:error_attachment_too_big, :max_size => number_to_human_size(Setting.attachment_max_size.to_i.kilobytes)), + :max_concurrent_uploads => Redmine::Configuration['max_concurrent_ajax_uploads'].to_i, + :upload_path => uploads_path(:format => 'js'), + :description_placeholder => l(:label_optional_description), + :field_is_public => l(:field_is_public), + :are_you_sure => l(:text_are_you_sure), + :file_count => l(:label_file_count), + :delete_all_files => l(:text_are_you_sure_all) + } %> + + + + + + +<%#= number_to_human_size(Setting.attachment_max_size.to_i.kilobytes) %> + diff --git a/app/views/users/_course_attachment.html.erb b/app/views/users/_course_attachment.html.erb new file mode 100644 index 000000000..386e6d177 --- /dev/null +++ b/app/views/users/_course_attachment.html.erb @@ -0,0 +1,40 @@ +
    +
    +
    + <%= link_to image_tag(url_to_avatar(activity.author), :width => "50", :height => "50"), user_path(activity.author_id), :alt => "用户头像" %> +
    +
    +
    + <% if activity.try(:author).try(:realname) == ' ' %> + <%= link_to activity.try(:author), user_path(activity.author_id), :class => "newsBlue mr15" %> + <% else %> + <%= link_to activity.try(:author).try(:realname), user_path(activity.author_id), :class => "newsBlue mr15" %> + <% end %> + TO + <%= link_to activity.course.name.to_s+" | 课程资源", course_files_path(activity.course), :class => "newsBlue ml15" %> +
    +
    + <%= link_to activity.filename, course_files_path(activity.course), :class => "postGrey" %> +
    +
    +
    + 文件大小: + <%= number_to_human_size activity.filesize%> +
    +
    上传时间:<%= format_time(activity.created_on) %>
    +
    + +
    +
    +
    +
    \ No newline at end of file diff --git a/app/views/users/_course_create.html.erb b/app/views/users/_course_create.html.erb new file mode 100644 index 000000000..699b20216 --- /dev/null +++ b/app/views/users/_course_create.html.erb @@ -0,0 +1,36 @@ +
    +
    +
    + <%= link_to image_tag(url_to_avatar(activity.teacher), :width => "50", :height => "50"), user_path(activity.tea_id), :alt => "用户头像" %> +
    +
    +
    + <% if activity.try(:teacher).try(:realname) == ' ' %> + <%= link_to activity.try(:teacher), user_path(activity.tea_id), :class => "newsBlue mr15" %> + <% else %> + <%= link_to activity.try(:teacher).try(:realname), user_path(activity.tea_id), :class => "newsBlue mr15" %> + <% end %> + TO + <%= link_to activity.name.to_s+" | 课程", course_path(activity.id,:host=>Setting.host_course), :class => "newsBlue ml15" %> +
    +
    + <%= link_to activity.name, course_path(activity.id,:host=>Setting.host_course), :class => "postGrey" %> +
    +
    + 创建时间:<%= format_time(activity.created_at) %> +
    + +
    +
    +
    +
    \ No newline at end of file diff --git a/app/views/users/_course_homework.html.erb b/app/views/users/_course_homework.html.erb new file mode 100644 index 000000000..868f952fa --- /dev/null +++ b/app/views/users/_course_homework.html.erb @@ -0,0 +1,74 @@ +<% is_teacher = User.current.allowed_to?(:as_teacher,activity.course) %> +
    +
    +
    + <%= link_to image_tag(url_to_avatar(activity.user), :width => "50", :height => "50"), user_path(activity.user_id), :alt => "用户头像" %> +
    +
    +
    + <% if activity.try(:user).try(:realname) == ' ' %> + <%= link_to activity.try(:user), user_path(activity.user_id,:host=>Setting.host_user), :class => "newsBlue mr15" %> + <% else %> + <%= link_to activity.try(:user).try(:realname), user_path(activity.user_id,:host=>Setting.host_user), :class => "newsBlue mr15" %> + <% end %> TO + <%= link_to activity.course.name.to_s+" | 课程作业", homework_common_index_path(:course => activity.course.id, :host=> Setting.host_course), :class => "newsBlue ml15"%> +
    + + <% if activity.homework_detail_manual.comment_status == 1%> + 未开启匿评 + <% elsif activity.homework_detail_manual.comment_status == 2%> + 匿评中 + <% elsif activity.homework_detail_manual.comment_status == 3%> + 匿评已结束 + <% end%> +
    +
    + <% is_teacher = User.current.allowed_to?(:as_teacher,activity.course) %> + <%= user_for_homework_common activity,is_teacher %> +
    + + <% if activity.homework_type == 2 && is_teacher%> +
    + <%= link_to "模拟答题", new_user_commit_homework_users_path(homework_id: activity.id, is_test: true), class: 'c_blue test-program-btn', title: '教师可以通过模拟答题设置作业的标准答案' %> +
    + <% end %> + <% if activity.homework_type == 2%> +
    + 语言: + <%= activity.language_name%> +
    + <% end %> + +
    截止时间:<%= activity.end_time.to_s %>
    +
    +
    + <%= activity.description.html_safe %> +
    + <%# if is_teacher%> + +
    +
    +
    +
    \ No newline at end of file diff --git a/app/views/users/_course_journalsformessage.html.erb b/app/views/users/_course_journalsformessage.html.erb new file mode 100644 index 000000000..aab26c20b --- /dev/null +++ b/app/views/users/_course_journalsformessage.html.erb @@ -0,0 +1,125 @@ +
    +
    +
    + <%= link_to image_tag(url_to_avatar(activity.user), :width => "50", :height => "50"), user_path(activity.user_id), :alt => "用户头像" %> +
    +
    +
    + <% if @ctivity.try(:user).try(:realname) == ' ' %> + <%= link_to activity.try(:user), user_path(activity.user_id), :class => "newsBlue mr15" %> + <% else %> + <%= link_to activity.try(:user).try(:realname), user_path(activity.user_id), :class => "newsBlue mr15" %> + <% end %> TO + <% course=Course.find(activity.jour_id) %> + <%= link_to course.name.to_s+" | 课程留言", course_feedback_path(course), :class => "newsBlue ml15" %> +
    +
    + <% if activity.parent %> + <%= link_to activity.parent.notes.html_safe, course_feedback_path(course), :class => "postGrey" %> + <% else %> + <%= link_to activity.notes.html_safe, course_feedback_path(course), :class => "postGrey" %> + <% end %> +
    +
    + 留言时间:<%= format_time(activity.created_on) %> +
    +
    +
    +
    + <% count=course.journals_for_messages.where('m_parent_id IS NULL').count %> +
    +
    +
    +
    + 回复(<%= count %>) +
    +
    + <%if count>2 %> + + <% end %> +
    + + <% replies_all_i = 0 %> + <% if count > 0 %> +
    +
      + <% course.journals_for_messages.where('m_parent_id IS NULL').reorder("created_on desc").each do |comment| %> + <% replies_all_i = replies_all_i + 1 %> +
    • +
      + <%= link_to image_tag(url_to_avatar(comment.user), :width => "33", :height => "33", :class =>"mt8"), user_path(comment.user_id), :alt => "用户头像" %> +
      +
      +
      + <% if comment.try(:user).try(:realname) == ' ' %> + <%= link_to comment.try(:user), user_path(comment.user_id), :class => "newsBlue mr10 f14" %> + <% else %> + <%= link_to comment.try(:user).try(:realname), user_path(comment.user_id), :class => "newsBlue mr10 f14" %> + <% end %> + <%= format_time(comment.created_on) %> +
      +
      + <%= comment.notes.html_safe %>
      + <% fetch_user_leaveWord_reply(comment).each do |reply| unless fetch_user_leaveWord_reply(comment).nil? %> +
      +
      + <%= link_to image_tag(url_to_avatar(reply.user), :width => "33", :height => "33", :class =>"mt8"), user_path(reply.user_id), :alt => "用户头像" %> +
      +
      +
      + <% if reply.try(:user).try(:realname) == ' ' %> + <%= link_to reply.try(:user), user_path(reply.user_id), :class => "newsBlue mr10 f14" %> + <% else %> + <%= link_to reply.try(:user).try(:realname), user_path(reply.user_id), :class => "newsBlue mr10 f14" %> + <% end %> + <%= l(:label_reply_to)%> + <% if comment.try(:user).try(:realname) == ' ' %> + <%= link_to comment.try(:user), user_path(comment.user_id), :class => "newsBlue mr10 f14 ml10" %> + <% else %> + <%= link_to comment.try(:user).try(:realname), user_path(comment.user_id), :class => "newsBlue mr10 f14 ml10" %> + <% end %> + <%= format_time reply.created_on %> +
      +
      + <%= reply.notes.html_safe %>
      +
      +
      +
      +
      + <% end %> + <% end %> +
      +
      +
    • + <% end %> +
    +
    + <% end %> + +
    +
    <%= link_to image_tag(url_to_avatar(User.current), :width => "33", :height => "33"), :alt => "用户头像" %>
    +
    +
    + <%= form_for('new_form',:url => {:controller => 'words', :action => 'create_reply', :id => activity.id},:method => "post", :remote => true) do |f|%> + <%= hidden_field_tag 'reference_id', params[:reference_id], :value => activity.id %> + <%= hidden_field_tag 'reference_user_id', params[:reference_user_id], :value => activity.user.id %> + <%= hidden_field_tag 'reference_message_id', params[:reference_message_id], :value => activity.id %> + <%= hidden_field_tag 'show_name',params[:show_name],:value =>true %> + <%= hidden_field_tag 'user_activity_id',params[:user_activity_id],:value =>user_activity_id %> + +
    + +
    +

    + <% end%> +
    +
    +
    +
    +
    +
    +
    \ No newline at end of file diff --git a/app/views/users/_course_message.html.erb b/app/views/users/_course_message.html.erb new file mode 100644 index 000000000..8ec605567 --- /dev/null +++ b/app/views/users/_course_message.html.erb @@ -0,0 +1,121 @@ +
    +
    +
    + <%= link_to image_tag(url_to_avatar(activity.author), :width => "50", :height => "50"), user_path(activity.author_id,:host=>Setting.host_user), :alt => "用户头像" %> +
    +
    +
    + <% if activity.try(:author).try(:realname) == ' ' %> + <%= link_to activity.try(:author), user_path(activity.author_id,:host=>Setting.host_user), :class => "newsBlue mr15" %> + <% else %> + <%= link_to activity.try(:author).try(:realname), user_path(activity.author_id,:host=>Setting.host_user), :class => "newsBlue mr15" %> + <% end %> + TO + <%= link_to activity.course.name.to_s+" | 课程讨论区", course_boards_path(activity.course,:host=> Setting.host_course), :class => "newsBlue ml15 mr5"%> +
    +
    + <% if activity.parent_id.nil? %> + <%= link_to activity.subject.to_s.html_safe, course_boards_path(activity.course,:parent_id =>activity.id, :topic_id => activity.id,:host=> Setting.host_course), :class=> "postGrey" %> + <% else %> + <%= link_to activity.parent.subject.to_s.html_safe, course_boards_path(activity.course,:parent_id =>activity.parent_id, :topic_id => activity.id,:host=> Setting.host_course), :class=> "postGrey"%> + <% end %> +
    +
    + 发帖时间:<%= format_time(activity.created_on) %> +
    + +
    + <% if activity.parent_id.nil? %> + <%= activity.content.to_s.html_safe%> + <% else %> + <%= activity.parent.content.to_s.html_safe%> + <% end %> +
    + +
    +
    +
    + <% count=0 %> + <% if activity.parent %> + <% count=activity.parent.children.count%> + <% else %> + <% count=activity.children.count%> + <% end %> +
    +
    +
    +
    回复( + <%= count %> + )
    +
    <%#=format_date(activity.updated_on)%>
    + <%if count > 2 %> + + <% end %> +
    + + <% activity= activity.parent ? activity.parent : activity%> + <% replies_all_i = 0 %> + <% if count > 0 %> +
    +
      + <% activity.children.reorder("created_on desc").each do |reply|%> + <% replies_all_i=replies_all_i+1 %> +
    • +
      + <%= link_to image_tag(url_to_avatar(reply.author), :width => "33", :height => "33", :class =>"mt8"), user_path(reply.author_id,:host=>Setting.host_user), :alt => "用户头像" %> +
      +
      +
      + <% if reply.try(:author).try(:realname) == ' ' %> + <%= link_to reply.try(:author), user_path(reply.author_id,:host=>Setting.host_user), :class => "newsBlue mr10 f14" %> + <% else %> + <%= link_to reply.try(:author).try(:realname), user_path(reply.author_id,:host=>Setting.host_user), :class => "newsBlue mr10 f14" %> + <% end %> + <%= format_time(reply.created_on) %> +
      +
      + <%= reply.content.html_safe %> +
      +
      +
      +
    • + <% end %> +
    +
    + <% end %> + +
    +
    <%= link_to image_tag(url_to_avatar(User.current), :width => "33", :height => "33"), user_path(activity.author_id), :alt => "用户头像" %>
    +
    +
    + <%= form_for('new_form',:url => {:controller=>'messages',:action => 'reply', :id => activity.id, :board_id => activity.board_id, :is_board => 'true'},:method => "post", :remote => true) do |f|%> + + + +
    + +
    +

    + <% end%> +
    +
    +
    +
    +
    +
    +
    +
    diff --git a/app/views/users/_course_news.html.erb b/app/views/users/_course_news.html.erb new file mode 100644 index 000000000..4b5b73ceb --- /dev/null +++ b/app/views/users/_course_news.html.erb @@ -0,0 +1,91 @@ +
    +
    +
    + <%= link_to image_tag(url_to_avatar(activity.author), :width => "50", :height => "50"), user_path(activity.author_id), :alt => "用户头像" %> +
    +
    +
    + <% if @ctivity.try(:author).try(:realname) == ' ' %> + <%= link_to activity.try(:author), user_path(activity.author_id), :class => "newsBlue mr15" %> + <% else %> + <%= link_to activity.try(:author).try(:realname), user_path(activity.author_id), :class => "newsBlue mr15" %> + <% end %> TO + <%= link_to activity.course.name.to_s+" | 课程通知", course_news_index_path(activity.course), :class => "newsBlue ml15" %> +
    +
    + <%= link_to activity.title.to_s, news_path(activity), :class => "postGrey" %> +
    +
    + 发布时间:<%= format_time(activity.created_on) %> +
    +
    + <%= activity.description.html_safe %> +
    +
    +
    +
    + <% count=activity.comments.count %> +
    +
    +
    +
    + 回复(<%= count %>) +
    +
    <%#= format_date(activity.updated_on) %>
    + <%if count>2 %> + + <% end %> +
    + + <% replies_all_i = 0 %> + <% if count > 0 %> +
    +
      + <% activity.comments.reorder("created_on desc").each do |comment| %> + <% replies_all_i = replies_all_i + 1 %> +
    • +
      + <%= link_to image_tag(url_to_avatar(comment.author), :width => "33", :height => "33", :class =>"mt8"), user_path(comment.author_id), :alt => "用户头像" %> +
      +
      +
      + <% if comment.try(:author).try(:realname) == ' ' %> + <%= link_to comment.try(:author), user_path(comment.author_id), :class => "newsBlue mr10 f14" %> + <% else %> + <%= link_to comment.try(:author).try(:realname), user_path(comment.author_id), :class => "newsBlue mr10 f14" %> + <% end %> + <%= format_time(comment.created_on) %> +
      +
      + <%= comment.comments.html_safe %>
      +
      +
      +
    • + <% end %> +
    +
    + <% end %> + +
    +
    <%= link_to image_tag(url_to_avatar(User.current), :width => "33", :height => "33"), user_path(activity.author_id), :alt => "用户头像" %>
    +
    +
    + <%= form_for('new_form',:url => {:controller => 'comments', :action => 'create', :id => activity},:method => "post", :remote => true) do |f|%> + + +
    + +
    +

    + <% end%> +
    +
    +
    +
    +
    +
    +
    \ No newline at end of file diff --git a/app/views/users/_course_poll.html.erb b/app/views/users/_course_poll.html.erb new file mode 100644 index 000000000..0b91a6ed3 --- /dev/null +++ b/app/views/users/_course_poll.html.erb @@ -0,0 +1,48 @@ +<% has_commit = has_commit_poll?(activity.id ,User.current)%> +<% poll_name = activity.polls_name.empty? ? l(:label_poll_new) : activity.polls_name%> +<% if ( activity.polls_status==2) %> +
    +
    +
    + + <%= link_to image_tag(url_to_avatar(activity.user), :width => "50", :height => "50"), user_path(activity.user_id), :alt => "用户头像" %> +
    +
    +
    + <% if activity.try(:user).try(:realname) == ' ' %> + <%= link_to activity.try(:user), user_path(activity.user_id), :class => "newsBlue mr15" %> + <% else %> + <%= link_to activity.try(:user).try(:realname), user_path(activity.user_id), :class => "newsBlue mr15" %> + <% end %> + TO + <%= link_to Course.find(activity.polls_group_id).name.to_s+" | 问卷", poll_index_path(:polls_type => "Course", :polls_group_id => activity.polls_group_id), :class => "newsBlue ml15" %> + +
    +
    + <%#= link_to activity.polls_name.to_s/*+"(问卷名称)"*/, %> + <% if has_commit %> + <%= link_to poll_name, poll_result_poll_path(activity.id), :class => "postGrey"%> + <% else %> + <%= link_to poll_name, poll_path(activity.id), :class => "postGrey"%> + <% end %> +
    +
    + 发布时间:<%= format_time(activity.published_at) %> +
    +
    <%=activity.polls_description.html_safe.to_s%>
    + +
    +
    +
    +
    +<% end %> \ No newline at end of file diff --git a/app/views/users/_influence_new_score_index.html.erb b/app/views/users/_influence_new_score_index.html.erb index 505785351..f99cdee19 100644 --- a/app/views/users/_influence_new_score_index.html.erb +++ b/app/views/users/_influence_new_score_index.html.erb @@ -5,4 +5,4 @@
        <%= l('userscore.active.update_issues')%> * 2 = <%= option_num.issue_done_ratio %> * 2 = <%= option_num.issue_done_ratio * 2 %>
        <%= l('userscore.active.release_issues')%> * 4 = <%= option_num.post_issue %> * 4 = <%= option_num.post_issue * 4 %>
        <%= l('userscore.active.release_messages')%> * 1 = <%= option_num.memo %> * 2 = <%= option_num.memo * 2 %>
    -
        <%= l(:label_user_score_of_active)%> = <%= option_num.changeset * 4 %> + <%= option_num.document * 4 %> + <%= option_num.attachment * 4 %> + <%= option_num.issue_done_ratio * 2 %> + <%= option_num.post_issue * 4 %> + <%= option_num.memo * 2 %> = <%= active(option_num) %>
    \ No newline at end of file +
        <%= l(:label_user_score_of_active)%> = <%= option_num.changeset * 4 %> + <%= option_num.document * 4 %> + <%= option_num.attachment * 4 %> + <%= option_num.issue_done_ratio * 2 %> + <%= option_num.post_issue * 4 %> + <%= option_num.memo * 2 %> = <%= project_active(option_num) %>
    \ No newline at end of file diff --git a/app/views/users/_project_attachment.html.erb b/app/views/users/_project_attachment.html.erb new file mode 100644 index 000000000..5215e9ccc --- /dev/null +++ b/app/views/users/_project_attachment.html.erb @@ -0,0 +1,29 @@ +
    +
    +
    + 用户头像
    +
    + + +
    + +
    截止时间:2015-08-20
    +
    +
    (作业描述)系统中有多个ckeditor,且每个ckeditor的id未知,怎么样做到当光标聚焦某个ckeditor的文本框中,该编辑器的默认值应自动消失的处理;网络拓扑图开发;
    + +
    +
    +
    +
    \ No newline at end of file diff --git a/app/views/users/_project_create.html.erb b/app/views/users/_project_create.html.erb new file mode 100644 index 000000000..862087e68 --- /dev/null +++ b/app/views/users/_project_create.html.erb @@ -0,0 +1,29 @@ +
    +
    +
    + 用户头像
    +
    + + +
    + +
    截止时间:2015-08-20
    +
    +
    (作业描述)系统中有多个ckeditor,且每个ckeditor的id未知,怎么样做到当光标聚焦某个ckeditor的文本框中,该编辑器的默认值应自动消失的处理;网络拓扑图开发;
    + +
    +
    +
    +
    \ No newline at end of file diff --git a/app/views/users/_project_document.html.erb b/app/views/users/_project_document.html.erb new file mode 100644 index 000000000..e6067e860 --- /dev/null +++ b/app/views/users/_project_document.html.erb @@ -0,0 +1,29 @@ +
    +
    +
    + 用户头像
    +
    + + +
    + +
    截止时间:2015-08-20
    +
    +
    (作业描述)系统中有多个ckeditor,且每个ckeditor的id未知,怎么样做到当光标聚焦某个ckeditor的文本框中,该编辑器的默认值应自动消失的处理;网络拓扑图开发;
    + +
    +
    +
    +
    \ No newline at end of file diff --git a/app/views/users/_project_issue.html.erb b/app/views/users/_project_issue.html.erb new file mode 100644 index 000000000..02d1940a6 --- /dev/null +++ b/app/views/users/_project_issue.html.erb @@ -0,0 +1,135 @@ +
    +
    +
    + <%= link_to image_tag(url_to_avatar(activity.author), :width => "50", :height => "50"), user_path(activity.author_id), :alt => "用户头像" %> +
    +
    +
    + <% if activity.try(:author).try(:realname) == ' ' %> + <%= link_to activity.try(:author), user_path(activity.author_id), :class => "newsBlue mr15" %> + <% else %> + <%= link_to activity.try(:author).try(:realname), user_path(activity.author_id), :class => "newsBlue mr15" %> + <% end %> TO + <%= link_to activity.project.name.to_s+" | 项目问题", project_issues_path(activity.project), :class => "newsBlue ml15"%> +
    +
    + <%= link_to activity.subject.to_s, issue_path(activity), :class => "postGrey" %> + + <%= get_issue_priority(activity.priority_id)[1] %> + +
    +
    +
    指派给   + <% unless activity.assigned_to_id.nil? %> + <% if activity.try(:assigned_to).try(:realname) == ' ' %> + <%= link_to activity.try(:assigned_to), user_path(activity.assigned_to_id), :class => "newsBlue mr15" %> + <% else %> + <%= link_to activity.try(:assigned_to).try(:realname), user_path(activity.assigned_to_id), :class => "newsBlue mr15" %> + <% end %> + <% end %> +
    +
    + 时间: + <%=format_time(activity.created_on) %> +
    +
    +
    + <% if activity.description? %> + <%= textAreailizable activity, :description, :attachments => activity.attachments %> + <% end %> + <%#= activity.description.html_safe %> +
    +
    + <% if activity.attachments.any? %> + <% activity.attachments.each do |attachment| %> +
    + + <%= link_to_short_attachment attachment,:length=> 58, :class => 'homepagePostFileAtt newsBlue', :download => true -%> + + <% if attachment.is_text? %> + <%= link_to image_tag('magnifier.png'), + :controller => 'attachments', + :action => 'show', + :id => attachment, + :filename => attachment.filename %> + <% end %> + ( + <%= number_to_human_size attachment.filesize %>) + +
    + <% end %> + <% end %> +
    +
    +
    +
    + <% count = activity.journals.count %> +
    +
    +
    +
    回复(<%= count %>)
    +
    <%#= format_date(activity.updated_on) %>
    + <% if count > 2 %> + + <% end %> +
    + + <% replies_all_i = 0 %> + <% if count > 0 %> +
    +
      + <% activity.journals.reorder("created_on desc").each do |reply| %> + <% replies_all_i=replies_all_i + 1 %> +
    • +
      + <%= link_to image_tag(url_to_avatar(reply.user), :width => "33", :height => "33", :class =>"mt8"), user_path(reply.user_id), :alt => "用户头像" %> +
      +
      +
      + <% if reply.try(:user).try(:realname) == ' ' %> + <%= link_to reply.try(:user), user_path(reply.user_id), :class => "newsBlue mr10 f14" %> + <% else %> + <%= link_to reply.try(:user).try(:realname), user_path(reply.user_id), :class => "newsBlue mr10 f14" %> + <% end %> + <%= format_time(reply.created_on) %> +
      +
      + <% if reply.details.any? %> + <% details_to_strings(reply.details).each do |string| %> +

      <%= string %>

      + <% end %> + <% end %> +

      <%= reply.notes.html_safe %>

      +
      +
      +
      +
    • + <% end %> +
    +
    + <% end %> + +
    +
    <%= link_to image_tag(url_to_avatar(User.current), :width => "33", :height => "33"), user_path(activity.author_id), :alt => "用户头像" %>
    +
    +
    + <%= form_for('new_form',:url => add_journal_issue_path(activity.id),:method => "post", :remote => true) do |f|%> + + +
    + +
    +

    + <% end%> +
    +
    +
    +
    +
    + +
    +
    diff --git a/app/views/users/_project_journal.html.erb b/app/views/users/_project_journal.html.erb new file mode 100644 index 000000000..692354f9f --- /dev/null +++ b/app/views/users/_project_journal.html.erb @@ -0,0 +1,29 @@ +
    +
    +
    + 用户头像
    +
    + + +
    + +
    截止时间:2015-08-20
    +
    +
    (作业描述)系统中有多个ckeditor,且每个ckeditor的id未知,怎么样做到当光标聚焦某个ckeditor的文本框中,该编辑器的默认值应自动消失的处理;网络拓扑图开发;
    + +
    +
    +
    +
    \ No newline at end of file diff --git a/app/views/users/_project_message.html.erb b/app/views/users/_project_message.html.erb new file mode 100644 index 000000000..ead43d7e4 --- /dev/null +++ b/app/views/users/_project_message.html.erb @@ -0,0 +1,108 @@ +
    +
    +
    + <%= link_to image_tag(url_to_avatar(activity.author), :width => "50", :height => "50"), user_path(activity.author_id), :alt => "用户头像" %> +
    +
    +
    + <% if activity.try(:author).try(:realname) == ' ' %> + <%= link_to activity.try(:author), user_path(activity.author_id), :class => "newsBlue mr15" %> + <% else %> + <%= link_to activity.try(:author).try(:realname), user_path(activity.author_id), :class => "newsBlue mr15" %> + <% end %> + TO + <%= link_to activity.project.name.to_s+" | 项目讨论区",project_boards_path(activity.project), :class => "newsBlue ml15 mr5"%> + +
    +
    + <% if activity.parent_id.nil? %> + <%= link_to activity.subject.to_s.html_safe, project_boards_path(activity.project,:parent_id =>activity.id, :topic_id => activity.id), :class=> "postGrey" + %> + <% else %> + <%= link_to activity.parent.subject.to_s.html_safe, project_boards_path(activity.project,:parent_id =>activity.parent_id, :topic_id => activity.id), :class=> "postGrey" + %> + <% end %> +
    +
    + 时间:<%= format_time(activity.created_on) %> +
    +
    + <% if activity.parent_id.nil? %> + <%= activity.content.to_s.html_safe%> + <% else %> + <%= activity.parent.content.to_s.html_safe%> + <% end %> +
    +
    +
    +
    + <% count = 0 %> + <% if activity.parent %> + <% count=activity.parent.children.count%> + <% else %> + <% count=activity.children.count%> + <% end %> +
    +
    +
    +
    回复( + <%=count %> + )
    +
    <%#=format_date(activity.updated_on)%>
    + <%if count>2 %> + + <% end %> +
    + + <% activity= activity.parent_id.nil? ? activity : activity.parent %> + <% replies_all_i = 0 %> + <% if count > 0 %> +
    +
      + <% activity.children.reorder("created_on desc").each do |reply| %> + <% replies_all_i=replies_all_i+1 %> +
    • +
      + <%= link_to image_tag(url_to_avatar(reply.author), :width => "33", :height => "33", :class =>"mt8"), user_path(reply.author_id), :alt => "用户头像" %> +
      +
      +
      + <% if reply.try(:author).try(:realname) == ' ' %> + <%= link_to reply.try(:author), user_path(reply.author_id), :class => "newsBlue mr10 f14" %> + <% else %> + <%= link_to reply.try(:author).try(:realname), user_path(reply.author_id), :class => "newsBlue mr10 f14" %> + <% end %> + <%= format_time(reply.created_on) %> +
      +
      + <%= reply.content.html_safe %>
      +
      +
      +
    • + <% end %> +
    +
    + <% end %> + +
    +
    <%= link_to image_tag(url_to_avatar(User.current), :width => "33", :height => "33"), user_path(activity.author_id), :alt => "用户头像" %>
    +
    +
    + <%= form_for('new_form',:url => {:controller=>'messages',:action => 'reply', :id => activity.id, :board_id => activity.board_id, :is_board => 'true'},:method => "post", :remote => true) do |f|%> + + + +
    + +
    +

    + <% end%> +
    +
    +
    +
    +
    + + +
    +
    \ No newline at end of file diff --git a/app/views/users/_project_news.html.erb b/app/views/users/_project_news.html.erb new file mode 100644 index 000000000..a347ffd3a --- /dev/null +++ b/app/views/users/_project_news.html.erb @@ -0,0 +1,29 @@ +
    +
    +
    + 用户头像
    +
    + + +
    + +
    截止时间:2015-08-20
    +
    +
    (作业描述)系统中有多个ckeditor,且每个ckeditor的id未知,怎么样做到当光标聚焦某个ckeditor的文本框中,该编辑器的默认值应自动消失的处理;网络拓扑图开发;
    + +
    +
    +
    +
    \ No newline at end of file diff --git a/app/views/users/_resource_search_form.html.erb b/app/views/users/_resource_search_form.html.erb new file mode 100644 index 000000000..376007fec --- /dev/null +++ b/app/views/users/_resource_search_form.html.erb @@ -0,0 +1,7 @@ +<%= form_tag( url_for(:controller => 'users',:action => 'resource_search',:id=>user.id), + :remote=>true ,:method => 'get',:class=>'resourcesSearchloadBox',:id=>'resource_search_form') do %> + + <%= hidden_field_tag(:type,type) %> + <%= submit_tag '',:class=>'homepageSearchIcon',:onfocus=>'this.blur();',:style=>'border-style:none' %> + +<% end %> \ No newline at end of file diff --git a/app/views/users/_resource_share_for_project_popup.html.erb b/app/views/users/_resource_share_for_project_popup.html.erb new file mode 100644 index 000000000..40bbd5e7c --- /dev/null +++ b/app/views/users/_resource_share_for_project_popup.html.erb @@ -0,0 +1,52 @@ + + +
    +
    +
    将资源发送至
    +
    + +
    +
    +
    + +
    + <%= form_tag search_user_project_user_path(user),:method => 'get', + :remote=>true,:id=>'search_user_project_form',:class=>'resourcesSearchBox' do %> + <%= hidden_field_tag(:send_id, send_id) %> + <%= hidden_field_tag(:send_ids, send_ids) %> + + + <%= submit_tag '',:class=>'searchIconPopup',:onfocus=>"this.blur();",:style=>'border-style:none' %> + <% end %> +
    + <%= form_tag add_exist_file_to_project_user_path(user),:remote=>true,:id=>'projects_list_form' %> +
    + + <%= hidden_field_tag(:send_id, send_id) %> + <%= hidden_field_tag(:send_ids, send_ids) %> +
    + <% if !projects.empty? %> + <% projects.each do |project| %> +
      +
    • + +
    • +
    • <%= project.name%>
    • +
    + <% end %> +
    +
    +
    +
    + + <%= submit_tag '确定',:class=>'sendSourceText',:onfocus=>'this.blur();' %> +
    + +
    +
    + <% end %> +
    + diff --git a/app/views/users/_resource_share_popup.html.erb b/app/views/users/_resource_share_popup.html.erb new file mode 100644 index 000000000..ed2ed44a6 --- /dev/null +++ b/app/views/users/_resource_share_popup.html.erb @@ -0,0 +1,52 @@ + + +
    +
    +
    将资源发送至
    +
    + +
    +
    +
    + +
    + <%= form_tag search_user_course_user_path(user),:method => 'get', + :remote=>true,:id=>'search_user_course_form',:class=>'resourcesSearchBox' do %> + <%= hidden_field_tag(:send_id, send_id) %> + <%= hidden_field_tag(:send_ids, send_ids) %> + + + <%= submit_tag '',:class=>'searchIconPopup',:onfocus=>"this.blur();",:style=>'border-style:none' %> + <% end %> +
    + <%= form_tag add_exist_file_to_course_user_path(user),:remote=>true,:id=>'course_list_form' %> +
    + + <%= hidden_field_tag(:send_id, send_id) %> + <%= hidden_field_tag(:send_ids, send_ids) %> +
    + <% if !courses.empty? %> + <% courses.each do |course| %> +
      +
    • + +
    • +
    • <%= truncate(course.name,:lendght=>25) + '['+course.time.to_s+course.term + ']'%>
    • +
    + <% end %> +
    +
    +
    +
    + + <%= submit_tag '确定',:class=>'sendSourceText',:onfocus=>'this.blur();' %> +
    + +
    +
    + <% end %> +
    + diff --git a/app/views/users/_resource_upload_popup.html.erb b/app/views/users/_resource_upload_popup.html.erb new file mode 100644 index 000000000..27eebceec --- /dev/null +++ b/app/views/users/_resource_upload_popup.html.erb @@ -0,0 +1,43 @@ + + + + + +
    上传资源 +
    +
    + +
    +
    (未选择文件)
    +
    您可以上传小于50MB的文件
    +
    +
    +
    + +
    +
    + +
    +
    + + +
    +
    +
    + diff --git a/app/views/users/_resources_list.html.erb b/app/views/users/_resources_list.html.erb new file mode 100644 index 000000000..f134e8f42 --- /dev/null +++ b/app/views/users/_resources_list.html.erb @@ -0,0 +1,25 @@ + +<% if attachments.nil? || attachments.empty? %> + + + +<% else %> + <% attachments.each do |attach| %> +
      +
    • + +
    • +
    • + + <%= link_to truncate(attach.filename,:length=>30), download_named_attachment_path(attach.id, attach.filename), + :title => attach.filename,:class=>'resourcesBlack'%> +
    • +
    • <%= number_to_human_size(attach.filesize) %>
    • +
    • <%= get_resource_type(attach.container_type)%>
    • +
    • <%=User.find(attach.author_id).realname.blank? ? User.find(attach.author_id).nickname : User.find(attach.author_id).realname %>
    • +
    • <%= attach.author_id %>
    • +
    • <%= format_date(attach.created_on) %>
    • +
    • <%= attach.id %>
    • +
    + <% end %> +<% end %> diff --git a/app/views/users/_score_new_index.html.erb b/app/views/users/_score_new_index.html.erb index e50b240fd..c1d23d0ed 100644 --- a/app/views/users/_score_new_index.html.erb +++ b/app/views/users/_score_new_index.html.erb @@ -5,8 +5,8 @@ <%= l(:label_user_score_of_skill)%> + <%= l(:label_user_score_of_active) %>
    = <%= format("%.2f" ,collaboration(option_num)).to_i %> + <%= format("%.2f" , influence(option_num) ).to_i %> - + <%= "(" if skill(option_num) < 0 %> <%= format("%.2f" , skill(option_num)).to_i %> <%= ")" if skill(option_num) < 0 %> + <%= format("%.2f" , active(option_num)).to_i %>
    - <% if (format("%.2f" ,collaboration(option_num)).to_i + format("%.2f" , influence(option_num) ).to_i + format("%.2f" , skill(option_num)).to_i + format("%.2f" , active(option_num)).to_i) < 0 %> + + <%= "(" if skill(option_num) < 0 %> <%= format("%.2f" , skill(option_num)).to_i %> <%= ")" if skill(option_num) < 0 %> + <%= format("%.2f" ,project_active(option_num)).to_i %>
    + <% if (format("%.2f" ,collaboration(option_num)).to_i + format("%.2f" , influence(option_num) ).to_i + format("%.2f" , skill(option_num)).to_i + format("%.2f" , project_active(option_num)).to_i) < 0 %>
    <%= l(:label_score_less_than_zero) %>
    <% else %>
    = <%= format("%.2f" ,option_num.total_score).to_i %>
    diff --git a/app/views/users/_show_new_score.html.erb b/app/views/users/_show_new_score.html.erb index 2081c38d6..4e89506a6 100644 --- a/app/views/users/_show_new_score.html.erb +++ b/app/views/users/_show_new_score.html.erb @@ -68,7 +68,7 @@
  • <%= link_to l(:label_user_score_of_active), "javascript:void(0)", :onclick => "show_div('influence_new_score_index')" %> : - <%= format("%.2f" , active(option_num)).to_i %> + <%= format("%.2f" , project_active(option_num)).to_i %>
  • diff --git a/app/views/users/_show_user_homework_form.html.erb b/app/views/users/_show_user_homework_form.html.erb new file mode 100644 index 000000000..ef0265683 --- /dev/null +++ b/app/views/users/_show_user_homework_form.html.erb @@ -0,0 +1,13 @@ +<% user_homeworks.each do |homework|%> +
      +
    • + +
    • + +
    +
    + 创建时间:<%= format_date homework.created_at%> +
    +<% end%> \ No newline at end of file diff --git a/app/views/users/_show_user_homeworks.html.erb b/app/views/users/_show_user_homeworks.html.erb new file mode 100644 index 000000000..935cc4513 --- /dev/null +++ b/app/views/users/_show_user_homeworks.html.erb @@ -0,0 +1,27 @@ +
    +
    +
    导入作业
    +
    + +
    + <%= form_tag user_search_homeworks_user_path(User.current.id), :multipart => true, :remote => true, :class => "coursesSearchBox" do%> + + + <% end%> +
    + <%= form_tag(user_select_homework_users_path, :multipart => true,:remote => true,:name=>"select_homework_form",:id=>'select_homework_form') do %> + +
    + <%= render :partial => 'users/show_user_homework_form', :locals => {:user_homeworks => @user_homeworks}%> +
    +
    +
    + 确定 +
    +
    + 取消 +
    +
    + <% end%> +
    +
    \ No newline at end of file diff --git a/app/views/users/_show_user_resource.html.erb b/app/views/users/_show_user_resource.html.erb new file mode 100644 index 000000000..929cea75b --- /dev/null +++ b/app/views/users/_show_user_resource.html.erb @@ -0,0 +1,67 @@ + + +
    +
    引用资源库资源
    +
    +
    + +
    + + <%= form_tag(user_ref_resource_search_user_path(user),:method => 'get',:remote=>'true',:class=>'referenceSearchBox') do%> + + + <% end %> + +
    +
    +
    +
    +
      +
    • +
    • 资源名称
    • +
    • 大小
    • +
    • 类别
    • +
    • 上传者
    • +
    • 上传时间
    • +
    +
    + <%= form_tag(import_resources_to_homework_user_path(user),:method => 'post',:remote=>'true') do %> + +
    + <%= render :partial => 'resources_list' ,:locals=>{ :attachments => @attachments} %> +
    +
    +
      + <%= pagination_links_full @atta_pages, @atta_count, :per_page_links => false, :remote => @is_remote, :flag => true%> +
    +
    +
    + 确定 + 取消 +
    +
    + <% end %> + diff --git a/app/views/users/_upload_resource.html.erb b/app/views/users/_upload_resource.html.erb new file mode 100644 index 000000000..d73b2986a --- /dev/null +++ b/app/views/users/_upload_resource.html.erb @@ -0,0 +1,54 @@ + + 上传资源 + +
    + <%= form_tag(user_resource_create_user_path, :multipart => true,:remote => !ie8?,:name=>"upload_form",:id=>'upload_form') do %> +
    + + <% if defined?(container) && container && container.saved_attachments %> + + <% container.attachments.each_with_index do |attachment, i| %> + + <%= text_field_tag("attachments[p#{i}][filename]", attachment.filename, :class => 'filename readonly', :readonly=>'readonly')%> + <%= text_field_tag("attachments[p#{i}][description]", attachment.description, :maxlength => 254, :placeholder => l(:label_optional_description), :class => 'description', :style=>"display: inline-block;") %> + <%= l(:field_is_public)%>: + <%= check_box_tag("attachments[p#{i}][is_public_checkbox]", attachment.is_public,attachment.is_public == 1 ? true : false,:class => 'remove-upload')%> + <%= if attachment.id.nil? + #待补充代码 + else + link_to(' '.html_safe, attachment_path(attachment, :attachment_id => "p#{i}", :format => 'js'), :method => 'delete', :remote => true, :class => 'remove-upload') + end + %> + <%#= render :partial => 'tags/tag', :locals => {:obj => attachment, :object_flag => "6"} %> + + <%= hidden_field_tag "attachments[p#{i}][token]", "#{attachment.token}" %> + + <% end %> + <% end %> + +
    +
    + + + <%= render :partial => 'attachment_list' %> +
    + + + +
    +
    +
    (未选择文件)
    +
    您可以上传小于50MB的文件
    +
    +
    +
    +
    +
    + + <%= submit_tag '确定',:onclick=>'submit_files();',:onfocus=>'this.blur()',:class=>'sendSourceText' %> +
    + +
    + <% end %> +
    + \ No newline at end of file diff --git a/app/views/users/_user_activities.html.erb b/app/views/users/_user_activities.html.erb new file mode 100644 index 000000000..29752121f --- /dev/null +++ b/app/views/users/_user_activities.html.erb @@ -0,0 +1,99 @@ +<%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg',"init_activity_KindEditor" %> + +<% first_user_activity = user_activities.first.id unless user_activities.first.nil? %> +<% user_activities.each do |user_activity| + if user_activities %> + + <% act= user_activity.act unless user_activity.act_type == "ProjectCreateInfo" %> + <% case user_activity.container_type.to_s %> + <% when 'Course' %> + <% if act %> + <% case user_activity.act_type.to_s %> + <% when 'HomeworkCommon' %> + <%= render :partial => 'course_homework', :locals => {:activity => act,:user_activity_id =>user_activity.id,:first_user_activity =>first_user_activity,:page => page} %> + <% when 'News' %> + <%= render :partial => 'course_news', :locals => {:activity => act,:user_activity_id =>user_activity.id,:first_user_activity =>first_user_activity,:page => page} %> + <% when 'Message'%> + <%= render :partial => 'course_message', :locals => {:activity => act,:user_activity_id =>user_activity.id,:first_user_activity =>first_user_activity,:page => page} %> + <% when 'Poll' %> + <%= render :partial => 'course_poll', :locals => {:activity => act, :user_activity_id => user_activity.id,:first_user_activity =>first_user_activity,:page => page} %> + <% end %> + <% end %> + <% when 'Project' %> + <% if act %> + <% case user_activity.act_type.to_s %> + <% when 'Issue' %> + <%= render :partial => 'project_issue', :locals => {:activity => act,:user_activity_id =>user_activity.id,:first_user_activity =>first_user_activity,:page => page} %> + <% when 'Message' %> + <%= render :partial => 'project_message', :locals => {:activity => act,:user_activity_id =>user_activity.id,:first_user_activity =>first_user_activity,:page => page} %> + <% end %> + <% end %> + <% end %> + <% end %> +<% end %> + +<% if user_activities.count == 10%> +
    展开更多<%=link_to "", user_activities_path(@user.id,:type => type,:page => page),:id => "more_activities_link",:remote => "true",:class => "none" %>
    + <%#= link_to "点击展开更多",user_activities_path(@user.id,:type => type,:page => page),:id => "show_more_activities",:remote => "true",:class => "loadMore mt10 f_grey"%> +<% end%> + + \ No newline at end of file diff --git a/app/views/users/_user_fans_item.html.erb b/app/views/users/_user_fans_item.html.erb index 4ca8fbefc..b3fc7905c 100644 --- a/app/views/users/_user_fans_item.html.erb +++ b/app/views/users/_user_fans_item.html.erb @@ -1,3 +1,5 @@ +<% unless list.nil?%> +<% for item in list %> + <% if(User.current.logged? && User.current != item )%> <%if(item.watched_by?(User.current))%> - 取消关注 + 取消关注 <% else %> - 添加关注 + 添加关注 <% end %> <% end %>
    +<% end %> +<% end %> \ No newline at end of file diff --git a/app/views/users/_user_homework_attachment.html.erb b/app/views/users/_user_homework_attachment.html.erb new file mode 100644 index 000000000..9b7c6c06a --- /dev/null +++ b/app/views/users/_user_homework_attachment.html.erb @@ -0,0 +1,60 @@ +
    + + <% if defined?(container) && container && container.saved_attachments %> + <% container.attachments.each_with_index do |attachment, i| %> + + <%= text_field_tag("attachments[p#{i}][filename]", attachment.filename, :class => 'filename link_file', :readonly=>'readonly')%> + <%= text_field_tag("attachments[p#{i}][description]", attachment.description, :maxlength => 254, :placeholder => l(:label_optional_description), :class => 'description', :style=>"display: inline-block;") %> + <%= l(:field_is_public)%>: + <%= check_box_tag("attachments[p#{i}][is_public_checkbox]", attachment.is_public,attachment.is_public == 1 ? true : false,:class => 'is_public')%> + <%= link_to(' '.html_safe, attachment_path(attachment, :attachment_id => "p#{i}", :format => 'js'), :method => 'delete', :remote => true, :class => 'remove-upload') unless attachment.id.nil? %> + <%= hidden_field_tag "attachments[p#{i}][token]", "#{attachment.token}" %> + +
    + <% end %> + <% container.saved_attachments.each_with_index do |attachment, i| %> + + <%= text_field_tag("attachments[p#{i}][filename]", attachment.filename, :class => 'filename readonly', :readonly=>'readonly')%> + <%= text_field_tag("attachments[p#{i}][description]", attachment.description, :maxlength => 254, :placeholder => l(:label_optional_description), :class => 'description', :style=>"display: inline-block;") %> + <%= l(:field_is_public)%>: + <%= check_box_tag("attachments[p#{i}][is_public_checkbox]", attachment.is_public,attachment.is_public == 1 ? true : false,:class => 'is_public')%> + <%= link_to(' '.html_safe, attachment_path(attachment, :attachment_id => "p#{i}", :format => 'js'), :method => 'delete', :remote => true, :class => 'remove-upload') unless attachment.id.nil? %> + <%= hidden_field_tag "attachments[p#{i}][token]", "#{attachment.token}" %> + +
    + <% end %> + <% end %> +
    + <%= file_field_tag 'attachments[dummy][file]', + :id => '_file', + :class => ie8? ? '' : 'file_selector', + :multiple => true, + :onchange => 'addInputFiles(this);', + :style => ie8? ? '' : 'display:none', + :data => { + :max_file_size => Setting.attachment_max_size.to_i.kilobytes, + :max_file_size_message => l(:error_attachment_too_big, :max_size => number_to_human_size(Setting.attachment_max_size.to_i.kilobytes)), + :max_concurrent_uploads => Redmine::Configuration['max_concurrent_ajax_uploads'].to_i, + :upload_path => uploads_path(:format => 'js',:project =>nil), + :description_placeholder => l(:label_optional_description), + :field_is_public => l(:field_is_public), + :are_you_sure => l(:text_are_you_sure), + :file_count => l(:label_file_count), + :delete_all_files => l(:text_are_you_sure_all) + } %> +
    +
    + +
    + + 上传附件 + <%= link_to "资源库",{:controller => 'users',:action=>'user_import_resource',:id=>User.current.id,:homework_id=>container.id},:class => "FilesBtn fl mt3 mr20",:remote => true%> + <% if defined?(has_program) && has_program %> + 编程 + + <% end %> +
    + +<% content_for :header_tags do %> + <%= javascript_include_tag 'attachments' %> +<% end %> \ No newline at end of file diff --git a/app/views/users/_user_homework_form.html.erb b/app/views/users/_user_homework_form.html.erb new file mode 100644 index 000000000..6167e4e10 --- /dev/null +++ b/app/views/users/_user_homework_form.html.erb @@ -0,0 +1,92 @@ +<% content_for :header_tags do %> + <%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg'%> + <%= javascript_include_tag 'homework','baiduTemplate' %> + +<% end %> + +
    +
    + +

    +
    +
    + +
    + <%= link_to("导入作业", user_import_homeworks_user_path(User.current.id,:select_course => defined?(select_course)),:class => "BlueCirBtn fl mr10",:remote => true) unless edit_mode%> +
    + + <%= calendar_for('homework_end_time')%> +
    +
    +
    +

    +
    +
    +
    + <% if edit_mode %> + <%= f.kindeditor :description, :editor_id => 'homework_description_editor', :height => "150px", :owner_id => homework.id, :owner_type => OwnerTypeHelper::HOMEWORKCOMMON %> + <% else %> + <%= hidden_field_tag :asset_id, params[:asset_id], :required => false, :style => 'display:none' %> + <%= f.kindeditor :description, :editor_id => 'homework_description_editor', :height => "150px" %> + <% end %> +
    +
    + +
    + <%= select_tag :course_id, options_for_select(get_as_teacher_courses(User.current), homework.course_id), {:class => "InputBox w709",:value => "请选择发布作业的课程"} %> +
    +

    +
    + +
    + + <%= render :partial => 'users/user_homework_attachment', :locals => {:container => homework, :has_program=>!(edit_mode && homework.homework_type == 1)} %> +
    + + +
    + <% if edit_mode %> + 确定 + + <%= link_to "取消",user_homeworks_user_path(User.current.id),:class => "fr mr10 mt3"%> + <% else %> + 发送 + + 取消 + <% end %> +
    +
    + + + +
    +
    +
    + + + + + + + diff --git a/app/views/users/_user_homework_list.html.erb b/app/views/users/_user_homework_list.html.erb new file mode 100644 index 000000000..336a62d37 --- /dev/null +++ b/app/views/users/_user_homework_list.html.erb @@ -0,0 +1,90 @@ +<% homework_commons.each do |homework_common|%> + <% is_teacher = User.current.allowed_to?(:as_teacher,homework_common.course) %> +
    +
    +
    + <%=link_to image_tag(url_to_avatar(homework_common.user),width:"50px", height: "50px"), user_activities_path(homework_common.user.id)%> +
    +
    +
    + <%= link_to homework_common.user.show_name, user_activities_path(homework_common.user_id), :class => "newsBlue mr15"%> + TO + <%= link_to homework_common.course.name, course_path(homework_common.course_id), :class => "newsBlue ml15"%> +
    + + + <% if homework_common.homework_detail_manual%> + <% if homework_common.homework_detail_manual.comment_status == 1%> + 未开启匿评 + <% elsif homework_common.homework_detail_manual.comment_status == 2%> + 匿评中 + <% elsif homework_common.homework_detail_manual.comment_status == 3%> + 匿评已结束 + <% end%> + <% end%> + +
    +
    + <%= user_for_homework_common homework_common,is_teacher %> +
    + <% if homework_common.homework_type == 2 && is_teacher%> +
    + <%= link_to "模拟答题", new_user_commit_homework_users_path(homework_id: homework_common.id, is_test: true), class: 'c_blue test-program-btn', title: '教师可以通过模拟答题设置作业的标准答案' %> +
    + <% end %> + <% if homework_common.homework_type == 2%> +
    + 语言: + <%= homework_common.language_name%> +
    + <% end %> +
    + <%= l(:label_end_time)%>:<%= homework_common.end_time%> +
    +
    +
    + <%= homework_common.description.html_safe %> +
    +
    + <%= render :partial => 'student_work/work_attachments', :locals => {:attachments => homework_common.attachments} %> +
    +
    + <% if is_teacher%> + <%# if false%> +
    +
      +
    • +
        +
      • + <%= link_to l(:button_edit),edit_homework_common_path(homework_common,:is_in_course => is_in_course), :class => "postOptionLink"%> +
      • +
      • + <%= link_to(l(:label_bid_respond_delete), homework_common_path(homework_common,:is_in_course => is_in_course),:method => 'delete', :confirm => l(:text_are_you_sure), :class => "postOptionLink") %> +
      • +
      • + <%= link_to("匿评设置", start_evaluation_set_homework_common_path(homework_common),:class => "postOptionLink", :remote => true) if homework_common.homework_detail_manual.comment_status == 1%> +
      • +
      • + <%= homework_anonymous_comment homework_common %> +
      • +
      +
    • +
    +
    + <% end%> +
    +
    +
    +
    +<% end%> +<% if homework_commons.count == 10%> + <% if is_in_course == 1%> + + <%= link_to "加载更多",homework_common_index_path(:course => course_id,:page => page,:is_in_course => is_in_course),:id => "user_show_more_homework",:remote => "true",:class => "loadMore f_grey"%> + <% else%> + + <%= link_to "加载更多",user_homeworks_user_path(User.current.id,:page => page,:is_in_course => is_in_course),:id => "user_show_more_homework",:remote => "true",:class => "loadMore f_grey"%> + <% end%> +<% end%> \ No newline at end of file diff --git a/app/views/users/_user_jour_reply.html.erb b/app/views/users/_user_jour_reply.html.erb index ee94cb35a..60eda9fcd 100644 --- a/app/views/users/_user_jour_reply.html.erb +++ b/app/views/users/_user_jour_reply.html.erb @@ -3,9 +3,9 @@
    <%= link_to image_tag(url_to_avatar(reply.user),:width => '32',:height => '32'), user_path(reply.user),:class => "users_pic_sub fl mr5" %>
    - <%= link_to "#{reply.user.login} ".html_safe, user_path(reply.user),:class => 'course_name fl c_blue02 ', :target => "_blank"%> + <%= link_to "#{reply.user.nickname} ".html_safe, user_path(reply.user),:class => 'course_name fl c_blue02 ', :target => "_blank"%>  回复  - <%= link_to "#{parent_jour.user.login} : ".html_safe, user_path(parent_jour.user),:class => 'course_name fl c_blue02 mr5 ', :target => "_blank"%> + <%= link_to "#{parent_jour.user.nickname} : ".html_safe, user_path(parent_jour.user),:class => 'course_name fl c_blue02 mr5 ', :target => "_blank"%>
    <%= reply.notes.html_safe %>
    diff --git a/app/views/users/_user_jours.html.erb b/app/views/users/_user_jours.html.erb index 9d7a601d5..75a7d0fda 100644 --- a/app/views/users/_user_jours.html.erb +++ b/app/views/users/_user_jours.html.erb @@ -8,7 +8,7 @@ div.ke-toolbar .ke-outline{border:none;} div.respond-form .reply_btn{margin-left:565px;margin-top:5px;} - div.recall_con{width:600px;} + div.recall_con{width:570px;} div.recall_con .reply_btn{margin-left:555px;margin-top:5px;} <%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg' %> diff --git a/app/views/users/_user_jours_new.html.erb b/app/views/users/_user_jours_new.html.erb index 9a9e14787..0fe301641 100644 --- a/app/views/users/_user_jours_new.html.erb +++ b/app/views/users/_user_jours_new.html.erb @@ -1,8 +1,8 @@ -
    +
    <%= link_to image_tag(url_to_avatar(jour.user),:width => '46',:height => '46'), user_path(jour.user),:class => "users_pic fl" %>
    - <%= link_to "#{jour.user.login} : ".html_safe, user_path(jour.user),:class => 'fl c_blue02 f14 fb mb5', :target => "_blank"%> + <%= link_to "#{jour.user.nickname} : ".html_safe, user_path(jour.user),:class => 'fl c_blue02 f14 fb mb5', :target => "_blank"%>
    diff --git a/app/views/users/_user_message_course.html.erb b/app/views/users/_user_message_course.html.erb new file mode 100644 index 000000000..fee28f761 --- /dev/null +++ b/app/views/users/_user_message_course.html.erb @@ -0,0 +1,340 @@ +<% if ma.class == CourseMessage %> + <% if ma.course_message_type == "News" %> +
      +
    • <%=link_to image_tag(url_to_avatar(ma.course_message.author), :width => "30", :height => "30"),user_path(ma.course_message.author) %>
    • +
    • <%=link_to ma.course_message.author, user_path(ma.course_message.author), :class => "newsBlue homepageNewsPublisher" %>">发布了通知:
    • +
    • + <%= link_to ma.course_message.title, {:controller => 'news', :action => 'show', :id => ma.course_message.id }, + :class =>"#{ma.viewed == 0 ? "newsBlack" : "newsGrey"}", + :onmouseover =>"message_titile_show($(this),event)", + :onmouseout => "message_titile_hide($(this))" %>
    • + +
    • <%= time_tag(ma.created_at).html_safe %>
    • +
    + <% end %> + <% if ma.course_message_type == "Comment" %> +
      +
    • <%=link_to image_tag(url_to_avatar(ma.course_message.author), :width => "30", :height => "30"), user_path(ma.course_message.author) %>
    • +
    • <%=link_to ma.course_message.author, user_path(ma.course_message.author), :class => "newsBlue homepageNewsPublisher" %>">评论了通知:
    • +
    • + <%= link_to ma.course_message.commented.title, {:controller => 'news', :action => 'show', :id => ma.course_message.commented.id }, + :class =>"#{ma.viewed == 0 ? "newsBlack" : "newsGrey"}", + :onmouseover =>"message_titile_show($(this),event)", + :onmouseout => "message_titile_hide($(this))" %>
    • + +
    • <%= time_tag(ma.created_at).html_safe %>
    • +
    + <% end %> + <% if ma.course_message_type == "HomeworkCommon" && ma.status.nil? %> +
      +
    • <%=link_to image_tag(url_to_avatar(ma.course_message.user), :width => "30", :height => "30"), user_path(ma.course_message.user) %>
    • +
    • <%=link_to ma.course_message.user.lastname + ma.course_message.user.firstname + "老师", user_path(ma.course_message.user), :class => "newsBlue homepageNewsPublisher" %> + ">发布了课程作业: +
    • +
    • + <%= link_to ma.course_message.name, student_work_index_path(:homework => ma.course_message.id), + :class =>"#{ma.viewed == 0 ? "newsBlack" : "newsGrey"}", + :onmouseover =>"message_titile_show($(this),event)", + :onmouseout => "message_titile_hide($(this))" %>
    • + +
    • <%= time_tag(ma.created_at).html_safe %>
    • +
    + <% end %> + <% if ma.course_message_type == "HomeworkCommon" && ma.status == 1 %> +
      +
    • <%=link_to image_tag(url_to_avatar(ma.course_message.user), :width => "30", :height => "30"), user_path(ma.course_message.user) %>
    • +
    • <%=link_to ma.course_message.user, user_path(ma.course_message.user), :class => "newsBlue homepageNewsPublisher" %>">发布的作业:
    • +
    • + <%= link_to ma.course_message.name, student_work_index_path(:homework => ma.course_message.id), + :class => "#{ma.viewed == 0 ? "newsBlack" : "newsGrey"}", + :onmouseover => "message_titile_show($(this),event)", + :onmouseout => "message_titile_hide($(this))" %> +
    • + +
    •    截止时间快到了!
    • +
    • <%= time_tag(ma.created_at).html_safe %>
    • +
    + <% end %> + + <% if ma.course_message_type == "HomeworkCommon" && ma.status == 2 %> +
      +
    • + <%= link_to image_tag(url_to_avatar(ma.course_message.user), :width => "30", :height => "30"), user_path(ma.course_message.user) %> +
    • +
    • + <%= link_to ma.course_message.user.lastname + ma.course_message.user.firstname + "老师", + user_path(ma.course_message.user), :class => "newsBlue homepageNewsPublisher" %> + ">启动了作业匿评: +
    • +
    • + <%= link_to "作业题目:" + ma.course_message.name, student_work_index_path(:homework => ma.course_message.id), :class => "#{ma.viewed == 0 ? "newsBlack" : "newsGrey"}", + :onmouseover => "message_titile_show($(this),event)", + :onmouseout => "message_titile_hide($(this))" %> +
    • + +
    • <%= time_tag(ma.created_at).html_safe %>
    • +
    + <% end %> + + <% if ma.course_message_type == "HomeworkCommon" && ma.status == 3 %> +
      +
    • <%=link_to image_tag(url_to_avatar(ma.course_message.user), :width => "30", :height => "30"), user_path(ma.course_message.user) %>
    • +
    • + <%=link_to ma.course_message.user.lastname + ma.course_message.user.firstname + "老师", + user_path(ma.course_message.user), :class => "newsBlue homepageNewsPublisher" %>">关闭了作业匿评:
    • +
    • + <%= link_to "作业题目:" + ma.course_message.name, student_work_index_path(:homework => ma.course_message.id), :class =>"#{ma.viewed == 0 ? "newsBlack" : "newsGrey"}", + :onmouseover =>"message_titile_show($(this),event)", + :onmouseout => "message_titile_hide($(this))"%> +
    • + +
    • <%= time_tag(ma.created_at).html_safe %>
    • +
    + <% end %> + + <% if ma.course_message_type == "HomeworkCommon" && ma.status == 4 %> +
      +
    • + <%= link_to image_tag(url_to_avatar(ma.course_message.user), :width => "30", :height => "30"), user_path(ma.course_message.user) %> +
    • +
    • + <%= link_to ma.course_message.user.lastname + ma.course_message.user.firstname + "老师", + user_path(ma.course_message.user), :class => "newsBlue homepageNewsPublisher" %> + ">启动作业匿评失败 +
    • +
    • + <%= link_to "作业题目:" + ma.course_message.name, student_work_index_path(:homework => ma.course_message.id), :class => "#{ma.viewed == 0 ? "newsBlack" : "newsGrey"}", + :onmouseover => "message_titile_show($(this),event)", + :onmouseout => "message_titile_hide($(this))" %> +
    • + +
    • <%= time_tag(ma.created_at).html_safe %>
    • +
    + <% end %> + + <% if ma.course_message_type == "Poll" %> + + <% end %> + <% if ma.course_message_type == "Message" %> + + <% end %> + <% if ma.course_message_type == "StudentWorksScore" %> + + <% end %> + <% if ma.course_message_type == "JournalsForMessage" %> + <% if ma.course_message.jour_type == 'Course' %> + <% if params[:type] != 'homework' %> + + <% end %> + <% else %> + + <% end %> + <% end %> +<% end %> \ No newline at end of file diff --git a/app/views/users/_user_message_forge.html.erb b/app/views/users/_user_message_forge.html.erb new file mode 100644 index 000000000..b93122bd2 --- /dev/null +++ b/app/views/users/_user_message_forge.html.erb @@ -0,0 +1,213 @@ +<% if ma.class == ForgeMessage %> + + <% if ma.forge_message_type == "AppliedProject" %> + + <% end %> + + <% if ma.forge_message_type == "ProjectInvite" %> + <% inviter = User.find(ma.forge_message_id) %> +
      +
    • + <%=link_to image_tag(url_to_avatar(inviter), :width => "30", :height => "30"), user_path(inviter) %> +
    • +
    • + <%=link_to inviter, user_path(inviter), :class => "newsBlue homepageNewsPublisher" %> + '>邀请你加入项目 +
    • + <% if ma.user.member_of?(ma.project) %> +
    • + <% else %> +
    • + <% end %> + <%= link_to ma.project, project_path(ma.project), + :class => "#{ma.viewed == 0 ? "newsBlack" : "newsGrey"}", + :onmouseover => "message_titile_show($(this),event)", + :onmouseout => "message_titile_hide($(this))" %> +
    • + + <% unless User.current.member_of?(ma.project) %> +
    • + <%=link_to "同意加入", {:controller => 'projects', :action => 'member', :id => ma.project_id, :message_id =>ma.id, :key => ma.secret_key}, + :value => ma.secret_key, + :class => "green_btn_cir ml10", + :style => "color:#fff" %> +
    • + <% end %> +
    • <%= time_tag(ma.created_at).html_safe %>
    • +
    + <% end %> + <% if ma.forge_message_type == "Issue" %> + <% if ma.status == 1%> + + <% else %> + + <% end %> + <% end %> + <% if ma.forge_message_type == "Journal" %> + + <% end %> + <% if ma.forge_message_type == "Message" %> + + <% end %> + <% if ma.forge_message_type == "News" %> + + <% end %> + <% if ma.forge_message_type == "Comment" %> +
      +
    • <%=link_to image_tag(url_to_avatar(ma.forge_message.author), :width => "30", :height => "30"), user_path(ma.forge_message.author) %>
    • +
    • <%=link_to ma.forge_message.author, user_path(ma.forge_message.author), :class => "newsBlue homepageNewsPublisher" %> + ">评论了新闻:
    • +
    • + <%= link_to "#{ma.forge_message.commented.title}", + {:controller => 'news', :action => 'show', :id => ma.forge_message.commented.id },:class =>"#{ma.viewed == 0 ? "newsBlack" : "newsGrey"}", + :onmouseover => "message_titile_show($(this),event)", + :onmouseout => "message_titile_hide($(this))" %> +
    • + +
    • <%= time_tag(ma.created_at).html_safe %>
    • +
    + <% end %> +<% end %> \ No newline at end of file diff --git a/app/views/users/_user_message_forum.html.erb b/app/views/users/_user_message_forum.html.erb new file mode 100644 index 000000000..102b4a155 --- /dev/null +++ b/app/views/users/_user_message_forum.html.erb @@ -0,0 +1,41 @@ +<% if ma.class == MemoMessage %> + <% if ma.memo_type == "Memo" %> + + <% end %> +<% end %> \ No newline at end of file diff --git a/app/views/users/_user_message_system.html.erb b/app/views/users/_user_message_system.html.erb new file mode 100644 index 000000000..efbd5d76b --- /dev/null +++ b/app/views/users/_user_message_system.html.erb @@ -0,0 +1,30 @@ +<% if ma.class == SystemMessage %> + <%# @user_system_messages.each do |usm| %> +
      +
    • + +
    • +
    • + Trustie平台发布新消息: +
    • + 【系统消息】 +
    • + + <%= link_to ma.subject.blank? ? (ma.content.nil? ? ma.description.html_safe : ma.content.html_safe) : ma.subject, user_system_messages_path(User.current), + :id => "content_link_#{ma.id}", + :onmouseover =>"message_titile_show($(this),event);", + :onmouseout => "message_titile_hide($(this));" + %> +
    • + +
    • <%= time_tag(ma.created_at).html_safe %>
    • +
    + <%# end %> +<% end %> \ No newline at end of file diff --git a/app/views/users/_user_message_userfeedaback.html.erb b/app/views/users/_user_message_userfeedaback.html.erb new file mode 100644 index 000000000..672dfda64 --- /dev/null +++ b/app/views/users/_user_message_userfeedaback.html.erb @@ -0,0 +1,30 @@ +<% if ma.class == UserFeedbackMessage %> + <% if ma.journals_for_message_type == "JournalsForMessage" %> + + <% end %> +<% end %> \ No newline at end of file diff --git a/app/views/users/_user_programing_attr.html.erb b/app/views/users/_user_programing_attr.html.erb new file mode 100644 index 000000000..e0bee689a --- /dev/null +++ b/app/views/users/_user_programing_attr.html.erb @@ -0,0 +1,44 @@ + +

    编程作业的测试集设置

    +
    +
    +
    + +
    + <% if edit_mode && homework.is_program_homework? %> + <% homework.homework_tests.each_with_index do |test, index| %> +
    + + + + <% if index != 0 %> + + <% end %> +
    +
    + <% end %> + <% else %> +
    + + + +
    +
    + <% end %> + +
    + 温馨提示:您可以在发布作业后,在作业“模拟答题”中进行标准代码的检测。 + 确  定 +
    +
    + +
    + + \ No newline at end of file diff --git a/app/views/users/_user_show.html.erb b/app/views/users/_user_show.html.erb index 8e3d27666..9eabb2be5 100644 --- a/app/views/users/_user_show.html.erb +++ b/app/views/users/_user_show.html.erb @@ -23,8 +23,23 @@ - <%= l(:label_x_has_fans,:count=>user.watcher_users.count)%> - <%= l(:label_has_watchers,:count=>User.watched_by(user.id).count) %> + <%= l(:label_x_has_fans,:count=>user.watcher_users.count, :remote => true)%> + <%= l(:label_has_watchers,:count=>User.watched_by(user.id).count, :remote => true) %> + <% if User.current.logged?%> + <% if User.current == user%> + 编辑资料 + <%else%> + <%if(user.watched_by?(User.current))%> + + <%=link_to "取消关注", watch_path(:object_type=> 'user',:object_id=>user.id,:target_id=>user.id, :remote => "true"), :class => "fr qx_btn mr10", :method => "delete", :title => "取消关注" %> + + <% else %> + + <%= link_to "添加关注", watch_path(:object_type=>'user',:object_id=>user.id,:target_id=>user.id, :remote => "true"), :class => "fr gz_btn mr10", :method => "post", :title => "添加关注" %> + + <% end %> + <% end%> + <% end %> diff --git a/app/views/users/add_exist_file_to_course.js.erb b/app/views/users/add_exist_file_to_course.js.erb new file mode 100644 index 000000000..c61790c40 --- /dev/null +++ b/app/views/users/add_exist_file_to_course.js.erb @@ -0,0 +1,9 @@ +<% if @flag == true%> +$("#search_div").html('<%= escape_javascript( render :partial => 'resource_search_form',:locals => {:user=>@user,:type=>@type} ) %>'); +$("#resources_list").html('<%= escape_javascript( render :partial => 'resources_list' ,:locals=>{ :attachments => @attachments})%>'); +$("#res_count").html(0); +$("#checkboxAll").attr('checked',false); +$("#res_all_count").html(<%= @atta_count%>); +closePopUp(); +<% else%> +<% end %> \ No newline at end of file diff --git a/app/views/users/add_exist_file_to_project.js.erb b/app/views/users/add_exist_file_to_project.js.erb new file mode 100644 index 000000000..c61790c40 --- /dev/null +++ b/app/views/users/add_exist_file_to_project.js.erb @@ -0,0 +1,9 @@ +<% if @flag == true%> +$("#search_div").html('<%= escape_javascript( render :partial => 'resource_search_form',:locals => {:user=>@user,:type=>@type} ) %>'); +$("#resources_list").html('<%= escape_javascript( render :partial => 'resources_list' ,:locals=>{ :attachments => @attachments})%>'); +$("#res_count").html(0); +$("#checkboxAll").attr('checked',false); +$("#res_all_count").html(<%= @atta_count%>); +closePopUp(); +<% else%> +<% end %> \ No newline at end of file diff --git a/app/views/users/edit_brief_introduction.js.erb b/app/views/users/edit_brief_introduction.js.erb new file mode 100644 index 000000000..c64482715 --- /dev/null +++ b/app/views/users/edit_brief_introduction.js.erb @@ -0,0 +1,3 @@ +$("#user_brief_introduction_show").html("<%= escape_javascript render(:partial => "layouts/user_brief_introduction", :locals => {:user => @user}) %>"); +$("#user_brief_introduction_show").show(); +$("#user_brief_introduction_edit").hide(); \ No newline at end of file diff --git a/app/views/users/import_resources_to_homework.js.erb b/app/views/users/import_resources_to_homework.js.erb new file mode 100644 index 000000000..61fcd294d --- /dev/null +++ b/app/views/users/import_resources_to_homework.js.erb @@ -0,0 +1,16 @@ +<% unless @attachments.empty?%> + <% @attachments.each_with_index do |attachment, i| %> + $("#attachments_fields").append( + ''+ + '<%= text_field_tag("attachments[p#{i}][filename]", attachment.filename, :class => "filename link_file", :readonly=>"readonly")%>'+ + '<%= text_field_tag("attachments[p#{i}][description]", attachment.description, :maxlength => 254, :placeholder => l(:label_optional_description), :class => "description", :style=>"display: inline-block;") %>'+ + '<%= l(:field_is_public)%>:'+ + '<%= check_box_tag("attachments[p#{i}][is_public_checkbox]", attachment.is_public,attachment.is_public == 1 ? true : false,:class => "is_public")%>'+ + '<%= link_to(" ".html_safe, attachment_path(attachment, :attachment_id => "p#{i}", :format => "js"), :method => "delete", :remote => true, :class => "remove-upload") unless attachment.id.nil? %>'+ + '<%= hidden_field_tag "attachments[p#{i}][token]", "#{attachment.token}" %>'+ + ''+ + '
    ') + + <% end %> + hideResource(); +<% end %> \ No newline at end of file diff --git a/app/views/users/new_user_commit_homework.html.erb b/app/views/users/new_user_commit_homework.html.erb new file mode 100644 index 000000000..c3a736058 --- /dev/null +++ b/app/views/users/new_user_commit_homework.html.erb @@ -0,0 +1,140 @@ +<% content_for :header_tags do %> + <%= javascript_include_tag "/assets/codemirror/codemirror_python_ruby_c" %> + <%= javascript_include_tag 'homework','baiduTemplate' %> + <%= stylesheet_link_tag "/assets/codemirror/codemirror" %> + +<% end %> + + + + + +
    + + +
    +
    <%= @is_test ? '模拟答题' : '提交作品' %>
    +
    +
    + +
    +
    +
    +
    + <%= @homework.name %> +
    + + 截止时间:<%= @homework.end_time %> + +
    + <%= @homework.user.show_name %> +

    + <%= @homework.description.html_safe %> +

    +
    + +
    +
    + <%= form_for(@student_work, + :html => { :multipart => true }, + :url => {:controller => 'users', + :action => 'user_commit_homework', + :student_work_id => @student_work.id, + :homework => @homework.id + }, + :method => :post) do |f|%> + +
    + 请使用 <%= @homework.language_name %> 语言编写 + style="display-hidden" id="data-language"> +
    +
    + <%= f.text_area :name, id: 'program-title', class:"InputBox W700", placeholder:"请概括你的代码的功能" %> +
    +
    + <%= f.text_area :description, id: 'program-src', class:"InputBox W700 H150", placeholder:"请贴入你的代码", rows: 10 %> + +
    +
    + 测试代码 + <% unless @is_test %> + 提交代码 + <% end %> +
    +
    + <% end %> +
    +
    + +
    +
    + + <% @student_work.student_work_tests.each_with_index do |test, index| %> +
    +

    + 第<%= @student_work.student_work_tests.count - index%>次测试 +

    + <%= format_time(test.created_at).to_s%> +
    +
    + <% if test.status.to_i == -2 %> +
    <%= test.results.first %>
    + <% else %> +
    +
      + <% test.results.each_with_index do |x, i| %> +
    • 测试<%=i+1%> + <% if x["status"].to_i != 0 %> + 测试错误! + 您的输出: + <%=x["result"]%> + 正确输出: + <%=x["output"]%> +
      +
    • + <% else %> + 测试正确! +
      + + <% end %> + <% end %> +
    +
    + <% end %> + <% end %> +
    +
    \ No newline at end of file diff --git a/app/views/users/rename_resource.js.erb b/app/views/users/rename_resource.js.erb new file mode 100644 index 000000000..5556fb313 --- /dev/null +++ b/app/views/users/rename_resource.js.erb @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/app/views/users/resource_preview.js.erb b/app/views/users/resource_preview.js.erb new file mode 100644 index 000000000..c3e1fb3ab --- /dev/null +++ b/app/views/users/resource_preview.js.erb @@ -0,0 +1,5 @@ +<% if @preview_able %> +top.location.href = '<%=download_named_attachment_path(@file.id, @file.filename, preview: true) %>' +<% else %> +window.alert('该资源不可预览') +<% end %> \ No newline at end of file diff --git a/app/views/users/resource_search.js.erb b/app/views/users/resource_search.js.erb new file mode 100644 index 000000000..d295ce003 --- /dev/null +++ b/app/views/users/resource_search.js.erb @@ -0,0 +1,5 @@ +$("#resources_list").html('<%= escape_javascript( render :partial => 'resources_list' ,:locals=>{ :attachments => @attachments})%>'); +$("#pages").html('<%= pagination_links_full @atta_pages, @atta_count, :per_page_links => false, :remote => @is_remote, :flag => true %>'); +$("#res_all_count").html(<%= @atta_count%>); +$("#res_count").html(0); +$("#checkboxAll").attr('checked',false); \ No newline at end of file diff --git a/app/views/users/search.html.erb b/app/views/users/search.html.erb index 13979f79f..f5287cbd4 100644 --- a/app/views/users/search.html.erb +++ b/app/views/users/search.html.erb @@ -1,94 +1,70 @@ - + function searchByChange() + { + $("#search_by_input").val($("#search_by").val()); + } + -
    - <%= form_tag( users_search_path, :method => :get, :id => 'search_user_form') do %> - - - - - - - - - - -
    - <%= l(:label_software_user ) %> - - <%= l(:label_user_location) %> : - - - -
    - <%=link_to l(:field_homepage), home_path %> > - <%= l(:label_software_user)%> -
    -
    -<% end %> - - -
    - <% if @users.size > 0 %> - <%= render :partial => 'user_show' %> +
    + <%= form_tag( users_search_path, :method => :get, :id => 'search_user_form') do %> + + + + + + + + + + +
    + <%= l(:label_software_user ) %> + + <%= l(:label_user_location) %> : + + +
    + <%=link_to l(:field_homepage), home_path %> > + <%= l(:label_software_user)%> +
    +
    + <% end %> - - <% else %> - <%= render :partial => "layouts/no_content"%> - <% end %> -
    - +
    +
    +
    -<% html_title(l(:label_user_plural)) -%> diff --git a/app/views/users/search_user_course.js.erb b/app/views/users/search_user_course.js.erb new file mode 100644 index 000000000..60ddd6d9c --- /dev/null +++ b/app/views/users/search_user_course.js.erb @@ -0,0 +1,18 @@ +//var screenWidth = $(window).width(); +//var screenHeight = $(window).height(); //当前浏览器窗口的 宽高 +//var scrolltop = $(document).scrollTop();//获取当前窗口距离页面顶部高度 +//var objLeft = (screenWidth - 2)/2.5 ; //2 可以根据需要修改 +//var objTop = (screenHeight - 100)/2 + scrolltop; //100可以根据需要修改 +//var popupHeight = $(".resourceSharePopup").outerHeight(true); +//$(".resourceSharePopup").css("marginTop",-popupHeight/2); +// +//$("#upload_box").css('left','').css('top',''); +//$("#upload_box").html('<%#= escape_javascript( render :partial => "resource_share_popup" ,:locals => {:courses=>@course,:user=>@user,:send_id=>@send_id,:send_ids=>@send_ids})%>'); +//$("#upload_box").css('display','block'); +$("#ajax-modal").html('<%= escape_javascript( render :partial => 'resource_share_popup' ,:locals => {:courses=>@course,:user=>@user,:send_id=>@send_id,:send_ids=>@send_ids})%>'); +showModal('ajax-modal', '452px'); +$('#ajax-modal').siblings().remove(); +$('#ajax-modal').before(""); +$('#ajax-modal').parent().css("top","").css("left",""); +$('#ajax-modal').parent().addClass("popbox").addClass("resourceUploadPopup"); +$('#ajax-modal').css("padding-left","16px").css("padding-bottom","16px"); \ No newline at end of file diff --git a/app/views/users/search_user_project.js.erb b/app/views/users/search_user_project.js.erb new file mode 100644 index 000000000..26a0f265c --- /dev/null +++ b/app/views/users/search_user_project.js.erb @@ -0,0 +1,14 @@ + +//var popupHeight = $(".resourceSharePopup").outerHeight(true); +//$(".resourceSharePopup").css("marginTop",-popupHeight/2); +// +//$("#upload_box").css('left','').css('top',''); +//$("#upload_box").html('<%#= escape_javascript( render :partial => "resource_share_for_project_popup" ,:locals => {:projects=>@projects,:user=>@user,:send_id=>@send_id,:send_ids=>@send_ids})%>'); +//$("#upload_box").css('display','block'); +$("#ajax-modal").html('<%= escape_javascript( render :partial => 'resource_share_for_project_popup' ,:locals => {:projects=>@projects,:user=>@user,:send_id=>@send_id,:send_ids=>@send_ids})%>'); +showModal('ajax-modal', '452px'); +$('#ajax-modal').siblings().remove(); +$('#ajax-modal').before(""); +$('#ajax-modal').parent().css("top","").css("left",""); +$('#ajax-modal').parent().addClass("resourceUploadPopup").addClass("popbox") +$('#ajax-modal').css("padding-left","16px").css("padding-bottom","16px"); diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb index e53d734c6..de166b4e7 100644 --- a/app/views/users/show.html.erb +++ b/app/views/users/show.html.erb @@ -1,40 +1,41 @@ -<%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg',"user" %> -<% @center_flag = (User.current == @user) %> -
    - - <% if @user.allowed_to?(:add_project, nil, :global => true) %> - 新建项目 - <% else %> - 加入项目 - <% end %> - - <% if @user.user_extensions.identity == 0 && @user.allowed_to?(:add_course, nil, :global => true) %> - 新建课程 - <% else %> - - 加入课程 - <% end %> -
    + +
    +
    最新动态
    +
      +
    • +
        +
      • +
          +
        • 课程动态
        • +
        • <%= link_to "作业动态", {:controller => "users", :action => "show", :type => "course_homework"}, :class => "homepagePostTypeAssignment postTypeGrey"%> +
        • +
        • <%= link_to "通知动态", {:controller => "users", :action => "show", :type => "course_news"}, :class => "homepagePostTypeNotice postTypeGrey"%> + +
        • <%= link_to "论坛动态", {:controller => "users", :action => "show", :type => "course_message"}, :class => "homepagePostTypeForum postTypeGrey"%> +
        • <%= link_to "问卷动态", {:controller => "users", :action => "show", :type => "course_poll"}, :class => "homepagePostTypeQuiz postTypeGrey"%> + + +
        +
      • +
      • +
          +
        • 项目动态
        • +
        • <%= link_to "问题动态", {:controller => "users", :action => "show", :type => "project_issue"}, :class => "homepagePostTypeQuestion postTypeGrey"%> +
        • <%= link_to "论坛动态", {:controller => "users", :action => "show", :type => "project_message"}, :class => "homepagePostTypeForum postTypeGrey"%> + +
        +
      • +
      • +
          +
        • 更多
        • +
        • <%= link_to "我的动态", {:controller => "users", :action => "show", :type => "current_user"}, :class =>"homepagePostTypeMine postTypeGrey"%> +
        • <%= link_to "全部动态", {:controller => "users", :action => "show", :type => nil}, :class =>"homepagePostTypeAll postTypeGrey"%> +
        +
      • +
      +
    • +
    -
    - - - - - -
    +<%= render :partial => 'users/user_activities', :locals => {:user_activities => @user_activities,:page => 0,:type => @type} %> diff --git a/app/views/users/show.js.erb b/app/views/users/show.js.erb new file mode 100644 index 000000000..eb5de9c6a --- /dev/null +++ b/app/views/users/show.js.erb @@ -0,0 +1,2 @@ +$("#show_more_activities").replaceWith("<%= escape_javascript( render :partial => 'users/user_activities',:locals => {:user_activities => @user_activities, :page => @page,:type => @type} )%>"); + diff --git a/app/views/users/show_new_score.js.erb b/app/views/users/show_new_score.js.erb index 40ef7d5c5..51f430fa9 100644 --- a/app/views/users/show_new_score.js.erb +++ b/app/views/users/show_new_score.js.erb @@ -1,4 +1,9 @@ $('#ajax-modal').html('<%= escape_javascript(render :partial => 'users/show_new_score') %>'); showModal('ajax-modal', '400px'); -$('#ajax-modal').siblings().show(); -$('#ajax-modal').addClass('new-watcher'); +$('#ajax-modal').css('height','auto'); +$('#ajax-modal').siblings().remove(); +$('#ajax-modal').before("" + +""); +//$('#ajax-modal').parent().removeClass("alert_praise"); +$('#ajax-modal').parent().css("top","30%").css("left","35%"); +$('#ajax-modal').parent().addClass("alert_box"); diff --git a/app/views/users/user_commit_homework.html.erb b/app/views/users/user_commit_homework.html.erb new file mode 100644 index 000000000..a7416cf40 --- /dev/null +++ b/app/views/users/user_commit_homework.html.erb @@ -0,0 +1,114 @@ + + + + + + +
    +
    +
    +
    提交作品
    +
    +
    +
    +
    <%= @homework.name %>
    截止时间:<%= @homework.end_time %> +
    + <%= @homework.user.show_name %> +

    <%= @homework.description %>
    +输入 2 1 1 4 4 2 3 6 5
    +输出 15
    +

    +
    +

    注:迟交扣2分,缺评一个作品扣2

    +
    +
    + <%= form_for(@student_work, + :html => { :multipart => true }, + :url => {:controller => 'student_work', + :action => 'create', + :student_work_id => @student_work.id, + :homework => @homework.id + }, + :method => :post) do |f|%> + +
    + 请使用 <%= @homework.language_name %> 语言编写 +
    +
    + <%= f.text_area :name, id: 'program-title', class:"InputBox W700", placeholder:"请概括你的代码的功能" %> +
    +
    + <%= f.text_area :description, id: 'program-src', class:" W700 H150", placeholder:"请贴入你的代码", rows: 10 %> +
    + + <% end %> +
    +
    +
    + <% @student_work.student_work_tests.each_with_index do |test, index| %> +
    +

    第<%= @student_work.student_work_tests.count - index%>次测试

    <%= test.created_at.to_s(:db) %> +
    +
    + <% if test.status.to_i == -2 %> +
    <%= test.results.first %>
    + <% else %> +
    +
      + <% test.results.each_with_index do |x, i| %> +
    • 测试<%=i+1%> + <% if x["status"].to_i != 0 %> + 测试错误! + 您的输出: + <%=x["result"]%> + 正确输出: + <%=x["output"]%> +
      +
    • + <% else %> + 测试正确! +
      + + <% end %> + <% end %> +
    +
    + <% end %> + <% end %> +
    +
    \ No newline at end of file diff --git a/app/views/users/user_course_activities.html.erb b/app/views/users/user_course_activities.html.erb index bdebee6a5..ed5b66ed4 100644 --- a/app/views/users/user_course_activities.html.erb +++ b/app/views/users/user_course_activities.html.erb @@ -10,10 +10,19 @@ <%= rec[:item].user.show_name %> <%= get_activity_opt(rec[:item],rec[:e]) %> - - <%= get_activity_act_showname_htmlclear(rec[:item]) %> - + <% if(( rec[:e].is_public == false || rec[:e].is_public == 0 )&& !rec[:e].visible?)%> + + <%= get_activity_act_showname_htmlclear(rec[:item]) %> + + <% else %> + + <%= get_activity_act_showname_htmlclear(rec[:item]) %> + + <% end %> + <%= time_tag(get_activity_act_createtime(rec[:item])).html_safe %>
    <% end %> \ No newline at end of file diff --git a/app/views/users/user_courses4show.html.erb b/app/views/users/user_courses4show.html.erb deleted file mode 100644 index 7aab1b2a5..000000000 --- a/app/views/users/user_courses4show.html.erb +++ /dev/null @@ -1,16 +0,0 @@ -<% for item in @list %> - - -<% end %> diff --git a/app/views/users/user_courses4show.js.erb b/app/views/users/user_courses4show.js.erb new file mode 100644 index 000000000..12696e232 --- /dev/null +++ b/app/views/users/user_courses4show.js.erb @@ -0,0 +1 @@ +$("#user_show_more_course").replaceWith("<%= escape_javascript( render :partial => 'layouts/user_courses',:locals => {:courses => @courses,:user => @user, :page => @page} )%>"); diff --git a/app/views/users/user_fanslist.html.erb b/app/views/users/user_fanslist.html.erb index 0b42da9f8..63b03e5dd 100644 --- a/app/views/users/user_fanslist.html.erb +++ b/app/views/users/user_fanslist.html.erb @@ -1,25 +1,35 @@ -
    -
    + + +
    <% if @action == 'fans' %>

    粉丝

    -
    共有<%=@obj_count%>名粉丝
    +
    共有<%=@obj_count%>名粉丝
    <% elsif @action == 'visitor' %>

    访客

    共有<%=@obj_count%>访客
    <% else %>

    关注

    -
    一共关注<%=@obj_count%>
    +
    一共关注<%=@obj_count%>
    <% end %>
    - <% for item in @list %> - <%= render :partial => 'users/user_fans_item', :locals => {:item => item,:target=>@user} %> - <% end %> +
    + <%# for item in @list %> + <%= render :partial => 'users/user_fans_item', :locals => {:list => @list,:target=>@user,:action_name=>@action,:page=>params[:page]} %> + <%# end %> +

    <%= l(:label_no_data) %>

      <%= pagination_links_full @obj_pages, @obj_count, :per_page_links => false, :remote => false, :flag => true%>
    -
    + diff --git a/app/views/users/user_homeworks.html.erb b/app/views/users/user_homeworks.html.erb index 74560909d..7b212101c 100644 --- a/app/views/users/user_homeworks.html.erb +++ b/app/views/users/user_homeworks.html.erb @@ -1,9 +1,29 @@ -u - - <% if @user.user_extensions.identity == 0 %> - <%= render :partial => 'my_create_homework' %> - <% else %> - <%= render :partial => 'my_homework' %> - <% end %> + +
    +
    作业
    +
    +
    +<% if @is_teacher%> + +
    + <% homework = HomeworkCommon.new %> + <% homework.homework_detail_manual = HomeworkDetailManual.new%> + <%= labelled_form_for homework,:url => user_new_homework_users_path,:method => "post" do |f| %> +
    + <%= render :partial => 'users/user_homework_form', :locals => { :homework => homework,:f => f,:edit_mode => false } %> +
    + <% end%> +
    +<% end%> +<%= render :partial => 'users/user_homework_list', :locals => {:homework_commons => @homework_commons,:page => 0,:is_in_course => 0} %> diff --git a/app/views/users/user_homeworks.js.erb b/app/views/users/user_homeworks.js.erb new file mode 100644 index 000000000..cc1bc051a --- /dev/null +++ b/app/views/users/user_homeworks.js.erb @@ -0,0 +1,2 @@ +$("#user_show_more_homework").replaceWith("<%= escape_javascript( render :partial => 'users/user_homework_list',:locals => {:homework_commons => @homework_commons, :page => @page,:is_in_course => 0} )%>"); + diff --git a/app/views/users/user_import_homeworks.js.erb b/app/views/users/user_import_homeworks.js.erb new file mode 100644 index 000000000..d00886b1c --- /dev/null +++ b/app/views/users/user_import_homeworks.js.erb @@ -0,0 +1,7 @@ +$('#ajax-modal').html('<%= escape_javascript(render :partial => 'users/show_user_homeworks') %>'); +showModal('ajax-modal', '580px'); +$('#ajax-modal').css('height','300px').css("width","580px"); +$('#ajax-modal').siblings().remove(); +$('#ajax-modal').before("" + +""); +$('#ajax-modal').parent().css("top","20%").css("left","25%").css("position","fixed"); diff --git a/app/views/users/user_import_resource.js.erb b/app/views/users/user_import_resource.js.erb new file mode 100644 index 000000000..0e35acd95 --- /dev/null +++ b/app/views/users/user_import_resource.js.erb @@ -0,0 +1,8 @@ +$('#ajax-modal').html('<%= escape_javascript(render :partial => 'users/show_user_resource',:locals => {:user => @user,:homework_id=>@homework_id}) %>'); +showModal('ajax-modal', '730px'); +$('#ajax-modal').css('height','500px').css("width","730px"); +$('#ajax-modal').siblings().remove(); +$('#ajax-modal').before("
    " + +"
    "); +$('#ajax-modal').parent().css("top","30%").css("left","").css("position","fixed"); +$('#ajax-modal').parent().addClass("popbox").addClass("referenceResourcesPopup"); \ No newline at end of file diff --git a/app/views/users/user_messages.html.erb b/app/views/users/user_messages.html.erb new file mode 100644 index 000000000..d0f7bb9bb --- /dev/null +++ b/app/views/users/user_messages.html.erb @@ -0,0 +1,115 @@ +
    +
    <%= title_for_message(params[:type]) %>
    +
      +
    • +
        +
      • +
          +
        • <%= link_to "全部",user_message_path(User.current), :class => "resourcesGrey" %>
        • +
        • <%= link_to "未读消息", user_message_path(User.current, :type => 'unviewed'), :class => "resourcesGrey" %>
        • +
        • <%= link_to "系统消息", user_system_messages_path(User.current), :class => "resourcesGrey" %>
        • + +
        • <%= link_to "作业消息", user_message_path(User.current, :type => 'homework'), :class => "resourcesGrey" %>
        • +
        • <%= link_to "课程讨论",user_message_path(User.current, :type => 'course_message'), :class => "resourcesGrey" %>
        • +
        • <%= link_to "课程通知",user_message_path(User.current, :type => 'course_news'), :class => "resourcesGrey" %>
        • +
        • <%= link_to "课程问卷", user_message_path(User.current, :type => 'poll'), :class => "resourcesGrey" %>
        • +
        +
      • + +
      • +
          +
        • <%= link_to "项目任务", user_message_path(User.current, :type => 'issue'), :class => "resourcesGrey" %>
        • +
        • <%= link_to "项目讨论", user_message_path(User.current, :type => 'forge_message'), :class => "resourcesGrey" %>
        • +
        • <%= link_to "项目新闻", user_message_path(User.current, :type => 'forge_news'), :class => "resourcesGrey" %>
        • +
        • <%= link_to "用户申请", user_message_path(User.current, :type => 'apply'), :class => "resourcesGrey" %>
        • + +
        • <%= link_to "贴吧帖子", user_message_path(User.current, :type => 'forum'), :class => "resourcesGrey" %>
        • + <%# 系统贴吧 %> +
        • <%= link_to "用户留言",user_message_path(User.current, :type => 'user_feedback'), :class => "resourcesGrey" %>
        • +
        +
      • +
      +
    • +
    +
    +
    +
    + <% if (!@message_alls.nil? && @message_alls.count >0) %> + <% if params[:type].nil? || params[:type] == "unviewed" %> +
    + 有 <%= unviewed_message(@user) %> 条未读 + <% unless (unviewed_message(@user) == 0 || User.current != @user) %> + <%= link_to "全部设为已读", user_message_path(User.current, :viewed => 'all') %> + <% end %> +
    + <% end %> + + + <% unless @message_alls.nil? %> + <% @message_alls.each do |ma| %> + <%# 系统消息 %> + <%= render :partial => 'users/user_message_system', :locals => {:ma => ma} %> + + <%# 课程消息 %> + <%= render :partial => 'users/user_message_course', :locals => {:ma => ma} %> + + + <%= render :partial => 'users/user_message_forge', :locals => {:ma => ma} %> + + + <%= render :partial => 'users/user_message_forum', :locals => {:ma => ma} %> + + + <%= render :partial => 'users/user_message_userfeedaback', :locals => {:ma => ma} %> + + <% end %> +
      + <%= pagination_links_full @obj_pages, @obj_count, :per_page_links => false, :remote => false, :flag => true%> +
    + <% end %> + + <% else %> +
    您目前还没有相关消息!
    + <% end %> +
    +
    +
    + + + + + + + + + + + + diff --git a/app/views/users/user_newfeedback.html.erb b/app/views/users/user_newfeedback.html.erb index a8107ce5f..b94e33b16 100644 --- a/app/views/users/user_newfeedback.html.erb +++ b/app/views/users/user_newfeedback.html.erb @@ -1,29 +1,35 @@ -
    - - <% if @user.user_extensions.identity == 0 && @user.allowed_to?(:add_course, nil, :global => true) %> - 新建课程 - <% end %> +<%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg',"init_KindEditor","user" %> + +
    +
    +
    留言
    +
    +
    -
    -<%= javascript_include_tag "/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg',"user" %> -
    - - - -
    +
    <%= form_for('new_form',:url => leave_user_message_path(@user.id),:method => "post") do |f|%> - +

    - 取消 - 留言 + 取消 + 留言 <% end%>
    -
    +
    <%if @jour%> <% @jour.each do |jour|%> <%= render :partial => 'user_jours_new', :locals => {:jour => jour} %> diff --git a/app/views/users/user_projects4show.html.erb b/app/views/users/user_projects4show.html.erb deleted file mode 100644 index 3c709bd5d..000000000 --- a/app/views/users/user_projects4show.html.erb +++ /dev/null @@ -1,16 +0,0 @@ -<% for item in @list %> - -<% end %> diff --git a/app/views/users/user_projects4show.js.erb b/app/views/users/user_projects4show.js.erb new file mode 100644 index 000000000..c19a79c81 --- /dev/null +++ b/app/views/users/user_projects4show.js.erb @@ -0,0 +1 @@ +$("#user_show_more_project").replaceWith("<%= escape_javascript( render :partial => 'layouts/user_projects',:locals => {:projects => @projects,:user => @user, :page => @page} )%>"); diff --git a/app/views/users/user_ref_resource_search.js.erb b/app/views/users/user_ref_resource_search.js.erb new file mode 100644 index 000000000..52f54bee4 --- /dev/null +++ b/app/views/users/user_ref_resource_search.js.erb @@ -0,0 +1,2 @@ +$("#user_ref_resources").html('<%= escape_javascript(render :partial => 'resources_list',:locals=>{:attachments => @attachments})%>'); +$("#resource_ref_pages").html('<%= pagination_links_full @atta_pages, @atta_count, :per_page_links => false, :remote => @is_remote, :flag => true %>'); \ No newline at end of file diff --git a/app/views/users/user_resource.html.erb b/app/views/users/user_resource.html.erb new file mode 100644 index 000000000..f6bb3c8cb --- /dev/null +++ b/app/views/users/user_resource.html.erb @@ -0,0 +1,529 @@ + +<%= javascript_include_tag 'bootstrap'%> +<%= stylesheet_link_tag 'project' %> +<%= stylesheet_link_tag 'leftside' %> +<%= javascript_include_tag 'attachments'%> + + + + + + +
    +
    资源库
    +
      +
    • +
        +
      • + <%= link_to '全部' ,user_resource_user_path(:id=>@user.id,:type=>1),:remote=>true,:method => 'get',:class=>'resourcesTypeAll resourcesGrey' %> +
      • +
      • + <%= link_to '课程资源' ,user_resource_user_path(:id=>@user.id,:type=>2),:remote=>true,:method => 'get',:class=>'homepagePostTypeAssignment postTypeGrey' %> +
      • +
      • + <%= link_to '项目资源' ,user_resource_user_path(:id=>@user.id,:type=>3),:remote=>true,:method => 'get',:class=>'homepagePostTypeQuiz postTypeGrey' %> +
      • +
      • + <%= link_to '用户资源' ,user_resource_user_path(:id=>@user.id,:type=>5),:remote=>true,:method => 'get',:class=>'resourcesTypeUser resourcesGrey' %> +
      • +
      • + <%= link_to '附件' ,user_resource_user_path(:id=>@user.id,:type=>4),:remote=>true,:method => 'get',:class=>'resourcesTypeAtt resourcesGrey' %> +
      • +
      +
    • +
    +
    + +
    +
    + +
    + <%= render :partial => 'resource_search_form',:locals => {:user=>@user,:type=>@type} %> +
    +
    为您找到<%= @atta_count%>个资源
    +
    +
    +
      +
    • +
    • 资源名称
    • +
    • 大小
    • +
    • 类别
    • +
    • 上传者
    • +
    • 上传时间
    • +
    +
    +
    +
    + + <%= render :partial => 'resources_list' ,:locals=>{ :attachments => @attachments} %> + +
    +
    +
    + +
    + 全选 + 删除 +
    +
    选择 0 个资源
    +
    + 发送 +
    +
    +
    +
    +
    +
    +
      + <%= pagination_links_full @atta_pages, @atta_count, :per_page_links => false, :remote => @is_remote, :flag => true%> +
    +
    +
    + +
    + + + + + + + diff --git a/app/views/users/user_resource.js.erb b/app/views/users/user_resource.js.erb new file mode 100644 index 000000000..bb195d4bf --- /dev/null +++ b/app/views/users/user_resource.js.erb @@ -0,0 +1,6 @@ +$("#search_div").html('<%= escape_javascript( render :partial => 'resource_search_form',:locals => {:user=>@user,:type=>@type} ) %>'); +$("#resources_list").html('<%= escape_javascript( render :partial => 'resources_list' ,:locals=>{ :attachments => @attachments})%>'); +$("#pages").html('<%= pagination_links_full @atta_pages, @atta_count, :per_page_links => false, :remote => @is_remote, :flag => true %>'); +$("#res_count").html(0); +$("#checkboxAll").attr('checked',false); +$("#res_all_count").html(<%= @atta_count%>); \ No newline at end of file diff --git a/app/views/users/user_resource_create.js.erb b/app/views/users/user_resource_create.js.erb new file mode 100644 index 000000000..2d6c4f4d8 --- /dev/null +++ b/app/views/users/user_resource_create.js.erb @@ -0,0 +1,7 @@ + +closeModal(); +$("#resources_list").html('<%= escape_javascript( render :partial => 'resources_list' ,:locals=>{ :attachments => @attachments})%>'); +//这里不能将翻页的更新 +$("#res_all_count").html(parseInt($("#res_all_count").html())+1); +$("#res_count").html(0); +$("#checkboxAll").attr('checked',false); \ No newline at end of file diff --git a/app/views/users/user_resource_delete.js.erb b/app/views/users/user_resource_delete.js.erb new file mode 100644 index 000000000..a956ed212 --- /dev/null +++ b/app/views/users/user_resource_delete.js.erb @@ -0,0 +1,2 @@ +$("#resources_list").html('<%= escape_javascript( render :partial => 'resources_list' ,:locals=>{ :attachments => @attachments})%>'); +$("#pages").html('<%= pagination_links_full @atta_pages, @atta_count, :per_page_links => false, :remote => @is_remote, :flag => true %>'); \ No newline at end of file diff --git a/app/views/users/user_resource_type.js.erb b/app/views/users/user_resource_type.js.erb new file mode 100644 index 000000000..52f54bee4 --- /dev/null +++ b/app/views/users/user_resource_type.js.erb @@ -0,0 +1,2 @@ +$("#user_ref_resources").html('<%= escape_javascript(render :partial => 'resources_list',:locals=>{:attachments => @attachments})%>'); +$("#resource_ref_pages").html('<%= pagination_links_full @atta_pages, @atta_count, :per_page_links => false, :remote => @is_remote, :flag => true %>'); \ No newline at end of file diff --git a/app/views/users/user_search_homeworks.js.erb b/app/views/users/user_search_homeworks.js.erb new file mode 100644 index 000000000..760d4fdf1 --- /dev/null +++ b/app/views/users/user_search_homeworks.js.erb @@ -0,0 +1 @@ +$("#homework_list_form_show").html("<%= escape_javascript(render :partial => 'users/show_user_homework_form', :locals => {:user_homeworks => @user_homeworks})%>"); \ No newline at end of file diff --git a/app/views/users/user_select_homework.js.erb b/app/views/users/user_select_homework.js.erb new file mode 100644 index 000000000..1d9cc8d70 --- /dev/null +++ b/app/views/users/user_select_homework.js.erb @@ -0,0 +1,13 @@ +//$("#HomeWorkCon").replaceWith("<%#= escape_javascript(render :partial => 'users/user_homework_form', :locals => { :homework => @homework,:edit_mode => true })%>"); +hideModal('#coursesChoosePopup'); +$("#homework_name").val("<%= @homework.name%>"); +$("#homework_end_time").val("<%= @homework.end_time%>"); +<% if @select_course == "0"%> + $("#course_id").val("<%= @homework.course_id%>"); +<% end%> +$("#homework_attachments").html("<%= escape_javascript(render :partial => 'users/user_homework_attachment', :locals => { :container => @homework,:has_program => true })%>"); +homework_description_editor.html("<%= escape_javascript(@homework.description.html_safe)%>"); +$("#BluePopupBox").html("<%=escape_javascript( render :partial => 'users/user_programing_attr', :locals => {:edit_mode => true, :homework => @homework})%>"); +//$("input[name='homework_type']").val("<%#= @homework.homework_type%>"); +$("#homework_editor").show(); +$("#BluePopupBox a.BlueCirBtn").click(); diff --git a/app/views/users/user_system_messages.html.erb b/app/views/users/user_system_messages.html.erb new file mode 100644 index 000000000..899cd7a8f --- /dev/null +++ b/app/views/users/user_system_messages.html.erb @@ -0,0 +1,60 @@ +
    +
    系统消息
    +
      +
    • +
        +
      • <%= link_to "全部",user_message_path(User.current), :class => "resourcesGrey" %>
      • +
      • <%= link_to "未读消息", user_message_path(User.current, :type => 'unviewed'), :class => "resourcesGrey" %>
      • +
      • <%= link_to "用户申请", user_message_path(User.current, :type => 'apply'), :class => "resourcesGrey" %>
      • + <%# 课程相关消息 %> +
      • <%= link_to "作业消息", user_message_path(User.current, :type => 'homework'), :class => "resourcesGrey" %>
      • +
      • <%= link_to "课程讨论",user_message_path(User.current, :type => 'course_message'), :class => "resourcesGrey" %>
      • +
      • <%= link_to "课程通知",user_message_path(User.current, :type => 'course_news'), :class => "resourcesGrey" %>
      • + + + + + <%# 项目相关消息 %> +
      • <%= link_to "项目任务", user_message_path(User.current, :type => 'issue'), :class => "resourcesGrey" %>
      • + + + + + <%# 项目相关消息 %> +
      • <%= link_to "贴吧帖子", user_message_path(User.current, :type => 'forum'), :class => "resourcesGrey" %>
      • + <%# 系统贴吧 %> +
      • <%= link_to "用户留言",user_message_path(User.current, :type => 'user_feedback'), :class => "resourcesGrey" %>
      • + <%# 系统消息 %> +
      • <%= link_to "系统消息", user_system_messages_path(User.current), :class => "resourcesGrey" %>
      • +
      +
    • +
    +
    + +<% @sytem_messages.each do |system_message| %> +
    +
    +
    + <%= image_tag("/images/logo.png", :width => "42", :height => "42",class: "mt3") %> +
    +
    +
    + Trustie平台 发布了系统消息: + <%= system_message.subject.nil? ? "系统消息" : system_message.subject %> +
    +
    +
    +

    + <%= system_message.content.nil? ? system_message.description.html_safe : system_message.content.html_safe %> +

    +
    +
    +

    截止时间:<%= format_time(system_message.created_at) %>

    +
    +
    +
    +
    +<% end %> +
      + <%= pagination_links_full @obj_pages, @obj_count, :per_page_links => false, :remote => false, :flag => true%> +
    \ No newline at end of file diff --git a/app/views/versions/_form.html.erb b/app/views/versions/_form.html.erb index f0ed7c84f..6ff8b070f 100644 --- a/app/views/versions/_form.html.erb +++ b/app/views/versions/_form.html.erb @@ -14,20 +14,20 @@ <%= f.select :status, Version::VERSION_STATUSES.collect {|s| [l("version_status_#{s}"), s]}, :label => "" %> -
  • - - <%= f.text_field :wiki_page_title, :size =>60, :label => "", :disabled => @project.wiki.nil? %> -
  • + + + +
  • <%= f.text_field :effective_date, :size => 10, :readonly => true,:class=>"fl" ,:style=>"margin-left:7px;",:label=>""%> <%= calendar_for('version_effective_date') %>
  • -
  • - - <%= f.select :sharing, @version.allowed_sharings.collect {|v| [format_version_sharing(v), v]},:label=>"" %> -
  • + + + + <% @version.custom_field_values.each do |value| %> diff --git a/app/views/versions/_overview.html.erb b/app/views/versions/_overview.html.erb index 47d65c34a..8d34a20da 100644 --- a/app/views/versions/_overview.html.erb +++ b/app/views/versions/_overview.html.erb @@ -13,5 +13,5 @@ project_issues_path(version.project, :status_id => 'o', :fixed_version_id => version, :set_filter => 1), :class =>"c_dblue") %>)

    <% else %> -

    <%= l(:label_roadmap_no_issues) %>

    +
    <%= l(:label_roadmap_no_issues) %>
    <% end %> diff --git a/app/views/versions/show.html.erb b/app/views/versions/show.html.erb index 1a7fce16d..6bfacbe86 100644 --- a/app/views/versions/show.html.erb +++ b/app/views/versions/show.html.erb @@ -4,7 +4,7 @@
    <%= link_to(l(:button_edit), edit_version_path(@version), :class => 'icon icon-edit') if User.current.allowed_to?(:manage_versions, @version.project) %> -<%= link_to_if_authorized(l(:button_edit_associated_wikipage, +<%#= link_to_if_authorized(l(:button_edit_associated_wikipage, :page_title => @version.wiki_page_title.truncate(30, omission: '...')), {:controller => 'wiki', :action => 'edit', @@ -17,7 +17,7 @@ <%= call_hook(:view_versions_show_contextual, { :version => @version, :project => @project }) %>
    -

    +

    <%= h(@version.name) %>

    @@ -27,11 +27,11 @@
    <% if @version.estimated_hours > 0 || User.current.allowed_to?(:view_time_entries, @project) %> -
    <%= l(:label_time_tracking) %> +
    <%= l(:label_time_tracking) %> ","
    -

    <%= l(:field_estimated_hours) %>:

    +

    <%= l(:field_estimated_hours) %>:

    <%= html_hours(l_hours(@version.estimated_hours)) %> @@ -40,7 +40,7 @@ <% if User.current.allowed_to?(:view_time_entries, @project) %>
    -

    <%= l(:label_spent_time) %>:

    +

    <%= l(:label_spent_time) %>:

    <%= html_hours(l_hours(@version.spent_hours)) %> diff --git a/app/views/watchers/_set_watcher.js.erb b/app/views/watchers/_set_watcher.js.erb index da794d18b..d875a38c4 100644 --- a/app/views/watchers/_set_watcher.js.erb +++ b/app/views/watchers/_set_watcher.js.erb @@ -1,57 +1,21 @@ <% if( params[:object_type] == 'user') %> + //点击头像下面的添加关注按钮 <% if( params[:target_id] == params[:object_id] ) %> - <% target = User.find_by_id(params[:target_id]) %> - //btn - var btn_html = "<%= escape_javascript( render( :partial => 'layouts/user_watch_btn', :locals => {:target => target} ) )%>"; - $('#user_watch_id').replaceWith(btn_html); - //count - $("*[nh_name='fans_count']").html("<%= target.watcher_users.count.to_s %>"); - //left list - var list_left_html = "<%= escape_javascript( render( :partial => 'layouts/user_fans_list', :locals => {:user => target} ) )%>"; - $('#fans_nav_list').replaceWith(list_left_html); - //list - if( $("#nh_fans_list") != undefined && $("#nh_fans_list").length != 0 ){ - <% if( opt == 'add') %> - var list_html = "<%= escape_javascript( render( :partial => 'users/user_fans_item', :locals => {:item=>User.current,:target => target} ) )%>"; - $("#nh_fans_list").after(list_html); - $("#nodata").hide(); - <% else %> - $("#fans_item_<%= User.current.id %>",$("#nh_fans_list").parent('div')).remove(); - if( $('>div',$("#nh_fans_list").parent('div')).length == 1 ){ - $("#nodata").show(); - } - <% end %> - } - + $("#watch_user_btn_div").html("<%= escape_javascript render(:partial => "layouts/user_watch_btn", :locals => {:target => watched.first}) %>"); + $("#user_fans_number").html("<%= watched.first.watcher_users.count.to_s%>"); + //在当前用户的粉丝、关注页面 <% elsif( params[:target_id] == User.current.id.to_s )%> - <% target = User.find_by_id(params[:target_id]) %> - <% item = User.find_by_id(params[:object_id]) %> - //count - $("*[nh_name='watcher_count']").html("<%= User.watched_by(target.id).count.to_s %>"); - //left list - var list_left_html = "<%= escape_javascript( render( :partial => 'layouts/user_watch_list', :locals => {:user => target} ) )%>"; - $('#watcher_nav_list').replaceWith(list_left_html); - //list - if( $("#nh_wacth_list") != undefined && $("#nh_wacth_list").length != 0 ){ - <% if( opt == 'delete') %> - $("#fans_item_<%= item.id %>",$("#nh_wacth_list").parent('div')).remove(); - if( $('>div',$("#nh_wacth_list").parent('div')).length == 1 ){ - $("#nodata").show(); - } - <% end %> - }else if($("#nh_fans_list") != undefined && $("#nh_fans_list").length != 0){ - var list_html = "<%= escape_javascript( render( :partial => 'users/user_fans_item', :locals => {:item=>item,:target => target} ) )%>"; - $('#fans_item_<%= item.id %>').replaceWith(list_html); - } - + $("#users_list").html("<%= escape_javascript (render :partial => 'users/user_fans_item', :locals => {:list => list,:target=>User.current,:action_name=>action_name,:page=>params[:page]}) %>"); + $("#watch_user_number_div").html('<%= escape_javascript ( link_to User.watched_by(params[:target_id]).count.to_s, {:controller=>"users", :action=>"user_watchlist",:id=>params[:target_id]},:class=>"homepageImageNumber") %>'); + $("#fans_user_number_div").html('<%= escape_javascript ( link_to User.find(params[:target_id]).watcher_users.count.to_s, {:controller=>"users", :action=>"user_fanslist",:id=>params[:target_id]},:class=>"homepageImageNumber", :id => "user_fans_number") %>'); + $("#fans_span").html('<%= count %>'); + $("#watch_span").html('<%= count %>'); + //在其他用户的粉丝、关注页面 <% else %> - <% target = User.find_by_id(params[:target_id]) %> - <% item = User.find_by_id(params[:object_id]) %> - //list - var list_html = "<%= escape_javascript( render( :partial => 'users/user_fans_item', :locals => {:item=>item,:target => target} ) )%>"; - $('#fans_item_<%= item.id %>').replaceWith(list_html); +$("#users_list").html("<%= escape_javascript (render :partial => 'users/user_fans_item', :locals => {:list => list,:target=>User.find(params[:target_id]),:action_name=>action_name,:page=>params[:page]}) %>"); +//在他人的用户分析下关注,不会改变他人的关注数,所以不必要刷新 + //$("#watch_user_number").html('<%#= escape_javascript ( link_to User.watched_by(params[:target_id]).count.to_s, {:controller=>"users", :action=>"user_watchlist",:id=>params[:target_id]},:class=>"homepageImageNumber") %>'); <% end %> - <% else %> <% selector = ".#{watcher_css(watched)}" %> diff --git a/app/views/welcome/_link_to_another.html.erb b/app/views/welcome/_link_to_another.html.erb index 6540409d1..b5940a113 100644 --- a/app/views/welcome/_link_to_another.html.erb +++ b/app/views/welcome/_link_to_another.html.erb @@ -1,5 +1,6 @@ <%hidden_non_project = Setting.find_by_name("hidden_non_project") - visiable = hidden_non_project && hidden_non_project.value == "0"%> + visiable = true #hidden_non_project && hidden_non_project.value == "0" +%> <% unless visiable%>
    <%=l(:label_projects_management_platform)%> diff --git a/app/views/words/create_reply.js.erb b/app/views/words/create_reply.js.erb index 6aad1bfb5..d91ce08ce 100644 --- a/app/views/words/create_reply.js.erb +++ b/app/views/words/create_reply.js.erb @@ -1,27 +1,30 @@ <% if @save_succ %> - <% if !@jfm.nil? && @jfm.jour_type == 'Principal' %> - $("#<%= @jfm.m_parent_id%>").children("div[nhname='reply_list']").prepend("<%= escape_javascript( render(:partial => 'users/user_jour_reply',:locals => {:reply=>@jfm} )) %>"); - div_1 = $("#<%= @jfm.m_reply_id%>").children("div[nhname='div_form']"); - div_1.hide(); - div_2 = $("#<%= @jfm.m_reply_id%>").children("div[nhname='sub_div_form']"); - div_2.hide(); - <% else %> - - var pre_append = $('<%= j( - render :partial => "words/journal_reply_items", - :locals => {:reply => @jfm, :journal => @jfm.parent, :m_reply_id => @jfm,:show_name => @show_name} - ) %>').hide(); - $('#journal_reply_ul_<%=@jfm.m_parent_id%>').append(pre_append); - pre_append.fadeIn(600); - var textarea = $('#project_respond_form_<%=@jfm.m_reply_id.to_s%> textarea'); - textarea.val(''); - $('#project_respond_form_<%=@jfm.m_reply_id.to_s%>').hide(); - var textarea1 = $('#course_respond_form_<%=@jfm.m_reply_id.to_s%> textarea'); - textarea1.val(''); - $('#course_respond_form_<%=@jfm.m_reply_id.to_s%>').hide(); - setMaxLengthItem(pre_append.find('textarea')[0]); - <% end %> - + <% if @user_activity_id %> + $("#user_activity_<%= @user_activity_id%>").replaceWith("<%= escape_javascript(render :partial => 'users/course_journalsformessage', :locals => {:activity => @activity,:user_activity_id =>@user_activity_id}) %>"); + init_activity_KindEditor_data('<%= @user_activity_id%>', "", "87%"); + <% else %> + <% if !@jfm.nil? && @jfm.jour_type == 'Principal' %> + $("#<%= @jfm.m_parent_id%>").children("div[nhname='reply_list']").prepend("<%= escape_javascript( render(:partial => 'users/user_jour_reply',:locals => {:reply=>@jfm} )) %>"); + div_1 = $("#<%= @jfm.m_reply_id%>").children("div[nhname='div_form']"); + div_1.hide(); + div_2 = $("#<%= @jfm.m_reply_id%>").children("div[nhname='sub_div_form']"); + div_2.hide(); + <% else %> + var pre_append = $('<%= j( + render :partial => "words/journal_reply_items", + :locals => {:reply => @jfm, :journal => @jfm.parent, :m_reply_id => @jfm,:show_name => @show_name} + ) %>').hide(); + $('#journal_reply_ul_<%=@jfm.m_parent_id%>').append(pre_append); + pre_append.fadeIn(600); + var textarea = $('#project_respond_form_<%=@jfm.m_reply_id.to_s%> textarea'); + textarea.val(''); + $('#project_respond_form_<%=@jfm.m_reply_id.to_s%>').hide(); + var textarea1 = $('#course_respond_form_<%=@jfm.m_reply_id.to_s%> textarea'); + textarea1.val(''); + $('#course_respond_form_<%=@jfm.m_reply_id.to_s%>').hide(); + setMaxLengthItem(pre_append.find('textarea')[0]); + <% end %> + <% end %> <% else %> - alert("<%= l(:label_feedback_fail) %>"); + alert("<%= l(:label_feedback_fail) %>"); <% end %> \ No newline at end of file diff --git a/config/configuration.yml b/config/configuration.yml index 390754a87..ef39f6493 100644 --- a/config/configuration.yml +++ b/config/configuration.yml @@ -197,11 +197,17 @@ default: #max_concurrent_ajax_uploads: 2 #pic_types: "bmp,jpeg,jpg,png,gif" + repository_root_path: '/tmp/htdocs' + judge_server: 'http://judge.trustie.net/' + # specific configuration options for production environment # that overrides the default ones production: - cookie_domain: ".trustie.net" + # CJK support rmagick_font_path: /usr/share/fonts/ipa-mincho/ipam.ttf + judge_server: 'http://192.168.80.21:8080/' + repository_root_path: '/home/pdl/redmine-2.3.2-0/apache2/htdocs' + cookie_domain: ".trustie.net" email_delivery: delivery_method: :smtp smtp_settings: diff --git a/config/locales/account/zh.yml b/config/locales/account/zh.yml index 69edc7aa3..c7c76707d 100644 --- a/config/locales/account/zh.yml +++ b/config/locales/account/zh.yml @@ -37,7 +37,7 @@ zh: label_password_lost: "忘记密码?" button_login: 登录 # account_controller中判断用户名或密码输入有误的提示信息 - notice_account_invalid_creditentials: "无效的用户名或密码" + notice_account_invalid_creditentials: "无效的用户名或密码,注意登录名区分大小写,谢谢!" # account_controller中判断未激活的提示信息 notice_account_invalid_creditentials_new: "您还未到邮箱激活。如果您丢失帐户,电子邮件验证帮助我们的支持团队验证帐户的所有权,并允许您接收所有您要求的通知。" diff --git a/config/locales/admins/en.yml b/config/locales/admins/en.yml index 479d2f0f0..ed23107cb 100644 --- a/config/locales/admins/en.yml +++ b/config/locales/admins/en.yml @@ -11,3 +11,5 @@ en: label_registration_activation_by_email: account activation by email label_registration_manual_activation: manual account activation label_registration_automatic_activation: automatic account activation + + label_system_message: system messages diff --git a/config/locales/admins/zh.yml b/config/locales/admins/zh.yml index 936b3109f..5d857efae 100644 --- a/config/locales/admins/zh.yml +++ b/config/locales/admins/zh.yml @@ -14,3 +14,7 @@ zh: label_registration_manual_activation: 手动激活帐号 label_registration_automatic_activation: 自动激活帐号 + label_system_message: 系统消息 + label_admin_message_fail: 消息内容过长! + label_content_blank_fail: 消息内容不能为空! + diff --git a/config/locales/commons/zh.yml b/config/locales/commons/zh.yml index 457d56dad..7cbb223c6 100644 --- a/config/locales/commons/zh.yml +++ b/config/locales/commons/zh.yml @@ -284,7 +284,8 @@ zh: label_tags_issue: "问题名称" label_tags_issue_description: 问题描述 - label_tags_project_name: "项目名称:" + label_tags_project_name: "项目名称:" + label_projects_new_name: "项目名称" label_tags_project_description: "项目描述" label_tags_user_mail: "用户邮箱:" diff --git a/config/locales/en.yml b/config/locales/en.yml index f532f5cbc..2071529f0 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -51,7 +51,7 @@ en: error_session_expired: "Your session has expired. Please login again." warning_attachments_not_saved: "%{count} file(s) could not be saved." - mail_subject_lost_password: "Your %{value} password" + mail_subject_lost_password: "%{value} Your password" mail_body_lost_password: 'To change your password, click on the following link:' mail_subject_register: "Your %{value} account activation" mail_body_register: 'To activate your account, click on the following link:' diff --git a/config/locales/mailers/zh.yml b/config/locales/mailers/zh.yml index 211f2e62d..1d432cbff 100644 --- a/config/locales/mailers/zh.yml +++ b/config/locales/mailers/zh.yml @@ -24,3 +24,8 @@ zh: mail_course_title_userin: "在课程" mail_course_homework_active: "中发布了作业" mail_attention: "请您关注!" + mail_homework_endtime: "作业截止时间快到了!" + mail_homework: "作业:" + mail_anonymous_comment_close: "作业匿评已经关闭!" + mail_anonymous_comment_open: "作业匿评已经开启!" + mail_anonymous_comment_failed: "作业匿评开启失败!" \ No newline at end of file diff --git a/config/locales/my/zh.yml b/config/locales/my/zh.yml index 4220aceca..25a949df4 100644 --- a/config/locales/my/zh.yml +++ b/config/locales/my/zh.yml @@ -33,7 +33,6 @@ zh: label_account_identity_studentID: 请输入学号 field_brief_introduction_my: 个人签名 - field_description: 个人简介 field_is_required: 必填 field_firstname: 名字或组织名 firstname_empty: 名字不能为空 diff --git a/config/locales/projects/en.yml b/config/locales/projects/en.yml index b142c6ca8..703e0878e 100644 --- a/config/locales/projects/en.yml +++ b/config/locales/projects/en.yml @@ -42,10 +42,10 @@ en: label_member: "Members" project_module_attachments: "Resources" - label_project_mail_attachments: Project Resources - label_project_mail_upload: had uploaded project resources + label_project_mail_attachments: "Project Resources" + label_project_mail_upload: "had uploaded project resources" - label_invite: Invitation + label_invite: "Invitation" label_invite_new_user: "Send email to invite new user" label_invite_trustie_user: "Invite the Trustie registered user" diff --git a/config/locales/projects/zh.yml b/config/locales/projects/zh.yml index e47cd476c..dbce93219 100644 --- a/config/locales/projects/zh.yml +++ b/config/locales/projects/zh.yml @@ -60,6 +60,10 @@ zh: label_friend_organization: 圈子模式 label_research_group: 研讨模式 label_development_team: 开发模式 + label_type_project: 项目类型 + label_type_des_development: 开发模式:面向小组开发,支持问题跟踪、代码托管、论坛交流等所有功能。 + label_type_des_research: 研讨模式:面向小组研究,支持任务分工、论坛交流、资源分享等。 + label_type_des_friend: 圈子模式:面向好友分享,支持论坛交流、资源分享等。 label_member: 成员 project_module_attachments: 资源 @@ -67,6 +71,13 @@ zh: label_project_mail_upload: 上传了资源 label_invite: 邀请 + + # 项目消息通知 + label_forge_message: 消息 + label_issue_message: 问题 + label_course_message: 课程消息 + label_project_message: 项目消息 + label_issue_tracking: 问题跟踪 label_release_issue: 发布问题 @@ -340,7 +351,7 @@ zh: # # 邀请 # - label_invite_new_user: "发送邮件邀请新用户" + label_invite_new_user: "邀请用户加入项目" label_invite_join: 邀请加入 label_invite_email_tips: 输入好友的邮箱地址,Trustie会自动为该好友注册平台账号! notice_registed_error: 您输入的邮箱地址为空或者该邮箱已被注册! @@ -363,7 +374,6 @@ zh: # label_project_new_description: '项目可以是软件开发项目,也可以是协作研究项目。' field_name: 名称 - field_description: 描述 field_identifier: 标识 field_enterprise_name: 组织名称 label_organization_choose: --请选择组织-- diff --git a/config/locales/zh.yml b/config/locales/zh.yml index 1018a213a..5efe4a2cc 100644 --- a/config/locales/zh.yml +++ b/config/locales/zh.yml @@ -36,6 +36,7 @@ zh: notice_create_failed: 创建失败,请先完善个人信息 notice_failed_create: 创建失败 notice_successful_update: 更新成功 + notice_successful_message: 消息创建成功! notice_successful_edit: 修改成功 notice_failed_edit: 修改失败 notice_successful_delete: 删除成功 @@ -49,7 +50,10 @@ zh: notice_not_contest_setting_authorized: 对不起,您无权配置此竞赛。 notice_not_contest_delete_authorized: 对不起,您无权删除此竞赛。 notice_not_authorized_archived_project: 要访问的项目已经归档。 + notice_not_authorized_message: 您访问的消息不存在! notice_email_sent: "邮件已发送至 %{value}" + notice_email_login_used: 无法自动为该邮箱注册新用户,该邮箱地址已经有人作为登录名使用! + notice_email_invited: 已经向该邮箱发送过邀请,正在等待对方的回复,三小时后您可以再次发送邀请! notice_email_error: "发送邮件时发生错误 (%{value})" notice_feeds_access_key_reseted: 您的RSS存取键已被重置。 notice_api_access_key_reseted: 您的API访问键已被重置。 @@ -85,7 +89,7 @@ zh: error_unable_to_connect: "无法连接 (%{value})" warning_attachments_not_saved: "%{count} 个文件保存失败" - mail_subject_lost_password: "您的 %{value} 密码" + mail_subject_lost_password: "%{value} 您的密码" mail_body_lost_password: '请点击以下链接来修改您的密码:' mail_subject_register: "%{value}帐号激活" mail_body_register: '请点击以下链接来激活您的帐号:' @@ -552,6 +556,7 @@ zh: label_registered_on: 注册于 label_overall_activity: 活动概览 label_new: 新建 + label_latest_login_user_list: 最近登录用户列表 label_logged_as: 登录为 label_environment: 环境 @@ -690,7 +695,7 @@ zh: label_sort_lowest: 置底 label_roadmap_due_in: "截止日期到 %{value}" label_roadmap_overdue: "%{value} 延期" - label_roadmap_no_issues: 该版本没有问题 + label_roadmap_no_issues: 该版本还没有对应的缺陷,可以在“发布问题”的“目标版本”中指定版本! label_user_search_type: 搜索类型 label_search_by_login: 登录名 label_search_by_name: 名字 @@ -1252,6 +1257,7 @@ zh: label_leave_message_to: 给用户 %{name}留言 label_leave_message: 留言内容 label_message: 留言板 + label_leave_message_list: 留言列表 field_add: 添加于 %{time} 之前 label_student_response: 作业答疑 # modified by bai @@ -1748,6 +1754,7 @@ zh: cancel_apply: 取消申请 apply_master: 申请成为版主 you_are_master: 您是该项目的版主 + label_notification_list: 通知 #add by linchun (竞赛相关) label_upload_softwarepackage: 上传软件包 @@ -2017,7 +2024,11 @@ zh: label_end_time: 截止时间 label_send_email: 确定发送 - label_input_email: 请输入邮箱地址 + label_input_email: 请输入邮箱地址(必填) + label_input_email_firstname: 请输入用户名字(可选) + label_input_email_lastname: 请输入用户姓氏(可选) + label_input_email_gender: 请输入用户性别 + #api end project_module_files: 资源库 @@ -2058,5 +2069,23 @@ zh: lable_unset: 未设置 label_chose_group: 请选择分班 + label_hostedz_organization: 主办单位 + label_hosted_by: 国防科学技术大学并行与分布处理国家重点实验室 + label_sponsor: 计算机科学与技术系 + label_partners: 合作单位 + label_co_organizer_NUDT: 国防科学技术大学计算机学院 + label_co_organizer_EECS: 北京大学 + label_co_organizer_BHU: 北京航空航天大学 + label_co_organizer_CAS: 中国科学院软件研究所 + label_co_organizer_InforS: 中创软件 + label_rights_reserved: Copyright 2007~2015, All Rights Riserved + label_about_us: 关于我们 + label_contact_us: 联系我们 + label_recruitment_information: 招聘信息 + label_surpport_group: 帮助中心 + #label_forums: 论坛反馈 + label_forums: 贴吧交流 + label_language: 语言 + label_license: 湘ICP备09019772 diff --git a/config/routes.rb b/config/routes.rb index a8cffb2ed..d6c36212a 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -28,6 +28,9 @@ RedmineApp::Application.routes.draw do mount Mobile::API => '/api' + # Enable Grack support + # mount Trustie::Grack.new, at: '/', constraints: lambda { |request| /[-\/\w\.]+\.git\//.match(request.path_info) }, via: [:get, :post] + resources :homework_users resources :no_uses delete 'no_uses', :to => 'no_uses#delete' @@ -39,7 +42,7 @@ RedmineApp::Application.routes.draw do end - resources :school do + resources :school, :except => [:show] do collection do end @@ -83,10 +86,13 @@ RedmineApp::Application.routes.draw do get 'close_poll' get 'export_poll' get 'import_poll' + end collection do delete 'delete_poll_question' post 'update_poll_question' + get 'other_poll' + post 'import_other_poll' end end @@ -95,6 +101,8 @@ RedmineApp::Application.routes.draw do get 'start_anonymous_comment' get 'stop_anonymous_comment' get 'alert_anonymous_comment' + get 'start_evaluation_set' + post 'set_evaluation_attr' end collection do post 'next_step' @@ -113,7 +121,9 @@ RedmineApp::Application.routes.draw do get 'student_work_absence_penalty' get 'absence_penalty_list' get 'evaluation_list' - post 'set_program_score' + # post 'set_program_score' + post 'program_test' + post 'set_score_rule' end end @@ -165,7 +175,7 @@ RedmineApp::Application.routes.draw do resources :contests, only: [:index] do resources :contestnotifications do # get 'preview', on: :collection - resources :notificationcomments + resources :notificationcomments end collection do @@ -213,12 +223,14 @@ RedmineApp::Application.routes.draw do resources :forums do collection do match 'search_forum', :via => [:get, :post] - + match 'check_forum_name',:via => [:get] end member do post 'create_memo' post 'create_feedback' match 'search_memo', :via => [:get, :post] + match 'delete_forum_tag',:via =>[:get] + match 'add_forum_tag',:via=>[:get] end resources :memos do collection do @@ -226,7 +238,7 @@ RedmineApp::Application.routes.draw do end end end - + resources :shares @@ -245,17 +257,25 @@ RedmineApp::Application.routes.draw do match 'welcome/contest', :via => :get # end longjun - #added by baiyu - match 'git_usage/ch_usage', :via => :get, :as => 'ch_usage' - match 'git_usage/en_usage', :via => :get, :as => 'en_usage' #added by nie match '/projects/search', :via => [:get, :post] match '/users/search', :via => [:get, :post] #end + # 消息相关路由 + resources :system_messages do + collection do + post 'create', :as => 'system_messages' + get 'index', :as => 'index' + end + end + # match 'system_messages/index', to: 'system_messages#index', :via => :get, :as => 'system_messages' + match 'account/heartbeat', to: 'account#heartbeat', :via => :get match 'login', :to => 'account#login', :as => 'signin', :via => [:get, :post] match 'logout', :to => 'account#logout', :as => 'signout', :via => [:get, :post] + match 'agreement',:to => 'account#agreement',:as => 'agreement',:via=>[:get] + match 'about_us',:to=>'account#about_us',:as=>'about_us',:via=>[:get] match 'account/register', :via => [:get, :post], :as => 'register' match 'account/lost_password', :via => [:get, :post], :as => 'lost_password' match 'account/activate', :via => :get @@ -297,11 +317,18 @@ RedmineApp::Application.routes.draw do get 'projects/:id/issues/report/:detail', :to => 'reports#issue_report_details', :as => 'project_issues_report_details' post '/users/:id/user_activities', :to => 'users#show', :as => "user_activities" + post '/courses/:id/course_activity', :to => 'courses#show', :as => 'course_activity' + #added by young resources :users do collection do match "tag_saveEx" , :via => [:get, :post] + post "user_new_homework" + get 'new_user_commit_homework' + post "user_commit_homework" + post 'user_select_homework' end + member do match 'user_projects_index', :to => 'users#user_projects_index', :via => :get match 'user_projects', :to => 'users#user_projects', :via => :get @@ -318,7 +345,11 @@ RedmineApp::Application.routes.draw do match 'user_feedback4show', :to => 'users#user_feedback4show', :via => :get match 'user_visitorlist', :to => 'users#user_visitorlist', :via => :get match 'user_homeworks', :to => 'users#user_homeworks', :via => :get + get 'user_import_homeworks' + post 'user_search_homeworks' + get 'user_import_resource' match 'watch_projects', :to => 'users#watch_projects', :via => :get + # # added by bai match 'show_score', :to => 'users#show_score', :via => :get match 'topic_score_index', :to => 'users#topic_score_index', :via => [:get, :post] @@ -341,11 +372,31 @@ RedmineApp::Application.routes.draw do match 'file_score_index', :to => 'projects#file_score_index', :via => [:get, :post] match 'code_submit_score_index', :to => 'projects#code_submit_score_index', :via => [:get, :post] match 'projects_topic_score_index', :to => 'projects#projects_topic_score_index', :via => [:get, :post] - # end + get 'edit_brief_introduction' + get "user_resource" + get "resource_search" + post "user_resource_create" + post "user_resource_delete" + get "search_user_course" + post "add_exist_file_to_course" + post "add_exist_file_to_project" + get 'resource_preview' + post 'rename_resource' + get 'search_user_project' + get 'user_resource_type' + get 'user_ref_resource_search' + post 'import_resources_to_homework' + # end end end match 'users/:id/user_newfeedback', :to => 'users#user_newfeedback', :via => :get, :as => "feedback" match 'users/:id/user_projects', :to => 'users#user_projects', :via => :get + #消息 + match 'users/:id/user_messages', :to => 'users#user_messages', :via => :get, :as => "user_message" + match 'users/:id/user_system_messages', :to => 'users#user_system_messages', :via => :get, :as => "user_system_messages" + #match 'users/:id/user_messages/:homework', :to => 'users#user_messages_homework', :via => :get, :as => "user_message_homewrok" + + #end match 'my/account', :via => [:get, :post] @@ -399,15 +450,7 @@ RedmineApp::Application.routes.draw do get 'feedback', :action => 'feedback', :as => 'project_feedback' get 'watcherlist', :action=> 'watcherlist' - # 添加dts测试工具 - get 'dts_dep', :action=> 'dts_dep' - get 'yun_dep', :action=> 'yun_dep' - get 'soft_knowledge', :action=> 'soft_knowledge' - get 'soft_file', :action=> 'soft_file' - get 'online_dev', :action=> 'online_dev' - get 'soft_service', :action=> 'soft_service' - - get 'invite_members', :action=> 'invite_members' + # get 'invite_members', :action=> 'invite_members' get 'invite_members_by_mail', :action=> 'invite_members_by_mail' # get 'dts_repos', :aciton => 'dts_repos' get 'send_mail_to_member', :action => 'send_mail_to_member' @@ -458,7 +501,7 @@ RedmineApp::Application.routes.draw do collection do match "getattachtype" , :via => [:get, :post] match "search_project",:via => [:post,:get] - #match 'getattachtype/:attachtype', :to => 'files#getattachtype', :via => [:get, :post] + #match 'getattachtype/:attachtype', :to => 'files#getattachtype', :via => [:get, :post] end end @@ -488,7 +531,7 @@ RedmineApp::Application.routes.draw do resources :repositories, :except => [:index, :show] do member do get 'newrepo', :via => [:get, :post] - # get 'create', :via=>[:get, :post] + # get 'create', :via=>[:get, :post] end end match 'wiki/index', :via => :get @@ -519,6 +562,9 @@ RedmineApp::Application.routes.draw do match 'bulk_edit', :via => [:get, :post] post 'bulk_update' end + member do + post 'add_journal' + end resources :time_entries, :controller => 'timelog' do collection do get 'report' @@ -575,8 +621,8 @@ RedmineApp::Application.routes.draw do :controller => 'repositories', :format => false, :constraints => { - :action => /(browse|show|entry|raw|annotate|diff)/, - :rev => /[a-z0-9\.\-_]+/ + :action => /(browse|show|entry|raw|annotate|diff)/, + :rev => /[a-z0-9\.\-_]+/ } get 'projects/:id/repository/statistics', :to => 'repositories#stats' @@ -593,8 +639,8 @@ RedmineApp::Application.routes.draw do :controller => 'repositories', :format => false, :constraints => { - :action => /(browse|show|entry|raw|annotate|diff)/, - :rev => /[a-z0-9\.\-_]+/ + :action => /(browse|show|entry|raw|annotate|diff)/, + :rev => /[a-z0-9\.\-_]+/ } get 'projects/:id/repository/:repository_id/:action(/*path(.:ext))', :controller => 'repositories', @@ -670,6 +716,7 @@ RedmineApp::Application.routes.draw do match 'admin/projects', :via => :get get 'admin/courses' match 'admin/users', :via => :get + match 'admin/messages', :via => :get match 'admin/first_page_made', as: :first_page_made match 'admin/course_page_made', as: :course_page_made match 'admin/contest_page_made', as: :contest_page_made @@ -684,13 +731,20 @@ RedmineApp::Application.routes.draw do match 'admin/default_configuration', :via => :post get 'admin/organization' get 'admin/schools' + get 'admin/leave_messages' + match 'admin/messages_list', as: :messages_list + match 'admin/project_messages', as: :project_messages + match'admin/course_messages', as: :course_messages + get 'admin/notices' + get 'admin/latest_login_users' + get 'admin/homework' resources :auth_sources do member do get 'test_connection', :as => 'try_connection' end collection do - get 'autocomplete_for_new_user' + get 'autocomplete_for_new_user' end end @@ -720,6 +774,7 @@ RedmineApp::Application.routes.draw do post 'join_in/join_group', :to => 'courses#join_group', :as => 'join_group' delete 'join_in/join_group', :to => 'courses#unjoin_group' get 'copy_course' + match 'course_activity', :to => 'courses#course_activity', :via => :get, :as => "course_activity" end collection do match 'join_private_courses', :via => [:get, :post] @@ -752,7 +807,7 @@ RedmineApp::Application.routes.draw do collection do match 'chang_read_flag', :via => :get end - end + end end # end of resources :courses match 'courses/:id/feedback', :to => 'courses#feedback', :via => :get, :as => 'course_feedback' @@ -835,6 +890,7 @@ RedmineApp::Application.routes.draw do match 'tags/remove_tag', :as=>"remove_tag" match 'tags/remove_tag_new', :as=>"remove_tag_new" match 'tags/tag_save', :as => "save_tag" + match 'tags/update_tag_name',:as => "update_tag_name" match 'words/add_brief_introdution' @@ -846,6 +902,7 @@ RedmineApp::Application.routes.draw do match 'system_log/clear' ##ended by lizanle + resources :git_callback do collection do post 'post_update' diff --git a/db/migrate/20150801034945_change_result_default.rb b/db/migrate/20150801034945_change_result_default.rb new file mode 100644 index 000000000..1f629aa45 --- /dev/null +++ b/db/migrate/20150801034945_change_result_default.rb @@ -0,0 +1,9 @@ +class ChangeResultDefault < ActiveRecord::Migration + def up + change_column :homework_tests,:result,:integer,:default => nil + end + + def down + change_column :homework_tests,:result,:integer,:default => 0 + end +end diff --git a/db/migrate/20150810064247_add_created_at_to_activities.rb b/db/migrate/20150810064247_add_created_at_to_activities.rb new file mode 100644 index 000000000..e2f35441f --- /dev/null +++ b/db/migrate/20150810064247_add_created_at_to_activities.rb @@ -0,0 +1,8 @@ +class AddCreatedAtToActivities < ActiveRecord::Migration + def up + add_column :activities, :created_at, :timestamp + end + def end + remove_column :activities, :created_at + end +end diff --git a/db/migrate/20150811010817_update_activities_data.rb b/db/migrate/20150811010817_update_activities_data.rb new file mode 100644 index 000000000..374407cd3 --- /dev/null +++ b/db/migrate/20150811010817_update_activities_data.rb @@ -0,0 +1,21 @@ +class UpdateActivitiesData < ActiveRecord::Migration + def up + # count = Activity.all.count / 20 + 1 + # transaction do + # for i in 1 ... count do i + # Activity.page(i).per(20).each do |activity| + # type = activity.act_type + # if type=='Contest' || type=='Message' || type=='News'|| type=='Journal'|| type=='Issue'|| type=='Principal'||type=='JournalsForMessage' + # activity.created_at = activity.act.created_on if activity.act + # elsif type=='Contestnotification' || type=='HomeworkCommon' || type=='Poll' + # activity.created_at = activity.act.created_at if activity.act + # end + # activity.save + # end + # end + # end + end + + def down + end +end diff --git a/db/migrate/20150811065543_add_course_activities.rb b/db/migrate/20150811065543_add_course_activities.rb new file mode 100644 index 000000000..86b96bd44 --- /dev/null +++ b/db/migrate/20150811065543_add_course_activities.rb @@ -0,0 +1,25 @@ +class AddCourseActivities < ActiveRecord::Migration + def up + create_table :user_activities do |t| + t.string :act_type + t.integer :act_id + t.string :container_type + t.integer :container_id + + t.timestamps + end + + create_table :course_activities do |t| + t.integer :user_id + t.integer :course_id + t.integer :course_act_id + t.string :course_act_type + t.timestamps + end + end + + def down + drop_table :course_activities + drop_table :user_activities + end +end diff --git a/db/migrate/20150811080754_course_activities.rb b/db/migrate/20150811080754_course_activities.rb new file mode 100644 index 000000000..910cb4520 --- /dev/null +++ b/db/migrate/20150811080754_course_activities.rb @@ -0,0 +1,40 @@ +#encoding=UTF-8 +class CourseActivities < ActiveRecord::Migration + def up + Course.all.each do |course| + transaction do + course.course_acts << CourseActivity.new(:user_id => course.tea_id,:course_id => course.id) + #作业 + course.homework_commons.each do |homework_common| + homework_common.course_acts << CourseActivity.new(:user_id => homework_common.user_id,:course_id => course.id) + end + #通知 + course.news.each do |new| + new.course_acts << CourseActivity.new(:user_id => new.author_id,:course_id => course.id) + end + #资源 + course.attachments.each do |attachment| + attachment.course_acts << CourseActivity.new(:user_id => attachment.author_id,:course_id => course.id) + end + #讨论区 + if course.boards.first + course.boards.first.messages.each do |message| + message.course_acts << CourseActivity.new(:user_id => message.author_id,:course_id => course.id) + end + end + #留言 + course.journals_for_messages.each do |jour| + jour.course_acts << CourseActivity.new(:user_id => jour.user_id,:course_id => course.id) + end + #问卷 + Poll.where("polls_type = 'Course' and polls_group_id = #{course.id}").each do |poll| + poll.course_acts << CourseActivity.new(:user_id => poll.user_id,:course_id => course.id) + end + end + end + end + + def down + # CourseActivity.destroy_all + end +end diff --git a/db/migrate/20150811083322_create_forge_messages.rb b/db/migrate/20150811083322_create_forge_messages.rb new file mode 100644 index 000000000..f81b68712 --- /dev/null +++ b/db/migrate/20150811083322_create_forge_messages.rb @@ -0,0 +1,13 @@ +class CreateForgeMessages < ActiveRecord::Migration + def change + create_table :forge_messages do |t| + t.integer :user_id + t.integer :project_id + t.integer :forge_message_id + t.string :forge_message_type + t.integer :viewed + + t.timestamps + end + end +end diff --git a/db/migrate/20150814011838_create_course_messages.rb b/db/migrate/20150814011838_create_course_messages.rb new file mode 100644 index 000000000..266f2b075 --- /dev/null +++ b/db/migrate/20150814011838_create_course_messages.rb @@ -0,0 +1,13 @@ +class CreateCourseMessages < ActiveRecord::Migration + def change + create_table :course_messages do |t| + t.integer :user_id + t.integer :course_id + t.integer :course_message_id + t.string :course_message_type + t.integer :viewed + + t.timestamps + end + end +end diff --git a/db/migrate/20150814024425_change_attachment_time.rb b/db/migrate/20150814024425_change_attachment_time.rb new file mode 100644 index 000000000..fd1ffb7a7 --- /dev/null +++ b/db/migrate/20150814024425_change_attachment_time.rb @@ -0,0 +1,13 @@ +class ChangeAttachmentTime < ActiveRecord::Migration + def up + Attachment.where("container_type = 'Course'").each do |attachment| + if attachment.container && attachment.container.created_at.to_i > attachment.created_on.to_i + attachment.created_on = attachment.container.created_at + 3600 * 24 + attachment.save + end + end + end + + def down + end +end diff --git a/db/migrate/20150814031258_update_course_activity_time.rb b/db/migrate/20150814031258_update_course_activity_time.rb new file mode 100644 index 000000000..26d0dc4bc --- /dev/null +++ b/db/migrate/20150814031258_update_course_activity_time.rb @@ -0,0 +1,26 @@ +class UpdateCourseActivityTime < ActiveRecord::Migration + def up + count = CourseActivity.all.count / 30 + 1 + transaction do + for i in 1 ... count do i + CourseActivity.page(i).per(30).each do |activity| + if activity.course_act + if activity.course_act.respond_to?("created_at") + activity.created_at = activity.course_act.created_at + elsif activity.course_act.respond_to?("created_on") + activity.created_at = activity.course_act.created_on + end + activity.save + + user_activity = UserActivity.where("act_type = '#{activity.course_act_type.to_s}' and act_id = '#{activity.course_act_id}'").first + user_activity.created_at = activity.created_at + user_activity.save + end + end + end + end + end + + def down + end +end diff --git a/db/migrate/20150815030833_add_system_score_to_student_work.rb b/db/migrate/20150815030833_add_system_score_to_student_work.rb new file mode 100644 index 000000000..1f2df648e --- /dev/null +++ b/db/migrate/20150815030833_add_system_score_to_student_work.rb @@ -0,0 +1,9 @@ +class AddSystemScoreToStudentWork < ActiveRecord::Migration + def up + add_column :student_works,:system_score,:integer + end + + def down + remove_column :student_works,:system_score + end +end diff --git a/db/migrate/20150819090720_create_memo_messages.rb b/db/migrate/20150819090720_create_memo_messages.rb new file mode 100644 index 000000000..d050a7815 --- /dev/null +++ b/db/migrate/20150819090720_create_memo_messages.rb @@ -0,0 +1,13 @@ +class CreateMemoMessages < ActiveRecord::Migration + def change + create_table :memo_messages do |t| + t.integer :user_id + t.integer :forum_id + t.integer :memo_id + t.string :memo_type + t.integer :viewed + + t.timestamps + end + end +end diff --git a/db/migrate/20150820004659_create_user_feedback_messages.rb b/db/migrate/20150820004659_create_user_feedback_messages.rb new file mode 100644 index 000000000..c5f5b85d9 --- /dev/null +++ b/db/migrate/20150820004659_create_user_feedback_messages.rb @@ -0,0 +1,12 @@ +class CreateUserFeedbackMessages < ActiveRecord::Migration + def change + create_table :user_feedback_messages do |t| + t.integer :user_id + t.integer :journals_for_message_id + t.string :journals_for_message_type + t.integer :viewed + + t.timestamps + end + end +end diff --git a/db/migrate/20150820022416_create_user_activity.rb b/db/migrate/20150820022416_create_user_activity.rb new file mode 100644 index 000000000..0ff64b1f3 --- /dev/null +++ b/db/migrate/20150820022416_create_user_activity.rb @@ -0,0 +1,9 @@ +class CreateUserActivity < ActiveRecord::Migration + def up + + end + + def down + + end +end diff --git a/db/migrate/20150820025358_about_user_activities.rb b/db/migrate/20150820025358_about_user_activities.rb new file mode 100644 index 000000000..e02b4711f --- /dev/null +++ b/db/migrate/20150820025358_about_user_activities.rb @@ -0,0 +1,37 @@ +class AboutUserActivities < ActiveRecord::Migration + def up + forge_count = ForgeActivity.all.count / 30 + 2 + transaction do + for i in 1 ... forge_count do i + ForgeActivity.page(i).per(30).each do |activity| + user_activity = UserActivity.new + user_activity.act_id = activity.forge_act_id + user_activity.act_type = activity.forge_act_type + user_activity.container_type = "Project" + user_activity.container_id = activity.project_id + user_activity.created_at = activity.created_at + user_activity.save + end + end + end + + # course_count = CourseActivity.all.count / 30 + 2 + # transaction do + # for i in 1 ... course_count do i + # CourseActivity.page(i).per(30).each do |activity| + # user_activity = UserActivity.new + # user_activity.act_id = activity.course_act_id + # user_activity.act_type = activity.course_act_type + # user_activity.container_type = "Course" + # user_activity.container_id = activity.course_id + # user_activity.created_at = activity.created_at + # user_activity.save + # end + # end + # end + end + + def down + # UserActivity.destroy_all + end +end diff --git a/db/migrate/20150824133916_create_message_alls.rb b/db/migrate/20150824133916_create_message_alls.rb new file mode 100644 index 000000000..aa4a986a8 --- /dev/null +++ b/db/migrate/20150824133916_create_message_alls.rb @@ -0,0 +1,11 @@ +class CreateMessageAlls < ActiveRecord::Migration + def change + create_table :message_alls do |t| + t.integer :user_id + t.integer :message_id + t.string :message_type + + t.timestamps + end + end +end diff --git a/db/migrate/20150826020407_add_content_to_course_message.rb b/db/migrate/20150826020407_add_content_to_course_message.rb new file mode 100644 index 000000000..4aad9ab6a --- /dev/null +++ b/db/migrate/20150826020407_add_content_to_course_message.rb @@ -0,0 +1,5 @@ +class AddContentToCourseMessage < ActiveRecord::Migration + def change + add_column :course_messages, :content, :string + end +end diff --git a/db/migrate/20150826061843_add_status_to_course_message.rb b/db/migrate/20150826061843_add_status_to_course_message.rb new file mode 100644 index 000000000..4e8e04ce6 --- /dev/null +++ b/db/migrate/20150826061843_add_status_to_course_message.rb @@ -0,0 +1,5 @@ +class AddStatusToCourseMessage < ActiveRecord::Migration + def change + add_column :course_messages, :status, :integer + end +end diff --git a/db/migrate/20150828011415_change_student_work_tests.rb b/db/migrate/20150828011415_change_student_work_tests.rb new file mode 100644 index 000000000..7d4459ab6 --- /dev/null +++ b/db/migrate/20150828011415_change_student_work_tests.rb @@ -0,0 +1,13 @@ +class ChangeStudentWorkTests < ActiveRecord::Migration + + def change + change_table :student_work_tests do |t| + t.remove :error_msg + t.remove :result + t.remove :homework_test_id + t.integer :status, default: 9 + t.text :results + end + end + +end diff --git a/db/migrate/20150828155329_add_src_to_student_work_tests.rb b/db/migrate/20150828155329_add_src_to_student_work_tests.rb new file mode 100644 index 000000000..89bd80882 --- /dev/null +++ b/db/migrate/20150828155329_add_src_to_student_work_tests.rb @@ -0,0 +1,5 @@ +class AddSrcToStudentWorkTests < ActiveRecord::Migration + def change + add_column :student_work_tests, :src, :text + end +end diff --git a/db/migrate/20150829023459_forge_messages.rb b/db/migrate/20150829023459_forge_messages.rb new file mode 100644 index 000000000..96369a323 --- /dev/null +++ b/db/migrate/20150829023459_forge_messages.rb @@ -0,0 +1,80 @@ +# encoding: UTF-8 +class ForgeMessages < ActiveRecord::Migration + def up + # Project.all.each do |project| + # transaction do + # project.forge_messages << ForgeMessage.new(:user_id => project.user_id, :project_id => project.id) + # + # # 新闻 + # project.news.each do |new| + # new.project.members.each do |m| + # if m.user_id != new.author_id + # if m.created_on < new.created_on # 在成员加入项目之后 + # new.forge_messages << ForgeMessage.new(:user_id => m.user_id, :project_id => new.project_id, :viewed => true) + # end + # end + # end + # end + # + # # 新闻回复 + # project.news.each do |new| + # if new.comments + # new.comments.each do |comment| + # if comment.author_id != comment.commented.author_id + # comment.forge_messages << ForgeMessage.new(:user_id => comment.commented.author_id, :project_id => comment.commented.project.id, :viewed => true) + # end + # end + # end + # end + # + # # 讨论区 + # if project.boards.first + # project.boards.first.messages.each do |message| + # if message.parent_id.nil? # 主贴 + # message.project.members.each do |m| + # if m.user_id != message.author_id + # if m.created_on < message.created_on + # message.forge_messages << ForgeMessage.new(:user_id => m.user_id, :project_id => message.board.project_id, :viewed => true) + # end + # end + # end + # else # 回帖 + # message.project.members.each do |m| + # if m.user_id == Message.find(message.parent_id).author_id && m.user_id != message.author_id # 只针对主贴回复,回复自己的帖子不发消息 + # if m.created_on < message.created_on + # message.forge_messages << ForgeMessage.new(:user_id => m.user_id, :project_id => message.board.project_id, :viewed => true) + # end + # end + # end + # end + # end + # end + # + # # 缺陷 + # project.issues.each do |issue| + # unless issue.author_id == issue.assigned_to_id + # issue.forge_messages << ForgeMessage.new(:user_id => issue.assigned_to_id, :project_id => issue.project_id, :viewed => true) + # end + # end + # + # # 缺陷更新 + # project.issues.each do |issue| + # if issue.journals + # issue.journals.each do |journal| + # if journal.user_id != journal.issue.author_id + # journal.forge_messages << ForgeMessage.new(:user_id => journal.issue.author_id, :project_id => journal.issue.project_id, :viewed => true) + # end + # if journal.user_id != journal.issue.assigned_to_id && journal.issue.assigned_to_id != journal.issue.author_id # 指派人不是自己的话,则给指派人发送 + # journal.forge_messages << ForgeMessage.new(:user_id => journal.issue.assigned_to_id, :project_id => journal.issue.project_id, :viewed => true) + # end + # end + # end + # end + # + # end + # end + end + + def down + end +end diff --git a/db/migrate/20150829024549_course_messages.rb b/db/migrate/20150829024549_course_messages.rb new file mode 100644 index 000000000..9d66bf9cd --- /dev/null +++ b/db/migrate/20150829024549_course_messages.rb @@ -0,0 +1,116 @@ +# encoding: UTF-8 +class CourseMessages < ActiveRecord::Migration + def up + # Course.all.each do |course| + # transaction do + # put course.id + # course.course_messages << CourseMessage.new(:user_id => course.tea_id,:course_id => course.id) + # # 作业 + # course.homework_commons.each do |homework_common| + # homework_common.course.members.each do |m| + # if m.user_id != homework_common.user_id + # if m.created_on < homework_common.created_at + # homework_common.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => true) + # end + # end + # end + # end + # + # # 通知 + # course.news.each do |new| + # new.course.members.each do |m| + # if m.user_id != new.author_id + # if m.created_on < new.created_on # 在成员加入课程之后 + # new.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => true) + # end + # end + # end + # end + # + # # 通知的回复 + # course.news.each do |new| + # if new.comments + # new.comments.each do |comment| + # if comment.author_id != comment.commented.author_id + # comment.course_messages << CourseMessage.new(:user_id => comment.commented.author_id, :course_id => course.id, :viewed => true) + # end + # end + # end + # end + # + # # 讨论区 + # if course.boards.first + # course.boards.first.messages.each do |message| + # if message.parent_id.nil? # 主贴 + # message.course.members.each do |m| + # if message.author.allowed_to?(:as_teacher, message.course) && m.user_id != message.author_id # 老师 自己的帖子不给自己发送消息 + # if m.created_on < message.created_on + # message.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => true) + # end + # end + # end + # else # 回帖 + # message.course.members.each do |m| + # if m.user_id == Message.find(message.parent_id).author_id && m.user_id != message.author_id # 只针对主贴回复,回复自己的帖子不发消息 + # if m.created_on < message.created_on + # message.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => true) + # end + # end + # end + # end + # end + # end + # + # # 问卷 + # Poll.where("polls_type = 'Course' and polls_group_id = #{course.id}").each do |poll| + # if poll.polls_status == 2 #问卷是发布状态 + # Course.find(poll.polls_group_id).members.each do |m| + # if m.user_id != poll.user_id + # if m.created_on < poll.created_at + # poll.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => true) + # end + # end + # end + # elsif poll.polls_status == 1 #问卷是新建状态 + # poll.course_messages.destroy_all + # end + # end + + # 作品评阅 + # course.homework_commons.each do |homework_common| + # if homework_common.student_works + # homework_common.student_works.each do |student_work| + # if student_work.student_works_scores + # student_work.student_works_scores.each do |student_works_score| + # receiver = student_works_score.student_work.user + # if student_works_score.created_at == student_works_score.updated_at + # if student_works_score.comment.nil? + # student_works_score.course_messages << CourseMessage.new(:user_id => receiver.id, :course_id => course.id, + # :viewed => true, :content => "作业评分:#{student_works_score.score}", :status=> true) + # else + # student_works_score.course_messages << CourseMessage.new(:user_id => receiver.id, :course_id => course.id, + # :viewed => true, :content => "作业评分:#{student_works_score.score}    评语:#{student_works_score.comment}", :status=> true) + # end + # else # 更新 + # if student_works_score.comment.nil? + # student_works_score.course_messages << CourseMessage.new(:user_id => receiver.id, :course_id => course.id, + # :viewed => true, :content => "作业评分:#{student_works_score.score}", :status=> true) + # else + # student_works_score.course_messages << CourseMessage.new(:user_id => receiver.id, :course_id => course.id, + # :viewed => true, :content => "作业评分:#{student_works_score.score}    评语:#{student_works_score.comment}", :status=> true) + # end + # end + # end + # end + # end + # end + # end + # 作品讨论 + + # end + # end + end + + def down + end +end diff --git a/db/migrate/20150829081822_update_message_time.rb b/db/migrate/20150829081822_update_message_time.rb new file mode 100644 index 000000000..a5b2457ad --- /dev/null +++ b/db/migrate/20150829081822_update_message_time.rb @@ -0,0 +1,27 @@ +class UpdateMessageTime < ActiveRecord::Migration + def up + # course_count = CourseMessage.all.count / 30 + 1 + # transaction do + # for i in 1 ... course_count do i + # CourseMessage.page(i).per(30).each do |cmessage| + # if cmessage.course_message + # if cmessage.course_message.respond_to?("created_at") + # cmessage.created_at = cmessage.course_message.created_at + # elsif cmessage.course_message.respond_to?("created_on") + # cmessage.created_at = cmessage.course_message.created_on + # end + # cmessage.save + # puts cmessage.id + # + # course_all_message = MessageAll.where("message_type = '#{cmessage.class.to_s}' and message_id = '#{cmessage.id}'").first + # course_all_message.created_at = cmessage.created_at + # course_all_message.save + # end + # end + # end + # end + end + + def down + end +end diff --git a/db/migrate/20150829130302_update_forge_message_time.rb b/db/migrate/20150829130302_update_forge_message_time.rb new file mode 100644 index 000000000..3121278ae --- /dev/null +++ b/db/migrate/20150829130302_update_forge_message_time.rb @@ -0,0 +1,27 @@ +class UpdateForgeMessageTime < ActiveRecord::Migration + def up + # forge_count = ForgeMessage.all.count / 30 + 1 + # transaction do + # for i in 1 ... forge_count do i + # ForgeMessage.page(i).per(30).each do |fmessage| + # if fmessage.forge_message + # if fmessage.forge_message.respond_to?("created_at") + # fmessage.created_at = fmessage.forge_message.created_at + # elsif fmessage.forge_message.respond_to?("created_on") + # fmessage.created_at = fmessage.forge_message.created_on + # end + # fmessage.save + # puts fmessage.id + # + # forge_all_message = MessageAll.where("message_type = '#{fmessage.class.to_s}' and message_id = '#{fmessage.id}'").first + # forge_all_message.created_at = fmessage.created_at + # forge_all_message.save + # end + # end + # end + # end + end + + def down + end +end diff --git a/db/migrate/20150831070611_about_memo_message.rb b/db/migrate/20150831070611_about_memo_message.rb new file mode 100644 index 000000000..a6e4a34c1 --- /dev/null +++ b/db/migrate/20150831070611_about_memo_message.rb @@ -0,0 +1,36 @@ +class AboutMemoMessage < ActiveRecord::Migration + def up + # Memo.all.each do |memo| + # transaction do + # # 贴吧帖子 + # receivers = [] + # u = User.find(6) + # receivers << u + # # 主贴 + # if memo.parent_id.nil? + # if memo.author_id != memo.forum.creator_id # 发帖人不是吧主 + # receivers << memo.forum.creator + # end + # else # 回帖 + # # 添加吧主 + # if memo.author_id != memo.forum.creator_id + # receivers << memo.forum.creator + # end + # # 添加发帖人 + # unless memo.parent.nil? + # if memo.author_id != memo.parent.author_id + # receivers << memo.parent.author + # puts memo.id + # end + # end + # end + # receivers.each do |r| + # memo.memo_messages << MemoMessage.new(:user_id => r.id, :forum_id => memo.forum_id, :memo_id => memo.id, :memo_type => "Memo", :viewed => true) + # end + # end + # end + end + + def down + end +end diff --git a/db/migrate/20150831093918_about_user_feedback_message.rb b/db/migrate/20150831093918_about_user_feedback_message.rb new file mode 100644 index 000000000..a76b7c5e3 --- /dev/null +++ b/db/migrate/20150831093918_about_user_feedback_message.rb @@ -0,0 +1,36 @@ +class AboutUserFeedbackMessage < ActiveRecord::Migration + def up + # JournalsForMessage.all.each do |jour_for_message| + # transaction do + # # 主留言 + # if jour_for_message.jour_type == 'Principal' + # receivers = [] + # if jour_for_message.reply_id == 0 + # if jour_for_message.user_id != jour_for_message.jour_id # 过滤自己给自己的留言消息 + # receivers << jour_for_message.jour + # end + # else # 留言回复 + # reply_to = User.find(jour_for_message.reply_id) + # if jour_for_message.user_id != jour_for_message.reply_id # 添加我回复的那个人 + # receivers << reply_to + # end + # unless jour_for_message.parent.nil? + # if jour_for_message.user_id != jour_for_message.parent.jour_id && jour_for_message.reply_id != jour_for_message.parent.jour_id # 给东家发信息,如果回复的对象是东家则不发 + # receivers << jour_for_message.parent.jour + # end + # end + # end + # unless receivers.blank? + # receivers.each do |r| + # puts jour_for_message.id + # jour_for_message.user_feedback_messages << UserFeedbackMessage.new(:user_id => r.id, :journals_for_message_id => jour_for_message.id, :journals_for_message_type => "Principal", :viewed => true) + # end + # end + # end + # end + # end + end + + def down + end +end diff --git a/db/migrate/20150901004812_update_memo_message_time.rb b/db/migrate/20150901004812_update_memo_message_time.rb new file mode 100644 index 000000000..8760a50a4 --- /dev/null +++ b/db/migrate/20150901004812_update_memo_message_time.rb @@ -0,0 +1,27 @@ +class UpdateMemoMessageTime < ActiveRecord::Migration + def up + # memo_count = Memo.all.count / 30 + 1 + # transaction do + # for i in 1 ... memo_count do i + # MemoMessage.page(i).per(30).each do |memo_message| + # if memo_message.memo + # if memo_message.memo.respond_to?("created_at") + # memo_message.created_at = memo_message.memo.created_at + # elsif memo_message.memo.respond_to?("created_on") + # memo_message.created_at = memo_message.memo.created_on + # end + # memo_message.save + # puts memo_message.id + # + # memo_messages = MessageAll.where("message_type = '#{memo_message.class.to_s}' and message_id = '#{memo_message.id}'").first + # memo_messages.created_at = memo_message.created_at + # memo_messages.save + # end + # end + # end + # end + end + + def down + end +end diff --git a/db/migrate/20150901004910_update_userfeeback_message_time.rb b/db/migrate/20150901004910_update_userfeeback_message_time.rb new file mode 100644 index 000000000..95bfbd2ac --- /dev/null +++ b/db/migrate/20150901004910_update_userfeeback_message_time.rb @@ -0,0 +1,27 @@ +class UpdateUserfeebackMessageTime < ActiveRecord::Migration + def up + # user_feedback_count = UserFeedbackMessage.all.count / 30 + 1 + # transaction do + # for i in 1 ... user_feedback_count do i + # UserFeedbackMessage.page(i).per(30).each do |ufm| + # if ufm.journals_for_message + # if ufm.journals_for_message.respond_to?("created_at") + # ufm.created_at = ufm.journals_for_message.created_at + # elsif ufm.journals_for_message.respond_to?("created_on") + # ufm.created_at = ufm.journals_for_message.created_on + # end + # puts ufm.id + # ufm.save + # + # user_feedback_messages = MessageAll.where("message_type = '#{ufm.class.to_s}' and message_id = '#{ufm.id}'").first + # user_feedback_messages.created_at = ufm.created_at + # user_feedback_messages.save + # end + # end + # end + # end + end + + def down + end +end diff --git a/db/migrate/20150906025009_forge_activitues_date.rb b/db/migrate/20150906025009_forge_activitues_date.rb new file mode 100644 index 000000000..b282d1938 --- /dev/null +++ b/db/migrate/20150906025009_forge_activitues_date.rb @@ -0,0 +1,25 @@ +class ForgeActivituesDate < ActiveRecord::Migration + def up + forge_count = ForgeActivity.all.count / 30 + 2 + transaction do + for i in 1 ... forge_count do i + ForgeActivity.page(i).per(30).each do |activity| + unless activity.forge_act_type == "ProjectCreateInfo" + if activity.forge_act + unless activity.forge_act.project + # puts activity.id + activity.destroy + end + else + # puts activity.id.to_s + "----" + activity.destroy + end + end + end + end + end + end + + def down + end +end diff --git a/db/migrate/20150906065702_create_onclick_times.rb b/db/migrate/20150906065702_create_onclick_times.rb new file mode 100644 index 000000000..3922b775e --- /dev/null +++ b/db/migrate/20150906065702_create_onclick_times.rb @@ -0,0 +1,10 @@ +class CreateOnclickTimes < ActiveRecord::Migration + def change + create_table :onclick_times do |t| + t.integer :user_id + t.datetime :onclick_time + + t.timestamps + end + end +end diff --git a/db/migrate/20150906083453_delete_anonymous_jour.rb b/db/migrate/20150906083453_delete_anonymous_jour.rb new file mode 100644 index 000000000..52e5454e5 --- /dev/null +++ b/db/migrate/20150906083453_delete_anonymous_jour.rb @@ -0,0 +1,8 @@ +class DeleteAnonymousJour < ActiveRecord::Migration + def up + Journal.where("user_id = 2").destroy_all + end + + def down + end +end diff --git a/db/migrate/20150906090419_delete_anonymous_feedback.rb b/db/migrate/20150906090419_delete_anonymous_feedback.rb new file mode 100644 index 000000000..771fd4856 --- /dev/null +++ b/db/migrate/20150906090419_delete_anonymous_feedback.rb @@ -0,0 +1,8 @@ +class DeleteAnonymousFeedback < ActiveRecord::Migration + def up + JournalsForMessage.where("user_id = 2").destroy_all + end + + def down + end +end diff --git a/db/migrate/20150906091723_delete_anonymous_message.rb b/db/migrate/20150906091723_delete_anonymous_message.rb new file mode 100644 index 000000000..dc60bc5e4 --- /dev/null +++ b/db/migrate/20150906091723_delete_anonymous_message.rb @@ -0,0 +1,8 @@ +class DeleteAnonymousMessage < ActiveRecord::Migration + def up + Message.where("author_id = 2").destroy_all + end + + def down + end +end diff --git a/db/migrate/20150907064144_add_user_id_to_user_activities.rb b/db/migrate/20150907064144_add_user_id_to_user_activities.rb new file mode 100644 index 000000000..a038f4dab --- /dev/null +++ b/db/migrate/20150907064144_add_user_id_to_user_activities.rb @@ -0,0 +1,5 @@ +class AddUserIdToUserActivities < ActiveRecord::Migration + def change + add_column :user_activities, :user_id, :int + end +end diff --git a/db/migrate/20150907064547_update_user_activities.rb b/db/migrate/20150907064547_update_user_activities.rb new file mode 100644 index 000000000..b4c56c009 --- /dev/null +++ b/db/migrate/20150907064547_update_user_activities.rb @@ -0,0 +1,40 @@ +class UpdateUserActivities < ActiveRecord::Migration + def up + count = UserActivity.all.count / 30 + 2 + transaction do + for i in 1 ... count do i + UserActivity.page(i).per(30).each do |activity| + if activity.container_type.to_s == 'Project' + forge_activity = ForgeActivity.where("forge_act_type = '#{activity.act_type.to_s}' and forge_act_id = #{activity.act_id}").first + if forge_activity + activity.user_id = forge_activity.user_id + else + activity.user_id = 0 + end + + elsif activity.container_type.to_s == 'Course' + course_activity = CourseActivity.where("course_act_type = '#{activity.act_type.to_s}' and course_act_id = #{activity.act_id}").first + if course_activity + activity.user_id = course_activity.user_id + else + activity.user_id = 0 + end + end + activity.save + end + end + end + end + + def down + count = UserActivity.all.count / 30 + 2 + transaction do + for i in 1 ... count do i + UserActivity.page(i).per(30).each do |activity| + activity.user_id = nil + activity.save + end + end + end + end +end diff --git a/db/migrate/20150907152238_add_is_test_to_student_works.rb b/db/migrate/20150907152238_add_is_test_to_student_works.rb new file mode 100644 index 000000000..b58da7c16 --- /dev/null +++ b/db/migrate/20150907152238_add_is_test_to_student_works.rb @@ -0,0 +1,5 @@ +class AddIsTestToStudentWorks < ActiveRecord::Migration + def change + add_column :student_works, :is_test, :boolean, default: false + end +end diff --git a/db/migrate/20150909062619_create_system_messages.rb b/db/migrate/20150909062619_create_system_messages.rb new file mode 100644 index 000000000..a51715ead --- /dev/null +++ b/db/migrate/20150909062619_create_system_messages.rb @@ -0,0 +1,11 @@ +class CreateSystemMessages < ActiveRecord::Migration + def change + create_table :system_messages do |t| + t.integer :id + t.integer :user_id + t.string :content + + t.timestamps + end + end +end diff --git a/db/migrate/20150911031029_about_programing_homework.rb b/db/migrate/20150911031029_about_programing_homework.rb new file mode 100644 index 000000000..50786834b --- /dev/null +++ b/db/migrate/20150911031029_about_programing_homework.rb @@ -0,0 +1,25 @@ +class AboutProgramingHomework < ActiveRecord::Migration + def up + HomeworkCommon.where(:homework_type => 2).each do |homework| + unless homework.homework_detail_manual + homework_detail_manual = HomeworkDetailManual.new + homework_detail_manual.ta_proportion = 0.6 + homework_detail_manual.comment_status = 1 + homework_detail_manual.evaluation_start = homework.created_at + homework_detail_manual.evaluation_end = homework.created_at + homework_detail_manual.evaluation_num = 3 + homework_detail_manual.absence_penalty = 2 + homework_detail_manual.homework_common_id = homework.id + homework_detail_manual.save + end + end + end + + def down + HomeworkCommon.where(:homework_type => 2).each do |homework| + if homework.homework_detail_manual + homework.homework_detail_manual.destroy + end + end + end +end diff --git a/db/migrate/20150911064528_alter_user_activities.rb b/db/migrate/20150911064528_alter_user_activities.rb new file mode 100644 index 000000000..b6ede5bdb --- /dev/null +++ b/db/migrate/20150911064528_alter_user_activities.rb @@ -0,0 +1,21 @@ +class AlterUserActivities < ActiveRecord::Migration + def up + UserActivity.all.each do |activity| + if activity.act_type == 'Message' + if activity.act + unless activity.act.parent_id.nil? + parent_act = UserActivity.where("act_id = #{activity.act.parent.id} and act_type='Message'").first + parent_act.created_at = activity.act.parent.children.maximum("created_on") + parent_act.save + activity.destroy + end + else + activity.destroy + end + end + end + end + + def down + end +end diff --git a/db/migrate/20150914063751_add_description_to_system_message.rb b/db/migrate/20150914063751_add_description_to_system_message.rb new file mode 100644 index 000000000..9cc9e4172 --- /dev/null +++ b/db/migrate/20150914063751_add_description_to_system_message.rb @@ -0,0 +1,5 @@ +class AddDescriptionToSystemMessage < ActiveRecord::Migration + def change + add_column :system_messages, :description, :text + end +end diff --git a/db/migrate/20150915063302_add_mail_to_invite_list.rb b/db/migrate/20150915063302_add_mail_to_invite_list.rb new file mode 100644 index 000000000..800b5abd4 --- /dev/null +++ b/db/migrate/20150915063302_add_mail_to_invite_list.rb @@ -0,0 +1,5 @@ +class AddMailToInviteList < ActiveRecord::Migration + def change + add_column :invite_lists, :mail, :string + end +end diff --git a/db/migrate/20150917022239_add_teacher_priority_to_homework.rb b/db/migrate/20150917022239_add_teacher_priority_to_homework.rb new file mode 100644 index 000000000..20ab421bc --- /dev/null +++ b/db/migrate/20150917022239_add_teacher_priority_to_homework.rb @@ -0,0 +1,5 @@ +class AddTeacherPriorityToHomework < ActiveRecord::Migration + def change + add_column :homework_commons,:teacher_priority,:integer,:default => 1 + end +end diff --git a/db/migrate/20150917071652_update_user_activities_update_at.rb b/db/migrate/20150917071652_update_user_activities_update_at.rb new file mode 100644 index 000000000..7fbd425f4 --- /dev/null +++ b/db/migrate/20150917071652_update_user_activities_update_at.rb @@ -0,0 +1,16 @@ +class UpdateUserActivitiesUpdateAt < ActiveRecord::Migration + def up + count = UserActivity.all.count / 30 + 2 + transaction do + for i in 1 ... count do i + UserActivity.page(i).per(30).each do |activity| + activity.updated_at = activity.created_at + activity.save + end + end + end + end + + def down + end +end diff --git a/db/migrate/20150917081214_add_subject_to_system_message.rb b/db/migrate/20150917081214_add_subject_to_system_message.rb new file mode 100644 index 000000000..69cdd2a63 --- /dev/null +++ b/db/migrate/20150917081214_add_subject_to_system_message.rb @@ -0,0 +1,5 @@ +class AddSubjectToSystemMessage < ActiveRecord::Migration + def change + add_column :system_messages, :subject, :string + end +end diff --git a/db/migrate/20150918004521_system_score_default.rb b/db/migrate/20150918004521_system_score_default.rb new file mode 100644 index 000000000..6195caad9 --- /dev/null +++ b/db/migrate/20150918004521_system_score_default.rb @@ -0,0 +1,15 @@ +class SystemScoreDefault < ActiveRecord::Migration + def up + change_column :student_works,:system_score,:float,:default => 0 + + + # StudentWork.where("system_score is null").each do |student_work| + # student_work.system_score = 0 + # student_work.save + # end + end + + def down + change_column :student_works,:system_score,:float + end +end diff --git a/db/migrate/20150918005722_about_normal_homework.rb b/db/migrate/20150918005722_about_normal_homework.rb new file mode 100644 index 000000000..8e0ddf00a --- /dev/null +++ b/db/migrate/20150918005722_about_normal_homework.rb @@ -0,0 +1,20 @@ +class AboutNormalHomework < ActiveRecord::Migration + def up + HomeworkCommon.where(:homework_type => 0).each do |homework| + unless homework.homework_detail_manual + homework_detail_manual = HomeworkDetailManual.new + homework_detail_manual.ta_proportion = 0.6 + homework_detail_manual.comment_status = 1 + homework_detail_manual.evaluation_start = homework.created_at + homework_detail_manual.evaluation_end = homework.created_at + homework_detail_manual.evaluation_num = 3 + homework_detail_manual.absence_penalty = 5 + homework_detail_manual.homework_common_id = homework.id + homework_detail_manual.save + end + end + end + + def down + end +end diff --git a/db/migrate/20150918063404_normal_homework_type.rb b/db/migrate/20150918063404_normal_homework_type.rb new file mode 100644 index 000000000..0d70d94be --- /dev/null +++ b/db/migrate/20150918063404_normal_homework_type.rb @@ -0,0 +1,9 @@ +class NormalHomeworkType < ActiveRecord::Migration + def up + HomeworkCommon.where("homework_type = 0").update_all(:homework_type => 1) + end + + def down + HomeworkCommon.where("homework_type = 0").update_all(:homework_type => 1) + end +end diff --git a/db/migrate/20150918134804_add_secret_key_to_forge_message.rb b/db/migrate/20150918134804_add_secret_key_to_forge_message.rb new file mode 100644 index 000000000..1de5a8ae9 --- /dev/null +++ b/db/migrate/20150918134804_add_secret_key_to_forge_message.rb @@ -0,0 +1,5 @@ +class AddSecretKeyToForgeMessage < ActiveRecord::Migration + def change + add_column :forge_messages, :secret_key, :string + end +end diff --git a/db/migrate/20150924063215_add_reply_id_to_message.rb b/db/migrate/20150924063215_add_reply_id_to_message.rb new file mode 100644 index 000000000..b55449ad7 --- /dev/null +++ b/db/migrate/20150924063215_add_reply_id_to_message.rb @@ -0,0 +1,5 @@ +class AddReplyIdToMessage < ActiveRecord::Migration + def change + add_column :messages, :reply_id, :integer + end +end diff --git a/db/migrate/20150925025200_alter_activities.rb b/db/migrate/20150925025200_alter_activities.rb new file mode 100644 index 000000000..8a5480617 --- /dev/null +++ b/db/migrate/20150925025200_alter_activities.rb @@ -0,0 +1,53 @@ +class AlterActivities < ActiveRecord::Migration + def up + UserActivity.all.each do |activity| + if activity.act_type == 'JournalsForMessage' + if activity.act + unless activity.act.m_parent_id.nil? + parent_act = UserActivity.where("act_id = #{activity.act.m_parent_id} and act_type='JournalsForMessage' and container_type='Course'").first + if parent_act + parent_act.created_at = activity.act.parent.children.maximum("created_on") + parent_act.save + activity.destroy + end + end + else + activity.destroy + end + end + end + + CourseActivity.all.each do |activity| + if activity.course_act_type == 'JournalsForMessage' + if activity.course_act + unless activity.course_act.m_parent_id.nil? + parent_act = CourseActivity.where("course_act_id = #{activity.course_act.m_parent_id} and course_act_type='JournalsForMessage'").first + if parent_act + parent_act.created_at = activity.course_act.parent.children.maximum("created_on") + parent_act.save + activity.destroy + end + end + else + activity.destroy + end + elsif activity.course_act_type == 'Message' + if activity.course_act + unless activity.course_act.parent_id.nil? + parent_act = CourseActivity.where("course_act_id = #{activity.course_act.parent_id} and course_act_type='Message'").first + if parent_act + parent_act.created_at = activity.course_act.parent.children.maximum("created_on") + parent_act.save + activity.destroy + end + end + else + activity.destroy + end + end + end + end + + def down + end +end diff --git a/db/migrate/20150925060939_update_course_activities_updated_at.rb b/db/migrate/20150925060939_update_course_activities_updated_at.rb new file mode 100644 index 000000000..fe8393361 --- /dev/null +++ b/db/migrate/20150925060939_update_course_activities_updated_at.rb @@ -0,0 +1,16 @@ +class UpdateCourseActivitiesUpdatedAt < ActiveRecord::Migration + def up + count = CourseActivity.all.count / 30 + 2 + transaction do + for i in 1 ... count do i + CourseActivity.page(i).per(30).each do |activity| + activity.updated_at = activity.created_at + activity.save + end + end + end + end + + def down + end +end diff --git a/db/migrate/20150928090128_add_status_to_forge_message.rb b/db/migrate/20150928090128_add_status_to_forge_message.rb new file mode 100644 index 000000000..e08af8802 --- /dev/null +++ b/db/migrate/20150928090128_add_status_to_forge_message.rb @@ -0,0 +1,5 @@ +class AddStatusToForgeMessage < ActiveRecord::Migration + def change + add_column :forge_messages, :status, :integer + end +end diff --git a/db/migrate/20150930011457_alter_user_activities_news.rb b/db/migrate/20150930011457_alter_user_activities_news.rb new file mode 100644 index 000000000..f91cbb791 --- /dev/null +++ b/db/migrate/20150930011457_alter_user_activities_news.rb @@ -0,0 +1,18 @@ +class AlterUserActivitiesNews < ActiveRecord::Migration + def up + UserActivity.all.each do |activity| + if activity.act_type == 'News' + if activity.act + activity.created_at = activity.act.created_on + activity.updated_at = activity.act.respond_to?("updated_on") ? activity.act.updated_on : activity.act.created_on + activity.save + else + activity.destroy + end + end + end + end + + def down + end +end diff --git a/db/schema.rb b/db/schema.rb index 96be7103e..9c874b3e8 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,14 +11,15 @@ # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20150730130816) do +ActiveRecord::Schema.define(:version => 20150917022239) do create_table "activities", :force => true do |t| - t.integer "act_id", :null => false - t.string "act_type", :null => false - t.integer "user_id", :null => false - t.integer "activity_container_id" - t.string "activity_container_type", :default => "" + t.integer "act_id", :null => false + t.string "act_type", :null => false + t.integer "user_id", :null => false + t.integer "activity_container_id" + t.string "activity_container_type", :default => "" + t.datetime "created_at" end add_index "activities", ["act_id", "act_type"], :name => "index_activities_on_act_id_and_act_type" @@ -324,6 +325,15 @@ ActiveRecord::Schema.define(:version => 20150730130816) do t.datetime "updated_on", :null => false end + create_table "course_activities", :force => true do |t| + t.integer "user_id" + t.integer "course_id" + t.integer "course_act_id" + t.string "course_act_type" + t.datetime "created_at", :null => false + t.datetime "updated_at", :null => false + end + create_table "course_attachments", :force => true do |t| t.string "filename" t.string "disk_filename" @@ -356,6 +366,18 @@ ActiveRecord::Schema.define(:version => 20150730130816) do t.datetime "updated_at", :null => false end + create_table "course_messages", :force => true do |t| + t.integer "user_id" + t.integer "course_id" + t.integer "course_message_id" + t.string "course_message_type" + t.integer "viewed" + t.datetime "created_at", :null => false + t.datetime "updated_at", :null => false + t.string "content" + t.integer "status" + end + create_table "course_statuses", :force => true do |t| t.integer "changesets_count" t.integer "watchers_count" @@ -475,23 +497,26 @@ ActiveRecord::Schema.define(:version => 20150730130816) do add_index "documents", ["created_on"], :name => "index_documents_on_created_on" add_index "documents", ["project_id"], :name => "documents_project_id" - create_table "dts", :force => true do |t| - t.string "IPLineCode" - t.string "Description" - t.string "Num" - t.string "Variable" - t.string "TraceInfo" - t.string "Method" + create_table "dts", :primary_key => "Num", :force => true do |t| + t.string "Defect", :limit => 50 + t.string "Category", :limit => 50 t.string "File" - t.string "IPLine" - t.string "Review" - t.string "Category" - t.string "Defect" - t.string "PreConditions" - t.string "StartLine" + t.string "Method" + t.string "Module", :limit => 20 + t.string "Variable", :limit => 50 + t.integer "StartLine" + t.integer "IPLine" + t.string "IPLineCode", :limit => 200 + t.string "Judge", :limit => 15 + t.integer "Review", :limit => 1 + t.string "Description" + t.text "PreConditions", :limit => 2147483647 + t.text "TraceInfo", :limit => 2147483647 + t.text "Code", :limit => 2147483647 t.integer "project_id" - t.datetime "created_at", :null => false - t.datetime "updated_at", :null => false + t.datetime "created_at" + t.datetime "updated_at" + t.integer "id", :null => false end create_table "enabled_modules", :force => true do |t| @@ -542,6 +567,16 @@ ActiveRecord::Schema.define(:version => 20150730130816) do add_index "forge_activities", ["forge_act_id"], :name => "index_forge_activities_on_forge_act_id" + create_table "forge_messages", :force => true do |t| + t.integer "user_id" + t.integer "project_id" + t.integer "forge_message_id" + t.string "forge_message_type" + t.integer "viewed" + t.datetime "created_at", :null => false + t.datetime "updated_at", :null => false + end + create_table "forums", :force => true do |t| t.string "name", :null => false t.text "description" @@ -589,6 +624,7 @@ ActiveRecord::Schema.define(:version => 20150730130816) do t.integer "course_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false + t.integer "teacher_priority", :default => 1 end create_table "homework_detail_manuals", :force => true do |t| @@ -634,7 +670,7 @@ ActiveRecord::Schema.define(:version => 20150730130816) do t.integer "homework_common_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false - t.integer "result", :default => 0 + t.integer "result" t.text "error_msg" end @@ -650,6 +686,7 @@ ActiveRecord::Schema.define(:version => 20150730130816) do t.integer "user_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false + t.string "mail" end create_table "issue_categories", :force => true do |t| @@ -746,6 +783,16 @@ ActiveRecord::Schema.define(:version => 20150730130816) do add_index "journal_details", ["journal_id"], :name => "journal_details_journal_id" + create_table "journal_details_copy", :force => true do |t| + t.integer "journal_id", :default => 0, :null => false + t.string "property", :limit => 30, :default => "", :null => false + t.string "prop_key", :limit => 30, :default => "", :null => false + t.text "old_value" + t.text "value" + end + + add_index "journal_details_copy", ["journal_id"], :name => "journal_details_journal_id" + create_table "journal_replies", :id => false, :force => true do |t| t.integer "journal_id" t.integer "user_id" @@ -819,6 +866,16 @@ ActiveRecord::Schema.define(:version => 20150730130816) do add_index "members", ["user_id", "project_id", "course_id"], :name => "index_members_on_user_id_and_project_id", :unique => true add_index "members", ["user_id"], :name => "index_members_on_user_id" + create_table "memo_messages", :force => true do |t| + t.integer "user_id" + t.integer "forum_id" + t.integer "memo_id" + t.string "memo_type" + t.integer "viewed" + t.datetime "created_at", :null => false + t.datetime "updated_at", :null => false + end + create_table "memos", :force => true do |t| t.integer "forum_id", :null => false t.integer "parent_id" @@ -834,6 +891,14 @@ ActiveRecord::Schema.define(:version => 20150730130816) do t.integer "viewed_count", :default => 0 end + create_table "message_alls", :force => true do |t| + t.integer "user_id" + t.integer "message_id" + t.string "message_type" + t.datetime "created_at", :null => false + t.datetime "updated_at", :null => false + end + create_table "messages", :force => true do |t| t.integer "board_id", :null => false t.integer "parent_id" @@ -886,6 +951,13 @@ ActiveRecord::Schema.define(:version => 20150730130816) do t.datetime "updated_at", :null => false end + create_table "onclick_times", :force => true do |t| + t.integer "user_id" + t.datetime "onclick_time" + t.datetime "created_at", :null => false + t.datetime "updated_at", :null => false + end + create_table "open_id_authentication_associations", :force => true do |t| t.integer "issued" t.integer "lifetime" @@ -1246,11 +1318,11 @@ ActiveRecord::Schema.define(:version => 20150730130816) do create_table "student_work_tests", :force => true do |t| t.integer "student_work_id" - t.integer "homework_test_id" - t.integer "result" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false - t.text "error_msg" + t.integer "status", :default => 9 + t.text "results" + t.text "src" end create_table "student_works", :force => true do |t| @@ -1267,6 +1339,8 @@ ActiveRecord::Schema.define(:version => 20150730130816) do t.datetime "updated_at", :null => false t.integer "late_penalty", :default => 0 t.integer "absence_penalty", :default => 0 + t.float "system_score", :default => 0.0 + t.boolean "is_test", :default => false end create_table "student_works_evaluation_distributions", :force => true do |t| @@ -1296,6 +1370,14 @@ ActiveRecord::Schema.define(:version => 20150730130816) do add_index "students_for_courses", ["course_id"], :name => "index_students_for_courses_on_course_id" add_index "students_for_courses", ["student_id"], :name => "index_students_for_courses_on_student_id" + create_table "system_messages", :force => true do |t| + t.integer "user_id" + t.string "content" + t.datetime "created_at", :null => false + t.datetime "updated_at", :null => false + t.text "description" + end + create_table "taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" @@ -1363,6 +1445,16 @@ ActiveRecord::Schema.define(:version => 20150730130816) do t.integer "fields_bits", :default => 0 end + create_table "user_activities", :force => true do |t| + t.string "act_type" + t.integer "act_id" + t.string "container_type" + t.integer "container_id" + t.datetime "created_at", :null => false + t.datetime "updated_at", :null => false + t.integer "user_id" + end + create_table "user_extensions", :force => true do |t| t.integer "user_id", :null => false t.date "birthday" @@ -1384,6 +1476,15 @@ ActiveRecord::Schema.define(:version => 20150730130816) do t.string "description", :default => "" end + create_table "user_feedback_messages", :force => true do |t| + t.integer "user_id" + t.integer "journals_for_message_id" + t.string "journals_for_message_type" + t.integer "viewed" + t.datetime "created_at", :null => false + t.datetime "updated_at", :null => false + end + create_table "user_grades", :force => true do |t| t.integer "user_id", :null => false t.integer "project_id", :null => false diff --git a/lib/grack/.travis.yml b/lib/grack/.travis.yml new file mode 100644 index 000000000..76e67ac43 --- /dev/null +++ b/lib/grack/.travis.yml @@ -0,0 +1,14 @@ +language: ruby +env: + - TRAVIS=true +branches: + only: + - 'master' +rvm: + - 1.9.3-p327 + - 2.0.0 +before_script: + - "bundle install" + - "git submodule init" + - "git submodule update" +script: "bundle exec rake" diff --git a/lib/grack/CHANGELOG b/lib/grack/CHANGELOG new file mode 100644 index 000000000..057db50e1 --- /dev/null +++ b/lib/grack/CHANGELOG @@ -0,0 +1,16 @@ +2.0.2 + - Revert MR that broke smart HTTP clients. + +2.0.1 + - Make sure child processes get reaped after popen, again. + +2.0.0 + - Use safer shell commands and avoid Dir.chdir + - Restrict the environment for shell commands + - Make Grack::Server thread-safe (zimbatm) + - Make sure child processes get reaped after popen + - Verify requested path is actually a Git directory (Ryan Canty) + + +1.1.0 + - Modifies service_rpc to use chunked transfer (https://github.com/gitlabhq/grack/pull/1) diff --git a/lib/grack/Gemfile b/lib/grack/Gemfile new file mode 100644 index 000000000..b7113caa8 --- /dev/null +++ b/lib/grack/Gemfile @@ -0,0 +1,10 @@ +source "http://ruby.taobao.org" + +gemspec + +group :development do + gem 'byebug' + gem 'rake' + gem 'pry' + gem 'rack-test' +end diff --git a/lib/grack/Gemfile.lock b/lib/grack/Gemfile.lock new file mode 100644 index 000000000..52d60f85d --- /dev/null +++ b/lib/grack/Gemfile.lock @@ -0,0 +1,37 @@ +PATH + remote: . + specs: + gitlab-grack (2.0.2) + rack (~> 1.5.1) + +GEM + remote: http://ruby.taobao.org/ + specs: + byebug (4.0.5) + columnize (= 0.9.0) + coderay (1.1.0) + columnize (0.9.0) + metaclass (0.0.1) + method_source (0.8.2) + mocha (0.14.0) + metaclass (~> 0.0.1) + pry (0.10.1) + coderay (~> 1.1.0) + method_source (~> 0.8.1) + slop (~> 3.4) + rack (1.5.2) + rack-test (0.6.2) + rack (>= 1.0) + rake (10.1.0) + slop (3.6.0) + +PLATFORMS + ruby + +DEPENDENCIES + byebug + gitlab-grack! + mocha (~> 0.11) + pry + rack-test + rake diff --git a/lib/grack/README.md b/lib/grack/README.md new file mode 100644 index 000000000..0a1acdaae --- /dev/null +++ b/lib/grack/README.md @@ -0,0 +1,95 @@ +Grack - Ruby/Rack Git Smart-HTTP Server Handler +=============================================== + +[![Build Status](https://travis-ci.org/gitlabhq/grack.png)](https://travis-ci.org/gitlabhq/grack) +[![Code Climate](https://codeclimate.com/github/gitlabhq/grack.png)](https://codeclimate.com/github/gitlabhq/grack) + +This project aims to replace the builtin git-http-backend CGI handler +distributed with C Git with a Rack application. This reason for doing this +is to allow far more webservers to be able to handle Git smart http requests. + +The default git-http-backend only runs as a CGI script, and specifically is +only targeted for Apache 2.x usage (it requires PATH_INFO to be set and +specifically formatted). So, instead of trying to get it to work with +other CGI capable webservers (Lighttpd, etc), we can get it running on nearly +every major and minor webserver out there by making it Rack capable. Rack +applications can run with the following handlers: + +* CGI +* FCGI +* Mongrel (and EventedMongrel and SwiftipliedMongrel) +* WEBrick +* SCGI +* LiteSpeed +* Thin + +These web servers include Rack handlers in their distributions: + +* Ebb +* Fuzed +* Phusion Passenger (which is mod_rack for Apache and for nginx) +* Unicorn +* Puma + +With [Warbler](http://caldersphere.rubyforge.org/warbler/classes/Warbler.html), +and JRuby, we can also generate a WAR file that can be deployed in any Java +web application server (Tomcat, Glassfish, Websphere, JBoss, etc). + +Since the git-http-backend is really just a simple wrapper for the upload-pack +and receive-pack processes with the '--stateless-rpc' option, it does not +actually re-implement very much. + +Dependencies +======================== +* Ruby - http://www.ruby-lang.org +* Rack - http://rack.rubyforge.org +* A Rack-compatible web server +* Git >= 1.7 (currently the 'pu' branch) +* Mocha (only for running the tests) + +Quick Start +======================== + $ gem install rack + $ (edit config.ru to set git project path) + $ rackup --host 127.0.0.1 -p 8080 config.ru + $ git clone http://127.0.0.1:8080/schacon/grit.git + +Contributing +======================== +If you would like to contribute to the Grack project, I prefer to get +pull-requests via GitHub. You should include tests for whatever functionality +you add. Just fork this project, push your changes to your fork and click +the 'pull request' button. To run the tests, you first need to install the +'mocha' mocking library and initialize the submodule. + + $ sudo gem install mocha + $ git submodule init + $ git submodule update + +Then you should be able to run the tests with a 'rake' command. You can also +run coverage tests with 'rake rcov' if you have rcov installed. + +License +======================== + (The MIT License) + + Copyright (c) 2009 Scott Chacon + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + 'Software'), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/lib/grack/Rakefile b/lib/grack/Rakefile new file mode 100644 index 000000000..255246bf4 --- /dev/null +++ b/lib/grack/Rakefile @@ -0,0 +1,27 @@ +#!/usr/bin/env rake +require "bundler/gem_tasks" + +task :default => :test + +desc "Run the tests." +task :test do + Dir.glob("tests/*_test.rb").each do |f| + system "ruby #{f}" + end +end + +desc "Run test coverage." +task :rcov do + system "rcov tests/*_test.rb -i lib/git_http.rb -x rack -x Library -x tests" + system "open coverage/index.html" +end + +namespace :grack do + desc "Start Grack" + task :start do + system('./bin/testserver') + end +end + +desc "Start everything." +multitask :start => [ 'grack:start' ] diff --git a/lib/grack/bin/console b/lib/grack/bin/console new file mode 100644 index 000000000..b9297ffab --- /dev/null +++ b/lib/grack/bin/console @@ -0,0 +1,6 @@ +#! /bin/bash + +set -e + +cd $(dirname "$0")/.. +exec /usr/bin/env bundle exec pry -Ilib -r grack diff --git a/lib/grack/bin/testserver b/lib/grack/bin/testserver new file mode 100644 index 000000000..3c0db5b3f --- /dev/null +++ b/lib/grack/bin/testserver @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby +libdir = File.absolute_path( File.join( File.dirname(__FILE__), '../lib' ) ) +$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir) + +Bundler.require(:default, :development) + + +require 'grack' +require 'rack' +root = File.absolute_path( File.join( File.dirname(__FILE__), '../examples' ) ) +app = Grack::Server.new({ + project_root: root, + upload_pack: true, + receive_pack:true +}) + +app1= Rack::Builder.new do + use Grack::Auth do |username, password| + [username, password] == ['123', '455'] + end + run app +end + +Rack::Server.start app: app1, Port: 3001 diff --git a/lib/grack/examples/111.git/HEAD b/lib/grack/examples/111.git/HEAD new file mode 100644 index 000000000..cb089cd89 --- /dev/null +++ b/lib/grack/examples/111.git/HEAD @@ -0,0 +1 @@ +ref: refs/heads/master diff --git a/lib/grack/examples/111.git/config b/lib/grack/examples/111.git/config new file mode 100644 index 000000000..e6da23157 --- /dev/null +++ b/lib/grack/examples/111.git/config @@ -0,0 +1,6 @@ +[core] + repositoryformatversion = 0 + filemode = true + bare = true + ignorecase = true + precomposeunicode = true diff --git a/lib/grack/examples/111.git/description b/lib/grack/examples/111.git/description new file mode 100644 index 000000000..498b267a8 --- /dev/null +++ b/lib/grack/examples/111.git/description @@ -0,0 +1 @@ +Unnamed repository; edit this file 'description' to name the repository. diff --git a/lib/grack/examples/111.git/hooks/applypatch-msg.sample b/lib/grack/examples/111.git/hooks/applypatch-msg.sample new file mode 100644 index 000000000..8b2a2fe84 --- /dev/null +++ b/lib/grack/examples/111.git/hooks/applypatch-msg.sample @@ -0,0 +1,15 @@ +#!/bin/sh +# +# An example hook script to check the commit log message taken by +# applypatch from an e-mail message. +# +# The hook should exit with non-zero status after issuing an +# appropriate message if it wants to stop the commit. The hook is +# allowed to edit the commit message file. +# +# To enable this hook, rename this file to "applypatch-msg". + +. git-sh-setup +test -x "$GIT_DIR/hooks/commit-msg" && + exec "$GIT_DIR/hooks/commit-msg" ${1+"$@"} +: diff --git a/lib/grack/examples/111.git/hooks/commit-msg.sample b/lib/grack/examples/111.git/hooks/commit-msg.sample new file mode 100644 index 000000000..b58d1184a --- /dev/null +++ b/lib/grack/examples/111.git/hooks/commit-msg.sample @@ -0,0 +1,24 @@ +#!/bin/sh +# +# An example hook script to check the commit log message. +# Called by "git commit" with one argument, the name of the file +# that has the commit message. The hook should exit with non-zero +# status after issuing an appropriate message if it wants to stop the +# commit. The hook is allowed to edit the commit message file. +# +# To enable this hook, rename this file to "commit-msg". + +# Uncomment the below to add a Signed-off-by line to the message. +# Doing this in a hook is a bad idea in general, but the prepare-commit-msg +# hook is more suited to it. +# +# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') +# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" + +# This example catches duplicate Signed-off-by lines. + +test "" = "$(grep '^Signed-off-by: ' "$1" | + sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { + echo >&2 Duplicate Signed-off-by lines. + exit 1 +} diff --git a/lib/grack/examples/111.git/hooks/post-update.sample b/lib/grack/examples/111.git/hooks/post-update.sample new file mode 100644 index 000000000..ec17ec193 --- /dev/null +++ b/lib/grack/examples/111.git/hooks/post-update.sample @@ -0,0 +1,8 @@ +#!/bin/sh +# +# An example hook script to prepare a packed repository for use over +# dumb transports. +# +# To enable this hook, rename this file to "post-update". + +exec git update-server-info diff --git a/lib/grack/examples/111.git/hooks/pre-applypatch.sample b/lib/grack/examples/111.git/hooks/pre-applypatch.sample new file mode 100644 index 000000000..b1f187c2e --- /dev/null +++ b/lib/grack/examples/111.git/hooks/pre-applypatch.sample @@ -0,0 +1,14 @@ +#!/bin/sh +# +# An example hook script to verify what is about to be committed +# by applypatch from an e-mail message. +# +# The hook should exit with non-zero status after issuing an +# appropriate message if it wants to stop the commit. +# +# To enable this hook, rename this file to "pre-applypatch". + +. git-sh-setup +test -x "$GIT_DIR/hooks/pre-commit" && + exec "$GIT_DIR/hooks/pre-commit" ${1+"$@"} +: diff --git a/lib/grack/examples/111.git/hooks/pre-commit.sample b/lib/grack/examples/111.git/hooks/pre-commit.sample new file mode 100644 index 000000000..68d62d544 --- /dev/null +++ b/lib/grack/examples/111.git/hooks/pre-commit.sample @@ -0,0 +1,49 @@ +#!/bin/sh +# +# An example hook script to verify what is about to be committed. +# Called by "git commit" with no arguments. The hook should +# exit with non-zero status after issuing an appropriate message if +# it wants to stop the commit. +# +# To enable this hook, rename this file to "pre-commit". + +if git rev-parse --verify HEAD >/dev/null 2>&1 +then + against=HEAD +else + # Initial commit: diff against an empty tree object + against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 +fi + +# If you want to allow non-ASCII filenames set this variable to true. +allownonascii=$(git config --bool hooks.allownonascii) + +# Redirect output to stderr. +exec 1>&2 + +# Cross platform projects tend to avoid non-ASCII filenames; prevent +# them from being added to the repository. We exploit the fact that the +# printable range starts at the space character and ends with tilde. +if [ "$allownonascii" != "true" ] && + # Note that the use of brackets around a tr range is ok here, (it's + # even required, for portability to Solaris 10's /usr/bin/tr), since + # the square bracket bytes happen to fall in the designated range. + test $(git diff --cached --name-only --diff-filter=A -z $against | + LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 +then + cat <<\EOF +Error: Attempt to add a non-ASCII file name. + +This can cause problems if you want to work with people on other platforms. + +To be portable it is advisable to rename the file. + +If you know what you are doing you can disable this check using: + + git config hooks.allownonascii true +EOF + exit 1 +fi + +# If there are whitespace errors, print the offending file names and fail. +exec git diff-index --check --cached $against -- diff --git a/lib/grack/examples/111.git/hooks/pre-push.sample b/lib/grack/examples/111.git/hooks/pre-push.sample new file mode 100644 index 000000000..6187dbf43 --- /dev/null +++ b/lib/grack/examples/111.git/hooks/pre-push.sample @@ -0,0 +1,53 @@ +#!/bin/sh + +# An example hook script to verify what is about to be pushed. Called by "git +# push" after it has checked the remote status, but before anything has been +# pushed. If this script exits with a non-zero status nothing will be pushed. +# +# This hook is called with the following parameters: +# +# $1 -- Name of the remote to which the push is being done +# $2 -- URL to which the push is being done +# +# If pushing without using a named remote those arguments will be equal. +# +# Information about the commits which are being pushed is supplied as lines to +# the standard input in the form: +# +# +# +# This sample shows how to prevent push of commits where the log message starts +# with "WIP" (work in progress). + +remote="$1" +url="$2" + +z40=0000000000000000000000000000000000000000 + +while read local_ref local_sha remote_ref remote_sha +do + if [ "$local_sha" = $z40 ] + then + # Handle delete + : + else + if [ "$remote_sha" = $z40 ] + then + # New branch, examine all commits + range="$local_sha" + else + # Update to existing branch, examine new commits + range="$remote_sha..$local_sha" + fi + + # Check for WIP commit + commit=`git rev-list -n 1 --grep '^WIP' "$range"` + if [ -n "$commit" ] + then + echo >&2 "Found WIP commit in $local_ref, not pushing" + exit 1 + fi + fi +done + +exit 0 diff --git a/lib/grack/examples/111.git/hooks/pre-rebase.sample b/lib/grack/examples/111.git/hooks/pre-rebase.sample new file mode 100644 index 000000000..9773ed4cb --- /dev/null +++ b/lib/grack/examples/111.git/hooks/pre-rebase.sample @@ -0,0 +1,169 @@ +#!/bin/sh +# +# Copyright (c) 2006, 2008 Junio C Hamano +# +# The "pre-rebase" hook is run just before "git rebase" starts doing +# its job, and can prevent the command from running by exiting with +# non-zero status. +# +# The hook is called with the following parameters: +# +# $1 -- the upstream the series was forked from. +# $2 -- the branch being rebased (or empty when rebasing the current branch). +# +# This sample shows how to prevent topic branches that are already +# merged to 'next' branch from getting rebased, because allowing it +# would result in rebasing already published history. + +publish=next +basebranch="$1" +if test "$#" = 2 +then + topic="refs/heads/$2" +else + topic=`git symbolic-ref HEAD` || + exit 0 ;# we do not interrupt rebasing detached HEAD +fi + +case "$topic" in +refs/heads/??/*) + ;; +*) + exit 0 ;# we do not interrupt others. + ;; +esac + +# Now we are dealing with a topic branch being rebased +# on top of master. Is it OK to rebase it? + +# Does the topic really exist? +git show-ref -q "$topic" || { + echo >&2 "No such branch $topic" + exit 1 +} + +# Is topic fully merged to master? +not_in_master=`git rev-list --pretty=oneline ^master "$topic"` +if test -z "$not_in_master" +then + echo >&2 "$topic is fully merged to master; better remove it." + exit 1 ;# we could allow it, but there is no point. +fi + +# Is topic ever merged to next? If so you should not be rebasing it. +only_next_1=`git rev-list ^master "^$topic" ${publish} | sort` +only_next_2=`git rev-list ^master ${publish} | sort` +if test "$only_next_1" = "$only_next_2" +then + not_in_topic=`git rev-list "^$topic" master` + if test -z "$not_in_topic" + then + echo >&2 "$topic is already up-to-date with master" + exit 1 ;# we could allow it, but there is no point. + else + exit 0 + fi +else + not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"` + /usr/bin/perl -e ' + my $topic = $ARGV[0]; + my $msg = "* $topic has commits already merged to public branch:\n"; + my (%not_in_next) = map { + /^([0-9a-f]+) /; + ($1 => 1); + } split(/\n/, $ARGV[1]); + for my $elem (map { + /^([0-9a-f]+) (.*)$/; + [$1 => $2]; + } split(/\n/, $ARGV[2])) { + if (!exists $not_in_next{$elem->[0]}) { + if ($msg) { + print STDERR $msg; + undef $msg; + } + print STDERR " $elem->[1]\n"; + } + } + ' "$topic" "$not_in_next" "$not_in_master" + exit 1 +fi + +exit 0 + +################################################################ + +This sample hook safeguards topic branches that have been +published from being rewound. + +The workflow assumed here is: + + * Once a topic branch forks from "master", "master" is never + merged into it again (either directly or indirectly). + + * Once a topic branch is fully cooked and merged into "master", + it is deleted. If you need to build on top of it to correct + earlier mistakes, a new topic branch is created by forking at + the tip of the "master". This is not strictly necessary, but + it makes it easier to keep your history simple. + + * Whenever you need to test or publish your changes to topic + branches, merge them into "next" branch. + +The script, being an example, hardcodes the publish branch name +to be "next", but it is trivial to make it configurable via +$GIT_DIR/config mechanism. + +With this workflow, you would want to know: + +(1) ... if a topic branch has ever been merged to "next". Young + topic branches can have stupid mistakes you would rather + clean up before publishing, and things that have not been + merged into other branches can be easily rebased without + affecting other people. But once it is published, you would + not want to rewind it. + +(2) ... if a topic branch has been fully merged to "master". + Then you can delete it. More importantly, you should not + build on top of it -- other people may already want to + change things related to the topic as patches against your + "master", so if you need further changes, it is better to + fork the topic (perhaps with the same name) afresh from the + tip of "master". + +Let's look at this example: + + o---o---o---o---o---o---o---o---o---o "next" + / / / / + / a---a---b A / / + / / / / + / / c---c---c---c B / + / / / \ / + / / / b---b C \ / + / / / / \ / + ---o---o---o---o---o---o---o---o---o---o---o "master" + + +A, B and C are topic branches. + + * A has one fix since it was merged up to "next". + + * B has finished. It has been fully merged up to "master" and "next", + and is ready to be deleted. + + * C has not merged to "next" at all. + +We would want to allow C to be rebased, refuse A, and encourage +B to be deleted. + +To compute (1): + + git rev-list ^master ^topic next + git rev-list ^master next + + if these match, topic has not merged in next at all. + +To compute (2): + + git rev-list master..topic + + if this is empty, it is fully merged to "master". diff --git a/lib/grack/examples/111.git/hooks/prepare-commit-msg.sample b/lib/grack/examples/111.git/hooks/prepare-commit-msg.sample new file mode 100644 index 000000000..f093a02ec --- /dev/null +++ b/lib/grack/examples/111.git/hooks/prepare-commit-msg.sample @@ -0,0 +1,36 @@ +#!/bin/sh +# +# An example hook script to prepare the commit log message. +# Called by "git commit" with the name of the file that has the +# commit message, followed by the description of the commit +# message's source. The hook's purpose is to edit the commit +# message file. If the hook fails with a non-zero status, +# the commit is aborted. +# +# To enable this hook, rename this file to "prepare-commit-msg". + +# This hook includes three examples. The first comments out the +# "Conflicts:" part of a merge commit. +# +# The second includes the output of "git diff --name-status -r" +# into the message, just before the "git status" output. It is +# commented because it doesn't cope with --amend or with squashed +# commits. +# +# The third example adds a Signed-off-by line to the message, that can +# still be edited. This is rarely a good idea. + +case "$2,$3" in + merge,) + /usr/bin/perl -i.bak -ne 's/^/# /, s/^# #/#/ if /^Conflicts/ .. /#/; print' "$1" ;; + +# ,|template,) +# /usr/bin/perl -i.bak -pe ' +# print "\n" . `git diff --cached --name-status -r` +# if /^#/ && $first++ == 0' "$1" ;; + + *) ;; +esac + +# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') +# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" diff --git a/lib/grack/examples/111.git/hooks/update.sample b/lib/grack/examples/111.git/hooks/update.sample new file mode 100644 index 000000000..d84758373 --- /dev/null +++ b/lib/grack/examples/111.git/hooks/update.sample @@ -0,0 +1,128 @@ +#!/bin/sh +# +# An example hook script to blocks unannotated tags from entering. +# Called by "git receive-pack" with arguments: refname sha1-old sha1-new +# +# To enable this hook, rename this file to "update". +# +# Config +# ------ +# hooks.allowunannotated +# This boolean sets whether unannotated tags will be allowed into the +# repository. By default they won't be. +# hooks.allowdeletetag +# This boolean sets whether deleting tags will be allowed in the +# repository. By default they won't be. +# hooks.allowmodifytag +# This boolean sets whether a tag may be modified after creation. By default +# it won't be. +# hooks.allowdeletebranch +# This boolean sets whether deleting branches will be allowed in the +# repository. By default they won't be. +# hooks.denycreatebranch +# This boolean sets whether remotely creating branches will be denied +# in the repository. By default this is allowed. +# + +# --- Command line +refname="$1" +oldrev="$2" +newrev="$3" + +# --- Safety check +if [ -z "$GIT_DIR" ]; then + echo "Don't run this script from the command line." >&2 + echo " (if you want, you could supply GIT_DIR then run" >&2 + echo " $0 )" >&2 + exit 1 +fi + +if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then + echo "usage: $0 " >&2 + exit 1 +fi + +# --- Config +allowunannotated=$(git config --bool hooks.allowunannotated) +allowdeletebranch=$(git config --bool hooks.allowdeletebranch) +denycreatebranch=$(git config --bool hooks.denycreatebranch) +allowdeletetag=$(git config --bool hooks.allowdeletetag) +allowmodifytag=$(git config --bool hooks.allowmodifytag) + +# check for no description +projectdesc=$(sed -e '1q' "$GIT_DIR/description") +case "$projectdesc" in +"Unnamed repository"* | "") + echo "*** Project description file hasn't been set" >&2 + exit 1 + ;; +esac + +# --- Check types +# if $newrev is 0000...0000, it's a commit to delete a ref. +zero="0000000000000000000000000000000000000000" +if [ "$newrev" = "$zero" ]; then + newrev_type=delete +else + newrev_type=$(git cat-file -t $newrev) +fi + +case "$refname","$newrev_type" in + refs/tags/*,commit) + # un-annotated tag + short_refname=${refname##refs/tags/} + if [ "$allowunannotated" != "true" ]; then + echo "*** The un-annotated tag, $short_refname, is not allowed in this repository" >&2 + echo "*** Use 'git tag [ -a | -s ]' for tags you want to propagate." >&2 + exit 1 + fi + ;; + refs/tags/*,delete) + # delete tag + if [ "$allowdeletetag" != "true" ]; then + echo "*** Deleting a tag is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/tags/*,tag) + # annotated tag + if [ "$allowmodifytag" != "true" ] && git rev-parse $refname > /dev/null 2>&1 + then + echo "*** Tag '$refname' already exists." >&2 + echo "*** Modifying a tag is not allowed in this repository." >&2 + exit 1 + fi + ;; + refs/heads/*,commit) + # branch + if [ "$oldrev" = "$zero" -a "$denycreatebranch" = "true" ]; then + echo "*** Creating a branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/heads/*,delete) + # delete branch + if [ "$allowdeletebranch" != "true" ]; then + echo "*** Deleting a branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/remotes/*,commit) + # tracking branch + ;; + refs/remotes/*,delete) + # delete tracking branch + if [ "$allowdeletebranch" != "true" ]; then + echo "*** Deleting a tracking branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + *) + # Anything else (is there anything else?) + echo "*** Update hook: unknown type of update to ref $refname of type $newrev_type" >&2 + exit 1 + ;; +esac + +# --- Finished +exit 0 diff --git a/lib/grack/examples/111.git/info/exclude b/lib/grack/examples/111.git/info/exclude new file mode 100644 index 000000000..a5196d1be --- /dev/null +++ b/lib/grack/examples/111.git/info/exclude @@ -0,0 +1,6 @@ +# git ls-files --others --exclude-from=.git/info/exclude +# Lines that start with '#' are comments. +# For a project mostly in C, the following would be a good set of +# exclude patterns (uncomment them if you want to use them): +# *.[oa] +# *~ diff --git a/lib/grack/examples/111.git/info/refs b/lib/grack/examples/111.git/info/refs new file mode 100644 index 000000000..e69de29bb diff --git a/lib/grack/examples/111.git/objects/61/9289f137abd616d94899f2c9b6726de091ac92 b/lib/grack/examples/111.git/objects/61/9289f137abd616d94899f2c9b6726de091ac92 new file mode 100644 index 000000000..38a5c4463 Binary files /dev/null and b/lib/grack/examples/111.git/objects/61/9289f137abd616d94899f2c9b6726de091ac92 differ diff --git a/lib/grack/examples/111.git/objects/ce/013625030ba8dba906f756967f9e9ca394464a b/lib/grack/examples/111.git/objects/ce/013625030ba8dba906f756967f9e9ca394464a new file mode 100644 index 000000000..6802d4949 Binary files /dev/null and b/lib/grack/examples/111.git/objects/ce/013625030ba8dba906f756967f9e9ca394464a differ diff --git a/lib/grack/examples/111.git/objects/e1/022324d23146d29075a3e7c6f637cb67f091b5 b/lib/grack/examples/111.git/objects/e1/022324d23146d29075a3e7c6f637cb67f091b5 new file mode 100644 index 000000000..385d8c426 --- /dev/null +++ b/lib/grack/examples/111.git/objects/e1/022324d23146d29075a3e7c6f637cb67f091b5 @@ -0,0 +1,3 @@ +xM + @= gRz5B0o탏Fmg)@(eC )c$Y)E $Fkzţx1e>]o@gg +Yku5JM/0 \ No newline at end of file diff --git a/lib/grack/examples/111.git/objects/info/packs b/lib/grack/examples/111.git/objects/info/packs new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/lib/grack/examples/111.git/objects/info/packs @@ -0,0 +1 @@ + diff --git a/lib/grack/examples/111.git/refs/heads/master b/lib/grack/examples/111.git/refs/heads/master new file mode 100644 index 000000000..864350cd1 --- /dev/null +++ b/lib/grack/examples/111.git/refs/heads/master @@ -0,0 +1 @@ +e1022324d23146d29075a3e7c6f637cb67f091b5 diff --git a/lib/grack/examples/dispatch.fcgi b/lib/grack/examples/dispatch.fcgi new file mode 100644 index 000000000..5ca764fba --- /dev/null +++ b/lib/grack/examples/dispatch.fcgi @@ -0,0 +1,9 @@ +#! /usr/bin/env ruby +$LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__) + '/lib') +require 'lib/git_http' +config = { + :project_root => "/opt", + :upload_pack => true, + :receive_pack => false, +} +Rack::Handler::FastCGI.run(GitHttp::App.new(config)) \ No newline at end of file diff --git a/lib/grack/grack.gemspec b/lib/grack/grack.gemspec new file mode 100644 index 000000000..e743ce314 --- /dev/null +++ b/lib/grack/grack.gemspec @@ -0,0 +1,20 @@ +# -*- encoding: utf-8 -*- +require File.expand_path('../lib/grack/version', __FILE__) + +Gem::Specification.new do |gem| + gem.authors = ["Scott Chacon"] + gem.email = ["schacon@gmail.com"] + gem.description = %q{Ruby/Rack Git Smart-HTTP Server Handler} + gem.summary = %q{Ruby/Rack Git Smart-HTTP Server Handler} + gem.homepage = "https://github.com/gitlabhq/grack" + + gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } + gem.files = `git ls-files`.split("\n") + gem.test_files = `git ls-files -- tests/*`.split("\n") + gem.name = "grack" + gem.require_paths = ["lib"] + gem.version = Grack::VERSION + + gem.add_dependency("rack", "~> 1.4.5") + gem.add_development_dependency("mocha", "~> 0.11") +end diff --git a/lib/grack/install.txt b/lib/grack/install.txt new file mode 100644 index 000000000..c53e1a3e3 --- /dev/null +++ b/lib/grack/install.txt @@ -0,0 +1,60 @@ +Installation +======================== + +** This documentation is not finished yet. I haven't tested all of +these and it's obviously incomplete - these are currently just notes. + +FastCGI +--------------------------------------- +Here is an example config from lighttpd server: +---- +# main fastcgi entry +$HTTP["url"] =~ "^/myapp/.+$" { + fastcgi.server = ( "/myapp" => + ( "localhost" => + ( "bin-path" => "/var/www/localhost/cgi-bin/dispatch.fcgi", + "docroot" => "/var/www/localhost/htdocs/myapp", + "host" => "127.0.0.1", + "port" => 1026, + "check-local" => "disable" + ) + ) + ) +} # HTTP[url] +---- +You can use the examples/dispatch.fcgi file as your dispatcher. + +(Example Apache setup?) + +Installing in a Java application server +--------------------------------------- +# install Warbler +$ sudo gem install warbler +$ cd gitsmart +$ (edit config.ru) +$ warble +$ cp gitsmart.war /path/to/java/autodeploy/dir + +Unicorn +--------------------------------------- +With Unicorn (http://unicorn.bogomips.org/) you can just run 'unicorn' +in the directory with the config.ru file. + +Thin +--------------------------------------- +thin.yml +--- +pid: /home/deploy/myapp/server/thin.pid +log: /home/deploy/myapp/logs/thin.log +timeout: 30 +port: 7654 +max_conns: 1024 +chdir: /home/deploy/myapp/site_files +rackup: /home/deploy/myapp/server/config.ru +max_persistent_conns: 512 +environment: production +address: 127.0.0.1 +servers: 1 +daemonize: true + + diff --git a/lib/grack/lib/grack.rb b/lib/grack/lib/grack.rb new file mode 100644 index 000000000..2c625d227 --- /dev/null +++ b/lib/grack/lib/grack.rb @@ -0,0 +1,5 @@ +require "grack/bundle" + +module Grack + +end diff --git a/lib/grack/lib/grack/auth.rb b/lib/grack/lib/grack/auth.rb new file mode 100644 index 000000000..6a50cbd56 --- /dev/null +++ b/lib/grack/lib/grack/auth.rb @@ -0,0 +1,37 @@ +require 'rack/auth/basic' +require 'rack/auth/abstract/handler' +require 'rack/auth/abstract/request' + +module Grack + class Auth < Rack::Auth::Basic + def call(env) + @env = env + @request = Rack::Request.new(env) + @auth = Request.new(env) + + if not @auth.provided? + unauthorized + elsif not @auth.basic? + bad_request + else + result = if (access = valid?(@auth) and access == true) + @env['REMOTE_USER'] = @auth.username + @app.call(env) + else + if access == '404' + render_not_found + elsif access == '403' + render_no_access + else + unauthorized + end + end + result + end + end# method call + + # def valid? + # false + # end + end# class Auth +end# module Grack diff --git a/lib/grack/lib/grack/bundle.rb b/lib/grack/lib/grack/bundle.rb new file mode 100644 index 000000000..c6a789a4e --- /dev/null +++ b/lib/grack/lib/grack/bundle.rb @@ -0,0 +1,19 @@ +require 'rack/builder' +require 'grack/auth' +require 'grack/server' + +module Grack + module Bundle + extend self + + def new(config) + Rack::Builder.new do + use Grack::Auth do |username, password| + yield(username, password) + end + run Grack::Server.new(config) + end + end + + end +end diff --git a/lib/grack/lib/grack/git.rb b/lib/grack/lib/grack/git.rb new file mode 100644 index 000000000..cf5362c20 --- /dev/null +++ b/lib/grack/lib/grack/git.rb @@ -0,0 +1,85 @@ +module Grack + class Git + attr_reader :repo + + def initialize(git_path, repo_path) + @git_path = git_path + @repo = repo_path + end + + def update_server_info + execute(%W(update-server-info)) + end + + def command(cmd) + [@git_path || 'git'] + cmd + end + + def capture(cmd) + # _Not_ the same as `IO.popen(...).read` + # By using a block we tell IO.popen to close (wait for) the child process + # after we are done reading its output. + if RUBY_VERSION.start_with?("2") + IO.popen(popen_env, cmd, popen_options) { |p| p.read } + else + IO.popen(cmd, popen_options) { |p| p.read } + end + end + + def execute(cmd) + cmd = command(cmd) + if block_given? + + if RUBY_VERSION.start_with?("2") + IO.popen(popen_env, cmd, File::RDWR, popen_options) do |pipe| + yield(pipe) + end + else + IO.popen(cmd, File::RDWR, popen_options) do |pipe| + yield(pipe) + end + end + else + capture(cmd).chomp + end + end + + def popen_options + { chdir: repo, unsetenv_others: true } + end + + def popen_env + { 'PATH' => ENV['PATH'], 'GL_ID' => ENV['GL_ID'] } + end + + def config_setting(service_name) + service_name = service_name.gsub('-', '') + setting = config("http.#{service_name}") + + if service_name == 'uploadpack' + setting != 'false' + else + setting == 'true' + end + end + + def config(config_name) + execute(%W(config #{config_name})) + end + + def valid_repo? + return false unless File.exists?(repo) && File.realpath(repo) == repo + + match = execute(%W(rev-parse --git-dir)).match(/\.$|\.git$/) + + if RUBY_VERSION.start_with?("2") + if match.to_s == '.git' + # Since the parent could be a git repo, we want to make sure the actual repo contains a git dir. + return false unless Dir.entries(repo).include?('.git') + end + end + + match + end + end +end diff --git a/lib/grack/lib/grack/server.rb b/lib/grack/lib/grack/server.rb new file mode 100644 index 000000000..6b4fe8801 --- /dev/null +++ b/lib/grack/lib/grack/server.rb @@ -0,0 +1,308 @@ +require 'zlib' +require 'rack/request' +require 'rack/response' +require 'rack/utils' +require 'time' + +require 'grack/git' + +module Grack + class Server + attr_reader :git + + SERVICES = [ + ["POST", 'service_rpc', "(.*?)/git-upload-pack$", 'upload-pack'], + ["POST", 'service_rpc', "(.*?)/git-receive-pack$", 'receive-pack'], + + ["GET", 'get_info_refs', "(.*?)/info/refs$"], + ["GET", 'get_text_file', "(.*?)/HEAD$"], + ["GET", 'get_text_file', "(.*?)/objects/info/alternates$"], + ["GET", 'get_text_file', "(.*?)/objects/info/http-alternates$"], + ["GET", 'get_info_packs', "(.*?)/objects/info/packs$"], + ["GET", 'get_text_file', "(.*?)/objects/info/[^/]*$"], + ["GET", 'get_loose_object', "(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"], + ["GET", 'get_pack_file', "(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"], + ["GET", 'get_idx_file', "(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"], + ] + + def initialize(config = false) + set_config(config) + end + + def set_config(config) + @config = config || {} + end + + def set_config_setting(key, value) + @config[key] = value + end + + def call(env) + dup._call(env) + end + + def _call(env) + @env = env + @req = Rack::Request.new(env) + + cmd, path, @reqfile, @rpc = match_routing + + return render_method_not_allowed if cmd == 'not_allowed' + return render_not_found unless cmd + + @git = get_git(env["REP_PATH"] || path) + return render_not_found unless git.valid_repo? + + self.method(cmd).call + end + + # --------------------------------- + # actual command handling functions + # --------------------------------- + + # Uses chunked (streaming) transfer, otherwise response + # blocks to calculate Content-Length header + # http://en.wikipedia.org/wiki/Chunked_transfer_encoding + + CRLF = "\r\n" + + def service_rpc + return render_no_access unless has_access?(@rpc, true) + + input = read_body + + @res = Rack::Response.new + @res.status = 200 + @res["Content-Type"] = "application/x-git-%s-result" % @rpc + @res["Transfer-Encoding"] = "chunked" + @res["Cache-Control"] = "no-cache" + + @res.finish do + git.execute([@rpc, '--stateless-rpc', git.repo]) do |pipe| + pipe.write(input) + pipe.close_write + + while block = pipe.read(8192) # 8KB at a time + @res.write encode_chunk(block) # stream it to the client + end + + @res.write terminating_chunk + end + end + end + + def encode_chunk(chunk) + size_in_hex = chunk.size.to_s(16) + [size_in_hex, CRLF, chunk, CRLF].join + end + + def terminating_chunk + [0, CRLF, CRLF].join + end + + def get_info_refs + service_name = get_service_type + return dumb_info_refs unless has_access?(service_name) + + refs = git.execute([service_name, '--stateless-rpc', '--advertise-refs', git.repo]) + + @res = Rack::Response.new + @res.status = 200 + @res["Content-Type"] = "application/x-git-%s-advertisement" % service_name + hdr_nocache + + @res.write(pkt_write("# service=git-#{service_name}\n")) + @res.write(pkt_flush) + @res.write(refs) + + @res.finish + end + + def dumb_info_refs + git.update_server_info + send_file(@reqfile, "text/plain; charset=utf-8") do + hdr_nocache + end + end + + def get_info_packs + # objects/info/packs + send_file(@reqfile, "text/plain; charset=utf-8") do + hdr_nocache + end + end + + def get_loose_object + send_file(@reqfile, "application/x-git-loose-object") do + hdr_cache_forever + end + end + + def get_pack_file + send_file(@reqfile, "application/x-git-packed-objects") do + hdr_cache_forever + end + end + + def get_idx_file + send_file(@reqfile, "application/x-git-packed-objects-toc") do + hdr_cache_forever + end + end + + def get_text_file + send_file(@reqfile, "text/plain") do + hdr_nocache + end + end + + # ------------------------ + # logic helping functions + # ------------------------ + + # some of this borrowed from the Rack::File implementation + def send_file(reqfile, content_type) + reqfile = File.join(git.repo, reqfile) + return render_not_found unless File.exists?(reqfile) + + return render_not_found unless reqfile == File.realpath(reqfile) + + # reqfile looks legit: no path traversal, no leading '|' + + @res = Rack::Response.new + @res.status = 200 + @res["Content-Type"] = content_type + @res["Last-Modified"] = File.mtime(reqfile).httpdate + + yield + + if size = File.size?(reqfile) + @res["Content-Length"] = size.to_s + @res.finish do + File.open(reqfile, "rb") do |file| + while part = file.read(8192) + @res.write part + end + end + end + else + body = [File.read(reqfile)] + size = Rack::Utils.bytesize(body.first) + @res["Content-Length"] = size + @res.write body + @res.finish + end + end + + def get_git(path) + # root = @config[:project_root] || Dir.pwd + # path = File.join(root, path) + Grack::Git.new(@config[:git_path], path) + end + + def get_service_type + service_type = @req.params['service'] + return false unless service_type + return false if service_type[0, 4] != 'git-' + service_type.gsub('git-', '') + end + + def match_routing + cmd = nil + path = nil + + SERVICES.each do |method, handler, match, rpc| + next unless m = Regexp.new(match).match(@req.path_info) + + return ['not_allowed'] unless method == @req.request_method + + cmd = handler + path = m[1] + file = @req.path_info.sub(path + '/', '') + + return [cmd, path, file, rpc] + end + + nil + end + + def has_access?(rpc, check_content_type = false) + if check_content_type + conten_type = "application/x-git-%s-request" % rpc + return false unless @req.content_type == conten_type + end + + return false unless ['upload-pack', 'receive-pack'].include?(rpc) + + if rpc == 'receive-pack' + return @config[:receive_pack] if @config.include?(:receive_pack) + end + + if rpc == 'upload-pack' + return @config[:upload_pack] if @config.include?(:upload_pack) + end + + git.config_setting(rpc) + end + + def read_body + if @env["HTTP_CONTENT_ENCODING"] =~ /gzip/ + Zlib::GzipReader.new(@req.body).read + else + @req.body.read + end + end + + # -------------------------------------- + # HTTP error response handling functions + # -------------------------------------- + + PLAIN_TYPE = { "Content-Type" => "text/plain" } + + def render_method_not_allowed + if @env['SERVER_PROTOCOL'] == "HTTP/1.1" + [405, PLAIN_TYPE, ["Method Not Allowed"]] + else + [400, PLAIN_TYPE, ["Bad Request"]] + end + end + + def render_not_found + [404, PLAIN_TYPE, ["Not Found"]] + end + + def render_no_access + [403, PLAIN_TYPE, ["Forbidden"]] + end + + + # ------------------------------ + # packet-line handling functions + # ------------------------------ + + def pkt_flush + '0000' + end + + def pkt_write(str) + (str.size + 4).to_s(16).rjust(4, '0') + str + end + + # ------------------------ + # header writing functions + # ------------------------ + + def hdr_nocache + @res["Expires"] = "Fri, 01 Jan 1980 00:00:00 GMT" + @res["Pragma"] = "no-cache" + @res["Cache-Control"] = "no-cache, max-age=0, must-revalidate" + end + + def hdr_cache_forever + now = Time.now().to_i + @res["Date"] = now.to_s + @res["Expires"] = (now + 31536000).to_s; + @res["Cache-Control"] = "public, max-age=31536000"; + end + end +end diff --git a/lib/grack/lib/grack/version.rb b/lib/grack/lib/grack/version.rb new file mode 100644 index 000000000..66a1e1b41 --- /dev/null +++ b/lib/grack/lib/grack/version.rb @@ -0,0 +1,3 @@ +module Grack + VERSION = "2.0.2" +end diff --git a/lib/grack/tests/main_test.rb b/lib/grack/tests/main_test.rb new file mode 100644 index 000000000..cf70296ec --- /dev/null +++ b/lib/grack/tests/main_test.rb @@ -0,0 +1,264 @@ +require 'rack' +require 'rack/test' +require 'test/unit' +require 'mocha' +require 'digest/sha1' + +require_relative '../lib/grack/server.rb' +require_relative '../lib/grack/git.rb' +require 'pp' + +class GitHttpTest < Test::Unit::TestCase + include Rack::Test::Methods + + def example + File.expand_path(File.dirname(__FILE__)) + end + + def app + config = { + :project_root => example, + :upload_pack => true, + :receive_pack => true, + } + Grack::Server.new(config) + end + + def test_upload_pack_advertisement + get "/example/info/refs?service=git-upload-pack" + assert_equal 200, r.status + assert_equal "application/x-git-upload-pack-advertisement", r.headers["Content-Type"] + assert_equal "001e# service=git-upload-pack", r.body.split("\n").first + assert_match 'multi_ack_detailed', r.body + end + + def test_no_access_wrong_content_type_up + post "/example/git-upload-pack" + assert_equal 403, r.status + end + + def test_no_access_wrong_content_type_rp + post "/example/git-receive-pack" + assert_equal 403, r.status + end + + def test_no_access_wrong_method_rcp + get "/example/git-upload-pack" + assert_equal 400, r.status + end + + def test_no_access_wrong_command_rcp + post "/example/git-upload-packfile" + assert_equal 404, r.status + end + + def test_no_access_wrong_path_rcp + Grack::Git.any_instance.stubs(:valid_repo?).returns(false) + post "/example-wrong/git-upload-pack" + assert_equal 404, r.status + end + + def test_upload_pack_rpc + Grack::Git.any_instance.stubs(:valid_repo?).returns(true) + IO.stubs(:popen).returns(MockProcess.new) + post "/example/git-upload-pack", {}, {"CONTENT_TYPE" => "application/x-git-upload-pack-request"} + assert_equal 200, r.status + assert_equal "application/x-git-upload-pack-result", r.headers["Content-Type"] + end + + def test_receive_pack_advertisement + get "/example/info/refs?service=git-receive-pack" + assert_equal 200, r.status + assert_equal "application/x-git-receive-pack-advertisement", r.headers["Content-Type"] + assert_equal "001f# service=git-receive-pack", r.body.split("\n").first + assert_match 'report-status', r.body + assert_match 'delete-refs', r.body + assert_match 'ofs-delta', r.body + end + + def test_recieve_pack_rpc + Grack::Git.any_instance.stubs(:valid_repo?).returns(true) + IO.stubs(:popen).yields(MockProcess.new) + post "/example/git-receive-pack", {}, {"CONTENT_TYPE" => "application/x-git-receive-pack-request"} + assert_equal 200, r.status + assert_equal "application/x-git-receive-pack-result", r.headers["Content-Type"] + end + + def test_info_refs_dumb + get "/example/.git/info/refs" + assert_equal 200, r.status + end + + def test_info_packs + get "/example/.git/objects/info/packs" + assert_equal 200, r.status + assert_match /P pack-(.*?).pack/, r.body + end + + def test_loose_objects + path, content = write_test_objects + get "/example/.git/objects/#{path}" + assert_equal 200, r.status + assert_equal content, r.body + remove_test_objects + end + + def test_pack_file + path, content = write_test_objects + get "/example/.git/objects/pack/pack-#{content}.pack" + assert_equal 200, r.status + assert_equal content, r.body + remove_test_objects + end + + def test_index_file + path, content = write_test_objects + get "/example/.git/objects/pack/pack-#{content}.idx" + assert_equal 200, r.status + assert_equal content, r.body + remove_test_objects + end + + def test_text_file + get "/example/.git/HEAD" + assert_equal 200, r.status + assert_equal 41, r.body.size # submodules have detached head + end + + def test_no_size_avail + File.stubs('size?').returns(false) + get "/example/.git/HEAD" + assert_equal 200, r.status + assert_equal 46, r.body.size # submodules have detached head + end + + def test_config_upload_pack_off + a1 = app + a1.set_config_setting(:upload_pack, false) + session = Rack::Test::Session.new(a1) + session.get "/example/info/refs?service=git-upload-pack" + assert_equal 404, session.last_response.status + end + + def test_config_receive_pack_off + a1 = app + a1.set_config_setting(:receive_pack, false) + session = Rack::Test::Session.new(a1) + session.get "/example/info/refs?service=git-receive-pack" + assert_equal 404, session.last_response.status + end + + def test_config_bad_service + get "/example/info/refs?service=git-receive-packfile" + assert_equal 404, r.status + end + + def test_git_config_receive_pack + app1 = Grack::Server.new({:project_root => example}) + app1.instance_variable_set(:@git, Grack::Git.new('git', example )) + session = Rack::Test::Session.new(app1) + git = Grack::Git + git.any_instance.stubs(:config).with('http.receivepack').returns('') + session.get "/example/info/refs?service=git-receive-pack" + assert_equal 404, session.last_response.status + + git.any_instance.stubs(:config).with('http.receivepack').returns('true') + session.get "/example/info/refs?service=git-receive-pack" + assert_equal 200, session.last_response.status + + git.any_instance.stubs(:config).with('http.receivepack').returns('false') + session.get "/example/info/refs?service=git-receive-pack" + assert_equal 404, session.last_response.status + end + + def test_git_config_upload_pack + app1 = Grack::Server.new({:project_root => example}) + # app1.instance_variable_set(:@git, Grack::Git.new('git', example )) + session = Rack::Test::Session.new(app1) + git = Grack::Git + git.any_instance.stubs(:config).with('http.uploadpack').returns('') + session.get "/example/info/refs?service=git-upload-pack" + assert_equal 200, session.last_response.status + + git.any_instance.stubs(:config).with('http.uploadpack').returns('true') + session.get "/example/info/refs?service=git-upload-pack" + assert_equal 200, session.last_response.status + + git.any_instance.stubs(:config).with('http.uploadpack').returns('false') + session.get "/example/info/refs?service=git-upload-pack" + assert_equal 404, session.last_response.status + end + + def test_send_file + app1 = app + app1.instance_variable_set(:@git, Grack::Git.new('git', Dir.pwd)) + # Reject path traversal + assert_equal 404, app1.send_file('tests/../tests', 'text/plain').first + # Reject paths starting with '|', avoid File.read('|touch /tmp/pawned; ls /tmp') + assert_equal 404, app1.send_file('|tests', 'text/plain').first + end + + def test_get_git + # Guard against non-existent directories + git1 = Grack::Git.new('git', 'foobar') + assert_equal false, git1.valid_repo? + # Guard against path traversal + git2 = Grack::Git.new('git', '/../tests') + assert_equal false, git2.valid_repo? + end + + private + + def r + last_response + end + + def write_test_objects + content = Digest::SHA1.hexdigest('gitrocks') + base = File.join(File.expand_path(File.dirname(__FILE__)), 'example', '.git', 'objects') + obj = File.join(base, '20') + Dir.mkdir(obj) rescue nil + file = File.join(obj, content[0, 38]) + File.open(file, 'w') { |f| f.write(content) } + pack = File.join(base, 'pack', "pack-#{content}.pack") + File.open(pack, 'w') { |f| f.write(content) } + idx = File.join(base, 'pack', "pack-#{content}.idx") + File.open(idx, 'w') { |f| f.write(content) } + ["20/#{content[0,38]}", content] + end + + def remove_test_objects + content = Digest::SHA1.hexdigest('gitrocks') + base = File.join(File.expand_path(File.dirname(__FILE__)), 'example', '.git', 'objects') + obj = File.join(base, '20') + file = File.join(obj, content[0, 38]) + pack = File.join(base, 'pack', "pack-#{content}.pack") + idx = File.join(base, 'pack', "pack-#{content}.idx") + File.unlink(file) + File.unlink(pack) + File.unlink(idx) + end + +end + +class MockProcess + def initialize + @counter = 0 + end + + def write(data) + end + + def read(data = nil) + '' + end + + def eof? + @counter += 1 + @counter > 1 ? true : false + end + + def close_write + true + end +end diff --git a/lib/rails_kindeditor/app/controllers/kindeditor/assets_controller.rb b/lib/rails_kindeditor/app/controllers/kindeditor/assets_controller.rb index 0e1177563..d7d5948d4 100644 --- a/lib/rails_kindeditor/app/controllers/kindeditor/assets_controller.rb +++ b/lib/rails_kindeditor/app/controllers/kindeditor/assets_controller.rb @@ -13,7 +13,7 @@ class Kindeditor::AssetsController < ApplicationController logger.warn '========= Warning: the owner_id is 0, "delete uploaded files automatically" will not work. =========' if defined?(logger) && @asset.owner_id == 0 @asset.asset_type = @dir if @asset.save - render :text => ({:error => 0, :url => @asset.asset.url,:asset_id => @asset.id}.to_json) + render :text => ({:error => 0, :url => "http://"+Setting.host_name + "/" + @asset.asset.url,:asset_id => @asset.id}.to_json) else show_error(@asset.errors.full_messages) end diff --git a/lib/rails_kindeditor/lib/rails_kindeditor/helper.rb b/lib/rails_kindeditor/lib/rails_kindeditor/helper.rb index d5f91ebf8..eef2eb576 100644 --- a/lib/rails_kindeditor/lib/rails_kindeditor/helper.rb +++ b/lib/rails_kindeditor/lib/rails_kindeditor/helper.rb @@ -7,7 +7,11 @@ module RailsKindeditor input_html = input_html.merge(style: 'display:none') output = ActiveSupport::SafeBuffer.new output << text_area_tag(name, content, input_html) - output << javascript_tag(js_replace(id, options.merge(window_onload: 'true'))) + output << javascript_tag(js_replace(id, options.merge(window_onload: 'true', + :autoHeightMode=>true, + afterCreate: 'eval(function(){enablePasteImg(self);this.loadPlugin("autoheight")})', + emotionsBasePath: 'http://' + Setting.host_name + ))) end def kindeditor(name, method, options = {}) @@ -17,7 +21,10 @@ module RailsKindeditor output_buffer = ActiveSupport::SafeBuffer.new output_buffer << build_text_area_tag(name, method, self, options, input_html) output_buffer << javascript_tag(js_replace(input_html['id'],options.merge(window_onload: 'true', - afterCreate: 'eval(function(){enablePasteImg(self);})'))) + :autoHeightMode=>true, + afterCreate: 'eval(function(){enablePasteImg(self);this.loadPlugin("autoheight")})', + emotionsBasePath: 'http://' + Setting.host_name + ))) end def kindeditor_upload_json_path(*args) diff --git a/lib/redmine.rb b/lib/redmine.rb index 0f6c14b8a..8ebdacfa6 100644 --- a/lib/redmine.rb +++ b/lib/redmine.rb @@ -369,6 +369,7 @@ Redmine::MenuManager.map :admin_menu do |menu| menu.push :projects, {:controller => 'admin', :action => 'projects'}, :caption => :label_project_plural menu.push :courses, {:controller => 'admin', :action => 'courses'}, :caption => :label_course_all menu.push :users, {:controller => 'admin', :action => 'users'}, :caption => :label_user_plural + menu.push :messages, {:controller => 'admin', :action => 'messages'}, :caption => :label_system_message menu.push :schools, {:controller => 'admin', :action => 'schools'}, :caption => :label_school_plural menu.push :first_page_made, {:controller => 'admin',:action => 'first_page_made'},:caption => :label_first_page_made menu.push :mobile_version, {:controller => 'admin',:action => 'mobile_version'},:caption => :label_mobile_version @@ -386,6 +387,11 @@ Redmine::MenuManager.map :admin_menu do |menu| :html => {:class => 'server_authentication'} menu.push :plugins, {:controller => 'admin', :action => 'plugins'}, :last => true menu.push :info, {:controller => 'admin', :action => 'info'}, :caption => :label_information_plural, :last => true + menu.push :leave_messages, {:controller => 'admin', :action => 'leave_messages'}, :caption => :label_leave_message_list + menu.push :messages_list, {:controller => 'admin', :action => 'messages_list'}, :caption => :label_message_plural + menu.push :notices, {:controller => 'admin', :action => 'notices'}, :caption => :label_notification_list + menu.push :latest_login_users, {:controller => 'admin', :action => 'latest_login_users'}, :caption => :label_latest_login_user_list + menu.push :homework, {:controller => 'admin', :action => 'homework'}, :caption => :label_user_homework end #Modified by young diff --git a/lib/tasks/homework_endtime.rake b/lib/tasks/homework_endtime.rake new file mode 100644 index 000000000..d5d894122 --- /dev/null +++ b/lib/tasks/homework_endtime.rake @@ -0,0 +1,18 @@ +#coding=utf-8 + +namespace :homework_endtime do + desc "send a message for Job deadline" + task :message => :environment do + contrast_time = Time.now - 86400 + homework_commons = HomeworkCommon.where("end_time >=? and end_time <=?",contrast_time, Time.now) + homework_commons.each do |homework_common| + if CourseMessage.where("course_message_type =? and course_message_id =? and status =?", "HomeworkCommon", homework_common.id, 1).first.nil? + homework_common.course.student.each do |s| + homework_common.course_messages << CourseMessage.new(:user_id => s.student_id, :course_id => homework_common.course_id, :viewed => false, :status => true) + # 发送邮件通知 + Mailer.homework_endtime__added(homework_common, s.student_id).deliver + end + end + end + end +end diff --git a/lib/tasks/homework_evaluation.rake b/lib/tasks/homework_evaluation.rake new file mode 100644 index 000000000..6cf4dd6da --- /dev/null +++ b/lib/tasks/homework_evaluation.rake @@ -0,0 +1,77 @@ +#coding=utf-8 + +namespace :homework_evaluation do + desc "start and end evaluation" + def get_assigned_homeworks(student_works, n, index) + student_works += student_works + student_works[index + 1 .. index + n] + end + #自动开启匿评的任务 + task :start_evaluation => :environment do + homework_detail_manuals = HomeworkDetailManual.where("evaluation_start = '#{Date.today}'") + homework_detail_manuals.each do |homework_detail_manual| + homework_common = homework_detail_manual.homework_common + if homework_detail_manual.comment_status == 1 #新建状态才可开启匿评 + student_works = homework_common.student_works + if student_works && student_works.size >= 2 + student_works.each_with_index do |work, index| + user = work.user + n = homework_detail_manual.evaluation_num + n = n < student_works.size ? n : student_works.size - 1 + assigned_homeworks = get_assigned_homeworks(student_works, n, index) + assigned_homeworks.each do |h| + student_works_evaluation_distributions = StudentWorksEvaluationDistribution.new(user_id: user.id, student_work_id: h.id) + student_works_evaluation_distributions.save + end + end + homework_detail_manual.update_column('comment_status', 2) + # 匿评开启消息邮件通知,# 所有人 + #send_message_anonymous_comment(homework_common, 2) + course = homework_common.course + course.members.each do |m| + homework_common.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => false, :status => 2) + end + # 邮件通知 + Mailer.send_mail_anonymous_comment_open(homework_common).deliver + else + #作业数小于2,启动失败, 只给老师发 + # status==4 发送失败 + # 匿评开启消息邮件通知,# 所有人 + course = homework_common.course + course.members.each do |m| + if m.user.allowed_to?(:as_teacher,course) + homework_common.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => false, :status => 4) + end + end + # 邮件通知 + Mailer.send_mail_anonymous_comment_fail(homework_common).deliver + end + end + end + end + + #自动关闭匿评的任务 + task :end_evaluation => :environment do + homework_detail_manuals = HomeworkDetailManual.where("evaluation_end = '#{Date.today}'") + homework_detail_manuals.each do |homework_detail_manual| + homework_common = homework_detail_manual.homework_common + if homework_detail_manual.comment_status == 2 #开启匿评状态才可关闭匿评 + #计算缺评扣分 + work_ids = "(" + homework_common.student_works.map(&:id).join(",") + ")" + homework_common.student_works.each do |student_work| + absence_penalty_count = student_work.user.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count - student_work.user.student_works_scores.where("student_work_id IN #{work_ids}").count + student_work.absence_penalty = absence_penalty_count > 0 ? absence_penalty_count * homework_detail_manuals.absence_penalty : 0 + student_work.save + end + homework_detail_manual.update_column('comment_status', 3) + # 匿评关闭消息通知 给所有人发 + course = homework_common.course + course.members.each do |m| + homework_common.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => false, :status => 3) + end + # 邮件通知 + Mailer.send_mail_anonymous_comment_close(homework_common).deliver + end + end + end +end diff --git a/lib/tasks/issue_due_date.rake b/lib/tasks/issue_due_date.rake new file mode 100644 index 000000000..f40fa290f --- /dev/null +++ b/lib/tasks/issue_due_date.rake @@ -0,0 +1,21 @@ +#coding=utf-8 +namespace :issue_due_date do + desc "send a message for Issue'due_date deadline" + task :end_time => :environment do + contrast_time = Time.now - 86400 + issues = Issue.where("due_date >=? and due_date <=?",contrast_time,Time.now) + issues.each do |issue| + if ForgeMessage.where("forge_message_type =? and forge_message_id =? and status =?", "Issue", issue.id, 1).first.nil? + recipients = [] + assigner = User.find(issue.assigned_to_id) + recipients << issue.author + recipients << assigner + recipients.each do |r| + issue.forge_messages << ForgeMessage.new(:user_id => r.id, :project_id => issue.project_id, :viewed => false, :status => 1) + # 发送邮件通知 + # Mailer.homework_endtime__added(homework_common, s.student_id).deliver + end + end + end + end +end diff --git a/lib/trustie.rb b/lib/trustie.rb index 4f1f68fe1..2010e2d43 100644 --- a/lib/trustie.rb +++ b/lib/trustie.rb @@ -1,3 +1,4 @@ require 'trustie/utils' require 'trustie/utils/image' require 'trustie/gitlab/api' +require 'trustie/grack/grack' diff --git a/lib/trustie/grack/auth.rb b/lib/trustie/grack/auth.rb new file mode 100644 index 000000000..5464b18ca --- /dev/null +++ b/lib/trustie/grack/auth.rb @@ -0,0 +1,103 @@ +#coding=utf-8 +# +require 'rack/auth/basic' +require 'rack/auth/abstract/handler' +require 'rack/auth/abstract/request' + +module Grack + + class Auth < Rack::Auth::Basic + DOWNLOAD_COMMANDS = %w{ git-upload-pack git-upload-archive } + PUSH_COMMANDS = %w{ git-receive-pack } + + attr_accessor :user, :repository + def call(env) + @env = env + @request = Rack::Request.new(env) + @auth = Request.new(env) + + if not @auth.provided? + unauthorized + elsif not @auth.basic? + bad_request + else + result = if (access = valid?(@auth) and access == true) + @env['REMOTE_USER'] = @auth.username + env['REP_PATH'] = repository.root_url + @app.call(env) + else + if access == '404' + render_not_found + elsif access == '403' + #render_no_access + unauthorized + else + unauthorized + end + end + result + end + end# method call + + + def render_not_found + [404, {"Content-Type" => "text/plain"}, ["Not Found"]] + end + + def valid?(auth) + self.repository = auth_rep + return "404" unless repository + username, password = auth.credentials + self.user = auth_user(username, password) + return '403' unless user + access = auth_request + puts "access #{access}" + access + end + + def auth_rep + rep = nil + match = @request.path_info.match(/(\/.+\.git)\//) + if match + rep = Repository.where("root_url like ?", "%#{match[1]}").first + end + rep + end + + def auth_user(username, password) + u, last_login_on = User.try_to_login(username, password) + unless u && (u.member_of?(repository.project) || u.admin?) + u = nil + end + u + end + + def auth_request + case git_cmd + when *DOWNLOAD_COMMANDS + user != nil + when *PUSH_COMMANDS + unless user + false + else + ### 只有Manager和Development才有push权限 + repository.project.members.where(user_id: user.id).first.roles.any?{|r| r.name == 'Manager' || r.name == 'Developer'} + end + else + false + end + end + + def git_cmd + if @request.get? + @request.params['service'] + elsif @request.post? + File.basename(@request.path) + else + nil + end + end + + end# class Auth +end# module Grack + diff --git a/lib/trustie/grack/grack.rb b/lib/trustie/grack/grack.rb new file mode 100644 index 000000000..1dc4bdc0d --- /dev/null +++ b/lib/trustie/grack/grack.rb @@ -0,0 +1,18 @@ +require_relative 'auth' + +module Trustie + module Grack + + def self.new + Rack::Builder.new do + use ::Grack::Auth + run ::Grack::Server.new( + project_root: Redmine::Configuration['repository_root_path'] || "/home/pdl/redmine-2.3.2-0/apache2/htdocs", + upload_pack: true, + receive_pack:true + ) + end + end + + end +end diff --git a/public/assets/codemirror/clike.js b/public/assets/codemirror/clike.js new file mode 100644 index 000000000..e13b79c14 --- /dev/null +++ b/public/assets/codemirror/clike.js @@ -0,0 +1,604 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("clike", function(config, parserConfig) { + var indentUnit = config.indentUnit, + statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, + dontAlignCalls = parserConfig.dontAlignCalls, + keywords = parserConfig.keywords || {}, + types = parserConfig.types || {}, + builtin = parserConfig.builtin || {}, + blockKeywords = parserConfig.blockKeywords || {}, + defKeywords = parserConfig.defKeywords || {}, + atoms = parserConfig.atoms || {}, + hooks = parserConfig.hooks || {}, + multiLineStrings = parserConfig.multiLineStrings, + indentStatements = parserConfig.indentStatements !== false, + indentSwitch = parserConfig.indentSwitch !== false, + namespaceSeparator = parserConfig.namespaceSeparator; + var isOperatorChar = /[+\-*&%=<>!?|\/]/; + + var curPunc, isDefKeyword; + + function tokenBase(stream, state) { + var ch = stream.next(); + if (hooks[ch]) { + var result = hooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + curPunc = ch; + return null; + } + if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + return "number"; + } + if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + } + if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "operator"; + } + stream.eatWhile(/[\w\$_\xa1-\uffff]/); + if (namespaceSeparator) while (stream.match(namespaceSeparator)) + stream.eatWhile(/[\w\$_\xa1-\uffff]/); + + var cur = stream.current(); + if (keywords.propertyIsEnumerable(cur)) { + if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; + if (defKeywords.propertyIsEnumerable(cur)) isDefKeyword = true; + return "keyword"; + } + if (types.propertyIsEnumerable(cur)) return "variable-3"; + if (builtin.propertyIsEnumerable(cur)) { + if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; + return "builtin"; + } + if (atoms.propertyIsEnumerable(cur)) return "atom"; + return "variable"; + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) {end = true; break;} + escaped = !escaped && next == "\\"; + } + if (end || !(escaped || multiLineStrings)) + state.tokenize = null; + return "string"; + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + function Context(indented, column, type, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.align = align; + this.prev = prev; + } + function isStatement(type) { + return type == "statement" || type == "switchstatement" || type == "namespace"; + } + function pushContext(state, col, type) { + var indent = state.indented; + if (state.context && isStatement(state.context.type) && !isStatement(type)) + indent = state.context.indented; + return state.context = new Context(indent, col, type, null, state.context); + } + function popContext(state) { + var t = state.context.type; + if (t == ")" || t == "]" || t == "}") + state.indented = state.context.indented; + return state.context = state.context.prev; + } + + function typeBefore(stream, state) { + if (state.prevToken == "variable" || state.prevToken == "variable-3") return true; + if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, stream.start))) return true; + } + + function isTopScope(context) { + for (;;) { + if (!context || context.type == "top") return true; + if (context.type == "}" && context.prev.type != "namespace") return false; + context = context.prev; + } + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: null, + context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), + indented: 0, + startOfLine: true, + prevToken: null + }; + }, + + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + } + if (stream.eatSpace()) return null; + curPunc = isDefKeyword = null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style == "comment" || style == "meta") return style; + if (ctx.align == null) ctx.align = true; + + if ((curPunc == ";" || curPunc == ":" || curPunc == ",")) + while (isStatement(state.context.type)) popContext(state); + else if (curPunc == "{") pushContext(state, stream.column(), "}"); + else if (curPunc == "[") pushContext(state, stream.column(), "]"); + else if (curPunc == "(") pushContext(state, stream.column(), ")"); + else if (curPunc == "}") { + while (isStatement(ctx.type)) ctx = popContext(state); + if (ctx.type == "}") ctx = popContext(state); + while (isStatement(ctx.type)) ctx = popContext(state); + } + else if (curPunc == ctx.type) popContext(state); + else if (indentStatements && + (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") || + (isStatement(ctx.type) && curPunc == "newstatement"))) { + var type = "statement"; + if (curPunc == "newstatement" && indentSwitch && stream.current() == "switch") + type = "switchstatement"; + else if (style == "keyword" && stream.current() == "namespace") + type = "namespace"; + pushContext(state, stream.column(), type); + } + + if (style == "variable" && + ((state.prevToken == "def" || + (parserConfig.typeFirstDefinitions && typeBefore(stream, state) && + isTopScope(state.context) && stream.match(/^\s*\(/, false))))) + style = "def"; + + if (hooks.token) { + var result = hooks.token(stream, state, style); + if (result !== undefined) style = result; + } + + if (style == "def" && parserConfig.styleDefs === false) style = "variable"; + + state.startOfLine = false; + state.prevToken = isDefKeyword ? "def" : style || curPunc; + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass; + var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); + if (isStatement(ctx.type) && firstChar == "}") ctx = ctx.prev; + var closing = firstChar == ctx.type; + var switchBlock = ctx.prev && ctx.prev.type == "switchstatement"; + if (isStatement(ctx.type)) + return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit); + if (ctx.align && (!dontAlignCalls || ctx.type != ")")) + return ctx.column + (closing ? 0 : 1); + if (ctx.type == ")" && !closing) + return ctx.indented + statementIndentUnit; + + return ctx.indented + (closing ? 0 : indentUnit) + + (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0); + }, + + electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/, + blockCommentStart: "/*", + blockCommentEnd: "*/", + lineComment: "//", + fold: "brace" + }; +}); + + function words(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + var cKeywords = "auto if break case register continue return default do sizeof " + + "static else struct switch extern typedef float union for " + + "goto while enum const volatile"; + var cTypes = "int long char short double float unsigned signed void size_t ptrdiff_t"; + + function cppHook(stream, state) { + if (!state.startOfLine) return false; + for (;;) { + if (stream.skipTo("\\")) { + stream.next(); + if (stream.eol()) { + state.tokenize = cppHook; + break; + } + } else { + stream.skipToEnd(); + state.tokenize = null; + break; + } + } + return "meta"; + } + + function pointerHook(_stream, state) { + if (state.prevToken == "variable-3") return "variable-3"; + return false; + } + + function cpp11StringHook(stream, state) { + stream.backUp(1); + // Raw strings. + if (stream.match(/(R|u8R|uR|UR|LR)/)) { + var match = stream.match(/"([^\s\\()]{0,16})\(/); + if (!match) { + return false; + } + state.cpp11RawStringDelim = match[1]; + state.tokenize = tokenRawString; + return tokenRawString(stream, state); + } + // Unicode strings/chars. + if (stream.match(/(u8|u|U|L)/)) { + if (stream.match(/["']/, /* eat */ false)) { + return "string"; + } + return false; + } + // Ignore this hook. + stream.next(); + return false; + } + + function cppLooksLikeConstructor(word) { + var lastTwo = /(\w+)::(\w+)$/.exec(word); + return lastTwo && lastTwo[1] == lastTwo[2]; + } + + // C#-style strings where "" escapes a quote. + function tokenAtString(stream, state) { + var next; + while ((next = stream.next()) != null) { + if (next == '"' && !stream.eat('"')) { + state.tokenize = null; + break; + } + } + return "string"; + } + + // C++11 raw string literal is "( anything )", where + // can be a string up to 16 characters long. + function tokenRawString(stream, state) { + // Escape characters that have special regex meanings. + var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&'); + var match = stream.match(new RegExp(".*?\\)" + delim + '"')); + if (match) + state.tokenize = null; + else + stream.skipToEnd(); + return "string"; + } + + function def(mimes, mode) { + if (typeof mimes == "string") mimes = [mimes]; + var words = []; + function add(obj) { + if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop)) + words.push(prop); + } + add(mode.keywords); + add(mode.types); + add(mode.builtin); + add(mode.atoms); + if (words.length) { + mode.helperType = mimes[0]; + CodeMirror.registerHelper("hintWords", mimes[0], words); + } + + for (var i = 0; i < mimes.length; ++i) + CodeMirror.defineMIME(mimes[i], mode); + } + + def(["text/x-csrc", "text/x-c", "text/x-chdr"], { + name: "clike", + keywords: words(cKeywords), + types: words(cTypes + " bool _Complex _Bool float_t double_t intptr_t intmax_t " + + "int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t " + + "uint32_t uint64_t"), + blockKeywords: words("case do else for if switch while struct"), + defKeywords: words("struct"), + typeFirstDefinitions: true, + atoms: words("null true false"), + hooks: {"#": cppHook, "*": pointerHook}, + modeProps: {fold: ["brace", "include"]} + }); + + def(["text/x-c++src", "text/x-c++hdr"], { + name: "clike", + keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try explicit new " + + "static_cast typeid catch operator template typename class friend private " + + "this using const_cast inline public throw virtual delete mutable protected " + + "alignas alignof constexpr decltype nullptr noexcept thread_local final " + + "static_assert override"), + types: words(cTypes + " bool wchar_t"), + blockKeywords: words("catch class do else finally for if struct switch try while"), + defKeywords: words("class namespace struct enum union"), + typeFirstDefinitions: true, + atoms: words("true false null"), + hooks: { + "#": cppHook, + "*": pointerHook, + "u": cpp11StringHook, + "U": cpp11StringHook, + "L": cpp11StringHook, + "R": cpp11StringHook, + token: function(stream, state, style) { + if (style == "variable" && stream.peek() == "(" && + (state.prevToken == ";" || state.prevToken == null || + state.prevToken == "}") && + cppLooksLikeConstructor(stream.current())) + return "def"; + } + }, + namespaceSeparator: "::", + modeProps: {fold: ["brace", "include"]} + }); + + def("text/x-java", { + name: "clike", + keywords: words("abstract assert break case catch class const continue default " + + "do else enum extends final finally float for goto if implements import " + + "instanceof interface native new package private protected public " + + "return static strictfp super switch synchronized this throw throws transient " + + "try volatile while"), + types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " + + "Integer Long Number Object Short String StringBuffer StringBuilder Void"), + blockKeywords: words("catch class do else finally for if switch try while"), + defKeywords: words("class interface package enum"), + typeFirstDefinitions: true, + atoms: words("true false null"), + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; + } + }, + modeProps: {fold: ["brace", "import"]} + }); + + def("text/x-csharp", { + name: "clike", + keywords: words("abstract as async await base break case catch checked class const continue" + + " default delegate do else enum event explicit extern finally fixed for" + + " foreach goto if implicit in interface internal is lock namespace new" + + " operator out override params private protected public readonly ref return sealed" + + " sizeof stackalloc static struct switch this throw try typeof unchecked" + + " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + + " global group into join let orderby partial remove select set value var yield"), + types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" + + " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" + + " UInt64 bool byte char decimal double short int long object" + + " sbyte float string ushort uint ulong"), + blockKeywords: words("catch class do else finally for foreach if struct switch try while"), + defKeywords: words("class interface namespace struct var"), + typeFirstDefinitions: true, + atoms: words("true false null"), + hooks: { + "@": function(stream, state) { + if (stream.eat('"')) { + state.tokenize = tokenAtString; + return tokenAtString(stream, state); + } + stream.eatWhile(/[\w\$_]/); + return "meta"; + } + } + }); + + function tokenTripleString(stream, state) { + var escaped = false; + while (!stream.eol()) { + if (!escaped && stream.match('"""')) { + state.tokenize = null; + break; + } + escaped = stream.next() == "\\" && !escaped; + } + return "string"; + } + + def("text/x-scala", { + name: "clike", + keywords: words( + + /* scala */ + "abstract case catch class def do else extends false final finally for forSome if " + + "implicit import lazy match new null object override package private protected return " + + "sealed super this throw trait try type val var while with yield _ : = => <- <: " + + "<% >: # @ " + + + /* package scala */ + "assert assume require print println printf readLine readBoolean readByte readShort " + + "readChar readInt readLong readFloat readDouble " + + + ":: #:: " + ), + types: words( + "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " + + "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " + + "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " + + "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " + + "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " + + + /* package java.lang */ + "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" + ), + multiLineStrings: true, + blockKeywords: words("catch class do else finally for forSome if match switch try while"), + defKeywords: words("class def object package trait type val var"), + atoms: words("true false null"), + indentStatements: false, + indentSwitch: false, + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; + }, + '"': function(stream, state) { + if (!stream.match('""')) return false; + state.tokenize = tokenTripleString; + return state.tokenize(stream, state); + }, + "'": function(stream) { + stream.eatWhile(/[\w\$_\xa1-\uffff]/); + return "atom"; + } + }, + modeProps: {closeBrackets: {triples: '"'}} + }); + + def(["x-shader/x-vertex", "x-shader/x-fragment"], { + name: "clike", + keywords: words("sampler1D sampler2D sampler3D samplerCube " + + "sampler1DShadow sampler2DShadow " + + "const attribute uniform varying " + + "break continue discard return " + + "for while do if else struct " + + "in out inout"), + types: words("float int bool void " + + "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " + + "mat2 mat3 mat4"), + blockKeywords: words("for while do if else struct"), + builtin: words("radians degrees sin cos tan asin acos atan " + + "pow exp log exp2 sqrt inversesqrt " + + "abs sign floor ceil fract mod min max clamp mix step smoothstep " + + "length distance dot cross normalize ftransform faceforward " + + "reflect refract matrixCompMult " + + "lessThan lessThanEqual greaterThan greaterThanEqual " + + "equal notEqual any all not " + + "texture1D texture1DProj texture1DLod texture1DProjLod " + + "texture2D texture2DProj texture2DLod texture2DProjLod " + + "texture3D texture3DProj texture3DLod texture3DProjLod " + + "textureCube textureCubeLod " + + "shadow1D shadow2D shadow1DProj shadow2DProj " + + "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " + + "dFdx dFdy fwidth " + + "noise1 noise2 noise3 noise4"), + atoms: words("true false " + + "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " + + "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " + + "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " + + "gl_FogCoord gl_PointCoord " + + "gl_Position gl_PointSize gl_ClipVertex " + + "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " + + "gl_TexCoord gl_FogFragCoord " + + "gl_FragCoord gl_FrontFacing " + + "gl_FragData gl_FragDepth " + + "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " + + "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " + + "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " + + "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " + + "gl_ProjectionMatrixInverseTranspose " + + "gl_ModelViewProjectionMatrixInverseTranspose " + + "gl_TextureMatrixInverseTranspose " + + "gl_NormalScale gl_DepthRange gl_ClipPlane " + + "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " + + "gl_FrontLightModelProduct gl_BackLightModelProduct " + + "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " + + "gl_FogParameters " + + "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " + + "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " + + "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " + + "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " + + "gl_MaxDrawBuffers"), + indentSwitch: false, + hooks: {"#": cppHook}, + modeProps: {fold: ["brace", "include"]} + }); + + def("text/x-nesc", { + name: "clike", + keywords: words(cKeywords + "as atomic async call command component components configuration event generic " + + "implementation includes interface module new norace nx_struct nx_union post provides " + + "signal task uses abstract extends"), + types: words(cTypes), + blockKeywords: words("case do else for if switch while struct"), + atoms: words("null true false"), + hooks: {"#": cppHook}, + modeProps: {fold: ["brace", "include"]} + }); + + def("text/x-objectivec", { + name: "clike", + keywords: words(cKeywords + "inline restrict _Bool _Complex _Imaginery BOOL Class bycopy byref id IMP in " + + "inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"), + types: words(cTypes), + atoms: words("YES NO NULL NILL ON OFF true false"), + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$]/); + return "keyword"; + }, + "#": cppHook + }, + modeProps: {fold: "brace"} + }); + + def("text/x-squirrel", { + name: "clike", + keywords: words("base break clone continue const default delete enum extends function in class" + + " foreach local resume return this throw typeof yield constructor instanceof static"), + types: words(cTypes), + blockKeywords: words("case catch class else for foreach if switch try while"), + defKeywords: words("function local class"), + typeFirstDefinitions: true, + atoms: words("true false null"), + hooks: {"#": cppHook}, + modeProps: {fold: ["brace", "include"]} + }); + +}); diff --git a/public/assets/codemirror/codemirror.css b/public/assets/codemirror/codemirror.css new file mode 100644 index 000000000..12a488ad5 --- /dev/null +++ b/public/assets/codemirror/codemirror.css @@ -0,0 +1,335 @@ +/* BASICS */ + +.CodeMirror { + /* Set height, width, borders, and global font properties here */ + font-family: monospace; + height: 300px; + color: black; + border: 1px solid #D9D9D9; +} + +/* PADDING */ + +.CodeMirror-lines { + padding: 4px 0; /* Vertical padding around content */ +} +.CodeMirror pre { + padding: 0 4px; /* Horizontal padding of content */ +} + +.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + background-color: white; /* The little square between H and V scrollbars */ +} + +/* GUTTER */ + +.CodeMirror-gutters { + border-right: 1px solid #ddd; + background-color: #f7f7f7; + white-space: nowrap; +} +.CodeMirror-linenumbers {} +.CodeMirror-linenumber { + padding: 0 3px 0 5px; + min-width: 20px; + text-align: right; + color: #999; + white-space: nowrap; +} + +.CodeMirror-guttermarker { color: black; } +.CodeMirror-guttermarker-subtle { color: #999; } + +/* CURSOR */ + +.CodeMirror-cursor { + border-left: 1px solid black; + border-right: none; + width: 0; +} +/* Shown when moving in bi-directional text */ +.CodeMirror div.CodeMirror-secondarycursor { + border-left: 1px solid silver; +} +.cm-fat-cursor .CodeMirror-cursor { + width: auto; + border: 0; + background: #7e7; +} +.cm-fat-cursor div.CodeMirror-cursors { + z-index: 1; +} + +.cm-animate-fat-cursor { + width: auto; + border: 0; + -webkit-animation: blink 1.06s steps(1) infinite; + -moz-animation: blink 1.06s steps(1) infinite; + animation: blink 1.06s steps(1) infinite; + background-color: #7e7; +} +@-moz-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@-webkit-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} + +/* Can style cursor different in overwrite (non-insert) mode */ +.CodeMirror-overwrite .CodeMirror-cursor {} + +.cm-tab { display: inline-block; text-decoration: inherit; } + +.CodeMirror-ruler { + border-left: 1px solid #ccc; + position: absolute; +} + +/* DEFAULT THEME */ + +.cm-s-default .cm-header {color: blue;} +.cm-s-default .cm-quote {color: #090;} +.cm-negative {color: #d44;} +.cm-positive {color: #292;} +.cm-header, .cm-strong {font-weight: bold;} +.cm-em {font-style: italic;} +.cm-link {text-decoration: underline;} +.cm-strikethrough {text-decoration: line-through;} + +.cm-s-default .cm-keyword {color: #708;} +.cm-s-default .cm-atom {color: #219;} +.cm-s-default .cm-number {color: #164;} +.cm-s-default .cm-def {color: #00f;} +.cm-s-default .cm-variable, +.cm-s-default .cm-punctuation, +.cm-s-default .cm-property, +.cm-s-default .cm-operator {} +.cm-s-default .cm-variable-2 {color: #05a;} +.cm-s-default .cm-variable-3 {color: #085;} +.cm-s-default .cm-comment {color: #a50;} +.cm-s-default .cm-string {color: #a11;} +.cm-s-default .cm-string-2 {color: #f50;} +.cm-s-default .cm-meta {color: #555;} +.cm-s-default .cm-qualifier {color: #555;} +.cm-s-default .cm-builtin {color: #30a;} +.cm-s-default .cm-bracket {color: #997;} +.cm-s-default .cm-tag {color: #170;} +.cm-s-default .cm-attribute {color: #00c;} +.cm-s-default .cm-hr {color: #999;} +.cm-s-default .cm-link {color: #00c;} + +.cm-s-default .cm-error {color: #f00;} +.cm-invalidchar {color: #f00;} + +.CodeMirror-composing { border-bottom: 2px solid; } + +/* Default styles for common addons */ + +div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} +div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} +.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } +.CodeMirror-activeline-background {background: #e8f2ff;} + +/* STOP */ + +/* The rest of this file contains styles related to the mechanics of + the editor. You probably shouldn't touch them. */ + +.CodeMirror { + position: relative; + overflow: hidden; + background: white; +} + +.CodeMirror-scroll { + overflow: scroll !important; /* Things will break if this is overridden */ + /* 30px is the magic margin used to hide the element's real scrollbars */ + /* See overflow: hidden in .CodeMirror */ + margin-bottom: -30px; margin-right: -30px; + padding-bottom: 30px; + height: 100%; + outline: none; /* Prevent dragging from highlighting the element */ + position: relative; +} +.CodeMirror-sizer { + position: relative; + border-right: 30px solid transparent; +} + +/* The fake, visible scrollbars. Used to force redraw during scrolling + before actuall scrolling happens, thus preventing shaking and + flickering artifacts. */ +.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + position: absolute; + z-index: 6; + display: none; +} +.CodeMirror-vscrollbar { + right: 0; top: 0; + overflow-x: hidden; + overflow-y: scroll; +} +.CodeMirror-hscrollbar { + bottom: 0; left: 0; + overflow-y: hidden; + overflow-x: scroll; +} +.CodeMirror-scrollbar-filler { + right: 0; bottom: 0; +} +.CodeMirror-gutter-filler { + left: 0; bottom: 0; +} + +.CodeMirror-gutters { + position: absolute; left: 0; top: 0; + z-index: 3; +} +.CodeMirror-gutter { + white-space: normal; + height: 100%; + display: inline-block; + margin-bottom: -30px; + /* Hack to make IE7 behave */ + *zoom:1; + *display:inline; +} +.CodeMirror-gutter-wrapper { + position: absolute; + z-index: 4; + background: none !important; + border: none !important; +} +.CodeMirror-gutter-background { + position: absolute; + top: 0; bottom: 0; + z-index: 4; +} +.CodeMirror-gutter-elt { + position: absolute; + cursor: default; + z-index: 4; +} +.CodeMirror-gutter-wrapper { + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; +} + +.CodeMirror-lines { + cursor: text; + min-height: 1px; /* prevents collapsing before first draw */ +} +.CodeMirror pre { + /* Reset some styles that the rest of the page might have set */ + -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; + border-width: 0; + background: transparent; + font-family: inherit; + font-size: inherit; + margin: 0; + white-space: pre; + word-wrap: normal; + line-height: inherit; + color: inherit; + z-index: 2; + position: relative; + overflow: visible; + -webkit-tap-highlight-color: transparent; +} +.CodeMirror-wrap pre { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal; +} + +.CodeMirror-linebackground { + position: absolute; + left: 0; right: 0; top: 0; bottom: 0; + z-index: 0; +} + +.CodeMirror-linewidget { + position: relative; + z-index: 2; + overflow: auto; +} + +.CodeMirror-widget {} + +.CodeMirror-code { + outline: none; +} + +/* Force content-box sizing for the elements where we expect it */ +.CodeMirror-scroll, +.CodeMirror-sizer, +.CodeMirror-gutter, +.CodeMirror-gutters, +.CodeMirror-linenumber { + -moz-box-sizing: content-box; + box-sizing: content-box; +} + +.CodeMirror-measure { + position: absolute; + width: 100%; + height: 0; + overflow: hidden; + visibility: hidden; +} + +.CodeMirror-cursor { position: absolute; } +.CodeMirror-measure pre { position: static; } + +div.CodeMirror-cursors { + visibility: hidden; + position: relative; + z-index: 3; +} +div.CodeMirror-dragcursors { + visibility: visible; +} + +.CodeMirror-focused div.CodeMirror-cursors { + visibility: visible; +} + +.CodeMirror-selected { background: #d9d9d9; } +.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } +.CodeMirror-crosshair { cursor: crosshair; } +.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } +.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } + +.cm-searching { + background: #ffa; + background: rgba(255, 255, 0, .4); +} + +/* IE7 hack to prevent it from returning funny offsetTops on the spans */ +.CodeMirror span { *vertical-align: text-bottom; } + +/* Used to force a border model for a node */ +.cm-force-border { padding-right: .1px; } + +@media print { + /* Hide the cursor when printing */ + .CodeMirror div.CodeMirror-cursors { + visibility: hidden; + } +} + +/* See issue #2901 */ +.cm-tab-wrap-hack:after { content: ''; } + +/* Help users use markselection to safely style text background */ +span.CodeMirror-selectedtext { background: none; } diff --git a/public/assets/codemirror/codemirror.js b/public/assets/codemirror/codemirror.js new file mode 100644 index 000000000..5de8a1332 --- /dev/null +++ b/public/assets/codemirror/codemirror.js @@ -0,0 +1,8822 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// This is CodeMirror (http://codemirror.net), a code editor +// implemented in JavaScript on top of the browser's DOM. +// +// You can find some technical background for some of the code below +// at http://marijnhaverbeke.nl/blog/#cm-internals . + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + module.exports = mod(); + else if (typeof define == "function" && define.amd) // AMD + return define([], mod); + else // Plain browser env + this.CodeMirror = mod(); +})(function() { + "use strict"; + + // BROWSER SNIFFING + + // Kludges for bugs and behavior differences that can't be feature + // detected are enabled based on userAgent etc sniffing. + + var gecko = /gecko\/\d/i.test(navigator.userAgent); + var ie_upto10 = /MSIE \d/.test(navigator.userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); + var ie = ie_upto10 || ie_11up; + var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]); + var webkit = /WebKit\//.test(navigator.userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); + var chrome = /Chrome\//.test(navigator.userAgent); + var presto = /Opera\//.test(navigator.userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); + var phantom = /PhantomJS/.test(navigator.userAgent); + + var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); + // This is woefully incomplete. Suggestions for alternative methods welcome. + var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); + var mac = ios || /Mac/.test(navigator.platform); + var windows = /win/i.test(navigator.platform); + + var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/); + if (presto_version) presto_version = Number(presto_version[1]); + if (presto_version && presto_version >= 15) { presto = false; webkit = true; } + // Some browsers use the wrong event properties to signal cmd/ctrl on OS X + var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); + var captureRightClick = gecko || (ie && ie_version >= 9); + + // Optimize some code when these features are not used. + var sawReadOnlySpans = false, sawCollapsedSpans = false; + + // EDITOR CONSTRUCTOR + + // A CodeMirror instance represents an editor. This is the object + // that user code is usually dealing with. + + function CodeMirror(place, options) { + if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); + + this.options = options = options ? copyObj(options) : {}; + // Determine effective options based on given values and defaults. + copyObj(defaults, options, false); + setGuttersForLineNumbers(options); + + var doc = options.value; + if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator); + this.doc = doc; + + var input = new CodeMirror.inputStyles[options.inputStyle](this); + var display = this.display = new Display(place, doc, input); + display.wrapper.CodeMirror = this; + updateGutters(this); + themeChanged(this); + if (options.lineWrapping) + this.display.wrapper.className += " CodeMirror-wrap"; + if (options.autofocus && !mobile) display.input.focus(); + initScrollbars(this); + + this.state = { + keyMaps: [], // stores maps added by addKeyMap + overlays: [], // highlighting overlays, as added by addOverlay + modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, // used to disable editing during key handlers when in readOnly mode + pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll + selectingText: false, + draggingText: false, + highlight: new Delayed(), // stores highlight worker timeout + keySeq: null, // Unfinished key sequence + specialChars: null + }; + + var cm = this; + + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20); + + registerEventHandlers(this); + ensureGlobalHandlers(); + + startOperation(this); + this.curOp.forceUpdate = true; + attachDoc(this, doc); + + if ((options.autofocus && !mobile) || cm.hasFocus()) + setTimeout(bind(onFocus, this), 20); + else + onBlur(this); + + for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt)) + optionHandlers[opt](this, options[opt], Init); + maybeUpdateLineNumberWidth(this); + if (options.finishInit) options.finishInit(this); + for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); + endOperation(this); + // Suppress optimizelegibility in Webkit, since it breaks text + // measuring on line wrapping boundaries. + if (webkit && options.lineWrapping && + getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") + display.lineDiv.style.textRendering = "auto"; + } + + // DISPLAY CONSTRUCTOR + + // The display handles the DOM integration, both for input reading + // and content drawing. It holds references to DOM nodes and + // display-related state. + + function Display(place, doc, input) { + var d = this; + this.input = input; + + // Covers bottom-right square when both scrollbars are present. + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); + d.scrollbarFiller.setAttribute("cm-not-content", "true"); + // Covers bottom of gutter when coverGutterNextToScrollbar is on + // and h scrollbar is present. + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); + d.gutterFiller.setAttribute("cm-not-content", "true"); + // Will contain the actual code, positioned to cover the viewport. + d.lineDiv = elt("div", null, "CodeMirror-code"); + // Elements are added to these to represent selection and cursors. + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); + d.cursorDiv = elt("div", null, "CodeMirror-cursors"); + // A visibility: hidden element used to find the size of things. + d.measure = elt("div", null, "CodeMirror-measure"); + // When lines outside of the viewport are measured, they are drawn in this. + d.lineMeasure = elt("div", null, "CodeMirror-measure"); + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, "position: relative; outline: none"); + // Moved around its parent to cover visible view. + d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); + // Set to the height of the document, allowing scrolling. + d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); + d.sizerWidth = null; + // Behavior of elts with overflow: auto and padding is + // inconsistent across browsers. This is used to ensure the + // scrollable area is big enough. + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); + // Will contain the gutters, if any. + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + // Actual scrollable element. + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); + d.scroller.setAttribute("tabIndex", "-1"); + // The element in which the editor lives. + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); + + // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) + if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } + if (!webkit && !(gecko && mobile)) d.scroller.draggable = true; + + if (place) { + if (place.appendChild) place.appendChild(d.wrapper); + else place(d.wrapper); + } + + // Current rendered range (may be bigger than the view window). + d.viewFrom = d.viewTo = doc.first; + d.reportedViewFrom = d.reportedViewTo = doc.first; + // Information about the rendered lines. + d.view = []; + d.renderedView = null; + // Holds info about a single rendered line when it was rendered + // for measurement, while not in view. + d.externalMeasured = null; + // Empty space (in pixels) above the view + d.viewOffset = 0; + d.lastWrapHeight = d.lastWrapWidth = 0; + d.updateLineNumbers = null; + + d.nativeBarWidth = d.barHeight = d.barWidth = 0; + d.scrollbarsClipped = false; + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; + // Set to true when a non-horizontal-scrolling line widget is + // added. As an optimization, line widget aligning is skipped when + // this is false. + d.alignWidgets = false; + + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null; + d.maxLineLength = 0; + d.maxLineChanged = false; + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; + + // True when shift is held down. + d.shift = false; + + // Used to track whether anything happened since the context menu + // was opened. + d.selForContextMenu = null; + + d.activeTouch = null; + + input.init(d); + } + + // STATE UPDATES + + // Used to get the editor into a consistent state again when options change. + + function loadMode(cm) { + cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); + resetModeState(cm); + } + + function resetModeState(cm) { + cm.doc.iter(function(line) { + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + }); + cm.doc.frontier = cm.doc.first; + startWorker(cm, 100); + cm.state.modeGen++; + if (cm.curOp) regChange(cm); + } + + function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap"); + cm.display.sizer.style.minWidth = ""; + cm.display.sizerWidth = null; + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap"); + findMaxLine(cm); + } + estimateLineHeights(cm); + regChange(cm); + clearCaches(cm); + setTimeout(function(){updateScrollbars(cm);}, 100); + } + + // Returns a function that estimates the height of a line, to use as + // first approximation until the line becomes visible (and is thus + // properly measurable). + function estimateHeight(cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); + return function(line) { + if (lineIsHidden(cm.doc, line)) return 0; + + var widgetsHeight = 0; + if (line.widgets) for (var i = 0; i < line.widgets.length; i++) { + if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; + } + + if (wrapping) + return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; + else + return widgetsHeight + th; + }; + } + + function estimateLineHeights(cm) { + var doc = cm.doc, est = estimateHeight(cm); + doc.iter(function(line) { + var estHeight = est(line); + if (estHeight != line.height) updateLineHeight(line, estHeight); + }); + } + + function themeChanged(cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + clearCaches(cm); + } + + function guttersChanged(cm) { + updateGutters(cm); + regChange(cm); + setTimeout(function(){alignHorizontally(cm);}, 20); + } + + // Rebuild the gutter elements, ensure the margin to the left of the + // code matches their width. + function updateGutters(cm) { + var gutters = cm.display.gutters, specs = cm.options.gutters; + removeChildren(gutters); + for (var i = 0; i < specs.length; ++i) { + var gutterClass = specs[i]; + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); + if (gutterClass == "CodeMirror-linenumbers") { + cm.display.lineGutter = gElt; + gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = i ? "" : "none"; + updateGutterSpace(cm); + } + + function updateGutterSpace(cm) { + var width = cm.display.gutters.offsetWidth; + cm.display.sizer.style.marginLeft = width + "px"; + } + + // Compute the character length of a line, taking into account + // collapsed ranges (see markText) that might hide parts, and join + // other lines onto it. + function lineLength(line) { + if (line.height == 0) return 0; + var len = line.text.length, merged, cur = line; + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true); + cur = found.from.line; + len += found.from.ch - found.to.ch; + } + cur = line; + while (merged = collapsedSpanAtEnd(cur)) { + var found = merged.find(0, true); + len -= cur.text.length - found.from.ch; + cur = found.to.line; + len += cur.text.length - found.to.ch; + } + return len; + } + + // Find the longest line in the document. + function findMaxLine(cm) { + var d = cm.display, doc = cm.doc; + d.maxLine = getLine(doc, doc.first); + d.maxLineLength = lineLength(d.maxLine); + d.maxLineChanged = true; + doc.iter(function(line) { + var len = lineLength(line); + if (len > d.maxLineLength) { + d.maxLineLength = len; + d.maxLine = line; + } + }); + } + + // Make sure the gutters options contains the element + // "CodeMirror-linenumbers" when the lineNumbers option is true. + function setGuttersForLineNumbers(options) { + var found = indexOf(options.gutters, "CodeMirror-linenumbers"); + if (found == -1 && options.lineNumbers) { + options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); + } else if (found > -1 && !options.lineNumbers) { + options.gutters = options.gutters.slice(0); + options.gutters.splice(found, 1); + } + } + + // SCROLLBARS + + // Prepare DOM reads needed to update the scrollbars. Done in one + // shot to minimize update/measure roundtrips. + function measureForScrollbars(cm) { + var d = cm.display, gutterW = d.gutters.offsetWidth; + var docH = Math.round(cm.doc.height + paddingVert(cm.display)); + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW + }; + } + + function NativeScrollbars(place, scroll, cm) { + this.cm = cm; + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); + place(vert); place(horiz); + + on(vert, "scroll", function() { + if (vert.clientHeight) scroll(vert.scrollTop, "vertical"); + }); + on(horiz, "scroll", function() { + if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal"); + }); + + this.checkedOverlay = false; + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; + } + + NativeScrollbars.prototype = copyObj({ + update: function(measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1; + var needsV = measure.scrollHeight > measure.clientHeight + 1; + var sWidth = measure.nativeBarWidth; + + if (needsV) { + this.vert.style.display = "block"; + this.vert.style.bottom = needsH ? sWidth + "px" : "0"; + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); + // A bug in IE8 can cause this value to be negative, so guard it. + this.vert.firstChild.style.height = + Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; + } else { + this.vert.style.display = ""; + this.vert.firstChild.style.height = "0"; + } + + if (needsH) { + this.horiz.style.display = "block"; + this.horiz.style.right = needsV ? sWidth + "px" : "0"; + this.horiz.style.left = measure.barLeft + "px"; + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); + this.horiz.firstChild.style.width = + (measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; + } else { + this.horiz.style.display = ""; + this.horiz.firstChild.style.width = "0"; + } + + if (!this.checkedOverlay && measure.clientHeight > 0) { + if (sWidth == 0) this.overlayHack(); + this.checkedOverlay = true; + } + + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}; + }, + setScrollLeft: function(pos) { + if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos; + }, + setScrollTop: function(pos) { + if (this.vert.scrollTop != pos) this.vert.scrollTop = pos; + }, + overlayHack: function() { + var w = mac && !mac_geMountainLion ? "12px" : "18px"; + this.horiz.style.minHeight = this.vert.style.minWidth = w; + var self = this; + var barMouseDown = function(e) { + if (e_target(e) != self.vert && e_target(e) != self.horiz) + operation(self.cm, onMouseDown)(e); + }; + on(this.vert, "mousedown", barMouseDown); + on(this.horiz, "mousedown", barMouseDown); + }, + clear: function() { + var parent = this.horiz.parentNode; + parent.removeChild(this.horiz); + parent.removeChild(this.vert); + } + }, NativeScrollbars.prototype); + + function NullScrollbars() {} + + NullScrollbars.prototype = copyObj({ + update: function() { return {bottom: 0, right: 0}; }, + setScrollLeft: function() {}, + setScrollTop: function() {}, + clear: function() {} + }, NullScrollbars.prototype); + + CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; + + function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear(); + if (cm.display.scrollbars.addClass) + rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + + cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); + // Prevent clicks in the scrollbars from killing focus + on(node, "mousedown", function() { + if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0); + }); + node.setAttribute("cm-not-content", "true"); + }, function(pos, axis) { + if (axis == "horizontal") setScrollLeft(cm, pos); + else setScrollTop(cm, pos); + }, cm); + if (cm.display.scrollbars.addClass) + addClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + + function updateScrollbars(cm, measure) { + if (!measure) measure = measureForScrollbars(cm); + var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; + updateScrollbarsInner(cm, measure); + for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) + updateHeightsInViewport(cm); + updateScrollbarsInner(cm, measureForScrollbars(cm)); + startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; + } + } + + // Re-synchronize the fake scrollbars with the actual size of the + // content. + function updateScrollbarsInner(cm, measure) { + var d = cm.display; + var sizes = d.scrollbars.update(measure); + + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; + + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block"; + d.scrollbarFiller.style.height = sizes.bottom + "px"; + d.scrollbarFiller.style.width = sizes.right + "px"; + } else d.scrollbarFiller.style.display = ""; + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block"; + d.gutterFiller.style.height = sizes.bottom + "px"; + d.gutterFiller.style.width = measure.gutterWidth + "px"; + } else d.gutterFiller.style.display = ""; + } + + // Compute the lines that are visible in a given viewport (defaults + // the the current scroll position). viewport may contain top, + // height, and ensure (see op.scrollToPos) properties. + function visibleLines(display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; + top = Math.floor(top - paddingTop(display)); + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; + + var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); + // Ensure is a {from: {line, ch}, to: {line, ch}} object, and + // forces those lines into the viewport (if possible). + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; + if (ensureFrom < from) { + from = ensureFrom; + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); + to = ensureTo; + } + } + return {from: from, to: Math.max(to, from + 1)}; + } + + // LINE NUMBERS + + // Re-align line numbers and gutter marks to compensate for + // horizontal scrolling. + function alignHorizontally(cm) { + var display = cm.display, view = display.view; + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; + var gutterW = display.gutters.offsetWidth, left = comp + "px"; + for (var i = 0; i < view.length; i++) if (!view[i].hidden) { + if (cm.options.fixedGutter && view[i].gutter) + view[i].gutter.style.left = left; + var align = view[i].alignable; + if (align) for (var j = 0; j < align.length; j++) + align[j].style.left = left; + } + if (cm.options.fixedGutter) + display.gutters.style.left = (comp + gutterW) + "px"; + } + + // Used to ensure that the line number gutter is still the right + // size for the current document size. Returns true when an update + // is needed. + function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) return false; + var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt")); + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; + display.lineGutter.style.width = ""; + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; + display.lineNumWidth = display.lineNumInnerWidth + padding; + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; + display.lineGutter.style.width = display.lineNumWidth + "px"; + updateGutterSpace(cm); + return true; + } + return false; + } + + function lineNumberFor(options, i) { + return String(options.lineNumberFormatter(i + options.firstLineNumber)); + } + + // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, + // but using getBoundingClientRect to get a sub-pixel-accurate + // result. + function compensateForHScroll(display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; + } + + // DISPLAY DRAWING + + function DisplayUpdate(cm, viewport, force) { + var display = cm.display; + + this.viewport = viewport; + // Store some values that we'll need later (but don't want to force a relayout for) + this.visible = visibleLines(display, cm.doc, viewport); + this.editorIsHidden = !display.wrapper.offsetWidth; + this.wrapperHeight = display.wrapper.clientHeight; + this.wrapperWidth = display.wrapper.clientWidth; + this.oldDisplayWidth = displayWidth(cm); + this.force = force; + this.dims = getDimensions(cm); + this.events = []; + } + + DisplayUpdate.prototype.signal = function(emitter, type) { + if (hasHandler(emitter, type)) + this.events.push(arguments); + }; + DisplayUpdate.prototype.finish = function() { + for (var i = 0; i < this.events.length; i++) + signal.apply(null, this.events[i]); + }; + + function maybeClipScrollbars(cm) { + var display = cm.display; + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; + display.heightForcer.style.height = scrollGap(cm) + "px"; + display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; + display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; + display.scrollbarsClipped = true; + } + } + + // Does the actual updating of the line display. Bails out + // (returning false) when there is nothing to be done and forced is + // false. + function updateDisplayIfNeeded(cm, update) { + var display = cm.display, doc = cm.doc; + + if (update.editorIsHidden) { + resetView(cm); + return false; + } + + // Bail out if the visible area is already rendered and nothing changed. + if (!update.force && + update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && countDirtyView(cm) == 0) + return false; + + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm); + update.dims = getDimensions(cm); + } + + // Compute a suitable new viewport (from & to) + var end = doc.first + doc.size; + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); + var to = Math.min(end, update.visible.to + cm.options.viewportMargin); + if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); + if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from); + to = visualLineEndNo(cm.doc, to); + } + + var different = from != display.viewFrom || to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; + adjustView(cm, from, to); + + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); + // Position the mover div to align with the current scroll position + cm.display.mover.style.top = display.viewOffset + "px"; + + var toUpdate = countDirtyView(cm); + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) + return false; + + // For big changes, we hide the enclosing element during the + // update, since that speeds up the operations on most browsers. + var focused = activeElt(); + if (toUpdate > 4) display.lineDiv.style.display = "none"; + patchDisplay(cm, display.updateLineNumbers, update.dims); + if (toUpdate > 4) display.lineDiv.style.display = ""; + display.renderedView = display.view; + // There might have been a widget with a focused element that got + // hidden or updated, if so re-focus it. + if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); + + // Prevent selection and cursors from interfering with the scroll + // width and height. + removeChildren(display.cursorDiv); + removeChildren(display.selectionDiv); + display.gutters.style.height = display.sizer.style.minHeight = 0; + + if (different) { + display.lastWrapHeight = update.wrapperHeight; + display.lastWrapWidth = update.wrapperWidth; + startWorker(cm, 400); + } + + display.updateLineNumbers = null; + + return true; + } + + function postUpdateDisplay(cm, update) { + var viewport = update.viewport; + for (var first = true;; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + // Clip forced viewport to actual scrollable area. + if (viewport && viewport.top != null) + viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; + // Updated line heights might result in the drawn area not + // actually covering the viewport. Keep looping until it does. + update.visible = visibleLines(cm.display, cm.doc, viewport); + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) + break; + } + if (!updateDisplayIfNeeded(cm, update)) break; + updateHeightsInViewport(cm); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + setDocumentHeight(cm, barMeasure); + updateScrollbars(cm, barMeasure); + } + + update.signal(cm, "update", cm); + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); + cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; + } + } + + function updateDisplaySimple(cm, viewport) { + var update = new DisplayUpdate(cm, viewport); + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm); + postUpdateDisplay(cm, update); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + setDocumentHeight(cm, barMeasure); + updateScrollbars(cm, barMeasure); + update.finish(); + } + } + + function setDocumentHeight(cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px"; + var total = measure.docHeight + cm.display.barHeight; + cm.display.heightForcer.style.top = total + "px"; + cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px"; + } + + // Read the actual heights of the rendered lines, and update their + // stored heights to match. + function updateHeightsInViewport(cm) { + var display = cm.display; + var prevBottom = display.lineDiv.offsetTop; + for (var i = 0; i < display.view.length; i++) { + var cur = display.view[i], height; + if (cur.hidden) continue; + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight; + height = bot - prevBottom; + prevBottom = bot; + } else { + var box = cur.node.getBoundingClientRect(); + height = box.bottom - box.top; + } + var diff = cur.line.height - height; + if (height < 2) height = textHeight(display); + if (diff > .001 || diff < -.001) { + updateLineHeight(cur.line, height); + updateWidgetHeight(cur.line); + if (cur.rest) for (var j = 0; j < cur.rest.length; j++) + updateWidgetHeight(cur.rest[j]); + } + } + } + + // Read and store the height of line widgets associated with the + // given line. + function updateWidgetHeight(line) { + if (line.widgets) for (var i = 0; i < line.widgets.length; ++i) + line.widgets[i].height = line.widgets[i].node.offsetHeight; + } + + // Do a bulk-read of the DOM positions and sizes needed to draw the + // view, so that we don't interleave reading and writing to the DOM. + function getDimensions(cm) { + var d = cm.display, left = {}, width = {}; + var gutterLeft = d.gutters.clientLeft; + for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { + left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; + width[cm.options.gutters[i]] = n.clientWidth; + } + return {fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth}; + } + + // Sync the actual display DOM structure with display.view, removing + // nodes for lines that are no longer in view, and creating the ones + // that are not there yet, and updating the ones that are out of + // date. + function patchDisplay(cm, updateNumbersFrom, dims) { + var display = cm.display, lineNumbers = cm.options.lineNumbers; + var container = display.lineDiv, cur = container.firstChild; + + function rm(node) { + var next = node.nextSibling; + // Works around a throw-scroll bug in OS X Webkit + if (webkit && mac && cm.display.currentWheelTarget == node) + node.style.display = "none"; + else + node.parentNode.removeChild(node); + return next; + } + + var view = display.view, lineN = display.viewFrom; + // Loop over the elements in the view, syncing cur (the DOM nodes + // in display.lineDiv) with the view as we go. + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (lineView.hidden) { + } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet + var node = buildLineElement(cm, lineView, lineN, dims); + container.insertBefore(node, cur); + } else { // Already drawn + while (cur != lineView.node) cur = rm(cur); + var updateNumber = lineNumbers && updateNumbersFrom != null && + updateNumbersFrom <= lineN && lineView.lineNumber; + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; + updateLineForChanges(cm, lineView, lineN, dims); + } + if (updateNumber) { + removeChildren(lineView.lineNumber); + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); + } + cur = lineView.node.nextSibling; + } + lineN += lineView.size; + } + while (cur) cur = rm(cur); + } + + // When an aspect of a line changes, a string is added to + // lineView.changes. This updates the relevant part of the line's + // DOM structure. + function updateLineForChanges(cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j]; + if (type == "text") updateLineText(cm, lineView); + else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); + else if (type == "class") updateLineClasses(lineView); + else if (type == "widget") updateLineWidgets(cm, lineView, dims); + } + lineView.changes = null; + } + + // Lines with gutter elements, widgets or a background class need to + // be wrapped, and have the extra elements added to the wrapper div + function ensureLineWrapped(lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative"); + if (lineView.text.parentNode) + lineView.text.parentNode.replaceChild(lineView.node, lineView.text); + lineView.node.appendChild(lineView.text); + if (ie && ie_version < 8) lineView.node.style.zIndex = 2; + } + return lineView.node; + } + + function updateLineBackground(lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; + if (cls) cls += " CodeMirror-linebackground"; + if (lineView.background) { + if (cls) lineView.background.className = cls; + else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } + } else if (cls) { + var wrap = ensureLineWrapped(lineView); + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); + } + } + + // Wrapper around buildLineContent which will reuse the structure + // in display.externalMeasured when possible. + function getLineContent(cm, lineView) { + var ext = cm.display.externalMeasured; + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null; + lineView.measure = ext.measure; + return ext.built; + } + return buildLineContent(cm, lineView); + } + + // Redraw the line's text. Interacts with the background and text + // classes because the mode may output tokens that influence these + // classes. + function updateLineText(cm, lineView) { + var cls = lineView.text.className; + var built = getLineContent(cm, lineView); + if (lineView.text == lineView.node) lineView.node = built.pre; + lineView.text.parentNode.replaceChild(built.pre, lineView.text); + lineView.text = built.pre; + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass; + lineView.textClass = built.textClass; + updateLineClasses(lineView); + } else if (cls) { + lineView.text.className = cls; + } + } + + function updateLineClasses(lineView) { + updateLineBackground(lineView); + if (lineView.line.wrapClass) + ensureLineWrapped(lineView).className = lineView.line.wrapClass; + else if (lineView.node != lineView.text) + lineView.node.className = ""; + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; + lineView.text.className = textClass || ""; + } + + function updateLineGutter(cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter); + lineView.gutter = null; + } + if (lineView.gutterBackground) { + lineView.node.removeChild(lineView.gutterBackground); + lineView.gutterBackground = null; + } + if (lineView.line.gutterClass) { + var wrap = ensureLineWrapped(lineView); + lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, + "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + + "px; width: " + dims.gutterTotalWidth + "px"); + wrap.insertBefore(lineView.gutterBackground, lineView.text); + } + var markers = lineView.line.gutterMarkers; + if (cm.options.lineNumbers || markers) { + var wrap = ensureLineWrapped(lineView); + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"); + cm.display.input.setUneditable(gutterWrap); + wrap.insertBefore(gutterWrap, lineView.text); + if (lineView.line.gutterClass) + gutterWrap.className += " " + lineView.line.gutterClass; + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) + lineView.lineNumber = gutterWrap.appendChild( + elt("div", lineNumberFor(cm.options, lineN), + "CodeMirror-linenumber CodeMirror-gutter-elt", + "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + + cm.display.lineNumInnerWidth + "px")); + if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { + var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; + if (found) + gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); + } + } + } + + function updateLineWidgets(cm, lineView, dims) { + if (lineView.alignable) lineView.alignable = null; + for (var node = lineView.node.firstChild, next; node; node = next) { + var next = node.nextSibling; + if (node.className == "CodeMirror-linewidget") + lineView.node.removeChild(node); + } + insertLineWidgets(cm, lineView, dims); + } + + // Build a line's DOM representation from scratch + function buildLineElement(cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView); + lineView.text = lineView.node = built.pre; + if (built.bgClass) lineView.bgClass = built.bgClass; + if (built.textClass) lineView.textClass = built.textClass; + + updateLineClasses(lineView); + updateLineGutter(cm, lineView, lineN, dims); + insertLineWidgets(cm, lineView, dims); + return lineView.node; + } + + // A lineView may contain multiple logical lines (when merged by + // collapsed spans). The widgets for all of them need to be drawn. + function insertLineWidgets(cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); + if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) + insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); + } + + function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { + if (!line.widgets) return; + var wrap = ensureLineWrapped(lineView); + for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); + if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true"); + positionLineWidget(widget, node, lineView, dims); + cm.display.input.setUneditable(node); + if (allowAbove && widget.above) + wrap.insertBefore(node, lineView.gutter || lineView.text); + else + wrap.appendChild(node); + signalLater(widget, "redraw"); + } + } + + function positionLineWidget(widget, node, lineView, dims) { + if (widget.noHScroll) { + (lineView.alignable || (lineView.alignable = [])).push(node); + var width = dims.wrapperWidth; + node.style.left = dims.fixedPos + "px"; + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth; + node.style.paddingLeft = dims.gutterTotalWidth + "px"; + } + node.style.width = width + "px"; + } + if (widget.coverGutter) { + node.style.zIndex = 5; + node.style.position = "relative"; + if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; + } + } + + // POSITION OBJECT + + // A Pos instance represents a position within the text. + var Pos = CodeMirror.Pos = function(line, ch) { + if (!(this instanceof Pos)) return new Pos(line, ch); + this.line = line; this.ch = ch; + }; + + // Compare two positions, return 0 if they are the same, a negative + // number when a is less, and a positive number otherwise. + var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; }; + + function copyPos(x) {return Pos(x.line, x.ch);} + function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; } + function minPos(a, b) { return cmp(a, b) < 0 ? a : b; } + + // INPUT HANDLING + + function ensureFocus(cm) { + if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } + } + + function isReadOnly(cm) { + return cm.options.readOnly || cm.doc.cantEdit; + } + + // This will be set to an array of strings when copying, so that, + // when pasting, we know what kind of selections the copied text + // was made out of. + var lastCopied = null; + + function applyTextInput(cm, inserted, deleted, sel, origin) { + var doc = cm.doc; + cm.display.shift = false; + if (!sel) sel = doc.sel; + + var paste = cm.state.pasteIncoming || origin == "paste"; + var textLines = doc.splitLines(inserted), multiPaste = null; + // When pasing N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.length == 0) { + multiPaste = []; + for (var i = 0; i < lastCopied.length; i++) + multiPaste.push(doc.splitLines(lastCopied[i])); + } + } else if (textLines.length == sel.ranges.length) { + multiPaste = map(textLines, function(l) { return [l]; }); + } + } + + // Normal behavior is to insert the new text into every selection + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i]; + var from = range.from(), to = range.to(); + if (range.empty()) { + if (deleted && deleted > 0) // Handle deletion + from = Pos(from.line, from.ch - deleted); + else if (cm.state.overwrite && !paste) // Handle overwrite + to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); + } + var updateInput = cm.curOp.updateInput; + var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; + makeChange(cm.doc, changeEvent); + signalLater(cm, "inputRead", cm, changeEvent); + } + if (inserted && !paste) + triggerElectric(cm, inserted); + + ensureCursorVisible(cm); + cm.curOp.updateInput = updateInput; + cm.curOp.typing = true; + cm.state.pasteIncoming = cm.state.cutIncoming = false; + } + + function handlePaste(e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("text/plain"); + if (pasted) { + e.preventDefault(); + if (!isReadOnly(cm) && !cm.options.disableInput) + runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); }); + return true; + } + } + + function triggerElectric(cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) return; + var sel = cm.doc.sel; + + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i]; + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue; + var mode = cm.getModeAt(range.head); + var indented = false; + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) + if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range.head.line, "smart"); + break; + } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) + indented = indentLine(cm, range.head.line, "smart"); + } + if (indented) signalLater(cm, "electricInput", cm, range.head.line); + } + } + + function copyableRanges(cm) { + var text = [], ranges = []; + for (var i = 0; i < cm.doc.sel.ranges.length; i++) { + var line = cm.doc.sel.ranges[i].head.line; + var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; + ranges.push(lineRange); + text.push(cm.getRange(lineRange.anchor, lineRange.head)); + } + return {text: text, ranges: ranges}; + } + + function disableBrowserMagic(field) { + field.setAttribute("autocorrect", "off"); + field.setAttribute("autocapitalize", "off"); + field.setAttribute("spellcheck", "false"); + } + + // TEXTAREA INPUT STYLE + + function TextareaInput(cm) { + this.cm = cm; + // See input.poll and input.reset + this.prevInput = ""; + + // Flag that indicates whether we expect input to appear real soon + // now (after some event like 'keypress' or 'input') and are + // polling intensively. + this.pollingFast = false; + // Self-resetting timeout for the poller + this.polling = new Delayed(); + // Tracks when input.reset has punted to just putting a short + // string into the textarea instead of the full selection. + this.inaccurateSelection = false; + // Used to work around IE issue with selection being forgotten when focus moves away from textarea + this.hasSelection = false; + this.composing = null; + }; + + function hiddenTextarea() { + var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none"); + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) te.style.width = "1000px"; + else te.setAttribute("wrap", "off"); + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) te.style.border = "1px solid black"; + disableBrowserMagic(te); + return div; + } + + TextareaInput.prototype = copyObj({ + init: function(display) { + var input = this, cm = this.cm; + + // Wraps and hides input textarea + var div = this.wrapper = hiddenTextarea(); + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + var te = this.textarea = div.firstChild; + display.wrapper.insertBefore(div, display.wrapper.firstChild); + + // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) + if (ios) te.style.width = "0px"; + + on(te, "input", function() { + if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null; + input.poll(); + }); + + on(te, "paste", function(e) { + if (handlePaste(e, cm)) return true; + + cm.state.pasteIncoming = true; + input.fastPoll(); + }); + + function prepareCopyCut(e) { + if (cm.somethingSelected()) { + lastCopied = cm.getSelections(); + if (input.inaccurateSelection) { + input.prevInput = ""; + input.inaccurateSelection = false; + te.value = lastCopied.join("\n"); + selectInput(te); + } + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + lastCopied = ranges.text; + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll); + } else { + input.prevInput = ""; + te.value = ranges.text.join("\n"); + selectInput(te); + } + } + if (e.type == "cut") cm.state.cutIncoming = true; + } + on(te, "cut", prepareCopyCut); + on(te, "copy", prepareCopyCut); + + on(display.scroller, "paste", function(e) { + if (eventInWidget(display, e)) return; + cm.state.pasteIncoming = true; + input.focus(); + }); + + // Prevent normal selection in the editor (we handle our own) + on(display.lineSpace, "selectstart", function(e) { + if (!eventInWidget(display, e)) e_preventDefault(e); + }); + + on(te, "compositionstart", function() { + var start = cm.getCursor("from"); + input.composing = { + start: start, + range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) + }; + }); + on(te, "compositionend", function() { + if (input.composing) { + input.poll(); + input.composing.range.clear(); + input.composing = null; + } + }); + }, + + prepareSelection: function() { + // Redraw the selection and/or cursor + var cm = this.cm, display = cm.display, doc = cm.doc; + var result = prepareSelection(cm); + + // Move the hidden textarea near the cursor to prevent scrolling artifacts + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top)); + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left)); + } + + return result; + }, + + showSelection: function(drawn) { + var cm = this.cm, display = cm.display; + removeChildrenAndAdd(display.cursorDiv, drawn.cursors); + removeChildrenAndAdd(display.selectionDiv, drawn.selection); + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px"; + this.wrapper.style.left = drawn.teLeft + "px"; + } + }, + + // Reset the input to correspond to the selection (or to be empty, + // when not typing and nothing is selected) + reset: function(typing) { + if (this.contextMenuPending) return; + var minimal, selected, cm = this.cm, doc = cm.doc; + if (cm.somethingSelected()) { + this.prevInput = ""; + var range = doc.sel.primary(); + minimal = hasCopyEvent && + (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); + var content = minimal ? "-" : selected || cm.getSelection(); + this.textarea.value = content; + if (cm.state.focused) selectInput(this.textarea); + if (ie && ie_version >= 9) this.hasSelection = content; + } else if (!typing) { + this.prevInput = this.textarea.value = ""; + if (ie && ie_version >= 9) this.hasSelection = null; + } + this.inaccurateSelection = minimal; + }, + + getField: function() { return this.textarea; }, + + supportsTouch: function() { return false; }, + + focus: function() { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { this.textarea.focus(); } + catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM + } + }, + + blur: function() { this.textarea.blur(); }, + + resetPosition: function() { + this.wrapper.style.top = this.wrapper.style.left = 0; + }, + + receivedFocus: function() { this.slowPoll(); }, + + // Poll for input changes, using the normal rate of polling. This + // runs as long as the editor is focused. + slowPoll: function() { + var input = this; + if (input.pollingFast) return; + input.polling.set(this.cm.options.pollInterval, function() { + input.poll(); + if (input.cm.state.focused) input.slowPoll(); + }); + }, + + // When an event has just come in that is likely to add or change + // something in the input textarea, we poll faster, to ensure that + // the change appears on the screen quickly. + fastPoll: function() { + var missed = false, input = this; + input.pollingFast = true; + function p() { + var changed = input.poll(); + if (!changed && !missed) {missed = true; input.polling.set(60, p);} + else {input.pollingFast = false; input.slowPoll();} + } + input.polling.set(20, p); + }, + + // Read input from the textarea, and update the document to match. + // When something is selected, it is present in the textarea, and + // selected (unless it is huge, in which case a placeholder is + // used). When nothing is selected, the cursor sits after previously + // seen text (can be empty), which is stored in prevInput (we must + // not reset the textarea when typing, because that breaks IME). + poll: function() { + var cm = this.cm, input = this.textarea, prevInput = this.prevInput; + // Since this is called a *lot*, try to bail out as cheaply as + // possible when it is clear that nothing happened. hasSelection + // will be the case when there is a lot of text in the textarea, + // in which case reading its value would be expensive. + if (this.contextMenuPending || !cm.state.focused || + (hasSelection(input) && !prevInput && !this.composing) || + isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq) + return false; + + var text = input.value; + // If nothing changed, bail. + if (text == prevInput && !cm.somethingSelected()) return false; + // Work around nonsensical selection resetting in IE9/10, and + // inexplicable appearance of private area unicode characters on + // some key combos in Mac (#2689). + if (ie && ie_version >= 9 && this.hasSelection === text || + mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset(); + return false; + } + + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0); + if (first == 0x200b && !prevInput) prevInput = "\u200b"; + if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); } + } + // Find the part of the input that is actually new + var same = 0, l = Math.min(prevInput.length, text.length); + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; + + var self = this; + runInOp(cm, function() { + applyTextInput(cm, text.slice(same), prevInput.length - same, + null, self.composing ? "*compose" : null); + + // Don't leave long text in the textarea, since it makes further polling slow + if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = ""; + else self.prevInput = text; + + if (self.composing) { + self.composing.range.clear(); + self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"), + {className: "CodeMirror-composing"}); + } + }); + return true; + }, + + ensurePolled: function() { + if (this.pollingFast && this.poll()) this.pollingFast = false; + }, + + onKeyPress: function() { + if (ie && ie_version >= 9) this.hasSelection = null; + this.fastPoll(); + }, + + onContextMenu: function(e) { + var input = this, cm = input.cm, display = cm.display, te = input.textarea; + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; + if (!pos || presto) return; // Opera is difficult. + + // Reset the current text selection only if the click is done outside of the selection + // and 'resetSelectionOnContextMenu' option is true. + var reset = cm.options.resetSelectionOnContextMenu; + if (reset && cm.doc.sel.contains(pos) == -1) + operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); + + var oldCSS = te.style.cssText; + input.wrapper.style.position = "absolute"; + te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " + + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + + "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712) + display.input.focus(); + if (webkit) window.scrollTo(null, oldScrollY); + display.input.reset(); + // Adds "Select all" to context menu in FF + if (!cm.somethingSelected()) te.value = input.prevInput = " "; + input.contextMenuPending = true; + display.selForContextMenu = cm.doc.sel; + clearTimeout(display.detectingSelectAll); + + // Select-all will be greyed out if there's nothing to select, so + // this adds a zero-width space so that we can later check whether + // it got selected. + function prepareSelectAllHack() { + if (te.selectionStart != null) { + var selected = cm.somethingSelected(); + var extval = "\u200b" + (selected ? te.value : ""); + te.value = "\u21da"; // Used to catch context-menu undo + te.value = extval; + input.prevInput = selected ? "" : "\u200b"; + te.selectionStart = 1; te.selectionEnd = extval.length; + // Re-set this, in case some other handler touched the + // selection in the meantime. + display.selForContextMenu = cm.doc.sel; + } + } + function rehide() { + input.contextMenuPending = false; + input.wrapper.style.position = "relative"; + te.style.cssText = oldCSS; + if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); + + // Try to detect the user choosing select-all + if (te.selectionStart != null) { + if (!ie || (ie && ie_version < 9)) prepareSelectAllHack(); + var i = 0, poll = function() { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && + te.selectionEnd > 0 && input.prevInput == "\u200b") + operation(cm, commands.selectAll)(cm); + else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500); + else display.input.reset(); + }; + display.detectingSelectAll = setTimeout(poll, 200); + } + } + + if (ie && ie_version >= 9) prepareSelectAllHack(); + if (captureRightClick) { + e_stop(e); + var mouseup = function() { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }; + on(window, "mouseup", mouseup); + } else { + setTimeout(rehide, 50); + } + }, + + setUneditable: nothing, + + needsContentAttribute: false + }, TextareaInput.prototype); + + // CONTENTEDITABLE INPUT STYLE + + function ContentEditableInput(cm) { + this.cm = cm; + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; + this.polling = new Delayed(); + this.gracePeriod = false; + } + + ContentEditableInput.prototype = copyObj({ + init: function(display) { + var input = this, cm = input.cm; + var div = input.div = display.lineDiv; + div.contentEditable = "true"; + disableBrowserMagic(div); + + on(div, "paste", function(e) { handlePaste(e, cm); }) + + on(div, "compositionstart", function(e) { + var data = e.data; + input.composing = {sel: cm.doc.sel, data: data, startData: data}; + if (!data) return; + var prim = cm.doc.sel.primary(); + var line = cm.getLine(prim.head.line); + var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length)); + if (found > -1 && found <= prim.head.ch) + input.composing.sel = simpleSelection(Pos(prim.head.line, found), + Pos(prim.head.line, found + data.length)); + }); + on(div, "compositionupdate", function(e) { + input.composing.data = e.data; + }); + on(div, "compositionend", function(e) { + var ours = input.composing; + if (!ours) return; + if (e.data != ours.startData && !/\u200b/.test(e.data)) + ours.data = e.data; + // Need a small delay to prevent other code (input event, + // selection polling) from doing damage when fired right after + // compositionend. + setTimeout(function() { + if (!ours.handled) + input.applyComposition(ours); + if (input.composing == ours) + input.composing = null; + }, 50); + }); + + on(div, "touchstart", function() { + input.forceCompositionEnd(); + }); + + on(div, "input", function() { + if (input.composing) return; + if (!input.pollContent()) + runInOp(input.cm, function() {regChange(cm);}); + }); + + function onCopyCut(e) { + if (cm.somethingSelected()) { + lastCopied = cm.getSelections(); + if (e.type == "cut") cm.replaceSelection("", null, "cut"); + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + lastCopied = ranges.text; + if (e.type == "cut") { + cm.operation(function() { + cm.setSelections(ranges.ranges, 0, sel_dontScroll); + cm.replaceSelection("", null, "cut"); + }); + } + } + // iOS exposes the clipboard API, but seems to discard content inserted into it + if (e.clipboardData && !ios) { + e.preventDefault(); + e.clipboardData.clearData(); + e.clipboardData.setData("text/plain", lastCopied.join("\n")); + } else { + // Old-fashioned briefly-focus-a-textarea hack + var kludge = hiddenTextarea(), te = kludge.firstChild; + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); + te.value = lastCopied.join("\n"); + var hadFocus = document.activeElement; + selectInput(te); + setTimeout(function() { + cm.display.lineSpace.removeChild(kludge); + hadFocus.focus(); + }, 50); + } + } + on(div, "copy", onCopyCut); + on(div, "cut", onCopyCut); + }, + + prepareSelection: function() { + var result = prepareSelection(this.cm, false); + result.focus = this.cm.state.focused; + return result; + }, + + showSelection: function(info) { + if (!info || !this.cm.display.view.length) return; + if (info.focus) this.showPrimarySelection(); + this.showMultipleSelections(info); + }, + + showPrimarySelection: function() { + var sel = window.getSelection(), prim = this.cm.doc.sel.primary(); + var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset); + var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset); + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && + cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && + cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) + return; + + var start = posToDOM(this.cm, prim.from()); + var end = posToDOM(this.cm, prim.to()); + if (!start && !end) return; + + var view = this.cm.display.view; + var old = sel.rangeCount && sel.getRangeAt(0); + if (!start) { + start = {node: view[0].measure.map[2], offset: 0}; + } else if (!end) { // FIXME dangerously hacky + var measure = view[view.length - 1].measure; + var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; + end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; + } + + try { var rng = range(start.node, start.offset, end.offset, end.node); } + catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible + if (rng) { + sel.removeAllRanges(); + sel.addRange(rng); + if (old && sel.anchorNode == null) sel.addRange(old); + else if (gecko) this.startGracePeriod(); + } + this.rememberSelection(); + }, + + startGracePeriod: function() { + var input = this; + clearTimeout(this.gracePeriod); + this.gracePeriod = setTimeout(function() { + input.gracePeriod = false; + if (input.selectionChanged()) + input.cm.operation(function() { input.cm.curOp.selectionChanged = true; }); + }, 20); + }, + + showMultipleSelections: function(info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); + }, + + rememberSelection: function() { + var sel = window.getSelection(); + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; + }, + + selectionInEditor: function() { + var sel = window.getSelection(); + if (!sel.rangeCount) return false; + var node = sel.getRangeAt(0).commonAncestorContainer; + return contains(this.div, node); + }, + + focus: function() { + if (this.cm.options.readOnly != "nocursor") this.div.focus(); + }, + blur: function() { this.div.blur(); }, + getField: function() { return this.div; }, + + supportsTouch: function() { return true; }, + + receivedFocus: function() { + var input = this; + if (this.selectionInEditor()) + this.pollSelection(); + else + runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; }); + + function poll() { + if (input.cm.state.focused) { + input.pollSelection(); + input.polling.set(input.cm.options.pollInterval, poll); + } + } + this.polling.set(this.cm.options.pollInterval, poll); + }, + + selectionChanged: function() { + var sel = window.getSelection(); + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; + }, + + pollSelection: function() { + if (!this.composing && !this.gracePeriod && this.selectionChanged()) { + var sel = window.getSelection(), cm = this.cm; + this.rememberSelection(); + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var head = domToPos(cm, sel.focusNode, sel.focusOffset); + if (anchor && head) runInOp(cm, function() { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); + if (anchor.bad || head.bad) cm.curOp.selectionChanged = true; + }); + } + }, + + pollContent: function() { + var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); + var from = sel.from(), to = sel.to(); + if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false; + + var fromIndex; + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + var fromLine = lineNo(display.view[0].line); + var fromNode = display.view[0].node; + } else { + var fromLine = lineNo(display.view[fromIndex].line); + var fromNode = display.view[fromIndex - 1].node.nextSibling; + } + var toIndex = findViewIndex(cm, to.line); + if (toIndex == display.view.length - 1) { + var toLine = display.viewTo - 1; + var toNode = display.lineDiv.lastChild; + } else { + var toLine = lineNo(display.view[toIndex + 1].line) - 1; + var toNode = display.view[toIndex + 1].node.previousSibling; + } + + var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } + else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } + else break; + } + + var cutFront = 0, cutEnd = 0; + var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) + ++cutFront; + var newBot = lst(newText), oldBot = lst(oldText); + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0)); + while (cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) + ++cutEnd; + + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd); + newText[0] = newText[0].slice(cutFront); + + var chFrom = Pos(fromLine, cutFront); + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input"); + return true; + } + }, + + ensurePolled: function() { + this.forceCompositionEnd(); + }, + reset: function() { + this.forceCompositionEnd(); + }, + forceCompositionEnd: function() { + if (!this.composing || this.composing.handled) return; + this.applyComposition(this.composing); + this.composing.handled = true; + this.div.blur(); + this.div.focus(); + }, + applyComposition: function(composing) { + if (composing.data && composing.data != composing.startData) + operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel); + }, + + setUneditable: function(node) { + node.setAttribute("contenteditable", "false"); + }, + + onKeyPress: function(e) { + e.preventDefault(); + operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); + }, + + onContextMenu: nothing, + resetPosition: nothing, + + needsContentAttribute: true + }, ContentEditableInput.prototype); + + function posToDOM(cm, pos) { + var view = findViewForLine(cm, pos.line); + if (!view || view.hidden) return null; + var line = getLine(cm.doc, pos.line); + var info = mapFromLineView(view, line, pos.line); + + var order = getOrder(line), side = "left"; + if (order) { + var partPos = getBidiPartAt(order, pos.ch); + side = partPos % 2 ? "right" : "left"; + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); + result.offset = result.collapse == "right" ? result.end : result.start; + return result; + } + + function badPos(pos, bad) { if (bad) pos.bad = true; return pos; } + + function domToPos(cm, node, offset) { + var lineNode; + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset]; + if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); + node = null; offset = 0; + } else { + for (lineNode = node;; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) return null; + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break; + } + } + for (var i = 0; i < cm.display.view.length; i++) { + var lineView = cm.display.view[i]; + if (lineView.node == lineNode) + return locateNodeInLineView(lineView, node, offset); + } + } + + function locateNodeInLineView(lineView, node, offset) { + var wrapper = lineView.text.firstChild, bad = false; + if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true); + if (node == wrapper) { + bad = true; + node = wrapper.childNodes[offset]; + offset = 0; + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line; + return badPos(Pos(lineNo(line), line.text.length), bad); + } + } + + var textNode = node.nodeType == 3 ? node : null, topNode = node; + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild; + if (offset) offset = textNode.nodeValue.length; + } + while (topNode.parentNode != wrapper) topNode = topNode.parentNode; + var measure = lineView.measure, maps = measure.maps; + + function find(textNode, topNode, offset) { + for (var i = -1; i < (maps ? maps.length : 0); i++) { + var map = i < 0 ? measure.map : maps[i]; + for (var j = 0; j < map.length; j += 3) { + var curNode = map[j + 2]; + if (curNode == textNode || curNode == topNode) { + var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); + var ch = map[j] + offset; + if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]; + return Pos(line, ch); + } + } + } + } + var found = find(textNode, topNode, offset); + if (found) return badPos(found, bad); + + // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0); + if (found) + return badPos(Pos(found.line, found.ch - dist), bad); + else + dist += after.textContent.length; + } + for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1); + if (found) + return badPos(Pos(found.line, found.ch + dist), bad); + else + dist += after.textContent.length; + } + } + + function domTextBetween(cm, from, to, fromLine, toLine) { + var text = "", closing = false, lineSep = cm.doc.lineSeparator(); + function recognizeMarker(id) { return function(marker) { return marker.id == id; }; } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text"); + if (cmText != null) { + if (cmText == "") cmText = node.textContent.replace(/\u200b/g, ""); + text += cmText; + return; + } + var markerID = node.getAttribute("cm-marker"), range; + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); + if (found.length && (range = found[0].find())) + text += getBetween(cm.doc, range.from, range.to).join(lineSep); + return; + } + if (node.getAttribute("contenteditable") == "false") return; + for (var i = 0; i < node.childNodes.length; i++) + walk(node.childNodes[i]); + if (/^(pre|div|p)$/i.test(node.nodeName)) + closing = true; + } else if (node.nodeType == 3) { + var val = node.nodeValue; + if (!val) return; + if (closing) { + text += lineSep; + closing = false; + } + text += val; + } + } + for (;;) { + walk(from); + if (from == to) break; + from = from.nextSibling; + } + return text; + } + + CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; + + // SELECTION / CURSOR + + // Selection objects are immutable. A new one is created every time + // the selection changes. A selection is one or more non-overlapping + // (and non-touching) ranges, sorted, and an integer that indicates + // which one is the primary selection (the one that's scrolled into + // view, that getCursor returns, etc). + function Selection(ranges, primIndex) { + this.ranges = ranges; + this.primIndex = primIndex; + } + + Selection.prototype = { + primary: function() { return this.ranges[this.primIndex]; }, + equals: function(other) { + if (other == this) return true; + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; + for (var i = 0; i < this.ranges.length; i++) { + var here = this.ranges[i], there = other.ranges[i]; + if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; + } + return true; + }, + deepCopy: function() { + for (var out = [], i = 0; i < this.ranges.length; i++) + out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); + return new Selection(out, this.primIndex); + }, + somethingSelected: function() { + for (var i = 0; i < this.ranges.length; i++) + if (!this.ranges[i].empty()) return true; + return false; + }, + contains: function(pos, end) { + if (!end) end = pos; + for (var i = 0; i < this.ranges.length; i++) { + var range = this.ranges[i]; + if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) + return i; + } + return -1; + } + }; + + function Range(anchor, head) { + this.anchor = anchor; this.head = head; + } + + Range.prototype = { + from: function() { return minPos(this.anchor, this.head); }, + to: function() { return maxPos(this.anchor, this.head); }, + empty: function() { + return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; + } + }; + + // Take an unsorted, potentially overlapping set of ranges, and + // build a selection out of it. 'Consumes' ranges array (modifying + // it). + function normalizeSelection(ranges, primIndex) { + var prim = ranges[primIndex]; + ranges.sort(function(a, b) { return cmp(a.from(), b.from()); }); + primIndex = indexOf(ranges, prim); + for (var i = 1; i < ranges.length; i++) { + var cur = ranges[i], prev = ranges[i - 1]; + if (cmp(prev.to(), cur.from()) >= 0) { + var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; + if (i <= primIndex) --primIndex; + ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); + } + } + return new Selection(ranges, primIndex); + } + + function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0); + } + + // Most of the external API clips given positions to make sure they + // actually exist within the document. + function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} + function clipPos(doc, pos) { + if (pos.line < doc.first) return Pos(doc.first, 0); + var last = doc.first + doc.size - 1; + if (pos.line > last) return Pos(last, getLine(doc, last).text.length); + return clipToLen(pos, getLine(doc, pos.line).text.length); + } + function clipToLen(pos, linelen) { + var ch = pos.ch; + if (ch == null || ch > linelen) return Pos(pos.line, linelen); + else if (ch < 0) return Pos(pos.line, 0); + else return pos; + } + function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} + function clipPosArray(doc, array) { + for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); + return out; + } + + // SELECTION UPDATES + + // The 'scroll' parameter given to many of these indicated whether + // the new cursor position should be scrolled into view after + // modifying the selection. + + // If shift is held or the extend flag is set, extends a range to + // include a given position (and optionally a second position). + // Otherwise, simply returns the range between the given positions. + // Used for cursor motion and such. + function extendRange(doc, range, head, other) { + if (doc.cm && doc.cm.display.shift || doc.extend) { + var anchor = range.anchor; + if (other) { + var posBefore = cmp(head, anchor) < 0; + if (posBefore != (cmp(other, anchor) < 0)) { + anchor = head; + head = other; + } else if (posBefore != (cmp(head, other) < 0)) { + head = other; + } + } + return new Range(anchor, head); + } else { + return new Range(other || head, head); + } + } + + // Extend the primary selection range, discard the rest. + function extendSelection(doc, head, other, options) { + setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); + } + + // Extend all selections (pos is an array of selections with length + // equal the number of selections) + function extendSelections(doc, heads, options) { + for (var out = [], i = 0; i < doc.sel.ranges.length; i++) + out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); + var newSel = normalizeSelection(out, doc.sel.primIndex); + setSelection(doc, newSel, options); + } + + // Updates a single range in the selection. + function replaceOneSelection(doc, i, range, options) { + var ranges = doc.sel.ranges.slice(0); + ranges[i] = range; + setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); + } + + // Reset the selection to a single range. + function setSimpleSelection(doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options); + } + + // Give beforeSelectionChange handlers a change to influence a + // selection update. + function filterSelectionChange(doc, sel) { + var obj = { + ranges: sel.ranges, + update: function(ranges) { + this.ranges = []; + for (var i = 0; i < ranges.length; i++) + this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), + clipPos(doc, ranges[i].head)); + } + }; + signal(doc, "beforeSelectionChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); + if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); + else return sel; + } + + function setSelectionReplaceHistory(doc, sel, options) { + var done = doc.history.done, last = lst(done); + if (last && last.ranges) { + done[done.length - 1] = sel; + setSelectionNoUndo(doc, sel, options); + } else { + setSelection(doc, sel, options); + } + } + + // Set a new selection. + function setSelection(doc, sel, options) { + setSelectionNoUndo(doc, sel, options); + addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); + } + + function setSelectionNoUndo(doc, sel, options) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) + sel = filterSelectionChange(doc, sel); + + var bias = options && options.bias || + (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); + setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); + + if (!(options && options.scroll === false) && doc.cm) + ensureCursorVisible(doc.cm); + } + + function setSelectionInner(doc, sel) { + if (sel.equals(doc.sel)) return; + + doc.sel = sel; + + if (doc.cm) { + doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; + signalCursorActivity(doc.cm); + } + signalLater(doc, "cursorActivity", doc); + } + + // Verify that the selection does not partially select any atomic + // marked ranges. + function reCheckSelection(doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); + } + + // Return a selection that does not partially select any atomic + // ranges. + function skipAtomicInSelection(doc, sel, bias, mayClear) { + var out; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear); + var newHead = skipAtomic(doc, range.head, bias, mayClear); + if (out || newAnchor != range.anchor || newHead != range.head) { + if (!out) out = sel.ranges.slice(0, i); + out[i] = new Range(newAnchor, newHead); + } + } + return out ? normalizeSelection(out, sel.primIndex) : sel; + } + + // Ensure a given position is not inside an atomic range. + function skipAtomic(doc, pos, bias, mayClear) { + var flipped = false, curPos = pos; + var dir = bias || 1; + doc.cantEdit = false; + search: for (;;) { + var line = getLine(doc, curPos.line); + if (line.markedSpans) { + for (var i = 0; i < line.markedSpans.length; ++i) { + var sp = line.markedSpans[i], m = sp.marker; + if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && + (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter"); + if (m.explicitlyCleared) { + if (!line.markedSpans) break; + else {--i; continue;} + } + } + if (!m.atomic) continue; + var newPos = m.find(dir < 0 ? -1 : 1); + if (cmp(newPos, curPos) == 0) { + newPos.ch += dir; + if (newPos.ch < 0) { + if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); + else newPos = null; + } else if (newPos.ch > line.text.length) { + if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); + else newPos = null; + } + if (!newPos) { + if (flipped) { + // Driven in a corner -- no valid cursor position found at all + // -- try again *with* clearing, if we didn't already + if (!mayClear) return skipAtomic(doc, pos, bias, true); + // Otherwise, turn off editing until further notice, and return the start of the doc + doc.cantEdit = true; + return Pos(doc.first, 0); + } + flipped = true; newPos = pos; dir = -dir; + } + } + curPos = newPos; + continue search; + } + } + } + return curPos; + } + } + + // SELECTION DRAWING + + function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()); + } + + function prepareSelection(cm, primary) { + var doc = cm.doc, result = {}; + var curFragment = result.cursors = document.createDocumentFragment(); + var selFragment = result.selection = document.createDocumentFragment(); + + for (var i = 0; i < doc.sel.ranges.length; i++) { + if (primary === false && i == doc.sel.primIndex) continue; + var range = doc.sel.ranges[i]; + var collapsed = range.empty(); + if (collapsed || cm.options.showCursorWhenSelecting) + drawSelectionCursor(cm, range.head, curFragment); + if (!collapsed) + drawSelectionRange(cm, range, selFragment); + } + return result; + } + + // Draws a cursor for the given range + function drawSelectionCursor(cm, head, output) { + var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); + + var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); + cursor.style.left = pos.left + "px"; + cursor.style.top = pos.top + "px"; + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; + + if (pos.other) { + // Secondary cursor, shown when on a 'jump' in bi-directional text + var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); + otherCursor.style.display = ""; + otherCursor.style.left = pos.other.left + "px"; + otherCursor.style.top = pos.other.top + "px"; + otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; + } + } + + // Draws the given range as a highlighted selection + function drawSelectionRange(cm, range, output) { + var display = cm.display, doc = cm.doc; + var fragment = document.createDocumentFragment(); + var padding = paddingH(cm.display), leftSide = padding.left; + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; + + function add(left, top, width, bottom) { + if (top < 0) top = 0; + top = Math.round(top); + bottom = Math.round(bottom); + fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + + "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + + "px; height: " + (bottom - top) + "px")); + } + + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc, line); + var lineLen = lineObj.text.length; + var start, end; + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias); + } + + iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { + var leftPos = coords(from, "left"), rightPos, left, right; + if (from == to) { + rightPos = leftPos; + left = right = leftPos.left; + } else { + rightPos = coords(to - 1, "right"); + if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } + left = leftPos.left; + right = rightPos.right; + } + if (fromArg == null && from == 0) left = leftSide; + if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part + add(left, leftPos.top, null, leftPos.bottom); + left = leftSide; + if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); + } + if (toArg == null && to == lineLen) right = rightSide; + if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) + start = leftPos; + if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) + end = rightPos; + if (left < leftSide + 1) left = leftSide; + add(left, rightPos.top, right - left, rightPos.bottom); + }); + return {start: start, end: end}; + } + + var sFrom = range.from(), sTo = range.to(); + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch); + } else { + var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); + var singleVLine = visualLine(fromLine) == visualLine(toLine); + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); + } + } + if (leftEnd.bottom < rightStart.top) + add(leftSide, leftEnd.bottom, null, rightStart.top); + } + + output.appendChild(fragment); + } + + // Cursor-blinking + function restartBlink(cm) { + if (!cm.state.focused) return; + var display = cm.display; + clearInterval(display.blinker); + var on = true; + display.cursorDiv.style.visibility = ""; + if (cm.options.cursorBlinkRate > 0) + display.blinker = setInterval(function() { + display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; + }, cm.options.cursorBlinkRate); + else if (cm.options.cursorBlinkRate < 0) + display.cursorDiv.style.visibility = "hidden"; + } + + // HIGHLIGHT WORKER + + function startWorker(cm, time) { + if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) + cm.state.highlight.set(time, bind(highlightWorker, cm)); + } + + function highlightWorker(cm) { + var doc = cm.doc; + if (doc.frontier < doc.first) doc.frontier = doc.first; + if (doc.frontier >= cm.display.viewTo) return; + var end = +new Date + cm.options.workTime; + var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); + var changedLines = []; + + doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) { + if (doc.frontier >= cm.display.viewFrom) { // Visible + var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength; + var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true); + line.styles = highlighted.styles; + var oldCls = line.styleClasses, newCls = highlighted.classes; + if (newCls) line.styleClasses = newCls; + else if (oldCls) line.styleClasses = null; + var ischange = !oldStyles || oldStyles.length != line.styles.length || + oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); + for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; + if (ischange) changedLines.push(doc.frontier); + line.stateAfter = tooLong ? state : copyState(doc.mode, state); + } else { + if (line.text.length <= cm.options.maxHighlightLength) + processLine(cm, line.text, state); + line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; + } + ++doc.frontier; + if (+new Date > end) { + startWorker(cm, cm.options.workDelay); + return true; + } + }); + if (changedLines.length) runInOp(cm, function() { + for (var i = 0; i < changedLines.length; i++) + regLineChange(cm, changedLines[i], "text"); + }); + } + + // Finds the line to start with when starting a parse. Tries to + // find a line with a stateAfter, so that it can start with a + // valid state. If that fails, it returns the line with the + // smallest indentation, which tends to need the least context to + // parse correctly. + function findStartLine(cm, n, precise) { + var minindent, minline, doc = cm.doc; + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); + for (var search = n; search > lim; --search) { + if (search <= doc.first) return doc.first; + var line = getLine(doc, search - 1); + if (line.stateAfter && (!precise || search <= doc.frontier)) return search; + var indented = countColumn(line.text, null, cm.options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline; + } + + function getStateBefore(cm, n, precise) { + var doc = cm.doc, display = cm.display; + if (!doc.mode.startState) return true; + var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; + if (!state) state = startState(doc.mode); + else state = copyState(doc.mode, state); + doc.iter(pos, n, function(line) { + processLine(cm, line.text, state); + var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; + line.stateAfter = save ? copyState(doc.mode, state) : null; + ++pos; + }); + if (precise) doc.frontier = pos; + return state; + } + + // POSITION MEASUREMENT + + function paddingTop(display) {return display.lineSpace.offsetTop;} + function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} + function paddingH(display) { + if (display.cachedPaddingH) return display.cachedPaddingH; + var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; + var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; + if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data; + return data; + } + + function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; } + function displayWidth(cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; + } + function displayHeight(cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; + } + + // Ensure the lineView.wrapping.heights array is populated. This is + // an array of bottom offsets for the lines that make up a drawn + // line. When lineWrapping is on, there might be more than one + // height. + function ensureLineHeights(cm, lineView, rect) { + var wrapping = cm.options.lineWrapping; + var curWidth = wrapping && displayWidth(cm); + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = []; + if (wrapping) { + lineView.measure.width = curWidth; + var rects = lineView.text.firstChild.getClientRects(); + for (var i = 0; i < rects.length - 1; i++) { + var cur = rects[i], next = rects[i + 1]; + if (Math.abs(cur.bottom - next.bottom) > 2) + heights.push((cur.bottom + next.top) / 2 - rect.top); + } + } + heights.push(rect.bottom - rect.top); + } + } + + // Find a line map (mapping character offsets to text nodes) and a + // measurement cache for the given line number. (A line view might + // contain multiple lines when collapsed ranges are present.) + function mapFromLineView(lineView, line, lineN) { + if (lineView.line == line) + return {map: lineView.measure.map, cache: lineView.measure.cache}; + for (var i = 0; i < lineView.rest.length; i++) + if (lineView.rest[i] == line) + return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]}; + for (var i = 0; i < lineView.rest.length; i++) + if (lineNo(lineView.rest[i]) > lineN) + return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true}; + } + + // Render a line into the hidden node display.externalMeasured. Used + // when measurement is needed for a line that's not in the viewport. + function updateExternalMeasurement(cm, line) { + line = visualLine(line); + var lineN = lineNo(line); + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); + view.lineN = lineN; + var built = view.built = buildLineContent(cm, view); + view.text = built.pre; + removeChildrenAndAdd(cm.display.lineMeasure, built.pre); + return view; + } + + // Get a {top, bottom, left, right} box (in line-local coordinates) + // for a given character. + function measureChar(cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); + } + + // Find a line view that corresponds to the given line number. + function findViewForLine(cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) + return cm.display.view[findViewIndex(cm, lineN)]; + var ext = cm.display.externalMeasured; + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) + return ext; + } + + // Measurement can be split in two steps, the set-up work that + // applies to the whole line, and the measurement of the actual + // character. Functions like coordsChar, that need to do a lot of + // measurements in a row, can thus ensure that the set-up work is + // only done once. + function prepareMeasureForLine(cm, line) { + var lineN = lineNo(line); + var view = findViewForLine(cm, lineN); + if (view && !view.text) { + view = null; + } else if (view && view.changes) { + updateLineForChanges(cm, view, lineN, getDimensions(cm)); + cm.curOp.forceUpdate = true; + } + if (!view) + view = updateExternalMeasurement(cm, line); + + var info = mapFromLineView(view, line, lineN); + return { + line: line, view: view, rect: null, + map: info.map, cache: info.cache, before: info.before, + hasHeights: false + }; + } + + // Given a prepared measurement object, measures the position of an + // actual character (or fetches it from the cache). + function measureCharPrepared(cm, prepared, ch, bias, varHeight) { + if (prepared.before) ch = -1; + var key = ch + (bias || ""), found; + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key]; + } else { + if (!prepared.rect) + prepared.rect = prepared.view.text.getBoundingClientRect(); + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect); + prepared.hasHeights = true; + } + found = measureCharInner(cm, prepared, ch, bias); + if (!found.bogus) prepared.cache[key] = found; + } + return {left: found.left, right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom}; + } + + var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; + + function nodeAndOffsetInLineMap(map, ch, bias) { + var node, start, end, collapse; + // First, search the line map for the text node corresponding to, + // or closest to, the target character. + for (var i = 0; i < map.length; i += 3) { + var mStart = map[i], mEnd = map[i + 1]; + if (ch < mStart) { + start = 0; end = 1; + collapse = "left"; + } else if (ch < mEnd) { + start = ch - mStart; + end = start + 1; + } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { + end = mEnd - mStart; + start = end - 1; + if (ch >= mEnd) collapse = "right"; + } + if (start != null) { + node = map[i + 2]; + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) + collapse = bias; + if (bias == "left" && start == 0) + while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { + node = map[(i -= 3) + 2]; + collapse = "left"; + } + if (bias == "right" && start == mEnd - mStart) + while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { + node = map[(i += 3) + 2]; + collapse = "right"; + } + break; + } + } + return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}; + } + + function measureCharInner(cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); + var node = place.node, start = place.start, end = place.end, collapse = place.collapse; + + var rect; + if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. + for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start; + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end; + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { + rect = node.parentNode.getBoundingClientRect(); + } else if (ie && cm.options.lineWrapping) { + var rects = range(node, start, end).getClientRects(); + if (rects.length) + rect = rects[bias == "right" ? rects.length - 1 : 0]; + else + rect = nullRect; + } else { + rect = range(node, start, end).getBoundingClientRect() || nullRect; + } + if (rect.left || rect.right || start == 0) break; + end = start; + start = start - 1; + collapse = "right"; + } + if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect); + } else { // If it is a widget, simply get the box for the whole widget. + if (start > 0) collapse = bias = "right"; + var rects; + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) + rect = rects[bias == "right" ? rects.length - 1 : 0]; + else + rect = node.getBoundingClientRect(); + } + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0]; + if (rSpan) + rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; + else + rect = nullRect; + } + + var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; + var mid = (rtop + rbot) / 2; + var heights = prepared.view.measure.heights; + for (var i = 0; i < heights.length - 1; i++) + if (mid < heights[i]) break; + var top = i ? heights[i - 1] : 0, bot = heights[i]; + var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top: top, bottom: bot}; + if (!rect.left && !rect.right) result.bogus = true; + if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } + + return result; + } + + // Work around problem with bounding client rects on ranges being + // returned incorrectly when zoomed on IE10 and below. + function maybeUpdateRectForZooming(measure, rect) { + if (!window.screen || screen.logicalXDPI == null || + screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) + return rect; + var scaleX = screen.logicalXDPI / screen.deviceXDPI; + var scaleY = screen.logicalYDPI / screen.deviceYDPI; + return {left: rect.left * scaleX, right: rect.right * scaleX, + top: rect.top * scaleY, bottom: rect.bottom * scaleY}; + } + + function clearLineMeasurementCacheFor(lineView) { + if (lineView.measure) { + lineView.measure.cache = {}; + lineView.measure.heights = null; + if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) + lineView.measure.caches[i] = {}; + } + } + + function clearLineMeasurementCache(cm) { + cm.display.externalMeasure = null; + removeChildren(cm.display.lineMeasure); + for (var i = 0; i < cm.display.view.length; i++) + clearLineMeasurementCacheFor(cm.display.view[i]); + } + + function clearCaches(cm) { + clearLineMeasurementCache(cm); + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; + if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; + cm.display.lineNumChars = null; + } + + function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } + function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } + + // Converts a {top, bottom, left, right} box from line-local + // coordinates into another coordinate system. Context may be one of + // "line", "div" (display.lineDiv), "local"/null (editor), "window", + // or "page". + function intoCoordSystem(cm, lineObj, rect, context) { + if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { + var size = widgetHeight(lineObj.widgets[i]); + rect.top += size; rect.bottom += size; + } + if (context == "line") return rect; + if (!context) context = "local"; + var yOff = heightAtLine(lineObj); + if (context == "local") yOff += paddingTop(cm.display); + else yOff -= cm.display.viewOffset; + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect(); + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); + rect.left += xOff; rect.right += xOff; + } + rect.top += yOff; rect.bottom += yOff; + return rect; + } + + // Coverts a box from "div" coords to another coordinate system. + // Context may be "window", "page", "div", or "local"/null. + function fromCoordSystem(cm, coords, context) { + if (context == "div") return coords; + var left = coords.left, top = coords.top; + // First move into "page" coordinate system + if (context == "page") { + left -= pageScrollX(); + top -= pageScrollY(); + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect(); + left += localBox.left; + top += localBox.top; + } + + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; + } + + function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) lineObj = getLine(cm.doc, pos.line); + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); + } + + // Returns a box for a given cursor position, which may have an + // 'other' property containing the position of the secondary cursor + // on a bidi boundary. + function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line); + if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); + function get(ch, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); + if (right) m.left = m.right; else m.right = m.left; + return intoCoordSystem(cm, lineObj, m, context); + } + function getBidi(ch, partPos) { + var part = order[partPos], right = part.level % 2; + if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { + part = order[--partPos]; + ch = bidiRight(part) - (part.level % 2 ? 0 : 1); + right = true; + } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { + part = order[++partPos]; + ch = bidiLeft(part) - part.level % 2; + right = false; + } + if (right && ch == part.to && ch > part.from) return get(ch - 1); + return get(ch, right); + } + var order = getOrder(lineObj), ch = pos.ch; + if (!order) return get(ch); + var partPos = getBidiPartAt(order, ch); + var val = getBidi(ch, partPos); + if (bidiOther != null) val.other = getBidi(ch, bidiOther); + return val; + } + + // Used to cheaply estimate the coordinates for a position. Used for + // intermediate scroll updates. + function estimateCoords(cm, pos) { + var left = 0, pos = clipPos(cm.doc, pos); + if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; + var lineObj = getLine(cm.doc, pos.line); + var top = heightAtLine(lineObj) + paddingTop(cm.display); + return {left: left, right: left, top: top, bottom: top + lineObj.height}; + } + + // Positions returned by coordsChar contain some extra information. + // xRel is the relative x position of the input coordinates compared + // to the found position (so xRel > 0 means the coordinates are to + // the right of the character position, for example). When outside + // is true, that means the coordinates lie outside the line's + // vertical range. + function PosWithInfo(line, ch, outside, xRel) { + var pos = Pos(line, ch); + pos.xRel = xRel; + if (outside) pos.outside = true; + return pos; + } + + // Compute the character position closest to the given coordinates. + // Input must be lineSpace-local ("div" coordinate system). + function coordsChar(cm, x, y) { + var doc = cm.doc; + y += cm.display.viewOffset; + if (y < 0) return PosWithInfo(doc.first, 0, true, -1); + var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; + if (lineN > last) + return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); + if (x < 0) x = 0; + + var lineObj = getLine(doc, lineN); + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y); + var merged = collapsedSpanAtEnd(lineObj); + var mergedPos = merged && merged.find(0, true); + if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) + lineN = lineNo(lineObj = mergedPos.to.line); + else + return found; + } + } + + function coordsCharInner(cm, lineObj, lineNo, x, y) { + var innerOff = y - heightAtLine(lineObj); + var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; + var preparedMeasure = prepareMeasureForLine(cm, lineObj); + + function getX(ch) { + var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); + wrongLine = true; + if (innerOff > sp.bottom) return sp.left - adjust; + else if (innerOff < sp.top) return sp.left + adjust; + else wrongLine = false; + return sp.left; + } + + var bidi = getOrder(lineObj), dist = lineObj.text.length; + var from = lineLeft(lineObj), to = lineRight(lineObj); + var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; + + if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); + // Do a binary search between these bounds. + for (;;) { + if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { + var ch = x < fromX || x - fromX <= toX - x ? from : to; + var xDiff = x - (ch == from ? fromX : toX); + while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; + var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, + xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); + return pos; + } + var step = Math.ceil(dist / 2), middle = from + step; + if (bidi) { + middle = from; + for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); + } + var middleX = getX(middle); + if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} + else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} + } + } + + var measureText; + // Compute the default text height. + function textHeight(display) { + if (display.cachedTextHeight != null) return display.cachedTextHeight; + if (measureText == null) { + measureText = elt("pre"); + // Measure a bunch of lines, for browsers that compute + // fractional heights. + for (var i = 0; i < 49; ++i) { + measureText.appendChild(document.createTextNode("x")); + measureText.appendChild(elt("br")); + } + measureText.appendChild(document.createTextNode("x")); + } + removeChildrenAndAdd(display.measure, measureText); + var height = measureText.offsetHeight / 50; + if (height > 3) display.cachedTextHeight = height; + removeChildren(display.measure); + return height || 1; + } + + // Compute the default character width. + function charWidth(display) { + if (display.cachedCharWidth != null) return display.cachedCharWidth; + var anchor = elt("span", "xxxxxxxxxx"); + var pre = elt("pre", [anchor]); + removeChildrenAndAdd(display.measure, pre); + var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; + if (width > 2) display.cachedCharWidth = width; + return width || 10; + } + + // OPERATIONS + + // Operations are used to wrap a series of changes to the editor + // state in such a way that each change won't have to update the + // cursor and display (which would be awkward, slow, and + // error-prone). Instead, display updates are batched and then all + // combined and executed at once. + + var operationGroup = null; + + var nextOpId = 0; + // Start a new operation. + function startOperation(cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: null, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId // Unique ID + }; + if (operationGroup) { + operationGroup.ops.push(cm.curOp); + } else { + cm.curOp.ownsGroup = operationGroup = { + ops: [cm.curOp], + delayedCallbacks: [] + }; + } + } + + function fireCallbacksForOps(group) { + // Calls delayed callbacks and cursorActivity handlers until no + // new ones appear + var callbacks = group.delayedCallbacks, i = 0; + do { + for (; i < callbacks.length; i++) + callbacks[i].call(null); + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j]; + if (op.cursorActivityHandlers) + while (op.cursorActivityCalled < op.cursorActivityHandlers.length) + op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); + } + } while (i < callbacks.length); + } + + // Finish an operation, updating the display and signalling delayed events + function endOperation(cm) { + var op = cm.curOp, group = op.ownsGroup; + if (!group) return; + + try { fireCallbacksForOps(group); } + finally { + operationGroup = null; + for (var i = 0; i < group.ops.length; i++) + group.ops[i].cm.curOp = null; + endOperations(group); + } + } + + // The DOM updates done when an operation finishes are batched so + // that the minimum number of relayouts are required. + function endOperations(group) { + var ops = group.ops; + for (var i = 0; i < ops.length; i++) // Read DOM + endOperation_R1(ops[i]); + for (var i = 0; i < ops.length; i++) // Write DOM (maybe) + endOperation_W1(ops[i]); + for (var i = 0; i < ops.length; i++) // Read DOM + endOperation_R2(ops[i]); + for (var i = 0; i < ops.length; i++) // Write DOM (maybe) + endOperation_W2(ops[i]); + for (var i = 0; i < ops.length; i++) // Read DOM + endOperation_finish(ops[i]); + } + + function endOperation_R1(op) { + var cm = op.cm, display = cm.display; + maybeClipScrollbars(cm); + if (op.updateMaxLine) findMaxLine(cm); + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo) || + display.maxLineChanged && cm.options.lineWrapping; + op.update = op.mustUpdate && + new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); + } + + function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); + } + + function endOperation_R2(op) { + var cm = op.cm, display = cm.display; + if (op.updatedDisplay) updateHeightsInViewport(cm); + + op.barMeasure = measureForScrollbars(cm); + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; + cm.display.sizerWidth = op.adjustWidthTo; + op.barMeasure.scrollWidth = + Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); + } + + if (op.updatedDisplay || op.selectionChanged) + op.preparedSelection = display.input.prepareSelection(); + } + + function endOperation_W2(op) { + var cm = op.cm; + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; + if (op.maxScrollLeft < cm.doc.scrollLeft) + setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); + cm.display.maxLineChanged = false; + } + + if (op.preparedSelection) + cm.display.input.showSelection(op.preparedSelection); + if (op.updatedDisplay) + setDocumentHeight(cm, op.barMeasure); + if (op.updatedDisplay || op.startHeight != cm.doc.height) + updateScrollbars(cm, op.barMeasure); + + if (op.selectionChanged) restartBlink(cm); + + if (cm.state.focused && op.updateInput) + cm.display.input.reset(op.typing); + if (op.focus && op.focus == activeElt()) ensureFocus(op.cm); + } + + function endOperation_finish(op) { + var cm = op.cm, display = cm.display, doc = cm.doc; + + if (op.updatedDisplay) postUpdateDisplay(cm, op.update); + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) + display.wheelStartX = display.wheelStartY = null; + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { + doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); + display.scrollbars.setScrollTop(doc.scrollTop); + display.scroller.scrollTop = doc.scrollTop; + } + if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { + doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft)); + display.scrollbars.setScrollLeft(doc.scrollLeft); + display.scroller.scrollLeft = doc.scrollLeft; + alignHorizontally(cm); + } + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); + if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; + if (hidden) for (var i = 0; i < hidden.length; ++i) + if (!hidden[i].lines.length) signal(hidden[i], "hide"); + if (unhidden) for (var i = 0; i < unhidden.length; ++i) + if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); + + if (display.wrapper.offsetHeight) + doc.scrollTop = cm.display.scroller.scrollTop; + + // Fire change events, and delayed event handlers + if (op.changeObjs) + signal(cm, "changes", cm, op.changeObjs); + if (op.update) + op.update.finish(); + } + + // Run the given function in an operation + function runInOp(cm, f) { + if (cm.curOp) return f(); + startOperation(cm); + try { return f(); } + finally { endOperation(cm); } + } + // Wraps a function in an operation. Returns the wrapped function. + function operation(cm, f) { + return function() { + if (cm.curOp) return f.apply(cm, arguments); + startOperation(cm); + try { return f.apply(cm, arguments); } + finally { endOperation(cm); } + }; + } + // Used to add methods to editor and doc instances, wrapping them in + // operations. + function methodOp(f) { + return function() { + if (this.curOp) return f.apply(this, arguments); + startOperation(this); + try { return f.apply(this, arguments); } + finally { endOperation(this); } + }; + } + function docMethodOp(f) { + return function() { + var cm = this.cm; + if (!cm || cm.curOp) return f.apply(this, arguments); + startOperation(cm); + try { return f.apply(this, arguments); } + finally { endOperation(cm); } + }; + } + + // VIEW TRACKING + + // These objects are used to represent the visible (currently drawn) + // part of the document. A LineView may correspond to multiple + // logical lines, if those are connected by collapsed ranges. + function LineView(doc, line, lineN) { + // The starting line + this.line = line; + // Continuing lines, if any + this.rest = visualLineContinued(line); + // Number of logical lines in this visual line + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; + this.node = this.text = null; + this.hidden = lineIsHidden(doc, line); + } + + // Create a range of LineView objects for the given lines. + function buildViewArray(cm, from, to) { + var array = [], nextPos; + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); + nextPos = pos + view.size; + array.push(view); + } + return array; + } + + // Updates the display.view data structure for a given change to the + // document. From and to are in pre-change coordinates. Lendiff is + // the amount of lines added or subtracted by the change. This is + // used for changes that span multiple lines, or change the way + // lines are divided into visual lines. regLineChange (below) + // registers single-line changes. + function regChange(cm, from, to, lendiff) { + if (from == null) from = cm.doc.first; + if (to == null) to = cm.doc.first + cm.doc.size; + if (!lendiff) lendiff = 0; + + var display = cm.display; + if (lendiff && to < display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers > from)) + display.updateLineNumbers = from; + + cm.curOp.viewChanged = true; + + if (from >= display.viewTo) { // Change after + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) + resetView(cm); + } else if (to <= display.viewFrom) { // Change before + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm); + } else { + display.viewFrom += lendiff; + display.viewTo += lendiff; + } + } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap + resetView(cm); + } else if (from <= display.viewFrom) { // Top overlap + var cut = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cut) { + display.view = display.view.slice(cut.index); + display.viewFrom = cut.lineN; + display.viewTo += lendiff; + } else { + resetView(cm); + } + } else if (to >= display.viewTo) { // Bottom overlap + var cut = viewCuttingPoint(cm, from, from, -1); + if (cut) { + display.view = display.view.slice(0, cut.index); + display.viewTo = cut.lineN; + } else { + resetView(cm); + } + } else { // Gap in the middle + var cutTop = viewCuttingPoint(cm, from, from, -1); + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)); + display.viewTo += lendiff; + } else { + resetView(cm); + } + } + + var ext = display.externalMeasured; + if (ext) { + if (to < ext.lineN) + ext.lineN += lendiff; + else if (from < ext.lineN + ext.size) + display.externalMeasured = null; + } + } + + // Register a change to a single line. Type must be one of "text", + // "gutter", "class", "widget" + function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true; + var display = cm.display, ext = cm.display.externalMeasured; + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) + display.externalMeasured = null; + + if (line < display.viewFrom || line >= display.viewTo) return; + var lineView = display.view[findViewIndex(cm, line)]; + if (lineView.node == null) return; + var arr = lineView.changes || (lineView.changes = []); + if (indexOf(arr, type) == -1) arr.push(type); + } + + // Clear the view. + function resetView(cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first; + cm.display.view = []; + cm.display.viewOffset = 0; + } + + // Find the view element corresponding to a given line. Return null + // when the line isn't visible. + function findViewIndex(cm, n) { + if (n >= cm.display.viewTo) return null; + n -= cm.display.viewFrom; + if (n < 0) return null; + var view = cm.display.view; + for (var i = 0; i < view.length; i++) { + n -= view[i].size; + if (n < 0) return i; + } + } + + function viewCuttingPoint(cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), diff, view = cm.display.view; + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) + return {index: index, lineN: newN}; + for (var i = 0, n = cm.display.viewFrom; i < index; i++) + n += view[i].size; + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) return null; + diff = (n + view[index].size) - oldN; + index++; + } else { + diff = n - oldN; + } + oldN += diff; newN += diff; + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) return null; + newN += dir * view[index - (dir < 0 ? 1 : 0)].size; + index += dir; + } + return {index: index, lineN: newN}; + } + + // Force the view to cover a given range, adding empty view element + // or clipping off existing ones as needed. + function adjustView(cm, from, to) { + var display = cm.display, view = display.view; + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to); + display.viewFrom = from; + } else { + if (display.viewFrom > from) + display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); + else if (display.viewFrom < from) + display.view = display.view.slice(findViewIndex(cm, from)); + display.viewFrom = from; + if (display.viewTo < to) + display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); + else if (display.viewTo > to) + display.view = display.view.slice(0, findViewIndex(cm, to)); + } + display.viewTo = to; + } + + // Count the number of lines in the view whose DOM representation is + // out of date (or nonexistent). + function countDirtyView(cm) { + var view = cm.display.view, dirty = 0; + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; + } + return dirty; + } + + // EVENT HANDLERS + + // Attach the necessary event handlers when initializing the editor + function registerEventHandlers(cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + // Older IE's will not fire a second mousedown for a double click + if (ie && ie_version < 11) + on(d.scroller, "dblclick", operation(cm, function(e) { + if (signalDOMEvent(cm, e)) return; + var pos = posFromMouse(cm, e); + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; + e_preventDefault(e); + var word = cm.findWordAt(pos); + extendSelection(cm.doc, word.anchor, word.head); + })); + else + on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); + // Some browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for these browsers. + if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); + + // Used to suppress mouse event handling when a touch happens + var touchFinished, prevTouch = {end: 0}; + function finishTouch() { + if (d.activeTouch) { + touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000); + prevTouch = d.activeTouch; + prevTouch.end = +new Date; + } + }; + function isMouseLikeTouchEvent(e) { + if (e.touches.length != 1) return false; + var touch = e.touches[0]; + return touch.radiusX <= 1 && touch.radiusY <= 1; + } + function farAway(touch, other) { + if (other.left == null) return true; + var dx = other.left - touch.left, dy = other.top - touch.top; + return dx * dx + dy * dy > 20 * 20; + } + on(d.scroller, "touchstart", function(e) { + if (!isMouseLikeTouchEvent(e)) { + clearTimeout(touchFinished); + var now = +new Date; + d.activeTouch = {start: now, moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null}; + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX; + d.activeTouch.top = e.touches[0].pageY; + } + } + }); + on(d.scroller, "touchmove", function() { + if (d.activeTouch) d.activeTouch.moved = true; + }); + on(d.scroller, "touchend", function(e) { + var touch = d.activeTouch; + if (touch && !eventInWidget(d, e) && touch.left != null && + !touch.moved && new Date - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), range; + if (!touch.prev || farAway(touch, touch.prev)) // Single tap + range = new Range(pos, pos); + else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap + range = cm.findWordAt(pos); + else // Triple tap + range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); + cm.setSelection(range.anchor, range.head); + cm.focus(); + e_preventDefault(e); + } + finishTouch(); + }); + on(d.scroller, "touchcancel", finishTouch); + + // Sync scrolling between fake scrollbars and real scrollable + // area, ensure viewport is updated when scrolling. + on(d.scroller, "scroll", function() { + if (d.scroller.clientHeight) { + setScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); + } + }); + + // Listen to wheel events in order to try and update the viewport on time. + on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); + on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); + + // Prevent wrapper from ever scrolling + on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); + + d.dragFunctions = { + enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);}, + over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, + start: function(e){onDragStart(cm, e);}, + drop: operation(cm, onDrop), + leave: function() {clearDragCursor(cm);} + }; + + var inp = d.input.getField(); + on(inp, "keyup", function(e) { onKeyUp.call(cm, e); }); + on(inp, "keydown", operation(cm, onKeyDown)); + on(inp, "keypress", operation(cm, onKeyPress)); + on(inp, "focus", bind(onFocus, cm)); + on(inp, "blur", bind(onBlur, cm)); + } + + function dragDropChanged(cm, value, old) { + var wasOn = old && old != CodeMirror.Init; + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions; + var toggle = value ? on : off; + toggle(cm.display.scroller, "dragstart", funcs.start); + toggle(cm.display.scroller, "dragenter", funcs.enter); + toggle(cm.display.scroller, "dragover", funcs.over); + toggle(cm.display.scroller, "dragleave", funcs.leave); + toggle(cm.display.scroller, "drop", funcs.drop); + } + } + + // Called when the window resizes + function onResize(cm) { + var d = cm.display; + if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) + return; + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.scrollbarsClipped = false; + cm.setSize(); + } + + // MOUSE EVENTS + + // Return true when the given mouse event happened in a widget + function eventInWidget(display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || + (n.parentNode == display.sizer && n != display.mover)) + return true; + } + } + + // Given a mouse event, find the corresponding position. If liberal + // is false, it checks whether a gutter or scrollbar was clicked, + // and returns null if it was. forRect is used by rectangular + // selections, and tries to estimate a character position even for + // coordinates beyond the right of the text. + function posFromMouse(cm, e, liberal, forRect) { + var display = cm.display; + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null; + + var x, y, space = display.lineSpace.getBoundingClientRect(); + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX - space.left; y = e.clientY - space.top; } + catch (e) { return null; } + var coords = coordsChar(cm, x, y), line; + if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); + } + return coords; + } + + // A mouse down can be a single click, double click, triple click, + // start of selection drag, start of text drag, new cursor + // (ctrl-click), rectangle drag (alt-drag), or xwin + // middle-click-paste. Or it might be a click on something we should + // not interfere with, such as a scrollbar or widget. + function onMouseDown(e) { + var cm = this, display = cm.display; + if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return; + display.shift = e.shiftKey; + + if (eventInWidget(display, e)) { + if (!webkit) { + // Briefly turn off draggability, to allow widgets to do + // normal dragging things. + display.scroller.draggable = false; + setTimeout(function(){display.scroller.draggable = true;}, 100); + } + return; + } + if (clickInGutter(cm, e)) return; + var start = posFromMouse(cm, e); + window.focus(); + + switch (e_button(e)) { + case 1: + // #3261: make sure, that we're not starting a second selection + if (cm.state.selectingText) + cm.state.selectingText(e); + else if (start) + leftButtonDown(cm, e, start); + else if (e_target(e) == display.scroller) + e_preventDefault(e); + break; + case 2: + if (webkit) cm.state.lastMiddleDown = +new Date; + if (start) extendSelection(cm.doc, start); + setTimeout(function() {display.input.focus();}, 20); + e_preventDefault(e); + break; + case 3: + if (captureRightClick) onContextMenu(cm, e); + else delayBlurEvent(cm); + break; + } + } + + var lastClick, lastDoubleClick; + function leftButtonDown(cm, e, start) { + if (ie) setTimeout(bind(ensureFocus, cm), 0); + else cm.curOp.focus = activeElt(); + + var now = +new Date, type; + if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { + type = "triple"; + } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { + type = "double"; + lastDoubleClick = {time: now, pos: start}; + } else { + type = "single"; + lastClick = {time: now, pos: start}; + } + + var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained; + if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && + type == "single" && (contained = sel.contains(start)) > -1 && + (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && + (cmp(contained.to(), start) > 0 || start.xRel < 0)) + leftButtonStartDrag(cm, e, start, modifier); + else + leftButtonSelect(cm, e, start, type, modifier); + } + + // Start a text drag. When it ends, see if any dragging actually + // happen, and treat as a click if it didn't. + function leftButtonStartDrag(cm, e, start, modifier) { + var display = cm.display, startTime = +new Date; + var dragEnd = operation(cm, function(e2) { + if (webkit) display.scroller.draggable = false; + cm.state.draggingText = false; + off(document, "mouseup", dragEnd); + off(display.scroller, "drop", dragEnd); + if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { + e_preventDefault(e2); + if (!modifier && +new Date - 200 < startTime) + extendSelection(cm.doc, start); + // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) + if (webkit || ie && ie_version == 9) + setTimeout(function() {document.body.focus(); display.input.focus();}, 20); + else + display.input.focus(); + } + }); + // Let the drag handler handle this. + if (webkit) display.scroller.draggable = true; + cm.state.draggingText = dragEnd; + // IE's approach to draggable + if (display.scroller.dragDrop) display.scroller.dragDrop(); + on(document, "mouseup", dragEnd); + on(display.scroller, "drop", dragEnd); + } + + // Normal selection, as opposed to text dragging. + function leftButtonSelect(cm, e, start, type, addNew) { + var display = cm.display, doc = cm.doc; + e_preventDefault(e); + + var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; + if (addNew && !e.shiftKey) { + ourIndex = doc.sel.contains(start); + if (ourIndex > -1) + ourRange = ranges[ourIndex]; + else + ourRange = new Range(start, start); + } else { + ourRange = doc.sel.primary(); + ourIndex = doc.sel.primIndex; + } + + if (e.altKey) { + type = "rect"; + if (!addNew) ourRange = new Range(start, start); + start = posFromMouse(cm, e, true, true); + ourIndex = -1; + } else if (type == "double") { + var word = cm.findWordAt(start); + if (cm.display.shift || doc.extend) + ourRange = extendRange(doc, ourRange, word.anchor, word.head); + else + ourRange = word; + } else if (type == "triple") { + var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); + if (cm.display.shift || doc.extend) + ourRange = extendRange(doc, ourRange, line.anchor, line.head); + else + ourRange = line; + } else { + ourRange = extendRange(doc, ourRange, start); + } + + if (!addNew) { + ourIndex = 0; + setSelection(doc, new Selection([ourRange], 0), sel_mouse); + startSel = doc.sel; + } else if (ourIndex == -1) { + ourIndex = ranges.length; + setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}); + } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { + setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), + {scroll: false, origin: "*mouse"}); + startSel = doc.sel; + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); + } + + var lastPos = start; + function extendTo(pos) { + if (cmp(lastPos, pos) == 0) return; + lastPos = pos; + + if (type == "rect") { + var ranges = [], tabSize = cm.options.tabSize; + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); + var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); + line <= end; line++) { + var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); + if (left == right) + ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); + else if (text.length > leftPos) + ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); + } + if (!ranges.length) ranges.push(new Range(start, start)); + setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), + {origin: "*mouse", scroll: false}); + cm.scrollIntoView(pos); + } else { + var oldRange = ourRange; + var anchor = oldRange.anchor, head = pos; + if (type != "single") { + if (type == "double") + var range = cm.findWordAt(pos); + else + var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))); + if (cmp(range.anchor, anchor) > 0) { + head = range.head; + anchor = minPos(oldRange.from(), range.anchor); + } else { + head = range.anchor; + anchor = maxPos(oldRange.to(), range.head); + } + } + var ranges = startSel.ranges.slice(0); + ranges[ourIndex] = new Range(clipPos(doc, anchor), head); + setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); + } + } + + var editorSize = display.wrapper.getBoundingClientRect(); + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0; + + function extend(e) { + var curCount = ++counter; + var cur = posFromMouse(cm, e, true, type == "rect"); + if (!cur) return; + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt(); + extendTo(cur); + var visible = visibleLines(display, doc); + if (cur.line >= visible.to || cur.line < visible.from) + setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; + if (outside) setTimeout(operation(cm, function() { + if (counter != curCount) return; + display.scroller.scrollTop += outside; + extend(e); + }), 50); + } + } + + function done(e) { + cm.state.selectingText = false; + counter = Infinity; + e_preventDefault(e); + display.input.focus(); + off(document, "mousemove", move); + off(document, "mouseup", up); + doc.history.lastSelOrigin = null; + } + + var move = operation(cm, function(e) { + if (!e_button(e)) done(e); + else extend(e); + }); + var up = operation(cm, done); + cm.state.selectingText = up; + on(document, "mousemove", move); + on(document, "mouseup", up); + } + + // Determines whether an event happened in the gutter, and fires the + // handlers for the corresponding event. + function gutterEvent(cm, e, type, prevent, signalfn) { + try { var mX = e.clientX, mY = e.clientY; } + catch(e) { return false; } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; + if (prevent) e_preventDefault(e); + + var display = cm.display; + var lineBox = display.lineDiv.getBoundingClientRect(); + + if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); + mY -= lineBox.top - display.viewOffset; + + for (var i = 0; i < cm.options.gutters.length; ++i) { + var g = display.gutters.childNodes[i]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.options.gutters[i]; + signalfn(cm, type, cm, line, gutter, e); + return e_defaultPrevented(e); + } + } + } + + function clickInGutter(cm, e) { + return gutterEvent(cm, e, "gutterClick", true, signalLater); + } + + // Kludge to work around strange IE behavior where it'll sometimes + // re-fire a series of drag-related events right after the drop (#1551) + var lastDrop = 0; + + function onDrop(e) { + var cm = this; + clearDragCursor(cm); + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) + return; + e_preventDefault(e); + if (ie) lastDrop = +new Date; + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; + if (!pos || isReadOnly(cm)) return; + // Might be a file drop, in which case we simply extract the text + // and insert it. + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0; + var loadFile = function(file, i) { + var reader = new FileReader; + reader.onload = operation(cm, function() { + text[i] = reader.result; + if (++read == n) { + pos = clipPos(cm.doc, pos); + var change = {from: pos, to: pos, + text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), + origin: "paste"}; + makeChange(cm.doc, change); + setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); + } + }); + reader.readAsText(file); + }; + for (var i = 0; i < n; ++i) loadFile(files[i], i); + } else { // Normal drop + // Don't do a replace if the drop happened inside of the selected text. + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e); + // Ensure the editor is re-focused + setTimeout(function() {cm.display.input.focus();}, 20); + return; + } + try { + var text = e.dataTransfer.getData("Text"); + if (text) { + if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey)) + var selected = cm.listSelections(); + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); + if (selected) for (var i = 0; i < selected.length; ++i) + replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag"); + cm.replaceSelection(text, "around", "paste"); + cm.display.input.focus(); + } + } + catch(e){} + } + } + + function onDragStart(cm, e) { + if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; + + e.dataTransfer.setData("Text", cm.getSelection()); + + // Use dummy image instead of default browsers image. + // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (presto) { + img.width = img.height = 1; + cm.display.wrapper.appendChild(img); + // Force a relayout, or Opera won't use our image for some obscure reason + img._top = img.offsetTop; + } + e.dataTransfer.setDragImage(img, 0, 0); + if (presto) img.parentNode.removeChild(img); + } + } + + function onDragOver(cm, e) { + var pos = posFromMouse(cm, e); + if (!pos) return; + var frag = document.createDocumentFragment(); + drawSelectionCursor(cm, pos, frag); + if (!cm.display.dragCursor) { + cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); + cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); + } + removeChildrenAndAdd(cm.display.dragCursor, frag); + } + + function clearDragCursor(cm) { + if (cm.display.dragCursor) { + cm.display.lineSpace.removeChild(cm.display.dragCursor); + cm.display.dragCursor = null; + } + } + + // SCROLL EVENTS + + // Sync the scrollable area and scrollbars, ensure the viewport + // covers the visible area. + function setScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) return; + cm.doc.scrollTop = val; + if (!gecko) updateDisplaySimple(cm, {top: val}); + if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; + cm.display.scrollbars.setScrollTop(val); + if (gecko) updateDisplaySimple(cm); + startWorker(cm, 100); + } + // Sync scroller and scrollbar, ensure the gutter elements are + // aligned. + function setScrollLeft(cm, val, isScroller) { + if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); + cm.doc.scrollLeft = val; + alignHorizontally(cm); + if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; + cm.display.scrollbars.setScrollLeft(val); + } + + // Since the delta values reported on mouse wheel events are + // unstandardized between browsers and even browser versions, and + // generally horribly unpredictable, this code starts by measuring + // the scroll effect that the first few mouse wheel events have, + // and, from that, detects the way it can convert deltas to pixel + // offsets afterwards. + // + // The reason we want to know the amount a wheel event will scroll + // is that it gives us a chance to update the display before the + // actual scrolling happens, reducing flickering. + + var wheelSamples = 0, wheelPixelsPerUnit = null; + // Fill in a browser-detected starting value on browsers where we + // know one. These don't have to be accurate -- the result of them + // being wrong would just be a slight flicker on the first wheel + // scroll (if it is large enough). + if (ie) wheelPixelsPerUnit = -.53; + else if (gecko) wheelPixelsPerUnit = 15; + else if (chrome) wheelPixelsPerUnit = -.7; + else if (safari) wheelPixelsPerUnit = -1/3; + + var wheelEventDelta = function(e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY; + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; + else if (dy == null) dy = e.wheelDelta; + return {x: dx, y: dy}; + }; + CodeMirror.wheelEventPixels = function(e) { + var delta = wheelEventDelta(e); + delta.x *= wheelPixelsPerUnit; + delta.y *= wheelPixelsPerUnit; + return delta; + }; + + function onScrollWheel(cm, e) { + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; + + var display = cm.display, scroll = display.scroller; + // Quit if there's nothing to scroll here + if (!(dx && scroll.scrollWidth > scroll.clientWidth || + dy && scroll.scrollHeight > scroll.clientHeight)) return; + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i = 0; i < view.length; i++) { + if (view[i].node == cur) { + cm.display.currentWheelTarget = cur; + break outer; + } + } + } + } + + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { + if (dy) + setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); + setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); + e_preventDefault(e); + display.wheelStartX = null; // Abort measurement, if in progress + return; + } + + // 'Project' the visible viewport to cover the area that is being + // scrolled into view (if we know enough to estimate it). + if (dy && wheelPixelsPerUnit != null) { + var pixels = dy * wheelPixelsPerUnit; + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; + if (pixels < 0) top = Math.max(0, top + pixels - 50); + else bot = Math.min(cm.doc.height, bot + pixels + 50); + updateDisplaySimple(cm, {top: top, bottom: bot}); + } + + if (wheelSamples < 20) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; + display.wheelDX = dx; display.wheelDY = dy; + setTimeout(function() { + if (display.wheelStartX == null) return; + var movedX = scroll.scrollLeft - display.wheelStartX; + var movedY = scroll.scrollTop - display.wheelStartY; + var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX); + display.wheelStartX = display.wheelStartY = null; + if (!sample) return; + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + display.wheelDX += dx; display.wheelDY += dy; + } + } + } + + // KEY EVENTS + + // Run a handler that was bound to a key. + function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound]; + if (!bound) return false; + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + cm.display.input.ensurePolled(); + var prevShift = cm.display.shift, done = false; + try { + if (isReadOnly(cm)) cm.state.suppressEdits = true; + if (dropShift) cm.display.shift = false; + done = bound(cm) != Pass; + } finally { + cm.display.shift = prevShift; + cm.state.suppressEdits = false; + } + return done; + } + + function lookupKeyForEditor(cm, name, handle) { + for (var i = 0; i < cm.state.keyMaps.length; i++) { + var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); + if (result) return result; + } + return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) + || lookupKey(name, cm.options.keyMap, handle, cm); + } + + var stopSeq = new Delayed; + function dispatchKey(cm, name, e, handle) { + var seq = cm.state.keySeq; + if (seq) { + if (isModifierKey(name)) return "handled"; + stopSeq.set(50, function() { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null; + cm.display.input.reset(); + } + }); + name = seq + " " + name; + } + var result = lookupKeyForEditor(cm, name, handle); + + if (result == "multi") + cm.state.keySeq = name; + if (result == "handled") + signalLater(cm, "keyHandled", cm, name, e); + + if (result == "handled" || result == "multi") { + e_preventDefault(e); + restartBlink(cm); + } + + if (seq && !result && /\'$/.test(name)) { + e_preventDefault(e); + return true; + } + return !!result; + } + + // Handle a key from the keydown event. + function handleKeyBinding(cm, e) { + var name = keyName(e, true); + if (!name) return false; + + if (e.shiftKey && !cm.state.keySeq) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);}) + || dispatchKey(cm, name, e, function(b) { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) + return doHandleBinding(cm, b); + }); + } else { + return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); }); + } + } + + // Handle a key from the keypress event + function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, + function(b) { return doHandleBinding(cm, b, true); }); + } + + var lastStoppedKey = null; + function onKeyDown(e) { + var cm = this; + cm.curOp.focus = activeElt(); + if (signalDOMEvent(cm, e)) return; + // IE does strange things with escape. + if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false; + var code = e.keyCode; + cm.display.shift = code == 16 || e.shiftKey; + var handled = handleKeyBinding(cm, e); + if (presto) { + lastStoppedKey = handled ? code : null; + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) + cm.replaceSelection("", null, "cut"); + } + + // Turn mouse into crosshair when Alt is held on Mac. + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) + showCrossHair(cm); + } + + function showCrossHair(cm) { + var lineDiv = cm.display.lineDiv; + addClass(lineDiv, "CodeMirror-crosshair"); + + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair"); + off(document, "keyup", up); + off(document, "mouseover", up); + } + } + on(document, "keyup", up); + on(document, "mouseover", up); + } + + function onKeyUp(e) { + if (e.keyCode == 16) this.doc.sel.shift = false; + signalDOMEvent(this, e); + } + + function onKeyPress(e) { + var cm = this; + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return; + var keyCode = e.keyCode, charCode = e.charCode; + if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} + if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return; + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + if (handleCharBinding(cm, e, ch)) return; + cm.display.input.onKeyPress(e); + } + + // FOCUS/BLUR EVENTS + + function delayBlurEvent(cm) { + cm.state.delayingBlurEvent = true; + setTimeout(function() { + if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false; + onBlur(cm); + } + }, 100); + } + + function onFocus(cm) { + if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false; + + if (cm.options.readOnly == "nocursor") return; + if (!cm.state.focused) { + signal(cm, "focus", cm); + cm.state.focused = true; + addClass(cm.display.wrapper, "CodeMirror-focused"); + // This test prevents this from firing when a context + // menu is closed (since the input reset would kill the + // select-all detection hack) + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset(); + if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730 + } + cm.display.input.receivedFocus(); + } + restartBlink(cm); + } + function onBlur(cm) { + if (cm.state.delayingBlurEvent) return; + + if (cm.state.focused) { + signal(cm, "blur", cm); + cm.state.focused = false; + rmClass(cm.display.wrapper, "CodeMirror-focused"); + } + clearInterval(cm.display.blinker); + setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150); + } + + // CONTEXT MENU HANDLING + + // To make the context menu work, we need to briefly unhide the + // textarea (making it as unobtrusive as possible) to let the + // right-click take effect on it. + function onContextMenu(cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return; + cm.display.input.onContextMenu(e); + } + + function contextMenuInGutter(cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) return false; + return gutterEvent(cm, e, "gutterContextMenu", false, signal); + } + + // UPDATING + + // Compute the position of the end of a change (its 'to' property + // refers to the pre-change end). + var changeEnd = CodeMirror.changeEnd = function(change) { + if (!change.text) return change.to; + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); + }; + + // Adjust a position to refer to the post-change position of the + // same text, or the end of the change if the change covers it. + function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) return pos; + if (cmp(pos, change.to) <= 0) return changeEnd(change); + + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; + if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; + return Pos(line, ch); + } + + function computeSelAfterChange(doc, change) { + var out = []; + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + out.push(new Range(adjustForChange(range.anchor, change), + adjustForChange(range.head, change))); + } + return normalizeSelection(out, doc.sel.primIndex); + } + + function offsetPos(pos, old, nw) { + if (pos.line == old.line) + return Pos(nw.line, pos.ch - old.ch + nw.ch); + else + return Pos(nw.line + (pos.line - old.line), pos.ch); + } + + // Used by replaceSelections to allow moving the selection to the + // start or around the replaced test. Hint may be "start" or "around". + function computeReplacedSel(doc, changes, hint) { + var out = []; + var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + var from = offsetPos(change.from, oldPrev, newPrev); + var to = offsetPos(changeEnd(change), oldPrev, newPrev); + oldPrev = change.to; + newPrev = to; + if (hint == "around") { + var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; + out[i] = new Range(inv ? to : from, inv ? from : to); + } else { + out[i] = new Range(from, from); + } + } + return new Selection(out, doc.sel.primIndex); + } + + // Allow "beforeChange" event handlers to influence a change + function filterChange(doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function() { this.canceled = true; } + }; + if (update) obj.update = function(from, to, text, origin) { + if (from) this.from = clipPos(doc, from); + if (to) this.to = clipPos(doc, to); + if (text) this.text = text; + if (origin !== undefined) this.origin = origin; + }; + signal(doc, "beforeChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); + + if (obj.canceled) return null; + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; + } + + // Apply a change to a document, and add it to the document's + // history, and propagating it to all linked documents. + function makeChange(doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); + if (doc.cm.state.suppressEdits) return; + } + + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true); + if (!change) return; + } + + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); + if (split) { + for (var i = split.length - 1; i >= 0; --i) + makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); + } else { + makeChangeInner(doc, change); + } + } + + function makeChangeInner(doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; + var selAfter = computeSelAfterChange(doc, change); + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); + + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); + var rebased = []; + + linkedDocs(doc, function(doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); + }); + } + + // Revert a change stored in a document's history. + function makeChangeFromHistory(doc, type, allowSelectionOnly) { + if (doc.cm && doc.cm.state.suppressEdits) return; + + var hist = doc.history, event, selAfter = doc.sel; + var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; + + // Verify that there is a useable event (so that ctrl-z won't + // needlessly clear selection events) + for (var i = 0; i < source.length; i++) { + event = source[i]; + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) + break; + } + if (i == source.length) return; + hist.lastOrigin = hist.lastSelOrigin = null; + + for (;;) { + event = source.pop(); + if (event.ranges) { + pushSelectionToHistory(event, dest); + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, {clearRedo: false}); + return; + } + selAfter = event; + } + else break; + } + + // Build up a reverse change object to add to the opposite history + // stack (redo when undoing, and vice versa). + var antiChanges = []; + pushSelectionToHistory(selAfter, dest); + dest.push({changes: antiChanges, generation: hist.generation}); + hist.generation = event.generation || ++hist.maxGeneration; + + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); + + for (var i = event.changes.length - 1; i >= 0; --i) { + var change = event.changes[i]; + change.origin = type; + if (filter && !filterChange(doc, change, false)) { + source.length = 0; + return; + } + + antiChanges.push(historyChangeFromChange(doc, change)); + + var after = i ? computeSelAfterChange(doc, change) : lst(source); + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); + if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); + var rebased = []; + + // Propagate to the linked documents + linkedDocs(doc, function(doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); + }); + } + } + + // Sub-views need their line numbers shifted when text is added + // above or below them in the parent document. + function shiftDoc(doc, distance) { + if (distance == 0) return; + doc.first += distance; + doc.sel = new Selection(map(doc.sel.ranges, function(range) { + return new Range(Pos(range.anchor.line + distance, range.anchor.ch), + Pos(range.head.line + distance, range.head.ch)); + }), doc.sel.primIndex); + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance); + for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) + regLineChange(doc.cm, l, "gutter"); + } + } + + // More lower-level change function, handling only a single document + // (not linked ones). + function makeChangeSingleDoc(doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) + return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); + + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); + return; + } + if (change.from.line > doc.lastLine()) return; + + // Clip the change to the size of this doc + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line); + shiftDoc(doc, shift); + change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], origin: change.origin}; + } + var last = doc.lastLine(); + if (change.to.line > last) { + change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], origin: change.origin}; + } + + change.removed = getBetween(doc, change.from, change.to); + + if (!selAfter) selAfter = computeSelAfterChange(doc, change); + if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); + else updateDoc(doc, change, spans); + setSelectionNoUndo(doc, selAfter, sel_dontScroll); + } + + // Handle the interaction of a change to a document with the editor + // that this document is part of. + function makeChangeSingleDocInEditor(cm, change, spans) { + var doc = cm.doc, display = cm.display, from = change.from, to = change.to; + + var recomputeMaxLength = false, checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); + doc.iter(checkWidthStart, to.line + 1, function(line) { + if (line == display.maxLine) { + recomputeMaxLength = true; + return true; + } + }); + } + + if (doc.sel.contains(change.from, change.to) > -1) + signalCursorActivity(cm); + + updateDoc(doc, change, spans, estimateHeight(cm)); + + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function(line) { + var len = lineLength(line); + if (len > display.maxLineLength) { + display.maxLine = line; + display.maxLineLength = len; + display.maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) cm.curOp.updateMaxLine = true; + } + + // Adjust frontier, schedule worker + doc.frontier = Math.min(doc.frontier, from.line); + startWorker(cm, 400); + + var lendiff = change.text.length - (to.line - from.line) - 1; + // Remember that these lines changed, for updating the display + if (change.full) + regChange(cm); + else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) + regLineChange(cm, from.line, "text"); + else + regChange(cm, from.line, to.line + 1, lendiff); + + var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); + if (changeHandler || changesHandler) { + var obj = { + from: from, to: to, + text: change.text, + removed: change.removed, + origin: change.origin + }; + if (changeHandler) signalLater(cm, "change", cm, obj); + if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); + } + cm.display.selForContextMenu = null; + } + + function replaceRange(doc, code, from, to, origin) { + if (!to) to = from; + if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } + if (typeof code == "string") code = doc.splitLines(code); + makeChange(doc, {from: from, to: to, text: code, origin: origin}); + } + + // SCROLLING THINGS INTO VIEW + + // If an editor sits on the top or bottom of the window, partially + // scrolled out of view, this ensures that the cursor is visible. + function maybeScrollWindow(cm, coords) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) return; + + var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; + if (coords.top + box.top < 0) doScroll = true; + else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + + (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + + (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " + + coords.left + "px; width: 2px;"); + cm.display.lineSpace.appendChild(scrollNode); + scrollNode.scrollIntoView(doScroll); + cm.display.lineSpace.removeChild(scrollNode); + } + } + + // Scroll a given position into view (immediately), verifying that + // it actually became visible (as line heights are accurately + // measured, the position of something may 'drift' during drawing). + function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) margin = 0; + for (var limit = 0; limit < 5; limit++) { + var changed = false, coords = cursorCoords(cm, pos); + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); + var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), + Math.min(coords.top, endCoords.top) - margin, + Math.max(coords.left, endCoords.left), + Math.max(coords.bottom, endCoords.bottom) + margin); + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; + if (scrollPos.scrollTop != null) { + setScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; + } + if (!changed) break; + } + return coords; + } + + // Scroll a given set of coordinates into view (immediately). + function scrollIntoView(cm, x1, y1, x2, y2) { + var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); + if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); + if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); + } + + // Calculate a new scroll position needed to scroll the given + // rectangle into view. Returns an object with scrollTop and + // scrollLeft properties. When these are undefined, the + // vertical/horizontal position does not need to be adjusted. + function calculateScrollPos(cm, x1, y1, x2, y2) { + var display = cm.display, snapMargin = textHeight(cm.display); + if (y1 < 0) y1 = 0; + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; + var screen = displayHeight(cm), result = {}; + if (y2 - y1 > screen) y2 = y1 + screen; + var docBottom = cm.doc.height + paddingVert(display); + var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; + if (y1 < screentop) { + result.scrollTop = atTop ? 0 : y1; + } else if (y2 > screentop + screen) { + var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); + if (newTop != screentop) result.scrollTop = newTop; + } + + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; + var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); + var tooWide = x2 - x1 > screenw; + if (tooWide) x2 = x1 + screenw; + if (x1 < 10) + result.scrollLeft = 0; + else if (x1 < screenleft) + result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)); + else if (x2 > screenw + screenleft - 3) + result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw; + return result; + } + + // Store a relative adjustment to the scroll position in the current + // operation (to be applied when the operation finishes). + function addToScrollPos(cm, left, top) { + if (left != null || top != null) resolveScrollToPos(cm); + if (left != null) + cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left; + if (top != null) + cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; + } + + // Make sure that at the end of the operation the current cursor is + // shown. + function ensureCursorVisible(cm) { + resolveScrollToPos(cm); + var cur = cm.getCursor(), from = cur, to = cur; + if (!cm.options.lineWrapping) { + from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; + to = Pos(cur.line, cur.ch + 1); + } + cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; + } + + // When an operation has its scrollToPos property set, and another + // scroll action is applied before the end of the operation, this + // 'simulates' scrolling that position into view in a cheap way, so + // that the effect of intermediate scroll commands is not ignored. + function resolveScrollToPos(cm) { + var range = cm.curOp.scrollToPos; + if (range) { + cm.curOp.scrollToPos = null; + var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); + var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), + Math.min(from.top, to.top) - range.margin, + Math.max(from.right, to.right), + Math.max(from.bottom, to.bottom) + range.margin); + cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); + } + } + + // API UTILITIES + + // Indent the given line. The how parameter can be "smart", + // "add"/null, "subtract", or "prev". When aggressive is false + // (typically set to true for forced single-line indents), empty + // lines are not indented, and places where the mode returns Pass + // are left alone. + function indentLine(cm, n, how, aggressive) { + var doc = cm.doc, state; + if (how == null) how = "add"; + if (how == "smart") { + // Fall back to "prev" when the mode doesn't have an indentation + // method. + if (!doc.mode.indent) how = "prev"; + else state = getStateBefore(cm, n); + } + + var tabSize = cm.options.tabSize; + var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); + if (line.stateAfter) line.stateAfter = null; + var curSpaceString = line.text.match(/^\s*/)[0], indentation; + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0; + how = "not"; + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass || indentation > 150) { + if (!aggressive) return; + how = "prev"; + } + } + if (how == "prev") { + if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); + else indentation = 0; + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit; + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit; + } else if (typeof how == "number") { + indentation = curSpace + how; + } + indentation = Math.max(0, indentation); + + var indentString = "", pos = 0; + if (cm.options.indentWithTabs) + for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} + if (pos < indentation) indentString += spaceStr(indentation - pos); + + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); + line.stateAfter = null; + return true; + } else { + // Ensure that, if the cursor was in the whitespace at the start + // of the line, it is moved to the end of that space. + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + if (range.head.line == n && range.head.ch < curSpaceString.length) { + var pos = Pos(n, curSpaceString.length); + replaceOneSelection(doc, i, new Range(pos, pos)); + break; + } + } + } + } + + // Utility for applying a change to a line by handle or number, + // returning the number and optionally registering the line as + // changed. + function changeLine(doc, handle, changeType, op) { + var no = handle, line = handle; + if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); + else no = lineNo(handle); + if (no == null) return null; + if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType); + return line; + } + + // Helper for deleting text near the selection(s), used to implement + // backspace, delete, and similar functionality. + function deleteNearSelection(cm, compute) { + var ranges = cm.doc.sel.ranges, kill = []; + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (var i = 0; i < ranges.length; i++) { + var toKill = compute(ranges[i]); + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop(); + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from; + break; + } + } + kill.push(toKill); + } + // Next, remove those actual ranges. + runInOp(cm, function() { + for (var i = kill.length - 1; i >= 0; i--) + replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); + ensureCursorVisible(cm); + }); + } + + // Used for horizontal relative motion. Dir is -1 or 1 (left or + // right), unit can be "char", "column" (like char, but doesn't + // cross line boundaries), "word" (across next word), or "group" (to + // the start of next group of word or non-word-non-whitespace + // chars). The visually param controls whether, in right-to-left + // text, direction 1 means to move towards the next index in the + // string, or towards the character to the right of the current + // position. The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosH(doc, pos, dir, unit, visually) { + var line = pos.line, ch = pos.ch, origDir = dir; + var lineObj = getLine(doc, line); + var possible = true; + function findNextLine() { + var l = line + dir; + if (l < doc.first || l >= doc.first + doc.size) return (possible = false); + line = l; + return lineObj = getLine(doc, l); + } + function moveOnce(boundToLine) { + var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); + if (next == null) { + if (!boundToLine && findNextLine()) { + if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); + else ch = dir < 0 ? lineObj.text.length : 0; + } else return (possible = false); + } else ch = next; + return true; + } + + if (unit == "char") moveOnce(); + else if (unit == "column") moveOnce(true); + else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group"; + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); + for (var first = true;; first = false) { + if (dir < 0 && !moveOnce(!first)) break; + var cur = lineObj.text.charAt(ch) || "\n"; + var type = isWordChar(cur, helper) ? "w" + : group && cur == "\n" ? "n" + : !group || /\s/.test(cur) ? null + : "p"; + if (group && !first && !type) type = "s"; + if (sawType && sawType != type) { + if (dir < 0) {dir = 1; moveOnce();} + break; + } + + if (type) sawType = type; + if (dir > 0 && !moveOnce(!first)) break; + } + } + var result = skipAtomic(doc, Pos(line, ch), origDir, true); + if (!possible) result.hitSide = true; + return result; + } + + // For relative vertical movement. Dir may be -1 or 1. Unit can be + // "page" or "line". The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosV(cm, pos, dir, unit) { + var doc = cm.doc, x = pos.left, y; + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); + y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + for (;;) { + var target = coordsChar(cm, x, y); + if (!target.outside) break; + if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } + y += dir * 5; + } + return target; + } + + // EDITOR METHODS + + // The publicly visible API. Note that methodOp(f) means + // 'wrap f in an operation, performed on its `this` parameter'. + + // This is not the complete set of editor methods. Most of the + // methods defined on the Doc type are also injected into + // CodeMirror.prototype, for backwards compatibility and + // convenience. + + CodeMirror.prototype = { + constructor: CodeMirror, + focus: function(){window.focus(); this.display.input.focus();}, + + setOption: function(option, value) { + var options = this.options, old = options[option]; + if (options[option] == value && option != "mode") return; + options[option] = value; + if (optionHandlers.hasOwnProperty(option)) + operation(this, optionHandlers[option])(this, value, old); + }, + + getOption: function(option) {return this.options[option];}, + getDoc: function() {return this.doc;}, + + addKeyMap: function(map, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); + }, + removeKeyMap: function(map) { + var maps = this.state.keyMaps; + for (var i = 0; i < maps.length; ++i) + if (maps[i] == map || maps[i].name == map) { + maps.splice(i, 1); + return true; + } + }, + + addOverlay: methodOp(function(spec, options) { + var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); + if (mode.startState) throw new Error("Overlays may not be stateful."); + this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); + this.state.modeGen++; + regChange(this); + }), + removeOverlay: methodOp(function(spec) { + var overlays = this.state.overlays; + for (var i = 0; i < overlays.length; ++i) { + var cur = overlays[i].modeSpec; + if (cur == spec || typeof spec == "string" && cur.name == spec) { + overlays.splice(i, 1); + this.state.modeGen++; + regChange(this); + return; + } + } + }), + + indentLine: methodOp(function(n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; + else dir = dir ? "add" : "subtract"; + } + if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); + }), + indentSelection: methodOp(function(how) { + var ranges = this.doc.sel.ranges, end = -1; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (!range.empty()) { + var from = range.from(), to = range.to(); + var start = Math.max(end, from.line); + end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; + for (var j = start; j < end; ++j) + indentLine(this, j, how); + var newRanges = this.doc.sel.ranges; + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) + replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); + } else if (range.head.line > end) { + indentLine(this, range.head.line, how, true); + end = range.head.line; + if (i == this.doc.sel.primIndex) ensureCursorVisible(this); + } + } + }), + + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(pos, precise) { + return takeToken(this, pos, precise); + }, + + getLineTokens: function(line, precise) { + return takeToken(this, Pos(line), precise, true); + }, + + getTokenTypeAt: function(pos) { + pos = clipPos(this.doc, pos); + var styles = getLineStyles(this, getLine(this.doc, pos.line)); + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; + var type; + if (ch == 0) type = styles[2]; + else for (;;) { + var mid = (before + after) >> 1; + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; + else if (styles[mid * 2 + 1] < ch) before = mid + 1; + else { type = styles[mid * 2 + 2]; break; } + } + var cut = type ? type.indexOf("cm-overlay ") : -1; + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); + }, + + getModeAt: function(pos) { + var mode = this.doc.mode; + if (!mode.innerMode) return mode; + return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; + }, + + getHelper: function(pos, type) { + return this.getHelpers(pos, type)[0]; + }, + + getHelpers: function(pos, type) { + var found = []; + if (!helpers.hasOwnProperty(type)) return found; + var help = helpers[type], mode = this.getModeAt(pos); + if (typeof mode[type] == "string") { + if (help[mode[type]]) found.push(help[mode[type]]); + } else if (mode[type]) { + for (var i = 0; i < mode[type].length; i++) { + var val = help[mode[type][i]]; + if (val) found.push(val); + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]); + } else if (help[mode.name]) { + found.push(help[mode.name]); + } + for (var i = 0; i < help._global.length; i++) { + var cur = help._global[i]; + if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) + found.push(cur.val); + } + return found; + }, + + getStateAfter: function(line, precise) { + var doc = this.doc; + line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); + return getStateBefore(this, line + 1, precise); + }, + + cursorCoords: function(start, mode) { + var pos, range = this.doc.sel.primary(); + if (start == null) pos = range.head; + else if (typeof start == "object") pos = clipPos(this.doc, start); + else pos = start ? range.from() : range.to(); + return cursorCoords(this, pos, mode || "page"); + }, + + charCoords: function(pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page"); + }, + + coordsChar: function(coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page"); + return coordsChar(this, coords.left, coords.top); + }, + + lineAtHeight: function(height, mode) { + height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; + return lineAtHeight(this.doc, height + this.display.viewOffset); + }, + heightAtLine: function(line, mode) { + var end = false, lineObj; + if (typeof line == "number") { + var last = this.doc.first + this.doc.size - 1; + if (line < this.doc.first) line = this.doc.first; + else if (line > last) { line = last; end = true; } + lineObj = getLine(this.doc, line); + } else { + lineObj = line; + } + return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + + (end ? this.doc.height - heightAtLine(lineObj) : 0); + }, + + defaultTextHeight: function() { return textHeight(this.display); }, + defaultCharWidth: function() { return charWidth(this.display); }, + + setGutterMarker: methodOp(function(line, gutterID, value) { + return changeLine(this.doc, line, "gutter", function(line) { + var markers = line.gutterMarkers || (line.gutterMarkers = {}); + markers[gutterID] = value; + if (!value && isEmpty(markers)) line.gutterMarkers = null; + return true; + }); + }), + + clearGutter: methodOp(function(gutterID) { + var cm = this, doc = cm.doc, i = doc.first; + doc.iter(function(line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + line.gutterMarkers[gutterID] = null; + regLineChange(cm, i, "gutter"); + if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; + } + ++i; + }); + }), + + lineInfo: function(line) { + if (typeof line == "number") { + if (!isLine(this.doc, line)) return null; + var n = line; + line = getLine(this.doc, line); + if (!line) return null; + } else { + var n = lineNo(line); + if (n == null) return null; + } + return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, + textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, + widgets: line.widgets}; + }, + + getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};}, + + addWidget: function(pos, node, scroll, vert, horiz) { + var display = this.display; + pos = cursorCoords(this, clipPos(this.doc, pos)); + var top = pos.bottom, left = pos.left; + node.style.position = "absolute"; + node.setAttribute("cm-ignore-events", "true"); + this.display.input.setUneditable(node); + display.sizer.appendChild(node); + if (vert == "over") { + top = pos.top; + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + // Default to positioning above (if specified and possible); otherwise default to positioning below + if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) + top = pos.top - node.offsetHeight; + else if (pos.bottom + node.offsetHeight <= vspace) + top = pos.bottom; + if (left + node.offsetWidth > hspace) + left = hspace - node.offsetWidth; + } + node.style.top = top + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") left = 0; + else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; + node.style.left = left + "px"; + } + if (scroll) + scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); + }, + + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + + execCommand: function(cmd) { + if (commands.hasOwnProperty(cmd)) + return commands[cmd].call(null, this); + }, + + triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), + + findPosH: function(from, amount, unit, visually) { + var dir = 1; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + cur = findPosH(this.doc, cur, dir, unit, visually); + if (cur.hitSide) break; + } + return cur; + }, + + moveH: methodOp(function(dir, unit) { + var cm = this; + cm.extendSelectionsBy(function(range) { + if (cm.display.shift || cm.doc.extend || range.empty()) + return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually); + else + return dir < 0 ? range.from() : range.to(); + }, sel_move); + }), + + deleteH: methodOp(function(dir, unit) { + var sel = this.doc.sel, doc = this.doc; + if (sel.somethingSelected()) + doc.replaceSelection("", null, "+delete"); + else + deleteNearSelection(this, function(range) { + var other = findPosH(doc, range.head, dir, unit, false); + return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; + }); + }), + + findPosV: function(from, amount, unit, goalColumn) { + var dir = 1, x = goalColumn; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + var coords = cursorCoords(this, cur, "div"); + if (x == null) x = coords.left; + else coords.left = x; + cur = findPosV(this, coords, dir, unit); + if (cur.hitSide) break; + } + return cur; + }, + + moveV: methodOp(function(dir, unit) { + var cm = this, doc = this.doc, goals = []; + var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); + doc.extendSelectionsBy(function(range) { + if (collapse) + return dir < 0 ? range.from() : range.to(); + var headPos = cursorCoords(cm, range.head, "div"); + if (range.goalColumn != null) headPos.left = range.goalColumn; + goals.push(headPos.left); + var pos = findPosV(cm, headPos, dir, unit); + if (unit == "page" && range == doc.sel.primary()) + addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top); + return pos; + }, sel_move); + if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++) + doc.sel.ranges[i].goalColumn = goals[i]; + }), + + // Find the word at the given position (as returned by coordsChar). + findWordAt: function(pos) { + var doc = this.doc, line = getLine(doc, pos.line).text; + var start = pos.ch, end = pos.ch; + if (line) { + var helper = this.getHelper(pos, "wordChars"); + if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; + var startChar = line.charAt(start); + var check = isWordChar(startChar, helper) + ? function(ch) { return isWordChar(ch, helper); } + : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} + : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; + while (start > 0 && check(line.charAt(start - 1))) --start; + while (end < line.length && check(line.charAt(end))) ++end; + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)); + }, + + toggleOverwrite: function(value) { + if (value != null && value == this.state.overwrite) return; + if (this.state.overwrite = !this.state.overwrite) + addClass(this.display.cursorDiv, "CodeMirror-overwrite"); + else + rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); + + signal(this, "overwriteToggle", this, this.state.overwrite); + }, + hasFocus: function() { return this.display.input.getField() == activeElt(); }, + + scrollTo: methodOp(function(x, y) { + if (x != null || y != null) resolveScrollToPos(this); + if (x != null) this.curOp.scrollLeft = x; + if (y != null) this.curOp.scrollTop = y; + }), + getScrollInfo: function() { + var scroller = this.display.scroller; + return {left: scroller.scrollLeft, top: scroller.scrollTop, + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), clientWidth: displayWidth(this)}; + }, + + scrollIntoView: methodOp(function(range, margin) { + if (range == null) { + range = {from: this.doc.sel.primary().head, to: null}; + if (margin == null) margin = this.options.cursorScrollMargin; + } else if (typeof range == "number") { + range = {from: Pos(range, 0), to: null}; + } else if (range.from == null) { + range = {from: range, to: null}; + } + if (!range.to) range.to = range.from; + range.margin = margin || 0; + + if (range.from.line != null) { + resolveScrollToPos(this); + this.curOp.scrollToPos = range; + } else { + var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), + Math.min(range.from.top, range.to.top) - range.margin, + Math.max(range.from.right, range.to.right), + Math.max(range.from.bottom, range.to.bottom) + range.margin); + this.scrollTo(sPos.scrollLeft, sPos.scrollTop); + } + }), + + setSize: methodOp(function(width, height) { + var cm = this; + function interpret(val) { + return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; + } + if (width != null) cm.display.wrapper.style.width = interpret(width); + if (height != null) cm.display.wrapper.style.height = interpret(height); + if (cm.options.lineWrapping) clearLineMeasurementCache(this); + var lineNo = cm.display.viewFrom; + cm.doc.iter(lineNo, cm.display.viewTo, function(line) { + if (line.widgets) for (var i = 0; i < line.widgets.length; i++) + if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; } + ++lineNo; + }); + cm.curOp.forceUpdate = true; + signal(cm, "refresh", this); + }), + + operation: function(f){return runInOp(this, f);}, + + refresh: methodOp(function() { + var oldHeight = this.display.cachedTextHeight; + regChange(this); + this.curOp.forceUpdate = true; + clearCaches(this); + this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); + updateGutterSpace(this); + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) + estimateLineHeights(this); + signal(this, "refresh", this); + }), + + swapDoc: methodOp(function(doc) { + var old = this.doc; + old.cm = null; + attachDoc(this, doc); + clearCaches(this); + this.display.input.reset(); + this.scrollTo(doc.scrollLeft, doc.scrollTop); + this.curOp.forceScroll = true; + signalLater(this, "swapDoc", this, old); + return old; + }), + + getInputField: function(){return this.display.input.getField();}, + getWrapperElement: function(){return this.display.wrapper;}, + getScrollerElement: function(){return this.display.scroller;}, + getGutterElement: function(){return this.display.gutters;} + }; + eventMixin(CodeMirror); + + // OPTION DEFAULTS + + // The default configuration options. + var defaults = CodeMirror.defaults = {}; + // Functions to run when options are changed. + var optionHandlers = CodeMirror.optionHandlers = {}; + + function option(name, deflt, handle, notOnInit) { + CodeMirror.defaults[name] = deflt; + if (handle) optionHandlers[name] = + notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; + } + + // Passed to option handlers when there is no old value. + var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; + + // These two are, on init, called from the constructor because they + // have to be initialized before the editor can start at all. + option("value", "", function(cm, val) { + cm.setValue(val); + }, true); + option("mode", null, function(cm, val) { + cm.doc.modeOption = val; + loadMode(cm); + }, true); + + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option("tabSize", 4, function(cm) { + resetModeState(cm); + clearCaches(cm); + regChange(cm); + }, true); + option("lineSeparator", null, function(cm, val) { + cm.doc.lineSep = val; + if (!val) return; + var newBreaks = [], lineNo = cm.doc.first; + cm.doc.iter(function(line) { + for (var pos = 0;;) { + var found = line.text.indexOf(val, pos); + if (found == -1) break; + pos = found + val.length; + newBreaks.push(Pos(lineNo, found)); + } + lineNo++; + }); + for (var i = newBreaks.length - 1; i >= 0; i--) + replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) + }); + option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); + if (old != CodeMirror.Init) cm.refresh(); + }); + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true); + option("electricChars", true); + option("inputStyle", mobile ? "contenteditable" : "textarea", function() { + throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME + }, true); + option("rtlMoveVisually", !windows); + option("wholeLineUpdateBefore", true); + + option("theme", "default", function(cm) { + themeChanged(cm); + guttersChanged(cm); + }, true); + option("keyMap", "default", function(cm, val, old) { + var next = getKeyMap(val); + var prev = old != CodeMirror.Init && getKeyMap(old); + if (prev && prev.detach) prev.detach(cm, next); + if (next.attach) next.attach(cm, prev || null); + }); + option("extraKeys", null); + + option("lineWrapping", false, wrappingChanged, true); + option("gutters", [], function(cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("fixedGutter", true, function(cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; + cm.refresh(); + }, true); + option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true); + option("scrollbarStyle", "native", function(cm) { + initScrollbars(cm); + updateScrollbars(cm); + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); + }, true); + option("lineNumbers", false, function(cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("firstLineNumber", 1, guttersChanged, true); + option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); + option("showCursorWhenSelecting", false, updateSelection, true); + + option("resetSelectionOnContextMenu", true); + option("lineWiseCopyCut", true); + + option("readOnly", false, function(cm, val) { + if (val == "nocursor") { + onBlur(cm); + cm.display.input.blur(); + cm.display.disabled = true; + } else { + cm.display.disabled = false; + if (!val) cm.display.input.reset(); + } + }); + option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true); + option("dragDrop", true, dragDropChanged); + + option("cursorBlinkRate", 530); + option("cursorScrollMargin", 0); + option("cursorHeight", 1, updateSelection, true); + option("singleCursorHeightPerLine", true, updateSelection, true); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true, resetModeState, true); + option("addModeClass", false, resetModeState, true); + option("pollInterval", 100); + option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;}); + option("historyEventDelay", 1250); + option("viewportMargin", 10, function(cm){cm.refresh();}, true); + option("maxHighlightLength", 10000, resetModeState, true); + option("moveInputWithCursor", true, function(cm, val) { + if (!val) cm.display.input.resetPosition(); + }); + + option("tabindex", null, function(cm, val) { + cm.display.input.getField().tabIndex = val || ""; + }); + option("autofocus", null); + + // MODE DEFINITION AND QUERYING + + // Known modes, by name and by MIME + var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; + + // Extra arguments are stored as the mode's dependencies, which is + // used by (legacy) mechanisms like loadmode.js to automatically + // load a mode. (Preferred mechanism is the require/define calls.) + CodeMirror.defineMode = function(name, mode) { + if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; + if (arguments.length > 2) + mode.dependencies = Array.prototype.slice.call(arguments, 2); + modes[name] = mode; + }; + + CodeMirror.defineMIME = function(mime, spec) { + mimeModes[mime] = spec; + }; + + // Given a MIME type, a {name, ...options} config object, or a name + // string, return a mode config object. + CodeMirror.resolveMode = function(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name]; + if (typeof found == "string") found = {name: found}; + spec = createObj(found, spec); + spec.name = found.name; + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return CodeMirror.resolveMode("application/xml"); + } + if (typeof spec == "string") return {name: spec}; + else return spec || {name: "null"}; + }; + + // Given a mode spec (anything that resolveMode accepts), find and + // initialize an actual mode object. + CodeMirror.getMode = function(options, spec) { + var spec = CodeMirror.resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) return CodeMirror.getMode(options, "text/plain"); + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) continue; + if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; + modeObj[prop] = exts[prop]; + } + } + modeObj.name = spec.name; + if (spec.helperType) modeObj.helperType = spec.helperType; + if (spec.modeProps) for (var prop in spec.modeProps) + modeObj[prop] = spec.modeProps[prop]; + + return modeObj; + }; + + // Minimal default mode. + CodeMirror.defineMode("null", function() { + return {token: function(stream) {stream.skipToEnd();}}; + }); + CodeMirror.defineMIME("text/plain", "null"); + + // This can be used to attach properties to mode objects from + // outside the actual mode definition. + var modeExtensions = CodeMirror.modeExtensions = {}; + CodeMirror.extendMode = function(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); + copyObj(properties, exts); + }; + + // EXTENSIONS + + CodeMirror.defineExtension = function(name, func) { + CodeMirror.prototype[name] = func; + }; + CodeMirror.defineDocExtension = function(name, func) { + Doc.prototype[name] = func; + }; + CodeMirror.defineOption = option; + + var initHooks = []; + CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; + + var helpers = CodeMirror.helpers = {}; + CodeMirror.registerHelper = function(type, name, value) { + if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}; + helpers[type][name] = value; + }; + CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { + CodeMirror.registerHelper(type, name, value); + helpers[type]._global.push({pred: predicate, val: value}); + }; + + // MODE STATE HANDLING + + // Utility functions for working with state. Exported because nested + // modes need to do this for their inner modes. + + var copyState = CodeMirror.copyState = function(mode, state) { + if (state === true) return state; + if (mode.copyState) return mode.copyState(state); + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) val = val.concat([]); + nstate[n] = val; + } + return nstate; + }; + + var startState = CodeMirror.startState = function(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + }; + + // Given a mode and a state (for that mode), find the inner mode and + // state at the position that the state refers to. + CodeMirror.innerMode = function(mode, state) { + while (mode.innerMode) { + var info = mode.innerMode(state); + if (!info || info.mode == mode) break; + state = info.state; + mode = info.mode; + } + return info || {mode: mode, state: state}; + }; + + // STANDARD COMMANDS + + // Commands are parameter-less actions that can be performed on an + // editor, mostly used for keybindings. + var commands = CodeMirror.commands = { + selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, + singleSelection: function(cm) { + cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); + }, + killLine: function(cm) { + deleteNearSelection(cm, function(range) { + if (range.empty()) { + var len = getLine(cm.doc, range.head.line).text.length; + if (range.head.ch == len && range.head.line < cm.lastLine()) + return {from: range.head, to: Pos(range.head.line + 1, 0)}; + else + return {from: range.head, to: Pos(range.head.line, len)}; + } else { + return {from: range.from(), to: range.to()}; + } + }); + }, + deleteLine: function(cm) { + deleteNearSelection(cm, function(range) { + return {from: Pos(range.from().line, 0), + to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; + }); + }, + delLineLeft: function(cm) { + deleteNearSelection(cm, function(range) { + return {from: Pos(range.from().line, 0), to: range.from()}; + }); + }, + delWrappedLineLeft: function(cm) { + deleteNearSelection(cm, function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + var leftPos = cm.coordsChar({left: 0, top: top}, "div"); + return {from: leftPos, to: range.from()}; + }); + }, + delWrappedLineRight: function(cm) { + deleteNearSelection(cm, function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + return {from: range.from(), to: rightPos }; + }); + }, + undo: function(cm) {cm.undo();}, + redo: function(cm) {cm.redo();}, + undoSelection: function(cm) {cm.undoSelection();}, + redoSelection: function(cm) {cm.redoSelection();}, + goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, + goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, + goLineStart: function(cm) { + cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, + {origin: "+move", bias: 1}); + }, + goLineStartSmart: function(cm) { + cm.extendSelectionsBy(function(range) { + return lineStartSmart(cm, range.head); + }, {origin: "+move", bias: 1}); + }, + goLineEnd: function(cm) { + cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, + {origin: "+move", bias: -1}); + }, + goLineRight: function(cm) { + cm.extendSelectionsBy(function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + }, sel_move); + }, + goLineLeft: function(cm) { + cm.extendSelectionsBy(function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + return cm.coordsChar({left: 0, top: top}, "div"); + }, sel_move); + }, + goLineLeftSmart: function(cm) { + cm.extendSelectionsBy(function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + var pos = cm.coordsChar({left: 0, top: top}, "div"); + if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head); + return pos; + }, sel_move); + }, + goLineUp: function(cm) {cm.moveV(-1, "line");}, + goLineDown: function(cm) {cm.moveV(1, "line");}, + goPageUp: function(cm) {cm.moveV(-1, "page");}, + goPageDown: function(cm) {cm.moveV(1, "page");}, + goCharLeft: function(cm) {cm.moveH(-1, "char");}, + goCharRight: function(cm) {cm.moveH(1, "char");}, + goColumnLeft: function(cm) {cm.moveH(-1, "column");}, + goColumnRight: function(cm) {cm.moveH(1, "column");}, + goWordLeft: function(cm) {cm.moveH(-1, "word");}, + goGroupRight: function(cm) {cm.moveH(1, "group");}, + goGroupLeft: function(cm) {cm.moveH(-1, "group");}, + goWordRight: function(cm) {cm.moveH(1, "word");}, + delCharBefore: function(cm) {cm.deleteH(-1, "char");}, + delCharAfter: function(cm) {cm.deleteH(1, "char");}, + delWordBefore: function(cm) {cm.deleteH(-1, "word");}, + delWordAfter: function(cm) {cm.deleteH(1, "word");}, + delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, + delGroupAfter: function(cm) {cm.deleteH(1, "group");}, + indentAuto: function(cm) {cm.indentSelection("smart");}, + indentMore: function(cm) {cm.indentSelection("add");}, + indentLess: function(cm) {cm.indentSelection("subtract");}, + insertTab: function(cm) {cm.replaceSelection("\t");}, + insertSoftTab: function(cm) { + var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; + for (var i = 0; i < ranges.length; i++) { + var pos = ranges[i].from(); + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); + spaces.push(new Array(tabSize - col % tabSize + 1).join(" ")); + } + cm.replaceSelections(spaces); + }, + defaultTab: function(cm) { + if (cm.somethingSelected()) cm.indentSelection("add"); + else cm.execCommand("insertTab"); + }, + transposeChars: function(cm) { + runInOp(cm, function() { + var ranges = cm.listSelections(), newSel = []; + for (var i = 0; i < ranges.length; i++) { + var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; + if (line) { + if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1); + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1); + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), cur, "+transpose"); + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text; + if (prev) + cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose"); + } + } + newSel.push(new Range(cur, cur)); + } + cm.setSelections(newSel); + }); + }, + newlineAndIndent: function(cm) { + runInOp(cm, function() { + var len = cm.listSelections().length; + for (var i = 0; i < len; i++) { + var range = cm.listSelections()[i]; + cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input"); + cm.indentLine(range.from().line + 1, null, true); + ensureCursorVisible(cm); + } + }); + }, + toggleOverwrite: function(cm) {cm.toggleOverwrite();} + }; + + + // STANDARD KEYMAPS + + var keyMap = CodeMirror.keyMap = {}; + + keyMap.basic = { + "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", + "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", + "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", + "Tab": "defaultTab", "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", + "Esc": "singleSelection" + }; + // Note that the save and find-related commands aren't defined by + // default. User code or addons can define them. Unknown commands + // are simply ignored. + keyMap.pcDefault = { + "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", + "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", + fallthrough: "basic" + }; + // Very basic readline/emacs-style bindings, which are standard on Mac. + keyMap.emacsy = { + "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", + "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", + "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", + "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", + fallthrough: ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + + // KEYMAP DISPATCH + + function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/), name = parts[parts.length - 1]; + var alt, ctrl, shift, cmd; + for (var i = 0; i < parts.length - 1; i++) { + var mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) cmd = true; + else if (/^a(lt)?$/i.test(mod)) alt = true; + else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; + else if (/^s(hift)$/i.test(mod)) shift = true; + else throw new Error("Unrecognized modifier name: " + mod); + } + if (alt) name = "Alt-" + name; + if (ctrl) name = "Ctrl-" + name; + if (cmd) name = "Cmd-" + name; + if (shift) name = "Shift-" + name; + return name; + } + + // This is a kludge to keep keymaps mostly working as raw objects + // (backwards compatibility) while at the same time support features + // like normalization and multi-stroke key bindings. It compiles a + // new normalized keymap, and then updates the old object to reflect + // this. + CodeMirror.normalizeKeyMap = function(keymap) { + var copy = {}; + for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname]; + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue; + if (value == "...") { delete keymap[keyname]; continue; } + + var keys = map(keyname.split(" "), normalizeKeyName); + for (var i = 0; i < keys.length; i++) { + var val, name; + if (i == keys.length - 1) { + name = keys.join(" "); + val = value; + } else { + name = keys.slice(0, i + 1).join(" "); + val = "..."; + } + var prev = copy[name]; + if (!prev) copy[name] = val; + else if (prev != val) throw new Error("Inconsistent bindings for " + name); + } + delete keymap[keyname]; + } + for (var prop in copy) keymap[prop] = copy[prop]; + return keymap; + }; + + var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) { + map = getKeyMap(map); + var found = map.call ? map.call(key, context) : map[key]; + if (found === false) return "nothing"; + if (found === "...") return "multi"; + if (found != null && handle(found)) return "handled"; + + if (map.fallthrough) { + if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") + return lookupKey(key, map.fallthrough, handle, context); + for (var i = 0; i < map.fallthrough.length; i++) { + var result = lookupKey(key, map.fallthrough[i], handle, context); + if (result) return result; + } + } + }; + + // Modifier key presses don't count as 'real' key presses for the + // purpose of keymap fallthrough. + var isModifierKey = CodeMirror.isModifierKey = function(value) { + var name = typeof value == "string" ? value : keyNames[value.keyCode]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; + }; + + // Look up the name of a key as indicated by an event object. + var keyName = CodeMirror.keyName = function(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) return false; + var base = keyNames[event.keyCode], name = base; + if (name == null || event.altGraphKey) return false; + if (event.altKey && base != "Alt") name = "Alt-" + name; + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name; + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name; + if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name; + return name; + }; + + function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val; + } + + // FROMTEXTAREA + + CodeMirror.fromTextArea = function(textarea, options) { + options = options ? copyObj(options) : {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabIndex) + options.tabindex = textarea.tabIndex; + if (!options.placeholder && textarea.placeholder) + options.placeholder = textarea.placeholder; + // Set autofocus to true if this textarea is focused, or if it has + // autofocus and no other element is focused. + if (options.autofocus == null) { + var hasFocus = activeElt(); + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + + function save() {textarea.value = cm.getValue();} + if (textarea.form) { + on(textarea.form, "submit", save); + // Deplorable hack to make the submit method do the right thing. + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form, realSubmit = form.submit; + try { + var wrappedSubmit = form.submit = function() { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }; + } catch(e) {} + } + } + + options.finishInit = function(cm) { + cm.save = save; + cm.getTextArea = function() { return textarea; }; + cm.toTextArea = function() { + cm.toTextArea = isNaN; // Prevent this from being ran twice + save(); + textarea.parentNode.removeChild(cm.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + off(textarea.form, "submit", save); + if (typeof textarea.form.submit == "function") + textarea.form.submit = realSubmit; + } + }; + }; + + textarea.style.display = "none"; + var cm = CodeMirror(function(node) { + textarea.parentNode.insertBefore(node, textarea.nextSibling); + }, options); + return cm; + }; + + // STRING STREAM + + // Fed to the mode parsers, provides helper functions to make + // parsers more succinct. + + var StringStream = CodeMirror.StringStream = function(string, tabSize) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + }; + + StringStream.prototype = { + eol: function() {return this.pos >= this.string.length;}, + sol: function() {return this.pos == this.lineStart;}, + peek: function() {return this.string.charAt(this.pos) || undefined;}, + next: function() { + if (this.pos < this.string.length) + return this.string.charAt(this.pos++); + }, + eat: function(match) { + var ch = this.string.charAt(this.pos); + if (typeof match == "string") var ok = ch == match; + else var ok = ch && (match.test ? match.test(ch) : match(ch)); + if (ok) {++this.pos; return ch;} + }, + eatWhile: function(match) { + var start = this.pos; + while (this.eat(match)){} + return this.pos > start; + }, + eatSpace: function() { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; + return this.pos > start; + }, + skipToEnd: function() {this.pos = this.string.length;}, + skipTo: function(ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true;} + }, + backUp: function(n) {this.pos -= n;}, + column: function() { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); + this.lastColumnPos = this.start; + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + indentation: function() { + return countColumn(this.string, null, this.tabSize) - + (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + match: function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) this.pos += pattern.length; + return true; + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) return null; + if (match && consume !== false) this.pos += match[0].length; + return match; + } + }, + current: function(){return this.string.slice(this.start, this.pos);}, + hideFirstChars: function(n, inner) { + this.lineStart += n; + try { return inner(); } + finally { this.lineStart -= n; } + } + }; + + // TEXTMARKERS + + // Created with markText and setBookmark methods. A TextMarker is a + // handle that can be used to clear or find a marked position in the + // document. Line objects hold arrays (markedSpans) containing + // {from, to, marker} object pointing to such marker objects, and + // indicating that such a marker is present on that line. Multiple + // lines may point to the same marker when it spans across lines. + // The spans will have null for their from/to properties when the + // marker continues beyond the start/end of the line. Markers have + // links back to the lines they currently touch. + + var nextMarkerId = 0; + + var TextMarker = CodeMirror.TextMarker = function(doc, type) { + this.lines = []; + this.type = type; + this.doc = doc; + this.id = ++nextMarkerId; + }; + eventMixin(TextMarker); + + // Clear the marker. + TextMarker.prototype.clear = function() { + if (this.explicitlyCleared) return; + var cm = this.doc.cm, withOp = cm && !cm.curOp; + if (withOp) startOperation(cm); + if (hasHandler(this, "clear")) { + var found = this.find(); + if (found) signalLater(this, "clear", found.from, found.to); + } + var min = null, max = null; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); + else if (cm) { + if (span.to != null) max = lineNo(line); + if (span.from != null) min = lineNo(line); + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) + updateLineHeight(line, textHeight(cm.display)); + } + if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { + var visual = visualLine(this.lines[i]), len = lineLength(visual); + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual; + cm.display.maxLineLength = len; + cm.display.maxLineChanged = true; + } + } + + if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false; + if (cm) reCheckSelection(cm.doc); + } + if (cm) signalLater(cm, "markerCleared", cm, this); + if (withOp) endOperation(cm); + if (this.parent) this.parent.clear(); + }; + + // Find the position of the marker in the document. Returns a {from, + // to} object by default. Side can be passed to get a specific side + // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the + // Pos objects returned contain a line object, rather than a line + // number (used to prevent looking up the same line twice). + TextMarker.prototype.find = function(side, lineObj) { + if (side == null && this.type == "bookmark") side = 1; + var from, to; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from); + if (side == -1) return from; + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to); + if (side == 1) return to; + } + } + return from && {from: from, to: to}; + }; + + // Signals that the marker's widget changed, and surrounding layout + // should be recomputed. + TextMarker.prototype.changed = function() { + var pos = this.find(-1, true), widget = this, cm = this.doc.cm; + if (!pos || !cm) return; + runInOp(cm, function() { + var line = pos.line, lineN = lineNo(pos.line); + var view = findViewForLine(cm, lineN); + if (view) { + clearLineMeasurementCacheFor(view); + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; + } + cm.curOp.updateMaxLine = true; + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height; + widget.height = null; + var dHeight = widgetHeight(widget) - oldHeight; + if (dHeight) + updateLineHeight(line, line.height + dHeight); + } + }); + }; + + TextMarker.prototype.attachLine = function(line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) + (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); + } + this.lines.push(line); + }; + TextMarker.prototype.detachLine = function(line) { + this.lines.splice(indexOf(this.lines, line), 1); + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); + } + }; + + // Collapsed markers have unique ids, in order to be able to order + // them, which is needed for uniquely determining an outer marker + // when they overlap (they may nest, but not partially overlap). + var nextMarkerId = 0; + + // Create a marker, wire it up to the right lines, and + function markText(doc, from, to, options, type) { + // Shared markers (across linked documents) are handled separately + // (markTextShared will call out to this again, once per + // document). + if (options && options.shared) return markTextShared(doc, from, to, options, type); + // Ensure we are in an operation. + if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); + + var marker = new TextMarker(doc, type), diff = cmp(from, to); + if (options) copyObj(options, marker, false); + // Don't connect empty markers unless clearWhenEmpty is false + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) + return marker; + if (marker.replacedWith) { + // Showing up as a widget implies collapsed (widget replaces text) + marker.collapsed = true; + marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); + if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true"); + if (options.insertLeft) marker.widgetNode.insertLeft = true; + } + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || + from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) + throw new Error("Inserting collapsed marker partially overlapping an existing one"); + sawCollapsedSpans = true; + } + + if (marker.addToHistory) + addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); + + var curLine = from.line, cm = doc.cm, updateMaxLine; + doc.iter(curLine, to.line + 1, function(line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) + updateMaxLine = true; + if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); + addMarkedSpan(line, new MarkedSpan(marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null)); + ++curLine; + }); + // lineIsHidden depends on the presence of the spans, so needs a second pass + if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { + if (lineIsHidden(doc, line)) updateLineHeight(line, 0); + }); + + if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); + + if (marker.readOnly) { + sawReadOnlySpans = true; + if (doc.history.done.length || doc.history.undone.length) + doc.clearHistory(); + } + if (marker.collapsed) { + marker.id = ++nextMarkerId; + marker.atomic = true; + } + if (cm) { + // Sync editor state + if (updateMaxLine) cm.curOp.updateMaxLine = true; + if (marker.collapsed) + regChange(cm, from.line, to.line + 1); + else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) + for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text"); + if (marker.atomic) reCheckSelection(cm.doc); + signalLater(cm, "markerAdded", cm, marker); + } + return marker; + } + + // SHARED TEXTMARKERS + + // A shared marker spans multiple linked documents. It is + // implemented as a meta-marker-object controlling multiple normal + // markers. + var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) { + this.markers = markers; + this.primary = primary; + for (var i = 0; i < markers.length; ++i) + markers[i].parent = this; + }; + eventMixin(SharedTextMarker); + + SharedTextMarker.prototype.clear = function() { + if (this.explicitlyCleared) return; + this.explicitlyCleared = true; + for (var i = 0; i < this.markers.length; ++i) + this.markers[i].clear(); + signalLater(this, "clear"); + }; + SharedTextMarker.prototype.find = function(side, lineObj) { + return this.primary.find(side, lineObj); + }; + + function markTextShared(doc, from, to, options, type) { + options = copyObj(options); + options.shared = false; + var markers = [markText(doc, from, to, options, type)], primary = markers[0]; + var widget = options.widgetNode; + linkedDocs(doc, function(doc) { + if (widget) options.widgetNode = widget.cloneNode(true); + markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); + for (var i = 0; i < doc.linked.length; ++i) + if (doc.linked[i].isParent) return; + primary = lst(markers); + }); + return new SharedTextMarker(markers, primary); + } + + function findSharedMarkers(doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), + function(m) { return m.parent; }); + } + + function copySharedMarkers(doc, markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], pos = marker.find(); + var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); + marker.markers.push(subMark); + subMark.parent = marker; + } + } + } + + function detachSharedMarkers(markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], linked = [marker.primary.doc];; + linkedDocs(marker.primary.doc, function(d) { linked.push(d); }); + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j]; + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null; + marker.markers.splice(j--, 1); + } + } + } + } + + // TEXTMARKER SPANS + + function MarkedSpan(marker, from, to) { + this.marker = marker; + this.from = from; this.to = to; + } + + // Search an array of spans for a span matching the given marker. + function getMarkedSpanFor(spans, marker) { + if (spans) for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.marker == marker) return span; + } + } + // Remove a span from an array, returning undefined if no spans are + // left (we don't store arrays for lines without spans). + function removeMarkedSpan(spans, span) { + for (var r, i = 0; i < spans.length; ++i) + if (spans[i] != span) (r || (r = [])).push(spans[i]); + return r; + } + // Add a span to a line. + function addMarkedSpan(line, span) { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; + span.marker.attachLine(line); + } + + // Used for the algorithm that adjusts markers for a change in the + // document. These functions cut an array of spans at a given + // character position, returning an array of remaining chunks (or + // undefined if nothing remains). + function markedSpansBefore(old, startCh, isInsert) { + if (old) for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); + (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); + } + } + return nw; + } + function markedSpansAfter(old, endCh, isInsert) { + if (old) for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); + (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh)); + } + } + return nw; + } + + // Given a change object, compute the new set of marker spans that + // cover the line in which the change took place. Removes spans + // entirely within the change, reconnects spans belonging to the + // same marker that appear on both sides of the change, and cuts off + // spans partially within the change. Returns an array of span + // arrays with one element for each line in (after) the change. + function stretchSpansOverChange(doc, change) { + if (change.full) return null; + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; + if (!oldFirst && !oldLast) return null; + + var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh, isInsert); + var last = markedSpansAfter(oldLast, endCh, isInsert); + + // Next, merge those two ends + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); + if (first) { + // Fix up .to properties of first + for (var i = 0; i < first.length; ++i) { + var span = first[i]; + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker); + if (!found) span.to = startCh; + else if (sameLine) span.to = found.to == null ? null : found.to + offset; + } + } + } + if (last) { + // Fix up .from in last (or move them into first in case of sameLine) + for (var i = 0; i < last.length; ++i) { + var span = last[i]; + if (span.to != null) span.to += offset; + if (span.from == null) { + var found = getMarkedSpanFor(first, span.marker); + if (!found) { + span.from = offset; + if (sameLine) (first || (first = [])).push(span); + } + } else { + span.from += offset; + if (sameLine) (first || (first = [])).push(span); + } + } + } + // Make sure we didn't create any zero-length spans + if (first) first = clearEmptySpans(first); + if (last && last != first) last = clearEmptySpans(last); + + var newMarkers = [first]; + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = change.text.length - 2, gapMarkers; + if (gap > 0 && first) + for (var i = 0; i < first.length; ++i) + if (first[i].to == null) + (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null)); + for (var i = 0; i < gap; ++i) + newMarkers.push(gapMarkers); + newMarkers.push(last); + } + return newMarkers; + } + + // Remove spans that are empty and don't have a clearWhenEmpty + // option of false. + function clearEmptySpans(spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) + spans.splice(i--, 1); + } + if (!spans.length) return null; + return spans; + } + + // Used for un/re-doing changes from the history. Combines the + // result of computing the existing spans with the set of spans that + // existed in the history (so that deleting around a span and then + // undoing brings back the span). + function mergeOldSpans(doc, change) { + var old = getOldSpans(doc, change); + var stretched = stretchSpansOverChange(doc, change); + if (!old) return stretched; + if (!stretched) return old; + + for (var i = 0; i < old.length; ++i) { + var oldCur = old[i], stretchCur = stretched[i]; + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j]; + for (var k = 0; k < oldCur.length; ++k) + if (oldCur[k].marker == span.marker) continue spans; + oldCur.push(span); + } + } else if (stretchCur) { + old[i] = stretchCur; + } + } + return old; + } + + // Used to 'clip' out readOnly ranges when making a change. + function removeReadOnlyRanges(doc, from, to) { + var markers = null; + doc.iter(from.line, to.line + 1, function(line) { + if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { + var mark = line.markedSpans[i].marker; + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) + (markers || (markers = [])).push(mark); + } + }); + if (!markers) return null; + var parts = [{from: from, to: to}]; + for (var i = 0; i < markers.length; ++i) { + var mk = markers[i], m = mk.find(0); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; + var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) + newParts.push({from: p.from, to: m.from}); + if (dto > 0 || !mk.inclusiveRight && !dto) + newParts.push({from: m.to, to: p.to}); + parts.splice.apply(parts, newParts); + j += newParts.length - 1; + } + } + return parts; + } + + // Connect or disconnect spans from a line. + function detachMarkedSpans(line) { + var spans = line.markedSpans; + if (!spans) return; + for (var i = 0; i < spans.length; ++i) + spans[i].marker.detachLine(line); + line.markedSpans = null; + } + function attachMarkedSpans(line, spans) { + if (!spans) return; + for (var i = 0; i < spans.length; ++i) + spans[i].marker.attachLine(line); + line.markedSpans = spans; + } + + // Helpers used when computing which overlapping collapsed span + // counts as the larger one. + function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; } + function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; } + + // Returns a number indicating which of two overlapping collapsed + // spans is larger (and thus includes the other). Falls back to + // comparing ids when the spans cover exactly the same range. + function compareCollapsedMarkers(a, b) { + var lenDiff = a.lines.length - b.lines.length; + if (lenDiff != 0) return lenDiff; + var aPos = a.find(), bPos = b.find(); + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); + if (fromCmp) return -fromCmp; + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); + if (toCmp) return toCmp; + return b.id - a.id; + } + + // Find out whether a line ends or starts in a collapsed span. If + // so, return the marker for that span. + function collapsedSpanAtSide(line, start) { + var sps = sawCollapsedSpans && line.markedSpans, found; + if (sps) for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) + found = sp.marker; + } + return found; + } + function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); } + function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); } + + // Test whether there exists a collapsed span that partially + // overlaps (covers the start or end, but not both) of a new span. + // Such overlap is not allowed. + function conflictingCollapsedRange(doc, lineNo, from, to, marker) { + var line = getLine(doc, lineNo); + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) for (var i = 0; i < sps.length; ++i) { + var sp = sps[i]; + if (!sp.marker.collapsed) continue; + var found = sp.marker.find(0); + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; + if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) || + fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight))) + return true; + } + } + + // A visual line is a line as drawn on the screen. Folding, for + // example, can cause multiple logical lines to appear on the same + // visual line. This finds the start of the visual line that the + // given line is part of (usually that is the line itself). + function visualLine(line) { + var merged; + while (merged = collapsedSpanAtStart(line)) + line = merged.find(-1, true).line; + return line; + } + + // Returns an array of logical lines that continue the visual line + // started by the argument, or undefined if there are no such lines. + function visualLineContinued(line) { + var merged, lines; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + (lines || (lines = [])).push(line); + } + return lines; + } + + // Get the line number of the start of the visual line that the + // given line number is part of. + function visualLineNo(doc, lineN) { + var line = getLine(doc, lineN), vis = visualLine(line); + if (line == vis) return lineN; + return lineNo(vis); + } + // Get the line number of the start of the next visual line after + // the given line. + function visualLineEndNo(doc, lineN) { + if (lineN > doc.lastLine()) return lineN; + var line = getLine(doc, lineN), merged; + if (!lineIsHidden(doc, line)) return lineN; + while (merged = collapsedSpanAtEnd(line)) + line = merged.find(1, true).line; + return lineNo(line) + 1; + } + + // Compute whether a line is hidden. Lines count as hidden when they + // are part of a visual line that starts with another line, or when + // they are entirely covered by collapsed, non-widget span. + function lineIsHidden(doc, line) { + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (!sp.marker.collapsed) continue; + if (sp.from == null) return true; + if (sp.marker.widgetNode) continue; + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) + return true; + } + } + function lineIsHiddenInner(doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true); + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); + } + if (span.marker.inclusiveRight && span.to == line.text.length) + return true; + for (var sp, i = 0; i < line.markedSpans.length; ++i) { + sp = line.markedSpans[i]; + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && + (sp.to == null || sp.to != span.from) && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp)) return true; + } + } + + // LINE WIDGETS + + // Line widgets are block elements displayed above or below a line. + + var LineWidget = CodeMirror.LineWidget = function(doc, node, options) { + if (options) for (var opt in options) if (options.hasOwnProperty(opt)) + this[opt] = options[opt]; + this.doc = doc; + this.node = node; + }; + eventMixin(LineWidget); + + function adjustScrollWhenAboveVisible(cm, line, diff) { + if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) + addToScrollPos(cm, null, diff); + } + + LineWidget.prototype.clear = function() { + var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); + if (no == null || !ws) return; + for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); + if (!ws.length) line.widgets = null; + var height = widgetHeight(this); + updateLineHeight(line, Math.max(0, line.height - height)); + if (cm) runInOp(cm, function() { + adjustScrollWhenAboveVisible(cm, line, -height); + regLineChange(cm, no, "widget"); + }); + }; + LineWidget.prototype.changed = function() { + var oldH = this.height, cm = this.doc.cm, line = this.line; + this.height = null; + var diff = widgetHeight(this) - oldH; + if (!diff) return; + updateLineHeight(line, line.height + diff); + if (cm) runInOp(cm, function() { + cm.curOp.forceUpdate = true; + adjustScrollWhenAboveVisible(cm, line, diff); + }); + }; + + function widgetHeight(widget) { + if (widget.height != null) return widget.height; + var cm = widget.doc.cm; + if (!cm) return 0; + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;"; + if (widget.coverGutter) + parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; + if (widget.noHScroll) + parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); + } + return widget.height = widget.node.offsetHeight; + } + + function addLineWidget(doc, handle, node, options) { + var widget = new LineWidget(doc, node, options); + var cm = doc.cm; + if (cm && widget.noHScroll) cm.display.alignWidgets = true; + changeLine(doc, handle, "widget", function(line) { + var widgets = line.widgets || (line.widgets = []); + if (widget.insertAt == null) widgets.push(widget); + else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); + widget.line = line; + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop; + updateLineHeight(line, line.height + widgetHeight(widget)); + if (aboveVisible) addToScrollPos(cm, null, widget.height); + cm.curOp.forceUpdate = true; + } + return true; + }); + return widget; + } + + // LINE DATA STRUCTURE + + // Line objects. These hold state related to a line, including + // highlighting info (the styles array). + var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { + this.text = text; + attachMarkedSpans(this, markedSpans); + this.height = estimateHeight ? estimateHeight(this) : 1; + }; + eventMixin(Line); + Line.prototype.lineNo = function() { return lineNo(this); }; + + // Change the content (text, markers) of a line. Automatically + // invalidates cached information and tries to re-estimate the + // line's height. + function updateLine(line, text, markedSpans, estimateHeight) { + line.text = text; + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + if (line.order != null) line.order = null; + detachMarkedSpans(line); + attachMarkedSpans(line, markedSpans); + var estHeight = estimateHeight ? estimateHeight(line) : 1; + if (estHeight != line.height) updateLineHeight(line, estHeight); + } + + // Detach a line from the document tree and its markers. + function cleanUpLine(line) { + line.parent = null; + detachMarkedSpans(line); + } + + function extractLineClasses(type, output) { + if (type) for (;;) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); + if (!lineClass) break; + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); + var prop = lineClass[1] ? "bgClass" : "textClass"; + if (output[prop] == null) + output[prop] = lineClass[2]; + else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) + output[prop] += " " + lineClass[2]; + } + return type; + } + + function callBlankLine(mode, state) { + if (mode.blankLine) return mode.blankLine(state); + if (!mode.innerMode) return; + var inner = CodeMirror.innerMode(mode, state); + if (inner.mode.blankLine) return inner.mode.blankLine(inner.state); + } + + function readToken(mode, stream, state, inner) { + for (var i = 0; i < 10; i++) { + if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode; + var style = mode.token(stream, state); + if (stream.pos > stream.start) return style; + } + throw new Error("Mode " + mode.name + " failed to advance stream."); + } + + // Utility for getTokenAt and getLineTokens + function takeToken(cm, pos, precise, asArray) { + function getObj(copy) { + return {start: stream.start, end: stream.pos, + string: stream.current(), + type: style || null, + state: copy ? copyState(doc.mode, state) : state}; + } + + var doc = cm.doc, mode = doc.mode, style; + pos = clipPos(doc, pos); + var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise); + var stream = new StringStream(line.text, cm.options.tabSize), tokens; + if (asArray) tokens = []; + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos; + style = readToken(mode, stream, state); + if (asArray) tokens.push(getObj(true)); + } + return asArray ? tokens : getObj(); + } + + // Run the given mode's parser over a line, calling f for each token. + function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans; + if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; + var curStart = 0, curStyle = null; + var stream = new StringStream(text, cm.options.tabSize), style; + var inner = cm.options.addModeClass && [null]; + if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses); + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false; + if (forceToEnd) processLine(cm, text, state, stream.pos); + stream.pos = text.length; + style = null; + } else { + style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses); + } + if (inner) { + var mName = inner[0].name; + if (mName) style = "m-" + (style ? mName + " " + style : mName); + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 50000); + f(curStart, curStyle); + } + curStyle = style; + } + stream.start = stream.pos; + } + while (curStart < stream.pos) { + // Webkit seems to refuse to render text nodes longer than 57444 characters + var pos = Math.min(stream.pos, curStart + 50000); + f(pos, curStyle); + curStart = pos; + } + } + + // Compute a style array (an array starting with a mode generation + // -- for invalidation -- followed by pairs of end positions and + // style strings), which is used to highlight the tokens on the + // line. + function highlightLine(cm, line, state, forceToEnd) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + var st = [cm.state.modeGen], lineClasses = {}; + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, state, function(end, style) { + st.push(end, style); + }, lineClasses, forceToEnd); + + // Run overlays, adjust style array. + for (var o = 0; o < cm.state.overlays.length; ++o) { + var overlay = cm.state.overlays[o], i = 1, at = 0; + runMode(cm, line.text, overlay.mode, true, function(end, style) { + var start = i; + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + var i_end = st[i]; + if (i_end > end) + st.splice(i, 1, end, st[i+1], i_end); + i += 2; + at = Math.min(end, i_end); + } + if (!style) return; + if (overlay.opaque) { + st.splice(start, i - start, end, "cm-overlay " + style); + i = start + 2; + } else { + for (; start < i; start += 2) { + var cur = st[start+1]; + st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style; + } + } + }, lineClasses); + } + + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}; + } + + function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var state = getStateBefore(cm, lineNo(line)); + var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state); + line.stateAfter = state; + line.styles = result.styles; + if (result.classes) line.styleClasses = result.classes; + else if (line.styleClasses) line.styleClasses = null; + if (updateFrontier === cm.doc.frontier) cm.doc.frontier++; + } + return line.styles; + } + + // Lightweight form of highlight -- proceed over this line and + // update state, but don't save a style array. Used for lines that + // aren't currently visible. + function processLine(cm, text, state, startAt) { + var mode = cm.doc.mode; + var stream = new StringStream(text, cm.options.tabSize); + stream.start = stream.pos = startAt || 0; + if (text == "") callBlankLine(mode, state); + while (!stream.eol()) { + readToken(mode, stream, state); + stream.start = stream.pos; + } + } + + // Convert a style as returned by a mode (either null, or a string + // containing one or more styles) to a CSS style. This is cached, + // and also looks for line-wide styles. + var styleToClassCache = {}, styleToClassCacheWithMode = {}; + function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) return null; + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; + return cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")); + } + + // Render the DOM representation of the text of a line. Also builds + // up a 'line map', which points at the DOM nodes that represent + // specific stretches of text, and is used by the measuring code. + // The returned object contains the DOM node, this map, and + // information about line-wide styles that were set by the mode. + function buildLineContent(cm, lineView) { + // The padding-right forces the element to have a 'border', which + // is needed on Webkit to be able to get line-level bounding + // rectangles for it (in measureChar). + var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); + var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, + col: 0, pos: 0, cm: cm, + splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; + lineView.measure = {}; + + // Iterate over the logical lines that make up this visual line. + for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { + var line = i ? lineView.rest[i - 1] : lineView.line, order; + builder.pos = 0; + builder.addToken = buildToken; + // Optionally wire in some hacks into the token-rendering + // algorithm, to deal with browser quirks. + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) + builder.addToken = buildTokenBadBidi(builder.addToken, order); + builder.map = []; + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); + if (line.styleClasses) { + if (line.styleClasses.bgClass) + builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); + if (line.styleClasses.textClass) + builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); + } + + // Ensure at least a single node is present, for measuring. + if (builder.map.length == 0) + builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); + + // Store the map and a cache object for the current logical line + if (i == 0) { + lineView.measure.map = builder.map; + lineView.measure.cache = {}; + } else { + (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); + (lineView.measure.caches || (lineView.measure.caches = [])).push({}); + } + } + + // See issue #2901 + if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className)) + builder.content.className = "cm-tab-wrap-hack"; + + signal(cm, "renderLine", cm, lineView.line, builder.pre); + if (builder.pre.className) + builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); + + return builder; + } + + function defaultSpecialCharPlaceholder(ch) { + var token = elt("span", "\u2022", "cm-invalidchar"); + token.title = "\\u" + ch.charCodeAt(0).toString(16); + token.setAttribute("aria-label", token.title); + return token; + } + + // Build up the DOM representation for a single token, and add it to + // the line map. Takes care to render special characters separately. + function buildToken(builder, text, style, startStyle, endStyle, title, css) { + if (!text) return; + var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text; + var special = builder.cm.state.specialChars, mustWrap = false; + if (!special.test(text)) { + builder.col += text.length; + var content = document.createTextNode(displayText); + builder.map.push(builder.pos, builder.pos + text.length, content); + if (ie && ie_version < 9) mustWrap = true; + builder.pos += text.length; + } else { + var content = document.createDocumentFragment(), pos = 0; + while (true) { + special.lastIndex = pos; + var m = special.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); + else content.appendChild(txt); + builder.map.push(builder.pos, builder.pos + skipped, txt); + builder.col += skipped; + builder.pos += skipped; + } + if (!m) break; + pos += skipped + 1; + if (m[0] == "\t") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; + var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + txt.setAttribute("role", "presentation"); + txt.setAttribute("cm-text", "\t"); + builder.col += tabWidth; + } else if (m[0] == "\r" || m[0] == "\n") { + var txt = content.appendChild(elt("span", m[0] == "\r" ? "␍" : "␤", "cm-invalidchar")); + txt.setAttribute("cm-text", m[0]); + builder.col += 1; + } else { + var txt = builder.cm.options.specialCharPlaceholder(m[0]); + txt.setAttribute("cm-text", m[0]); + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); + else content.appendChild(txt); + builder.col += 1; + } + builder.map.push(builder.pos, builder.pos + 1, txt); + builder.pos++; + } + } + if (style || startStyle || endStyle || mustWrap || css) { + var fullStyle = style || ""; + if (startStyle) fullStyle += startStyle; + if (endStyle) fullStyle += endStyle; + var token = elt("span", [content], fullStyle, css); + if (title) token.title = title; + return builder.content.appendChild(token); + } + builder.content.appendChild(content); + } + + function splitSpaces(old) { + var out = " "; + for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; + out += " "; + return out; + } + + // Work around nonsense dimensions being reported for stretches of + // right-to-left text. + function buildTokenBadBidi(inner, order) { + return function(builder, text, style, startStyle, endStyle, title, css) { + style = style ? style + " cm-force-border" : "cm-force-border"; + var start = builder.pos, end = start + text.length; + for (;;) { + // Find the part that overlaps with the start of this text + for (var i = 0; i < order.length; i++) { + var part = order[i]; + if (part.to > start && part.from <= start) break; + } + if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css); + inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); + startStyle = null; + text = text.slice(part.to - start); + start = part.to; + } + }; + } + + function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode; + if (widget) builder.map.push(builder.pos, builder.pos + size, widget); + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) + widget = builder.content.appendChild(document.createElement("span")); + widget.setAttribute("cm-marker", marker.id); + } + if (widget) { + builder.cm.display.input.setUneditable(widget); + builder.content.appendChild(widget); + } + builder.pos += size; + } + + // Outputs a number of spans to make up a line, taking highlighting + // and marked text into account. + function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0; + if (!spans) { + for (var i = 1; i < styles.length; i+=2) + builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options)); + return; + } + + var len = allText.length, pos = 0, i = 1, text = "", style, css; + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = title = css = ""; + collapsed = null; nextChange = Infinity; + var foundBookmarks = []; + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker; + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m); + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to; + spanEndStyle = ""; + } + if (m.className) spanStyle += " " + m.className; + if (m.css) css = m.css; + if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; + if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; + if (m.title && !title) title = m.title; + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) + collapsed = sp; + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; + } + } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, collapsed.from == null); + if (collapsed.to == null) return; + if (collapsed.to == pos) collapsed = false; + } + if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j) + buildCollapsedSpan(builder, 0, foundBookmarks[j]); + } + if (pos >= len) break; + + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text; + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); + } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} + pos = end; + spanStartStyle = ""; + } + text = allText.slice(at, at = styles[i++]); + style = interpretTokenStyle(styles[i++], builder.cm.options); + } + } + } + + // DOCUMENT DATA STRUCTURE + + // By default, updates that start and end at the beginning of a line + // are treated specially, in order to make the association of line + // widgets and marker elements with the text behave more intuitive. + function isWholeLineUpdate(doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && + (!doc.cm || doc.cm.options.wholeLineUpdateBefore); + } + + // Perform a change on the document data structure. + function updateDoc(doc, change, markedSpans, estimateHeight) { + function spansFor(n) {return markedSpans ? markedSpans[n] : null;} + function update(line, text, spans) { + updateLine(line, text, spans, estimateHeight); + signalLater(line, "change", line, change); + } + function linesFor(start, end) { + for (var i = start, result = []; i < end; ++i) + result.push(new Line(text[i], spansFor(i), estimateHeight)); + return result; + } + + var from = change.from, to = change.to, text = change.text; + var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; + + // Adjust the line structure + if (change.full) { + doc.insert(0, linesFor(0, text.length)); + doc.remove(text.length, doc.size - text.length); + } else if (isWholeLineUpdate(doc, change)) { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = linesFor(0, text.length - 1); + update(lastLine, lastLine.text, lastSpans); + if (nlines) doc.remove(from.line, nlines); + if (added.length) doc.insert(from.line, added); + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); + } else { + var added = linesFor(1, text.length - 1); + added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + doc.insert(from.line + 1, added); + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); + doc.remove(from.line + 1, nlines); + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); + var added = linesFor(1, text.length - 1); + if (nlines > 1) doc.remove(from.line + 1, nlines - 1); + doc.insert(from.line + 1, added); + } + + signalLater(doc, "change", doc, change); + } + + // The document is represented as a BTree consisting of leaves, with + // chunk of lines in them, and branches, with up to ten leaves or + // other branch nodes below them. The top node is always a branch + // node, and is the document object itself (meaning it has + // additional methods and properties). + // + // All nodes have parent links. The tree is used both to go from + // line numbers to line objects, and to go from objects to numbers. + // It also indexes by height, and is used to convert between height + // and line object, and to find the total height of the document. + // + // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html + + function LeafChunk(lines) { + this.lines = lines; + this.parent = null; + for (var i = 0, height = 0; i < lines.length; ++i) { + lines[i].parent = this; + height += lines[i].height; + } + this.height = height; + } + + LeafChunk.prototype = { + chunkSize: function() { return this.lines.length; }, + // Remove the n lines at offset 'at'. + removeInner: function(at, n) { + for (var i = at, e = at + n; i < e; ++i) { + var line = this.lines[i]; + this.height -= line.height; + cleanUpLine(line); + signalLater(line, "delete"); + } + this.lines.splice(at, n); + }, + // Helper used to collapse a small branch into a single leaf. + collapse: function(lines) { + lines.push.apply(lines, this.lines); + }, + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function(at, lines, height) { + this.height += height; + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); + for (var i = 0; i < lines.length; ++i) lines[i].parent = this; + }, + // Used to iterate over a part of the tree. + iterN: function(at, n, op) { + for (var e = at + n; at < e; ++at) + if (op(this.lines[at])) return true; + } + }; + + function BranchChunk(children) { + this.children = children; + var size = 0, height = 0; + for (var i = 0; i < children.length; ++i) { + var ch = children[i]; + size += ch.chunkSize(); height += ch.height; + ch.parent = this; + } + this.size = size; + this.height = height; + this.parent = null; + } + + BranchChunk.prototype = { + chunkSize: function() { return this.size; }, + removeInner: function(at, n) { + this.size -= n; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height; + child.removeInner(at, rm); + this.height -= oldHeight - child.height; + if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } + if ((n -= rm) == 0) break; + at = 0; + } else at -= sz; + } + // If the result is smaller than 25 lines, ensure that it is a + // single leaf node. + if (this.size - n < 25 && + (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + collapse: function(lines) { + for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines); + }, + insertInner: function(at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at <= sz) { + child.insertInner(at, lines, height); + if (child.lines && child.lines.length > 50) { + while (child.lines.length > 50) { + var spilled = child.lines.splice(child.lines.length - 25, 25); + var newleaf = new LeafChunk(spilled); + child.height -= newleaf.height; + this.children.splice(i + 1, 0, newleaf); + newleaf.parent = this; + } + this.maybeSpill(); + } + break; + } + at -= sz; + } + }, + // When a node has grown, check whether it should be split. + maybeSpill: function() { + if (this.children.length <= 10) return; + var me = this; + do { + var spilled = me.children.splice(me.children.length - 5, 5); + var sibling = new BranchChunk(spilled); + if (!me.parent) { // Become the parent node + var copy = new BranchChunk(me.children); + copy.parent = me; + me.children = [copy, sibling]; + me = copy; + } else { + me.size -= sibling.size; + me.height -= sibling.height; + var myIndex = indexOf(me.parent.children, me); + me.parent.children.splice(myIndex + 1, 0, sibling); + } + sibling.parent = me.parent; + } while (me.children.length > 10); + me.parent.maybeSpill(); + }, + iterN: function(at, n, op) { + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var used = Math.min(n, sz - at); + if (child.iterN(at, used, op)) return true; + if ((n -= used) == 0) break; + at = 0; + } else at -= sz; + } + } + }; + + var nextDocId = 0; + var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) { + if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep); + if (firstLine == null) firstLine = 0; + + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); + this.first = firstLine; + this.scrollTop = this.scrollLeft = 0; + this.cantEdit = false; + this.cleanGeneration = 1; + this.frontier = firstLine; + var start = Pos(firstLine, 0); + this.sel = simpleSelection(start); + this.history = new History(null); + this.id = ++nextDocId; + this.modeOption = mode; + this.lineSep = lineSep; + + if (typeof text == "string") text = this.splitLines(text); + updateDoc(this, {from: start, to: start, text: text}); + setSelection(this, simpleSelection(start), sel_dontScroll); + }; + + Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function(from, to, op) { + if (op) this.iterN(from - this.first, to - from, op); + else this.iterN(this.first, this.first + this.size, from); + }, + + // Non-public interface for adding and removing lines. + insert: function(at, lines) { + var height = 0; + for (var i = 0; i < lines.length; ++i) height += lines[i].height; + this.insertInner(at - this.first, lines, height); + }, + remove: function(at, n) { this.removeInner(at - this.first, n); }, + + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + + getValue: function(lineSep) { + var lines = getLines(this, this.first, this.first + this.size); + if (lineSep === false) return lines; + return lines.join(lineSep || this.lineSeparator()); + }, + setValue: docMethodOp(function(code) { + var top = Pos(this.first, 0), last = this.first + this.size - 1; + makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), + text: this.splitLines(code), origin: "setValue", full: true}, true); + setSelection(this, simpleSelection(top)); + }), + replaceRange: function(code, from, to, origin) { + from = clipPos(this, from); + to = to ? clipPos(this, to) : from; + replaceRange(this, code, from, to, origin); + }, + getRange: function(from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); + if (lineSep === false) return lines; + return lines.join(lineSep || this.lineSeparator()); + }, + + getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, + + getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, + getLineNumber: function(line) {return lineNo(line);}, + + getLineHandleVisualStart: function(line) { + if (typeof line == "number") line = getLine(this, line); + return visualLine(line); + }, + + lineCount: function() {return this.size;}, + firstLine: function() {return this.first;}, + lastLine: function() {return this.first + this.size - 1;}, + + clipPos: function(pos) {return clipPos(this, pos);}, + + getCursor: function(start) { + var range = this.sel.primary(), pos; + if (start == null || start == "head") pos = range.head; + else if (start == "anchor") pos = range.anchor; + else if (start == "end" || start == "to" || start === false) pos = range.to(); + else pos = range.from(); + return pos; + }, + listSelections: function() { return this.sel.ranges; }, + somethingSelected: function() {return this.sel.somethingSelected();}, + + setCursor: docMethodOp(function(line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); + }), + setSelection: docMethodOp(function(anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); + }), + extendSelection: docMethodOp(function(head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); + }), + extendSelections: docMethodOp(function(heads, options) { + extendSelections(this, clipPosArray(this, heads, options)); + }), + extendSelectionsBy: docMethodOp(function(f, options) { + extendSelections(this, map(this.sel.ranges, f), options); + }), + setSelections: docMethodOp(function(ranges, primary, options) { + if (!ranges.length) return; + for (var i = 0, out = []; i < ranges.length; i++) + out[i] = new Range(clipPos(this, ranges[i].anchor), + clipPos(this, ranges[i].head)); + if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); + setSelection(this, normalizeSelection(out, primary), options); + }), + addSelection: docMethodOp(function(anchor, head, options) { + var ranges = this.sel.ranges.slice(0); + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); + setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); + }), + + getSelection: function(lineSep) { + var ranges = this.sel.ranges, lines; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + lines = lines ? lines.concat(sel) : sel; + } + if (lineSep === false) return lines; + else return lines.join(lineSep || this.lineSeparator()); + }, + getSelections: function(lineSep) { + var parts = [], ranges = this.sel.ranges; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator()); + parts[i] = sel; + } + return parts; + }, + replaceSelection: function(code, collapse, origin) { + var dup = []; + for (var i = 0; i < this.sel.ranges.length; i++) + dup[i] = code; + this.replaceSelections(dup, collapse, origin || "+input"); + }, + replaceSelections: docMethodOp(function(code, collapse, origin) { + var changes = [], sel = this.sel; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin}; + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); + for (var i = changes.length - 1; i >= 0; i--) + makeChange(this, changes[i]); + if (newSel) setSelectionReplaceHistory(this, newSel); + else if (this.cm) ensureCursorVisible(this.cm); + }), + undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), + redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), + undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), + redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), + + setExtending: function(val) {this.extend = val;}, + getExtending: function() {return this.extend;}, + + historySize: function() { + var hist = this.history, done = 0, undone = 0; + for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; + for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; + return {undo: done, redo: undone}; + }, + clearHistory: function() {this.history = new History(this.history.maxGeneration);}, + + markClean: function() { + this.cleanGeneration = this.changeGeneration(true); + }, + changeGeneration: function(forceSplit) { + if (forceSplit) + this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; + return this.history.generation; + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration); + }, + + getHistory: function() { + return {done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone)}; + }, + setHistory: function(histData) { + var hist = this.history = new History(this.history.maxGeneration); + hist.done = copyHistoryArray(histData.done.slice(0), null, true); + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); + }, + + addLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + if (!line[prop]) line[prop] = cls; + else if (classTest(cls).test(line[prop])) return false; + else line[prop] += " " + cls; + return true; + }); + }), + removeLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + var cur = line[prop]; + if (!cur) return false; + else if (cls == null) line[prop] = null; + else { + var found = cur.match(classTest(cls)); + if (!found) return false; + var end = found.index + found[0].length; + line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + } + return true; + }); + }), + + addLineWidget: docMethodOp(function(handle, node, options) { + return addLineWidget(this, handle, node, options); + }), + removeLineWidget: function(widget) { widget.clear(); }, + + markText: function(from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); + }, + setBookmark: function(pos, options) { + var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents}; + pos = clipPos(this, pos); + return markText(this, pos, pos, realOpts, "bookmark"); + }, + findMarksAt: function(pos) { + pos = clipPos(this, pos); + var markers = [], spans = getLine(this, pos.line).markedSpans; + if (spans) for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if ((span.from == null || span.from <= pos.ch) && + (span.to == null || span.to >= pos.ch)) + markers.push(span.marker.parent || span.marker); + } + return markers; + }, + findMarks: function(from, to, filter) { + from = clipPos(this, from); to = clipPos(this, to); + var found = [], lineNo = from.line; + this.iter(from.line, to.line + 1, function(line) { + var spans = line.markedSpans; + if (spans) for (var i = 0; i < spans.length; i++) { + var span = spans[i]; + if (!(lineNo == from.line && from.ch > span.to || + span.from == null && lineNo != from.line|| + lineNo == to.line && span.from > to.ch) && + (!filter || filter(span.marker))) + found.push(span.marker.parent || span.marker); + } + ++lineNo; + }); + return found; + }, + getAllMarks: function() { + var markers = []; + this.iter(function(line) { + var sps = line.markedSpans; + if (sps) for (var i = 0; i < sps.length; ++i) + if (sps[i].from != null) markers.push(sps[i].marker); + }); + return markers; + }, + + posFromIndex: function(off) { + var ch, lineNo = this.first; + this.iter(function(line) { + var sz = line.text.length + 1; + if (sz > off) { ch = off; return true; } + off -= sz; + ++lineNo; + }); + return clipPos(this, Pos(lineNo, ch)); + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords); + var index = coords.ch; + if (coords.line < this.first || coords.ch < 0) return 0; + this.iter(this.first, coords.line, function (line) { + index += line.text.length + 1; + }); + return index; + }, + + copy: function(copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), + this.modeOption, this.first, this.lineSep); + doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; + doc.sel = this.sel; + doc.extend = false; + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth; + doc.setHistory(this.getHistory()); + } + return doc; + }, + + linkedDoc: function(options) { + if (!options) options = {}; + var from = this.first, to = this.first + this.size; + if (options.from != null && options.from > from) from = options.from; + if (options.to != null && options.to < to) to = options.to; + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep); + if (options.sharedHist) copy.history = this.history; + (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); + copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; + copySharedMarkers(copy, findSharedMarkers(this)); + return copy; + }, + unlinkDoc: function(other) { + if (other instanceof CodeMirror) other = other.doc; + if (this.linked) for (var i = 0; i < this.linked.length; ++i) { + var link = this.linked[i]; + if (link.doc != other) continue; + this.linked.splice(i, 1); + other.unlinkDoc(this); + detachSharedMarkers(findSharedMarkers(this)); + break; + } + // If the histories were shared, split them again + if (other.history == this.history) { + var splitIds = [other.id]; + linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); + other.history = new History(null); + other.history.done = copyHistoryArray(this.history.done, splitIds); + other.history.undone = copyHistoryArray(this.history.undone, splitIds); + } + }, + iterLinkedDocs: function(f) {linkedDocs(this, f);}, + + getMode: function() {return this.mode;}, + getEditor: function() {return this.cm;}, + + splitLines: function(str) { + if (this.lineSep) return str.split(this.lineSep); + return splitLinesAuto(str); + }, + lineSeparator: function() { return this.lineSep || "\n"; } + }); + + // Public alias. + Doc.prototype.eachLine = Doc.prototype.iter; + + // Set up methods on CodeMirror's prototype to redirect to the editor's document. + var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); + for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) + CodeMirror.prototype[prop] = (function(method) { + return function() {return method.apply(this.doc, arguments);}; + })(Doc.prototype[prop]); + + eventMixin(Doc); + + // Call f for all linked documents. + function linkedDocs(doc, f, sharedHistOnly) { + function propagate(doc, skip, sharedHist) { + if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { + var rel = doc.linked[i]; + if (rel.doc == skip) continue; + var shared = sharedHist && rel.sharedHist; + if (sharedHistOnly && !shared) continue; + f(rel.doc, shared); + propagate(rel.doc, doc, shared); + } + } + propagate(doc, null, true); + } + + // Attach a document to an editor. + function attachDoc(cm, doc) { + if (doc.cm) throw new Error("This document is already in use."); + cm.doc = doc; + doc.cm = cm; + estimateLineHeights(cm); + loadMode(cm); + if (!cm.options.lineWrapping) findMaxLine(cm); + cm.options.mode = doc.modeOption; + regChange(cm); + } + + // LINE UTILITIES + + // Find the line object corresponding to the given line number. + function getLine(doc, n) { + n -= doc.first; + if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document."); + for (var chunk = doc; !chunk.lines;) { + for (var i = 0;; ++i) { + var child = chunk.children[i], sz = child.chunkSize(); + if (n < sz) { chunk = child; break; } + n -= sz; + } + } + return chunk.lines[n]; + } + + // Get the part of a document between two positions, as an array of + // strings. + function getBetween(doc, start, end) { + var out = [], n = start.line; + doc.iter(start.line, end.line + 1, function(line) { + var text = line.text; + if (n == end.line) text = text.slice(0, end.ch); + if (n == start.line) text = text.slice(start.ch); + out.push(text); + ++n; + }); + return out; + } + // Get the lines between from and to, as array of strings. + function getLines(doc, from, to) { + var out = []; + doc.iter(from, to, function(line) { out.push(line.text); }); + return out; + } + + // Update the height of a line, propagating the height change + // upwards to parent nodes. + function updateLineHeight(line, height) { + var diff = height - line.height; + if (diff) for (var n = line; n; n = n.parent) n.height += diff; + } + + // Given a line object, find its line number by walking up through + // its parent links. + function lineNo(line) { + if (line.parent == null) return null; + var cur = line.parent, no = indexOf(cur.lines, line); + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i = 0;; ++i) { + if (chunk.children[i] == cur) break; + no += chunk.children[i].chunkSize(); + } + } + return no + cur.first; + } + + // Find the line at the given vertical position, using the height + // information in the document tree. + function lineAtHeight(chunk, h) { + var n = chunk.first; + outer: do { + for (var i = 0; i < chunk.children.length; ++i) { + var child = chunk.children[i], ch = child.height; + if (h < ch) { chunk = child; continue outer; } + h -= ch; + n += child.chunkSize(); + } + return n; + } while (!chunk.lines); + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i], lh = line.height; + if (h < lh) break; + h -= lh; + } + return n + i; + } + + + // Find the height above the given line. + function heightAtLine(lineObj) { + lineObj = visualLine(lineObj); + + var h = 0, chunk = lineObj.parent; + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i]; + if (line == lineObj) break; + else h += line.height; + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i = 0; i < p.children.length; ++i) { + var cur = p.children[i]; + if (cur == chunk) break; + else h += cur.height; + } + } + return h; + } + + // Get the bidi ordering for the given line (and cache it). Returns + // false for lines that are fully left-to-right, and an array of + // BidiSpan objects otherwise. + function getOrder(line) { + var order = line.order; + if (order == null) order = line.order = bidiOrdering(line.text); + return order; + } + + // HISTORY + + function History(startGen) { + // Arrays of change events and selections. Doing something adds an + // event to done and clears undo. Undoing moves events from done + // to undone, redoing moves them in the other direction. + this.done = []; this.undone = []; + this.undoDepth = Infinity; + // Used to track when changes can be merged into a single undo + // event + this.lastModTime = this.lastSelTime = 0; + this.lastOp = this.lastSelOp = null; + this.lastOrigin = this.lastSelOrigin = null; + // Used by the isClean() method + this.generation = this.maxGeneration = startGen || 1; + } + + // Create a history change event from an updateDoc-style change + // object. + function historyChangeFromChange(doc, change) { + var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); + linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); + return histChange; + } + + // Pop all selection events off the end of a history array. Stop at + // a change event. + function clearSelectionEvents(array) { + while (array.length) { + var last = lst(array); + if (last.ranges) array.pop(); + else break; + } + } + + // Find the top change event in the history. Pop off selection + // events that are in the way. + function lastChangeEvent(hist, force) { + if (force) { + clearSelectionEvents(hist.done); + return lst(hist.done); + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done); + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop(); + return lst(hist.done); + } + } + + // Register a change in the history. Merges changes that are within + // a single operation, ore are close together with an origin that + // allows merging (starting with "+") into a single event. + function addChangeToHistory(doc, change, selAfter, opId) { + var hist = doc.history; + hist.undone.length = 0; + var time = +new Date, cur; + + if ((hist.lastOp == opId || + hist.lastOrigin == change.origin && change.origin && + ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || + change.origin.charAt(0) == "*")) && + (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + // Merge this change into the last event + var last = lst(cur.changes); + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + // Optimized case for simple insertion -- don't want to add + // new changesets for every character typed + last.to = changeEnd(change); + } else { + // Add new sub-event + cur.changes.push(historyChangeFromChange(doc, change)); + } + } else { + // Can not be merged, start a new event. + var before = lst(hist.done); + if (!before || !before.ranges) + pushSelectionToHistory(doc.sel, hist.done); + cur = {changes: [historyChangeFromChange(doc, change)], + generation: hist.generation}; + hist.done.push(cur); + while (hist.done.length > hist.undoDepth) { + hist.done.shift(); + if (!hist.done[0].ranges) hist.done.shift(); + } + } + hist.done.push(selAfter); + hist.generation = ++hist.maxGeneration; + hist.lastModTime = hist.lastSelTime = time; + hist.lastOp = hist.lastSelOp = opId; + hist.lastOrigin = hist.lastSelOrigin = change.origin; + + if (!last) signal(doc, "historyAdded"); + } + + function selectionEventCanBeMerged(doc, origin, prev, sel) { + var ch = origin.charAt(0); + return ch == "*" || + ch == "+" && + prev.ranges.length == sel.ranges.length && + prev.somethingSelected() == sel.somethingSelected() && + new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); + } + + // Called whenever the selection changes, sets the new selection as + // the pending selection in the history, and pushes the old pending + // selection into the 'done' array when it was significantly + // different (in number of selected ranges, emptiness, or time). + function addSelectionToHistory(doc, sel, opId, options) { + var hist = doc.history, origin = options && options.origin; + + // A new event is started when the previous origin does not match + // the current, or the origins don't allow matching. Origins + // starting with * are always merged, those starting with + are + // merged when similar and close together in time. + if (opId == hist.lastSelOp || + (origin && hist.lastSelOrigin == origin && + (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || + selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) + hist.done[hist.done.length - 1] = sel; + else + pushSelectionToHistory(sel, hist.done); + + hist.lastSelTime = +new Date; + hist.lastSelOrigin = origin; + hist.lastSelOp = opId; + if (options && options.clearRedo !== false) + clearSelectionEvents(hist.undone); + } + + function pushSelectionToHistory(sel, dest) { + var top = lst(dest); + if (!(top && top.ranges && top.equals(sel))) + dest.push(sel); + } + + // Used to store marked span information in the history. + function attachLocalSpans(doc, change, from, to) { + var existing = change["spans_" + doc.id], n = 0; + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { + if (line.markedSpans) + (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; + ++n; + }); + } + + // When un/re-doing restores text containing marked spans, those + // that have been explicitly cleared should not be restored. + function removeClearedSpans(spans) { + if (!spans) return null; + for (var i = 0, out; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } + else if (out) out.push(spans[i]); + } + return !out ? spans : out.length ? out : null; + } + + // Retrieve and filter the old marked spans stored in a change event. + function getOldSpans(doc, change) { + var found = change["spans_" + doc.id]; + if (!found) return null; + for (var i = 0, nw = []; i < change.text.length; ++i) + nw.push(removeClearedSpans(found[i])); + return nw; + } + + // Used both to provide a JSON-safe object in .getHistory, and, when + // detaching a document, to split the history in two + function copyHistoryArray(events, newGroup, instantiateSel) { + for (var i = 0, copy = []; i < events.length; ++i) { + var event = events[i]; + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); + continue; + } + var changes = event.changes, newChanges = []; + copy.push({changes: newChanges}); + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m; + newChanges.push({from: change.from, to: change.to, text: change.text}); + if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop] = change[prop]; + delete change[prop]; + } + } + } + } + return copy; + } + + // Rebasing/resetting history to deal with externally-sourced changes + + function rebaseHistSelSingle(pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff; + } else if (from < pos.line) { + pos.line = from; + pos.ch = 0; + } + } + + // Tries to rebase an array of history events given a change in the + // document. If the change touches the same lines as the event, the + // event, and everything 'behind' it, is discarded. If the change is + // before the event, the event's positions are updated. Uses a + // copy-on-write scheme for the positions, to avoid having to + // reallocate them all on every rebase, but also avoid problems with + // shared position objects being unsafely updated. + function rebaseHistArray(array, from, to, diff) { + for (var i = 0; i < array.length; ++i) { + var sub = array[i], ok = true; + if (sub.ranges) { + if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); + } + continue; + } + for (var j = 0; j < sub.changes.length; ++j) { + var cur = sub.changes[j]; + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch); + cur.to = Pos(cur.to.line + diff, cur.to.ch); + } else if (from <= cur.to.line) { + ok = false; + break; + } + } + if (!ok) { + array.splice(0, i + 1); + i = 0; + } + } + } + + function rebaseHist(hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; + rebaseHistArray(hist.done, from, to, diff); + rebaseHistArray(hist.undone, from, to, diff); + } + + // EVENT UTILITIES + + // Due to the fact that we still support jurassic IE versions, some + // compatibility wrappers are needed. + + var e_preventDefault = CodeMirror.e_preventDefault = function(e) { + if (e.preventDefault) e.preventDefault(); + else e.returnValue = false; + }; + var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) { + if (e.stopPropagation) e.stopPropagation(); + else e.cancelBubble = true; + }; + function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; + } + var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);}; + + function e_target(e) {return e.target || e.srcElement;} + function e_button(e) { + var b = e.which; + if (b == null) { + if (e.button & 1) b = 1; + else if (e.button & 2) b = 3; + else if (e.button & 4) b = 2; + } + if (mac && e.ctrlKey && b == 1) b = 3; + return b; + } + + // EVENT HANDLING + + // Lightweight event framework. on/off also work on DOM nodes, + // registering native DOM handlers. + + var on = CodeMirror.on = function(emitter, type, f) { + if (emitter.addEventListener) + emitter.addEventListener(type, f, false); + else if (emitter.attachEvent) + emitter.attachEvent("on" + type, f); + else { + var map = emitter._handlers || (emitter._handlers = {}); + var arr = map[type] || (map[type] = []); + arr.push(f); + } + }; + + var off = CodeMirror.off = function(emitter, type, f) { + if (emitter.removeEventListener) + emitter.removeEventListener(type, f, false); + else if (emitter.detachEvent) + emitter.detachEvent("on" + type, f); + else { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + for (var i = 0; i < arr.length; ++i) + if (arr[i] == f) { arr.splice(i, 1); break; } + } + }; + + var signal = CodeMirror.signal = function(emitter, type /*, values...*/) { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + var args = Array.prototype.slice.call(arguments, 2); + for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); + }; + + var orphanDelayedCallbacks = null; + + // Often, we want to signal events at a point where we are in the + // middle of some work, but don't want the handler to start calling + // other methods on the editor, which might be in an inconsistent + // state or simply not expect any other events to happen. + // signalLater looks whether there are any handlers, and schedules + // them to be executed when the last operation ends, or, if no + // operation is active, when a timeout fires. + function signalLater(emitter, type /*, values...*/) { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + var args = Array.prototype.slice.call(arguments, 2), list; + if (operationGroup) { + list = operationGroup.delayedCallbacks; + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks; + } else { + list = orphanDelayedCallbacks = []; + setTimeout(fireOrphanDelayed, 0); + } + function bnd(f) {return function(){f.apply(null, args);};}; + for (var i = 0; i < arr.length; ++i) + list.push(bnd(arr[i])); + } + + function fireOrphanDelayed() { + var delayed = orphanDelayedCallbacks; + orphanDelayedCallbacks = null; + for (var i = 0; i < delayed.length; ++i) delayed[i](); + } + + // The DOM events that CodeMirror handles can be overridden by + // registering a (non-DOM) handler on the editor for the event name, + // and preventDefault-ing the event in that handler. + function signalDOMEvent(cm, e, override) { + if (typeof e == "string") + e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; + signal(cm, override || e.type, cm, e); + return e_defaultPrevented(e) || e.codemirrorIgnore; + } + + function signalCursorActivity(cm) { + var arr = cm._handlers && cm._handlers.cursorActivity; + if (!arr) return; + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); + for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1) + set.push(arr[i]); + } + + function hasHandler(emitter, type) { + var arr = emitter._handlers && emitter._handlers[type]; + return arr && arr.length > 0; + } + + // Add on and off methods to a constructor's prototype, to make + // registering events on such objects more convenient. + function eventMixin(ctor) { + ctor.prototype.on = function(type, f) {on(this, type, f);}; + ctor.prototype.off = function(type, f) {off(this, type, f);}; + } + + // MISC UTILITIES + + // Number of pixels added to scroller and sizer to hide scrollbar + var scrollerGap = 30; + + // Returned or thrown by various protocols to signal 'I'm not + // handling this'. + var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; + + // Reused option objects for setSelection & friends + var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; + + function Delayed() {this.id = null;} + Delayed.prototype.set = function(ms, f) { + clearTimeout(this.id); + this.id = setTimeout(f, ms); + }; + + // Counts the column offset in a string, taking tabs into account. + // Used mostly to find indentation. + var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) end = string.length; + } + for (var i = startIndex || 0, n = startValue || 0;;) { + var nextTab = string.indexOf("\t", i); + if (nextTab < 0 || nextTab >= end) + return n + (end - i); + n += nextTab - i; + n += tabSize - (n % tabSize); + i = nextTab + 1; + } + }; + + // The inverse of countColumn -- find the offset that corresponds to + // a particular column. + function findColumn(string, goal, tabSize) { + for (var pos = 0, col = 0;;) { + var nextTab = string.indexOf("\t", pos); + if (nextTab == -1) nextTab = string.length; + var skipped = nextTab - pos; + if (nextTab == string.length || col + skipped >= goal) + return pos + Math.min(skipped, goal - col); + col += nextTab - pos; + col += tabSize - (col % tabSize); + pos = nextTab + 1; + if (col >= goal) return pos; + } + } + + var spaceStrs = [""]; + function spaceStr(n) { + while (spaceStrs.length <= n) + spaceStrs.push(lst(spaceStrs) + " "); + return spaceStrs[n]; + } + + function lst(arr) { return arr[arr.length-1]; } + + var selectInput = function(node) { node.select(); }; + if (ios) // Mobile Safari apparently has a bug where select() is broken. + selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; + else if (ie) // Suppress mysterious IE10 errors + selectInput = function(node) { try { node.select(); } catch(_e) {} }; + + function indexOf(array, elt) { + for (var i = 0; i < array.length; ++i) + if (array[i] == elt) return i; + return -1; + } + function map(array, f) { + var out = []; + for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); + return out; + } + + function nothing() {} + + function createObj(base, props) { + var inst; + if (Object.create) { + inst = Object.create(base); + } else { + nothing.prototype = base; + inst = new nothing(); + } + if (props) copyObj(props, inst); + return inst; + }; + + function copyObj(obj, target, overwrite) { + if (!target) target = {}; + for (var prop in obj) + if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) + target[prop] = obj[prop]; + return target; + } + + function bind(f) { + var args = Array.prototype.slice.call(arguments, 1); + return function(){return f.apply(null, args);}; + } + + var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + var isWordCharBasic = CodeMirror.isWordChar = function(ch) { + return /\w/.test(ch) || ch > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); + }; + function isWordChar(ch, helper) { + if (!helper) return isWordCharBasic(ch); + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true; + return helper.test(ch); + } + + function isEmpty(obj) { + for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; + return true; + } + + // Extending unicode characters. A series of a non-extending char + + // any number of extending chars is treated as a single unit as far + // as editing and measuring is concerned. This is not fully correct, + // since some scripts/fonts/browsers also treat other configurations + // of code points as a group. + var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; + function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } + + // DOM UTILITIES + + function elt(tag, content, className, style) { + var e = document.createElement(tag); + if (className) e.className = className; + if (style) e.style.cssText = style; + if (typeof content == "string") e.appendChild(document.createTextNode(content)); + else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); + return e; + } + + var range; + if (document.createRange) range = function(node, start, end, endNode) { + var r = document.createRange(); + r.setEnd(endNode || node, end); + r.setStart(node, start); + return r; + }; + else range = function(node, start, end) { + var r = document.body.createTextRange(); + try { r.moveToElementText(node.parentNode); } + catch(e) { return r; } + r.collapse(true); + r.moveEnd("character", end); + r.moveStart("character", start); + return r; + }; + + function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --count) + e.removeChild(e.firstChild); + return e; + } + + function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e); + } + + var contains = CodeMirror.contains = function(parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + child = child.parentNode; + if (parent.contains) + return parent.contains(child); + do { + if (child.nodeType == 11) child = child.host; + if (child == parent) return true; + } while (child = child.parentNode); + }; + + function activeElt() { + var activeElement = document.activeElement; + while (activeElement && activeElement.root && activeElement.root.activeElement) + activeElement = activeElement.root.activeElement; + return activeElement; + } + // Older versions of IE throws unspecified error when touching + // document.activeElement in some cases (during loading, in iframe) + if (ie && ie_version < 11) activeElt = function() { + try { return document.activeElement; } + catch(e) { return document.body; } + }; + + function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); } + var rmClass = CodeMirror.rmClass = function(node, cls) { + var current = node.className; + var match = classTest(cls).exec(current); + if (match) { + var after = current.slice(match.index + match[0].length); + node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); + } + }; + var addClass = CodeMirror.addClass = function(node, cls) { + var current = node.className; + if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls; + }; + function joinClasses(a, b) { + var as = a.split(" "); + for (var i = 0; i < as.length; i++) + if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i]; + return b; + } + + // WINDOW-WIDE EVENTS + + // These must be handled carefully, because naively registering a + // handler for each editor will cause the editors to never be + // garbage collected. + + function forEachCodeMirror(f) { + if (!document.body.getElementsByClassName) return; + var byClass = document.body.getElementsByClassName("CodeMirror"); + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror; + if (cm) f(cm); + } + } + + var globalsRegistered = false; + function ensureGlobalHandlers() { + if (globalsRegistered) return; + registerGlobalHandlers(); + globalsRegistered = true; + } + function registerGlobalHandlers() { + // When the window resizes, we need to refresh active editors. + var resizeTimer; + on(window, "resize", function() { + if (resizeTimer == null) resizeTimer = setTimeout(function() { + resizeTimer = null; + forEachCodeMirror(onResize); + }, 100); + }); + // When the window loses focus, we want to show the editor as blurred + on(window, "blur", function() { + forEachCodeMirror(onBlur); + }); + } + + // FEATURE DETECTION + + // Detect drag-and-drop + var dragAndDrop = function() { + // There is *some* kind of drag-and-drop support in IE6-8, but I + // couldn't get it to work yet. + if (ie && ie_version < 9) return false; + var div = elt('div'); + return "draggable" in div || "dragDrop" in div; + }(); + + var zwspSupported; + function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "\u200b"); + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); + if (measure.firstChild.offsetHeight != 0) + zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); + } + var node = zwspSupported ? elt("span", "\u200b") : + elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); + node.setAttribute("cm-text", ""); + return node; + } + + // Feature-detect IE's crummy client rect reporting for bidi text + var badBidiRects; + function hasBadBidiRects(measure) { + if (badBidiRects != null) return badBidiRects; + var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); + var r0 = range(txt, 0, 1).getBoundingClientRect(); + if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780) + var r1 = range(txt, 1, 2).getBoundingClientRect(); + return badBidiRects = (r1.right - r0.right < 3); + } + + // See if "".split is the broken IE version, if so, provide an + // alternative way to split lines. + var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { + var pos = 0, result = [], l = string.length; + while (pos <= l) { + var nl = string.indexOf("\n", pos); + if (nl == -1) nl = string.length; + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); + var rt = line.indexOf("\r"); + if (rt != -1) { + result.push(line.slice(0, rt)); + pos += rt + 1; + } else { + result.push(line); + pos = nl + 1; + } + } + return result; + } : function(string){return string.split(/\r\n?|\n/);}; + + var hasSelection = window.getSelection ? function(te) { + try { return te.selectionStart != te.selectionEnd; } + catch(e) { return false; } + } : function(te) { + try {var range = te.ownerDocument.selection.createRange();} + catch(e) {} + if (!range || range.parentElement() != te) return false; + return range.compareEndPoints("StartToEnd", range) != 0; + }; + + var hasCopyEvent = (function() { + var e = elt("div"); + if ("oncopy" in e) return true; + e.setAttribute("oncopy", "return;"); + return typeof e.oncopy == "function"; + })(); + + var badZoomedRects = null; + function hasBadZoomedRects(measure) { + if (badZoomedRects != null) return badZoomedRects; + var node = removeChildrenAndAdd(measure, elt("span", "x")); + var normal = node.getBoundingClientRect(); + var fromRange = range(node, 0, 1).getBoundingClientRect(); + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; + } + + // KEY NAMES + + var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", + 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", + 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", + 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete", + 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", + 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"}; + CodeMirror.keyNames = keyNames; + (function() { + // Number keys + for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); + // Alphabetic keys + for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); + // Function keys + for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; + })(); + + // BIDI HELPERS + + function iterateBidiSections(order, from, to, f) { + if (!order) return f(from, to, "ltr"); + var found = false; + for (var i = 0; i < order.length; ++i) { + var part = order[i]; + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); + found = true; + } + } + if (!found) f(from, to, "ltr"); + } + + function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } + function bidiRight(part) { return part.level % 2 ? part.from : part.to; } + + function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } + function lineRight(line) { + var order = getOrder(line); + if (!order) return line.text.length; + return bidiRight(lst(order)); + } + + function lineStart(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLine(line); + if (visual != line) lineN = lineNo(visual); + var order = getOrder(visual); + var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); + return Pos(lineN, ch); + } + function lineEnd(cm, lineN) { + var merged, line = getLine(cm.doc, lineN); + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + lineN = null; + } + var order = getOrder(line); + var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); + return Pos(lineN == null ? lineNo(line) : lineN, ch); + } + function lineStartSmart(cm, pos) { + var start = lineStart(cm, pos.line); + var line = getLine(cm.doc, start.line); + var order = getOrder(line); + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(0, line.text.search(/\S/)); + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; + return Pos(start.line, inWS ? 0 : firstNonWS); + } + return start; + } + + function compareBidiLevel(order, a, b) { + var linedir = order[0].level; + if (a == linedir) return true; + if (b == linedir) return false; + return a < b; + } + var bidiOther; + function getBidiPartAt(order, pos) { + bidiOther = null; + for (var i = 0, found; i < order.length; ++i) { + var cur = order[i]; + if (cur.from < pos && cur.to > pos) return i; + if ((cur.from == pos || cur.to == pos)) { + if (found == null) { + found = i; + } else if (compareBidiLevel(order, cur.level, order[found].level)) { + if (cur.from != cur.to) bidiOther = found; + return i; + } else { + if (cur.from != cur.to) bidiOther = i; + return found; + } + } + } + return found; + } + + function moveInLine(line, pos, dir, byUnit) { + if (!byUnit) return pos + dir; + do pos += dir; + while (pos > 0 && isExtendingChar(line.text.charAt(pos))); + return pos; + } + + // This is needed in order to move 'visually' through bi-directional + // text -- i.e., pressing left should make the cursor go left, even + // when in RTL text. The tricky part is the 'jumps', where RTL and + // LTR text touch each other. This often requires the cursor offset + // to move more than one unit, in order to visually move one unit. + function moveVisually(line, start, dir, byUnit) { + var bidi = getOrder(line); + if (!bidi) return moveLogically(line, start, dir, byUnit); + var pos = getBidiPartAt(bidi, start), part = bidi[pos]; + var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); + + for (;;) { + if (target > part.from && target < part.to) return target; + if (target == part.from || target == part.to) { + if (getBidiPartAt(bidi, target) == pos) return target; + part = bidi[pos += dir]; + return (dir > 0) == part.level % 2 ? part.to : part.from; + } else { + part = bidi[pos += dir]; + if (!part) return null; + if ((dir > 0) == part.level % 2) + target = moveInLine(line, part.to, -1, byUnit); + else + target = moveInLine(line, part.from, 1, byUnit); + } + } + } + + function moveLogically(line, start, dir, byUnit) { + var target = start + dir; + if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; + return target < 0 || target > line.text.length ? null : target; + } + + // Bidirectional ordering algorithm + // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm + // that this (partially) implements. + + // One-char codes used for character types: + // L (L): Left-to-Right + // R (R): Right-to-Left + // r (AL): Right-to-Left Arabic + // 1 (EN): European Number + // + (ES): European Number Separator + // % (ET): European Number Terminator + // n (AN): Arabic Number + // , (CS): Common Number Separator + // m (NSM): Non-Spacing Mark + // b (BN): Boundary Neutral + // s (B): Paragraph Separator + // t (S): Segment Separator + // w (WS): Whitespace + // N (ON): Other Neutrals + + // Returns null if characters are ordered as they appear + // (left-to-right), or an array of sections ({from, to, level} + // objects) in the order in which they occur visually. + var bidiOrdering = (function() { + // Character types for codepoints 0 to 0xff + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; + // Character types for codepoints 0x600 to 0x6ff + var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; + function charType(code) { + if (code <= 0xf7) return lowTypes.charAt(code); + else if (0x590 <= code && code <= 0x5f4) return "R"; + else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); + else if (0x6ee <= code && code <= 0x8ac) return "r"; + else if (0x2000 <= code && code <= 0x200b) return "w"; + else if (code == 0x200c) return "b"; + else return "L"; + } + + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; + // Browsers seem to always treat the boundaries of block elements as being L. + var outerType = "L"; + + function BidiSpan(level, from, to) { + this.level = level; + this.from = from; this.to = to; + } + + return function(str) { + if (!bidiRE.test(str)) return false; + var len = str.length, types = []; + for (var i = 0, type; i < len; ++i) + types.push(type = charType(str.charCodeAt(i))); + + // W1. Examine each non-spacing mark (NSM) in the level run, and + // change the type of the NSM to the type of the previous + // character. If the NSM is at the start of the level run, it will + // get the type of sor. + for (var i = 0, prev = outerType; i < len; ++i) { + var type = types[i]; + if (type == "m") types[i] = prev; + else prev = type; + } + + // W2. Search backwards from each instance of a European number + // until the first strong type (R, L, AL, or sor) is found. If an + // AL is found, change the type of the European number to Arabic + // number. + // W3. Change all ALs to R. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (type == "1" && cur == "r") types[i] = "n"; + else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } + } + + // W4. A single European separator between two European numbers + // changes to a European number. A single common separator between + // two numbers of the same type changes to that type. + for (var i = 1, prev = types[0]; i < len - 1; ++i) { + var type = types[i]; + if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; + else if (type == "," && prev == types[i+1] && + (prev == "1" || prev == "n")) types[i] = prev; + prev = type; + } + + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + for (var i = 0; i < len; ++i) { + var type = types[i]; + if (type == ",") types[i] = "N"; + else if (type == "%") { + for (var end = i + 1; end < len && types[end] == "%"; ++end) {} + var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // W7. Search backwards from each instance of a European number + // until the first strong type (R, L, or sor) is found. If an L is + // found, then change the type of the European number to L. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (cur == "L" && type == "1") types[i] = "L"; + else if (isStrong.test(type)) cur = type; + } + + // N1. A sequence of neutrals takes the direction of the + // surrounding strong text if the text on both sides has the same + // direction. European and Arabic numbers act as if they were R in + // terms of their influence on neutrals. Start-of-level-run (sor) + // and end-of-level-run (eor) are used at level run boundaries. + // N2. Any remaining neutrals take the embedding direction. + for (var i = 0; i < len; ++i) { + if (isNeutral.test(types[i])) { + for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} + var before = (i ? types[i-1] : outerType) == "L"; + var after = (end < len ? types[end] : outerType) == "L"; + var replace = before || after ? "L" : "R"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + var order = [], m; + for (var i = 0; i < len;) { + if (countsAsLeft.test(types[i])) { + var start = i; + for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} + order.push(new BidiSpan(0, start, i)); + } else { + var pos = i, at = order.length; + for (++i; i < len && types[i] != "L"; ++i) {} + for (var j = pos; j < i;) { + if (countsAsNum.test(types[j])) { + if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); + var nstart = j; + for (++j; j < i && countsAsNum.test(types[j]); ++j) {} + order.splice(at, 0, new BidiSpan(2, nstart, j)); + pos = j; + } else ++j; + } + if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); + } + } + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length; + order.unshift(new BidiSpan(0, 0, m[0].length)); + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length; + order.push(new BidiSpan(0, len - m[0].length, len)); + } + if (order[0].level == 2) + order.unshift(new BidiSpan(1, order[0].to, order[0].to)); + if (order[0].level != lst(order).level) + order.push(new BidiSpan(order[0].level, len, len)); + + return order; + }; + })(); + + // THE END + + CodeMirror.version = "5.6.0"; + + return CodeMirror; +}); diff --git a/public/assets/codemirror/codemirror_python_ruby_c.js b/public/assets/codemirror/codemirror_python_ruby_c.js new file mode 100644 index 000000000..cfc0eb6ee --- /dev/null +++ b/public/assets/codemirror/codemirror_python_ruby_c.js @@ -0,0 +1,18 @@ +/* CodeMirror - Minified & Bundled + Generated on 2015/9/19 with http://codemirror.net/doc/compress.html + Version: HEAD + + CodeMirror Library: + - codemirror.js + Modes: + - clike.js + - python.js + - ruby.js + */ + +!function(a){if("object"==typeof exports&&"object"==typeof module)module.exports=a();else{if("function"==typeof define&&define.amd)return define([],a);this.CodeMirror=a()}}(function(){"use strict";function v(a,b){if(!(this instanceof v))return new v(a,b);this.options=b=b?hg(b):{},hg(Ad,b,!1),I(b);var c=b.value;"string"==typeof c&&(c=new af(c,b.mode,null,b.lineSeparator)),this.doc=c;var g=new v.inputStyles[b.inputStyle](this),h=this.display=new w(a,c,g);h.wrapper.CodeMirror=this,E(this),C(this),b.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),b.autofocus&&!n&&h.input.focus(),M(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,selectingText:!1,draggingText:!1,highlight:new Yf,keySeq:null,specialChars:null};var i=this;d&&11>e&&setTimeout(function(){i.display.input.reset(!0)},20),pc(this),Bg(),Vb(this),this.curOp.forceUpdate=!0,ef(this,c),b.autofocus&&!n||i.hasFocus()?setTimeout(ig(Zc,this),20):$c(this);for(var j in Bd)Bd.hasOwnProperty(j)&&Bd[j](this,b[j],Dd);R(this),b.finishInit&&b.finishInit(this);for(var k=0;ke&&(h.gutters.style.zIndex=-1,h.scroller.style.paddingRight=0),f||a&&n||(h.scroller.draggable=!0),b&&(b.appendChild?b.appendChild(h.wrapper):b(h.wrapper)),h.viewFrom=h.viewTo=c.first,h.reportedViewFrom=h.reportedViewTo=c.first,h.view=[],h.renderedView=null,h.externalMeasured=null,h.viewOffset=0,h.lastWrapHeight=h.lastWrapWidth=0,h.updateLineNumbers=null,h.nativeBarWidth=h.barHeight=h.barWidth=0,h.scrollbarsClipped=!1,h.lineNumWidth=h.lineNumInnerWidth=h.lineNumChars=null,h.alignWidgets=!1,h.cachedCharWidth=h.cachedTextHeight=h.cachedPaddingH=null,h.maxLine=null,h.maxLineLength=0,h.maxLineChanged=!1,h.wheelDX=h.wheelDY=h.wheelStartX=h.wheelStartY=null,h.shift=!1,h.selForContextMenu=null,h.activeTouch=null,g.init(h)}function x(a){a.doc.mode=v.getMode(a.options,a.doc.modeOption),y(a)}function y(a){a.doc.iter(function(a){a.stateAfter&&(a.stateAfter=null),a.styles&&(a.styles=null)}),a.doc.frontier=a.doc.first,ib(a,100),a.state.modeGen++,a.curOp&&ic(a)}function z(a){a.options.lineWrapping?(xg(a.display.wrapper,"CodeMirror-wrap"),a.display.sizer.style.minWidth="",a.display.sizerWidth=null):(wg(a.display.wrapper,"CodeMirror-wrap"),H(a)),B(a),ic(a),Fb(a),setTimeout(function(){N(a)},100)}function A(a){var b=Rb(a.display),c=a.options.lineWrapping,d=c&&Math.max(5,a.display.scroller.clientWidth/Sb(a.display)-3);return function(e){if(we(a.doc,e))return 0;var f=0;if(e.widgets)for(var g=0;gb.maxLineLength&&(b.maxLineLength=c,b.maxLine=a)})}function I(a){var b=dg(a.gutters,"CodeMirror-linenumbers");-1==b&&a.lineNumbers?a.gutters=a.gutters.concat(["CodeMirror-linenumbers"]):b>-1&&!a.lineNumbers&&(a.gutters=a.gutters.slice(0),a.gutters.splice(b,1))}function J(a){var b=a.display,c=b.gutters.offsetWidth,d=Math.round(a.doc.height+nb(a.display));return{clientHeight:b.scroller.clientHeight,viewHeight:b.wrapper.clientHeight,scrollWidth:b.scroller.scrollWidth,clientWidth:b.scroller.clientWidth,viewWidth:b.wrapper.clientWidth,barLeft:a.options.fixedGutter?c:0,docHeight:d,scrollHeight:d+pb(a)+b.barHeight,nativeBarWidth:b.nativeBarWidth,gutterWidth:c}}function K(a,b,c){this.cm=c;var f=this.vert=pg("div",[pg("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),g=this.horiz=pg("div",[pg("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");a(f),a(g),Jf(f,"scroll",function(){f.clientHeight&&b(f.scrollTop,"vertical")}),Jf(g,"scroll",function(){g.clientWidth&&b(g.scrollLeft,"horizontal")}),this.checkedOverlay=!1,d&&8>e&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")}function L(){}function M(a){a.display.scrollbars&&(a.display.scrollbars.clear(),a.display.scrollbars.addClass&&wg(a.display.wrapper,a.display.scrollbars.addClass)),a.display.scrollbars=new v.scrollbarModel[a.options.scrollbarStyle](function(b){a.display.wrapper.insertBefore(b,a.display.scrollbarFiller),Jf(b,"mousedown",function(){a.state.focused&&setTimeout(function(){a.display.input.focus()},0)}),b.setAttribute("cm-not-content","true")},function(b,c){"horizontal"==c?Ic(a,b):Hc(a,b)},a),a.display.scrollbars.addClass&&xg(a.display.wrapper,a.display.scrollbars.addClass)}function N(a,b){b||(b=J(a));var c=a.display.barWidth,d=a.display.barHeight;O(a,b);for(var e=0;4>e&&c!=a.display.barWidth||d!=a.display.barHeight;e++)c!=a.display.barWidth&&a.options.lineWrapping&&$(a),O(a,J(a)),c=a.display.barWidth,d=a.display.barHeight}function O(a,b){var c=a.display,d=c.scrollbars.update(b);c.sizer.style.paddingRight=(c.barWidth=d.right)+"px",c.sizer.style.paddingBottom=(c.barHeight=d.bottom)+"px",d.right&&d.bottom?(c.scrollbarFiller.style.display="block",c.scrollbarFiller.style.height=d.bottom+"px",c.scrollbarFiller.style.width=d.right+"px"):c.scrollbarFiller.style.display="",d.bottom&&a.options.coverGutterNextToScrollbar&&a.options.fixedGutter?(c.gutterFiller.style.display="block",c.gutterFiller.style.height=d.bottom+"px",c.gutterFiller.style.width=b.gutterWidth+"px"):c.gutterFiller.style.display=""}function P(a,b,c){var d=c&&null!=c.top?Math.max(0,c.top):a.scroller.scrollTop;d=Math.floor(d-mb(a));var e=c&&null!=c.bottom?c.bottom:d+a.wrapper.clientHeight,f=lf(b,d),g=lf(b,e);if(c&&c.ensure){var h=c.ensure.from.line,i=c.ensure.to.line;f>h?(f=h,g=lf(b,mf(ff(b,h))+a.wrapper.clientHeight)):Math.min(i,b.lastLine())>=g&&(f=lf(b,mf(ff(b,i))-a.wrapper.clientHeight),g=i)}return{from:f,to:Math.max(g,f+1)}}function Q(a){var b=a.display,c=b.view;if(b.alignWidgets||b.gutters.firstChild&&a.options.fixedGutter){for(var d=T(b)-b.scroller.scrollLeft+a.doc.scrollLeft,e=b.gutters.offsetWidth,f=d+"px",g=0;g=c.viewFrom&&b.visible.to<=c.viewTo&&(null==c.updateLineNumbers||c.updateLineNumbers>=c.viewTo)&&c.renderedView==c.view&&0==oc(a))return!1;R(a)&&(kc(a),b.dims=aa(a));var e=d.first+d.size,f=Math.max(b.visible.from-a.options.viewportMargin,d.first),g=Math.min(e,b.visible.to+a.options.viewportMargin);c.viewFromg&&c.viewTo-g<20&&(g=Math.min(e,c.viewTo)),u&&(f=ue(a.doc,f),g=ve(a.doc,g));var h=f!=c.viewFrom||g!=c.viewTo||c.lastWrapHeight!=b.wrapperHeight||c.lastWrapWidth!=b.wrapperWidth;nc(a,f,g),c.viewOffset=mf(ff(a.doc,c.viewFrom)),a.display.mover.style.top=c.viewOffset+"px";var i=oc(a);if(!h&&0==i&&!b.force&&c.renderedView==c.view&&(null==c.updateLineNumbers||c.updateLineNumbers>=c.viewTo))return!1;var j=ug();return i>4&&(c.lineDiv.style.display="none"),ba(a,c.updateLineNumbers,b.dims),i>4&&(c.lineDiv.style.display=""),c.renderedView=c.view,j&&ug()!=j&&j.offsetHeight&&j.focus(),rg(c.cursorDiv),rg(c.selectionDiv),c.gutters.style.height=c.sizer.style.minHeight=0,h&&(c.lastWrapHeight=b.wrapperHeight,c.lastWrapWidth=b.wrapperWidth,ib(a,400)),c.updateLineNumbers=null,!0}function X(a,b){for(var c=b.viewport,d=!0;(d&&a.options.lineWrapping&&b.oldDisplayWidth!=qb(a)||(c&&null!=c.top&&(c={top:Math.min(a.doc.height+nb(a.display)-rb(a),c.top)}),b.visible=P(a.display,a.doc,c),!(b.visible.from>=a.display.viewFrom&&b.visible.to<=a.display.viewTo)))&&W(a,b);d=!1){$(a);var e=J(a);db(a),Z(a,e),N(a,e)}b.signal(a,"update",a),(a.display.viewFrom!=a.display.reportedViewFrom||a.display.viewTo!=a.display.reportedViewTo)&&(b.signal(a,"viewportChange",a,a.display.viewFrom,a.display.viewTo),a.display.reportedViewFrom=a.display.viewFrom,a.display.reportedViewTo=a.display.viewTo)}function Y(a,b){var c=new U(a,b);if(W(a,c)){$(a),X(a,c);var d=J(a);db(a),Z(a,d),N(a,d),c.finish()}}function Z(a,b){a.display.sizer.style.minHeight=b.docHeight+"px";var c=b.docHeight+a.display.barHeight;a.display.heightForcer.style.top=c+"px",a.display.gutters.style.height=Math.max(c+pb(a),b.clientHeight)+"px"}function $(a){for(var b=a.display,c=b.lineDiv.offsetTop,f=0;fe){var i=g.node.offsetTop+g.node.offsetHeight;h=i-c,c=i}else{var j=g.node.getBoundingClientRect();h=j.bottom-j.top}var k=g.line.height-h;if(2>h&&(h=Rb(b)),(k>.001||-.001>k)&&(jf(g.line,h),_(g.line),g.rest))for(var l=0;l=b&&m.lineNumber;m.changes&&(dg(m.changes,"gutter")>-1&&(p=!1),ca(a,m,k,c)),p&&(rg(m.lineNumber),m.lineNumber.appendChild(document.createTextNode(S(a.options,k)))),h=m.node.nextSibling}else{var n=ka(a,m,k,c);g.insertBefore(n,h)}k+=m.size}for(;h;)h=i(h)}function ca(a,b,c,d){for(var e=0;ee&&(a.node.style.zIndex=2)),a.node}function ea(a){var b=a.bgClass?a.bgClass+" "+(a.line.bgClass||""):a.line.bgClass;if(b&&(b+=" CodeMirror-linebackground"),a.background)b?a.background.className=b:(a.background.parentNode.removeChild(a.background),a.background=null);else if(b){var c=da(a);a.background=c.insertBefore(pg("div",null,b),c.firstChild)}}function fa(a,b){var c=a.display.externalMeasured;return c&&c.line==b.line?(a.display.externalMeasured=null,b.measure=c.measure,c.built):Qe(a,b)}function ga(a,b){var c=b.text.className,d=fa(a,b);b.text==b.node&&(b.node=d.pre),b.text.parentNode.replaceChild(d.pre,b.text),b.text=d.pre,d.bgClass!=b.bgClass||d.textClass!=b.textClass?(b.bgClass=d.bgClass,b.textClass=d.textClass,ha(b)):c&&(b.text.className=c)}function ha(a){ea(a),a.line.wrapClass?da(a).className=a.line.wrapClass:a.node!=a.text&&(a.node.className="");var b=a.textClass?a.textClass+" "+(a.line.textClass||""):a.line.textClass;a.text.className=b||""}function ia(a,b,c,d){if(b.gutter&&(b.node.removeChild(b.gutter),b.gutter=null),b.gutterBackground&&(b.node.removeChild(b.gutterBackground),b.gutterBackground=null),b.line.gutterClass){var e=da(b);b.gutterBackground=pg("div",null,"CodeMirror-gutter-background "+b.line.gutterClass,"left: "+(a.options.fixedGutter?d.fixedPos:-d.gutterTotalWidth)+"px; width: "+d.gutterTotalWidth+"px"),e.insertBefore(b.gutterBackground,b.text)}var f=b.line.gutterMarkers;if(a.options.lineNumbers||f){var e=da(b),g=b.gutter=pg("div",null,"CodeMirror-gutter-wrapper","left: "+(a.options.fixedGutter?d.fixedPos:-d.gutterTotalWidth)+"px");if(a.display.input.setUneditable(g),e.insertBefore(g,b.text),b.line.gutterClass&&(g.className+=" "+b.line.gutterClass),!a.options.lineNumbers||f&&f["CodeMirror-linenumbers"]||(b.lineNumber=g.appendChild(pg("div",S(a.options,c),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+d.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+a.display.lineNumInnerWidth+"px"))),f)for(var h=0;h1)if(va&&va.join("\n")==b){if(d.ranges.length%va.length==0){i=[];for(var j=0;j=0;j--){var k=d.ranges[j],l=k.from(),m=k.to();k.empty()&&(c&&c>0?l=oa(l.line,l.ch-c):a.state.overwrite&&!g&&(m=oa(m.line,Math.min(ff(f,m.line).text.length,m.ch+bg(h).length))));var n=a.curOp.updateInput,o={from:l,to:m,text:i?i[j%i.length]:h,origin:e||(g?"paste":a.state.cutIncoming?"cut":"+input")};hd(a.doc,o),Nf(a,"inputRead",a,o)}b&&!g&&ya(a,b),td(a),a.curOp.updateInput=n,a.curOp.typing=!0,a.state.pasteIncoming=a.state.cutIncoming=!1}function xa(a,b){var c=a.clipboardData&&a.clipboardData.getData("text/plain");return c?(a.preventDefault(),ua(b)||b.options.disableInput||cc(b,function(){wa(b,c,0,null,"paste")}),!0):void 0}function ya(a,b){if(a.options.electricChars&&a.options.smartIndent)for(var c=a.doc.sel,d=c.ranges.length-1;d>=0;d--){var e=c.ranges[d];if(!(e.head.ch>100||d&&c.ranges[d-1].head.line==e.head.line)){var f=a.getModeAt(e.head),g=!1;if(f.electricChars){for(var h=0;h-1){g=vd(a,e.head.line,"smart");break}}else f.electricInput&&f.electricInput.test(ff(a.doc,e.head.line).text.slice(0,e.head.ch))&&(g=vd(a,e.head.line,"smart"));g&&Nf(a,"electricInput",a,e.head.line)}}}function za(a){for(var b=[],c=[],d=0;de?i.map:j[e],g=0;ge?a.line:a.rest[e]),l=f[g]+d;return(0>d||h!=b)&&(l=f[g+(d?1:0)]),oa(k,l)}}}var d=a.text.firstChild,e=!1;if(!b||!tg(d,b))return Fa(oa(kf(a.line),0),!0);if(b==d&&(e=!0,b=d.childNodes[c],c=0,!b)){var f=a.rest?bg(a.rest):a.line;return Fa(oa(kf(f),f.text.length),e)}var g=3==b.nodeType?b:null,h=b;for(g||1!=b.childNodes.length||3!=b.firstChild.nodeType||(g=b.firstChild,c&&(c=g.nodeValue.length));h.parentNode!=d;)h=h.parentNode;var i=a.measure,j=i.maps,l=k(g,h,c);if(l)return Fa(l,e);for(var m=h.nextSibling,n=g?g.nodeValue.length-c:0;m;m=m.nextSibling){if(l=k(m,m.firstChild,0))return Fa(oa(l.line,l.ch-n),e);n+=m.textContent.length}for(var o=h.previousSibling,n=c;o;o=o.previousSibling){if(l=k(o,o.firstChild,-1))return Fa(oa(l.line,l.ch+n),e);n+=m.textContent.length}}function Ia(a,b,c,d,e){function i(a){return function(b){return b.id==a}}function j(b){if(1==b.nodeType){var c=b.getAttribute("cm-text");if(null!=c)return""==c&&(c=b.textContent.replace(/\u200b/g,"")),void(f+=c);var l,k=b.getAttribute("cm-marker");if(k){var m=a.findMarks(oa(d,0),oa(e+1,0),i(+k));return void(m.length&&(l=m[0].find())&&(f+=gf(a.doc,l.from,l.to).join(h)))}if("false"==b.getAttribute("contenteditable"))return;for(var n=0;n=0){var g=sa(f.from(),e.from()),h=ra(f.to(),e.to()),i=f.empty()?e.from()==e.head:f.from()==f.head;b>=d&&--b,a.splice(--d,2,new Ka(i?h:g,i?g:h))}}return new Ja(a,b)}function Ma(a,b){return new Ja([new Ka(a,b||a)],0)}function Na(a,b){return Math.max(a.first,Math.min(b,a.first+a.size-1))}function Oa(a,b){if(b.linec?oa(c,ff(a,c).text.length):Pa(b,ff(a,b.line).text.length)}function Pa(a,b){var c=a.ch;return null==c||c>b?oa(a.line,b):0>c?oa(a.line,0):a}function Qa(a,b){return b>=a.first&&b=f.ch:j.to>f.ch))){if(d&&(Lf(k,"beforeCursorEnter"),k.explicitlyCleared)){if(h.markedSpans){--i;continue}break}if(!k.atomic)continue;var l=k.find(0>g?-1:1);if(0==pa(l,f)&&(l.ch+=g,l.ch<0?l=l.line>a.first?Oa(a,oa(l.line-1)):null:l.ch>h.text.length&&(l=l.lineb&&(b=0),b=Math.round(b),d=Math.round(d),f.appendChild(pg("div",null,"CodeMirror-selected","position: absolute; left: "+a+"px; top: "+b+"px; width: "+(null==c?i-a:c)+"px; height: "+(d-b)+"px"))}function k(b,c,d){function m(c,d){return Kb(a,oa(b,c),"div",f,d)}var k,l,f=ff(e,b),g=f.text.length;return Og(nf(f),c||0,null==d?g:d,function(a,b,e){var n,o,p,f=m(a,"left");if(a==b)n=f,o=p=f.left;else{if(n=m(b-1,"right"),"rtl"==e){var q=f;f=n,n=q}o=f.left,p=n.right}null==c&&0==a&&(o=h),n.top-f.top>3&&(j(o,f.top,null,f.bottom),o=h,f.bottoml.bottom||n.bottom==l.bottom&&n.right>l.right)&&(l=n),h+1>o&&(o=h),j(o,n.top,p-o,n.bottom)}),{start:k,end:l}}var d=a.display,e=a.doc,f=document.createDocumentFragment(),g=ob(a.display),h=g.left,i=Math.max(d.sizerWidth,qb(a)-d.sizer.offsetLeft)-g.right,l=b.from(),m=b.to();if(l.line==m.line)k(l.line,l.ch,m.ch);else{var n=ff(e,l.line),o=ff(e,m.line),p=se(n)==se(o),q=k(l.line,l.ch,p?n.text.length+1:null).end,r=k(m.line,p?0:null,m.ch).start;p&&(q.top0?b.blinker=setInterval(function(){b.cursorDiv.style.visibility=(c=!c)?"":"hidden"},a.options.cursorBlinkRate):a.options.cursorBlinkRate<0&&(b.cursorDiv.style.visibility="hidden")}}function ib(a,b){a.doc.mode.startState&&a.doc.frontier=a.display.viewTo)){var c=+new Date+a.options.workTime,d=Jd(b.mode,lb(a,b.frontier)),e=[];b.iter(b.frontier,Math.min(b.first+b.size,a.display.viewTo+500),function(f){if(b.frontier>=a.display.viewFrom){var g=f.styles,h=f.text.length>a.options.maxHighlightLength,i=Ke(a,f,h?Jd(b.mode,d):d,!0);f.styles=i.styles;var j=f.styleClasses,k=i.classes;k?f.styleClasses=k:j&&(f.styleClasses=null);for(var l=!g||g.length!=f.styles.length||j!=k&&(!j||!k||j.bgClass!=k.bgClass||j.textClass!=k.textClass),m=0;!l&&mc?(ib(a,a.options.workDelay),!0):void 0}),e.length&&cc(a,function(){for(var b=0;bg;--h){if(h<=f.first)return f.first;var i=ff(f,h-1);if(i.stateAfter&&(!c||h<=f.frontier))return h;var j=Zf(i.text,null,a.options.tabSize);(null==e||d>j)&&(e=h-1,d=j)}return e}function lb(a,b,c){var d=a.doc,e=a.display;if(!d.mode.startState)return!0;var f=kb(a,b,c),g=f>d.first&&ff(d,f-1).stateAfter;return g=g?Jd(d.mode,g):Kd(d.mode),d.iter(f,b,function(c){Me(a,c.text,g);var h=f==b-1||f%5==0||f>=e.viewFrom&&f2&&f.push((i.bottom+j.top)/2-c.top)}}f.push(c.bottom-c.top)}}function tb(a,b,c){if(a.line==b)return{map:a.measure.map,cache:a.measure.cache};for(var d=0;dc)return{map:a.measure.maps[d],cache:a.measure.caches[d],before:!0}}function ub(a,b){b=se(b);var c=kf(b),d=a.display.externalMeasured=new gc(a.doc,b,c);d.lineN=c;var e=d.built=Qe(a,d);return d.text=e.pre,sg(a.display.lineMeasure,e.pre),d}function vb(a,b,c,d){return yb(a,xb(a,b),c,d)}function wb(a,b){if(b>=a.display.viewFrom&&b=c.lineN&&bb?(e=0,f=1,g="left"):j>b?(e=b-i,f=e+1):(h==a.length-3||b==j&&a[h+3]>b)&&(f=j-i,e=f-1,b>=j&&(g="right")),null!=e){if(d=a[h+2],i==j&&c==(d.insertLeft?"left":"right")&&(g=c),"left"==c&&0==e)for(;h&&a[h-2]==a[h-3]&&a[h-1].insertLeft;)d=a[(h-=3)+2],g="left";if("right"==c&&e==j-i)for(;hm;m++){for(;i&&og(b.line.text.charAt(g.coverStart+i));)--i;for(;g.coverStart+je&&0==i&&j==g.coverEnd-g.coverStart)l=h.parentNode.getBoundingClientRect();else if(d&&a.options.lineWrapping){var n=qg(h,i,j).getClientRects();l=n.length?n["right"==f?n.length-1:0]:zb}else l=qg(h,i,j).getBoundingClientRect()||zb;if(l.left||l.right||0==i)break;j=i,i-=1,k="right"}d&&11>e&&(l=Cb(a.display.measure,l))}else{i>0&&(k=f="right");var n;l=a.options.lineWrapping&&(n=h.getClientRects()).length>1?n["right"==f?n.length-1:0]:h.getBoundingClientRect()}if(d&&9>e&&!i&&(!l||!l.left&&!l.right)){var o=h.parentNode.getClientRects()[0];l=o?{left:o.left,right:o.left+Sb(a.display),top:o.top,bottom:o.bottom}:zb}for(var p=l.top-b.rect.top,q=l.bottom-b.rect.top,r=(p+q)/2,s=b.view.measure.heights,m=0;mc.from?g(a-1):g(a,d)}d=d||ff(a.doc,b.line),e||(e=xb(a,d));var i=nf(d),j=b.ch;if(!i)return g(j);var k=Yg(i,j),l=h(j,k);return null!=Xg&&(l.other=h(j,Xg)),l}function Mb(a,b){var c=0,b=Oa(a.doc,b);a.options.lineWrapping||(c=Sb(a.display)*b.ch);var d=ff(a.doc,b.line),e=mf(d)+mb(a.display);return{left:c,right:c,top:e,bottom:e+d.height}}function Nb(a,b,c,d){var e=oa(a,b);return e.xRel=d,c&&(e.outside=!0),e}function Ob(a,b,c){var d=a.doc;if(c+=a.display.viewOffset,0>c)return Nb(d.first,0,!0,-1);var e=lf(d,c),f=d.first+d.size-1;if(e>f)return Nb(d.first+d.size-1,ff(d,f).text.length,!0,1);0>b&&(b=0);for(var g=ff(d,e);;){var h=Pb(a,g,e,b,c),i=qe(g),j=i&&i.find(0,!0);if(!i||!(h.ch>j.from.ch||h.ch==j.from.ch&&h.xRel>0))return h;e=kf(g=j.to.line)}}function Pb(a,b,c,d,e){function j(d){var e=Lb(a,oa(c,d),"line",b,i);return g=!0,f>e.bottom?e.left-h:fq)return Nb(c,n,r,1);for(;;){if(k?n==m||n==$g(b,m,1):1>=n-m){for(var s=o>d||q-d>=d-o?m:n,t=d-(s==m?o:q);og(b.text.charAt(s));)++s;var u=Nb(c,s,s==m?p:r,-1>t?-1:t>1?1:0);return u}var v=Math.ceil(l/2),w=m+v;if(k){w=m;for(var x=0;v>x;++x)w=$g(b,w,1)}var y=j(w);y>d?(n=w,q=y,(r=g)&&(q+=1e3),l=v):(m=w,o=y,p=g,l-=v)}}function Rb(a){if(null!=a.cachedTextHeight)return a.cachedTextHeight;if(null==Qb){Qb=pg("pre");for(var b=0;49>b;++b)Qb.appendChild(document.createTextNode("x")),Qb.appendChild(pg("br"));Qb.appendChild(document.createTextNode("x"))}sg(a.measure,Qb);var c=Qb.offsetHeight/50;return c>3&&(a.cachedTextHeight=c),rg(a.measure),c||1}function Sb(a){if(null!=a.cachedCharWidth)return a.cachedCharWidth;var b=pg("span","xxxxxxxxxx"),c=pg("pre",[b]);sg(a.measure,c);var d=b.getBoundingClientRect(),e=(d.right-d.left)/10;return e>2&&(a.cachedCharWidth=e),e||10}function Vb(a){a.curOp={cm:a,viewChanged:!1,startHeight:a.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Ub},Tb?Tb.ops.push(a.curOp):a.curOp.ownsGroup=Tb={ops:[a.curOp],delayedCallbacks:[]}}function Wb(a){var b=a.delayedCallbacks,c=0;do{for(;c=c.viewTo)||c.maxLineChanged&&b.options.lineWrapping,a.update=a.mustUpdate&&new U(b,a.mustUpdate&&{top:a.scrollTop,ensure:a.scrollToPos},a.forceUpdate)}function $b(a){a.updatedDisplay=a.mustUpdate&&W(a.cm,a.update)}function _b(a){var b=a.cm,c=b.display;a.updatedDisplay&&$(b),a.barMeasure=J(b),c.maxLineChanged&&!b.options.lineWrapping&&(a.adjustWidthTo=vb(b,c.maxLine,c.maxLine.text.length).left+3,b.display.sizerWidth=a.adjustWidthTo,a.barMeasure.scrollWidth=Math.max(c.scroller.clientWidth,c.sizer.offsetLeft+a.adjustWidthTo+pb(b)+b.display.barWidth),a.maxScrollLeft=Math.max(0,c.sizer.offsetLeft+a.adjustWidthTo-qb(b))),(a.updatedDisplay||a.selectionChanged)&&(a.preparedSelection=c.input.prepareSelection())}function ac(a){var b=a.cm;null!=a.adjustWidthTo&&(b.display.sizer.style.minWidth=a.adjustWidthTo+"px",a.maxScrollLeftf;f=e){var g=new gc(a.doc,ff(a.doc,f),f);e=f+g.size,d.push(g)}return d}function ic(a,b,c,d){null==b&&(b=a.doc.first),null==c&&(c=a.doc.first+a.doc.size),d||(d=0);var e=a.display;if(d&&cb)&&(e.updateLineNumbers=b),a.curOp.viewChanged=!0,b>=e.viewTo)u&&ue(a.doc,b)e.viewFrom?kc(a):(e.viewFrom+=d,e.viewTo+=d);else if(b<=e.viewFrom&&c>=e.viewTo)kc(a);else if(b<=e.viewFrom){var f=mc(a,c,c+d,1);f?(e.view=e.view.slice(f.index),e.viewFrom=f.lineN,e.viewTo+=d):kc(a)}else if(c>=e.viewTo){var f=mc(a,b,b,-1);f?(e.view=e.view.slice(0,f.index),e.viewTo=f.lineN):kc(a)}else{var g=mc(a,b,b,-1),h=mc(a,c,c+d,1);g&&h?(e.view=e.view.slice(0,g.index).concat(hc(a,g.lineN,h.lineN)).concat(e.view.slice(h.index)),e.viewTo+=d):kc(a)}var i=e.externalMeasured;i&&(c=e.lineN&&b=d.viewTo)){var f=d.view[lc(a,b)];if(null!=f.node){var g=f.changes||(f.changes=[]);-1==dg(g,c)&&g.push(c)}}}function kc(a){a.display.viewFrom=a.display.viewTo=a.doc.first,a.display.view=[],a.display.viewOffset=0}function lc(a,b){if(b>=a.display.viewTo)return null;if(b-=a.display.viewFrom,0>b)return null;for(var c=a.display.view,d=0;db)return d}function mc(a,b,c,d){var f,e=lc(a,b),g=a.display.view;if(!u||c==a.doc.first+a.doc.size)return{index:e,lineN:c};for(var h=0,i=a.display.viewFrom;e>h;h++)i+=g[h].size;if(i!=b){if(d>0){if(e==g.length-1)return null;f=i+g[e].size-b,e++}else f=i-b;b+=f,c+=f}for(;ue(a.doc,c)!=c;){if(e==(0>d?0:g.length-1))return null;c+=d*g[e-(0>d?1:0)].size,e+=d}return{index:e,lineN:c}}function nc(a,b,c){var d=a.display,e=d.view;0==e.length||b>=d.viewTo||c<=d.viewFrom?(d.view=hc(a,b,c),d.viewFrom=b):(d.viewFrom>b?d.view=hc(a,b,d.viewFrom).concat(d.view):d.viewFromc&&(d.view=d.view.slice(0,lc(a,c)))),d.viewTo=c}function oc(a){for(var b=a.display.view,c=0,d=0;d400}var b=a.display;Jf(b.scroller,"mousedown",dc(a,uc)),d&&11>e?Jf(b.scroller,"dblclick",dc(a,function(b){if(!Pf(a,b)){var c=tc(a,b);if(c&&!Bc(a,b)&&!sc(a.display,b)){Df(b);var d=a.findWordAt(c);Ta(a.doc,d.anchor,d.head)}}})):Jf(b.scroller,"dblclick",function(b){Pf(a,b)||Df(b)}),s||Jf(b.scroller,"contextmenu",function(b){_c(a,b)});var c,f={end:0};Jf(b.scroller,"touchstart",function(a){if(!h(a)){clearTimeout(c);var d=+new Date;b.activeTouch={start:d,moved:!1,prev:d-f.end<=300?f:null},1==a.touches.length&&(b.activeTouch.left=a.touches[0].pageX,b.activeTouch.top=a.touches[0].pageY)}}),Jf(b.scroller,"touchmove",function(){b.activeTouch&&(b.activeTouch.moved=!0)}),Jf(b.scroller,"touchend",function(c){var d=b.activeTouch;if(d&&!sc(b,c)&&null!=d.left&&!d.moved&&new Date-d.start<300){var f,e=a.coordsChar(b.activeTouch,"page");f=!d.prev||i(d,d.prev)?new Ka(e,e):!d.prev.prev||i(d,d.prev.prev)?a.findWordAt(e):new Ka(oa(e.line,0),Oa(a.doc,oa(e.line+1,0))),a.setSelection(f.anchor,f.head),a.focus(),Df(c)}g()}),Jf(b.scroller,"touchcancel",g),Jf(b.scroller,"scroll",function(){b.scroller.clientHeight&&(Hc(a,b.scroller.scrollTop),Ic(a,b.scroller.scrollLeft,!0),Lf(a,"scroll",a))}),Jf(b.scroller,"mousewheel",function(b){Mc(a,b)}),Jf(b.scroller,"DOMMouseScroll",function(b){Mc(a,b)}),Jf(b.wrapper,"scroll",function(){b.wrapper.scrollTop=b.wrapper.scrollLeft=0}),b.dragFunctions={enter:function(b){Pf(a,b)||Gf(b)},over:function(b){Pf(a,b)||(Fc(a,b),Gf(b))},start:function(b){Ec(a,b)},drop:dc(a,Dc),leave:function(){Gc(a)}};var j=b.input.getField();Jf(j,"keyup",function(b){Wc.call(a,b)}),Jf(j,"keydown",dc(a,Uc)),Jf(j,"keypress",dc(a,Xc)),Jf(j,"focus",ig(Zc,a)),Jf(j,"blur",ig($c,a))}function qc(a,b,c){var d=c&&c!=v.Init;if(!b!=!d){var e=a.display.dragFunctions,f=b?Jf:Kf;f(a.display.scroller,"dragstart",e.start),f(a.display.scroller,"dragenter",e.enter),f(a.display.scroller,"dragover",e.over),f(a.display.scroller,"dragleave",e.leave),f(a.display.scroller,"drop",e.drop)}}function rc(a){var b=a.display;(b.lastWrapHeight!=b.wrapper.clientHeight||b.lastWrapWidth!=b.wrapper.clientWidth)&&(b.cachedCharWidth=b.cachedTextHeight=b.cachedPaddingH=null,b.scrollbarsClipped=!1,a.setSize())}function sc(a,b){for(var c=Hf(b);c!=a.wrapper;c=c.parentNode)if(!c||1==c.nodeType&&"true"==c.getAttribute("cm-ignore-events")||c.parentNode==a.sizer&&c!=a.mover)return!0}function tc(a,b,c,d){var e=a.display;if(!c&&"true"==Hf(b).getAttribute("cm-not-content"))return null;var f,g,h=e.lineSpace.getBoundingClientRect();try{f=b.clientX-h.left,g=b.clientY-h.top}catch(b){return null}var j,i=Ob(a,f,g);if(d&&1==i.xRel&&(j=ff(a.doc,i.line).text).length==i.ch){var k=Zf(j,j.length,a.options.tabSize)-j.length;i=oa(i.line,Math.max(0,Math.round((f-ob(a.display).left)/Sb(a.display))-k))}return i}function uc(a){var b=this,c=b.display;if(!(c.activeTouch&&c.input.supportsTouch()||Pf(b,a))){if(c.shift=a.shiftKey,sc(c,a))return void(f||(c.scroller.draggable=!1,setTimeout(function(){c.scroller.draggable=!0},100)));if(!Bc(b,a)){var d=tc(b,a);switch(window.focus(),If(a)){case 1:b.state.selectingText?b.state.selectingText(a):d?xc(b,a,d):Hf(a)==c.scroller&&Df(a);break;case 2:f&&(b.state.lastMiddleDown=+new Date),d&&Ta(b.doc,d),setTimeout(function(){c.input.focus()},20),Df(a);break;case 3:s?_c(b,a):Yc(b)}}}}function xc(a,b,c){d?setTimeout(ig(ta,a),0):a.curOp.focus=ug();var f,e=+new Date;wc&&wc.time>e-400&&0==pa(wc.pos,c)?f="triple":vc&&vc.time>e-400&&0==pa(vc.pos,c)?(f="double",wc={time:e,pos:c}):(f="single",vc={time:e,pos:c});var i,g=a.doc.sel,h=o?b.metaKey:b.ctrlKey;a.options.dragDrop&&Dg&&!ua(a)&&"single"==f&&(i=g.contains(c))>-1&&(pa((i=g.ranges[i]).from(),c)<0||c.xRel>0)&&(pa(i.to(),c)>0||c.xRel<0)?yc(a,b,c,h):zc(a,b,c,f,h)}function yc(a,b,c,g){var h=a.display,i=+new Date,j=dc(a,function(k){f&&(h.scroller.draggable=!1),a.state.draggingText=!1,Kf(document,"mouseup",j),Kf(h.scroller,"drop",j),Math.abs(b.clientX-k.clientX)+Math.abs(b.clientY-k.clientY)<10&&(Df(k),!g&&+new Date-200=p;p++){var r=ff(g,p).text,s=$f(r,m,f);m==o?e.push(new Ka(oa(p,s),oa(p,s))):r.length>s&&e.push(new Ka(oa(p,s),oa(p,$f(r,o,f))))}e.length||e.push(new Ka(c,c)),Za(g,La(j.ranges.slice(0,i).concat(e),i),{origin:"*mouse",scroll:!1}),a.scrollIntoView(b)}else{var t=h,u=t.anchor,v=b;if("single"!=d){if("double"==d)var w=a.findWordAt(b);else var w=new Ka(oa(b.line,0),Oa(g,oa(b.line+1,0)));pa(w.anchor,u)>0?(v=w.head,u=sa(t.from(),w.anchor)):(v=w.anchor,u=ra(t.to(),w.head))}var e=j.ranges.slice(0);e[i]=new Ka(Oa(g,u),v),Za(g,La(e,i),Wf)}}function r(b){var c=++q,e=tc(a,b,!0,"rect"==d);if(e)if(0!=pa(e,n)){a.curOp.focus=ug(),o(e);var h=P(f,g);(e.line>=h.to||e.linep.bottom?20:0;i&&setTimeout(dc(a,function(){q==c&&(f.scroller.scrollTop+=i,r(b))}),50)}}function s(b){a.state.selectingText=!1,q=1/0,Df(b),f.input.focus(),Kf(document,"mousemove",t),Kf(document,"mouseup",u),g.history.lastSelOrigin=null}var f=a.display,g=a.doc;Df(b);var h,i,j=g.sel,k=j.ranges;if(e&&!b.shiftKey?(i=g.sel.contains(c),h=i>-1?k[i]:new Ka(c,c)):(h=g.sel.primary(),i=g.sel.primIndex),b.altKey)d="rect",e||(h=new Ka(c,c)),c=tc(a,b,!0,!0),i=-1;else if("double"==d){var l=a.findWordAt(c);h=a.display.shift||g.extend?Sa(g,h,l.anchor,l.head):l}else if("triple"==d){var m=new Ka(oa(c.line,0),Oa(g,oa(c.line+1,0)));h=a.display.shift||g.extend?Sa(g,h,m.anchor,m.head):m}else h=Sa(g,h,c);e?-1==i?(i=k.length,Za(g,La(k.concat([h]),i),{scroll:!1,origin:"*mouse"})):k.length>1&&k[i].empty()&&"single"==d&&!b.shiftKey?(Za(g,La(k.slice(0,i).concat(k.slice(i+1)),0),{scroll:!1,origin:"*mouse"}),j=g.sel):Va(g,i,h,Wf):(i=0,Za(g,new Ja([h],0),Wf),j=g.sel);var n=c,p=f.wrapper.getBoundingClientRect(),q=0,t=dc(a,function(a){If(a)?r(a):s(a)}),u=dc(a,s);a.state.selectingText=u,Jf(document,"mousemove",t),Jf(document,"mouseup",u)}function Ac(a,b,c,d,e){try{var f=b.clientX,g=b.clientY}catch(b){return!1}if(f>=Math.floor(a.display.gutters.getBoundingClientRect().right))return!1;d&&Df(b);var h=a.display,i=h.lineDiv.getBoundingClientRect();if(g>i.bottom||!Rf(a,c))return Ff(b);g-=i.top-h.viewOffset;for(var j=0;j=f){var l=lf(a.doc,g),m=a.options.gutters[j];return e(a,c,a,l,m,b),Ff(b)}}}function Bc(a,b){return Ac(a,b,"gutterClick",!0,Nf)}function Dc(a){var b=this;if(Gc(b),!Pf(b,a)&&!sc(b.display,a)){Df(a),d&&(Cc=+new Date);var c=tc(b,a,!0),e=a.dataTransfer.files;if(c&&!ua(b))if(e&&e.length&&window.FileReader&&window.File)for(var f=e.length,g=Array(f),h=0,i=function(a,d){var e=new FileReader;e.onload=dc(b,function(){if(g[d]=e.result,++h==f){c=Oa(b.doc,c);var a={from:c,to:c,text:b.doc.splitLines(g.join(b.doc.lineSeparator())),origin:"paste"};hd(b.doc,a),Ya(b.doc,Ma(c,bd(a)))}}),e.readAsText(a)},j=0;f>j;++j)i(e[j],j);else{if(b.state.draggingText&&b.doc.sel.contains(c)>-1)return b.state.draggingText(a),void setTimeout(function(){b.display.input.focus()},20);try{var g=a.dataTransfer.getData("Text");if(g){if(b.state.draggingText&&!(o?a.altKey:a.ctrlKey))var k=b.listSelections();if($a(b.doc,Ma(c,c)),k)for(var j=0;jj.clientWidth||g&&j.scrollHeight>j.clientHeight){if(g&&o&&f)a:for(var k=c.target,l=h.view;k!=j;k=k.parentNode)for(var m=0;mn?p=Math.max(0,p+n-50):q=Math.min(b.doc.height,q+n+50),Y(b,{top:p,bottom:q})}20>Jc&&(null==h.wheelStartX?(h.wheelStartX=j.scrollLeft,h.wheelStartY=j.scrollTop,h.wheelDX=e,h.wheelDY=g,setTimeout(function(){if(null!=h.wheelStartX){var a=j.scrollLeft-h.wheelStartX,b=j.scrollTop-h.wheelStartY,c=b&&h.wheelDY&&b/h.wheelDY||a&&h.wheelDX&&a/h.wheelDX;h.wheelStartX=h.wheelStartY=null,c&&(Kc=(Kc*Jc+c)/(Jc+1),++Jc)}},200)):(h.wheelDX+=e,h.wheelDY+=g))}}function Nc(a,b,c){if("string"==typeof b&&(b=Ld[b],!b))return!1;a.display.input.ensurePolled();var d=a.display.shift,e=!1;try{ua(a)&&(a.state.suppressEdits=!0),c&&(a.display.shift=!1),e=b(a)!=Uf}finally{a.display.shift=d,a.state.suppressEdits=!1}return e}function Oc(a,b,c){for(var d=0;de&&27==a.keyCode&&(a.returnValue=!1);var c=a.keyCode;b.display.shift=16==c||a.shiftKey;var f=Rc(b,a);i&&(Tc=f?c:null,!f&&88==c&&!Kg&&(o?a.metaKey:a.ctrlKey)&&b.replaceSelection("",null,"cut")),18!=c||/\bCodeMirror-crosshair\b/.test(b.display.lineDiv.className)||Vc(b)}}function Vc(a){function c(a){18!=a.keyCode&&a.altKey||(wg(b,"CodeMirror-crosshair"),Kf(document,"keyup",c),Kf(document,"mouseover",c))}var b=a.display.lineDiv;xg(b,"CodeMirror-crosshair"),Jf(document,"keyup",c),Jf(document,"mouseover",c)}function Wc(a){16==a.keyCode&&(this.doc.sel.shift=!1),Pf(this,a)}function Xc(a){var b=this;if(!(sc(b.display,a)||Pf(b,a)||a.ctrlKey&&!a.altKey||o&&a.metaKey)){var c=a.keyCode,d=a.charCode;if(i&&c==Tc)return Tc=null,void Df(a);if(!i||a.which&&!(a.which<10)||!Rc(b,a)){var e=String.fromCharCode(null==d?c:d);Sc(b,a,e)||b.display.input.onKeyPress(a)}}}function Yc(a){a.state.delayingBlurEvent=!0,setTimeout(function(){a.state.delayingBlurEvent&&(a.state.delayingBlurEvent=!1,$c(a))},100)}function Zc(a){a.state.delayingBlurEvent&&(a.state.delayingBlurEvent=!1),"nocursor"!=a.options.readOnly&&(a.state.focused||(Lf(a,"focus",a),a.state.focused=!0,xg(a.display.wrapper,"CodeMirror-focused"),a.curOp||a.display.selForContextMenu==a.doc.sel||(a.display.input.reset(),f&&setTimeout(function(){a.display.input.reset(!0)},20)),a.display.input.receivedFocus()),hb(a))}function $c(a){a.state.delayingBlurEvent||(a.state.focused&&(Lf(a,"blur",a),a.state.focused=!1,wg(a.display.wrapper,"CodeMirror-focused")),clearInterval(a.display.blinker),setTimeout(function(){a.state.focused||(a.display.shift=!1)},150))}function _c(a,b){sc(a.display,b)||ad(a,b)||a.display.input.onContextMenu(b)}function ad(a,b){return Rf(a,"gutterContextMenu")?Ac(a,b,"gutterContextMenu",!1,Lf):!1}function cd(a,b){if(pa(a,b.from)<0)return a;if(pa(a,b.to)<=0)return bd(b);var c=a.line+b.text.length-(b.to.line-b.from.line)-1,d=a.ch;return a.line==b.to.line&&(d+=bd(b).ch-b.to.ch),oa(c,d)}function dd(a,b){for(var c=[],d=0;d=0;--e)id(a,{from:d[e].from,to:d[e].to,text:e?[""]:b.text});else id(a,b)}}function id(a,b){if(1!=b.text.length||""!=b.text[0]||0!=pa(b.from,b.to)){var c=dd(a,b);sf(a,b,c,a.cm?a.cm.curOp.id:NaN),ld(a,b,c,fe(a,b));var d=[];df(a,function(a,c){c||-1!=dg(d,a.history)||(Cf(a.history,b),d.push(a.history)),ld(a,b,null,fe(a,b))})}}function jd(a,b,c){if(!a.cm||!a.cm.state.suppressEdits){for(var e,d=a.history,f=a.sel,g="undo"==b?d.done:d.undone,h="undo"==b?d.undone:d.done,i=0;i=0;--i){var l=e.changes[i];if(l.origin=b,k&&!gd(a,l,!1))return void(g.length=0);j.push(pf(a,l));var m=i?dd(a,l):bg(g);ld(a,l,m,he(a,l)),!i&&a.cm&&a.cm.scrollIntoView({from:l.from,to:bd(l)});var n=[];df(a,function(a,b){b||-1!=dg(n,a.history)||(Cf(a.history,l),n.push(a.history)),ld(a,l,null,he(a,l))})}}}}function kd(a,b){if(0!=b&&(a.first+=b,a.sel=new Ja(eg(a.sel.ranges,function(a){return new Ka(oa(a.anchor.line+b,a.anchor.ch),oa(a.head.line+b,a.head.ch))}),a.sel.primIndex),a.cm)){ic(a.cm,a.first,a.first-b,b);for(var c=a.cm.display,d=c.viewFrom;da.lastLine())){if(b.from.linef&&(b={from:b.from,to:oa(f,ff(a,f).text.length),text:[b.text[0]],origin:b.origin}),b.removed=gf(a,b.from,b.to),c||(c=dd(a,b)),a.cm?md(a.cm,b,d):Ye(a,b,d),$a(a,c,Vf)}}function md(a,b,c){var d=a.doc,e=a.display,f=b.from,g=b.to,h=!1,i=f.line;a.options.lineWrapping||(i=kf(se(ff(d,f.line))),d.iter(i,g.line+1,function(a){return a==e.maxLine?(h=!0,!0):void 0})),d.sel.contains(b.from,b.to)>-1&&Qf(a),Ye(d,b,c,A(a)),a.options.lineWrapping||(d.iter(i,f.line+b.text.length,function(a){var b=G(a);b>e.maxLineLength&&(e.maxLine=a,e.maxLineLength=b,e.maxLineChanged=!0,h=!1)}),h&&(a.curOp.updateMaxLine=!0)),d.frontier=Math.min(d.frontier,f.line),ib(a,400);var j=b.text.length-(g.line-f.line)-1;b.full?ic(a):f.line!=g.line||1!=b.text.length||Xe(a.doc,b)?ic(a,f.line,g.line+1,j):jc(a,f.line,"text");var k=Rf(a,"changes"),l=Rf(a,"change");if(l||k){var m={from:f,to:g,text:b.text,removed:b.removed,origin:b.origin};l&&Nf(a,"change",a,m),k&&(a.curOp.changeObjs||(a.curOp.changeObjs=[])).push(m)}a.display.selForContextMenu=null}function nd(a,b,c,d,e){if(d||(d=c),pa(d,c)<0){var f=d;d=c,c=f}"string"==typeof b&&(b=a.splitLines(b)),hd(a,{from:c,to:d,text:b,origin:e})}function od(a,b){if(!Pf(a,"scrollCursorIntoView")){var c=a.display,d=c.sizer.getBoundingClientRect(),e=null;if(b.top+d.top<0?e=!0:b.bottom+d.top>(window.innerHeight||document.documentElement.clientHeight)&&(e=!1),null!=e&&!l){var f=pg("div","\u200b",null,"position: absolute; top: "+(b.top-c.viewOffset-mb(a.display))+"px; height: "+(b.bottom-b.top+pb(a)+c.barHeight)+"px; left: "+b.left+"px; width: 2px;");a.display.lineSpace.appendChild(f),f.scrollIntoView(e),a.display.lineSpace.removeChild(f)}}}function pd(a,b,c,d){null==d&&(d=0);for(var e=0;5>e;e++){var f=!1,g=Lb(a,b),h=c&&c!=b?Lb(a,c):g,i=rd(a,Math.min(g.left,h.left),Math.min(g.top,h.top)-d,Math.max(g.left,h.left),Math.max(g.bottom,h.bottom)+d),j=a.doc.scrollTop,k=a.doc.scrollLeft;if(null!=i.scrollTop&&(Hc(a,i.scrollTop),Math.abs(a.doc.scrollTop-j)>1&&(f=!0)),null!=i.scrollLeft&&(Ic(a,i.scrollLeft),Math.abs(a.doc.scrollLeft-k)>1&&(f=!0)),!f)break}return g}function qd(a,b,c,d,e){var f=rd(a,b,c,d,e);null!=f.scrollTop&&Hc(a,f.scrollTop),null!=f.scrollLeft&&Ic(a,f.scrollLeft)}function rd(a,b,c,d,e){var f=a.display,g=Rb(a.display);0>c&&(c=0);var h=a.curOp&&null!=a.curOp.scrollTop?a.curOp.scrollTop:f.scroller.scrollTop,i=rb(a),j={};e-c>i&&(e=c+i);var k=a.doc.height+nb(f),l=g>c,m=e>k-g;if(h>c)j.scrollTop=l?0:c;else if(e>h+i){var n=Math.min(c,(m?k:e)-i);n!=h&&(j.scrollTop=n)}var o=a.curOp&&null!=a.curOp.scrollLeft?a.curOp.scrollLeft:f.scroller.scrollLeft,p=qb(a)-(a.options.fixedGutter?f.gutters.offsetWidth:0),q=d-b>p;return q&&(d=b+p),10>b?j.scrollLeft=0:o>b?j.scrollLeft=Math.max(0,b-(q?0:10)):d>p+o-3&&(j.scrollLeft=d+(q?0:10)-p),j}function sd(a,b,c){(null!=b||null!=c)&&ud(a),null!=b&&(a.curOp.scrollLeft=(null==a.curOp.scrollLeft?a.doc.scrollLeft:a.curOp.scrollLeft)+b),null!=c&&(a.curOp.scrollTop=(null==a.curOp.scrollTop?a.doc.scrollTop:a.curOp.scrollTop)+c)}function td(a){ud(a);var b=a.getCursor(),c=b,d=b;a.options.lineWrapping||(c=b.ch?oa(b.line,b.ch-1):b,d=oa(b.line,b.ch+1)),a.curOp.scrollToPos={from:c,to:d,margin:a.options.cursorScrollMargin,isCursor:!0}}function ud(a){var b=a.curOp.scrollToPos;if(b){a.curOp.scrollToPos=null;var c=Mb(a,b.from),d=Mb(a,b.to),e=rd(a,Math.min(c.left,d.left),Math.min(c.top,d.top)-b.margin,Math.max(c.right,d.right),Math.max(c.bottom,d.bottom)+b.margin);a.scrollTo(e.scrollLeft,e.scrollTop)}}function vd(a,b,c,d){var f,e=a.doc;null==c&&(c="add"),"smart"==c&&(e.mode.indent?f=lb(a,b):c="prev");var g=a.options.tabSize,h=ff(e,b),i=Zf(h.text,null,g);h.stateAfter&&(h.stateAfter=null);var k,j=h.text.match(/^\s*/)[0];if(d||/\S/.test(h.text)){if("smart"==c&&(k=e.mode.indent(f,h.text.slice(j.length),h.text),k==Uf||k>150)){if(!d)return;c="prev"}}else k=0,c="not";"prev"==c?k=b>e.first?Zf(ff(e,b-1).text,null,g):0:"add"==c?k=i+a.options.indentUnit:"subtract"==c?k=i-a.options.indentUnit:"number"==typeof c&&(k=i+c),k=Math.max(0,k); +var l="",m=0;if(a.options.indentWithTabs)for(var n=Math.floor(k/g);n;--n)m+=g,l+=" ";if(k>m&&(l+=ag(k-m)),l!=j)return nd(e,l,oa(b,0),oa(b,j.length),"+input"),h.stateAfter=null,!0;for(var n=0;n=0;b--)nd(a.doc,"",d[b].from,d[b].to,"+delete");td(a)})}function yd(a,b,c,d,e){function k(){var b=f+c;return b=a.first+a.size?j=!1:(f=b,i=ff(a,b))}function l(a){var b=(e?$g:_g)(i,g,c,!0);if(null==b){if(a||!k())return j=!1;g=e?(0>c?Sg:Rg)(i):0>c?i.text.length:0}else g=b;return!0}var f=b.line,g=b.ch,h=c,i=ff(a,f),j=!0;if("char"==d)l();else if("column"==d)l(!0);else if("word"==d||"group"==d)for(var m=null,n="group"==d,o=a.cm&&a.cm.getHelper(b,"wordChars"),p=!0;!(0>c)||l(!p);p=!1){var q=i.text.charAt(g)||"\n",r=lg(q,o)?"w":n&&"\n"==q?"n":!n||/\s/.test(q)?null:"p";if(!n||p||r||(r="s"),m&&m!=r){0>c&&(c=1,l());break}if(r&&(m=r),c>0&&!l(!p))break}var s=cb(a,oa(f,g),h,!0);return j||(s.hitSide=!0),s}function zd(a,b,c,d){var g,e=a.doc,f=b.left;if("page"==d){var h=Math.min(a.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);g=b.top+c*(h-(0>c?1.5:.5)*Rb(a.display))}else"line"==d&&(g=c>0?b.bottom+3:b.top-3);for(;;){var i=Ob(a,f,g);if(!i.outside)break;if(0>c?0>=g:g>=e.height){i.hitSide=!0;break}g+=5*c}return i}function Cd(a,b,c,d){v.defaults[a]=b,c&&(Bd[a]=d?function(a,b,d){d!=Dd&&c(a,b,d)}:c)}function Nd(a){for(var c,d,e,f,b=a.split(/-(?!$)/),a=b[b.length-1],g=0;g0||0==g&&f.clearWhenEmpty!==!1)return f;if(f.replacedWith&&(f.collapsed=!0,f.widgetNode=pg("span",[f.replacedWith],"CodeMirror-widget"),d.handleMouseEvents||f.widgetNode.setAttribute("cm-ignore-events","true"),d.insertLeft&&(f.widgetNode.insertLeft=!0)),f.collapsed){if(re(a,b.line,b,c,f)||b.line!=c.line&&re(a,c.line,b,c,f))throw new Error("Inserting collapsed marker partially overlapping an existing one");u=!0}f.addToHistory&&sf(a,{from:b,to:c,origin:"markText"},a.sel,NaN);var j,h=b.line,i=a.cm;if(a.iter(h,c.line+1,function(a){i&&f.collapsed&&!i.options.lineWrapping&&se(a)==i.display.maxLine&&(j=!0),f.collapsed&&h!=b.line&&jf(a,0),ce(a,new _d(f,h==b.line?b.ch:null,h==c.line?c.ch:null)),++h}),f.collapsed&&a.iter(b.line,c.line+1,function(b){we(a,b)&&jf(b,0)}),f.clearOnEnter&&Jf(f,"beforeCursorEnter",function(){f.clear()}),f.readOnly&&(t=!0,(a.history.done.length||a.history.undone.length)&&a.clearHistory()),f.collapsed&&(f.id=++Td,f.atomic=!0),i){if(j&&(i.curOp.updateMaxLine=!0),f.collapsed)ic(i,b.line,c.line+1);else if(f.className||f.title||f.startStyle||f.endStyle||f.css)for(var k=b.line;k<=c.line;k++)jc(i,k,"text");f.atomic&&ab(i.doc),Nf(i,"markerAdded",i,f)}return f}function Xd(a,b,c,d,e){d=hg(d),d.shared=!1;var f=[Vd(a,b,c,d,e)],g=f[0],h=d.widgetNode;return df(a,function(a){h&&(d.widgetNode=h.cloneNode(!0)),f.push(Vd(a,Oa(a,b),Oa(a,c),d,e));for(var i=0;i=b:f.to>b);(e||(e=[])).push(new _d(g,f.from,i?null:f.to))}}return e}function ee(a,b,c){if(a)for(var e,d=0;d=b:f.to>b);if(h||f.from==b&&"bookmark"==g.type&&(!c||f.marker.insertLeft)){var i=null==f.from||(g.inclusiveLeft?f.from<=b:f.from0&&h)for(var l=0;ll;++l)o.push(q);o.push(i)}return o}function ge(a){for(var b=0;b0)){var k=[i,1],l=pa(j.from,h.from),m=pa(j.to,h.to);(0>l||!g.inclusiveLeft&&!l)&&k.push({from:j.from,to:h.from}),(m>0||!g.inclusiveRight&&!m)&&k.push({from:h.to,to:j.to}),e.splice.apply(e,k),i+=k.length-1}}return e}function je(a){var b=a.markedSpans;if(b){for(var c=0;c=0&&0>=l||0>=k&&l>=0)&&(0>=k&&(pa(j.to,c)>0||i.marker.inclusiveRight&&e.inclusiveLeft)||k>=0&&(pa(j.from,d)<0||i.marker.inclusiveLeft&&e.inclusiveRight)))return!0}}}function se(a){for(var b;b=pe(a);)a=b.find(-1,!0).line;return a}function te(a){for(var b,c;b=qe(a);)a=b.find(1,!0).line,(c||(c=[])).push(a);return c}function ue(a,b){var c=ff(a,b),d=se(c);return c==d?b:kf(d)}function ve(a,b){if(b>a.lastLine())return b;var d,c=ff(a,b);if(!we(a,c))return b;for(;d=qe(c);)c=d.find(1,!0).line;return kf(c)+1}function we(a,b){var c=u&&b.markedSpans;if(c)for(var d,e=0;ee;e++){d&&(d[0]=v.innerMode(a,c).mode);var f=a.token(b,c);if(b.pos>b.start)return f}throw new Error("Mode "+a.name+" failed to advance stream.")}function Ie(a,b,c,d){function e(a){return{start:k.start,end:k.pos,string:k.current(),type:h||null,state:a?Jd(f.mode,j):j}}var h,f=a.doc,g=f.mode;b=Oa(f,b);var l,i=ff(f,b.line),j=lb(a,b.line,c),k=new Sd(i.text,a.options.tabSize);for(d&&(l=[]);(d||k.posa.options.maxHighlightLength?(h=!1,g&&Me(a,b,d,k.pos),k.pos=b.length,l=null):l=Fe(He(c,k,d,m),f),m){var n=m[0].name;n&&(l="m-"+(l?n+" "+l:n))}if(!h||j!=l){for(;ij;){var d=e[i];d>a&&e.splice(i,1,a,e[i+1],d),i+=2,j=Math.min(a,d)}if(b)if(h.opaque)e.splice(c,i-c,a,"cm-overlay "+b),i=c+2;else for(;i>c;c+=2){var f=e[c+1];e[c+1]=(f?f+" ":"")+"cm-overlay "+b}},f)}return{styles:e,classes:f.bgClass||f.textClass?f:null}}function Le(a,b,c){if(!b.styles||b.styles[0]!=a.state.modeGen){var d=lb(a,kf(b)),e=Ke(a,b,b.text.length>a.options.maxHighlightLength?Jd(a.doc.mode,d):d);b.stateAfter=d,b.styles=e.styles,e.classes?b.styleClasses=e.classes:b.styleClasses&&(b.styleClasses=null),c===a.doc.frontier&&a.doc.frontier++}return b.styles}function Me(a,b,c,d){var e=a.doc.mode,f=new Sd(b,a.options.tabSize);for(f.start=f.pos=d||0,""==b&&Ge(e,c);!f.eol();)He(e,f,c),f.start=f.pos}function Pe(a,b){if(!a||/^\s*$/.test(a))return null;var c=b.addModeClass?Oe:Ne;return c[a]||(c[a]=a.replace(/\S+/g,"cm-$&"))}function Qe(a,b){var c=pg("span",null,null,f?"padding-right: .1px":null),e={pre:pg("pre",[c],"CodeMirror-line"),content:c,col:0,pos:0,cm:a,splitSpaces:(d||f)&&a.getOption("lineWrapping")};b.measure={};for(var g=0;g<=(b.rest?b.rest.length:0);g++){var i,h=g?b.rest[g-1]:b.line;e.pos=0,e.addToken=Se,Hg(a.display.measure)&&(i=nf(h))&&(e.addToken=Ue(e.addToken,i)),e.map=[];var j=b!=a.display.externalMeasured&&kf(h);We(h,e,Le(a,h,j)),h.styleClasses&&(h.styleClasses.bgClass&&(e.bgClass=yg(h.styleClasses.bgClass,e.bgClass||"")),h.styleClasses.textClass&&(e.textClass=yg(h.styleClasses.textClass,e.textClass||""))),0==e.map.length&&e.map.push(0,0,e.content.appendChild(Fg(a.display.measure))),0==g?(b.measure.map=e.map,b.measure.cache={}):((b.measure.maps||(b.measure.maps=[])).push(e.map),(b.measure.caches||(b.measure.caches=[])).push({}))}return f&&/\bcm-tab\b/.test(e.content.lastChild.className)&&(e.content.className="cm-tab-wrap-hack"),Lf(a,"renderLine",a,b.line,e.pre),e.pre.className&&(e.textClass=yg(e.pre.className,e.textClass||"")),e}function Re(a){var b=pg("span","\u2022","cm-invalidchar");return b.title="\\u"+a.charCodeAt(0).toString(16),b.setAttribute("aria-label",b.title),b}function Se(a,b,c,f,g,h,i){if(b){var j=a.splitSpaces?b.replace(/ {3,}/g,Te):b,k=a.cm.state.specialChars,l=!1;if(k.test(b))for(var m=document.createDocumentFragment(),n=0;;){k.lastIndex=n;var o=k.exec(b),p=o?o.index-n:b.length-n;if(p){var q=document.createTextNode(j.slice(n,n+p));d&&9>e?m.appendChild(pg("span",[q])):m.appendChild(q),a.map.push(a.pos,a.pos+p,q),a.col+=p,a.pos+=p}if(!o)break;if(n+=p+1," "==o[0]){var r=a.cm.options.tabSize,s=r-a.col%r,q=m.appendChild(pg("span",ag(s),"cm-tab"));q.setAttribute("role","presentation"),q.setAttribute("cm-text"," "),a.col+=s}else if("\r"==o[0]||"\n"==o[0]){var q=m.appendChild(pg("span","\r"==o[0]?"\u240d":"\u2424","cm-invalidchar"));q.setAttribute("cm-text",o[0]),a.col+=1}else{var q=a.cm.options.specialCharPlaceholder(o[0]);q.setAttribute("cm-text",o[0]),d&&9>e?m.appendChild(pg("span",[q])):m.appendChild(q),a.col+=1}a.map.push(a.pos,a.pos+1,q),a.pos++}else{a.col+=b.length;var m=document.createTextNode(j);a.map.push(a.pos,a.pos+b.length,m),d&&9>e&&(l=!0),a.pos+=b.length}if(c||f||g||l||i){var t=c||"";f&&(t+=f),g&&(t+=g);var u=pg("span",[m],t,i);return h&&(u.title=h),a.content.appendChild(u)}a.content.appendChild(m)}}function Te(a){for(var b=" ",c=0;cj&&m.from<=j)break}if(m.to>=k)return a(c,d,e,f,g,h,i);a(c,d.slice(0,m.to-j),e,f,null,h,i),f=null,d=d.slice(m.to-j),j=m.to}}}function Ve(a,b,c,d){var e=!d&&c.widgetNode;e&&a.map.push(a.pos,a.pos+b,e),!d&&a.cm.display.input.needsContentAttribute&&(e||(e=a.content.appendChild(document.createElement("span"))),e.setAttribute("cm-marker",c.id)),e&&(a.cm.display.input.setUneditable(e),a.content.appendChild(e)),a.pos+=b}function We(a,b,c){var d=a.markedSpans,e=a.text,f=0;if(d)for(var k,l,n,o,p,q,r,h=e.length,i=0,g=1,j="",m=0;;){if(m==i){n=o=p=q=l="",r=null,m=1/0;for(var s=[],t=0;ti||v.collapsed&&u.to==i&&u.from==i)?(null!=u.to&&u.to!=i&&m>u.to&&(m=u.to,o=""),v.className&&(n+=" "+v.className),v.css&&(l=v.css),v.startStyle&&u.from==i&&(p+=" "+v.startStyle),v.endStyle&&u.to==m&&(o+=" "+v.endStyle),v.title&&!q&&(q=v.title),v.collapsed&&(!r||ne(r.marker,v)<0)&&(r=u)):u.from>i&&m>u.from&&(m=u.from)}if(r&&(r.from||0)==i){if(Ve(b,(null==r.to?h+1:r.to)-i,r.marker,null==r.from),null==r.to)return;r.to==i&&(r=!1)}if(!r&&s.length)for(var t=0;t=h)break;for(var w=Math.min(h,m);;){if(j){var x=i+j.length;if(!r){var y=x>w?j.slice(0,w-i):j;b.addToken(b,y,k?k+n:n,p,i+y.length==m?o:"",q,l)}if(x>=w){j=j.slice(w-i),i=w;break}i=x,p=""}j=e.slice(f,f=c[g++]),k=Pe(c[g++],b.cm.options)}}else for(var g=1;gc;++c)f.push(new Ce(j[c],e(c),d));return f}var h=b.from,i=b.to,j=b.text,k=ff(a,h.line),l=ff(a,i.line),m=bg(j),n=e(j.length-1),o=i.line-h.line;if(b.full)a.insert(0,g(0,j.length)),a.remove(j.length,a.size-j.length);else if(Xe(a,b)){var p=g(0,j.length-1);f(l,l.text,n),o&&a.remove(h.line,o),p.length&&a.insert(h.line,p)}else if(k==l)if(1==j.length)f(k,k.text.slice(0,h.ch)+m+k.text.slice(i.ch),n);else{var p=g(1,j.length-1);p.push(new Ce(m+k.text.slice(i.ch),n,d)),f(k,k.text.slice(0,h.ch)+j[0],e(0)),a.insert(h.line+1,p)}else if(1==j.length)f(k,k.text.slice(0,h.ch)+j[0]+l.text.slice(i.ch),e(0)),a.remove(h.line+1,o);else{f(k,k.text.slice(0,h.ch)+j[0],e(0)),f(l,m+l.text.slice(i.ch),n);var p=g(1,j.length-1);o>1&&a.remove(h.line+1,o-1),a.insert(h.line+1,p)}Nf(a,"change",a,b)}function Ze(a){this.lines=a,this.parent=null;for(var b=0,c=0;bb||b>=a.size)throw new Error("There is no line "+(b+a.first)+" in the document.");for(var c=a;!c.lines;)for(var d=0;;++d){var e=c.children[d],f=e.chunkSize();if(f>b){c=e;break}b-=f}return c.lines[b]}function gf(a,b,c){var d=[],e=b.line;return a.iter(b.line,c.line+1,function(a){var f=a.text;e==c.line&&(f=f.slice(0,c.ch)),e==b.line&&(f=f.slice(b.ch)),d.push(f),++e}),d}function hf(a,b,c){var d=[];return a.iter(b,c,function(a){d.push(a.text)}),d}function jf(a,b){var c=b-a.height;if(c)for(var d=a;d;d=d.parent)d.height+=c}function kf(a){if(null==a.parent)return null;for(var b=a.parent,c=dg(b.lines,a),d=b.parent;d;b=d,d=d.parent)for(var e=0;d.children[e]!=b;++e)c+=d.children[e].chunkSize();return c+b.first}function lf(a,b){var c=a.first;a:do{for(var d=0;db){a=e;continue a}b-=f,c+=e.chunkSize()}return c}while(!a.lines);for(var d=0;db)break;b-=h}return c+d}function mf(a){a=se(a);for(var b=0,c=a.parent,d=0;d1&&!a.done[a.done.length-2].ranges?(a.done.pop(),bg(a.done)):void 0}function sf(a,b,c,d){var e=a.history;e.undone.length=0;var g,f=+new Date;if((e.lastOp==d||e.lastOrigin==b.origin&&b.origin&&("+"==b.origin.charAt(0)&&a.cm&&e.lastModTime>f-a.cm.options.historyEventDelay||"*"==b.origin.charAt(0)))&&(g=rf(e,e.lastOp==d))){var h=bg(g.changes);0==pa(b.from,b.to)&&0==pa(b.from,h.to)?h.to=bd(b):g.changes.push(pf(a,b))}else{var i=bg(e.done);for(i&&i.ranges||vf(a.sel,e.done),g={changes:[pf(a,b)],generation:e.generation},e.done.push(g);e.done.length>e.undoDepth;)e.done.shift(),e.done[0].ranges||e.done.shift()}e.done.push(c),e.generation=++e.maxGeneration,e.lastModTime=e.lastSelTime=f,e.lastOp=e.lastSelOp=d,e.lastOrigin=e.lastSelOrigin=b.origin,h||Lf(a,"historyAdded")}function tf(a,b,c,d){var e=b.charAt(0);return"*"==e||"+"==e&&c.ranges.length==d.ranges.length&&c.somethingSelected()==d.somethingSelected()&&new Date-a.history.lastSelTime<=(a.cm?a.cm.options.historyEventDelay:500)}function uf(a,b,c,d){var e=a.history,f=d&&d.origin;c==e.lastSelOp||f&&e.lastSelOrigin==f&&(e.lastModTime==e.lastSelTime&&e.lastOrigin==f||tf(a,f,bg(e.done),b))?e.done[e.done.length-1]=b:vf(b,e.done),e.lastSelTime=+new Date,e.lastSelOrigin=f,e.lastSelOp=c,d&&d.clearRedo!==!1&&qf(e.undone)}function vf(a,b){var c=bg(b);c&&c.ranges&&c.equals(a)||b.push(a)}function wf(a,b,c,d){var e=b["spans_"+a.id],f=0;a.iter(Math.max(a.first,c),Math.min(a.first+a.size,d),function(c){c.markedSpans&&((e||(e=b["spans_"+a.id]={}))[f]=c.markedSpans),++f})}function xf(a){if(!a)return null;for(var c,b=0;b-1&&(bg(h)[l]=j[l],delete j[l])}}}return e}function Af(a,b,c,d){c0}function Sf(a){a.prototype.on=function(a,b){Jf(this,a,b)},a.prototype.off=function(a,b){Kf(this,a,b)}}function Yf(){this.id=null}function ag(a){for(;_f.length<=a;)_f.push(bg(_f)+" ");return _f[a]}function bg(a){return a[a.length-1]}function dg(a,b){for(var c=0;c-1&&kg(a)?!0:b.test(a):kg(a)}function mg(a){for(var b in a)if(a.hasOwnProperty(b)&&a[b])return!1;return!0}function og(a){return a.charCodeAt(0)>=768&&ng.test(a)}function pg(a,b,c,d){var e=document.createElement(a);if(c&&(e.className=c),d&&(e.style.cssText=d),"string"==typeof b)e.appendChild(document.createTextNode(b));else if(b)for(var f=0;f0;--b)a.removeChild(a.firstChild);return a}function sg(a,b){return rg(a).appendChild(b)}function ug(){for(var a=document.activeElement;a&&a.root&&a.root.activeElement;)a=a.root.activeElement;return a}function vg(a){return new RegExp("(^|\\s)"+a+"(?:$|\\s)\\s*")}function yg(a,b){for(var c=a.split(" "),d=0;d2&&!(d&&8>e))}var c=Eg?pg("span","\u200b"):pg("span","\xa0",null,"display: inline-block; width: 1px; margin-right: -1px");return c.setAttribute("cm-text",""),c}function Hg(a){if(null!=Gg)return Gg;var b=sg(a,document.createTextNode("A\u062eA")),c=qg(b,0,1).getBoundingClientRect();if(!c||c.left==c.right)return!1;var d=qg(b,1,2).getBoundingClientRect();return Gg=d.right-c.right<3}function Mg(a){if(null!=Lg)return Lg;var b=sg(a,pg("span","x")),c=b.getBoundingClientRect(),d=qg(b,0,1).getBoundingClientRect();return Lg=Math.abs(c.left-d.left)>1}function Og(a,b,c,d){if(!a)return d(b,c,"ltr");for(var e=!1,f=0;fb||b==c&&g.to==b)&&(d(Math.max(g.from,b),Math.min(g.to,c),1==g.level?"rtl":"ltr"),e=!0)}e||d(b,c,"ltr")}function Pg(a){return a.level%2?a.to:a.from}function Qg(a){return a.level%2?a.from:a.to}function Rg(a){var b=nf(a);return b?Pg(b[0]):0}function Sg(a){var b=nf(a);return b?Qg(bg(b)):a.text.length}function Tg(a,b){var c=ff(a.doc,b),d=se(c);d!=c&&(b=kf(d));var e=nf(d),f=e?e[0].level%2?Sg(d):Rg(d):0;return oa(b,f)}function Ug(a,b){for(var c,d=ff(a.doc,b);c=qe(d);)d=c.find(1,!0).line,b=null;var e=nf(d),f=e?e[0].level%2?Rg(d):Sg(d):d.text.length;return oa(null==b?kf(d):b,f)}function Vg(a,b){var c=Tg(a,b.line),d=ff(a.doc,c.line),e=nf(d);if(!e||0==e[0].level){var f=Math.max(0,d.text.search(/\S/)),g=b.line==c.line&&b.ch<=f&&b.ch;return oa(c.line,g?0:f)}return c}function Wg(a,b,c){var d=a[0].level;return b==d?!0:c==d?!1:c>b}function Yg(a,b){Xg=null;for(var d,c=0;cb)return c;if(e.from==b||e.to==b){if(null!=d)return Wg(a,e.level,a[d].level)?(e.from!=e.to&&(Xg=d),c):(e.from!=e.to&&(Xg=c),d);d=c}}return d}function Zg(a,b,c,d){if(!d)return b+c;do b+=c;while(b>0&&og(a.text.charAt(b)));return b}function $g(a,b,c,d){var e=nf(a);if(!e)return _g(a,b,c,d);for(var f=Yg(e,b),g=e[f],h=Zg(a,b,g.level%2?-c:c,d);;){if(h>g.from&&h0==g.level%2?g.to:g.from);if(g=e[f+=c],!g)return null;h=c>0==g.level%2?Zg(a,g.to,-1,d):Zg(a,g.from,1,d)}}function _g(a,b,c,d){var e=b+c;if(d)for(;e>0&&og(a.text.charAt(e));)e+=c;return 0>e||e>a.text.length?null:e}var a=/gecko\/\d/i.test(navigator.userAgent),b=/MSIE \d/.test(navigator.userAgent),c=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),d=b||c,e=d&&(b?document.documentMode||6:c[1]),f=/WebKit\//.test(navigator.userAgent),g=f&&/Qt\/\d+\.\d+/.test(navigator.userAgent),h=/Chrome\//.test(navigator.userAgent),i=/Opera\//.test(navigator.userAgent),j=/Apple Computer/.test(navigator.vendor),k=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),l=/PhantomJS/.test(navigator.userAgent),m=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),n=m||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),o=m||/Mac/.test(navigator.platform),p=/win/i.test(navigator.platform),q=i&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);q&&(q=Number(q[1])),q&&q>=15&&(i=!1,f=!0);var r=o&&(g||i&&(null==q||12.11>q)),s=a||d&&e>=9,t=!1,u=!1;K.prototype=hg({update:function(a){var b=a.scrollWidth>a.clientWidth+1,c=a.scrollHeight>a.clientHeight+1,d=a.nativeBarWidth;if(c){this.vert.style.display="block",this.vert.style.bottom=b?d+"px":"0";var e=a.viewHeight-(b?d:0);this.vert.firstChild.style.height=Math.max(0,a.scrollHeight-a.clientHeight+e)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(b){this.horiz.style.display="block",this.horiz.style.right=c?d+"px":"0",this.horiz.style.left=a.barLeft+"px";var f=a.viewWidth-a.barLeft-(c?d:0);this.horiz.firstChild.style.width=a.scrollWidth-a.clientWidth+f+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedOverlay&&a.clientHeight>0&&(0==d&&this.overlayHack(),this.checkedOverlay=!0),{right:c?d:0,bottom:b?d:0}},setScrollLeft:function(a){this.horiz.scrollLeft!=a&&(this.horiz.scrollLeft=a)},setScrollTop:function(a){this.vert.scrollTop!=a&&(this.vert.scrollTop=a)},overlayHack:function(){var a=o&&!k?"12px":"18px";this.horiz.style.minHeight=this.vert.style.minWidth=a;var b=this,c=function(a){Hf(a)!=b.vert&&Hf(a)!=b.horiz&&dc(b.cm,uc)(a)};Jf(this.vert,"mousedown",c),Jf(this.horiz,"mousedown",c)},clear:function(){var a=this.horiz.parentNode;a.removeChild(this.horiz),a.removeChild(this.vert)}},K.prototype),L.prototype=hg({update:function(){return{bottom:0,right:0}},setScrollLeft:function(){},setScrollTop:function(){},clear:function(){}},L.prototype),v.scrollbarModel={"native":K,"null":L},U.prototype.signal=function(a,b){Rf(a,b)&&this.events.push(arguments)},U.prototype.finish=function(){for(var a=0;a=9&&b.hasSelection&&(b.hasSelection=null),b.poll()}),Jf(g,"paste",function(a){return xa(a,c)?!0:(c.state.pasteIncoming=!0,void b.fastPoll())}),Jf(g,"cut",h),Jf(g,"copy",h),Jf(a.scroller,"paste",function(d){sc(a,d)||(c.state.pasteIncoming=!0,b.focus())}),Jf(a.lineSpace,"selectstart",function(b){sc(a,b)||Df(b)}),Jf(g,"compositionstart",function(){var a=c.getCursor("from");b.composing&&b.composing.range.clear(), +b.composing={start:a,range:c.markText(a,c.getCursor("to"),{className:"CodeMirror-composing"})}}),Jf(g,"compositionend",function(){b.composing&&(b.poll(),b.composing.range.clear(),b.composing=null)})},prepareSelection:function(){var a=this.cm,b=a.display,c=a.doc,d=eb(a);if(a.options.moveInputWithCursor){var e=Lb(a,c.sel.primary().head,"div"),f=b.wrapper.getBoundingClientRect(),g=b.lineDiv.getBoundingClientRect();d.teTop=Math.max(0,Math.min(b.wrapper.clientHeight-10,e.top+g.top-f.top)),d.teLeft=Math.max(0,Math.min(b.wrapper.clientWidth-10,e.left+g.left-f.left))}return d},showSelection:function(a){var b=this.cm,c=b.display;sg(c.cursorDiv,a.cursors),sg(c.selectionDiv,a.selection),null!=a.teTop&&(this.wrapper.style.top=a.teTop+"px",this.wrapper.style.left=a.teLeft+"px")},reset:function(a){if(!this.contextMenuPending){var b,c,f=this.cm,g=f.doc;if(f.somethingSelected()){this.prevInput="";var h=g.sel.primary();b=Kg&&(h.to().line-h.from().line>100||(c=f.getSelection()).length>1e3);var i=b?"-":c||f.getSelection();this.textarea.value=i,f.state.focused&&cg(this.textarea),d&&e>=9&&(this.hasSelection=i)}else a||(this.prevInput=this.textarea.value="",d&&e>=9&&(this.hasSelection=null));this.inaccurateSelection=b}},getField:function(){return this.textarea},supportsTouch:function(){return!1},focus:function(){if("nocursor"!=this.cm.options.readOnly&&(!n||ug()!=this.textarea))try{this.textarea.focus()}catch(a){}},blur:function(){this.textarea.blur()},resetPosition:function(){this.wrapper.style.top=this.wrapper.style.left=0},receivedFocus:function(){this.slowPoll()},slowPoll:function(){var a=this;a.pollingFast||a.polling.set(this.cm.options.pollInterval,function(){a.poll(),a.cm.state.focused&&a.slowPoll()})},fastPoll:function(){function c(){var d=b.poll();d||a?(b.pollingFast=!1,b.slowPoll()):(a=!0,b.polling.set(60,c))}var a=!1,b=this;b.pollingFast=!0,b.polling.set(20,c)},poll:function(){var a=this.cm,b=this.textarea,c=this.prevInput;if(this.contextMenuPending||!a.state.focused||Jg(b)&&!c&&!this.composing||ua(a)||a.options.disableInput||a.state.keySeq)return!1;var f=b.value;if(f==c&&!a.somethingSelected())return!1;if(d&&e>=9&&this.hasSelection===f||o&&/[\uf700-\uf7ff]/.test(f))return a.display.input.reset(),!1;if(a.doc.sel==a.display.selForContextMenu){var g=f.charCodeAt(0);if(8203!=g||c||(c="\u200b"),8666==g)return this.reset(),this.cm.execCommand("undo")}for(var h=0,i=Math.min(c.length,f.length);i>h&&c.charCodeAt(h)==f.charCodeAt(h);)++h;var j=this;return cc(a,function(){wa(a,f.slice(h),c.length-h,null,j.composing?"*compose":null),f.length>1e3||f.indexOf("\n")>-1?b.value=j.prevInput="":j.prevInput=f,j.composing&&(j.composing.range.clear(),j.composing.range=a.markText(j.composing.start,a.getCursor("to"),{className:"CodeMirror-composing"}))}),!0},ensurePolled:function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},onKeyPress:function(){d&&e>=9&&(this.hasSelection=null),this.fastPoll()},onContextMenu:function(a){function o(){if(null!=h.selectionStart){var a=c.somethingSelected(),d="\u200b"+(a?h.value:"");h.value="\u21da",h.value=d,b.prevInput=a?"":"\u200b",h.selectionStart=1,h.selectionEnd=d.length,g.selForContextMenu=c.doc.sel}}function p(){if(b.contextMenuPending=!1,b.wrapper.style.position="relative",h.style.cssText=m,d&&9>e&&g.scrollbars.setScrollTop(g.scroller.scrollTop=k),null!=h.selectionStart){(!d||d&&9>e)&&o();var a=0,f=function(){g.selForContextMenu==c.doc.sel&&0==h.selectionStart&&h.selectionEnd>0&&"\u200b"==b.prevInput?dc(c,Ld.selectAll)(c):a++<10?g.detectingSelectAll=setTimeout(f,500):g.input.reset()};g.detectingSelectAll=setTimeout(f,200)}}var b=this,c=b.cm,g=c.display,h=b.textarea,j=tc(c,a),k=g.scroller.scrollTop;if(j&&!i){var l=c.options.resetSelectionOnContextMenu;l&&-1==c.doc.sel.contains(j)&&dc(c,Za)(c.doc,Ma(j),Vf);var m=h.style.cssText;if(b.wrapper.style.position="absolute",h.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(a.clientY-5)+"px; left: "+(a.clientX-5)+"px; z-index: 1000; background: "+(d?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",f)var n=window.scrollY;if(g.input.focus(),f&&window.scrollTo(null,n),g.input.reset(),c.somethingSelected()||(h.value=b.prevInput=" "),b.contextMenuPending=!0,g.selForContextMenu=c.doc.sel,clearTimeout(g.detectingSelectAll),d&&e>=9&&o(),s){Gf(a);var q=function(){Kf(window,"mouseup",q),setTimeout(p,20)};Jf(window,"mouseup",q)}else setTimeout(p,50)}},setUneditable:fg,needsContentAttribute:!1},Ba.prototype),Da.prototype=hg({init:function(a){function e(a){if(c.somethingSelected())va=c.getSelections(),"cut"==a.type&&c.replaceSelection("",null,"cut");else{if(!c.options.lineWiseCopyCut)return;var b=za(c);va=b.text,"cut"==a.type&&c.operation(function(){c.setSelections(b.ranges,0,Vf),c.replaceSelection("",null,"cut")})}if(a.clipboardData&&!m)a.preventDefault(),a.clipboardData.clearData(),a.clipboardData.setData("text/plain",va.join("\n"));else{var d=Ca(),e=d.firstChild;c.display.lineSpace.insertBefore(d,c.display.lineSpace.firstChild),e.value=va.join("\n");var f=document.activeElement;cg(e),setTimeout(function(){c.display.lineSpace.removeChild(d),f.focus()},50)}}var b=this,c=b.cm,d=b.div=a.lineDiv;d.contentEditable="true",Aa(d),Jf(d,"paste",function(a){xa(a,c)}),Jf(d,"compositionstart",function(a){var d=a.data;if(b.composing={sel:c.doc.sel,data:d,startData:d},d){var e=c.doc.sel.primary(),f=c.getLine(e.head.line),g=f.indexOf(d,Math.max(0,e.head.ch-d.length));g>-1&&g<=e.head.ch&&(b.composing.sel=Ma(oa(e.head.line,g),oa(e.head.line,g+d.length)))}}),Jf(d,"compositionupdate",function(a){b.composing.data=a.data}),Jf(d,"compositionend",function(a){var c=b.composing;c&&(a.data==c.startData||/\u200b/.test(a.data)||(c.data=a.data),setTimeout(function(){c.handled||b.applyComposition(c),b.composing==c&&(b.composing=null)},50))}),Jf(d,"touchstart",function(){b.forceCompositionEnd()}),Jf(d,"input",function(){b.composing||b.pollContent()||cc(b.cm,function(){ic(c)})}),Jf(d,"copy",e),Jf(d,"cut",e)},prepareSelection:function(){var a=eb(this.cm,!1);return a.focus=this.cm.state.focused,a},showSelection:function(a){a&&this.cm.display.view.length&&(a.focus&&this.showPrimarySelection(),this.showMultipleSelections(a))},showPrimarySelection:function(){var b=window.getSelection(),c=this.cm.doc.sel.primary(),d=Ga(this.cm,b.anchorNode,b.anchorOffset),e=Ga(this.cm,b.focusNode,b.focusOffset);if(!d||d.bad||!e||e.bad||0!=pa(sa(d,e),c.from())||0!=pa(ra(d,e),c.to())){var f=Ea(this.cm,c.from()),g=Ea(this.cm,c.to());if(f||g){var h=this.cm.display.view,i=b.rangeCount&&b.getRangeAt(0);if(f){if(!g){var j=h[h.length-1].measure,k=j.maps?j.maps[j.maps.length-1]:j.map;g={node:k[k.length-1],offset:k[k.length-2]-k[k.length-3]}}}else f={node:h[0].measure.map[2],offset:0};try{var l=qg(f.node,f.offset,g.offset,g.node)}catch(m){}l&&(b.removeAllRanges(),b.addRange(l),i&&null==b.anchorNode?b.addRange(i):a&&this.startGracePeriod()),this.rememberSelection()}}},startGracePeriod:function(){var a=this;clearTimeout(this.gracePeriod),this.gracePeriod=setTimeout(function(){a.gracePeriod=!1,a.selectionChanged()&&a.cm.operation(function(){a.cm.curOp.selectionChanged=!0})},20)},showMultipleSelections:function(a){sg(this.cm.display.cursorDiv,a.cursors),sg(this.cm.display.selectionDiv,a.selection)},rememberSelection:function(){var a=window.getSelection();this.lastAnchorNode=a.anchorNode,this.lastAnchorOffset=a.anchorOffset,this.lastFocusNode=a.focusNode,this.lastFocusOffset=a.focusOffset},selectionInEditor:function(){var a=window.getSelection();if(!a.rangeCount)return!1;var b=a.getRangeAt(0).commonAncestorContainer;return tg(this.div,b)},focus:function(){"nocursor"!=this.cm.options.readOnly&&this.div.focus()},blur:function(){this.div.blur()},getField:function(){return this.div},supportsTouch:function(){return!0},receivedFocus:function(){function b(){a.cm.state.focused&&(a.pollSelection(),a.polling.set(a.cm.options.pollInterval,b))}var a=this;this.selectionInEditor()?this.pollSelection():cc(this.cm,function(){a.cm.curOp.selectionChanged=!0}),this.polling.set(this.cm.options.pollInterval,b)},selectionChanged:function(){var a=window.getSelection();return a.anchorNode!=this.lastAnchorNode||a.anchorOffset!=this.lastAnchorOffset||a.focusNode!=this.lastFocusNode||a.focusOffset!=this.lastFocusOffset},pollSelection:function(){if(!this.composing&&!this.gracePeriod&&this.selectionChanged()){var a=window.getSelection(),b=this.cm;this.rememberSelection();var c=Ga(b,a.anchorNode,a.anchorOffset),d=Ga(b,a.focusNode,a.focusOffset);c&&d&&cc(b,function(){Za(b.doc,Ma(c,d),Vf),(c.bad||d.bad)&&(b.curOp.selectionChanged=!0)})}},pollContent:function(){var a=this.cm,b=a.display,c=a.doc.sel.primary(),d=c.from(),e=c.to();if(d.lineb.viewTo-1)return!1;var f;if(d.line==b.viewFrom||0==(f=lc(a,d.line)))var g=kf(b.view[0].line),h=b.view[0].node;else var g=kf(b.view[f].line),h=b.view[f-1].node.nextSibling;var i=lc(a,e.line);if(i==b.view.length-1)var j=b.viewTo-1,k=b.lineDiv.lastChild;else var j=kf(b.view[i+1].line)-1,k=b.view[i+1].node.previousSibling;for(var l=a.doc.splitLines(Ia(a,h,k,g,j)),m=gf(a.doc,oa(g,0),oa(j,ff(a.doc,j).text.length));l.length>1&&m.length>1;)if(bg(l)==bg(m))l.pop(),m.pop(),j--;else{if(l[0]!=m[0])break;l.shift(),m.shift(),g++}for(var n=0,o=0,p=l[0],q=m[0],r=Math.min(p.length,q.length);r>n&&p.charCodeAt(n)==q.charCodeAt(n);)++n;for(var s=bg(l),t=bg(m),u=Math.min(s.length-(1==l.length?n:0),t.length-(1==m.length?n:0));u>o&&s.charCodeAt(s.length-o-1)==t.charCodeAt(t.length-o-1);)++o;l[l.length-1]=s.slice(0,s.length-o),l[0]=l[0].slice(n);var v=oa(g,n),w=oa(j,m.length?bg(m).length-o:0);return l.length>1||l[0]||pa(v,w)?(nd(a.doc,l,v,w,"+input"),!0):void 0},ensurePolled:function(){this.forceCompositionEnd()},reset:function(){this.forceCompositionEnd()},forceCompositionEnd:function(){this.composing&&!this.composing.handled&&(this.applyComposition(this.composing),this.composing.handled=!0,this.div.blur(),this.div.focus())},applyComposition:function(a){a.data&&a.data!=a.startData&&dc(this.cm,wa)(this.cm,a.data,0,a.sel)},setUneditable:function(a){a.setAttribute("contenteditable","false")},onKeyPress:function(a){a.preventDefault(),dc(this.cm,wa)(this.cm,String.fromCharCode(null==a.charCode?a.keyCode:a.charCode),0)},onContextMenu:fg,resetPosition:fg,needsContentAttribute:!0},Da.prototype),v.inputStyles={textarea:Ba,contenteditable:Da},Ja.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(a){if(a==this)return!0;if(a.primIndex!=this.primIndex||a.ranges.length!=this.ranges.length)return!1;for(var b=0;b=0&&pa(a,d.to())<=0)return c}return-1}},Ka.prototype={from:function(){return sa(this.anchor,this.head)},to:function(){return ra(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var Qb,vc,wc,zb={left:0,right:0,top:0,bottom:0},Tb=null,Ub=0,Cc=0,Jc=0,Kc=null;d?Kc=-.53:a?Kc=15:h?Kc=-.7:j&&(Kc=-1/3);var Lc=function(a){var b=a.wheelDeltaX,c=a.wheelDeltaY;return null==b&&a.detail&&a.axis==a.HORIZONTAL_AXIS&&(b=a.detail),null==c&&a.detail&&a.axis==a.VERTICAL_AXIS?c=a.detail:null==c&&(c=a.wheelDelta),{x:b,y:c}};v.wheelEventPixels=function(a){var b=Lc(a);return b.x*=Kc,b.y*=Kc,b};var Pc=new Yf,Tc=null,bd=v.changeEnd=function(a){return a.text?oa(a.from.line+a.text.length-1,bg(a.text).length+(1==a.text.length?a.from.ch:0)):a.to};v.prototype={constructor:v,focus:function(){window.focus(),this.display.input.focus()},setOption:function(a,b){var c=this.options,d=c[a];(c[a]!=b||"mode"==a)&&(c[a]=b,Bd.hasOwnProperty(a)&&dc(this,Bd[a])(this,b,d))},getOption:function(a){return this.options[a]},getDoc:function(){return this.doc},addKeyMap:function(a,b){this.state.keyMaps[b?"push":"unshift"](Rd(a))},removeKeyMap:function(a){for(var b=this.state.keyMaps,c=0;cc&&(vd(this,e.head.line,a,!0),c=e.head.line,d==this.doc.sel.primIndex&&td(this));else{var f=e.from(),g=e.to(),h=Math.max(c,f.line);c=Math.min(this.lastLine(),g.line-(g.ch?0:1))+1;for(var i=h;c>i;++i)vd(this,i,a);var j=this.doc.sel.ranges;0==f.ch&&b.length==j.length&&j[d].from().ch>0&&Va(this.doc,d,new Ka(f,j[d].to()),Vf)}}}),getTokenAt:function(a,b){return Ie(this,a,b)},getLineTokens:function(a,b){return Ie(this,oa(a),b,!0)},getTokenTypeAt:function(a){a=Oa(this.doc,a);var f,b=Le(this,ff(this.doc,a.line)),c=0,d=(b.length-1)/2,e=a.ch;if(0==e)f=b[2];else for(;;){var g=c+d>>1;if((g?b[2*g-1]:0)>=e)d=g;else{if(!(b[2*g+1]h?f:0==h?null:f.slice(0,h-1)},getModeAt:function(a){var b=this.doc.mode;return b.innerMode?v.innerMode(b,this.getTokenAt(a).state).mode:b},getHelper:function(a,b){return this.getHelpers(a,b)[0]},getHelpers:function(a,b){var c=[];if(!Id.hasOwnProperty(b))return c;var d=Id[b],e=this.getModeAt(a);if("string"==typeof e[b])d[e[b]]&&c.push(d[e[b]]);else if(e[b])for(var f=0;fe&&(a=e,c=!0),d=ff(this.doc,a)}else d=a;return Ib(this,d,{top:0,left:0},b||"page").top+(c?this.doc.height-mf(d):0)},defaultTextHeight:function(){return Rb(this.display)},defaultCharWidth:function(){return Sb(this.display)},setGutterMarker:ec(function(a,b,c){return wd(this.doc,a,"gutter",function(a){var d=a.gutterMarkers||(a.gutterMarkers={});return d[b]=c,!c&&mg(d)&&(a.gutterMarkers=null),!0})}),clearGutter:ec(function(a){var b=this,c=b.doc,d=c.first;c.iter(function(c){c.gutterMarkers&&c.gutterMarkers[a]&&(c.gutterMarkers[a]=null,jc(b,d,"gutter"),mg(c.gutterMarkers)&&(c.gutterMarkers=null)),++d})}),lineInfo:function(a){if("number"==typeof a){if(!Qa(this.doc,a))return null;var b=a;if(a=ff(this.doc,a),!a)return null}else{var b=kf(a);if(null==b)return null}return{line:b,handle:a,text:a.text,gutterMarkers:a.gutterMarkers,textClass:a.textClass,bgClass:a.bgClass,wrapClass:a.wrapClass,widgets:a.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(a,b,c,d,e){var f=this.display;a=Lb(this,Oa(this.doc,a));var g=a.bottom,h=a.left;if(b.style.position="absolute",b.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(b),f.sizer.appendChild(b),"over"==d)g=a.top;else if("above"==d||"near"==d){var i=Math.max(f.wrapper.clientHeight,this.doc.height),j=Math.max(f.sizer.clientWidth,f.lineSpace.clientWidth);("above"==d||a.bottom+b.offsetHeight>i)&&a.top>b.offsetHeight?g=a.top-b.offsetHeight:a.bottom+b.offsetHeight<=i&&(g=a.bottom),h+b.offsetWidth>j&&(h=j-b.offsetWidth)}b.style.top=g+"px",b.style.left=b.style.right="","right"==e?(h=f.sizer.clientWidth-b.offsetWidth,b.style.right="0px"):("left"==e?h=0:"middle"==e&&(h=(f.sizer.clientWidth-b.offsetWidth)/2),b.style.left=h+"px"),c&&qd(this,h,g,h+b.offsetWidth,g+b.offsetHeight)},triggerOnKeyDown:ec(Uc),triggerOnKeyPress:ec(Xc),triggerOnKeyUp:Wc,execCommand:function(a){return Ld.hasOwnProperty(a)?Ld[a].call(null,this):void 0},triggerElectric:ec(function(a){ya(this,a)}),findPosH:function(a,b,c,d){var e=1;0>b&&(e=-1,b=-b);for(var f=0,g=Oa(this.doc,a);b>f&&(g=yd(this.doc,g,e,c,d),!g.hitSide);++f);return g},moveH:ec(function(a,b){var c=this;c.extendSelectionsBy(function(d){return c.display.shift||c.doc.extend||d.empty()?yd(c.doc,d.head,a,b,c.options.rtlMoveVisually):0>a?d.from():d.to()},Xf)}),deleteH:ec(function(a,b){var c=this.doc.sel,d=this.doc;c.somethingSelected()?d.replaceSelection("",null,"+delete"):xd(this,function(c){var e=yd(d,c.head,a,b,!1);return 0>a?{from:e,to:c.head}:{from:c.head,to:e}})}),findPosV:function(a,b,c,d){var e=1,f=d;0>b&&(e=-1,b=-b);for(var g=0,h=Oa(this.doc,a);b>g;++g){var i=Lb(this,h,"div");if(null==f?f=i.left:i.left=f,h=zd(this,i,e,c),h.hitSide)break}return h},moveV:ec(function(a,b){var c=this,d=this.doc,e=[],f=!c.display.shift&&!d.extend&&d.sel.somethingSelected();if(d.extendSelectionsBy(function(g){if(f)return 0>a?g.from():g.to();var h=Lb(c,g.head,"div");null!=g.goalColumn&&(h.left=g.goalColumn),e.push(h.left);var i=zd(c,h,a,b);return"page"==b&&g==d.sel.primary()&&sd(c,null,Kb(c,i,"div").top-h.top),i},Xf),e.length)for(var g=0;g0&&h(c.charAt(d-1));)--d;for(;e.5)&&B(this),Lf(this,"refresh",this)}),swapDoc:ec(function(a){var b=this.doc;return b.cm=null,ef(this,a),Fb(this),this.display.input.reset(),this.scrollTo(a.scrollLeft,a.scrollTop),this.curOp.forceScroll=!0,Nf(this,"swapDoc",this,b),b}),getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},Sf(v);var Ad=v.defaults={},Bd=v.optionHandlers={},Dd=v.Init={toString:function(){return"CodeMirror.Init"}};Cd("value","",function(a,b){a.setValue(b)},!0),Cd("mode",null,function(a,b){a.doc.modeOption=b,x(a)},!0),Cd("indentUnit",2,x,!0),Cd("indentWithTabs",!1),Cd("smartIndent",!0),Cd("tabSize",4,function(a){y(a),Fb(a),ic(a)},!0),Cd("lineSeparator",null,function(a,b){if(a.doc.lineSep=b,b){var c=[],d=a.doc.first;a.doc.iter(function(a){for(var e=0;;){var f=a.text.indexOf(b,e);if(-1==f)break;e=f+b.length,c.push(oa(d,f))}d++});for(var e=c.length-1;e>=0;e--)nd(a.doc,b,c[e],oa(c[e].line,c[e].ch+b.length))}}),Cd("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(a,b,c){a.state.specialChars=new RegExp(b.source+(b.test(" ")?"":"| "),"g"),c!=v.Init&&a.refresh()}),Cd("specialCharPlaceholder",Re,function(a){a.refresh()},!0),Cd("electricChars",!0),Cd("inputStyle",n?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},!0),Cd("rtlMoveVisually",!p),Cd("wholeLineUpdateBefore",!0),Cd("theme","default",function(a){C(a),D(a)},!0),Cd("keyMap","default",function(a,b,c){var d=Rd(b),e=c!=v.Init&&Rd(c);e&&e.detach&&e.detach(a,d),d.attach&&d.attach(a,e||null)}),Cd("extraKeys",null),Cd("lineWrapping",!1,z,!0),Cd("gutters",[],function(a){I(a.options),D(a)},!0),Cd("fixedGutter",!0,function(a,b){a.display.gutters.style.left=b?T(a.display)+"px":"0",a.refresh()},!0),Cd("coverGutterNextToScrollbar",!1,function(a){N(a)},!0),Cd("scrollbarStyle","native",function(a){M(a),N(a),a.display.scrollbars.setScrollTop(a.doc.scrollTop),a.display.scrollbars.setScrollLeft(a.doc.scrollLeft)},!0),Cd("lineNumbers",!1,function(a){I(a.options),D(a)},!0),Cd("firstLineNumber",1,D,!0),Cd("lineNumberFormatter",function(a){return a},D,!0),Cd("showCursorWhenSelecting",!1,db,!0),Cd("resetSelectionOnContextMenu",!0),Cd("lineWiseCopyCut",!0),Cd("readOnly",!1,function(a,b){"nocursor"==b?($c(a),a.display.input.blur(),a.display.disabled=!0):(a.display.disabled=!1,b||a.display.input.reset())}),Cd("disableInput",!1,function(a,b){b||a.display.input.reset()},!0),Cd("dragDrop",!0,qc),Cd("cursorBlinkRate",530),Cd("cursorScrollMargin",0),Cd("cursorHeight",1,db,!0),Cd("singleCursorHeightPerLine",!0,db,!0),Cd("workTime",100),Cd("workDelay",100),Cd("flattenSpans",!0,y,!0),Cd("addModeClass",!1,y,!0),Cd("pollInterval",100),Cd("undoDepth",200,function(a,b){a.doc.history.undoDepth=b}),Cd("historyEventDelay",1250),Cd("viewportMargin",10,function(a){a.refresh()},!0),Cd("maxHighlightLength",1e4,y,!0),Cd("moveInputWithCursor",!0,function(a,b){b||a.display.input.resetPosition()}),Cd("tabindex",null,function(a,b){a.display.input.getField().tabIndex=b||""}),Cd("autofocus",null);var Ed=v.modes={},Fd=v.mimeModes={};v.defineMode=function(a,b){v.defaults.mode||"null"==a||(v.defaults.mode=a),arguments.length>2&&(b.dependencies=Array.prototype.slice.call(arguments,2)),Ed[a]=b},v.defineMIME=function(a,b){Fd[a]=b},v.resolveMode=function(a){if("string"==typeof a&&Fd.hasOwnProperty(a))a=Fd[a];else if(a&&"string"==typeof a.name&&Fd.hasOwnProperty(a.name)){var b=Fd[a.name];"string"==typeof b&&(b={name:b}),a=gg(b,a),a.name=b.name}else if("string"==typeof a&&/^[\w\-]+\/[\w\-]+\+xml$/.test(a))return v.resolveMode("application/xml");return"string"==typeof a?{name:a}:a||{name:"null"}},v.getMode=function(a,b){var b=v.resolveMode(b),c=Ed[b.name];if(!c)return v.getMode(a,"text/plain");var d=c(a,b);if(Gd.hasOwnProperty(b.name)){var e=Gd[b.name];for(var f in e)e.hasOwnProperty(f)&&(d.hasOwnProperty(f)&&(d["_"+f]=d[f]),d[f]=e[f])}if(d.name=b.name,b.helperType&&(d.helperType=b.helperType),b.modeProps)for(var f in b.modeProps)d[f]=b.modeProps[f];return d},v.defineMode("null",function(){return{token:function(a){a.skipToEnd()}}}),v.defineMIME("text/plain","null");var Gd=v.modeExtensions={};v.extendMode=function(a,b){var c=Gd.hasOwnProperty(a)?Gd[a]:Gd[a]={};hg(b,c)},v.defineExtension=function(a,b){v.prototype[a]=b},v.defineDocExtension=function(a,b){af.prototype[a]=b},v.defineOption=Cd;var Hd=[];v.defineInitHook=function(a){Hd.push(a)};var Id=v.helpers={};v.registerHelper=function(a,b,c){Id.hasOwnProperty(a)||(Id[a]=v[a]={_global:[]}),Id[a][b]=c},v.registerGlobalHelper=function(a,b,c,d){v.registerHelper(a,b,d),Id[a]._global.push({pred:c,val:d})};var Jd=v.copyState=function(a,b){if(b===!0)return b;if(a.copyState)return a.copyState(b);var c={};for(var d in b){var e=b[d];e instanceof Array&&(e=e.concat([])),c[d]=e}return c},Kd=v.startState=function(a,b,c){return a.startState?a.startState(b,c):!0};v.innerMode=function(a,b){for(;a.innerMode;){var c=a.innerMode(b);if(!c||c.mode==a)break;b=c.state,a=c.mode}return c||{mode:a,state:b}};var Ld=v.commands={selectAll:function(a){a.setSelection(oa(a.firstLine(),0),oa(a.lastLine()),Vf)},singleSelection:function(a){a.setSelection(a.getCursor("anchor"),a.getCursor("head"),Vf)},killLine:function(a){xd(a,function(b){if(b.empty()){var c=ff(a.doc,b.head.line).text.length;return b.head.ch==c&&b.head.line0)e=new oa(e.line,e.ch+1),a.replaceRange(f.charAt(e.ch-1)+f.charAt(e.ch-2),oa(e.line,e.ch-2),e,"+transpose");else if(e.line>a.doc.first){var g=ff(a.doc,e.line-1).text;g&&a.replaceRange(f.charAt(0)+a.doc.lineSeparator()+g.charAt(g.length-1),oa(e.line-1,g.length-1),oa(e.line,1),"+transpose")}c.push(new Ka(e,e))}a.setSelections(c)})},newlineAndIndent:function(a){cc(a,function(){for(var b=a.listSelections().length,c=0;b>c;c++){var d=a.listSelections()[c];a.replaceRange(a.doc.lineSeparator(),d.anchor,d.head,"+input"),a.indentLine(d.from().line+1,null,!0),td(a)}})},toggleOverwrite:function(a){a.toggleOverwrite()}},Md=v.keyMap={};Md.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},Md.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},Md.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars"},Md.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection", +"Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},Md["default"]=o?Md.macDefault:Md.pcDefault,v.normalizeKeyMap=function(a){var b={};for(var c in a)if(a.hasOwnProperty(c)){var d=a[c];if(/^(name|fallthrough|(de|at)tach)$/.test(c))continue;if("..."==d){delete a[c];continue}for(var e=eg(c.split(" "),Nd),f=0;f=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.posb},eatSpace:function(){for(var a=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>a},skipToEnd:function(){this.pos=this.string.length},skipTo:function(a){var b=this.string.indexOf(a,this.pos);return b>-1?(this.pos=b,!0):void 0},backUp:function(a){this.pos-=a},column:function(){return this.lastColumnPos0?null:(f&&b!==!1&&(this.pos+=f[0].length),f)}var d=function(a){return c?a.toLowerCase():a},e=this.string.substr(this.pos,a.length);return d(e)==d(a)?(b!==!1&&(this.pos+=a.length),!0):void 0},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(a,b){this.lineStart+=a;try{return b()}finally{this.lineStart-=a}}};var Td=0,Ud=v.TextMarker=function(a,b){this.lines=[],this.type=b,this.doc=a,this.id=++Td};Sf(Ud),Ud.prototype.clear=function(){if(!this.explicitlyCleared){var a=this.doc.cm,b=a&&!a.curOp;if(b&&Vb(a),Rf(this,"clear")){var c=this.find();c&&Nf(this,"clear",c.from,c.to)}for(var d=null,e=null,f=0;fa.display.maxLineLength&&(a.display.maxLine=i,a.display.maxLineLength=j,a.display.maxLineChanged=!0)}null!=d&&a&&this.collapsed&&ic(a,d,e+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,a&&ab(a.doc)),a&&Nf(a,"markerCleared",a,this),b&&Xb(a),this.parent&&this.parent.clear()}},Ud.prototype.find=function(a,b){null==a&&"bookmark"==this.type&&(a=1);for(var c,d,e=0;ec;++c){var e=this.lines[c];this.height-=e.height,Ee(e),Nf(e,"delete")}this.lines.splice(a,b)},collapse:function(a){a.push.apply(a,this.lines)},insertInner:function(a,b,c){this.height+=c,this.lines=this.lines.slice(0,a).concat(b).concat(this.lines.slice(a));for(var d=0;da;++a)if(c(this.lines[a]))return!0}},$e.prototype={chunkSize:function(){return this.size},removeInner:function(a,b){this.size-=b;for(var c=0;ca){var f=Math.min(b,e-a),g=d.height;if(d.removeInner(a,f),this.height-=g-d.height,e==f&&(this.children.splice(c--,1),d.parent=null),0==(b-=f))break;a=0}else a-=e}if(this.size-b<25&&(this.children.length>1||!(this.children[0]instanceof Ze))){var h=[];this.collapse(h),this.children=[new Ze(h)],this.children[0].parent=this}},collapse:function(a){for(var b=0;b=a){if(e.insertInner(a,b,c),e.lines&&e.lines.length>50){for(;e.lines.length>50;){var g=e.lines.splice(e.lines.length-25,25),h=new Ze(g);e.height-=h.height,this.children.splice(d+1,0,h),h.parent=this}this.maybeSpill()}break}a-=f}},maybeSpill:function(){if(!(this.children.length<=10)){var a=this;do{var b=a.children.splice(a.children.length-5,5),c=new $e(b);if(a.parent){a.size-=c.size,a.height-=c.height;var e=dg(a.parent.children,a);a.parent.children.splice(e+1,0,c)}else{var d=new $e(a.children);d.parent=a,a.children=[d,c],a=d}c.parent=a.parent}while(a.children.length>10);a.parent.maybeSpill()}},iterN:function(a,b,c){for(var d=0;da){var g=Math.min(b,f-a);if(e.iterN(a,g,c))return!0;if(0==(b-=g))break;a=0}else a-=f}}};var _e=0,af=v.Doc=function(a,b,c,d){if(!(this instanceof af))return new af(a,b,c,d);null==c&&(c=0),$e.call(this,[new Ze([new Ce("",null)])]),this.first=c,this.scrollTop=this.scrollLeft=0,this.cantEdit=!1,this.cleanGeneration=1,this.frontier=c;var e=oa(c,0);this.sel=Ma(e),this.history=new of(null),this.id=++_e,this.modeOption=b,this.lineSep=d,"string"==typeof a&&(a=this.splitLines(a)),Ye(this,{from:e,to:e,text:a}),Za(this,Ma(e),Vf)};af.prototype=gg($e.prototype,{constructor:af,iter:function(a,b,c){c?this.iterN(a-this.first,b-a,c):this.iterN(this.first,this.first+this.size,a)},insert:function(a,b){for(var c=0,d=0;d=0;f--)hd(this,d[f]);h?Ya(this,h):this.cm&&td(this.cm)}),undo:fc(function(){jd(this,"undo")}),redo:fc(function(){jd(this,"redo")}),undoSelection:fc(function(){jd(this,"undo",!0)}),redoSelection:fc(function(){jd(this,"redo",!0)}),setExtending:function(a){this.extend=a},getExtending:function(){return this.extend},historySize:function(){for(var a=this.history,b=0,c=0,d=0;d=a.ch)&&b.push(e.marker.parent||e.marker)}return b},findMarks:function(a,b,c){a=Oa(this,a),b=Oa(this,b);var d=[],e=a.line;return this.iter(a.line,b.line+1,function(f){var g=f.markedSpans;if(g)for(var h=0;hi.to||null==i.from&&e!=a.line||e==b.line&&i.from>b.ch||c&&!c(i.marker)||d.push(i.marker.parent||i.marker)}++e}),d},getAllMarks:function(){var a=[];return this.iter(function(b){var c=b.markedSpans;if(c)for(var d=0;da?(b=a,!0):(a-=e,void++c)}),Oa(this,oa(c,b))},indexFromPos:function(a){a=Oa(this,a);var b=a.ch;return a.lineb&&(b=a.from),null!=a.to&&a.toh||h>=b)return g+(b-f);g+=h-f,g+=c-g%c,f=h+1}},$f=v.findColumn=function(a,b,c){for(var d=0,e=0;;){var f=a.indexOf(" ",d);-1==f&&(f=a.length);var g=f-d;if(f==a.length||e+g>=b)return d+Math.min(g,b-e);if(e+=f-d,e+=c-e%c,d=f+1,e>=b)return d}},_f=[""],cg=function(a){a.select()};m?cg=function(a){a.selectionStart=0,a.selectionEnd=a.value.length}:d&&(cg=function(a){try{a.select()}catch(b){}});var qg,jg=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,kg=v.isWordChar=function(a){return/\w/.test(a)||a>"\x80"&&(a.toUpperCase()!=a.toLowerCase()||jg.test(a))},ng=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;qg=document.createRange?function(a,b,c,d){var e=document.createRange();return e.setEnd(d||a,c),e.setStart(a,b),e}:function(a,b,c){var d=document.body.createTextRange();try{d.moveToElementText(a.parentNode)}catch(e){return d}return d.collapse(!0),d.moveEnd("character",c),d.moveStart("character",b),d};var tg=v.contains=function(a,b){if(3==b.nodeType&&(b=b.parentNode),a.contains)return a.contains(b);do if(11==b.nodeType&&(b=b.host),b==a)return!0;while(b=b.parentNode)};d&&11>e&&(ug=function(){try{return document.activeElement}catch(a){return document.body}});var Eg,Gg,wg=v.rmClass=function(a,b){var c=a.className,d=vg(b).exec(c);if(d){var e=c.slice(d.index+d[0].length);a.className=c.slice(0,d.index)+(e?d[1]+e:"")}},xg=v.addClass=function(a,b){var c=a.className;vg(b).test(c)||(a.className+=(c?" ":"")+b)},Ag=!1,Dg=function(){if(d&&9>e)return!1;var a=pg("div");return"draggable"in a||"dragDrop"in a}(),Ig=v.splitLines=3!="\n\nb".split(/\n/).length?function(a){for(var b=0,c=[],d=a.length;d>=b;){var e=a.indexOf("\n",b);-1==e&&(e=a.length);var f=a.slice(b,"\r"==a.charAt(e-1)?e-1:e),g=f.indexOf("\r");-1!=g?(c.push(f.slice(0,g)),b+=g+1):(c.push(f),b=e+1)}return c}:function(a){return a.split(/\r\n?|\n/)},Jg=window.getSelection?function(a){try{return a.selectionStart!=a.selectionEnd}catch(b){return!1}}:function(a){try{var b=a.ownerDocument.selection.createRange()}catch(c){}return b&&b.parentElement()==a?0!=b.compareEndPoints("StartToEnd",b):!1},Kg=function(){var a=pg("div");return"oncopy"in a?!0:(a.setAttribute("oncopy","return;"),"function"==typeof a.oncopy)}(),Lg=null,Ng=v.keyNames={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",106:"*",107:"=",109:"-",110:".",111:"/",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};!function(){for(var a=0;10>a;a++)Ng[a+48]=Ng[a+96]=String(a);for(var a=65;90>=a;a++)Ng[a]=String.fromCharCode(a);for(var a=1;12>=a;a++)Ng[a+111]=Ng[a+63235]="F"+a}();var Xg,ah=function(){function c(c){return 247>=c?a.charAt(c):c>=1424&&1524>=c?"R":c>=1536&&1773>=c?b.charAt(c-1536):c>=1774&&2220>=c?"r":c>=8192&&8203>=c?"w":8204==c?"b":"L"}function j(a,b,c){this.level=a,this.from=b,this.to=c}var a="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",b="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",d=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,e=/[stwN]/,f=/[LRr]/,g=/[Lb1n]/,h=/[1n]/,i="L";return function(a){if(!d.test(a))return!1;for(var m,b=a.length,k=[],l=0;b>l;++l)k.push(m=c(a.charCodeAt(l)));for(var l=0,n=i;b>l;++l){var m=k[l];"m"==m?k[l]=n:n=m}for(var l=0,o=i;b>l;++l){var m=k[l];"1"==m&&"r"==o?k[l]="n":f.test(m)&&(o=m,"r"==m&&(k[l]="R"))}for(var l=1,n=k[0];b-1>l;++l){var m=k[l];"+"==m&&"1"==n&&"1"==k[l+1]?k[l]="1":","!=m||n!=k[l+1]||"1"!=n&&"n"!=n||(k[l]=n),n=m}for(var l=0;b>l;++l){var m=k[l];if(","==m)k[l]="N";else if("%"==m){for(var p=l+1;b>p&&"%"==k[p];++p);for(var q=l&&"!"==k[l-1]||b>p&&"1"==k[p]?"1":"N",r=l;p>r;++r)k[r]=q;l=p-1}}for(var l=0,o=i;b>l;++l){var m=k[l];"L"==o&&"1"==m?k[l]="L":f.test(m)&&(o=m)}for(var l=0;b>l;++l)if(e.test(k[l])){for(var p=l+1;b>p&&e.test(k[p]);++p);for(var s="L"==(l?k[l-1]:i),t="L"==(b>p?k[p]:i),q=s||t?"L":"R",r=l;p>r;++r)k[r]=q;l=p-1}for(var v,u=[],l=0;b>l;)if(g.test(k[l])){var w=l;for(++l;b>l&&g.test(k[l]);++l);u.push(new j(0,w,l))}else{var x=l,y=u.length;for(++l;b>l&&"L"!=k[l];++l);for(var r=x;l>r;)if(h.test(k[r])){r>x&&u.splice(y,0,new j(1,x,r));var z=r;for(++r;l>r&&h.test(k[r]);++r);u.splice(y,0,new j(2,z,r)),x=r}else++r;l>x&&u.splice(y,0,new j(1,x,l))}return 1==u[0].level&&(v=a.match(/^\s+/))&&(u[0].from=v[0].length,u.unshift(new j(0,0,v[0].length))),1==bg(u).level&&(v=a.match(/\s+$/))&&(bg(u).to-=v[0].length,u.push(new j(0,b-v[0].length,b))),2==u[0].level&&u.unshift(new j(1,u[0].to,u[0].to)),u[0].level!=bg(u).level&&u.push(new j(u[0].level,b,b)),u}}();return v.version="5.6.1",v}),function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)}(function(a){"use strict";function b(a){for(var b={},c=a.split(" "),d=0;d|[*\]])\s*$|\*$/.test(a.string.slice(0,a.start))?!0:void 0}function C(a){for(;;){if(!a||"top"==a.type)return!0;if("}"==a.type&&"namespace"!=a.prev.type)return!1;a=a.prev}}var s,t,d=b.indentUnit,e=c.statementIndentUnit||d,f=c.dontAlignCalls,g=c.keywords||{},h=c.types||{},i=c.builtin||{},j=c.blockKeywords||{},k=c.defKeywords||{},l=c.atoms||{},m=c.hooks||{},n=c.multiLineStrings,o=c.indentStatements!==!1,p=c.indentSwitch!==!1,q=c.namespaceSeparator,r=/[+\-*&%=<>!?|\/]/;return{startState:function(a){return{tokenize:null,context:new x((a||0)-d,0,"top",!1),indented:0,startOfLine:!0,prevToken:null}},token:function(a,b){var d=b.context;if(a.sol()&&(null==d.align&&(d.align=!1),b.indented=a.indentation(),b.startOfLine=!0),a.eatSpace())return null;s=t=null;var e=(b.tokenize||u)(a,b);if("comment"==e||"meta"==e)return e;if(null==d.align&&(d.align=!0),";"==s||":"==s||","==s)for(;y(b.context.type);)A(b);else if("{"==s)z(b,a.column(),"}");else if("["==s)z(b,a.column(),"]");else if("("==s)z(b,a.column(),")");else if("}"==s){for(;y(d.type);)d=A(b);for("}"==d.type&&(d=A(b));y(d.type);)d=A(b)}else if(s==d.type)A(b);else if(o&&(("}"==d.type||"top"==d.type)&&";"!=s||y(d.type)&&"newstatement"==s)){var f="statement";"newstatement"==s&&p&&"switch"==a.current()?f="switchstatement":"keyword"==e&&"namespace"==a.current()&&(f="namespace"),z(b,a.column(),f)}if("variable"==e&&("def"==b.prevToken||c.typeFirstDefinitions&&B(a,b)&&C(b.context)&&a.match(/^\s*\(/,!1))&&(e="def"),m.token){var g=m.token(a,b,e);void 0!==g&&(e=g)}return"def"==e&&c.styleDefs===!1&&(e="variable"),b.startOfLine=!1,b.prevToken=t?"def":e||s,e},indent:function(b,c){if(b.tokenize!=u&&null!=b.tokenize)return a.Pass;var g=b.context,h=c&&c.charAt(0);y(g.type)&&"}"==h&&(g=g.prev);var i=h==g.type,j=g.prev&&"switchstatement"==g.prev.type;return y(g.type)?g.indented+("{"==h?0:e):!g.align||f&&")"==g.type?")"!=g.type||i?g.indented+(i?0:d)+(i||!j||/^(?:case|default)\b/.test(c)?0:d):g.indented+e:g.column+(i?0:1)},electricInput:p?/^\s*(?:case .*?:|default:|\{\}?|\})$/:/^\s*[{}]$/,blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:"//",fold:"brace"}});var c="auto if break case register continue return default do sizeof static else struct switch extern typedef float union for goto while enum const volatile",d="int long char short double float unsigned signed void size_t ptrdiff_t";k(["text/x-csrc","text/x-c","text/x-chdr"],{name:"clike",keywords:b(c),types:b(d+" bool _Complex _Bool float_t double_t intptr_t intmax_t int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t uint32_t uint64_t"),blockKeywords:b("case do else for if switch while struct"),defKeywords:b("struct"),typeFirstDefinitions:!0,atoms:b("null true false"),hooks:{"#":e,"*":f},modeProps:{fold:["brace","include"]}}),k(["text/x-c++src","text/x-c++hdr"],{name:"clike",keywords:b(c+" asm dynamic_cast namespace reinterpret_cast try explicit new static_cast typeid catch operator template typename class friend private this using const_cast inline public throw virtual delete mutable protected alignas alignof constexpr decltype nullptr noexcept thread_local final static_assert override"),types:b(d+" bool wchar_t"),blockKeywords:b("catch class do else finally for if struct switch try while"),defKeywords:b("class namespace struct enum union"),typeFirstDefinitions:!0,atoms:b("true false null"),hooks:{"#":e,"*":f,u:g,U:g,L:g,R:g,token:function(a,b,c){return"variable"!=c||"("!=a.peek()||";"!=b.prevToken&&null!=b.prevToken&&"}"!=b.prevToken||!h(a.current())?void 0:"def"; +}},namespaceSeparator:"::",modeProps:{fold:["brace","include"]}}),k("text/x-java",{name:"clike",keywords:b("abstract assert break case catch class const continue default do else enum extends final finally float for goto if implements import instanceof interface native new package private protected public return static strictfp super switch synchronized this throw throws transient try volatile while"),types:b("byte short int long float double boolean char void Boolean Byte Character Double Float Integer Long Number Object Short String StringBuffer StringBuilder Void"),blockKeywords:b("catch class do else finally for if switch try while"),defKeywords:b("class interface package enum"),typeFirstDefinitions:!0,atoms:b("true false null"),hooks:{"@":function(a){return a.eatWhile(/[\w\$_]/),"meta"}},modeProps:{fold:["brace","import"]}}),k("text/x-csharp",{name:"clike",keywords:b("abstract as async await base break case catch checked class const continue default delegate do else enum event explicit extern finally fixed for foreach goto if implicit in interface internal is lock namespace new operator out override params private protected public readonly ref return sealed sizeof stackalloc static struct switch this throw try typeof unchecked unsafe using virtual void volatile while add alias ascending descending dynamic from get global group into join let orderby partial remove select set value var yield"),types:b("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32 UInt64 bool byte char decimal double short int long object sbyte float string ushort uint ulong"),blockKeywords:b("catch class do else finally for foreach if struct switch try while"),defKeywords:b("class interface namespace struct var"),typeFirstDefinitions:!0,atoms:b("true false null"),hooks:{"@":function(a,b){return a.eat('"')?(b.tokenize=i,i(a,b)):(a.eatWhile(/[\w\$_]/),"meta")}}}),k("text/x-scala",{name:"clike",keywords:b("abstract case catch class def do else extends false final finally for forSome if implicit import lazy match new null object override package private protected return sealed super this throw trait try type val var while with yield _ : = => <- <: <% >: # @ assert assume require print println printf readLine readBoolean readByte readShort readChar readInt readLong readFloat readDouble :: #:: "),types:b("AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable Compiler Double Exception Float Integer Long Math Number Object Package Pair Process Runtime Runnable SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"),multiLineStrings:!0,blockKeywords:b("catch class do else finally for forSome if match switch try while"),defKeywords:b("class def object package trait type val var"),atoms:b("true false null"),indentStatements:!1,indentSwitch:!1,hooks:{"@":function(a){return a.eatWhile(/[\w\$_]/),"meta"},'"':function(a,b){return a.match('""')?(b.tokenize=l,b.tokenize(a,b)):!1},"'":function(a){return a.eatWhile(/[\w\$_\xa1-\uffff]/),"atom"}},modeProps:{closeBrackets:{triples:'"'}}}),k(["x-shader/x-vertex","x-shader/x-fragment"],{name:"clike",keywords:b("sampler1D sampler2D sampler3D samplerCube sampler1DShadow sampler2DShadow const attribute uniform varying break continue discard return for while do if else struct in out inout"),types:b("float int bool void vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 mat2 mat3 mat4"),blockKeywords:b("for while do if else struct"),builtin:b("radians degrees sin cos tan asin acos atan pow exp log exp2 sqrt inversesqrt abs sign floor ceil fract mod min max clamp mix step smoothstep length distance dot cross normalize ftransform faceforward reflect refract matrixCompMult lessThan lessThanEqual greaterThan greaterThanEqual equal notEqual any all not texture1D texture1DProj texture1DLod texture1DProjLod texture2D texture2DProj texture2DLod texture2DProjLod texture3D texture3DProj texture3DLod texture3DProjLod textureCube textureCubeLod shadow1D shadow2D shadow1DProj shadow2DProj shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod dFdx dFdy fwidth noise1 noise2 noise3 noise4"),atoms:b("true false gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 gl_FogCoord gl_PointCoord gl_Position gl_PointSize gl_ClipVertex gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor gl_TexCoord gl_FogFragCoord gl_FragCoord gl_FrontFacing gl_FragData gl_FragDepth gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose gl_ProjectionMatrixInverseTranspose gl_ModelViewProjectionMatrixInverseTranspose gl_TextureMatrixInverseTranspose gl_NormalScale gl_DepthRange gl_ClipPlane gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel gl_FrontLightModelProduct gl_BackLightModelProduct gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ gl_FogParameters gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits gl_MaxDrawBuffers"),indentSwitch:!1,hooks:{"#":e},modeProps:{fold:["brace","include"]}}),k("text/x-nesc",{name:"clike",keywords:b(c+"as atomic async call command component components configuration event generic implementation includes interface module new norace nx_struct nx_union post provides signal task uses abstract extends"),types:b(d),blockKeywords:b("case do else for if switch while struct"),atoms:b("null true false"),hooks:{"#":e},modeProps:{fold:["brace","include"]}}),k("text/x-objectivec",{name:"clike",keywords:b(c+"inline restrict _Bool _Complex _Imaginery BOOL Class bycopy byref id IMP in inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"),types:b(d),atoms:b("YES NO NULL NILL ON OFF true false"),hooks:{"@":function(a){return a.eatWhile(/[\w\$]/),"keyword"},"#":e},modeProps:{fold:"brace"}}),k("text/x-squirrel",{name:"clike",keywords:b("base break clone continue const default delete enum extends function in class foreach local resume return this throw typeof yield constructor instanceof static"),types:b(d),blockKeywords:b("case catch class else for foreach if switch try while"),defKeywords:b("function local class"),typeFirstDefinitions:!0,atoms:b("true false null"),hooks:{"#":e},modeProps:{fold:["brace","include"]}})}),function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)}(function(a){"use strict";function b(a){return new RegExp("^(("+a.join(")|(")+"))\\b")}function h(a){return a.scopes[a.scopes.length-1]}var c=b(["and","or","not","is"]),d=["as","assert","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","lambda","pass","raise","return","try","while","with","yield","in"],e=["abs","all","any","bin","bool","bytearray","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip","__import__","NotImplemented","Ellipsis","__debug__"],f={builtins:["apply","basestring","buffer","cmp","coerce","execfile","file","intern","long","raw_input","reduce","reload","unichr","unicode","xrange","False","True","None"],keywords:["exec","print"]},g={builtins:["ascii","bytes","exec","print"],keywords:["nonlocal","False","True","None","async","await"]};a.registerHelper("hintWords","python",d.concat(e)),a.defineMode("python",function(i,j){function x(a,b){if(a.sol()&&"py"==h(b).type){var c=h(b).offset;if(a.eatSpace()){var d=a.indentation();return d>c?A(a,b,"py"):c>d&&B(a,b)&&(b.errorToken=!0),null}var e=y(a,b);return c>0&&B(a,b)&&(e+=" "+k),e}return y(a,b)}function y(a,b){if(a.eatSpace())return null;var d=a.peek();if("#"==d)return a.skipToEnd(),"comment";if(a.match(/^[0-9\.]/,!1)){var e=!1;if(a.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)&&(e=!0),a.match(/^\d+\.\d*/)&&(e=!0),a.match(/^\.\d+/)&&(e=!0),e)return a.eat(/J/i),"number";var f=!1;if(a.match(/^0x[0-9a-f]+/i)&&(f=!0),a.match(/^0b[01]+/i)&&(f=!0),a.match(/^0o[0-7]+/i)&&(f=!0),a.match(/^[1-9]\d*(e[\+\-]?\d+)?/)&&(a.eat(/J/i),f=!0),a.match(/^0(?![\dx])/i)&&(f=!0),f)return a.eat(/L/i),"number"}return a.match(u)?(b.tokenize=z(a.current()),b.tokenize(a,b)):a.match(o)||a.match(n)?null:a.match(m)||a.match(p)?"operator":a.match(l)?null:a.match(v)||a.match(c)?"keyword":a.match(w)?"builtin":a.match(/^(self|cls)\b/)?"variable-2":a.match(q)?"def"==b.lastToken||"class"==b.lastToken?"def":"variable":(a.next(),k)}function z(a){function d(d,e){for(;!d.eol();)if(d.eatWhile(/[^'"\\]/),d.eat("\\")){if(d.next(),b&&d.eol())return c}else{if(d.match(a))return e.tokenize=x,c;d.eat(/['"]/)}if(b){if(j.singleLineStringErrors)return k;e.tokenize=x}return c}for(;"rub".indexOf(a.charAt(0).toLowerCase())>=0;)a=a.substr(1);var b=1==a.length,c="string";return d.isString=!0,d}function A(a,b,c){var d=0,e=null;if("py"==c)for(;"py"!=h(b).type;)b.scopes.pop();d=h(b).offset+("py"==c?i.indentUnit:r),"py"==c||a.match(/^(\s|#.*)*$/,!1)||(e=a.column()+1),b.scopes.push({offset:d,type:c,align:e})}function B(a,b){for(var c=a.indentation();h(b).offset>c;){if("py"!=h(b).type)return!0;b.scopes.pop()}return h(b).offset!=c}function C(a,b){var c=b.tokenize(a,b),d=a.current();if("."==d)return c=a.match(q,!1)?null:k,null==c&&"meta"==b.lastStyle&&(c="meta"),c;if("@"==d)return j.version&&3==parseInt(j.version,10)?a.match(q,!1)?"meta":"operator":a.match(q,!1)?"meta":k;"variable"!=c&&"builtin"!=c||"meta"!=b.lastStyle||(c="meta"),("pass"==d||"return"==d)&&(b.dedent+=1),"lambda"==d&&(b.lambda=!0),":"!=d||b.lambda||"py"!=h(b).type||A(a,b,"py");var e=1==d.length?"[({".indexOf(d):-1;if(-1!=e&&A(a,b,"])}".slice(e,e+1)),e="])}".indexOf(d),-1!=e){if(h(b).type!=d)return k;b.scopes.pop()}return b.dedent>0&&a.eol()&&"py"==h(b).type&&(b.scopes.length>1&&b.scopes.pop(),b.dedent-=1),c}var k="error",l=j.singleDelimiters||new RegExp("^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]"),m=j.doubleOperators||new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))"),n=j.doubleDelimiters||new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))"),o=j.tripleDelimiters||new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");if(j.version&&3==parseInt(j.version,10))var p=j.singleOperators||new RegExp("^[\\+\\-\\*/%&|\\^~<>!@]"),q=j.identifiers||new RegExp("^[_A-Za-z\xa1-\uffff][_A-Za-z0-9\xa1-\uffff]*");else var p=j.singleOperators||new RegExp("^[\\+\\-\\*/%&|\\^~<>!]"),q=j.identifiers||new RegExp("^[_A-Za-z][_A-Za-z0-9]*");var r=j.hangingIndent||i.indentUnit,s=d,t=e;if(void 0!=j.extra_keywords&&(s=s.concat(j.extra_keywords)),void 0!=j.extra_builtins&&(t=t.concat(j.extra_builtins)),j.version&&3==parseInt(j.version,10)){s=s.concat(g.keywords),t=t.concat(g.builtins);var u=new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))","i")}else{s=s.concat(f.keywords),t=t.concat(f.builtins);var u=new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))","i")}var v=b(s),w=b(t),D={startState:function(a){return{tokenize:x,scopes:[{offset:a||0,type:"py",align:null}],lastStyle:null,lastToken:null,lambda:!1,dedent:0}},token:function(a,b){var c=b.errorToken;c&&(b.errorToken=!1);var d=C(a,b);b.lastStyle=d;var e=a.current();return e&&d&&(b.lastToken=e),a.eol()&&b.lambda&&(b.lambda=!1),c?d+" "+k:d},indent:function(b,c){if(b.tokenize!=x)return b.tokenize.isString?a.Pass:0;var d=h(b),e=c&&c.charAt(0)==d.type;return null!=d.align?d.align-(e?1:0):e&&b.scopes.length>1?b.scopes[b.scopes.length-2].offset:d.offset},closeBrackets:{triples:"'\""},lineComment:"#",fold:"indent"};return D}),a.defineMIME("text/x-python","python");var i=function(a){return a.split(" ")};a.defineMIME("text/x-cython",{name:"python",extra_keywords:i("by cdef cimport cpdef ctypedef enum exceptextern gil include nogil property publicreadonly struct union DEF IF ELIF ELSE")})}),function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)}(function(a){"use strict";a.defineMode("ruby",function(a){function b(a){for(var b={},c=0,d=a.length;d>c;++c)b[a[c]]=!0;return b}function h(a,b,c){return c.tokenize.push(a),a(b,c)}function i(a,b){if(a.sol()&&a.match("=begin")&&a.eol())return b.tokenize.push(n),"comment";if(a.eatSpace())return null;var d,c=a.next();if("`"==c||"'"==c||'"'==c)return h(l(c,"string",'"'==c||"`"==c),a,b);if("/"==c){var e=a.current().length;if(a.skipTo("/")){var i=a.current().length;a.backUp(a.current().length-e);for(var j=0;a.current().lengthj)break}if(a.backUp(a.current().length-e),0==j)return h(l(c,"string-2",!0),a,b)}return"operator"}if("%"==c){var o="string",p=!0;a.eat("s")?o="atom":a.eat(/[WQ]/)?o="string":a.eat(/[r]/)?o="string-2":a.eat(/[wxq]/)&&(o="string",p=!1);var q=a.eat(/[^\w\s=]/);return q?(f.propertyIsEnumerable(q)&&(q=f[q]),h(l(q,o,p,!0),a,b)):"operator"}if("#"==c)return a.skipToEnd(),"comment";if("<"==c&&(d=a.match(/^<-?[\`\"\']?([a-zA-Z_?]\w*)[\`\"\']?(?:;|$)/)))return h(m(d[1]),a,b);if("0"==c)return a.eat("x")?a.eatWhile(/[\da-fA-F]/):a.eat("b")?a.eatWhile(/[01]/):a.eatWhile(/[0-7]/),"number";if(/\d/.test(c))return a.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+\-]?[\d_]+)?/),"number";if("?"==c){for(;a.match(/^\\[CM]-/););return a.eat("\\")?a.eatWhile(/\w/):a.next(),"string"}if(":"==c)return a.eat("'")?h(l("'","atom",!1),a,b):a.eat('"')?h(l('"',"atom",!0),a,b):a.eat(/[\<\>]/)?(a.eat(/[\<\>]/),"atom"):a.eat(/[\+\-\*\/\&\|\:\!]/)?"atom":a.eat(/[a-zA-Z$@_\xa1-\uffff]/)?(a.eatWhile(/[\w$\xa1-\uffff]/),a.eat(/[\?\!\=]/),"atom"):"operator";if("@"==c&&a.match(/^@?[a-zA-Z_\xa1-\uffff]/))return a.eat("@"),a.eatWhile(/[\w\xa1-\uffff]/),"variable-2";if("$"==c)return a.eat(/[a-zA-Z_]/)?a.eatWhile(/[\w]/):a.eat(/\d/)?a.eat(/\d/):a.next(),"variable-3";if(/[a-zA-Z_\xa1-\uffff]/.test(c))return a.eatWhile(/[\w\xa1-\uffff]/),a.eat(/[\?\!]/),a.eat(":")?"atom":"ident";if("|"!=c||!b.varList&&"{"!=b.lastTok&&"do"!=b.lastTok){if(/[\(\)\[\]{}\\;]/.test(c))return g=c,null;if("-"==c&&a.eat(">"))return"arrow";if(/[=+\-\/*:\.^%<>~|]/.test(c)){var r=a.eatWhile(/[=+\-\/*:\.^%<>~|]/);return"."!=c||r||(g="."),"operator"}return null}return g="|",null}function j(a){return a||(a=1),function(b,c){if("}"==b.peek()){if(1==a)return c.tokenize.pop(),c.tokenize[c.tokenize.length-1](b,c);c.tokenize[c.tokenize.length-1]=j(a-1)}else"{"==b.peek()&&(c.tokenize[c.tokenize.length-1]=j(a+1));return i(b,c)}}function k(){var a=!1;return function(b,c){return a?(c.tokenize.pop(),c.tokenize[c.tokenize.length-1](b,c)):(a=!0,i(b,c))}}function l(a,b,c,d){return function(e,f){var h,g=!1;for("read-quoted-paused"===f.context.type&&(f.context=f.context.prev,e.eat("}"));null!=(h=e.next());){if(h==a&&(d||!g)){f.tokenize.pop();break}if(c&&"#"==h&&!g){if(e.eat("{")){"}"==a&&(f.context={prev:f.context,type:"read-quoted-paused"}),f.tokenize.push(j());break}if(/[@\$]/.test(e.peek())){f.tokenize.push(k());break}}g=!g&&"\\"==h}return b}}function m(a){return function(b,c){return b.match(a)?c.tokenize.pop():b.skipToEnd(),"string"}}function n(a,b){return a.sol()&&a.match("=end")&&a.eol()&&b.tokenize.pop(),a.skipToEnd(),"comment"}var g,c=b(["alias","and","BEGIN","begin","break","case","class","def","defined?","do","else","elsif","END","end","ensure","false","for","if","in","module","next","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","nil","raise","throw","catch","fail","loop","callcc","caller","lambda","proc","public","protected","private","require","load","require_relative","extend","autoload","__END__","__FILE__","__LINE__","__dir__"]),d=b(["def","class","case","for","while","module","then","catch","loop","proc","begin"]),e=b(["end","until"]),f={"[":"]","{":"}","(":")"};return{startState:function(){return{tokenize:[i],indented:0,context:{type:"top",indented:-a.indentUnit},continuedLine:!1,lastTok:null,varList:!1}},token:function(a,b){g=null,a.sol()&&(b.indented=a.indentation());var h,f=b.tokenize[b.tokenize.length-1](a,b),i=g;if("ident"==f){var j=a.current();f="."==b.lastTok?"property":c.propertyIsEnumerable(a.current())?"keyword":/^[A-Z]/.test(j)?"tag":"def"==b.lastTok||"class"==b.lastTok||b.varList?"def":"variable","keyword"==f&&(i=j,d.propertyIsEnumerable(j)?h="indent":e.propertyIsEnumerable(j)?h="dedent":"if"!=j&&"unless"!=j||a.column()!=a.indentation()?"do"==j&&b.context.indented=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))"); + var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))"); + var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))"); + + if (parserConf.version && parseInt(parserConf.version, 10) == 3){ + // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator + var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!@]"); + var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*"); + } else { + var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]"); + var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*"); + } + + var hangingIndent = parserConf.hangingIndent || conf.indentUnit; + + var myKeywords = commonKeywords, myBuiltins = commonBuiltins; + if(parserConf.extra_keywords != undefined){ + myKeywords = myKeywords.concat(parserConf.extra_keywords); + } + if(parserConf.extra_builtins != undefined){ + myBuiltins = myBuiltins.concat(parserConf.extra_builtins); + } + if (parserConf.version && parseInt(parserConf.version, 10) == 3) { + myKeywords = myKeywords.concat(py3.keywords); + myBuiltins = myBuiltins.concat(py3.builtins); + var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i"); + } else { + myKeywords = myKeywords.concat(py2.keywords); + myBuiltins = myBuiltins.concat(py2.builtins); + var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i"); + } + var keywords = wordRegexp(myKeywords); + var builtins = wordRegexp(myBuiltins); + + // tokenizers + function tokenBase(stream, state) { + // Handle scope changes + if (stream.sol() && top(state).type == "py") { + var scopeOffset = top(state).offset; + if (stream.eatSpace()) { + var lineOffset = stream.indentation(); + if (lineOffset > scopeOffset) + pushScope(stream, state, "py"); + else if (lineOffset < scopeOffset && dedent(stream, state)) + state.errorToken = true; + return null; + } else { + var style = tokenBaseInner(stream, state); + if (scopeOffset > 0 && dedent(stream, state)) + style += " " + ERRORCLASS; + return style; + } + } + return tokenBaseInner(stream, state); + } + + function tokenBaseInner(stream, state) { + if (stream.eatSpace()) return null; + + var ch = stream.peek(); + + // Handle Comments + if (ch == "#") { + stream.skipToEnd(); + return "comment"; + } + + // Handle Number Literals + if (stream.match(/^[0-9\.]/, false)) { + var floatLiteral = false; + // Floats + if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; } + if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; } + if (stream.match(/^\.\d+/)) { floatLiteral = true; } + if (floatLiteral) { + // Float literals may be "imaginary" + stream.eat(/J/i); + return "number"; + } + // Integers + var intLiteral = false; + // Hex + if (stream.match(/^0x[0-9a-f]+/i)) intLiteral = true; + // Binary + if (stream.match(/^0b[01]+/i)) intLiteral = true; + // Octal + if (stream.match(/^0o[0-7]+/i)) intLiteral = true; + // Decimal + if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) { + // Decimal literals may be "imaginary" + stream.eat(/J/i); + // TODO - Can you have imaginary longs? + intLiteral = true; + } + // Zero by itself with no other piece of number. + if (stream.match(/^0(?![\dx])/i)) intLiteral = true; + if (intLiteral) { + // Integer literals may be "long" + stream.eat(/L/i); + return "number"; + } + } + + // Handle Strings + if (stream.match(stringPrefixes)) { + state.tokenize = tokenStringFactory(stream.current()); + return state.tokenize(stream, state); + } + + // Handle operators and Delimiters + if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) + return null; + + if (stream.match(doubleOperators) || stream.match(singleOperators)) + return "operator"; + + if (stream.match(singleDelimiters)) + return null; + + if (stream.match(keywords) || stream.match(wordOperators)) + return "keyword"; + + if (stream.match(builtins)) + return "builtin"; + + if (stream.match(/^(self|cls)\b/)) + return "variable-2"; + + if (stream.match(identifiers)) { + if (state.lastToken == "def" || state.lastToken == "class") + return "def"; + return "variable"; + } + + // Handle non-detected items + stream.next(); + return ERRORCLASS; + } + + function tokenStringFactory(delimiter) { + while ("rub".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) + delimiter = delimiter.substr(1); + + var singleline = delimiter.length == 1; + var OUTCLASS = "string"; + + function tokenString(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^'"\\]/); + if (stream.eat("\\")) { + stream.next(); + if (singleline && stream.eol()) + return OUTCLASS; + } else if (stream.match(delimiter)) { + state.tokenize = tokenBase; + return OUTCLASS; + } else { + stream.eat(/['"]/); + } + } + if (singleline) { + if (parserConf.singleLineStringErrors) + return ERRORCLASS; + else + state.tokenize = tokenBase; + } + return OUTCLASS; + } + tokenString.isString = true; + return tokenString; + } + + function pushScope(stream, state, type) { + var offset = 0, align = null; + if (type == "py") { + while (top(state).type != "py") + state.scopes.pop(); + } + offset = top(state).offset + (type == "py" ? conf.indentUnit : hangingIndent); + if (type != "py" && !stream.match(/^(\s|#.*)*$/, false)) + align = stream.column() + 1; + state.scopes.push({offset: offset, type: type, align: align}); + } + + function dedent(stream, state) { + var indented = stream.indentation(); + while (top(state).offset > indented) { + if (top(state).type != "py") return true; + state.scopes.pop(); + } + return top(state).offset != indented; + } + + function tokenLexer(stream, state) { + var style = state.tokenize(stream, state); + var current = stream.current(); + + // Handle '.' connected identifiers + if (current == ".") { + style = stream.match(identifiers, false) ? null : ERRORCLASS; + if (style == null && state.lastStyle == "meta") { + // Apply 'meta' style to '.' connected identifiers when + // appropriate. + style = "meta"; + } + return style; + } + + // Handle decorators + if (current == "@"){ + if(parserConf.version && parseInt(parserConf.version, 10) == 3){ + return stream.match(identifiers, false) ? "meta" : "operator"; + } else { + return stream.match(identifiers, false) ? "meta" : ERRORCLASS; + } + } + + if ((style == "variable" || style == "builtin") + && state.lastStyle == "meta") + style = "meta"; + + // Handle scope changes. + if (current == "pass" || current == "return") + state.dedent += 1; + + if (current == "lambda") state.lambda = true; + if (current == ":" && !state.lambda && top(state).type == "py") + pushScope(stream, state, "py"); + + var delimiter_index = current.length == 1 ? "[({".indexOf(current) : -1; + if (delimiter_index != -1) + pushScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1)); + + delimiter_index = "])}".indexOf(current); + if (delimiter_index != -1) { + if (top(state).type == current) state.scopes.pop(); + else return ERRORCLASS; + } + if (state.dedent > 0 && stream.eol() && top(state).type == "py") { + if (state.scopes.length > 1) state.scopes.pop(); + state.dedent -= 1; + } + + return style; + } + + var external = { + startState: function(basecolumn) { + return { + tokenize: tokenBase, + scopes: [{offset: basecolumn || 0, type: "py", align: null}], + lastStyle: null, + lastToken: null, + lambda: false, + dedent: 0 + }; + }, + + token: function(stream, state) { + var addErr = state.errorToken; + if (addErr) state.errorToken = false; + var style = tokenLexer(stream, state); + + state.lastStyle = style; + + var current = stream.current(); + if (current && style) + state.lastToken = current; + + if (stream.eol() && state.lambda) + state.lambda = false; + return addErr ? style + " " + ERRORCLASS : style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase) + return state.tokenize.isString ? CodeMirror.Pass : 0; + + var scope = top(state); + var closing = textAfter && textAfter.charAt(0) == scope.type; + if (scope.align != null) + return scope.align - (closing ? 1 : 0); + else if (closing && state.scopes.length > 1) + return state.scopes[state.scopes.length - 2].offset; + else + return scope.offset; + }, + + closeBrackets: {triples: "'\""}, + lineComment: "#", + fold: "indent" + }; + return external; + }); + + CodeMirror.defineMIME("text/x-python", "python"); + + var words = function(str) { return str.split(" "); }; + + CodeMirror.defineMIME("text/x-cython", { + name: "python", + extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+ + "extern gil include nogil property public"+ + "readonly struct union DEF IF ELIF ELSE") + }); + +}); diff --git a/public/assets/codemirror/ruby.js b/public/assets/codemirror/ruby.js new file mode 100644 index 000000000..771f855ab --- /dev/null +++ b/public/assets/codemirror/ruby.js @@ -0,0 +1,285 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("ruby", function(config) { + function wordObj(words) { + var o = {}; + for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true; + return o; + } + var keywords = wordObj([ + "alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined?", "do", "else", + "elsif", "END", "end", "ensure", "false", "for", "if", "in", "module", "next", "not", "or", + "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", + "until", "when", "while", "yield", "nil", "raise", "throw", "catch", "fail", "loop", "callcc", + "caller", "lambda", "proc", "public", "protected", "private", "require", "load", + "require_relative", "extend", "autoload", "__END__", "__FILE__", "__LINE__", "__dir__" + ]); + var indentWords = wordObj(["def", "class", "case", "for", "while", "module", "then", + "catch", "loop", "proc", "begin"]); + var dedentWords = wordObj(["end", "until"]); + var matching = {"[": "]", "{": "}", "(": ")"}; + var curPunc; + + function chain(newtok, stream, state) { + state.tokenize.push(newtok); + return newtok(stream, state); + } + + function tokenBase(stream, state) { + if (stream.sol() && stream.match("=begin") && stream.eol()) { + state.tokenize.push(readBlockComment); + return "comment"; + } + if (stream.eatSpace()) return null; + var ch = stream.next(), m; + if (ch == "`" || ch == "'" || ch == '"') { + return chain(readQuoted(ch, "string", ch == '"' || ch == "`"), stream, state); + } else if (ch == "/") { + var currentIndex = stream.current().length; + if (stream.skipTo("/")) { + var search_till = stream.current().length; + stream.backUp(stream.current().length - currentIndex); + var balance = 0; // balance brackets + while (stream.current().length < search_till) { + var chchr = stream.next(); + if (chchr == "(") balance += 1; + else if (chchr == ")") balance -= 1; + if (balance < 0) break; + } + stream.backUp(stream.current().length - currentIndex); + if (balance == 0) + return chain(readQuoted(ch, "string-2", true), stream, state); + } + return "operator"; + } else if (ch == "%") { + var style = "string", embed = true; + if (stream.eat("s")) style = "atom"; + else if (stream.eat(/[WQ]/)) style = "string"; + else if (stream.eat(/[r]/)) style = "string-2"; + else if (stream.eat(/[wxq]/)) { style = "string"; embed = false; } + var delim = stream.eat(/[^\w\s=]/); + if (!delim) return "operator"; + if (matching.propertyIsEnumerable(delim)) delim = matching[delim]; + return chain(readQuoted(delim, style, embed, true), stream, state); + } else if (ch == "#") { + stream.skipToEnd(); + return "comment"; + } else if (ch == "<" && (m = stream.match(/^<-?[\`\"\']?([a-zA-Z_?]\w*)[\`\"\']?(?:;|$)/))) { + return chain(readHereDoc(m[1]), stream, state); + } else if (ch == "0") { + if (stream.eat("x")) stream.eatWhile(/[\da-fA-F]/); + else if (stream.eat("b")) stream.eatWhile(/[01]/); + else stream.eatWhile(/[0-7]/); + return "number"; + } else if (/\d/.test(ch)) { + stream.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+\-]?[\d_]+)?/); + return "number"; + } else if (ch == "?") { + while (stream.match(/^\\[CM]-/)) {} + if (stream.eat("\\")) stream.eatWhile(/\w/); + else stream.next(); + return "string"; + } else if (ch == ":") { + if (stream.eat("'")) return chain(readQuoted("'", "atom", false), stream, state); + if (stream.eat('"')) return chain(readQuoted('"', "atom", true), stream, state); + + // :> :>> :< :<< are valid symbols + if (stream.eat(/[\<\>]/)) { + stream.eat(/[\<\>]/); + return "atom"; + } + + // :+ :- :/ :* :| :& :! are valid symbols + if (stream.eat(/[\+\-\*\/\&\|\:\!]/)) { + return "atom"; + } + + // Symbols can't start by a digit + if (stream.eat(/[a-zA-Z$@_\xa1-\uffff]/)) { + stream.eatWhile(/[\w$\xa1-\uffff]/); + // Only one ? ! = is allowed and only as the last character + stream.eat(/[\?\!\=]/); + return "atom"; + } + return "operator"; + } else if (ch == "@" && stream.match(/^@?[a-zA-Z_\xa1-\uffff]/)) { + stream.eat("@"); + stream.eatWhile(/[\w\xa1-\uffff]/); + return "variable-2"; + } else if (ch == "$") { + if (stream.eat(/[a-zA-Z_]/)) { + stream.eatWhile(/[\w]/); + } else if (stream.eat(/\d/)) { + stream.eat(/\d/); + } else { + stream.next(); // Must be a special global like $: or $! + } + return "variable-3"; + } else if (/[a-zA-Z_\xa1-\uffff]/.test(ch)) { + stream.eatWhile(/[\w\xa1-\uffff]/); + stream.eat(/[\?\!]/); + if (stream.eat(":")) return "atom"; + return "ident"; + } else if (ch == "|" && (state.varList || state.lastTok == "{" || state.lastTok == "do")) { + curPunc = "|"; + return null; + } else if (/[\(\)\[\]{}\\;]/.test(ch)) { + curPunc = ch; + return null; + } else if (ch == "-" && stream.eat(">")) { + return "arrow"; + } else if (/[=+\-\/*:\.^%<>~|]/.test(ch)) { + var more = stream.eatWhile(/[=+\-\/*:\.^%<>~|]/); + if (ch == "." && !more) curPunc = "."; + return "operator"; + } else { + return null; + } + } + + function tokenBaseUntilBrace(depth) { + if (!depth) depth = 1; + return function(stream, state) { + if (stream.peek() == "}") { + if (depth == 1) { + state.tokenize.pop(); + return state.tokenize[state.tokenize.length-1](stream, state); + } else { + state.tokenize[state.tokenize.length - 1] = tokenBaseUntilBrace(depth - 1); + } + } else if (stream.peek() == "{") { + state.tokenize[state.tokenize.length - 1] = tokenBaseUntilBrace(depth + 1); + } + return tokenBase(stream, state); + }; + } + function tokenBaseOnce() { + var alreadyCalled = false; + return function(stream, state) { + if (alreadyCalled) { + state.tokenize.pop(); + return state.tokenize[state.tokenize.length-1](stream, state); + } + alreadyCalled = true; + return tokenBase(stream, state); + }; + } + function readQuoted(quote, style, embed, unescaped) { + return function(stream, state) { + var escaped = false, ch; + + if (state.context.type === 'read-quoted-paused') { + state.context = state.context.prev; + stream.eat("}"); + } + + while ((ch = stream.next()) != null) { + if (ch == quote && (unescaped || !escaped)) { + state.tokenize.pop(); + break; + } + if (embed && ch == "#" && !escaped) { + if (stream.eat("{")) { + if (quote == "}") { + state.context = {prev: state.context, type: 'read-quoted-paused'}; + } + state.tokenize.push(tokenBaseUntilBrace()); + break; + } else if (/[@\$]/.test(stream.peek())) { + state.tokenize.push(tokenBaseOnce()); + break; + } + } + escaped = !escaped && ch == "\\"; + } + return style; + }; + } + function readHereDoc(phrase) { + return function(stream, state) { + if (stream.match(phrase)) state.tokenize.pop(); + else stream.skipToEnd(); + return "string"; + }; + } + function readBlockComment(stream, state) { + if (stream.sol() && stream.match("=end") && stream.eol()) + state.tokenize.pop(); + stream.skipToEnd(); + return "comment"; + } + + return { + startState: function() { + return {tokenize: [tokenBase], + indented: 0, + context: {type: "top", indented: -config.indentUnit}, + continuedLine: false, + lastTok: null, + varList: false}; + }, + + token: function(stream, state) { + curPunc = null; + if (stream.sol()) state.indented = stream.indentation(); + var style = state.tokenize[state.tokenize.length-1](stream, state), kwtype; + var thisTok = curPunc; + if (style == "ident") { + var word = stream.current(); + style = state.lastTok == "." ? "property" + : keywords.propertyIsEnumerable(stream.current()) ? "keyword" + : /^[A-Z]/.test(word) ? "tag" + : (state.lastTok == "def" || state.lastTok == "class" || state.varList) ? "def" + : "variable"; + if (style == "keyword") { + thisTok = word; + if (indentWords.propertyIsEnumerable(word)) kwtype = "indent"; + else if (dedentWords.propertyIsEnumerable(word)) kwtype = "dedent"; + else if ((word == "if" || word == "unless") && stream.column() == stream.indentation()) + kwtype = "indent"; + else if (word == "do" && state.context.indented < state.indented) + kwtype = "indent"; + } + } + if (curPunc || (style && style != "comment")) state.lastTok = thisTok; + if (curPunc == "|") state.varList = !state.varList; + + if (kwtype == "indent" || /[\(\[\{]/.test(curPunc)) + state.context = {prev: state.context, type: curPunc || style, indented: state.indented}; + else if ((kwtype == "dedent" || /[\)\]\}]/.test(curPunc)) && state.context.prev) + state.context = state.context.prev; + + if (stream.eol()) + state.continuedLine = (curPunc == "\\" || style == "operator"); + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize[state.tokenize.length-1] != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0); + var ct = state.context; + var closing = ct.type == matching[firstChar] || + ct.type == "keyword" && /^(?:end|until|else|elsif|when|rescue)\b/.test(textAfter); + return ct.indented + (closing ? 0 : config.indentUnit) + + (state.continuedLine ? config.indentUnit : 0); + }, + + electricChars: "}de", // enD and rescuE + lineComment: "#" + }; +}); + +CodeMirror.defineMIME("text/x-ruby", "ruby"); + +}); diff --git a/public/assets/kindeditor/kindeditor.js b/public/assets/kindeditor/kindeditor.js index 270618522..da7434d9b 100644 --- a/public/assets/kindeditor/kindeditor.js +++ b/public/assets/kindeditor/kindeditor.js @@ -243,6 +243,7 @@ K.options = { shadowMode : true, loadStyleMode : true, basePath : K.basePath, + emotionsBasePath: 'http://forge.trustie.net', //TODO themesPath : K.basePath + 'themes/', langPath : K.basePath + 'lang/', pluginsPath : K.basePath + 'plugins/', @@ -258,16 +259,16 @@ K.options = { fullscreenShortcut : false, bodyClass : 'ke-content', indentChar : '\t', - cssPath : '', + cssPath : K.basePath +'plugins/code/previewcode.css', cssData : '', minWidth : 650, minHeight : 100, minChangeSize : 50, zIndex : 811213, - items : [ 'emoticons', - 'source','plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', '|', - 'formatblock', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', - 'italic', 'underline', 'removeformat', '|','imagedirectupload','table', 'media',"more" + items : ['code','emoticons','fontname', + 'forecolor', 'hilitecolor', 'bold', '|', 'justifyleft', 'justifycenter', 'insertorderedlist','insertunorderedlist', '|', + 'formatblock', 'fontsize', '|','indent', 'outdent', + '|','imagedirectupload','table', 'media', 'preview',"more" ], noDisableItems : ['source', 'fullscreen'], colorTable : [ @@ -3536,8 +3537,8 @@ function _getInitHtml(themesPath, bodyClass, cssPath, cssData) { (_direction === '' ? '' : ''), '', '').appendTo($("head")); - } - var cb = settings.boxClass, cl = settings.listClass, cf = settings.focusClass, cm = settings.markCalss; //插件的class变量 - var z = settings.zIndex, newArr = mailArr = settings.mailArr, hint = settings.textHint, text = settings.hintText, fc = settings.focusColor, bc = settings.blurColor; +// var settings = $.extend({}, defaults, options || {}); +// //页面装载CSS样式 +// if(settings.autoClass && $("#mailListAppendCss").size() === 0){ +// $('').appendTo($("head")); +// } +// var cb = settings.boxClass, cl = settings.listClass, cf = settings.focusClass, cm = settings.markCalss; //插件的class变量 +// var z = settings.zIndex, newArr = mailArr = settings.mailArr, hint = settings.textHint, text = settings.hintText, fc = settings.focusColor, bc = settings.blurColor; //创建邮件内部列表内容 - $.createHtml = function(str, arr, cur){ - var mailHtml = ""; - if($.isArray(arr)){ - $.each(arr, function(i, n){ - if(i === cur){ - mailHtml += '
    '+str+'@'+arr[i]+'
    '; - }else{ - mailHtml += '
    '+str+'@'+arr[i]+'
    '; - } - }); - } - return mailHtml; - }; +// $.createHtml = function(str, arr, cur){ +// var mailHtml = ""; +// if($.isArray(arr)){ +// $.each(arr, function(i, n){ +// if(i === cur){ +// mailHtml += '
    '+str+'@'+arr[i]+'
    '; +// }else{ +// mailHtml += '
    '+str+'@'+arr[i]+'
    '; +// } +// }); +// } +// return mailHtml; +// }; //一些全局变量 var index = -1, s; - $(this).each(function(){ - var that = $(this), i = $(".justForJs").size(); - if(i > 0){ //只绑定一个文本框 - return; - } - var w = that.outerWidth(), h = that.outerHeight(); //获取当前对象(即文本框)的宽高 - //样式的初始化 - that.wrap('') - .before('
    '); - var x = $("#mailListBox_" + i), liveValue; //列表框对象 - that.focus(function(){ - //父标签的层级 - $(this).css("color", fc).parent().css("z-index", z); - //提示文字的显示与隐藏 - if(hint && text){ - var focus_v = $.trim($(this).val()); - if(focus_v === text){ - $(this).val(""); - } - } - //键盘事件 - $(this).keyup(function(e){ - s = v = $.trim($(this).val()); - if(/@/.test(v)){ - s = v.replace(/@.*/, ""); - } - if(v.length > 0){ - //如果按键是上下键 - if(e.keyCode === 38){ - //向上 - if(index <= 0){ - index = newArr.length; - } - index--; - }else if(e.keyCode === 40){ - //向下 - if(index >= newArr.length - 1){ - index = -1; - } - index++; - }else if(e.keyCode === 13){ - //回车 - if(index > -1 && index < newArr.length){ - //如果当前有激活列表 - $(this).val($("#mailList_"+index).text()); - } - }else{ - if(/@/.test(v)){ - index = -1; - //获得@后面的值 - //s = v.replace(/@.*/, ""); - //创建新匹配数组 - var site = v.replace(/.*@/, ""); - newArr = $.map(mailArr, function(n){ - var reg = new RegExp(site); - if(reg.test(n)){ - return n; - } - }); - }else{ - newArr = mailArr; - } - } - x.html($.createHtml(s, newArr, index)).css("left", 0); - if(e.keyCode === 13){ - //回车 - if(index > -1 && index < newArr.length){ - //如果当前有激活列表 - x.css("left", "-6000px"); - } - } - }else{ - x.css("left", "-6000px"); - } - }).blur(function(){ - if(hint && text){ - var blur_v = $.trim($(this).val()); - if(blur_v === ""){ - $(this).val(text); - } - } - $(this).css("color", bc).unbind("keyup").parent().css("z-index",0); - x.css("left", "-6000px"); - - }).keydown(function(event){ - if(event.keyCode == 13){ - return false; - } - }); - //鼠标经过列表项事件 - //鼠标经过 - $(".mailHover").live("mouseover", function(){ - index = Number($(this).attr("id").split("_")[1]); - liveValue = $("#mailList_"+index).text(); - x.children("." + cf).removeClass(cf).addClass(cl); - $(this).addClass(cf).removeClass(cl); - }); - $(".mailHover").live("click", function(){ - $("#mail").val($(this).html()); - }); - - - }); - - x.bind("mousedown", function(){ - that.val(liveValue); - }); - }); +// $(this).each(function(){ +// var that = $(this), i = $(".justForJs").size(); +// if(i > 0){ //只绑定一个文本框 +// return; +// } +// var w = that.outerWidth(), h = that.outerHeight(); //获取当前对象(即文本框)的宽高 +// //样式的初始化 +// that.wrap('') +// .before('
    '); +// var x = $("#mailListBox_" + i), liveValue; //列表框对象 +// that.focus(function(){ +// //父标签的层级 +// $(this).css("color", fc).parent().css("z-index", z); +// //提示文字的显示与隐藏 +// if(hint && text){ +// var focus_v = $.trim($(this).val()); +// if(focus_v === text){ +// $(this).val(""); +// } +// } +// //键盘事件 +// $(this).keyup(function(e){ +// s = v = $.trim($(this).val()); +// if(/@/.test(v)){ +// s = v.replace(/@.*/, ""); +// } +// if(v.length > 0){ +// //如果按键是上下键 +// if(e.keyCode === 38){ +// //向上 +// if(index <= 0){ +// index = newArr.length; +// } +// index--; +// }else if(e.keyCode === 40){ +// //向下 +// if(index >= newArr.length - 1){ +// index = -1; +// } +// index++; +// }else if(e.keyCode === 13){ +// //回车 +// if(index > -1 && index < newArr.length){ +// //如果当前有激活列表 +// $(this).val($("#mailList_"+index).text()); +// } +// }else{ +// if(/@/.test(v)){ +// index = -1; +// //获得@后面的值 +// //s = v.replace(/@.*/, ""); +// //创建新匹配数组 +// var site = v.replace(/.*@/, ""); +// newArr = $.map(mailArr, function(n){ +// var reg = new RegExp(site); +// if(reg.test(n)){ +// return n; +// } +// }); +// }else{ +// newArr = mailArr; +// } +// } +// x.html($.createHtml(s, newArr, index)).css("left", 0); +// if(e.keyCode === 13){ +// //回车 +// if(index > -1 && index < newArr.length){ +// //如果当前有激活列表 +// x.css("left", "-6000px"); +// } +// } +// }else{ +// x.css("left", "-6000px"); +// } +// }).blur(function(){ +// if(hint && text){ +// var blur_v = $.trim($(this).val()); +// if(blur_v === ""){ +// $(this).val(text); +// } +// } +// $(this).css("color", bc).unbind("keyup").parent().css("z-index",0); +// x.css("left", "-6000px"); +// +// }).keydown(function(event){ +// if(event.keyCode == 13){ +// return false; +// } +// }); +// //鼠标经过列表项事件 +// //鼠标经过 +// $(".mailHover").on("mouseover", function(){ +// index = Number($(this).attr("id").split("_")[1]); +// liveValue = $("#mailList_"+index).text(); +// x.children("." + cf).removeClass(cf).addClass(cl); +// $(this).addClass(cf).removeClass(cl); +// }); +// $(".mailHover").on("click", function(){ +// $("#mail").val($(this).html()); +// }); +// +// +// }); +// +// x.bind("mousedown", function(){ +// that.val(liveValue); +// }); +// }); }; })(jQuery); \ No newline at end of file diff --git a/public/javascripts/jquery-1.3.2.js b/public/javascripts/jquery-1.3.2.js new file mode 100644 index 000000000..b1ae21d8b --- /dev/null +++ b/public/javascripts/jquery-1.3.2.js @@ -0,0 +1,19 @@ +/* + * jQuery JavaScript Library v1.3.2 + * http://jquery.com/ + * + * Copyright (c) 2009 John Resig + * Dual licensed under the MIT and GPL licenses. + * http://docs.jquery.com/License + * + * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) + * Revision: 6246 + */ +(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("",""]||!O.indexOf("",""]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
    "]||!O.indexOf("
    "]||(!O.indexOf("",""]||!O.indexOf("",""]||!o.support.htmlSerialize&&[1,"div
    ","
    "]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}}); +/* + * Sizzle CSS Selector Engine - v0.9.3 + * Copyright 2009, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return UT[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="

    ";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="
    ";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("
    ").append(M.responseText.replace(//g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='
    ';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})(); \ No newline at end of file diff --git a/public/javascripts/jquery.autosize.js b/public/javascripts/jquery.autosize.js new file mode 100644 index 000000000..4a7bc8fd2 --- /dev/null +++ b/public/javascripts/jquery.autosize.js @@ -0,0 +1,274 @@ +/*! + Autosize 1.18.13 + license: MIT + http://www.jacklmoore.com/autosize +*/ +(function ($) { + var + defaults = { + className: 'autosizejs', + id: 'autosizejs', + append: '\n', + callback: false, + resizeDelay: 10, + placeholder: true + }, + + // border:0 is unnecessary, but avoids a bug in Firefox on OSX + copy = '