code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
#include <iostream>
#include <string>
#include "TFile.h"
#include "TTree.h"
#include "TH1F.h"
#include "TMVA/Factory.h"
using namespace std;
class TMVAVar{
public:
TMVAVar(string v, string t, string u, char y):
varname(v),vartitle(t),unit(u),vartype(y){}
string varname;
string vartitle;
string unit;
char vartype;
};
void train(TFile* sigFile,
TFile* bkgFile,
TFile* outFile,
std::vector<TMVAVar*>& vars,
std::vector<string>& spectators,
string treeName,
string tag,
string cut){
outFile->cd();
TTree* sigTree = (TTree*)sigFile->Get(treeName.c_str());
TTree* bkgTree = (TTree*)bkgFile->Get(treeName.c_str());
outFile->cd();
cout << "Creating factory" << endl;
TMVA::Factory* factory = new TMVA::Factory( Form("MVA_%s",tag.c_str()), outFile,
"V:Color:DrawProgressBar:AnalysisType=Classification" );
Double_t weight=1.;
cout << "Adding trees" << endl;
factory->AddSignalTree (sigTree, weight);
factory->AddBackgroundTree(bkgTree, weight);
cout << "Adding spectators and weights" << endl;
for(unsigned int i=0; i<spectators.size(); i++){
cout << "... " << spectators[i] << endl;
factory->AddSpectator(spectators[i].c_str());
}
// this one we hard code
factory->AddSpectator("weight");
factory->SetWeightExpression("weight");
cout << "Adding variables" << endl;
for(unsigned int i=0; i<vars.size(); i++){
cout << "... " << vars[i]->varname << endl;
factory->AddVariable(vars[i]->varname.c_str(),
vars[i]->vartitle.c_str(),
vars[i]->unit.c_str(),
vars[i]->vartype);
}
cout << "Preparing trees" << endl;
factory->PrepareTrainingAndTestTree(cut.c_str(),"NormMode=None");
/*
factory->BookMethod( TMVA::Types::kCuts, "Cuts",
"FitMethod=GA:VarProp=FMax");
*/
outFile->cd();
cout << "Booking BDT" << endl;
factory->BookMethod( TMVA::Types::kBDT, "BDT",
"!H:V:NTrees=850:nEventsMin=150:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" );
cout << "Training" << endl;
factory->TrainAllMethods();
factory->TestAllMethods();
factory->EvaluateAllMethods();
return;
}
void train_DG(string signal,
string background,
string output,
string tag,
string cut,
std::vector<string>& variables,
std::vector<string>& spectators){
TFile* sig = new TFile(signal.c_str(),"RO");
TFile* bkg = new TFile(background.c_str(),"RO");
// this is a bit of a kludge, in that we assume all variables are floats and
// all have units of GeV. maybe fix it later.
std::vector<TMVAVar*> vars;
for(unsigned int i=0; i<variables.size(); i++){
if(variables[i][0] != 'n')
vars.push_back(new TMVAVar(variables[i], variables[i], "GeV", 'F'));
else
vars.push_back(new TMVAVar(variables[i], variables[i], "", 'i'));
}
TFile* out = new TFile(output.c_str(),"RECREATE");
train(sig,bkg,out,vars,spectators,"OutputTree",tag,cut);
out->Close();
}
int main(int argc, char** argv){
string signal;
string background;
string output;
string tag;
string cut;
bool useZmass=false;
std::vector<string> variables,spectators;
opterr = 0;
int c;
while ((c = getopt (argc, argv, "s:b:o:t:c:v:p:")) != -1)
switch (c){
case 's':
signal=optarg;
break;
case 'b':
background=optarg;
break;
case 'o':
output=optarg;
break;
case 't':
tag=optarg;
break;
case 'c':
cut=optarg;
break;
case 'v':
variables.push_back(optarg);
break;
case 'p':
spectators.push_back(optarg);
break;
default:
return 0;
}
if(!variables.size()){
std::cout << "No training variables specified -- not running TMVA." << std::endl;
return 0;
}
train_DG(signal,background,output,tag,cut,variables,spectators);
return 0;
}
|
mhance/physics
|
Snowmass/DelphesReader/scripts/train_MVA.C
|
C++
|
gpl-2.0
| 3,923 |
cmd_sound/pci/lx6464es/built-in.o := rm -f sound/pci/lx6464es/built-in.o; arm-linux-gnueabihf-ar rcsD sound/pci/lx6464es/built-in.o
|
Dee-UK/D33_KK_Kernel
|
sound/pci/lx6464es/.built-in.o.cmd
|
Batchfile
|
gpl-2.0
| 133 |
#!/usr/bin/env rspec
# Copyright (c) [2018] SUSE LLC
#
# All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, contact SUSE LLC.
#
# To contact SUSE LLC about this file by physical or electronic mail, you may
# find current contact information at www.suse.com.
require_relative "../test_helper"
require "cwm/rspec"
require "y2partitioner/widgets/fstab_selector"
require "y2partitioner/actions/controllers/fstabs"
describe Y2Partitioner::Widgets::FstabSelector do
def button(contents, id)
contents.nested_find do |widget|
widget.is_a?(Yast::Term) &&
widget.value == :PushButton &&
widget.params.first.params.include?(id)
end
end
def filesystem(device_name)
device = Y2Partitioner::DeviceGraphs.instance.current.find_by_name(device_name)
device.filesystem
end
subject { described_class.new(controller) }
let(:controller) { Y2Partitioner::Actions::Controllers::Fstabs.new }
before do
devicegraph_stub("mixed_disks.yml")
allow(controller).to receive(:fstabs).and_return(fstabs)
allow(fstab1).to receive(:entries).and_return(fstab1_entries)
allow(fstab2).to receive(:entries).and_return(fstab2_entries)
allow(fstab3).to receive(:entries).and_return(fstab3_entries)
allow(Yast::UI).to receive(:ChangeWidget).and_call_original
controller.selected_fstab = selected_fstab
end
let(:fstab1) { Y2Storage::Fstab.new("", filesystem("/dev/sda2")) }
let(:fstab2) { Y2Storage::Fstab.new("", filesystem("/dev/sdb2")) }
let(:fstab3) { Y2Storage::Fstab.new("", filesystem("/dev/sdb6")) }
let(:fstab1_entries) do
[
fstab_entry("/dev/sda2", "/", ext4, [], 0, 0),
fstab_entry("/dev/sdb2", "/home", ext4, [], 0, 0)
]
end
let(:fstab2_entries) do
[
fstab_entry("/dev/sda2", "/", ext4, [], 0, 0)
]
end
let(:fstab3_entries) do
[
fstab_entry("/dev/unknown", "/", ext4, [], 0, 0)
]
end
let(:ext4) { Y2Storage::Filesystems::Type::EXT4 }
let(:fstabs) { [fstab1, fstab2, fstab3] }
let(:selected_fstab) { fstab1 }
include_examples "CWM::CustomWidget"
describe "#init" do
let(:selected_fstab) { nil }
it "selects the first fstab" do
subject.init
expect(controller.selected_fstab).to eq(fstabs.first)
end
it "disables button to 'select previous' fstab" do
expect(Yast::UI).to receive(:ChangeWidget).with(Id(:show_prev), :Enabled, false)
subject.init
end
context "when there is only one fstab" do
let(:fstabs) { [fstab1] }
it "disables button to 'select next' fstab" do
expect(Yast::UI).to receive(:ChangeWidget).with(Id(:show_next), :Enabled, false)
subject.init
end
end
context "when there are several fstabs" do
let(:fstabs) { [fstab1, fstab2] }
it "does not disable button to 'select next' fstab" do
expect(Yast::UI).to_not receive(:ChangeWidget).with(Id(:show_next), :Enabled, false)
subject.init
end
end
end
describe "#contents" do
let(:selected_fstab) { fstab1 }
it "shows the selected fstab" do
expect(Y2Partitioner::Widgets::FstabSelector::FstabContent).to receive(:new)
.with(controller.selected_fstab)
subject.contents
end
it "shows buttons to switch between fstabs" do
expect(button(subject.contents, :show_prev)).to_not be_nil
expect(button(subject.contents, :show_next)).to_not be_nil
end
end
describe "#handle" do
let(:event) { { "ID" => button } }
context "when 'show prev' button is selected" do
let(:selected_fstab) { fstab2 }
let(:button) { :show_prev }
it "selects the previous fstab" do
subject.handle(event)
expect(controller.selected_fstab).to eq(fstab1)
end
context "when the previous fstab is the first one" do
let(:selected_fstab) { fstab2 }
it "disables button to 'select previous' fstab" do
expect(Yast::UI).to receive(:ChangeWidget).with(Id(:show_prev), :Enabled, false)
subject.handle(event)
end
end
context "when the previous fstab is not the first one" do
let(:selected_fstab) { fstab3 }
it "does not disable button to 'select previous' fstab" do
expect(Yast::UI).to_not receive(:ChangeWidget).with(Id(:show_prev), :Enabled, false)
subject.handle(event)
end
end
end
context "when 'show next' button is selected" do
let(:selected_fstab) { fstab1 }
let(:button) { :show_next }
it "selects the next fstab" do
subject.handle(event)
expect(controller.selected_fstab).to eq(fstab2)
end
context "when the next fstab is the last one" do
let(:selected_fstab) { fstab2 }
# Mock #find_by_any_name that is called by SimpleEtcFstabEntry#find_device.
# FIXME: that happens many times, which shows some caching is missing in the widget.
before { allow(Y2Storage::BlkDevice).to receive(:find_by_any_name) }
it "disables button to 'select next' fstab" do
expect(Yast::UI).to receive(:ChangeWidget).with(Id(:show_next), :Enabled, false)
subject.handle(event)
end
end
context "when the next fstab is not the last one" do
let(:selected_fstab) { fstab1 }
it "does not disable button to 'select next' fstab" do
expect(Yast::UI).to_not receive(:ChangeWidget).with(Id(:show_next), :Enabled, false)
subject.handle(event)
end
end
end
context "when 'help' button is selected" do
let(:button) { :help }
it "shows the help" do
expect(Yast::Wizard).to receive(:ShowHelp).with(/has scanned/)
subject.handle(event)
end
end
end
describe "#validate" do
before do
allow(Yast2::Popup).to receive(:show).and_return(accept)
# See comment above about #find_by_any_name and SimpleEtcFstabEntry#find_device
allow(Y2Storage::BlkDevice).to receive(:find_by_any_name)
end
let(:accept) { nil }
context "when some mount point of the selected fstab cannot be imported" do
let(:selected_fstab) { fstab3 }
it "shows an error popup" do
expect(Yast2::Popup).to receive(:show)
subject.validate
end
context "and the user accepts" do
let(:accept) { :yes }
it "returns true" do
expect(subject.validate).to eq(true)
end
end
context "and the user does not accept" do
let(:accept) { :no }
it "returns false" do
expect(subject.validate).to eq(false)
end
end
end
context "when all mount points of the selected fstab can be imported" do
let(:selected_fstab) { fstab1 }
it "does not show an error" do
expect(Yast2::Popup).to_not receive(:show)
subject.validate
end
it "returns true" do
expect(subject.validate).to eq(true)
end
end
end
describe Y2Partitioner::Widgets::FstabSelector::FstabArea do
include_examples "CWM::CustomWidget"
end
describe Y2Partitioner::Widgets::FstabSelector::FstabContent do
subject { described_class.new(selected_fstab) }
include_examples "CWM::CustomWidget"
end
describe Y2Partitioner::Widgets::FstabSelector::FstabTable do
subject { described_class.new(selected_fstab) }
include_examples "CWM::CustomWidget"
end
end
|
yast/yast-storage-ng
|
test/y2partitioner/widgets/fstab_selector_test.rb
|
Ruby
|
gpl-2.0
| 7,960 |
/**
* vboreplay - Tool to replay from a VBO file.
* Copyright (C) 2015 Chalmers ReVeRe
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef VBOREPLAYTESTSUITE_H_
#define VBOREPLAYTESTSUITE_H_
#include "cxxtest/TestSuite.h"
// Include local header files.
#include "../include/VBOReplay.h"
using namespace std;
using namespace revere;
/**
* This class derives from VBOReplay to allow access to protected methods.
*/
class VBOReplayTestling : public VBOReplay {
private:
VBOReplayTestling();
public:
VBOReplayTestling(const int32_t &argc, char **argv) :
VBOReplay(argc, argv) {}
// Here, you need to add all methods which are protected in VBOReplay and which are needed for the test cases.
};
/**
* The actual testsuite starts here.
*/
class VBOReplayTest : public CxxTest::TestSuite {
private:
VBOReplayTestling *dt;
public:
/**
* This method will be called before each testXYZ-method.
*/
void setUp() {
// Prepare the data that would be available from commandline.
string argv0("vboreplay");
string argv1("--cid=100");
int32_t argc = 2;
char **argv;
argv = new char*[2];
argv[0] = const_cast<char*>(argv0.c_str());
argv[1] = const_cast<char*>(argv1.c_str());
// Create an instance of sensorboard through SensorBoardTestling which will be deleted in tearDown().
dt = new VBOReplayTestling(argc, argv);
}
/**
* This method will be called after each testXYZ-method.
*/
void tearDown() {
delete dt;
dt = NULL;
}
////////////////////////////////////////////////////////////////////////////////////
// Below this line the actual testcases are defined.
////////////////////////////////////////////////////////////////////////////////////
void testVBOReplaySuccessfullyCreated() {
TS_ASSERT(dt != NULL);
}
////////////////////////////////////////////////////////////////////////////////////
// Below this line the necessary constructor for initializing the pointer variables,
// and the forbidden copy constructor and assignment operator are declared.
//
// These functions are normally not changed.
////////////////////////////////////////////////////////////////////////////////////
public:
/**
* This constructor is only necessary to initialize the pointer variable.
*/
VBOReplayTest() : dt(NULL) {}
private:
/**
* "Forbidden" copy constructor. Goal: The compiler should warn
* already at compile time for unwanted bugs caused by any misuse
* of the copy constructor.
*
* @param obj Reference to an object of this class.
*/
VBOReplayTest(const VBOReplayTest &/*obj*/);
/**
* "Forbidden" assignment operator. Goal: The compiler should warn
* already at compile time for unwanted bugs caused by any misuse
* of the assignment operator.
*
* @param obj Reference to an object of this class.
* @return Reference to this instance.
*/
VBOReplayTest& operator=(const VBOReplayTest &/*obj*/);
};
#endif /*VBOREPLAYTESTSUITE_H_*/
|
Pletron/opendlv
|
code/tools/vboreplay/testsuites/VBOReplayTestSuite.h
|
C
|
gpl-2.0
| 4,104 |
/******************************************************************************
* Wormux, a free clone of the game Worms from Team17.
* Copyright (C) 2001-2004 Lawrence Azzoug.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
******************************************************************************
* Keyboard managment.
*****************************************************************************/
#include "keyboard.h"
#include <sstream>
#include <iostream>
#include "cursor.h"
#include "game_msg.h"
#include "interface.h"
#include "../game/config.h"
#include "../game/game.h"
#include "../game/game_loop.h"
#include "../game/game_mode.h"
#include "../game/time.h"
#include "../graphic/video.h"
#include "../include/action_handler.h"
#include "../include/constant.h"
#include "../map/camera.h"
#include "../team/macro.h"
#include "../team/move.h"
#include "../tool/i18n.h"
#include "../tool/math_tools.h"
#include "../sound/jukebox.h"
#include "../map/camera.h"
#include "../weapon/weapon.h"
#include "../weapon/weapons_list.h"
// Active le mode tricheur ?
#ifdef DEBUG
# define MODE_TRICHEUR
//# define USE_HAND_POSITION_MODIFIER
#endif
// Vitesse du definalement au clavier
#define SCROLL_CLAVIER 20 // ms
Clavier * Clavier::singleton = NULL;
Clavier * Clavier::GetInstance() {
if (singleton == NULL) {
singleton = new Clavier();
}
return singleton;
}
Clavier::Clavier()
{}
void Clavier::Reset()
{
//Disable repeated events when a key is kept down
SDL_EnableKeyRepeat(0,0);
for (uint i = 0; i < ACTION_MAX; i++)
PressedKeys[i] = false ;
}
void Clavier::SetKeyAction(int key, Action_t at)
{
layout[key] = at;
}
void Clavier::HandleKeyEvent( const SDL_Event *event)
{
std::map<int, Action_t>::iterator it = layout.find(event->key.keysym.sym);
if ( it == layout.end() )
return;
Action_t action = it->second;
//We can perform the next actions, only if the player is played localy:
//if(!ActiveTeam().is_local)
// return;
if(action <= ACTION_CHANGE_CHARACTER)
{
switch (action) {
// case ACTION_ADD:
// if (lance_grenade.time < 15)
// lance_grenade.time ++;
// break ;
// case ACTION_SUBSTRACT:
// if (lance_grenade.time > 1)
// lance_grenade.time --;
// break ;
default:
break ;
}
}
int event_type=0;
switch( event->type)
{
case SDL_KEYDOWN: event_type = KEY_PRESSED;break;
case SDL_KEYUP: event_type = KEY_RELEASED;break;
}
if(event_type==KEY_PRESSED)
HandleKeyPressed(action);
if(event_type==KEY_RELEASED)
HandleKeyReleased(action);
if (ActiveTeam().GetWeapon().override_keys &&
ActiveTeam().GetWeapon().IsActive())
{
ActiveTeam().AccessWeapon().HandleKeyEvent((int)action, event_type);
return ;
}
ActiveCharacter().HandleKeyEvent( action, event_type);
}
// Handle a pressed key
void Clavier::HandleKeyPressed (const Action_t &action)
{
PressedKeys[action] = true ;
//We can perform the next actions, only if the player is played localy:
if(!ActiveTeam().is_local)
return;
if (GameLoop::GetInstance()->ReadState() == GameLoop::PLAYING &&
ActiveTeam().GetWeapon().CanChangeWeapon())
{
int weapon_sort = -1;
switch(action) {
case ACTION_WEAPONS1:
weapon_sort = 1;
break;
case ACTION_WEAPONS2:
weapon_sort = 2;
break;
case ACTION_WEAPONS3:
weapon_sort = 3;
break;
case ACTION_WEAPONS4:
weapon_sort = 4;
break;
case ACTION_WEAPONS5:
weapon_sort = 5;
break;
case ACTION_WEAPONS6:
weapon_sort = 6;
break;
case ACTION_WEAPONS7:
weapon_sort = 7;
break;
case ACTION_WEAPONS8:
weapon_sort = 8;
break;
case ACTION_CHANGE_CHARACTER:
if (GameMode::GetInstance()->AllowCharacterSelection())
ActionHandler::GetInstance()->NewAction(ActionInt(action,
ActiveTeam().NextCharacterIndex()));
return ;
default:
break ;
}
if ( weapon_sort > 0 )
{
Weapon_type weapon;
if (weapons_list.GetWeaponBySort(weapon_sort, weapon))
ActionHandler::GetInstance()->NewAction(ActionInt(ACTION_CHANGE_WEAPON, weapon));
return;
}
}
}
// Handle a released key
void Clavier::HandleKeyReleased (const Action_t &action)
{
PressedKeys[action] = false ;
// We manage here only actions which are active on KEY_RELEASED event.
Interface * interface = Interface::GetInstance();
switch(action) {
case ACTION_QUIT:
Game::GetInstance()->SetEndOfGameStatus( true );
return;
case ACTION_PAUSE:
Game::GetInstance()->Pause();
return;
case ACTION_FULLSCREEN:
#ifdef TODO
video.SetFullScreen( !video.IsFullScreen() );
#endif
return;
case ACTION_TOGGLE_INTERFACE:
interface->EnableDisplay (!interface->IsDisplayed());
return;
case ACTION_CENTER:
CurseurVer::GetInstance()->SuitVerActif();
camera.ChangeObjSuivi (&ActiveCharacter(), true, true, true);
return;
case ACTION_TOGGLE_WEAPONS_MENUS:
interface->weapons_menu.SwitchDisplay();
return;
default:
break ;
}
}
// Refresh keys which are still pressed.
void Clavier::Refresh()
{
//Treat KEY_REFRESH events:
for (uint i = 0; i < ACTION_MAX; i++)
if(PressedKeys[i])
{
if (ActiveTeam().GetWeapon().override_keys &&
ActiveTeam().GetWeapon().IsActive())
{
ActiveTeam().AccessWeapon().HandleKeyEvent(i, KEY_REFRESH);
}
else
{
ActiveCharacter().HandleKeyEvent(i,KEY_REFRESH);
}
}
}
void Clavier::TestCamera()
{
}
|
yeKcim/warmux
|
old/wormux-0.7/src/interface/keyboard.cpp
|
C++
|
gpl-2.0
| 6,358 |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* gs_stack_pop.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dwillems <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/12/19 14:13:02 by dwillems #+# #+# */
/* Updated: 2015/12/21 16:01:45 by dwillems ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
t_stack *gs_stack_pop(t_stack **list)
{
t_stack *ret;
if (gs_stack_isempty(*list))
return (NULL);
ret = *list;
*list = (*list)->next;
return (ret);
}
|
42dannywillems/42_libft
|
srcs/gs_stack_pop.c
|
C
|
gpl-2.0
| 1,070 |
module Email
class Processor
def initialize(mail)
@mail = mail
end
def self.process!(mail)
Email::Processor.new(mail).process!
end
def process!
begin
receiver = Email::Receiver.new(@mail)
receiver.process!
rescue Email::Receiver::BouncedEmailError => e
# never reply to bounced emails
log_email_process_failure(@mail, e)
set_incoming_email_rejection_message(receiver.incoming_email, I18n.t("emails.incoming.errors.bounced_email_error"))
rescue => e
log_email_process_failure(@mail, e)
incoming_email = receiver.try(:incoming_email)
rejection_message = handle_failure(@mail, e, incoming_email)
if rejection_message.present?
set_incoming_email_rejection_message(incoming_email, rejection_message.body.to_s)
end
end
end
private
def handle_failure(mail_string, e, incoming_email)
message_template = case e
when Email::Receiver::EmptyEmailError then :email_reject_empty
when Email::Receiver::NoBodyDetectedError then :email_reject_empty
when Email::Receiver::UserNotFoundError then :email_reject_user_not_found
when Email::Receiver::ScreenedEmailError then :email_reject_screened_email
when Email::Receiver::AutoGeneratedEmailError then :email_reject_auto_generated
when Email::Receiver::InactiveUserError then :email_reject_inactive_user
when Email::Receiver::BlockedUserError then :email_reject_blocked_user
when Email::Receiver::BadDestinationAddress then :email_reject_bad_destination_address
when Email::Receiver::StrangersNotAllowedError then :email_reject_strangers_not_allowed
when Email::Receiver::InsufficientTrustLevelError then :email_reject_insufficient_trust_level
when Email::Receiver::ReplyUserNotMatchingError then :email_reject_reply_user_not_matching
when Email::Receiver::TopicNotFoundError then :email_reject_topic_not_found
when Email::Receiver::TopicClosedError then :email_reject_topic_closed
when Email::Receiver::InvalidPost then :email_reject_invalid_post
when ActiveRecord::Rollback then :email_reject_invalid_post
when Email::Receiver::InvalidPostAction then :email_reject_invalid_post_action
when Discourse::InvalidAccess then :email_reject_invalid_access
when RateLimiter::LimitExceeded then :email_reject_rate_limit_specified
end
template_args = {}
client_message = nil
# there might be more information available in the exception
if message_template == :email_reject_invalid_post && e.message.size > 6
message_template = :email_reject_invalid_post_specified
template_args[:post_error] = e.message
end
if message_template == :email_reject_rate_limit_specified
template_args[:rate_limit_description] = e.description
end
if message_template
# inform the user about the rejection
message = Mail::Message.new(mail_string)
template_args[:former_title] = message.subject
template_args[:destination] = message.to
template_args[:site_name] = SiteSetting.title
client_message = RejectionMailer.send_rejection(message_template, message.from, template_args)
# only send one rejection email per day to the same email address
if can_send_rejection_email?(message.from, message_template)
Email::Sender.new(client_message, message_template).send
end
else
msg = "Unrecognized error type (#{e.class}: #{e.message}) when processing incoming email"
msg += "\n\nBacktrace:\n#{e.backtrace.map { |l| " #{l}" }.join("\n")}"
msg += "\n\nMail:\n#{mail_string}"
Rails.logger.error(msg)
end
client_message
end
def can_send_rejection_email?(email, type)
key = "rejection_email:#{email}:#{type}:#{Date.today}"
if $redis.setnx(key, "1")
$redis.expire(key, 25.hours)
true
else
false
end
end
def set_incoming_email_rejection_message(incoming_email, message)
incoming_email.update_attributes!(rejection_message: message)
end
def log_email_process_failure(mail_string, exception)
if SiteSetting.log_mail_processing_failures
Rails.logger.warn("Email can not be processed: #{exception}\n\n#{mail_string}")
end
end
end
end
|
ngpestelos/discourse
|
lib/email/processor.rb
|
Ruby
|
gpl-2.0
| 4,640 |
#
# Makefile for the ATM Protocol Families.
#
# Note! Dependencies are done automagically by 'make dep', which also
# removes any old dependencies. DON'T put your own dependencies here
# unless it's something special (ie not a .c file).
#
# Note 2! The CFLAGS definition is now in the main makefile...
O_TARGET := atm.o
export-objs := common.o atm_misc.o raw.o resources.o ipcommon.o proc.o
list-multi := mpoa.o
mpoa-objs := mpc.o mpoa_caches.o mpoa_proc.o
obj-$(CONFIG_ATM) := addr.o pvc.o signaling.o svc.o common.o atm_misc.o raw.o resources.o
ifeq ($(CONFIG_ATM_CLIP),y)
obj-y += clip.o
NEED_IPCOM = ipcommon.o
endif
ifeq ($(CONFIG_NET_SCH_ATM),y)
NEED_IPCOM = ipcommon.o
endif
obj-y += $(NEED_IPCOM)
ifeq ($(CONFIG_PROC_FS),y)
obj-y += proc.o
endif
obj-$(CONFIG_ATM_LANE) += lec.o
obj-$(CONFIG_ATM_MPOA) += mpoa.o
obj-$(CONFIG_PPPOATM) += pppoatm.o
include $(TOPDIR)/Rules.make
mpoa.o: $(mpoa-objs)
$(LD) -r -o mpoa.o $(mpoa-objs)
|
hugh712/my_driver_study
|
Jollen/jk2410/kernel-jk2410/net/atm/Makefile
|
Makefile
|
gpl-2.0
| 949 |
# -*- coding: utf-8 -*-
"""
***************************************************************************
SumLines.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os.path
from PyQt4 import QtGui
from PyQt4.QtCore import *
from qgis.core import *
from sextante.core.GeoAlgorithm import GeoAlgorithm
from sextante.core.QGisLayers import QGisLayers
from sextante.core.SextanteLog import SextanteLog
from sextante.parameters.ParameterVector import ParameterVector
from sextante.parameters.ParameterString import ParameterString
from sextante.outputs.OutputVector import OutputVector
from sextante.algs.ftools import FToolsUtils as utils
class SumLines(GeoAlgorithm):
LINES = "LINES"
POLYGONS = "POLYGONS"
LEN_FIELD = "LEN_FIELD"
COUNT_FIELD = "COUNT_FIELD"
OUTPUT = "OUTPUT"
#===========================================================================
# def getIcon(self):
# return QtGui.QIcon(os.path.dirname(__file__) + "/icons/sum_lines.png")
#===========================================================================
def defineCharacteristics(self):
self.name = "Sum line lengths"
self.group = "Vector analysis tools"
self.addParameter(ParameterVector(self.LINES, "Lines", ParameterVector.VECTOR_TYPE_LINE))
self.addParameter(ParameterVector(self.POLYGONS, "Polygons", ParameterVector.VECTOR_TYPE_POLYGON))
self.addParameter(ParameterString(self.LEN_FIELD, "Lines length field name", "LENGTH"))
self.addParameter(ParameterString(self.COUNT_FIELD, "Lines count field name", "COUNT"))
self.addOutput(OutputVector(self.OUTPUT, "Result"))
def processAlgorithm(self, progress):
lineLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.LINES))
polyLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POLYGONS))
lengthFieldName = self.getParameterValue(self.LEN_FIELD)
countFieldName = self.getParameterValue(self.COUNT_FIELD)
polyProvider = polyLayer.dataProvider()
idxLength, fieldList = utils.findOrCreateField(polyLayer, polyLayer.pendingFields(), lengthFieldName)
idxCount, fieldList = utils.findOrCreateField(polyLayer, fieldList, countFieldName)
writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList.toList(),
polyProvider.geometryType(), polyProvider.crs())
spatialIndex = utils.createSpatialIndex(lineLayer)
ftLine = QgsFeature()
ftPoly = QgsFeature()
outFeat = QgsFeature()
inGeom = QgsGeometry()
outGeom = QgsGeometry()
distArea = QgsDistanceArea()
current = 0
features = QGisLayers.features(polyLayer)
total = 100.0 / float(len(features))
hasIntersections = False
for ftPoly in features:
inGeom = QgsGeometry(ftPoly.geometry())
attrs = ftPoly.attributes()
count = 0
length = 0
hasIntersections = False
lines = spatialIndex.intersects(inGeom.boundingBox())
if len(lines) > 0:
hasIntersections = True
if hasIntersections:
for i in lines:
request = QgsFeatureRequest().setFilterFid(i)
ftLine = lineLayer.getFeatures(request).next()
tmpGeom = QgsGeometry(ftLine.geometry())
if inGeom.intersects(tmpGeom):
outGeom = inGeom.intersection(tmpGeom)
length += distArea.measure(outGeom)
count += 1
outFeat.setGeometry(inGeom)
if idxLength == len(attrs):
attrs.append(length)
else:
attrs[idxLength] = length
if idxCount == len(attrs):
attrs.append(count)
else:
attrs[idxCount] = count
outFeat.setAttributes(attrs)
writer.addFeature(outFeat)
current += 1
progress.setPercentage(int(current * total))
del writer
|
alexgleith/Quantum-GIS
|
python/plugins/sextante/algs/ftools/SumLines.py
|
Python
|
gpl-2.0
| 5,049 |
<?php
/**
* Upgrade API: WP_Upgrader class
*
* Requires skin classes and WP_Upgrader subclasses for backward compatibility.
*
* @package WordPress
* @subpackage Upgrader
* @since 2.8.0
*/
/** WP_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader-skin.php';
/** Plugin_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader-skin.php';
/** Theme_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-theme-upgrader-skin.php';
/** Bulk_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-bulk-upgrader-skin.php';
/** Bulk_Plugin_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-bulk-plugin-upgrader-skin.php';
/** Bulk_Theme_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-bulk-theme-upgrader-skin.php';
/** Plugin_Installer_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-plugin-installer-skin.php';
/** Theme_Installer_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-theme-installer-skin.php';
/** Language_Pack_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-language-pack-upgrader-skin.php';
/** Automatic_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-automatic-upgrader-skin.php';
/** WP_Ajax_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-wp-ajax-upgrader-skin.php';
/**
* Core class used for upgrading/installing a local set of files via
* the Filesystem Abstraction classes from a Zip file.
*
* @since 2.8.0
*/
class WP_Upgrader {
/**
* The error/notification strings used to update the user on the progress.
*
* @since 2.8.0
* @access public
* @var array $strings
*/
public $strings = array();
/**
* The upgrader skin being used.
*
* @since 2.8.0
* @access public
* @var Automatic_Upgrader_Skin|WP_Upgrader_Skin $skin
*/
public $skin = null;
/**
* The result of the installation.
*
* This is set by WP_Upgrader::install_package(), only when the package is installed
* successfully. It will then be an array, unless a WP_Error is returned by the
* {@see 'upgrader_post_install'} filter. In that case, the WP_Error will be assigned to
* it.
*
* @since 2.8.0
* @access public
*
* @var WP_Error|array $result {
* @type string $source The full path to the source the files were installed from.
* @type string $source_files List of all the files in the source directory.
* @type string $destination The full path to the install destination folder.
* @type string $destination_name The name of the destination folder, or empty if `$destination`
* and `$local_destination` are the same.
* @type string $local_destination The full local path to the destination folder. This is usually
* the same as `$destination`.
* @type string $remote_destination The full remote path to the destination folder
* (i.e., from `$wp_filesystem`).
* @type bool $clear_destination Whether the destination folder was cleared.
* }
*/
public $result = array();
/**
* The total number of updates being performed.
*
* Set by the bulk update methods.
*
* @since 3.0.0
* @access public
* @var int $update_count
*/
public $update_count = 0;
/**
* The current update if multiple updates are being performed.
*
* Used by the bulk update methods, and incremented for each update.
*
* @since 3.0.0
* @access public
* @var int
*/
public $update_current = 0;
/**
* Construct the upgrader with a skin.
*
* @since 2.8.0
* @access public
*
* @param WP_Upgrader_Skin $skin The upgrader skin to use. Default is a WP_Upgrader_Skin.
* instance.
*/
public function __construct( $skin = null ) {
if ( null == $skin )
$this->skin = new WP_Upgrader_Skin();
else
$this->skin = $skin;
}
/**
* Initialize the upgrader.
*
* This will set the relationship between the skin being used and this upgrader,
* and also add the generic strings to `WP_Upgrader::$strings`.
*
* @since 2.8.0
* @access public
*/
public function init() {
$this->skin->set_upgrader($this);
$this->generic_strings();
}
/**
* Add the generic strings to WP_Upgrader::$strings.
*
* @since 2.8.0
* @access public
*/
public function generic_strings() {
$this->strings['bad_request'] = __('Invalid data provided.');
$this->strings['fs_unavailable'] = __('Could not access filesystem.');
$this->strings['fs_error'] = __('Filesystem error.');
$this->strings['fs_no_root_dir'] = __('Unable to locate WordPress root directory.');
$this->strings['fs_no_content_dir'] = __('Unable to locate WordPress content directory (wp-content).');
$this->strings['fs_no_plugins_dir'] = __('Unable to locate WordPress plugin directory.');
$this->strings['fs_no_themes_dir'] = __('Unable to locate WordPress theme directory.');
/* translators: %s: directory name */
$this->strings['fs_no_folder'] = __('Unable to locate needed folder (%s).');
$this->strings['download_failed'] = __('Download failed.');
$this->strings['installing_package'] = __('Installing the latest version…');
$this->strings['no_files'] = __('The package contains no files.');
$this->strings['folder_exists'] = __('Destination folder already exists.');
$this->strings['mkdir_failed'] = __('Could not create directory.');
$this->strings['incompatible_archive'] = __('The package could not be installed.');
$this->strings['files_not_writable'] = __( 'The update cannot be installed because we will be unable to copy some files. This is usually due to inconsistent file permissions.' );
$this->strings['maintenance_start'] = __('Enabling Maintenance mode…');
$this->strings['maintenance_end'] = __('Disabling Maintenance mode…');
}
/**
* Connect to the filesystem.
*
* @since 2.8.0
* @access public
*
* @global WP_Filesystem_Base $wp_filesystem Subclass
*
* @param array $directories Optional. A list of directories. If any of these do
* not exist, a WP_Error object will be returned.
* Default empty array.
* @param bool $allow_relaxed_file_ownership Whether to allow relaxed file ownership.
* Default false.
* @return bool|WP_Error True if able to connect, false or a WP_Error otherwise.
*/
public function fs_connect( $directories = array(), $allow_relaxed_file_ownership = false ) {
global $wp_filesystem;
if ( false === ( $credentials = $this->skin->request_filesystem_credentials( false, $directories[0], $allow_relaxed_file_ownership ) ) ) {
return false;
}
if ( ! WP_Filesystem( $credentials, $directories[0], $allow_relaxed_file_ownership ) ) {
$error = true;
if ( is_object($wp_filesystem) && $wp_filesystem->errors->get_error_code() )
$error = $wp_filesystem->errors;
// Failed to connect, Error and request again
$this->skin->request_filesystem_credentials( $error, $directories[0], $allow_relaxed_file_ownership );
return false;
}
if ( ! is_object($wp_filesystem) )
return new WP_Error('fs_unavailable', $this->strings['fs_unavailable'] );
if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() )
return new WP_Error('fs_error', $this->strings['fs_error'], $wp_filesystem->errors);
foreach ( (array)$directories as $dir ) {
switch ( $dir ) {
case ABSPATH:
if ( ! $wp_filesystem->abspath() )
return new WP_Error('fs_no_root_dir', $this->strings['fs_no_root_dir']);
break;
case WP_CONTENT_DIR:
if ( ! $wp_filesystem->wp_content_dir() )
return new WP_Error('fs_no_content_dir', $this->strings['fs_no_content_dir']);
break;
case WP_PLUGIN_DIR:
if ( ! $wp_filesystem->wp_plugins_dir() )
return new WP_Error('fs_no_plugins_dir', $this->strings['fs_no_plugins_dir']);
break;
case get_theme_root():
if ( ! $wp_filesystem->wp_themes_dir() )
return new WP_Error('fs_no_themes_dir', $this->strings['fs_no_themes_dir']);
break;
default:
if ( ! $wp_filesystem->find_folder($dir) )
return new WP_Error( 'fs_no_folder', sprintf( $this->strings['fs_no_folder'], esc_html( basename( $dir ) ) ) );
break;
}
}
return true;
} //end fs_connect();
/**
* Download a package.
*
* @since 2.8.0
* @access public
*
* @param string $package The URI of the package. If this is the full path to an
* existing local file, it will be returned untouched.
* @return string|WP_Error The full path to the downloaded package file, or a WP_Error object.
*/
public function download_package( $package ) {
/**
* Filters whether to return the package.
*
* @since 3.7.0
* @access public
*
* @param bool $reply Whether to bail without returning the package.
* Default false.
* @param string $package The package file name.
* @param WP_Upgrader $this The WP_Upgrader instance.
*/
$reply = apply_filters( 'upgrader_pre_download', false, $package, $this );
if ( false !== $reply )
return $reply;
if ( ! preg_match('!^(http|https|ftp)://!i', $package) && file_exists($package) ) //Local file or remote?
return $package; //must be a local file..
if ( empty($package) )
return new WP_Error('no_package', $this->strings['no_package']);
$this->skin->feedback('downloading_package', $package);
$download_file = download_url($package);
if ( is_wp_error($download_file) )
return new WP_Error('download_failed', $this->strings['download_failed'], $download_file->get_error_message());
return $download_file;
}
/**
* Unpack a compressed package file.
*
* @since 2.8.0
* @access public
*
* @global WP_Filesystem_Base $wp_filesystem Subclass
*
* @param string $package Full path to the package file.
* @param bool $delete_package Optional. Whether to delete the package file after attempting
* to unpack it. Default true.
* @return string|WP_Error The path to the unpacked contents, or a WP_Error on failure.
*/
public function unpack_package( $package, $delete_package = true ) {
global $wp_filesystem;
$this->skin->feedback('unpack_package');
$upgrade_folder = $wp_filesystem->wp_content_dir() . 'upgrade/';
//Clean up contents of upgrade directory beforehand.
$upgrade_files = $wp_filesystem->dirlist($upgrade_folder);
if ( !empty($upgrade_files) ) {
foreach ( $upgrade_files as $file )
$wp_filesystem->delete($upgrade_folder . $file['name'], true);
}
// We need a working directory - Strip off any .tmp or .zip suffixes
$working_dir = $upgrade_folder . basename( basename( $package, '.tmp' ), '.zip' );
// Clean up working directory
if ( $wp_filesystem->is_dir($working_dir) )
$wp_filesystem->delete($working_dir, true);
// Unzip package to working directory
$result = unzip_file( $package, $working_dir );
// Once extracted, delete the package if required.
if ( $delete_package )
unlink($package);
if ( is_wp_error($result) ) {
$wp_filesystem->delete($working_dir, true);
if ( 'incompatible_archive' == $result->get_error_code() ) {
return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], $result->get_error_data() );
}
return $result;
}
return $working_dir;
}
/**
* Clears the directory where this item is going to be installed into.
*
* @since 4.3.0
* @access public
*
* @global WP_Filesystem_Base $wp_filesystem Subclass
*
* @param string $remote_destination The location on the remote filesystem to be cleared
* @return bool|WP_Error True upon success, WP_Error on failure.
*/
public function clear_destination( $remote_destination ) {
global $wp_filesystem;
if ( ! $wp_filesystem->exists( $remote_destination ) ) {
return true;
}
// Check all files are writable before attempting to clear the destination.
$unwritable_files = array();
$_files = $wp_filesystem->dirlist( $remote_destination, true, true );
// Flatten the resulting array, iterate using each as we append to the array during iteration.
while ( $f = each( $_files ) ) {
$file = $f['value'];
$name = $f['key'];
if ( ! isset( $file['files'] ) ) {
continue;
}
foreach ( $file['files'] as $filename => $details ) {
$_files[ $name . '/' . $filename ] = $details;
}
}
// Check writability.
foreach ( $_files as $filename => $file_details ) {
if ( ! $wp_filesystem->is_writable( $remote_destination . $filename ) ) {
// Attempt to alter permissions to allow writes and try again.
$wp_filesystem->chmod( $remote_destination . $filename, ( 'd' == $file_details['type'] ? FS_CHMOD_DIR : FS_CHMOD_FILE ) );
if ( ! $wp_filesystem->is_writable( $remote_destination . $filename ) ) {
$unwritable_files[] = $filename;
}
}
}
if ( ! empty( $unwritable_files ) ) {
return new WP_Error( 'files_not_writable', $this->strings['files_not_writable'], implode( ', ', $unwritable_files ) );
}
if ( ! $wp_filesystem->delete( $remote_destination, true ) ) {
return new WP_Error( 'remove_old_failed', $this->strings['remove_old_failed'] );
}
return true;
}
/**
* Install a package.
*
* Copies the contents of a package form a source directory, and installs them in
* a destination directory. Optionally removes the source. It can also optionally
* clear out the destination folder if it already exists.
*
* @since 2.8.0
* @access public
*
* @global WP_Filesystem_Base $wp_filesystem Subclass
* @global array $wp_theme_directories
*
* @param array|string $args {
* Optional. Array or string of arguments for installing a package. Default empty array.
*
* @type string $source Required path to the package source. Default empty.
* @type string $destination Required path to a folder to install the package in.
* Default empty.
* @type bool $clear_destination Whether to delete any files already in the destination
* folder. Default false.
* @type bool $clear_working Whether to delete the files form the working directory
* after copying to the destination. Default false.
* @type bool $abort_if_destination_exists Whether to abort the installation if
* the destination folder already exists. Default true.
* @type array $hook_extra Extra arguments to pass to the filter hooks called by
* WP_Upgrader::install_package(). Default empty array.
* }
*
* @return array|WP_Error The result (also stored in `WP_Upgrader::$result`), or a WP_Error on failure.
*/
public function install_package( $args = array() ) {
global $wp_filesystem, $wp_theme_directories;
$defaults = array(
'source' => '', // Please always pass this
'destination' => '', // and this
'clear_destination' => false,
'clear_working' => false,
'abort_if_destination_exists' => true,
'hook_extra' => array()
);
$args = wp_parse_args($args, $defaults);
// These were previously extract()'d.
$source = $args['source'];
$destination = $args['destination'];
$clear_destination = $args['clear_destination'];
@set_time_limit( 300 );
if ( empty( $source ) || empty( $destination ) ) {
return new WP_Error( 'bad_request', $this->strings['bad_request'] );
}
$this->skin->feedback( 'installing_package' );
/**
* Filters the install response before the installation has started.
*
* Returning a truthy value, or one that could be evaluated as a WP_Error
* will effectively short-circuit the installation, returning that value
* instead.
*
* @since 2.8.0
*
* @param bool|WP_Error $response Response.
* @param array $hook_extra Extra arguments passed to hooked filters.
*/
$res = apply_filters( 'upgrader_pre_install', true, $args['hook_extra'] );
if ( is_wp_error( $res ) ) {
return $res;
}
//Retain the Original source and destinations
$remote_source = $args['source'];
$local_destination = $destination;
$source_files = array_keys( $wp_filesystem->dirlist( $remote_source ) );
$remote_destination = $wp_filesystem->find_folder( $local_destination );
//Locate which directory to copy to the new folder, This is based on the actual folder holding the files.
if ( 1 == count( $source_files ) && $wp_filesystem->is_dir( trailingslashit( $args['source'] ) . $source_files[0] . '/' ) ) { //Only one folder? Then we want its contents.
$source = trailingslashit( $args['source'] ) . trailingslashit( $source_files[0] );
} elseif ( count( $source_files ) == 0 ) {
return new WP_Error( 'incompatible_archive_empty', $this->strings['incompatible_archive'], $this->strings['no_files'] ); // There are no files?
} else { // It's only a single file, the upgrader will use the folder name of this file as the destination folder. Folder name is based on zip filename.
$source = trailingslashit( $args['source'] );
}
/**
* Filters the source file location for the upgrade package.
*
* @since 2.8.0
* @since 4.4.0 The $hook_extra parameter became available.
*
* @param string $source File source location.
* @param string $remote_source Remote file source location.
* @param WP_Upgrader $this WP_Upgrader instance.
* @param array $hook_extra Extra arguments passed to hooked filters.
*/
$source = apply_filters( 'upgrader_source_selection', $source, $remote_source, $this, $args['hook_extra'] );
if ( is_wp_error( $source ) ) {
return $source;
}
// Has the source location changed? If so, we need a new source_files list.
if ( $source !== $remote_source ) {
$source_files = array_keys( $wp_filesystem->dirlist( $source ) );
}
/*
* Protection against deleting files in any important base directories.
* Theme_Upgrader & Plugin_Upgrader also trigger this, as they pass the
* destination directory (WP_PLUGIN_DIR / wp-content/themes) intending
* to copy the directory into the directory, whilst they pass the source
* as the actual files to copy.
*/
$protected_directories = array( ABSPATH, WP_CONTENT_DIR, WP_PLUGIN_DIR, WP_CONTENT_DIR . '/themes' );
if ( is_array( $wp_theme_directories ) ) {
$protected_directories = array_merge( $protected_directories, $wp_theme_directories );
}
if ( in_array( $destination, $protected_directories ) ) {
$remote_destination = trailingslashit( $remote_destination ) . trailingslashit( basename( $source ) );
$destination = trailingslashit( $destination ) . trailingslashit( basename( $source ) );
}
if ( $clear_destination ) {
// We're going to clear the destination if there's something there.
$this->skin->feedback('remove_old');
$removed = $this->clear_destination( $remote_destination );
/**
* Filters whether the upgrader cleared the destination.
*
* @since 2.8.0
*
* @param mixed $removed Whether the destination was cleared. true on success, WP_Error on failure
* @param string $local_destination The local package destination.
* @param string $remote_destination The remote package destination.
* @param array $hook_extra Extra arguments passed to hooked filters.
*/
$removed = apply_filters( 'upgrader_clear_destination', $removed, $local_destination, $remote_destination, $args['hook_extra'] );
if ( is_wp_error( $removed ) ) {
return $removed;
}
} elseif ( $args['abort_if_destination_exists'] && $wp_filesystem->exists($remote_destination) ) {
//If we're not clearing the destination folder and something exists there already, Bail.
//But first check to see if there are actually any files in the folder.
$_files = $wp_filesystem->dirlist($remote_destination);
if ( ! empty($_files) ) {
$wp_filesystem->delete($remote_source, true); //Clear out the source files.
return new WP_Error('folder_exists', $this->strings['folder_exists'], $remote_destination );
}
}
//Create destination if needed
if ( ! $wp_filesystem->exists( $remote_destination ) ) {
if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) ) {
return new WP_Error( 'mkdir_failed_destination', $this->strings['mkdir_failed'], $remote_destination );
}
}
// Copy new version of item into place.
$result = copy_dir($source, $remote_destination);
if ( is_wp_error($result) ) {
if ( $args['clear_working'] ) {
$wp_filesystem->delete( $remote_source, true );
}
return $result;
}
//Clear the Working folder?
if ( $args['clear_working'] ) {
$wp_filesystem->delete( $remote_source, true );
}
$destination_name = basename( str_replace($local_destination, '', $destination) );
if ( '.' == $destination_name ) {
$destination_name = '';
}
$this->result = compact( 'source', 'source_files', 'destination', 'destination_name', 'local_destination', 'remote_destination', 'clear_destination' );
/**
* Filters the install response after the installation has finished.
*
* @since 2.8.0
*
* @param bool $response Install response.
* @param array $hook_extra Extra arguments passed to hooked filters.
* @param array $result Installation result data.
*/
$res = apply_filters( 'upgrader_post_install', true, $args['hook_extra'], $this->result );
if ( is_wp_error($res) ) {
$this->result = $res;
return $res;
}
//Bombard the calling function will all the info which we've just used.
return $this->result;
}
/**
* Run an upgrade/install.
*
* Attempts to download the package (if it is not a local file), unpack it, and
* install it in the destination folder.
*
* @since 2.8.0
* @access public
*
* @param array $options {
* Array or string of arguments for upgrading/installing a package.
*
* @type string $package The full path or URI of the package to install.
* Default empty.
* @type string $destination The full path to the destination folder.
* Default empty.
* @type bool $clear_destination Whether to delete any files already in the
* destination folder. Default false.
* @type bool $clear_working Whether to delete the files form the working
* directory after copying to the destination.
* Default false.
* @type bool $abort_if_destination_exists Whether to abort the installation if the destination
* folder already exists. When true, `$clear_destination`
* should be false. Default true.
* @type bool $is_multi Whether this run is one of multiple upgrade/install
* actions being performed in bulk. When true, the skin
* WP_Upgrader::header() and WP_Upgrader::footer()
* aren't called. Default false.
* @type array $hook_extra Extra arguments to pass to the filter hooks called by
* WP_Upgrader::run().
* }
* @return array|false|WP_error The result from self::install_package() on success, otherwise a WP_Error,
* or false if unable to connect to the filesystem.
*/
public function run( $options ) {
$defaults = array(
'package' => '', // Please always pass this.
'destination' => '', // And this
'clear_destination' => false,
'abort_if_destination_exists' => true, // Abort if the Destination directory exists, Pass clear_destination as false please
'clear_working' => true,
'is_multi' => false,
'hook_extra' => array() // Pass any extra $hook_extra args here, this will be passed to any hooked filters.
);
$options = wp_parse_args( $options, $defaults );
/**
* Filters the package options before running an update.
*
* See also {@see 'upgrader_process_complete'}.
*
* @since 4.3.0
*
* @param array $options {
* Options used by the upgrader.
*
* @type string $package Package for update.
* @type string $destination Update location.
* @type bool $clear_destination Clear the destination resource.
* @type bool $clear_working Clear the working resource.
* @type bool $abort_if_destination_exists Abort if the Destination directory exists.
* @type bool $is_multi Whether the upgrader is running multiple times.
* @type array $hook_extra {
* Extra hook arguments.
*
* @type string $action Type of action. Default 'update'.
* @type string $type Type of update process. Accepts 'plugin', 'theme', or 'core'.
* @type bool $bulk Whether the update process is a bulk update. Default true.
* @type string $plugin The base plugin path from the plugins directory.
* @type string $theme The stylesheet or template name of the theme.
* @type string $language_update_type The language pack update type. Accepts 'plugin', 'theme',
* or 'core'.
* @type object $language_update The language pack update offer.
* }
* }
*/
$options = apply_filters( 'upgrader_package_options', $options );
if ( ! $options['is_multi'] ) { // call $this->header separately if running multiple times
$this->skin->header();
}
// Connect to the Filesystem first.
$res = $this->fs_connect( array( WP_CONTENT_DIR, $options['destination'] ) );
// Mainly for non-connected filesystem.
if ( ! $res ) {
if ( ! $options['is_multi'] ) {
$this->skin->footer();
}
return false;
}
$this->skin->before();
if ( is_wp_error($res) ) {
$this->skin->error($res);
$this->skin->after();
if ( ! $options['is_multi'] ) {
$this->skin->footer();
}
return $res;
}
/*
* Download the package (Note, This just returns the filename
* of the file if the package is a local file)
*/
$download = $this->download_package( $options['package'] );
if ( is_wp_error($download) ) {
$this->skin->error($download);
$this->skin->after();
if ( ! $options['is_multi'] ) {
$this->skin->footer();
}
return $download;
}
$delete_package = ( $download != $options['package'] ); // Do not delete a "local" file
// Unzips the file into a temporary directory.
$working_dir = $this->unpack_package( $download, $delete_package );
if ( is_wp_error($working_dir) ) {
$this->skin->error($working_dir);
$this->skin->after();
if ( ! $options['is_multi'] ) {
$this->skin->footer();
}
return $working_dir;
}
// With the given options, this installs it to the destination directory.
$result = $this->install_package( array(
'source' => $working_dir,
'destination' => $options['destination'],
'clear_destination' => $options['clear_destination'],
'abort_if_destination_exists' => $options['abort_if_destination_exists'],
'clear_working' => $options['clear_working'],
'hook_extra' => $options['hook_extra']
) );
$this->skin->set_result($result);
if ( is_wp_error($result) ) {
$this->skin->error($result);
$this->skin->feedback('process_failed');
} else {
// Install succeeded.
$this->skin->feedback('process_success');
}
$this->skin->after();
if ( ! $options['is_multi'] ) {
/**
* Fires when the upgrader process is complete.
*
* See also {@see 'upgrader_package_options'}.
*
* @since 3.6.0
* @since 3.7.0 Added to WP_Upgrader::run().
* @since 4.6.0 `$translations` was added as a possible argument to `$hook_extra`.
*
* @param WP_Upgrader $this WP_Upgrader instance. In other contexts, $this, might be a
* Theme_Upgrader, Plugin_Upgrader, Core_Upgrade, or Language_Pack_Upgrader instance.
* @param array $hook_extra {
* Array of bulk item update data.
*
* @type string $action Type of action. Default 'update'.
* @type string $type Type of update process. Accepts 'plugin', 'theme', 'translation', or 'core'.
* @type bool $bulk Whether the update process is a bulk update. Default true.
* @type array $plugins Array of the basename paths of the plugins' main files.
* @type array $themes The theme slugs.
* @type array $translations {
* Array of translations update data.
*
* @type string $language The locale the translation is for.
* @type string $type Type of translation. Accepts 'plugin', 'theme', or 'core'.
* @type string $slug Text domain the translation is for. The slug of a theme/plugin or
* 'default' for core translations.
* @type string $version The version of a theme, plugin, or core.
* }
* }
*/
do_action( 'upgrader_process_complete', $this, $options['hook_extra'] );
$this->skin->footer();
}
return $result;
}
/**
* Toggle maintenance mode for the site.
*
* Creates/deletes the maintenance file to enable/disable maintenance mode.
*
* @since 2.8.0
* @access public
*
* @global WP_Filesystem_Base $wp_filesystem Subclass
*
* @param bool $enable True to enable maintenance mode, false to disable.
*/
public function maintenance_mode( $enable = false ) {
global $wp_filesystem;
$file = $wp_filesystem->abspath() . '.maintenance';
if ( $enable ) {
$this->skin->feedback('maintenance_start');
// Create maintenance file to signal that we are upgrading
$maintenance_string = '<?php $upgrading = ' . time() . '; ?>';
$wp_filesystem->delete($file);
$wp_filesystem->put_contents($file, $maintenance_string, FS_CHMOD_FILE);
} elseif ( ! $enable && $wp_filesystem->exists( $file ) ) {
$this->skin->feedback('maintenance_end');
$wp_filesystem->delete($file);
}
}
/**
* Creates a lock using WordPress options.
*
* @since 4.5.0
* @access public
* @static
*
* @param string $lock_name The name of this unique lock.
* @param int $release_timeout Optional. The duration in seconds to respect an existing lock.
* Default: 1 hour.
* @return bool False if a lock couldn't be created or if the lock is no longer valid. True otherwise.
*/
public static function create_lock( $lock_name, $release_timeout = null ) {
global $wpdb;
if ( ! $release_timeout ) {
$release_timeout = HOUR_IN_SECONDS;
}
$lock_option = $lock_name . '.lock';
// Try to lock.
$lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_option, time() ) );
if ( ! $lock_result ) {
$lock_result = get_option( $lock_option );
// If a lock couldn't be created, and there isn't a lock, bail.
if ( ! $lock_result ) {
return false;
}
// Check to see if the lock is still valid. If not, bail.
if ( $lock_result > ( time() - $release_timeout ) ) {
return false;
}
// There must exist an expired lock, clear it and re-gain it.
WP_Upgrader::release_lock( $lock_name );
return WP_Upgrader::create_lock( $lock_name, $release_timeout );
}
// Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
update_option( $lock_option, time() );
return true;
}
/**
* Releases an upgrader lock.
*
* @since 4.5.0
* @access public
* @static
*
* @see WP_Upgrader::create_lock()
*
* @param string $lock_name The name of this unique lock.
* @return bool True if the lock was successfully released. False on failure.
*/
public static function release_lock( $lock_name ) {
return delete_option( $lock_name . '.lock' );
}
}
/** Plugin_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader.php';
/** Theme_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-theme-upgrader.php';
/** Language_Pack_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-language-pack-upgrader.php';
/** Core_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-core-upgrader.php';
/** File_Upload_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-file-upload-upgrader.php';
/** WP_Automatic_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-wp-automatic-upgrader.php';
|
trvinhlong/tanks
|
wp-admin/includes/class-wp-upgrader.php
|
PHP
|
gpl-2.0
| 33,601 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 1.5.4">
<title>git-bundle(1)</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700">
<style>
/* Asciidoctor default stylesheet | MIT License | http://asciidoctor.org */
/* Remove comment around @import statement below when using as a custom stylesheet */
/*@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700";*/
article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}
audio,canvas,video{display:inline-block}
audio:not([controls]){display:none;height:0}
[hidden],template{display:none}
script{display:none!important}
html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}
body{margin:0}
a{background:transparent}
a:focus{outline:thin dotted}
a:active,a:hover{outline:0}
h1{font-size:2em;margin:.67em 0}
abbr[title]{border-bottom:1px dotted}
b,strong{font-weight:bold}
dfn{font-style:italic}
hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}
mark{background:#ff0;color:#000}
code,kbd,pre,samp{font-family:monospace;font-size:1em}
pre{white-space:pre-wrap}
q{quotes:"\201C" "\201D" "\2018" "\2019"}
small{font-size:80%}
sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}
sup{top:-.5em}
sub{bottom:-.25em}
img{border:0}
svg:not(:root){overflow:hidden}
figure{margin:0}
fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}
legend{border:0;padding:0}
button,input,select,textarea{font-family:inherit;font-size:100%;margin:0}
button,input{line-height:normal}
button,select{text-transform:none}
button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}
button[disabled],html input[disabled]{cursor:default}
input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}
input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}
input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}
button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}
textarea{overflow:auto;vertical-align:top}
table{border-collapse:collapse;border-spacing:0}
*,*:before,*:after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}
html,body{font-size:100%}
body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto}
a:hover{cursor:pointer}
img,object,embed{max-width:100%;height:auto}
object,embed{height:100%}
img{-ms-interpolation-mode:bicubic}
.left{float:left!important}
.right{float:right!important}
.text-left{text-align:left!important}
.text-right{text-align:right!important}
.text-center{text-align:center!important}
.text-justify{text-align:justify!important}
.hide{display:none}
body{-webkit-font-smoothing:antialiased}
img,object,svg{display:inline-block;vertical-align:middle}
textarea{height:auto;min-height:50px}
select{width:100%}
.center{margin-left:auto;margin-right:auto}
.spread{width:100%}
p.lead,.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{font-size:1.21875em;line-height:1.6}
.subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em}
div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr}
a{color:#2156a5;text-decoration:underline;line-height:inherit}
a:hover,a:focus{color:#1d4b8f}
a img{border:none}
p{font-family:inherit;font-weight:400;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility}
p aside{font-size:.875em;line-height:1.35;font-style:italic}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em}
h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0}
h1{font-size:2.125em}
h2{font-size:1.6875em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em}
h4,h5{font-size:1.125em}
h6{font-size:1em}
hr{border:solid #ddddd8;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0}
em,i{font-style:italic;line-height:inherit}
strong,b{font-weight:bold;line-height:inherit}
small{font-size:60%;line-height:inherit}
code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)}
ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit}
ul,ol,ul.no-bullet,ol.no-bullet{margin-left:1.5em}
ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em}
ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit}
ul.square{list-style-type:square}
ul.circle{list-style-type:circle}
ul.disc{list-style-type:disc}
ul.no-bullet{list-style:none}
ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0}
dl dt{margin-bottom:.3125em;font-weight:bold}
dl dd{margin-bottom:1.25em}
abbr,acronym{text-transform:uppercase;font-size:90%;color:rgba(0,0,0,.8);border-bottom:1px dotted #ddd;cursor:help}
abbr{text-transform:none}
blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd}
blockquote cite{display:block;font-size:.9375em;color:rgba(0,0,0,.6)}
blockquote cite:before{content:"\2014 \0020"}
blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,.6)}
blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)}
@media only screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2}
h1{font-size:2.75em}
h2{font-size:2.3125em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em}
h4{font-size:1.4375em}}
table{background:#fff;margin-bottom:1.25em;border:solid 1px #dedede}
table thead,table tfoot{background:#f7f8f7;font-weight:bold}
table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left}
table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)}
table tr.even,table tr.alt,table tr:nth-of-type(even){background:#f8f8f7}
table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6}
body{tab-size:4}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em}
h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400}
.clearfix:before,.clearfix:after,.float-group:before,.float-group:after{content:" ";display:table}
.clearfix:after,.float-group:after{clear:both}
*:not(pre)>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background-color:#f7f7f8;-webkit-border-radius:4px;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed}
pre,pre>code{line-height:1.45;color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;text-rendering:optimizeSpeed}
.keyseq{color:rgba(51,51,51,.8)}
kbd{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background-color:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em white inset;box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em #fff inset;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap}
.keyseq kbd:first-child{margin-left:0}
.keyseq kbd:last-child{margin-right:0}
.menuseq,.menu{color:rgba(0,0,0,.8)}
b.button:before,b.button:after{position:relative;top:-1px;font-weight:400}
b.button:before{content:"[";padding:0 3px 0 2px}
b.button:after{content:"]";padding:0 2px 0 3px}
p a>code:hover{color:rgba(0,0,0,.9)}
#header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em}
#header:before,#header:after,#content:before,#content:after,#footnotes:before,#footnotes:after,#footer:before,#footer:after{content:" ";display:table}
#header:after,#content:after,#footnotes:after,#footer:after{clear:both}
#content{margin-top:1.25em}
#content:before{content:none}
#header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0}
#header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #ddddd8}
#header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #ddddd8;padding-bottom:8px}
#header .details{border-bottom:1px solid #ddddd8;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap}
#header .details span:first-child{margin-left:-.125em}
#header .details span.email a{color:rgba(0,0,0,.85)}
#header .details br{display:none}
#header .details br+span:before{content:"\00a0\2013\00a0"}
#header .details br+span.author:before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)}
#header .details br+span#revremark:before{content:"\00a0|\00a0"}
#header #revnumber{text-transform:capitalize}
#header #revnumber:after{content:"\00a0"}
#content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #ddddd8;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem}
#toc{border-bottom:1px solid #efefed;padding-bottom:.5em}
#toc>ul{margin-left:.125em}
#toc ul.sectlevel0>li>a{font-style:italic}
#toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0}
#toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none}
#toc li{line-height:1.3334;margin-top:.3334em}
#toc a{text-decoration:none}
#toc a:active{text-decoration:underline}
#toctitle{color:#7a2518;font-size:1.2em}
@media only screen and (min-width:768px){#toctitle{font-size:1.375em}
body.toc2{padding-left:15em;padding-right:0}
#toc.toc2{margin-top:0!important;background-color:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #efefed;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto}
#toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em}
#toc.toc2>ul{font-size:.9em;margin-bottom:0}
#toc.toc2 ul ul{margin-left:0;padding-left:1em}
#toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em}
body.toc2.toc-right{padding-left:0;padding-right:15em}
body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #efefed;left:auto;right:0}}
@media only screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0}
#toc.toc2{width:20em}
#toc.toc2 #toctitle{font-size:1.375em}
#toc.toc2>ul{font-size:.95em}
#toc.toc2 ul ul{padding-left:1.25em}
body.toc2.toc-right{padding-left:0;padding-right:20em}}
#content #toc{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
#content #toc>:first-child{margin-top:0}
#content #toc>:last-child{margin-bottom:0}
#footer{max-width:100%;background-color:rgba(0,0,0,.8);padding:1.25em}
#footer-text{color:rgba(255,255,255,.8);line-height:1.44}
.sect1{padding-bottom:.625em}
@media only screen and (min-width:768px){.sect1{padding-bottom:1.25em}}
.sect1+.sect1{border-top:1px solid #efefed}
#content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400}
#content h1>a.anchor:before,h2>a.anchor:before,h3>a.anchor:before,#toctitle>a.anchor:before,.sidebarblock>.content>.title>a.anchor:before,h4>a.anchor:before,h5>a.anchor:before,h6>a.anchor:before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em}
#content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible}
#content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none}
#content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221}
.audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em}
.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic}
table.tableblock>caption.title{white-space:nowrap;overflow:visible;max-width:0}
.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{color:rgba(0,0,0,.85)}
table.tableblock #preamble>.sectionbody>.paragraph:first-of-type p{font-size:inherit}
.admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%}
.admonitionblock>table td.icon{text-align:center;width:80px}
.admonitionblock>table td.icon img{max-width:none}
.admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase}
.admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #ddddd8;color:rgba(0,0,0,.6)}
.admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0}
.exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;-webkit-border-radius:4px;border-radius:4px}
.exampleblock>.content>:first-child{margin-top:0}
.exampleblock>.content>:last-child{margin-bottom:0}
.sidebarblock{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
.sidebarblock>:first-child{margin-top:0}
.sidebarblock>:last-child{margin-bottom:0}
.sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center}
.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0}
.literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#f7f7f8}
.sidebarblock .literalblock pre,.sidebarblock .listingblock pre:not(.highlight),.sidebarblock .listingblock pre[class="highlight"],.sidebarblock .listingblock pre[class^="highlight "],.sidebarblock .listingblock pre.CodeRay,.sidebarblock .listingblock pre.prettyprint{background:#f2f1f1}
.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{-webkit-border-radius:4px;border-radius:4px;word-wrap:break-word;padding:1em;font-size:.8125em}
.literalblock pre.nowrap,.literalblock pre[class].nowrap,.listingblock pre.nowrap,.listingblock pre[class].nowrap{overflow-x:auto;white-space:pre;word-wrap:normal}
@media only screen and (min-width:768px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:.90625em}}
@media only screen and (min-width:1280px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:1em}}
.literalblock.output pre{color:#f7f7f8;background-color:rgba(0,0,0,.9)}
.listingblock pre.highlightjs{padding:0}
.listingblock pre.highlightjs>code{padding:1em;-webkit-border-radius:4px;border-radius:4px}
.listingblock pre.prettyprint{border-width:0}
.listingblock>.content{position:relative}
.listingblock code[data-lang]:before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:#999}
.listingblock:hover code[data-lang]:before{display:block}
.listingblock.terminal pre .command:before{content:attr(data-prompt);padding-right:.5em;color:#999}
.listingblock.terminal pre .command:not([data-prompt]):before{content:"$"}
table.pyhltable{border-collapse:separate;border:0;margin-bottom:0;background:none}
table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0;line-height:1.45}
table.pyhltable td.code{padding-left:.75em;padding-right:0}
pre.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #ddddd8}
pre.pygments .lineno{display:inline-block;margin-right:.25em}
table.pyhltable .linenodiv{background:none!important;padding-right:0!important}
.quoteblock{margin:0 1em 1.25em 1.5em;display:table}
.quoteblock>.title{margin-left:-1.5em;margin-bottom:.75em}
.quoteblock blockquote,.quoteblock blockquote p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify}
.quoteblock blockquote{margin:0;padding:0;border:0}
.quoteblock blockquote:before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)}
.quoteblock blockquote>.paragraph:last-child p{margin-bottom:0}
.quoteblock .attribution{margin-top:.5em;margin-right:.5ex;text-align:right}
.quoteblock .quoteblock{margin-left:0;margin-right:0;padding:.5em 0;border-left:3px solid rgba(0,0,0,.6)}
.quoteblock .quoteblock blockquote{padding:0 0 0 .75em}
.quoteblock .quoteblock blockquote:before{display:none}
.verseblock{margin:0 1em 1.25em 1em}
.verseblock pre{font-family:"Open Sans","DejaVu Sans",sans;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility}
.verseblock pre strong{font-weight:400}
.verseblock .attribution{margin-top:1.25rem;margin-left:.5ex}
.quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic}
.quoteblock .attribution br,.verseblock .attribution br{display:none}
.quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)}
.quoteblock.abstract{margin:0 0 1.25em 0;display:block}
.quoteblock.abstract blockquote,.quoteblock.abstract blockquote p{text-align:left;word-spacing:0}
.quoteblock.abstract blockquote:before,.quoteblock.abstract blockquote p:first-of-type:before{display:none}
table.tableblock{max-width:100%;border-collapse:separate}
table.tableblock td>.paragraph:last-child p>p:last-child,table.tableblock th>p:last-child,table.tableblock td>p:last-child{margin-bottom:0}
table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede}
table.grid-all th.tableblock,table.grid-all td.tableblock{border-width:0 1px 1px 0}
table.grid-all tfoot>tr>th.tableblock,table.grid-all tfoot>tr>td.tableblock{border-width:1px 1px 0 0}
table.grid-cols th.tableblock,table.grid-cols td.tableblock{border-width:0 1px 0 0}
table.grid-all *>tr>.tableblock:last-child,table.grid-cols *>tr>.tableblock:last-child{border-right-width:0}
table.grid-rows th.tableblock,table.grid-rows td.tableblock{border-width:0 0 1px 0}
table.grid-all tbody>tr:last-child>th.tableblock,table.grid-all tbody>tr:last-child>td.tableblock,table.grid-all thead:last-child>tr>th.tableblock,table.grid-rows tbody>tr:last-child>th.tableblock,table.grid-rows tbody>tr:last-child>td.tableblock,table.grid-rows thead:last-child>tr>th.tableblock{border-bottom-width:0}
table.grid-rows tfoot>tr>th.tableblock,table.grid-rows tfoot>tr>td.tableblock{border-width:1px 0 0 0}
table.frame-all{border-width:1px}
table.frame-sides{border-width:0 1px}
table.frame-topbot{border-width:1px 0}
th.halign-left,td.halign-left{text-align:left}
th.halign-right,td.halign-right{text-align:right}
th.halign-center,td.halign-center{text-align:center}
th.valign-top,td.valign-top{vertical-align:top}
th.valign-bottom,td.valign-bottom{vertical-align:bottom}
th.valign-middle,td.valign-middle{vertical-align:middle}
table thead th,table tfoot th{font-weight:bold}
tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7}
tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold}
p.tableblock>code:only-child{background:none;padding:0}
p.tableblock{font-size:1em}
td>div.verse{white-space:pre}
ol{margin-left:1.75em}
ul li ol{margin-left:1.5em}
dl dd{margin-left:1.125em}
dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0}
ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em}
ul.unstyled,ol.unnumbered,ul.checklist,ul.none{list-style-type:none}
ul.unstyled,ol.unnumbered,ul.checklist{margin-left:.625em}
ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1em;font-size:.85em}
ul.checklist li>p:first-child>input[type="checkbox"]:first-child{width:1em;position:relative;top:1px}
ul.inline{margin:0 auto .625em auto;margin-left:-1.375em;margin-right:0;padding:0;list-style:none;overflow:hidden}
ul.inline>li{list-style:none;float:left;margin-left:1.375em;display:block}
ul.inline>li>*{display:block}
.unstyled dl dt{font-weight:400;font-style:normal}
ol.arabic{list-style-type:decimal}
ol.decimal{list-style-type:decimal-leading-zero}
ol.loweralpha{list-style-type:lower-alpha}
ol.upperalpha{list-style-type:upper-alpha}
ol.lowerroman{list-style-type:lower-roman}
ol.upperroman{list-style-type:upper-roman}
ol.lowergreek{list-style-type:lower-greek}
.hdlist>table,.colist>table{border:0;background:none}
.hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none}
td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em}
td.hdlist1{font-weight:bold;padding-bottom:1.25em}
.literalblock+.colist,.listingblock+.colist{margin-top:-.5em}
.colist>table tr>td:first-of-type{padding:0 .75em;line-height:1}
.colist>table tr>td:last-of-type{padding:.25em 0}
.thumb,.th{line-height:0;display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px #ddd;box-shadow:0 0 0 1px #ddd}
.imageblock.left,.imageblock[style*="float: left"]{margin:.25em .625em 1.25em 0}
.imageblock.right,.imageblock[style*="float: right"]{margin:.25em 0 1.25em .625em}
.imageblock>.title{margin-bottom:0}
.imageblock.thumb,.imageblock.th{border-width:6px}
.imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em}
.image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0}
.image.left{margin-right:.625em}
.image.right{margin-left:.625em}
a.image{text-decoration:none;display:inline-block}
a.image object{pointer-events:none}
sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super}
sup.footnote a,sup.footnoteref a{text-decoration:none}
sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline}
#footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em}
#footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em 0;border-width:1px 0 0 0}
#footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;text-indent:-1.05em;margin-bottom:.2em}
#footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none}
#footnotes .footnote:last-of-type{margin-bottom:0}
#content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0}
.gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0}
.gist .file-data>table td.line-data{width:99%}
div.unbreakable{page-break-inside:avoid}
.big{font-size:larger}
.small{font-size:smaller}
.underline{text-decoration:underline}
.overline{text-decoration:overline}
.line-through{text-decoration:line-through}
.aqua{color:#00bfbf}
.aqua-background{background-color:#00fafa}
.black{color:#000}
.black-background{background-color:#000}
.blue{color:#0000bf}
.blue-background{background-color:#0000fa}
.fuchsia{color:#bf00bf}
.fuchsia-background{background-color:#fa00fa}
.gray{color:#606060}
.gray-background{background-color:#7d7d7d}
.green{color:#006000}
.green-background{background-color:#007d00}
.lime{color:#00bf00}
.lime-background{background-color:#00fa00}
.maroon{color:#600000}
.maroon-background{background-color:#7d0000}
.navy{color:#000060}
.navy-background{background-color:#00007d}
.olive{color:#606000}
.olive-background{background-color:#7d7d00}
.purple{color:#600060}
.purple-background{background-color:#7d007d}
.red{color:#bf0000}
.red-background{background-color:#fa0000}
.silver{color:#909090}
.silver-background{background-color:#bcbcbc}
.teal{color:#006060}
.teal-background{background-color:#007d7d}
.white{color:#bfbfbf}
.white-background{background-color:#fafafa}
.yellow{color:#bfbf00}
.yellow-background{background-color:#fafa00}
span.icon>.fa{cursor:default}
.admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default}
.admonitionblock td.icon .icon-note:before{content:"\f05a";color:#19407c}
.admonitionblock td.icon .icon-tip:before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111}
.admonitionblock td.icon .icon-warning:before{content:"\f071";color:#bf6900}
.admonitionblock td.icon .icon-caution:before{content:"\f06d";color:#bf3400}
.admonitionblock td.icon .icon-important:before{content:"\f06a";color:#bf0000}
.conum[data-value]{display:inline-block;color:#fff!important;background-color:rgba(0,0,0,.8);-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold}
.conum[data-value] *{color:#fff!important}
.conum[data-value]+b{display:none}
.conum[data-value]:after{content:attr(data-value)}
pre .conum[data-value]{position:relative;top:-.125em}
b.conum *{color:inherit!important}
.conum:not([data-value]):empty{display:none}
dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility}
h1,h2,p,td.content,span.alt{letter-spacing:-.01em}
p strong,td.content strong,div.footnote strong{letter-spacing:-.005em}
p,blockquote,dt,td.content,span.alt{font-size:1.0625rem}
p{margin-bottom:1.25rem}
.sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em}
.exampleblock>.content{background-color:#fffef7;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc}
.print-only{display:none!important}
@media print{@page{margin:1.25cm .75cm}
*{-webkit-box-shadow:none!important;box-shadow:none!important;text-shadow:none!important}
a{color:inherit!important;text-decoration:underline!important}
a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important}
a[href^="http:"]:not(.bare):after,a[href^="https:"]:not(.bare):after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em}
abbr[title]:after{content:" (" attr(title) ")"}
pre,blockquote,tr,img,object,svg{page-break-inside:avoid}
thead{display:table-header-group}
svg{max-width:100%}
p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3}
h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid}
#toc,.sidebarblock,.exampleblock>.content{background:none!important}
#toc{border-bottom:1px solid #ddddd8!important;padding-bottom:0!important}
.sect1{padding-bottom:0!important}
.sect1+.sect1{border:0!important}
#header>h1:first-child{margin-top:1.25rem}
body.book #header{text-align:center}
body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em 0}
body.book #header .details{border:0!important;display:block;padding:0!important}
body.book #header .details span:first-child{margin-left:0!important}
body.book #header .details br{display:block}
body.book #header .details br+span:before{content:none!important}
body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important}
body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always}
.listingblock code[data-lang]:before{display:block}
#footer{background:none!important;padding:0 .9375em}
#footer-text{color:rgba(0,0,0,.6)!important;font-size:.9em}
.hide-on-print{display:none!important}
.print-only{display:block!important}
.hide-for-print{display:none!important}
.show-for-print{display:inherit!important}}
</style>
</head>
<body class="manpage">
<div id="header">
<h1>git-bundle(1) Manual Page</h1>
<h2>NAME</h2>
<div class="sectionbody">
<p>git-bundle - Move objects and refs by archive</p>
</div>
</div>
<div id="content">
<div class="sect1">
<h2 id="_synopsis">SYNOPSIS</h2>
<div class="sectionbody">
<div class="verseblock">
<pre class="content"><em>git bundle</em> create <file> <git-rev-list-args>
<em>git bundle</em> verify <file>
<em>git bundle</em> list-heads <file> [<refname>…​]
<em>git bundle</em> unbundle <file> [<refname>…​]</pre>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_description">DESCRIPTION</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Some workflows require that one or more branches of development on one
machine be replicated on another machine, but the two machines cannot
be directly connected, and therefore the interactive Git protocols (git,
ssh, http) cannot be used. This command provides support for
<em>git fetch</em> and <em>git pull</em> to operate by packaging objects and references
in an archive at the originating machine, then importing those into
another repository using <em>git fetch</em> and <em>git pull</em>
after moving the archive by some means (e.g., by sneakernet). As no
direct connection between the repositories exists, the user must specify a
basis for the bundle that is held by the destination repository: the
bundle assumes that all objects in the basis are already in the
destination repository.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_options">OPTIONS</h2>
<div class="sectionbody">
<div class="dlist">
<dl>
<dt class="hdlist1">create <file></dt>
<dd>
<p>Used to create a bundle named <em>file</em>. This requires the
<em>git-rev-list-args</em> arguments to define the bundle contents.</p>
</dd>
<dt class="hdlist1">verify <file></dt>
<dd>
<p>Used to check that a bundle file is valid and will apply
cleanly to the current repository. This includes checks on the
bundle format itself as well as checking that the prerequisite
commits exist and are fully linked in the current repository.
<em>git bundle</em> prints a list of missing commits, if any, and exits
with a non-zero status.</p>
</dd>
<dt class="hdlist1">list-heads <file></dt>
<dd>
<p>Lists the references defined in the bundle. If followed by a
list of references, only references matching those given are
printed out.</p>
</dd>
<dt class="hdlist1">unbundle <file></dt>
<dd>
<p>Passes the objects in the bundle to <em>git index-pack</em>
for storage in the repository, then prints the names of all
defined references. If a list of references is given, only
references matching those in the list are printed. This command is
really plumbing, intended to be called only by <em>git fetch</em>.</p>
</dd>
<dt class="hdlist1"><git-rev-list-args></dt>
<dd>
<p>A list of arguments, acceptable to <em>git rev-parse</em> and
<em>git rev-list</em> (and containing a named ref, see SPECIFYING REFERENCES
below), that specifies the specific objects and references
to transport. For example, <code>master~10..master</code> causes the
current master reference to be packaged along with all objects
added since its 10th ancestor commit. There is no explicit
limit to the number of references and objects that may be
packaged.</p>
</dd>
<dt class="hdlist1">[<refname>…​]</dt>
<dd>
<p>A list of references used to limit the references reported as
available. This is principally of use to <em>git fetch</em>, which
expects to receive only those references asked for and not
necessarily everything in the pack (in this case, <em>git bundle</em> acts
like <em>git fetch-pack</em>).</p>
</dd>
</dl>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_specifying_references">SPECIFYING REFERENCES</h2>
<div class="sectionbody">
<div class="paragraph">
<p><em>git bundle</em> will only package references that are shown by
<em>git show-ref</em>: this includes heads, tags, and remote heads. References
such as <code>master~1</code> cannot be packaged, but are perfectly suitable for
defining the basis. More than one reference may be packaged, and more
than one basis can be specified. The objects packaged are those not
contained in the union of the given bases. Each basis can be
specified explicitly (e.g. <code>^master~10</code>), or implicitly (e.g.
<code>master~10..master</code>, <code>--since=10.days.ago master</code>).</p>
</div>
<div class="paragraph">
<p>It is very important that the basis used be held by the destination.
It is okay to err on the side of caution, causing the bundle file
to contain objects already in the destination, as these are ignored
when unpacking at the destination.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_example">EXAMPLE</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Assume you want to transfer the history from a repository R1 on machine A
to another repository R2 on machine B.
For whatever reason, direct connection between A and B is not allowed,
but we can move data from A to B via some mechanism (CD, email, etc.).
We want to update R2 with development made on the branch master in R1.</p>
</div>
<div class="paragraph">
<p>To bootstrap the process, you can first create a bundle that does not have
any basis. You can use a tag to remember up to what commit you last
processed, in order to make it easy to later update the other repository
with an incremental bundle:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>machineA$ cd R1
machineA$ git bundle create file.bundle master
machineA$ git tag -f lastR2bundle master</pre>
</div>
</div>
<div class="paragraph">
<p>Then you transfer file.bundle to the target machine B. Because this
bundle does not require any existing object to be extracted, you can
create a new repository on machine B by cloning from it:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>machineB$ git clone -b master /home/me/tmp/file.bundle R2</pre>
</div>
</div>
<div class="paragraph">
<p>This will define a remote called "origin" in the resulting repository that
lets you fetch and pull from the bundle. The $GIT_DIR/config file in R2 will
have an entry like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>[remote "origin"]
url = /home/me/tmp/file.bundle
fetch = refs/heads/*:refs/remotes/origin/*</pre>
</div>
</div>
<div class="paragraph">
<p>To update the resulting mine.git repository, you can fetch or pull after
replacing the bundle stored at /home/me/tmp/file.bundle with incremental
updates.</p>
</div>
<div class="paragraph">
<p>After working some more in the original repository, you can create an
incremental bundle to update the other repository:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>machineA$ cd R1
machineA$ git bundle create file.bundle lastR2bundle..master
machineA$ git tag -f lastR2bundle master</pre>
</div>
</div>
<div class="paragraph">
<p>You then transfer the bundle to the other machine to replace
/home/me/tmp/file.bundle, and pull from it.</p>
</div>
<div class="listingblock">
<div class="content">
<pre>machineB$ cd R2
machineB$ git pull</pre>
</div>
</div>
<div class="paragraph">
<p>If you know up to what commit the intended recipient repository should
have the necessary objects, you can use that knowledge to specify the
basis, giving a cut-off point to limit the revisions and objects that go
in the resulting bundle. The previous example used the lastR2bundle tag
for this purpose, but you can use any other options that you would give to
the <a href="git-log.html">git-log</a>(1) command. Here are more examples:</p>
</div>
<div class="paragraph">
<p>You can use a tag that is present in both:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bundle create mybundle v1.0.0..master</pre>
</div>
</div>
<div class="paragraph">
<p>You can use a basis based on time:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bundle create mybundle --since=10.days master</pre>
</div>
</div>
<div class="paragraph">
<p>You can use the number of commits:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bundle create mybundle -10 master</pre>
</div>
</div>
<div class="paragraph">
<p>You can run <code>git-bundle verify</code> to see if you can extract from a bundle
that was created with a basis:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bundle verify mybundle</pre>
</div>
</div>
<div class="paragraph">
<p>This will list what commits you must have in order to extract from the
bundle and will error out if you do not have them.</p>
</div>
<div class="paragraph">
<p>A bundle from a recipient repository’s point of view is just like a
regular repository which it fetches or pulls from. You can, for example, map
references when fetching:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git fetch mybundle master:localRef</pre>
</div>
</div>
<div class="paragraph">
<p>You can also see what references it offers:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git ls-remote mybundle</pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_git">GIT</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Part of the <a href="git.html">git</a>(1) suite</p>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer-text">
Last updated 2016-11-02 12:15:32 W. Europe Standard Time
</div>
</div>
</body>
</html>
|
arpitdwivedi/testproject
|
mingw64/share/doc/git-doc/git-bundle.html
|
HTML
|
gpl-2.0
| 39,629 |
# homework-planner
An iOS app that lets you keep track of your schoolwork
|
rossistboss/homework-planner
|
README.md
|
Markdown
|
gpl-2.0
| 74 |
# Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from opus_core.opus_package import OpusPackage
class package(OpusPackage):
name = 'waterdemand'
required_opus_packages = ['opus_core']
|
christianurich/VIBe2UrbanSim
|
3rdparty/opus/src/waterdemand/opus_package_info.py
|
Python
|
gpl-2.0
| 272 |
/*
* Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
*/
# include "incls/_precompiled.incl"
# include "incls/_vframe_hp.cpp.incl"
// ------------- compiledVFrame --------------
StackValueCollection* compiledVFrame::locals() const {
// Natives has no scope
if (scope() == NULL) return new StackValueCollection(0);
GrowableArray<ScopeValue*>* scv_list = scope()->locals();
if (scv_list == NULL) return new StackValueCollection(0);
// scv_list is the list of ScopeValues describing the JVM stack state.
// There is one scv_list entry for every JVM stack state in use.
int length = scv_list->length();
StackValueCollection* result = new StackValueCollection(length);
// In rare instances set_locals may have occurred in which case
// there are local values that are not described by the ScopeValue anymore
GrowableArray<jvmtiDeferredLocalVariable*>* deferred = NULL;
GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread()->deferred_locals();
if (list != NULL ) {
// In real life this never happens or is typically a single element search
for (int i = 0; i < list->length(); i++) {
if (list->at(i)->matches((vframe*)this)) {
deferred = list->at(i)->locals();
break;
}
}
}
for( int i = 0; i < length; i++ ) {
result->add( create_stack_value(scv_list->at(i)) );
}
// Replace specified locals with any deferred writes that are present
if (deferred != NULL) {
for ( int l = 0; l < deferred->length() ; l ++) {
jvmtiDeferredLocalVariable* val = deferred->at(l);
switch (val->type()) {
case T_BOOLEAN:
result->set_int_at(val->index(), val->value().z);
break;
case T_CHAR:
result->set_int_at(val->index(), val->value().c);
break;
case T_FLOAT:
result->set_float_at(val->index(), val->value().f);
break;
case T_DOUBLE:
result->set_double_at(val->index(), val->value().d);
break;
case T_BYTE:
result->set_int_at(val->index(), val->value().b);
break;
case T_SHORT:
result->set_int_at(val->index(), val->value().s);
break;
case T_INT:
result->set_int_at(val->index(), val->value().i);
break;
case T_LONG:
result->set_long_at(val->index(), val->value().j);
break;
case T_OBJECT:
{
Handle obj((oop)val->value().l);
result->set_obj_at(val->index(), obj);
}
break;
default:
ShouldNotReachHere();
}
}
}
return result;
}
void compiledVFrame::set_locals(StackValueCollection* values) const {
fatal("Should use update_local for each local update");
}
void compiledVFrame::update_local(BasicType type, int index, jvalue value) {
#ifdef ASSERT
assert(fr().is_deoptimized_frame(), "frame must be scheduled for deoptimization");
#endif /* ASSERT */
GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = thread()->deferred_locals();
if (deferred != NULL ) {
// See if this vframe has already had locals with deferred writes
int f;
for ( f = 0 ; f < deferred->length() ; f++ ) {
if (deferred->at(f)->matches(this)) {
// Matching, vframe now see if the local already had deferred write
GrowableArray<jvmtiDeferredLocalVariable*>* locals = deferred->at(f)->locals();
int l;
for (l = 0 ; l < locals->length() ; l++ ) {
if (locals->at(l)->index() == index) {
locals->at(l)->set_value(value);
return;
}
}
// No matching local already present. Push a new value onto the deferred collection
locals->push(new jvmtiDeferredLocalVariable(index, type, value));
return;
}
}
// No matching vframe must push a new vframe
} else {
// No deferred updates pending for this thread.
// allocate in C heap
deferred = new(ResourceObj::C_HEAP) GrowableArray<jvmtiDeferredLocalVariableSet*> (1, true);
thread()->set_deferred_locals(deferred);
}
deferred->push(new jvmtiDeferredLocalVariableSet(method(), bci(), fr().id()));
assert(deferred->top()->id() == fr().id(), "Huh? Must match");
deferred->top()->set_local_at(index, type, value);
}
StackValueCollection* compiledVFrame::expressions() const {
// Natives has no scope
if (scope() == NULL) return new StackValueCollection(0);
GrowableArray<ScopeValue*>* scv_list = scope()->expressions();
if (scv_list == NULL) return new StackValueCollection(0);
// scv_list is the list of ScopeValues describing the JVM stack state.
// There is one scv_list entry for every JVM stack state in use.
int length = scv_list->length();
StackValueCollection* result = new StackValueCollection(length);
for( int i = 0; i < length; i++ )
result->add( create_stack_value(scv_list->at(i)) );
return result;
}
// The implementation of the following two methods was factorized into the
// class StackValue because it is also used from within deoptimization.cpp for
// rematerialization and relocking of non-escaping objects.
StackValue *compiledVFrame::create_stack_value(ScopeValue *sv) const {
return StackValue::create_stack_value(&_fr, register_map(), sv);
}
BasicLock* compiledVFrame::resolve_monitor_lock(Location location) const {
return StackValue::resolve_monitor_lock(&_fr, location);
}
GrowableArray<MonitorInfo*>* compiledVFrame::monitors() const {
// Natives has no scope
if (scope() == NULL) {
nmethod* nm = code();
methodOop method = nm->method();
assert(method->is_native(), "");
if (!method->is_synchronized()) {
return new GrowableArray<MonitorInfo*>(0);
}
// This monitor is really only needed for UseBiasedLocking, but
// return it in all cases for now as it might be useful for stack
// traces and tools as well
GrowableArray<MonitorInfo*> *monitors = new GrowableArray<MonitorInfo*>(1);
// Casting away const
frame& fr = (frame&) _fr;
MonitorInfo* info = new MonitorInfo(fr.compiled_synchronized_native_monitor_owner(nm),
fr.compiled_synchronized_native_monitor(nm), false);
monitors->push(info);
return monitors;
}
GrowableArray<MonitorValue*>* monitors = scope()->monitors();
if (monitors == NULL) {
return new GrowableArray<MonitorInfo*>(0);
}
GrowableArray<MonitorInfo*>* result = new GrowableArray<MonitorInfo*>(monitors->length());
for (int index = 0; index < monitors->length(); index++) {
MonitorValue* mv = monitors->at(index);
StackValue *owner_sv = create_stack_value(mv->owner()); // it is an oop
result->push(new MonitorInfo(owner_sv->get_obj()(), resolve_monitor_lock(mv->basic_lock()), mv->eliminated()));
}
return result;
}
compiledVFrame::compiledVFrame(const frame* fr, const RegisterMap* reg_map, JavaThread* thread, nmethod* nm)
: javaVFrame(fr, reg_map, thread) {
_scope = NULL;
// Compiled method (native stub or Java code)
// native wrappers have no scope data, it is implied
if (!nm->is_native_method()) {
_scope = nm->scope_desc_at(_fr.pc());
}
}
compiledVFrame::compiledVFrame(const frame* fr, const RegisterMap* reg_map, JavaThread* thread, ScopeDesc* scope)
: javaVFrame(fr, reg_map, thread) {
_scope = scope;
guarantee(_scope != NULL, "scope must be present");
}
bool compiledVFrame::is_top() const {
// FIX IT: Remove this when new native stubs are in place
if (scope() == NULL) return true;
return scope()->is_top();
}
nmethod* compiledVFrame::code() const {
return CodeCache::find_nmethod(_fr.pc());
}
methodOop compiledVFrame::method() const {
if (scope() == NULL) {
// native nmethods have no scope the method is implied
nmethod* nm = code();
assert(nm->is_native_method(), "must be native");
return nm->method();
}
return scope()->method()();
}
int compiledVFrame::bci() const {
int raw = raw_bci();
return raw == SynchronizationEntryBCI ? 0 : raw;
}
int compiledVFrame::raw_bci() const {
if (scope() == NULL) {
// native nmethods have no scope the method/bci is implied
nmethod* nm = code();
assert(nm->is_native_method(), "must be native");
return 0;
}
return scope()->bci();
}
vframe* compiledVFrame::sender() const {
const frame f = fr();
if (scope() == NULL) {
// native nmethods have no scope the method/bci is implied
nmethod* nm = code();
assert(nm->is_native_method(), "must be native");
return vframe::sender();
} else {
return scope()->is_top()
? vframe::sender()
: new compiledVFrame(&f, register_map(), thread(), scope()->sender());
}
}
jvmtiDeferredLocalVariableSet::jvmtiDeferredLocalVariableSet(methodOop method, int bci, intptr_t* id) {
_method = method;
_bci = bci;
_id = id;
// Alway will need at least one, must be on C heap
_locals = new(ResourceObj::C_HEAP) GrowableArray<jvmtiDeferredLocalVariable*> (1, true);
}
jvmtiDeferredLocalVariableSet::~jvmtiDeferredLocalVariableSet() {
for (int i = 0; i < _locals->length() ; i++ ) {
delete _locals->at(i);
}
// Free growableArray and c heap for elements
delete _locals;
}
bool jvmtiDeferredLocalVariableSet::matches(vframe* vf) {
if (!vf->is_compiled_frame()) return false;
compiledVFrame* cvf = (compiledVFrame*)vf;
return cvf->fr().id() == id() && cvf->method() == method() && cvf->bci() == bci();
}
void jvmtiDeferredLocalVariableSet::set_local_at(int idx, BasicType type, jvalue val) {
int i;
for ( i = 0 ; i < locals()->length() ; i++ ) {
if ( locals()->at(i)->index() == idx) {
assert(locals()->at(i)->type() == type, "Wrong type");
locals()->at(i)->set_value(val);
return;
}
}
locals()->push(new jvmtiDeferredLocalVariable(idx, type, val));
}
void jvmtiDeferredLocalVariableSet::oops_do(OopClosure* f) {
f->do_oop((oop*) &_method);
for ( int i = 0; i < locals()->length(); i++ ) {
if ( locals()->at(i)->type() == T_OBJECT) {
f->do_oop(locals()->at(i)->oop_addr());
}
}
}
jvmtiDeferredLocalVariable::jvmtiDeferredLocalVariable(int index, BasicType type, jvalue value) {
_index = index;
_type = type;
_value = value;
}
#ifndef PRODUCT
void compiledVFrame::verify() const {
Unimplemented();
}
#endif // PRODUCT
|
guanxiaohua/TransGC
|
src/share/vm/runtime/vframe_hp.cpp
|
C++
|
gpl-2.0
| 11,614 |
/*
ettercap -- parsing utilities
Copyright (C) ALoR & NaGA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <ec.h>
#include <ec_interfaces.h>
#include <ec_sniff.h>
#include <ec_send.h>
#include <ec_log.h>
#include <ec_format.h>
#include <ec_update.h>
#include <ec_mitm.h>
#include <ec_filter.h>
#include <ec_plugins.h>
#include <ec_conf.h>
#include <ec_strings.h>
#include <ctype.h>
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#else
#include <missing/getopt.h>
#endif
/* protos... */
static void ec_usage(void);
void parse_options(int argc, char **argv);
int expand_token(char *s, u_int max, void (*func)(void *t, u_int n), void *t );
int set_regex(char *regex);
static char **parse_iflist(char *list);
/* from the ec_wifi.c decoder */
extern int set_wep_key(u_char *string);
/*****************************************/
void ec_usage(void)
{
fprintf(stdout, "\nUsage: %s [OPTIONS] [TARGET1] [TARGET2]\n", GBL_PROGRAM);
fprintf(stdout, "\nTARGET is in the format MAC/IP/IPv6/PORTs (see the man for further detail)\n");
fprintf(stdout, "\nSniffing and Attack options:\n");
fprintf(stdout, " -M, --mitm <METHOD:ARGS> perform a mitm attack\n");
fprintf(stdout, " -o, --only-mitm don't sniff, only perform the mitm attack\n");
fprintf(stdout, " -b, --broadcast sniff packets destined to broadcast\n");
fprintf(stdout, " -B, --bridge <IFACE> use bridged sniff (needs 2 ifaces)\n");
fprintf(stdout, " -p, --nopromisc do not put the iface in promisc mode\n");
fprintf(stdout, " -S, --nosslmitm do not forge SSL certificates\n");
fprintf(stdout, " -u, --unoffensive do not forward packets\n");
fprintf(stdout, " -r, --read <file> read data from pcapfile <file>\n");
fprintf(stdout, " -f, --pcapfilter <string> set the pcap filter <string>\n");
fprintf(stdout, " -R, --reversed use reversed TARGET matching\n");
fprintf(stdout, " -t, --proto <proto> sniff only this proto (default is all)\n");
fprintf(stdout, " --certificate <file> certificate file to use for SSL MiTM\n");
fprintf(stdout, " --private-key <file> private key file to use for SSL MiTM\n");
fprintf(stdout, "\nUser Interface Type:\n");
fprintf(stdout, " -T, --text use text only GUI\n");
fprintf(stdout, " -q, --quiet do not display packet contents\n");
fprintf(stdout, " -s, --script <CMD> issue these commands to the GUI\n");
fprintf(stdout, " -C, --curses use curses GUI\n");
fprintf(stdout, " -D, --daemon daemonize ettercap (no GUI)\n");
fprintf(stdout, " -G, --gtk use GTK+ GUI\n");
fprintf(stdout, "\nLogging options:\n");
fprintf(stdout, " -w, --write <file> write sniffed data to pcapfile <file>\n");
fprintf(stdout, " -L, --log <logfile> log all the traffic to this <logfile>\n");
fprintf(stdout, " -l, --log-info <logfile> log only passive infos to this <logfile>\n");
fprintf(stdout, " -m, --log-msg <logfile> log all the messages to this <logfile>\n");
fprintf(stdout, " -c, --compress use gzip compression on log files\n");
fprintf(stdout, "\nVisualization options:\n");
fprintf(stdout, " -d, --dns resolves ip addresses into hostnames\n");
fprintf(stdout, " -V, --visual <format> set the visualization format\n");
fprintf(stdout, " -e, --regex <regex> visualize only packets matching this regex\n");
fprintf(stdout, " -E, --ext-headers print extended header for every pck\n");
fprintf(stdout, " -Q, --superquiet do not display user and password\n");
fprintf(stdout, "\nGeneral options:\n");
fprintf(stdout, " -i, --iface <iface> use this network interface\n");
fprintf(stdout, " -I, --liface show all the network interfaces\n");
fprintf(stdout, " -Y, --secondary <ifaces> list of secondary network interfaces\n");
fprintf(stdout, " -n, --netmask <netmask> force this <netmask> on iface\n");
fprintf(stdout, " -A, --address <address> force this local <address> on iface\n");
fprintf(stdout, " -P, --plugin <plugin> launch this <plugin>\n");
fprintf(stdout, " -F, --filter <file> load the filter <file> (content filter)\n");
fprintf(stdout, " -z, --silent do not perform the initial ARP scan\n");
fprintf(stdout, " -j, --load-hosts <file> load the hosts list from <file>\n");
fprintf(stdout, " -k, --save-hosts <file> save the hosts list to <file>\n");
fprintf(stdout, " -W, --wep-key <wkey> use this wep key to decrypt wifi packets\n");
fprintf(stdout, " -a, --config <config> use the alterative config file <config>\n");
fprintf(stdout, "\nStandard options:\n");
fprintf(stdout, " -U, --update updates the databases from ettercap website\n");
fprintf(stdout, " -v, --version prints the version and exit\n");
fprintf(stdout, " -h, --help this help screen\n");
fprintf(stdout, "\n\n");
//clean_exit(0);
exit(0);
}
void parse_options(int argc, char **argv)
{
int c;
static struct option long_options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ "update", no_argument, NULL, 'U' },
{ "iface", required_argument, NULL, 'i' },
{ "lifaces", no_argument, NULL, 'I' },
{ "netmask", required_argument, NULL, 'n' },
{ "address", required_argument, NULL, 'A' },
{ "write", required_argument, NULL, 'w' },
{ "read", required_argument, NULL, 'r' },
{ "pcapfilter", required_argument, NULL, 'f' },
{ "reversed", no_argument, NULL, 'R' },
{ "proto", required_argument, NULL, 't' },
{ "plugin", required_argument, NULL, 'P' },
{ "filter", required_argument, NULL, 'F' },
{ "superquiet", no_argument, NULL, 'Q' },
{ "quiet", no_argument, NULL, 'q' },
{ "script", required_argument, NULL, 's' },
{ "silent", no_argument, NULL, 'z' },
{ "unoffensive", no_argument, NULL, 'u' },
{ "nosslmitm", no_argument, NULL, 'S' },
{ "load-hosts", required_argument, NULL, 'j' },
{ "save-hosts", required_argument, NULL, 'k' },
{ "wep-key", required_argument, NULL, 'W' },
{ "config", required_argument, NULL, 'a' },
{ "dns", no_argument, NULL, 'd' },
{ "regex", required_argument, NULL, 'e' },
{ "visual", required_argument, NULL, 'V' },
{ "ext-headers", no_argument, NULL, 'E' },
{ "log", required_argument, NULL, 'L' },
{ "log-info", required_argument, NULL, 'l' },
{ "log-msg", required_argument, NULL, 'm' },
{ "compress", no_argument, NULL, 'c' },
{ "text", no_argument, NULL, 'T' },
{ "curses", no_argument, NULL, 'C' },
{ "daemon", no_argument, NULL, 'D' },
{ "gtk", no_argument, NULL, 'G' },
{ "mitm", required_argument, NULL, 'M' },
{ "only-mitm", no_argument, NULL, 'o' },
{ "bridge", required_argument, NULL, 'B' },
{ "broadcast", required_argument, NULL, 'b' },
{ "promisc", no_argument, NULL, 'p' },
{ "gateway", required_argument, NULL, 'Y' },
{ "certificate", required_argument, NULL, 0 },
{ "private-key", required_argument, NULL, 0 },
{ 0 , 0 , 0 , 0}
};
for (c = 0; c < argc; c++)
DEBUG_MSG("parse_options -- [%d] [%s]", c, argv[c]);
/* OPTIONS INITIALIZATION */
GBL_PCAP->promisc = 1;
GBL_FORMAT = &ascii_format;
GBL_OPTIONS->ssl_mitm = 1;
GBL_OPTIONS->broadcast = 0;
GBL_OPTIONS->ssl_cert = NULL;
GBL_OPTIONS->ssl_pkey = NULL;
/* OPTIONS INITIALIZED */
optind = 0;
int option_index = 0;
while ((c = getopt_long (argc, argv, "A:a:bB:CchDdEe:F:f:GhIi:j:k:L:l:M:m:n:oP:pQqiRr:s:STt:UuV:vW:w:Y:z", long_options, &option_index)) != EOF) {
/* used for parsing arguments */
char *opt_end = optarg;
while (opt_end && *opt_end) opt_end++;
/* enable a loaded filter script? */
uint8_t f_enabled = 1;
switch (c) {
case 'M':
GBL_OPTIONS->mitm = 1;
if (mitm_set(optarg) != ESUCCESS)
FATAL_ERROR("MITM method '%s' not supported...\n", optarg);
break;
case 'o':
GBL_OPTIONS->only_mitm = 1;
//select_text_interface();
break;
case 'b':
GBL_OPTIONS->broadcast = 1;
break;
case 'B':
GBL_OPTIONS->iface_bridge = strdup(optarg);
set_bridge_sniff();
break;
case 'p':
GBL_PCAP->promisc = 0;
break;
case 'T':
select_text_interface();
break;
case 'C':
select_curses_interface();
break;
case 'G':
select_gtk_interface();
break;
case 'D':
select_daemon_interface();
break;
case 'R':
GBL_OPTIONS->reversed = 1;
break;
case 't':
GBL_OPTIONS->proto = strdup(optarg);
break;
case 'P':
/* user has requested the list */
if (!strcasecmp(optarg, "list")) {
plugin_list();
clean_exit(0);
}
/* else set the plugin */
GBL_OPTIONS->plugin = strdup(optarg);
break;
case 'i':
GBL_OPTIONS->iface = strdup(optarg);
break;
case 'I':
/* this option is only useful in the text interface */
select_text_interface();
GBL_OPTIONS->lifaces = 1;
break;
case 'Y':
GBL_OPTIONS->secondary = parse_iflist(optarg);
break;
case 'n':
GBL_OPTIONS->netmask = strdup(optarg);
break;
case 'A':
GBL_OPTIONS->address = strdup(optarg);
break;
case 'r':
/* we don't want to scan the lan while reading from file */
GBL_OPTIONS->silent = 1;
GBL_OPTIONS->read = 1;
GBL_OPTIONS->pcapfile_in = strdup(optarg);
break;
case 'w':
GBL_OPTIONS->write = 1;
GBL_OPTIONS->pcapfile_out = strdup(optarg);
break;
case 'f':
GBL_PCAP->filter = strdup(optarg);
break;
case 'F':
/* is there a :0 or :1 appended to the filename? */
if ( (opt_end-optarg >=2) && *(opt_end-2) == ':' ) {
*(opt_end-2) = '\0';
f_enabled = !( *(opt_end-1) == '0' );
}
if (filter_load_file(optarg, GBL_FILTERS, f_enabled) != ESUCCESS)
FATAL_ERROR("Cannot load filter file \"%s\"", optarg);
break;
case 'L':
if (set_loglevel(LOG_PACKET, optarg) == -EFATAL)
clean_exit(-EFATAL);
break;
case 'l':
if (set_loglevel(LOG_INFO, optarg) == -EFATAL)
clean_exit(-EFATAL);
break;
case 'm':
if (set_msg_loglevel(LOG_TRUE, optarg) == -EFATAL)
clean_exit(-EFATAL);
break;
case 'c':
GBL_OPTIONS->compress = 1;
break;
case 'e':
if (set_regex(optarg) == -EFATAL)
clean_exit(-EFATAL);
break;
case 'Q':
GBL_OPTIONS->superquiet = 1;
/* no break, quiet must be enabled */
case 'q':
GBL_OPTIONS->quiet = 1;
break;
case 's':
GBL_OPTIONS->script = strdup(optarg);
break;
case 'z':
GBL_OPTIONS->silent = 1;
break;
case 'u':
GBL_OPTIONS->unoffensive = 1;
break;
case 'S':
GBL_OPTIONS->ssl_mitm = 0;
break;
case 'd':
GBL_OPTIONS->resolve = 1;
break;
case 'j':
GBL_OPTIONS->silent = 1;
GBL_OPTIONS->load_hosts = 1;
GBL_OPTIONS->hostsfile = strdup(optarg);
break;
case 'k':
GBL_OPTIONS->save_hosts = 1;
GBL_OPTIONS->hostsfile = strdup(optarg);
break;
case 'V':
if (set_format(optarg) != ESUCCESS)
clean_exit(-EFATAL);
break;
case 'E':
GBL_OPTIONS->ext_headers = 1;
break;
case 'W':
set_wep_key((u_char*)optarg);
break;
case 'a':
GBL_CONF->file = strdup(optarg);
break;
case 'U':
/* load the conf for the connect timeout value */
load_conf();
global_update();
/* NOT REACHED */
break;
case 'h':
ec_usage();
break;
case 'v':
printf("%s %s\n", GBL_PROGRAM, GBL_VERSION);
clean_exit(0);
break;
/* Certificate and private key options */
case 0:
if (!strcmp(long_options[option_index].name, "certificate")) {
GBL_OPTIONS->ssl_cert = strdup(optarg);
} else if (!strcmp(long_options[option_index].name, "private-key")) {
GBL_OPTIONS->ssl_pkey = strdup(optarg);
} else {
fprintf(stdout, "\nTry `%s --help' for more options.\n\n", GBL_PROGRAM);
clean_exit(-1);
}
break;
case ':': // missing parameter
fprintf(stdout, "\nTry `%s --help' for more options.\n\n", GBL_PROGRAM);
clean_exit(-1);
break;
case '?': // unknown option
fprintf(stdout, "\nTry `%s --help' for more options.\n\n", GBL_PROGRAM);
clean_exit(-1);
break;
}
}
DEBUG_MSG("parse_options: options parsed");
/* TARGET1 and TARGET2 parsing */
if (argv[optind]) {
GBL_OPTIONS->target1 = strdup(argv[optind]);
DEBUG_MSG("TARGET1: %s", GBL_OPTIONS->target1);
if (argv[optind+1]) {
GBL_OPTIONS->target2 = strdup(argv[optind+1]);
DEBUG_MSG("TARGET2: %s", GBL_OPTIONS->target2);
}
}
/* create the list form the TARGET format (MAC/IPrange/PORTrange) */
compile_display_filter();
DEBUG_MSG("parse_options: targets parsed");
/* check for other options */
if (GBL_SNIFF->start == NULL)
set_unified_sniff();
if (GBL_OPTIONS->read && GBL_PCAP->filter)
FATAL_ERROR("Cannot read from file and set a filter on interface");
if (GBL_OPTIONS->read && GBL_SNIFF->type != SM_UNIFIED )
FATAL_ERROR("You can read from a file ONLY in unified sniffing mode !");
if (GBL_OPTIONS->mitm && GBL_SNIFF->type != SM_UNIFIED )
FATAL_ERROR("You can't do mitm attacks in bridged sniffing mode !");
if (GBL_SNIFF->type == SM_BRIDGED && GBL_PCAP->promisc == 0)
FATAL_ERROR("During bridged sniffing the iface must be in promisc mode !");
if (GBL_OPTIONS->quiet && GBL_UI->type != UI_TEXT)
FATAL_ERROR("The quiet option is useful only with text only UI");
if (GBL_OPTIONS->load_hosts && GBL_OPTIONS->save_hosts)
FATAL_ERROR("Cannot load and save at the same time the hosts list...");
if (GBL_OPTIONS->unoffensive && GBL_OPTIONS->mitm)
FATAL_ERROR("Cannot use mitm attacks in unoffensive mode");
if (GBL_OPTIONS->read && GBL_OPTIONS->mitm)
FATAL_ERROR("Cannot use mitm attacks while reading from file");
if (GBL_UI->init == NULL)
FATAL_ERROR("Please select an User Interface");
/* force text interface for only mitm attack */
/* Do not select text interface for only MiTM mode
if (GBL_OPTIONS->only_mitm) {
if (GBL_OPTIONS->mitm)
select_text_interface();
else
FATAL_ERROR("Only mitm requires at least one mitm method");
} */
DEBUG_MSG("parse_options: options combination looks good");
return;
}
/*
* This function parses the input in the form [1-3,17,5-11]
* and fill the structure with expanded numbers.
*/
int expand_token(char *s, u_int max, void (*func)(void *t, u_int n), void *t )
{
char *str = strdup(s);
char *p, *q, r;
char *end;
u_int a = 0, b = 0;
DEBUG_MSG("expand_token %s", s);
p = str;
end = p + strlen(p);
while (p < end) {
q = p;
/* find the end of the first digit */
while ( isdigit((int)*q) && q++ < end);
r = *q;
*q = 0;
/* get the first digit */
a = atoi(p);
if (a > max)
FATAL_MSG("Out of range (%d) !!", max);
/* it is a range ? */
if ( r == '-') {
p = ++q;
/* find the end of the range */
while ( isdigit((int)*q) && q++ < end);
*q = 0;
if (*p == '\0')
FATAL_MSG("Invalid range !!");
/* get the second digit */
b = atoi(p);
if (b > max)
FATAL_MSG("Out of range (%d)!!", max);
if (b < a)
FATAL_MSG("Invalid decrementing range !!");
} else {
/* it is not a range */
b = a;
}
/* process the range and invoke the callback */
for(; a <= b; a++) {
func(t, a);
}
if (q == end) break;
else p = q + 1;
}
SAFE_FREE(str);
return ESUCCESS;
}
/*
* compile the regex
*/
int set_regex(char *regex)
{
int err;
char errbuf[100];
DEBUG_MSG("set_regex: %s", regex);
/* free any previous compilation */
if (GBL_OPTIONS->regex)
regfree(GBL_OPTIONS->regex);
/* unset the regex if empty */
if (!strcmp(regex, "")) {
SAFE_FREE(GBL_OPTIONS->regex);
return ESUCCESS;
}
/* allocate the new structure */
SAFE_CALLOC(GBL_OPTIONS->regex, 1, sizeof(regex_t));
/* compile the regex */
err = regcomp(GBL_OPTIONS->regex, regex, REG_EXTENDED | REG_NOSUB | REG_ICASE );
if (err) {
regerror(err, GBL_OPTIONS->regex, errbuf, sizeof(errbuf));
FATAL_MSG("%s\n", errbuf);
}
return ESUCCESS;
}
static char **parse_iflist(char *list)
{
int i, n;
char **r, *t, *p;
for(i = 0, n = 1; list[i] != '\0'; list[i++] == ',' ? n++ : n);
SAFE_CALLOC(r, n + 1, sizeof(char*));
/* its self-explaining */
for(r[i=0]=ec_strtok(list,",",&p);i<n&&(t=ec_strtok(NULL,",",&p))!=NULL;r[++i]=strdup(t));
r[n] = NULL;
return r;
}
/* EOF */
// vim:ts=3:expandtab
|
alor/ettercap
|
src/ec_parser.c
|
C
|
gpl-2.0
| 20,672 |
/*
* Copyright (C) 2010, 2011, 2012 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WKContextPrivate.h"
#include "APIClient.h"
#include "APIDownloadClient.h"
#include "APILegacyContextHistoryClient.h"
#include "APINavigationData.h"
#include "APIProcessPoolConfiguration.h"
#include "APIURLRequest.h"
#include "AuthenticationChallengeProxy.h"
#include "DownloadProxy.h"
#include "WKAPICast.h"
#include "WKContextConfigurationRef.h"
#include "WKRetainPtr.h"
#include "WebCertificateInfo.h"
#include "WebIconDatabase.h"
#include "WebProcessPool.h"
#include <wtf/PassRefPtr.h>
#include <wtf/RefPtr.h>
#include <wtf/text/WTFString.h>
// Supplements
#include "WebCookieManagerProxy.h"
#include "WebGeolocationManagerProxy.h"
#include "WebNotificationManagerProxy.h"
#if ENABLE(BATTERY_STATUS)
#include "WebBatteryManagerProxy.h"
#endif
namespace API {
template<> struct ClientTraits<WKContextDownloadClientBase> {
typedef std::tuple<WKContextDownloadClientV0> Versions;
};
template<> struct ClientTraits<WKContextHistoryClientBase> {
typedef std::tuple<WKContextHistoryClientV0> Versions;
};
}
using namespace WebCore;
using namespace WebKit;
WKTypeID WKContextGetTypeID()
{
return toAPI(WebProcessPool::APIType);
}
WKContextRef WKContextCreate()
{
auto configuration = API::ProcessPoolConfiguration::createWithLegacyOptions();
return toAPI(&WebProcessPool::create(configuration).leakRef());
}
WKContextRef WKContextCreateWithInjectedBundlePath(WKStringRef pathRef)
{
auto configuration = API::ProcessPoolConfiguration::createWithLegacyOptions();
configuration->setInjectedBundlePath(toWTFString(pathRef));
return toAPI(&WebProcessPool::create(configuration).leakRef());
}
WKContextRef WKContextCreateWithConfiguration(WKContextConfigurationRef configuration)
{
return toAPI(&WebProcessPool::create(*toImpl(configuration)).leakRef());
}
void WKContextSetClient(WKContextRef contextRef, const WKContextClientBase* wkClient)
{
toImpl(contextRef)->initializeClient(wkClient);
}
void WKContextSetInjectedBundleClient(WKContextRef contextRef, const WKContextInjectedBundleClientBase* wkClient)
{
toImpl(contextRef)->initializeInjectedBundleClient(wkClient);
}
void WKContextSetHistoryClient(WKContextRef contextRef, const WKContextHistoryClientBase* wkClient)
{
class HistoryClient final : public API::Client<WKContextHistoryClientBase>, public API::LegacyContextHistoryClient {
public:
explicit HistoryClient(const WKContextHistoryClientBase* client)
{
initialize(client);
}
private:
virtual void didNavigateWithNavigationData(WebProcessPool& processPool, WebPageProxy& page, const WebNavigationDataStore& navigationDataStore, WebFrameProxy& frame) override
{
if (!m_client.didNavigateWithNavigationData)
return;
RefPtr<API::NavigationData> navigationData = API::NavigationData::create(navigationDataStore);
m_client.didNavigateWithNavigationData(toAPI(&processPool), toAPI(&page), toAPI(navigationData.get()), toAPI(&frame), m_client.base.clientInfo);
}
virtual void didPerformClientRedirect(WebProcessPool& processPool, WebPageProxy& page, const String& sourceURL, const String& destinationURL, WebFrameProxy& frame) override
{
if (!m_client.didPerformClientRedirect)
return;
m_client.didPerformClientRedirect(toAPI(&processPool), toAPI(&page), toURLRef(sourceURL.impl()), toURLRef(destinationURL.impl()), toAPI(&frame), m_client.base.clientInfo);
}
virtual void didPerformServerRedirect(WebProcessPool& processPool, WebPageProxy& page, const String& sourceURL, const String& destinationURL, WebFrameProxy& frame) override
{
if (!m_client.didPerformServerRedirect)
return;
m_client.didPerformServerRedirect(toAPI(&processPool), toAPI(&page), toURLRef(sourceURL.impl()), toURLRef(destinationURL.impl()), toAPI(&frame), m_client.base.clientInfo);
}
virtual void didUpdateHistoryTitle(WebProcessPool& processPool, WebPageProxy& page, const String& title, const String& url, WebFrameProxy& frame) override
{
if (!m_client.didUpdateHistoryTitle)
return;
m_client.didUpdateHistoryTitle(toAPI(&processPool), toAPI(&page), toAPI(title.impl()), toURLRef(url.impl()), toAPI(&frame), m_client.base.clientInfo);
}
virtual void populateVisitedLinks(WebProcessPool& processPool) override
{
if (!m_client.populateVisitedLinks)
return;
m_client.populateVisitedLinks(toAPI(&processPool), m_client.base.clientInfo);
}
virtual bool addsVisitedLinks() const override
{
return m_client.populateVisitedLinks;
}
};
WebProcessPool& processPool = *toImpl(contextRef);
processPool.setHistoryClient(std::make_unique<HistoryClient>(wkClient));
bool addsVisitedLinks = processPool.historyClient().addsVisitedLinks();
for (auto& process : processPool.processes()) {
for (auto& page : process->pages())
page->setAddsVisitedLinks(addsVisitedLinks);
}
}
void WKContextSetDownloadClient(WKContextRef contextRef, const WKContextDownloadClientBase* wkClient)
{
class DownloadClient final : public API::Client<WKContextDownloadClientBase>, public API::DownloadClient {
public:
explicit DownloadClient(const WKContextDownloadClientBase* client)
{
initialize(client);
}
private:
virtual void didStart(WebProcessPool* processPool, DownloadProxy* downloadProxy) override
{
if (!m_client.didStart)
return;
m_client.didStart(toAPI(processPool), toAPI(downloadProxy), m_client.base.clientInfo);
}
virtual void didReceiveAuthenticationChallenge(WebProcessPool* processPool, DownloadProxy* downloadProxy, AuthenticationChallengeProxy* authenticationChallengeProxy) override
{
if (!m_client.didReceiveAuthenticationChallenge)
return;
m_client.didReceiveAuthenticationChallenge(toAPI(processPool), toAPI(downloadProxy), toAPI(authenticationChallengeProxy), m_client.base.clientInfo);
}
virtual void didReceiveResponse(WebProcessPool* processPool, DownloadProxy* downloadProxy, const ResourceResponse& response) override
{
if (!m_client.didReceiveResponse)
return;
m_client.didReceiveResponse(toAPI(processPool), toAPI(downloadProxy), toAPI(API::URLResponse::create(response).ptr()), m_client.base.clientInfo);
}
virtual void didReceiveData(WebProcessPool* processPool, DownloadProxy* downloadProxy, uint64_t length) override
{
if (!m_client.didReceiveData)
return;
m_client.didReceiveData(toAPI(processPool), toAPI(downloadProxy), length, m_client.base.clientInfo);
}
virtual bool shouldDecodeSourceDataOfMIMEType(WebProcessPool* processPool, DownloadProxy* downloadProxy, const String& mimeType) override
{
if (!m_client.shouldDecodeSourceDataOfMIMEType)
return true;
return m_client.shouldDecodeSourceDataOfMIMEType(toAPI(processPool), toAPI(downloadProxy), toAPI(mimeType.impl()), m_client.base.clientInfo);
}
virtual String decideDestinationWithSuggestedFilename(WebProcessPool* processPool, DownloadProxy* downloadProxy, const String& filename, bool& allowOverwrite) override
{
if (!m_client.decideDestinationWithSuggestedFilename)
return String();
WKRetainPtr<WKStringRef> destination(AdoptWK, m_client.decideDestinationWithSuggestedFilename(toAPI(processPool), toAPI(downloadProxy), toAPI(filename.impl()), &allowOverwrite, m_client.base.clientInfo));
return toWTFString(destination.get());
}
virtual void didCreateDestination(WebProcessPool* processPool, DownloadProxy* downloadProxy, const String& path) override
{
if (!m_client.didCreateDestination)
return;
m_client.didCreateDestination(toAPI(processPool), toAPI(downloadProxy), toAPI(path.impl()), m_client.base.clientInfo);
}
virtual void didFinish(WebProcessPool* processPool, DownloadProxy* downloadProxy) override
{
if (!m_client.didFinish)
return;
m_client.didFinish(toAPI(processPool), toAPI(downloadProxy), m_client.base.clientInfo);
}
virtual void didFail(WebProcessPool* processPool, DownloadProxy* downloadProxy, const ResourceError& error) override
{
if (!m_client.didFail)
return;
m_client.didFail(toAPI(processPool), toAPI(downloadProxy), toAPI(error), m_client.base.clientInfo);
}
virtual void didCancel(WebProcessPool* processPool, DownloadProxy* downloadProxy) override
{
if (!m_client.didCancel)
return;
m_client.didCancel(toAPI(processPool), toAPI(downloadProxy), m_client.base.clientInfo);
}
virtual void processDidCrash(WebProcessPool* processPool, DownloadProxy* downloadProxy) override
{
if (!m_client.processDidCrash)
return;
m_client.processDidCrash(toAPI(processPool), toAPI(downloadProxy), m_client.base.clientInfo);
}
};
toImpl(contextRef)->setDownloadClient(std::make_unique<DownloadClient>(wkClient));
}
void WKContextSetConnectionClient(WKContextRef contextRef, const WKContextConnectionClientBase* wkClient)
{
toImpl(contextRef)->initializeConnectionClient(wkClient);
}
WKDownloadRef WKContextDownloadURLRequest(WKContextRef contextRef, WKURLRequestRef requestRef)
{
return toAPI(toImpl(contextRef)->download(0, toImpl(requestRef)->resourceRequest()));
}
WKDownloadRef WKContextResumeDownload(WKContextRef contextRef, WKDataRef resumeData, WKStringRef path)
{
return toAPI(toImpl(contextRef)->resumeDownload(toImpl(resumeData), toWTFString(path)));
}
void WKContextSetInitializationUserDataForInjectedBundle(WKContextRef contextRef, WKTypeRef userDataRef)
{
toImpl(contextRef)->setInjectedBundleInitializationUserData(toImpl(userDataRef));
}
void WKContextPostMessageToInjectedBundle(WKContextRef contextRef, WKStringRef messageNameRef, WKTypeRef messageBodyRef)
{
toImpl(contextRef)->postMessageToInjectedBundle(toImpl(messageNameRef)->string(), toImpl(messageBodyRef));
}
void WKContextGetGlobalStatistics(WKContextStatistics* statistics)
{
const WebProcessPool::Statistics& webContextStatistics = WebProcessPool::statistics();
statistics->wkViewCount = webContextStatistics.wkViewCount;
statistics->wkPageCount = webContextStatistics.wkPageCount;
statistics->wkFrameCount = webContextStatistics.wkFrameCount;
}
void WKContextAddVisitedLink(WKContextRef contextRef, WKStringRef visitedURL)
{
String visitedURLString = toImpl(visitedURL)->string();
if (visitedURLString.isEmpty())
return;
toImpl(contextRef)->visitedLinkStore().addVisitedLinkHash(visitedLinkHash(visitedURLString));
}
void WKContextClearVisitedLinks(WKContextRef contextRef)
{
toImpl(contextRef)->visitedLinkStore().removeAll();
}
void WKContextSetCacheModel(WKContextRef contextRef, WKCacheModel cacheModel)
{
toImpl(contextRef)->setCacheModel(toCacheModel(cacheModel));
}
WKCacheModel WKContextGetCacheModel(WKContextRef contextRef)
{
return toAPI(toImpl(contextRef)->cacheModel());
}
void WKContextSetMaximumNumberOfProcesses(WKContextRef contextRef, unsigned numberOfProcesses)
{
toImpl(contextRef)->setMaximumNumberOfProcesses(numberOfProcesses);
}
unsigned WKContextGetMaximumNumberOfProcesses(WKContextRef contextRef)
{
return toImpl(contextRef)->maximumNumberOfProcesses();
}
void WKContextSetAlwaysUsesComplexTextCodePath(WKContextRef contextRef, bool alwaysUseComplexTextCodePath)
{
toImpl(contextRef)->setAlwaysUsesComplexTextCodePath(alwaysUseComplexTextCodePath);
}
void WKContextSetShouldUseFontSmoothing(WKContextRef contextRef, bool useFontSmoothing)
{
toImpl(contextRef)->setShouldUseFontSmoothing(useFontSmoothing);
}
void WKContextSetAdditionalPluginsDirectory(WKContextRef contextRef, WKStringRef pluginsDirectory)
{
#if ENABLE(NETSCAPE_PLUGIN_API)
toImpl(contextRef)->setAdditionalPluginsDirectory(toImpl(pluginsDirectory)->string());
#else
UNUSED_PARAM(contextRef);
UNUSED_PARAM(pluginsDirectory);
#endif
}
void WKContextRegisterURLSchemeAsEmptyDocument(WKContextRef contextRef, WKStringRef urlScheme)
{
toImpl(contextRef)->registerURLSchemeAsEmptyDocument(toImpl(urlScheme)->string());
}
void WKContextRegisterURLSchemeAsSecure(WKContextRef contextRef, WKStringRef urlScheme)
{
toImpl(contextRef)->registerURLSchemeAsSecure(toImpl(urlScheme)->string());
}
void WKContextRegisterURLSchemeAsBypassingContentSecurityPolicy(WKContextRef contextRef, WKStringRef urlScheme)
{
toImpl(contextRef)->registerURLSchemeAsBypassingContentSecurityPolicy(toImpl(urlScheme)->string());
}
void WKContextRegisterURLSchemeAsCachePartitioned(WKContextRef contextRef, WKStringRef urlScheme)
{
#if ENABLE(CACHE_PARTITIONING)
toImpl(contextRef)->registerURLSchemeAsCachePartitioned(toImpl(urlScheme)->string());
#else
UNUSED_PARAM(contextRef);
UNUSED_PARAM(urlScheme);
#endif
}
void WKContextSetDomainRelaxationForbiddenForURLScheme(WKContextRef contextRef, WKStringRef urlScheme)
{
toImpl(contextRef)->setDomainRelaxationForbiddenForURLScheme(toImpl(urlScheme)->string());
}
void WKContextSetCanHandleHTTPSServerTrustEvaluation(WKContextRef contextRef, bool value)
{
toImpl(contextRef)->setCanHandleHTTPSServerTrustEvaluation(value);
}
WKCookieManagerRef WKContextGetCookieManager(WKContextRef contextRef)
{
return toAPI(toImpl(contextRef)->supplement<WebCookieManagerProxy>());
}
WKWebsiteDataStoreRef WKContextGetWebsiteDataStore(WKContextRef context)
{
return toAPI(toImpl(context)->websiteDataStore());
}
WKApplicationCacheManagerRef WKContextGetApplicationCacheManager(WKContextRef context)
{
return reinterpret_cast<WKApplicationCacheManagerRef>(WKContextGetWebsiteDataStore(context));
}
WKBatteryManagerRef WKContextGetBatteryManager(WKContextRef contextRef)
{
#if ENABLE(BATTERY_STATUS)
return toAPI(toImpl(contextRef)->supplement<WebBatteryManagerProxy>());
#else
UNUSED_PARAM(contextRef);
return 0;
#endif
}
WKGeolocationManagerRef WKContextGetGeolocationManager(WKContextRef contextRef)
{
return toAPI(toImpl(contextRef)->supplement<WebGeolocationManagerProxy>());
}
WKIconDatabaseRef WKContextGetIconDatabase(WKContextRef contextRef)
{
return toAPI(toImpl(contextRef)->iconDatabase());
}
WKKeyValueStorageManagerRef WKContextGetKeyValueStorageManager(WKContextRef context)
{
return reinterpret_cast<WKKeyValueStorageManagerRef>(WKContextGetWebsiteDataStore(context));
}
WKMediaSessionFocusManagerRef WKContextGetMediaSessionFocusManager(WKContextRef context)
{
#if ENABLE(MEDIA_SESSION)
return toAPI(toImpl(context)->supplement<WebMediaSessionFocusManager>());
#else
UNUSED_PARAM(context);
return nullptr;
#endif
}
WKNotificationManagerRef WKContextGetNotificationManager(WKContextRef contextRef)
{
return toAPI(toImpl(contextRef)->supplement<WebNotificationManagerProxy>());
}
WKPluginSiteDataManagerRef WKContextGetPluginSiteDataManager(WKContextRef context)
{
#if ENABLE(NETSCAPE_PLUGIN_API)
return reinterpret_cast<WKPluginSiteDataManagerRef>(WKContextGetWebsiteDataStore(context));
#else
UNUSED_PARAM(context);
return nullptr;
#endif
}
WKResourceCacheManagerRef WKContextGetResourceCacheManager(WKContextRef context)
{
return reinterpret_cast<WKResourceCacheManagerRef>(WKContextGetWebsiteDataStore(context));
}
void WKContextStartMemorySampler(WKContextRef contextRef, WKDoubleRef interval)
{
toImpl(contextRef)->startMemorySampler(toImpl(interval)->value());
}
void WKContextStopMemorySampler(WKContextRef contextRef)
{
toImpl(contextRef)->stopMemorySampler();
}
void WKContextSetIconDatabasePath(WKContextRef contextRef, WKStringRef iconDatabasePath)
{
toImpl(contextRef)->setIconDatabasePath(toImpl(iconDatabasePath)->string());
}
void WKContextAllowSpecificHTTPSCertificateForHost(WKContextRef contextRef, WKCertificateInfoRef certificateRef, WKStringRef hostRef)
{
toImpl(contextRef)->allowSpecificHTTPSCertificateForHost(toImpl(certificateRef), toImpl(hostRef)->string());
}
WK_EXPORT void WKContextSetCookieStorageDirectory(WKContextRef contextRef, WKStringRef cookieStorageDirectory)
{
toImpl(contextRef)->setCookieStorageDirectory(toImpl(cookieStorageDirectory)->string());
}
void WKContextDisableProcessTermination(WKContextRef contextRef)
{
toImpl(contextRef)->disableProcessTermination();
}
void WKContextEnableProcessTermination(WKContextRef contextRef)
{
toImpl(contextRef)->enableProcessTermination();
}
void WKContextSetHTTPPipeliningEnabled(WKContextRef contextRef, bool enabled)
{
toImpl(contextRef)->setHTTPPipeliningEnabled(enabled);
}
void WKContextWarmInitialProcess(WKContextRef contextRef)
{
toImpl(contextRef)->warmInitialProcess();
}
void WKContextGetStatistics(WKContextRef contextRef, void* context, WKContextGetStatisticsFunction callback)
{
toImpl(contextRef)->getStatistics(0xFFFFFFFF, toGenericCallbackFunction(context, callback));
}
void WKContextGetStatisticsWithOptions(WKContextRef contextRef, WKStatisticsOptions optionsMask, void* context, WKContextGetStatisticsFunction callback)
{
toImpl(contextRef)->getStatistics(optionsMask, toGenericCallbackFunction(context, callback));
}
void WKContextGarbageCollectJavaScriptObjects(WKContextRef contextRef)
{
toImpl(contextRef)->garbageCollectJavaScriptObjects();
}
void WKContextSetJavaScriptGarbageCollectorTimerEnabled(WKContextRef contextRef, bool enable)
{
toImpl(contextRef)->setJavaScriptGarbageCollectorTimerEnabled(enable);
}
void WKContextUseTestingNetworkSession(WKContextRef context)
{
toImpl(context)->useTestingNetworkSession();
}
void WKContextClearCachedCredentials(WKContextRef context)
{
toImpl(context)->clearCachedCredentials();
}
WKDictionaryRef WKContextCopyPlugInAutoStartOriginHashes(WKContextRef contextRef)
{
return toAPI(toImpl(contextRef)->plugInAutoStartOriginHashes().leakRef());
}
void WKContextSetPlugInAutoStartOriginHashes(WKContextRef contextRef, WKDictionaryRef dictionaryRef)
{
if (!dictionaryRef)
return;
toImpl(contextRef)->setPlugInAutoStartOriginHashes(*toImpl(dictionaryRef));
}
void WKContextSetPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(WKContextRef contextRef, WKDictionaryRef dictionaryRef, double time)
{
if (!dictionaryRef)
return;
toImpl(contextRef)->setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(*toImpl(dictionaryRef), time);
}
void WKContextSetPlugInAutoStartOrigins(WKContextRef contextRef, WKArrayRef arrayRef)
{
if (!arrayRef)
return;
toImpl(contextRef)->setPlugInAutoStartOrigins(*toImpl(arrayRef));
}
void WKContextSetInvalidMessageFunction(WKContextInvalidMessageFunction invalidMessageFunction)
{
WebProcessPool::setInvalidMessageCallback(invalidMessageFunction);
}
void WKContextSetMemoryCacheDisabled(WKContextRef contextRef, bool disabled)
{
toImpl(contextRef)->setMemoryCacheDisabled(disabled);
}
void WKContextSetFontWhitelist(WKContextRef contextRef, WKArrayRef arrayRef)
{
toImpl(contextRef)->setFontWhitelist(toImpl(arrayRef));
}
|
qtproject/qtwebkit
|
Source/WebKit2/UIProcess/API/C/WKContext.cpp
|
C++
|
gpl-2.0
| 21,085 |
// BossComeDlg.cpp : implementation file
//
#include "stdafx.h"
#include "duallistdemo.h"
#include "BossComeDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CBossComeDlg dialog
CBossComeDlg::CBossComeDlg(CWnd* pParent /*=NULL*/)
: CDialog(CBossComeDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CBossComeDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void CBossComeDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CBossComeDlg)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CBossComeDlg, CDialog)
//{{AFX_MSG_MAP(CBossComeDlg)
ON_BN_CLICKED(IDC_SPELL_CHECK, OnSpellCheck)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CBossComeDlg message handlers
BOOL CBossComeDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CString str;
str=" ¹ØÓÚ×öºÃ±¾Ô¹¤×÷µÄһЩ¾ßÌåÏë·¨ \r\n";
str+="Ò»¡¢¼á³Ö×öºÃ±¾Ö°¹¤×÷£¬°ÑÒµÎñºÍ¼¼Êõ·½ÃæµÄе÷ÈÎÎñ½øÒ»²½\r\n×¥ÆðÀ´¡£¹¤×÷Ҫרע¡£\r\n";
str+="¶þ¡¢ÐéÐÄÌýȡͬʵÄÒâ¼û¡£ÕâÒ»µãºÜÖØÒª¡£\r\n";
str+="Èý¡¢ÎÒĿǰ¹¤×÷Çé¿öºÜºÃ£¬µ«ÊÇÒªÕùÈ¡¸üºÃ£¬ÎÞÖ¹¾³µØÌá¸ß×Ô¼ºµÄÄÜÁ¦¡£\r\n";
str+="ËÄ¡¢Ö÷¶¯¡¢»ý¼«¡¢Öƶ¨¼Æ»®¡¢°´Ê±Íê³É¼Æ»®£¬Ã¿Ò»Ìì¶¼ÒªÎÊ×Ô¼º£º\r\nÎÒ¹¤×÷µÃÔõôÑùÁË£¿\r\n";
str+="Îå¡¢Àϰ塢¾Àí·Ç³£ÓÐÄÜÁ¦£¬¶øÇÒ¶ÔÎҺܹØÐĺÜÕչˣ¬ÎÒÒ»¶¨ÒªÈÏ\r\nÕæ¹¤×÷,\r\n";
str+="Áù¡¢Ã¿Ììϰàºó£¬°Ñ×Ô¼ºµÄ°ì¹«×ÀÊÕʰ¸É¾»£¬ÒòΪÕû½àÓÐÖúÓÚÓªÔì\r\n¸ßÐ§ÒæµÄ¹¤×÷Æø·Õ£¬Ò²ÄܸøÈË¿ÕÆøÇåÏãµÄ¸Ð¾õ¡£\r\n";
str+="Æß¡¢Ã¿ÖÜÁù°ëÒ¹£¬Ó¦°ÑÏÂÒ»ÖܸÃ×öµÄÊÂÇ鿼ÂǺ㬲¢ÇÒ×îºÃ°Ñ½ÏÈÝ\r\nÒ×µÄÊ·ÅÔÚÖÜËÄÏÂÎ磬°ë¸öÐÇÆÚ¶¼¸É¾¢Ê®×ã¡£ \r\n";
str+="°Ë¡¢Ëµ»°ºÍ×öʲ»Òª×Ô×öÖ÷ÕÅ£¬ÖØÒªµÄʶ¼Òª¾ÀíºÍÀϰåÖ¸µã£¬ËûÃÇÊÇ\r\n¾ø¶ÔÊÇÕýÈ·µÄ¡£\r\n";
// TODO: Add extra initialization here
m_Word.SubclassDlgItem (IDC_EDIT1, this);
m_Word.SetWindowText (str);
// m_Word.LineScroll (m_Word.GetLineCount(), 0);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CBossComeDlg::OnSpellCheck()
{
// TODO: Add your control notification handler code here
AfxMessageBox("ƴд¼ì²é½¨Ò飺¡°¿ÕÆøÇåÏ㡱¸ÄΪ¡°¿ÕÆøÇåС±\n¡°Àϰ塱¸ÄΪ¡°ÀϰåÄ¡£",MB_ICONINFORMATION );
}
|
chrisguo/beijing_fushengji
|
BossComeDlg.cpp
|
C++
|
gpl-2.0
| 2,460 |
/* packet-json.c
* Routines for JSON dissection
* References:
* RFC 4627: https://tools.ietf.org/html/rfc4627
* Website: http://json.org/
*
* Copyright 2010, Jakub Zawadzki <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#define NEW_PROTO_TREE_API
#include "config.h"
#include <epan/packet.h>
#include <epan/tvbparse.h>
#include <epan/proto_data.h>
#include <wsutil/wsjson.h>
#include <wsutil/str_util.h>
#include <wsutil/unicode-utils.h>
#include <wiretap/wtap.h>
#include "packet-http.h"
#include "packet-acdr.h"
void proto_register_json(void);
void proto_reg_handoff_json(void);
static char *json_string_unescape(tvbparse_elem_t *tok);
static dissector_handle_t json_handle;
static int proto_json = -1;
//Used to get AC DR proto data
static int proto_acdr = -1;
static gint ett_json = -1;
static gint ett_json_array = -1;
static gint ett_json_object = -1;
static gint ett_json_member = -1;
/* Define the trees for json compact form */
static gint ett_json_compact = -1;
static gint ett_json_array_compact = -1;
static gint ett_json_object_compact = -1;
static gint ett_json_member_compact = -1;
static header_field_info *hfi_json = NULL;
#define JSON_HFI_INIT HFI_INIT(proto_json)
static header_field_info hfi_json_array JSON_HFI_INIT =
{ "Array", "json.array", FT_NONE, BASE_NONE, NULL, 0x00, "JSON array", HFILL };
static header_field_info hfi_json_object JSON_HFI_INIT =
{ "Object", "json.object", FT_NONE, BASE_NONE, NULL, 0x00, "JSON object", HFILL };
static header_field_info hfi_json_member JSON_HFI_INIT =
{ "Member", "json.member", FT_NONE, BASE_NONE, NULL, 0x00, "JSON object member", HFILL };
static header_field_info hfi_json_key JSON_HFI_INIT =
{ "Key", "json.key", FT_STRING, STR_UNICODE, NULL, 0x00, NULL, HFILL };
static header_field_info hfi_json_value_string JSON_HFI_INIT = /* FT_STRINGZ? */
{ "String value", "json.value.string", FT_STRING, STR_UNICODE, NULL, 0x00, "JSON string value", HFILL };
static header_field_info hfi_json_value_number JSON_HFI_INIT = /* FT_DOUBLE/ FT_INT64? */
{ "Number value", "json.value.number", FT_STRING, BASE_NONE, NULL, 0x00, "JSON number value", HFILL };
static header_field_info hfi_json_value_false JSON_HFI_INIT =
{ "False value", "json.value.false", FT_NONE, BASE_NONE, NULL, 0x00, "JSON false value", HFILL };
static header_field_info hfi_json_value_null JSON_HFI_INIT =
{ "Null value", "json.value.null", FT_NONE, BASE_NONE, NULL, 0x00, "JSON null value", HFILL };
static header_field_info hfi_json_value_true JSON_HFI_INIT =
{ "True value", "json.value.true", FT_NONE, BASE_NONE, NULL, 0x00, "JSON true value", HFILL };
/* HFIs below are used only for compact form display */
static header_field_info hfi_json_array_compact JSON_HFI_INIT =
{ "Array compact", "json.array_compact", FT_NONE, BASE_NONE, NULL, 0x00, "JSON array compact", HFILL };
static header_field_info hfi_json_object_compact JSON_HFI_INIT =
{ "Object compact", "json.object_compact", FT_NONE, BASE_NONE, NULL, 0x00, "JSON object compact", HFILL };
static header_field_info hfi_json_member_compact JSON_HFI_INIT =
{ "Member compact", "json.member_compact", FT_NONE, BASE_NONE, NULL, 0x00, "JSON member compact", HFILL };
static header_field_info hfi_json_array_item_compact JSON_HFI_INIT =
{ "Array item compact", "json.array_item_compact", FT_NONE, BASE_NONE, NULL, 0x00, "JSON array item compact", HFILL };
/* Preferences */
static gboolean json_compact = FALSE;
static tvbparse_wanted_t* want;
static tvbparse_wanted_t* want_ignore;
static dissector_handle_t text_lines_handle;
typedef enum {
JSON_TOKEN_INVALID = -1,
JSON_TOKEN_NUMBER = 0,
JSON_TOKEN_STRING,
JSON_TOKEN_FALSE,
JSON_TOKEN_NULL,
JSON_TOKEN_TRUE,
/* not really tokens ... */
JSON_OBJECT,
JSON_ARRAY
} json_token_type_t;
typedef struct {
wmem_stack_t *stack;
wmem_stack_t *stack_compact; /* Used for compact json form only */
wmem_stack_t *array_idx; /* Used for compact json form only.
Top item: -3.
Object: < 0.
Array -1: no key, -2: has key */
} json_parser_data_t;
#define JSON_COMPACT_TOP_ITEM -3
#define JSON_COMPACT_OBJECT_WITH_KEY -2
#define JSON_COMPACT_OBJECT_WITHOUT_KEY -1
#define JSON_COMPACT_ARRAY 0
#define JSON_ARRAY_BEGIN(json_tvbparse_data) wmem_stack_push(json_tvbparse_data->array_idx, GINT_TO_POINTER(JSON_COMPACT_ARRAY))
#define JSON_OBJECT_BEGIN(json_tvbparse_data) wmem_stack_push(json_tvbparse_data->array_idx, GINT_TO_POINTER(JSON_COMPACT_OBJECT_WITHOUT_KEY))
#define JSON_ARRAY_OBJECT_END(json_tvbparse_data) wmem_stack_pop(json_tvbparse_data->array_idx)
#define JSON_INSIDE_ARRAY(idx) (idx >= JSON_COMPACT_ARRAY)
#define JSON_OBJECT_SET_HAS_KEY(idx) (idx == JSON_COMPACT_OBJECT_WITH_KEY)
static void
json_array_index_increment(json_parser_data_t *data)
{
gint idx = GPOINTER_TO_INT(wmem_stack_pop(data->array_idx));
idx++;
wmem_stack_push(data->array_idx, GINT_TO_POINTER(idx));
}
static void
json_object_add_key(json_parser_data_t *data)
{
wmem_stack_pop(data->array_idx);
wmem_stack_push(data->array_idx, GINT_TO_POINTER(JSON_COMPACT_OBJECT_WITH_KEY));
}
static int
dissect_json(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data)
{
proto_tree *json_tree = NULL;
proto_item *ti = NULL;
json_parser_data_t parser_data;
tvbparse_t *tt;
http_message_info_t *message_info;
const char *data_name;
int offset;
/* JSON dissector can be called in a JSON native file or when transported
* by another protocol, will make entry in the Protocol column on summary display accordingly
*/
wmem_list_frame_t *proto = wmem_list_frame_prev(wmem_list_tail(pinfo->layers));
if (proto) {
const char *name = proto_get_protocol_filter_name(GPOINTER_TO_INT(wmem_list_frame_data(proto)));
if (strcmp(name, "frame")) {
col_append_sep_str(pinfo->cinfo, COL_PROTOCOL, "/", "JSON");
col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "JavaScript Object Notation");
} else {
col_set_str(pinfo->cinfo, COL_PROTOCOL, "JSON");
col_set_str(pinfo->cinfo, COL_INFO, "JavaScript Object Notation");
}
}
data_name = pinfo->match_string;
if (! (data_name && data_name[0])) {
/*
* No information from "match_string"
*/
message_info = (http_message_info_t *)data;
if (message_info == NULL) {
/*
* No information from dissector data
*/
data_name = NULL;
} else {
data_name = message_info->media_str;
if (! (data_name && data_name[0])) {
/*
* No information from dissector data
*/
data_name = NULL;
}
}
}
if (tree) {
ti = proto_tree_add_item(tree, hfi_json, tvb, 0, -1, ENC_NA);
json_tree = proto_item_add_subtree(ti, ett_json);
if (data_name)
proto_item_append_text(ti, ": %s", data_name);
}
offset = 0;
/* XXX*/
p_add_proto_data(pinfo->pool, pinfo, proto_json, 0, tvb);
parser_data.stack = wmem_stack_new(wmem_packet_scope());
wmem_stack_push(parser_data.stack, json_tree);
if (json_compact) {
proto_tree *json_tree_compact = NULL;
json_tree_compact = proto_tree_add_subtree(json_tree, tvb, 0, -1, ett_json_compact, NULL, "JSON compact form:");
parser_data.stack_compact = wmem_stack_new(wmem_packet_scope());
wmem_stack_push(parser_data.stack_compact, json_tree_compact);
parser_data.array_idx = wmem_stack_new(wmem_packet_scope());
wmem_stack_push(parser_data.array_idx, GINT_TO_POINTER(JSON_COMPACT_TOP_ITEM)); /* top element */
}
tt = tvbparse_init(tvb, offset, -1, &parser_data, want_ignore);
/* XXX, only one json in packet? */
while ((tvbparse_get(tt, want)))
;
offset = tvbparse_curr_offset(tt);
proto_item_set_len(ti, offset);
/* if we have some unparsed data, pass to data-text-lines dissector (?) */
if (tvb_reported_length_remaining(tvb, offset) > 0) {
tvbuff_t *next_tvb;
next_tvb = tvb_new_subset_remaining(tvb, offset);
call_dissector_with_data(text_lines_handle, next_tvb, pinfo, tree, data);
} else if (data_name) {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ", "(%s)", data_name);
}
return tvb_captured_length(tvb);
}
/*
* For dissecting JSON in a file; we don't get passed a media type.
*/
static int
dissect_json_file(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
{
return dissect_json(tvb, pinfo, tree, NULL);
}
static void before_object(void *tvbparse_data, const void *wanted_data _U_, tvbparse_elem_t *tok) {
json_parser_data_t *data = (json_parser_data_t *) tvbparse_data;
proto_tree *tree = (proto_tree *)wmem_stack_peek(data->stack);
proto_tree *subtree;
proto_item *ti;
ti = proto_tree_add_item(tree, &hfi_json_object, tok->tvb, tok->offset, tok->len, ENC_NA);
subtree = proto_item_add_subtree(ti, ett_json_object);
wmem_stack_push(data->stack, subtree);
if (json_compact) {
proto_tree *tree_compact = (proto_tree *)wmem_stack_peek(data->stack_compact);
proto_tree *subtree_compact;
proto_item *ti_compact;
gint idx = GPOINTER_TO_INT(wmem_stack_peek(data->array_idx));
if (JSON_INSIDE_ARRAY(idx)) {
ti_compact = proto_tree_add_none_format(tree_compact, &hfi_json_object_compact, tok->tvb, tok->offset, tok->len, "%d:", idx);
subtree_compact = proto_item_add_subtree(ti_compact, ett_json_object_compact);
json_array_index_increment(data);
} else {
subtree_compact = tree_compact;
}
wmem_stack_push(data->stack_compact, subtree_compact);
JSON_OBJECT_BEGIN(data);
}
}
static void after_object(void *tvbparse_data, const void *wanted_data _U_, tvbparse_elem_t *elem _U_) {
json_parser_data_t *data = (json_parser_data_t *) tvbparse_data;
wmem_stack_pop(data->stack);
if (json_compact) {
proto_tree *tree_compact = (proto_tree *)wmem_stack_peek(data->stack_compact);
proto_item *parent_item = proto_tree_get_parent(tree_compact);
gint idx = GPOINTER_TO_INT(wmem_stack_peek(data->array_idx));
if (JSON_OBJECT_SET_HAS_KEY(idx))
proto_item_append_text(parent_item, " {...}");
else
proto_item_append_text(parent_item, " {}");
wmem_stack_pop(data->stack_compact);
JSON_ARRAY_OBJECT_END(data);
}
}
static void before_member(void *tvbparse_data, const void *wanted_data _U_, tvbparse_elem_t *tok) {
json_parser_data_t *data = (json_parser_data_t *) tvbparse_data;
proto_tree *tree = (proto_tree *)wmem_stack_peek(data->stack);
proto_tree *subtree;
proto_item *ti;
ti = proto_tree_add_item(tree, &hfi_json_member, tok->tvb, tok->offset, tok->len, ENC_NA);
subtree = proto_item_add_subtree(ti, ett_json_member);
wmem_stack_push(data->stack, subtree);
if (json_compact) {
proto_tree *tree_compact = (proto_tree *)wmem_stack_peek(data->stack_compact);
proto_tree *subtree_compact;
proto_item *ti_compact;
tvbparse_elem_t *key_tok = tok->sub;
if (key_tok && key_tok->id == JSON_TOKEN_STRING) {
char *key_str = json_string_unescape(key_tok);
ti_compact = proto_tree_add_none_format(tree_compact, &hfi_json_member_compact, tok->tvb, tok->offset, tok->len, "%s:", key_str);
} else {
ti_compact = proto_tree_add_item(tree_compact, &hfi_json_member_compact, tok->tvb, tok->offset, tok->len, ENC_NA);
}
subtree_compact = proto_item_add_subtree(ti_compact, ett_json_member_compact);
wmem_stack_push(data->stack_compact, subtree_compact);
}
}
static void after_member(void *tvbparse_data, const void *wanted_data _U_, tvbparse_elem_t *tok) {
json_parser_data_t *data = (json_parser_data_t *) tvbparse_data;
proto_tree *tree = (proto_tree *)wmem_stack_pop(data->stack);
if (tree) {
tvbparse_elem_t *key_tok = tok->sub;
if (key_tok && key_tok->id == JSON_TOKEN_STRING) {
char *key = json_string_unescape(key_tok);
proto_tree_add_string(tree, &hfi_json_key, key_tok->tvb, key_tok->offset, key_tok->len, key);
proto_item_append_text(tree, " Key: %s", key);
}
}
if (json_compact) {
wmem_stack_pop(data->stack_compact);
json_object_add_key(data);
}
}
static void before_array(void *tvbparse_data, const void *wanted_data _U_, tvbparse_elem_t *tok) {
json_parser_data_t *data = (json_parser_data_t *) tvbparse_data;
proto_tree *tree = (proto_tree *)wmem_stack_peek(data->stack);
proto_tree *subtree;
proto_item *ti;
ti = proto_tree_add_item(tree, &hfi_json_array, tok->tvb, tok->offset, tok->len, ENC_NA);
subtree = proto_item_add_subtree(ti, ett_json_array);
wmem_stack_push(data->stack, subtree);
if (json_compact) {
JSON_ARRAY_BEGIN(data);
}
}
static void after_array(void *tvbparse_data, const void *wanted_data _U_, tvbparse_elem_t *elem _U_) {
json_parser_data_t *data = (json_parser_data_t *) tvbparse_data;
wmem_stack_pop(data->stack);
if (json_compact) {
proto_tree *tree_compact = (proto_tree *)wmem_stack_peek(data->stack_compact);
proto_item *parent_item = proto_tree_get_parent(tree_compact);
gint idx = GPOINTER_TO_INT(wmem_stack_peek(data->array_idx));
if (idx == 0)
proto_item_append_text(parent_item, " []");
else
proto_item_append_text(parent_item, " [...]");
JSON_ARRAY_OBJECT_END(data);
}
}
static int
json_tvb_memcpy_utf8(char *buf, tvbuff_t *tvb, int offset, int offset_max)
{
int len = ws_utf8_char_len((guint8) *buf);
/* XXX, before moving to core API check if it's off-by-one safe.
* For JSON analyzer it's not a problem
* (string always terminated by ", which is not valid UTF-8 continuation character) */
if (len == -1 || ((guint) (offset + len)) >= (guint) offset_max) {
*buf = '?';
return 1;
}
/* assume it's valid UTF-8 */
tvb_memcpy(tvb, buf + 1, offset + 1, len - 1);
if (!g_utf8_validate(buf, len, NULL)) {
*buf = '?';
return 1;
}
return len;
}
static char *json_string_unescape(tvbparse_elem_t *tok)
{
char *str = (char *)wmem_alloc(wmem_packet_scope(), tok->len - 1);
int i, j;
j = 0;
for (i = 1; i < tok->len - 1; i++) {
guint8 ch = tvb_get_guint8(tok->tvb, tok->offset + i);
int bin;
if (ch == '\\') {
i++;
ch = tvb_get_guint8(tok->tvb, tok->offset + i);
switch (ch) {
case '\"':
case '\\':
case '/':
str[j++] = ch;
break;
case 'b':
str[j++] = '\b';
break;
case 'f':
str[j++] = '\f';
break;
case 'n':
str[j++] = '\n';
break;
case 'r':
str[j++] = '\r';
break;
case 't':
str[j++] = '\t';
break;
case 'u':
{
guint32 unicode_hex = 0;
gboolean valid = TRUE;
int k;
for (k = 0; k < 4; k++) {
i++;
unicode_hex <<= 4;
ch = tvb_get_guint8(tok->tvb, tok->offset + i);
bin = ws_xton(ch);
if (bin == -1) {
valid = FALSE;
break;
}
unicode_hex |= bin;
}
if ((IS_LEAD_SURROGATE(unicode_hex))) {
ch = tvb_get_guint8(tok->tvb, tok->offset + i + 1);
if (ch == '\\') {
i++;
ch = tvb_get_guint8(tok->tvb, tok->offset + i + 1);
if (ch == 'u') {
guint16 lead_surrogate = unicode_hex;
guint16 trail_surrogate = 0;
i++;
for (k = 0; k < 4; k++) {
i++;
trail_surrogate <<= 4;
ch = tvb_get_guint8(tok->tvb, tok->offset + i);
bin = ws_xton(ch);
if (bin == -1) {
valid = FALSE;
break;
}
trail_surrogate |= bin;
}
if ((IS_TRAIL_SURROGATE(trail_surrogate))) {
unicode_hex = SURROGATE_VALUE(lead_surrogate,trail_surrogate);
} else {
valid = FALSE;
}
} else {
valid = FALSE;
}
} else {
valid = FALSE;
}
} else if ((IS_TRAIL_SURROGATE(unicode_hex))) {
i++;
valid = FALSE;
}
if (valid && g_unichar_validate(unicode_hex) && g_unichar_isprint(unicode_hex)) {
/* \uXXXX => 6 bytes */
int charlen = g_unichar_to_utf8(unicode_hex, &str[j]);
j += charlen;
} else
str[j++] = '?';
break;
}
default:
/* not valid by JSON grammar (also tvbparse rules should not allow it) */
DISSECTOR_ASSERT_NOT_REACHED();
break;
}
} else {
int utf_len;
str[j] = ch;
/* XXX if it's not valid UTF-8 character, add some expert info? (it violates JSON grammar) */
utf_len = json_tvb_memcpy_utf8(&str[j], tok->tvb, tok->offset + i, tok->offset + tok->len);
j += utf_len;
i += (utf_len - 1);
}
}
str[j] = '\0';
return str;
}
static void after_value(void *tvbparse_data, const void *wanted_data _U_, tvbparse_elem_t *tok) {
json_parser_data_t *data = (json_parser_data_t *) tvbparse_data;
proto_tree *tree = (proto_tree *)wmem_stack_peek(data->stack);
json_token_type_t value_id = JSON_TOKEN_INVALID;
if (tok->sub)
value_id = (json_token_type_t)tok->sub->id;
switch (value_id) {
case JSON_TOKEN_STRING:
if (tok->len >= 2)
proto_tree_add_string(tree, &hfi_json_value_string, tok->tvb, tok->offset, tok->len, json_string_unescape(tok));
else
proto_tree_add_item(tree, &hfi_json_value_string, tok->tvb, tok->offset, tok->len, ENC_ASCII|ENC_NA);
break;
case JSON_TOKEN_NUMBER:
/* XXX, convert to number */
proto_tree_add_item(tree, &hfi_json_value_number, tok->tvb, tok->offset, tok->len, ENC_ASCII|ENC_NA);
break;
case JSON_TOKEN_FALSE:
proto_tree_add_item(tree, &hfi_json_value_false, tok->tvb, tok->offset, tok->len, ENC_NA);
break;
case JSON_TOKEN_NULL:
proto_tree_add_item(tree, &hfi_json_value_null, tok->tvb, tok->offset, tok->len, ENC_NA);
break;
case JSON_TOKEN_TRUE:
proto_tree_add_item(tree, &hfi_json_value_true, tok->tvb, tok->offset, tok->len, ENC_NA);
break;
case JSON_OBJECT:
case JSON_ARRAY:
/* already added */
break;
default:
proto_tree_add_format_text(tree, tok->tvb, tok->offset, tok->len);
break;
}
if (json_compact) {
proto_tree *tree_compact = (proto_tree *)wmem_stack_peek(data->stack_compact);
gint idx = GPOINTER_TO_INT(wmem_stack_peek(data->array_idx));
char *val_str = tvb_get_string_enc(wmem_packet_scope(), tok->tvb, tok->offset, tok->len, ENC_UTF_8);
if (value_id == JSON_OBJECT || value_id == JSON_ARRAY) {
return;
}
if (JSON_INSIDE_ARRAY(idx)) {
proto_tree_add_none_format(tree_compact, &hfi_json_array_item_compact, tok->tvb, tok->offset, tok->len, "%d: %s", idx, val_str);
json_array_index_increment(data);
} else {
proto_item *parent_item = proto_tree_get_parent(tree_compact);
proto_item_append_text(parent_item, " %s", val_str);
}
}
}
static void init_json_parser(void) {
static tvbparse_wanted_t _want_object;
static tvbparse_wanted_t _want_array;
tvbparse_wanted_t *want_object, *want_array;
tvbparse_wanted_t *want_member;
tvbparse_wanted_t *want_string;
tvbparse_wanted_t *want_number, *want_int;
tvbparse_wanted_t *want_value;
tvbparse_wanted_t *want_value_separator;
#define tvbparse_optional(id, private_data, before_cb, after_cb, wanted) \
tvbparse_some(id, 0, 1, private_data, before_cb, after_cb, wanted)
tvbparse_wanted_t *want_quot = tvbparse_char(-1,"\"",NULL,NULL,NULL);
want_string = tvbparse_set_seq(JSON_TOKEN_STRING, NULL, NULL, NULL,
want_quot,
tvbparse_some(-1, 0, G_MAXINT, NULL, NULL, NULL,
tvbparse_set_oneof(-1, NULL, NULL, NULL,
tvbparse_not_chars(-1, 0, 0, "\"" "\\", NULL, NULL, NULL), /* XXX, without invalid unicode characters */
tvbparse_set_seq(-1, NULL, NULL, NULL,
tvbparse_char(-1, "\\", NULL, NULL, NULL),
tvbparse_set_oneof(-1, NULL, NULL, NULL,
tvbparse_chars(-1, 0, 1, "\"" "\\" "/bfnrt", NULL, NULL, NULL),
tvbparse_set_seq(-1, NULL, NULL, NULL,
tvbparse_char(-1, "u", NULL, NULL, NULL),
tvbparse_chars(-1, 4, 4, "0123456789abcdefABCDEF", NULL, NULL, NULL),
NULL),
NULL),
NULL),
NULL)
),
want_quot,
NULL);
want_value_separator = tvbparse_char(-1, ",", NULL, NULL, NULL);
/* int = zero / ( digit1-9 *DIGIT ) */
want_int = tvbparse_set_oneof(-1, NULL, NULL, NULL,
tvbparse_char(-1, "0", NULL, NULL, NULL),
tvbparse_set_seq(-1, NULL, NULL, NULL,
tvbparse_chars(-1, 1, 1, "123456789", NULL, NULL, NULL),
tvbparse_optional(-1, NULL, NULL, NULL, /* tvbparse_chars() don't respect 0 as min_len ;/ */
tvbparse_chars(-1, 0, 0, "0123456789", NULL, NULL, NULL)),
NULL),
NULL);
/* number = [ minus ] int [ frac ] [ exp ] */
want_number = tvbparse_set_seq(JSON_TOKEN_NUMBER, NULL, NULL, NULL,
tvbparse_optional(-1, NULL, NULL, NULL, /* tvbparse_chars() don't respect 0 as min_len ;/ */
tvbparse_chars(-1, 0, 1, "-", NULL, NULL, NULL)),
want_int,
/* frac = decimal-point 1*DIGIT */
tvbparse_optional(-1, NULL, NULL, NULL,
tvbparse_set_seq(-1, NULL, NULL, NULL,
tvbparse_char(-1, ".", NULL, NULL, NULL),
tvbparse_chars(-1, 1, 0, "0123456789", NULL, NULL, NULL),
NULL)),
/* exp = e [ minus / plus ] 1*DIGIT */
tvbparse_optional(-1, NULL, NULL, NULL,
tvbparse_set_seq(-1, NULL, NULL, NULL,
tvbparse_char(-1, "eE", NULL, NULL, NULL),
tvbparse_optional(-1, NULL, NULL, NULL, /* tvbparse_chars() don't respect 0 as min_len ;/ */
tvbparse_chars(-1, 0, 1, "-+", NULL, NULL, NULL)),
tvbparse_chars(-1, 1, 0, "0123456789", NULL, NULL, NULL),
NULL)),
NULL);
/* value = false / null / true / object / array / number / string */
want_value = tvbparse_set_oneof(-1, NULL, NULL, after_value,
tvbparse_string(JSON_TOKEN_FALSE, "false", NULL, NULL, NULL),
tvbparse_string(JSON_TOKEN_NULL, "null", NULL, NULL, NULL),
tvbparse_string(JSON_TOKEN_TRUE, "true", NULL, NULL, NULL),
&_want_object,
&_want_array,
want_number,
want_string,
NULL);
/* array = begin-array [ value *( value-separator value ) ] end-array */
want_array = tvbparse_set_seq(JSON_ARRAY, NULL, before_array, after_array,
tvbparse_char(-1, "[", NULL, NULL, NULL),
tvbparse_optional(-1, NULL, NULL, NULL,
tvbparse_set_seq(-1, NULL, NULL, NULL,
want_value,
tvbparse_some(-1, 0, G_MAXINT, NULL, NULL, NULL,
tvbparse_set_seq(-1, NULL, NULL, NULL,
want_value_separator,
want_value,
NULL)),
NULL)
),
tvbparse_char(-1, "]", NULL, NULL, NULL),
NULL);
_want_array = *want_array;
/* member = string name-separator value */
want_member = tvbparse_set_seq(-1, NULL, before_member, after_member,
want_string,
tvbparse_char(-1, ":", NULL, NULL, NULL),
want_value,
NULL);
/* object = begin-object [ member *( value-separator member ) ] end-object */
want_object = tvbparse_set_seq(JSON_OBJECT, NULL, before_object, after_object,
tvbparse_char(-1, "{", NULL, NULL, NULL),
tvbparse_optional(-1, NULL, NULL, NULL,
tvbparse_set_seq(-1, NULL, NULL, NULL,
want_member,
tvbparse_some(-1, 0, G_MAXINT, NULL, NULL, NULL,
tvbparse_set_seq(-1, NULL, NULL, NULL,
want_value_separator,
want_member,
NULL)),
NULL)
),
tvbparse_char(-1, "}", NULL, NULL, NULL),
NULL);
_want_object = *want_object;
want_ignore = tvbparse_chars(-1, 1, 0, " \t\r\n", NULL, NULL, NULL);
/* JSON-text = object / array */
want = tvbparse_set_oneof(-1, NULL, NULL, NULL,
want_object,
want_array,
/* tvbparse_not_chars(-1, 1, 0, " \t\r\n", NULL, NULL, NULL), */
NULL);
/* XXX, heur? */
}
/* This function tries to understand if the payload is json or not */
static gboolean
dissect_json_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
guint len = tvb_captured_length(tvb);
const guint8* buf = tvb_get_string_enc(wmem_packet_scope(), tvb, 0, len, ENC_ASCII);
if (json_validate(buf, len) == FALSE)
return FALSE;
return (dissect_json(tvb, pinfo, tree, data) != 0);
}
/* This function tries to understand if the payload is sitting on top of AC DR */
static gboolean
dissect_json_acdr_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
guint acdr_prot = GPOINTER_TO_UINT(p_get_proto_data(pinfo->pool, pinfo, proto_acdr, 0));
if (acdr_prot == ACDR_VoiceAI)
return dissect_json_heur(tvb, pinfo, tree, data);
return FALSE;
}
void
proto_register_json(void)
{
static gint *ett[] = {
&ett_json,
&ett_json_array,
&ett_json_object,
&ett_json_member,
&ett_json_compact,
&ett_json_array_compact,
&ett_json_object_compact,
&ett_json_member_compact
};
#ifndef HAVE_HFI_SECTION_INIT
static header_field_info *hfi[] = {
&hfi_json_array,
&hfi_json_object,
&hfi_json_member,
&hfi_json_key,
&hfi_json_value_string,
&hfi_json_value_number,
&hfi_json_value_false,
&hfi_json_value_null,
&hfi_json_value_true,
&hfi_json_array_compact,
&hfi_json_object_compact,
&hfi_json_member_compact,
&hfi_json_array_item_compact,
};
#endif
module_t *json_module;
proto_json = proto_register_protocol("JavaScript Object Notation", "JSON", "json");
hfi_json = proto_registrar_get_nth(proto_json);
proto_register_fields(proto_json, hfi, array_length(hfi));
proto_register_subtree_array(ett, array_length(ett));
json_handle = register_dissector("json", dissect_json, proto_json);
init_json_parser();
json_module = prefs_register_protocol(proto_json, NULL);
prefs_register_bool_preference(json_module, "compact_form",
"Display JSON in compact form",
"Display JSON like in browsers devtool",
&json_compact);
}
void
proto_reg_handoff_json(void)
{
dissector_handle_t json_file_handle = create_dissector_handle(dissect_json_file, proto_json);
heur_dissector_add("hpfeeds", dissect_json_heur, "JSON over HPFEEDS", "json_hpfeeds", proto_json, HEURISTIC_ENABLE);
heur_dissector_add("db-lsp", dissect_json_heur, "JSON over DB-LSP", "json_db_lsp", proto_json, HEURISTIC_ENABLE);
heur_dissector_add("udp", dissect_json_acdr_heur, "JSON over AC DR", "json_acdr", proto_json, HEURISTIC_ENABLE);
dissector_add_uint("wtap_encap", WTAP_ENCAP_JSON, json_file_handle);
dissector_add_for_decode_as("udp.port", json_file_handle);
dissector_add_string("media_type", "application/json", json_handle); /* RFC 4627 */
dissector_add_string("media_type", "application/json-rpc", json_handle); /* JSON-RPC over HTTP */
dissector_add_string("media_type", "application/jsonrequest", json_handle); /* JSON-RPC over HTTP */
dissector_add_string("media_type", "application/dds-web+json", json_handle); /* DDS Web Integration Service over HTTP */
dissector_add_string("media_type", "application/vnd.oma.lwm2m+json", json_handle); /* LWM2M JSON over CoAP */
dissector_add_string("media_type", "application/problem+json", json_handle); /* RFC 7807 Problem Details for HTTP APIs*/
dissector_add_string("media_type", "application/merge-patch+json", json_handle); /* RFC 7386 HTTP PATCH methods (RFC 5789) */
dissector_add_string("grpc_message_type", "application/grpc+json", json_handle);
dissector_add_uint_range_with_preference("tcp.port", "", json_file_handle); /* JSON-RPC over TCP */
dissector_add_uint_range_with_preference("udp.port", "", json_file_handle); /* JSON-RPC over UDP */
text_lines_handle = find_dissector_add_dependency("data-text-lines", proto_json);
proto_acdr = proto_get_id_by_filter_name("acdr");
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
|
zzqcn/wireshark
|
epan/dissectors/packet-json.c
|
C
|
gpl-2.0
| 27,265 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<title>Mensagem da loja {shop_name}</title>
<style> @media only screen and (max-width: 300px){
body {
width:218px !important;
margin:auto !important;
}
.table {width:195px !important;margin:auto !important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto !important;display: block !important;}
span.title{font-size:20px !important;line-height: 23px !important}
span.subtitle{font-size: 14px !important;line-height: 18px !important;padding-top:10px !important;display:block !important;}
td.box p{font-size: 12px !important;font-weight: bold !important;}
.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr {
display: block !important;
}
.table-recap{width: 200px!important;}
.table-recap tr td, .conf_body td{text-align:center !important;}
.address{display: block !important;margin-bottom: 10px !important;}
.space_address{display: none !important;}
}
@media only screen and (min-width: 301px) and (max-width: 500px) {
body {width:308px!important;margin:auto!important;}
.table {width:285px!important;margin:auto!important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr {
display: block !important;
}
.table-recap{width: 295px !important;}
.table-recap tr td, .conf_body td{text-align:center !important;}
}
@media only screen and (min-width: 501px) and (max-width: 768px) {
body {width:478px!important;margin:auto!important;}
.table {width:450px!important;margin:auto!important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
}
@media only screen and (max-device-width: 480px) {
body {width:308px!important;margin:auto!important;}
.table {width:285px;margin:auto!important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
.table-recap{width: 295px!important;}
.table-recap tr td, .conf_body td{text-align:center!important;}
.address{display: block !important;margin-bottom: 10px !important;}
.space_address{display: none !important;}
}
</style>
</head>
<body style="-webkit-text-size-adjust:none;background-color:#fff;width:650px;font-family:Open-sans, sans-serif;color:#555454;font-size:13px;line-height:18px;margin:auto">
<table class="table table-mail" style="width:100%;margin-top:10px;-moz-box-shadow:0 0 5px #afafaf;-webkit-box-shadow:0 0 5px #afafaf;-o-box-shadow:0 0 5px #afafaf;box-shadow:0 0 5px #afafaf;filter:progid:DXImageTransform.Microsoft.Shadow(color=#afafaf,Direction=134,Strength=5)">
<tr>
<td class="space" style="width:20px;padding:7px 0"> </td>
<td align="center" style="padding:7px 0">
<table class="table" bgcolor="#ffffff" style="width:100%">
<tr>
<td align="center" class="logo" style="border-bottom:4px solid #333333;padding:7px 0">
<a title="{shop_name}" href="{shop_url}" style="color:#337ff1">
<img src="{shop_logo}" alt="{shop_name}" />
</a>
</td>
</tr>
<tr>
<td align="center" class="titleblock" style="padding:7px 0">
<font size="2" face="Open-sans, sans-serif" color="#555454">
<span class="title" style="font-weight:500;font-size:28px;text-transform:uppercase;line-height:33px">Olá {firstname} {lastname},</span><br/>
<span class="subtitle" style="font-weight:500;font-size:16px;text-transform:uppercase;line-height:25px">Muito obrigado por comprar na {shop_name}!</span>
</font>
</td>
</tr>
<tr>
<td class="space_footer" style="padding:0!important"> </td>
</tr>
<tr>
<td class="box" style="border:1px solid #D6D4D4;background-color:#f8f8f8;padding:7px 0">
<table class="table" style="width:100%">
<tr>
<td width="10" style="padding:7px 0"> </td>
<td style="padding:7px 0">
<font size="2" face="Open-sans, sans-serif" color="#555454">
<p data-html-only="1" style="border-bottom:1px solid #D6D4D4;margin:3px 0 7px;text-transform:uppercase;font-weight:500;font-size:18px;padding-bottom:10px">
Seu pedido {order_name} - Aguardando confirmação de pagamento </p>
<span style="color:#777">
Seu pedido com a referência <span style="color:#333"><strong>{order_name}</strong></span> foi concluído com sucesso e será <strong> enviado assim que recebermos o seu pagamento </strong>. </span>
</font>
</td>
<td width="10" style="padding:7px 0"> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td class="space_footer" style="padding:0!important"> </td>
</tr>
<tr>
<td class="box" style="border:1px solid #D6D4D4;background-color:#f8f8f8;padding:7px 0">
<table class="table" style="width:100%">
<tr>
<td width="10" style="padding:7px 0"> </td>
<td style="padding:7px 0">
<font size="2" face="Open-sans, sans-serif" color="#555454">
<p style="border-bottom:1px solid #D6D4D4;margin:3px 0 7px;text-transform:uppercase;font-weight:500;font-size:18px;padding-bottom:10px">
Você selecionou o pagamento por cheque. </p>
<span style="color:#777">
Por favor incluia esses dados no cheque:<br />
<span style="color:#333"><strong>Total:</strong></span> {total_paid}<br />
<span style="color:#333"><strong>Pagamento do pedido:</strong></span> {cheque_name}<br />
<span style="color:#333"><strong>Por favor enviei um email para:</strong></span> {cheque_address_html}
</span>
</font>
</td>
<td width="10" style="padding:7px 0"> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td class="space_footer" style="padding:0!important"> </td>
</tr>
<tr>
<td class="linkbelow" style="padding:7px 0">
<font size="2" face="Open-sans, sans-serif" color="#555454">
<span>
Você pode revisar seu pedido e baixar sua fatura na seção <a href="{history_url}" style="color:#337ff1">"Meus Pedidos"</a> na sua conta, clicando em <a href="{my_account_url}" style="color:#337ff1">"Minha Conta"</a> na nossa loja. </span>
</font>
</td>
</tr>
<tr>
<td class="linkbelow" style="padding:7px 0">
<font size="2" face="Open-sans, sans-serif" color="#555454">
<span>
Se você tem uma conta de convidado, você pode acompanhar seu pedido através do link <a href="guest_tracking_url}" style="color:#337ff1"></a> em nossa loja na seção "Rastreamento de convidado". </span>
</font>
</td>
</tr>
<tr>
<td class="space_footer" style="padding:0!important"> </td>
</tr>
<tr>
<td class="footer" style="border-top:4px solid #333333;padding:7px 0">
<span><a href="{shop_url}" style="color:#337ff1">{shop_name}</a> baseado em <a href="http://www.prestashop.com/" style="color:#337ff1">PrestaShop™</a></span>
</td>
</tr>
</table>
</td>
<td class="space" style="width:20px;padding:7px 0"> </td>
</tr>
</table>
</body>
</html>
|
fernandaos12/ateliebambolina
|
mails/br/cheque.html
|
HTML
|
gpl-2.0
| 7,495 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_22) on Tue May 29 00:12:37 CEST 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
LegacyNavigator (leJOS NXJ PC-API documentation)
</TITLE>
<META NAME="keywords" CONTENT="lejos.robotics.navigation.LegacyNavigator class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="LegacyNavigator (leJOS NXJ PC-API documentation)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../lejos/robotics/navigation/DifferentialPilot.html" title="class in lejos.robotics.navigation"><B>PREV CLASS</B></A>
<A HREF="../../../lejos/robotics/navigation/LegacyPilot.html" title="class in lejos.robotics.navigation"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?lejos/robotics/navigation/LegacyNavigator.html" target="_top"><B>FRAMES</B></A>
<A HREF="LegacyNavigator.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
lejos.robotics.navigation</FONT>
<BR>
Class LegacyNavigator</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>lejos.robotics.navigation.LegacyNavigator</B>
</PRE>
<HR>
<B>Deprecated.</B> <I>This class will disappear in NXJ version 1.0. Use a PathController instead.</I>
<P>
<DL>
<DT><PRE><FONT SIZE="-1">@Deprecated
</FONT>public class <B>LegacyNavigator</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
The LegacyNavigator class is a renamed version of SimpleNavigator in the 0.85 release.
It uses dead reckoning to keep track of its robot pose (the location in the plane
and its heading - the direction in which it moves). While dead reckoning is relatively
easy to implement and very quick to calculate, its disadvantage
is that errors in the estimated pose accumulate.<br>
LegacyNavigator can perform three elementary movements in a plane: travel in a straight line,
move in the arc of a circle, and a rotate in place. The movement commands
have an immediate return option which is useful, for example, for a client
class that uses s LegacyNavigataor to detect obstacles or monitor incoming messages while moving.
<br>
This class uses a private Pilot object to execute these moves. The Pilot directly
controls the hardware, which must be able to turn in place,
for example using 2 wheel differential steering. The Pilot is passed to the Navigator
a the parameter of its constructor. After the Navigator is constructed,
the client has no further need for the Pilot, but issues commands to the Navigator.
If the client bypasses the navigator and issues commands directly to the Pilot, this will destroy
the accuracy of the Navigataor's pose.<br>
<b>A note about coordinates:</b> All angles are in degrees, distances in the units used to specify robot dimensions.
Angles related to positions in the plane are relative to the X axis ; direction of the Y axis is 90 degrees.
The x and y coordinate values and the direction angle are all initialized to 0, so if the first move is forward() the robot will run along
the x axis.<br>
<P>
<P>
<DL>
<DT><B>See Also:</B><DD><CODE>lejos.robotics.navigation.PathController</CODE></DL>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#LegacyNavigator(float, float, lejos.robotics.RegulatedMotor, lejos.robotics.RegulatedMotor)">LegacyNavigator</A></B>(float wheelDiameter,
float trackWidth,
<A HREF="../../../lejos/robotics/RegulatedMotor.html" title="interface in lejos.robotics">RegulatedMotor</A> leftMotor,
<A HREF="../../../lejos/robotics/RegulatedMotor.html" title="interface in lejos.robotics">RegulatedMotor</A> rightMotor)</CODE>
<BR>
<B>Deprecated.</B> <I>The correct way is to create the Pilot in advance and to use that in construction of the
LegacyNavigator. Otherwise the LegacyNavigator needs to know detail it should not care about!</I></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#LegacyNavigator(float, float, lejos.robotics.RegulatedMotor, lejos.robotics.RegulatedMotor, boolean)">LegacyNavigator</A></B>(float wheelDiameter,
float trackWidth,
<A HREF="../../../lejos/robotics/RegulatedMotor.html" title="interface in lejos.robotics">RegulatedMotor</A> leftMotor,
<A HREF="../../../lejos/robotics/RegulatedMotor.html" title="interface in lejos.robotics">RegulatedMotor</A> rightMotor,
boolean reverse)</CODE>
<BR>
<B>Deprecated.</B> <I>The correct way is to create the Pilot in advance and to use that in construction of the
LegacyNavigator. Otherwise the LegacyNavigator needs to know detail it should not care about!</I></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#LegacyNavigator(lejos.robotics.navigation.LegacyPilot)">LegacyNavigator</A></B>(<A HREF="../../../lejos/robotics/navigation/LegacyPilot.html" title="class in lejos.robotics.navigation">LegacyPilot</A> pilot)</CODE>
<BR>
<B>Deprecated.</B> Allocates a LegacyNavigator with a Pilot that you supply.</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> float</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#angleTo(float, float)">angleTo</A></B>(float x,
float y)</CODE>
<BR>
<B>Deprecated.</B> Returns the direction angle from robot current location to the point with coordinates x,y</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#arc(float)">arc</A></B>(float radius)</CODE>
<BR>
<B>Deprecated.</B> Starts the NXT robot moving in a circular path with a specified radius; <br>
The center of the turning circle is on the left side of the robot if parameter radius is positive
and on the right if negative.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#arc(float, int)">arc</A></B>(float radius,
int angle)</CODE>
<BR>
<B>Deprecated.</B> Moves the NXT robot in a circular arc through the specified angle; <br>
The center of the turning circle is on the left side of the robot if parameter radius is positive
and on the right if negative.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#arc(float, int, boolean)">arc</A></B>(float radius,
int angle,
boolean immediateReturn)</CODE>
<BR>
<B>Deprecated.</B> Moves the NXT robot in a circular arc through a specific angle; <br>
The center of the turning circle is on the left side of the robot if parameter radius is positive
and on the right if negative.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#backward()">backward</A></B>()</CODE>
<BR>
<B>Deprecated.</B> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> float</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#distanceTo(float, float)">distanceTo</A></B>(float x,
float y)</CODE>
<BR>
<B>Deprecated.</B> Returns the distance from robot current location to the point with coordinates x,y</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#forward()">forward</A></B>()</CODE>
<BR>
<B>Deprecated.</B> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> float</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#getAngle()">getAngle</A></B>()</CODE>
<BR>
<B>Deprecated.</B> gets the current robot pose</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> float</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#getHeading()">getHeading</A></B>()</CODE>
<BR>
<B>Deprecated.</B> gets the current value of the robot heading</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../lejos/robotics/navigation/Pose.html" title="class in lejos.robotics.navigation">Pose</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#getPose()">getPose</A></B>()</CODE>
<BR>
<B>Deprecated.</B> Returns a new updated Pose</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> float</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#getX()">getX</A></B>()</CODE>
<BR>
<B>Deprecated.</B> gets the current value of the X coordinate</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> float</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#getY()">getY</A></B>()</CODE>
<BR>
<B>Deprecated.</B> gets the current value of the Y coordinate</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#goTo(float, float)">goTo</A></B>(float x,
float y)</CODE>
<BR>
<B>Deprecated.</B> Robot moves to grid coordinates x,y.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#goTo(float, float, boolean)">goTo</A></B>(float x,
float y,
boolean immediateReturn)</CODE>
<BR>
<B>Deprecated.</B> Robot moves to grid coordinates x,y.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#isMoving()">isMoving</A></B>()</CODE>
<BR>
<B>Deprecated.</B> returns true if the robot is moving</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#rotate(float)">rotate</A></B>(float angle)</CODE>
<BR>
<B>Deprecated.</B> Rotates the NXT robot through a specific number of degrees in a direction (+ or -).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#rotate(float, boolean)">rotate</A></B>(float angle,
boolean immediateReturn)</CODE>
<BR>
<B>Deprecated.</B> Rotates the NXT robot through a specific number of degrees in a direction (+ or -).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#rotateLeft()">rotateLeft</A></B>()</CODE>
<BR>
<B>Deprecated.</B> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#rotateRight()">rotateRight</A></B>()</CODE>
<BR>
<B>Deprecated.</B> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#rotateTo(float)">rotateTo</A></B>(float angle)</CODE>
<BR>
<B>Deprecated.</B> Rotates the NXT robot to point in a specific direction, using the smallest
rotation necessary</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#rotateTo(float, boolean)">rotateTo</A></B>(float angle,
boolean immediateReturn)</CODE>
<BR>
<B>Deprecated.</B> Rotates the NXT robot to point in a specific direction relative to the x axis.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#setMoveSpeed(float)">setMoveSpeed</A></B>(float speed)</CODE>
<BR>
<B>Deprecated.</B> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#setPose(float, float, float)">setPose</A></B>(float x,
float y,
float heading)</CODE>
<BR>
<B>Deprecated.</B> sets the robot pose to the new coordinates and heading</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#setPose(lejos.robotics.navigation.Pose)">setPose</A></B>(<A HREF="../../../lejos/robotics/navigation/Pose.html" title="class in lejos.robotics.navigation">Pose</A> pose)</CODE>
<BR>
<B>Deprecated.</B> sets the robot pose</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#setPosition(float, float, float)">setPosition</A></B>(float x,
float y,
float heading)</CODE>
<BR>
<B>Deprecated.</B> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#setRotateSpeed(float)">setRotateSpeed</A></B>(float speed)</CODE>
<BR>
<B>Deprecated.</B> sets the robot turn speed -degrees/second</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#setTravelSpeed(float)">setTravelSpeed</A></B>(float speed)</CODE>
<BR>
<B>Deprecated.</B> sets the robots movement speed - distance units/second</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#setTurnSpeed(float)">setTurnSpeed</A></B>(float speed)</CODE>
<BR>
<B>Deprecated.</B> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#steer(int)">steer</A></B>(int turnRate)</CODE>
<BR>
<B>Deprecated.</B> Starts the robot moving along a curved path.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#steer(int, int)">steer</A></B>(int turnRate,
int angle)</CODE>
<BR>
<B>Deprecated.</B> Moves the robot along a curved path through a specified turn angle.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#steer(int, int, boolean)">steer</A></B>(int turnRate,
int angle,
boolean immediateReturn)</CODE>
<BR>
<B>Deprecated.</B> Moves the robot along a curved path for a specified angle of rotation.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#stop()">stop</A></B>()</CODE>
<BR>
<B>Deprecated.</B> Stops the robot.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#travel(float)">travel</A></B>(float distance)</CODE>
<BR>
<B>Deprecated.</B> Moves the NXT robot a specific distance.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#travel(float, boolean)">travel</A></B>(float distance,
boolean immediateReturn)</CODE>
<BR>
<B>Deprecated.</B> Moves the NXT robot a specific distance.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#travelArc(float, float)">travelArc</A></B>(float radius,
float distance)</CODE>
<BR>
<B>Deprecated.</B> Moves the NXT robot in a circular arc through a specific distance; <br>
The center of the turning circle is on the left side of the robot if parameter radius is positive
and on the right if negative.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#travelArc(float, float, boolean)">travelArc</A></B>(float radius,
float distance,
boolean immediateReturn)</CODE>
<BR>
<B>Deprecated.</B> Moves the NXT robot in a circular arc through a specific distance; <br>
The center of the turning circle is on the left side of the robot if parameter radius is positive
and on the right if negative.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#updatePose()">updatePose</A></B>()</CODE>
<BR>
<B>Deprecated.</B> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#updatePosition()">updatePosition</A></B>()</CODE>
<BR>
<B>Deprecated.</B> </TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="LegacyNavigator(lejos.robotics.navigation.LegacyPilot)"><!-- --></A><H3>
LegacyNavigator</H3>
<PRE>
public <B>LegacyNavigator</B>(<A HREF="../../../lejos/robotics/navigation/LegacyPilot.html" title="class in lejos.robotics.navigation">LegacyPilot</A> pilot)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Allocates a LegacyNavigator with a Pilot that you supply.
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>pilot</CODE> - can be any class that implements the pilot interface</DL>
</DL>
<HR>
<A NAME="LegacyNavigator(float, float, lejos.robotics.RegulatedMotor, lejos.robotics.RegulatedMotor, boolean)"><!-- --></A><H3>
LegacyNavigator</H3>
<PRE>
<FONT SIZE="-1">@Deprecated
</FONT>public <B>LegacyNavigator</B>(float wheelDiameter,
float trackWidth,
<A HREF="../../../lejos/robotics/RegulatedMotor.html" title="interface in lejos.robotics">RegulatedMotor</A> leftMotor,
<A HREF="../../../lejos/robotics/RegulatedMotor.html" title="interface in lejos.robotics">RegulatedMotor</A> rightMotor,
boolean reverse)</PRE>
<DL>
<DD><B>Deprecated.</B> <I>The correct way is to create the Pilot in advance and to use that in construction of the
LegacyNavigator. Otherwise the LegacyNavigator needs to know detail it should not care about!</I>
<P>
<DD>Allocates a LegacyNavigator object and initializes it with a new TachoPilot <br>
If you want to use a different Pilot class, use the single parameter constructor.
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>wheelDiameter</CODE> - The diameter of the wheel, usually printed on the Lego tire.
Use any units you wish (e.g. 56 mm = 5.6 cm = 2.36 in)<DD><CODE>trackWidth</CODE> - The distance from the center of the left tire to the center
of the right tire, same units as wheel diameter<DD><CODE>rightMotor</CODE> - The motor used to drive the right wheel e.g. Motor.C.<DD><CODE>leftMotor</CODE> - The motor used to drive the left wheel e.g. Motor.A.<DD><CODE>reverse</CODE> - If motor.forward() dives the robot backwards, set this parameter true.</DL>
</DL>
<HR>
<A NAME="LegacyNavigator(float, float, lejos.robotics.RegulatedMotor, lejos.robotics.RegulatedMotor)"><!-- --></A><H3>
LegacyNavigator</H3>
<PRE>
<FONT SIZE="-1">@Deprecated
</FONT>public <B>LegacyNavigator</B>(float wheelDiameter,
float trackWidth,
<A HREF="../../../lejos/robotics/RegulatedMotor.html" title="interface in lejos.robotics">RegulatedMotor</A> leftMotor,
<A HREF="../../../lejos/robotics/RegulatedMotor.html" title="interface in lejos.robotics">RegulatedMotor</A> rightMotor)</PRE>
<DL>
<DD><B>Deprecated.</B> <I>The correct way is to create the Pilot in advance and to use that in construction of the
LegacyNavigator. Otherwise the LegacyNavigator needs to know detail it should not care about!</I>
<P>
<DD>Allocates a LegacyNavigator object and initializes it with a new TachoPilot.<br>
If you want to use a different Pilot class, use the single parameter constructor.
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>wheelDiameter</CODE> - The diameter of the wheel, usually printed on the Lego tire.
Use any units you wish (e.g. 56 mm = 5.6 cm = 2.36 in)<DD><CODE>trackWidth</CODE> - The distance from the center of the left tire to the center
of the right tire, sane units as wheel diameter<DD><CODE>rightMotor</CODE> - The motor used to drive the right wheel e.g. Motor.C.<DD><CODE>leftMotor</CODE> - The motor used to drive the left wheel e.g. Motor.A</DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getX()"><!-- --></A><H3>
getX</H3>
<PRE>
public float <B>getX</B>()</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>gets the current value of the X coordinate
<P>
<DD><DL>
<DT><B>Returns:</B><DD>current x</DL>
</DD>
</DL>
<HR>
<A NAME="getY()"><!-- --></A><H3>
getY</H3>
<PRE>
public float <B>getY</B>()</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>gets the current value of the Y coordinate
<P>
<DD><DL>
<DT><B>Returns:</B><DD>current Y</DL>
</DD>
</DL>
<HR>
<A NAME="getHeading()"><!-- --></A><H3>
getHeading</H3>
<PRE>
public float <B>getHeading</B>()</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>gets the current value of the robot heading
<P>
<DD><DL>
<DT><B>Returns:</B><DD>current heading</DL>
</DD>
</DL>
<HR>
<A NAME="getAngle()"><!-- --></A><H3>
getAngle</H3>
<PRE>
public float <B>getAngle</B>()</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>gets the current robot pose
<P>
<DD><DL>
<DT><B>Returns:</B><DD>current pose</DL>
</DD>
</DL>
<HR>
<A NAME="forward()"><!-- --></A><H3>
forward</H3>
<PRE>
public void <B>forward</B>()</PRE>
<DL>
<DD><B>Deprecated.</B> <DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="backward()"><!-- --></A><H3>
backward</H3>
<PRE>
public void <B>backward</B>()</PRE>
<DL>
<DD><B>Deprecated.</B> <DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="rotateLeft()"><!-- --></A><H3>
rotateLeft</H3>
<PRE>
public void <B>rotateLeft</B>()</PRE>
<DL>
<DD><B>Deprecated.</B> <DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="rotateRight()"><!-- --></A><H3>
rotateRight</H3>
<PRE>
public void <B>rotateRight</B>()</PRE>
<DL>
<DD><B>Deprecated.</B> <DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getPose()"><!-- --></A><H3>
getPose</H3>
<PRE>
public <A HREF="../../../lejos/robotics/navigation/Pose.html" title="class in lejos.robotics.navigation">Pose</A> <B>getPose</B>()</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Returns a new updated Pose
<P>
<DD><DL>
<DT><B>Returns:</B><DD>the pose</DL>
</DD>
</DL>
<HR>
<A NAME="setPose(float, float, float)"><!-- --></A><H3>
setPose</H3>
<PRE>
public void <B>setPose</B>(float x,
float y,
float heading)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>sets the robot pose to the new coordinates and heading
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>x</CODE> - coordinate<DD><CODE>y</CODE> - coordinate<DD><CODE>heading</CODE> - direction of robot forward movement</DL>
</DD>
</DL>
<HR>
<A NAME="setPose(lejos.robotics.navigation.Pose)"><!-- --></A><H3>
setPose</H3>
<PRE>
public void <B>setPose</B>(<A HREF="../../../lejos/robotics/navigation/Pose.html" title="class in lejos.robotics.navigation">Pose</A> pose)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>sets the robot pose
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>pose</CODE> - new pose</DL>
</DD>
</DL>
<HR>
<A NAME="setPosition(float, float, float)"><!-- --></A><H3>
setPosition</H3>
<PRE>
public void <B>setPosition</B>(float x,
float y,
float heading)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="setMoveSpeed(float)"><!-- --></A><H3>
setMoveSpeed</H3>
<PRE>
public void <B>setMoveSpeed</B>(float speed)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="setTravelSpeed(float)"><!-- --></A><H3>
setTravelSpeed</H3>
<PRE>
public void <B>setTravelSpeed</B>(float speed)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>sets the robots movement speed - distance units/second
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>speed</CODE> - </DL>
</DD>
</DL>
<HR>
<A NAME="setTurnSpeed(float)"><!-- --></A><H3>
setTurnSpeed</H3>
<PRE>
public void <B>setTurnSpeed</B>(float speed)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="setRotateSpeed(float)"><!-- --></A><H3>
setRotateSpeed</H3>
<PRE>
public void <B>setRotateSpeed</B>(float speed)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>sets the robot turn speed -degrees/second
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>speed</CODE> - </DL>
</DD>
</DL>
<HR>
<A NAME="stop()"><!-- --></A><H3>
stop</H3>
<PRE>
public void <B>stop</B>()</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Stops the robot. Depending on the robot speed, it travels a bit before actually
coming to a complete halt.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="isMoving()"><!-- --></A><H3>
isMoving</H3>
<PRE>
public boolean <B>isMoving</B>()</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>returns true if the robot is moving
<P>
<DD><DL>
<DT><B>Returns:</B><DD>true if it is moving</DL>
</DD>
</DL>
<HR>
<A NAME="travel(float)"><!-- --></A><H3>
travel</H3>
<PRE>
public void <B>travel</B>(float distance)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Moves the NXT robot a specific distance. A positive value moves it forwards and
a negative value moves it backwards.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>distance</CODE> - The positive or negative distance to move the robot, same units as _wheelDiameter</DL>
</DD>
</DL>
<HR>
<A NAME="travel(float, boolean)"><!-- --></A><H3>
travel</H3>
<PRE>
public void <B>travel</B>(float distance,
boolean immediateReturn)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Moves the NXT robot a specific distance. A positive value moves it forwards and
a negative value moves it backwards.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>distance</CODE> - The positive or negative distance to move the robot, same units as _wheelDiameter<DD><CODE>immediateReturn</CODE> - if true, the method returns immediately</DL>
</DD>
</DL>
<HR>
<A NAME="rotate(float)"><!-- --></A><H3>
rotate</H3>
<PRE>
public void <B>rotate</B>(float angle)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Rotates the NXT robot through a specific number of degrees in a direction (+ or -).
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>angle</CODE> - Angle to rotate in degrees. A positive value rotates left, a negative value right.</DL>
</DD>
</DL>
<HR>
<A NAME="rotate(float, boolean)"><!-- --></A><H3>
rotate</H3>
<PRE>
public void <B>rotate</B>(float angle,
boolean immediateReturn)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Rotates the NXT robot through a specific number of degrees in a direction (+ or -).
If immediateReturn is true, method returns immediately.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>angle</CODE> - Angle to rotate in degrees. A positive value rotates left, a negative value right.<DD><CODE>immediateReturn</CODE> - if true, the method returns immediately</DL>
</DD>
</DL>
<HR>
<A NAME="rotateTo(float)"><!-- --></A><H3>
rotateTo</H3>
<PRE>
public void <B>rotateTo</B>(float angle)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Rotates the NXT robot to point in a specific direction, using the smallest
rotation necessary
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>angle</CODE> - The angle to rotate to, in degrees.</DL>
</DD>
</DL>
<HR>
<A NAME="rotateTo(float, boolean)"><!-- --></A><H3>
rotateTo</H3>
<PRE>
public void <B>rotateTo</B>(float angle,
boolean immediateReturn)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Rotates the NXT robot to point in a specific direction relative to the x axis. It make the smallest
rotation necessary .
If immediateReturn is true, method returns immediately
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>angle</CODE> - The angle to rotate to, in degrees.<DD><CODE>immediateReturn</CODE> - if true, method returns immediately</DL>
</DD>
</DL>
<HR>
<A NAME="goTo(float, float)"><!-- --></A><H3>
goTo</H3>
<PRE>
public void <B>goTo</B>(float x,
float y)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Robot moves to grid coordinates x,y. First it rotates to the proper direction
then travels in a straight line to that point
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>x</CODE> - destination X coordinate<DD><CODE>y</CODE> - destination Y coordinate</DL>
</DD>
</DL>
<HR>
<A NAME="goTo(float, float, boolean)"><!-- --></A><H3>
goTo</H3>
<PRE>
public void <B>goTo</B>(float x,
float y,
boolean immediateReturn)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Robot moves to grid coordinates x,y. First it rotates to the proper direction
then travels in a straight line to that point
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>x</CODE> - destination X coordinate<DD><CODE>y</CODE> - destination Y coordinate</DL>
</DD>
</DL>
<HR>
<A NAME="distanceTo(float, float)"><!-- --></A><H3>
distanceTo</H3>
<PRE>
public float <B>distanceTo</B>(float x,
float y)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Returns the distance from robot current location to the point with coordinates x,y
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>x</CODE> - coordinate of destination<DD><CODE>y</CODE> - coordinate of destination
<DT><B>Returns:</B><DD>the distance</DL>
</DD>
</DL>
<HR>
<A NAME="angleTo(float, float)"><!-- --></A><H3>
angleTo</H3>
<PRE>
public float <B>angleTo</B>(float x,
float y)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Returns the direction angle from robot current location to the point with coordinates x,y
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>x</CODE> - coordinate of destination<DD><CODE>y</CODE> - coordinate of destination
<DT><B>Returns:</B><DD>angle</DL>
</DD>
</DL>
<HR>
<A NAME="updatePosition()"><!-- --></A><H3>
updatePosition</H3>
<PRE>
public void <B>updatePosition</B>()</PRE>
<DL>
<DD><B>Deprecated.</B> <DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="updatePose()"><!-- --></A><H3>
updatePose</H3>
<PRE>
public void <B>updatePose</B>()</PRE>
<DL>
<DD><B>Deprecated.</B> <DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="arc(float)"><!-- --></A><H3>
arc</H3>
<PRE>
public void <B>arc</B>(float radius)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Starts the NXT robot moving in a circular path with a specified radius; <br>
The center of the turning circle is on the left side of the robot if parameter radius is positive
and on the right if negative. <br>
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>radius</CODE> - - the radius of the circular path. If positive, the left wheel is on the inside of the turn.
If negative, the left wheel is on the outside.</DL>
</DD>
</DL>
<HR>
<A NAME="arc(float, int)"><!-- --></A><H3>
arc</H3>
<PRE>
public void <B>arc</B>(float radius,
int angle)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Moves the NXT robot in a circular arc through the specified angle; <br>
The center of the turning circle is on the left side of the robot if parameter radius is positive
and on the right if negative.
Robot will stop when total rotation equals angle. If angle is negative, robot will move travel backwards.
<br>See also <A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#travelArc(float, float)"><CODE>travelArc(float radius, float distance)</CODE></A>
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>radius</CODE> - - the radius of the circular path. If positive, the left wheel is on the inside of the turn.
If negative, the left wheel is on the outside.</DL>
</DD>
</DL>
<HR>
<A NAME="arc(float, int, boolean)"><!-- --></A><H3>
arc</H3>
<PRE>
public void <B>arc</B>(float radius,
int angle,
boolean immediateReturn)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Moves the NXT robot in a circular arc through a specific angle; <br>
The center of the turning circle is on the left side of the robot if parameter radius is positive
and on the right if negative.
Robot will stop when total rotation equals angle. If angle is negative, robot will travel backwards.
<br>See also <A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#travelArc(float, float, boolean)"><CODE>travelArc(float radius, float distance, boolean immedisteReturn)</CODE></A>
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>radius</CODE> - - the radius of the circular path. If positive, the left wheel is on the inside of the turn.
If negative, the left wheel is on the outside.<DD><CODE>angle</CODE> - The sign of the angle determines the direction of robot motion<DD><CODE>immediateReturn</CODE> - if true, the method returns immediately</DL>
</DD>
</DL>
<HR>
<A NAME="travelArc(float, float)"><!-- --></A><H3>
travelArc</H3>
<PRE>
public void <B>travelArc</B>(float radius,
float distance)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Moves the NXT robot in a circular arc through a specific distance; <br>
The center of the turning circle is on the left side of the robot if parameter radius is positive
and on the right if negative.
Robot will stop when distance traveled equals distance. If distance is negative, robot will travel backwards.
<br>See also <A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#arc(float, int)"><CODE>arc(float radius, int angle)</CODE></A>
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>radius</CODE> - of the turning circle; the sign determines if the center if the turn is left or right of the robot.<DD><CODE>distance</CODE> - The sign of the distance determines the direction of robot motion
updatePosition() before the robot moves again.</DL>
</DD>
</DL>
<HR>
<A NAME="travelArc(float, float, boolean)"><!-- --></A><H3>
travelArc</H3>
<PRE>
public void <B>travelArc</B>(float radius,
float distance,
boolean immediateReturn)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Moves the NXT robot in a circular arc through a specific distance; <br>
The center of the turning circle is on the left side of the robot if parameter radius is positive
and on the right if negative.
Robot will stop when distance traveled equals distance. If distance is negative, robot will travel backwards.
<br>See also <A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#arc(float, int, boolean)"><CODE>arc(float radius, int angle, boolean immediateReturn)</CODE></A>
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>radius</CODE> - of the turning circle; the sign determines if the center if the turn is left or right of the robot.<DD><CODE>distance</CODE> - The sign of the distance determines the direction of robot motion<DD><CODE>immediateReturn</CODE> - if true, the method returns immediately.</DL>
</DD>
</DL>
<HR>
<A NAME="steer(int)"><!-- --></A><H3>
steer</H3>
<PRE>
public void <B>steer</B>(int turnRate)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Starts the robot moving along a curved path. This method is similar to the
<A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#arc(float)"><CODE>arc(float radius)</CODE></A> method except it uses a ratio of motor
speeds to determine the curvature of the path and therefore has the ability to drive straight. This makes
it useful for line following applications.
<p>
The <code>turnRate</code> specifies the sharpness of the turn, between -200 and +200.<br>
The <code>turnRate</code> is used to calculate the ratio of inner wheel speed to outer wheel speed <b>as a percent</b>.<br>
<I>Formula:</I> <code>ratio = 100 - abs(turnRate)</code>.<br>
When the ratio is negative, the outer and inner wheels rotate in
opposite directions.
<p>
If <code>turnRate</code> is positive, the center of the turning circle is on the left side of the robot.<br>
If <code>turnRate</code> is negative, the center of the turning circle is on the right side of the robot.<br>
If <code>turnRate</code> is zero, the robot travels in a straight line
<p>
Examples of how the formula works:
<UL>
<LI><code>steer(0)</code> -> inner and outer wheels turn at the same speed, travel straight
<LI><code>steer(25)</code> -> the inner wheel turns at 75% of the speed of the outer wheel, turn left
<LI><code>steer(100)</code> -> the inner wheel stops and the outer wheel is at 100 percent, turn left
<LI><code>steer(200)</code> -> the inner wheel turns at the same speed as the outer wheel - a zero radius turn.
</UL>
<p>
Note: If you have specified a drift correction in the constructor it will not be applied in this method.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>turnRate</CODE> - If positive, the left side of the robot is on the inside of the turn. If negative,
the left side is on the outside.</DL>
</DD>
</DL>
<HR>
<A NAME="steer(int, int)"><!-- --></A><H3>
steer</H3>
<PRE>
public void <B>steer</B>(int turnRate,
int angle)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Moves the robot along a curved path through a specified turn angle. This method is similar to the
<A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#arc(float, int)"><CODE>arc(float radius , int angle)</CODE></A> method except it uses a ratio of motor
speeds to determine the curvature of the path and therefore has the ability to drive straight. This makes
it useful for line following applications. This method does not return until the robot has
completed moving <code>angle</code> degrees along the arc.<br>
The <code>turnRate</code> specifies the sharpness of the turn, between -200 and +200.<br>
For details about how this parameter works. see <A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#steer(int)"><CODE>steer(int turnRate)</CODE></A>
<p>
The robot will stop when the degrees it has moved along the arc equals <code>angle</code>.<br>
If <code>angle</code> is positive, the robot will move travel forwards.<br>
If <code>angle</code> is negative, the robot will move travel backwards.
If <code>angle</code> is zero, the robot will not move and the method returns immediately.
<p>
Note: If you have specified a drift correction in the constructor it will not be applied in this method.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>turnRate</CODE> - If positive, the left side of the robot is on the inside of the turn. If negative,
the left side is on the outside.<DD><CODE>angle</CODE> - The angle through which the robot will rotate. If negative, robot traces the turning circle backwards.</DL>
</DD>
</DL>
<HR>
<A NAME="steer(int, int, boolean)"><!-- --></A><H3>
steer</H3>
<PRE>
public void <B>steer</B>(int turnRate,
int angle,
boolean immediateReturn)</PRE>
<DL>
<DD><B>Deprecated.</B> <DD>Moves the robot along a curved path for a specified angle of rotation. This method is similar to the
<A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#arc(float, int, boolean)"><CODE>arc(float radius, int angle, boolean immediateReturn)</CODE></A> method except it uses a ratio of motor
speeds to speeds to determine the curvature of the path and therefore has the ability to drive straight.
This makes it useful for line following applications. This method has the ability to return immediately
by using the <code>immediateReturn</code> parameter set to <b>true</b>.
<p>
The <code>turnRate</code> specifies the sharpness of the turn, between -200 and +200.<br>
For details about how this parameter works, see <A HREF="../../../lejos/robotics/navigation/LegacyNavigator.html#steer(int)"><CODE>steer(int turnRate)</CODE></A>
<p>
The robot will stop when the degrees it has moved along the arc equals <code>angle</code>.<br>
If <code>angle</code> is positive, the robot will move travel forwards.<br>
If <code>angle</code> is negative, the robot will move travel backwards.
If <code>angle</code> is zero, the robot will not move and the method returns immediately.
<p>
Note: If you have specified a drift correction in the constructor it will not be applied in this method.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>turnRate</CODE> - If positive, the left side of the robot is on the inside of the turn. If negative,
the left side is on the outside.<DD><CODE>angle</CODE> - The angle through which the robot will rotate. If negative, robot traces the turning circle backwards.<DD><CODE>immediateReturn</CODE> - If immediateReturn is true then the method returns immediately.</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../lejos/robotics/navigation/DifferentialPilot.html" title="class in lejos.robotics.navigation"><B>PREV CLASS</B></A>
<A HREF="../../../lejos/robotics/navigation/LegacyPilot.html" title="class in lejos.robotics.navigation"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?lejos/robotics/navigation/LegacyNavigator.html" target="_top"><B>FRAMES</B></A>
<A HREF="LegacyNavigator.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
|
gusDuarte/enchanting-usb3
|
leJOS_NXJ_0.9.1beta-3/docs/pc/lejos/robotics/navigation/LegacyNavigator.html
|
HTML
|
gpl-2.0
| 54,035 |
/* linux/drivers/usb/gadget/u_lgeusb.c
*
* Copyright (C) 2011,2012 LG Electronics Inc.
* Author : Hyeon H. Park <[email protected]>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
/*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#if 0 /* */
#include <mach/msm_hsusb.h>
#include <mach/rpc_hsusb.h>
#endif
#include <mach/board.h>
#ifdef CONFIG_MACH_LGE
#include <mach/board_lge.h>
#endif
#include <linux/platform_data/lge_android_usb.h>
#include "u_lgeusb.h"
static struct mutex lgeusb_lock;
#ifdef CONFIG_USB_G_LGE_ANDROID_AUTORUN
static u16 user_mode;
#endif
/* */
#define MAX_SERIAL_NO_LEN 256
#define LGE_VENDOR_ID 0x1004
#define LGE_PRODUCT_ID 0x618E
#define LGE_FACTORY_PID 0x6000
struct lgeusb_dev {
struct device *dev;
u16 vendor_id;
u16 factory_pid;
u8 iSerialNumber;
char *product;
char *manufacturer;
char *fcomposition;
enum lgeusb_mode current_mode;
int (*get_serial_number)(char *serial);
int (*get_factory_cable)(void);
};
static char model_string[32];
static char swver_string[32];
static char subver_string[32];
static char phoneid_string[32];
static struct lgeusb_dev *_lgeusb_dev;
/* */
#define LGE_ID_ATTR(field, format_string) \
static ssize_t \
lgeusb_ ## field ## _show(struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
struct lgeusb_dev *usbdev = _lgeusb_dev; \
return sprintf(buf, format_string, usbdev->field); \
} \
static ssize_t \
lgeusb_ ## field ## _store(struct device *dev, struct device_attribute *attr, \
const char *buf, size_t size) \
{ \
int value; \
struct lgeusb_dev *usbdev = _lgeusb_dev; \
if (sscanf(buf, format_string, &value) == 1) { \
usbdev->field = value; \
return size; \
} \
return -1; \
} \
static DEVICE_ATTR(field, S_IRUGO | S_IWUSR, lgeusb_ ## field ## _show, lgeusb_ ## field ## _store);
#define LGE_RDONLY_STRING_ATTR(field, string) \
static ssize_t \
lgeusb_ ## field ## _show(struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
struct lgeusb_dev *usbdev = _lgeusb_dev; \
return sprintf(buf, "%s", usbdev->string); \
} \
static DEVICE_ATTR(field, S_IRUGO | S_IWUSR, lgeusb_ ## field ## _show, NULL);
#define LGE_STRING_ATTR(field, buffer) \
static ssize_t \
field ## _show(struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
return snprintf(buf, PAGE_SIZE, "%s", buffer); \
} \
static ssize_t \
field ## _store(struct device *dev, struct device_attribute *attr, \
const char *buf, size_t size) \
{ \
if (size >= sizeof(buffer)) \
return -EINVAL; \
if (sscanf(buf, "%31s", buffer) == 1) { \
return size; \
} \
return -1; \
} \
static DEVICE_ATTR(field, S_IRUGO | S_IWUSR, field ## _show, field ## _store);
LGE_ID_ATTR(vendor_id, "%04X\n")
LGE_ID_ATTR(factory_pid, "%04X\n")
LGE_ID_ATTR(iSerialNumber, "%d\n")
LGE_RDONLY_STRING_ATTR(product_name, product)
LGE_RDONLY_STRING_ATTR(manufacturer_name, manufacturer)
LGE_RDONLY_STRING_ATTR(fcomposition, fcomposition)
LGE_STRING_ATTR(model_name, model_string)
LGE_STRING_ATTR(sw_version, swver_string)
LGE_STRING_ATTR(sub_version, subver_string)
LGE_STRING_ATTR(phone_id, phoneid_string)
static ssize_t lgeusb_mode_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct lgeusb_dev *usbdev = _lgeusb_dev;
int is_factory_cable = 0;
int ret = 0;
if (usbdev->get_factory_cable)
is_factory_cable = usbdev->get_factory_cable();
mutex_lock(&lgeusb_lock);
if (is_factory_cable)
usbdev->current_mode = LGEUSB_FACTORY_MODE;
else
usbdev->current_mode = LGEUSB_ANDROID_MODE;
mutex_unlock(&lgeusb_lock);
switch (is_factory_cable) {
case LGEUSB_FACTORY_56K:
ret = sprintf(buf, "%s\n", "factory_56k");
break;
case LGEUSB_FACTORY_130K:
ret = sprintf(buf, "%s\n", "factory_130k");
break;
case LGEUSB_FACTORY_910K:
ret = sprintf(buf, "%s\n", "factory_910k");
break;
default:
ret = sprintf(buf, "%s\n", "normal");
break;
}
return ret;
}
static DEVICE_ATTR(lge_usb_mode, S_IRUGO | S_IWUSR, lgeusb_mode_show, NULL);
#ifdef CONFIG_USB_G_LGE_ANDROID_AUTORUN
/* */
static int autorun_user_mode_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
ret = sprintf(buf, "%d", user_mode);
return ret;
}
static int autorun_user_mode_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
int ret = 0;
unsigned long tmp;
ret = strict_strtoul(buf, 10, &tmp);
if (ret)
return ret;
mutex_lock(&lgeusb_lock);
user_mode = (unsigned int)tmp;
mutex_unlock(&lgeusb_lock);
pr_info("autorun user mode : %d\n", user_mode);
return ret;
}
static DEVICE_ATTR(autorun_user_mode, S_IRUGO | S_IWUSR, autorun_user_mode_show, autorun_user_mode_store);
int lgeusb_get_autorun_user_mode(void)
{
return user_mode;
}
#endif
static struct device_attribute *lge_android_usb_attributes[] = {
&dev_attr_vendor_id,
&dev_attr_factory_pid,
&dev_attr_product_name,
&dev_attr_manufacturer_name,
&dev_attr_fcomposition,
&dev_attr_lge_usb_mode,
&dev_attr_iSerialNumber,
&dev_attr_model_name,
&dev_attr_sw_version,
&dev_attr_sub_version,
&dev_attr_phone_id,
#ifdef CONFIG_USB_G_LGE_ANDROID_AUTORUN
&dev_attr_autorun_user_mode,
#endif
NULL
};
static int lgeusb_create_device_file(struct lgeusb_dev *dev)
{
struct device_attribute **attrs = lge_android_usb_attributes;
struct device_attribute *attr;
int ret;
while ((attr = *attrs++)) {
ret = device_create_file(dev->dev, attr);
if (ret)
pr_err("usb: lgeusb: error on creating device file %s\n",
attr->attr.name);
}
return 0;
}
int lgeusb_get_pif_cable(void)
{
struct lgeusb_dev *usbdev = _lgeusb_dev;
if (usbdev->get_factory_cable)
return usbdev->get_factory_cable();
return 0;
}
int lgeusb_get_vendor_id(void)
{
struct lgeusb_dev *usbdev = _lgeusb_dev;
return usbdev ? usbdev->vendor_id : -EINVAL;
}
int lgeusb_get_factory_pid(void)
{
struct lgeusb_dev *usbdev = _lgeusb_dev;
return usbdev ? usbdev->factory_pid : -EINVAL;
}
int lgeusb_get_serial_number(void)
{
struct lgeusb_dev *usbdev = _lgeusb_dev;
return usbdev ? usbdev->iSerialNumber : -EINVAL;
}
int lgeusb_get_manufacturer_name(char *manufact_name)
{
struct lgeusb_dev *usbdev = _lgeusb_dev;
char *manufact = manufact_name;
if (!manufact || !usbdev || !usbdev->manufacturer)
return -EINVAL;
strlcpy(manufact, usbdev->manufacturer, MAX_SERIAL_NO_LEN - 1);
pr_debug("lgeusb: manfacturer name %s\n", manufact);
return 0;
}
int lgeusb_get_product_name(char *prod_name)
{
struct lgeusb_dev *usbdev = _lgeusb_dev;
char *prod = prod_name;
if (!prod || !usbdev || !usbdev->product)
return -EINVAL;
strlcpy(prod, usbdev->product, MAX_SERIAL_NO_LEN - 1);
pr_debug("lgeusb: product name %s\n", prod);
return 0;
}
int lgeusb_get_factory_composition(char *fcomposition)
{
struct lgeusb_dev *usbdev = _lgeusb_dev;
char *fcompo = fcomposition;
if (!fcomposition || !usbdev || !usbdev->fcomposition)
return -EINVAL;
strlcpy(fcompo, usbdev->fcomposition, MAX_SERIAL_NO_LEN - 1);
pr_debug("lgeusb: factory composition %s\n", fcompo);
return 0;
}
int lgeusb_get_model_name(char *model)
{
if (!model || strlen(model) > 15)
return -EINVAL;
strlcpy(model, model_string, strlen(model) - 1);
pr_info("lgeusb: model name %s\n", model);
return 0;
}
int lgeusb_get_phone_id(char *phoneid)
{
if (!phoneid || strlen(phoneid) > 15)
return -EINVAL;
strlcpy(phoneid, phoneid_string, strlen(phoneid) - 1);
pr_info("lgeusb: phoneid %s\n", phoneid);
return 0;
}
int lgeusb_get_sw_ver(char *sw_ver)
{
if (!sw_ver || strlen(sw_ver) > 15)
return -EINVAL;
strlcpy(sw_ver, swver_string, strlen(sw_ver) - 1);
pr_info("lgeusb: sw version %s\n", sw_ver);
return 0;
}
int lgeusb_get_sub_ver(char *sub_ver)
{
if (!sub_ver || strlen(sub_ver) > 15)
return -EINVAL;
strlcpy(sub_ver, subver_string, strlen(sub_ver) - 1);
pr_info("lgeusb: sw sub version %s\n", sub_ver);
return 0;
}
static struct platform_driver lge_android_usb_platform_driver = {
.driver = {
.name = "lge_android_usb",
},
};
static int __init lgeusb_probe(struct platform_device *pdev)
{
struct lge_android_usb_platform_data *pdata = pdev->dev.platform_data;
struct lgeusb_dev *usbdev = _lgeusb_dev;
dev_dbg(&pdev->dev, "%s: pdata: %p\n", __func__, pdata);
usbdev->dev = &pdev->dev;
if (pdata) {
if (pdata->vendor_id)
usbdev->vendor_id = pdata->vendor_id;
if (pdata->factory_pid)
usbdev->factory_pid = pdata->factory_pid;
if (pdata->iSerialNumber)
usbdev->iSerialNumber = pdata->iSerialNumber;
if (pdata->product_name)
usbdev->product = pdata->product_name;
if (pdata->manufacturer_name)
usbdev->manufacturer = pdata->manufacturer_name;
if (pdata->factory_composition)
usbdev->fcomposition = pdata->factory_composition;
if (pdata->get_factory_cable)
usbdev->get_factory_cable = pdata->get_factory_cable;
}
usbdev->current_mode = LGEUSB_DEFAULT_MODE;
lgeusb_create_device_file(usbdev);
return 0;
}
static int __init lgeusb_init(void)
{
struct lgeusb_dev *dev;
pr_info("u_lgeusb init\n");
mutex_init(&lgeusb_lock);
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
_lgeusb_dev = dev;
/* */
dev->vendor_id = LGE_VENDOR_ID;
dev->factory_pid = LGE_FACTORY_PID;
return platform_driver_probe(&lge_android_usb_platform_driver,
lgeusb_probe);
}
module_init(lgeusb_init);
static void __exit lgeusb_cleanup(void)
{
platform_driver_unregister(&lge_android_usb_platform_driver);
kfree(_lgeusb_dev);
_lgeusb_dev = NULL;
}
module_exit(lgeusb_cleanup);
|
aicjofs/android_kernel_lge_v500
|
drivers/usb/gadget/u_lgeusb.c
|
C
|
gpl-2.0
| 11,287 |
/******************************************************************************
* Wormux is a convivial mass murder game.
* Copyright (C) 2001-2007 Wormux Team.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
******************************************************************************
* WeaponLauncher: generic weapon to launch a projectile
*****************************************************************************/
#include "weapon/weapon_launcher.h"
#include "weapon/weapon_cfg.h"
#include <sstream>
#include "weapon/explosion.h"
#include "character/character.h"
#include "game/config.h"
#include "game/game.h"
#include "game/time.h"
#include "graphic/sprite.h"
#include "include/action_handler.h"
#include "interface/game_msg.h"
#include "map/camera.h"
#include "object/objects_list.h"
#include "sound/jukebox.h"
#include "team/macro.h"
#include "team/team.h"
#include "team/teams_list.h"
#include "tool/debug.h"
#include "tool/i18n.h"
#include "tool/math_tools.h"
#include "tool/resource_manager.h"
#ifdef DEBUG
//#define DEBUG_EXPLOSION_CONFIG
#endif
WeaponBullet::WeaponBullet(const std::string &name,
ExplosiveWeaponConfig& cfg,
WeaponLauncher * p_launcher) :
WeaponProjectile(name, cfg, p_launcher)
{
explode_colliding_character = true;
m_allow_negative_y = false;
ResetTimeOut();
}
// Signal that the bullet has hit the ground
void WeaponBullet::SignalGroundCollision()
{
jukebox.Play("share", "weapon/ricoche1");
WeaponProjectile::SignalGroundCollision();
launcher->IncMissedShots();
}
void WeaponBullet::SignalOutOfMap()
{
WeaponProjectile::SignalOutOfMap();
launcher->IncMissedShots();
Camera::GetInstance()->FollowObject(&ActiveCharacter(), true);
}
void WeaponBullet::SignalObjectCollision(PhysicalObj * obj)
{
if (typeid(*obj) != typeid(Character))
Explosion();
obj->SetEnergyDelta(-(int)cfg.damage);
obj->AddSpeed(2, GetSpeedAngle());
Ghost();
}
void WeaponBullet::Refresh()
{
WeaponProjectile::Refresh();
image->SetRotation_rad(GetSpeedAngle());
}
void WeaponBullet::DoExplosion()
{
Point2i pos = GetCenter();
ApplyExplosion(pos, cfg, "", false, ParticleEngine::LittleESmoke, GetUniqueId());
}
//-----------------------------------------------------------------------------
WeaponProjectile::WeaponProjectile(const std::string &name,
ExplosiveWeaponConfig& p_cfg,
WeaponLauncher * p_launcher)
: PhysicalObj(name), cfg(p_cfg)
{
m_allow_negative_y = true;
SetCollisionModel(false, true, true);
launcher = p_launcher;
explode_colliding_character = false;
explode_with_timeout = true;
explode_with_collision = true;
image = resource_manager.LoadSprite( weapons_res_profile, name);
image->EnableRotationCache(32);
SetSize(image->GetSize());
// Set rectangle test
int dx = image->GetWidth()/2-1;
int dy = image->GetHeight()/2-1;
SetTestRect(dx, dx, dy, dy);
ResetTimeOut();
// generate a unique id for the projectile
m_unique_id = name + Game::GetUniqueId();
}
WeaponProjectile::~WeaponProjectile()
{
// delete image; /*-> it causes a segfault :-/ */
}
void WeaponProjectile::Shoot(double strength)
{
MSG_DEBUG("weapon.projectile", "shoot with strength:%f", strength);
Init();
if (launcher != NULL)
launcher->IncActiveProjectile();
// Set the physical factors
ResetConstants();
// Set the initial position.
SetOverlappingObject(&ActiveCharacter(), 100);
lst_objects.AddObject(this);
Camera::GetInstance()->FollowObject(this, true);
double angle = ActiveCharacter().GetFiringAngle();
RandomizeShoot(angle, strength);
MSG_DEBUG("weapon.projectile", "shoot from position %d,%d (size %d, %d) - hand position:%d,%d",
ActiveCharacter().GetX(),
ActiveCharacter().GetY(),
ActiveCharacter().GetWidth(),
ActiveCharacter().GetHeight(),
ActiveCharacter().GetHandPosition().GetX(),
ActiveCharacter().GetHandPosition().GetY());
MSG_DEBUG("weapon.projectile", "shoot with strength:%f, angle:%f, position:%d,%d",
strength, angle, GetX(), GetY());
begin_time = Time::GetInstance()->Read();
ShootSound();
// bug #10236 : problem with flamethrower collision detection
// Check if the object is colliding something between hand position and gun hole
Point2i hand_position = ActiveCharacter().GetHandPosition() - GetSize() / 2;
Point2i hole_position = launcher->GetGunHolePosition() - GetSize() / 2;
Point2d f_hand_position(hand_position.GetX() / PIXEL_PER_METER, hand_position.GetY() / PIXEL_PER_METER);
Point2d f_hole_position(hole_position.GetX() / PIXEL_PER_METER, hole_position.GetY() / PIXEL_PER_METER);
SetXY(hand_position);
SetSpeed(strength, angle);
NotifyMove(f_hand_position, f_hole_position);
if(last_collision_type == NO_COLLISION) {
// Set the initial position and speed.
SetXY(hole_position);
SetSpeed(strength, angle);
PutOutOfGround(angle);
}
}
void WeaponProjectile::ShootSound()
{
jukebox.Play(ActiveTeam().GetSoundProfile(), "fire");
}
void WeaponProjectile::Refresh()
{
if(energy == 0) {
Explosion();
return;
}
// Explose after timeout
double tmp = Time::GetInstance()->Read() - begin_time;
if(cfg.timeout && tmp > 1000 * (GetTotalTimeout())) SignalTimeout();
}
void WeaponProjectile::SetEnergyDelta(int /*delta*/, bool /*do_report*/)
{
// Don't call Explosion here, we're already in an explosion
energy = 0;
}
void WeaponProjectile::Draw()
{
image->Draw(GetPosition());
int tmp = GetTotalTimeout();
if (cfg.timeout && tmp != 0)
{
tmp -= (int)((Time::GetInstance()->Read() - begin_time) / 1000);
if (tmp >= 0)
{
std::ostringstream ss;
ss << tmp ;
int txt_x = GetX() + GetWidth() / 2;
int txt_y = GetY() - GetHeight();
(*Font::GetInstance(Font::FONT_SMALL)).WriteCenterTop( Point2i(txt_x, txt_y) - Camera::GetInstance()->GetPosition(),
ss.str(), white_color);
}
}
}
bool WeaponProjectile::IsImmobile() const
{
if(explode_with_timeout && begin_time + GetTotalTimeout() * 1000 > Time::GetInstance()->Read())
return false;
return PhysicalObj::IsImmobile();
}
// projectile explode and signal to the launcher the collision
void WeaponProjectile::SignalObjectCollision(PhysicalObj * obj)
{
ASSERT(obj != NULL);
MSG_DEBUG("weapon.projectile", "SignalObjectCollision \"%s\" with \"%s\": %d, %d",
m_name.c_str(), obj->GetName().c_str(), GetX(), GetY());
if (explode_colliding_character)
Explosion();
}
// projectile explode when hiting the ground
void WeaponProjectile::SignalGroundCollision()
{
MSG_DEBUG("weapon.projectile", "SignalGroundCollision \"%s\": %d, %d", m_name.c_str(), GetX(), GetY());
if (explode_with_collision)
Explosion();
}
// Default behavior : signal to launcher a collision and explode
void WeaponProjectile::SignalCollision()
{
MSG_DEBUG("weapon.projectile", "SignalCollision \"%s\": %d, %d", m_name.c_str(), GetX(), GetY());
if (launcher != NULL && !launcher->ignore_collision_signal) launcher->SignalProjectileCollision();
}
// Default behavior : signal to launcher projectile is drowning
void WeaponProjectile::SignalDrowning()
{
MSG_DEBUG("weapon.projectile", "SignalDrowning \"%s\": %d, %d", m_name.c_str(), GetX(), GetY());
PhysicalObj::SignalDrowning();
if (launcher != NULL && !launcher->ignore_drowning_signal)
launcher->SignalProjectileDrowning();
jukebox.Play("share", "sink");
}
// Default behavior : signal to launcher a projectile is going out of water
void WeaponProjectile::SignalGoingOutOfWater()
{
MSG_DEBUG("weapon.projectile", "SignalDrowning \"%s\": %d, %d", m_name.c_str(), GetX(), GetY());
PhysicalObj::SignalGoingOutOfWater();
if (launcher != NULL && !launcher->ignore_going_out_of_water_signal)
launcher->SignalProjectileGoingOutOfWater();
}
// Signal a ghost state
void WeaponProjectile::SignalGhostState(bool)
{
MSG_DEBUG("weapon.projectile", "SignalGhostState \"%s\": %d, %d", m_name.c_str(), GetX(), GetY());
if (launcher != NULL && !launcher->ignore_ghost_state_signal)
launcher->SignalProjectileGhostState();
}
void WeaponProjectile::SignalOutOfMap()
{
MSG_DEBUG("weapon.projectile", "SignalOutOfMap \"%s\": %d, %d", m_name.c_str(), GetX(), GetY());
}
// the projectile explode and signal the explosion to launcher
void WeaponProjectile::Explosion()
{
MSG_DEBUG("weapon.projectile", "Explosion \"%s\": %d, %d", m_name.c_str(), GetX(), GetY());
DoExplosion();
SignalExplosion();
Ghost();
}
void WeaponProjectile::SignalExplosion()
{
MSG_DEBUG("weapon.projectile", "SignalExplosion \"%s\": %d, %d", m_name.c_str(), GetX(), GetY());
if (launcher != NULL && !launcher->ignore_explosion_signal)
launcher->SignalProjectileExplosion();
}
void WeaponProjectile::DoExplosion()
{
Point2i pos = GetCenter();
ApplyExplosion(pos, cfg, "weapon/explosion", true, ParticleEngine::BigESmoke, GetUniqueId());
}
void WeaponProjectile::IncrementTimeOut()
{
if (cfg.allow_change_timeout && GetTotalTimeout()<(int)cfg.timeout*2)
m_timeout_modifier += 1 ;
}
void WeaponProjectile::DecrementTimeOut()
{
// -1s for grenade timout. 1 is min.
if (cfg.allow_change_timeout && GetTotalTimeout()>1)
m_timeout_modifier -= 1 ;
}
void WeaponProjectile::SetTimeOut(int timeout)
{
if (cfg.allow_change_timeout && timeout <= (int)cfg.timeout*2 && timeout >= 1)
m_timeout_modifier = timeout - cfg.timeout ;
}
int WeaponProjectile::GetTotalTimeout() const
{
return (int)(cfg.timeout)+m_timeout_modifier;
}
// Signal a projectile timeout and explode
void WeaponProjectile::SignalTimeout()
{
MSG_DEBUG("weapon.projectile", "\"%s\" timeout has expired", m_name.c_str());
if (launcher != NULL && !launcher->ignore_timeout_signal)
launcher->SignalProjectileTimeout();
if (explode_with_timeout)
Explosion();
}
//Public function which let know if changing timeout is allowed.
bool WeaponProjectile::change_timeout_allowed() const
{
return cfg.allow_change_timeout;
}
//-----------------------------------------------------------------------------
WeaponLauncher::WeaponLauncher(Weapon_type type,
const std::string &id,
EmptyWeaponConfig * params,
weapon_visibility_t visibility) :
Weapon(type, id, params, visibility)
{
projectile = NULL;
nb_active_projectile = 0;
missed_shots = 0;
announce_missed_shots = true;
ignore_timeout_signal = false;
ignore_collision_signal = false;
ignore_explosion_signal = false;
ignore_ghost_state_signal = false;
ignore_drowning_signal = false;
ignore_going_out_of_water_signal = false;
}
WeaponLauncher::~WeaponLauncher()
{
if (projectile)
delete projectile;
}
bool WeaponLauncher::p_Shoot()
{
// if (m_strength == max_strength)
// {
// m_strength = 0;
// DirectExplosion();
// return true;
// }
projectile->Shoot(m_strength);
projectile = NULL;
ReloadLauncher();
return true;
}
bool WeaponLauncher::IsInUse() const
{
return m_last_fire_time > 0 && m_last_fire_time + m_time_between_each_shot > Time::GetInstance()->Read();
}
bool WeaponLauncher::ReloadLauncher()
{
if (projectile)
return false;
projectile = GetProjectileInstance();
return true;
}
// Direct Explosion when pushing weapon to max power !
void WeaponLauncher::DirectExplosion()
{
Point2i pos = ActiveCharacter().GetCenter();
ApplyExplosion(pos, cfg());
}
void WeaponLauncher::Draw()
{
//Display timeout for projectil if can be changed.
if (projectile->change_timeout_allowed())
{
if( IsInUse() ) //Do not display after launching.
return;
int tmp = projectile->GetTotalTimeout();
std::ostringstream ss;
ss << tmp;
ss << "s";
int txt_x = ActiveCharacter().GetX() + ActiveCharacter().GetWidth() / 2;
int txt_y = ActiveCharacter().GetY() - ActiveCharacter().GetHeight();
(*Font::GetInstance(Font::FONT_SMALL)).WriteCenterTop( Point2i(txt_x, txt_y) - Camera::GetInstance()->GetPosition(),
ss.str(), white_color);
}
Weapon::Draw();
#ifdef DEBUG_EXPLOSION_CONFIG
ExplosiveWeaponConfig* cfg = dynamic_cast<ExplosiveWeaponConfig*>(extra_params);
if( cfg != NULL )
{
Point2i p = ActiveCharacter().GetHandPosition() - Camera::GetInstance()->GetPosition();
// Red color for the blast range (should be superior to the explosion_range)
AppWormux::GetInstance()->video->window.CircleColor(p.x, p.y, (int)cfg->blast_range, c_red);
// Yellow color for the blast range (should be superior to the explosion_range)
AppWormux::GetInstance()->video->window.CircleColor(p.x, p.y, (int)cfg->explosion_range, c_black);
}
AppWormux::GetInstance()->video->window.CircleColor(GetGunHolePosition().x-Camera::GetInstance()->GetPositionX(), GetGunHolePosition().y-Camera::GetInstance()->GetPositionY(), 5, c_black);
#endif
}
void WeaponLauncher::p_Select()
{
missed_shots = 0;
if (projectile->change_timeout_allowed())
{
projectile->ResetTimeOut();
}
Weapon::p_Select();
}
void WeaponLauncher::IncMissedShots()
{
missed_shots++;
if(announce_missed_shots)
GameMessages::GetInstance()->Add (_("Your shot has missed!"));
}
void WeaponLauncher::HandleKeyReleased_Num1(bool /*shift*/)
{
projectile->SetTimeOut(1);
NetworkSetTimeoutProjectile();
}
void WeaponLauncher::HandleKeyReleased_Num2(bool /*shift*/)
{
projectile->SetTimeOut(2);
NetworkSetTimeoutProjectile();
}
void WeaponLauncher::HandleKeyReleased_Num3(bool /*shift*/)
{
projectile->SetTimeOut(3);
NetworkSetTimeoutProjectile();
}
void WeaponLauncher::HandleKeyReleased_Num4(bool /*shift*/)
{
projectile->SetTimeOut(4);
NetworkSetTimeoutProjectile();
}
void WeaponLauncher::HandleKeyReleased_Num5(bool /*shift*/)
{
projectile->SetTimeOut(5);
NetworkSetTimeoutProjectile();
}
void WeaponLauncher::HandleKeyReleased_Num6(bool /*shift*/)
{
projectile->SetTimeOut(6);
NetworkSetTimeoutProjectile();
}
void WeaponLauncher::HandleKeyReleased_Num7(bool /*shift*/)
{
projectile->SetTimeOut(7);
NetworkSetTimeoutProjectile();
}
void WeaponLauncher::HandleKeyReleased_Num8(bool /*shift*/)
{
projectile->SetTimeOut(8);
NetworkSetTimeoutProjectile();
}
void WeaponLauncher::HandleKeyReleased_Num9(bool /*shift*/)
{
projectile->SetTimeOut(9);
NetworkSetTimeoutProjectile();
}
void WeaponLauncher::HandleKeyReleased_Less(bool /*shift*/)
{
projectile->DecrementTimeOut();
NetworkSetTimeoutProjectile();
}
void WeaponLauncher::HandleKeyReleased_More(bool /*shift*/)
{
projectile->IncrementTimeOut();
NetworkSetTimeoutProjectile();
}
void WeaponLauncher::NetworkSetTimeoutProjectile() const
{
ActionHandler::GetInstance()->NewAction(new Action(Action::ACTION_WEAPON_SET_TIMEOUT,
projectile->m_timeout_modifier));
}
void WeaponLauncher::HandleMouseWheelUp(bool /*shift*/)
{
projectile->IncrementTimeOut();
NetworkSetTimeoutProjectile();
}
void WeaponLauncher::HandleMouseWheelDown(bool /*shift*/)
{
projectile->DecrementTimeOut();
NetworkSetTimeoutProjectile();
}
ExplosiveWeaponConfig& WeaponLauncher::cfg()
{
return static_cast<ExplosiveWeaponConfig&>(*extra_params);
}
|
yeKcim/warmux
|
old/wormux-0.8beta3/src/weapon/weapon_launcher.cpp
|
C++
|
gpl-2.0
| 15,983 |
/*
* NSA Security-Enhanced Linux (SELinux) security module
*
* This file contains the SELinux hook function implementations.
*
* Authors: Stephen Smalley, <[email protected]>
* Chris Vance, <[email protected]>
* Wayne Salamon, <[email protected]>
* James Morris <[email protected]>
*
* Copyright (C) 2001,2002 Networks Associates Technology, Inc.
* Copyright (C) 2003-2008 Red Hat, Inc., James Morris <[email protected]>
* Eric Paris <[email protected]>
* Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
* <[email protected]>
* Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P.
* Paul Moore <[email protected]>
* Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
* Yuichi Nakamura <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/kd.h>
#include <linux/kernel.h>
#include <linux/tracehook.h>
#include <linux/errno.h>
#include <linux/ext2_fs.h>
#include <linux/sched.h>
#include <linux/security.h>
#include <linux/xattr.h>
#include <linux/capability.h>
#include <linux/unistd.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/proc_fs.h>
#include <linux/swap.h>
#include <linux/spinlock.h>
#include <linux/syscalls.h>
#include <linux/dcache.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/namei.h>
#include <linux/mount.h>
#include <linux/netfilter_ipv4.h>
#include <linux/netfilter_ipv6.h>
#include <linux/tty.h>
#include <net/icmp.h>
#include <net/ip.h> /* for local_port_range[] */
#include <net/tcp.h> /* struct or_callable used in sock_rcv_skb */
#include <net/inet_connection_sock.h>
#include <net/net_namespace.h>
#include <net/netlabel.h>
#include <linux/uaccess.h>
#include <asm/ioctls.h>
#include <linux/atomic.h>
#include <linux/bitops.h>
#include <linux/interrupt.h>
#include <linux/netdevice.h> /* for network interface checks */
#include <linux/netlink.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/dccp.h>
#include <linux/quota.h>
#include <linux/un.h> /* for Unix socket types */
#include <net/af_unix.h> /* for Unix socket types */
#include <linux/parser.h>
#include <linux/nfs_mount.h>
#include <net/ipv6.h>
#include <linux/hugetlb.h>
#include <linux/personality.h>
#include <linux/audit.h>
#include <linux/string.h>
#include <linux/selinux.h>
#include <linux/mutex.h>
#include <linux/posix-timers.h>
#include <linux/syslog.h>
#include <linux/user_namespace.h>
#include <linux/export.h>
#include "avc.h"
#include "objsec.h"
#include "netif.h"
#include "netnode.h"
#include "netport.h"
#include "xfrm.h"
#include "netlabel.h"
#include "audit.h"
#include "avc_ss.h"
#define NUM_SEL_MNT_OPTS 5
extern struct security_operations *security_ops;
/* SECMARK reference count */
static atomic_t selinux_secmark_refcount = ATOMIC_INIT(0);
#ifdef CONFIG_SECURITY_SELINUX_DEVELOP
int selinux_enforcing;
static int __init enforcing_setup(char *str)
{
unsigned long enforcing;
if (!strict_strtoul(str, 0, &enforcing))
selinux_enforcing = enforcing ? 1 : 0;
return 1;
}
__setup("enforcing=", enforcing_setup);
#endif
#ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
int selinux_enabled = CONFIG_SECURITY_SELINUX_BOOTPARAM_VALUE;
static int __init selinux_enabled_setup(char *str)
{
unsigned long enabled;
if (!strict_strtoul(str, 0, &enabled))
selinux_enabled = enabled ? 1 : 0;
return 1;
}
__setup("selinux=", selinux_enabled_setup);
#else
int selinux_enabled = 1;
#endif
static struct kmem_cache *sel_inode_cache;
/**
* selinux_secmark_enabled - Check to see if SECMARK is currently enabled
*
* Description:
* This function checks the SECMARK reference counter to see if any SECMARK
* targets are currently configured, if the reference counter is greater than
* zero SECMARK is considered to be enabled. Returns true (1) if SECMARK is
* enabled, false (0) if SECMARK is disabled.
*
*/
static int selinux_secmark_enabled(void)
{
return (atomic_read(&selinux_secmark_refcount) > 0);
}
/*
* initialise the security for the init task
*/
static void cred_init_security(void)
{
struct cred *cred = (struct cred *) current->real_cred;
struct task_security_struct *tsec;
tsec = kzalloc(sizeof(struct task_security_struct), GFP_KERNEL);
if (!tsec)
panic("SELinux: Failed to initialize initial task.\n");
tsec->osid = tsec->sid = SECINITSID_KERNEL;
cred->security = tsec;
}
/*
* get the security ID of a set of credentials
*/
static inline u32 cred_sid(const struct cred *cred)
{
const struct task_security_struct *tsec;
tsec = cred->security;
return tsec->sid;
}
/*
* get the objective security ID of a task
*/
static inline u32 task_sid(const struct task_struct *task)
{
u32 sid;
rcu_read_lock();
sid = cred_sid(__task_cred(task));
rcu_read_unlock();
return sid;
}
/*
* get the subjective security ID of the current task
*/
static inline u32 current_sid(void)
{
const struct task_security_struct *tsec = current_security();
return tsec->sid;
}
/* Allocate and free functions for each kind of security blob. */
static int inode_alloc_security(struct inode *inode)
{
struct inode_security_struct *isec;
u32 sid = current_sid();
isec = kmem_cache_zalloc(sel_inode_cache, GFP_NOFS);
if (!isec)
return -ENOMEM;
mutex_init(&isec->lock);
INIT_LIST_HEAD(&isec->list);
isec->inode = inode;
isec->sid = SECINITSID_UNLABELED;
isec->sclass = SECCLASS_FILE;
isec->task_sid = sid;
inode->i_security = isec;
return 0;
}
static void inode_free_security(struct inode *inode)
{
struct inode_security_struct *isec = inode->i_security;
struct superblock_security_struct *sbsec = inode->i_sb->s_security;
spin_lock(&sbsec->isec_lock);
if (!list_empty(&isec->list))
list_del_init(&isec->list);
spin_unlock(&sbsec->isec_lock);
inode->i_security = NULL;
kmem_cache_free(sel_inode_cache, isec);
}
static int file_alloc_security(struct file *file)
{
struct file_security_struct *fsec;
u32 sid = current_sid();
fsec = kzalloc(sizeof(struct file_security_struct), GFP_KERNEL);
if (!fsec)
return -ENOMEM;
fsec->sid = sid;
fsec->fown_sid = sid;
file->f_security = fsec;
return 0;
}
static void file_free_security(struct file *file)
{
struct file_security_struct *fsec = file->f_security;
file->f_security = NULL;
kfree(fsec);
}
static int superblock_alloc_security(struct super_block *sb)
{
struct superblock_security_struct *sbsec;
sbsec = kzalloc(sizeof(struct superblock_security_struct), GFP_KERNEL);
if (!sbsec)
return -ENOMEM;
mutex_init(&sbsec->lock);
INIT_LIST_HEAD(&sbsec->isec_head);
spin_lock_init(&sbsec->isec_lock);
sbsec->sb = sb;
sbsec->sid = SECINITSID_UNLABELED;
sbsec->def_sid = SECINITSID_FILE;
sbsec->mntpoint_sid = SECINITSID_UNLABELED;
sb->s_security = sbsec;
return 0;
}
static void superblock_free_security(struct super_block *sb)
{
struct superblock_security_struct *sbsec = sb->s_security;
sb->s_security = NULL;
kfree(sbsec);
}
/* The file system's label must be initialized prior to use. */
static const char *labeling_behaviors[6] = {
"uses xattr",
"uses transition SIDs",
"uses task SIDs",
"uses genfs_contexts",
"not configured for labeling",
"uses mountpoint labeling",
};
static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
static inline int inode_doinit(struct inode *inode)
{
return inode_doinit_with_dentry(inode, NULL);
}
enum {
Opt_error = -1,
Opt_context = 1,
Opt_fscontext = 2,
Opt_defcontext = 3,
Opt_rootcontext = 4,
Opt_labelsupport = 5,
};
static const match_table_t tokens = {
{Opt_context, CONTEXT_STR "%s"},
{Opt_fscontext, FSCONTEXT_STR "%s"},
{Opt_defcontext, DEFCONTEXT_STR "%s"},
{Opt_rootcontext, ROOTCONTEXT_STR "%s"},
{Opt_labelsupport, LABELSUPP_STR},
{Opt_error, NULL},
};
#define SEL_MOUNT_FAIL_MSG "SELinux: duplicate or incompatible mount options\n"
static int may_context_mount_sb_relabel(u32 sid,
struct superblock_security_struct *sbsec,
const struct cred *cred)
{
const struct task_security_struct *tsec = cred->security;
int rc;
rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
FILESYSTEM__RELABELFROM, NULL);
if (rc)
return rc;
rc = avc_has_perm(tsec->sid, sid, SECCLASS_FILESYSTEM,
FILESYSTEM__RELABELTO, NULL);
return rc;
}
static int may_context_mount_inode_relabel(u32 sid,
struct superblock_security_struct *sbsec,
const struct cred *cred)
{
const struct task_security_struct *tsec = cred->security;
int rc;
rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
FILESYSTEM__RELABELFROM, NULL);
if (rc)
return rc;
rc = avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM,
FILESYSTEM__ASSOCIATE, NULL);
return rc;
}
static int sb_finish_set_opts(struct super_block *sb)
{
struct superblock_security_struct *sbsec = sb->s_security;
struct dentry *root = sb->s_root;
struct inode *root_inode = root->d_inode;
int rc = 0;
if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
/* Make sure that the xattr handler exists and that no
error other than -ENODATA is returned by getxattr on
the root directory. -ENODATA is ok, as this may be
the first boot of the SELinux kernel before we have
assigned xattr values to the filesystem. */
if (!root_inode->i_op->getxattr) {
printk(KERN_WARNING "SELinux: (dev %s, type %s) has no "
"xattr support\n", sb->s_id, sb->s_type->name);
rc = -EOPNOTSUPP;
goto out;
}
rc = root_inode->i_op->getxattr(root, XATTR_NAME_SELINUX, NULL, 0);
if (rc < 0 && rc != -ENODATA) {
if (rc == -EOPNOTSUPP)
printk(KERN_WARNING "SELinux: (dev %s, type "
"%s) has no security xattr handler\n",
sb->s_id, sb->s_type->name);
else
printk(KERN_WARNING "SELinux: (dev %s, type "
"%s) getxattr errno %d\n", sb->s_id,
sb->s_type->name, -rc);
goto out;
}
}
sbsec->flags |= (SE_SBINITIALIZED | SE_SBLABELSUPP);
if (sbsec->behavior > ARRAY_SIZE(labeling_behaviors))
printk(KERN_ERR "SELinux: initialized (dev %s, type %s), unknown behavior\n",
sb->s_id, sb->s_type->name);
else
printk(KERN_DEBUG "SELinux: initialized (dev %s, type %s), %s\n",
sb->s_id, sb->s_type->name,
labeling_behaviors[sbsec->behavior-1]);
if (sbsec->behavior == SECURITY_FS_USE_GENFS ||
sbsec->behavior == SECURITY_FS_USE_MNTPOINT ||
sbsec->behavior == SECURITY_FS_USE_NONE ||
sbsec->behavior > ARRAY_SIZE(labeling_behaviors))
sbsec->flags &= ~SE_SBLABELSUPP;
/* Special handling for sysfs. Is genfs but also has setxattr handler*/
if (strncmp(sb->s_type->name, "sysfs", sizeof("sysfs")) == 0)
sbsec->flags |= SE_SBLABELSUPP;
/* Initialize the root inode. */
rc = inode_doinit_with_dentry(root_inode, root);
/* Initialize any other inodes associated with the superblock, e.g.
inodes created prior to initial policy load or inodes created
during get_sb by a pseudo filesystem that directly
populates itself. */
spin_lock(&sbsec->isec_lock);
next_inode:
if (!list_empty(&sbsec->isec_head)) {
struct inode_security_struct *isec =
list_entry(sbsec->isec_head.next,
struct inode_security_struct, list);
struct inode *inode = isec->inode;
spin_unlock(&sbsec->isec_lock);
inode = igrab(inode);
if (inode) {
if (!IS_PRIVATE(inode))
inode_doinit(inode);
iput(inode);
}
spin_lock(&sbsec->isec_lock);
list_del_init(&isec->list);
goto next_inode;
}
spin_unlock(&sbsec->isec_lock);
out:
return rc;
}
/*
* This function should allow an FS to ask what it's mount security
* options were so it can use those later for submounts, displaying
* mount options, or whatever.
*/
static int selinux_get_mnt_opts(const struct super_block *sb,
struct security_mnt_opts *opts)
{
int rc = 0, i;
struct superblock_security_struct *sbsec = sb->s_security;
char *context = NULL;
u32 len;
char tmp;
security_init_mnt_opts(opts);
if (!(sbsec->flags & SE_SBINITIALIZED))
return -EINVAL;
if (!ss_initialized)
return -EINVAL;
tmp = sbsec->flags & SE_MNTMASK;
/* count the number of mount options for this sb */
for (i = 0; i < 8; i++) {
if (tmp & 0x01)
opts->num_mnt_opts++;
tmp >>= 1;
}
/* Check if the Label support flag is set */
if (sbsec->flags & SE_SBLABELSUPP)
opts->num_mnt_opts++;
opts->mnt_opts = kcalloc(opts->num_mnt_opts, sizeof(char *), GFP_ATOMIC);
if (!opts->mnt_opts) {
rc = -ENOMEM;
goto out_free;
}
opts->mnt_opts_flags = kcalloc(opts->num_mnt_opts, sizeof(int), GFP_ATOMIC);
if (!opts->mnt_opts_flags) {
rc = -ENOMEM;
goto out_free;
}
i = 0;
if (sbsec->flags & FSCONTEXT_MNT) {
rc = security_sid_to_context(sbsec->sid, &context, &len);
if (rc)
goto out_free;
opts->mnt_opts[i] = context;
opts->mnt_opts_flags[i++] = FSCONTEXT_MNT;
}
if (sbsec->flags & CONTEXT_MNT) {
rc = security_sid_to_context(sbsec->mntpoint_sid, &context, &len);
if (rc)
goto out_free;
opts->mnt_opts[i] = context;
opts->mnt_opts_flags[i++] = CONTEXT_MNT;
}
if (sbsec->flags & DEFCONTEXT_MNT) {
rc = security_sid_to_context(sbsec->def_sid, &context, &len);
if (rc)
goto out_free;
opts->mnt_opts[i] = context;
opts->mnt_opts_flags[i++] = DEFCONTEXT_MNT;
}
if (sbsec->flags & ROOTCONTEXT_MNT) {
struct inode *root = sbsec->sb->s_root->d_inode;
struct inode_security_struct *isec = root->i_security;
rc = security_sid_to_context(isec->sid, &context, &len);
if (rc)
goto out_free;
opts->mnt_opts[i] = context;
opts->mnt_opts_flags[i++] = ROOTCONTEXT_MNT;
}
if (sbsec->flags & SE_SBLABELSUPP) {
opts->mnt_opts[i] = NULL;
opts->mnt_opts_flags[i++] = SE_SBLABELSUPP;
}
BUG_ON(i != opts->num_mnt_opts);
return 0;
out_free:
security_free_mnt_opts(opts);
return rc;
}
static int bad_option(struct superblock_security_struct *sbsec, char flag,
u32 old_sid, u32 new_sid)
{
char mnt_flags = sbsec->flags & SE_MNTMASK;
/* check if the old mount command had the same options */
if (sbsec->flags & SE_SBINITIALIZED)
if (!(sbsec->flags & flag) ||
(old_sid != new_sid))
return 1;
/* check if we were passed the same options twice,
* aka someone passed context=a,context=b
*/
if (!(sbsec->flags & SE_SBINITIALIZED))
if (mnt_flags & flag)
return 1;
return 0;
}
/*
* Allow filesystems with binary mount data to explicitly set mount point
* labeling information.
*/
static int selinux_set_mnt_opts(struct super_block *sb,
struct security_mnt_opts *opts)
{
const struct cred *cred = current_cred();
int rc = 0, i;
struct superblock_security_struct *sbsec = sb->s_security;
const char *name = sb->s_type->name;
struct inode *inode = sbsec->sb->s_root->d_inode;
struct inode_security_struct *root_isec = inode->i_security;
u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
u32 defcontext_sid = 0;
char **mount_options = opts->mnt_opts;
int *flags = opts->mnt_opts_flags;
int num_opts = opts->num_mnt_opts;
mutex_lock(&sbsec->lock);
if (!ss_initialized) {
if (!num_opts) {
/* Defer initialization until selinux_complete_init,
after the initial policy is loaded and the security
server is ready to handle calls. */
goto out;
}
rc = -EINVAL;
printk(KERN_WARNING "SELinux: Unable to set superblock options "
"before the security server is initialized\n");
goto out;
}
/*
* Binary mount data FS will come through this function twice. Once
* from an explicit call and once from the generic calls from the vfs.
* Since the generic VFS calls will not contain any security mount data
* we need to skip the double mount verification.
*
* This does open a hole in which we will not notice if the first
* mount using this sb set explict options and a second mount using
* this sb does not set any security options. (The first options
* will be used for both mounts)
*/
if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
&& (num_opts == 0))
goto out;
/*
* parse the mount options, check if they are valid sids.
* also check if someone is trying to mount the same sb more
* than once with different security options.
*/
for (i = 0; i < num_opts; i++) {
u32 sid;
if (flags[i] == SE_SBLABELSUPP)
continue;
rc = security_context_to_sid(mount_options[i],
strlen(mount_options[i]), &sid);
if (rc) {
printk(KERN_WARNING "SELinux: security_context_to_sid"
"(%s) failed for (dev %s, type %s) errno=%d\n",
mount_options[i], sb->s_id, name, rc);
goto out;
}
switch (flags[i]) {
case FSCONTEXT_MNT:
fscontext_sid = sid;
if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
fscontext_sid))
goto out_double_mount;
sbsec->flags |= FSCONTEXT_MNT;
break;
case CONTEXT_MNT:
context_sid = sid;
if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
context_sid))
goto out_double_mount;
sbsec->flags |= CONTEXT_MNT;
break;
case ROOTCONTEXT_MNT:
rootcontext_sid = sid;
if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
rootcontext_sid))
goto out_double_mount;
sbsec->flags |= ROOTCONTEXT_MNT;
break;
case DEFCONTEXT_MNT:
defcontext_sid = sid;
if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
defcontext_sid))
goto out_double_mount;
sbsec->flags |= DEFCONTEXT_MNT;
break;
default:
rc = -EINVAL;
goto out;
}
}
if (sbsec->flags & SE_SBINITIALIZED) {
/* previously mounted with options, but not on this attempt? */
if ((sbsec->flags & SE_MNTMASK) && !num_opts)
goto out_double_mount;
rc = 0;
goto out;
}
if (strcmp(sb->s_type->name, "proc") == 0)
sbsec->flags |= SE_SBPROC;
/* Determine the labeling behavior to use for this filesystem type. */
rc = security_fs_use((sbsec->flags & SE_SBPROC) ? "proc" : sb->s_type->name, &sbsec->behavior, &sbsec->sid);
if (rc) {
printk(KERN_WARNING "%s: security_fs_use(%s) returned %d\n",
__func__, sb->s_type->name, rc);
goto out;
}
/* sets the context of the superblock for the fs being mounted. */
if (fscontext_sid) {
rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred);
if (rc)
goto out;
sbsec->sid = fscontext_sid;
}
/*
* Switch to using mount point labeling behavior.
* sets the label used on all file below the mountpoint, and will set
* the superblock context if not already set.
*/
if (context_sid) {
if (!fscontext_sid) {
rc = may_context_mount_sb_relabel(context_sid, sbsec,
cred);
if (rc)
goto out;
sbsec->sid = context_sid;
} else {
rc = may_context_mount_inode_relabel(context_sid, sbsec,
cred);
if (rc)
goto out;
}
if (!rootcontext_sid)
rootcontext_sid = context_sid;
sbsec->mntpoint_sid = context_sid;
sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
}
if (rootcontext_sid) {
rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
cred);
if (rc)
goto out;
root_isec->sid = rootcontext_sid;
root_isec->initialized = 1;
}
if (defcontext_sid) {
if (sbsec->behavior != SECURITY_FS_USE_XATTR) {
rc = -EINVAL;
printk(KERN_WARNING "SELinux: defcontext option is "
"invalid for this filesystem type\n");
goto out;
}
if (defcontext_sid != sbsec->def_sid) {
rc = may_context_mount_inode_relabel(defcontext_sid,
sbsec, cred);
if (rc)
goto out;
}
sbsec->def_sid = defcontext_sid;
}
rc = sb_finish_set_opts(sb);
out:
mutex_unlock(&sbsec->lock);
return rc;
out_double_mount:
rc = -EINVAL;
printk(KERN_WARNING "SELinux: mount invalid. Same superblock, different "
"security settings for (dev %s, type %s)\n", sb->s_id, name);
goto out;
}
static void selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
struct super_block *newsb)
{
const struct superblock_security_struct *oldsbsec = oldsb->s_security;
struct superblock_security_struct *newsbsec = newsb->s_security;
int set_fscontext = (oldsbsec->flags & FSCONTEXT_MNT);
int set_context = (oldsbsec->flags & CONTEXT_MNT);
int set_rootcontext = (oldsbsec->flags & ROOTCONTEXT_MNT);
/*
* if the parent was able to be mounted it clearly had no special lsm
* mount options. thus we can safely deal with this superblock later
*/
if (!ss_initialized)
return;
/* how can we clone if the old one wasn't set up?? */
BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
/* if fs is reusing a sb, just let its options stand... */
if (newsbsec->flags & SE_SBINITIALIZED)
return;
mutex_lock(&newsbsec->lock);
newsbsec->flags = oldsbsec->flags;
newsbsec->sid = oldsbsec->sid;
newsbsec->def_sid = oldsbsec->def_sid;
newsbsec->behavior = oldsbsec->behavior;
if (set_context) {
u32 sid = oldsbsec->mntpoint_sid;
if (!set_fscontext)
newsbsec->sid = sid;
if (!set_rootcontext) {
struct inode *newinode = newsb->s_root->d_inode;
struct inode_security_struct *newisec = newinode->i_security;
newisec->sid = sid;
}
newsbsec->mntpoint_sid = sid;
}
if (set_rootcontext) {
const struct inode *oldinode = oldsb->s_root->d_inode;
const struct inode_security_struct *oldisec = oldinode->i_security;
struct inode *newinode = newsb->s_root->d_inode;
struct inode_security_struct *newisec = newinode->i_security;
newisec->sid = oldisec->sid;
}
sb_finish_set_opts(newsb);
mutex_unlock(&newsbsec->lock);
}
static int selinux_parse_opts_str(char *options,
struct security_mnt_opts *opts)
{
char *p;
char *context = NULL, *defcontext = NULL;
char *fscontext = NULL, *rootcontext = NULL;
int rc, num_mnt_opts = 0;
opts->num_mnt_opts = 0;
/* Standard string-based options. */
while ((p = strsep(&options, "|")) != NULL) {
int token;
substring_t args[MAX_OPT_ARGS];
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case Opt_context:
if (context || defcontext) {
rc = -EINVAL;
printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
goto out_err;
}
context = match_strdup(&args[0]);
if (!context) {
rc = -ENOMEM;
goto out_err;
}
break;
case Opt_fscontext:
if (fscontext) {
rc = -EINVAL;
printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
goto out_err;
}
fscontext = match_strdup(&args[0]);
if (!fscontext) {
rc = -ENOMEM;
goto out_err;
}
break;
case Opt_rootcontext:
if (rootcontext) {
rc = -EINVAL;
printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
goto out_err;
}
rootcontext = match_strdup(&args[0]);
if (!rootcontext) {
rc = -ENOMEM;
goto out_err;
}
break;
case Opt_defcontext:
if (context || defcontext) {
rc = -EINVAL;
printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
goto out_err;
}
defcontext = match_strdup(&args[0]);
if (!defcontext) {
rc = -ENOMEM;
goto out_err;
}
break;
case Opt_labelsupport:
break;
default:
rc = -EINVAL;
printk(KERN_WARNING "SELinux: unknown mount option\n");
goto out_err;
}
}
rc = -ENOMEM;
opts->mnt_opts = kcalloc(NUM_SEL_MNT_OPTS, sizeof(char *), GFP_ATOMIC);
if (!opts->mnt_opts)
goto out_err;
opts->mnt_opts_flags = kcalloc(NUM_SEL_MNT_OPTS, sizeof(int), GFP_ATOMIC);
if (!opts->mnt_opts_flags) {
kfree(opts->mnt_opts);
goto out_err;
}
if (fscontext) {
opts->mnt_opts[num_mnt_opts] = fscontext;
opts->mnt_opts_flags[num_mnt_opts++] = FSCONTEXT_MNT;
}
if (context) {
opts->mnt_opts[num_mnt_opts] = context;
opts->mnt_opts_flags[num_mnt_opts++] = CONTEXT_MNT;
}
if (rootcontext) {
opts->mnt_opts[num_mnt_opts] = rootcontext;
opts->mnt_opts_flags[num_mnt_opts++] = ROOTCONTEXT_MNT;
}
if (defcontext) {
opts->mnt_opts[num_mnt_opts] = defcontext;
opts->mnt_opts_flags[num_mnt_opts++] = DEFCONTEXT_MNT;
}
opts->num_mnt_opts = num_mnt_opts;
return 0;
out_err:
kfree(context);
kfree(defcontext);
kfree(fscontext);
kfree(rootcontext);
return rc;
}
/*
* string mount options parsing and call set the sbsec
*/
static int superblock_doinit(struct super_block *sb, void *data)
{
int rc = 0;
char *options = data;
struct security_mnt_opts opts;
security_init_mnt_opts(&opts);
if (!data)
goto out;
BUG_ON(sb->s_type->fs_flags & FS_BINARY_MOUNTDATA);
rc = selinux_parse_opts_str(options, &opts);
if (rc)
goto out_err;
out:
rc = selinux_set_mnt_opts(sb, &opts);
out_err:
security_free_mnt_opts(&opts);
return rc;
}
static void selinux_write_opts(struct seq_file *m,
struct security_mnt_opts *opts)
{
int i;
char *prefix;
for (i = 0; i < opts->num_mnt_opts; i++) {
char *has_comma;
if (opts->mnt_opts[i])
has_comma = strchr(opts->mnt_opts[i], ',');
else
has_comma = NULL;
switch (opts->mnt_opts_flags[i]) {
case CONTEXT_MNT:
prefix = CONTEXT_STR;
break;
case FSCONTEXT_MNT:
prefix = FSCONTEXT_STR;
break;
case ROOTCONTEXT_MNT:
prefix = ROOTCONTEXT_STR;
break;
case DEFCONTEXT_MNT:
prefix = DEFCONTEXT_STR;
break;
case SE_SBLABELSUPP:
seq_putc(m, ',');
seq_puts(m, LABELSUPP_STR);
continue;
default:
BUG();
return;
};
/* we need a comma before each option */
seq_putc(m, ',');
seq_puts(m, prefix);
if (has_comma)
seq_putc(m, '\"');
seq_puts(m, opts->mnt_opts[i]);
if (has_comma)
seq_putc(m, '\"');
}
}
static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
{
struct security_mnt_opts opts;
int rc;
rc = selinux_get_mnt_opts(sb, &opts);
if (rc) {
/* before policy load we may get EINVAL, don't show anything */
if (rc == -EINVAL)
rc = 0;
return rc;
}
selinux_write_opts(m, &opts);
security_free_mnt_opts(&opts);
return rc;
}
static inline u16 inode_mode_to_security_class(umode_t mode)
{
switch (mode & S_IFMT) {
case S_IFSOCK:
return SECCLASS_SOCK_FILE;
case S_IFLNK:
return SECCLASS_LNK_FILE;
case S_IFREG:
return SECCLASS_FILE;
case S_IFBLK:
return SECCLASS_BLK_FILE;
case S_IFDIR:
return SECCLASS_DIR;
case S_IFCHR:
return SECCLASS_CHR_FILE;
case S_IFIFO:
return SECCLASS_FIFO_FILE;
}
return SECCLASS_FILE;
}
static inline int default_protocol_stream(int protocol)
{
return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP);
}
static inline int default_protocol_dgram(int protocol)
{
return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
}
static inline u16 socket_type_to_security_class(int family, int type, int protocol)
{
switch (family) {
case PF_UNIX:
switch (type) {
case SOCK_STREAM:
case SOCK_SEQPACKET:
return SECCLASS_UNIX_STREAM_SOCKET;
case SOCK_DGRAM:
return SECCLASS_UNIX_DGRAM_SOCKET;
}
break;
case PF_INET:
case PF_INET6:
switch (type) {
case SOCK_STREAM:
if (default_protocol_stream(protocol))
return SECCLASS_TCP_SOCKET;
else
return SECCLASS_RAWIP_SOCKET;
case SOCK_DGRAM:
if (default_protocol_dgram(protocol))
return SECCLASS_UDP_SOCKET;
else
return SECCLASS_RAWIP_SOCKET;
case SOCK_DCCP:
return SECCLASS_DCCP_SOCKET;
default:
return SECCLASS_RAWIP_SOCKET;
}
break;
case PF_NETLINK:
switch (protocol) {
case NETLINK_ROUTE:
return SECCLASS_NETLINK_ROUTE_SOCKET;
case NETLINK_FIREWALL:
return SECCLASS_NETLINK_FIREWALL_SOCKET;
case NETLINK_INET_DIAG:
return SECCLASS_NETLINK_TCPDIAG_SOCKET;
case NETLINK_NFLOG:
return SECCLASS_NETLINK_NFLOG_SOCKET;
case NETLINK_XFRM:
return SECCLASS_NETLINK_XFRM_SOCKET;
case NETLINK_SELINUX:
return SECCLASS_NETLINK_SELINUX_SOCKET;
case NETLINK_AUDIT:
return SECCLASS_NETLINK_AUDIT_SOCKET;
case NETLINK_IP6_FW:
return SECCLASS_NETLINK_IP6FW_SOCKET;
case NETLINK_DNRTMSG:
return SECCLASS_NETLINK_DNRT_SOCKET;
case NETLINK_KOBJECT_UEVENT:
return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
default:
return SECCLASS_NETLINK_SOCKET;
}
case PF_PACKET:
return SECCLASS_PACKET_SOCKET;
case PF_KEY:
return SECCLASS_KEY_SOCKET;
case PF_APPLETALK:
return SECCLASS_APPLETALK_SOCKET;
}
return SECCLASS_SOCKET;
}
#ifdef CONFIG_PROC_FS
static int selinux_proc_get_sid(struct dentry *dentry,
u16 tclass,
u32 *sid)
{
int rc;
char *buffer, *path;
buffer = (char *)__get_free_page(GFP_KERNEL);
if (!buffer)
return -ENOMEM;
path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
if (IS_ERR(path))
rc = PTR_ERR(path);
else {
/* each process gets a /proc/PID/ entry. Strip off the
* PID part to get a valid selinux labeling.
* e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
while (path[1] >= '0' && path[1] <= '9') {
path[1] = '/';
path++;
}
rc = security_genfs_sid("proc", path, tclass, sid);
}
free_page((unsigned long)buffer);
return rc;
}
#else
static int selinux_proc_get_sid(struct dentry *dentry,
u16 tclass,
u32 *sid)
{
return -EINVAL;
}
#endif
/* The inode's security attributes must be initialized before first use. */
static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
{
struct superblock_security_struct *sbsec = NULL;
struct inode_security_struct *isec = inode->i_security;
u32 sid;
struct dentry *dentry;
#define INITCONTEXTLEN 255
char *context = NULL;
unsigned len = 0;
int rc = 0;
if (isec->initialized)
goto out;
mutex_lock(&isec->lock);
if (isec->initialized)
goto out_unlock;
sbsec = inode->i_sb->s_security;
if (!(sbsec->flags & SE_SBINITIALIZED)) {
/* Defer initialization until selinux_complete_init,
after the initial policy is loaded and the security
server is ready to handle calls. */
spin_lock(&sbsec->isec_lock);
if (list_empty(&isec->list))
list_add(&isec->list, &sbsec->isec_head);
spin_unlock(&sbsec->isec_lock);
goto out_unlock;
}
switch (sbsec->behavior) {
case SECURITY_FS_USE_XATTR:
if (!inode->i_op->getxattr) {
isec->sid = sbsec->def_sid;
break;
}
/* Need a dentry, since the xattr API requires one.
Life would be simpler if we could just pass the inode. */
if (opt_dentry) {
/* Called from d_instantiate or d_splice_alias. */
dentry = dget(opt_dentry);
} else {
/* Called from selinux_complete_init, try to find a dentry. */
dentry = d_find_alias(inode);
}
if (!dentry) {
/*
* this is can be hit on boot when a file is accessed
* before the policy is loaded. When we load policy we
* may find inodes that have no dentry on the
* sbsec->isec_head list. No reason to complain as these
* will get fixed up the next time we go through
* inode_doinit with a dentry, before these inodes could
* be used again by userspace.
*/
goto out_unlock;
}
len = INITCONTEXTLEN;
context = kmalloc(len+1, GFP_NOFS);
if (!context) {
rc = -ENOMEM;
dput(dentry);
goto out_unlock;
}
context[len] = '\0';
rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
context, len);
if (rc == -ERANGE) {
kfree(context);
/* Need a larger buffer. Query for the right size. */
rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
NULL, 0);
if (rc < 0) {
dput(dentry);
goto out_unlock;
}
len = rc;
context = kmalloc(len+1, GFP_NOFS);
if (!context) {
rc = -ENOMEM;
dput(dentry);
goto out_unlock;
}
context[len] = '\0';
rc = inode->i_op->getxattr(dentry,
XATTR_NAME_SELINUX,
context, len);
}
dput(dentry);
if (rc < 0) {
if (rc != -ENODATA) {
printk(KERN_WARNING "SELinux: %s: getxattr returned "
"%d for dev=%s ino=%ld\n", __func__,
-rc, inode->i_sb->s_id, inode->i_ino);
kfree(context);
goto out_unlock;
}
/* Map ENODATA to the default file SID */
sid = sbsec->def_sid;
rc = 0;
} else {
rc = security_context_to_sid_default(context, rc, &sid,
sbsec->def_sid,
GFP_NOFS);
if (rc) {
char *dev = inode->i_sb->s_id;
unsigned long ino = inode->i_ino;
if (rc == -EINVAL) {
if (printk_ratelimit())
printk(KERN_NOTICE "SELinux: inode=%lu on dev=%s was found to have an invalid "
"context=%s. This indicates you may need to relabel the inode or the "
"filesystem in question.\n", ino, dev, context);
} else {
printk(KERN_WARNING "SELinux: %s: context_to_sid(%s) "
"returned %d for dev=%s ino=%ld\n",
__func__, context, -rc, dev, ino);
}
kfree(context);
/* Leave with the unlabeled SID */
rc = 0;
break;
}
}
kfree(context);
isec->sid = sid;
break;
case SECURITY_FS_USE_TASK:
isec->sid = isec->task_sid;
break;
case SECURITY_FS_USE_TRANS:
/* Default to the fs SID. */
isec->sid = sbsec->sid;
/* Try to obtain a transition SID. */
isec->sclass = inode_mode_to_security_class(inode->i_mode);
rc = security_transition_sid(isec->task_sid, sbsec->sid,
isec->sclass, NULL, &sid);
if (rc)
goto out_unlock;
isec->sid = sid;
break;
case SECURITY_FS_USE_MNTPOINT:
isec->sid = sbsec->mntpoint_sid;
break;
default:
/* Default to the fs superblock SID. */
isec->sid = sbsec->sid;
if ((sbsec->flags & SE_SBPROC) && !S_ISLNK(inode->i_mode)) {
if (opt_dentry) {
isec->sclass = inode_mode_to_security_class(inode->i_mode);
rc = selinux_proc_get_sid(opt_dentry,
isec->sclass,
&sid);
if (rc)
goto out_unlock;
isec->sid = sid;
}
}
break;
}
isec->initialized = 1;
out_unlock:
mutex_unlock(&isec->lock);
out:
if (isec->sclass == SECCLASS_FILE)
isec->sclass = inode_mode_to_security_class(inode->i_mode);
return rc;
}
/* Convert a Linux signal to an access vector. */
static inline u32 signal_to_av(int sig)
{
u32 perm = 0;
switch (sig) {
case SIGCHLD:
/* Commonly granted from child to parent. */
perm = PROCESS__SIGCHLD;
break;
case SIGKILL:
/* Cannot be caught or ignored */
perm = PROCESS__SIGKILL;
break;
case SIGSTOP:
/* Cannot be caught or ignored */
perm = PROCESS__SIGSTOP;
break;
default:
/* All other signals. */
perm = PROCESS__SIGNAL;
break;
}
return perm;
}
/*
* Check permission between a pair of credentials
* fork check, ptrace check, etc.
*/
static int cred_has_perm(const struct cred *actor,
const struct cred *target,
u32 perms)
{
u32 asid = cred_sid(actor), tsid = cred_sid(target);
return avc_has_perm(asid, tsid, SECCLASS_PROCESS, perms, NULL);
}
/*
* Check permission between a pair of tasks, e.g. signal checks,
* fork check, ptrace check, etc.
* tsk1 is the actor and tsk2 is the target
* - this uses the default subjective creds of tsk1
*/
static int task_has_perm(const struct task_struct *tsk1,
const struct task_struct *tsk2,
u32 perms)
{
const struct task_security_struct *__tsec1, *__tsec2;
u32 sid1, sid2;
rcu_read_lock();
__tsec1 = __task_cred(tsk1)->security; sid1 = __tsec1->sid;
__tsec2 = __task_cred(tsk2)->security; sid2 = __tsec2->sid;
rcu_read_unlock();
return avc_has_perm(sid1, sid2, SECCLASS_PROCESS, perms, NULL);
}
/*
* Check permission between current and another task, e.g. signal checks,
* fork check, ptrace check, etc.
* current is the actor and tsk2 is the target
* - this uses current's subjective creds
*/
static int current_has_perm(const struct task_struct *tsk,
u32 perms)
{
u32 sid, tsid;
sid = current_sid();
tsid = task_sid(tsk);
return avc_has_perm(sid, tsid, SECCLASS_PROCESS, perms, NULL);
}
#if CAP_LAST_CAP > 63
#error Fix SELinux to handle capabilities > 63.
#endif
/* Check whether a task is allowed to use a capability. */
static int task_has_capability(struct task_struct *tsk,
const struct cred *cred,
int cap, int audit)
{
struct common_audit_data ad;
struct av_decision avd;
u16 sclass;
u32 sid = cred_sid(cred);
u32 av = CAP_TO_MASK(cap);
int rc;
COMMON_AUDIT_DATA_INIT(&ad, CAP);
ad.tsk = tsk;
ad.u.cap = cap;
switch (CAP_TO_INDEX(cap)) {
case 0:
sclass = SECCLASS_CAPABILITY;
break;
case 1:
sclass = SECCLASS_CAPABILITY2;
break;
default:
printk(KERN_ERR
"SELinux: out of range capability %d\n", cap);
BUG();
return -EINVAL;
}
rc = avc_has_perm_noaudit(sid, sid, sclass, av, 0, &avd);
if (audit == SECURITY_CAP_AUDIT) {
int rc2 = avc_audit(sid, sid, sclass, av, &avd, rc, &ad, 0);
if (rc2)
return rc2;
}
return rc;
}
/* Check whether a task is allowed to use a system operation. */
static int task_has_system(struct task_struct *tsk,
u32 perms)
{
u32 sid = task_sid(tsk);
return avc_has_perm(sid, SECINITSID_KERNEL,
SECCLASS_SYSTEM, perms, NULL);
}
/* Check whether a task has a particular permission to an inode.
The 'adp' parameter is optional and allows other audit
data to be passed (e.g. the dentry). */
static int inode_has_perm(const struct cred *cred,
struct inode *inode,
u32 perms,
struct common_audit_data *adp,
unsigned flags)
{
struct inode_security_struct *isec;
u32 sid;
validate_creds(cred);
if (unlikely(IS_PRIVATE(inode)))
return 0;
sid = cred_sid(cred);
isec = inode->i_security;
return avc_has_perm_flags(sid, isec->sid, isec->sclass, perms, adp, flags);
}
static int inode_has_perm_noadp(const struct cred *cred,
struct inode *inode,
u32 perms,
unsigned flags)
{
struct common_audit_data ad;
COMMON_AUDIT_DATA_INIT(&ad, INODE);
ad.u.inode = inode;
return inode_has_perm(cred, inode, perms, &ad, flags);
}
/* Same as inode_has_perm, but pass explicit audit data containing
the dentry to help the auditing code to more easily generate the
pathname if needed. */
static inline int dentry_has_perm(const struct cred *cred,
struct dentry *dentry,
u32 av)
{
struct inode *inode = dentry->d_inode;
struct common_audit_data ad;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = dentry;
return inode_has_perm(cred, inode, av, &ad, 0);
}
/* Same as inode_has_perm, but pass explicit audit data containing
the path to help the auditing code to more easily generate the
pathname if needed. */
static inline int path_has_perm(const struct cred *cred,
struct path *path,
u32 av)
{
struct inode *inode = path->dentry->d_inode;
struct common_audit_data ad;
COMMON_AUDIT_DATA_INIT(&ad, PATH);
ad.u.path = *path;
return inode_has_perm(cred, inode, av, &ad, 0);
}
/* Check whether a task can use an open file descriptor to
access an inode in a given way. Check access to the
descriptor itself, and then use dentry_has_perm to
check a particular permission to the file.
Access to the descriptor is implicitly granted if it
has the same SID as the process. If av is zero, then
access to the file is not checked, e.g. for cases
where only the descriptor is affected like seek. */
static int file_has_perm(const struct cred *cred,
struct file *file,
u32 av)
{
struct file_security_struct *fsec = file->f_security;
struct inode *inode = file->f_path.dentry->d_inode;
struct common_audit_data ad;
u32 sid = cred_sid(cred);
int rc;
COMMON_AUDIT_DATA_INIT(&ad, PATH);
ad.u.path = file->f_path;
if (sid != fsec->sid) {
rc = avc_has_perm(sid, fsec->sid,
SECCLASS_FD,
FD__USE,
&ad);
if (rc)
goto out;
}
/* av is zero if only checking access to the descriptor. */
rc = 0;
if (av)
rc = inode_has_perm(cred, inode, av, &ad, 0);
out:
return rc;
}
/* Check whether a task can create a file. */
static int may_create(struct inode *dir,
struct dentry *dentry,
u16 tclass)
{
const struct task_security_struct *tsec = current_security();
struct inode_security_struct *dsec;
struct superblock_security_struct *sbsec;
u32 sid, newsid;
struct common_audit_data ad;
int rc;
dsec = dir->i_security;
sbsec = dir->i_sb->s_security;
sid = tsec->sid;
newsid = tsec->create_sid;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = dentry;
rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR,
DIR__ADD_NAME | DIR__SEARCH,
&ad);
if (rc)
return rc;
if (!newsid || !(sbsec->flags & SE_SBLABELSUPP)) {
rc = security_transition_sid(sid, dsec->sid, tclass,
&dentry->d_name, &newsid);
if (rc)
return rc;
}
rc = avc_has_perm(sid, newsid, tclass, FILE__CREATE, &ad);
if (rc)
return rc;
return avc_has_perm(newsid, sbsec->sid,
SECCLASS_FILESYSTEM,
FILESYSTEM__ASSOCIATE, &ad);
}
/* Check whether a task can create a key. */
static int may_create_key(u32 ksid,
struct task_struct *ctx)
{
u32 sid = task_sid(ctx);
return avc_has_perm(sid, ksid, SECCLASS_KEY, KEY__CREATE, NULL);
}
#define MAY_LINK 0
#define MAY_UNLINK 1
#define MAY_RMDIR 2
/* Check whether a task can link, unlink, or rmdir a file/directory. */
static int may_link(struct inode *dir,
struct dentry *dentry,
int kind)
{
struct inode_security_struct *dsec, *isec;
struct common_audit_data ad;
u32 sid = current_sid();
u32 av;
int rc;
dsec = dir->i_security;
isec = dentry->d_inode->i_security;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = dentry;
av = DIR__SEARCH;
av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR, av, &ad);
if (rc)
return rc;
switch (kind) {
case MAY_LINK:
av = FILE__LINK;
break;
case MAY_UNLINK:
av = FILE__UNLINK;
break;
case MAY_RMDIR:
av = DIR__RMDIR;
break;
default:
printk(KERN_WARNING "SELinux: %s: unrecognized kind %d\n",
__func__, kind);
return 0;
}
rc = avc_has_perm(sid, isec->sid, isec->sclass, av, &ad);
return rc;
}
static inline int may_rename(struct inode *old_dir,
struct dentry *old_dentry,
struct inode *new_dir,
struct dentry *new_dentry)
{
struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
struct common_audit_data ad;
u32 sid = current_sid();
u32 av;
int old_is_dir, new_is_dir;
int rc;
old_dsec = old_dir->i_security;
old_isec = old_dentry->d_inode->i_security;
old_is_dir = S_ISDIR(old_dentry->d_inode->i_mode);
new_dsec = new_dir->i_security;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = old_dentry;
rc = avc_has_perm(sid, old_dsec->sid, SECCLASS_DIR,
DIR__REMOVE_NAME | DIR__SEARCH, &ad);
if (rc)
return rc;
rc = avc_has_perm(sid, old_isec->sid,
old_isec->sclass, FILE__RENAME, &ad);
if (rc)
return rc;
if (old_is_dir && new_dir != old_dir) {
rc = avc_has_perm(sid, old_isec->sid,
old_isec->sclass, DIR__REPARENT, &ad);
if (rc)
return rc;
}
ad.u.dentry = new_dentry;
av = DIR__ADD_NAME | DIR__SEARCH;
if (new_dentry->d_inode)
av |= DIR__REMOVE_NAME;
rc = avc_has_perm(sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
if (rc)
return rc;
if (new_dentry->d_inode) {
new_isec = new_dentry->d_inode->i_security;
new_is_dir = S_ISDIR(new_dentry->d_inode->i_mode);
rc = avc_has_perm(sid, new_isec->sid,
new_isec->sclass,
(new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
if (rc)
return rc;
}
return 0;
}
/* Check whether a task can perform a filesystem operation. */
static int superblock_has_perm(const struct cred *cred,
struct super_block *sb,
u32 perms,
struct common_audit_data *ad)
{
struct superblock_security_struct *sbsec;
u32 sid = cred_sid(cred);
sbsec = sb->s_security;
return avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
}
/* Convert a Linux mode and permission mask to an access vector. */
static inline u32 file_mask_to_av(int mode, int mask)
{
u32 av = 0;
if ((mode & S_IFMT) != S_IFDIR) {
if (mask & MAY_EXEC)
av |= FILE__EXECUTE;
if (mask & MAY_READ)
av |= FILE__READ;
if (mask & MAY_APPEND)
av |= FILE__APPEND;
else if (mask & MAY_WRITE)
av |= FILE__WRITE;
} else {
if (mask & MAY_EXEC)
av |= DIR__SEARCH;
if (mask & MAY_WRITE)
av |= DIR__WRITE;
if (mask & MAY_READ)
av |= DIR__READ;
}
return av;
}
/* Convert a Linux file to an access vector. */
static inline u32 file_to_av(struct file *file)
{
u32 av = 0;
if (file->f_mode & FMODE_READ)
av |= FILE__READ;
if (file->f_mode & FMODE_WRITE) {
if (file->f_flags & O_APPEND)
av |= FILE__APPEND;
else
av |= FILE__WRITE;
}
if (!av) {
/*
* Special file opened with flags 3 for ioctl-only use.
*/
av = FILE__IOCTL;
}
return av;
}
/*
* Convert a file to an access vector and include the correct open
* open permission.
*/
static inline u32 open_file_to_av(struct file *file)
{
u32 av = file_to_av(file);
if (selinux_policycap_openperm)
av |= FILE__OPEN;
return av;
}
/* Hook functions begin here. */
static int selinux_ptrace_access_check(struct task_struct *child,
unsigned int mode)
{
int rc;
rc = cap_ptrace_access_check(child, mode);
if (rc)
return rc;
if (mode == PTRACE_MODE_READ) {
u32 sid = current_sid();
u32 csid = task_sid(child);
return avc_has_perm(sid, csid, SECCLASS_FILE, FILE__READ, NULL);
}
return current_has_perm(child, PROCESS__PTRACE);
}
static int selinux_ptrace_traceme(struct task_struct *parent)
{
int rc;
rc = cap_ptrace_traceme(parent);
if (rc)
return rc;
return task_has_perm(parent, current, PROCESS__PTRACE);
}
static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
kernel_cap_t *inheritable, kernel_cap_t *permitted)
{
int error;
error = current_has_perm(target, PROCESS__GETCAP);
if (error)
return error;
return cap_capget(target, effective, inheritable, permitted);
}
static int selinux_capset(struct cred *new, const struct cred *old,
const kernel_cap_t *effective,
const kernel_cap_t *inheritable,
const kernel_cap_t *permitted)
{
int error;
error = cap_capset(new, old,
effective, inheritable, permitted);
if (error)
return error;
return cred_has_perm(old, new, PROCESS__SETCAP);
}
/*
* (This comment used to live with the selinux_task_setuid hook,
* which was removed).
*
* Since setuid only affects the current process, and since the SELinux
* controls are not based on the Linux identity attributes, SELinux does not
* need to control this operation. However, SELinux does control the use of
* the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
*/
static int selinux_capable(struct task_struct *tsk, const struct cred *cred,
struct user_namespace *ns, int cap, int audit)
{
int rc;
rc = cap_capable(tsk, cred, ns, cap, audit);
if (rc)
return rc;
return task_has_capability(tsk, cred, cap, audit);
}
static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
{
const struct cred *cred = current_cred();
int rc = 0;
if (!sb)
return 0;
switch (cmds) {
case Q_SYNC:
case Q_QUOTAON:
case Q_QUOTAOFF:
case Q_SETINFO:
case Q_SETQUOTA:
rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
break;
case Q_GETFMT:
case Q_GETINFO:
case Q_GETQUOTA:
rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
break;
default:
rc = 0; /* let the kernel handle invalid cmds */
break;
}
return rc;
}
static int selinux_quota_on(struct dentry *dentry)
{
const struct cred *cred = current_cred();
return dentry_has_perm(cred, dentry, FILE__QUOTAON);
}
static int selinux_syslog(int type)
{
int rc;
switch (type) {
case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */
case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
rc = task_has_system(current, SYSTEM__SYSLOG_READ);
break;
case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
case SYSLOG_ACTION_CONSOLE_ON: /* Enable logging to console */
/* Set level of messages printed to console */
case SYSLOG_ACTION_CONSOLE_LEVEL:
rc = task_has_system(current, SYSTEM__SYSLOG_CONSOLE);
break;
case SYSLOG_ACTION_CLOSE: /* Close log */
case SYSLOG_ACTION_OPEN: /* Open log */
case SYSLOG_ACTION_READ: /* Read from log */
case SYSLOG_ACTION_READ_CLEAR: /* Read/clear last kernel messages */
case SYSLOG_ACTION_CLEAR: /* Clear ring buffer */
default:
rc = task_has_system(current, SYSTEM__SYSLOG_MOD);
break;
}
return rc;
}
/*
* Check that a process has enough memory to allocate a new virtual
* mapping. 0 means there is enough memory for the allocation to
* succeed and -ENOMEM implies there is not.
*
* Do not audit the selinux permission check, as this is applied to all
* processes that allocate mappings.
*/
static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
{
int rc, cap_sys_admin = 0;
rc = selinux_capable(current, current_cred(),
&init_user_ns, CAP_SYS_ADMIN,
SECURITY_CAP_NOAUDIT);
if (rc == 0)
cap_sys_admin = 1;
return __vm_enough_memory(mm, pages, cap_sys_admin);
}
/* binprm security operations */
static int selinux_bprm_set_creds(struct linux_binprm *bprm)
{
const struct task_security_struct *old_tsec;
struct task_security_struct *new_tsec;
struct inode_security_struct *isec;
struct common_audit_data ad;
struct inode *inode = bprm->file->f_path.dentry->d_inode;
int rc;
rc = cap_bprm_set_creds(bprm);
if (rc)
return rc;
/* SELinux context only depends on initial program or script and not
* the script interpreter */
if (bprm->cred_prepared)
return 0;
old_tsec = current_security();
new_tsec = bprm->cred->security;
isec = inode->i_security;
/* Default to the current task SID. */
new_tsec->sid = old_tsec->sid;
new_tsec->osid = old_tsec->sid;
/* Reset fs, key, and sock SIDs on execve. */
new_tsec->create_sid = 0;
new_tsec->keycreate_sid = 0;
new_tsec->sockcreate_sid = 0;
if (old_tsec->exec_sid) {
new_tsec->sid = old_tsec->exec_sid;
/* Reset exec SID on execve. */
new_tsec->exec_sid = 0;
} else {
/* Check for a default transition on this program. */
rc = security_transition_sid(old_tsec->sid, isec->sid,
SECCLASS_PROCESS, NULL,
&new_tsec->sid);
if (rc)
return rc;
}
COMMON_AUDIT_DATA_INIT(&ad, PATH);
ad.u.path = bprm->file->f_path;
if (bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID)
new_tsec->sid = old_tsec->sid;
if (new_tsec->sid == old_tsec->sid) {
rc = avc_has_perm(old_tsec->sid, isec->sid,
SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
if (rc)
return rc;
} else {
/* Check permissions for the transition. */
rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
if (rc)
return rc;
rc = avc_has_perm(new_tsec->sid, isec->sid,
SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
if (rc)
return rc;
/* Check for shared state */
if (bprm->unsafe & LSM_UNSAFE_SHARE) {
rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
SECCLASS_PROCESS, PROCESS__SHARE,
NULL);
if (rc)
return -EPERM;
}
/* Make sure that anyone attempting to ptrace over a task that
* changes its SID has the appropriate permit */
if (bprm->unsafe &
(LSM_UNSAFE_PTRACE | LSM_UNSAFE_PTRACE_CAP)) {
struct task_struct *tracer;
struct task_security_struct *sec;
u32 ptsid = 0;
rcu_read_lock();
tracer = ptrace_parent(current);
if (likely(tracer != NULL)) {
sec = __task_cred(tracer)->security;
ptsid = sec->sid;
}
rcu_read_unlock();
if (ptsid != 0) {
rc = avc_has_perm(ptsid, new_tsec->sid,
SECCLASS_PROCESS,
PROCESS__PTRACE, NULL);
if (rc)
return -EPERM;
}
}
/* Clear any possibly unsafe personality bits on exec: */
bprm->per_clear |= PER_CLEAR_ON_SETID;
}
return 0;
}
static int selinux_bprm_secureexec(struct linux_binprm *bprm)
{
const struct task_security_struct *tsec = current_security();
u32 sid, osid;
int atsecure = 0;
sid = tsec->sid;
osid = tsec->osid;
if (osid != sid) {
/* Enable secure mode for SIDs transitions unless
the noatsecure permission is granted between
the two SIDs, i.e. ahp returns 0. */
atsecure = avc_has_perm(osid, sid,
SECCLASS_PROCESS,
PROCESS__NOATSECURE, NULL);
}
return (atsecure || cap_bprm_secureexec(bprm));
}
/* Derived from fs/exec.c:flush_old_files. */
static inline void flush_unauthorized_files(const struct cred *cred,
struct files_struct *files)
{
struct common_audit_data ad;
struct file *file, *devnull = NULL;
struct tty_struct *tty;
struct fdtable *fdt;
long j = -1;
int drop_tty = 0;
tty = get_current_tty();
if (tty) {
spin_lock(&tty_files_lock);
if (!list_empty(&tty->tty_files)) {
struct tty_file_private *file_priv;
struct inode *inode;
/* Revalidate access to controlling tty.
Use inode_has_perm on the tty inode directly rather
than using file_has_perm, as this particular open
file may belong to another process and we are only
interested in the inode-based check here. */
file_priv = list_first_entry(&tty->tty_files,
struct tty_file_private, list);
file = file_priv->file;
inode = file->f_path.dentry->d_inode;
if (inode_has_perm_noadp(cred, inode,
FILE__READ | FILE__WRITE, 0)) {
drop_tty = 1;
}
}
spin_unlock(&tty_files_lock);
tty_kref_put(tty);
}
/* Reset controlling tty. */
if (drop_tty)
no_tty();
/* Revalidate access to inherited open files. */
COMMON_AUDIT_DATA_INIT(&ad, INODE);
spin_lock(&files->file_lock);
for (;;) {
unsigned long set, i;
int fd;
j++;
i = j * __NFDBITS;
fdt = files_fdtable(files);
if (i >= fdt->max_fds)
break;
set = fdt->open_fds->fds_bits[j];
if (!set)
continue;
spin_unlock(&files->file_lock);
for ( ; set ; i++, set >>= 1) {
if (set & 1) {
file = fget(i);
if (!file)
continue;
if (file_has_perm(cred,
file,
file_to_av(file))) {
sys_close(i);
fd = get_unused_fd();
if (fd != i) {
if (fd >= 0)
put_unused_fd(fd);
fput(file);
continue;
}
if (devnull) {
get_file(devnull);
} else {
devnull = dentry_open(
dget(selinux_null),
mntget(selinuxfs_mount),
O_RDWR, cred);
if (IS_ERR(devnull)) {
devnull = NULL;
put_unused_fd(fd);
fput(file);
continue;
}
}
fd_install(fd, devnull);
}
fput(file);
}
}
spin_lock(&files->file_lock);
}
spin_unlock(&files->file_lock);
}
/*
* Prepare a process for imminent new credential changes due to exec
*/
static void selinux_bprm_committing_creds(struct linux_binprm *bprm)
{
struct task_security_struct *new_tsec;
struct rlimit *rlim, *initrlim;
int rc, i;
new_tsec = bprm->cred->security;
if (new_tsec->sid == new_tsec->osid)
return;
/* Close files for which the new task SID is not authorized. */
flush_unauthorized_files(bprm->cred, current->files);
/* Always clear parent death signal on SID transitions. */
current->pdeath_signal = 0;
/* Check whether the new SID can inherit resource limits from the old
* SID. If not, reset all soft limits to the lower of the current
* task's hard limit and the init task's soft limit.
*
* Note that the setting of hard limits (even to lower them) can be
* controlled by the setrlimit check. The inclusion of the init task's
* soft limit into the computation is to avoid resetting soft limits
* higher than the default soft limit for cases where the default is
* lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
*/
rc = avc_has_perm(new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS,
PROCESS__RLIMITINH, NULL);
if (rc) {
/* protect against do_prlimit() */
task_lock(current);
for (i = 0; i < RLIM_NLIMITS; i++) {
rlim = current->signal->rlim + i;
initrlim = init_task.signal->rlim + i;
rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
}
task_unlock(current);
update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
}
}
/*
* Clean up the process immediately after the installation of new credentials
* due to exec
*/
static void selinux_bprm_committed_creds(struct linux_binprm *bprm)
{
const struct task_security_struct *tsec = current_security();
struct itimerval itimer;
u32 osid, sid;
int rc, i;
osid = tsec->osid;
sid = tsec->sid;
if (sid == osid)
return;
/* Check whether the new SID can inherit signal state from the old SID.
* If not, clear itimers to avoid subsequent signal generation and
* flush and unblock signals.
*
* This must occur _after_ the task SID has been updated so that any
* kill done after the flush will be checked against the new SID.
*/
rc = avc_has_perm(osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
if (rc) {
memset(&itimer, 0, sizeof itimer);
for (i = 0; i < 3; i++)
do_setitimer(i, &itimer, NULL);
spin_lock_irq(¤t->sighand->siglock);
if (!(current->signal->flags & SIGNAL_GROUP_EXIT)) {
__flush_signals(current);
flush_signal_handlers(current, 1);
sigemptyset(¤t->blocked);
}
spin_unlock_irq(¤t->sighand->siglock);
}
/* Wake up the parent if it is waiting so that it can recheck
* wait permission to the new task SID. */
read_lock(&tasklist_lock);
__wake_up_parent(current, current->real_parent);
read_unlock(&tasklist_lock);
}
/* superblock security operations */
static int selinux_sb_alloc_security(struct super_block *sb)
{
return superblock_alloc_security(sb);
}
static void selinux_sb_free_security(struct super_block *sb)
{
superblock_free_security(sb);
}
static inline int match_prefix(char *prefix, int plen, char *option, int olen)
{
if (plen > olen)
return 0;
return !memcmp(prefix, option, plen);
}
static inline int selinux_option(char *option, int len)
{
return (match_prefix(CONTEXT_STR, sizeof(CONTEXT_STR)-1, option, len) ||
match_prefix(FSCONTEXT_STR, sizeof(FSCONTEXT_STR)-1, option, len) ||
match_prefix(DEFCONTEXT_STR, sizeof(DEFCONTEXT_STR)-1, option, len) ||
match_prefix(ROOTCONTEXT_STR, sizeof(ROOTCONTEXT_STR)-1, option, len) ||
match_prefix(LABELSUPP_STR, sizeof(LABELSUPP_STR)-1, option, len));
}
static inline void take_option(char **to, char *from, int *first, int len)
{
if (!*first) {
**to = ',';
*to += 1;
} else
*first = 0;
memcpy(*to, from, len);
*to += len;
}
static inline void take_selinux_option(char **to, char *from, int *first,
int len)
{
int current_size = 0;
if (!*first) {
**to = '|';
*to += 1;
} else
*first = 0;
while (current_size < len) {
if (*from != '"') {
**to = *from;
*to += 1;
}
from += 1;
current_size += 1;
}
}
static int selinux_sb_copy_data(char *orig, char *copy)
{
int fnosec, fsec, rc = 0;
char *in_save, *in_curr, *in_end;
char *sec_curr, *nosec_save, *nosec;
int open_quote = 0;
in_curr = orig;
sec_curr = copy;
nosec = (char *)get_zeroed_page(GFP_KERNEL);
if (!nosec) {
rc = -ENOMEM;
goto out;
}
nosec_save = nosec;
fnosec = fsec = 1;
in_save = in_end = orig;
do {
if (*in_end == '"')
open_quote = !open_quote;
if ((*in_end == ',' && open_quote == 0) ||
*in_end == '\0') {
int len = in_end - in_curr;
if (selinux_option(in_curr, len))
take_selinux_option(&sec_curr, in_curr, &fsec, len);
else
take_option(&nosec, in_curr, &fnosec, len);
in_curr = in_end + 1;
}
} while (*in_end++);
strcpy(in_save, nosec_save);
free_page((unsigned long)nosec_save);
out:
return rc;
}
static int selinux_sb_remount(struct super_block *sb, void *data)
{
int rc, i, *flags;
struct security_mnt_opts opts;
char *secdata, **mount_options;
struct superblock_security_struct *sbsec = sb->s_security;
if (!(sbsec->flags & SE_SBINITIALIZED))
return 0;
if (!data)
return 0;
if (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
return 0;
security_init_mnt_opts(&opts);
secdata = alloc_secdata();
if (!secdata)
return -ENOMEM;
rc = selinux_sb_copy_data(data, secdata);
if (rc)
goto out_free_secdata;
rc = selinux_parse_opts_str(secdata, &opts);
if (rc)
goto out_free_secdata;
mount_options = opts.mnt_opts;
flags = opts.mnt_opts_flags;
for (i = 0; i < opts.num_mnt_opts; i++) {
u32 sid;
size_t len;
if (flags[i] == SE_SBLABELSUPP)
continue;
len = strlen(mount_options[i]);
rc = security_context_to_sid(mount_options[i], len, &sid);
if (rc) {
printk(KERN_WARNING "SELinux: security_context_to_sid"
"(%s) failed for (dev %s, type %s) errno=%d\n",
mount_options[i], sb->s_id, sb->s_type->name, rc);
goto out_free_opts;
}
rc = -EINVAL;
switch (flags[i]) {
case FSCONTEXT_MNT:
if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
goto out_bad_option;
break;
case CONTEXT_MNT:
if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
goto out_bad_option;
break;
case ROOTCONTEXT_MNT: {
struct inode_security_struct *root_isec;
root_isec = sb->s_root->d_inode->i_security;
if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
goto out_bad_option;
break;
}
case DEFCONTEXT_MNT:
if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
goto out_bad_option;
break;
default:
goto out_free_opts;
}
}
rc = 0;
out_free_opts:
security_free_mnt_opts(&opts);
out_free_secdata:
free_secdata(secdata);
return rc;
out_bad_option:
printk(KERN_WARNING "SELinux: unable to change security options "
"during remount (dev %s, type=%s)\n", sb->s_id,
sb->s_type->name);
goto out_free_opts;
}
static int selinux_sb_kern_mount(struct super_block *sb, int flags, void *data)
{
const struct cred *cred = current_cred();
struct common_audit_data ad;
int rc;
rc = superblock_doinit(sb, data);
if (rc)
return rc;
/* Allow all mounts performed by the kernel */
if (flags & MS_KERNMOUNT)
return 0;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = sb->s_root;
return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
}
static int selinux_sb_statfs(struct dentry *dentry)
{
const struct cred *cred = current_cred();
struct common_audit_data ad;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = dentry->d_sb->s_root;
return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
}
static int selinux_mount(char *dev_name,
struct path *path,
char *type,
unsigned long flags,
void *data)
{
const struct cred *cred = current_cred();
if (flags & MS_REMOUNT)
return superblock_has_perm(cred, path->mnt->mnt_sb,
FILESYSTEM__REMOUNT, NULL);
else
return path_has_perm(cred, path, FILE__MOUNTON);
}
static int selinux_umount(struct vfsmount *mnt, int flags)
{
const struct cred *cred = current_cred();
return superblock_has_perm(cred, mnt->mnt_sb,
FILESYSTEM__UNMOUNT, NULL);
}
/* inode security operations */
static int selinux_inode_alloc_security(struct inode *inode)
{
return inode_alloc_security(inode);
}
static void selinux_inode_free_security(struct inode *inode)
{
inode_free_security(inode);
}
static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
const struct qstr *qstr, char **name,
void **value, size_t *len)
{
const struct task_security_struct *tsec = current_security();
struct inode_security_struct *dsec;
struct superblock_security_struct *sbsec;
u32 sid, newsid, clen;
int rc;
char *namep = NULL, *context;
dsec = dir->i_security;
sbsec = dir->i_sb->s_security;
sid = tsec->sid;
newsid = tsec->create_sid;
if ((sbsec->flags & SE_SBINITIALIZED) &&
(sbsec->behavior == SECURITY_FS_USE_MNTPOINT))
newsid = sbsec->mntpoint_sid;
else if (!newsid || !(sbsec->flags & SE_SBLABELSUPP)) {
rc = security_transition_sid(sid, dsec->sid,
inode_mode_to_security_class(inode->i_mode),
qstr, &newsid);
if (rc) {
printk(KERN_WARNING "%s: "
"security_transition_sid failed, rc=%d (dev=%s "
"ino=%ld)\n",
__func__,
-rc, inode->i_sb->s_id, inode->i_ino);
return rc;
}
}
/* Possibly defer initialization to selinux_complete_init. */
if (sbsec->flags & SE_SBINITIALIZED) {
struct inode_security_struct *isec = inode->i_security;
isec->sclass = inode_mode_to_security_class(inode->i_mode);
isec->sid = newsid;
isec->initialized = 1;
}
if (!ss_initialized || !(sbsec->flags & SE_SBLABELSUPP))
return -EOPNOTSUPP;
if (name) {
namep = kstrdup(XATTR_SELINUX_SUFFIX, GFP_NOFS);
if (!namep)
return -ENOMEM;
*name = namep;
}
if (value && len) {
rc = security_sid_to_context_force(newsid, &context, &clen);
if (rc) {
kfree(namep);
return rc;
}
*value = context;
*len = clen;
}
return 0;
}
static int selinux_inode_create(struct inode *dir, struct dentry *dentry, int mask)
{
return may_create(dir, dentry, SECCLASS_FILE);
}
static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
{
return may_link(dir, old_dentry, MAY_LINK);
}
static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
{
return may_link(dir, dentry, MAY_UNLINK);
}
static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
{
return may_create(dir, dentry, SECCLASS_LNK_FILE);
}
static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, int mask)
{
return may_create(dir, dentry, SECCLASS_DIR);
}
static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
{
return may_link(dir, dentry, MAY_RMDIR);
}
static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t dev)
{
return may_create(dir, dentry, inode_mode_to_security_class(mode));
}
static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
struct inode *new_inode, struct dentry *new_dentry)
{
return may_rename(old_inode, old_dentry, new_inode, new_dentry);
}
static int selinux_inode_readlink(struct dentry *dentry)
{
const struct cred *cred = current_cred();
return dentry_has_perm(cred, dentry, FILE__READ);
}
static int selinux_inode_follow_link(struct dentry *dentry, struct nameidata *nameidata)
{
const struct cred *cred = current_cred();
return dentry_has_perm(cred, dentry, FILE__READ);
}
static int selinux_inode_permission(struct inode *inode, int mask)
{
const struct cred *cred = current_cred();
struct common_audit_data ad;
u32 perms;
bool from_access;
unsigned flags = mask & MAY_NOT_BLOCK;
from_access = mask & MAY_ACCESS;
mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
/* No permission to check. Existence test. */
if (!mask)
return 0;
COMMON_AUDIT_DATA_INIT(&ad, INODE);
ad.u.inode = inode;
if (from_access)
ad.selinux_audit_data.auditdeny |= FILE__AUDIT_ACCESS;
perms = file_mask_to_av(inode->i_mode, mask);
return inode_has_perm(cred, inode, perms, &ad, flags);
}
static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
{
const struct cred *cred = current_cred();
unsigned int ia_valid = iattr->ia_valid;
/* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
if (ia_valid & ATTR_FORCE) {
ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
ATTR_FORCE);
if (!ia_valid)
return 0;
}
if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
return dentry_has_perm(cred, dentry, FILE__SETATTR);
return dentry_has_perm(cred, dentry, FILE__WRITE);
}
static int selinux_inode_getattr(struct vfsmount *mnt, struct dentry *dentry)
{
const struct cred *cred = current_cred();
struct path path;
path.dentry = dentry;
path.mnt = mnt;
return path_has_perm(cred, &path, FILE__GETATTR);
}
static int selinux_inode_setotherxattr(struct dentry *dentry, const char *name)
{
const struct cred *cred = current_cred();
if (!strncmp(name, XATTR_SECURITY_PREFIX,
sizeof XATTR_SECURITY_PREFIX - 1)) {
if (!strcmp(name, XATTR_NAME_CAPS)) {
if (!capable(CAP_SETFCAP))
return -EPERM;
} else if (!capable(CAP_SYS_ADMIN)) {
/* A different attribute in the security namespace.
Restrict to administrator. */
return -EPERM;
}
}
/* Not an attribute we recognize, so just check the
ordinary setattr permission. */
return dentry_has_perm(cred, dentry, FILE__SETATTR);
}
static int selinux_inode_setxattr(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags)
{
struct inode *inode = dentry->d_inode;
struct inode_security_struct *isec = inode->i_security;
struct superblock_security_struct *sbsec;
struct common_audit_data ad;
u32 newsid, sid = current_sid();
int rc = 0;
if (strcmp(name, XATTR_NAME_SELINUX))
return selinux_inode_setotherxattr(dentry, name);
sbsec = inode->i_sb->s_security;
if (!(sbsec->flags & SE_SBLABELSUPP))
return -EOPNOTSUPP;
if (!inode_owner_or_capable(inode))
return -EPERM;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = dentry;
rc = avc_has_perm(sid, isec->sid, isec->sclass,
FILE__RELABELFROM, &ad);
if (rc)
return rc;
rc = security_context_to_sid(value, size, &newsid);
if (rc == -EINVAL) {
if (!capable(CAP_MAC_ADMIN))
return rc;
rc = security_context_to_sid_force(value, size, &newsid);
}
if (rc)
return rc;
rc = avc_has_perm(sid, newsid, isec->sclass,
FILE__RELABELTO, &ad);
if (rc)
return rc;
rc = security_validate_transition(isec->sid, newsid, sid,
isec->sclass);
if (rc)
return rc;
return avc_has_perm(newsid,
sbsec->sid,
SECCLASS_FILESYSTEM,
FILESYSTEM__ASSOCIATE,
&ad);
}
static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
const void *value, size_t size,
int flags)
{
struct inode *inode = dentry->d_inode;
struct inode_security_struct *isec = inode->i_security;
u32 newsid;
int rc;
if (strcmp(name, XATTR_NAME_SELINUX)) {
/* Not an attribute we recognize, so nothing to do. */
return;
}
rc = security_context_to_sid_force(value, size, &newsid);
if (rc) {
printk(KERN_ERR "SELinux: unable to map context to SID"
"for (%s, %lu), rc=%d\n",
inode->i_sb->s_id, inode->i_ino, -rc);
return;
}
isec->sid = newsid;
return;
}
static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
{
const struct cred *cred = current_cred();
return dentry_has_perm(cred, dentry, FILE__GETATTR);
}
static int selinux_inode_listxattr(struct dentry *dentry)
{
const struct cred *cred = current_cred();
return dentry_has_perm(cred, dentry, FILE__GETATTR);
}
static int selinux_inode_removexattr(struct dentry *dentry, const char *name)
{
if (strcmp(name, XATTR_NAME_SELINUX))
return selinux_inode_setotherxattr(dentry, name);
/* No one is allowed to remove a SELinux security label.
You can change the label, but all data must be labeled. */
return -EACCES;
}
/*
* Copy the inode security context value to the user.
*
* Permission check is handled by selinux_inode_getxattr hook.
*/
static int selinux_inode_getsecurity(const struct inode *inode, const char *name, void **buffer, bool alloc)
{
u32 size;
int error;
char *context = NULL;
struct inode_security_struct *isec = inode->i_security;
if (strcmp(name, XATTR_SELINUX_SUFFIX))
return -EOPNOTSUPP;
/*
* If the caller has CAP_MAC_ADMIN, then get the raw context
* value even if it is not defined by current policy; otherwise,
* use the in-core value under current policy.
* Use the non-auditing forms of the permission checks since
* getxattr may be called by unprivileged processes commonly
* and lack of permission just means that we fall back to the
* in-core context value, not a denial.
*/
error = selinux_capable(current, current_cred(),
&init_user_ns, CAP_MAC_ADMIN,
SECURITY_CAP_NOAUDIT);
if (!error)
error = security_sid_to_context_force(isec->sid, &context,
&size);
else
error = security_sid_to_context(isec->sid, &context, &size);
if (error)
return error;
error = size;
if (alloc) {
*buffer = context;
goto out_nofree;
}
kfree(context);
out_nofree:
return error;
}
static int selinux_inode_setsecurity(struct inode *inode, const char *name,
const void *value, size_t size, int flags)
{
struct inode_security_struct *isec = inode->i_security;
u32 newsid;
int rc;
if (strcmp(name, XATTR_SELINUX_SUFFIX))
return -EOPNOTSUPP;
if (!value || !size)
return -EACCES;
rc = security_context_to_sid((void *)value, size, &newsid);
if (rc)
return rc;
isec->sid = newsid;
isec->initialized = 1;
return 0;
}
static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
{
const int len = sizeof(XATTR_NAME_SELINUX);
if (buffer && len <= buffer_size)
memcpy(buffer, XATTR_NAME_SELINUX, len);
return len;
}
static void selinux_inode_getsecid(const struct inode *inode, u32 *secid)
{
struct inode_security_struct *isec = inode->i_security;
*secid = isec->sid;
}
/* file security operations */
static int selinux_revalidate_file_permission(struct file *file, int mask)
{
const struct cred *cred = current_cred();
struct inode *inode = file->f_path.dentry->d_inode;
/* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
mask |= MAY_APPEND;
return file_has_perm(cred, file,
file_mask_to_av(inode->i_mode, mask));
}
static int selinux_file_permission(struct file *file, int mask)
{
struct inode *inode = file->f_path.dentry->d_inode;
struct file_security_struct *fsec = file->f_security;
struct inode_security_struct *isec = inode->i_security;
u32 sid = current_sid();
if (!mask)
/* No permission to check. Existence test. */
return 0;
if (sid == fsec->sid && fsec->isid == isec->sid &&
fsec->pseqno == avc_policy_seqno())
/* No change since dentry_open check. */
return 0;
return selinux_revalidate_file_permission(file, mask);
}
static int selinux_file_alloc_security(struct file *file)
{
return file_alloc_security(file);
}
static void selinux_file_free_security(struct file *file)
{
file_free_security(file);
}
static int selinux_file_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
const struct cred *cred = current_cred();
int error = 0;
switch (cmd) {
case FIONREAD:
/* fall through */
case FIBMAP:
/* fall through */
case FIGETBSZ:
/* fall through */
case EXT2_IOC_GETFLAGS:
/* fall through */
case EXT2_IOC_GETVERSION:
error = file_has_perm(cred, file, FILE__GETATTR);
break;
case EXT2_IOC_SETFLAGS:
/* fall through */
case EXT2_IOC_SETVERSION:
error = file_has_perm(cred, file, FILE__SETATTR);
break;
/* sys_ioctl() checks */
case FIONBIO:
/* fall through */
case FIOASYNC:
error = file_has_perm(cred, file, 0);
break;
case KDSKBENT:
case KDSKBSENT:
error = task_has_capability(current, cred, CAP_SYS_TTY_CONFIG,
SECURITY_CAP_AUDIT);
break;
/* default case assumes that the command will go
* to the file's ioctl() function.
*/
default:
error = file_has_perm(cred, file, FILE__IOCTL);
}
return error;
}
static int default_noexec;
static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
{
const struct cred *cred = current_cred();
int rc = 0;
if (default_noexec &&
(prot & PROT_EXEC) && (!file || (!shared && (prot & PROT_WRITE)))) {
/*
* We are making executable an anonymous mapping or a
* private file mapping that will also be writable.
* This has an additional check.
*/
rc = cred_has_perm(cred, cred, PROCESS__EXECMEM);
if (rc)
goto error;
}
if (file) {
/* read access is always possible with a mapping */
u32 av = FILE__READ;
/* write access only matters if the mapping is shared */
if (shared && (prot & PROT_WRITE))
av |= FILE__WRITE;
if (prot & PROT_EXEC)
av |= FILE__EXECUTE;
return file_has_perm(cred, file, av);
}
error:
return rc;
}
static int selinux_file_mmap(struct file *file, unsigned long reqprot,
unsigned long prot, unsigned long flags,
unsigned long addr, unsigned long addr_only)
{
int rc = 0;
u32 sid = current_sid();
/*
* notice that we are intentionally putting the SELinux check before
* the secondary cap_file_mmap check. This is such a likely attempt
* at bad behaviour/exploit that we always want to get the AVC, even
* if DAC would have also denied the operation.
*/
if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
rc = avc_has_perm(sid, sid, SECCLASS_MEMPROTECT,
MEMPROTECT__MMAP_ZERO, NULL);
if (rc)
return rc;
}
/* do DAC check on address space usage */
rc = cap_file_mmap(file, reqprot, prot, flags, addr, addr_only);
if (rc || addr_only)
return rc;
if (selinux_checkreqprot)
prot = reqprot;
return file_map_prot_check(file, prot,
(flags & MAP_TYPE) == MAP_SHARED);
}
static int selinux_file_mprotect(struct vm_area_struct *vma,
unsigned long reqprot,
unsigned long prot)
{
const struct cred *cred = current_cred();
if (selinux_checkreqprot)
prot = reqprot;
if (default_noexec &&
(prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
int rc = 0;
if (vma->vm_start >= vma->vm_mm->start_brk &&
vma->vm_end <= vma->vm_mm->brk) {
rc = cred_has_perm(cred, cred, PROCESS__EXECHEAP);
} else if (!vma->vm_file &&
vma->vm_start <= vma->vm_mm->start_stack &&
vma->vm_end >= vma->vm_mm->start_stack) {
rc = current_has_perm(current, PROCESS__EXECSTACK);
} else if (vma->vm_file && vma->anon_vma) {
/*
* We are making executable a file mapping that has
* had some COW done. Since pages might have been
* written, check ability to execute the possibly
* modified content. This typically should only
* occur for text relocations.
*/
rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD);
}
if (rc)
return rc;
}
return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
}
static int selinux_file_lock(struct file *file, unsigned int cmd)
{
const struct cred *cred = current_cred();
return file_has_perm(cred, file, FILE__LOCK);
}
static int selinux_file_fcntl(struct file *file, unsigned int cmd,
unsigned long arg)
{
const struct cred *cred = current_cred();
int err = 0;
switch (cmd) {
case F_SETFL:
if (!file->f_path.dentry || !file->f_path.dentry->d_inode) {
err = -EINVAL;
break;
}
if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
err = file_has_perm(cred, file, FILE__WRITE);
break;
}
/* fall through */
case F_SETOWN:
case F_SETSIG:
case F_GETFL:
case F_GETOWN:
case F_GETSIG:
/* Just check FD__USE permission */
err = file_has_perm(cred, file, 0);
break;
case F_GETLK:
case F_SETLK:
case F_SETLKW:
#if BITS_PER_LONG == 32
case F_GETLK64:
case F_SETLK64:
case F_SETLKW64:
#endif
if (!file->f_path.dentry || !file->f_path.dentry->d_inode) {
err = -EINVAL;
break;
}
err = file_has_perm(cred, file, FILE__LOCK);
break;
}
return err;
}
static int selinux_file_set_fowner(struct file *file)
{
struct file_security_struct *fsec;
fsec = file->f_security;
fsec->fown_sid = current_sid();
return 0;
}
static int selinux_file_send_sigiotask(struct task_struct *tsk,
struct fown_struct *fown, int signum)
{
struct file *file;
u32 sid = task_sid(tsk);
u32 perm;
struct file_security_struct *fsec;
/* struct fown_struct is never outside the context of a struct file */
file = container_of(fown, struct file, f_owner);
fsec = file->f_security;
if (!signum)
perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
else
perm = signal_to_av(signum);
return avc_has_perm(fsec->fown_sid, sid,
SECCLASS_PROCESS, perm, NULL);
}
static int selinux_file_receive(struct file *file)
{
const struct cred *cred = current_cred();
return file_has_perm(cred, file, file_to_av(file));
}
static int selinux_dentry_open(struct file *file, const struct cred *cred)
{
struct file_security_struct *fsec;
struct inode *inode;
struct inode_security_struct *isec;
inode = file->f_path.dentry->d_inode;
fsec = file->f_security;
isec = inode->i_security;
/*
* Save inode label and policy sequence number
* at open-time so that selinux_file_permission
* can determine whether revalidation is necessary.
* Task label is already saved in the file security
* struct as its SID.
*/
fsec->isid = isec->sid;
fsec->pseqno = avc_policy_seqno();
/*
* Since the inode label or policy seqno may have changed
* between the selinux_inode_permission check and the saving
* of state above, recheck that access is still permitted.
* Otherwise, access might never be revalidated against the
* new inode label or new policy.
* This check is not redundant - do not remove.
*/
return inode_has_perm_noadp(cred, inode, open_file_to_av(file), 0);
}
/* task security operations */
static int selinux_task_create(unsigned long clone_flags)
{
return current_has_perm(current, PROCESS__FORK);
}
/*
* allocate the SELinux part of blank credentials
*/
static int selinux_cred_alloc_blank(struct cred *cred, gfp_t gfp)
{
struct task_security_struct *tsec;
tsec = kzalloc(sizeof(struct task_security_struct), gfp);
if (!tsec)
return -ENOMEM;
cred->security = tsec;
return 0;
}
/*
* detach and free the LSM part of a set of credentials
*/
static void selinux_cred_free(struct cred *cred)
{
struct task_security_struct *tsec = cred->security;
/*
* cred->security == NULL if security_cred_alloc_blank() or
* security_prepare_creds() returned an error.
*/
BUG_ON(cred->security && (unsigned long) cred->security < PAGE_SIZE);
cred->security = (void *) 0x7UL;
kfree(tsec);
}
/*
* prepare a new set of credentials for modification
*/
static int selinux_cred_prepare(struct cred *new, const struct cred *old,
gfp_t gfp)
{
const struct task_security_struct *old_tsec;
struct task_security_struct *tsec;
old_tsec = old->security;
tsec = kmemdup(old_tsec, sizeof(struct task_security_struct), gfp);
if (!tsec)
return -ENOMEM;
new->security = tsec;
return 0;
}
/*
* transfer the SELinux data to a blank set of creds
*/
static void selinux_cred_transfer(struct cred *new, const struct cred *old)
{
const struct task_security_struct *old_tsec = old->security;
struct task_security_struct *tsec = new->security;
*tsec = *old_tsec;
}
/*
* set the security data for a kernel service
* - all the creation contexts are set to unlabelled
*/
static int selinux_kernel_act_as(struct cred *new, u32 secid)
{
struct task_security_struct *tsec = new->security;
u32 sid = current_sid();
int ret;
ret = avc_has_perm(sid, secid,
SECCLASS_KERNEL_SERVICE,
KERNEL_SERVICE__USE_AS_OVERRIDE,
NULL);
if (ret == 0) {
tsec->sid = secid;
tsec->create_sid = 0;
tsec->keycreate_sid = 0;
tsec->sockcreate_sid = 0;
}
return ret;
}
/*
* set the file creation context in a security record to the same as the
* objective context of the specified inode
*/
static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
{
struct inode_security_struct *isec = inode->i_security;
struct task_security_struct *tsec = new->security;
u32 sid = current_sid();
int ret;
ret = avc_has_perm(sid, isec->sid,
SECCLASS_KERNEL_SERVICE,
KERNEL_SERVICE__CREATE_FILES_AS,
NULL);
if (ret == 0)
tsec->create_sid = isec->sid;
return ret;
}
static int selinux_kernel_module_request(char *kmod_name)
{
u32 sid;
struct common_audit_data ad;
sid = task_sid(current);
COMMON_AUDIT_DATA_INIT(&ad, KMOD);
ad.u.kmod_name = kmod_name;
return avc_has_perm(sid, SECINITSID_KERNEL, SECCLASS_SYSTEM,
SYSTEM__MODULE_REQUEST, &ad);
}
static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
{
return current_has_perm(p, PROCESS__SETPGID);
}
static int selinux_task_getpgid(struct task_struct *p)
{
return current_has_perm(p, PROCESS__GETPGID);
}
static int selinux_task_getsid(struct task_struct *p)
{
return current_has_perm(p, PROCESS__GETSESSION);
}
static void selinux_task_getsecid(struct task_struct *p, u32 *secid)
{
*secid = task_sid(p);
}
static int selinux_task_setnice(struct task_struct *p, int nice)
{
int rc;
rc = cap_task_setnice(p, nice);
if (rc)
return rc;
return current_has_perm(p, PROCESS__SETSCHED);
}
static int selinux_task_setioprio(struct task_struct *p, int ioprio)
{
int rc;
rc = cap_task_setioprio(p, ioprio);
if (rc)
return rc;
return current_has_perm(p, PROCESS__SETSCHED);
}
static int selinux_task_getioprio(struct task_struct *p)
{
return current_has_perm(p, PROCESS__GETSCHED);
}
static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
struct rlimit *new_rlim)
{
struct rlimit *old_rlim = p->signal->rlim + resource;
/* Control the ability to change the hard limit (whether
lowering or raising it), so that the hard limit can
later be used as a safe reset point for the soft limit
upon context transitions. See selinux_bprm_committing_creds. */
if (old_rlim->rlim_max != new_rlim->rlim_max)
return current_has_perm(p, PROCESS__SETRLIMIT);
return 0;
}
static int selinux_task_setscheduler(struct task_struct *p)
{
int rc;
rc = cap_task_setscheduler(p);
if (rc)
return rc;
return current_has_perm(p, PROCESS__SETSCHED);
}
static int selinux_task_getscheduler(struct task_struct *p)
{
return current_has_perm(p, PROCESS__GETSCHED);
}
static int selinux_task_movememory(struct task_struct *p)
{
return current_has_perm(p, PROCESS__SETSCHED);
}
static int selinux_task_kill(struct task_struct *p, struct siginfo *info,
int sig, u32 secid)
{
u32 perm;
int rc;
if (!sig)
perm = PROCESS__SIGNULL; /* null signal; existence test */
else
perm = signal_to_av(sig);
if (secid)
rc = avc_has_perm(secid, task_sid(p),
SECCLASS_PROCESS, perm, NULL);
else
rc = current_has_perm(p, perm);
return rc;
}
static int selinux_task_wait(struct task_struct *p)
{
return task_has_perm(p, current, PROCESS__SIGCHLD);
}
static void selinux_task_to_inode(struct task_struct *p,
struct inode *inode)
{
struct inode_security_struct *isec = inode->i_security;
u32 sid = task_sid(p);
isec->sid = sid;
isec->initialized = 1;
}
/* Returns error only if unable to parse addresses */
static int selinux_parse_skb_ipv4(struct sk_buff *skb,
struct common_audit_data *ad, u8 *proto)
{
int offset, ihlen, ret = -EINVAL;
struct iphdr _iph, *ih;
offset = skb_network_offset(skb);
ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
if (ih == NULL)
goto out;
ihlen = ih->ihl * 4;
if (ihlen < sizeof(_iph))
goto out;
ad->u.net.v4info.saddr = ih->saddr;
ad->u.net.v4info.daddr = ih->daddr;
ret = 0;
if (proto)
*proto = ih->protocol;
switch (ih->protocol) {
case IPPROTO_TCP: {
struct tcphdr _tcph, *th;
if (ntohs(ih->frag_off) & IP_OFFSET)
break;
offset += ihlen;
th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
if (th == NULL)
break;
ad->u.net.sport = th->source;
ad->u.net.dport = th->dest;
break;
}
case IPPROTO_UDP: {
struct udphdr _udph, *uh;
if (ntohs(ih->frag_off) & IP_OFFSET)
break;
offset += ihlen;
uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
if (uh == NULL)
break;
ad->u.net.sport = uh->source;
ad->u.net.dport = uh->dest;
break;
}
case IPPROTO_DCCP: {
struct dccp_hdr _dccph, *dh;
if (ntohs(ih->frag_off) & IP_OFFSET)
break;
offset += ihlen;
dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
if (dh == NULL)
break;
ad->u.net.sport = dh->dccph_sport;
ad->u.net.dport = dh->dccph_dport;
break;
}
default:
break;
}
out:
return ret;
}
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
/* Returns error only if unable to parse addresses */
static int selinux_parse_skb_ipv6(struct sk_buff *skb,
struct common_audit_data *ad, u8 *proto)
{
u8 nexthdr;
int ret = -EINVAL, offset;
struct ipv6hdr _ipv6h, *ip6;
offset = skb_network_offset(skb);
ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
if (ip6 == NULL)
goto out;
ipv6_addr_copy(&ad->u.net.v6info.saddr, &ip6->saddr);
ipv6_addr_copy(&ad->u.net.v6info.daddr, &ip6->daddr);
ret = 0;
nexthdr = ip6->nexthdr;
offset += sizeof(_ipv6h);
offset = ipv6_skip_exthdr(skb, offset, &nexthdr);
if (offset < 0)
goto out;
if (proto)
*proto = nexthdr;
switch (nexthdr) {
case IPPROTO_TCP: {
struct tcphdr _tcph, *th;
th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
if (th == NULL)
break;
ad->u.net.sport = th->source;
ad->u.net.dport = th->dest;
break;
}
case IPPROTO_UDP: {
struct udphdr _udph, *uh;
uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
if (uh == NULL)
break;
ad->u.net.sport = uh->source;
ad->u.net.dport = uh->dest;
break;
}
case IPPROTO_DCCP: {
struct dccp_hdr _dccph, *dh;
dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
if (dh == NULL)
break;
ad->u.net.sport = dh->dccph_sport;
ad->u.net.dport = dh->dccph_dport;
break;
}
/* includes fragments */
default:
break;
}
out:
return ret;
}
#endif /* IPV6 */
static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
char **_addrp, int src, u8 *proto)
{
char *addrp;
int ret;
switch (ad->u.net.family) {
case PF_INET:
ret = selinux_parse_skb_ipv4(skb, ad, proto);
if (ret)
goto parse_error;
addrp = (char *)(src ? &ad->u.net.v4info.saddr :
&ad->u.net.v4info.daddr);
goto okay;
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
case PF_INET6:
ret = selinux_parse_skb_ipv6(skb, ad, proto);
if (ret)
goto parse_error;
addrp = (char *)(src ? &ad->u.net.v6info.saddr :
&ad->u.net.v6info.daddr);
goto okay;
#endif /* IPV6 */
default:
addrp = NULL;
goto okay;
}
parse_error:
printk(KERN_WARNING
"SELinux: failure in selinux_parse_skb(),"
" unable to parse packet\n");
return ret;
okay:
if (_addrp)
*_addrp = addrp;
return 0;
}
/**
* selinux_skb_peerlbl_sid - Determine the peer label of a packet
* @skb: the packet
* @family: protocol family
* @sid: the packet's peer label SID
*
* Description:
* Check the various different forms of network peer labeling and determine
* the peer label/SID for the packet; most of the magic actually occurs in
* the security server function security_net_peersid_cmp(). The function
* returns zero if the value in @sid is valid (although it may be SECSID_NULL)
* or -EACCES if @sid is invalid due to inconsistencies with the different
* peer labels.
*
*/
static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
{
int err;
u32 xfrm_sid;
u32 nlbl_sid;
u32 nlbl_type;
selinux_skb_xfrm_sid(skb, &xfrm_sid);
selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
err = security_net_peersid_resolve(nlbl_sid, nlbl_type, xfrm_sid, sid);
if (unlikely(err)) {
printk(KERN_WARNING
"SELinux: failure in selinux_skb_peerlbl_sid(),"
" unable to determine packet's peer label\n");
return -EACCES;
}
return 0;
}
/**
* selinux_conn_sid - Determine the child socket label for a connection
* @sk_sid: the parent socket's SID
* @skb_sid: the packet's SID
* @conn_sid: the resulting connection SID
*
* If @skb_sid is valid then the user:role:type information from @sk_sid is
* combined with the MLS information from @skb_sid in order to create
* @conn_sid. If @skb_sid is not valid then then @conn_sid is simply a copy
* of @sk_sid. Returns zero on success, negative values on failure.
*
*/
static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
{
int err = 0;
if (skb_sid != SECSID_NULL)
err = security_sid_mls_copy(sk_sid, skb_sid, conn_sid);
else
*conn_sid = sk_sid;
return err;
}
/* socket security operations */
static int socket_sockcreate_sid(const struct task_security_struct *tsec,
u16 secclass, u32 *socksid)
{
if (tsec->sockcreate_sid > SECSID_NULL) {
*socksid = tsec->sockcreate_sid;
return 0;
}
return security_transition_sid(tsec->sid, tsec->sid, secclass, NULL,
socksid);
}
static int sock_has_perm(struct task_struct *task, struct sock *sk, u32 perms)
{
struct sk_security_struct *sksec = sk->sk_security;
struct common_audit_data ad;
u32 tsid = task_sid(task);
if (sksec->sid == SECINITSID_KERNEL)
return 0;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.sk = sk;
return avc_has_perm(tsid, sksec->sid, sksec->sclass, perms, &ad);
}
static int selinux_socket_create(int family, int type,
int protocol, int kern)
{
const struct task_security_struct *tsec = current_security();
u32 newsid;
u16 secclass;
int rc;
if (kern)
return 0;
secclass = socket_type_to_security_class(family, type, protocol);
rc = socket_sockcreate_sid(tsec, secclass, &newsid);
if (rc)
return rc;
return avc_has_perm(tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
}
static int selinux_socket_post_create(struct socket *sock, int family,
int type, int protocol, int kern)
{
const struct task_security_struct *tsec = current_security();
struct inode_security_struct *isec = SOCK_INODE(sock)->i_security;
struct sk_security_struct *sksec;
int err = 0;
isec->sclass = socket_type_to_security_class(family, type, protocol);
if (kern)
isec->sid = SECINITSID_KERNEL;
else {
err = socket_sockcreate_sid(tsec, isec->sclass, &(isec->sid));
if (err)
return err;
}
isec->initialized = 1;
if (sock->sk) {
sksec = sock->sk->sk_security;
sksec->sid = isec->sid;
sksec->sclass = isec->sclass;
err = selinux_netlbl_socket_post_create(sock->sk, family);
}
return err;
}
/* Range of port numbers used to automatically bind.
Need to determine whether we should perform a name_bind
permission check between the socket and the port number. */
static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
{
struct sock *sk = sock->sk;
u16 family;
int err;
err = sock_has_perm(current, sk, SOCKET__BIND);
if (err)
goto out;
/*
* If PF_INET or PF_INET6, check name_bind permission for the port.
* Multiple address binding for SCTP is not supported yet: we just
* check the first address now.
*/
family = sk->sk_family;
if (family == PF_INET || family == PF_INET6) {
char *addrp;
struct sk_security_struct *sksec = sk->sk_security;
struct common_audit_data ad;
struct sockaddr_in *addr4 = NULL;
struct sockaddr_in6 *addr6 = NULL;
unsigned short snum;
u32 sid, node_perm;
if (family == PF_INET) {
addr4 = (struct sockaddr_in *)address;
snum = ntohs(addr4->sin_port);
addrp = (char *)&addr4->sin_addr.s_addr;
} else {
addr6 = (struct sockaddr_in6 *)address;
snum = ntohs(addr6->sin6_port);
addrp = (char *)&addr6->sin6_addr.s6_addr;
}
if (snum) {
int low, high;
inet_get_local_port_range(&low, &high);
if (snum < max(PROT_SOCK, low) || snum > high) {
err = sel_netport_sid(sk->sk_protocol,
snum, &sid);
if (err)
goto out;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.sport = htons(snum);
ad.u.net.family = family;
err = avc_has_perm(sksec->sid, sid,
sksec->sclass,
SOCKET__NAME_BIND, &ad);
if (err)
goto out;
}
}
switch (sksec->sclass) {
case SECCLASS_TCP_SOCKET:
node_perm = TCP_SOCKET__NODE_BIND;
break;
case SECCLASS_UDP_SOCKET:
node_perm = UDP_SOCKET__NODE_BIND;
break;
case SECCLASS_DCCP_SOCKET:
node_perm = DCCP_SOCKET__NODE_BIND;
break;
default:
node_perm = RAWIP_SOCKET__NODE_BIND;
break;
}
err = sel_netnode_sid(addrp, family, &sid);
if (err)
goto out;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.sport = htons(snum);
ad.u.net.family = family;
if (family == PF_INET)
ad.u.net.v4info.saddr = addr4->sin_addr.s_addr;
else
ipv6_addr_copy(&ad.u.net.v6info.saddr, &addr6->sin6_addr);
err = avc_has_perm(sksec->sid, sid,
sksec->sclass, node_perm, &ad);
if (err)
goto out;
}
out:
return err;
}
static int selinux_socket_connect(struct socket *sock, struct sockaddr *address, int addrlen)
{
struct sock *sk = sock->sk;
struct sk_security_struct *sksec = sk->sk_security;
int err;
err = sock_has_perm(current, sk, SOCKET__CONNECT);
if (err)
return err;
/*
* If a TCP or DCCP socket, check name_connect permission for the port.
*/
if (sksec->sclass == SECCLASS_TCP_SOCKET ||
sksec->sclass == SECCLASS_DCCP_SOCKET) {
struct common_audit_data ad;
struct sockaddr_in *addr4 = NULL;
struct sockaddr_in6 *addr6 = NULL;
unsigned short snum;
u32 sid, perm;
if (sk->sk_family == PF_INET) {
addr4 = (struct sockaddr_in *)address;
if (addrlen < sizeof(struct sockaddr_in))
return -EINVAL;
snum = ntohs(addr4->sin_port);
} else {
addr6 = (struct sockaddr_in6 *)address;
if (addrlen < SIN6_LEN_RFC2133)
return -EINVAL;
snum = ntohs(addr6->sin6_port);
}
err = sel_netport_sid(sk->sk_protocol, snum, &sid);
if (err)
goto out;
perm = (sksec->sclass == SECCLASS_TCP_SOCKET) ?
TCP_SOCKET__NAME_CONNECT : DCCP_SOCKET__NAME_CONNECT;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.dport = htons(snum);
ad.u.net.family = sk->sk_family;
err = avc_has_perm(sksec->sid, sid, sksec->sclass, perm, &ad);
if (err)
goto out;
}
err = selinux_netlbl_socket_connect(sk, address);
out:
return err;
}
static int selinux_socket_listen(struct socket *sock, int backlog)
{
return sock_has_perm(current, sock->sk, SOCKET__LISTEN);
}
static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
{
int err;
struct inode_security_struct *isec;
struct inode_security_struct *newisec;
err = sock_has_perm(current, sock->sk, SOCKET__ACCEPT);
if (err)
return err;
newisec = SOCK_INODE(newsock)->i_security;
isec = SOCK_INODE(sock)->i_security;
newisec->sclass = isec->sclass;
newisec->sid = isec->sid;
newisec->initialized = 1;
return 0;
}
static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
int size)
{
return sock_has_perm(current, sock->sk, SOCKET__WRITE);
}
static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
int size, int flags)
{
return sock_has_perm(current, sock->sk, SOCKET__READ);
}
static int selinux_socket_getsockname(struct socket *sock)
{
return sock_has_perm(current, sock->sk, SOCKET__GETATTR);
}
static int selinux_socket_getpeername(struct socket *sock)
{
return sock_has_perm(current, sock->sk, SOCKET__GETATTR);
}
static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
{
int err;
err = sock_has_perm(current, sock->sk, SOCKET__SETOPT);
if (err)
return err;
return selinux_netlbl_socket_setsockopt(sock, level, optname);
}
static int selinux_socket_getsockopt(struct socket *sock, int level,
int optname)
{
return sock_has_perm(current, sock->sk, SOCKET__GETOPT);
}
static int selinux_socket_shutdown(struct socket *sock, int how)
{
return sock_has_perm(current, sock->sk, SOCKET__SHUTDOWN);
}
static int selinux_socket_unix_stream_connect(struct sock *sock,
struct sock *other,
struct sock *newsk)
{
struct sk_security_struct *sksec_sock = sock->sk_security;
struct sk_security_struct *sksec_other = other->sk_security;
struct sk_security_struct *sksec_new = newsk->sk_security;
struct common_audit_data ad;
int err;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.sk = other;
err = avc_has_perm(sksec_sock->sid, sksec_other->sid,
sksec_other->sclass,
UNIX_STREAM_SOCKET__CONNECTTO, &ad);
if (err)
return err;
/* server child socket */
sksec_new->peer_sid = sksec_sock->sid;
err = security_sid_mls_copy(sksec_other->sid, sksec_sock->sid,
&sksec_new->sid);
if (err)
return err;
/* connecting socket */
sksec_sock->peer_sid = sksec_new->sid;
return 0;
}
static int selinux_socket_unix_may_send(struct socket *sock,
struct socket *other)
{
struct sk_security_struct *ssec = sock->sk->sk_security;
struct sk_security_struct *osec = other->sk->sk_security;
struct common_audit_data ad;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.sk = other->sk;
return avc_has_perm(ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
&ad);
}
static int selinux_inet_sys_rcv_skb(int ifindex, char *addrp, u16 family,
u32 peer_sid,
struct common_audit_data *ad)
{
int err;
u32 if_sid;
u32 node_sid;
err = sel_netif_sid(ifindex, &if_sid);
if (err)
return err;
err = avc_has_perm(peer_sid, if_sid,
SECCLASS_NETIF, NETIF__INGRESS, ad);
if (err)
return err;
err = sel_netnode_sid(addrp, family, &node_sid);
if (err)
return err;
return avc_has_perm(peer_sid, node_sid,
SECCLASS_NODE, NODE__RECVFROM, ad);
}
static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
u16 family)
{
int err = 0;
struct sk_security_struct *sksec = sk->sk_security;
u32 sk_sid = sksec->sid;
struct common_audit_data ad;
char *addrp;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.netif = skb->skb_iif;
ad.u.net.family = family;
err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
if (err)
return err;
if (selinux_secmark_enabled()) {
err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
PACKET__RECV, &ad);
if (err)
return err;
}
err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
if (err)
return err;
err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
return err;
}
static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
int err;
struct sk_security_struct *sksec = sk->sk_security;
u16 family = sk->sk_family;
u32 sk_sid = sksec->sid;
struct common_audit_data ad;
char *addrp;
u8 secmark_active;
u8 peerlbl_active;
if (family != PF_INET && family != PF_INET6)
return 0;
/* Handle mapped IPv4 packets arriving via IPv6 sockets */
if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
family = PF_INET;
/* If any sort of compatibility mode is enabled then handoff processing
* to the selinux_sock_rcv_skb_compat() function to deal with the
* special handling. We do this in an attempt to keep this function
* as fast and as clean as possible. */
if (!selinux_policycap_netpeer)
return selinux_sock_rcv_skb_compat(sk, skb, family);
secmark_active = selinux_secmark_enabled();
peerlbl_active = netlbl_enabled() || selinux_xfrm_enabled();
if (!secmark_active && !peerlbl_active)
return 0;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.netif = skb->skb_iif;
ad.u.net.family = family;
err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
if (err)
return err;
if (peerlbl_active) {
u32 peer_sid;
err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
if (err)
return err;
err = selinux_inet_sys_rcv_skb(skb->skb_iif, addrp, family,
peer_sid, &ad);
if (err) {
selinux_netlbl_err(skb, err, 0);
return err;
}
err = avc_has_perm(sk_sid, peer_sid, SECCLASS_PEER,
PEER__RECV, &ad);
if (err)
selinux_netlbl_err(skb, err, 0);
}
if (secmark_active) {
err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
PACKET__RECV, &ad);
if (err)
return err;
}
return err;
}
static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval,
int __user *optlen, unsigned len)
{
int err = 0;
char *scontext;
u32 scontext_len;
struct sk_security_struct *sksec = sock->sk->sk_security;
u32 peer_sid = SECSID_NULL;
if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
sksec->sclass == SECCLASS_TCP_SOCKET)
peer_sid = sksec->peer_sid;
if (peer_sid == SECSID_NULL)
return -ENOPROTOOPT;
err = security_sid_to_context(peer_sid, &scontext, &scontext_len);
if (err)
return err;
if (scontext_len > len) {
err = -ERANGE;
goto out_len;
}
if (copy_to_user(optval, scontext, scontext_len))
err = -EFAULT;
out_len:
if (put_user(scontext_len, optlen))
err = -EFAULT;
kfree(scontext);
return err;
}
static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
{
u32 peer_secid = SECSID_NULL;
u16 family;
if (skb && skb->protocol == htons(ETH_P_IP))
family = PF_INET;
else if (skb && skb->protocol == htons(ETH_P_IPV6))
family = PF_INET6;
else if (sock)
family = sock->sk->sk_family;
else
goto out;
if (sock && family == PF_UNIX)
selinux_inode_getsecid(SOCK_INODE(sock), &peer_secid);
else if (skb)
selinux_skb_peerlbl_sid(skb, family, &peer_secid);
out:
*secid = peer_secid;
if (peer_secid == SECSID_NULL)
return -EINVAL;
return 0;
}
static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
{
struct sk_security_struct *sksec;
sksec = kzalloc(sizeof(*sksec), priority);
if (!sksec)
return -ENOMEM;
sksec->peer_sid = SECINITSID_UNLABELED;
sksec->sid = SECINITSID_UNLABELED;
selinux_netlbl_sk_security_reset(sksec);
sk->sk_security = sksec;
return 0;
}
static void selinux_sk_free_security(struct sock *sk)
{
struct sk_security_struct *sksec = sk->sk_security;
sk->sk_security = NULL;
selinux_netlbl_sk_security_free(sksec);
kfree(sksec);
}
static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
{
struct sk_security_struct *sksec = sk->sk_security;
struct sk_security_struct *newsksec = newsk->sk_security;
newsksec->sid = sksec->sid;
newsksec->peer_sid = sksec->peer_sid;
newsksec->sclass = sksec->sclass;
selinux_netlbl_sk_security_reset(newsksec);
}
static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
{
if (!sk)
*secid = SECINITSID_ANY_SOCKET;
else {
struct sk_security_struct *sksec = sk->sk_security;
*secid = sksec->sid;
}
}
static void selinux_sock_graft(struct sock *sk, struct socket *parent)
{
struct inode_security_struct *isec = SOCK_INODE(parent)->i_security;
struct sk_security_struct *sksec = sk->sk_security;
if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
sk->sk_family == PF_UNIX)
isec->sid = sksec->sid;
sksec->sclass = isec->sclass;
}
static int selinux_inet_conn_request(struct sock *sk, struct sk_buff *skb,
struct request_sock *req)
{
struct sk_security_struct *sksec = sk->sk_security;
int err;
u16 family = sk->sk_family;
u32 connsid;
u32 peersid;
/* handle mapped IPv4 packets arriving via IPv6 sockets */
if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
family = PF_INET;
err = selinux_skb_peerlbl_sid(skb, family, &peersid);
if (err)
return err;
err = selinux_conn_sid(sksec->sid, peersid, &connsid);
if (err)
return err;
req->secid = connsid;
req->peer_secid = peersid;
return selinux_netlbl_inet_conn_request(req, family);
}
static void selinux_inet_csk_clone(struct sock *newsk,
const struct request_sock *req)
{
struct sk_security_struct *newsksec = newsk->sk_security;
newsksec->sid = req->secid;
newsksec->peer_sid = req->peer_secid;
/* NOTE: Ideally, we should also get the isec->sid for the
new socket in sync, but we don't have the isec available yet.
So we will wait until sock_graft to do it, by which
time it will have been created and available. */
/* We don't need to take any sort of lock here as we are the only
* thread with access to newsksec */
selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
}
static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
{
u16 family = sk->sk_family;
struct sk_security_struct *sksec = sk->sk_security;
/* handle mapped IPv4 packets arriving via IPv6 sockets */
if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
family = PF_INET;
selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
}
static int selinux_secmark_relabel_packet(u32 sid)
{
const struct task_security_struct *__tsec;
u32 tsid;
__tsec = current_security();
tsid = __tsec->sid;
return avc_has_perm(tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO, NULL);
}
static void selinux_secmark_refcount_inc(void)
{
atomic_inc(&selinux_secmark_refcount);
}
static void selinux_secmark_refcount_dec(void)
{
atomic_dec(&selinux_secmark_refcount);
}
static void selinux_req_classify_flow(const struct request_sock *req,
struct flowi *fl)
{
fl->flowi_secid = req->secid;
}
static int selinux_tun_dev_create(void)
{
u32 sid = current_sid();
/* we aren't taking into account the "sockcreate" SID since the socket
* that is being created here is not a socket in the traditional sense,
* instead it is a private sock, accessible only to the kernel, and
* representing a wide range of network traffic spanning multiple
* connections unlike traditional sockets - check the TUN driver to
* get a better understanding of why this socket is special */
return avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
NULL);
}
static void selinux_tun_dev_post_create(struct sock *sk)
{
struct sk_security_struct *sksec = sk->sk_security;
/* we don't currently perform any NetLabel based labeling here and it
* isn't clear that we would want to do so anyway; while we could apply
* labeling without the support of the TUN user the resulting labeled
* traffic from the other end of the connection would almost certainly
* cause confusion to the TUN user that had no idea network labeling
* protocols were being used */
/* see the comments in selinux_tun_dev_create() about why we don't use
* the sockcreate SID here */
sksec->sid = current_sid();
sksec->sclass = SECCLASS_TUN_SOCKET;
}
static int selinux_tun_dev_attach(struct sock *sk)
{
struct sk_security_struct *sksec = sk->sk_security;
u32 sid = current_sid();
int err;
err = avc_has_perm(sid, sksec->sid, SECCLASS_TUN_SOCKET,
TUN_SOCKET__RELABELFROM, NULL);
if (err)
return err;
err = avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET,
TUN_SOCKET__RELABELTO, NULL);
if (err)
return err;
sksec->sid = sid;
return 0;
}
static int selinux_nlmsg_perm(struct sock *sk, struct sk_buff *skb)
{
int err = 0;
u32 perm;
struct nlmsghdr *nlh;
struct sk_security_struct *sksec = sk->sk_security;
if (skb->len < NLMSG_SPACE(0)) {
err = -EINVAL;
goto out;
}
nlh = nlmsg_hdr(skb);
err = selinux_nlmsg_lookup(sksec->sclass, nlh->nlmsg_type, &perm);
if (err) {
if (err == -EINVAL) {
audit_log(current->audit_context, GFP_KERNEL, AUDIT_SELINUX_ERR,
"SELinux: unrecognized netlink message"
" type=%hu for sclass=%hu\n",
nlh->nlmsg_type, sksec->sclass);
if (!selinux_enforcing || security_get_allow_unknown())
err = 0;
}
/* Ignore */
if (err == -ENOENT)
err = 0;
goto out;
}
err = sock_has_perm(current, sk, perm);
out:
return err;
}
#ifdef CONFIG_NETFILTER
static unsigned int selinux_ip_forward(struct sk_buff *skb, int ifindex,
u16 family)
{
int err;
char *addrp;
u32 peer_sid;
struct common_audit_data ad;
u8 secmark_active;
u8 netlbl_active;
u8 peerlbl_active;
if (!selinux_policycap_netpeer)
return NF_ACCEPT;
secmark_active = selinux_secmark_enabled();
netlbl_active = netlbl_enabled();
peerlbl_active = netlbl_active || selinux_xfrm_enabled();
if (!secmark_active && !peerlbl_active)
return NF_ACCEPT;
if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
return NF_DROP;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.netif = ifindex;
ad.u.net.family = family;
if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
return NF_DROP;
if (peerlbl_active) {
err = selinux_inet_sys_rcv_skb(ifindex, addrp, family,
peer_sid, &ad);
if (err) {
selinux_netlbl_err(skb, err, 1);
return NF_DROP;
}
}
if (secmark_active)
if (avc_has_perm(peer_sid, skb->secmark,
SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
return NF_DROP;
if (netlbl_active)
/* we do this in the FORWARD path and not the POST_ROUTING
* path because we want to make sure we apply the necessary
* labeling before IPsec is applied so we can leverage AH
* protection */
if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
return NF_DROP;
return NF_ACCEPT;
}
static unsigned int selinux_ipv4_forward(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return selinux_ip_forward(skb, in->ifindex, PF_INET);
}
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
static unsigned int selinux_ipv6_forward(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return selinux_ip_forward(skb, in->ifindex, PF_INET6);
}
#endif /* IPV6 */
static unsigned int selinux_ip_output(struct sk_buff *skb,
u16 family)
{
struct sock *sk;
u32 sid;
if (!netlbl_enabled())
return NF_ACCEPT;
/* we do this in the LOCAL_OUT path and not the POST_ROUTING path
* because we want to make sure we apply the necessary labeling
* before IPsec is applied so we can leverage AH protection */
sk = skb->sk;
if (sk) {
struct sk_security_struct *sksec;
if (sk->sk_state == TCP_LISTEN)
/* if the socket is the listening state then this
* packet is a SYN-ACK packet which means it needs to
* be labeled based on the connection/request_sock and
* not the parent socket. unfortunately, we can't
* lookup the request_sock yet as it isn't queued on
* the parent socket until after the SYN-ACK is sent.
* the "solution" is to simply pass the packet as-is
* as any IP option based labeling should be copied
* from the initial connection request (in the IP
* layer). it is far from ideal, but until we get a
* security label in the packet itself this is the
* best we can do. */
return NF_ACCEPT;
/* standard practice, label using the parent socket */
sksec = sk->sk_security;
sid = sksec->sid;
} else
sid = SECINITSID_KERNEL;
if (selinux_netlbl_skbuff_setsid(skb, family, sid) != 0)
return NF_DROP;
return NF_ACCEPT;
}
static unsigned int selinux_ipv4_output(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return selinux_ip_output(skb, PF_INET);
}
static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
int ifindex,
u16 family)
{
struct sock *sk = skb->sk;
struct sk_security_struct *sksec;
struct common_audit_data ad;
char *addrp;
u8 proto;
if (sk == NULL)
return NF_ACCEPT;
sksec = sk->sk_security;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.netif = ifindex;
ad.u.net.family = family;
if (selinux_parse_skb(skb, &ad, &addrp, 0, &proto))
return NF_DROP;
if (selinux_secmark_enabled())
if (avc_has_perm(sksec->sid, skb->secmark,
SECCLASS_PACKET, PACKET__SEND, &ad))
return NF_DROP_ERR(-ECONNREFUSED);
if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
return NF_DROP_ERR(-ECONNREFUSED);
return NF_ACCEPT;
}
static unsigned int selinux_ip_postroute(struct sk_buff *skb, int ifindex,
u16 family)
{
u32 secmark_perm;
u32 peer_sid;
struct sock *sk;
struct common_audit_data ad;
char *addrp;
u8 secmark_active;
u8 peerlbl_active;
/* If any sort of compatibility mode is enabled then handoff processing
* to the selinux_ip_postroute_compat() function to deal with the
* special handling. We do this in an attempt to keep this function
* as fast and as clean as possible. */
if (!selinux_policycap_netpeer)
return selinux_ip_postroute_compat(skb, ifindex, family);
#ifdef CONFIG_XFRM
/* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
* packet transformation so allow the packet to pass without any checks
* since we'll have another chance to perform access control checks
* when the packet is on it's final way out.
* NOTE: there appear to be some IPv6 multicast cases where skb->dst
* is NULL, in this case go ahead and apply access control. */
if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL)
return NF_ACCEPT;
#endif
secmark_active = selinux_secmark_enabled();
peerlbl_active = netlbl_enabled() || selinux_xfrm_enabled();
if (!secmark_active && !peerlbl_active)
return NF_ACCEPT;
sk = skb->sk;
if (sk == NULL) {
/* Without an associated socket the packet is either coming
* from the kernel or it is being forwarded; check the packet
* to determine which and if the packet is being forwarded
* query the packet directly to determine the security label. */
if (skb->skb_iif) {
secmark_perm = PACKET__FORWARD_OUT;
if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
return NF_DROP;
} else {
secmark_perm = PACKET__SEND;
peer_sid = SECINITSID_KERNEL;
}
} else if (sk->sk_state == TCP_LISTEN) {
/* Locally generated packet but the associated socket is in the
* listening state which means this is a SYN-ACK packet. In
* this particular case the correct security label is assigned
* to the connection/request_sock but unfortunately we can't
* query the request_sock as it isn't queued on the parent
* socket until after the SYN-ACK packet is sent; the only
* viable choice is to regenerate the label like we do in
* selinux_inet_conn_request(). See also selinux_ip_output()
* for similar problems. */
u32 skb_sid;
struct sk_security_struct *sksec = sk->sk_security;
if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
return NF_DROP;
if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
return NF_DROP;
secmark_perm = PACKET__SEND;
} else {
/* Locally generated packet, fetch the security label from the
* associated socket. */
struct sk_security_struct *sksec = sk->sk_security;
peer_sid = sksec->sid;
secmark_perm = PACKET__SEND;
}
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.netif = ifindex;
ad.u.net.family = family;
if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
return NF_DROP;
if (secmark_active)
if (avc_has_perm(peer_sid, skb->secmark,
SECCLASS_PACKET, secmark_perm, &ad))
return NF_DROP_ERR(-ECONNREFUSED);
if (peerlbl_active) {
u32 if_sid;
u32 node_sid;
if (sel_netif_sid(ifindex, &if_sid))
return NF_DROP;
if (avc_has_perm(peer_sid, if_sid,
SECCLASS_NETIF, NETIF__EGRESS, &ad))
return NF_DROP_ERR(-ECONNREFUSED);
if (sel_netnode_sid(addrp, family, &node_sid))
return NF_DROP;
if (avc_has_perm(peer_sid, node_sid,
SECCLASS_NODE, NODE__SENDTO, &ad))
return NF_DROP_ERR(-ECONNREFUSED);
}
return NF_ACCEPT;
}
static unsigned int selinux_ipv4_postroute(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return selinux_ip_postroute(skb, out->ifindex, PF_INET);
}
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
static unsigned int selinux_ipv6_postroute(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return selinux_ip_postroute(skb, out->ifindex, PF_INET6);
}
#endif /* IPV6 */
#endif /* CONFIG_NETFILTER */
static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
{
int err;
err = cap_netlink_send(sk, skb);
if (err)
return err;
return selinux_nlmsg_perm(sk, skb);
}
static int selinux_netlink_recv(struct sk_buff *skb, int capability)
{
int err;
struct common_audit_data ad;
u32 sid;
err = cap_netlink_recv(skb, capability);
if (err)
return err;
COMMON_AUDIT_DATA_INIT(&ad, CAP);
ad.u.cap = capability;
security_task_getsecid(current, &sid);
return avc_has_perm(sid, sid, SECCLASS_CAPABILITY,
CAP_TO_MASK(capability), &ad);
}
static int ipc_alloc_security(struct task_struct *task,
struct kern_ipc_perm *perm,
u16 sclass)
{
struct ipc_security_struct *isec;
u32 sid;
isec = kzalloc(sizeof(struct ipc_security_struct), GFP_KERNEL);
if (!isec)
return -ENOMEM;
sid = task_sid(task);
isec->sclass = sclass;
isec->sid = sid;
perm->security = isec;
return 0;
}
static void ipc_free_security(struct kern_ipc_perm *perm)
{
struct ipc_security_struct *isec = perm->security;
perm->security = NULL;
kfree(isec);
}
static int msg_msg_alloc_security(struct msg_msg *msg)
{
struct msg_security_struct *msec;
msec = kzalloc(sizeof(struct msg_security_struct), GFP_KERNEL);
if (!msec)
return -ENOMEM;
msec->sid = SECINITSID_UNLABELED;
msg->security = msec;
return 0;
}
static void msg_msg_free_security(struct msg_msg *msg)
{
struct msg_security_struct *msec = msg->security;
msg->security = NULL;
kfree(msec);
}
static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
u32 perms)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
isec = ipc_perms->security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = ipc_perms->key;
return avc_has_perm(sid, isec->sid, isec->sclass, perms, &ad);
}
static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
{
return msg_msg_alloc_security(msg);
}
static void selinux_msg_msg_free_security(struct msg_msg *msg)
{
msg_msg_free_security(msg);
}
/* message queue security operations */
static int selinux_msg_queue_alloc_security(struct msg_queue *msq)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
int rc;
rc = ipc_alloc_security(current, &msq->q_perm, SECCLASS_MSGQ);
if (rc)
return rc;
isec = msq->q_perm.security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = msq->q_perm.key;
rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
MSGQ__CREATE, &ad);
if (rc) {
ipc_free_security(&msq->q_perm);
return rc;
}
return 0;
}
static void selinux_msg_queue_free_security(struct msg_queue *msq)
{
ipc_free_security(&msq->q_perm);
}
static int selinux_msg_queue_associate(struct msg_queue *msq, int msqflg)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
isec = msq->q_perm.security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = msq->q_perm.key;
return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
MSGQ__ASSOCIATE, &ad);
}
static int selinux_msg_queue_msgctl(struct msg_queue *msq, int cmd)
{
int err;
int perms;
switch (cmd) {
case IPC_INFO:
case MSG_INFO:
/* No specific object, just general system-wide information. */
return task_has_system(current, SYSTEM__IPC_INFO);
case IPC_STAT:
case MSG_STAT:
perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
break;
case IPC_SET:
perms = MSGQ__SETATTR;
break;
case IPC_RMID:
perms = MSGQ__DESTROY;
break;
default:
return 0;
}
err = ipc_has_perm(&msq->q_perm, perms);
return err;
}
static int selinux_msg_queue_msgsnd(struct msg_queue *msq, struct msg_msg *msg, int msqflg)
{
struct ipc_security_struct *isec;
struct msg_security_struct *msec;
struct common_audit_data ad;
u32 sid = current_sid();
int rc;
isec = msq->q_perm.security;
msec = msg->security;
/*
* First time through, need to assign label to the message
*/
if (msec->sid == SECINITSID_UNLABELED) {
/*
* Compute new sid based on current process and
* message queue this message will be stored in
*/
rc = security_transition_sid(sid, isec->sid, SECCLASS_MSG,
NULL, &msec->sid);
if (rc)
return rc;
}
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = msq->q_perm.key;
/* Can this process write to the queue? */
rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
MSGQ__WRITE, &ad);
if (!rc)
/* Can this process send the message */
rc = avc_has_perm(sid, msec->sid, SECCLASS_MSG,
MSG__SEND, &ad);
if (!rc)
/* Can the message be put in the queue? */
rc = avc_has_perm(msec->sid, isec->sid, SECCLASS_MSGQ,
MSGQ__ENQUEUE, &ad);
return rc;
}
static int selinux_msg_queue_msgrcv(struct msg_queue *msq, struct msg_msg *msg,
struct task_struct *target,
long type, int mode)
{
struct ipc_security_struct *isec;
struct msg_security_struct *msec;
struct common_audit_data ad;
u32 sid = task_sid(target);
int rc;
isec = msq->q_perm.security;
msec = msg->security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = msq->q_perm.key;
rc = avc_has_perm(sid, isec->sid,
SECCLASS_MSGQ, MSGQ__READ, &ad);
if (!rc)
rc = avc_has_perm(sid, msec->sid,
SECCLASS_MSG, MSG__RECEIVE, &ad);
return rc;
}
/* Shared Memory security operations */
static int selinux_shm_alloc_security(struct shmid_kernel *shp)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
int rc;
rc = ipc_alloc_security(current, &shp->shm_perm, SECCLASS_SHM);
if (rc)
return rc;
isec = shp->shm_perm.security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = shp->shm_perm.key;
rc = avc_has_perm(sid, isec->sid, SECCLASS_SHM,
SHM__CREATE, &ad);
if (rc) {
ipc_free_security(&shp->shm_perm);
return rc;
}
return 0;
}
static void selinux_shm_free_security(struct shmid_kernel *shp)
{
ipc_free_security(&shp->shm_perm);
}
static int selinux_shm_associate(struct shmid_kernel *shp, int shmflg)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
isec = shp->shm_perm.security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = shp->shm_perm.key;
return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
SHM__ASSOCIATE, &ad);
}
/* Note, at this point, shp is locked down */
static int selinux_shm_shmctl(struct shmid_kernel *shp, int cmd)
{
int perms;
int err;
switch (cmd) {
case IPC_INFO:
case SHM_INFO:
/* No specific object, just general system-wide information. */
return task_has_system(current, SYSTEM__IPC_INFO);
case IPC_STAT:
case SHM_STAT:
perms = SHM__GETATTR | SHM__ASSOCIATE;
break;
case IPC_SET:
perms = SHM__SETATTR;
break;
case SHM_LOCK:
case SHM_UNLOCK:
perms = SHM__LOCK;
break;
case IPC_RMID:
perms = SHM__DESTROY;
break;
default:
return 0;
}
err = ipc_has_perm(&shp->shm_perm, perms);
return err;
}
static int selinux_shm_shmat(struct shmid_kernel *shp,
char __user *shmaddr, int shmflg)
{
u32 perms;
if (shmflg & SHM_RDONLY)
perms = SHM__READ;
else
perms = SHM__READ | SHM__WRITE;
return ipc_has_perm(&shp->shm_perm, perms);
}
/* Semaphore security operations */
static int selinux_sem_alloc_security(struct sem_array *sma)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
int rc;
rc = ipc_alloc_security(current, &sma->sem_perm, SECCLASS_SEM);
if (rc)
return rc;
isec = sma->sem_perm.security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = sma->sem_perm.key;
rc = avc_has_perm(sid, isec->sid, SECCLASS_SEM,
SEM__CREATE, &ad);
if (rc) {
ipc_free_security(&sma->sem_perm);
return rc;
}
return 0;
}
static void selinux_sem_free_security(struct sem_array *sma)
{
ipc_free_security(&sma->sem_perm);
}
static int selinux_sem_associate(struct sem_array *sma, int semflg)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
isec = sma->sem_perm.security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = sma->sem_perm.key;
return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
SEM__ASSOCIATE, &ad);
}
/* Note, at this point, sma is locked down */
static int selinux_sem_semctl(struct sem_array *sma, int cmd)
{
int err;
u32 perms;
switch (cmd) {
case IPC_INFO:
case SEM_INFO:
/* No specific object, just general system-wide information. */
return task_has_system(current, SYSTEM__IPC_INFO);
case GETPID:
case GETNCNT:
case GETZCNT:
perms = SEM__GETATTR;
break;
case GETVAL:
case GETALL:
perms = SEM__READ;
break;
case SETVAL:
case SETALL:
perms = SEM__WRITE;
break;
case IPC_RMID:
perms = SEM__DESTROY;
break;
case IPC_SET:
perms = SEM__SETATTR;
break;
case IPC_STAT:
case SEM_STAT:
perms = SEM__GETATTR | SEM__ASSOCIATE;
break;
default:
return 0;
}
err = ipc_has_perm(&sma->sem_perm, perms);
return err;
}
static int selinux_sem_semop(struct sem_array *sma,
struct sembuf *sops, unsigned nsops, int alter)
{
u32 perms;
if (alter)
perms = SEM__READ | SEM__WRITE;
else
perms = SEM__READ;
return ipc_has_perm(&sma->sem_perm, perms);
}
static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
{
u32 av = 0;
av = 0;
if (flag & S_IRUGO)
av |= IPC__UNIX_READ;
if (flag & S_IWUGO)
av |= IPC__UNIX_WRITE;
if (av == 0)
return 0;
return ipc_has_perm(ipcp, av);
}
static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
{
struct ipc_security_struct *isec = ipcp->security;
*secid = isec->sid;
}
static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
{
if (inode)
inode_doinit_with_dentry(inode, dentry);
}
static int selinux_getprocattr(struct task_struct *p,
char *name, char **value)
{
const struct task_security_struct *__tsec;
u32 sid;
int error;
unsigned len;
if (current != p) {
error = current_has_perm(p, PROCESS__GETATTR);
if (error)
return error;
}
rcu_read_lock();
__tsec = __task_cred(p)->security;
if (!strcmp(name, "current"))
sid = __tsec->sid;
else if (!strcmp(name, "prev"))
sid = __tsec->osid;
else if (!strcmp(name, "exec"))
sid = __tsec->exec_sid;
else if (!strcmp(name, "fscreate"))
sid = __tsec->create_sid;
else if (!strcmp(name, "keycreate"))
sid = __tsec->keycreate_sid;
else if (!strcmp(name, "sockcreate"))
sid = __tsec->sockcreate_sid;
else
goto invalid;
rcu_read_unlock();
if (!sid)
return 0;
error = security_sid_to_context(sid, value, &len);
if (error)
return error;
return len;
invalid:
rcu_read_unlock();
return -EINVAL;
}
static int selinux_setprocattr(struct task_struct *p,
char *name, void *value, size_t size)
{
struct task_security_struct *tsec;
struct task_struct *tracer;
struct cred *new;
u32 sid = 0, ptsid;
int error;
char *str = value;
if (current != p) {
/* SELinux only allows a process to change its own
security attributes. */
return -EACCES;
}
/*
* Basic control over ability to set these attributes at all.
* current == p, but we'll pass them separately in case the
* above restriction is ever removed.
*/
if (!strcmp(name, "exec"))
error = current_has_perm(p, PROCESS__SETEXEC);
else if (!strcmp(name, "fscreate"))
error = current_has_perm(p, PROCESS__SETFSCREATE);
else if (!strcmp(name, "keycreate"))
error = current_has_perm(p, PROCESS__SETKEYCREATE);
else if (!strcmp(name, "sockcreate"))
error = current_has_perm(p, PROCESS__SETSOCKCREATE);
else if (!strcmp(name, "current"))
error = current_has_perm(p, PROCESS__SETCURRENT);
else
error = -EINVAL;
if (error)
return error;
/* Obtain a SID for the context, if one was specified. */
if (size && str[1] && str[1] != '\n') {
if (str[size-1] == '\n') {
str[size-1] = 0;
size--;
}
error = security_context_to_sid(value, size, &sid);
if (error == -EINVAL && !strcmp(name, "fscreate")) {
if (!capable(CAP_MAC_ADMIN))
return error;
error = security_context_to_sid_force(value, size,
&sid);
}
if (error)
return error;
}
new = prepare_creds();
if (!new)
return -ENOMEM;
/* Permission checking based on the specified context is
performed during the actual operation (execve,
open/mkdir/...), when we know the full context of the
operation. See selinux_bprm_set_creds for the execve
checks and may_create for the file creation checks. The
operation will then fail if the context is not permitted. */
tsec = new->security;
if (!strcmp(name, "exec")) {
tsec->exec_sid = sid;
} else if (!strcmp(name, "fscreate")) {
tsec->create_sid = sid;
} else if (!strcmp(name, "keycreate")) {
error = may_create_key(sid, p);
if (error)
goto abort_change;
tsec->keycreate_sid = sid;
} else if (!strcmp(name, "sockcreate")) {
tsec->sockcreate_sid = sid;
} else if (!strcmp(name, "current")) {
error = -EINVAL;
if (sid == 0)
goto abort_change;
/* Only allow single threaded processes to change context */
error = -EPERM;
if (!current_is_single_threaded()) {
error = security_bounded_transition(tsec->sid, sid);
if (error)
goto abort_change;
}
/* Check permissions for the transition. */
error = avc_has_perm(tsec->sid, sid, SECCLASS_PROCESS,
PROCESS__DYNTRANSITION, NULL);
if (error)
goto abort_change;
/* Check for ptracing, and update the task SID if ok.
Otherwise, leave SID unchanged and fail. */
ptsid = 0;
task_lock(p);
tracer = ptrace_parent(p);
if (tracer)
ptsid = task_sid(tracer);
task_unlock(p);
if (tracer) {
error = avc_has_perm(ptsid, sid, SECCLASS_PROCESS,
PROCESS__PTRACE, NULL);
if (error)
goto abort_change;
}
tsec->sid = sid;
} else {
error = -EINVAL;
goto abort_change;
}
commit_creds(new);
return size;
abort_change:
abort_creds(new);
return error;
}
static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
{
return security_sid_to_context(secid, secdata, seclen);
}
static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
{
return security_context_to_sid(secdata, seclen, secid);
}
static void selinux_release_secctx(char *secdata, u32 seclen)
{
kfree(secdata);
}
/*
* called with inode->i_mutex locked
*/
static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
{
return selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX, ctx, ctxlen, 0);
}
/*
* called with inode->i_mutex locked
*/
static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
{
return __vfs_setxattr_noperm(dentry, XATTR_NAME_SELINUX, ctx, ctxlen, 0);
}
static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
{
int len = 0;
len = selinux_inode_getsecurity(inode, XATTR_SELINUX_SUFFIX,
ctx, true);
if (len < 0)
return len;
*ctxlen = len;
return 0;
}
#ifdef CONFIG_KEYS
static int selinux_key_alloc(struct key *k, const struct cred *cred,
unsigned long flags)
{
const struct task_security_struct *tsec;
struct key_security_struct *ksec;
ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
if (!ksec)
return -ENOMEM;
tsec = cred->security;
if (tsec->keycreate_sid)
ksec->sid = tsec->keycreate_sid;
else
ksec->sid = tsec->sid;
k->security = ksec;
return 0;
}
static void selinux_key_free(struct key *k)
{
struct key_security_struct *ksec = k->security;
k->security = NULL;
kfree(ksec);
}
static int selinux_key_permission(key_ref_t key_ref,
const struct cred *cred,
key_perm_t perm)
{
struct key *key;
struct key_security_struct *ksec;
u32 sid;
/* if no specific permissions are requested, we skip the
permission check. No serious, additional covert channels
appear to be created. */
if (perm == 0)
return 0;
sid = cred_sid(cred);
key = key_ref_to_ptr(key_ref);
ksec = key->security;
return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, perm, NULL);
}
static int selinux_key_getsecurity(struct key *key, char **_buffer)
{
struct key_security_struct *ksec = key->security;
char *context = NULL;
unsigned len;
int rc;
rc = security_sid_to_context(ksec->sid, &context, &len);
if (!rc)
rc = len;
*_buffer = context;
return rc;
}
#endif
static struct security_operations selinux_ops = {
.name = "selinux",
.ptrace_access_check = selinux_ptrace_access_check,
.ptrace_traceme = selinux_ptrace_traceme,
.capget = selinux_capget,
.capset = selinux_capset,
.capable = selinux_capable,
.quotactl = selinux_quotactl,
.quota_on = selinux_quota_on,
.syslog = selinux_syslog,
.vm_enough_memory = selinux_vm_enough_memory,
.netlink_send = selinux_netlink_send,
.netlink_recv = selinux_netlink_recv,
.bprm_set_creds = selinux_bprm_set_creds,
.bprm_committing_creds = selinux_bprm_committing_creds,
.bprm_committed_creds = selinux_bprm_committed_creds,
.bprm_secureexec = selinux_bprm_secureexec,
.sb_alloc_security = selinux_sb_alloc_security,
.sb_free_security = selinux_sb_free_security,
.sb_copy_data = selinux_sb_copy_data,
.sb_remount = selinux_sb_remount,
.sb_kern_mount = selinux_sb_kern_mount,
.sb_show_options = selinux_sb_show_options,
.sb_statfs = selinux_sb_statfs,
.sb_mount = selinux_mount,
.sb_umount = selinux_umount,
.sb_set_mnt_opts = selinux_set_mnt_opts,
.sb_clone_mnt_opts = selinux_sb_clone_mnt_opts,
.sb_parse_opts_str = selinux_parse_opts_str,
.inode_alloc_security = selinux_inode_alloc_security,
.inode_free_security = selinux_inode_free_security,
.inode_init_security = selinux_inode_init_security,
.inode_create = selinux_inode_create,
.inode_link = selinux_inode_link,
.inode_unlink = selinux_inode_unlink,
.inode_symlink = selinux_inode_symlink,
.inode_mkdir = selinux_inode_mkdir,
.inode_rmdir = selinux_inode_rmdir,
.inode_mknod = selinux_inode_mknod,
.inode_rename = selinux_inode_rename,
.inode_readlink = selinux_inode_readlink,
.inode_follow_link = selinux_inode_follow_link,
.inode_permission = selinux_inode_permission,
.inode_setattr = selinux_inode_setattr,
.inode_getattr = selinux_inode_getattr,
.inode_setxattr = selinux_inode_setxattr,
.inode_post_setxattr = selinux_inode_post_setxattr,
.inode_getxattr = selinux_inode_getxattr,
.inode_listxattr = selinux_inode_listxattr,
.inode_removexattr = selinux_inode_removexattr,
.inode_getsecurity = selinux_inode_getsecurity,
.inode_setsecurity = selinux_inode_setsecurity,
.inode_listsecurity = selinux_inode_listsecurity,
.inode_getsecid = selinux_inode_getsecid,
.file_permission = selinux_file_permission,
.file_alloc_security = selinux_file_alloc_security,
.file_free_security = selinux_file_free_security,
.file_ioctl = selinux_file_ioctl,
.file_mmap = selinux_file_mmap,
.file_mprotect = selinux_file_mprotect,
.file_lock = selinux_file_lock,
.file_fcntl = selinux_file_fcntl,
.file_set_fowner = selinux_file_set_fowner,
.file_send_sigiotask = selinux_file_send_sigiotask,
.file_receive = selinux_file_receive,
.dentry_open = selinux_dentry_open,
.task_create = selinux_task_create,
.cred_alloc_blank = selinux_cred_alloc_blank,
.cred_free = selinux_cred_free,
.cred_prepare = selinux_cred_prepare,
.cred_transfer = selinux_cred_transfer,
.kernel_act_as = selinux_kernel_act_as,
.kernel_create_files_as = selinux_kernel_create_files_as,
.kernel_module_request = selinux_kernel_module_request,
.task_setpgid = selinux_task_setpgid,
.task_getpgid = selinux_task_getpgid,
.task_getsid = selinux_task_getsid,
.task_getsecid = selinux_task_getsecid,
.task_setnice = selinux_task_setnice,
.task_setioprio = selinux_task_setioprio,
.task_getioprio = selinux_task_getioprio,
.task_setrlimit = selinux_task_setrlimit,
.task_setscheduler = selinux_task_setscheduler,
.task_getscheduler = selinux_task_getscheduler,
.task_movememory = selinux_task_movememory,
.task_kill = selinux_task_kill,
.task_wait = selinux_task_wait,
.task_to_inode = selinux_task_to_inode,
.ipc_permission = selinux_ipc_permission,
.ipc_getsecid = selinux_ipc_getsecid,
.msg_msg_alloc_security = selinux_msg_msg_alloc_security,
.msg_msg_free_security = selinux_msg_msg_free_security,
.msg_queue_alloc_security = selinux_msg_queue_alloc_security,
.msg_queue_free_security = selinux_msg_queue_free_security,
.msg_queue_associate = selinux_msg_queue_associate,
.msg_queue_msgctl = selinux_msg_queue_msgctl,
.msg_queue_msgsnd = selinux_msg_queue_msgsnd,
.msg_queue_msgrcv = selinux_msg_queue_msgrcv,
.shm_alloc_security = selinux_shm_alloc_security,
.shm_free_security = selinux_shm_free_security,
.shm_associate = selinux_shm_associate,
.shm_shmctl = selinux_shm_shmctl,
.shm_shmat = selinux_shm_shmat,
.sem_alloc_security = selinux_sem_alloc_security,
.sem_free_security = selinux_sem_free_security,
.sem_associate = selinux_sem_associate,
.sem_semctl = selinux_sem_semctl,
.sem_semop = selinux_sem_semop,
.d_instantiate = selinux_d_instantiate,
.getprocattr = selinux_getprocattr,
.setprocattr = selinux_setprocattr,
.secid_to_secctx = selinux_secid_to_secctx,
.secctx_to_secid = selinux_secctx_to_secid,
.release_secctx = selinux_release_secctx,
.inode_notifysecctx = selinux_inode_notifysecctx,
.inode_setsecctx = selinux_inode_setsecctx,
.inode_getsecctx = selinux_inode_getsecctx,
.unix_stream_connect = selinux_socket_unix_stream_connect,
.unix_may_send = selinux_socket_unix_may_send,
.socket_create = selinux_socket_create,
.socket_post_create = selinux_socket_post_create,
.socket_bind = selinux_socket_bind,
.socket_connect = selinux_socket_connect,
.socket_listen = selinux_socket_listen,
.socket_accept = selinux_socket_accept,
.socket_sendmsg = selinux_socket_sendmsg,
.socket_recvmsg = selinux_socket_recvmsg,
.socket_getsockname = selinux_socket_getsockname,
.socket_getpeername = selinux_socket_getpeername,
.socket_getsockopt = selinux_socket_getsockopt,
.socket_setsockopt = selinux_socket_setsockopt,
.socket_shutdown = selinux_socket_shutdown,
.socket_sock_rcv_skb = selinux_socket_sock_rcv_skb,
.socket_getpeersec_stream = selinux_socket_getpeersec_stream,
.socket_getpeersec_dgram = selinux_socket_getpeersec_dgram,
.sk_alloc_security = selinux_sk_alloc_security,
.sk_free_security = selinux_sk_free_security,
.sk_clone_security = selinux_sk_clone_security,
.sk_getsecid = selinux_sk_getsecid,
.sock_graft = selinux_sock_graft,
.inet_conn_request = selinux_inet_conn_request,
.inet_csk_clone = selinux_inet_csk_clone,
.inet_conn_established = selinux_inet_conn_established,
.secmark_relabel_packet = selinux_secmark_relabel_packet,
.secmark_refcount_inc = selinux_secmark_refcount_inc,
.secmark_refcount_dec = selinux_secmark_refcount_dec,
.req_classify_flow = selinux_req_classify_flow,
.tun_dev_create = selinux_tun_dev_create,
.tun_dev_post_create = selinux_tun_dev_post_create,
.tun_dev_attach = selinux_tun_dev_attach,
#ifdef CONFIG_SECURITY_NETWORK_XFRM
.xfrm_policy_alloc_security = selinux_xfrm_policy_alloc,
.xfrm_policy_clone_security = selinux_xfrm_policy_clone,
.xfrm_policy_free_security = selinux_xfrm_policy_free,
.xfrm_policy_delete_security = selinux_xfrm_policy_delete,
.xfrm_state_alloc_security = selinux_xfrm_state_alloc,
.xfrm_state_free_security = selinux_xfrm_state_free,
.xfrm_state_delete_security = selinux_xfrm_state_delete,
.xfrm_policy_lookup = selinux_xfrm_policy_lookup,
.xfrm_state_pol_flow_match = selinux_xfrm_state_pol_flow_match,
.xfrm_decode_session = selinux_xfrm_decode_session,
#endif
#ifdef CONFIG_KEYS
.key_alloc = selinux_key_alloc,
.key_free = selinux_key_free,
.key_permission = selinux_key_permission,
.key_getsecurity = selinux_key_getsecurity,
#endif
#ifdef CONFIG_AUDIT
.audit_rule_init = selinux_audit_rule_init,
.audit_rule_known = selinux_audit_rule_known,
.audit_rule_match = selinux_audit_rule_match,
.audit_rule_free = selinux_audit_rule_free,
#endif
};
static __init int selinux_init(void)
{
if (!security_module_enable(&selinux_ops)) {
selinux_enabled = 0;
return 0;
}
if (!selinux_enabled) {
printk(KERN_INFO "SELinux: Disabled at boot.\n");
return 0;
}
printk(KERN_INFO "SELinux: Initializing.\n");
/* Set the security state for the initial task. */
cred_init_security();
default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
sel_inode_cache = kmem_cache_create("selinux_inode_security",
sizeof(struct inode_security_struct),
0, SLAB_PANIC, NULL);
avc_init();
if (register_security(&selinux_ops))
panic("SELinux: Unable to register with kernel.\n");
if (selinux_enforcing)
printk(KERN_DEBUG "SELinux: Starting in enforcing mode\n");
else
printk(KERN_DEBUG "SELinux: Starting in permissive mode\n");
return 0;
}
static void delayed_superblock_init(struct super_block *sb, void *unused)
{
superblock_doinit(sb, NULL);
}
void selinux_complete_init(void)
{
printk(KERN_DEBUG "SELinux: Completing initialization.\n");
/* Set up any superblocks initialized prior to the policy load. */
printk(KERN_DEBUG "SELinux: Setting up existing superblocks.\n");
iterate_supers(delayed_superblock_init, NULL);
}
/* SELinux requires early initialization in order to label
all processes and objects when they are created. */
security_initcall(selinux_init);
#if defined(CONFIG_NETFILTER)
static struct nf_hook_ops selinux_ipv4_ops[] = {
{
.hook = selinux_ipv4_postroute,
.owner = THIS_MODULE,
.pf = PF_INET,
.hooknum = NF_INET_POST_ROUTING,
.priority = NF_IP_PRI_SELINUX_LAST,
},
{
.hook = selinux_ipv4_forward,
.owner = THIS_MODULE,
.pf = PF_INET,
.hooknum = NF_INET_FORWARD,
.priority = NF_IP_PRI_SELINUX_FIRST,
},
{
.hook = selinux_ipv4_output,
.owner = THIS_MODULE,
.pf = PF_INET,
.hooknum = NF_INET_LOCAL_OUT,
.priority = NF_IP_PRI_SELINUX_FIRST,
}
};
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
static struct nf_hook_ops selinux_ipv6_ops[] = {
{
.hook = selinux_ipv6_postroute,
.owner = THIS_MODULE,
.pf = PF_INET6,
.hooknum = NF_INET_POST_ROUTING,
.priority = NF_IP6_PRI_SELINUX_LAST,
},
{
.hook = selinux_ipv6_forward,
.owner = THIS_MODULE,
.pf = PF_INET6,
.hooknum = NF_INET_FORWARD,
.priority = NF_IP6_PRI_SELINUX_FIRST,
}
};
#endif /* IPV6 */
static int __init selinux_nf_ip_init(void)
{
int err = 0;
if (!selinux_enabled)
goto out;
printk(KERN_DEBUG "SELinux: Registering netfilter hooks\n");
err = nf_register_hooks(selinux_ipv4_ops, ARRAY_SIZE(selinux_ipv4_ops));
if (err)
panic("SELinux: nf_register_hooks for IPv4: error %d\n", err);
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
err = nf_register_hooks(selinux_ipv6_ops, ARRAY_SIZE(selinux_ipv6_ops));
if (err)
panic("SELinux: nf_register_hooks for IPv6: error %d\n", err);
#endif /* IPV6 */
out:
return err;
}
__initcall(selinux_nf_ip_init);
#ifdef CONFIG_SECURITY_SELINUX_DISABLE
static void selinux_nf_ip_exit(void)
{
printk(KERN_DEBUG "SELinux: Unregistering netfilter hooks\n");
nf_unregister_hooks(selinux_ipv4_ops, ARRAY_SIZE(selinux_ipv4_ops));
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
nf_unregister_hooks(selinux_ipv6_ops, ARRAY_SIZE(selinux_ipv6_ops));
#endif /* IPV6 */
}
#endif
#else /* CONFIG_NETFILTER */
#ifdef CONFIG_SECURITY_SELINUX_DISABLE
#define selinux_nf_ip_exit()
#endif
#endif /* CONFIG_NETFILTER */
#ifdef CONFIG_SECURITY_SELINUX_DISABLE
static int selinux_disabled;
int selinux_disable(void)
{
if (ss_initialized) {
/* Not permitted after initial policy load. */
return -EINVAL;
}
if (selinux_disabled) {
/* Only do this once. */
return -EINVAL;
}
printk(KERN_INFO "SELinux: Disabled at runtime.\n");
selinux_disabled = 1;
selinux_enabled = 0;
reset_security_ops();
/* Try to destroy the avc node cache */
avc_disable();
/* Unregister netfilter hooks. */
selinux_nf_ip_exit();
/* Unregister selinuxfs. */
exit_sel_fs();
return 0;
}
#endif
|
run/IOsched
|
security/selinux/hooks.c
|
C
|
gpl-2.0
| 146,829 |
<?php
/**
* The template for displaying all pages
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages and that other
* 'pages' on your WordPress site will use a different template.
*
* @package WordPress
* @subpackage Twenty_Thirteen
* @since Twenty Thirteen 1.0
*/
get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php if ( has_post_thumbnail() && ! post_password_required() ) : ?>
<div class="entry-thumbnail">
<?php the_post_thumbnail(); ?>
</div>
<?php endif; ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
</header><!-- .entry-header -->
<div class="entry-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'twentythirteen' ) . '</span>', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>' ) ); ?>
</div><!-- .entry-content -->
<footer class="entry-meta">
<?php edit_post_link( __( 'Edit', 'twentythirteen' ), '<span class="edit-link">', '</span>' ); ?>
</footer><!-- .entry-meta -->
</article><!-- #post -->
<?php comments_template(); ?>
<?php endwhile; ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php //get_sidebar(); ?>
<?php get_footer(); ?>
|
bomcpe11/bauhinia
|
wp-content/themes/custom1/page.php
|
PHP
|
gpl-2.0
| 1,610 |
/* Copyright (C) 2008, 2009, 2010 Curtis Gedak
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef FS_INFO_H_
#define FS_INFO_H_
#include "../include/Utils.h"
namespace GParted
{
class FS_Info
{
public:
FS_Info() ;
FS_Info( bool do_refresh ) ;
~FS_Info() ;
Glib::ustring get_fs_type( const Glib::ustring & path ) ;
Glib::ustring get_label( const Glib::ustring & path, bool & found ) ;
Glib::ustring get_uuid( const Glib::ustring & path ) ;
Glib::ustring get_path_by_uuid( const Glib::ustring & uuid ) ;
Glib::ustring get_path_by_label( const Glib::ustring & label ) ;
private:
void load_fs_info_cache() ;
void set_commands_found() ;
Glib::ustring get_device_entry( const Glib::ustring & path ) ;
static bool fs_info_cache_initialized ;
static bool blkid_found ;
static bool vol_id_found ;
static Glib::ustring fs_info_cache ;
};
}//GParted
#endif /*FS_INFO_H_*/
|
mgehre/gparted
|
include/FS_Info.h
|
C
|
gpl-2.0
| 1,579 |
/*
* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.net.http;
import java.io.IOException;
import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import jdk.internal.net.http.common.Logger;
import jdk.internal.net.http.common.MinimalFuture;
import jdk.internal.net.http.common.Utils;
import static java.net.http.HttpClient.Version.HTTP_1_1;
/**
* Splits request so that headers and body can be sent separately with optional
* (multiple) responses in between (e.g. 100 Continue). Also request and
* response always sent/received in different calls.
*
* Synchronous and asynchronous versions of each method are provided.
*
* Separate implementations of this class exist for HTTP/1.1 and HTTP/2
* Http1Exchange (HTTP/1.1)
* Stream (HTTP/2)
*
* These implementation classes are where work is allocated to threads.
*/
abstract class ExchangeImpl<T> {
private static final Logger debug =
Utils.getDebugLogger("ExchangeImpl"::toString, Utils.DEBUG);
final Exchange<T> exchange;
ExchangeImpl(Exchange<T> e) {
// e == null means a http/2 pushed stream
this.exchange = e;
}
final Exchange<T> getExchange() {
return exchange;
}
HttpClient client() {
return exchange.client();
}
/**
* Returns the {@link HttpConnection} instance to which this exchange is
* assigned.
*/
abstract HttpConnection connection();
/**
* Initiates a new exchange and assigns it to a connection if one exists
* already. connection usually null.
*/
static <U> CompletableFuture<? extends ExchangeImpl<U>>
get(Exchange<U> exchange, HttpConnection connection)
{
if (exchange.version() == HTTP_1_1) {
if (debug.on())
debug.log("get: HTTP/1.1: new Http1Exchange");
return createHttp1Exchange(exchange, connection);
} else {
Http2ClientImpl c2 = exchange.client().client2(); // #### improve
HttpRequestImpl request = exchange.request();
CompletableFuture<Http2Connection> c2f = c2.getConnectionFor(request, exchange);
if (debug.on())
debug.log("get: Trying to get HTTP/2 connection");
// local variable required here; see JDK-8223553
CompletableFuture<CompletableFuture<? extends ExchangeImpl<U>>> fxi =
c2f.handle((h2c, t) -> createExchangeImpl(h2c, t, exchange, connection));
return fxi.thenCompose(x->x);
}
}
private static <U> CompletableFuture<? extends ExchangeImpl<U>>
createExchangeImpl(Http2Connection c,
Throwable t,
Exchange<U> exchange,
HttpConnection connection)
{
if (debug.on())
debug.log("handling HTTP/2 connection creation result");
boolean secure = exchange.request().secure();
if (t != null) {
if (debug.on())
debug.log("handling HTTP/2 connection creation failed: %s",
(Object)t);
t = Utils.getCompletionCause(t);
if (t instanceof Http2Connection.ALPNException) {
Http2Connection.ALPNException ee = (Http2Connection.ALPNException)t;
AbstractAsyncSSLConnection as = ee.getConnection();
if (debug.on())
debug.log("downgrading to HTTP/1.1 with: %s", as);
CompletableFuture<? extends ExchangeImpl<U>> ex =
createHttp1Exchange(exchange, as);
return ex;
} else {
if (debug.on())
debug.log("HTTP/2 connection creation failed "
+ "with unexpected exception: %s", (Object)t);
return MinimalFuture.failedFuture(t);
}
}
if (secure && c== null) {
if (debug.on())
debug.log("downgrading to HTTP/1.1 ");
CompletableFuture<? extends ExchangeImpl<U>> ex =
createHttp1Exchange(exchange, null);
return ex;
}
if (c == null) {
// no existing connection. Send request with HTTP 1 and then
// upgrade if successful
if (debug.on())
debug.log("new Http1Exchange, try to upgrade");
return createHttp1Exchange(exchange, connection)
.thenApply((e) -> {
exchange.h2Upgrade();
return e;
});
} else {
if (debug.on()) debug.log("creating HTTP/2 streams");
Stream<U> s = c.createStream(exchange);
CompletableFuture<? extends ExchangeImpl<U>> ex = MinimalFuture.completedFuture(s);
return ex;
}
}
private static <T> CompletableFuture<Http1Exchange<T>>
createHttp1Exchange(Exchange<T> ex, HttpConnection as)
{
try {
return MinimalFuture.completedFuture(new Http1Exchange<>(ex, as));
} catch (Throwable e) {
return MinimalFuture.failedFuture(e);
}
}
// Called for 204 response - when no body is permitted
void nullBody(HttpResponse<T> resp, Throwable t) {
// only needed for HTTP/1.1 to close the connection
// or return it to the pool
}
/* The following methods have separate HTTP/1.1 and HTTP/2 implementations */
abstract CompletableFuture<ExchangeImpl<T>> sendHeadersAsync();
/** Sends a request body, after request headers have been sent. */
abstract CompletableFuture<ExchangeImpl<T>> sendBodyAsync();
abstract CompletableFuture<T> readBodyAsync(HttpResponse.BodyHandler<T> handler,
boolean returnConnectionToPool,
Executor executor);
/**
* Ignore/consume the body.
*/
abstract CompletableFuture<Void> ignoreBody();
/** Gets the response headers. Completes before body is read. */
abstract CompletableFuture<Response> getResponseAsync(Executor executor);
/** Cancels a request. Not currently exposed through API. */
abstract void cancel();
/**
* Cancels a request with a cause. Not currently exposed through API.
*/
abstract void cancel(IOException cause);
/**
* Called when the exchange is released, so that cleanup actions may be
* performed - such as deregistering callbacks.
* Typically released is called during upgrade, when an HTTP/2 stream
* takes over from an Http1Exchange, or when a new exchange is created
* during a multi exchange before the final response body was received.
*/
abstract void released();
/**
* Called when the exchange is completed, so that cleanup actions may be
* performed - such as deregistering callbacks.
* Typically, completed is called at the end of the exchange, when the
* final response body has been received (or an error has caused the
* completion of the exchange).
*/
abstract void completed();
/**
* Returns true if this exchange was canceled.
* @return true if this exchange was canceled.
*/
abstract boolean isCanceled();
/**
* Returns the cause for which this exchange was canceled, if available.
* @return the cause for which this exchange was canceled, if available.
*/
abstract Throwable getCancelCause();
}
|
md-5/jdk10
|
src/java.net.http/share/classes/jdk/internal/net/http/ExchangeImpl.java
|
Java
|
gpl-2.0
| 8,811 |
/*
* (C) 1999-2003 Lars Knoll ([email protected])
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
* Copyright (C) 2011 Research In Motion Limited. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "PropertySetCSSStyleDeclaration.h"
#include "CSSCustomPropertyValue.h"
#include "CSSParser.h"
#include "CSSStyleSheet.h"
#include "HTMLNames.h"
#include "InspectorInstrumentation.h"
#include "MutationObserverInterestGroup.h"
#include "MutationRecord.h"
#include "StyleProperties.h"
#include "StyledElement.h"
namespace WebCore {
namespace {
class StyleAttributeMutationScope {
WTF_MAKE_NONCOPYABLE(StyleAttributeMutationScope);
public:
StyleAttributeMutationScope(PropertySetCSSStyleDeclaration* decl)
{
++s_scopeCount;
if (s_scopeCount != 1) {
ASSERT(s_currentDecl == decl);
return;
}
ASSERT(!s_currentDecl);
s_currentDecl = decl;
if (!s_currentDecl->parentElement())
return;
bool shouldReadOldValue = false;
m_mutationRecipients = MutationObserverInterestGroup::createForAttributesMutation(*s_currentDecl->parentElement(), HTMLNames::styleAttr);
if (m_mutationRecipients && m_mutationRecipients->isOldValueRequested())
shouldReadOldValue = true;
AtomicString oldValue;
if (shouldReadOldValue)
oldValue = s_currentDecl->parentElement()->getAttribute(HTMLNames::styleAttr);
if (m_mutationRecipients) {
AtomicString requestedOldValue = m_mutationRecipients->isOldValueRequested() ? oldValue : nullAtom;
m_mutation = MutationRecord::createAttributes(*s_currentDecl->parentElement(), HTMLNames::styleAttr, requestedOldValue);
}
}
~StyleAttributeMutationScope()
{
--s_scopeCount;
if (s_scopeCount)
return;
if (m_mutation && s_shouldDeliver)
m_mutationRecipients->enqueueMutationRecord(m_mutation);
s_shouldDeliver = false;
if (!s_shouldNotifyInspector) {
s_currentDecl = 0;
return;
}
// We have to clear internal state before calling Inspector's code.
PropertySetCSSStyleDeclaration* localCopyStyleDecl = s_currentDecl;
s_currentDecl = 0;
s_shouldNotifyInspector = false;
if (localCopyStyleDecl->parentElement())
InspectorInstrumentation::didInvalidateStyleAttr(localCopyStyleDecl->parentElement()->document(), *localCopyStyleDecl->parentElement());
}
void enqueueMutationRecord()
{
s_shouldDeliver = true;
}
void didInvalidateStyleAttr()
{
s_shouldNotifyInspector = true;
}
private:
static unsigned s_scopeCount;
static PropertySetCSSStyleDeclaration* s_currentDecl;
static bool s_shouldNotifyInspector;
static bool s_shouldDeliver;
std::unique_ptr<MutationObserverInterestGroup> m_mutationRecipients;
RefPtr<MutationRecord> m_mutation;
};
unsigned StyleAttributeMutationScope::s_scopeCount = 0;
PropertySetCSSStyleDeclaration* StyleAttributeMutationScope::s_currentDecl = 0;
bool StyleAttributeMutationScope::s_shouldNotifyInspector = false;
bool StyleAttributeMutationScope::s_shouldDeliver = false;
} // namespace
void PropertySetCSSStyleDeclaration::ref()
{
m_propertySet->ref();
}
void PropertySetCSSStyleDeclaration::deref()
{
m_propertySet->deref();
}
unsigned PropertySetCSSStyleDeclaration::length() const
{
return m_propertySet->propertyCount();
}
String PropertySetCSSStyleDeclaration::item(unsigned i) const
{
if (i >= m_propertySet->propertyCount())
return "";
return m_propertySet->propertyAt(i).cssName();
}
String PropertySetCSSStyleDeclaration::cssText() const
{
return m_propertySet->asText();
}
void PropertySetCSSStyleDeclaration::setCssText(const String& text, ExceptionCode&)
{
StyleAttributeMutationScope mutationScope(this);
if (!willMutate())
return;
bool changed = m_propertySet->parseDeclaration(text, contextStyleSheet());
didMutate(changed ? PropertyChanged : NoChanges);
mutationScope.enqueueMutationRecord();
}
RefPtr<CSSValue> PropertySetCSSStyleDeclaration::getPropertyCSSValue(const String& propertyName)
{
if (isCustomPropertyName(propertyName)) {
RefPtr<CSSValue> value = m_propertySet->getCustomPropertyCSSValue(propertyName);
if (!value)
return nullptr;
return cloneAndCacheForCSSOM(value.get());
}
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return nullptr;
return cloneAndCacheForCSSOM(m_propertySet->getPropertyCSSValue(propertyID).get());
}
String PropertySetCSSStyleDeclaration::getPropertyValue(const String& propertyName)
{
if (isCustomPropertyName(propertyName))
return m_propertySet->getCustomPropertyValue(propertyName);
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return String();
return m_propertySet->getPropertyValue(propertyID);
}
String PropertySetCSSStyleDeclaration::getPropertyPriority(const String& propertyName)
{
if (isCustomPropertyName(propertyName))
return m_propertySet->customPropertyIsImportant(propertyName) ? "important" : "";
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return String();
return m_propertySet->propertyIsImportant(propertyID) ? "important" : "";
}
String PropertySetCSSStyleDeclaration::getPropertyShorthand(const String& propertyName)
{
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return String();
return m_propertySet->getPropertyShorthand(propertyID);
}
bool PropertySetCSSStyleDeclaration::isPropertyImplicit(const String& propertyName)
{
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return false;
return m_propertySet->isPropertyImplicit(propertyID);
}
void PropertySetCSSStyleDeclaration::setProperty(const String& propertyName, const String& value, const String& priority, ExceptionCode& ec)
{
StyleAttributeMutationScope mutationScope(this);
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (isCustomPropertyName(propertyName))
propertyID = CSSPropertyCustom;
if (!propertyID)
return;
if (!willMutate())
return;
bool important = priority.find("important", 0, false) != notFound;
ec = 0;
bool changed = propertyID != CSSPropertyCustom ? m_propertySet->setProperty(propertyID, value, important, contextStyleSheet()) : m_propertySet->setCustomProperty(propertyName, value, important, contextStyleSheet());
didMutate(changed ? PropertyChanged : NoChanges);
if (changed) {
// CSS DOM requires raising SYNTAX_ERR of parsing failed, but this is too dangerous for compatibility,
// see <http://bugs.webkit.org/show_bug.cgi?id=7296>.
mutationScope.enqueueMutationRecord();
}
}
String PropertySetCSSStyleDeclaration::removeProperty(const String& propertyName, ExceptionCode& ec)
{
StyleAttributeMutationScope mutationScope(this);
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (isCustomPropertyName(propertyName))
propertyID = CSSPropertyCustom;
if (!propertyID)
return String();
if (!willMutate())
return String();
ec = 0;
String result;
bool changed = propertyID != CSSPropertyCustom ? m_propertySet->removeProperty(propertyID, &result) : m_propertySet->removeCustomProperty(propertyName, &result);
didMutate(changed ? PropertyChanged : NoChanges);
if (changed)
mutationScope.enqueueMutationRecord();
return result;
}
RefPtr<CSSValue> PropertySetCSSStyleDeclaration::getPropertyCSSValueInternal(CSSPropertyID propertyID)
{
return m_propertySet->getPropertyCSSValue(propertyID);
}
String PropertySetCSSStyleDeclaration::getPropertyValueInternal(CSSPropertyID propertyID)
{
return m_propertySet->getPropertyValue(propertyID);
}
bool PropertySetCSSStyleDeclaration::setPropertyInternal(CSSPropertyID propertyID, const String& value, bool important, ExceptionCode& ec)
{
StyleAttributeMutationScope mutationScope(this);
if (!willMutate())
return false;
ec = 0;
bool changed = m_propertySet->setProperty(propertyID, value, important, contextStyleSheet());
didMutate(changed ? PropertyChanged : NoChanges);
if (changed)
mutationScope.enqueueMutationRecord();
return changed;
}
CSSValue* PropertySetCSSStyleDeclaration::cloneAndCacheForCSSOM(CSSValue* internalValue)
{
if (!internalValue)
return 0;
// The map is here to maintain the object identity of the CSSValues over multiple invocations.
// FIXME: It is likely that the identity is not important for web compatibility and this code should be removed.
if (!m_cssomCSSValueClones)
m_cssomCSSValueClones = std::make_unique<HashMap<CSSValue*, RefPtr<CSSValue>>>();
RefPtr<CSSValue>& clonedValue = m_cssomCSSValueClones->add(internalValue, RefPtr<CSSValue>()).iterator->value;
if (!clonedValue)
clonedValue = internalValue->cloneForCSSOM();
return clonedValue.get();
}
StyleSheetContents* PropertySetCSSStyleDeclaration::contextStyleSheet() const
{
CSSStyleSheet* cssStyleSheet = parentStyleSheet();
return cssStyleSheet ? &cssStyleSheet->contents() : 0;
}
Ref<MutableStyleProperties> PropertySetCSSStyleDeclaration::copyProperties() const
{
return m_propertySet->mutableCopy();
}
StyleRuleCSSStyleDeclaration::StyleRuleCSSStyleDeclaration(MutableStyleProperties& propertySet, CSSRule& parentRule)
: PropertySetCSSStyleDeclaration(&propertySet)
, m_refCount(1)
, m_parentRule(&parentRule)
{
m_propertySet->ref();
}
StyleRuleCSSStyleDeclaration::~StyleRuleCSSStyleDeclaration()
{
m_propertySet->deref();
}
void StyleRuleCSSStyleDeclaration::ref()
{
++m_refCount;
}
void StyleRuleCSSStyleDeclaration::deref()
{
ASSERT(m_refCount);
if (!--m_refCount)
delete this;
}
bool StyleRuleCSSStyleDeclaration::willMutate()
{
if (!m_parentRule || !m_parentRule->parentStyleSheet())
return false;
m_parentRule->parentStyleSheet()->willMutateRules();
return true;
}
void StyleRuleCSSStyleDeclaration::didMutate(MutationType type)
{
ASSERT(m_parentRule);
ASSERT(m_parentRule->parentStyleSheet());
if (type == PropertyChanged)
m_cssomCSSValueClones = nullptr;
// Style sheet mutation needs to be signaled even if the change failed. willMutate*/didMutate* must pair.
m_parentRule->parentStyleSheet()->didMutateRuleFromCSSStyleDeclaration();
}
CSSStyleSheet* StyleRuleCSSStyleDeclaration::parentStyleSheet() const
{
return m_parentRule ? m_parentRule->parentStyleSheet() : 0;
}
void StyleRuleCSSStyleDeclaration::reattach(MutableStyleProperties& propertySet)
{
m_propertySet->deref();
m_propertySet = &propertySet;
m_propertySet->ref();
}
void InlineCSSStyleDeclaration::didMutate(MutationType type)
{
if (type == NoChanges)
return;
m_cssomCSSValueClones = nullptr;
if (!m_parentElement)
return;
m_parentElement->invalidateStyleAttribute();
StyleAttributeMutationScope(this).didInvalidateStyleAttr();
}
CSSStyleSheet* InlineCSSStyleDeclaration::parentStyleSheet() const
{
return m_parentElement ? &m_parentElement->document().elementSheet() : 0;
}
} // namespace WebCore
|
qtproject/qtwebkit
|
Source/WebCore/css/PropertySetCSSStyleDeclaration.cpp
|
C++
|
gpl-2.0
| 12,353 |
<?php
define("INVALID_VALUE", -1);
define("VALID_VALUE", 1);
/*abstract*/ class base_wp_option {
/* Name of the option, as it will be insrted in database. No funny charachters please! */
var $name;
/* Label of the option, as it will be shown on settings page */
var $label;
/* Type of the option - i.e. text option, checkbox option etc. Every option type is
subclass of Wp_option class, and its name is "wp_option_{$option_type}" */
var $type;
/* Value of the option when the use hasn't setuped it yet.*/
var $default_value;
/* Value of the option */
var $value;
/* Hash that keeps key-value pairs of custom HTML attributes */
var $html_attrs = array();
/* Extra "help" text to be displayed under the field on the options's admin form. */
var $help_text;
var $validation_error;
var $hidden = false;
/*static*/
function factory($opt_type, $name, $label=null) {
$class_name = "Wp_option_$opt_type";
if (!class_exists($class_name)) {
trigger_error("Cannot create option from type $opt_type -- unknown type", E_USER_ERROR);
}
if (empty($name)) {
trigger_error("Cannot create option without name", E_USER_ERROR);
}
if (preg_match('~[^a-zA-Z0-9_]~', $name)) {
trigger_error("Option name can include only latin letters, numbers, dashes and underscores,
\"$name\" is not valid option name", E_USER_ERROR);
}
if (is_null($label)) {
$label = ucwords(str_replace(array('_', '-'), ' ', $name));
}
return new $class_name($name, $label);
}
/* Cosntructor. Do not override, use init() instead */
/* final */ function base_wp_option($name, $label) {
$this->name = $name;
$this->label = $label;
$this->init();
if (defined('WP_ADMIN')) {
$this->admin_init();
}
}
/* Implement this in child classes if you need to do some initialization.
This will be called immediatlly after the constructor */
function init() {}
/* Same as above, but for amin */
function admin_init() {}
/* Collects information from input and setups object value */
/*public*/ function set_value_from_input() {
$this->set_value($_REQUEST[$this->name]);
}
/* This needs to be implemented in every child class */
/*abstract*/ function render() {}
function set_value($value) {
$this->value = $value;
}
/* You can setup HTML tag attributes via this field. Pass them in hash array where key is the attribute name
and value is attribute value, i.e.:
array(
'maxlength'=>'32',
'style'=>'width: 180px;'
)
*/
function set_html_attr($attrs) {
$this->html_attrs = $attrs;
}
function get_custom_attrs() {
$html_attrs = array();
foreach ($this->html_attrs as $key => $value) {
$html_attrs[] = $key . '="' . $value . '"';
}
return implode(' ', $html_attrs);
}
function help_text($help_text) {
$this->help_text = $help_text;
}
function get_error() {
return $this->validation_error;
}
function hide() {
$this->hidden = true;
}
}
// Base class for all options that use wordpress interface for managing options via
// add_option / update_option / get_option
/*abstract*/ class wp_option extends base_wp_option {
function init() {
$this->set_value(get_option($this->name));
}
function admin_init() {
if (isset($_GET['delete']) && $_GET['delete'] == $this->name) {
$this->reset_value();
}
}
function render($field_html, $colspan = false) {
$html = '
<tr valign="top" class="' . get_class($this) . ' field-' . $this->name . '" ' . ($this->hidden ? 'style="display: none; "' : '') . '>
<th scope="row" class="field-label"><label for="' . $this->name . '">' . $this->label . '</label></th>
<td class="field">' . $field_html . ' <span class="description">' . $this->help_text . '</span></td>
</tr>
';
return $html;
}
function save() {
$this->value = get_magic_quotes_gpc() ? stripslashes($this->value) : $this->value;
update_option($this->name, $this->value);
}
function set_default_value($default_vallue) {
$current_value = get_option($this->name);
if ($current_value) {
return;
}
$this->default_value = $default_vallue;
add_option($this->name, $default_vallue);
$this->set_value($default_vallue);
}
function reset_value() {
$this->value = $this->default_value;
$this->save();
}
function add_to_get($key, $val) {
return '?' . preg_replace('~&?' . preg_quote($key) . '(=|$|&)([^&]*)?~', '', $_SERVER['QUERY_STRING']) . '&' . $key . '=' . $val;
}
function get_reset_link() {
return $this->add_to_get('delete', $this->name);
}
}
// Most basic option -- single line text
class wp_option_text extends wp_option {
function init() {
wp_option::init();
$this->html_attrs = array_merge(
array('class'=>'regular-text'),
$this->html_attrs
);
}
function render() {
$field_html = '<input type="text" name="' . $this->name . '" value="' . $this->value . '" id="' . $this->name . '" ' . $this->get_custom_attrs() . ' />';
return wp_option::render($field_html);
}
}
class wp_option_int extends wp_option_text {
function set_value_from_input() {
$val = $_REQUEST[$this->name];
if (!is_numeric($val)) {
$this->validation_error = "should be integer";
return INVALID_VALUE;
}
$this->set_value($val);
}
}
//
class wp_option_textarea extends wp_option {
function admin_init() {
wp_option::admin_init();
$this->help_text($this->help_text);
$this->html_attrs = array_merge(
array(
'class'=>'regular-text',
'rows'=>'5',
/**/
'style'=>'width: 500px',
),
$this->html_attrs
);
}
function help_text($help_text) {
$this->help_text = "<br />$help_text";
}
function render() {
$field_html = '<textarea name="' . $this->name . '" id="' . $this->name . '" ' . $this->get_custom_attrs() . '>' . $this->value . '</textarea>';
return wp_option::render($field_html);
}
}
class wp_option_header_scripts extends wp_option_textarea {
var $help_text = 'If you need to add scripts to your header, you should enter them in this box.';
function init() {
wp_option_textarea::init();
add_action('wp_head', array($this, 'print_the_code'));
}
function print_the_code() {
echo get_option($this->name);
}
}
class wp_option_footer_scripts extends wp_option_textarea {
var $help_text = 'If you need to add scripts to your footer (like Google Analytics tracking code), you should enter them in this box.';
function init() {
wp_option_textarea::init();
add_action('wp_footer', array($this, 'print_the_code'));
}
function print_the_code() {
echo get_option($this->name);
}
}
/* */
class wp_option_choose_category extends wp_option {
function render() {
$dropdown_html = wp_dropdown_categories(array(
'name'=>$this->name,
'echo'=>false,
'hide_empty'=>false,
'hierarchical'=>1,
'exclude'=>1, // Exclude uncategorized
'selected'=>$this->value,
'show_option_none'=>'Please Choose',
));
return wp_option::render($dropdown_html);
}
}
class wp_option_choose_page extends wp_option {
function render() {
$dropdown_html = wp_dropdown_pages(array(
'name'=>$this->name,
'echo'=>false,
'hierarchical'=>1,
'selected'=>$this->value,
'show_option_none'=>'Please Choose',
));
return wp_option::render($dropdown_html);
}
}
/* */
class wp_option_select extends wp_option {
var $opts = array();
function add_options($opts) {
$this->opts = $opts;
}
function render() {
$html = '<select name="' . $this->name . '">';
foreach ($this->opts as $key => $value) {
$selected = '';
if ($key==$this->value) {
$selected = 'selected="selected"';
}
$html .= "\n";
$html .= '<option value="' . $key . '" ' . $selected . '>' . $value . '</option>';
}
$html .= '</select>';
return wp_option::render($html);
}
}
/**
*
*/
class wp_option_file extends wp_option {
/**
* http://xref.limb-project.com/tests_runner/lib/spikephpcoverage/src/util/Utility.php.source.txt
*
* Make directory recursively.
* (Taken from: http://aidan.dotgeek.org/lib/?file=function.mkdirr.php)
*
* @param $dir Directory path to create
* @param $mode=0755
* @return True on success, False on failure
* @access protected
*/
function mkdir_recursive($dir, $mode=0755) {
// Check if directory already exists
if (is_dir($dir) || empty($dir)) {
return true;
}
// Crawl up the directory tree
$next_pathname = substr($dir, 0, strrpos($dir, DIRECTORY_SEPARATOR));
if ($this->mkdir_recursive($next_pathname, $mode)) {
if (!file_exists($dir)) {
return mkdir($dir, $mode);
}
}
return false;
}
function render() {
$html = '<input type="file" name="' . $this->name . '" />';
if ($this->value) {
$html .= " Current File: <a href=" . get_option('upload_path') . $this->value . "'>Download</a>";
$html .= " | <a href='".$this->get_reset_link()."'>Delete</a>";
}
return wp_option::render($html);
}
function get_file_extension($filename) {
$ext = preg_replace('~.*\.~', '', $filename);
return $ext;
}
function validate_file() {
return VALID_VALUE;
}
function set_value_from_input() {
if (empty($_FILES) || !is_uploaded_file($_FILES[$this->name]['tmp_name'])) {
return;
}
$valid = $this->validate_file();
if ($valid == INVALID_VALUE) {
return $valid;
}
$upload_location = wp_upload_dir();
$upload_dir = $upload_location['path'];
$filename = preg_replace('~[^\w\.]~', '', $_FILES[$this->name]['name']);
$destination = $upload_dir . '/' . $filename;
$filename_ch = 1;
while (file_exists($destination)) {
$destination = $upload_dir . '/' . $filename_ch . '-' . $filename;
$filename_ch++;
}
if (copy($_FILES[$this->name]['tmp_name'], $destination)) {
if ($this->value && file_exists($upload_dir . $this->value)) {
unlink($upload_dir . $this->value);
}
$this->value = $upload_location['url'] . '/' . $filename;
return VALID_VALUE;
} else {
$this->validation_error = "Error occured while writing a file. Please check whether " . $upload_dir . " is a writable directory.";
return INVALID_VALUE;
}
}
}
// Emulate static propertie in PHP4
$wp_option_image__stylesheet_printed = false;
class wp_option_image extends wp_option_file {
function _print_stylesheet() {
global $wp_option_image__stylesheet_printed;
if ($wp_option_image__stylesheet_printed) {
return;
}
echo '<link rel="stylesheet" href="'. get_option('home') . '/wp-includes/js/thickbox/thickbox.css" type="text/css" media="screen" title="no title" charset="utf-8" />';
$wp_option_image__stylesheet_printed = true;
}
function admin_init() {
add_action('admin_head', array($this, '_print_stylesheet'));
wp_enqueue_script('thickbox');
wp_option_file::admin_init();
}
function render() {
$html = '<input type="file" name="' . $this->name . '" />';
if ($this->value) {
$html .= " <a href='".$this->value."?TB_width=800' class='thickbox'>View Current Image</a>";
$html .= " | <a href='".$this->get_reset_link()."'>Delete</a>";
}
return wp_option::render($html);
}
function validate_file() {
$valid = getimagesize($_FILES[$this->name]['tmp_name']);
if (!$valid) {
$this->validation_error = "The uploaded filetype is invalid (".$this->get_file_extension($_FILES[$this->name]['name']).").";
return INVALID_VALUE;
}
return VALID_VALUE;
}
}
$___tiny_mce_included = false;
$___tiny_mce_loaded = false;
class wp_option_rich_text extends wp_option_textarea {
function include_js() {
global $___tiny_mce_included;
if ($___tiny_mce_included) {
return;
}
$___tiny_mce_included = true;
echo '<script src="' . get_option('home') . '/wp-includes/js/tinymce/tiny_mce.js" type="text/javascript" charset="utf-8"></script>';
}
function admin_init() {
add_action('admin_head', array($this, 'include_js'));
wp_option_textarea::admin_init();
}
function render() {
global $___tiny_mce_loaded;
ob_start();
include('rich-text-field.php');
$field_html = ob_get_contents();
ob_end_clean();
$___tiny_mce_loaded = true;
return wp_option::render($field_html);
}
}
class wp_option_separator extends wp_option {
function render() {
$html = '
<tr valign="top">
<th colspan="2" scope="row" class="field-label"><h3>' . $this->label . '</h3></th>
</tr>
';
return $html;
}
function set_value_from_input() {
;
}
}
class wp_option_img_url extends wp_option_text {
function render() {
$field_html =
'<input type="text" name="' . $this->name . '" value="' . $this->value . '" id="' . $this->name . '" ' . $this->get_custom_attrs() . ' />' .
'<a onclick="return false;" title="Add an Image" class="thickbox" style="text-decoration: none" id="add_image" href="media-upload.php?post_id=0&type=image&TB_iframe=true&width=640&height=464"><img alt="Add an Image" src="images/media-button-image.gif"/> Open Media Gallery</a>';
return wp_option::render($field_html);
}
}
$wp_option_set__sort_js_printed = false;
class wp_option_set extends wp_option_text {
var $choices = array();
var $sortable = false;
function render() {
if (!is_array($this->value) || empty($this->value)) {
$this->value = array();
$current_values = array();
} else {
$current_values = array_combine($this->value, $this->value);
}
if ($this->sortable) {
$html = $this->render_as_sortable($current_values);
return wp_option::render($html);
}
ob_start();
?>
<?php $loopID = 0; foreach ($this->choices as $key => $label) : ?>
<input type="checkbox" name="<?php echo $this->name?>[]" <?php echo (isset($current_values[$key])) ? 'checked' : '';?> value="<?php echo $key?>" id="<?php echo $this->name?>_<?php echo $loopID?>" />
<label for="<?php echo $this->name?>_<?php echo $loopID?>"><?php echo $label?></label>
<br />
<?php $loopID ++; endforeach; ?>
<?php
$html = ob_get_contents();
ob_end_clean();
return wp_option::render($html);
}
function render_sort_js() {
global $wp_option_set__sort_js_printed;
if ($wp_option_set__sort_js_printed == true) {
return;
}
$wp_option_set__sort_js_printed = true;
?>
<script type="text/javascript" charset="utf-8">
(function ($) {
$('.sort-line .move-up').live('click', function () {
var holder = $(this).parents('.sort-line');
var move_data = $(holder).find('.sort-data .chunk').remove();
var moved_data = $(holder).prev().find('.sort-data .chunk').remove();
$(holder).prev().find('.sort-data').append(move_data);
$(holder).find('.sort-data').append(moved_data);
return false;
});
$('.sort-line .move-down').live('click', function () {
var holder = $(this).parents('.sort-line');
var move_data = $(holder).find('.sort-data .chunk').remove();
var moved_data = $(holder).next().find('.sort-data .chunk').remove();
$(holder).next().find('.sort-data').append(move_data);
$(holder).find('.sort-data').append(moved_data);
return false;
});
})(jQuery)
</script>
<?php
}
/* NOTE: In order sorting to work you need to use get_pages() + foreach because wp_list_pages() ignores the order you input IDs in the include= clause */
function render_as_sortable($current_values) {
$nice_choices = array();
if (!empty($current_values)) {
$sliced_choices = array_flip($this->choices);
foreach ($current_values as $val) {
$ind = array_search($val, array_values($sliced_choices));
if (!($ind === FALSE)) {
$nice_choices[$val] = $this->choices[$val];
if ($ind != 0) {
$sliced_choices = array_slice($sliced_choices, 0, $ind) + array_slice($sliced_choices, $ind + 1);
} else {
$sliced_choices = array_slice($sliced_choices, 1);
}
}
}
$sliced_choices = array_flip($sliced_choices);
$nice_choices = $nice_choices + $sliced_choices;
} else {
$nice_choices = $this->choices;
}
ob_start();
?>
<?php $loopID = 0; foreach ($nice_choices as $key => $label) : ?>
<div class="sort-line">
<div style="display: inline; float: left; width: 40px;">
<?php if ($loopID > 0) : ?>
<a href="#" class="move-up" style="display: block; float: left; width: 10px; margin-right: 5px; text-indent: -4000px; font-size: 0px; background: url(<?php bloginfo('stylesheet_directory'); ?>/lib/images/arrow-up.gif) no-repeat 0 5px;">Up</a>
<?php endif; ?>
<?php if ($loopID < count($this->choices) - 1) : ?>
<a href="#" class="move-down" style="display: block; float: left; width: 10px; text-indent: -4000px; font-size: 0px; background: url(<?php bloginfo('stylesheet_directory'); ?>/lib/images/arrow-down.gif) no-repeat 0 5px; <?php echo $loopID==0 ? 'margin-left: 15px;' : '' ?>">Down</a>
<?php endif; ?>
</div>
<div class="sort-data" style="display: inline; float: left;">
<div class="chunk">
<input type="checkbox" name="<?php echo $this->name?>[]" <?php echo (isset($current_values[$key])) ? 'checked' : '';?> value="<?php echo $key?>" id="<?php echo $this->name?>_<?php echo $loopID?>" />
<label for="<?php echo $this->name?>_<?php echo $loopID?>"><?php echo $label?></label>
</div>
</div>
<div class="clear" style="height: 0px; line-height: 0px; font-size: 0px;"> </div>
</div>
<?php $loopID ++; endforeach; ?>
<?php $this->render_sort_js(); ?>
<?php
$html = ob_get_contents();
ob_end_clean();
return $html;
}
function add_choices($array) {
$this->choices = $array;
}
function save() {
update_option($this->name, $this->value);
}
function create_sortable() {
$this->sortable = true;
return $this;
}
}
class wp_option_choose_pages extends wp_option_set {
function init() {
$raw_pages = get_pages('child_of=0&parent=0');
$nice_pages = array();
$raw_pages = is_array($raw_pages) ? $raw_pages : array();
foreach ($raw_pages as $p) {
$nice_pages[$p->ID] = $p->post_title;
}
$this->add_choices($nice_pages);
wp_option_set::init();
}
}
class wp_option_choose_categories extends wp_option_set {
function init() {
$raw_cats = get_categories();
$nice_cats = array();
foreach ($raw_cats as $c) {
$nice_cats[$c->term_id] = $c->name;
}
$this->add_choices($nice_cats);
wp_option_set::init();
}
}
class wp_option_choose_links_category extends wp_option_set {
function init() {
}
}
class wp_option_color extends wp_option_text {
var $html_class_name;
function admin_init() {
$token = wp_create_nonce(mt_rand());
$this->html_class_name = "colorpicker_$token";
$handle = 'jq_colorpicker';
$js_src = get_bloginfo('stylesheet_directory') . '/lib/theme-options/colorpicker/colorpicker.js';
$css_src = get_bloginfo('stylesheet_directory') . '/lib/theme-options/colorpicker/colorpicker.css';
$deps = array('jquery');
wp_enqueue_script($handle, $js_src, $deps);
wp_enqueue_style( $handle, $css_src);
// Append additional class name to the input
$current_class = '';
if (isset($this->html_attrs['class'])) {
$current_class = $this->html_attrs['class'];
}
$new_class = "$current_class $this->html_class_name alignleft";
$this->html_attrs['class'] = $new_class;
wp_option_text::admin_init();
add_action('admin_footer', array($this, 'print_js'));
}
function print_js() {
?>
<script type="text/javascript" charset="utf-8">
jQuery(function ($) {
$('.color-preview').click(function () {
$(this).prev().click();
})
$('.<?php echo $this->html_class_name ?>').ColorPicker({
onChange: function (e, hex) {
$('.<?php echo $this->html_class_name ?>').val('#' + hex);
$('.<?php echo $this->html_class_name ?>').next().css('background', '#' + hex);
},
onSubmit: function(hsb, hex, rgb, el) {
$(el).ColorPickerHide();
},
color: '<?php echo $this->value ?>',
});
});
</script>
<?php
}
function set_value_from_input() {
$color = $_REQUEST[$this->name];
$val = preg_match('~^#~', $color) ? $color : "#$color";
$this->set_value($val);
}
function render() {
$field_html = '<input type="text" name="' . $this->name . '" value="' . $this->value . '" id="' . $this->name . '" ' . $this->get_custom_attrs() . ' /><span style="background: ' . $this->value . '; width: 22px; float: left; margin: 2px 4px;" class="color-preview"> </span>';
return wp_option::render($field_html);
}
}
include_once("choose-color-scheme.php");
?>
|
CoordCulturaDigital-Minc/culturadigital.br
|
wp-content/themes/chocotheme/lib/theme-options/option-fields.php
|
PHP
|
gpl-2.0
| 24,496 |
/*
* Copyright 2013 Francisco Franco
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/device.h>
#include <linux/miscdevice.h>
#include "../../sound/soc/codecs/wcd9xxx-common.h"
#define SOUNDCONTROL_VERSION 0
extern void update_headphones_volume_boost(int vol_boost);
extern void update_mic_gain(int vol_boost);
extern int high_perf_mode;
/*
* Volume boost value
*/
int headphones_boost = 0;
int headphones_boost_limit = 20;
int headphones_boost_limit_min = -20;
/*
* Mic boost value
*/
int mic_boost = 0;
int mic_boost_limit = 20;
int mic_boost_limit_min = -20;
/*
* Sysfs get/set entries
*/
static ssize_t headphones_boost_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", headphones_boost);
}
static ssize_t headphones_boost_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
int new_val;
sscanf(buf, "%d", &new_val);
if (new_val != headphones_boost) {
if (new_val <= headphones_boost_limit_min)
new_val = headphones_boost_limit_min;
else if (new_val >= headphones_boost_limit)
new_val = headphones_boost_limit;
pr_info("New headphones_boost: %d\n", new_val);
headphones_boost = new_val;
update_headphones_volume_boost(headphones_boost);
}
return size;
}
static ssize_t mic_boost_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", mic_boost);
}
static ssize_t mic_boost_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
int new_val;
sscanf(buf, "%d", &new_val);
if (new_val != mic_boost) {
if (new_val <= mic_boost_limit_min)
new_val = mic_boost_limit_min;
else if (new_val >= mic_boost_limit)
new_val = mic_boost_limit;
pr_info("New mic_boost: %d\n", new_val);
mic_boost = new_val;
update_mic_gain(mic_boost);
}
return size;
}
static ssize_t hph_perf_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
size_t count = 0;
count += sprintf(buf, "%d\n", high_perf_mode);
return count;
}
static ssize_t hph_perf_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
if (buf[0] >= '0' && buf[0] <= '1' && buf[1] == '\n')
if (high_perf_mode != buf[0] - '0')
high_perf_mode = buf[0] - '0';
return count;
}
static ssize_t soundcontrol_version(struct device * dev, struct device_attribute * attr, char * buf)
{
return sprintf(buf, "%d\n", SOUNDCONTROL_VERSION);
}
static DEVICE_ATTR(volume_boost, 0664, headphones_boost_show,
headphones_boost_store);
static DEVICE_ATTR(mic_boost, 0664, mic_boost_show, mic_boost_store);
static DEVICE_ATTR(highperf_enabled, 0664, hph_perf_show, hph_perf_store);
static DEVICE_ATTR(version, 0664 , soundcontrol_version, NULL);
static struct attribute *soundcontrol_attributes[] =
{
&dev_attr_volume_boost.attr,
&dev_attr_mic_boost.attr,
&dev_attr_highperf_enabled.attr,
&dev_attr_version.attr,
NULL
};
static struct attribute_group soundcontrol_group =
{
.attrs = soundcontrol_attributes,
};
static struct miscdevice soundcontrol_device =
{
.minor = MISC_DYNAMIC_MINOR,
.name = "soundcontrol",
};
static int __init soundcontrol_init(void)
{
int ret;
pr_info("%s misc_register(%s)\n", __FUNCTION__, soundcontrol_device.name);
ret = misc_register(&soundcontrol_device);
if (ret) {
pr_err("%s misc_register(%s) fail\n", __FUNCTION__, soundcontrol_device.name);
return 1;
}
if (sysfs_create_group(&soundcontrol_device.this_device->kobj, &soundcontrol_group) < 0) {
pr_err("%s sysfs_create_group fail\n", __FUNCTION__);
pr_err("Failed to create sysfs group for device (%s)!\n", soundcontrol_device.name);
}
return 0;
}
late_initcall(soundcontrol_init);
|
Elite-Kernels/elite_shamu
|
drivers/misc/sound_control.c
|
C
|
gpl-2.0
| 3,956 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>CORE POS - Fannie: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if ($('.searchresults').length > 0) { searchBox.DOMSearchField().focus(); }
});
</script>
<link rel="search" href="search-opensearch.php?v=opensearch.xml" type="application/opensearchdescription+xml" title="CORE POS - Fannie"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">CORE POS - Fannie
</div>
<div id="projectbrief">The CORE POS back end</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.4 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<div class="left">
<form id="FSearchBox" action="search.php" method="get">
<img id="MSearchSelect" src="search/mag.png" alt=""/>
<input type="text" id="MSearchField" name="query" value="Search" size="20" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"/>
</form>
</div><div class="right"></div>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">LaneSecurityPage Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="class_lane_security_page.html">LaneSecurityPage</a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$description</b> (defined in <a class="el" href="class_lane_security_page.html">LaneSecurityPage</a>)</td><td class="entry"><a class="el" href="class_lane_security_page.html">LaneSecurityPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>$header</b> (defined in <a class="el" href="class_lane_security_page.html">LaneSecurityPage</a>)</td><td class="entry"><a class="el" href="class_lane_security_page.html">LaneSecurityPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$page_set</b> (defined in <a class="el" href="class_c_o_r_e_p_o_s_1_1_fannie_1_1_a_p_i_1_1_install_page.html">COREPOS\Fannie\API\InstallPage</a>)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1_fannie_1_1_a_p_i_1_1_install_page.html">COREPOS\Fannie\API\InstallPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>$required</b> (defined in <a class="el" href="class_c_o_r_e_p_o_s_1_1_fannie_1_1_a_p_i_1_1_install_page.html">COREPOS\Fannie\API\InstallPage</a>)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1_fannie_1_1_a_p_i_1_1_install_page.html">COREPOS\Fannie\API\InstallPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$title</b> (defined in <a class="el" href="class_lane_security_page.html">LaneSecurityPage</a>)</td><td class="entry"><a class="el" href="class_lane_security_page.html">LaneSecurityPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>__construct</b>() (defined in <a class="el" href="class_lane_security_page.html">LaneSecurityPage</a>)</td><td class="entry"><a class="el" href="class_lane_security_page.html">LaneSecurityPage</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_lane_security_page.html#a24d8e83e8a4fda43c2ea6175ec1464d0">body_content</a>()</td><td class="entry"><a class="el" href="class_lane_security_page.html">LaneSecurityPage</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1_fannie_1_1_a_p_i_1_1_install_page.html#ac51f7c62904f93ad574a74327552a334">getFooter</a>()</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1_fannie_1_1_a_p_i_1_1_install_page.html">COREPOS\Fannie\API\InstallPage</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1_fannie_1_1_a_p_i_1_1_install_page.html#aa1954c1fb162c32d7bb7a285efb943e3">getHeader</a>()</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1_fannie_1_1_a_p_i_1_1_install_page.html">COREPOS\Fannie\API\InstallPage</a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Thu Apr 2 2015 12:27:29 for CORE POS - Fannie by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.4
</small></address>
</body>
</html>
|
GeorgeStreetCoop/CORE-POS
|
documentation/doxy/output/fannie/html/class_lane_security_page-members.html
|
HTML
|
gpl-2.0
| 6,455 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="hevea 1.10">
<LINK rel="stylesheet" type="text/css" href="cascmd_en.css">
<TITLE>Individual attributes</TITLE>
</HEAD>
<BODY >
<A HREF="cascmd_en463.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A>
<A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A>
<A HREF="cascmd_en465.html"><IMG SRC="next_motif.gif" ALT="Next"></A>
<HR>
<H3 CLASS="subsection"><A NAME="htoc522">3.1.1</A> Individual attributes</H3><P><A NAME="@default761"></A><A NAME="@default762"></A>
<A NAME="@default763"></A><A NAME="@default764"></A><A NAME="@default765"></A><A NAME="@default766"></A><A NAME="@default767"></A><A NAME="@default768"></A><A NAME="@default769"></A><A NAME="@default770"></A><A NAME="@default771"></A>
Graphic attributes are optional arguments of the
form <TT>display=value</TT>, they must be given
as last argument of a graphic instruction. Attributes
are ordered in several categories: color, point shape, point width,
line style, line thickness, legend value, position and presence.
In addition, surfaces may be filled or not, 3-d surfaces
may be filled with a texture, 3-d objects may also have properties
with respect to the light.
Attributes of different categories
may be added, e.g.<BR>
<TT>plotfunc(</TT><TT><I>x</I></TT><SUP><TT>2</TT></SUP><TT>+<I>y</I></TT><SUP><TT>2</TT></SUP><TT>,[x,y],display=red+line_width_3+filled</TT>
</P><UL CLASS="itemize"><LI CLASS="li-itemize">
Colors <TT>display=</TT> or <TT>color=</TT>
<UL CLASS="itemize"><LI CLASS="li-itemize">
<TT>black</TT>, <TT>white</TT>, <TT>red</TT>, <TT>blue</TT>, <TT>green</TT>,
<TT>magenta</TT>, <TT>cyan</TT>, <TT>yellow</TT>,
</LI><LI CLASS="li-itemize">a numeric value between 0 and 255,
</LI><LI CLASS="li-itemize">a numeric value between 256 and 256+7*16+14 for a color of the
rainbow,
</LI><LI CLASS="li-itemize">any other numeric value smaller than 65535, the rendering
is not garanteed to be portable.
</LI></UL>
</LI><LI CLASS="li-itemize">Point shapes <TT>display=</TT> one of the following value
<TT>rhombus_point plus_point square_point cross_point
triangle_point star_point point_point invisible_point</TT>
</LI><LI CLASS="li-itemize">Point width: <TT>display=</TT> one of the following value
<TT>point_width_n</TT> where <TT>n</TT> is an
integer between 1 and 7
</LI><LI CLASS="li-itemize">Line thickness: <TT>thickness=n</TT>
or <TT>display=line_width_n</TT> where <TT>n</TT> is an
integer between 1 and 7 or
</LI><LI CLASS="li-itemize">Line shape: <TT>display=</TT> one of the following value
<TT>dash_line solid_line dashdot_line dashdotdot_line
cap_flat_line cap_square_line cap_round_line </TT>
</LI><LI CLASS="li-itemize">Legend, value: <TT>legend="legendname"</TT>;
position: <TT>display=</TT> one of
<TT>quandrant1 quadrant2 quadrant3 quadrant4</TT>
corresponding to the position of the legend of the object
(using the trigonometric plan conventions).
The legend is not displayed if the attribute
<TT>display=hidden_name</TT> is added
</LI><LI CLASS="li-itemize"><TT>display=filled</TT> specifies that surfaces will be filled,
</LI><LI CLASS="li-itemize"><TT>gl_texture="picture_filename"</TT> is used to fill
a surface with a texture.
Cf. the interface manual for a more complete
description and for <TT>gl_material=</TT> options.
</LI></UL><P>
<B>Examples</B>
Input
</P><DIV CLASS="center"><TT>polygon(-1,-i,1,2*i,legend="P")</TT></DIV><P>
Input
</P><DIV CLASS="center"><TT>point(1+i,legend="hello")</TT></DIV><P>
Input
</P><DIV CLASS="center"><TT>A:=point(1+i);B:=point(-1);display(D:=droite(A,B),hidden_name)</TT></DIV><P>
Input
</P><DIV CLASS="center"><TT>color(segment(0,1+i),red)</TT></DIV><P>
Input
</P><DIV CLASS="center"><TT>segment(0,1+i,color=red)</TT></DIV><HR>
<A HREF="cascmd_en463.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A>
<A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A>
<A HREF="cascmd_en465.html"><IMG SRC="next_motif.gif" ALT="Next"></A>
</BODY>
</HTML>
|
hiplayer/giac
|
giac/giac-1.2.2/doc/en/cascmd_en/cascmd_en464.html
|
HTML
|
gpl-2.0
| 4,159 |
import unittest
class Test_motion(unittest.TestCase):
pass
if __name__ == "__main__":
unittest.main()
|
rizen1892/SmartHomeSolutions-Web
|
app/motion_tests.py
|
Python
|
gpl-2.0
| 112 |
<?php
/**
* Widget API: WP_Widget_Recent_Posts class
*
* @package WordPress
* @subpackage Widgets
* @since 4.4.0
*/
/**
* Core class used to implement a Recent Posts widget.
*
* @since 2.8.0
*
* @see WP_Widget
*/
class WP_Widget_Recent_Posts extends WP_Widget {
/**
* Sets up a new Recent Posts widget instance.
*
* @since 2.8.0
*/
public function __construct() {
$widget_ops = array(
'classname' => 'widget_recent_entries',
'description' => __( 'Your site’s most recent Posts.' ),
'customize_selective_refresh' => true,
);
parent::__construct( 'recent-posts', __( 'Recent Posts' ), $widget_ops );
$this->alt_option_name = 'widget_recent_entries';
}
/**
* Outputs the content for the current Recent Posts widget instance.
*
* @since 2.8.0
*
* @param array $args Display arguments including 'before_title', 'after_title',
* 'before_widget', and 'after_widget'.
* @param array $instance Settings for the current Recent Posts widget instance.
*/
public function widget( $args, $instance ) {
if ( ! isset( $args['widget_id'] ) ) {
$args['widget_id'] = $this->id;
}
$title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : __( 'Recent Posts' );
/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
$number = ( ! empty( $instance['number'] ) ) ? absint( $instance['number'] ) : 5;
if ( ! $number ) {
$number = 5;
}
$show_date = isset( $instance['show_date'] ) ? $instance['show_date'] : false;
$r = new WP_Query(
/**
* Filters the arguments for the Recent Posts widget.
*
* @since 3.4.0
* @since 4.9.0 Added the `$instance` parameter.
*
* @see WP_Query::get_posts()
*
* @param array $args An array of arguments used to retrieve the recent posts.
* @param array $instance Array of settings for the current widget.
*/
apply_filters(
'widget_posts_args',
array(
'posts_per_page' => $number,
'no_found_rows' => true,
'post_status' => 'publish',
'ignore_sticky_posts' => true,
),
$instance
)
);
if ( ! $r->have_posts() ) {
return;
}
?>
<?php echo $args['before_widget']; ?>
<?php
if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
}
?>
<ul>
<?php foreach ( $r->posts as $recent_post ) : ?>
<?php
$post_title = get_the_title( $recent_post->ID );
$title = ( ! empty( $post_title ) ) ? $post_title : __( '(no title)' );
$aria_current = '';
if ( get_queried_object_id() === $recent_post->ID ) {
$aria_current = ' aria-current="page"';
}
?>
<li>
<a href="<?php the_permalink( $recent_post->ID ); ?>"<?php echo $aria_current; ?>><?php echo $title; ?></a>
<?php if ( $show_date ) : ?>
<span class="post-date"><?php echo get_the_date( '', $recent_post->ID ); ?></span>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php
echo $args['after_widget'];
}
/**
* Handles updating the settings for the current Recent Posts widget instance.
*
* @since 2.8.0
*
* @param array $new_instance New settings for this instance as input by the user via
* WP_Widget::form().
* @param array $old_instance Old settings for this instance.
* @return array Updated settings to save.
*/
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = sanitize_text_field( $new_instance['title'] );
$instance['number'] = (int) $new_instance['number'];
$instance['show_date'] = isset( $new_instance['show_date'] ) ? (bool) $new_instance['show_date'] : false;
return $instance;
}
/**
* Outputs the settings form for the Recent Posts widget.
*
* @since 2.8.0
*
* @param array $instance Current settings.
*/
public function form( $instance ) {
$title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
$number = isset( $instance['number'] ) ? absint( $instance['number'] ) : 5;
$show_date = isset( $instance['show_date'] ) ? (bool) $instance['show_date'] : false;
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of posts to show:' ); ?></label>
<input class="tiny-text" id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" type="number" step="1" min="1" value="<?php echo $number; ?>" size="3" />
</p>
<p>
<input class="checkbox" type="checkbox"<?php checked( $show_date ); ?> id="<?php echo $this->get_field_id( 'show_date' ); ?>" name="<?php echo $this->get_field_name( 'show_date' ); ?>" />
<label for="<?php echo $this->get_field_id( 'show_date' ); ?>"><?php _e( 'Display post date?' ); ?></label>
</p>
<?php
}
}
|
Asif2BD/WordPress
|
wp-includes/widgets/class-wp-widget-recent-posts.php
|
PHP
|
gpl-2.0
| 5,261 |
// This file is part of Hermes2D.
//
// Hermes2D is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Hermes2D is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Hermes2D. If not, see <http://www.gnu.org/licenses/>.
#ifndef __H2D_NORM_H
#define __H2D_NORM_H
#include "solution.h"
#include "refmap.h"
extern H2D_API double calc_error(double (*fn)(MeshFunction*, MeshFunction*, RefMap*, RefMap*), MeshFunction* sln1, MeshFunction* sln2);
extern H2D_API double calc_norm(double (*fn)(MeshFunction*, RefMap*), MeshFunction* sln);
extern H2D_API double error_fn_l2(MeshFunction* sln1, MeshFunction* sln2, RefMap* ru, RefMap* rv);
extern H2D_API double norm_fn_l2(MeshFunction* sln, RefMap* ru);
extern H2D_API double l2_error(MeshFunction* sln1, MeshFunction* sln2);
extern H2D_API double l2_norm(MeshFunction* sln);
extern H2D_API double error_fn_h1(MeshFunction* sln1, MeshFunction* sln2, RefMap* ru, RefMap* rv);
extern H2D_API double norm_fn_h1(MeshFunction* sln, RefMap* ru);
extern H2D_API double h1_error(MeshFunction* sln1, MeshFunction* sln2);
extern H2D_API double h1_norm(MeshFunction* sln);
#ifdef H2D_COMPLEX
extern H2D_API double error_fn_hc(MeshFunction* sln1, MeshFunction* sln2, RefMap* ru, RefMap* rv);
extern H2D_API double norm_fn_hc(MeshFunction* sln, RefMap* ru);
extern H2D_API double hcurl_error(MeshFunction* sln1, MeshFunction* sln2);
extern H2D_API double hcurl_norm(MeshFunction* sln);
extern H2D_API double error_fn_hcl2(MeshFunction* sln1, MeshFunction* sln2, RefMap* ru, RefMap* rv);
extern H2D_API double norm_fn_hcl2(MeshFunction* sln, RefMap* ru);
extern H2D_API double hcurl_l2error(MeshFunction* sln1, MeshFunction* sln2);
extern H2D_API double hcurl_l2norm(MeshFunction* sln);
#endif
#endif
|
davidquantum/hermes2d
|
src/norm.h
|
C
|
gpl-2.0
| 2,188 |
//Kevin Green
//11:34 2015-10-29
package se.arbetsgrupp.ioproject;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public final class FileRW
{
public static Object Read(String filename) throws FileNotFoundException, IOException, ClassNotFoundException
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
Object returnthis = in.readObject();
in.close();
return returnthis;
}
public static void Write(Object inobj, String filename) throws IOException
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
out.writeObject(inobj);
out.close();
}
public void close()
{
// Nothing
}
}
|
kjrgreen/se.arbetsgrupp.ioproject
|
src/se/arbetsgrupp/ioproject/FileRW.java
|
Java
|
gpl-2.0
| 816 |
// CS0118: `x.a.B' is a `property' but a `type' was expected
// Line: 9
using System;
namespace x
{
class a
{
bool B { set {} }
void Test (B b) {}
}
}
|
xen2/mcs
|
errors/cs0118-4.cs
|
C#
|
gpl-2.0
| 162 |
<div class="<?php echo $this -> pre; ?>couponform">
<small><?php _e('Do you have a discount coupon code?', $this -> plugin_name); ?></small>
<form class="<?php echo $this -> pre; ?>" action="" method="post">
<input type="hidden" name="<?php echo $this -> pre; ?>method" value="applycoupon" />
<input type="text" class="<?php echo $this -> pre; ?>couponcodeinput" name="code" value="<?php echo esc_attr(stripslashes($_POST['code'])); ?>" />
<input class="<?php echo $this -> pre; ?>button" style="cursor:pointer;" type="submit" name="applycode" value="<?php _e('Apply Code', $this -> plugin_name); ?>" />
</form>
</div>
|
jillrdoty/MayDuganGiveCamp13
|
wp-content/plugins/wp-checkout/views/simpleblue/couponform.php
|
PHP
|
gpl-2.0
| 658 |
<?php include 'view/header.php'; ?>
<?php include 'view/sidebar_admin.php'; ?>
<div id="content">
<h1>Category Manager</h1>
<table id="category_table">
<?php foreach ($categories as $category) : ?>
<tr>
<form action="" method="post" >
<td>
<input type="text" name="name"
value="<?php echo $category['categoryName']; ?>" />
</td>
<td>
<input type="hidden" name="action" value="update_category" />
<input type="hidden" name="category_id"
value="<?php echo $category['categoryID']; ?>"/>
<input type="submit" value="Update"/>
</td>
</form>
<td>
<?php if ($category['productCount'] == 0) : ?>
<form action="" method="post" >
<input type="hidden" name="action" value="delete_category" />
<input type="hidden" name="category_id"
value="<?php echo $category['categoryID']; ?>" />
<input type="submit" value="Delete" />
</form>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<h2>Add Category</h2>
<form action="" method="post" id="add_category_form" >
<input type="hidden" name="action" value="add_category" />
<input type="input" name="name" />
<input type="submit" value="Add"/>
</form>
</div>
<?php include 'view/footer.php'; ?>
|
efuste/murachphp
|
ex_starts/ch24_ex2/admin/category/category_list.php
|
PHP
|
gpl-2.0
| 1,576 |
/* tulip_core.c: A DEC 21x4x-family ethernet driver for Linux. */
/*
Maintained by Jeff Garzik <[email protected]>
Copyright 2000,2001 The Linux Kernel Team
Written/copyright 1994-2001 by Donald Becker.
This software may be used and distributed according to the terms
of the GNU General Public License, incorporated herein by reference.
Please refer to Documentation/DocBook/tulip-user.{pdf,ps,html}
for more information on this driver, or visit the project
Web page at http://sourceforge.net/projects/tulip/
*/
#include <linux/config.h>
#define DRV_NAME "tulip"
#ifdef CONFIG_TULIP_NAPI
#define DRV_VERSION "1.1.13-NAPI" /* Keep at least for test */
#else
#define DRV_VERSION "1.1.13"
#endif
#define DRV_RELDATE "May 11, 2002"
#include <linux/module.h>
#include <linux/pci.h>
#include "tulip.h"
#include <linux/init.h>
#include <linux/etherdevice.h>
#include <linux/delay.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/crc32.h>
#include <asm/unaligned.h>
#include <asm/uaccess.h>
#ifdef __sparc__
#include <asm/pbm.h>
#endif
static char version[] __devinitdata =
"Linux Tulip driver version " DRV_VERSION " (" DRV_RELDATE ")\n";
/* A few user-configurable values. */
/* Maximum events (Rx packets, etc.) to handle at each interrupt. */
static unsigned int max_interrupt_work = 25;
#define MAX_UNITS 8
/* Used to pass the full-duplex flag, etc. */
static int full_duplex[MAX_UNITS];
static int options[MAX_UNITS];
static int mtu[MAX_UNITS]; /* Jumbo MTU for interfaces. */
/* The possible media types that can be set in options[] are: */
const char * const medianame[32] = {
"10baseT", "10base2", "AUI", "100baseTx",
"10baseT-FDX", "100baseTx-FDX", "100baseT4", "100baseFx",
"100baseFx-FDX", "MII 10baseT", "MII 10baseT-FDX", "MII",
"10baseT(forced)", "MII 100baseTx", "MII 100baseTx-FDX", "MII 100baseT4",
"MII 100baseFx-HDX", "MII 100baseFx-FDX", "Home-PNA 1Mbps", "Invalid-19",
"","","","", "","","","", "","","","Transceiver reset",
};
/* Set the copy breakpoint for the copy-only-tiny-buffer Rx structure. */
#if defined(__alpha__) || defined(__arm__) || defined(__hppa__) \
|| defined(__sparc_) || defined(__ia64__) \
|| defined(__sh__) || defined(__mips__)
static int rx_copybreak = 1518;
#else
static int rx_copybreak = 100;
#endif
/*
Set the bus performance register.
Typical: Set 16 longword cache alignment, no burst limit.
Cache alignment bits 15:14 Burst length 13:8
0000 No alignment 0x00000000 unlimited 0800 8 longwords
4000 8 longwords 0100 1 longword 1000 16 longwords
8000 16 longwords 0200 2 longwords 2000 32 longwords
C000 32 longwords 0400 4 longwords
Warning: many older 486 systems are broken and require setting 0x00A04800
8 longword cache alignment, 8 longword burst.
ToDo: Non-Intel setting could be better.
*/
#if defined(__alpha__) || defined(__ia64__) || defined(__x86_64__)
static int csr0 = 0x01A00000 | 0xE000;
#elif defined(__i386__) || defined(__powerpc__)
static int csr0 = 0x01A00000 | 0x8000;
#elif defined(__sparc__) || defined(__hppa__)
/* The UltraSparc PCI controllers will disconnect at every 64-byte
* crossing anyways so it makes no sense to tell Tulip to burst
* any more than that.
*/
static int csr0 = 0x01A00000 | 0x9000;
#elif defined(__arm__) || defined(__sh__)
static int csr0 = 0x01A00000 | 0x4800;
#elif defined(__mips__)
static int csr0 = 0x00200000 | 0x4000;
#else
#warning Processor architecture undefined!
static int csr0 = 0x00A00000 | 0x4800;
#endif
/* Operational parameters that usually are not changed. */
/* Time in jiffies before concluding the transmitter is hung. */
#define TX_TIMEOUT (4*HZ)
MODULE_AUTHOR("The Linux Kernel Team");
MODULE_DESCRIPTION("Digital 21*4* Tulip ethernet driver");
MODULE_LICENSE("GPL");
MODULE_PARM(tulip_debug, "i");
MODULE_PARM(max_interrupt_work, "i");
MODULE_PARM(rx_copybreak, "i");
MODULE_PARM(csr0, "i");
MODULE_PARM(options, "1-" __MODULE_STRING(MAX_UNITS) "i");
MODULE_PARM(full_duplex, "1-" __MODULE_STRING(MAX_UNITS) "i");
#define PFX DRV_NAME ": "
#ifdef TULIP_DEBUG
int tulip_debug = TULIP_DEBUG;
#else
int tulip_debug = 1;
#endif
/*
* This table use during operation for capabilities and media timer.
*
* It is indexed via the values in 'enum chips'
*/
struct tulip_chip_table tulip_tbl[] = {
{ }, /* placeholder for array, slot unused currently */
{ }, /* placeholder for array, slot unused currently */
/* DC21140 */
{ "Digital DS21140 Tulip", 128, 0x0001ebef,
HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM | HAS_PCI_MWI, tulip_timer },
/* DC21142, DC21143 */
{ "Digital DS21143 Tulip", 128, 0x0801fbff,
HAS_MII | HAS_MEDIA_TABLE | ALWAYS_CHECK_MII | HAS_ACPI | HAS_NWAY
| HAS_INTR_MITIGATION | HAS_PCI_MWI, t21142_timer },
/* LC82C168 */
{ "Lite-On 82c168 PNIC", 256, 0x0001fbef,
HAS_MII | HAS_PNICNWAY, pnic_timer },
/* MX98713 */
{ "Macronix 98713 PMAC", 128, 0x0001ebef,
HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM, mxic_timer },
/* MX98715 */
{ "Macronix 98715 PMAC", 256, 0x0001ebef,
HAS_MEDIA_TABLE, mxic_timer },
/* MX98725 */
{ "Macronix 98725 PMAC", 256, 0x0001ebef,
HAS_MEDIA_TABLE, mxic_timer },
/* AX88140 */
{ "ASIX AX88140", 128, 0x0001fbff,
HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM | MC_HASH_ONLY
| IS_ASIX, tulip_timer },
/* PNIC2 */
{ "Lite-On PNIC-II", 256, 0x0801fbff,
HAS_MII | HAS_NWAY | HAS_8023X | HAS_PCI_MWI, pnic2_timer },
/* COMET */
{ "ADMtek Comet", 256, 0x0001abef,
HAS_MII | MC_HASH_ONLY | COMET_MAC_ADDR, comet_timer },
/* COMPEX9881 */
{ "Compex 9881 PMAC", 128, 0x0001ebef,
HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM, mxic_timer },
/* I21145 */
{ "Intel DS21145 Tulip", 128, 0x0801fbff,
HAS_MII | HAS_MEDIA_TABLE | ALWAYS_CHECK_MII | HAS_ACPI
| HAS_NWAY | HAS_PCI_MWI, t21142_timer },
/* DM910X */
{ "Davicom DM9102/DM9102A", 128, 0x0001ebef,
HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM | HAS_ACPI,
tulip_timer },
/* RS7112 */
{ "Conexant LANfinity", 256, 0x0001ebef,
HAS_MII | HAS_ACPI, tulip_timer },
};
static struct pci_device_id tulip_pci_tbl[] = {
{ 0x1011, 0x0009, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DC21140 },
{ 0x1011, 0x0019, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DC21143 },
{ 0x11AD, 0x0002, PCI_ANY_ID, PCI_ANY_ID, 0, 0, LC82C168 },
{ 0x10d9, 0x0512, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MX98713 },
{ 0x10d9, 0x0531, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MX98715 },
/* { 0x10d9, 0x0531, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MX98725 },*/
{ 0x125B, 0x1400, PCI_ANY_ID, PCI_ANY_ID, 0, 0, AX88140 },
{ 0x11AD, 0xc115, PCI_ANY_ID, PCI_ANY_ID, 0, 0, PNIC2 },
{ 0x1317, 0x0981, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x1317, 0x0985, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x1317, 0x1985, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x1317, 0x9511, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x13D1, 0xAB02, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x13D1, 0xAB03, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x13D1, 0xAB08, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x104A, 0x0981, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x104A, 0x2774, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x1259, 0xa120, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x11F6, 0x9881, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMPEX9881 },
{ 0x8086, 0x0039, PCI_ANY_ID, PCI_ANY_ID, 0, 0, I21145 },
{ 0x1282, 0x9100, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DM910X },
{ 0x1282, 0x9102, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DM910X },
{ 0x1113, 0x1216, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x1113, 0x1217, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MX98715 },
{ 0x1113, 0x9511, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x1186, 0x1541, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x1186, 0x1561, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x14f1, 0x1803, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CONEXANT },
{ 0x1626, 0x8410, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x1737, 0xAB09, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x1737, 0xAB08, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x17B3, 0xAB08, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
{ 0x10b9, 0x5261, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DM910X }, /* ALi 1563 integrated ethernet */
{ 0x10b7, 0x9300, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, /* 3Com 3CSOHO100B-TX */
{ } /* terminate list */
};
MODULE_DEVICE_TABLE(pci, tulip_pci_tbl);
/* A full-duplex map for media types. */
const char tulip_media_cap[32] =
{0,0,0,16, 3,19,16,24, 27,4,7,5, 0,20,23,20, 28,31,0,0, };
static void tulip_tx_timeout(struct net_device *dev);
static void tulip_init_ring(struct net_device *dev);
static int tulip_start_xmit(struct sk_buff *skb, struct net_device *dev);
static int tulip_open(struct net_device *dev);
static int tulip_close(struct net_device *dev);
static void tulip_up(struct net_device *dev);
static void tulip_down(struct net_device *dev);
static struct net_device_stats *tulip_get_stats(struct net_device *dev);
static int private_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
static void set_rx_mode(struct net_device *dev);
#ifdef CONFIG_NET_POLL_CONTROLLER
static void poll_tulip(struct net_device *dev);
#endif
static void tulip_set_power_state (struct tulip_private *tp,
int sleep, int snooze)
{
if (tp->flags & HAS_ACPI) {
u32 tmp, newtmp;
pci_read_config_dword (tp->pdev, CFDD, &tmp);
newtmp = tmp & ~(CFDD_Sleep | CFDD_Snooze);
if (sleep)
newtmp |= CFDD_Sleep;
else if (snooze)
newtmp |= CFDD_Snooze;
if (tmp != newtmp)
pci_write_config_dword (tp->pdev, CFDD, newtmp);
}
}
static void tulip_up(struct net_device *dev)
{
struct tulip_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->base_addr;
int next_tick = 3*HZ;
int i;
/* Wake the chip from sleep/snooze mode. */
tulip_set_power_state (tp, 0, 0);
/* On some chip revs we must set the MII/SYM port before the reset!? */
if (tp->mii_cnt || (tp->mtable && tp->mtable->has_mii))
iowrite32(0x00040000, ioaddr + CSR6);
/* Reset the chip, holding bit 0 set at least 50 PCI cycles. */
iowrite32(0x00000001, ioaddr + CSR0);
udelay(100);
/* Deassert reset.
Wait the specified 50 PCI cycles after a reset by initializing
Tx and Rx queues and the address filter list. */
iowrite32(tp->csr0, ioaddr + CSR0);
udelay(100);
if (tulip_debug > 1)
printk(KERN_DEBUG "%s: tulip_up(), irq==%d.\n", dev->name, dev->irq);
iowrite32(tp->rx_ring_dma, ioaddr + CSR3);
iowrite32(tp->tx_ring_dma, ioaddr + CSR4);
tp->cur_rx = tp->cur_tx = 0;
tp->dirty_rx = tp->dirty_tx = 0;
if (tp->flags & MC_HASH_ONLY) {
u32 addr_low = le32_to_cpu(get_unaligned((u32 *)dev->dev_addr));
u32 addr_high = le16_to_cpu(get_unaligned((u16 *)(dev->dev_addr+4)));
if (tp->chip_id == AX88140) {
iowrite32(0, ioaddr + CSR13);
iowrite32(addr_low, ioaddr + CSR14);
iowrite32(1, ioaddr + CSR13);
iowrite32(addr_high, ioaddr + CSR14);
} else if (tp->flags & COMET_MAC_ADDR) {
iowrite32(addr_low, ioaddr + 0xA4);
iowrite32(addr_high, ioaddr + 0xA8);
iowrite32(0, ioaddr + 0xAC);
iowrite32(0, ioaddr + 0xB0);
}
} else {
/* This is set_rx_mode(), but without starting the transmitter. */
u16 *eaddrs = (u16 *)dev->dev_addr;
u16 *setup_frm = &tp->setup_frame[15*6];
dma_addr_t mapping;
/* 21140 bug: you must add the broadcast address. */
memset(tp->setup_frame, 0xff, sizeof(tp->setup_frame));
/* Fill the final entry of the table with our physical address. */
*setup_frm++ = eaddrs[0]; *setup_frm++ = eaddrs[0];
*setup_frm++ = eaddrs[1]; *setup_frm++ = eaddrs[1];
*setup_frm++ = eaddrs[2]; *setup_frm++ = eaddrs[2];
mapping = pci_map_single(tp->pdev, tp->setup_frame,
sizeof(tp->setup_frame),
PCI_DMA_TODEVICE);
tp->tx_buffers[tp->cur_tx].skb = NULL;
tp->tx_buffers[tp->cur_tx].mapping = mapping;
/* Put the setup frame on the Tx list. */
tp->tx_ring[tp->cur_tx].length = cpu_to_le32(0x08000000 | 192);
tp->tx_ring[tp->cur_tx].buffer1 = cpu_to_le32(mapping);
tp->tx_ring[tp->cur_tx].status = cpu_to_le32(DescOwned);
tp->cur_tx++;
}
tp->saved_if_port = dev->if_port;
if (dev->if_port == 0)
dev->if_port = tp->default_port;
/* Allow selecting a default media. */
i = 0;
if (tp->mtable == NULL)
goto media_picked;
if (dev->if_port) {
int looking_for = tulip_media_cap[dev->if_port] & MediaIsMII ? 11 :
(dev->if_port == 12 ? 0 : dev->if_port);
for (i = 0; i < tp->mtable->leafcount; i++)
if (tp->mtable->mleaf[i].media == looking_for) {
printk(KERN_INFO "%s: Using user-specified media %s.\n",
dev->name, medianame[dev->if_port]);
goto media_picked;
}
}
if ((tp->mtable->defaultmedia & 0x0800) == 0) {
int looking_for = tp->mtable->defaultmedia & MEDIA_MASK;
for (i = 0; i < tp->mtable->leafcount; i++)
if (tp->mtable->mleaf[i].media == looking_for) {
printk(KERN_INFO "%s: Using EEPROM-set media %s.\n",
dev->name, medianame[looking_for]);
goto media_picked;
}
}
/* Start sensing first non-full-duplex media. */
for (i = tp->mtable->leafcount - 1;
(tulip_media_cap[tp->mtable->mleaf[i].media] & MediaAlwaysFD) && i > 0; i--)
;
media_picked:
tp->csr6 = 0;
tp->cur_index = i;
tp->nwayset = 0;
if (dev->if_port) {
if (tp->chip_id == DC21143 &&
(tulip_media_cap[dev->if_port] & MediaIsMII)) {
/* We must reset the media CSRs when we force-select MII mode. */
iowrite32(0x0000, ioaddr + CSR13);
iowrite32(0x0000, ioaddr + CSR14);
iowrite32(0x0008, ioaddr + CSR15);
}
tulip_select_media(dev, 1);
} else if (tp->chip_id == DC21142) {
if (tp->mii_cnt) {
tulip_select_media(dev, 1);
if (tulip_debug > 1)
printk(KERN_INFO "%s: Using MII transceiver %d, status "
"%4.4x.\n",
dev->name, tp->phys[0], tulip_mdio_read(dev, tp->phys[0], 1));
iowrite32(csr6_mask_defstate, ioaddr + CSR6);
tp->csr6 = csr6_mask_hdcap;
dev->if_port = 11;
iowrite32(0x0000, ioaddr + CSR13);
iowrite32(0x0000, ioaddr + CSR14);
} else
t21142_start_nway(dev);
} else if (tp->chip_id == PNIC2) {
/* for initial startup advertise 10/100 Full and Half */
tp->sym_advertise = 0x01E0;
/* enable autonegotiate end interrupt */
iowrite32(ioread32(ioaddr+CSR5)| 0x00008010, ioaddr + CSR5);
iowrite32(ioread32(ioaddr+CSR7)| 0x00008010, ioaddr + CSR7);
pnic2_start_nway(dev);
} else if (tp->chip_id == LC82C168 && ! tp->medialock) {
if (tp->mii_cnt) {
dev->if_port = 11;
tp->csr6 = 0x814C0000 | (tp->full_duplex ? 0x0200 : 0);
iowrite32(0x0001, ioaddr + CSR15);
} else if (ioread32(ioaddr + CSR5) & TPLnkPass)
pnic_do_nway(dev);
else {
/* Start with 10mbps to do autonegotiation. */
iowrite32(0x32, ioaddr + CSR12);
tp->csr6 = 0x00420000;
iowrite32(0x0001B078, ioaddr + 0xB8);
iowrite32(0x0201B078, ioaddr + 0xB8);
next_tick = 1*HZ;
}
} else if ((tp->chip_id == MX98713 || tp->chip_id == COMPEX9881)
&& ! tp->medialock) {
dev->if_port = 0;
tp->csr6 = 0x01880000 | (tp->full_duplex ? 0x0200 : 0);
iowrite32(0x0f370000 | ioread16(ioaddr + 0x80), ioaddr + 0x80);
} else if (tp->chip_id == MX98715 || tp->chip_id == MX98725) {
/* Provided by BOLO, Macronix - 12/10/1998. */
dev->if_port = 0;
tp->csr6 = 0x01a80200;
iowrite32(0x0f370000 | ioread16(ioaddr + 0x80), ioaddr + 0x80);
iowrite32(0x11000 | ioread16(ioaddr + 0xa0), ioaddr + 0xa0);
} else if (tp->chip_id == COMET || tp->chip_id == CONEXANT) {
/* Enable automatic Tx underrun recovery. */
iowrite32(ioread32(ioaddr + 0x88) | 1, ioaddr + 0x88);
dev->if_port = tp->mii_cnt ? 11 : 0;
tp->csr6 = 0x00040000;
} else if (tp->chip_id == AX88140) {
tp->csr6 = tp->mii_cnt ? 0x00040100 : 0x00000100;
} else
tulip_select_media(dev, 1);
/* Start the chip's Tx to process setup frame. */
tulip_stop_rxtx(tp);
barrier();
udelay(5);
iowrite32(tp->csr6 | TxOn, ioaddr + CSR6);
/* Enable interrupts by setting the interrupt mask. */
iowrite32(tulip_tbl[tp->chip_id].valid_intrs, ioaddr + CSR5);
iowrite32(tulip_tbl[tp->chip_id].valid_intrs, ioaddr + CSR7);
tulip_start_rxtx(tp);
iowrite32(0, ioaddr + CSR2); /* Rx poll demand */
if (tulip_debug > 2) {
printk(KERN_DEBUG "%s: Done tulip_up(), CSR0 %8.8x, CSR5 %8.8x CSR6 %8.8x.\n",
dev->name, ioread32(ioaddr + CSR0), ioread32(ioaddr + CSR5),
ioread32(ioaddr + CSR6));
}
/* Set the timer to switch to check for link beat and perhaps switch
to an alternate media type. */
tp->timer.expires = RUN_AT(next_tick);
add_timer(&tp->timer);
#ifdef CONFIG_TULIP_NAPI
init_timer(&tp->oom_timer);
tp->oom_timer.data = (unsigned long)dev;
tp->oom_timer.function = oom_timer;
#endif
}
static int
tulip_open(struct net_device *dev)
{
int retval;
if ((retval = request_irq(dev->irq, &tulip_interrupt, SA_SHIRQ, dev->name, dev)))
return retval;
tulip_init_ring (dev);
tulip_up (dev);
netif_start_queue (dev);
return 0;
}
static void tulip_tx_timeout(struct net_device *dev)
{
struct tulip_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->base_addr;
unsigned long flags;
spin_lock_irqsave (&tp->lock, flags);
if (tulip_media_cap[dev->if_port] & MediaIsMII) {
/* Do nothing -- the media monitor should handle this. */
if (tulip_debug > 1)
printk(KERN_WARNING "%s: Transmit timeout using MII device.\n",
dev->name);
} else if (tp->chip_id == DC21140 || tp->chip_id == DC21142
|| tp->chip_id == MX98713 || tp->chip_id == COMPEX9881
|| tp->chip_id == DM910X) {
printk(KERN_WARNING "%s: 21140 transmit timed out, status %8.8x, "
"SIA %8.8x %8.8x %8.8x %8.8x, resetting...\n",
dev->name, ioread32(ioaddr + CSR5), ioread32(ioaddr + CSR12),
ioread32(ioaddr + CSR13), ioread32(ioaddr + CSR14), ioread32(ioaddr + CSR15));
if ( ! tp->medialock && tp->mtable) {
do
--tp->cur_index;
while (tp->cur_index >= 0
&& (tulip_media_cap[tp->mtable->mleaf[tp->cur_index].media]
& MediaIsFD));
if (--tp->cur_index < 0) {
/* We start again, but should instead look for default. */
tp->cur_index = tp->mtable->leafcount - 1;
}
tulip_select_media(dev, 0);
printk(KERN_WARNING "%s: transmit timed out, switching to %s "
"media.\n", dev->name, medianame[dev->if_port]);
}
} else if (tp->chip_id == PNIC2) {
printk(KERN_WARNING "%s: PNIC2 transmit timed out, status %8.8x, "
"CSR6/7 %8.8x / %8.8x CSR12 %8.8x, resetting...\n",
dev->name, (int)ioread32(ioaddr + CSR5), (int)ioread32(ioaddr + CSR6),
(int)ioread32(ioaddr + CSR7), (int)ioread32(ioaddr + CSR12));
} else {
printk(KERN_WARNING "%s: Transmit timed out, status %8.8x, CSR12 "
"%8.8x, resetting...\n",
dev->name, ioread32(ioaddr + CSR5), ioread32(ioaddr + CSR12));
dev->if_port = 0;
}
#if defined(way_too_many_messages)
if (tulip_debug > 3) {
int i;
for (i = 0; i < RX_RING_SIZE; i++) {
u8 *buf = (u8 *)(tp->rx_ring[i].buffer1);
int j;
printk(KERN_DEBUG "%2d: %8.8x %8.8x %8.8x %8.8x "
"%2.2x %2.2x %2.2x.\n",
i, (unsigned int)tp->rx_ring[i].status,
(unsigned int)tp->rx_ring[i].length,
(unsigned int)tp->rx_ring[i].buffer1,
(unsigned int)tp->rx_ring[i].buffer2,
buf[0], buf[1], buf[2]);
for (j = 0; buf[j] != 0xee && j < 1600; j++)
if (j < 100) printk(" %2.2x", buf[j]);
printk(" j=%d.\n", j);
}
printk(KERN_DEBUG " Rx ring %8.8x: ", (int)tp->rx_ring);
for (i = 0; i < RX_RING_SIZE; i++)
printk(" %8.8x", (unsigned int)tp->rx_ring[i].status);
printk("\n" KERN_DEBUG " Tx ring %8.8x: ", (int)tp->tx_ring);
for (i = 0; i < TX_RING_SIZE; i++)
printk(" %8.8x", (unsigned int)tp->tx_ring[i].status);
printk("\n");
}
#endif
/* Stop and restart the chip's Tx processes . */
tulip_restart_rxtx(tp);
/* Trigger an immediate transmit demand. */
iowrite32(0, ioaddr + CSR1);
tp->stats.tx_errors++;
spin_unlock_irqrestore (&tp->lock, flags);
dev->trans_start = jiffies;
netif_wake_queue (dev);
}
/* Initialize the Rx and Tx rings, along with various 'dev' bits. */
static void tulip_init_ring(struct net_device *dev)
{
struct tulip_private *tp = netdev_priv(dev);
int i;
tp->susp_rx = 0;
tp->ttimer = 0;
tp->nir = 0;
for (i = 0; i < RX_RING_SIZE; i++) {
tp->rx_ring[i].status = 0x00000000;
tp->rx_ring[i].length = cpu_to_le32(PKT_BUF_SZ);
tp->rx_ring[i].buffer2 = cpu_to_le32(tp->rx_ring_dma + sizeof(struct tulip_rx_desc) * (i + 1));
tp->rx_buffers[i].skb = NULL;
tp->rx_buffers[i].mapping = 0;
}
/* Mark the last entry as wrapping the ring. */
tp->rx_ring[i-1].length = cpu_to_le32(PKT_BUF_SZ | DESC_RING_WRAP);
tp->rx_ring[i-1].buffer2 = cpu_to_le32(tp->rx_ring_dma);
for (i = 0; i < RX_RING_SIZE; i++) {
dma_addr_t mapping;
/* Note the receive buffer must be longword aligned.
dev_alloc_skb() provides 16 byte alignment. But do *not*
use skb_reserve() to align the IP header! */
struct sk_buff *skb = dev_alloc_skb(PKT_BUF_SZ);
tp->rx_buffers[i].skb = skb;
if (skb == NULL)
break;
mapping = pci_map_single(tp->pdev, skb->tail,
PKT_BUF_SZ, PCI_DMA_FROMDEVICE);
tp->rx_buffers[i].mapping = mapping;
skb->dev = dev; /* Mark as being used by this device. */
tp->rx_ring[i].status = cpu_to_le32(DescOwned); /* Owned by Tulip chip */
tp->rx_ring[i].buffer1 = cpu_to_le32(mapping);
}
tp->dirty_rx = (unsigned int)(i - RX_RING_SIZE);
/* The Tx buffer descriptor is filled in as needed, but we
do need to clear the ownership bit. */
for (i = 0; i < TX_RING_SIZE; i++) {
tp->tx_buffers[i].skb = NULL;
tp->tx_buffers[i].mapping = 0;
tp->tx_ring[i].status = 0x00000000;
tp->tx_ring[i].buffer2 = cpu_to_le32(tp->tx_ring_dma + sizeof(struct tulip_tx_desc) * (i + 1));
}
tp->tx_ring[i-1].buffer2 = cpu_to_le32(tp->tx_ring_dma);
}
static int
tulip_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct tulip_private *tp = netdev_priv(dev);
int entry;
u32 flag;
dma_addr_t mapping;
spin_lock_irq(&tp->lock);
/* Calculate the next Tx descriptor entry. */
entry = tp->cur_tx % TX_RING_SIZE;
tp->tx_buffers[entry].skb = skb;
mapping = pci_map_single(tp->pdev, skb->data,
skb->len, PCI_DMA_TODEVICE);
tp->tx_buffers[entry].mapping = mapping;
tp->tx_ring[entry].buffer1 = cpu_to_le32(mapping);
if (tp->cur_tx - tp->dirty_tx < TX_RING_SIZE/2) {/* Typical path */
flag = 0x60000000; /* No interrupt */
} else if (tp->cur_tx - tp->dirty_tx == TX_RING_SIZE/2) {
flag = 0xe0000000; /* Tx-done intr. */
} else if (tp->cur_tx - tp->dirty_tx < TX_RING_SIZE - 2) {
flag = 0x60000000; /* No Tx-done intr. */
} else { /* Leave room for set_rx_mode() to fill entries. */
flag = 0xe0000000; /* Tx-done intr. */
netif_stop_queue(dev);
}
if (entry == TX_RING_SIZE-1)
flag = 0xe0000000 | DESC_RING_WRAP;
tp->tx_ring[entry].length = cpu_to_le32(skb->len | flag);
/* if we were using Transmit Automatic Polling, we would need a
* wmb() here. */
tp->tx_ring[entry].status = cpu_to_le32(DescOwned);
wmb();
tp->cur_tx++;
/* Trigger an immediate transmit demand. */
iowrite32(0, tp->base_addr + CSR1);
spin_unlock_irq(&tp->lock);
dev->trans_start = jiffies;
return 0;
}
static void tulip_clean_tx_ring(struct tulip_private *tp)
{
unsigned int dirty_tx;
for (dirty_tx = tp->dirty_tx ; tp->cur_tx - dirty_tx > 0;
dirty_tx++) {
int entry = dirty_tx % TX_RING_SIZE;
int status = le32_to_cpu(tp->tx_ring[entry].status);
if (status < 0) {
tp->stats.tx_errors++; /* It wasn't Txed */
tp->tx_ring[entry].status = 0;
}
/* Check for Tx filter setup frames. */
if (tp->tx_buffers[entry].skb == NULL) {
/* test because dummy frames not mapped */
if (tp->tx_buffers[entry].mapping)
pci_unmap_single(tp->pdev,
tp->tx_buffers[entry].mapping,
sizeof(tp->setup_frame),
PCI_DMA_TODEVICE);
continue;
}
pci_unmap_single(tp->pdev, tp->tx_buffers[entry].mapping,
tp->tx_buffers[entry].skb->len,
PCI_DMA_TODEVICE);
/* Free the original skb. */
dev_kfree_skb_irq(tp->tx_buffers[entry].skb);
tp->tx_buffers[entry].skb = NULL;
tp->tx_buffers[entry].mapping = 0;
}
}
static void tulip_down (struct net_device *dev)
{
struct tulip_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->base_addr;
unsigned long flags;
del_timer_sync (&tp->timer);
#ifdef CONFIG_TULIP_NAPI
del_timer_sync (&tp->oom_timer);
#endif
spin_lock_irqsave (&tp->lock, flags);
/* Disable interrupts by clearing the interrupt mask. */
iowrite32 (0x00000000, ioaddr + CSR7);
/* Stop the Tx and Rx processes. */
tulip_stop_rxtx(tp);
/* prepare receive buffers */
tulip_refill_rx(dev);
/* release any unconsumed transmit buffers */
tulip_clean_tx_ring(tp);
if (ioread32 (ioaddr + CSR6) != 0xffffffff)
tp->stats.rx_missed_errors += ioread32 (ioaddr + CSR8) & 0xffff;
spin_unlock_irqrestore (&tp->lock, flags);
init_timer(&tp->timer);
tp->timer.data = (unsigned long)dev;
tp->timer.function = tulip_tbl[tp->chip_id].media_timer;
dev->if_port = tp->saved_if_port;
/* Leave the driver in snooze, not sleep, mode. */
tulip_set_power_state (tp, 0, 1);
}
static int tulip_close (struct net_device *dev)
{
struct tulip_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->base_addr;
int i;
netif_stop_queue (dev);
tulip_down (dev);
if (tulip_debug > 1)
printk (KERN_DEBUG "%s: Shutting down ethercard, status was %2.2x.\n",
dev->name, ioread32 (ioaddr + CSR5));
free_irq (dev->irq, dev);
/* Free all the skbuffs in the Rx queue. */
for (i = 0; i < RX_RING_SIZE; i++) {
struct sk_buff *skb = tp->rx_buffers[i].skb;
dma_addr_t mapping = tp->rx_buffers[i].mapping;
tp->rx_buffers[i].skb = NULL;
tp->rx_buffers[i].mapping = 0;
tp->rx_ring[i].status = 0; /* Not owned by Tulip chip. */
tp->rx_ring[i].length = 0;
tp->rx_ring[i].buffer1 = 0xBADF00D0; /* An invalid address. */
if (skb) {
pci_unmap_single(tp->pdev, mapping, PKT_BUF_SZ,
PCI_DMA_FROMDEVICE);
dev_kfree_skb (skb);
}
}
for (i = 0; i < TX_RING_SIZE; i++) {
struct sk_buff *skb = tp->tx_buffers[i].skb;
if (skb != NULL) {
pci_unmap_single(tp->pdev, tp->tx_buffers[i].mapping,
skb->len, PCI_DMA_TODEVICE);
dev_kfree_skb (skb);
}
tp->tx_buffers[i].skb = NULL;
tp->tx_buffers[i].mapping = 0;
}
return 0;
}
static struct net_device_stats *tulip_get_stats(struct net_device *dev)
{
struct tulip_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->base_addr;
if (netif_running(dev)) {
unsigned long flags;
spin_lock_irqsave (&tp->lock, flags);
tp->stats.rx_missed_errors += ioread32(ioaddr + CSR8) & 0xffff;
spin_unlock_irqrestore(&tp->lock, flags);
}
return &tp->stats;
}
static void tulip_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct tulip_private *np = netdev_priv(dev);
strcpy(info->driver, DRV_NAME);
strcpy(info->version, DRV_VERSION);
strcpy(info->bus_info, pci_name(np->pdev));
}
static struct ethtool_ops ops = {
.get_drvinfo = tulip_get_drvinfo
};
/* Provide ioctl() calls to examine the MII xcvr state. */
static int private_ioctl (struct net_device *dev, struct ifreq *rq, int cmd)
{
struct tulip_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->base_addr;
struct mii_ioctl_data *data = if_mii(rq);
const unsigned int phy_idx = 0;
int phy = tp->phys[phy_idx] & 0x1f;
unsigned int regnum = data->reg_num;
switch (cmd) {
case SIOCGMIIPHY: /* Get address of MII PHY in use. */
if (tp->mii_cnt)
data->phy_id = phy;
else if (tp->flags & HAS_NWAY)
data->phy_id = 32;
else if (tp->chip_id == COMET)
data->phy_id = 1;
else
return -ENODEV;
case SIOCGMIIREG: /* Read MII PHY register. */
if (data->phy_id == 32 && (tp->flags & HAS_NWAY)) {
int csr12 = ioread32 (ioaddr + CSR12);
int csr14 = ioread32 (ioaddr + CSR14);
switch (regnum) {
case 0:
if (((csr14<<5) & 0x1000) ||
(dev->if_port == 5 && tp->nwayset))
data->val_out = 0x1000;
else
data->val_out = (tulip_media_cap[dev->if_port]&MediaIs100 ? 0x2000 : 0)
| (tulip_media_cap[dev->if_port]&MediaIsFD ? 0x0100 : 0);
break;
case 1:
data->val_out =
0x1848 +
((csr12&0x7000) == 0x5000 ? 0x20 : 0) +
((csr12&0x06) == 6 ? 0 : 4);
data->val_out |= 0x6048;
break;
case 4:
/* Advertised value, bogus 10baseTx-FD value from CSR6. */
data->val_out =
((ioread32(ioaddr + CSR6) >> 3) & 0x0040) +
((csr14 >> 1) & 0x20) + 1;
data->val_out |= ((csr14 >> 9) & 0x03C0);
break;
case 5: data->val_out = tp->lpar; break;
default: data->val_out = 0; break;
}
} else {
data->val_out = tulip_mdio_read (dev, data->phy_id & 0x1f, regnum);
}
return 0;
case SIOCSMIIREG: /* Write MII PHY register. */
if (!capable (CAP_NET_ADMIN))
return -EPERM;
if (regnum & ~0x1f)
return -EINVAL;
if (data->phy_id == phy) {
u16 value = data->val_in;
switch (regnum) {
case 0: /* Check for autonegotiation on or reset. */
tp->full_duplex_lock = (value & 0x9000) ? 0 : 1;
if (tp->full_duplex_lock)
tp->full_duplex = (value & 0x0100) ? 1 : 0;
break;
case 4:
tp->advertising[phy_idx] =
tp->mii_advertise = data->val_in;
break;
}
}
if (data->phy_id == 32 && (tp->flags & HAS_NWAY)) {
u16 value = data->val_in;
if (regnum == 0) {
if ((value & 0x1200) == 0x1200) {
if (tp->chip_id == PNIC2) {
pnic2_start_nway (dev);
} else {
t21142_start_nway (dev);
}
}
} else if (regnum == 4)
tp->sym_advertise = value;
} else {
tulip_mdio_write (dev, data->phy_id & 0x1f, regnum, data->val_in);
}
return 0;
default:
return -EOPNOTSUPP;
}
return -EOPNOTSUPP;
}
/* Set or clear the multicast filter for this adaptor.
Note that we only use exclusion around actually queueing the
new frame, not around filling tp->setup_frame. This is non-deterministic
when re-entered but still correct. */
#undef set_bit_le
#define set_bit_le(i,p) do { ((char *)(p))[(i)/8] |= (1<<((i)%8)); } while(0)
static void build_setup_frame_hash(u16 *setup_frm, struct net_device *dev)
{
struct tulip_private *tp = netdev_priv(dev);
u16 hash_table[32];
struct dev_mc_list *mclist;
int i;
u16 *eaddrs;
memset(hash_table, 0, sizeof(hash_table));
set_bit_le(255, hash_table); /* Broadcast entry */
/* This should work on big-endian machines as well. */
for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count;
i++, mclist = mclist->next) {
int index = ether_crc_le(ETH_ALEN, mclist->dmi_addr) & 0x1ff;
set_bit_le(index, hash_table);
}
for (i = 0; i < 32; i++) {
*setup_frm++ = hash_table[i];
*setup_frm++ = hash_table[i];
}
setup_frm = &tp->setup_frame[13*6];
/* Fill the final entry with our physical address. */
eaddrs = (u16 *)dev->dev_addr;
*setup_frm++ = eaddrs[0]; *setup_frm++ = eaddrs[0];
*setup_frm++ = eaddrs[1]; *setup_frm++ = eaddrs[1];
*setup_frm++ = eaddrs[2]; *setup_frm++ = eaddrs[2];
}
static void build_setup_frame_perfect(u16 *setup_frm, struct net_device *dev)
{
struct tulip_private *tp = netdev_priv(dev);
struct dev_mc_list *mclist;
int i;
u16 *eaddrs;
/* We have <= 14 addresses so we can use the wonderful
16 address perfect filtering of the Tulip. */
for (i = 0, mclist = dev->mc_list; i < dev->mc_count;
i++, mclist = mclist->next) {
eaddrs = (u16 *)mclist->dmi_addr;
*setup_frm++ = *eaddrs; *setup_frm++ = *eaddrs++;
*setup_frm++ = *eaddrs; *setup_frm++ = *eaddrs++;
*setup_frm++ = *eaddrs; *setup_frm++ = *eaddrs++;
}
/* Fill the unused entries with the broadcast address. */
memset(setup_frm, 0xff, (15-i)*12);
setup_frm = &tp->setup_frame[15*6];
/* Fill the final entry with our physical address. */
eaddrs = (u16 *)dev->dev_addr;
*setup_frm++ = eaddrs[0]; *setup_frm++ = eaddrs[0];
*setup_frm++ = eaddrs[1]; *setup_frm++ = eaddrs[1];
*setup_frm++ = eaddrs[2]; *setup_frm++ = eaddrs[2];
}
static void set_rx_mode(struct net_device *dev)
{
struct tulip_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->base_addr;
int csr6;
csr6 = ioread32(ioaddr + CSR6) & ~0x00D5;
tp->csr6 &= ~0x00D5;
if (dev->flags & IFF_PROMISC) { /* Set promiscuous. */
tp->csr6 |= AcceptAllMulticast | AcceptAllPhys;
csr6 |= AcceptAllMulticast | AcceptAllPhys;
/* Unconditionally log net taps. */
printk(KERN_INFO "%s: Promiscuous mode enabled.\n", dev->name);
} else if ((dev->mc_count > 1000) || (dev->flags & IFF_ALLMULTI)) {
/* Too many to filter well -- accept all multicasts. */
tp->csr6 |= AcceptAllMulticast;
csr6 |= AcceptAllMulticast;
} else if (tp->flags & MC_HASH_ONLY) {
/* Some work-alikes have only a 64-entry hash filter table. */
/* Should verify correctness on big-endian/__powerpc__ */
struct dev_mc_list *mclist;
int i;
if (dev->mc_count > 64) { /* Arbitrary non-effective limit. */
tp->csr6 |= AcceptAllMulticast;
csr6 |= AcceptAllMulticast;
} else {
u32 mc_filter[2] = {0, 0}; /* Multicast hash filter */
int filterbit;
for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count;
i++, mclist = mclist->next) {
if (tp->flags & COMET_MAC_ADDR)
filterbit = ether_crc_le(ETH_ALEN, mclist->dmi_addr);
else
filterbit = ether_crc(ETH_ALEN, mclist->dmi_addr) >> 26;
filterbit &= 0x3f;
mc_filter[filterbit >> 5] |= cpu_to_le32(1 << (filterbit & 31));
if (tulip_debug > 2) {
printk(KERN_INFO "%s: Added filter for %2.2x:%2.2x:%2.2x:"
"%2.2x:%2.2x:%2.2x %8.8x bit %d.\n", dev->name,
mclist->dmi_addr[0], mclist->dmi_addr[1],
mclist->dmi_addr[2], mclist->dmi_addr[3],
mclist->dmi_addr[4], mclist->dmi_addr[5],
ether_crc(ETH_ALEN, mclist->dmi_addr), filterbit);
}
}
if (mc_filter[0] == tp->mc_filter[0] &&
mc_filter[1] == tp->mc_filter[1])
; /* No change. */
else if (tp->flags & IS_ASIX) {
iowrite32(2, ioaddr + CSR13);
iowrite32(mc_filter[0], ioaddr + CSR14);
iowrite32(3, ioaddr + CSR13);
iowrite32(mc_filter[1], ioaddr + CSR14);
} else if (tp->flags & COMET_MAC_ADDR) {
iowrite32(mc_filter[0], ioaddr + 0xAC);
iowrite32(mc_filter[1], ioaddr + 0xB0);
}
tp->mc_filter[0] = mc_filter[0];
tp->mc_filter[1] = mc_filter[1];
}
} else {
unsigned long flags;
u32 tx_flags = 0x08000000 | 192;
/* Note that only the low-address shortword of setup_frame is valid!
The values are doubled for big-endian architectures. */
if (dev->mc_count > 14) { /* Must use a multicast hash table. */
build_setup_frame_hash(tp->setup_frame, dev);
tx_flags = 0x08400000 | 192;
} else {
build_setup_frame_perfect(tp->setup_frame, dev);
}
spin_lock_irqsave(&tp->lock, flags);
if (tp->cur_tx - tp->dirty_tx > TX_RING_SIZE - 2) {
/* Same setup recently queued, we need not add it. */
} else {
unsigned int entry;
int dummy = -1;
/* Now add this frame to the Tx list. */
entry = tp->cur_tx++ % TX_RING_SIZE;
if (entry != 0) {
/* Avoid a chip errata by prefixing a dummy entry. */
tp->tx_buffers[entry].skb = NULL;
tp->tx_buffers[entry].mapping = 0;
tp->tx_ring[entry].length =
(entry == TX_RING_SIZE-1) ? cpu_to_le32(DESC_RING_WRAP) : 0;
tp->tx_ring[entry].buffer1 = 0;
/* Must set DescOwned later to avoid race with chip */
dummy = entry;
entry = tp->cur_tx++ % TX_RING_SIZE;
}
tp->tx_buffers[entry].skb = NULL;
tp->tx_buffers[entry].mapping =
pci_map_single(tp->pdev, tp->setup_frame,
sizeof(tp->setup_frame),
PCI_DMA_TODEVICE);
/* Put the setup frame on the Tx list. */
if (entry == TX_RING_SIZE-1)
tx_flags |= DESC_RING_WRAP; /* Wrap ring. */
tp->tx_ring[entry].length = cpu_to_le32(tx_flags);
tp->tx_ring[entry].buffer1 =
cpu_to_le32(tp->tx_buffers[entry].mapping);
tp->tx_ring[entry].status = cpu_to_le32(DescOwned);
if (dummy >= 0)
tp->tx_ring[dummy].status = cpu_to_le32(DescOwned);
if (tp->cur_tx - tp->dirty_tx >= TX_RING_SIZE - 2)
netif_stop_queue(dev);
/* Trigger an immediate transmit demand. */
iowrite32(0, ioaddr + CSR1);
}
spin_unlock_irqrestore(&tp->lock, flags);
}
iowrite32(csr6, ioaddr + CSR6);
}
#ifdef CONFIG_TULIP_MWI
static void __devinit tulip_mwi_config (struct pci_dev *pdev,
struct net_device *dev)
{
struct tulip_private *tp = netdev_priv(dev);
u8 cache;
u16 pci_command;
u32 csr0;
if (tulip_debug > 3)
printk(KERN_DEBUG "%s: tulip_mwi_config()\n", pci_name(pdev));
tp->csr0 = csr0 = 0;
/* if we have any cache line size at all, we can do MRM */
csr0 |= MRM;
/* ...and barring hardware bugs, MWI */
if (!(tp->chip_id == DC21143 && tp->revision == 65))
csr0 |= MWI;
/* set or disable MWI in the standard PCI command bit.
* Check for the case where mwi is desired but not available
*/
if (csr0 & MWI) pci_set_mwi(pdev);
else pci_clear_mwi(pdev);
/* read result from hardware (in case bit refused to enable) */
pci_read_config_word(pdev, PCI_COMMAND, &pci_command);
if ((csr0 & MWI) && (!(pci_command & PCI_COMMAND_INVALIDATE)))
csr0 &= ~MWI;
/* if cache line size hardwired to zero, no MWI */
pci_read_config_byte(pdev, PCI_CACHE_LINE_SIZE, &cache);
if ((csr0 & MWI) && (cache == 0)) {
csr0 &= ~MWI;
pci_clear_mwi(pdev);
}
/* assign per-cacheline-size cache alignment and
* burst length values
*/
switch (cache) {
case 8:
csr0 |= MRL | (1 << CALShift) | (16 << BurstLenShift);
break;
case 16:
csr0 |= MRL | (2 << CALShift) | (16 << BurstLenShift);
break;
case 32:
csr0 |= MRL | (3 << CALShift) | (32 << BurstLenShift);
break;
default:
cache = 0;
break;
}
/* if we have a good cache line size, we by now have a good
* csr0, so save it and exit
*/
if (cache)
goto out;
/* we don't have a good csr0 or cache line size, disable MWI */
if (csr0 & MWI) {
pci_clear_mwi(pdev);
csr0 &= ~MWI;
}
/* sane defaults for burst length and cache alignment
* originally from de4x5 driver
*/
csr0 |= (8 << BurstLenShift) | (1 << CALShift);
out:
tp->csr0 = csr0;
if (tulip_debug > 2)
printk(KERN_DEBUG "%s: MWI config cacheline=%d, csr0=%08x\n",
pci_name(pdev), cache, csr0);
}
#endif
static int __devinit tulip_init_one (struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct tulip_private *tp;
/* See note below on the multiport cards. */
static unsigned char last_phys_addr[6] = {0x00, 'L', 'i', 'n', 'u', 'x'};
static struct pci_device_id early_486_chipsets[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82424) },
{ PCI_DEVICE(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_496) },
{ },
};
static int last_irq;
static int multiport_cnt; /* For four-port boards w/one EEPROM */
u8 chip_rev;
int i, irq;
unsigned short sum;
unsigned char *ee_data;
struct net_device *dev;
void __iomem *ioaddr;
static int board_idx = -1;
int chip_idx = ent->driver_data;
const char *chip_name = tulip_tbl[chip_idx].chip_name;
unsigned int eeprom_missing = 0;
unsigned int force_csr0 = 0;
#ifndef MODULE
static int did_version; /* Already printed version info. */
if (tulip_debug > 0 && did_version++ == 0)
printk (KERN_INFO "%s", version);
#endif
board_idx++;
/*
* Lan media wire a tulip chip to a wan interface. Needs a very
* different driver (lmc driver)
*/
if (pdev->subsystem_vendor == PCI_VENDOR_ID_LMC) {
printk (KERN_ERR PFX "skipping LMC card.\n");
return -ENODEV;
}
/*
* Early DM9100's need software CRC and the DMFE driver
*/
if (pdev->vendor == 0x1282 && pdev->device == 0x9100)
{
u32 dev_rev;
/* Read Chip revision */
pci_read_config_dword(pdev, PCI_REVISION_ID, &dev_rev);
if(dev_rev < 0x02000030)
{
printk(KERN_ERR PFX "skipping early DM9100 with Crc bug (use dmfe)\n");
return -ENODEV;
}
}
/*
* Looks for early PCI chipsets where people report hangs
* without the workarounds being on.
*/
/* 1. Intel Saturn. Switch to 8 long words burst, 8 long word cache
aligned. Aries might need this too. The Saturn errata are not
pretty reading but thankfully it's an old 486 chipset.
2. The dreaded SiS496 486 chipset. Same workaround as Intel
Saturn.
*/
if (pci_dev_present(early_486_chipsets)) {
csr0 = MRL | MRM | (8 << BurstLenShift) | (1 << CALShift);
force_csr0 = 1;
}
/* bugfix: the ASIX must have a burst limit or horrible things happen. */
if (chip_idx == AX88140) {
if ((csr0 & 0x3f00) == 0)
csr0 |= 0x2000;
}
/* PNIC doesn't have MWI/MRL/MRM... */
if (chip_idx == LC82C168)
csr0 &= ~0xfff10000; /* zero reserved bits 31:20, 16 */
/* DM9102A has troubles with MRM & clear reserved bits 24:22, 20, 16, 7:1 */
if ((pdev->vendor == 0x1282 && pdev->device == 0x9102)
|| (pdev->vendor == 0x10b9 && pdev->device == 0x5261))
csr0 &= ~0x01f100ff;
#if defined(__sparc__)
/* DM9102A needs 32-dword alignment/burst length on sparc - chip bug? */
if ((pdev->vendor == 0x1282 && pdev->device == 0x9102)
|| (pdev->vendor == 0x10b9 && pdev->device == 0x5261))
csr0 = (csr0 & ~0xff00) | 0xe000;
#endif
/*
* And back to business
*/
i = pci_enable_device(pdev);
if (i) {
printk (KERN_ERR PFX
"Cannot enable tulip board #%d, aborting\n",
board_idx);
return i;
}
irq = pdev->irq;
/* alloc_etherdev ensures aligned and zeroed private structures */
dev = alloc_etherdev (sizeof (*tp));
if (!dev) {
printk (KERN_ERR PFX "ether device alloc failed, aborting\n");
return -ENOMEM;
}
SET_MODULE_OWNER(dev);
SET_NETDEV_DEV(dev, &pdev->dev);
if (pci_resource_len (pdev, 0) < tulip_tbl[chip_idx].io_size) {
printk (KERN_ERR PFX "%s: I/O region (0x%lx@0x%lx) too small, "
"aborting\n", pci_name(pdev),
pci_resource_len (pdev, 0),
pci_resource_start (pdev, 0));
goto err_out_free_netdev;
}
/* grab all resources from both PIO and MMIO regions, as we
* don't want anyone else messing around with our hardware */
if (pci_request_regions (pdev, "tulip"))
goto err_out_free_netdev;
#ifndef USE_IO_OPS
ioaddr = pci_iomap(pdev, 1, tulip_tbl[chip_idx].io_size);
#else
ioaddr = pci_iomap(pdev, 0, tulip_tbl[chip_idx].io_size);
#endif
if (!ioaddr)
goto err_out_free_res;
pci_read_config_byte (pdev, PCI_REVISION_ID, &chip_rev);
/*
* initialize private data structure 'tp'
* it is zeroed and aligned in alloc_etherdev
*/
tp = netdev_priv(dev);
tp->rx_ring = pci_alloc_consistent(pdev,
sizeof(struct tulip_rx_desc) * RX_RING_SIZE +
sizeof(struct tulip_tx_desc) * TX_RING_SIZE,
&tp->rx_ring_dma);
if (!tp->rx_ring)
goto err_out_mtable;
tp->tx_ring = (struct tulip_tx_desc *)(tp->rx_ring + RX_RING_SIZE);
tp->tx_ring_dma = tp->rx_ring_dma + sizeof(struct tulip_rx_desc) * RX_RING_SIZE;
tp->chip_id = chip_idx;
tp->flags = tulip_tbl[chip_idx].flags;
tp->pdev = pdev;
tp->base_addr = ioaddr;
tp->revision = chip_rev;
tp->csr0 = csr0;
spin_lock_init(&tp->lock);
spin_lock_init(&tp->mii_lock);
init_timer(&tp->timer);
tp->timer.data = (unsigned long)dev;
tp->timer.function = tulip_tbl[tp->chip_id].media_timer;
dev->base_addr = (unsigned long)ioaddr;
#ifdef CONFIG_TULIP_MWI
if (!force_csr0 && (tp->flags & HAS_PCI_MWI))
tulip_mwi_config (pdev, dev);
#else
/* MWI is broken for DC21143 rev 65... */
if (chip_idx == DC21143 && chip_rev == 65)
tp->csr0 &= ~MWI;
#endif
/* Stop the chip's Tx and Rx processes. */
tulip_stop_rxtx(tp);
pci_set_master(pdev);
#ifdef CONFIG_GSC
if (pdev->subsystem_vendor == PCI_VENDOR_ID_HP) {
switch (pdev->subsystem_device) {
default:
break;
case 0x1061:
case 0x1062:
case 0x1063:
case 0x1098:
case 0x1099:
case 0x10EE:
tp->flags |= HAS_SWAPPED_SEEPROM | NEEDS_FAKE_MEDIA_TABLE;
chip_name = "GSC DS21140 Tulip";
}
}
#endif
/* Clear the missed-packet counter. */
ioread32(ioaddr + CSR8);
/* The station address ROM is read byte serially. The register must
be polled, waiting for the value to be read bit serially from the
EEPROM.
*/
ee_data = tp->eeprom;
sum = 0;
if (chip_idx == LC82C168) {
for (i = 0; i < 3; i++) {
int value, boguscnt = 100000;
iowrite32(0x600 | i, ioaddr + 0x98);
do
value = ioread32(ioaddr + CSR9);
while (value < 0 && --boguscnt > 0);
put_unaligned(le16_to_cpu(value), ((u16*)dev->dev_addr) + i);
sum += value & 0xffff;
}
} else if (chip_idx == COMET) {
/* No need to read the EEPROM. */
put_unaligned(cpu_to_le32(ioread32(ioaddr + 0xA4)), (u32 *)dev->dev_addr);
put_unaligned(cpu_to_le16(ioread32(ioaddr + 0xA8)), (u16 *)(dev->dev_addr + 4));
for (i = 0; i < 6; i ++)
sum += dev->dev_addr[i];
} else {
/* A serial EEPROM interface, we read now and sort it out later. */
int sa_offset = 0;
int ee_addr_size = tulip_read_eeprom(dev, 0xff, 8) & 0x40000 ? 8 : 6;
for (i = 0; i < sizeof(tp->eeprom); i+=2) {
u16 data = tulip_read_eeprom(dev, i/2, ee_addr_size);
ee_data[i] = data & 0xff;
ee_data[i + 1] = data >> 8;
}
/* DEC now has a specification (see Notes) but early board makers
just put the address in the first EEPROM locations. */
/* This does memcmp(ee_data, ee_data+16, 8) */
for (i = 0; i < 8; i ++)
if (ee_data[i] != ee_data[16+i])
sa_offset = 20;
if (chip_idx == CONEXANT) {
/* Check that the tuple type and length is correct. */
if (ee_data[0x198] == 0x04 && ee_data[0x199] == 6)
sa_offset = 0x19A;
} else if (ee_data[0] == 0xff && ee_data[1] == 0xff &&
ee_data[2] == 0) {
sa_offset = 2; /* Grrr, damn Matrox boards. */
multiport_cnt = 4;
}
#ifdef CONFIG_DDB5476
if ((pdev->bus->number == 0) && (PCI_SLOT(pdev->devfn) == 6)) {
/* DDB5476 MAC address in first EEPROM locations. */
sa_offset = 0;
/* No media table either */
tp->flags &= ~HAS_MEDIA_TABLE;
}
#endif
#ifdef CONFIG_DDB5477
if ((pdev->bus->number == 0) && (PCI_SLOT(pdev->devfn) == 4)) {
/* DDB5477 MAC address in first EEPROM locations. */
sa_offset = 0;
/* No media table either */
tp->flags &= ~HAS_MEDIA_TABLE;
}
#endif
#ifdef CONFIG_MIPS_COBALT
if ((pdev->bus->number == 0) &&
((PCI_SLOT(pdev->devfn) == 7) ||
(PCI_SLOT(pdev->devfn) == 12))) {
/* Cobalt MAC address in first EEPROM locations. */
sa_offset = 0;
/* No media table either */
tp->flags &= ~HAS_MEDIA_TABLE;
}
#endif
#ifdef CONFIG_GSC
/* Check to see if we have a broken srom */
if (ee_data[0] == 0x61 && ee_data[1] == 0x10) {
/* pci_vendor_id and subsystem_id are swapped */
ee_data[0] = ee_data[2];
ee_data[1] = ee_data[3];
ee_data[2] = 0x61;
ee_data[3] = 0x10;
/* HSC-PCI boards need to be byte-swaped and shifted
* up 1 word. This shift needs to happen at the end
* of the MAC first because of the 2 byte overlap.
*/
for (i = 4; i >= 0; i -= 2) {
ee_data[17 + i + 3] = ee_data[17 + i];
ee_data[16 + i + 5] = ee_data[16 + i];
}
}
#endif
for (i = 0; i < 6; i ++) {
dev->dev_addr[i] = ee_data[i + sa_offset];
sum += ee_data[i + sa_offset];
}
}
/* Lite-On boards have the address byte-swapped. */
if ((dev->dev_addr[0] == 0xA0 || dev->dev_addr[0] == 0xC0 || dev->dev_addr[0] == 0x02)
&& dev->dev_addr[1] == 0x00)
for (i = 0; i < 6; i+=2) {
char tmp = dev->dev_addr[i];
dev->dev_addr[i] = dev->dev_addr[i+1];
dev->dev_addr[i+1] = tmp;
}
/* On the Zynx 315 Etherarray and other multiport boards only the
first Tulip has an EEPROM.
On Sparc systems the mac address is held in the OBP property
"local-mac-address".
The addresses of the subsequent ports are derived from the first.
Many PCI BIOSes also incorrectly report the IRQ line, so we correct
that here as well. */
if (sum == 0 || sum == 6*0xff) {
#if defined(__sparc__)
struct pcidev_cookie *pcp = pdev->sysdata;
#endif
eeprom_missing = 1;
for (i = 0; i < 5; i++)
dev->dev_addr[i] = last_phys_addr[i];
dev->dev_addr[i] = last_phys_addr[i] + 1;
#if defined(__sparc__)
if ((pcp != NULL) && prom_getproplen(pcp->prom_node,
"local-mac-address") == 6) {
prom_getproperty(pcp->prom_node, "local-mac-address",
dev->dev_addr, 6);
}
#endif
#if defined(__i386__) /* Patch up x86 BIOS bug. */
if (last_irq)
irq = last_irq;
#endif
}
for (i = 0; i < 6; i++)
last_phys_addr[i] = dev->dev_addr[i];
last_irq = irq;
dev->irq = irq;
/* The lower four bits are the media type. */
if (board_idx >= 0 && board_idx < MAX_UNITS) {
if (options[board_idx] & MEDIA_MASK)
tp->default_port = options[board_idx] & MEDIA_MASK;
if ((options[board_idx] & FullDuplex) || full_duplex[board_idx] > 0)
tp->full_duplex = 1;
if (mtu[board_idx] > 0)
dev->mtu = mtu[board_idx];
}
if (dev->mem_start & MEDIA_MASK)
tp->default_port = dev->mem_start & MEDIA_MASK;
if (tp->default_port) {
printk(KERN_INFO "tulip%d: Transceiver selection forced to %s.\n",
board_idx, medianame[tp->default_port & MEDIA_MASK]);
tp->medialock = 1;
if (tulip_media_cap[tp->default_port] & MediaAlwaysFD)
tp->full_duplex = 1;
}
if (tp->full_duplex)
tp->full_duplex_lock = 1;
if (tulip_media_cap[tp->default_port] & MediaIsMII) {
u16 media2advert[] = { 0x20, 0x40, 0x03e0, 0x60, 0x80, 0x100, 0x200 };
tp->mii_advertise = media2advert[tp->default_port - 9];
tp->mii_advertise |= (tp->flags & HAS_8023X); /* Matching bits! */
}
if (tp->flags & HAS_MEDIA_TABLE) {
sprintf(dev->name, "tulip%d", board_idx); /* hack */
tulip_parse_eeprom(dev);
strcpy(dev->name, "eth%d"); /* un-hack */
}
if ((tp->flags & ALWAYS_CHECK_MII) ||
(tp->mtable && tp->mtable->has_mii) ||
( ! tp->mtable && (tp->flags & HAS_MII))) {
if (tp->mtable && tp->mtable->has_mii) {
for (i = 0; i < tp->mtable->leafcount; i++)
if (tp->mtable->mleaf[i].media == 11) {
tp->cur_index = i;
tp->saved_if_port = dev->if_port;
tulip_select_media(dev, 2);
dev->if_port = tp->saved_if_port;
break;
}
}
/* Find the connected MII xcvrs.
Doing this in open() would allow detecting external xcvrs
later, but takes much time. */
tulip_find_mii (dev, board_idx);
}
/* The Tulip-specific entries in the device structure. */
dev->open = tulip_open;
dev->hard_start_xmit = tulip_start_xmit;
dev->tx_timeout = tulip_tx_timeout;
dev->watchdog_timeo = TX_TIMEOUT;
#ifdef CONFIG_TULIP_NAPI
dev->poll = tulip_poll;
dev->weight = 16;
#endif
dev->stop = tulip_close;
dev->get_stats = tulip_get_stats;
dev->do_ioctl = private_ioctl;
dev->set_multicast_list = set_rx_mode;
#ifdef CONFIG_NET_POLL_CONTROLLER
dev->poll_controller = &poll_tulip;
#endif
SET_ETHTOOL_OPS(dev, &ops);
if (register_netdev(dev))
goto err_out_free_ring;
printk(KERN_INFO "%s: %s rev %d at %p,",
dev->name, chip_name, chip_rev, ioaddr);
pci_set_drvdata(pdev, dev);
if (eeprom_missing)
printk(" EEPROM not present,");
for (i = 0; i < 6; i++)
printk("%c%2.2X", i ? ':' : ' ', dev->dev_addr[i]);
printk(", IRQ %d.\n", irq);
if (tp->chip_id == PNIC2)
tp->link_change = pnic2_lnk_change;
else if (tp->flags & HAS_NWAY)
tp->link_change = t21142_lnk_change;
else if (tp->flags & HAS_PNICNWAY)
tp->link_change = pnic_lnk_change;
/* Reset the xcvr interface and turn on heartbeat. */
switch (chip_idx) {
case DC21140:
case DM910X:
default:
if (tp->mtable)
iowrite32(tp->mtable->csr12dir | 0x100, ioaddr + CSR12);
break;
case DC21142:
if (tp->mii_cnt || tulip_media_cap[dev->if_port] & MediaIsMII) {
iowrite32(csr6_mask_defstate, ioaddr + CSR6);
iowrite32(0x0000, ioaddr + CSR13);
iowrite32(0x0000, ioaddr + CSR14);
iowrite32(csr6_mask_hdcap, ioaddr + CSR6);
} else
t21142_start_nway(dev);
break;
case PNIC2:
/* just do a reset for sanity sake */
iowrite32(0x0000, ioaddr + CSR13);
iowrite32(0x0000, ioaddr + CSR14);
break;
case LC82C168:
if ( ! tp->mii_cnt) {
tp->nway = 1;
tp->nwayset = 0;
iowrite32(csr6_ttm | csr6_ca, ioaddr + CSR6);
iowrite32(0x30, ioaddr + CSR12);
iowrite32(0x0001F078, ioaddr + CSR6);
iowrite32(0x0201F078, ioaddr + CSR6); /* Turn on autonegotiation. */
}
break;
case MX98713:
case COMPEX9881:
iowrite32(0x00000000, ioaddr + CSR6);
iowrite32(0x000711C0, ioaddr + CSR14); /* Turn on NWay. */
iowrite32(0x00000001, ioaddr + CSR13);
break;
case MX98715:
case MX98725:
iowrite32(0x01a80000, ioaddr + CSR6);
iowrite32(0xFFFFFFFF, ioaddr + CSR14);
iowrite32(0x00001000, ioaddr + CSR12);
break;
case COMET:
/* No initialization necessary. */
break;
}
/* put the chip in snooze mode until opened */
tulip_set_power_state (tp, 0, 1);
return 0;
err_out_free_ring:
pci_free_consistent (pdev,
sizeof (struct tulip_rx_desc) * RX_RING_SIZE +
sizeof (struct tulip_tx_desc) * TX_RING_SIZE,
tp->rx_ring, tp->rx_ring_dma);
err_out_mtable:
if (tp->mtable)
kfree (tp->mtable);
pci_iounmap(pdev, ioaddr);
err_out_free_res:
pci_release_regions (pdev);
err_out_free_netdev:
free_netdev (dev);
return -ENODEV;
}
#ifdef CONFIG_PM
static int tulip_suspend (struct pci_dev *pdev, u32 state)
{
struct net_device *dev = pci_get_drvdata(pdev);
if (dev && netif_running (dev) && netif_device_present (dev)) {
netif_device_detach (dev);
tulip_down (dev);
/* pci_power_off(pdev, -1); */
}
return 0;
}
static int tulip_resume(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
if (dev && netif_running (dev) && !netif_device_present (dev)) {
#if 1
pci_enable_device (pdev);
#endif
/* pci_power_on(pdev); */
tulip_up (dev);
netif_device_attach (dev);
}
return 0;
}
#endif /* CONFIG_PM */
static void __devexit tulip_remove_one (struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata (pdev);
struct tulip_private *tp;
if (!dev)
return;
tp = netdev_priv(dev);
unregister_netdev(dev);
pci_free_consistent (pdev,
sizeof (struct tulip_rx_desc) * RX_RING_SIZE +
sizeof (struct tulip_tx_desc) * TX_RING_SIZE,
tp->rx_ring, tp->rx_ring_dma);
if (tp->mtable)
kfree (tp->mtable);
pci_iounmap(pdev, tp->base_addr);
free_netdev (dev);
pci_release_regions (pdev);
pci_set_drvdata (pdev, NULL);
/* pci_power_off (pdev, -1); */
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* Polling 'interrupt' - used by things like netconsole to send skbs
* without having to re-enable interrupts. It's not called while
* the interrupt routine is executing.
*/
static void poll_tulip (struct net_device *dev)
{
/* disable_irq here is not very nice, but with the lockless
interrupt handler we have no other choice. */
disable_irq(dev->irq);
tulip_interrupt (dev->irq, dev, NULL);
enable_irq(dev->irq);
}
#endif
static struct pci_driver tulip_driver = {
.name = DRV_NAME,
.id_table = tulip_pci_tbl,
.probe = tulip_init_one,
.remove = __devexit_p(tulip_remove_one),
#ifdef CONFIG_PM
.suspend = tulip_suspend,
.resume = tulip_resume,
#endif /* CONFIG_PM */
};
static int __init tulip_init (void)
{
#ifdef MODULE
printk (KERN_INFO "%s", version);
#endif
/* copy module parms into globals */
tulip_rx_copybreak = rx_copybreak;
tulip_max_interrupt_work = max_interrupt_work;
/* probe for and init boards */
return pci_module_init (&tulip_driver);
}
static void __exit tulip_cleanup (void)
{
pci_unregister_driver (&tulip_driver);
}
module_init(tulip_init);
module_exit(tulip_cleanup);
|
QiuLihua83/linux-2.6.10
|
drivers/net/tulip/tulip_core.c
|
C
|
gpl-2.0
| 55,977 |
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/**
* bonobo-storage-memory.c: Memory based Bonobo::Storage implementation
*
* Author:
* ÉRDI Gergõ <[email protected]>
*
* Copyright 2001 Gergõ Érdi
*
* TODO:
* * Make it implement PersistStream so you can flatten a
* StorageMem into a Stream
* * Create a subclass that supports commit/revert
*/
#include <config.h>
#include <string.h>
#include <bonobo/bonobo-storage-memory.h>
#include <bonobo/bonobo-stream-memory.h>
#include <bonobo/bonobo-exception.h>
#include <bonobo/bonobo-storage.h>
static BonoboObjectClass *bonobo_storage_mem_parent_class;
typedef struct {
gboolean is_directory;
BonoboObject *child;
} BonoboStorageMemEntry;
struct _BonoboStorageMemPriv {
GHashTable *entries;
};
typedef struct {
GList *list;
Bonobo_StorageInfoFields mask;
} DirCBData;
static void
bonobo_storage_mem_entry_free (gpointer data)
{
BonoboStorageMemEntry *entry = (BonoboStorageMemEntry*) data;
if (!entry)
return;
bonobo_object_unref (entry->child);
g_free (entry);
}
static BonoboStorageMemEntry *
bonobo_storage_mem_entry_dup (BonoboStorageMemEntry *entry)
{
BonoboStorageMemEntry *ret_val = g_new0 (BonoboStorageMemEntry, 1);
ret_val->is_directory = entry->is_directory;
ret_val->child = entry->child;
bonobo_object_ref (ret_val->child);
return ret_val;
}
static void
split_path (const char *path,
char **path_head,
char **path_tail)
{
gchar **path_parts;
if (g_path_is_absolute (path))
path = g_path_skip_root (path);
path_parts = g_strsplit (path, "/", 2);
*path_head = path_parts[0];
*path_tail = path_parts[1];
g_free (path_parts);
}
static BonoboStorageMem *
smem_get_parent (BonoboStorageMem *storage,
const char *path,
char **filename, /* g_free this */
BonoboStorageMemEntry **ret_entry) /* g_free this */
{
BonoboStorageMem *ret;
BonoboStorageMemEntry *entry;
gchar *path_head, *path_tail;
if (!strcmp (path, "/") || !strcmp (path, "")) {
if (filename)
*filename = g_strdup ("/");
if (ret_entry) {
*ret_entry = g_new0 (BonoboStorageMemEntry, 1);
(*ret_entry)->is_directory = TRUE;
(*ret_entry)->child = BONOBO_OBJECT (storage);
bonobo_object_ref ((*ret_entry)->child);
}
return storage;
}
split_path (path, &path_head, &path_tail);
entry = g_hash_table_lookup (storage->priv->entries,
path_head);
/* No child is found */
if (!entry) {
g_free (path_head);
if (filename)
*filename = path_tail;
if (ret_entry)
*ret_entry = NULL;
return NULL;
}
/* This is not the immediate parent */
if (path_tail && entry->is_directory) {
ret = smem_get_parent (
BONOBO_STORAGE_MEM (entry->child),
path_tail,
filename,
ret_entry);
g_free (path_head);
g_free (path_tail);
return ret;
}
/* This is the immediate parent */
if (filename)
*filename = g_strdup (path_head);
if (ret_entry)
*ret_entry = bonobo_storage_mem_entry_dup (entry);
g_free (path_tail);
g_free (path_head);
return storage;
}
static BonoboStorageMem *
smem_get_last_storage (BonoboStorageMem *storage,
const char *path,
char **last_path)
{
BonoboStorageMem *ret;
BonoboStorageMemEntry *entry;
gchar *path_head, *path_tail;
if (!strcmp (path, "/") || !strcmp (path, "")) {
if (last_path)
*last_path = NULL;
return storage;
}
split_path (path, &path_head, &path_tail);
entry = g_hash_table_lookup (storage->priv->entries,
path_head);
/* No appropriate child is found */
if (!entry) {
if (path_tail) {
g_free (path_head);
g_free (path_tail);
if (last_path)
*last_path = NULL;
return NULL;
} else {
if (last_path)
*last_path = path_head;
return storage;
}
}
if (!path_tail) {
if (entry->is_directory) {
g_free (path_head);
if (last_path)
*last_path = NULL;
return BONOBO_STORAGE_MEM (entry->child);
} else {
if (last_path)
*last_path = path_head;
return storage;
}
}
if (path_tail && entry->is_directory) {
ret = smem_get_last_storage (
BONOBO_STORAGE_MEM (entry->child),
path_tail, last_path);
g_free (path_head);
g_free (path_tail);
return ret;
}
g_free (path_tail);
g_free (path_head);
if (last_path)
*last_path = NULL;
return NULL;
}
static Bonobo_StorageInfo *
smem_get_stream_info (BonoboObject *stream,
const Bonobo_StorageInfoFields mask,
CORBA_Environment *ev)
{
Bonobo_StorageInfo *ret_val;
CORBA_Environment my_ev;
CORBA_exception_init (&my_ev);
ret_val = Bonobo_Stream_getInfo (bonobo_object_corba_objref (stream),
mask, &my_ev);
if (BONOBO_EX (&my_ev)) {
if (BONOBO_USER_EX (&my_ev, ex_Bonobo_Stream_IOError))
bonobo_exception_set (ev, ex_Bonobo_Storage_IOError);
if (BONOBO_USER_EX (&my_ev, ex_Bonobo_Stream_NoPermission))
bonobo_exception_set (ev, ex_Bonobo_Storage_NoPermission);
if (BONOBO_USER_EX (&my_ev, ex_Bonobo_Stream_NotSupported))
bonobo_exception_set (ev, ex_Bonobo_Storage_NotSupported);
}
if (mask & Bonobo_FIELD_TYPE)
ret_val->type = Bonobo_STORAGE_TYPE_REGULAR;
CORBA_exception_free (&my_ev);
return ret_val;
}
static void
smem_dir_hash_cb (gpointer key,
gpointer value,
gpointer user_data)
{
DirCBData *cb_data = user_data;
gchar *filename = key;
BonoboStorageMemEntry *entry = value;
Bonobo_StorageInfo *info;
Bonobo_StorageInfoFields mask = cb_data->mask;
if (entry->is_directory) {
info = Bonobo_StorageInfo__alloc ();
info->name = CORBA_string_dup (filename);
info->type = Bonobo_STORAGE_TYPE_DIRECTORY;
} else {
if (mask & Bonobo_FIELD_CONTENT_TYPE ||
mask & Bonobo_FIELD_SIZE) {
CORBA_Environment my_ev;
CORBA_exception_init (&my_ev);
info = smem_get_stream_info (entry->child, mask, &my_ev);
CORBA_exception_free (&my_ev);
}
else
info = Bonobo_StorageInfo__alloc ();
info->name = CORBA_string_dup (filename);
info->type = Bonobo_STORAGE_TYPE_REGULAR;
}
cb_data->list = g_list_prepend (cb_data->list, info);
}
static Bonobo_StorageInfo*
smem_get_info_impl (PortableServer_Servant servant,
const CORBA_char *path,
const Bonobo_StorageInfoFields mask,
CORBA_Environment *ev)
{
BonoboStorageMem *storage;
Bonobo_StorageInfo *ret_val = NULL;
BonoboStorageMem *parent_storage;
BonoboStorageMemEntry *entry = NULL;
gchar *filename = NULL;
storage = BONOBO_STORAGE_MEM (bonobo_object (servant));
parent_storage = smem_get_parent (storage, path, &filename, &entry);
if (!parent_storage) {
bonobo_exception_set (ev, ex_Bonobo_Storage_NotFound);
goto out;
}
if (entry->is_directory) {
if (mask & Bonobo_FIELD_CONTENT_TYPE ||
mask & Bonobo_FIELD_SIZE) {
bonobo_exception_set (ev, ex_Bonobo_Storage_NotSupported);
goto out;
}
ret_val = Bonobo_StorageInfo__alloc ();
ret_val->name = CORBA_string_dup (filename);
if (mask & Bonobo_FIELD_TYPE)
ret_val->type = Bonobo_STORAGE_TYPE_DIRECTORY;
} else {
if (mask & Bonobo_FIELD_CONTENT_TYPE ||
mask & Bonobo_FIELD_SIZE)
ret_val = smem_get_stream_info (entry->child, mask, ev);
else
ret_val = Bonobo_StorageInfo__alloc ();
ret_val->name = CORBA_string_dup (filename);
ret_val->type = Bonobo_STORAGE_TYPE_REGULAR;
}
out:
bonobo_storage_mem_entry_free (entry);
g_free (filename);
return ret_val;
}
static void
smem_set_info_impl (PortableServer_Servant servant,
const CORBA_char *path,
const Bonobo_StorageInfo *info,
Bonobo_StorageInfoFields mask,
CORBA_Environment *ev)
{
BonoboStorageMem *storage;
BonoboStorageMem *parent_storage;
BonoboStorageMemEntry *entry = NULL;
gchar *filename;
storage = BONOBO_STORAGE_MEM (bonobo_object (servant));
parent_storage = smem_get_parent (storage, path, &filename, &entry);
if (!parent_storage) {
bonobo_exception_set (ev, ex_Bonobo_Storage_NotFound);
goto out;
}
if (entry->is_directory)
bonobo_exception_set (ev, ex_Bonobo_Storage_NotSupported);
else {
CORBA_Environment my_ev;
CORBA_exception_init (&my_ev);
Bonobo_Stream_setInfo (
bonobo_object_corba_objref (entry->child),
info, mask,
&my_ev);
if (BONOBO_EX (&my_ev)) {
if (BONOBO_USER_EX (&my_ev, ex_Bonobo_Stream_IOError))
bonobo_exception_set (ev, ex_Bonobo_Storage_IOError);
if (BONOBO_USER_EX (&my_ev, ex_Bonobo_Stream_NoPermission))
bonobo_exception_set (ev, ex_Bonobo_Storage_NoPermission);
if (BONOBO_USER_EX (&my_ev, ex_Bonobo_Stream_NotSupported))
bonobo_exception_set (ev, ex_Bonobo_Storage_NotSupported);
}
CORBA_exception_free (&my_ev);
}
out:
g_free (filename);
bonobo_storage_mem_entry_free (entry);
}
static Bonobo_Stream
smem_open_stream_impl (PortableServer_Servant servant,
const CORBA_char *path,
Bonobo_Storage_OpenMode mode,
CORBA_Environment *ev)
{
BonoboStorageMem *storage;
BonoboStorageMem *parent;
BonoboStorageMemEntry *entry;
gchar *path_last;
BonoboObject *stream = NULL;
storage = BONOBO_STORAGE_MEM (bonobo_object (servant));
parent = smem_get_last_storage (storage, path, &path_last);
if (!parent) {
bonobo_exception_set (ev, ex_Bonobo_Storage_NotFound);
goto ex_out;
}
entry = g_hash_table_lookup (parent->priv->entries, path_last);
/* Error cases */
/* Case 1: Stream not found */
if (!entry && !(mode & Bonobo_Storage_CREATE)) {
bonobo_exception_set (ev, ex_Bonobo_Storage_NotFound);
goto ex_out;
}
/* Case 2: A storage by the same name exists */
if (entry && entry->is_directory) {
if (mode & Bonobo_Storage_CREATE)
bonobo_exception_set (ev, ex_Bonobo_Storage_NameExists);
else
bonobo_exception_set (ev, ex_Bonobo_Storage_NotStream);
goto ex_out;
}
if (!entry) {
stream = bonobo_stream_mem_create (NULL, 0,
FALSE, TRUE);
entry = g_new0 (BonoboStorageMemEntry, 1);
entry->is_directory = FALSE;
entry->child = stream;
g_hash_table_insert (parent->priv->entries,
g_strdup (path_last),
entry);
goto ok_out;
}
stream = entry->child;
ok_out:
g_free (path_last);
return bonobo_object_dup_ref (BONOBO_OBJREF (stream), ev);
ex_out:
g_free (path_last);
return CORBA_OBJECT_NIL;
}
static Bonobo_Storage
smem_open_storage_impl (PortableServer_Servant servant,
const CORBA_char *path,
Bonobo_Storage_OpenMode mode,
CORBA_Environment *ev)
{
BonoboStorageMem *storage;
BonoboStorageMem *parent_storage;
BonoboStorageMemEntry *entry;
BonoboObject *ret = NULL;
gchar *path_last = NULL;
storage = BONOBO_STORAGE_MEM (bonobo_object (servant));
parent_storage = smem_get_last_storage (storage, path, &path_last);
if (!parent_storage) {
bonobo_exception_set (ev, ex_Bonobo_Storage_NotFound);
goto ex_out;
}
entry = g_hash_table_lookup (parent_storage->priv->entries, path_last);
/* Error cases */
/* Case 1: Storage not found */
if (!entry && !(mode & Bonobo_Storage_CREATE)) {
bonobo_exception_set (ev, ex_Bonobo_Storage_NotFound);
goto ex_out;
}
/* Case 2: A stream by the same name exists */
if (entry && !entry->is_directory) {
if (mode & Bonobo_Storage_CREATE)
bonobo_exception_set (ev, ex_Bonobo_Storage_NameExists);
else
bonobo_exception_set (ev, ex_Bonobo_Storage_NotStorage);
goto ex_out;
}
if (!entry) {
ret = bonobo_storage_mem_create ();
entry = g_new0 (BonoboStorageMemEntry, 1);
entry->is_directory = TRUE;
entry->child = ret;
g_hash_table_insert (parent_storage->priv->entries,
g_strdup (path_last),
entry);
goto ok_out;
}
ret = entry->child;
ok_out:
g_free (path_last);
return bonobo_object_dup_ref (BONOBO_OBJREF (ret), ev);
ex_out:
g_free (path_last);
return CORBA_OBJECT_NIL;
}
static void
smem_copy_to_impl (PortableServer_Servant servant,
const Bonobo_Storage target,
CORBA_Environment *ev)
{
BonoboStorageMem *storage;
storage = BONOBO_STORAGE_MEM (bonobo_object (servant));
bonobo_storage_copy_to (
bonobo_object_corba_objref (BONOBO_OBJECT (storage)),
target, ev);
}
static Bonobo_Storage_DirectoryList *
smem_list_contents_impl (PortableServer_Servant servant,
const CORBA_char *path,
const Bonobo_StorageInfoFields mask,
CORBA_Environment *ev)
{
BonoboStorageMem *storage;
Bonobo_Storage_DirectoryList *ret_val = NULL;
Bonobo_StorageInfo *info;
BonoboStorageMem *last_storage;
gchar *path_last;
GList *list;
DirCBData cb_data;
int i;
storage = BONOBO_STORAGE_MEM (bonobo_object (servant));
last_storage = smem_get_last_storage (storage, path, &path_last);
if (!last_storage) {
bonobo_exception_set (ev, ex_Bonobo_Storage_NotFound);
goto out;
}
if (path_last) { /* The requested entry is a stream or does not
exist */
if (g_hash_table_lookup (last_storage->priv->entries, path_last))
bonobo_exception_set (ev, ex_Bonobo_Storage_NotStorage);
else
bonobo_exception_set (ev, ex_Bonobo_Storage_NotFound);
goto out;
}
cb_data.list = NULL;
cb_data.mask = mask;
g_hash_table_foreach (last_storage->priv->entries,
smem_dir_hash_cb, &cb_data);
ret_val = Bonobo_Storage_DirectoryList__alloc ();
list = cb_data.list;
ret_val->_length = g_list_length (list);
ret_val->_buffer = Bonobo_Storage_DirectoryList_allocbuf (ret_val->_length);
for (i = 0; list != NULL; list = list->next, i++) {
info = list->data;
ret_val->_buffer[i].name = CORBA_string_dup (info->name);
ret_val->_buffer[i].type = info->type;
ret_val->_buffer[i].content_type = CORBA_string_dup (info->content_type);
ret_val->_buffer[i].size = info->size;
CORBA_free (info);
}
g_list_free (cb_data.list);
out:
g_free (path_last);
return ret_val;
}
static void
smem_erase_impl (PortableServer_Servant servant,
const CORBA_char *path,
CORBA_Environment *ev)
{
BonoboStorageMem *storage;
BonoboStorageMemEntry *entry = NULL;
BonoboStorageMem *parent_storage;
gchar *filename = NULL;
storage = BONOBO_STORAGE_MEM (bonobo_object (servant));
parent_storage = smem_get_parent (storage, path, &filename, &entry);
if (!parent_storage) {
bonobo_exception_set (ev, ex_Bonobo_Storage_NotFound);
goto out;
}
if (entry->is_directory) {
BonoboStorageMem *storage_to_remove =
BONOBO_STORAGE_MEM (entry->child);
/* You can't remove the root item */
if (!strcmp (path, "/") || !strcmp (path, "")) {
bonobo_exception_set (ev, ex_Bonobo_Storage_IOError);
goto out;
}
/* Is the storage empty? */
if (g_hash_table_size (storage_to_remove->priv->entries)) {
bonobo_exception_set (ev, ex_Bonobo_Storage_NotEmpty);
goto out;
}
g_hash_table_remove (parent_storage->priv->entries, filename);
} else
g_hash_table_remove (parent_storage->priv->entries,
filename);
out:
bonobo_storage_mem_entry_free (entry);
g_free (filename);
}
static void
smem_rename_impl (PortableServer_Servant servant,
const CORBA_char *path,
const CORBA_char *new_path,
CORBA_Environment *ev)
{
BonoboStorageMem *storage;
BonoboStorageMem *parent_storage, *target_storage;
BonoboStorageMemEntry *entry;
gchar *filename = NULL, *new_filename;
if (!strcmp (path, "/") || !strcmp (path, "")) {
bonobo_exception_set (ev, ex_Bonobo_Storage_IOError);
goto out;
}
storage = BONOBO_STORAGE_MEM (bonobo_object (servant));
parent_storage = smem_get_parent (storage, path, &filename, &entry);
target_storage = smem_get_last_storage (storage, new_path, &new_filename);
/* Source or target does not exists */
if (!parent_storage || !target_storage) {
bonobo_exception_set (ev, ex_Bonobo_Storage_NotFound);
goto out;
}
/* Target exists and is not a storage */
if (new_filename && g_hash_table_lookup (target_storage->priv->entries,
new_filename)) {
bonobo_exception_set (ev, ex_Bonobo_Storage_NameExists);
goto out;
}
g_hash_table_remove (parent_storage->priv->entries, filename);
/* If target does not exists, new_filename will be non-NULL */
if (new_filename)
g_hash_table_insert (target_storage->priv->entries,
new_filename, entry);
else
g_hash_table_insert (target_storage->priv->entries,
g_strdup (filename), entry);
out:
g_free (filename);
}
static void
smem_commit_impl (PortableServer_Servant servant,
CORBA_Environment *ev)
{
bonobo_exception_set (ev, ex_Bonobo_Storage_NotSupported);
}
static void
smem_revert_impl (PortableServer_Servant servant,
CORBA_Environment *ev)
{
bonobo_exception_set (ev, ex_Bonobo_Storage_NotSupported);
}
static void
bonobo_storage_mem_finalize (GObject *object)
{
BonoboStorageMem *smem = BONOBO_STORAGE_MEM (object);
if (smem->priv) {
g_hash_table_destroy (smem->priv->entries);
g_free (smem->priv);
smem->priv = NULL;
}
G_OBJECT_CLASS (bonobo_storage_mem_parent_class)->finalize (object);
}
static void
bonobo_storage_mem_init (BonoboStorageMem *smem)
{
smem->priv = g_new0 (BonoboStorageMemPriv, 1);
smem->priv->entries = g_hash_table_new_full (
g_str_hash, g_str_equal, g_free,
bonobo_storage_mem_entry_free);
}
static void
bonobo_storage_mem_class_init (BonoboStorageMemClass *klass)
{
GObjectClass *object_class = (GObjectClass *) klass;
POA_Bonobo_Storage__epv *epv = &klass->epv;
bonobo_storage_mem_parent_class = g_type_class_peek_parent (klass);
object_class->finalize = bonobo_storage_mem_finalize;
epv->getInfo = smem_get_info_impl;
epv->setInfo = smem_set_info_impl;
epv->listContents = smem_list_contents_impl;
epv->openStream = smem_open_stream_impl;
epv->openStorage = smem_open_storage_impl;
epv->copyTo = smem_copy_to_impl;
epv->erase = smem_erase_impl;
epv->rename = smem_rename_impl;
epv->commit = smem_commit_impl;
epv->revert = smem_revert_impl;
}
BONOBO_TYPE_FUNC_FULL (BonoboStorageMem,
Bonobo_Storage,
BONOBO_TYPE_OBJECT,
bonobo_storage_mem)
BonoboObject *
bonobo_storage_mem_create (void)
{
BonoboStorageMem *smem;
smem = g_object_new (bonobo_storage_mem_get_type (), NULL);
if (!smem)
return NULL;
return BONOBO_STORAGE (smem);
}
|
Distrotech/libbonobo
|
bonobo/bonobo-storage-memory.c
|
C
|
gpl-2.0
| 18,712 |
/*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file blender/freestyle/intern/view_map/BoxGrid.cpp
* \ingroup freestyle
* \brief Class to define a cell grid surrounding the projected image of a scene
* \author Alexander Beels
* \date 2011-1-29
*/
#include <algorithm>
#include <stdexcept>
#include "BoxGrid.h"
#include "BKE_global.h"
using namespace std;
namespace Freestyle {
// Helper Classes
// OccluderData
///////////////
// Cell
/////////
BoxGrid::Cell::Cell() {}
BoxGrid::Cell::~Cell() {}
void BoxGrid::Cell::setDimensions(real x, real y, real sizeX, real sizeY)
{
const real epsilon = 1.0e-06;
boundary[0] = x - epsilon;
boundary[1] = x + sizeX + epsilon;
boundary[2] = y - epsilon;
boundary[3] = y + sizeY + epsilon;
}
bool BoxGrid::Cell::compareOccludersByShallowestPoint(const BoxGrid::OccluderData *a, const BoxGrid::OccluderData *b)
{
return a->shallowest < b->shallowest;
}
void BoxGrid::Cell::indexPolygons()
{
// Sort occluders by their shallowest points.
sort(faces.begin(), faces.end(), compareOccludersByShallowestPoint);
}
// Iterator
//////////////////
BoxGrid::Iterator::Iterator (BoxGrid& grid, Vec3r& center, real /*epsilon*/)
: _target(grid.transform(center)), _foundOccludee(false)
{
// Find target cell
_cell = grid.findCell(_target);
#if BOX_GRID_LOGGING
if (G.debug & G_DEBUG_FREESTYLE) {
cout << "Searching for occluders of edge centered at " << _target << " in cell [" <<
1_cell->boundary[0] << ", " << _cell->boundary[1] << ", " << _cell->boundary[2] <<
", " << _cell->boundary[3] << "] (" << _cell->faces.size() << " occluders)" << endl;
}
#endif
// Set iterator
_current = _cell->faces.begin();
}
BoxGrid::Iterator::~Iterator() {}
// BoxGrid
/////////////////
BoxGrid::BoxGrid(OccluderSource& source, GridDensityProvider& density, ViewMap *viewMap, Vec3r& viewpoint,
bool enableQI)
: _viewpoint(viewpoint), _enableQI(enableQI)
{
// Generate Cell structure
if (G.debug & G_DEBUG_FREESTYLE) {
cout << "Generate Cell structure" << endl;
}
assignCells(source, density, viewMap);
// Fill Cells
if (G.debug & G_DEBUG_FREESTYLE) {
cout << "Distribute occluders" << endl;
}
distributePolygons(source);
// Reorganize Cells
if (G.debug & G_DEBUG_FREESTYLE) {
cout << "Reorganize cells" << endl;
}
reorganizeCells();
if (G.debug & G_DEBUG_FREESTYLE) {
cout << "Ready to use BoxGrid" << endl;
}
}
BoxGrid::~BoxGrid() {}
void BoxGrid::assignCells (OccluderSource& /*source*/, GridDensityProvider& density, ViewMap *viewMap)
{
_cellSize = density.cellSize();
_cellsX = density.cellsX();
_cellsY = density.cellsY();
_cellOrigin[0] = density.cellOrigin(0);
_cellOrigin[1] = density.cellOrigin(1);
if (G.debug & G_DEBUG_FREESTYLE) {
cout << "Using " << _cellsX << "x" << _cellsY << " cells of size " << _cellSize << " square." << endl;
cout << "Cell origin: " << _cellOrigin[0] << ", " << _cellOrigin[1] << endl;
}
// Now allocate the cell table and fill it with default (empty) cells
_cells.resize(_cellsX * _cellsY);
for (cellContainer::iterator i = _cells.begin(), end = _cells.end(); i != end; ++i) {
(*i) = NULL;
}
// Identify cells that will be used, and set the dimensions for each
ViewMap::fedges_container& fedges = viewMap->FEdges();
for (ViewMap::fedges_container::iterator f = fedges.begin(), fend = fedges.end(); f != fend; ++f) {
if ((*f)->isInImage()) {
Vec3r point = transform((*f)->center3d());
unsigned int i, j;
getCellCoordinates(point, i, j);
if (_cells[i * _cellsY + j] == NULL) {
// This is an uninitialized cell
real x, y, width, height;
x = _cellOrigin[0] + _cellSize * i;
width = _cellSize;
y = _cellOrigin[1] + _cellSize * j;
height = _cellSize;
// Initialize cell
Cell *b = _cells[i * _cellsY + j] = new Cell();
b->setDimensions(x, y, width, height);
}
}
}
}
void BoxGrid::distributePolygons(OccluderSource& source)
{
unsigned long nFaces = 0;
unsigned long nKeptFaces = 0;
for (source.begin(); source.isValid(); source.next()) {
OccluderData *occluder = NULL;
try {
if (insertOccluder(source, occluder)) {
_faces.push_back(occluder);
++nKeptFaces;
}
}
catch (...) {
// If an exception was thrown, _faces.push_back() cannot have succeeded.
// occluder is not owned by anyone, and must be deleted.
// If the exception was thrown before or during new OccluderData(), then
// occluder is NULL, and this delete is harmless.
delete occluder;
throw;
}
++nFaces;
}
if (G.debug & G_DEBUG_FREESTYLE) {
cout << "Distributed " << nFaces << " occluders. Retained " << nKeptFaces << "." << endl;
}
}
void BoxGrid::reorganizeCells()
{
// Sort the occluders by shallowest point
for (vector<Cell*>::iterator i = _cells.begin(), end = _cells.end(); i != end; ++i) {
if (*i != NULL) {
(*i)->indexPolygons();
}
}
}
void BoxGrid::getCellCoordinates(const Vec3r& point, unsigned& x, unsigned& y)
{
x = min(_cellsX - 1, (unsigned) floor (max((double) 0.0f, point[0] - _cellOrigin[0]) / _cellSize));
y = min(_cellsY - 1, (unsigned) floor (max((double) 0.0f, point[1] - _cellOrigin[1]) / _cellSize));
}
BoxGrid::Cell *BoxGrid::findCell(const Vec3r& point)
{
unsigned int x, y;
getCellCoordinates(point, x, y);
return _cells[x * _cellsY + y];
}
bool BoxGrid::orthographicProjection() const
{
return true;
}
const Vec3r& BoxGrid::viewpoint() const
{
return _viewpoint;
}
bool BoxGrid::enableQI() const
{
return _enableQI;
}
BoxGrid::Transform::Transform() : GridHelpers::Transform() {}
Vec3r BoxGrid::Transform::operator()(const Vec3r& point) const
{
return Vec3r(point[0], point[1], -point[2]);
}
} /* namespace Freestyle */
|
pawkoz/dyplom
|
blender/source/blender/freestyle/intern/view_map/BoxGrid.cpp
|
C++
|
gpl-2.0
| 6,488 |
/**
* Created by sridharrajs on 2/12/16.
*/
'use strict';
angular
.module('yabt')
.controller('SettingsCtrl', SettingsCtrl);
function SettingsCtrl(Article) {
let self = this;
self.clearArticles = ()=> {
Article.deleteAll();
};
}
|
sridharrajs/yabt
|
client/settings/settings.controller.js
|
JavaScript
|
gpl-2.0
| 250 |
/*
* AVR USART
*
* Copyright (c) 2018 University of Kent
* Author: Sarah Harris
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>
*/
#ifndef HW_CHAR_AVR_USART_H
#define HW_CHAR_AVR_USART_H
#include "hw/sysbus.h"
#include "chardev/char-fe.h"
#include "hw/hw.h"
#include "qom/object.h"
/* Offsets of registers. */
#define USART_DR 0x06
#define USART_CSRA 0x00
#define USART_CSRB 0x01
#define USART_CSRC 0x02
#define USART_BRRH 0x05
#define USART_BRRL 0x04
/* Relevant bits in regiters. */
#define USART_CSRA_RXC (1 << 7)
#define USART_CSRA_TXC (1 << 6)
#define USART_CSRA_DRE (1 << 5)
#define USART_CSRA_MPCM (1 << 0)
#define USART_CSRB_RXCIE (1 << 7)
#define USART_CSRB_TXCIE (1 << 6)
#define USART_CSRB_DREIE (1 << 5)
#define USART_CSRB_RXEN (1 << 4)
#define USART_CSRB_TXEN (1 << 3)
#define USART_CSRB_CSZ2 (1 << 2)
#define USART_CSRB_RXB8 (1 << 1)
#define USART_CSRB_TXB8 (1 << 0)
#define USART_CSRC_MSEL1 (1 << 7)
#define USART_CSRC_MSEL0 (1 << 6)
#define USART_CSRC_PM1 (1 << 5)
#define USART_CSRC_PM0 (1 << 4)
#define USART_CSRC_CSZ1 (1 << 2)
#define USART_CSRC_CSZ0 (1 << 1)
#define TYPE_AVR_USART "avr-usart"
typedef struct AVRUsartState AVRUsartState;
DECLARE_INSTANCE_CHECKER(AVRUsartState, AVR_USART,
TYPE_AVR_USART)
struct AVRUsartState {
/* <private> */
SysBusDevice parent_obj;
/* <public> */
MemoryRegion mmio;
CharBackend chr;
bool enabled;
uint8_t data;
bool data_valid;
uint8_t char_mask;
/* Control and Status Registers */
uint8_t csra;
uint8_t csrb;
uint8_t csrc;
/* Baud Rate Registers (low/high byte) */
uint8_t brrh;
uint8_t brrl;
/* Receive Complete */
qemu_irq rxc_irq;
/* Transmit Complete */
qemu_irq txc_irq;
/* Data Register Empty */
qemu_irq dre_irq;
};
#endif /* HW_CHAR_AVR_USART_H */
|
dslutz/qemu
|
include/hw/char/avr_usart.h
|
C
|
gpl-2.0
| 2,525 |
module DomainChecks
def self.included(base)
base.belongs_to :domain
base.validates_presence_of :domain
base.before_validation :domain_checks_before_validation
base.before_save :ensure_same_domain
base.before_destroy :ensure_same_domain
unless base.instance_methods.include?("after_find")
base.class_eval do
def after_find
# empty method - defined so that aliast_method_chain would work
end
end
end
base.alias_method_chain(:after_find, :domain_checks)
end
# Sets the domain to current if not set to anything else
# for new objects
def domain_checks_before_validation
if self.new_record? && self.domain.nil? then
self.domain = Domain.current
end
end
# after_find callbacks must be defined directly.
# This overwrites other after_find methods,
# when this becomes a problem use method chaining
def after_find_with_domain_checks
after_find_without_domain_checks
ensure_same_domain
end
#
# Ensures that loaded/saved/destroyed objects belong to the current domain.
#
def ensure_same_domain
return if Thread.current[:domain_checks_suspended]
if Domain.current.nil? then
raise SecurityError.new("No current domain!")
end
unless (Domain.current.new_record? && Domain.current == self.domain) || (Domain.current.id == self.domain_id)
message = "Cross-domain access requested."
if RAILS_ENV == 'development' or RAILS_ENV == 'test' then
message << " Class: #{self.class.to_s}, id: #{self.id}, domain_id: #{self.domain_id}, current domain_id: #{Domain.current.id}"
end
raise SecurityError.new(message)
end
end
def self.disable
previous = Thread.current[:domain_checks_suspended]
begin
Thread.current[:domain_checks_suspended] = true
return yield
ensure
Thread.current[:domain_checks_suspended] = previous
end
end
end
|
Dreyerized/bananascrum
|
app/models/mixins/domain_checks.rb
|
Ruby
|
gpl-2.0
| 1,961 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2009-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.sms.gateways.internal;
import java.util.ArrayList;
import java.util.List;
import org.opennms.core.soa.Registration;
import org.opennms.core.soa.ServiceRegistry;
import org.opennms.sms.reflector.smsservice.GatewayGroup;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
/**
* <p>OnmsGatewayGroupRegistrar class.</p>
*
* @author ranger
* @version $Id: $
*/
public class OnmsGatewayGroupRegistrar implements GatewayGroupRegistrar, DisposableBean, InitializingBean {
private final List<Registration> m_registrations = new ArrayList<Registration>();
private ServiceRegistry m_serviceRegistry;
/** {@inheritDoc} */
@Override
public void registerGatewayGroup(GatewayGroup gatewayGroup) {
m_registrations.add( m_serviceRegistry.register(gatewayGroup, GatewayGroup.class));
}
/**
* <p>destroy</p>
*
* @throws java.lang.Exception if any.
*/
@Override
public void destroy() throws Exception {
for(Registration registration : m_registrations) {
registration.unregister();
}
}
/**
* <p>setServiceRegistry</p>
*
* @param serviceRegistry a {@link org.opennms.core.soa.ServiceRegistry} object.
*/
public void setServiceRegistry(ServiceRegistry serviceRegistry) {
m_serviceRegistry = serviceRegistry;
}
/**
* <p>getServiceRegistry</p>
*
* @return a {@link org.opennms.core.soa.ServiceRegistry} object.
*/
public ServiceRegistry getServiceRegistry() {
return m_serviceRegistry;
}
/**
* <p>afterPropertiesSet</p>
*
* @throws java.lang.Exception if any.
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(m_serviceRegistry, "serviceRegistry must not be null");
}
}
|
rfdrake/opennms
|
features/sms-reflector/sms-gateway/src/main/java/org/opennms/sms/gateways/internal/OnmsGatewayGroupRegistrar.java
|
Java
|
gpl-2.0
| 3,001 |
/*
* Compiz text plugin
* Description: Adds text to pixmap support to Compiz.
*
* text.c
*
* Copyright: (C) 2006-2007 Patrick Niklaus, Danny Baumann, Dennis Kasprzyk
* Authors: Patrick Niklaus <[email protected]>
* Danny Baumann <[email protected]>
* Dennis Kasprzyk <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#define _GNU_SOURCE
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <X11/Xatom.h>
#include <cairo-xlib-xrender.h>
#include <pango/pango.h>
#include <pango/pangocairo.h>
#include <compiz-core.h>
#include "compiz-text.h"
#define PI 3.14159265359f
static CompMetadata textMetadata;
static int displayPrivateIndex;
static int functionsPrivateIndex;
#define TEXT_DISPLAY_OPTION_ABI 0
#define TEXT_DISPLAY_OPTION_INDEX 1
#define TEXT_DISPLAY_OPTION_NUM 2
typedef struct _TextDisplay {
Atom visibleNameAtom;
CompOption opt[TEXT_DISPLAY_OPTION_NUM];
} TextDisplay;
#define GET_TEXT_DISPLAY(d) \
((TextDisplay *) (d)->base.privates[displayPrivateIndex].ptr)
#define TEXT_DISPLAY(d) \
TextDisplay *td = GET_TEXT_DISPLAY (d)
#define NUM_OPTIONS(d) (sizeof ((d)->opt) / sizeof (CompOption))
typedef struct _TextSurfaceData {
int width;
int height;
cairo_t *cr;
cairo_surface_t *surface;
PangoLayout *layout;
Pixmap pixmap;
XRenderPictFormat *format;
PangoFontDescription *font;
Screen *screen;
} TextSurfaceData;
static char *
textGetUtf8Property (CompDisplay *d,
Window id,
Atom atom)
{
Atom type;
int result, format;
unsigned long nItems, bytesAfter;
char *val, *retval = NULL;
result = XGetWindowProperty (d->display, id, atom, 0L, 65536, False,
d->utf8StringAtom, &type, &format, &nItems,
&bytesAfter, (unsigned char **) &val);
if (result != Success)
return NULL;
if (type == d->utf8StringAtom && format == 8 && val && nItems > 0)
{
retval = malloc (sizeof (char) * (nItems + 1));
if (retval)
{
strncpy (retval, val, nItems);
retval[nItems] = 0;
}
}
if (val)
XFree (val);
return retval;
}
static char *
textGetTextProperty (CompDisplay *d,
Window id,
Atom atom)
{
XTextProperty text;
char *retval = NULL;
text.nitems = 0;
if (XGetTextProperty (d->display, id, &text, atom))
{
if (text.value)
{
retval = malloc (sizeof (char) * (text.nitems + 1));
if (retval)
{
strncpy (retval, (char *) text.value, text.nitems);
retval[text.nitems] = 0;
}
XFree (text.value);
}
}
return retval;
}
static char *
textGetWindowName (CompDisplay *d,
Window id)
{
char *name;
TEXT_DISPLAY (d);
name = textGetUtf8Property (d, id, td->visibleNameAtom);
if (!name)
name = textGetUtf8Property (d, id, d->wmNameAtom);
if (!name)
name = textGetTextProperty (d, id, XA_WM_NAME);
return name;
}
/*
* Draw a rounded rectangle path
*/
static void
textDrawTextBackground (cairo_t *cr,
int x,
int y,
int width,
int height,
int radius)
{
int x0, y0, x1, y1;
x0 = x;
y0 = y;
x1 = x + width;
y1 = y + height;
cairo_new_path (cr);
cairo_arc (cr, x0 + radius, y1 - radius, radius, PI / 2, PI);
cairo_line_to (cr, x0, y0 + radius);
cairo_arc (cr, x0 + radius, y0 + radius, radius, PI, 3 * PI / 2);
cairo_line_to (cr, x1 - radius, y0);
cairo_arc (cr, x1 - radius, y0 + radius, radius, 3 * PI / 2, 2 * PI);
cairo_line_to (cr, x1, y1 - radius);
cairo_arc (cr, x1 - radius, y1 - radius, radius, 0, PI / 2);
cairo_close_path (cr);
}
static Bool
textInitCairo (CompScreen *s,
TextSurfaceData *data,
int width,
int height)
{
Display *dpy = s->display->display;
data->pixmap = None;
if (width > 0 && height > 0)
data->pixmap = XCreatePixmap (dpy, s->root, width, height, 32);
data->width = width;
data->height = height;
if (!data->pixmap)
{
compLogMessage ("text", CompLogLevelError,
"Couldn't create %d x %d pixmap.", width, height);
return FALSE;
}
data->surface = cairo_xlib_surface_create_with_xrender_format (dpy,
data->pixmap,
data->screen,
data->format,
width,
height);
if (cairo_surface_status (data->surface) != CAIRO_STATUS_SUCCESS)
{
compLogMessage ("text", CompLogLevelError, "Couldn't create surface.");
return FALSE;
}
data->cr = cairo_create (data->surface);
if (cairo_status (data->cr) != CAIRO_STATUS_SUCCESS)
{
compLogMessage ("text", CompLogLevelError,
"Couldn't create cairo context.");
return FALSE;
}
return TRUE;
}
static Bool
textInitSurface (CompScreen *s,
TextSurfaceData *data)
{
Display *dpy = s->display->display;
data->screen = ScreenOfDisplay (dpy, s->screenNum);
if (!data->screen)
{
compLogMessage ("text", CompLogLevelError,
"Couldn't get screen for %d.", s->screenNum);
return FALSE;
}
data->format = XRenderFindStandardFormat (dpy, PictStandardARGB32);
if (!data->format)
{
compLogMessage ("text", CompLogLevelError, "Couldn't get format.");
return FALSE;
}
if (!textInitCairo (s, data, 1, 1))
return FALSE;
/* init pango */
data->layout = pango_cairo_create_layout (data->cr);
if (!data->layout)
{
compLogMessage ("text", CompLogLevelError,
"Couldn't create pango layout.");
return FALSE;
}
data->font = pango_font_description_new ();
if (!data->font)
{
compLogMessage ("text", CompLogLevelError,
"Couldn't create font description.");
return FALSE;
}
return TRUE;
}
static Bool
textUpdateSurface (CompScreen *s,
TextSurfaceData *data,
int width,
int height)
{
Display *dpy = s->display->display;
cairo_surface_destroy (data->surface);
data->surface = NULL;
cairo_destroy (data->cr);
data->cr = NULL;
XFreePixmap (dpy, data->pixmap);
data->pixmap = None;
return textInitCairo (s, data, width, height);
}
static Bool
textRenderTextToSurface (CompScreen *s,
const char *text,
TextSurfaceData *data,
const CompTextAttrib *attrib)
{
int width, height, layoutWidth;
pango_font_description_set_family (data->font, attrib->family);
pango_font_description_set_absolute_size (data->font,
attrib->size * PANGO_SCALE);
pango_font_description_set_style (data->font, PANGO_STYLE_NORMAL);
if (attrib->flags & CompTextFlagStyleBold)
pango_font_description_set_weight (data->font, PANGO_WEIGHT_BOLD);
if (attrib->flags & CompTextFlagStyleItalic)
pango_font_description_set_style (data->font, PANGO_STYLE_ITALIC);
pango_layout_set_font_description (data->layout, data->font);
if (attrib->flags & CompTextFlagEllipsized)
pango_layout_set_ellipsize (data->layout, PANGO_ELLIPSIZE_END);
pango_layout_set_auto_dir (data->layout, FALSE);
pango_layout_set_text (data->layout, text, -1);
pango_layout_get_pixel_size (data->layout, &width, &height);
if (attrib->flags & CompTextFlagWithBackground)
{
width += 2 * attrib->bgHMargin;
height += 2 * attrib->bgVMargin;
}
width = MIN (attrib->maxWidth, width);
height = MIN (attrib->maxHeight, height);
/* update the size of the pango layout */
layoutWidth = attrib->maxWidth;
if (attrib->flags & CompTextFlagWithBackground)
layoutWidth -= 2 * attrib->bgHMargin;
pango_layout_set_width (data->layout, layoutWidth * PANGO_SCALE);
if (!textUpdateSurface (s, data, width, height))
return FALSE;
pango_cairo_update_layout (data->cr, data->layout);
cairo_save (data->cr);
cairo_set_operator (data->cr, CAIRO_OPERATOR_CLEAR);
cairo_paint (data->cr);
cairo_restore (data->cr);
cairo_set_operator (data->cr, CAIRO_OPERATOR_OVER);
if (attrib->flags & CompTextFlagWithBackground)
{
textDrawTextBackground (data->cr, 0, 0, width, height,
MIN (attrib->bgHMargin, attrib->bgVMargin));
cairo_set_source_rgba (data->cr,
attrib->bgColor[0] / 65535.0,
attrib->bgColor[1] / 65535.0,
attrib->bgColor[2] / 65535.0,
attrib->bgColor[3] / 65535.0);
cairo_fill (data->cr);
cairo_move_to (data->cr, attrib->bgHMargin, attrib->bgVMargin);
}
cairo_set_source_rgba (data->cr,
attrib->color[0] / 65535.0,
attrib->color[1] / 65535.0,
attrib->color[2] / 65535.0,
attrib->color[3] / 65535.0);
pango_cairo_show_layout (data->cr, data->layout);
return TRUE;
}
static void
textCleanupSurface (TextSurfaceData *data)
{
if (data->layout)
g_object_unref (data->layout);
if (data->surface)
cairo_surface_destroy (data->surface);
if (data->cr)
cairo_destroy (data->cr);
if (data->font)
pango_font_description_free (data->font);
}
static CompTextData *
textRenderText (CompScreen *s,
const char *text,
const CompTextAttrib *attrib)
{
TextSurfaceData surface;
CompTextData *retval = NULL;
if (!text || !strlen (text))
return NULL;
memset (&surface, 0, sizeof (TextSurfaceData));
if (textInitSurface (s, &surface) &&
textRenderTextToSurface (s, text, &surface, attrib))
{
retval = calloc (1, sizeof (CompTextData));
if (retval && !(attrib->flags & CompTextFlagNoAutoBinding))
{
retval->texture = malloc (sizeof (CompTexture));
if (!retval->texture)
{
free (retval);
retval = NULL;
}
}
if (retval)
{
retval->pixmap = surface.pixmap;
retval->width = surface.width;
retval->height = surface.height;
if (retval->texture)
{
initTexture (s, retval->texture);
if (!bindPixmapToTexture (s, retval->texture, retval->pixmap,
retval->width, retval->height, 32))
{
compLogMessage ("text", CompLogLevelError,
"Failed to bind text pixmap to texture.");
free (retval->texture);
free (retval);
retval = NULL;
}
}
}
}
if (!retval && surface.pixmap)
XFreePixmap (s->display->display, surface.pixmap);
textCleanupSurface (&surface);
return retval;
}
static CompTextData *
textRenderWindowTitle (CompScreen *s,
Window window,
Bool withViewportNumber,
const CompTextAttrib *attrib)
{
char *text = NULL;
CompTextData *retval;
if (withViewportNumber)
{
char *title;
title = textGetWindowName (s->display, window);
if (title)
{
CompWindow *w;
w = findWindowAtDisplay (s->display, window);
if (w)
{
int vx, vy, viewport;
defaultViewportForWindow (w, &vx, &vy);
viewport = vy * w->screen->hsize + vx + 1;
if (asprintf (&text, "%s -[%d]-", title, viewport) == -1)
{
free (title);
return textRenderText (s, "Error: textRenderWindowTitle", attrib);
}
free (title);
}
else
{
text = title;
}
}
}
else
{
text = textGetWindowName (s->display, window);
}
retval = textRenderText (s, text, attrib);
if (text)
free (text);
return retval;
}
static void
textDrawText (CompScreen *s,
const CompTextData *data,
float x,
float y,
float alpha)
{
GLboolean wasBlend;
GLint oldBlendSrc, oldBlendDst;
CompMatrix *m;
float width, height;
if (!data->texture)
return;
glGetIntegerv (GL_BLEND_SRC, &oldBlendSrc);
glGetIntegerv (GL_BLEND_DST, &oldBlendDst);
wasBlend = glIsEnabled (GL_BLEND);
if (!wasBlend)
glEnable (GL_BLEND);
glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glColor4f (alpha, alpha, alpha, alpha);
enableTexture (s, data->texture, COMP_TEXTURE_FILTER_GOOD);
m = &data->texture->matrix;
width = data->width;
height = data->height;
glBegin (GL_QUADS);
glTexCoord2f (COMP_TEX_COORD_X (m, 0), COMP_TEX_COORD_Y (m, 0));
glVertex2f (x, y - height);
glTexCoord2f (COMP_TEX_COORD_X (m, 0), COMP_TEX_COORD_Y (m, height));
glVertex2f (x, y);
glTexCoord2f (COMP_TEX_COORD_X (m, width), COMP_TEX_COORD_Y (m, height));
glVertex2f (x + width, y);
glTexCoord2f (COMP_TEX_COORD_X (m, width), COMP_TEX_COORD_Y (m, 0));
glVertex2f (x + width, y - height);
glEnd ();
disableTexture (s, data->texture);
glColor4usv (defaultColor);
if (!wasBlend)
glDisable (GL_BLEND);
glBlendFunc (oldBlendSrc, oldBlendDst);
}
static void
textFiniTextData (CompScreen *s,
CompTextData *data)
{
if (data->texture)
{
finiTexture (s, data->texture);
free (data->texture);
}
XFreePixmap (s->display->display, data->pixmap);
free (data);
}
static TextFunc textFunctions =
{
.renderText = textRenderText,
.renderWindowTitle = textRenderWindowTitle,
.drawText = textDrawText,
.finiTextData = textFiniTextData
};
static const CompMetadataOptionInfo textDisplayOptionInfo[] = {
{ "abi", "int", 0, 0, 0 },
{ "index", "int", 0, 0, 0 }
};
static CompOption *
textGetDisplayOptions (CompPlugin *plugin,
CompDisplay *display,
int *count)
{
TEXT_DISPLAY (display);
*count = NUM_OPTIONS (td);
return td->opt;
}
static Bool
textInitDisplay (CompPlugin *p,
CompDisplay *d)
{
TextDisplay *td;
if (!checkPluginABI ("core", CORE_ABIVERSION))
return FALSE;
td = malloc (sizeof (TextDisplay));
if (!td)
return FALSE;
if (!compInitDisplayOptionsFromMetadata (d,
&textMetadata,
textDisplayOptionInfo,
td->opt,
TEXT_DISPLAY_OPTION_NUM))
{
free (td);
return FALSE;
}
td->visibleNameAtom = XInternAtom (d->display,
"_NET_WM_VISIBLE_NAME", 0);
td->opt[TEXT_DISPLAY_OPTION_ABI].value.i = TEXT_ABIVERSION;
td->opt[TEXT_DISPLAY_OPTION_INDEX].value.i = functionsPrivateIndex;
d->base.privates[displayPrivateIndex].ptr = td;
d->base.privates[functionsPrivateIndex].ptr = &textFunctions;
return TRUE;
}
static void
textFiniDisplay (CompPlugin *p,
CompDisplay *d)
{
TEXT_DISPLAY (d);
compFiniDisplayOptions (d, td->opt, TEXT_DISPLAY_OPTION_NUM);
free (td);
}
static CompBool
textInitObject (CompPlugin *p,
CompObject *o)
{
static InitPluginObjectProc dispTab[] = {
(InitPluginObjectProc) 0, /* InitCore */
(InitPluginObjectProc) textInitDisplay
};
RETURN_DISPATCH (o, dispTab, ARRAY_SIZE (dispTab), TRUE, (p, o));
}
static void
textFiniObject (CompPlugin *p,
CompObject *o)
{
static FiniPluginObjectProc dispTab[] = {
(FiniPluginObjectProc) 0, /* FiniCore */
(FiniPluginObjectProc) textFiniDisplay
};
DISPATCH (o, dispTab, ARRAY_SIZE (dispTab), (p, o));
}
static CompOption *
textGetObjectOptions (CompPlugin *plugin,
CompObject *object,
int *count)
{
static GetPluginObjectOptionsProc dispTab[] = {
(GetPluginObjectOptionsProc) 0, /* GetCoreOptions */
(GetPluginObjectOptionsProc) textGetDisplayOptions
};
*count = 0;
RETURN_DISPATCH (object, dispTab, ARRAY_SIZE (dispTab),
NULL, (plugin, object, count));
}
static Bool
textInit (CompPlugin *p)
{
if (!compInitPluginMetadataFromInfo (&textMetadata,
p->vTable->name,
textDisplayOptionInfo,
TEXT_DISPLAY_OPTION_NUM,
NULL, 0))
return FALSE;
displayPrivateIndex = allocateDisplayPrivateIndex ();
if (displayPrivateIndex < 0)
{
compFiniMetadata (&textMetadata);
return FALSE;
}
functionsPrivateIndex = allocateDisplayPrivateIndex ();
if (functionsPrivateIndex < 0)
{
freeDisplayPrivateIndex (displayPrivateIndex);
compFiniMetadata (&textMetadata);
return FALSE;
}
compAddMetadataFromFile (&textMetadata, p->vTable->name);
return TRUE;
}
static void
textFini (CompPlugin *p)
{
freeDisplayPrivateIndex (displayPrivateIndex);
freeDisplayPrivateIndex (functionsPrivateIndex);
compFiniMetadata (&textMetadata);
}
static CompMetadata *
textGetMetadata (CompPlugin *p)
{
return &textMetadata;
}
CompPluginVTable textVTable = {
"text",
textGetMetadata,
textInit,
textFini,
textInitObject,
textFiniObject,
textGetObjectOptions,
0
};
CompPluginVTable *
getCompPluginInfo20070830 (void)
{
return &textVTable;
}
|
raveit65/compiz-plugins-main
|
src/text/text.c
|
C
|
gpl-2.0
| 17,370 |
/*
* Copyright (C) 2007 David Riseley
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace uk.org.riseley.puttySessionManager.model.eventargs
{
public class ExportSessionEventArgs : EventArgs
{
public enum ExportType {
REG_TYPE ,
CSV_TYPE ,
CLIP_TYPE
}
public ExportSessionEventArgs()
: this(ExportType.REG_TYPE)
{
}
public ExportSessionEventArgs(ExportType type)
{
this.type = type;
}
public ExportType type;
}
}
|
novakin/Kitty-Session-Manager
|
PuTTYSessionManager/model/eventargs/ExportSessionEventArgs.cs
|
C#
|
gpl-2.0
| 1,320 |
# All of the other examples directly embed the Javascript and CSS code for
# Bokeh's client-side runtime into the HTML. This leads to the HTML files
# being rather large. An alternative is to ask Bokeh to produce HTML that
# has a relative link to the Bokeh Javascript and CSS. This is easy to
# do; you just pass in a few extra arguments to the output_file() command.
import numpy as np
from bokeh.plotting import *
N = 100
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
output_file("relative_paths.html", title="Relative path example", mode="relative")
p = figure(tools="pan,wheel_zoom,box_zoom,reset,save")
p.circle(x,y, alpha=0.5, color="tomato", radius=0.1)
show(p)
# By default, the URLs for the Javascript and CSS will be relative to
# the current directory, i.e. the directory in which the HTML file is
# generated. You can provide a different "root" directory from which
# the relative paths will be computed:
#
# output_file("relative_paths.html", title="Relative path example",
# resources="relative", rootdir="some/other/path")
|
zrhans/python
|
exemplos/Examples.lnk/bokeh/plotting/file/relative_paths.py
|
Python
|
gpl-2.0
| 1,061 |
/*
* Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6844193
* @compile -XDignore.symbol.file MaxRetries.java
* @run main/othervm/timeout=300 -Dsun.net.spi.nameservice.provider.1=ns,mock MaxRetries
* @summary support max_retries in krb5.conf
*/
import javax.security.auth.login.LoginException;
import java.io.*;
import java.net.DatagramSocket;
import java.security.Security;
public class MaxRetries {
static int idlePort = -1;
static CommMatcher cm = new CommMatcher();
public static void main(String[] args)
throws Exception {
System.setProperty("sun.security.krb5.debug", "true");
OneKDC kdc = new OneKDC(null).writeJAASConf();
// An idle UDP socket to prevent PortUnreachableException
DatagramSocket ds = new DatagramSocket();
idlePort = ds.getLocalPort();
cm.addPort(idlePort);
cm.addPort(kdc.getPort());
System.setProperty("java.security.krb5.conf", "alternative-krb5.conf");
Security.setProperty("krb5.kdc.bad.policy", "trylast");
// We always make the real timeout to be 1 second
BadKdc.setRatio(0.25f);
rewriteMaxRetries(4);
// Explanation: In this case, max_retries=4 and timeout=4s.
// For AS-REQ without preauth, we will see 4 4s timeout on kdc#1
// ("a4" repeat 4 times), and one 4s timeout on kdc#2 ("b4"). For
// AS-REQ with preauth, one 4s timeout on kdc#2 (second "b4").
// we tolerate 4 real timeout on kdc#2, so make it "(b4){2,6}".
test1("a4a4a4a4b4b4", "a4a4a4a4(b4){2,6}");
test1("b4b4", "(b4){2,6}");
BadKdc.setRatio(1f);
rewriteMaxRetries(1);
// Explanation: Since max_retries=1 only, we could fail in 1st or 2nd
// AS-REQ to kdc#2.
String actual = test1("a1b1b1", "(a1b1b1|a1b1x|a1b1b1x)");
if (actual.endsWith("x")) {
// If 1st attempt fails, all bads are back available
test1("a1b1b1", "(a1b1b1|a1b1x|a1b1b1x)");
} else {
test1("b1b1", "(b1b1|b1x|b1b1x)");
}
BadKdc.setRatio(0.2f);
rewriteMaxRetries(-1);
test1("a5a5a5b5b5", "a5a5a5(b5){2,4}");
test1("b5b5", "(b5){2,4}");
BadKdc.setRatio(0.25f);
Security.setProperty("krb5.kdc.bad.policy",
"tryless:1,1000");
rewriteMaxRetries(4);
test1("a4a4a4a4b4a4b4", "a4a4a4a4(b4){1,3}a4(b4){1,3}");
test1("a4b4a4b4", "a4(b4){1,3}a4(b4){1,3}");
BadKdc.setRatio(1f);
rewriteMaxRetries(1);
actual = test1("a1b1a1b1", "(a1b1|a1b1x|a1b1a1b1|a1b1a1b1x)");
if (actual.endsWith("x")) {
test1("a1b1a1b1", "(a1b1|a1b1x|a1b1a1b1|a1b1a1b1x)");
} else {
test1("a1b1a1b1", "(a1b1|a1b1x|a1b1a1b1|a1b1a1b1x)");
}
BadKdc.setRatio(.2f);
rewriteMaxRetries(-1);
test1("a5a5a5b5a5b5", "a5a5a5(b5){1,2}a5(b5){1,2}");
test1("a5b5a5b5", "a5(b5){1,2}a5(b5){1,2}");
BadKdc.setRatio(1f);
rewriteMaxRetries(2);
if (BadKdc.toReal(2000) > 1000) {
// Explanation: if timeout is longer than 1s in tryLess,
// we will see "a1" at 2nd kdc#1 access
test1("a2a2b2a1b2", "a2a2(b2){1,2}a1(b2){1,2}");
} else {
test1("a2a2b2a2b2", "a2a2(b2){1,2}a2(b2){1,2}");
}
BadKdc.setRatio(1f);
rewriteUdpPrefLimit(-1, -1); // default, no limit
test2("UDP");
rewriteUdpPrefLimit(10, -1); // global rules
test2("TCP");
rewriteUdpPrefLimit(10, 10000); // realm rules
test2("UDP");
rewriteUdpPrefLimit(10000, 10); // realm rules
test2("TCP");
ds.close();
}
/**
* One round of test for max_retries and timeout.
*
* @param exact the expected exact match, where no timeout
* happens for real KDCs
* @param relaxed the expected relaxed match, where some timeout
* could happen for real KDCs
* @return the actual result
*/
private static String test1(String exact, String relaxed) throws Exception {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
PrintStream oldout = System.out;
System.setOut(new PrintStream(bo));
boolean failed = false;
long start = System.nanoTime();
try {
Context c = Context.fromJAAS("client");
} catch (LoginException e) {
failed = true;
}
System.setOut(oldout);
String[] lines = new String(bo.toByteArray()).split("\n");
System.out.println("----------------- TEST (" + exact
+ ") -----------------");
// Result, a series of timeout + kdc#
StringBuilder sb = new StringBuilder();
for (String line: lines) {
if (cm.match(line)) {
System.out.println(line);
sb.append(cm.kdc()).append(cm.timeout());
}
}
if (failed) {
sb.append("x");
}
System.out.println("Time: " + (System.nanoTime() - start) / 1000000000d);
String actual = sb.toString();
System.out.println("Actual: " + actual);
if (actual.equals(exact)) {
System.out.println("Exact match: " + exact);
} else if (actual.matches(relaxed)) {
System.out.println("!!!! Tolerant match: " + relaxed);
} else {
throw new Exception("Match neither " + exact + " nor " + relaxed);
}
return actual;
}
/**
* One round of test for udp_preference_limit.
* @param proto the expected protocol used
*/
private static void test2(String proto) throws Exception {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
PrintStream oldout = System.out;
System.setOut(new PrintStream(bo));
Context c = Context.fromJAAS("client");
System.setOut(oldout);
int count = 2;
String[] lines = new String(bo.toByteArray()).split("\n");
System.out.println("----------------- TEST -----------------");
for (String line: lines) {
if (cm.match(line)) {
System.out.println(line);
count--;
if (!cm.protocol().equals(proto)) {
throw new Exception("Wrong protocol value");
}
}
}
if (count != 0) {
throw new Exception("Retry count is " + count + " less");
}
}
/**
* Set udp_preference_limit for global and realm
*/
private static void rewriteUdpPrefLimit(int global, int realm)
throws Exception {
BufferedReader fr = new BufferedReader(new FileReader(OneKDC.KRB5_CONF));
FileWriter fw = new FileWriter("alternative-krb5.conf");
while (true) {
String s = fr.readLine();
if (s == null) {
break;
}
if (s.startsWith("[realms]")) {
// Reconfig global setting
fw.write("kdc_timeout = 5000\n");
if (global != -1) {
fw.write("udp_preference_limit = " + global + "\n");
}
} else if (s.trim().startsWith("kdc = ")) {
if (realm != -1) {
// Reconfig for realm
fw.write(" udp_preference_limit = " + realm + "\n");
}
}
fw.write(s + "\n");
}
fr.close();
fw.close();
sun.security.krb5.Config.refresh();
}
/**
* Set max_retries and timeout value for realm. The global value is always
* 3 and 5000.
*
* @param value max_retries and timeout/1000 for a realm, -1 means none.
*/
private static void rewriteMaxRetries(int value) throws Exception {
BufferedReader fr = new BufferedReader(new FileReader(OneKDC.KRB5_CONF));
FileWriter fw = new FileWriter("alternative-krb5.conf");
while (true) {
String s = fr.readLine();
if (s == null) {
break;
}
if (s.startsWith("[realms]")) {
// Reconfig global setting
fw.write("max_retries = 3\n");
fw.write("kdc_timeout = " + BadKdc.toReal(5000) + "\n");
} else if (s.trim().startsWith("kdc = ")) {
if (value != -1) {
// Reconfig for realm
fw.write(" max_retries = " + value + "\n");
fw.write(" kdc_timeout = " + BadKdc.toReal(value*1000) + "\n");
}
// Add a bad KDC as the first candidate
fw.write(" kdc = localhost:" + idlePort + "\n");
}
fw.write(s + "\n");
}
fr.close();
fw.close();
sun.security.krb5.Config.refresh();
}
}
|
ojdkbuild/lookaside_java-1.8.0-openjdk
|
jdk/test/sun/security/krb5/auto/MaxRetries.java
|
Java
|
gpl-2.0
| 9,989 |
local helpers = require "OAuth.helpers"
local url = "http://pili.la/api.php"
local function run(msg, matches)
local url_req = matches[1]
local request = {
url = url_req
}
local url = url .. "?" .. helpers.url_encode_arguments(request)
local res, code = http.request(url)
if code ~= 200 then
return "Sorry, can't connect"
end
return res
end
return {
description = "Short an url with the awesome http://pili.la",
usage = {
"!pili [url]: Short the url"
},
patterns = {
"^!pili (https?://[%w-_%.%?%.:/%+=&]+)$"
},
run = run
}
|
aTastyCookie/telegram-bot
|
plugins/pili.lua
|
Lua
|
gpl-2.0
| 596 |
wordpress
=========
Making a wordpress theme
|
rachellesalvadora/wordpress
|
first-theme/README.md
|
Markdown
|
gpl-2.0
| 46 |
namespace NotificationsExtensions
{
using System;
using System.Runtime.InteropServices;
internal sealed class NotificationContentValidationException : COMException
{
public NotificationContentValidationException(string message) : base(message, -2147024809)
{
}
}
}
|
anbare/NotificationsExtensions.Portable
|
Source/NotificationsExtensions/NotificationContentValidationException.cs
|
C#
|
gpl-2.0
| 314 |
/* This file is part of the KOffice project
* Copyright (C) 2005,2008,2010 Thomas Zander <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "TestPageManager.h"
#include <KWPageManager.h>
#include <KWPage.h>
#include <KoColorBackground.h>
#include <kdebug.h>
void TestPageManager::init()
{
}
void TestPageManager::getAddPages()
{
KWPageManager *pageManager = new KWPageManager();
QCOMPARE(pageManager->pageCount(), 0);
QVERIFY(! pageManager->page(0).isValid());
QVERIFY(! pageManager->page(1).isValid());
QVERIFY(! pageManager->page(-10).isValid());
QVERIFY(! pageManager->page(10).isValid());
KWPage page1 = pageManager->appendPage();
QCOMPARE(page1.pageNumber(), 1);
KWPage page3 = pageManager->appendPage();
QCOMPARE(page3.pageNumber(), 2);
QCOMPARE(pageManager->pageCount(), 2);
QCOMPARE(pageManager->page(1), page1);
QCOMPARE(pageManager->page(2), page3);
KWPage page2 = pageManager->insertPage(2);
QCOMPARE(page2.pageNumber(), 2);
QCOMPARE(pageManager->pageCount(), 3);
QCOMPARE(pageManager->page(1), page1);
QCOMPARE(pageManager->page(2), page2);
QCOMPARE(pageManager->page(3), page3);
KWPage page4 = pageManager->insertPage(4);
QCOMPARE(pageManager->pageCount(), 4);
QCOMPARE(pageManager->page(4), page4);
QCOMPARE(page1.pageNumber(), 1);
QCOMPARE(page2.pageNumber(), 2);
QCOMPARE(page3.pageNumber(), 3);
QCOMPARE(page4.pageNumber(), 4);
// fetching
KWPage page = pageManager->page(1);
QVERIFY(page.isValid());
QCOMPARE(page.pageNumber(), 1);
QCOMPARE(page.pageSide(), KWPage::Right);
QVERIFY(page.pageStyle().isValid());
KoPageLayout pageLayout = page.pageStyle().pageLayout();
pageLayout.width = 134.2;
pageLayout.height = 521.4;
page.pageStyle().setPageLayout(pageLayout);
QCOMPARE(page.width(), 134.2);
QCOMPARE(page.height(), 521.4);
#if 0 // TODO, missing feature :(
// test setStartPage
pageManager->setStartPage(4);
page = pageManager->page(0);
QCOMPARE(page == 0, true);
page = pageManager->page(3);
QCOMPARE(page == 0, true);
page = pageManager->page(5);
QCOMPARE(page == 0, true);
page = pageManager->page(4);
QCOMPARE(page == 0, false);
QCOMPARE(page->pageNumber(), 4);
QCOMPARE(page->pageSide(), KWPage::Left);
pageManager->setStartPage(1);
page = pageManager->page(0);
QCOMPARE(page == 0, true);
page = pageManager->page(3);
QCOMPARE(page == 0, true);
page = pageManager->page(2);
QCOMPARE(page == 0, true);
page = pageManager->page(1);
QCOMPARE(page == 0, false);
QCOMPARE(page->pageNumber(), 1);
QCOMPARE(page->pageSide(), KWPage::Right);
// adding pages
QCOMPARE(pageManager->pageCount(), 1);
QCOMPARE(pageManager->lastPageNumber(), 1);
pageManager->setStartPage(40);
QCOMPARE(pageManager->pageCount(), 1);
QCOMPARE(pageManager->lastPageNumber(), 40);
page = pageManager->appendPage();
QCOMPARE(pageManager->pageCount(), 2);
QCOMPARE(pageManager->lastPageNumber(), 41);
QCOMPARE(page == 0, false);
QCOMPARE(page->pageNumber(), 41);
QCOMPARE(page->pageSide(), KWPage::Right);
#endif
}
void TestPageManager::getAddPages2()
{
KWPageManager *pageManager = new KWPageManager();
KWPage page = pageManager->appendPage();
KoPageLayout pageLayout = page.pageStyle().pageLayout();
pageLayout.width = 200;
pageLayout.height = 200;
page.pageStyle().setPageLayout(pageLayout);
MockShape shape1;
shape1.setPosition(QPointF(0, 0));
shape1.setSize(QSizeF(2, 2));
QCOMPARE(pageManager->pageNumber(&shape1), 1);
MockShape shape2;
shape2.setPosition(QPointF(90, 90));
shape2.setSize(QSizeF(2, 2));
QCOMPARE(pageManager->pageNumber(&shape2), 1);
MockShape shape3;
shape3.setPosition(QPointF(190, 190));
shape3.setSize(QSizeF(9, 9));
QCOMPARE(pageManager->pageNumber(&shape3), 1);
KWPageStyle settingsPage2("page2");
pageLayout = settingsPage2.pageLayout();
pageLayout.width = 600;
pageLayout.height = 600;
settingsPage2.setPageLayout(pageLayout);
page = pageManager->appendPage(settingsPage2);
QCOMPARE(pageManager->pageNumber(&shape1), 1);
QCOMPARE(pageManager->pageNumber(&shape2), 1);
QCOMPARE(pageManager->pageNumber(&shape3), 1);
shape1.setPosition(QPointF(201, 201));
QCOMPARE(pageManager->pageNumber(&shape1), 2);
shape1.setPosition(QPointF(300, 3));
QCOMPARE(pageManager->pageNumber(&shape1), 1); // right of page 1
shape3.setPosition(QPointF(2, 690));
QCOMPARE(pageManager->pageNumber(&shape3), 2);
shape3.setPosition(QPointF(300, 300));
QCOMPARE(pageManager->pageNumber(&shape3), 2);
shape3.setPosition(QPointF(600, 700));
QCOMPARE(pageManager->pageNumber(&shape3), 2);
// QPointF based
QCOMPARE(pageManager->pageNumber(QPointF(201, 201)), 2);
// Y based
QCOMPARE(pageManager->pageNumber(201.0), 2);
QCOMPARE(pageManager->pageNumber(900.0), 2);
}
void TestPageManager::createInsertPages()
{
KWPageManager *pageManager = new KWPageManager();
QCOMPARE(pageManager->pageCount(), 0);
KWPage page1 = pageManager->appendPage();
QCOMPARE(pageManager->pageCount(), 1);
KWPage page3 = pageManager->appendPage();
QCOMPARE(pageManager->pageCount(), 2);
QCOMPARE(page3.pageNumber(), 2);
KWPage page2 = pageManager->insertPage(2);
QCOMPARE(pageManager->pageCount(), 3);
QCOMPARE(page1.pageNumber(), 1);
QCOMPARE(page2.pageNumber(), 2);
QCOMPARE(page3.pageNumber(), 3);
KWPage page4 = pageManager->insertPage(-100); // invalid numbers go at the end
KWPage page5 = pageManager->insertPage(100);
QCOMPARE(pageManager->pageCount(), 5);
QCOMPARE(page1.pageNumber(), 1);
QCOMPARE(page2.pageNumber(), 2);
QCOMPARE(page3.pageNumber(), 3);
QCOMPARE(page4.pageNumber(), 4);
QCOMPARE(page5.pageNumber(), 5);
KWPage page6 = pageManager->insertPage(1);
KWPage page7 = pageManager->insertPage(2);
QCOMPARE(pageManager->pageCount(), 7);
QCOMPARE(page6.pageNumber(), 1);
QCOMPARE(page7.pageNumber(), 2);
QCOMPARE(page1.pageNumber(), 3);
QCOMPARE(page2.pageNumber(), 4);
QCOMPARE(page3.pageNumber(), 5);
QCOMPARE(page4.pageNumber(), 6);
}
void TestPageManager::removePages()
{
KWPageManager *pageManager = new KWPageManager();
KWPage page1 = pageManager->appendPage();
KWPage page2 = pageManager->appendPage();
pageManager->appendPage();
KWPage page4 = pageManager->appendPage();
pageManager->removePage(3);
QCOMPARE(page1.pageNumber(), 1);
QCOMPARE(page2.pageNumber(), 2);
QCOMPARE(page4.pageNumber(), 3);
pageManager->removePage(page2);
QCOMPARE(page1.pageNumber(), 1);
QCOMPARE(page4.pageNumber(), 2);
}
void TestPageManager::pageInfo()
{
KWPageManager *pageManager = new KWPageManager();
KoPageLayout layout = pageManager->defaultPageStyle().pageLayout();
layout.width = 100;
layout.height = 200;
layout.format = KoPageFormat::IsoA4Size;
pageManager->defaultPageStyle().setPageLayout(layout);
QCOMPARE(pageManager->defaultPageStyle().pageLayout().width, 100.0);
QCOMPARE(pageManager->defaultPageStyle().pageLayout().format, KoPageFormat::IsoA4Size);
KWPageStyle pageStylePage2("Page 2");
layout = pageStylePage2.pageLayout();
layout.width = 50;
layout.height = 100;
pageStylePage2.setPageLayout(layout);
pageManager->addPageStyle(pageStylePage2);
QCOMPARE(pageManager->pageStyle("Page 2").pageLayout().width, 50.0);
KWPageStyle pageStylePage3("Page 3");
layout = pageStylePage3.pageLayout();
layout.width = 300;
layout.height = 600;
pageStylePage3.setPageLayout(layout);
pageManager->addPageStyle(pageStylePage3);
QCOMPARE(pageManager->pageStyle("Page 3").pageLayout().width, 300.0);
KWPage page1r = pageManager->appendPage();
KWPage page1l = pageManager->appendPage();
KWPage page2 = pageManager->appendPage(pageStylePage2);
KWPage page3 = pageManager->appendPage(pageStylePage3);
QVERIFY(page3.isValid());
QCOMPARE(pageManager->pageCount(), 4);
QCOMPARE(pageManager->page(1), page1r);
QCOMPARE(pageManager->page(2), page1l);
QCOMPARE(pageManager->page(2).pageStyle(), pageManager->defaultPageStyle());
QCOMPARE(pageManager->page(3).pageStyle(), pageStylePage2);
QCOMPARE(pageManager->page(4).pageStyle(), pageStylePage3);
QCOMPARE(pageManager->topOfPage(4), 500.0);
QCOMPARE(pageManager->bottomOfPage(4), 1100.0);
layout = pageStylePage3.pageLayout();
layout.height = 500;
pageStylePage3.setPageLayout(layout);
QCOMPARE(pageManager->bottomOfPage(4), 1000.0);
layout = pageManager->defaultPageStyle().pageLayout();
layout.topMargin = 5;
layout.leftMargin = 6;
layout.bottomMargin = 7;
layout.rightMargin = 8;
pageManager->defaultPageStyle().setPageLayout(layout);
layout = pageStylePage2.pageLayout();
layout.topMargin = 9;
layout.leftMargin = 10;
layout.bottomMargin = 11;
layout.rightMargin = 12;
pageStylePage2.setPageLayout(layout);
layout = page1l.pageStyle().pageLayout(); //layout is valid for page1l and page1r
layout.rightMargin = 14.0;
page1l.pageStyle().setPageLayout(layout);
QCOMPARE(page1l.rightMargin(), 14.0);
QCOMPARE(page1r.rightMargin(), 14.0);
// Page Edge / Page Margin
layout = pageManager->defaultPageStyle().pageLayout();
layout.pageEdge = 14.0;
pageManager->defaultPageStyle().setPageLayout(layout);
QCOMPARE(page1l.pageSide(), KWPage::Left);
QCOMPARE(page1r.pageSide(), KWPage::Right);
QCOMPARE(page1l.rightMargin(), 14.0);
QCOMPARE(page1l.leftMargin(), 14.0);
layout.bindingSide = 15.0;
pageManager->defaultPageStyle().setPageLayout(layout);
QCOMPARE(page1l.leftMargin(), 14.0);
QCOMPARE(page1l.rightMargin(), 15.0);
QCOMPARE(page1r.leftMargin(), 15.0);
QCOMPARE(page1r.rightMargin(), 14.0);
QCOMPARE(page2.rightMargin(), 12.0); // unchanged due to changes in page1
QCOMPARE(page2.leftMargin(), 10.0);
layout = pageStylePage2.pageLayout();
layout.pageEdge = 16.0;
pageStylePage2.setPageLayout(layout);
QCOMPARE(page2.pageStyle(), pageStylePage2);
QCOMPARE(page2.pageStyle().pageLayout().width, 50.0);
QCOMPARE(page2.pageStyle().pageLayout().height, 100.0);
QCOMPARE(page2.pageSide(), KWPage::Right);
QCOMPARE(page2.rightMargin(), 16.0);
layout.bindingSide = 17.0;
pageStylePage2.setPageLayout(layout);
QCOMPARE(page2.rightMargin(), 16.0);
QCOMPARE(page2.leftMargin(), 17.0);
layout.leftMargin = 18;
layout.rightMargin = 19;
pageStylePage2.setPageLayout(layout);
QCOMPARE(page2.rightMargin(), 16.0);
QCOMPARE(page2.leftMargin(), 17.0);
}
void TestPageManager::testClipToDocument()
{
KWPageManager *pageManager = new KWPageManager();
KoPageLayout lay;
lay.width = 300;
lay.height = 600;
lay.format = KoPageFormat::IsoA4Size;
pageManager->defaultPageStyle().setPageLayout(lay);
KWPageStyle pageStyle1("page1");
lay = pageStyle1.pageLayout();
lay.width = 100;
lay.height = 200;
pageStyle1.setPageLayout(lay);
pageManager->addPageStyle(pageStyle1);
KWPageStyle pageStyle2("page2");
lay = pageStyle2.pageLayout();
lay.width = 50;
lay.height = 100;
pageStyle2.setPageLayout(lay);
pageManager->addPageStyle(pageStyle2);
KWPage page1 = pageManager->appendPage(pageStyle1);
QVERIFY(page1.isValid());
KWPage page2 = pageManager->appendPage(pageStyle2);
QVERIFY(page2.isValid());
pageManager->appendPage(pageManager->defaultPageStyle());
QPointF p(10, 10);
QPointF result = pageManager->clipToDocument(p);
QCOMPARE(result, p);
p.setX(110);
result = pageManager->clipToDocument(p);
QCOMPARE(p.y(), result.y());
QCOMPARE(result.x(), 100.0);
p.setY(210);
result = pageManager->clipToDocument(p);
QCOMPARE(result.x(), 50.0);
QCOMPARE(result.y(), p.y());
p.setY(330);
result = pageManager->clipToDocument(p);
QCOMPARE(p == result, true);
p.setY(910);
p.setX(310);
result = pageManager->clipToDocument(p);
QCOMPARE(result.y(), 900.0);
QCOMPARE(result.x(), 300.0);
}
void TestPageManager::testOrientationHint()
{
KWPageManager pageManager;
KWPage page = pageManager.appendPage();
QCOMPARE(page.orientationHint(), KoPageFormat::Portrait);
page.setOrientationHint(KoPageFormat::Landscape);
QCOMPARE(page.orientationHint(), KoPageFormat::Landscape);
page.setOrientationHint(KoPageFormat::Portrait);
QCOMPARE(page.orientationHint(), KoPageFormat::Portrait);
page.setOrientationHint(KoPageFormat::Landscape);
KWPage page2 = pageManager.appendPage();
QCOMPARE(page2.orientationHint(), KoPageFormat::Landscape); // inherit from last page
page.setOrientationHint(KoPageFormat::Portrait);
QCOMPARE(page2.orientationHint(), KoPageFormat::Landscape); // but separate
QCOMPARE(page.orientationHint(), KoPageFormat::Portrait);
}
void TestPageManager::testDirectionHint()
{
KWPageManager pageManager;
KWPage page = pageManager.appendPage();
QCOMPARE(page.directionHint(), KoText::AutoDirection);
page.setDirectionHint(KoText::LeftRightTopBottom);
QCOMPARE(page.directionHint(), KoText::LeftRightTopBottom);
page.setDirectionHint(KoText::TopBottomRightLeft);
QCOMPARE(page.directionHint(), KoText::TopBottomRightLeft);
KWPage page2 = pageManager.appendPage();
QCOMPARE(page2.directionHint(), KoText::TopBottomRightLeft); // inherit from last page
page.setDirectionHint(KoText::LeftRightTopBottom);
QCOMPARE(page2.directionHint(), KoText::TopBottomRightLeft); // but separate
QCOMPARE(page.directionHint(), KoText::LeftRightTopBottom);
}
void TestPageManager::testPageNumber()
{
KWPageManager pageManager;
KWPage page = pageManager.appendPage();
QCOMPARE(page.pageNumber(), 1);
page.setPageNumber(1);
QCOMPARE(page.pageNumber(), 1);
QCOMPARE(page.pageSide(), KWPage::Right);
page.setPageNumber(5);
QCOMPARE(page.pageNumber(), 5);
QCOMPARE(page.pageSide(), KWPage::Right);
page.setPageNumber(2);
QCOMPARE(page.pageNumber(), 2);
QCOMPARE(page.pageSide(), KWPage::Left);
page.setPageSide(KWPage::PageSpread);
QCOMPARE(page.pageSide(), KWPage::PageSpread);
QVERIFY(pageManager.page(2) == page);
QVERIFY(pageManager.page(3) == page);
KWPage page2 = pageManager.appendPage();
QCOMPARE(page2.pageNumber(), 4);
KWPage page3 = pageManager.appendPage();
QCOMPARE(page3.pageNumber(), 5);
page.setPageNumber(10); // should renumber stuff
QCOMPARE(page.pageNumber(), 10);
QCOMPARE(page.pageSide(), KWPage::PageSpread);
QCOMPARE(page2.pageNumber(), 12);
QCOMPARE(page3.pageNumber(), 13);
page2.setPageNumber(20);
QCOMPARE(page.pageNumber(), 10);
QCOMPARE(page.pageSide(), KWPage::PageSpread);
QCOMPARE(page2.pageNumber(), 20);
QCOMPARE(page3.pageNumber(), 21);
}
void TestPageManager::testPageTraversal()
{
KWPageManager manager;
for (int i = 1; i < 6; ++i)
manager.appendPage();
KWPage page = manager.begin();
QCOMPARE(page.pageNumber(), 1);
page = page.next();
QCOMPARE(page.pageNumber(), 2);
page = page.next();
QCOMPARE(page.pageNumber(), 3);
page = page.next();
QCOMPARE(page.pageNumber(), 4);
page = page.next();
QCOMPARE(page.pageNumber(), 5);
QCOMPARE(page.isValid(), true);
page = page.next();
QCOMPARE(page.isValid(), false);
page = manager.last();
QCOMPARE(page.pageNumber(), 5);
QCOMPARE(page.isValid(), true);
page = page.previous();
QCOMPARE(page.pageNumber(), 4);
page = page.previous();
QCOMPARE(page.pageNumber(), 3);
page = page.previous();
QCOMPARE(page.pageNumber(), 2);
page = page.previous();
QCOMPARE(page.pageNumber(), 1);
QCOMPARE(page.isValid(), true);
page = page.previous();
QCOMPARE(page.isValid(), false);
}
void TestPageManager::testSetPageStyle()
{
KWPageManager manager;
KWPage page = manager.appendPage();
KWPageStyle style("myStyle");
KoPageLayout layout;
layout.height = 100;
style.setPageLayout(layout);
page.setPageStyle(style);
QCOMPARE(page.height(), 100.);
QVERIFY(manager.pageStyle("myStyle") == style);
}
void TestPageManager::testPageCount()
{
KWPageManager manager;
QCOMPARE(manager.pageCount(), 0);
KWPage page = manager.appendPage();
QCOMPARE(manager.pageCount(), 1);
KWPage page2 = manager.appendPage();
QCOMPARE(manager.pageCount(), 2);
KWPage page3 = manager.appendPage();
QCOMPARE(manager.pageCount(), 3);
page2.setPageSide(KWPage::PageSpread);
QCOMPARE(manager.pageCount(), 4);
}
void TestPageManager::testPageSpreadLayout()
{
KWPageManager manager;
KWPage page = manager.appendPage();
KoPageLayout layout = page.pageStyle().pageLayout();
layout.width = 450;
layout.height = 150;
QCOMPARE(page.pageNumber(), 1);
page.setPageSide(KWPage::PageSpread); // makes it page 2 (and 3)
QCOMPARE(page.pageNumber(), 2);
page.pageStyle().setPageLayout(layout);
KWPage page2 = manager.appendPage();
QCOMPARE(page2.pageNumber(), 4);
page2.setDirectionHint(KoText::LeftRightTopBottom);
layout.width = 200;
page2.pageStyle().setPageLayout(layout);
QCOMPARE(page.offsetInDocument(), 0.);
QCOMPARE(page2.offsetInDocument(), 150.);
QCOMPARE(manager.pageNumber(QPointF(10, 200)), 4);
QCOMPARE(manager.pageNumber(QPointF(10, 151)), 4);
KWPage four = page.next();
QCOMPARE(four.pageNumber(), 4);
KWPage invalid = four.next();
QVERIFY(!invalid.isValid());
QVERIFY(invalid.pageNumber() != 4);
KWPage copy = invalid;
QVERIFY(!copy.isValid());
QVERIFY(copy.pageNumber() != 4);
}
void TestPageManager::testInsertPage()
{
KWPageManager *pageManager = new KWPageManager();
QCOMPARE(pageManager->pageCount(), 0);
// inserting determines the position, not always the page number.
KWPage page3 = pageManager->insertPage(10);
QCOMPARE(page3.pageNumber(), 1);
KWPage page1 = pageManager->insertPage(1);
QCOMPARE(page1.pageNumber(), 1);
QCOMPARE(page3.pageNumber(), 2);
QCOMPARE(pageManager->pageCount(), 2);
QCOMPARE(pageManager->page(1), page1);
QCOMPARE(pageManager->page(2), page3);
KWPage page2 = pageManager->insertPage(2);
QCOMPARE(page2.pageNumber(), 2);
QCOMPARE(pageManager->pageCount(), 3);
QCOMPARE(pageManager->page(1), page1);
QCOMPARE(pageManager->page(2), page2);
QCOMPARE(pageManager->page(3), page3);
KWPage page4 = pageManager->insertPage(4);
QCOMPARE(pageManager->pageCount(), 4);
QCOMPARE(pageManager->page(4), page4);
QCOMPARE(page1.pageNumber(), 1);
QCOMPARE(page2.pageNumber(), 2);
QCOMPARE(page3.pageNumber(), 3);
QCOMPARE(page4.pageNumber(), 4);
}
void TestPageManager::testPadding()
{
// padding is the 'dead space' between actual pages. This allows us to print using bleed to PDF.
KWPageManager *pageManager = new KWPageManager();
KoInsets padding(6, 7, 9, 13);
pageManager->setPadding(padding);
KoInsets padding2 = pageManager->padding();
QCOMPARE(padding2.top, padding.top);
QCOMPARE(padding2.bottom, padding.bottom);
QCOMPARE(padding2.left, padding.left);
QCOMPARE(padding2.right, padding.right);
KoPageLayout lay;
QVERIFY(lay.leftMargin >= 0);
QVERIFY(lay.bindingSide == -1);
lay.width = 100;
lay.height = 50;
KWPageStyle style("testStyle");
style.setPageLayout(lay);
KWPage page1 = pageManager->appendPage(style);
QVERIFY(page1.isValid());
QCOMPARE(page1.offsetInDocument(), 0.);
QCOMPARE(page1.rect(), QRectF(0, 0, 100, 50));
KWPage page2 = pageManager->appendPage(style);
QCOMPARE(page2.offsetInDocument(), 50. + 6. + 9.);
QCOMPARE(page2.rect(), QRectF(0, 65, 100, 50));
KWPage page3 = pageManager->appendPage(style);
QCOMPARE(page3.offsetInDocument(), 115 + 6. + 9.);
QCOMPARE(page3.rect(), QRectF(0, 130, 100, 50));
padding = KoInsets(1, 2, 3, 4);
pageManager->setPadding(padding);
QCOMPARE(page3.offsetInDocument(), 2 * (50. + 1. + 3.)); // they moved :)
QCOMPARE(page3.rect(), QRectF(0, 108, 100, 50));
}
void TestPageManager::testPageOffset()
{
KWPageManager *pageManager = new KWPageManager();
for (int i=0; i < 500; ++i) {
KWPage page = pageManager->appendPage();
}
KWPage page = pageManager->page(1);
QVERIFY(page.isValid());
QCOMPARE(page.pageNumber(), 1);
QCOMPARE(page.offsetInDocument(), 0.);
const qreal pageHeight = page.pageStyle().pageLayout().height;
page = pageManager->page(50);
QVERIFY(page.isValid());
QCOMPARE(page.pageNumber(), 50);
QCOMPARE(page.offsetInDocument(), pageHeight * 49);
KoPageLayout layout = page.pageStyle().pageLayout();
layout.height = 400;
page.pageStyle().setPageLayout(layout);
QCOMPARE(page.offsetInDocument(), (qreal) 400 * 49);
}
void TestPageManager::testBackgroundRefCount()
{
KWPageStyle ps1("test");
QVERIFY(ps1.background() == 0);
KoColorBackground *background = new KoColorBackground(QColor(Qt::red));
QVERIFY(background->ref());
QCOMPARE(background->useCount(), 1);
ps1.setBackground(background);
QCOMPARE(background->useCount(), 2);
{
KWPageStyle ps2("test2");
QCOMPARE(background->useCount(), 2);
ps2 = ps1;
QCOMPARE(background->useCount(), 2);
}
QCOMPARE(background->useCount(), 2);
ps1 = ps1;
QCOMPARE(background->useCount(), 2);
ps1.setBackground(0);
QCOMPARE(background->useCount(), 1);
delete background;
}
void TestPageManager::testAppendPageSpread()
{
KWPageManager manager;
KWPageStyle style = manager.addPageStyle("pagestyle1");
KoPageLayout layout = style.pageLayout();
layout.leftMargin = -1;
layout.rightMargin = -1;
layout.pageEdge = 7;
layout.bindingSide = 13;
style.setPageLayout(layout);
KWPage page1 = manager.appendPage(style);
QCOMPARE(page1.pageNumber(), 1);
QCOMPARE(page1.pageSide(), KWPage::Right);
QCOMPARE(page1.width(), style.pageLayout().width);
KWPage test = page1.next();
QVERIFY(!test.isValid());
KWPage page2 = manager.appendPage(style);
QCOMPARE(page1.pageNumber(), 1);
QCOMPARE(page1.pageSide(), KWPage::Right);
QCOMPARE(page1.width(), style.pageLayout().width);
QCOMPARE(page2.pageNumber(), 2);
QCOMPARE(page2.pageSide(), KWPage::PageSpread);
QCOMPARE(page2.width(), style.pageLayout().width * 2);
test = page2.next();
QVERIFY(!test.isValid());
KWPage page3 = manager.insertPage(2, style);
QCOMPARE(page1.pageNumber(), 1);
QCOMPARE(page1.pageSide(), KWPage::Right);
QCOMPARE(page1.width(), style.pageLayout().width);
QCOMPARE(page2.pageNumber(), 4);
QCOMPARE(page2.pageSide(), KWPage::PageSpread);
QCOMPARE(page2.width(), style.pageLayout().width * 2);
QCOMPARE(page3.pageNumber(), 2);
QCOMPARE(page3.pageSide(), KWPage::PageSpread);
QCOMPARE(page3.width(), style.pageLayout().width * 2);
test = page2.next();
QVERIFY(!test.isValid());
KWPage realPage3 = manager.page(3);
QVERIFY(realPage3.isValid());
QCOMPARE(realPage3.pageNumber(), 2); // its still a pagespread
}
void TestPageManager::testRemovePageSpread()
{
KWPageManager manager;
KoPageLayout layout = manager.defaultPageStyle().pageLayout();
layout.leftMargin = -1;
layout.rightMargin = -1;
layout.pageEdge = 7;
layout.bindingSide = 13;
manager.defaultPageStyle().setPageLayout(layout);
KWPage page1 = manager.appendPage();
KWPage pageSpread1 = manager.appendPage();
KWPage pageSpread2 = manager.appendPage();
QCOMPARE(pageSpread1.pageSide(), KWPage::PageSpread);
QCOMPARE(pageSpread2.pageSide(), KWPage::PageSpread);
QCOMPARE(manager.pageCount(), 5);
manager.removePage(pageSpread2); // remove from end
QVERIFY(pageSpread1.isValid());
QCOMPARE(pageSpread1.pageSide(), KWPage::PageSpread);
QCOMPARE(manager.pageCount(), 3);
QVERIFY(!pageSpread2.isValid());
QVERIFY(pageSpread2.pageNumber() < 0);
// re-add so we can remove something in the middle
pageSpread2 = manager.appendPage();
QCOMPARE(pageSpread1.pageSide(), KWPage::PageSpread);
QCOMPARE(pageSpread2.pageSide(), KWPage::PageSpread);
QCOMPARE(manager.pageCount(), 5);
manager.removePage(pageSpread1); // remove pages 2&3
QVERIFY(!pageSpread1.isValid());
QVERIFY(pageSpread1.pageNumber() < 0);
QCOMPARE(pageSpread2.pageSide(), KWPage::PageSpread);
QCOMPARE(manager.pageCount(), 3);
QVERIFY(pageSpread2.isValid());
}
QTEST_KDEMAIN(TestPageManager, GUI)
#include <TestPageManager.moc>
|
TheTypoMaster/calligra-history
|
kword/part/tests/TestPageManager.cpp
|
C++
|
gpl-2.0
| 25,800 |
/*
This file is part of Jedi Knight 2.
Jedi Knight 2 is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
Jedi Knight 2 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Jedi Knight 2. If not, see <http://www.gnu.org/licenses/>.
*/
// Copyright 2001-2013 Raven Software
// cg_draw.c -- draw all of the graphical elements during
// active (after loading) gameplay
#include "../game/g_local.h"
#include "cg_local.h"
#include "cg_media.h"
#include "../game/objectives.h"
void CG_DrawIconBackground(void);
void CG_DrawMissionInformation( void );
void CG_DrawInventorySelect( void );
void CG_DrawForceSelect( void );
qboolean CG_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y);
qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y);
extern float g_crosshairEntDist;
extern int g_crosshairSameEntTime;
extern int g_crosshairEntNum;
extern int g_crosshairEntTime;
qboolean cg_forceCrosshair = qfalse;
// bad cheating
extern int g_rocketLockEntNum;
extern int g_rocketLockTime;
extern int g_rocketSlackTime;
vec3_t vfwd;
vec3_t vright;
vec3_t vup;
vec3_t vfwd_n;
vec3_t vright_n;
vec3_t vup_n;
int infoStringCount;
//===============================================================
/*
================
CG_Draw3DModel
================
*/
static void CG_Draw3DModel( float x, float y, float w, float h, qhandle_t model, qhandle_t skin, vec3_t origin, vec3_t angles ) {
refdef_t refdef;
refEntity_t ent;
memset( &refdef, 0, sizeof( refdef ) );
memset( &ent, 0, sizeof( ent ) );
AnglesToAxis( angles, ent.axis );
VectorCopy( origin, ent.origin );
ent.hModel = model;
ent.customSkin = skin;
ent.renderfx = RF_NOSHADOW; // no stencil shadows
refdef.rdflags = RDF_NOWORLDMODEL;
AxisClear( refdef.viewaxis );
refdef.fov_x = 30;
refdef.fov_y = 30;
refdef.x = x;
refdef.y = y;
refdef.width = w;
refdef.height = h;
refdef.time = cg.time;
cgi_R_ClearScene();
cgi_R_AddRefEntityToScene( &ent );
cgi_R_RenderScene( &refdef );
}
/*
================
CG_DrawHead
Used for both the status bar and the scoreboard
================
*/
void CG_DrawHead( float x, float y, float w, float h, int speaker_i, vec3_t headAngles )
{
qhandle_t hm = 0;
qhandle_t hs = 0;
float len;
vec3_t origin;
vec3_t mins, maxs;
gentity_t *ent;
qboolean extensions = qfalse;
int talking = 0;
//If the talking ent is actually on the level, use his info
if ( cg.gameTextEntNum != -1 && cg.gameTextEntNum < ENTITYNUM_WORLD )
{
ent = &g_entities[cg.gameTextEntNum];
if ( ent && ent->client )
{
hm = ent->client->clientInfo.headModel;
if ( hm )
{
hs = ent->client->clientInfo.headSkin;
extensions = ent->client->clientInfo.extensions;
talking = gi.VoiceVolume[ent->s.number];
}
}
}
if ( !hm )
{
return;
}
if ( !talking )
{//no sound playing, don't display the head any more
cg.gameNextTextTime = cg.time;
return;
}
//add talking anim
if ( extensions && talking > 0 )
{
hs = hs + talking;
}
// offset the origin y and z to center the head
cgi_R_ModelBounds( hm, mins, maxs );
origin[2] = -0.5 * ( mins[2] + maxs[2] );
origin[1] = 0.5 * ( mins[1] + maxs[1] );
// calculate distance so the head nearly fills the box
// assume heads are taller than wide
len = 0.7 * ( maxs[2] - mins[2] );
origin[0] = len / 0.268; // len / tan( fov/2 )
CG_Draw3DModel( x, y, w, h, hm, hs, origin, headAngles );
}
/*
================
CG_DrawTalk
================
*/
static void CG_DrawTalk(centity_t *cent)
{
float size;
vec3_t angles;
// int totalLines,y,i;
vec4_t color;
if ( cg.gameNextTextTime > cg.time)
{
color[0] = colorTable[CT_BLACK][0];
color[1] = colorTable[CT_BLACK][1];
color[2] = colorTable[CT_BLACK][2];
color[3] = 0.350F;
cgi_R_SetColor(color); // Background
CG_DrawPic( 5, 27, 50, 64, cgs.media.ammoslider );
cgi_R_SetColor(colorTable[CT_LTPURPLE1]);
CG_DrawPic( 5, 6, 128, 64, cgs.media.talkingtop );
/*
totalLines = cg.scrollTextLines - cg.gameTextCurrentLine;
y = 6;
CG_DrawPic( 55, y, 16, 16, cgs.media.bracketlu );
CG_DrawPic( 616, y, 16, 16, cgs.media.bracketru );
for (i=1;i<totalLines;++i)
{
y +=16;
CG_DrawPic( 55, y, 16, 16, cgs.media.ammoslider );
CG_DrawPic( 616,y, 16, 16, cgs.media.ammoslider );
}
y +=16;
CG_DrawPic( 55, y, 16, 16, cgs.media.bracketld );
CG_DrawPic( 616,y, 16, 16, cgs.media.bracketrd );
*/
size = ICON_SIZE * 1.5;
VectorClear( angles );
angles[YAW] = 180;
CG_DrawHead( -6, 25, size, size, cg.gameTextSpeaker, angles );
cgi_R_SetColor(colorTable[CT_LTPURPLE1]); // Bottom
CG_DrawPic( 5, 90, 64, 16, cgs.media.talkingbot );
cgi_R_SetColor(NULL);
}
}
int cgi_UI_GetMenuInfo(char *menuFile,int *x,int *y);
/*
================
CG_DrawHUDRightFrame1
================
*/
static void CG_DrawHUDRightFrame1(int x,int y)
{
cgi_R_SetColor( colorTable[CT_WHITE] );
// Inner gray wire frame
CG_DrawPic( x, y, 80, 80, cgs.media.HUDInnerRight ); //
}
/*
================
CG_DrawHUDRightFrame2
================
*/
static void CG_DrawHUDRightFrame2(int x,int y)
{
cgi_R_SetColor( colorTable[CT_WHITE] );
CG_DrawPic( x, y, 80, 80, cgs.media.HUDRightFrame ); // Metal frame
}
/*
================
CG_DrawMessageLit
================
*/
static void CG_DrawMessageLit(centity_t *cent,int x,int y)
{
cgi_R_SetColor(colorTable[CT_WHITE]);
if (cg.missionInfoFlashTime > cg.time )
{
if (!((cg.time / 600 ) & 1))
{
if (!cg.messageLitActive)
{
cgi_S_StartSound( NULL, 0, CHAN_AUTO, cgs.media.messageLitSound );
cg.messageLitActive = qtrue;
}
cgi_R_SetColor(colorTable[CT_HUD_RED]);
CG_DrawPic( x + 33,y + 41, 16,16, cgs.media.messageLitOn);
}
else
{
cg.messageLitActive = qfalse;
}
}
cgi_R_SetColor(colorTable[CT_WHITE]);
CG_DrawPic( x + 33,y + 41, 16,16, cgs.media.messageLitOff);
}
/*
================
CG_DrawForcePower
================
*/
static void CG_DrawForcePower(centity_t *cent,int x,int y)
{
int i;
vec4_t calcColor;
float value,extra=0,inc,percent;
if ( !cent->gent->client->ps.forcePowersKnown )
{
return;
}
inc = (float) cent->gent->client->ps.forcePowerMax / MAX_TICS;
value = cent->gent->client->ps.forcePower;
if ( value > cent->gent->client->ps.forcePowerMax )
{//supercharged with force
extra = value - cent->gent->client->ps.forcePowerMax;
value = cent->gent->client->ps.forcePowerMax;
}
for (i=MAX_TICS-1;i>=0;i--)
{
if ( extra )
{//supercharged
memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t));
percent = 0.75f + (sin( cg.time * 0.005f )*((extra/cent->gent->client->ps.forcePowerMax)*0.25f));
calcColor[0] *= percent;
calcColor[1] *= percent;
calcColor[2] *= percent;
}
else if ( value <= 0 ) // partial tic
{
memcpy(calcColor, colorTable[CT_BLACK], sizeof(vec4_t));
}
else if (value < inc) // partial tic
{
memcpy(calcColor, colorTable[CT_LTGREY], sizeof(vec4_t));
percent = value / inc;
calcColor[0] *= percent;
calcColor[1] *= percent;
calcColor[2] *= percent;
}
else
{
memcpy(calcColor, colorTable[CT_LTGREY], sizeof(vec4_t));
}
cgi_R_SetColor( calcColor);
CG_DrawPic( x + forceTicPos[i].x,
y + forceTicPos[i].y,
forceTicPos[i].width,
forceTicPos[i].height,
forceTicPos[i].tic );
value -= inc;
}
}
/*
================
CG_DrawAmmo
================
*/
static void CG_DrawAmmo(centity_t *cent,int x,int y)
{
playerState_t *ps;
int numColor_i;
int i;
vec4_t calcColor;
float value,inc,percent;
ps = &cg.snap->ps;
if (!cent->currentState.weapon ) // We don't have a weapon right now
{
return;
}
if ( cent->currentState.weapon == WP_STUN_BATON )
{
return;
}
if ( cent->currentState.weapon == WP_SABER && cent->gent )
{
cgi_R_SetColor( colorTable[CT_WHITE] );
if ( !cg.saberAnimLevelPending && cent->gent->client )
{//uninitialized after a loadgame, cheat across and get it
cg.saberAnimLevelPending = cent->gent->client->ps.saberAnimLevel;
}
// don't need to draw ammo, but we will draw the current saber style in this window
switch ( cg.saberAnimLevelPending )
{
case 1://FORCE_LEVEL_1:
case 5://FORCE_LEVEL_5://Tavion
CG_DrawPic( x, y, 80, 40, cgs.media.HUDSaberStyleFast );
break;
case 2://FORCE_LEVEL_2:
CG_DrawPic( x, y, 80, 40, cgs.media.HUDSaberStyleMed );
break;
case 3://FORCE_LEVEL_3:
case 4://FORCE_LEVEL_4://Desann
CG_DrawPic( x, y, 80, 40, cgs.media.HUDSaberStyleStrong );
break;
}
return;
}
else
{
value = ps->ammo[weaponData[cent->currentState.weapon].ammoIndex];
}
if (value < 0) // No ammo
{
return;
}
//
// ammo
//
if (cg.oldammo < value)
{
cg.oldAmmoTime = cg.time + 200;
}
cg.oldammo = value;
// Firing or reloading?
if (( cg.predicted_player_state.weaponstate == WEAPON_FIRING
&& cg.predicted_player_state.weaponTime > 100 ))
{
numColor_i = CT_LTGREY;
}
else
{
if ( value > 0 )
{
if (cg.oldAmmoTime > cg.time)
{
numColor_i = CT_YELLOW;
}
else
{
numColor_i = CT_HUD_ORANGE;
}
}
else
{
numColor_i = CT_RED;
}
}
cgi_R_SetColor( colorTable[numColor_i] );
CG_DrawNumField(x + 29, y + 26, 3, value, 6, 12, NUM_FONT_SMALL,qfalse);
inc = (float) ammoData[weaponData[cent->currentState.weapon].ammoIndex].max / MAX_TICS;
value =ps->ammo[weaponData[cent->currentState.weapon].ammoIndex];
for (i=MAX_TICS-1;i>=0;i--)
{
if (value <= 0) // partial tic
{
memcpy(calcColor, colorTable[CT_BLACK], sizeof(vec4_t));
}
else if (value < inc) // partial tic
{
memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t));
percent = value / inc;
calcColor[0] *= percent;
calcColor[1] *= percent;
calcColor[2] *= percent;
}
else
{
memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t));
}
cgi_R_SetColor( calcColor);
CG_DrawPic( x + ammoTicPos[i].x,
y + ammoTicPos[i].y,
ammoTicPos[i].width,
ammoTicPos[i].height,
ammoTicPos[i].tic );
value -= inc;
}
}
/*
================
CG_DrawHUDLeftFrame1
================
*/
static void CG_DrawHUDLeftFrame1(int x,int y)
{
// Inner gray wire frame
cgi_R_SetColor( colorTable[CT_WHITE] );
CG_DrawPic( x, y, 80, 80, cgs.media.HUDInnerLeft );
}
/*
================
CG_DrawHUDLeftFrame2
================
*/
static void CG_DrawHUDLeftFrame2(int x,int y)
{
// Inner gray wire frame
cgi_R_SetColor( colorTable[CT_WHITE] );
CG_DrawPic( x, y, 80, 80, cgs.media.HUDLeftFrame ); // Metal frame
}
/*
================
CG_DrawHealth
================
*/
static void CG_DrawHealth(int x,int y)
{
vec4_t calcColor;
float healthPercent;
playerState_t *ps;
ps = &cg.snap->ps;
memcpy(calcColor, colorTable[CT_HUD_RED], sizeof(vec4_t));
healthPercent = (float) ps->stats[STAT_HEALTH]/ps->stats[STAT_MAX_HEALTH];
calcColor[0] *= healthPercent;
calcColor[1] *= healthPercent;
calcColor[2] *= healthPercent;
cgi_R_SetColor( calcColor);
CG_DrawPic( x, y, 80, 80, cgs.media.HUDHealth );
// Draw the ticks
if (cg.HUDHealthFlag)
{
cgi_R_SetColor( colorTable[CT_HUD_RED] );
CG_DrawPic( x, y, 80, 80, cgs.media.HUDHealthTic );
}
cgi_R_SetColor( colorTable[CT_HUD_RED] );
CG_DrawNumField (x + 16, y + 40, 3, ps->stats[STAT_HEALTH], 6, 12,
NUM_FONT_SMALL,qtrue);
}
/*
================
CG_DrawArmor
================
*/
static void CG_DrawArmor(int x,int y)
{
vec4_t calcColor;
float armorPercent,hold;
playerState_t *ps;
ps = &cg.snap->ps;
// Outer Armor circular
memcpy(calcColor, colorTable[CT_HUD_GREEN], sizeof(vec4_t));
hold = ps->stats[STAT_ARMOR]-(ps->stats[STAT_MAX_HEALTH]/2);
armorPercent = (float) hold/(ps->stats[STAT_MAX_HEALTH]/2);
if (armorPercent <0)
{
armorPercent = 0;
}
calcColor[0] *= armorPercent;
calcColor[1] *= armorPercent;
calcColor[2] *= armorPercent;
cgi_R_SetColor( calcColor);
CG_DrawPic( x, y, 80, 80, cgs.media.HUDArmor1 );
// Inner Armor circular
if (armorPercent>0)
{
armorPercent = 1;
}
else
{
armorPercent = (float) ps->stats[STAT_ARMOR]/(ps->stats[STAT_MAX_HEALTH]/2);
}
memcpy(calcColor, colorTable[CT_HUD_GREEN], sizeof(vec4_t));
calcColor[0] *= armorPercent;
calcColor[1] *= armorPercent;
calcColor[2] *= armorPercent;
cgi_R_SetColor( calcColor);
CG_DrawPic( x, y, 80, 80, cgs.media.HUDArmor2 ); // Inner Armor circular
/*
if (ps->stats[STAT_ARMOR]) // Is there armor? Draw the HUD Armor TIC
{
// Make tic flash if inner armor is at 50% (25% of full armor)
if (armorPercent<.5) // Do whatever the flash timer says
{
if (cg.HUDTickFlashTime < cg.time) // Flip at the same time
{
cg.HUDTickFlashTime = cg.time + 100;
if (cg.HUDArmorFlag)
{
cg.HUDArmorFlag = qfalse;
}
else
{
cg.HUDArmorFlag = qtrue;
}
}
}
else
{
cg.HUDArmorFlag=qtrue;
}
}
else // No armor? Don't show it.
{
cg.HUDArmorFlag=qfalse;
}
if (cg.HUDArmorFlag)
{
cgi_R_SetColor( colorTable[CT_HUD_GREEN] );
CG_DrawPic( x, y, 80, 80, cgs.media.HUDArmorTic );
}
*/
cgi_R_SetColor( colorTable[CT_HUD_GREEN] );
CG_DrawNumField (x + 16 + 14, y + 40 + 14, 3, ps->stats[STAT_ARMOR], 6, 12,
NUM_FONT_SMALL,qfalse);
}
//-----------------------------------------------------
static qboolean CG_DrawCustomHealthHud( centity_t *cent )
{
float health = 0;
vec4_t color;
if (( cent->currentState.eFlags & EF_LOCKED_TO_WEAPON ))
{
// DRAW emplaced HUD
color[0] = color[1] = color[2] = 0.0f;
color[3] = 0.3f;
cgi_R_SetColor( color );
CG_DrawPic( 14, 480 - 50, 94, 32, cgs.media.whiteShader );
// NOTE: this looks ugly
if ( cent->gent && cent->gent->owner )
{
if (( cent->gent->owner->flags & FL_GODMODE ))
{
// chair is in godmode, so render the health of the player instead
health = cent->gent->health / (float)cent->gent->max_health;
}
else
{
// render the chair health
health = cent->gent->owner->health / (float)cent->gent->owner->max_health;
}
}
color[0] = 1.0f;
color[3] = 0.5f;
cgi_R_SetColor( color );
CG_DrawPic( 18, 480 - 41, 87 * health, 19, cgs.media.whiteShader );
cgi_R_SetColor( colorTable[CT_WHITE] );
CG_DrawPic( 2, 480 - 64, 128, 64, cgs.media.emplacedHealthBarShader);
return qfalse; // drew this hud, so don't draw the player one
}
else if (( cent->currentState.eFlags & EF_IN_ATST ))
{
// we are an ATST...
color[0] = color[1] = color[2] = 0.0f;
color[3] = 0.3f;
cgi_R_SetColor( color );
CG_DrawPic( 14, 480 - 50, 94, 32, cgs.media.whiteShader );
// we just calc the display value from the sum of health and armor
if ( g_entities[cg.snap->ps.viewEntity].activator ) // ensure we can look back to the atst_drivable to get the max health
{
health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR] ) /
(float)(g_entities[cg.snap->ps.viewEntity].max_health + g_entities[cg.snap->ps.viewEntity].activator->max_health );
}
else
{
health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR]) /
(float)(g_entities[cg.snap->ps.viewEntity].max_health + 800 ); // hacked max armor since we don't have an activator...should never happen
}
color[1] = 0.25f; // blue-green
color[2] = 1.0f;
color[3] = 0.5f;
cgi_R_SetColor( color );
CG_DrawPic( 18, 480 - 41, 87 * health, 19, cgs.media.whiteShader );
cgi_R_SetColor( colorTable[CT_WHITE] );
CG_DrawPic( 2, 480 - 64, 128, 64, cgs.media.emplacedHealthBarShader);
return qfalse; // drew this hud, so don't draw the player one
}
else if ( cg.snap->ps.viewEntity && ( g_entities[cg.snap->ps.viewEntity].dflags & DAMAGE_CUSTOM_HUD ))
{
// if we've gotten this far, we are assuming that we are a misc_panel_turret
color[0] = color[1] = color[2] = 0.0f;
color[3] = 0.3f;
cgi_R_SetColor( color );
CG_DrawPic( 14, 480 - 50, 94, 32, cgs.media.whiteShader );
health = g_entities[cg.snap->ps.viewEntity].health / (float)g_entities[cg.snap->ps.viewEntity].max_health;
color[1] = 1.0f;
color[3] = 0.5f;
cgi_R_SetColor( color );
CG_DrawPic( 18, 480 - 41, 87 * health, 19, cgs.media.whiteShader );
cgi_R_SetColor( colorTable[CT_WHITE] );
CG_DrawPic( 2, 480 - 64, 128, 64, cgs.media.ladyLuckHealthShader );
return qfalse; // drew this hud, so don't draw the player one
}
return qtrue;
}
//--------------------------------------
static void CG_DrawBatteryCharge( void )
{
if ( cg.batteryChargeTime > cg.time )
{
vec4_t color;
// FIXME: drawing it here will overwrite zoom masks...find a better place
if ( cg.batteryChargeTime < cg.time + 1000 )
{
// fading out for the last second
color[0] = color[1] = color[2] = 1.0f;
color[3] = (cg.batteryChargeTime - cg.time) / 1000.0f;
}
else
{
// draw full
color[0] = color[1] = color[2] = color[3] = 1.0f;
}
cgi_R_SetColor( color );
// batteries were just charged
CG_DrawPic( 605, 295, 24, 32, cgs.media.batteryChargeShader );
}
}
/*
================
CG_DrawHUD
================
*/
extern void *cgi_UI_GetMenuByName( const char *menu );
extern void cgi_UI_Menu_Paint( void *menu, qboolean force );
static void CG_DrawHUD( centity_t *cent )
{
int x,y,value;
if (cgi_UI_GetMenuInfo("lefthud",&x,&y))
{
// Draw all the HUD elements --eez
cgi_UI_Menu_Paint( cgi_UI_GetMenuByName( "lefthud" ), qtrue );
// Draw armor & health values
if ( cg_draw2D.integer == 2 )
{
CG_DrawSmallStringColor(x+5, y - 60,va("Armor:%d",cg.snap->ps.stats[STAT_ARMOR]), colorTable[CT_HUD_GREEN] );
CG_DrawSmallStringColor(x+5, y - 40,va("Health:%d",cg.snap->ps.stats[STAT_HEALTH]), colorTable[CT_HUD_GREEN] );
}
CG_DrawHUDLeftFrame1(x,y);
CG_DrawArmor(x,y);
CG_DrawHealth(x,y);
CG_DrawHUDLeftFrame2(x,y);
}
if (cgi_UI_GetMenuInfo("righthud",&x,&y))
{
// Draw all the HUD elements --eez
cgi_UI_Menu_Paint( cgi_UI_GetMenuByName( "righthud" ), qtrue );
// Draw armor & health values
if ( cg_draw2D.integer == 2 )
{
if ( cent->currentState.weapon != WP_SABER && cent->currentState.weapon != WP_STUN_BATON && cent->gent )
{
// Bob, just didn't want the ammo text drawing when the saber or the stun baton is the current weapon...change it back if this is wrong.
value = cg.snap->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex];
// value = cent->gent->client->ps.forcePower;
CG_DrawSmallStringColor(x, y - 60,va("Ammo:%d",value), colorTable[CT_HUD_GREEN] );
}
else
{
// value = cg.snap->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex];
}
// CG_DrawSmallStringColor(x, y - 60,va("Ammo:%d",value), colorTable[CT_HUD_GREEN] );
CG_DrawSmallStringColor(x, y - 40,va("Force:%d",cent->gent->client->ps.forcePower), colorTable[CT_HUD_GREEN] );
}
CG_DrawHUDRightFrame1(x,y);
CG_DrawForcePower(cent,x,y);
CG_DrawAmmo(cent,x,y);
CG_DrawMessageLit(cent,x,y);
CG_DrawHUDRightFrame2(x,y);
}
}
/*
================
CG_ClearDataPadCvars
================
*/
void CG_ClearDataPadCvars( void )
{
cg_updatedDataPadForcePower1.integer = 0; //don't wait for the cvar-refresh.
cg_updatedDataPadForcePower2.integer = 0; //don't wait for the cvar-refresh.
cg_updatedDataPadForcePower3.integer = 0; //don't wait for the cvar-refresh.
cgi_Cvar_Set( "cg_updatedDataPadForcePower1", "0" );
cgi_Cvar_Set( "cg_updatedDataPadForcePower2", "0" );
cgi_Cvar_Set( "cg_updatedDataPadForcePower3", "0" );
cg_updatedDataPadObjective.integer = 0; //don't wait for the cvar-refresh.
cgi_Cvar_Set( "cg_updatedDataPadObjective", "0" );
}
/*
================
CG_DrawDataPadHUD
================
*/
void CG_DrawDataPadHUD( centity_t *cent )
{
int x,y;
x = 34;
y = 286;
CG_DrawHUDLeftFrame1(x,y);
CG_DrawArmor(x,y);
CG_DrawHealth(x,y);
x = 526;
if ((missionInfo_Updated) && ((cg_updatedDataPadForcePower1.integer) || (cg_updatedDataPadObjective.integer)))
{
// Stop flashing light
cg.missionInfoFlashTime = 0;
missionInfo_Updated = qfalse;
// Set which force power to show.
// cg_updatedDataPadForcePower is set from Q3_Interface, because force powers would only be given
// from a script.
if (cg_updatedDataPadForcePower1.integer)
{
cg.DataPadforcepowerSelect = cg_updatedDataPadForcePower1.integer - 1; // Not pretty, I know
if (cg.DataPadforcepowerSelect >= MAX_DPSHOWPOWERS)
{ //duh
cg.DataPadforcepowerSelect = MAX_DPSHOWPOWERS-1;
}
else if (cg.DataPadforcepowerSelect<0)
{
cg.DataPadforcepowerSelect=0;
}
}
// CG_ClearDataPadCvars();
}
CG_DrawHUDRightFrame1(x,y);
CG_DrawForcePower(cent,x,y);
CG_DrawAmmo(cent,x,y);
CG_DrawMessageLit(cent,x,y);
cgi_R_SetColor( colorTable[CT_WHITE]);
CG_DrawPic( 0, 0, 640, 480, cgs.media.dataPadFrame );
}
//------------------------
// CG_DrawZoomMask
//------------------------
static void CG_DrawBinocularNumbers( qboolean power )
{
vec4_t color1;
cgi_R_SetColor( colorTable[CT_BLACK]);
CG_DrawPic( 212, 367, 200, 40, cgs.media.whiteShader );
if ( power )
{
// Numbers should be kind of greenish
color1[0] = 0.2f;
color1[1] = 0.4f;
color1[2] = 0.2f;
color1[3] = 0.3f;
cgi_R_SetColor( color1 );
// Draw scrolling numbers, use intervals 10 units apart--sorry, this section of code is just kind of hacked
// up with a bunch of magic numbers.....
int val = ((int)((cg.refdefViewAngles[YAW] + 180) / 10)) * 10;
float off = (cg.refdefViewAngles[YAW] + 180) - val;
for ( int i = -10; i < 30; i += 10 )
{
val -= 10;
if ( val < 0 )
{
val += 360;
}
// we only want to draw the very far left one some of the time, if it's too far to the left it will poke outside the mask.
if (( off > 3.0f && i == -10 ) || i > -10 )
{
// draw the value, but add 200 just to bump the range up...arbitrary, so change it if you like
CG_DrawNumField( 155 + i * 10 + off * 10, 374, 3, val + 200, 24, 14, NUM_FONT_CHUNKY, qtrue );
CG_DrawPic( 245 + (i-1) * 10 + off * 10, 376, 6, 6, cgs.media.whiteShader );
}
}
CG_DrawPic( 212, 367, 200, 28, cgs.media.binocularOverlay );
}
}
/*
================
CG_DrawZoomMask
================
*/
extern float cg_zoomFov; //from cg_view.cpp
static void CG_DrawZoomMask( void )
{
vec4_t color1;
centity_t *cent;
float level;
static qboolean flip = qtrue;
float charge = cg.snap->ps.batteryCharge / (float)MAX_BATTERIES; // convert charge to a percentage
qboolean power = qfalse;
cent = &cg_entities[0];
if ( charge > 0.0f )
{
power = qtrue;
}
//-------------
// Binoculars
//--------------------------------
if ( cg.zoomMode == 1 )
{
CG_RegisterItemVisuals( ITM_BINOCULARS_PICKUP );
// zoom level
level = (float)(80.0f - cg_zoomFov) / 80.0f;
// ...so we'll clamp it
if ( level < 0.0f )
{
level = 0.0f;
}
else if ( level > 1.0f )
{
level = 1.0f;
}
// Using a magic number to convert the zoom level to scale amount
level *= 162.0f;
if ( power )
{
// draw blue tinted distortion mask, trying to make it as small as is necessary to fill in the viewable area
cgi_R_SetColor( colorTable[CT_WHITE] );
CG_DrawPic( 34, 48, 570, 362, cgs.media.binocularStatic );
}
CG_DrawBinocularNumbers( power );
// Black out the area behind the battery display
cgi_R_SetColor( colorTable[CT_DKGREY]);
CG_DrawPic( 50, 389, 161, 16, cgs.media.whiteShader );
if ( power )
{
color1[0] = sin( cg.time * 0.01f ) * 0.5f + 0.5f;
color1[0] = color1[0] * color1[0];
color1[1] = color1[0];
color1[2] = color1[0];
color1[3] = 1.0f;
cgi_R_SetColor( color1 );
CG_DrawPic( 82, 94, 16, 16, cgs.media.binocularCircle );
}
CG_DrawPic( 0, 0, 640, 480, cgs.media.binocularMask );
if ( power )
{
// Flickery color
color1[0] = 0.7f + crandom() * 0.1f;
color1[1] = 0.8f + crandom() * 0.1f;
color1[2] = 0.7f + crandom() * 0.1f;
color1[3] = 1.0f;
cgi_R_SetColor( color1 );
CG_DrawPic( 4, 282 - level, 16, 16, cgs.media.binocularArrow );
}
else
{
// No power color
color1[0] = 0.15f;
color1[1] = 0.15f;
color1[2] = 0.15f;
color1[3] = 1.0f;
cgi_R_SetColor( color1 );
}
// The top triangle bit randomly flips when the power is on
if ( flip && power )
{
CG_DrawPic( 330, 60, -26, -30, cgs.media.binocularTri );
}
else
{
CG_DrawPic( 307, 40, 26, 30, cgs.media.binocularTri );
}
if ( random() > 0.98f && ( cg.time & 1024 ))
{
flip = !flip;
}
if ( power )
{
color1[0] = 1.0f * ( charge < 0.2f ? !!(cg.time & 256) : 1 );
color1[1] = charge * color1[0];
color1[2] = 0.0f;
color1[3] = 0.2f;
cgi_R_SetColor( color1 );
CG_DrawPic( 60, 394.5f, charge * 141, 5, cgs.media.whiteShader );
}
}
//------------
// Disruptor
//--------------------------------
else if ( cg.zoomMode == 2 )
{
level = (float)(80.0f - cg_zoomFov) / 80.0f;
// ...so we'll clamp it
if ( level < 0.0f )
{
level = 0.0f;
}
else if ( level > 1.0f )
{
level = 1.0f;
}
// Using a magic number to convert the zoom level to a rotation amount that correlates more or less with the zoom artwork.
level *= 103.0f;
// Draw target mask
cgi_R_SetColor( colorTable[CT_WHITE] );
CG_DrawPic( 0, 0, 640, 480, cgs.media.disruptorMask );
// apparently 99.0f is the full zoom level
if ( level >= 99 )
{
// Fully zoomed, so make the rotating insert pulse
color1[0] = 1.0f;
color1[1] = 1.0f;
color1[2] = 1.0f;
color1[3] = 0.7f + sin( cg.time * 0.01f ) * 0.3f;
cgi_R_SetColor( color1 );
}
// Draw rotating insert
CG_DrawRotatePic2( 320, 240, 640, 480, -level, cgs.media.disruptorInsert );
float cx, cy;
float max;
max = cg_entities[0].gent->client->ps.ammo[weaponData[WP_DISRUPTOR].ammoIndex] / (float)ammoData[weaponData[WP_DISRUPTOR].ammoIndex].max;
if ( max > 1.0f )
{
max = 1.0f;
}
color1[0] = (1.0f - max) * 2.0f;
color1[1] = max * 1.5f;
color1[2] = 0.0f;
color1[3] = 1.0f;
// If we are low on ammo, make us flash
if ( max < 0.15f && ( cg.time & 512 ))
{
VectorClear( color1 );
}
if ( color1[0] > 1.0f )
{
color1[0] = 1.0f;
}
if ( color1[1] > 1.0f )
{
color1[1] = 1.0f;
}
cgi_R_SetColor( color1 );
max *= 58.0f;
for ( float i = 18.5f; i <= 18.5f + max; i+= 3 ) // going from 15 to 45 degrees, with 5 degree increments
{
cx = 320 + sin( (i+90.0f)/57.296f ) * 190;
cy = 240 + cos( (i+90.0f)/57.296f ) * 190;
CG_DrawRotatePic2( cx, cy, 12, 24, 90 - i, cgs.media.disruptorInsertTick );
}
// FIXME: doesn't know about ammo!! which is bad because it draws charge beyond what ammo you may have..
if ( cg_entities[0].gent->client->ps.weaponstate == WEAPON_CHARGING_ALT )
{
cgi_R_SetColor( colorTable[CT_WHITE] );
// draw the charge level
max = ( cg.time - cg_entities[0].gent->client->ps.weaponChargeTime ) / ( 150.0f * 10.0f ); // bad hardcodedness 150 is disruptor charge unit and 10 is max charge units allowed.
if ( max > 1.0f )
{
max = 1.0f;
}
CG_DrawPic2( 257, 435, 134 * max, 34, 0,0,max,1,cgi_R_RegisterShaderNoMip( "gfx/2d/crop_charge" ));
}
}
//-----------
// Light Amp
//--------------------------------
else if ( cg.zoomMode == 3 )
{
CG_RegisterItemVisuals( ITM_LA_GOGGLES_PICKUP );
if ( power )
{
cgi_R_SetColor( colorTable[CT_WHITE] );
CG_DrawPic( 34, 29, 580, 410, cgs.media.laGogglesStatic );
CG_DrawPic( 570, 140, 12, 160, cgs.media.laGogglesSideBit );
float light = (128-cent->gent->lightLevel) * 0.5f;
if ( light < -81 ) // saber can really jack up local light levels....?magic number??
{
light = -81;
}
float pos1 = 220 + light;
float pos2 = 220 + cos( cg.time * 0.0004f + light * 0.05f ) * 40 + sin( cg.time * 0.0013f + 1 ) * 20 + sin( cg.time * 0.0021f ) * 5;
// Flickery color
color1[0] = 0.7f + crandom() * 0.2f;
color1[1] = 0.8f + crandom() * 0.2f;
color1[2] = 0.7f + crandom() * 0.2f;
color1[3] = 1.0f;
cgi_R_SetColor( color1 );
CG_DrawPic( 565, pos1, 22, 8, cgs.media.laGogglesBracket );
CG_DrawPic( 558, pos2, 14, 5, cgs.media.laGogglesArrow );
}
// Black out the area behind the battery display
cgi_R_SetColor( colorTable[CT_DKGREY]);
CG_DrawPic( 236, 357, 164, 16, cgs.media.whiteShader );
if ( power )
{
// Power bar
color1[0] = 1.0f * ( charge < 0.2f ? !!(cg.time & 256) : 1 );
color1[1] = charge * color1[0];
color1[2] = 0.0f;
color1[3] = 0.4f;
cgi_R_SetColor( color1 );
CG_DrawPic( 247.0f, 362.5f, charge * 143.0f, 6, cgs.media.whiteShader );
// pulsing dot bit
color1[0] = sin( cg.time * 0.01f ) * 0.5f + 0.5f;
color1[0] = color1[0] * color1[0];
color1[1] = color1[0];
color1[2] = color1[0];
color1[3] = 1.0f;
cgi_R_SetColor( color1 );
CG_DrawPic( 65, 94, 16, 16, cgs.media.binocularCircle );
}
CG_DrawPic( 0, 0, 640, 480, cgs.media.laGogglesMask );
}
}
/*
================
CG_DrawStats
================
*/
static void CG_DrawStats( void )
{
centity_t *cent;
if ( cg_drawStatus.integer == 0 ) {
return;
}
cent = &cg_entities[cg.snap->ps.clientNum];
if ((cg.snap->ps.viewEntity>0&&cg.snap->ps.viewEntity<ENTITYNUM_WORLD))
{
// MIGHT try and draw a custom hud if it wants...
CG_DrawCustomHealthHud( cent );
return;
}
cgi_UI_MenuPaintAll();
qboolean drawHud = qtrue;
if ( cent && cent->gent )
{
drawHud = CG_DrawCustomHealthHud( cent );
}
if (( drawHud ) && ( cg_drawHUD.integer ))
{
CG_DrawHUD( cent );
}
CG_DrawTalk(cent);
}
/*
===================
CG_DrawPickupItem
===================
*/
static void CG_DrawPickupItem( void ) {
int value;
float *fadeColor;
value = cg.itemPickup;
if ( value && cg_items[ value ].icon != -1 )
{
fadeColor = CG_FadeColor( cg.itemPickupTime, 3000 );
if ( fadeColor )
{
CG_RegisterItemVisuals( value );
cgi_R_SetColor( fadeColor );
CG_DrawPic( 573, 340, ICON_SIZE, ICON_SIZE, cg_items[ value ].icon );
//CG_DrawBigString( ICON_SIZE + 16, 398, bg_itemlist[ value ].classname, fadeColor[0] );
//CG_DrawProportionalString( ICON_SIZE + 16, 398,
// bg_itemlist[ value ].classname, CG_SMALLFONT,fadeColor );
cgi_R_SetColor( NULL );
}
}
}
void CMD_CGCam_Disable( void );
/*
===================
CG_DrawPickupItem
===================
*/
void CG_DrawCredits(void)
{
if (!cg.creditsStart)
{
//
cg.creditsStart = qtrue;
cgi_SP_Register("CREDITS", qfalse); // do not keep around after level
CG_Credits_Init("CREDITS_RAVEN", &colorTable[CT_ICON_BLUE]);
if ( cg_skippingcin.integer )
{//Were skipping a cinematic and it's over now
gi.cvar_set("timescale", "1");
gi.cvar_set("skippingCinematic", "0");
}
}
if (cg.creditsStart)
{
if ( !CG_Credits_Running() )
{
cgi_Cvar_Set( "cg_endcredits", "0" );
CMD_CGCam_Disable();
cgi_SendConsoleCommand("set nextmap disconnect ; cinematic outcast\n");
}
}
}
/*
================================================================================
CROSSHAIR
================================================================================
*/
/*
=================
CG_DrawCrosshair
=================
*/
static void CG_DrawCrosshair( vec3_t worldPoint )
{
float w, h;
qhandle_t hShader;
qboolean corona = qfalse;
vec4_t ecolor;
float f;
float x, y;
if ( !cg_drawCrosshair.integer )
{
return;
}
if ( cg.zoomMode > 0 && cg.zoomMode < 3 )
{
//not while scoped
return;
}
//set color based on what kind of ent is under crosshair
if ( g_crosshairEntNum >= ENTITYNUM_WORLD )
{
ecolor[0] = ecolor[1] = ecolor[2] = 1.0f;
}
else if ( cg_forceCrosshair && cg_crosshairForceHint.integer )
{
ecolor[0] = 0.2f;
ecolor[1] = 0.5f;
ecolor[2] = 1.0f;
corona = qtrue;
}
else if ( cg_crosshairIdentifyTarget.integer )
{
gentity_t *crossEnt = &g_entities[g_crosshairEntNum];
if ( crossEnt->client )
{
if ( crossEnt->client->ps.powerups[PW_CLOAKED] )
{//cloaked don't show up
ecolor[0] = 1.0f;//R
ecolor[1] = 1.0f;//G
ecolor[2] = 1.0f;//B
}
else if ( crossEnt->client->playerTeam == TEAM_PLAYER )
{
//Allies are green
ecolor[0] = 0.0f;//R
ecolor[1] = 1.0f;//G
ecolor[2] = 0.0f;//B
}
else if ( crossEnt->client->playerTeam == TEAM_NEUTRAL )
{
// NOTE: was yellow, but making it white unless they really decide they want to see colors
ecolor[0] = 1.0f;//R
ecolor[1] = 1.0f;//G
ecolor[2] = 1.0f;//B
}
else
{
//Enemies are red
ecolor[0] = 1.0f;//R
ecolor[1] = 0.1f;//G
ecolor[2] = 0.1f;//B
}
}
else if ( crossEnt->s.weapon == WP_TURRET && (crossEnt->svFlags&SVF_NONNPC_ENEMY) )
{
// a turret
if ( crossEnt->noDamageTeam == TEAM_PLAYER )
{
// mine are green
ecolor[0] = 0.0;//R
ecolor[1] = 1.0;//G
ecolor[2] = 0.0;//B
}
else
{
// hostile ones are red
ecolor[0] = 1.0;//R
ecolor[1] = 0.0;//G
ecolor[2] = 0.0;//B
}
}
else if ( crossEnt->s.weapon == WP_TRIP_MINE )
{
// tripmines are red
ecolor[0] = 1.0;//R
ecolor[1] = 0.0;//G
ecolor[2] = 0.0;//B
}
else
{
VectorCopy( crossEnt->startRGBA, ecolor );
if ( !ecolor[0] && !ecolor[1] && !ecolor[2] )
{
// We don't want a black crosshair, so use white since it will show up better
ecolor[0] = 1.0f;//R
ecolor[1] = 1.0f;//G
ecolor[2] = 1.0f;//B
}
}
}
else // cg_crosshairIdentifyTarget is not on, so make it white
{
ecolor[0] = ecolor[1] = ecolor[2] = 1.0f;
}
ecolor[3] = 1.0;
cgi_R_SetColor( ecolor );
if ( cg.forceCrosshairStartTime )
{
// both of these calcs will fade the corona in one direction
if ( cg.forceCrosshairEndTime )
{
ecolor[3] = (cg.time - cg.forceCrosshairEndTime) / 500.0f;
}
else
{
ecolor[3] = (cg.time - cg.forceCrosshairStartTime) / 300.0f;
}
// clamp
if ( ecolor[3] < 0 )
{
ecolor[3] = 0;
}
else if ( ecolor[3] > 1.0f )
{
ecolor[3] = 1.0f;
}
if ( !cg.forceCrosshairEndTime )
{
// but for the other direction, we'll need to reverse it
ecolor[3] = 1.0f - ecolor[3];
}
}
if ( corona ) // we are pointing at a crosshair item
{
if ( !cg.forceCrosshairStartTime )
{
// must have just happened because we are not fading in yet...start it now
cg.forceCrosshairStartTime = cg.time;
cg.forceCrosshairEndTime = 0;
}
if ( cg.forceCrosshairEndTime )
{
// must have just gone over a force thing again...and we were in the process of fading out. Set fade in level to the level where the fade left off
cg.forceCrosshairStartTime = cg.time - ( 1.0f - ecolor[3] ) * 300.0f;
cg.forceCrosshairEndTime = 0;
}
}
else // not pointing at a crosshair item
{
if ( cg.forceCrosshairStartTime && !cg.forceCrosshairEndTime ) // were currently fading in
{
// must fade back out, but we will have to set the fadeout time to be equal to the current level of faded-in-edness
cg.forceCrosshairEndTime = cg.time - ecolor[3] * 500.0f;
}
if ( cg.forceCrosshairEndTime && cg.time - cg.forceCrosshairEndTime > 500.0f ) // not pointing at anything and fade out is totally done
{
// reset everything
cg.forceCrosshairStartTime = 0;
cg.forceCrosshairEndTime = 0;
}
}
w = h = cg_crosshairSize.value;
// pulse the size of the crosshair when picking up items
f = cg.time - cg.itemPickupBlendTime;
if ( f > 0 && f < ITEM_BLOB_TIME ) {
f /= ITEM_BLOB_TIME;
w *= ( 1 + f );
h *= ( 1 + f );
}
if ( worldPoint && VectorLength( worldPoint ) )
{
if ( !CG_WorldCoordToScreenCoordFloat( worldPoint, &x, &y ) )
{//off screen, don't draw it
return;
}
x -= 320;//????
y -= 240;//????
}
else
{
x = cg_crosshairX.integer;
y = cg_crosshairY.integer;
}
if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD )
{
if ( !Q_stricmp( "misc_panel_turret", g_entities[cg.snap->ps.viewEntity].classname ))
{
// draws a custom crosshair that is twice as large as normal
cgi_R_DrawStretchPic( x + cg.refdef.x + 320 - w,
y + cg.refdef.y + 240 - h,
w * 2, h * 2, 0, 0, 1, 1, cgs.media.turretCrossHairShader );
}
}
else
{
hShader = cgs.media.crosshairShader[ cg_drawCrosshair.integer % NUM_CROSSHAIRS ];
cgi_R_DrawStretchPic( x + cg.refdef.x + 0.5 * (640 - w),
y + cg.refdef.y + 0.5 * (480 - h),
w, h, 0, 0, 1, 1, hShader );
}
if ( cg.forceCrosshairStartTime && cg_crosshairForceHint.integer ) // drawing extra bits
{
ecolor[0] = ecolor[1] = ecolor[2] = (1 - ecolor[3]) * ( sin( cg.time * 0.001f ) * 0.08f + 0.35f ); // don't draw full color
ecolor[3] = 1.0f;
cgi_R_SetColor( ecolor );
w *= 2.0f;
h *= 2.0f;
cgi_R_DrawStretchPic( x + cg.refdef.x + 0.5f * ( 640 - w ), y + cg.refdef.y + 0.5f * ( 480 - h ),
w, h,
0, 0, 1, 1,
cgs.media.forceCoronaShader );
}
}
/*
qboolean CG_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y)
Take any world coord and convert it to a 2D virtual 640x480 screen coord
*/
qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y)
{
vec3_t trans;
float xc, yc;
float px, py;
float z;
px = tan(cg.refdef.fov_x * (M_PI / 360) );
py = tan(cg.refdef.fov_y * (M_PI / 360) );
VectorSubtract(worldCoord, cg.refdef.vieworg, trans);
xc = 640 / 2.0;
yc = 480 / 2.0;
// z = how far is the object in our forward direction
z = DotProduct(trans, cg.refdef.viewaxis[0]);
if (z <= 0.001)
return qfalse;
*x = xc - DotProduct(trans, cg.refdef.viewaxis[1])*xc/(z*px);
*y = yc - DotProduct(trans, cg.refdef.viewaxis[2])*yc/(z*py);
return qtrue;
}
qboolean CG_WorldCoordToScreenCoord( vec3_t worldCoord, int *x, int *y ) {
float xF, yF;
if ( CG_WorldCoordToScreenCoordFloat( worldCoord, &xF, &yF ) ) {
*x = (int)xF;
*y = (int)yF;
return qtrue;
}
return qfalse;
}
// I'm keeping the rocket tracking code separate for now since I may want to do different logic...but it still uses trace info from scanCrosshairEnt
//-----------------------------------------
static void CG_ScanForRocketLock( void )
//-----------------------------------------
{
gentity_t *traceEnt;
static qboolean tempLock = qfalse; // this will break if anything else uses this locking code ( other than the player )
traceEnt = &g_entities[g_crosshairEntNum];
if ( !traceEnt || g_crosshairEntNum <= 0 || g_crosshairEntNum >= ENTITYNUM_WORLD || (!traceEnt->client && traceEnt->s.weapon != WP_TURRET ) || !traceEnt->health
|| ( traceEnt && traceEnt->client && traceEnt->client->ps.powerups[PW_CLOAKED] ))
{
// see how much locking we have
int dif = ( cg.time - g_rocketLockTime ) / ( 1200.0f / 8.0f );
// 8 is full locking....also if we just traced onto the world,
// give them 1/2 second of slop before dropping the lock
if ( dif < 8 && g_rocketSlackTime + 500 < cg.time )
{
// didn't have a full lock and not in grace period, so drop the lock
g_rocketLockTime = 0;
g_rocketSlackTime = 0;
tempLock = qfalse;
}
if ( g_rocketSlackTime + 500 >= cg.time && g_rocketLockEntNum < ENTITYNUM_WORLD )
{
// were locked onto an ent, aren't right now.....but still within the slop grace period
// keep the current lock amount
g_rocketLockTime += cg.frametime;
}
if ( !tempLock && g_rocketLockEntNum < ENTITYNUM_WORLD && dif >= 8 )
{
tempLock = qtrue;
if ( g_rocketLockTime + 1200 < cg.time )
{
g_rocketLockTime = cg.time - 1200; // doh, hacking the time so the targetting still gets drawn full
}
}
// keep locking to this thing for one second after it gets out of view
if ( g_rocketLockTime + 2000.0f < cg.time ) // since time was hacked above, I'm compensating so that 2000ms is really only 1000ms
{
// too bad, you had your chance
g_rocketLockEntNum = ENTITYNUM_NONE;
g_rocketSlackTime = 0;
g_rocketLockTime = 0;
}
}
else
{
tempLock = qfalse;
if ( g_rocketLockEntNum >= ENTITYNUM_WORLD )
{
if ( g_rocketSlackTime + 500 < cg.time )
{
// we just locked onto something, start the lock at the current time
g_rocketLockEntNum = g_crosshairEntNum;
g_rocketLockTime = cg.time;
g_rocketSlackTime = cg.time;
}
}
else
{
if ( g_rocketLockEntNum != g_crosshairEntNum )
{
g_rocketLockTime = cg.time;
}
// may as well always set this when we can potentially lock to something
g_rocketSlackTime = cg.time;
g_rocketLockEntNum = g_crosshairEntNum;
}
}
}
/*
=================
CG_ScanForCrosshairEntity
=================
*/
extern float forcePushPullRadius[];
static void CG_ScanForCrosshairEntity( qboolean scanAll )
{
trace_t trace;
gentity_t *traceEnt = NULL;
vec3_t start, end;
int content;
int ignoreEnt = cg.snap->ps.clientNum;
//FIXME: debounce this to about 10fps?
cg_forceCrosshair = qfalse;
if ( cg_entities[0].gent && cg_entities[0].gent->client ) // <-Mike said it should always do this //if (cg_crosshairForceHint.integer &&
{//try to check for force-affectable stuff first
vec3_t d_f, d_rt, d_up;
VectorCopy( g_entities[0].client->renderInfo.eyePoint, start );
AngleVectors( cg_entities[0].lerpAngles, d_f, d_rt, d_up );
VectorMA( start, 2048, d_f, end );//4028 is max for mind trick
//YES! This is very very bad... but it works! James made me do it. Really, he did. Blame James.
gi.trace( &trace, start, vec3_origin, vec3_origin, end,
ignoreEnt, MASK_OPAQUE|CONTENTS_SHOTCLIP|CONTENTS_BODY|CONTENTS_ITEM, G2_NOCOLLIDE, 10 );// ); took out CONTENTS_SOLID| so you can target people through glass.... took out CONTENTS_CORPSE so disintegrated guys aren't shown, could just remove their body earlier too...
if ( trace.entityNum < ENTITYNUM_WORLD )
{//hit something
traceEnt = &g_entities[trace.entityNum];
if ( traceEnt )
{
// Check for mind trickable-guys
if ( traceEnt->client )
{//is a client
if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_TELEPATHY] && traceEnt->health > 0 && VALIDSTRING(traceEnt->behaviorSet[BSET_MINDTRICK]) )
{//I have the ability to mind-trick and he is alive and he has a mind trick script
//NOTE: no need to check range since it's always 2048
cg_forceCrosshair = qtrue;
}
}
// No? Check for force-push/pullable doors and func_statics
else if ( traceEnt->s.eType == ET_MOVER )
{//hit a mover
if ( !Q_stricmp( "func_door", traceEnt->classname ) )
{//it's a func_door
if ( traceEnt->spawnflags & 2/*MOVER_FORCE_ACTIVATE*/ )
{//it's force-usable
if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] || cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH] )
{//player has push or pull
float maxRange;
if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] > cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH] )
{//use the better range
maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]];
}
else
{//use the better range
maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]];
}
if ( maxRange >= trace.fraction * 2048 )
{//actually close enough to use one of our force powers on it
cg_forceCrosshair = qtrue;
}
}
}
}
else if ( !Q_stricmp( "func_static", traceEnt->classname ) )
{//it's a func_static
if ( (traceEnt->spawnflags & 1/*F_PUSH*/) && (traceEnt->spawnflags & 2/*F_PULL*/) )
{//push or pullable
float maxRange;
if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] > cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH] )
{//use the better range
maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]];
}
else
{//use the better range
maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]];
}
if ( maxRange >= trace.fraction * 2048 )
{//actually close enough to use one of our force powers on it
cg_forceCrosshair = qtrue;
}
}
else if ( (traceEnt->spawnflags & 1/*F_PUSH*/) )
{//pushable only
if ( forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]] >= trace.fraction * 2048 )
{//actually close enough to use force push on it
cg_forceCrosshair = qtrue;
}
}
else if ( (traceEnt->spawnflags & 2/*F_PULL*/) )
{//pullable only
if ( forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]] >= trace.fraction * 2048 )
{//actually close enough to use force pull on it
cg_forceCrosshair = qtrue;
}
}
}
}
}
}
}
if ( !cg_forceCrosshair )
{
if ( cg_dynamicCrosshair.integer )
{//100% accurate
vec3_t d_f, d_rt, d_up;
if ( cg.snap->ps.weapon == WP_NONE ||
cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_STUN_BATON )
{
if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD )
{//in camera ent view
ignoreEnt = cg.snap->ps.viewEntity;
if ( g_entities[cg.snap->ps.viewEntity].client )
{
VectorCopy( g_entities[cg.snap->ps.viewEntity].client->renderInfo.eyePoint, start );
}
else
{
VectorCopy( cg_entities[cg.snap->ps.viewEntity].lerpOrigin, start );
}
AngleVectors( cg_entities[cg.snap->ps.viewEntity].lerpAngles, d_f, d_rt, d_up );
}
else
{
VectorCopy( g_entities[0].client->renderInfo.eyePoint, start );
AngleVectors( cg_entities[0].lerpAngles, d_f, d_rt, d_up );
}
}
else
{
extern void CalcMuzzlePoint( gentity_t *const ent, vec3_t forward, vec3_t right, vec3_t up, vec3_t muzzlePoint, float lead_in );
AngleVectors( cg_entities[0].lerpAngles, d_f, d_rt, d_up );
CalcMuzzlePoint( &g_entities[0], d_f, d_rt, d_up, start , 0 );
}
//VectorCopy( g_entities[0].client->renderInfo.muzzlePoint, start );
//FIXME: increase this? Increase when zoom in?
VectorMA( start, 4096, d_f, end );//was 8192
}
else
{//old way
VectorCopy( cg.refdef.vieworg, start );
//FIXME: increase this? Increase when zoom in?
VectorMA( start, 4096, cg.refdef.viewaxis[0], end );//was 8192
}
//YES! This is very very bad... but it works! James made me do it. Really, he did. Blame James.
gi.trace( &trace, start, vec3_origin, vec3_origin, end,
ignoreEnt, MASK_OPAQUE|CONTENTS_SHOTCLIP|CONTENTS_BODY|CONTENTS_ITEM, G2_NOCOLLIDE, 10 );// ); took out CONTENTS_SOLID| so you can target people through glass.... took out CONTENTS_CORPSE so disintegrated guys aren't shown, could just remove their body earlier too...
/*
CG_Trace( &trace, start, vec3_origin, vec3_origin, end,
cg.snap->ps.clientNum, MASK_PLAYERSOLID|CONTENTS_CORPSE|CONTENTS_ITEM );
*/
//FIXME: pick up corpses
if ( trace.startsolid || trace.allsolid )
{
// trace should not be allowed to pick up anything if it started solid. I tried actually moving the trace start back, which also worked,
// but the dynamic cursor drawing caused it to render around the clip of the gun when I pushed the blaster all the way into a wall.
// It looked quite horrible...but, if this is bad for some reason that I don't know
trace.entityNum = ENTITYNUM_NONE;
}
traceEnt = &g_entities[trace.entityNum];
}
// if the object is "dead", don't show it
/* if ( cg.crosshairClientNum && g_entities[cg.crosshairClientNum].health <= 0 )
{
cg.crosshairClientNum = 0;
return;
}
*/
//draw crosshair at endpoint
CG_DrawCrosshair( trace.endpos );
g_crosshairEntNum = trace.entityNum;
g_crosshairEntDist = 4096*trace.fraction;
if ( !traceEnt )
{
//not looking at anything
g_crosshairSameEntTime = 0;
g_crosshairEntTime = 0;
}
else
{//looking at a valid ent
//store the distance
if ( trace.entityNum != g_crosshairEntNum )
{//new crosshair ent
g_crosshairSameEntTime = 0;
}
else if ( g_crosshairEntDist < 256 )
{//close enough to start counting how long you've been looking
g_crosshairSameEntTime += cg.frametime;
}
//remember the last time you looked at the person
g_crosshairEntTime = cg.time;
}
if ( !traceEnt || (traceEnt->s.eFlags & EF_NO_TED) )
{
if ( traceEnt && scanAll )
{
}
else
{
return;
}
}
// if the player is in fog, don't show it
content = cgi_CM_PointContents( trace.endpos, 0 );
if ( content & CONTENTS_FOG )
{
return;
}
// if the player is cloaked, don't show it
if ( cg_entities[ trace.entityNum ].currentState.powerups & ( 1 << PW_CLOAKED ))
{
return;
}
// update the fade timer
if ( cg.crosshairClientNum != trace.entityNum )
{
infoStringCount = 0;
}
cg.crosshairClientNum = trace.entityNum;
cg.crosshairClientTime = cg.time;
}
/*
=====================
CG_DrawCrosshairNames
=====================
*/
static void CG_DrawCrosshairNames( void )
{
qboolean scanAll = qfalse;
centity_t *player = &cg_entities[0];
if ( cg_dynamicCrosshair.integer )
{
// still need to scan for dynamic crosshair
CG_ScanForCrosshairEntity( scanAll );
return;
}
if ( !player->gent )
{
return;
}
if ( !player->gent->client )
{
return;
}
// scan the known entities to see if the crosshair is sighted on one
// This is currently being called by the rocket tracking code, so we don't necessarily want to do duplicate traces :)
CG_ScanForCrosshairEntity( scanAll );
}
//--------------------------------------------------------------
static void CG_DrawRocketLocking( int lockEntNum, int lockTime )
//--------------------------------------------------------------
{
gentity_t *gent = &g_entities[lockEntNum];
if ( !gent )
{
return;
}
int cx, cy;
vec3_t org;
static int oldDif = 0;
VectorCopy( gent->currentOrigin, org );
org[2] += (gent->mins[2] + gent->maxs[2]) * 0.5f;
if ( CG_WorldCoordToScreenCoord( org, &cx, &cy ))
{
// we care about distance from enemy to eye, so this is good enough
float sz = Distance( gent->currentOrigin, cg.refdef.vieworg ) / 1024.0f;
if ( cg.zoomMode > 0 )
{
if ( cg.overrides.active & CG_OVERRIDE_FOV )
{
sz -= ( cg.overrides.fov - cg_zoomFov ) / 80.0f;
}
else
{
sz -= ( cg_fov.value - cg_zoomFov ) / 80.0f;
}
}
if ( sz > 1.0f )
{
sz = 1.0f;
}
else if ( sz < 0.0f )
{
sz = 0.0f;
}
sz = (1.0f - sz) * (1.0f - sz) * 32 + 6;
vec4_t color={0.0f,0.0f,0.0f,0.0f};
cy += sz * 0.5f;
// well now, take our current lock time and divide that by 8 wedge slices to get the current lock amount
int dif = ( cg.time - g_rocketLockTime ) / ( 1200.0f / 8.0f );
if ( dif < 0 )
{
oldDif = 0;
return;
}
else if ( dif > 8 )
{
dif = 8;
}
// do sounds
if ( oldDif != dif )
{
if ( dif == 8 )
{
cgi_S_StartSound( org, 0, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/rocket/lock.wav" ));
}
else
{
cgi_S_StartSound( org, 0, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/rocket/tick.wav" ));
}
}
oldDif = dif;
for ( int i = 0; i < dif; i++ )
{
color[0] = 1.0f;
color[1] = 0.0f;
color[2] = 0.0f;
color[3] = 0.1f * i + 0.2f;
cgi_R_SetColor( color );
// our slices are offset by about 45 degrees.
CG_DrawRotatePic( cx - sz, cy - sz, sz, sz, i * 45.0f, cgi_R_RegisterShaderNoMip( "gfx/2d/wedge" ));
}
// we are locked and loaded baby
if ( dif == 8 )
{
color[0] = color[1] = color[2] = sin( cg.time * 0.05f ) * 0.5f + 0.5f;
color[3] = 1.0f; // this art is additive, so the alpha value does nothing
cgi_R_SetColor( color );
CG_DrawPic( cx - sz, cy - sz * 2, sz * 2, sz * 2, cgi_R_RegisterShaderNoMip( "gfx/2d/lock" ));
}
}
}
//------------------------------------
static void CG_RunRocketLocking( void )
//------------------------------------
{
centity_t *player = &cg_entities[0];
// Only bother with this when the player is holding down the alt-fire button of the rocket launcher
if ( player->currentState.weapon == WP_ROCKET_LAUNCHER )
{
if ( player->currentState.eFlags & EF_ALT_FIRING )
{
CG_ScanForRocketLock();
if ( g_rocketLockEntNum > 0 && g_rocketLockEntNum < ENTITYNUM_WORLD && g_rocketLockTime > 0 )
{
CG_DrawRocketLocking( g_rocketLockEntNum, g_rocketLockTime );
}
}
else
{
// disengage any residual locking
g_rocketLockEntNum = ENTITYNUM_WORLD;
g_rocketLockTime = 0;
}
}
}
/*
=================
CG_DrawIntermission
=================
*/
static void CG_DrawIntermission( void ) {
CG_DrawScoreboard();
}
/*
==================
CG_DrawSnapshot
==================
*/
static float CG_DrawSnapshot( float y ) {
char *s;
int w;
s = va( "time:%i snap:%i cmd:%i", cg.snap->serverTime,
cg.latestSnapshotNum, cgs.serverCommandSequence );
w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f);
cgi_R_Font_DrawString(635 - w, y+2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f);
return y + BIGCHAR_HEIGHT + 10;
}
/*
==================
CG_DrawFPS
==================
*/
#define FPS_FRAMES 16
static float CG_DrawFPS( float y ) {
char *s;
static unsigned short previousTimes[FPS_FRAMES];
static unsigned short index;
static int previous, lastupdate;
int t, i, fps, total;
unsigned short frameTime;
// don't use serverTime, because that will be drifting to
// correct for internet lag changes, timescales, timedemos, etc
t = cgi_Milliseconds();
frameTime = t - previous;
previous = t;
if (t - lastupdate > 50) //don't sample faster than this
{
lastupdate = t;
previousTimes[index % FPS_FRAMES] = frameTime;
index++;
}
// average multiple frames together to smooth changes out a bit
total = 0;
for ( i = 0 ; i < FPS_FRAMES ; i++ ) {
total += previousTimes[i];
}
if ( !total ) {
total = 1;
}
fps = 1000 * FPS_FRAMES / total;
s = va( "%ifps", fps );
const int w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f);
cgi_R_Font_DrawString(635 - w, y+2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f);
return y + BIGCHAR_HEIGHT + 10;
}
/*
=================
CG_DrawTimer
=================
*/
static float CG_DrawTimer( float y ) {
char *s;
int w;
int mins, seconds, tens;
seconds = cg.time / 1000;
mins = seconds / 60;
seconds -= mins * 60;
tens = seconds / 10;
seconds -= tens * 10;
s = va( "%i:%i%i", mins, tens, seconds );
w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f);
cgi_R_Font_DrawString(635 - w, y+2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f);
return y + BIGCHAR_HEIGHT + 10;
}
/*
=================
CG_DrawAmmoWarning
=================
*/
static void CG_DrawAmmoWarning( void ) {
char text[1024]={0};
int w;
if ( cg_drawAmmoWarning.integer == 0 ) {
return;
}
if ( !cg.lowAmmoWarning ) {
return;
}
if ( weaponData[cg.snap->ps.weapon].ammoIndex == AMMO_NONE )
{//doesn't use ammo, so no warning
return;
}
if ( cg.lowAmmoWarning == 2 ) {
cgi_SP_GetStringTextString( "INGAME_INSUFFICIENTENERGY", text, sizeof(text) );
} else {
return;
//s = "LOW AMMO WARNING";
}
w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f);
cgi_R_Font_DrawString(320 - w/2, 64, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 1.0f);
}
//---------------------------------------
static qboolean CG_RenderingFromMiscCamera()
{
//centity_t *cent;
//cent = &cg_entities[cg.snap->ps.clientNum];
if ( cg.snap->ps.viewEntity > 0 &&
cg.snap->ps.viewEntity < ENTITYNUM_WORLD )// cent && cent->gent && cent->gent->client && cent->gent->client->ps.viewEntity)
{
// Only check viewEntities
if ( !Q_stricmp( "misc_camera", g_entities[cg.snap->ps.viewEntity].classname ))
{
// Only doing a misc_camera, so check health.
if ( g_entities[cg.snap->ps.viewEntity].health > 0 )
{
CG_DrawPic( 0, 0, 640, 480, cgi_R_RegisterShader( "gfx/2d/workingCamera" ));
}
else
{
CG_DrawPic( 0, 0, 640, 480, cgi_R_RegisterShader( "gfx/2d/brokenCamera" ));
}
// don't render other 2d stuff
return qtrue;
}
else if ( !Q_stricmp( "misc_panel_turret", g_entities[cg.snap->ps.viewEntity].classname ))
{
// could do a panel turret screen overlay...this is a cheesy placeholder
CG_DrawPic( 30, 90, 128, 300, cgs.media.turretComputerOverlayShader );
CG_DrawPic( 610, 90, -128, 300, cgs.media.turretComputerOverlayShader );
}
else
{
// FIXME: make sure that this assumption is correct...because I'm assuming that I must be a droid.
CG_DrawPic( 0, 0, 640, 480, cgi_R_RegisterShader( "gfx/2d/droid_view" ));
}
}
// not in misc_camera, render other stuff.
return qfalse;
}
/*
=================
CG_Draw2D
=================
*/
extern void CG_SaberClashFlare( void );
static void CG_Draw2D( void )
{
char text[1024]={0};
int w,y_pos;
centity_t *cent = &cg_entities[cg.snap->ps.clientNum];
// if we are taking a levelshot for the menu, don't draw anything
if ( cg.levelShot )
{
return;
}
if ( cg_draw2D.integer == 0 )
{
return;
}
if ( cg.snap->ps.pm_type == PM_INTERMISSION )
{
CG_DrawIntermission();
return;
}
if (cg_endcredits.integer)
{
if (!CG_Credits_Draw())
{
CG_DrawCredits(); // will probably get rid of this soon
}
}
CGCam_DrawWideScreen();
CG_DrawBatteryCharge();
// Draw this before the text so that any text won't get clipped off
if ( !in_camera )
{
CG_DrawZoomMask();
}
CG_DrawScrollText();
CG_DrawCaptionText();
if ( in_camera )
{//still draw the saber clash flare, but nothing else
CG_SaberClashFlare();
return;
}
if ( CG_RenderingFromMiscCamera())
{
// purposely doing an early out when in a misc_camera, change it if needed.
// allowing center print when in camera mode, probably just an alpha thing - dmv
CG_DrawCenterString();
return;
}
// don't draw any status if dead
if ( cg.snap->ps.stats[STAT_HEALTH] > 0 )
{
if ( !(cent->gent && cent->gent->s.eFlags & (EF_LOCKED_TO_WEAPON |EF_IN_ATST)))
{
CG_DrawIconBackground();
}
CG_DrawWeaponSelect();
if ( cg.zoomMode == 0 )
{
CG_DrawStats();
}
CG_DrawAmmoWarning();
//CROSSHAIR is now done from the crosshair ent trace
//if ( !cg.renderingThirdPerson && !cg_dynamicCrosshair.integer ) // disruptor draws it's own crosshair artwork; binocs draw nothing; third person draws its own crosshair
//{
// CG_DrawCrosshair( NULL );
//}
CG_DrawCrosshairNames();
CG_RunRocketLocking();
CG_DrawInventorySelect();
CG_DrawForceSelect();
CG_DrawPickupItem();
}
CG_SaberClashFlare();
float y = 0;
if (cg_drawSnapshot.integer) {
y=CG_DrawSnapshot(y);
}
if (cg_drawFPS.integer) {
y=CG_DrawFPS(y);
}
if (cg_drawTimer.integer) {
y=CG_DrawTimer(y);
}
// don't draw center string if scoreboard is up
if ( !CG_DrawScoreboard() ) {
CG_DrawCenterString();
}
if (missionInfo_Updated)
{
if (cg.predicted_player_state.pm_type != PM_DEAD)
{
// Was a objective given?
/* if ((cg_updatedDataPadForcePower.integer) || (cg_updatedDataPadObjective.integer))
{
// How long has the game been running? If within 15 seconds of starting, throw up the datapad.
if (cg.dataPadLevelStartTime>cg.time)
{
// Make it pop up
if (!in_camera)
{
cgi_SendConsoleCommand( "datapad" );
cg.dataPadLevelStartTime=cg.time; //and don't do it again this level!
}
}
}
*/
if (!cg.missionInfoFlashTime)
{
cg.missionInfoFlashTime = cg.time + cg_missionInfoFlashTime.integer;
}
if (cg.missionInfoFlashTime < cg.time) // Time's up. They didn't read it.
{
cg.missionInfoFlashTime = 0;
missionInfo_Updated = qfalse;
CG_ClearDataPadCvars();
}
cgi_SP_GetStringTextString( "INGAME_DATAPAD_UPDATED", text, sizeof(text) );
int x_pos = 0;
y_pos = (SCREEN_HEIGHT/2)+80;
if ( cg_missionInfoCentered.integer )
{
w = cgi_R_Font_StrLenPixels(text,cgs.media.qhFontSmall, 1.0f);
x_pos = (SCREEN_WIDTH/2)-(w/2);
}
cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_LTRED1], cgs.media.qhFontMedium, -1, 1.0f);
if (cg_updatedDataPadForcePower1.integer)
{
y_pos += 25;
cgi_SP_GetStringTextString("INGAME_NEW_FORCE_POWER_INFO", text, sizeof(text) );
if ( cg_missionInfoCentered.integer )
{
w = cgi_R_Font_StrLenPixels(text,cgs.media.qhFontSmall, 1.0f);
x_pos = (SCREEN_WIDTH/2)-(w/2);
}
cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_LTRED1], cgs.media.qhFontMedium, -1, 1.0f);
}
if (cg_updatedDataPadObjective.integer)
{
y_pos += 25;
cgi_SP_GetStringTextString( "INGAME_NEW_OBJECTIVE_INFO", text, sizeof(text) );
if ( cg_missionInfoCentered.integer )
{
w = cgi_R_Font_StrLenPixels(text,cgs.media.qhFontSmall, 1.0f);
x_pos = (SCREEN_WIDTH/2)-(w/2);
}
cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_LTRED1], cgs.media.qhFontMedium, -1, 1.0f);
}
// if (cent->gent->client->sess.missionObjectivesShown<3)
// {
// CG_DrawProportionalString((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2) + 20, ingame_text[IGT_MISSIONINFO_UPDATED2],
// CG_PULSE | CG_CENTER| CG_SMALLFONT, colorTable[CT_LTRED1] );
// }
}
}
}
/*
=====================
CG_DrawActive
Perform all drawing needed to completely fill the screen
=====================
*/
void CG_DrawActive( stereoFrame_t stereoView ) {
float separation;
vec3_t baseOrg;
// optionally draw the info screen instead
if ( !cg.snap ) {
CG_DrawInformation();
return;
}
//FIXME: these globals done once at start of frame for various funcs
AngleVectors (cg.refdefViewAngles, vfwd, vright, vup);
VectorCopy( vfwd, vfwd_n );
VectorCopy( vright, vright_n );
VectorCopy( vup, vup_n );
VectorNormalize( vfwd_n );
VectorNormalize( vright_n );
VectorNormalize( vup_n );
switch ( stereoView ) {
case STEREO_CENTER:
separation = 0;
break;
case STEREO_LEFT:
separation = -cg_stereoSeparation.value / 2;
break;
case STEREO_RIGHT:
separation = cg_stereoSeparation.value / 2;
break;
default:
separation = 0;
CG_Error( "CG_DrawActive: Undefined stereoView" );
}
// clear around the rendered view if sized down
CG_TileClear();
// offset vieworg appropriately if we're doing stereo separation
VectorCopy( cg.refdef.vieworg, baseOrg );
if ( separation != 0 ) {
VectorMA( cg.refdef.vieworg, -separation, cg.refdef.viewaxis[1], cg.refdef.vieworg );
}
if ( cg.zoomMode == 3 && cg.snap->ps.batteryCharge ) // doing the Light amp goggles thing
{
cgi_R_LAGoggles();
}
// draw 3D view
cgi_R_RenderScene( &cg.refdef );
// restore original viewpoint if running stereo
if ( separation != 0 ) {
VectorCopy( baseOrg, cg.refdef.vieworg );
}
// draw status bar and other floating elements
CG_Draw2D();
}
|
Razish/OpenJK-Speed
|
codeJK2/cgame/cg_draw.cpp
|
C++
|
gpl-2.0
| 63,182 |
/* $NetBSD: extern.c,v 1.7 2003/08/07 09:36:53 agc Exp $ */
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Ed James.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Copyright (c) 1987 by Ed James, UC Berkeley. All rights reserved.
*
* Copy permission is hereby granted provided that this notice is
* retained on all partial or complete copies.
*
* For more info on this and all of my stuff, mail [email protected].
*/
#include <sys/cdefs.h>
#ifndef lint
#if 0
static char sccsid[] = "@(#)extern.c 8.1 (Berkeley) 5/31/93";
#else
__RCSID("$NetBSD: extern.c,v 1.7 2003/08/07 09:36:53 agc Exp $");
#endif
#endif /* not lint */
#include "include.h"
char GAMES[] = "Game_List";
int clck, safe_planes, start_time, test_mode;
const char *file;
FILE *filein, *fileout;
C_SCREEN screen, *sp = &screen;
LIST air, ground;
struct termios tty_start, tty_new;
DISPLACEMENT displacement[MAXDIR] = {
{ 0, -1 },
{ 1, -1 },
{ 1, 0 },
{ 1, 1 },
{ 0, 1 },
{ -1, 1 },
{ -1, 0 },
{ -1, -1 }
};
|
ipwndev/DSLinux-Mirror
|
user/games/bsdgames/atc/extern.c
|
C
|
gpl-2.0
| 2,601 |
/*
Copyright (C) 1998-99 Paul Barton-Davis
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id$
*/
#ifndef __qm_pool_h__
#define __qm_pool_h__
#include <vector>
#include <string>
#include <pthread.h>
#include <pbd/ringbuffer.h>
class Pool
{
public:
Pool (std::string name, unsigned long item_size, unsigned long nitems);
virtual ~Pool ();
virtual void *alloc ();
virtual void release (void *);
std::string name() const { return _name; }
private:
RingBuffer<void*>* free_list;
std::string _name;
void *block;
};
class SingleAllocMultiReleasePool : public Pool
{
public:
SingleAllocMultiReleasePool (std::string name, unsigned long item_size, unsigned long nitems);
~SingleAllocMultiReleasePool ();
virtual void *alloc ();
virtual void release (void *);
private:
pthread_mutex_t lock;
};
class MultiAllocSingleReleasePool : public Pool
{
public:
MultiAllocSingleReleasePool (std::string name, unsigned long item_size, unsigned long nitems);
~MultiAllocSingleReleasePool ();
virtual void *alloc ();
virtual void release (void *);
private:
pthread_mutex_t lock;
};
#endif // __qm_pool_h__
|
essej/sooperlooper
|
libs/pbd/pbd/pool.h
|
C
|
gpl-2.0
| 1,799 |
\artigotrue
\chapter{TÍTULO DO PRIMEIRO ARTIGO}
\chapternote{Este capítulo é baseado em um artigo que eu ainda não publiquei.}
\shorttitle{Primeiro artigo}
\label{chap:chapter01}
\begin{chapterabstract}{brazilian}{Palavra-chave 1. Palavra-chave 2. Palavra-chave 3}
Este é o resumo do primeiro artigo da tese. Note que as palavras-chave devem ser separadas com um \emph{ponto}
ao invés de \emph{vírgula}.
\end{chapterabstract}
\begin{chapterabstract}{english}{Keyword 1. Keyword 2. Keyword 3}
This is the abstract of the first article of the thesis. Note that the keywords must be separated with a
\emph{dot} instead of a \emph{comma}.
\end{chapterabstract}
\formatchapter
\section{INTRODUÇÃO}
\blindtext[2]
\subsection{Hipótese e Objetivos}
\blindtext[2]
\section{MATERIAL E MÉTODOS}
Este é um texto bem formatado, escrito em Seropédica, RJ. \blindtext[1]
Este é o código fote de uma função construída no ambiente R:
\begin{verbatim}
> soma <- function (a, b) {a + b}
> soma(2, 2)
[1] 4
\end{verbatim}
Está é uma matriz bem formatada:
\begin{equation}
A_{m,n} =
\begin{pmatrix}
a_{1,1} & a_{1,2} & \cdots & a_{1,n} \\
a_{2,1} & a_{2,2} & \cdots & a_{2,n} \\
\vdots & \vdots & \ddots & \vdots \\
a_{m,1} & a_{m,2} & \cdots & a_{m,n}
\end{pmatrix}
\end{equation}
\begin{subequations}\label{eq:maxwell}
E estas são as equações de Maxwell:
\begin{align}
B'&=-\nabla \times E,\\
E'&=\nabla \times B - 4\pi j,
\end{align}
\end{subequations}
\section{RESULTADOS}
Aqui está mais um texto bem formatado. \blindtext[1]
Que tal fazer um link para a figura \autoref{fig:ocio}? E também citar o \citeonline{Feyerabend1977} com um
link para a localização da referência bibliográfica?
\begin{figure}[!ht]
\label{fig:ocio}
\centering
\includegraphics[width=16cm]{figura02}
\caption[O ócio criativo.]{O ócio criativo. Fonte:
\url{http://r1.ufrrj.br/graduacao/img/acesso-2012/o-ocio-criativo.jpg}}
\end{figure}
\subsection{Outros Resultados}
\blindtext[1]
\subsubsection{Ainda outros resultados}
\blindtext[1]
\section{DISCUSSÃO}
Aqui está o último texto muito bem formatado. \blindtext[2]
Que tal fazer um link para a equação \autoref{eq:maxwell}?
\section{CONCLUSÕES}
\begin{itemize}
\item Está é uma conclusão importante.
\item Está é outra conclusão importante.
\item Está é uma conclusão menos importante.
\end{itemize}
|
samuel-rosa/UFRuralRJ
|
capitulos-b/chapter01.tex
|
TeX
|
gpl-2.0
| 2,421 |
%This work is licensed under the
%Creative Commons Attribution-Share Alike 3.0 United States License.
%To view a copy of this license, visit
%http://creativecommons.org/licenses/by-sa/3.0/us/ or send a letter to
%Creative Commons,
%171 Second Street, Suite 300,
%San Francisco, California, 94105, USA.
\chapter{Monkey's Audio}
Monkey's Audio is a lossless RIFF WAVE compressor.
Unlike FLAC, which is a PCM compressor, Monkey's Audio also stores
IFF chunks and reproduces the original WAVE file in its entirety rather
than storing only the data it contains.
All of its fields are little-endian.
\section{File Stream}
\begin{figure}[h]
\includegraphics{figures/ape/stream.pdf}
\end{figure}
\clearpage
\section{Descriptor}
\begin{figure}[h]
\includegraphics{figures/ape/descriptor.pdf}
\end{figure}
\par
\noindent
\VAR{ID} is always \texttt{"MAC "} (note the trailing space).
\VAR{version} is the encoding software's version times 1000
(e.g. Monkey's Audio 3.99 = 3990).
The 6 length fields are the lengths of the entire
\VAR{Descriptor}, \VAR{Header}, \VAR{Seektable},
\VAR{Wave Header}, \VAR{Frames} and \VAR{Wave Footer} blocks,
in bytes.
%%FIXME - figure out what MD5 sum is the hash of
\subsection{Descriptor Example}
\begin{figure}[h]
\includegraphics{figures/ape/descriptor-example.pdf}
\end{figure}
\begin{table}[h]
\begin{tabular}{rl}
ID : & \texttt{"MAC "} \\
version : & \texttt{3990} (3.990) \\
descriptor length : & \texttt{52} (bytes)\\
header length : & \texttt{24} (bytes)\\
seektable length : & \texttt{4} (bytes) \\
wave header length : & \texttt{44} (bytes) \\
frames length : & \texttt{44} (bytes) \\
wave footer length : & \texttt{0} \\
MD5 sum : & \texttt{"41486031F2B6EBAA6F513E46C46396E6"}
\end{tabular}
\end{table}
\clearpage
\section{Header}
\begin{figure}[h]
\includegraphics{figures/ape/header.pdf}
\end{figure}
\par
\noindent
\VAR{compression level} indicates the level the file was compressed at.
%%FIXME - figure out format flags
\VAR{blocks per frame} is the number of PCM frames per APE frame,
not including the final frame.
\VAR{final frame blocks} is the number of PCM frames
in the final APE frame.
\VAR{total frames} is the total number of APE frames.
\VAR{bits per sample}, \VAR{channels} and \VAR{sample rate}
are stream parameters.
\subsection{Header Example}
\begin{figure}[h]
\includegraphics{figures/ape/header-example.pdf}
\end{figure}
\begin{table}[h]
\begin{tabular}{rl}
compression level : & \texttt{2000} \\
format flags : & \texttt{0} \\
blocks per frame : & \texttt{73728} \\
final frame blocks : & \texttt{25} \\
total frames : & \texttt{1} \\
bits per sample : & \texttt{16} \\
channels : & \texttt{1} \\
sample rate : & \texttt{44100} \\
\end{tabular}
\end{table}
%% {\relsize{-2}
%% \begin{equation}
%% \text{Length in Seconds} = \frac{((\text{Total Frames} - 1) \times \text{Blocks Per Frame}) + \text{Final Frame Blocks}}{\text{Sample Rate}}
%% \end{equation}
%% }
|
Excito/audiotools
|
docs/reference/ape.tex
|
TeX
|
gpl-2.0
| 2,925 |
module Animate
{
/**
* A simple array resource for referencing groups, or arrays, of other objects. Similar to arrays in Javascript.
*/
export class GroupArray extends ProjectResource<Engine.IGroup>
{
/**
* @param {IGroup} entry [Optional] The database entry of the resource
*/
constructor(entry?: Engine.IGroup)
{
// Call super-class constructor
super(entry);
}
/**
* Adds a new reference to the group
* @param {number} shallowId
*/
addReference(shallowId: number)
{
this.entry.items.push(shallowId);
this.saved = false;
}
/**
* Removes a reference from the group
* @param {number} shallowId
*/
removeReference(shallowId: number)
{
if (this.entry.items.indexOf(shallowId) != -1)
this.entry.items.splice(this.entry.items.indexOf(shallowId), 1);
this.saved = false;
}
/**
* Disposes and cleans up the data of this asset
*/
dispose()
{
//Call super
super.dispose();
}
}
}
|
PixelSwarm/hatchery-editor
|
client/lib/core/project-resources/group-array.ts
|
TypeScript
|
gpl-2.0
| 1,160 |
//+----------------------------------------------------------------------------+
//| Description: Magic Set Editor - Program to make Magic (tm) cards |
//| Copyright: (C) 2001 - 2012 Twan van Laarhoven and Sean Hunt |
//| License: GNU General Public License 2 or later (see file COPYING) |
//+----------------------------------------------------------------------------+
#ifndef HEADER_GUI_CARD_SELECT_WINDOW
#define HEADER_GUI_CARD_SELECT_WINDOW
// ----------------------------------------------------------------------------- : Includes
#include <util/prec.hpp>
DECLARE_POINTER_TYPE(Set);
DECLARE_POINTER_TYPE(Card);
DECLARE_POINTER_TYPE(ExportCardSelectionChoice);
class SelectCardList;
// ----------------------------------------------------------------------------- : ExportWindowBase
enum ExportCardSelectionType
{ EXPORT_SEL_ENTIRE_SET
, EXPORT_SEL_SUBSET
, EXPORT_SEL_CUSTOM
};
class ExportCardSelectionChoice : public IntrusivePtrBase<ExportCardSelectionChoice> {
public:
ExportCardSelectionChoice();
ExportCardSelectionChoice(const Set& set);
ExportCardSelectionChoice(const String& label, const vector<CardP>& cards);
ExportCardSelectionChoice(const String& label, const vector<CardP>* cards);
const String label;
const ExportCardSelectionType type;
const vector<CardP>* the_cards; ///< The cards
vector<CardP> own_cards; ///< Maybe we own the cards, in that case the_cards = &own_cards
};
typedef vector<ExportCardSelectionChoiceP> ExportCardSelectionChoices;
/// Base class for export windows, deals with card selection
class ExportWindowBase : public wxDialog {
public:
ExportWindowBase(Window* parent, const String& window_title,
const SetP& set, const ExportCardSelectionChoices& cards_choices, long style = wxDEFAULT_DIALOG_STYLE);
/// Create the controls, return a sizer containing them
wxSizer* Create();
/// Get the selected cards
const vector<CardP>& getSelection() const { return *cards; }
protected:
DECLARE_EVENT_TABLE();
SetP set; ///< Set to export
const vector<CardP>* cards; ///< Cards to export
private:
ExportCardSelectionChoices cards_choices; ///< Ways to select cards
size_t active_choice;
wxStaticText* card_count;
wxButton* select_cards;
void onChangeSelectionChoice(wxCommandEvent&);
void onSelectCards(wxCommandEvent&);
void update();
};
// ----------------------------------------------------------------------------- : CardSelectWindow
/// A window for selecting a subset of the cards from a set.
/** this is used when printing or exporting
*/
class CardSelectWindow : public wxDialog {
public:
CardSelectWindow(Window* parent, const SetP& set, const String& label, const String& title, bool sizer=true);
/// Is the given card selected?
bool isSelected(const CardP& card) const;
/// Get a list of all selected cards
void getSelection(vector<CardP>& out) const;
/// Change which cards are selected
void setSelection(const vector<CardP>& cards);
protected:
DECLARE_EVENT_TABLE();
SelectCardList* list;
SetP set;
wxButton* sel_all, *sel_none;
void onSelectAll (wxCommandEvent&);
void onSelectNone(wxCommandEvent&);
};
// ----------------------------------------------------------------------------- : EOF
#endif
|
ninzhan/MSE
|
src/gui/card_select_window.hpp
|
C++
|
gpl-2.0
| 3,366 |
/*****************************************************************
Copyright (c) 2000-2001 Matthias Elter <[email protected]>
Copyright (c) 2001 Richard Moore <[email protected]>
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 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.
******************************************************************/
#ifndef __taskmanager_h__
#define __taskmanager_h__
#include <sys/types.h>
#include <qpoint.h>
#include <qobject.h>
#include <qvaluelist.h>
#include <qptrlist.h>
#include <qpixmap.h>
#include <dcopobject.h>
#include <kwin.h>
#include <kstartupinfo.h>
#include "karambaapp.h"
class TaskManager;
/**
* A dynamic interface to a task (main window).
*
* @see TaskManager
* @see KWinModule
*/
class Task: public QObject
{
Q_OBJECT
Q_PROPERTY( QString name READ name )
Q_PROPERTY( QString visibleName READ visibleName )
Q_PROPERTY( QString visibleNameWithState READ visibleNameWithState )
Q_PROPERTY( QString iconName READ iconName )
Q_PROPERTY( QString visibleIconName READ visibleIconName )
Q_PROPERTY( QPixmap pixmap READ pixmap )
Q_PROPERTY( bool maximized READ isMaximized )
Q_PROPERTY( bool iconified READ isIconified )
Q_PROPERTY( bool shaded READ isShaded WRITE setShaded )
Q_PROPERTY( bool active READ isActive )
Q_PROPERTY( bool onCurrentDesktop READ isOnCurrentDesktop )
Q_PROPERTY( bool onAllDesktops READ isOnAllDesktops )
Q_PROPERTY( bool alwaysOnTop READ isAlwaysOnTop WRITE setAlwaysOnTop )
Q_PROPERTY( bool modified READ isModified )
Q_PROPERTY( int desktop READ desktop )
Q_PROPERTY( double thumbnailSize READ thumbnailSize WRITE setThumbnailSize )
Q_PROPERTY( bool hasThumbnail READ hasThumbnail )
Q_PROPERTY( QPixmap thumbnail READ thumbnail )
public:
Task( WId win, TaskManager * parent, const char *name = 0 );
virtual ~Task();
TaskManager* taskManager() const { return (TaskManager*) parent(); }
WId window() const { return _win; }
#ifdef KDE_3_2
QString name() const { return _info.name(); }
QString visibleName() const { return _info.visibleName(); }
/**
* Returns the desktop on which this task's window resides.
*/
int desktop() const { return _info.desktop(); }
#else
QString name() const { return _info.name; }
QString visibleName() const { return _info.visibleName; }
/**
* Returns the desktop on which this task's window resides.
*/
int desktop() const { return _info.desktop; }
#endif
QString visibleNameWithState() const { return _info.visibleNameWithState(); }
QString iconName() const;
QString visibleIconName() const;
QString className();
QString classClass();
/**
* A list of the window ids of all transient windows (dialogs) associated
* with this task.
*/
QValueList<WId> transients() const { return _transients; }
/**
* Returns a 16x16 (KIcon::Small) icon for the task. This method will
* only fall back to a static icon if there is no icon of any size in
* the WM hints.
*/
QPixmap pixmap() const { return _pixmap; }
/**
* Returns the best icon for any of the KIcon::StdSizes. If there is no
* icon of the specified size specified in the WM hints, it will try to
* get one using KIconLoader.
*
* <pre>
* bool gotStaticIcon;
* QPixmap icon = myTask->icon( KIcon::SizeMedium, gotStaticIcon );
* </pre>
*
* @param size Any of the constants in KIcon::StdSizes.
* @param isStaticIcon Set to true if KIconLoader was used, false otherwise.
* @see KIcon
*/
QPixmap bestIcon( int size, bool &isStaticIcon );
/**
* Tries to find an icon for the task with the specified size. If there
* is no icon that matches then it will either resize the closest available
* icon or return a null pixmap depending on the value of allowResize.
*
* Note that the last icon is cached, so a sequence of calls with the same
* parameters will only query the NET properties if the icon has changed or
* none was found.
*/
QPixmap icon( int width, int height, bool allowResize = false );
/**
* Returns true iff the windows with the specified ids should be grouped
* together in the task list.
*/
static bool idMatch(const QString &, const QString &);
// state
/**
* Returns true if the task's window is maximized.
*/
bool isMaximized() const;
/**
* Returns true if the task's window is iconified.
*/
bool isIconified() const;
/**
* Returns true if the task's window is shaded.
*/
bool isShaded() const;
/**
* Returns true if the task's window is the active window.
*/
bool isActive() const;
/**
* Returns true if the task's window is the topmost non-iconified,
* non-always-on-top window.
*/
bool isOnTop() const;
/**
* Returns true if the task's window is on the current virtual desktop.
*/
bool isOnCurrentDesktop() const;
/**
* Returns true if the task's window is on all virtual desktops.
*/
bool isOnAllDesktops() const;
/**
* Returns true if the task's window will remain at the top of the
* stacking order.
*/
bool isAlwaysOnTop() const;
/**
* Returns true if the document the task is editing has been modified.
* This is currently handled heuristically by looking for the string
* '[i18n_modified]' in the window title where i18n_modified is the
* word 'modified' in the current language.
*/
bool isModified() const ;
// internal
//* @internal
void refresh(bool icon = false);
//* @internal
void addTransient( WId w ) { _transients.append( w ); }
//* @internal
void removeTransient( WId w ) { _transients.remove( w ); }
//* @internal
bool hasTransient( WId w ) const { return _transients.contains( w ); }
//* @internal
void setActive(bool a);
// For thumbnails
/**
* Returns the current thumbnail size.
*/
double thumbnailSize() const { return _thumbSize; }
/**
* Sets the size for the window thumbnail. For example a size of
* 0.2 indicates the thumbnail will be 20% of the original window
* size.
*/
void setThumbnailSize( double size ) { _thumbSize = size; }
/**
* Returns true if this task has a thumbnail. Note that this method
* can only ever return true after a call to updateThumbnail().
*/
bool hasThumbnail() const { return !_thumb.isNull(); }
/**
* Returns the thumbnail for this task (or a null image if there is
* none).
*/
const QPixmap &thumbnail() const { return _thumb; }
public slots:
// actions
/**
* Maximise the main window of this task.
*/
void maximize();
/**
* Restore the main window of the task (if it was iconified).
*/
void restore();
/**
* Iconify the task.
*/
void iconify();
/**
* Activate the task's window.
*/
void close();
/**
* Raise the task's window.
*/
void raise();
/**
* Lower the task's window.
*/
void lower();
/**
* Activate the task's window.
*/
void activate();
/**
* Perform the action that is most appropriate for this task. If it
* is not active, activate it. Else if it is not the top window, raise
* it. Otherwise, iconify it.
*/
void activateRaiseOrIconify();
/**
* If true, the task's window will remain at the top of the stacking order.
*/
void setAlwaysOnTop(bool);
void toggleAlwaysOnTop();
/**
* If true then the task's window will be shaded. Most window managers
* represent this state by displaying on the window's title bar.
*/
void setShaded(bool);
void toggleShaded();
/**
* Moves the task's window to the specified virtual desktop.
*/
void toDesktop(int);
/**
* Moves the task's window to the current virtual desktop.
*/
void toCurrentDesktop();
/**
* This method informs the window manager of the location at which this
* task will be displayed when iconised. It is used, for example by the
* KWin inconify animation.
*/
void publishIconGeometry(QRect);
/**
* Tells the task to generate a new thumbnail. When the thumbnail is
* ready the thumbnailChanged() signal will be emitted.
*/
void updateThumbnail();
signals:
/**
* Indicates that this task has changed in some way.
*/
void changed();
/**
* Indicates that the icon for this task has changed.
*/
void iconChanged();
/**
* Indicates that this task is now the active task.
*/
void activated();
/**
* Indicates that this task is no longer the active task.
*/
void deactivated();
/**
* Indicates that the thumbnail for this task has changed.
*/
void thumbnailChanged();
protected slots:
//* @internal
void generateThumbnail();
private:
bool _active;
WId _win;
QPixmap _pixmap;
#ifdef KDE_3_2
KWin::WindowInfo _info;
#else
KWin::Info _info;
#endif
QValueList<WId> _transients;
int _lastWidth;
int _lastHeight;
bool _lastResize;
QPixmap _lastIcon;
double _thumbSize;
QPixmap _thumb;
QPixmap _grab;
class TaskPrivate *d;
};
/**
* Represents a task which is in the process of starting.
*
* @see TaskManager
*/
class Startup: public QObject
{
Q_OBJECT
Q_PROPERTY( QString text READ text )
Q_PROPERTY( QString bin READ bin )
Q_PROPERTY( QString icon READ icon )
public:
Startup( const KStartupInfoId& id, const KStartupInfoData& data, QObject * parent,
const char *name = 0);
virtual ~Startup();
/**
* The name of the starting task (if known).
*/
QString text() const { return _data.findName(); }
/**
* The name of the executable of the starting task.
*/
QString bin() const { return _data.bin(); }
/**
* The name of the icon to be used for the starting task.
*/
QString icon() const { return _data.findIcon(); }
void update( const KStartupInfoData& data );
const KStartupInfoId& id() const { return _id; }
signals:
/**
* Indicates that this startup has changed in some way.
*/
void changed();
private:
KStartupInfoId _id;
KStartupInfoData _data;
class StartupPrivate *d;
};
typedef QPtrList<Task> TaskList;
typedef QPtrList<Startup> StartupList;
/**
* A generic API for task managers. This class provides an easy way to
* build NET compliant task managers. It provides support for startup
* notification, virtual desktops and the full range of WM properties.
*
* @see Task
* @see Startup
* @see KWinModule
* @version $Id: taskmanager.h,v 1.2 2004/11/17 10:16:47 kodaaja Exp $
*/
class TaskManager : public QObject
{
Q_OBJECT
Q_PROPERTY( int currentDesktop READ currentDesktop )
Q_PROPERTY( int numberOfDesktops READ numberOfDesktops )
public:
TaskManager( QObject *parent = 0, const char *name = 0 );
virtual ~TaskManager();
/**
* Returns a list of all current tasks. Return type changed to
* QPtrList in KDE 3.
*/
TaskList tasks() const { return _tasks; }
/**
* Returns a list of all current startups. Return type changed to
* QPtrList in KDE 3.
*/
StartupList startups() const { return _startups; }
/**
* Returns the name of the nth desktop.
*/
QString desktopName(int n) const;
/**
* Returns the number of virtual desktops.
*/
int numberOfDesktops() const;
/**
* Returns the number of the current desktop.
*/
int currentDesktop() const;
/**
* Returns true if the specified task is on top.
*/
bool isOnTop( const Task*);
signals:
/**
* Emitted when the active window changed.
*/
void activeTaskChanged(Task*);
/**
* Emitted when a new task has started.
*/
void taskAdded(Task*);
/**
* Emitted when a task has terminated.
*/
void taskRemoved(Task*);
/**
* Emitted when a new task is expected.
*/
void startupAdded(Startup*);
/**
* Emitted when a startup item should be removed. This could be because
* the task has started, because it is known to have died, or simply
* as a result of a timeout.
*/
void startupRemoved(Startup*);
/**
* Emitted when the current desktop changes.
*/
void desktopChanged(int desktop);
/**
* Emitted when a window changes desktop.
*/
void windowChanged(WId);
protected slots:
//* @internal
void windowAdded(WId);
//* @internal
void windowRemoved(WId);
//* @internal
void windowChanged(WId, unsigned int);
//* @internal
void activeWindowChanged(WId);
//* @internal
void currentDesktopChanged(int);
//* @internal
void killStartup( const KStartupInfoId& );
//* @internal
void killStartup(Startup*);
//* @internal
void gotNewStartup( const KStartupInfoId&, const KStartupInfoData& );
//* @internal
void gotStartupChange( const KStartupInfoId&, const KStartupInfoData& );
//* @internal
void gotRemoveStartup( const KStartupInfoId& );
protected:
/**
* Returns the task for a given WId, or 0 if there is no such task.
*/
Task* findTask(WId w);
void configure_startup();
private:
Task* _active;
TaskList _tasks;
QValueList< WId > _skiptaskbar_windows;
StartupList _startups;
KStartupInfo* _startup_info;
class TaskManagerPrivate *d;
};
#endif
|
iegor/kdeutils
|
superkaramba/src/taskmanager.h
|
C
|
gpl-2.0
| 14,856 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Using noty v2 with Old Options</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="demonstration of some noty capabilities">
<link href='http://fonts.googleapis.com/css?family=PT+Sans:regular,italic,bold,bolditalic&subset=latin,latin-ext,cyrillic' rel='stylesheet' type='text/css'>
<style type="text/css">
html {
height: 100%;
width: 100%;
}
body {
font-family: 'PT Sans', Tahoma, Arial, serif;
line-height: 13px
}
</style>
<link rel="stylesheet" type="text/css" href="buttons.css"/>
<link href="css/left_nav.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div id="customContainer">Old options not supported anymore. (until: v2.2.0)</div>
</div>
<script src="jquery-1.7.2.min.js"></script>
<!-- noty -->
<script type="text/javascript" src="../js/noty/packaged/jquery.noty.packaged.min.js"></script>
<script src="js/metisMenu.min.js"></script>
<script type="text/javascript">
$("#menu").metisMenu();
</script>
</body>
</html>
|
phillipmadsen/deved
|
public/vendors/noty-2.2.4/demo/usingWithOldOptions.html
|
HTML
|
gpl-2.0
| 1,301 |
<?php
/**
* @category Helper
* @package JomSocial
* @copyright (C) 2008 by Slashes & Dots Sdn Bhd - All rights reserved!
* @license GNU/GPL, see LICENSE.php
*/
defined('_JEXEC') or die('Restricted access');
class CLinkGeneratorHelper
{
/**
* Deprecated since 1.8
* Use CLinkGeneratorHelper::replaceHyperlinks instead.
*/
static public function linkURL( $message )
{
return self::replaceURL( $message );
}
/**
* Replaces a given link to it's html format
*
* @param $link A valid link
*
* return $url HTML formatted codes that links to given link
*/
static public function getURL( $link )
{
$url = JString::trim($link);
$pattern = "/^(https?|ftp)\:\/\/?(.*)?/i";
if( preg_match($pattern, $url))
{
return '<a href="'.$url.'" target="_blank" rel="nofollow">'.$url.'</a>';
}
return '<a href="http://'.$url.'" target="_blank" rel="nofollow">'.$url.'</a>';
}
/**
* Replaces a given email to a hyperlinked html format
*
* @param $email A valid email
*
* return $link HTML formatted codes that links to given email
*/
static public function getEmailURL( $email )
{
$email = JString::trim( $email );
// @rule: Process email cloaking by Joomla. If it fails,
// we will need to find another solution.
$link = JHTML::_( 'email.cloak', $email );
if( empty($link) )
{
$link = '<a href="mailto:'.$email.'">'.$email.'</a>';
}
return $link;
}
/**
* Replaces a given link be it email or hyperlink and return the proper
* counterparts.
*
* @param $url A valid url
*
* return $link HTML formatted codes that links to given email
*/
static public function getHyperLink( $url )
{
$link = JString::trim( $url );
CFactory::load( 'helpers' , 'validate' );
if(CValidateHelper::email($link))
{
return self::getEmailURL($link);
}
if(CValidateHelper::url($link))
{
return self::getURL( $link );
}
// Since the link is really not a link, we just return the original format.
return $link;
}
/**
* Automatically hyperlink a user's link
*
* @param $userId User's id.
* @param $userName Username of user.
*
* return $urlLink HTML codes that hyperlink to users profile.
**/
static public function getUserURL( $userId , $userName )
{
$url = CRoute::_('index.php?option=com_community&view=profile&userid=' . $userId );
$urlLink = '<a href="'.$url.'" rel="nofollow">'. $userName .'</a>';
return $urlLink;
}
/**
* Automatically link urls in the provided message
*
* @param $message A string of message that may or may not contain a url.
*
* return $message A modified copy of the message with the proper hyperlinks.
*
* Link Test Case
* Working:-
* http://google.com
* http://google.com.my
* http://google.co
* http://google.co.my
* http://mail.google.com
* http://mail.google.com.my
* http://mail.google.co
* http://mail.google.co.my
* http://google.com?something=something
* http://google.com.my?something=something
* http://google.co?something=something
* http://google.co.my?something=something
* www.google.com
* www.google.com?something=something
* www.google.co
* www.google.co?something=something
* http://www.google.com
* http://www.google.co
*
* None Workining:-
* google.com
*
**/
static public function replaceURL( $message , $noFollow = false , $newWindow = false )
{
if ($message == '')
{
return '';
}
/*
List of test url it need to pass
http://www.dailypress.com/entertainment/galleriesandmuseums/dp-fea-mark-0508-20110506,0,5689988.story
*/
$http="";
if(strpos($message,'www')!== false && strpos($message,'http://') === false && strpos($message,'https://') === false){
$http="http://";
}
$replace = ($noFollow) ? ' rel="nofollow"' : '';
$replace .= ($newWindow) ? ' target="_blank"' : '';
$pattern = "/(((http[s]?:\/\/)|(www\.))(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+|\.[a-z]+(\.[a-z]{2,2})?)\/?[,a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?_()]+)/is";
$message = preg_replace($pattern, " <a href=\"".$http."$1\"".$replace.">$1</a>", $message);
// fix URLs without protocols
$message = preg_replace("/href='www/", "href='http://www", $message);
return $message;
}
/**
* Automatically link username in the provided message when message contains @username
*
* @param $message A string of message that may or may not contain @username
*
* return $message A modified copy of the message with the proper hyperlinks.
**/
static public function replaceAliasURL( $message, $email = false )
{
$pattern = '/@(("(.*)")|([A-Z0-9][A-Z0-9_-]+)([A-Z0-9][A-Z0-9_-]+))/i';
preg_match_all( $pattern , $message , $matches );
if( isset($matches[0]) && !empty($matches[0]) )
{
CFactory::load( 'helpers' , 'user' );
CFactory::load( 'helpers' , 'linkgenerator' );
$usernames = $matches[ 0 ];
for( $i = 0 ; $i < count( $usernames ); $i++ )
{
$username = $usernames[ $i ];
$username = CString::str_ireplace( '"' , '' , $username );
$username = explode( '@' , $username );
$username = $username[1];
$id = CUserHelper::getUserId( $username );
if( $id != 0 )
{
if ($email) {
$profileLink = CRoute::emailLink('index.php?option=com_community&view=profile&userid=' . $id, true);
$message = CString::str_ireplace( $username , $profileLink, $message );
} else {
$message = CString::str_ireplace( $username , CLinkGeneratorHelper::getUserURL($id,$username) , $message );
}
}
}
}
return $message;
}
}
/**
* Deprecated since 1.8
* Use CLinkGeneratorHelper::validateURL instead.
*/
function cValidateURL($url)
{
CFactory::load( 'helpers' , 'validate' );
return CValidateHelper::url( $url );
}
/**
* Deprecated since 1.8
* Use CLinkGeneratorHelper::validateEmail instead.
*/
function cValidateEmails($email)
{
CFactory::load( 'helpers' , 'validate');
return CValidateHelper::email( $data, $strict );
}
/**
* Deprecated since 1.8
* Use CLinkGeneratorHelper::replaceURL instead.
*/
function cAutoLinkUrl( $message )
{
return CLinkGeneratorHelper::replaceURL( $message );
}
/**
* Deprecated since 1.8
* Use CLinkGeneratorHelper::getURL instead.
*/
function cGenerateUrlLink( $url )
{
return CLinkGeneratorHelper::getURL( $url );
}
/**
* Deprecated since 1.8
* Use CLinkGeneratorHelper::getEmailURL instead.
*/
function cGenerateEmailLink( $email )
{
return CLinkGeneratorHelper::getEmailURL( $email );
}
/**
* Deprecated since 1.8
* Use CLinkGeneratorHelper::getHyperLink instead.
*/
function cGenerateHyperLink($hyperlink)
{
return CLinkGeneratorHelper::getHyperLink( $hyperlink );
}
/**
* Deprecated since 1.8
* Use CLinkGeneratorHelper::getUserURL instead.
*/
function cGenerateUserLink( $userId , $userName )
{
return CLinkGeneratorHelper::getUserURL( $userId , $userName );
}
/**
* Deprecated since 1.8
* Use CLinkGeneratorHelper::replaceURL instead.
*/
function cGenerateURILinks( $message )
{
return CLinkGeneratorHelper::replaceURL( $message );
}
/**
* Deprecated since 1.8
* Use CLinkGeneratorHelper::replaceAliasURL instead.
*/
function cGenerateUserAliasLinks( $message )
{
return CLinkGeneratorHelper::replaceAliasURL( $message );
}
|
kiennd146/nhazz.com
|
components/com_community/helpers/linkgenerator.php
|
PHP
|
gpl-2.0
| 7,778 |
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#include "precompiled.hpp"
#include "asm/macroAssembler.inline.hpp"
#include "code/codeBlob.hpp"
#include "code/vmreg.inline.hpp"
#include "gc/z/zBarrier.inline.hpp"
#include "gc/z/zBarrierSet.hpp"
#include "gc/z/zBarrierSetAssembler.hpp"
#include "gc/z/zBarrierSetRuntime.hpp"
#include "gc/z/zThreadLocalData.hpp"
#include "memory/resourceArea.hpp"
#include "runtime/sharedRuntime.hpp"
#include "utilities/macros.hpp"
#ifdef COMPILER1
#include "c1/c1_LIRAssembler.hpp"
#include "c1/c1_MacroAssembler.hpp"
#include "gc/z/c1/zBarrierSetC1.hpp"
#endif // COMPILER1
#ifdef COMPILER2
#include "gc/z/c2/zBarrierSetC2.hpp"
#endif // COMPILER2
#ifdef PRODUCT
#define BLOCK_COMMENT(str) /* nothing */
#else
#define BLOCK_COMMENT(str) __ block_comment(str)
#endif
#undef __
#define __ masm->
void ZBarrierSetAssembler::load_at(MacroAssembler* masm,
DecoratorSet decorators,
BasicType type,
Register dst,
Address src,
Register tmp1,
Register tmp_thread) {
if (!ZBarrierSet::barrier_needed(decorators, type)) {
// Barrier not needed
BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1, tmp_thread);
return;
}
assert_different_registers(rscratch1, rscratch2, src.base());
assert_different_registers(rscratch1, rscratch2, dst);
RegSet savedRegs = RegSet::range(r0, r28) - RegSet::of(dst, rscratch1, rscratch2);
Label done;
// Load bad mask into scratch register.
__ ldr(rscratch1, address_bad_mask_from_thread(rthread));
__ lea(rscratch2, src);
__ ldr(dst, src);
// Test reference against bad mask. If mask bad, then we need to fix it up.
__ tst(dst, rscratch1);
__ br(Assembler::EQ, done);
__ enter();
__ push(savedRegs, sp);
if (c_rarg0 != dst) {
__ mov(c_rarg0, dst);
}
__ mov(c_rarg1, rscratch2);
int step = 4 * wordSize;
__ mov(rscratch2, -step);
__ sub(sp, sp, step);
for (int i = 28; i >= 4; i -= 4) {
__ st1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
as_FloatRegister(i+3), __ T1D, Address(__ post(sp, rscratch2)));
}
__ st1(as_FloatRegister(0), as_FloatRegister(1), as_FloatRegister(2),
as_FloatRegister(3), __ T1D, Address(sp));
__ call_VM_leaf(ZBarrierSetRuntime::load_barrier_on_oop_field_preloaded_addr(decorators), 2);
for (int i = 0; i <= 28; i += 4) {
__ ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
as_FloatRegister(i+3), __ T1D, Address(__ post(sp, step)));
}
// Make sure dst has the return value.
if (dst != r0) {
__ mov(dst, r0);
}
__ pop(savedRegs, sp);
__ leave();
__ bind(done);
}
#ifdef ASSERT
void ZBarrierSetAssembler::store_at(MacroAssembler* masm,
DecoratorSet decorators,
BasicType type,
Address dst,
Register val,
Register tmp1,
Register tmp2) {
// Verify value
if (is_reference_type(type)) {
// Note that src could be noreg, which means we
// are storing null and can skip verification.
if (val != noreg) {
Label done;
// tmp1 and tmp2 are often set to noreg.
RegSet savedRegs = RegSet::of(rscratch1);
__ push(savedRegs, sp);
__ ldr(rscratch1, address_bad_mask_from_thread(rthread));
__ tst(val, rscratch1);
__ br(Assembler::EQ, done);
__ stop("Verify oop store failed");
__ should_not_reach_here();
__ bind(done);
__ pop(savedRegs, sp);
}
}
// Store value
BarrierSetAssembler::store_at(masm, decorators, type, dst, val, tmp1, tmp2);
}
#endif // ASSERT
void ZBarrierSetAssembler::arraycopy_prologue(MacroAssembler* masm,
DecoratorSet decorators,
bool is_oop,
Register src,
Register dst,
Register count,
RegSet saved_regs) {
if (!is_oop) {
// Barrier not needed
return;
}
BLOCK_COMMENT("ZBarrierSetAssembler::arraycopy_prologue {");
assert_different_registers(src, count, rscratch1);
__ pusha();
if (count == c_rarg0) {
if (src == c_rarg1) {
// exactly backwards!!
__ mov(rscratch1, c_rarg0);
__ mov(c_rarg0, c_rarg1);
__ mov(c_rarg1, rscratch1);
} else {
__ mov(c_rarg1, count);
__ mov(c_rarg0, src);
}
} else {
__ mov(c_rarg0, src);
__ mov(c_rarg1, count);
}
__ call_VM_leaf(ZBarrierSetRuntime::load_barrier_on_oop_array_addr(), 2);
__ popa();
BLOCK_COMMENT("} ZBarrierSetAssembler::arraycopy_prologue");
}
void ZBarrierSetAssembler::try_resolve_jobject_in_native(MacroAssembler* masm,
Register jni_env,
Register robj,
Register tmp,
Label& slowpath) {
BLOCK_COMMENT("ZBarrierSetAssembler::try_resolve_jobject_in_native {");
assert_different_registers(jni_env, robj, tmp);
// Resolve jobject
BarrierSetAssembler::try_resolve_jobject_in_native(masm, jni_env, robj, tmp, slowpath);
// The Address offset is too large to direct load - -784. Our range is +127, -128.
__ mov(tmp, (long int)(in_bytes(ZThreadLocalData::address_bad_mask_offset()) -
in_bytes(JavaThread::jni_environment_offset())));
// Load address bad mask
__ add(tmp, jni_env, tmp);
__ ldr(tmp, Address(tmp));
// Check address bad mask
__ tst(robj, tmp);
__ br(Assembler::NE, slowpath);
BLOCK_COMMENT("} ZBarrierSetAssembler::try_resolve_jobject_in_native");
}
#ifdef COMPILER1
#undef __
#define __ ce->masm()->
void ZBarrierSetAssembler::generate_c1_load_barrier_test(LIR_Assembler* ce,
LIR_Opr ref) const {
assert_different_registers(rscratch1, rthread, ref->as_register());
__ ldr(rscratch1, address_bad_mask_from_thread(rthread));
__ tst(ref->as_register(), rscratch1);
}
void ZBarrierSetAssembler::generate_c1_load_barrier_stub(LIR_Assembler* ce,
ZLoadBarrierStubC1* stub) const {
// Stub entry
__ bind(*stub->entry());
Register ref = stub->ref()->as_register();
Register ref_addr = noreg;
Register tmp = noreg;
if (stub->tmp()->is_valid()) {
// Load address into tmp register
ce->leal(stub->ref_addr(), stub->tmp());
ref_addr = tmp = stub->tmp()->as_pointer_register();
} else {
// Address already in register
ref_addr = stub->ref_addr()->as_address_ptr()->base()->as_pointer_register();
}
assert_different_registers(ref, ref_addr, noreg);
// Save r0 unless it is the result or tmp register
// Set up SP to accomodate parameters and maybe r0..
if (ref != r0 && tmp != r0) {
__ sub(sp, sp, 32);
__ str(r0, Address(sp, 16));
} else {
__ sub(sp, sp, 16);
}
// Setup arguments and call runtime stub
ce->store_parameter(ref_addr, 1);
ce->store_parameter(ref, 0);
__ far_call(stub->runtime_stub());
// Verify result
__ verify_oop(r0, "Bad oop");
// Move result into place
if (ref != r0) {
__ mov(ref, r0);
}
// Restore r0 unless it is the result or tmp register
if (ref != r0 && tmp != r0) {
__ ldr(r0, Address(sp, 16));
__ add(sp, sp, 32);
} else {
__ add(sp, sp, 16);
}
// Stub exit
__ b(*stub->continuation());
}
#undef __
#define __ sasm->
void ZBarrierSetAssembler::generate_c1_load_barrier_runtime_stub(StubAssembler* sasm,
DecoratorSet decorators) const {
__ prologue("zgc_load_barrier stub", false);
// We don't use push/pop_clobbered_registers() - we need to pull out the result from r0.
for (int i = 0; i < 32; i += 2) {
__ stpd(as_FloatRegister(i), as_FloatRegister(i + 1), Address(__ pre(sp,-16)));
}
const RegSet save_regs = RegSet::range(r1, r28);
__ push(save_regs, sp);
// Setup arguments
__ load_parameter(0, c_rarg0);
__ load_parameter(1, c_rarg1);
__ call_VM_leaf(ZBarrierSetRuntime::load_barrier_on_oop_field_preloaded_addr(decorators), 2);
__ pop(save_regs, sp);
for (int i = 30; i >= 0; i -= 2) {
__ ldpd(as_FloatRegister(i), as_FloatRegister(i + 1), Address(__ post(sp, 16)));
}
__ epilogue();
}
#endif // COMPILER1
#ifdef COMPILER2
OptoReg::Name ZBarrierSetAssembler::refine_register(const Node* node, OptoReg::Name opto_reg) {
if (!OptoReg::is_reg(opto_reg)) {
return OptoReg::Bad;
}
const VMReg vm_reg = OptoReg::as_VMReg(opto_reg);
if (vm_reg->is_FloatRegister()) {
return opto_reg & ~1;
}
return opto_reg;
}
#undef __
#define __ _masm->
class ZSaveLiveRegisters {
private:
MacroAssembler* const _masm;
RegSet _gp_regs;
RegSet _fp_regs;
public:
void initialize(ZLoadBarrierStubC2* stub) {
// Create mask of live registers
RegMask live = stub->live();
// Record registers that needs to be saved/restored
while (live.is_NotEmpty()) {
const OptoReg::Name opto_reg = live.find_first_elem();
live.Remove(opto_reg);
if (OptoReg::is_reg(opto_reg)) {
const VMReg vm_reg = OptoReg::as_VMReg(opto_reg);
if (vm_reg->is_Register()) {
_gp_regs += RegSet::of(vm_reg->as_Register());
} else if (vm_reg->is_FloatRegister()) {
_fp_regs += RegSet::of((Register)vm_reg->as_FloatRegister());
} else {
fatal("Unknown register type");
}
}
}
// Remove C-ABI SOE registers, scratch regs and _ref register that will be updated
_gp_regs -= RegSet::range(r19, r30) + RegSet::of(r8, r9, stub->ref());
}
ZSaveLiveRegisters(MacroAssembler* masm, ZLoadBarrierStubC2* stub) :
_masm(masm),
_gp_regs(),
_fp_regs() {
// Figure out what registers to save/restore
initialize(stub);
// Save registers
__ push(_gp_regs, sp);
__ push_fp(_fp_regs, sp);
}
~ZSaveLiveRegisters() {
// Restore registers
__ pop_fp(_fp_regs, sp);
__ pop(_gp_regs, sp);
}
};
#undef __
#define __ _masm->
class ZSetupArguments {
private:
MacroAssembler* const _masm;
const Register _ref;
const Address _ref_addr;
public:
ZSetupArguments(MacroAssembler* masm, ZLoadBarrierStubC2* stub) :
_masm(masm),
_ref(stub->ref()),
_ref_addr(stub->ref_addr()) {
// Setup arguments
if (_ref_addr.base() == noreg) {
// No self healing
if (_ref != c_rarg0) {
__ mov(c_rarg0, _ref);
}
__ mov(c_rarg1, 0);
} else {
// Self healing
if (_ref == c_rarg0) {
// _ref is already at correct place
__ lea(c_rarg1, _ref_addr);
} else if (_ref != c_rarg1) {
// _ref is in wrong place, but not in c_rarg1, so fix it first
__ lea(c_rarg1, _ref_addr);
__ mov(c_rarg0, _ref);
} else if (_ref_addr.base() != c_rarg0 && _ref_addr.index() != c_rarg0) {
assert(_ref == c_rarg1, "Mov ref first, vacating c_rarg0");
__ mov(c_rarg0, _ref);
__ lea(c_rarg1, _ref_addr);
} else {
assert(_ref == c_rarg1, "Need to vacate c_rarg1 and _ref_addr is using c_rarg0");
if (_ref_addr.base() == c_rarg0 || _ref_addr.index() == c_rarg0) {
__ mov(rscratch2, c_rarg1);
__ lea(c_rarg1, _ref_addr);
__ mov(c_rarg0, rscratch2);
} else {
ShouldNotReachHere();
}
}
}
}
~ZSetupArguments() {
// Transfer result
if (_ref != r0) {
__ mov(_ref, r0);
}
}
};
#undef __
#define __ masm->
void ZBarrierSetAssembler::generate_c2_load_barrier_stub(MacroAssembler* masm, ZLoadBarrierStubC2* stub) const {
BLOCK_COMMENT("ZLoadBarrierStubC2");
// Stub entry
__ bind(*stub->entry());
{
ZSaveLiveRegisters save_live_registers(masm, stub);
ZSetupArguments setup_arguments(masm, stub);
__ mov(rscratch1, stub->slow_path());
__ blr(rscratch1);
}
// Stub exit
__ b(*stub->continuation());
}
#undef __
#endif // COMPILER2
|
md-5/jdk10
|
src/hotspot/cpu/aarch64/gc/z/zBarrierSetAssembler_aarch64.cpp
|
C++
|
gpl-2.0
| 13,659 |
<html lang="en">
<head>
<title>GNU Free Documentation License - Untitled</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Untitled">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="prev" href="MRI.html#MRI" title="MRI">
<link rel="next" href="LD-Index.html#LD-Index" title="LD Index">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This file documents the GNU linker LD
(Sourcery G++ Lite 2010q1-202)
version 2.19.51.
Copyright (C) 1991, 92, 93, 94, 95, 96, 97, 98, 99, 2000,
2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled ``GNU Free Documentation License''.-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
<link rel="stylesheet" type="text/css" href="../cs.css">
</head>
<body>
<div class="node">
<a name="GNU-Free-Documentation-License"></a>
<p>
Next: <a rel="next" accesskey="n" href="LD-Index.html#LD-Index">LD Index</a>,
Previous: <a rel="previous" accesskey="p" href="MRI.html#MRI">MRI</a>,
Up: <a rel="up" accesskey="u" href="index.html#Top">Top</a>
<hr>
</div>
<h2 class="appendix">Appendix B GNU Free Documentation License</h2>
<!-- *-texinfo-*- -->
<div align="center">Version 1.1, March 2000</div>
<pre class="display"> Copyright (C) 2000, 2003 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
</pre>
<pre class="sp">
</pre>
<ol type=1 start=0>
<li>PREAMBLE
<p>The purpose of this License is to make a manual, textbook, or other
written document “free” in the sense of freedom: to assure everyone
the effective freedom to copy and redistribute it, with or without
modifying it, either commercially or noncommercially. Secondarily,
this License preserves for the author and publisher a way to get
credit for their work, while not being considered responsible for
modifications made by others.
<p>This License is a kind of “copyleft”, which means that derivative
works of the document must themselves be free in the same sense. It
complements the GNU General Public License, which is a copyleft
license designed for free software.
<p>We have designed this License in order to use it for manuals for free
software, because free software needs free documentation: a free
program should come with manuals providing the same freedoms that the
software does. But this License is not limited to software manuals;
it can be used for any textual work, regardless of subject matter or
whether it is published as a printed book. We recommend this License
principally for works whose purpose is instruction or reference.
<pre class="sp">
</pre>
<li>APPLICABILITY AND DEFINITIONS
<p>This License applies to any manual or other work that contains a
notice placed by the copyright holder saying it can be distributed
under the terms of this License. The “Document”, below, refers to any
such manual or work. Any member of the public is a licensee, and is
addressed as “you.”
<p>A “Modified Version” of the Document means any work containing the
Document or a portion of it, either copied verbatim, or with
modifications and/or translated into another language.
<p>A “Secondary Section” is a named appendix or a front-matter section of
the Document that deals exclusively with the relationship of the
publishers or authors of the Document to the Document's overall subject
(or to related matters) and contains nothing that could fall directly
within that overall subject. (For example, if the Document is in part a
textbook of mathematics, a Secondary Section may not explain any
mathematics.) The relationship could be a matter of historical
connection with the subject or with related matters, or of legal,
commercial, philosophical, ethical or political position regarding
them.
<p>The “Invariant Sections” are certain Secondary Sections whose titles
are designated, as being those of Invariant Sections, in the notice
that says that the Document is released under this License.
<p>The “Cover Texts” are certain short passages of text that are listed,
as Front-Cover Texts or Back-Cover Texts, in the notice that says that
the Document is released under this License.
<p>A “Transparent” copy of the Document means a machine-readable copy,
represented in a format whose specification is available to the
general public, whose contents can be viewed and edited directly and
straightforwardly with generic text editors or (for images composed of
pixels) generic paint programs or (for drawings) some widely available
drawing editor, and that is suitable for input to text formatters or
for automatic translation to a variety of formats suitable for input
to text formatters. A copy made in an otherwise Transparent file
format whose markup has been designed to thwart or discourage
subsequent modification by readers is not Transparent. A copy that is
not “Transparent” is called “Opaque.”
<p>Examples of suitable formats for Transparent copies include plain
ASCII without markup, Texinfo input format, LaTeX input format, SGML
or XML using a publicly available DTD, and standard-conforming simple
HTML designed for human modification. Opaque formats include
PostScript, PDF, proprietary formats that can be read and edited only
by proprietary word processors, SGML or XML for which the DTD and/or
processing tools are not generally available, and the
machine-generated HTML produced by some word processors for output
purposes only.
<p>The “Title Page” means, for a printed book, the title page itself,
plus such following pages as are needed to hold, legibly, the material
this License requires to appear in the title page. For works in
formats which do not have any title page as such, “Title Page” means
the text near the most prominent appearance of the work's title,
preceding the beginning of the body of the text.
<pre class="sp">
</pre>
<li>VERBATIM COPYING
<p>You may copy and distribute the Document in any medium, either
commercially or noncommercially, provided that this License, the
copyright notices, and the license notice saying this License applies
to the Document are reproduced in all copies, and that you add no other
conditions whatsoever to those of this License. You may not use
technical measures to obstruct or control the reading or further
copying of the copies you make or distribute. However, you may accept
compensation in exchange for copies. If you distribute a large enough
number of copies you must also follow the conditions in section 3.
<p>You may also lend copies, under the same conditions stated above, and
you may publicly display copies.
<pre class="sp">
</pre>
<li>COPYING IN QUANTITY
<p>If you publish printed copies of the Document numbering more than 100,
and the Document's license notice requires Cover Texts, you must enclose
the copies in covers that carry, clearly and legibly, all these Cover
Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
the back cover. Both covers must also clearly and legibly identify
you as the publisher of these copies. The front cover must present
the full title with all words of the title equally prominent and
visible. You may add other material on the covers in addition.
Copying with changes limited to the covers, as long as they preserve
the title of the Document and satisfy these conditions, can be treated
as verbatim copying in other respects.
<p>If the required texts for either cover are too voluminous to fit
legibly, you should put the first ones listed (as many as fit
reasonably) on the actual cover, and continue the rest onto adjacent
pages.
<p>If you publish or distribute Opaque copies of the Document numbering
more than 100, you must either include a machine-readable Transparent
copy along with each Opaque copy, or state in or with each Opaque copy
a publicly-accessible computer-network location containing a complete
Transparent copy of the Document, free of added material, which the
general network-using public has access to download anonymously at no
charge using public-standard network protocols. If you use the latter
option, you must take reasonably prudent steps, when you begin
distribution of Opaque copies in quantity, to ensure that this
Transparent copy will remain thus accessible at the stated location
until at least one year after the last time you distribute an Opaque
copy (directly or through your agents or retailers) of that edition to
the public.
<p>It is requested, but not required, that you contact the authors of the
Document well before redistributing any large number of copies, to give
them a chance to provide you with an updated version of the Document.
<pre class="sp">
</pre>
<li>MODIFICATIONS
<p>You may copy and distribute a Modified Version of the Document under
the conditions of sections 2 and 3 above, provided that you release
the Modified Version under precisely this License, with the Modified
Version filling the role of the Document, thus licensing distribution
and modification of the Modified Version to whoever possesses a copy
of it. In addition, you must do these things in the Modified Version:
<p>A. Use in the Title Page (and on the covers, if any) a title distinct
from that of the Document, and from those of previous versions
(which should, if there were any, be listed in the History section
of the Document). You may use the same title as a previous version
if the original publisher of that version gives permission.<br>
B. List on the Title Page, as authors, one or more persons or entities
responsible for authorship of the modifications in the Modified
Version, together with at least five of the principal authors of the
Document (all of its principal authors, if it has less than five).<br>
C. State on the Title page the name of the publisher of the
Modified Version, as the publisher.<br>
D. Preserve all the copyright notices of the Document.<br>
E. Add an appropriate copyright notice for your modifications
adjacent to the other copyright notices.<br>
F. Include, immediately after the copyright notices, a license notice
giving the public permission to use the Modified Version under the
terms of this License, in the form shown in the Addendum below.<br>
G. Preserve in that license notice the full lists of Invariant Sections
and required Cover Texts given in the Document's license notice.<br>
H. Include an unaltered copy of this License.<br>
I. Preserve the section entitled “History”, and its title, and add to
it an item stating at least the title, year, new authors, and
publisher of the Modified Version as given on the Title Page. If
there is no section entitled “History” in the Document, create one
stating the title, year, authors, and publisher of the Document as
given on its Title Page, then add an item describing the Modified
Version as stated in the previous sentence.<br>
J. Preserve the network location, if any, given in the Document for
public access to a Transparent copy of the Document, and likewise
the network locations given in the Document for previous versions
it was based on. These may be placed in the “History” section.
You may omit a network location for a work that was published at
least four years before the Document itself, or if the original
publisher of the version it refers to gives permission.<br>
K. In any section entitled “Acknowledgements” or “Dedications”,
preserve the section's title, and preserve in the section all the
substance and tone of each of the contributor acknowledgements
and/or dedications given therein.<br>
L. Preserve all the Invariant Sections of the Document,
unaltered in their text and in their titles. Section numbers
or the equivalent are not considered part of the section titles.<br>
M. Delete any section entitled “Endorsements.” Such a section
may not be included in the Modified Version.<br>
N. Do not retitle any existing section as “Endorsements”
or to conflict in title with any Invariant Section.<br>
<pre class="sp">
</pre>
If the Modified Version includes new front-matter sections or
appendices that qualify as Secondary Sections and contain no material
copied from the Document, you may at your option designate some or all
of these sections as invariant. To do this, add their titles to the
list of Invariant Sections in the Modified Version's license notice.
These titles must be distinct from any other section titles.
<p>You may add a section entitled “Endorsements”, provided it contains
nothing but endorsements of your Modified Version by various
parties–for example, statements of peer review or that the text has
been approved by an organization as the authoritative definition of a
standard.
<p>You may add a passage of up to five words as a Front-Cover Text, and a
passage of up to 25 words as a Back-Cover Text, to the end of the list
of Cover Texts in the Modified Version. Only one passage of
Front-Cover Text and one of Back-Cover Text may be added by (or
through arrangements made by) any one entity. If the Document already
includes a cover text for the same cover, previously added by you or
by arrangement made by the same entity you are acting on behalf of,
you may not add another; but you may replace the old one, on explicit
permission from the previous publisher that added the old one.
<p>The author(s) and publisher(s) of the Document do not by this License
give permission to use their names for publicity for or to assert or
imply endorsement of any Modified Version.
<pre class="sp">
</pre>
<li>COMBINING DOCUMENTS
<p>You may combine the Document with other documents released under this
License, under the terms defined in section 4 above for modified
versions, provided that you include in the combination all of the
Invariant Sections of all of the original documents, unmodified, and
list them all as Invariant Sections of your combined work in its
license notice.
<p>The combined work need only contain one copy of this License, and
multiple identical Invariant Sections may be replaced with a single
copy. If there are multiple Invariant Sections with the same name but
different contents, make the title of each such section unique by
adding at the end of it, in parentheses, the name of the original
author or publisher of that section if known, or else a unique number.
Make the same adjustment to the section titles in the list of
Invariant Sections in the license notice of the combined work.
<p>In the combination, you must combine any sections entitled “History”
in the various original documents, forming one section entitled
“History”; likewise combine any sections entitled “Acknowledgements”,
and any sections entitled “Dedications.” You must delete all sections
entitled “Endorsements.”
<pre class="sp">
</pre>
<li>COLLECTIONS OF DOCUMENTS
<p>You may make a collection consisting of the Document and other documents
released under this License, and replace the individual copies of this
License in the various documents with a single copy that is included in
the collection, provided that you follow the rules of this License for
verbatim copying of each of the documents in all other respects.
<p>You may extract a single document from such a collection, and distribute
it individually under this License, provided you insert a copy of this
License into the extracted document, and follow this License in all
other respects regarding verbatim copying of that document.
<pre class="sp">
</pre>
<li>AGGREGATION WITH INDEPENDENT WORKS
<p>A compilation of the Document or its derivatives with other separate
and independent documents or works, in or on a volume of a storage or
distribution medium, does not as a whole count as a Modified Version
of the Document, provided no compilation copyright is claimed for the
compilation. Such a compilation is called an “aggregate”, and this
License does not apply to the other self-contained works thus compiled
with the Document, on account of their being thus compiled, if they
are not themselves derivative works of the Document.
<p>If the Cover Text requirement of section 3 is applicable to these
copies of the Document, then if the Document is less than one quarter
of the entire aggregate, the Document's Cover Texts may be placed on
covers that surround only the Document within the aggregate.
Otherwise they must appear on covers around the whole aggregate.
<pre class="sp">
</pre>
<li>TRANSLATION
<p>Translation is considered a kind of modification, so you may
distribute translations of the Document under the terms of section 4.
Replacing Invariant Sections with translations requires special
permission from their copyright holders, but you may include
translations of some or all Invariant Sections in addition to the
original versions of these Invariant Sections. You may include a
translation of this License provided that you also include the
original English version of this License. In case of a disagreement
between the translation and the original English version of this
License, the original English version will prevail.
<pre class="sp">
</pre>
<li>TERMINATION
<p>You may not copy, modify, sublicense, or distribute the Document except
as expressly provided for under this License. Any other attempt to
copy, modify, sublicense or distribute the Document is void, and will
automatically terminate your rights under this License. However,
parties who have received copies, or rights, from you under this
License will not have their licenses terminated so long as such
parties remain in full compliance.
<pre class="sp">
</pre>
<li>FUTURE REVISIONS OF THIS LICENSE
<p>The Free Software Foundation may publish new, revised versions
of the GNU Free Documentation License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns. See
http://www.gnu.org/copyleft/.
<p>Each version of the License is given a distinguishing version number.
If the Document specifies that a particular numbered version of this
License “or any later version” applies to it, you have the option of
following the terms and conditions either of that specified version or
of any later version that has been published (not as a draft) by the
Free Software Foundation. If the Document does not specify a version
number of this License, you may choose any version ever published (not
as a draft) by the Free Software Foundation.
</ol>
<h3 class="unnumberedsec">ADDENDUM: How to use this License for your documents</h3>
<p>To use this License in a document you have written, include a copy of
the License in the document and put the following copyright and
license notices just after the title page:
<pre class="smallexample"> Copyright (C) <var>year</var> <var>your name</var>.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1
or any later version published by the Free Software Foundation;
with the Invariant Sections being <var>list their titles</var>, with the
Front-Cover Texts being <var>list</var>, and with the Back-Cover Texts being <var>list</var>.
A copy of the license is included in the section entitled "GNU
Free Documentation License."
</pre>
<p>If you have no Invariant Sections, write “with no Invariant Sections”
instead of saying which ones are invariant. If you have no
Front-Cover Texts, write “no Front-Cover Texts” instead of
“Front-Cover Texts being <var>list</var>”; likewise for Back-Cover Texts.
<p>If your document contains nontrivial examples of program code, we
recommend releasing these examples in parallel under your choice of
free software license, such as the GNU General Public License,
to permit their use in free software.
</body></html>
|
AmeriCanAndroid/kernel_htc_shooteru
|
toolchains/arm2010q1/share/doc/arm-arm-none-linux-gnueabi/html/ld.html/GNU-Free-Documentation-License.html
|
HTML
|
gpl-2.0
| 21,687 |
// btss41mlr.cpp
//
// A Rivendell switcher driver for the BroadcastTools SS 4.1 MLR
//
// (C) Copyright 2002-2020 Fred Gleason <[email protected]>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
#include <stdlib.h>
#include <qstringlist.h>
#include <qtimer.h>
#include <rdapplication.h>
#include "btss41mlr.h"
#include "globals.h"
BtSs41Mlr::BtSs41Mlr(RDMatrix *matrix,QObject *parent)
: Switcher(matrix,parent)
{
//
// Initialize Data Structures
//
bt_istate=0;
for(int i=0;i<BTSS41MLR_GPIO_PINS;i++) {
bt_gpi_state[i]=false;
bt_gpi_mask[i]=false;
}
//
// Get Matrix Parameters
//
bt_matrix=matrix->matrix();
bt_inputs=matrix->inputs();
bt_outputs=matrix->outputs();
bt_gpis=matrix->gpis();
bt_gpos=matrix->gpos();
//
// Initialize the TTY Port
//
RDTty *tty=new RDTty(rda->station()->name(),matrix->port(RDMatrix::Primary));
bt_device=new RDTTYDevice();
connect(bt_device,SIGNAL(readyRead()),this,SLOT(readyReadData()));
if(tty->active()) {
bt_device->setName(tty->port());
bt_device->setSpeed(tty->baudRate());
bt_device->setWordLength(tty->dataBits());
bt_device->setParity(tty->parity());
bt_device->open(QIODevice::Unbuffered|QIODevice::ReadWrite);
}
delete tty;
//
// Interval OneShots
//
bt_gpi_oneshot=new RDOneShot(this);
connect(bt_gpi_oneshot,SIGNAL(timeout(int)),this,SLOT(gpiOneshotData(int)));
bt_gpo_oneshot=new RDOneShot(this);
connect(bt_gpo_oneshot,SIGNAL(timeout(int)),this,SLOT(gpoOneshotData(int)));
}
BtSs41Mlr::~BtSs41Mlr()
{
delete bt_device;
delete bt_gpi_oneshot;
delete bt_gpo_oneshot;
}
RDMatrix::Type BtSs41Mlr::type()
{
return RDMatrix::BtSs41Mlr;
}
unsigned BtSs41Mlr::gpiQuantity()
{
return bt_gpis;
}
unsigned BtSs41Mlr::gpoQuantity()
{
return bt_gpos;
}
bool BtSs41Mlr::primaryTtyActive()
{
return true;
}
bool BtSs41Mlr::secondaryTtyActive()
{
return false;
}
void BtSs41Mlr::processCommand(RDMacro *cmd)
{
QString str;
switch(cmd->command()) {
case RDMacro::ST:
if((cmd->arg(1).toInt()<0)||(cmd->arg(1).toInt()>bt_inputs)||
(cmd->arg(2).toInt()<1)||(cmd->arg(2).toInt()>1)) {
cmd->acknowledge(false);
emit rmlEcho(cmd);
return;
}
if(cmd->arg(1).toInt()==0) {
str=QString().sprintf("*%dMA",BTSS41MLR_UNIT_ID);
bt_device->write(str,str.length());
}
else {
str=QString().sprintf("*%d%02d",BTSS41MLR_UNIT_ID,
cmd->arg(1).toInt());
bt_device->write(str,str.length());
}
cmd->acknowledge(true);
emit rmlEcho(cmd);
break;
default:
cmd->acknowledge(false);
emit rmlEcho(cmd);
break;
}
}
void BtSs41Mlr::readyReadData()
{
char buffer[256];
int n;
while((n=bt_device->read(buffer,255))>0) {
for(int i=0;i<n;i++) {
switch(0xFF&buffer[i]) {
case 10:
ProcessStatus(bt_accum);
bt_accum="";
break;
case 13:
break;
default:
bt_accum+=buffer[i];
break;
}
}
}
}
void BtSs41Mlr::gpiOneshotData(int value)
{
bt_gpi_mask[value]=false;
bt_device->write("*0SPA",5);
}
void BtSs41Mlr::gpoOneshotData(int value)
{
emit gpoChanged(bt_matrix,value,false);
}
void BtSs41Mlr::ProcessStatus(const QString &msg)
{
QStringList f0=msg.split(",");
if(f0.size()==10) {
if((f0[0]==QString().sprintf("S%dP",BTSS41MLR_UNIT_ID))&&(f0[1]=="A")) {
for(int i=0;i<bt_gpis;i++) {
if(f0[2+i]=="0") {
if(bt_gpi_state[i]&&(!bt_gpi_mask[i])) {
emit gpiChanged(bt_matrix,i,false);
bt_gpi_state[i]=false;
}
}
if(f0[2+i]=="1") {
if(!bt_gpi_state[i]&&(!bt_gpi_mask[i])) {
emit gpiChanged(bt_matrix,i,true);
bt_gpi_state[i]=true;
}
}
}
}
}
}
|
ElvishArtisan/rivendell
|
ripcd/btss41mlr.cpp
|
C++
|
gpl-2.0
| 4,267 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2015
*/
class CRM_Core_BAO_Mapping extends CRM_Core_DAO_Mapping {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return object
* CRM_Core_DAO_Mapping object on success, otherwise NULL
*/
public static function retrieve(&$params, &$defaults) {
$mapping = new CRM_Core_DAO_Mapping();
$mapping->copyValues($params);
if ($mapping->find(TRUE)) {
CRM_Core_DAO::storeValues($mapping, $defaults);
return $mapping;
}
return NULL;
}
/**
* Delete the mapping.
*
* @param int $id
* Mapping id.
*
* @return bool
*/
public static function del($id) {
// delete from mapping_field table
$mappingField = new CRM_Core_DAO_MappingField();
$mappingField->mapping_id = $id;
$mappingField->find();
while ($mappingField->fetch()) {
$mappingField->delete();
}
// delete from mapping table
$mapping = new CRM_Core_DAO_Mapping();
$mapping->id = $id;
if ($mapping->find(TRUE)) {
$result = $mapping->delete();
return $result;
}
return FALSE;
}
/**
* Takes an associative array and creates a contact object.
*
* The function extract all the params it needs to initialize the create a
* contact object. the params array could contain additional unused name/value
* pairs
*
* @param array $params
* An array of name/value pairs.
*
* @return object
* CRM_Core_DAO_Mapper object on success, otherwise NULL
*/
public static function add($params) {
$mapping = new CRM_Core_DAO_Mapping();
$mapping->copyValues($params);
$mapping->save();
return $mapping;
}
/**
* Get the list of mappings.
*
* @param string $mappingTypeId
* Mapping type id.
*
* @return array
* array of mapping name
*/
public static function getMappings($mappingTypeId) {
$mapping = array();
$mappingDAO = new CRM_Core_DAO_Mapping();
$mappingDAO->mapping_type_id = $mappingTypeId;
$mappingDAO->find();
while ($mappingDAO->fetch()) {
$mapping[$mappingDAO->id] = $mappingDAO->name;
}
return $mapping;
}
/**
* Get the mapping fields.
*
* @param int $mappingId
* Mapping id.
*
* @return array
* array of mapping fields
*/
public static function getMappingFields($mappingId) {
//mapping is to be loaded from database
$mapping = new CRM_Core_DAO_MappingField();
$mapping->mapping_id = $mappingId;
$mapping->orderBy('column_number');
$mapping->find();
$mappingName = $mappingLocation = $mappingContactType = $mappingPhoneType = array();
$mappingImProvider = $mappingRelation = $mappingOperator = $mappingValue = $mappingWebsiteType = array();
while ($mapping->fetch()) {
$mappingName[$mapping->grouping][$mapping->column_number] = $mapping->name;
$mappingContactType[$mapping->grouping][$mapping->column_number] = $mapping->contact_type;
if (!empty($mapping->location_type_id)) {
$mappingLocation[$mapping->grouping][$mapping->column_number] = $mapping->location_type_id;
}
if (!empty($mapping->phone_type_id)) {
$mappingPhoneType[$mapping->grouping][$mapping->column_number] = $mapping->phone_type_id;
}
// get IM service provider type id from mapping fields
if (!empty($mapping->im_provider_id)) {
$mappingImProvider[$mapping->grouping][$mapping->column_number] = $mapping->im_provider_id;
}
if (!empty($mapping->website_type_id)) {
$mappingWebsiteType[$mapping->grouping][$mapping->column_number] = $mapping->website_type_id;
}
if (!empty($mapping->relationship_type_id)) {
$mappingRelation[$mapping->grouping][$mapping->column_number] = "{$mapping->relationship_type_id}_{$mapping->relationship_direction}";
}
if (!empty($mapping->operator)) {
$mappingOperator[$mapping->grouping][$mapping->column_number] = $mapping->operator;
}
if (!empty($mapping->value)) {
$mappingValue[$mapping->grouping][$mapping->column_number] = $mapping->value;
}
}
return array(
$mappingName,
$mappingContactType,
$mappingLocation,
$mappingPhoneType,
$mappingImProvider,
$mappingRelation,
$mappingOperator,
$mappingValue,
$mappingWebsiteType,
);
}
/**
* Check Duplicate Mapping Name.
*
* @param string $nameField
* mapping Name.
* @param string $mapTypeId
* mapping Type.
*
* @return bool
*/
public static function checkMapping($nameField, $mapTypeId) {
$mapping = new CRM_Core_DAO_Mapping();
$mapping->name = $nameField;
$mapping->mapping_type_id = $mapTypeId;
return (bool) $mapping->find(TRUE);
}
/**
* Function returns associated array of elements, that will be passed for search.
*
* @param int $smartGroupId
* Smart group id.
*
* @return array
* associated array of elements
*/
public static function getFormattedFields($smartGroupId) {
$returnFields = array();
//get the fields from mapping table
$dao = new CRM_Core_DAO_MappingField();
$dao->mapping_id = $smartGroupId;
$dao->find();
while ($dao->fetch()) {
$fldName = $dao->name;
if ($dao->location_type_id) {
$fldName .= "-{$dao->location_type_id}";
}
if ($dao->phone_type) {
$fldName .= "-{$dao->phone_type}";
}
$returnFields[$fldName]['value'] = $dao->value;
$returnFields[$fldName]['op'] = $dao->operator;
$returnFields[$fldName]['grouping'] = $dao->grouping;
}
return $returnFields;
}
/**
* Build the mapping form.
*
* @param CRM_Core_Form $form
* @param string $mappingType
* (Export/Search Builder). (Import apparently used to use this but does no longer).
* @param int $mappingId
* @param int $columnNo
* @param int $blockCount
* (no of blocks shown).
* @param NULL $exportMode
*/
public static function buildMappingForm(&$form, $mappingType, $mappingId, $columnNo, $blockCount, $exportMode = NULL) {
$hasLocationTypes = array();
$hasRelationTypes = array();
$fields = array();
//get the saved mapping details
if ($mappingType == 'Export') {
$columnCount = array('1' => $columnNo);
$form->applyFilter('saveMappingName', 'trim');
//to save the current mappings
if (!isset($mappingId)) {
$saveDetailsName = ts('Save this field mapping');
$form->add('text', 'saveMappingName', ts('Name'));
$form->add('text', 'saveMappingDesc', ts('Description'));
}
else {
$form->assign('loadedMapping', $mappingId);
$params = array('id' => $mappingId);
$temp = array();
$mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
$form->assign('savedName', $mappingDetails->name);
$form->add('hidden', 'mappingId', $mappingId);
$form->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
$saveDetailsName = ts('Save as a new field mapping');
$form->add('text', 'saveMappingName', ts('Name'));
$form->add('text', 'saveMappingDesc', ts('Description'));
}
$form->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
$form->addFormRule(array('CRM_Export_Form_Map', 'formRule'), $form->get('mappingTypeId'));
}
elseif ($mappingType == 'Search Builder') {
$columnCount = $columnNo;
$form->addElement('submit', 'addBlock', ts('Also include contacts where'),
array('class' => 'submit-link')
);
}
$contactType = array('Individual', 'Household', 'Organization');
foreach ($contactType as $value) {
if ($mappingType == 'Search Builder') {
// get multiple custom group fields in this context
$contactFields = CRM_Contact_BAO_Contact::exportableFields($value, FALSE, FALSE, FALSE, TRUE);
}
else {
$contactFields = CRM_Contact_BAO_Contact::exportableFields($value, FALSE, TRUE);
}
$contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook::singleton()->getFields());
// exclude the address options disabled in the Address Settings
$fields[$value] = CRM_Core_BAO_Address::validateAddressOptions($contactFields);
ksort($fields[$value]);
if ($mappingType == 'Export') {
$relationships = array();
$relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $value);
asort($relationshipTypes);
foreach ($relationshipTypes as $key => $var) {
list($type) = explode('_', $key);
$relationships[$key]['title'] = $var;
$relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
$relationships[$key]['export'] = TRUE;
$relationships[$key]['relationship_type_id'] = $type;
$relationships[$key]['related'] = TRUE;
$relationships[$key]['hasRelationType'] = 1;
}
if (!empty($relationships)) {
$fields[$value] = array_merge($fields[$value],
array('related' => array('title' => ts('- related contact info -'))),
$relationships
);
}
}
}
//get the current employer for mapping.
if ($mappingType == 'Export') {
$fields['Individual']['current_employer_id']['title'] = ts('Current Employer ID');
}
// add component fields
$compArray = array();
//we need to unset groups, tags, notes for component export
if ($exportMode != CRM_Export_Form_Select::CONTACT_EXPORT) {
foreach (array(
'groups',
'tags',
'notes',
) as $value) {
unset($fields['Individual'][$value]);
unset($fields['Household'][$value]);
unset($fields['Organization'][$value]);
}
}
if ($mappingType == 'Search Builder') {
//build the common contact fields array.
$fields['Contact'] = array();
foreach ($fields['Individual'] as $key => $value) {
if (!empty($fields['Household'][$key]) && !empty($fields['Organization'][$key])) {
$fields['Contact'][$key] = $value;
unset($fields['Organization'][$key],
$fields['Household'][$key],
$fields['Individual'][$key]);
}
}
if (array_key_exists('note', $fields['Contact'])) {
$noteTitle = $fields['Contact']['note']['title'];
$fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
$fields['Contact']['note_body'] = array('title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body');
$fields['Contact']['note_subject'] = array(
'title' => $noteTitle . ': ' . ts('Subject Only'),
'name' => 'note_subject',
);
}
}
if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT)) {
if (CRM_Core_Permission::access('CiviContribute')) {
$fields['Contribution'] = CRM_Contribute_BAO_Contribution::exportableFields();
unset($fields['Contribution']['contribution_contact_id']);
$compArray['Contribution'] = ts('Contribution');
}
}
if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT)) {
if (CRM_Core_Permission::access('CiviEvent')) {
$fields['Participant'] = CRM_Event_BAO_Participant::exportableFields();
//get the component payment fields
if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
$componentPaymentFields = array();
foreach (CRM_Export_BAO_Export::componentPaymentFields() as $payField => $payTitle) {
$componentPaymentFields[$payField] = array('title' => $payTitle);
}
$fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
}
$compArray['Participant'] = ts('Participant');
}
}
if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT)) {
if (CRM_Core_Permission::access('CiviMember')) {
$fields['Membership'] = CRM_Member_BAO_Membership::getMembershipFields($exportMode);
unset($fields['Membership']['membership_contact_id']);
$compArray['Membership'] = ts('Membership');
}
}
if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT)) {
if (CRM_Core_Permission::access('CiviPledge')) {
$fields['Pledge'] = CRM_Pledge_BAO_Pledge::exportableFields();
unset($fields['Pledge']['pledge_contact_id']);
$compArray['Pledge'] = ts('Pledge');
}
}
if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::CASE_EXPORT)) {
if (CRM_Core_Permission::access('CiviCase')) {
$fields['Case'] = CRM_Case_BAO_Case::exportableFields();
$compArray['Case'] = ts('Case');
$fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Case');
$compArray['Activity'] = ts('Case Activity');
unset($fields['Case']['case_contact_id']);
}
}
if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT)) {
if (CRM_Core_Permission::access('CiviGrant')) {
$fields['Grant'] = CRM_Grant_BAO_Grant::exportableFields();
unset($fields['Grant']['grant_contact_id']);
if ($mappingType == 'Search Builder') {
unset($fields['Grant']['grant_type_id']);
}
$compArray['Grant'] = ts('Grant');
}
}
if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT)) {
$fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Activity');
$compArray['Activity'] = ts('Activity');
}
//Contact Sub Type For export
$contactSubTypes = array();
$subTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
foreach ($subTypes as $subType => $val) {
//adding subtype specific relationships CRM-5256
$csRelationships = array();
if ($mappingType == 'Export') {
$subTypeRelationshipTypes
= CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'],
FALSE, 'label', TRUE, $subType);
foreach ($subTypeRelationshipTypes as $key => $var) {
if (!array_key_exists($key, $fields[$val['parent']])) {
list($type) = explode('_', $key);
$csRelationships[$key]['title'] = $var;
$csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
$csRelationships[$key]['export'] = TRUE;
$csRelationships[$key]['relationship_type_id'] = $type;
$csRelationships[$key]['related'] = TRUE;
$csRelationships[$key]['hasRelationType'] = 1;
}
}
}
$fields[$subType] = $fields[$val['parent']] + $csRelationships;
//custom fields for sub type
$subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($subType);
$fields[$subType] += $subTypeFields;
if (!empty($subTypeFields) || !empty($csRelationships)) {
$contactSubTypes[$subType] = $val['label'];
}
}
foreach ($fields as $key => $value) {
foreach ($value as $key1 => $value1) {
//CRM-2676, replacing the conflict for same custom field name from different custom group.
$customGroupName = self::getCustomGroupName($key1);
if ($customGroupName) {
$relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title'];
}
else {
$relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title'];
}
if (isset($value1['hasLocationType'])) {
$hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
}
if (isset($value1['hasRelationType'])) {
$hasRelationTypes[$key][$key1] = $value1['hasRelationType'];
unset($relatedMapperFields[$key][$key1]);
}
}
if (array_key_exists('related', $relatedMapperFields[$key])) {
unset($relatedMapperFields[$key]['related']);
}
}
$locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
$defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
// FIXME: dirty hack to make the default option show up first. This
// avoids a mozilla browser bug with defaults on dynamically constructed
// selector widgets.
if ($defaultLocationType) {
$defaultLocation = $locationTypes[$defaultLocationType->id];
unset($locationTypes[$defaultLocationType->id]);
$locationTypes = array($defaultLocationType->id => $defaultLocation) + $locationTypes;
}
$locationTypes = array(' ' => ts('Primary')) + $locationTypes;
// since we need a hierarchical list to display contact types & subtypes,
// this is what we going to display in first selector
$contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE);
if ($mappingType == 'Search Builder') {
$contactTypes = array('Contact' => ts('Contacts')) + $contactTypes;
}
$sel1 = array('' => ts('- select record type -')) + $contactTypes + $compArray;
foreach ($sel1 as $key => $sel) {
if ($key) {
// sort everything BUT the contactType which is sorted separately by
// an initial commit of CRM-13278 (check ksort above)
if (!in_array($key, $contactType)) {
asort($mapperFields[$key]);
}
$sel2[$key] = array('' => ts('- select field -')) + $mapperFields[$key];
}
}
$sel3[''] = NULL;
$sel5[''] = NULL;
$phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
$imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
asort($phoneTypes);
foreach ($sel1 as $k => $sel) {
if ($k) {
foreach ($locationTypes as $key => $value) {
if (trim($key) != '') {
$sel4[$k]['phone'][$key] = &$phoneTypes;
$sel4[$k]['im'][$key] = &$imProviders;
}
}
}
}
foreach ($sel1 as $k => $sel) {
if ($k) {
foreach ($mapperFields[$k] as $key => $value) {
if (isset($hasLocationTypes[$k][$key])) {
$sel3[$k][$key] = $locationTypes;
}
else {
$sel3[$key] = NULL;
}
}
}
}
// Array for core fields and relationship custom data
$relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
if ($mappingType == 'Export') {
foreach ($sel1 as $k => $sel) {
if ($k) {
foreach ($mapperFields[$k] as $field => $dontCare) {
if (isset($hasRelationTypes[$k][$field])) {
list($id, $first, $second) = explode('_', $field);
// FIX ME: For now let's not expose custom data related to relationship
$relationshipCustomFields = array();
//$relationshipCustomFields = self::getRelationTypeCustomGroupData( $id );
//asort($relationshipCustomFields);
$relationshipType = new CRM_Contact_BAO_RelationshipType();
$relationshipType->id = $id;
if ($relationshipType->find(TRUE)) {
$direction = "contact_sub_type_$second";
$target_type = 'contact_type_' . $second;
if (isset($relationshipType->$direction)) {
$relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->$direction], (array) $relationshipCustomFields);
}
elseif (isset($relationshipType->$target_type)) {
$relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->$target_type], (array) $relationshipCustomFields);
}
}
$relationshipType->free();
asort($relatedFields);
$sel5[$k][$field] = $relatedFields;
}
}
}
}
//Location Type for relationship fields
foreach ($sel5 as $k => $v) {
if ($v) {
foreach ($v as $rel => $fields) {
foreach ($fields as $field => $fieldLabel) {
if (isset($hasLocationTypes[$k][$field])) {
$sel6[$k][$rel][$field] = $locationTypes;
}
}
}
}
}
//PhoneTypes for relationship fields
$sel7[''] = NULL;
foreach ($sel6 as $k => $rel) {
if ($k) {
foreach ($rel as $phonekey => $phonevalue) {
foreach ($locationTypes as $locType => $loc) {
if (trim($locType) != '') {
$sel7[$k][$phonekey]['phone'][$locType] = &$phoneTypes;
$sel7[$k][$phonekey]['im'][$locType] = &$imProviders;
}
}
}
}
}
}
//special fields that have location, hack for primary location
$specialFields = array(
'street_address',
'supplemental_address_1',
'supplemental_address_2',
'city',
'postal_code',
'postal_code_suffix',
'geo_code_1',
'geo_code_2',
'state_province',
'country',
'phone',
'email',
'im',
);
if (isset($mappingId)) {
list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
$mappingRelation, $mappingOperator, $mappingValue
) = CRM_Core_BAO_Mapping::getMappingFields($mappingId);
$blkCnt = count($mappingName);
if ($blkCnt >= $blockCount) {
$blockCount = $blkCnt + 1;
}
for ($x = 1; $x < $blockCount; $x++) {
if (isset($mappingName[$x])) {
$colCnt = count($mappingName[$x]);
if ($colCnt >= $columnCount[$x]) {
$columnCount[$x] = $colCnt;
}
}
}
}
$form->_blockCount = $blockCount;
$form->_columnCount = $columnCount;
$form->set('blockCount', $form->_blockCount);
$form->set('columnCount', $form->_columnCount);
$defaults = $noneArray = $nullArray = array();
for ($x = 1; $x < $blockCount; $x++) {
for ($i = 0; $i < $columnCount[$x]; $i++) {
$sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
$jsSet = FALSE;
if (isset($mappingId)) {
$locationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0;
if (isset($mappingName[$x][$i])) {
if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
if (isset($mappingRelation[$x][$i])) {
$relLocationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0;
if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
$relLocationId = " ";
}
$relPhoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
$defaults["mapper[$x][$i]"] = array(
$mappingContactType[$x][$i],
$mappingRelation[$x][$i],
$locationId,
$phoneType,
$mappingName[$x][$i],
$relLocationId,
$relPhoneType,
);
if (!$locationId) {
$noneArray[] = array($x, $i, 2);
}
if (!$phoneType && !$imProvider) {
$noneArray[] = array($x, $i, 3);
}
if (!$mappingName[$x][$i]) {
$noneArray[] = array($x, $i, 4);
}
if (!$relLocationId) {
$noneArray[] = array($x, $i, 5);
}
if (!$relPhoneType) {
$noneArray[] = array($x, $i, 6);
}
$noneArray[] = array($x, $i, 2);
}
else {
$phoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
$imProvider = isset($mappingImProvider[$x][$i]) ? $mappingImProvider[$x][$i] : NULL;
if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
$locationId = " ";
}
$defaults["mapper[$x][$i]"] = array(
$mappingContactType[$x][$i],
$mappingName[$x][$i],
$locationId,
$phoneType,
);
if (!$mappingName[$x][$i]) {
$noneArray[] = array($x, $i, 1);
}
if (!$locationId) {
$noneArray[] = array($x, $i, 2);
}
if (!$phoneType && !$imProvider) {
$noneArray[] = array($x, $i, 3);
}
$noneArray[] = array($x, $i, 4);
$noneArray[] = array($x, $i, 5);
$noneArray[] = array($x, $i, 6);
}
$jsSet = TRUE;
if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingOperator))) {
$defaults["operator[$x][$i]"] = CRM_Utils_Array::value($i, $mappingOperator[$x]);
}
if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingValue))) {
$defaults["value[$x][$i]"] = CRM_Utils_Array::value($i, $mappingValue[$x]);
}
}
}
}
//Fix for Search Builder
if ($mappingType == 'Export') {
$j = 7;
}
else {
$j = 4;
}
$formValues = $form->exportValues();
if (!$jsSet) {
if (empty($formValues)) {
// Incremented length for third select box(relationship type)
for ($k = 1; $k < $j; $k++) {
$noneArray[] = array($x, $i, $k);
}
}
else {
if (!empty($formValues['mapper'][$x])) {
foreach ($formValues['mapper'][$x] as $value) {
for ($k = 1; $k < $j; $k++) {
if (!isset($formValues['mapper'][$x][$i][$k]) ||
(!$formValues['mapper'][$x][$i][$k])
) {
$noneArray[] = array($x, $i, $k);
}
else {
$nullArray[] = array($x, $i, $k);
}
}
}
}
else {
for ($k = 1; $k < $j; $k++) {
$noneArray[] = array($x, $i, $k);
}
}
}
}
//Fix for Search Builder
if ($mappingType == 'Export') {
if (!isset($mappingId) || $i >= count(reset($mappingName))) {
if (isset($formValues['mapper']) &&
isset($formValues['mapper'][$x][$i][1]) &&
array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)
) {
$sel->setOptions(array($sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4));
}
else {
$sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
}
}
else {
$sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
}
}
else {
$sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
}
if ($mappingType == 'Search Builder') {
//CRM -2292, restricted array set
$operatorArray = array('' => ts('-operator-')) + CRM_Core_SelectValues::getSearchBuilderOperators();
$form->add('select', "operator[$x][$i]", '', $operatorArray);
$form->add('text', "value[$x][$i]", '');
}
}
//end of columnCnt for
if ($mappingType == 'Search Builder') {
$title = ts('Another search field');
}
else {
$title = ts('Select more fields');
}
$form->addElement('submit', "addMore[$x]", $title, array('class' => 'submit-link'));
}
//end of block for
$js = "<script type='text/javascript'>\n";
$formName = "document." . (($mappingType == 'Export') ? 'Map' : 'Builder');
if (!empty($nullArray)) {
$js .= "var nullArray = [";
$elements = array();
$seen = array();
foreach ($nullArray as $element) {
$key = "{$element[0]}, {$element[1]}, {$element[2]}";
if (!isset($seen[$key])) {
$elements[] = "[$key]";
$seen[$key] = 1;
}
}
$js .= implode(', ', $elements);
$js .= "]";
$js .= "
for (var i=0;i<nullArray.length;i++) {
if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {
{$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';
}
}
";
}
if (!empty($noneArray)) {
$js .= "var noneArray = [";
$elements = array();
$seen = array();
foreach ($noneArray as $element) {
$key = "{$element[0]}, {$element[1]}, {$element[2]}";
if (!isset($seen[$key])) {
$elements[] = "[$key]";
$seen[$key] = 1;
}
}
$js .= implode(', ', $elements);
$js .= "]";
$js .= "
for (var i=0;i<noneArray.length;i++) {
if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {
{$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';
}
}
";
}
$js .= "</script>\n";
$form->assign('initHideBoxes', $js);
$form->assign('columnCount', $columnCount);
$form->assign('blockCount', $blockCount);
$form->setDefaults($defaults);
$form->setDefaultAction('refresh');
}
/**
* Function returns all custom fields with group title and
* field label
*
* @param int $relationshipTypeId
* Related relationship type id.
*
* @return array
* all custom field titles
*/
public function getRelationTypeCustomGroupData($relationshipTypeId) {
$customFields = CRM_Core_BAO_CustomField::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
$groupTitle = array();
foreach ($customFields as $krelation => $vrelation) {
$groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
}
return $groupTitle;
}
/**
* Function returns all Custom group Names.
*
* @param int $customfieldId
* Related file id.
*
* @return null|string
* $customGroupName all custom group names
*/
public static function getCustomGroupName($customfieldId) {
if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($customfieldId)) {
$customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
$customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
if (strlen($customGroupName) > 13) {
$customGroupName = substr($customGroupName, 0, 10) . '...';
}
return $customGroupName;
}
}
/**
* Function returns associated array of elements, that will be passed for search
*
* @param array $params
* Associated array of submitted values.
* @param bool $row
* Row no of the fields.
*
*
* @return array
* formatted associated array of elements
*/
public static function formattedFields(&$params, $row = FALSE) {
$fields = array();
if (empty($params) || !isset($params['mapper'])) {
return $fields;
}
$types = array('Individual', 'Organization', 'Household');
foreach ($params['mapper'] as $key => $value) {
$contactType = NULL;
foreach ($value as $k => $v) {
if (in_array($v[0], $types)) {
if ($contactType && $contactType != $v[0]) {
CRM_Core_Error::fatal(ts("Cannot have two clauses with different types: %1, %2",
array(1 => $contactType, 2 => $v[0])
));
}
$contactType = $v[0];
}
if (!empty($v['1'])) {
$fldName = $v[1];
$v2 = CRM_Utils_Array::value('2', $v);
if ($v2 && trim($v2)) {
$fldName .= "-{$v[2]}";
}
$v3 = CRM_Utils_Array::value('3', $v);
if ($v3 && trim($v3)) {
$fldName .= "-{$v[3]}";
}
$value = $params['value'][$key][$k];
if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_'
&& substr($fldName, 0, 10) != 'financial_'
&& substr($fldName, 0, 8) != 'payment_') {
if (substr($fldName, 0, 13) != 'contribution_') {
$fldName = 'contribution_' . $fldName;
}
}
// CRM-14983: verify if values are comma separated convert to array
if (!is_array($value) && strstr($params['operator'][$key][$k], 'IN')) {
$value = explode(',', $value);
$value = array($params['operator'][$key][$k] => $value);
}
if ($row) {
$fields[] = array(
$fldName,
$params['operator'][$key][$k],
$value,
$key,
$k,
);
}
else {
$fields[] = array(
$fldName,
$params['operator'][$key][$k],
$value,
$key,
0,
);
}
}
}
if ($contactType) {
$fields[] = array(
'contact_type',
'=',
$contactType,
$key,
0,
);
}
}
//add sortByCharacter values
if (isset($params['sortByCharacter'])) {
$fields[] = array(
'sortByCharacter',
'=',
$params['sortByCharacter'],
0,
0,
);
}
return $fields;
}
/**
* @param array $params
*
* @return array
*/
public static function &returnProperties(&$params) {
$fields = array(
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
);
if (empty($params) || empty($params['mapper'])) {
return $fields;
}
$locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
foreach ($params['mapper'] as $key => $value) {
foreach ($value as $k => $v) {
if (isset($v[1])) {
if ($v[1] == 'groups' || $v[1] == 'tags') {
continue;
}
if (isset($v[2]) && is_numeric($v[2])) {
if (!array_key_exists('location', $fields)) {
$fields['location'] = array();
}
// make sure that we have a location fields and a location type for this
$locationName = $locationTypes[$v[2]];
if (!array_key_exists($locationName, $fields['location'])) {
$fields['location'][$locationName] = array();
$fields['location'][$locationName]['location_type'] = $v[2];
}
if ($v[1] == 'phone' || $v[1] == 'email' || $v[1] == 'im') {
// phone type handling
if (isset($v[3])) {
$fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
}
else {
$fields['location'][$locationName][$v[1]] = 1;
}
}
else {
$fields['location'][$locationName][$v[1]] = 1;
}
}
else {
$fields[$v[1]] = 1;
}
}
}
}
return $fields;
}
/**
* Save the mapping field info for search builder / export given the formvalues
*
* @param array $params
* Asscociated array of formvalues.
* @param int $mappingId
* Mapping id.
*
* @return NULL
*/
public static function saveMappingFields(&$params, $mappingId) {
//delete mapping fields records for exixting mapping
$mappingFields = new CRM_Core_DAO_MappingField();
$mappingFields->mapping_id = $mappingId;
$mappingFields->delete();
if (empty($params['mapper'])) {
return NULL;
}
//save record in mapping field table
foreach ($params['mapper'] as $key => $value) {
$colCnt = 0;
foreach ($value as $k => $v) {
if (!empty($v['1'])) {
$saveMappingFields = new CRM_Core_DAO_MappingField();
$saveMappingFields->mapping_id = $mappingId;
$saveMappingFields->name = CRM_Utils_Array::value('1', $v);
$saveMappingFields->contact_type = CRM_Utils_Array::value('0', $v);
$locationId = CRM_Utils_Array::value('2', $v);
$saveMappingFields->location_type_id = is_numeric($locationId) ? $locationId : NULL;
if ($v[1] == 'phone') {
$saveMappingFields->phone_type_id = CRM_Utils_Array::value('3', $v);
}
elseif ($v[1] == 'im') {
$saveMappingFields->im_provider_id = CRM_Utils_Array::value('3', $v);
}
if (!empty($params['operator'])) {
$saveMappingFields->operator = CRM_Utils_Array::value($k, $params['operator'][$key]);
}
if (!empty($params['value'])) {
$saveMappingFields->value = CRM_Utils_Array::value($k, $params['value'][$key]);
}
// Handle mapping for 'related contact' fields
if (count(explode('_', CRM_Utils_Array::value('1', $v))) > 2) {
list($id, $first, $second) = explode('_', CRM_Utils_Array::value('1', $v));
if (($first == 'a' && $second == 'b') || ($first == 'b' && $second == 'a')) {
if (!empty($v['2'])) {
$saveMappingFields->name = CRM_Utils_Array::value('2', $v);
}
elseif (!empty($v['4'])) {
$saveMappingFields->name = CRM_Utils_Array::value('4', $v);
}
if (is_numeric(CRM_Utils_Array::value('3', $v))) {
$locationTypeid = CRM_Utils_Array::value('3', $v);
}
elseif (is_numeric(CRM_Utils_Array::value('5', $v))) {
$locationTypeid = CRM_Utils_Array::value('5', $v);
}
if (is_numeric(CRM_Utils_Array::value('4', $v))) {
$phoneTypeid = CRM_Utils_Array::value('4', $v);
}
elseif (is_numeric(CRM_Utils_Array::value('6', $v))) {
$phoneTypeid = CRM_Utils_Array::value('6', $v);
}
$saveMappingFields->location_type_id = is_numeric($locationTypeid) ? $locationTypeid : NULL;
$saveMappingFields->phone_type_id = is_numeric($phoneTypeid) ? $phoneTypeid : NULL;
$saveMappingFields->relationship_type_id = $id;
$saveMappingFields->relationship_direction = "{$first}_{$second}";
}
}
$saveMappingFields->grouping = $key;
$saveMappingFields->column_number = $colCnt;
$saveMappingFields->save();
$colCnt++;
$locationTypeid = $phoneTypeid = NULL;
}
}
}
}
}
|
alfonsom/ccdrupal
|
sites/all/modules/civicrm/CRM/Core/BAO/Mapping.php
|
PHP
|
gpl-2.0
| 41,629 |
<?php
//Start session
session_start();
//Include database connection details
require_once('connection/config.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$name = clean($_POST['name']);
//define a default value for flag
$flag_0 = 0;
//Create INSERT query
$qry = "INSERT INTO currencies(currency_symbol,flag) VALUES('$name','$flag_0')";
$result = @mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: options.php");
exit();
}else {
die("Query failed " . mysql_error());
}
?>
|
Subh94/Hotel-Management-System
|
Restaurant/canteen/connection/admin/currencies-exec.php
|
PHP
|
gpl-2.0
| 1,246 |
/* mips.r3000-linux.elf-entry.h
created from mips.r3000-linux.elf-entry.bin, 9847 (0x2677) bytes
This file is part of the UPX executable compressor.
Copyright (C) 1996-2011 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1996-2011 Laszlo Molnar
Copyright (C) 2000-2011 John F. Reiser
All Rights Reserved.
UPX and the UCL library are free software; you can redistribute them
and/or modify them under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING.
If not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Markus F.X.J. Oberhumer Laszlo Molnar
<[email protected]> <[email protected]>
John F. Reiser
<[email protected]>
*/
#define STUB_MIPS_R3000_LINUX_ELF_ENTRY_SIZE 9847
#define STUB_MIPS_R3000_LINUX_ELF_ENTRY_ADLER32 0x36d02a72
#define STUB_MIPS_R3000_LINUX_ELF_ENTRY_CRC32 0x9c96ab6e
unsigned char stub_mips_r3000_linux_elf_entry[9847] = {
/* 0x0000 */ 127, 69, 76, 70, 1, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 0x0010 */ 0, 1, 0, 8, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
/* 0x0020 */ 0, 0, 28, 68, 0, 0, 0, 1, 0, 52, 0, 0, 0, 0, 0, 40,
/* 0x0030 */ 0, 22, 0, 19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 0x0040 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 17, 0, 48,
/* 0x0050 */ 39,247, 0, 0, 60, 13,128, 0, 1,160, 72, 33, 36, 11, 0, 1,
/* 0x0060 */ 4, 17, 0, 77, 36, 15, 0, 1, 17,192, 0, 5,144,142, 0, 0,
/* 0x0070 */ 36,132, 0, 1, 36,198, 0, 1, 16, 0,255,249,160,206,255,255,
/* 0x0080 */ 4, 17, 0, 69, 0, 15,120, 64, 4, 17, 0, 67, 1,238,120, 33,
/* 0x0090 */ 21,192, 0, 5, 37,238,255,254, 4, 17, 0, 63, 1,238,120, 33,
/* 0x00a0 */ 16, 0,255,247, 1,238,120, 33, 21,192, 0, 5, 37,239,255,253,
/* 0x00b0 */ 4, 17, 0, 57, 1, 96,120, 33, 16, 0, 0, 11, 49,204, 0, 1,
/* 0x00c0 */ 144,142, 0, 0, 0, 15,122, 0, 1,238,120, 33, 37,238, 0, 1,
/* 0x00d0 */ 17,192,255,255, 36,132, 0, 1, 0, 15,120, 66, 37,239, 0, 1,
/* 0x00e0 */ 1,224, 88, 33, 49,204, 0, 1, 4, 17, 0, 43, 0, 0, 0, 0,
/* 0x00f0 */ 21,128, 0, 12, 37,204,255,254, 17,192, 0, 5, 36, 12, 0, 1,
/* 0x0100 */ 4, 17, 0, 37, 0, 0, 0, 0, 16, 0, 0, 6, 1,192, 96, 33,
/* 0x0110 */ 4, 17, 0, 33, 0, 12, 96, 64, 4, 17, 0, 31, 1,142, 96, 33,
/* 0x0120 */ 17,192,255,251, 45,238, 5, 1, 37,140, 0, 5, 1,142, 96, 35,
/* 0x0130 */ 0,207,120, 35,145,238, 0, 0, 37,140,255,255, 37,239, 0, 1,
/* 0x0140 */ 36,198, 0, 1, 21,128,255,251,160,206,255,255, 16, 0,255,196,
/* 0x0150 */ 0, 0, 0, 0,136,137, 0, 0,152,137, 0, 3, 60, 1, 0,255,
/* 0x0160 */ 52, 33, 0,255, 0, 9,114, 2, 1,193,112, 36, 1, 33, 72, 36,
/* 0x0170 */ 0, 9, 74, 0, 1, 46, 72, 37, 0, 9,116, 2, 0, 9, 76, 0,
/* 0x0180 */ 1, 46, 72, 37, 36,132, 0, 4, 0, 9,119,194, 0, 9, 72, 64,
/* 0x0190 */ 3,224, 0, 8, 37, 41, 0, 1, 17,169,255,238, 0, 9,119,194,
/* 0x01a0 */ 3,224, 0, 8, 0, 9, 72, 64, 60, 13,128, 0, 1,160, 72, 33,
/* 0x01b0 */ 36, 11, 0, 1, 4, 17, 0, 73, 36, 15, 0, 1, 17,192, 0, 5,
/* 0x01c0 */ 144,142, 0, 0, 36,132, 0, 1, 36,198, 0, 1, 16, 0,255,249,
/* 0x01d0 */ 160,206,255,255, 4, 17, 0, 65, 0, 15,120, 64, 4, 17, 0, 63,
/* 0x01e0 */ 1,238,120, 33, 21,192, 0, 5, 37,238,255,254, 4, 17, 0, 59,
/* 0x01f0 */ 1,207,120, 33, 16, 0,255,247, 1,238,120, 33, 21,192, 0, 5,
/* 0x0200 */ 37,239,255,253, 4, 17, 0, 53, 1, 96,120, 33, 16, 0, 0, 11,
/* 0x0210 */ 49,204, 0, 1,144,142, 0, 0, 0, 15,122, 0, 1,238,120, 33,
/* 0x0220 */ 37,238, 0, 1, 17,192,255,255, 36,132, 0, 1, 0, 15,120, 66,
/* 0x0230 */ 37,239, 0, 1, 1,224, 88, 33, 49,204, 0, 1, 4, 17, 0, 39,
/* 0x0240 */ 0, 12, 96, 64, 1,142, 96, 33, 21,128, 0, 7, 37,140,255,254,
/* 0x0250 */ 36, 12, 0, 1, 4, 17, 0, 33, 0, 12, 96, 64, 4, 17, 0, 31,
/* 0x0260 */ 1,142, 96, 33, 17,192,255,251, 45,238, 5, 1, 37,140, 0, 4,
/* 0x0270 */ 1,142, 96, 35, 0,207,120, 35,145,238, 0, 0, 37,140,255,255,
/* 0x0280 */ 37,239, 0, 1, 36,198, 0, 1, 21,128,255,251,160,206,255,255,
/* 0x0290 */ 16, 0,255,200, 0, 0, 0, 0,136,137, 0, 0,152,137, 0, 3,
/* 0x02a0 */ 60, 1, 0,255, 52, 33, 0,255, 0, 9,114, 2, 1,193,112, 36,
/* 0x02b0 */ 1, 33, 72, 36, 0, 9, 74, 0, 1, 46, 72, 37, 0, 9,116, 2,
/* 0x02c0 */ 0, 9, 76, 0, 1, 46, 72, 37, 36,132, 0, 4, 0, 9,119,194,
/* 0x02d0 */ 0, 9, 72, 64, 3,224, 0, 8, 37, 41, 0, 1, 17,169,255,238,
/* 0x02e0 */ 0, 9,119,194, 3,224, 0, 8, 0, 9, 72, 64, 60, 13,128, 0,
/* 0x02f0 */ 1,160, 72, 33, 36, 11, 0, 1, 4, 17, 0, 66, 36, 15, 0, 1,
/* 0x0300 */ 17,192, 0, 5,144,142, 0, 0, 36,132, 0, 1, 36,198, 0, 1,
/* 0x0310 */ 16, 0,255,249,160,206,255,255, 4, 17, 0, 58, 0, 15,120, 64,
/* 0x0320 */ 4, 17, 0, 56, 1,238,120, 33, 17,192,255,251, 36, 14, 0, 2,
/* 0x0330 */ 21,238, 0, 3, 37,239,255,253, 16, 0, 0, 7, 1, 96,120, 33,
/* 0x0340 */ 144,142, 0, 0, 0, 15,122, 0, 1,238,120, 33, 37,239, 0, 1,
/* 0x0350 */ 17,224,255,255, 36,132, 0, 1, 4, 17, 0, 42, 1,224, 88, 33,
/* 0x0360 */ 1,192, 96, 33, 4, 17, 0, 39, 0, 12, 96, 64, 1,142, 96, 33,
/* 0x0370 */ 21,128, 0, 7, 37,140,255,254, 36, 12, 0, 1, 4, 17, 0, 33,
/* 0x0380 */ 0, 12, 96, 64, 4, 17, 0, 31, 1,142, 96, 33, 17,192,255,251,
/* 0x0390 */ 45,238, 13, 1, 37,140, 0, 4, 1,142, 96, 35, 0,207,120, 35,
/* 0x03a0 */ 145,238, 0, 0, 37,140,255,255, 37,239, 0, 1, 36,198, 0, 1,
/* 0x03b0 */ 21,128,255,251,160,206,255,255, 16, 0,255,207, 0, 0, 0, 0,
/* 0x03c0 */ 136,137, 0, 0,152,137, 0, 3, 60, 1, 0,255, 52, 33, 0,255,
/* 0x03d0 */ 0, 9,114, 2, 1,193,112, 36, 1, 33, 72, 36, 0, 9, 74, 0,
/* 0x03e0 */ 1, 46, 72, 37, 0, 9,116, 2, 0, 9, 76, 0, 1, 46, 72, 37,
/* 0x03f0 */ 36,132, 0, 4, 0, 9,119,194, 0, 9, 72, 64, 3,224, 0, 8,
/* 0x0400 */ 37, 41, 0, 1, 17,169,255,238, 0, 9,119,194, 3,224, 0, 8,
/* 0x0410 */ 0, 9, 72, 64,144,153, 0, 0, 36, 1,250, 0,144,152, 0, 1,
/* 0x0420 */ 51, 34, 0, 7, 0, 25,200,194, 3, 33, 8, 4, 36, 33,241, 96,
/* 0x0430 */ 3,161,232, 33,175,161, 0, 40, 39,170, 0, 32,175,191, 0, 44,
/* 0x0440 */ 140,233, 0, 0,175,166, 0, 36, 0,192, 64, 33, 39,167, 0, 28,
/* 0x0450 */ 36,166,255,254, 36,133, 0, 2, 39,164, 0, 48,160,130, 0, 2,
/* 0x0460 */ 51, 1, 0, 15,160,129, 0, 0, 0, 24,193, 2, 4, 17, 0, 16,
/* 0x0470 */ 160,152, 0, 1,175,162, 0, 28,143,164, 0, 36,143,165, 0, 32,
/* 0x0480 */ 36, 6, 0, 3, 36, 2, 16, 51, 0, 0, 0, 12,143,162, 0, 28,
/* 0x0490 */ 143,161, 0, 40,143,191, 0, 44, 3,161, 8, 35, 39,189, 0, 4,
/* 0x04a0 */ 23,161,255,254,175,160,255,252, 3,224, 0, 8, 0, 0, 0, 0,
/* 0x04b0 */ 39,189,255,200,175,183, 0, 52,175,182, 0, 48,175,181, 0, 44,
/* 0x04c0 */ 175,180, 0, 40,175,179, 0, 36,175,178, 0, 32,175,177, 0, 28,
/* 0x04d0 */ 175,176, 0, 24, 0,160,168, 33,175,167, 0, 12, 1, 0,152, 33,
/* 0x04e0 */ 175,169, 0, 16,175,170, 0, 20, 36,144, 0, 4,144,130, 0, 2,
/* 0x04f0 */ 36, 3, 0, 1, 0, 67, 16, 4, 36, 66,255,255,175,162, 0, 8,
/* 0x0500 */ 144,130, 0, 1, 0, 0, 0, 0, 0, 67, 16, 4, 36, 66,255,255,
/* 0x0510 */ 175,162, 0, 4,144,150, 0, 0,172,224, 0, 0,173, 64, 0, 0,
/* 0x0520 */ 144,132, 0, 1, 0, 0, 0, 0, 2,196, 32, 33, 36, 2, 3, 0,
/* 0x0530 */ 0,130, 32, 4, 36,132, 7, 54, 2, 0, 16, 33, 16, 0, 0, 4,
/* 0x0540 */ 0, 0, 88, 33, 36, 3, 4, 0,164, 67,255,254, 37,107, 0, 1,
/* 0x0550 */ 21,100,255,252, 36, 66, 0, 2, 2,166, 56, 33, 2,160,104, 33,
/* 0x0560 */ 0, 0,192, 33, 0, 0, 32, 33, 0,245, 16, 35, 16,130, 2,123,
/* 0x0570 */ 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37,
/* 0x0580 */ 36,132, 0, 1, 36, 2, 0, 5, 20,130,255,247, 37,173, 0, 1,
/* 0x0590 */ 0, 0, 80, 33, 0, 0,112, 33, 0, 0,144, 33, 36, 17, 0, 1,
/* 0x05a0 */ 36, 20, 0, 1, 36, 23, 0, 1,175,183, 0, 0, 16, 0, 2, 87,
/* 0x05b0 */ 36, 15,255,255, 52, 70,255,255, 0,207, 16, 43, 20, 64, 0, 8,
/* 0x05c0 */ 0, 0, 0, 0, 17,167, 2,101, 0, 15,122, 0, 0, 24, 26, 0,
/* 0x05d0 */ 145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1,
/* 0x05e0 */ 143,163, 0, 8, 0, 0, 0, 0, 1, 67, 40, 36, 0, 18,201, 0,
/* 0x05f0 */ 0,185, 16, 33, 0, 2, 16, 64, 2, 2, 88, 33,149, 99, 0, 0,
/* 0x0600 */ 0, 15, 18,194, 0, 67, 0, 24, 0, 0, 96, 18, 3, 12, 16, 43,
/* 0x0610 */ 16, 64, 0,125, 36, 2, 8, 0, 0, 67, 16, 35, 0, 2, 17, 67,
/* 0x0620 */ 0, 98, 16, 33,165, 98, 0, 0,143,163, 0, 4, 0, 0, 0, 0,
/* 0x0630 */ 1, 67, 16, 36, 2,194, 24, 4, 36, 2, 0, 8, 0, 86, 16, 35,
/* 0x0640 */ 0, 78, 16, 7, 0, 98, 16, 33, 0, 2, 26, 64, 0, 2, 18,192,
/* 0x0650 */ 0, 67, 16, 35, 2, 2, 16, 33, 36, 70, 14,108, 42, 66, 0, 7,
/* 0x0660 */ 16, 64, 0, 3, 1,128,120, 33, 16, 0, 0, 85, 36, 5, 0, 1,
/* 0x0670 */ 1, 81, 16, 35, 2, 98, 16, 33,144, 89, 0, 0, 36, 5, 0, 1,
/* 0x0680 */ 60, 2, 0,255, 52, 66,255,255, 0, 79, 16, 43, 20, 64, 0, 8,
/* 0x0690 */ 0, 0, 0, 0, 17,167, 2, 49, 0, 15,122, 0, 0, 24, 26, 0,
/* 0x06a0 */ 145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1,
/* 0x06b0 */ 0, 25,200, 64, 51, 44, 1, 0, 0, 12, 16, 64, 0,194, 16, 33,
/* 0x06c0 */ 0, 5,112, 64, 0, 78, 88, 33,149, 99, 2, 0, 0, 15, 18,194,
/* 0x06d0 */ 0, 67, 0, 24, 0, 0, 32, 18, 3, 4, 16, 43, 16, 64, 0, 9,
/* 0x06e0 */ 36, 2, 8, 0, 0, 67, 16, 35, 0, 2, 17, 67, 0, 98, 16, 33,
/* 0x06f0 */ 165, 98, 2, 0, 21,128, 0, 41, 1,192, 40, 33, 16, 0, 0, 9,
/* 0x0700 */ 0,128,120, 33, 1,228,120, 35, 3, 4,192, 35, 0, 3, 17, 66,
/* 0x0710 */ 0, 98, 16, 35,165, 98, 2, 0, 36,162, 0, 1, 17,128, 0, 40,
/* 0x0720 */ 0,162, 40, 33, 40,162, 1, 0, 16, 64, 0, 37, 60, 2, 0,255,
/* 0x0730 */ 16, 0,255,213, 52, 66,255,255, 52, 66,255,255, 0, 79, 16, 43,
/* 0x0740 */ 20, 64, 0, 9, 0, 5, 96, 64, 17,167, 2, 4, 0, 15,122, 0,
/* 0x0750 */ 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37,
/* 0x0760 */ 37,173, 0, 1, 0, 5, 96, 64, 0,204, 88, 33,149, 99, 0, 0,
/* 0x0770 */ 0, 15, 18,194, 0, 67, 0, 24, 0, 0, 32, 18, 3, 4, 16, 43,
/* 0x0780 */ 16, 64, 0, 8, 36, 2, 8, 0, 0, 67, 16, 35, 0, 2, 17, 67,
/* 0x0790 */ 0, 98, 16, 33,165, 98, 0, 0, 1,128, 40, 33, 16, 0, 0, 8,
/* 0x07a0 */ 0,128,120, 33, 1,228,120, 35, 3, 4,192, 35, 0, 3, 17, 66,
/* 0x07b0 */ 0, 98, 16, 35,165, 98, 0, 0, 36,162, 0, 1, 0,162, 40, 33,
/* 0x07c0 */ 40,162, 1, 0, 20, 64,255,220, 60, 2, 0,255, 48,174, 0,255,
/* 0x07d0 */ 2,106, 16, 33,160, 78, 0, 0, 42, 66, 0, 4, 16, 64, 0, 3,
/* 0x07e0 */ 37, 67, 0, 1, 16, 0, 1,200, 0, 0,144, 33, 42, 66, 0, 10,
/* 0x07f0 */ 16, 64, 0, 3, 0, 0, 0, 0, 16, 0, 1,195, 38, 82,255,253,
/* 0x0800 */ 16, 0, 1,193, 38, 82,255,250, 1,236, 32, 35, 0, 3, 17, 66,
/* 0x0810 */ 0, 98, 16, 35,165, 98, 0, 0, 0,196, 16, 43, 20, 64, 0, 8,
/* 0x0820 */ 3, 12,192, 35, 17,167, 1,205, 0, 4, 34, 0, 0, 24, 26, 0,
/* 0x0830 */ 145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1,
/* 0x0840 */ 0, 18, 16, 64, 2, 2,112, 33,149,195, 1,128, 0, 4, 18,194,
/* 0x0850 */ 0, 67, 0, 24, 0, 0, 96, 18, 3, 12, 16, 43, 16, 64, 0, 15,
/* 0x0860 */ 36, 2, 8, 0, 0, 67, 16, 35, 0, 2, 17, 67, 0, 98, 16, 33,
/* 0x0870 */ 165,194, 1,128, 42, 66, 0, 7, 20, 64, 0, 2, 0, 0,144, 33,
/* 0x0880 */ 36, 18, 0, 3, 38, 14, 6,100,175,183, 0, 0, 2,128,184, 33,
/* 0x0890 */ 2, 32,160, 33, 16, 0, 0,144, 1,128, 88, 33, 0,140, 88, 35,
/* 0x08a0 */ 0, 3, 17, 66, 0, 98, 16, 35,165,194, 1,128, 0,203, 16, 43,
/* 0x08b0 */ 20, 64, 0, 8, 3, 12,192, 35, 17,167, 1,168, 0, 11, 90, 0,
/* 0x08c0 */ 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37,
/* 0x08d0 */ 37,173, 0, 1,149,195, 1,152, 0, 11, 18,194, 0, 67, 0, 24,
/* 0x08e0 */ 0, 0, 32, 18, 3, 4, 16, 43, 16, 64, 0, 50, 36, 2, 8, 0,
/* 0x08f0 */ 0, 67, 16, 35, 0, 2, 17, 67, 0, 98, 16, 33,165,194, 1,152,
/* 0x0900 */ 60, 2, 1, 0, 0,130, 16, 43, 16, 64, 0, 8, 0,128, 88, 33,
/* 0x0910 */ 17,167, 1,146, 0, 4, 90, 0, 0, 24, 26, 0,145,162, 0, 0,
/* 0x0920 */ 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1, 0, 25, 16, 64,
/* 0x0930 */ 2, 2, 24, 33, 0, 5, 16, 64, 0, 98, 32, 33,148,131, 1,224,
/* 0x0940 */ 0, 11, 18,194, 0, 67, 0, 24, 0, 0, 96, 18, 3, 12, 16, 43,
/* 0x0950 */ 16, 64, 0, 18, 36, 2, 8, 0, 0, 67, 16, 35, 0, 2, 17, 67,
/* 0x0960 */ 0, 98, 16, 33, 17, 64, 1,125,164,130, 1,224, 42, 66, 0, 7,
/* 0x0970 */ 20, 64, 0, 2, 36, 18, 0, 9, 36, 18, 0, 11, 1, 81, 16, 35,
/* 0x0980 */ 2, 98, 16, 33,144, 78, 0, 0, 2,106, 16, 33,160, 78, 0, 0,
/* 0x0990 */ 37, 67, 0, 1, 16, 0, 1, 92, 1,128,120, 33, 1,108, 88, 35,
/* 0x09a0 */ 3, 12,192, 35, 0, 3, 17, 66, 0, 98, 16, 35, 16, 0, 0, 69,
/* 0x09b0 */ 164,130, 1,224, 1,100, 88, 35, 0, 3, 17, 66, 0, 98, 16, 35,
/* 0x09c0 */ 165,194, 1,152, 0,203, 16, 43, 20, 64, 0, 8, 3, 4,192, 35,
/* 0x09d0 */ 17,167, 1, 98, 0, 11, 90, 0, 0, 24, 26, 0,145,162, 0, 0,
/* 0x09e0 */ 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1,149,195, 1,176,
/* 0x09f0 */ 0, 11, 18,194, 0, 67, 0, 24, 0, 0, 32, 18, 3, 4, 16, 43,
/* 0x0a00 */ 16, 64, 0, 7, 36, 2, 8, 0, 0, 67, 16, 35, 0, 2, 17, 67,
/* 0x0a10 */ 0, 98, 16, 33,165,194, 1,176, 16, 0, 0, 28, 2,128, 16, 33,
/* 0x0a20 */ 1,100, 88, 35, 0, 3, 17, 66, 0, 98, 16, 35,165,194, 1,176,
/* 0x0a30 */ 0,203, 16, 43, 20, 64, 0, 8, 3, 4,192, 35, 17,167, 1, 71,
/* 0x0a40 */ 0, 11, 90, 0, 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0,
/* 0x0a50 */ 0, 98,192, 37, 37,173, 0, 1,149,195, 1,200, 0, 11, 18,194,
/* 0x0a60 */ 0, 67, 0, 24, 0, 0, 32, 18, 3, 4, 16, 43, 16, 64, 0, 11,
/* 0x0a70 */ 36, 2, 8, 0, 0, 67, 16, 35, 0, 2, 17, 67, 0, 98, 16, 33,
/* 0x0a80 */ 165,194, 1,200, 2,224, 16, 33, 2,128,184, 33, 2, 32,160, 33,
/* 0x0a90 */ 0, 64,136, 33, 16, 0, 0, 11, 0,128, 88, 33, 1,100, 88, 35,
/* 0x0aa0 */ 3, 4,192, 35, 0, 3, 17, 66, 0, 98, 16, 35,165,194, 1,200,
/* 0x0ab0 */ 143,162, 0, 0,175,183, 0, 0, 2,128,184, 33, 2, 32,160, 33,
/* 0x0ac0 */ 0, 64,136, 33, 42, 66, 0, 7, 20, 64, 0, 2, 36, 18, 0, 8,
/* 0x0ad0 */ 36, 18, 0, 11, 38, 14, 10,104, 60, 2, 0,255, 52, 76,255,255,
/* 0x0ae0 */ 1,139, 16, 43, 20, 64, 0, 8, 0, 0, 0, 0, 17,167, 1, 27,
/* 0x0af0 */ 0, 11, 90, 0, 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0,
/* 0x0b00 */ 0, 98,192, 37, 37,173, 0, 1,149,195, 0, 0, 0, 11, 18,194,
/* 0x0b10 */ 0, 67, 0, 24, 0, 0, 32, 18, 3, 4, 16, 43, 16, 64, 0, 12,
/* 0x0b20 */ 36, 2, 8, 0, 0, 67, 16, 35, 0, 2, 17, 67, 0, 98, 16, 33,
/* 0x0b30 */ 165,194, 0, 0, 0, 5, 17, 0, 1,194, 16, 33, 36, 69, 0, 4,
/* 0x0b40 */ 0,128,120, 33, 36, 8, 0, 3, 16, 0, 0, 41, 0, 0, 48, 33,
/* 0x0b50 */ 1,100, 88, 35, 0, 3, 17, 66, 0, 98, 16, 35,165,194, 0, 0,
/* 0x0b60 */ 1,139, 16, 43, 20, 64, 0, 8, 3, 4,192, 35, 17,167, 0,251,
/* 0x0b70 */ 0, 11, 90, 0, 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0,
/* 0x0b80 */ 0, 98,192, 37, 37,173, 0, 1,149,195, 0, 2, 0, 11, 18,194,
/* 0x0b90 */ 0, 67, 0, 24, 0, 0, 32, 18, 3, 4, 16, 43, 16, 64, 0, 12,
/* 0x0ba0 */ 36, 2, 8, 0, 0, 67, 16, 35, 0, 2, 17, 67, 0, 98, 16, 33,
/* 0x0bb0 */ 165,194, 0, 2, 0, 5, 17, 0, 1,194, 16, 33, 36, 69, 1, 4,
/* 0x0bc0 */ 0,128,120, 33, 36, 8, 0, 3, 16, 0, 0, 9, 36, 6, 0, 8,
/* 0x0bd0 */ 1,100,120, 35, 3, 4,192, 35, 0, 3, 17, 66, 0, 98, 16, 35,
/* 0x0be0 */ 165,194, 0, 2, 37,197, 2, 4, 36, 8, 0, 8, 36, 6, 0, 16,
/* 0x0bf0 */ 1, 0,112, 33, 36, 25, 0, 1, 60, 2, 0,255, 52, 66,255,255,
/* 0x0c00 */ 0, 79, 16, 43, 20, 64, 0, 9, 0, 25, 96, 64, 17,167, 0,211,
/* 0x0c10 */ 0, 15,122, 0, 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0,
/* 0x0c20 */ 0, 98,192, 37, 37,173, 0, 1, 0, 25, 96, 64, 0,172, 88, 33,
/* 0x0c30 */ 149, 99, 0, 0, 0, 15, 18,194, 0, 67, 0, 24, 0, 0, 32, 18,
/* 0x0c40 */ 3, 4, 16, 43, 16, 64, 0, 8, 36, 2, 8, 0, 0, 67, 16, 35,
/* 0x0c50 */ 0, 2, 17, 67, 0, 98, 16, 33,165, 98, 0, 0, 1,128,200, 33,
/* 0x0c60 */ 16, 0, 0, 8, 0,128,120, 33, 1,228,120, 35, 3, 4,192, 35,
/* 0x0c70 */ 0, 3, 17, 66, 0, 98, 16, 35,165, 98, 0, 0, 39, 34, 0, 1,
/* 0x0c80 */ 3, 34,200, 33, 37,206,255,255, 21,192,255,220, 60, 2, 0,255,
/* 0x0c90 */ 36, 2, 0, 1, 1, 2, 16, 4, 3, 34, 16, 35, 0, 70, 72, 33,
/* 0x0ca0 */ 42, 66, 0, 4, 16, 64, 0,134, 41, 34, 0, 4, 20, 64, 0, 2,
/* 0x0cb0 */ 1, 32, 24, 33, 36, 3, 0, 3, 0, 3, 17,192, 2, 2, 16, 33,
/* 0x0cc0 */ 36, 70, 3, 96, 36, 14, 0, 1, 36, 25, 0, 6, 60, 2, 0,255,
/* 0x0cd0 */ 52, 66,255,255, 0, 79, 16, 43, 20, 64, 0, 9, 0, 14, 96, 64,
/* 0x0ce0 */ 17,167, 0,158, 0, 15,122, 0, 0, 24, 26, 0,145,162, 0, 0,
/* 0x0cf0 */ 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1, 0, 14, 96, 64,
/* 0x0d00 */ 0,204, 88, 33,149, 99, 0, 0, 0, 15, 18,194, 0, 67, 0, 24,
/* 0x0d10 */ 0, 0, 32, 18, 3, 4, 16, 43, 16, 64, 0, 8, 36, 2, 8, 0,
/* 0x0d20 */ 0, 67, 16, 35, 0, 2, 17, 67, 0, 98, 16, 33,165, 98, 0, 0,
/* 0x0d30 */ 1,128,112, 33, 16, 0, 0, 8, 0,128,120, 33, 1,228,120, 35,
/* 0x0d40 */ 3, 4,192, 35, 0, 3, 17, 66, 0, 98, 16, 35,165, 98, 0, 0,
/* 0x0d50 */ 37,194, 0, 1, 1,194,112, 33, 39, 57,255,255, 23, 32,255,220,
/* 0x0d60 */ 60, 2, 0,255, 37,195,255,192, 40, 98, 0, 4, 20, 64, 0, 80,
/* 0x0d70 */ 0, 96,112, 33, 0, 3, 32, 67, 48, 98, 0, 1, 52, 75, 0, 2,
/* 0x0d80 */ 40, 98, 0, 14, 16, 64, 0, 8, 36,153,255,255, 3, 43,112, 4,
/* 0x0d90 */ 0, 14, 16, 64, 2, 2, 32, 33, 0, 3, 16, 64, 0,130, 16, 35,
/* 0x0da0 */ 16, 0, 0, 26, 36, 72, 5, 94, 36,132,255,251, 60, 2, 0,255,
/* 0x0db0 */ 52, 66,255,255, 0, 79, 16, 43, 20, 64, 0, 8, 0, 0, 0, 0,
/* 0x0dc0 */ 17,167, 0,102, 0, 15,122, 0, 0, 24, 26, 0,145,162, 0, 0,
/* 0x0dd0 */ 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1, 0, 15,120, 66,
/* 0x0de0 */ 3, 15, 16, 43, 20, 64, 0, 3, 0, 11, 88, 64, 3, 15,192, 35,
/* 0x0df0 */ 53,107, 0, 1, 36,132,255,255, 20,128,255,237, 60, 2, 0,255,
/* 0x0e00 */ 38, 8, 6, 68, 0, 11,113, 0, 36, 25, 0, 4, 36, 6, 0, 1,
/* 0x0e10 */ 36, 5, 0, 1, 60, 2, 0,255, 52, 66,255,255, 0, 79, 16, 43,
/* 0x0e20 */ 20, 64, 0, 9, 0, 5, 96, 64, 17,167, 0, 76, 0, 15,122, 0,
/* 0x0e30 */ 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37,
/* 0x0e40 */ 37,173, 0, 1, 0, 5, 96, 64, 1, 12, 88, 33,149, 99, 0, 0,
/* 0x0e50 */ 0, 15, 18,194, 0, 67, 0, 24, 0, 0, 32, 18, 3, 4, 16, 43,
/* 0x0e60 */ 16, 64, 0, 8, 36, 2, 8, 0, 0, 67, 16, 35, 0, 2, 17, 67,
/* 0x0e70 */ 0, 98, 16, 33,165, 98, 0, 0, 1,128, 40, 33, 16, 0, 0, 9,
/* 0x0e80 */ 0,128,120, 33, 1,228,120, 35, 3, 4,192, 35, 0, 3, 17, 66,
/* 0x0e90 */ 0, 98, 16, 35,165, 98, 0, 0, 36,162, 0, 1, 0,162, 40, 33,
/* 0x0ea0 */ 1,198,112, 37, 39, 57,255,255, 23, 32,255,218, 0, 6, 48, 64,
/* 0x0eb0 */ 37,209, 0, 1, 18, 32, 0, 26, 60, 2, 0,255, 38, 82, 0, 7,
/* 0x0ec0 */ 1, 81, 16, 43, 20, 64, 0, 38, 36, 2, 0, 1, 1, 81, 16, 35,
/* 0x0ed0 */ 2, 98, 88, 33, 2,106, 32, 33, 1, 64, 24, 33,145,110, 0, 0,
/* 0x0ee0 */ 36, 99, 0, 1, 1, 73, 16, 33, 36, 66, 0, 2, 16, 98, 0, 6,
/* 0x0ef0 */ 160,142, 0, 0, 37,107, 0, 1,143,162, 0, 16, 0, 0, 0, 0,
/* 0x0f00 */ 20, 98,255,246, 36,132, 0, 1, 0, 96, 80, 33,143,163, 0, 16,
/* 0x0f10 */ 0, 0, 0, 0, 1, 67, 16, 43, 20, 64,253,166, 60, 2, 0,255,
/* 0x0f20 */ 52, 66,255,255, 0, 79, 16, 43, 20, 64, 0, 4, 1,181, 40, 35,
/* 0x0f30 */ 17,167, 0, 10, 37,173, 0, 1, 1,181, 40, 35,143,162, 0, 12,
/* 0x0f40 */ 0, 0, 0, 0,172, 69, 0, 0,143,163, 0, 20, 0, 0, 0, 0,
/* 0x0f50 */ 172,106, 0, 0, 16, 0, 0, 2, 0, 0, 16, 33, 36, 2, 0, 1,
/* 0x0f60 */ 143,183, 0, 52,143,182, 0, 48,143,181, 0, 44,143,180, 0, 40,
/* 0x0f70 */ 143,179, 0, 36,143,178, 0, 32,143,177, 0, 28,143,176, 0, 24,
/* 0x0f80 */ 3,224, 0, 8, 39,189, 0, 56, 39,189,255,200,175,183, 0, 52,
/* 0x0f90 */ 175,182, 0, 48,175,181, 0, 44,175,180, 0, 40,175,179, 0, 36,
/* 0x0fa0 */ 175,178, 0, 32,175,177, 0, 28,175,176, 0, 24, 0,160,168, 33,
/* 0x0fb0 */ 175,167, 0, 12, 1, 0,152, 33,175,169, 0, 16,175,170, 0, 20,
/* 0x0fc0 */ 36,144, 0, 4,144,130, 0, 2, 36, 3, 0, 1, 0, 67, 16, 4,
/* 0x0fd0 */ 36, 66,255,255,175,162, 0, 8,144,130, 0, 1, 0, 0, 0, 0,
/* 0x0fe0 */ 0, 67, 16, 4, 36, 66,255,255,175,162, 0, 4,144,150, 0, 0,
/* 0x0ff0 */ 172,224, 0, 0,173, 64, 0, 0,144,132, 0, 1, 0, 0, 0, 0,
/* 0x1000 */ 2,196, 32, 33, 36, 2, 3, 0, 0,130, 32, 4, 36,132, 7, 54,
/* 0x1010 */ 2, 0, 16, 33, 16, 0, 0, 4, 0, 0, 88, 33, 36, 3, 4, 0,
/* 0x1020 */ 164, 67,255,254, 37,107, 0, 1, 21,100,255,252, 36, 66, 0, 2,
/* 0x1030 */ 2,166, 56, 33, 2,160,104, 33, 0, 0,192, 33, 0, 0, 32, 33,
/* 0x1040 */ 0,245, 16, 35, 16,130, 2,123, 0, 24, 26, 0,145,162, 0, 0,
/* 0x1050 */ 0, 0, 0, 0, 0, 98,192, 37, 36,132, 0, 1, 36, 2, 0, 5,
/* 0x1060 */ 20,130,255,247, 37,173, 0, 1, 0, 0, 80, 33, 0, 0,112, 33,
/* 0x1070 */ 0, 0,144, 33, 36, 17, 0, 1, 36, 20, 0, 1, 36, 23, 0, 1,
/* 0x1080 */ 175,183, 0, 0, 16, 0, 2, 87, 36, 15,255,255, 52, 70,255,255,
/* 0x1090 */ 0,207, 16, 43, 20, 64, 0, 8, 0, 0, 0, 0, 17,167, 2,101,
/* 0x10a0 */ 0, 15,122, 0, 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0,
/* 0x10b0 */ 0, 98,192, 37, 37,173, 0, 1,143,163, 0, 8, 0, 0, 0, 0,
/* 0x10c0 */ 1, 67, 40, 36, 0, 18,201, 0, 0,185, 16, 33, 0, 2, 16, 64,
/* 0x10d0 */ 2, 2, 88, 33,149, 99, 0, 0, 0, 15, 18,194, 0, 67, 0, 24,
/* 0x10e0 */ 0, 0, 96, 18, 3, 12, 16, 43, 16, 64, 0,125, 36, 2, 8, 0,
/* 0x10f0 */ 0, 67, 16, 35, 0, 2, 17, 67, 0, 98, 16, 33,165, 98, 0, 0,
/* 0x1100 */ 143,163, 0, 4, 0, 0, 0, 0, 1, 67, 16, 36, 2,194, 24, 4,
/* 0x1110 */ 36, 2, 0, 8, 0, 86, 16, 35, 0, 78, 16, 7, 0, 98, 16, 33,
/* 0x1120 */ 0, 2, 26, 64, 0, 2, 18,192, 0, 67, 16, 35, 2, 2, 16, 33,
/* 0x1130 */ 36, 70, 14,108, 42, 66, 0, 7, 16, 64, 0, 3, 1,128,120, 33,
/* 0x1140 */ 16, 0, 0, 85, 36, 5, 0, 1, 1, 81, 16, 35, 2, 98, 16, 33,
/* 0x1150 */ 144, 89, 0, 0, 36, 5, 0, 1, 60, 2, 0,255, 52, 66,255,255,
/* 0x1160 */ 0, 79, 16, 43, 20, 64, 0, 8, 0, 0, 0, 0, 17,167, 2, 49,
/* 0x1170 */ 0, 15,122, 0, 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0,
/* 0x1180 */ 0, 98,192, 37, 37,173, 0, 1, 0, 25,200, 64, 51, 44, 1, 0,
/* 0x1190 */ 0, 12, 16, 64, 0,194, 16, 33, 0, 5,112, 64, 0, 78, 88, 33,
/* 0x11a0 */ 149, 99, 2, 0, 0, 15, 18,194, 0, 67, 0, 24, 0, 0, 32, 18,
/* 0x11b0 */ 3, 4, 16, 43, 16, 64, 0, 9, 36, 2, 8, 0, 0, 67, 16, 35,
/* 0x11c0 */ 0, 2, 17, 67, 0, 98, 16, 33,165, 98, 2, 0, 21,128, 0, 41,
/* 0x11d0 */ 1,192, 40, 33, 16, 0, 0, 9, 0,128,120, 33, 1,228,120, 35,
/* 0x11e0 */ 3, 4,192, 35, 0, 3, 17, 66, 0, 98, 16, 35,165, 98, 2, 0,
/* 0x11f0 */ 36,162, 0, 1, 17,128, 0, 40, 0,162, 40, 33, 40,162, 1, 0,
/* 0x1200 */ 16, 64, 0, 37, 60, 2, 0,255, 16, 0,255,213, 52, 66,255,255,
/* 0x1210 */ 52, 66,255,255, 0, 79, 16, 43, 20, 64, 0, 9, 0, 5, 96, 64,
/* 0x1220 */ 17,167, 2, 4, 0, 15,122, 0, 0, 24, 26, 0,145,162, 0, 0,
/* 0x1230 */ 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1, 0, 5, 96, 64,
/* 0x1240 */ 0,204, 88, 33,149, 99, 0, 0, 0, 15, 18,194, 0, 67, 0, 24,
/* 0x1250 */ 0, 0, 32, 18, 3, 4, 16, 43, 16, 64, 0, 8, 36, 2, 8, 0,
/* 0x1260 */ 0, 67, 16, 35, 0, 2, 17, 67, 0, 98, 16, 33,165, 98, 0, 0,
/* 0x1270 */ 1,128, 40, 33, 16, 0, 0, 8, 0,128,120, 33, 1,228,120, 35,
/* 0x1280 */ 3, 4,192, 35, 0, 3, 17, 66, 0, 98, 16, 35,165, 98, 0, 0,
/* 0x1290 */ 36,162, 0, 1, 0,162, 40, 33, 40,162, 1, 0, 20, 64,255,220,
/* 0x12a0 */ 60, 2, 0,255, 48,174, 0,255, 2,106, 16, 33,160, 78, 0, 0,
/* 0x12b0 */ 42, 66, 0, 4, 16, 64, 0, 3, 37, 67, 0, 1, 16, 0, 1,200,
/* 0x12c0 */ 0, 0,144, 33, 42, 66, 0, 10, 16, 64, 0, 3, 0, 0, 0, 0,
/* 0x12d0 */ 16, 0, 1,195, 38, 82,255,253, 16, 0, 1,193, 38, 82,255,250,
/* 0x12e0 */ 1,236, 32, 35, 0, 3, 17, 66, 0, 98, 16, 35,165, 98, 0, 0,
/* 0x12f0 */ 0,196, 16, 43, 20, 64, 0, 8, 3, 12,192, 35, 17,167, 1,205,
/* 0x1300 */ 0, 4, 34, 0, 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0,
/* 0x1310 */ 0, 98,192, 37, 37,173, 0, 1, 0, 18, 16, 64, 2, 2,112, 33,
/* 0x1320 */ 149,195, 1,128, 0, 4, 18,194, 0, 67, 0, 24, 0, 0, 96, 18,
/* 0x1330 */ 3, 12, 16, 43, 16, 64, 0, 15, 36, 2, 8, 0, 0, 67, 16, 35,
/* 0x1340 */ 0, 2, 17, 67, 0, 98, 16, 33,165,194, 1,128, 42, 66, 0, 7,
/* 0x1350 */ 20, 64, 0, 2, 0, 0,144, 33, 36, 18, 0, 3, 38, 14, 6,100,
/* 0x1360 */ 175,183, 0, 0, 2,128,184, 33, 2, 32,160, 33, 16, 0, 0,144,
/* 0x1370 */ 1,128, 88, 33, 0,140, 88, 35, 0, 3, 17, 66, 0, 98, 16, 35,
/* 0x1380 */ 165,194, 1,128, 0,203, 16, 43, 20, 64, 0, 8, 3, 12,192, 35,
/* 0x1390 */ 17,167, 1,168, 0, 11, 90, 0, 0, 24, 26, 0,145,162, 0, 0,
/* 0x13a0 */ 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1,149,195, 1,152,
/* 0x13b0 */ 0, 11, 18,194, 0, 67, 0, 24, 0, 0, 32, 18, 3, 4, 16, 43,
/* 0x13c0 */ 16, 64, 0, 50, 36, 2, 8, 0, 0, 67, 16, 35, 0, 2, 17, 67,
/* 0x13d0 */ 0, 98, 16, 33,165,194, 1,152, 60, 2, 1, 0, 0,130, 16, 43,
/* 0x13e0 */ 16, 64, 0, 8, 0,128, 88, 33, 17,167, 1,146, 0, 4, 90, 0,
/* 0x13f0 */ 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37,
/* 0x1400 */ 37,173, 0, 1, 0, 25, 16, 64, 2, 2, 24, 33, 0, 5, 16, 64,
/* 0x1410 */ 0, 98, 32, 33,148,131, 1,224, 0, 11, 18,194, 0, 67, 0, 24,
/* 0x1420 */ 0, 0, 96, 18, 3, 12, 16, 43, 16, 64, 0, 18, 36, 2, 8, 0,
/* 0x1430 */ 0, 67, 16, 35, 0, 2, 17, 67, 0, 98, 16, 33, 17, 64, 1,125,
/* 0x1440 */ 164,130, 1,224, 42, 66, 0, 7, 20, 64, 0, 2, 36, 18, 0, 9,
/* 0x1450 */ 36, 18, 0, 11, 1, 81, 16, 35, 2, 98, 16, 33,144, 78, 0, 0,
/* 0x1460 */ 2,106, 16, 33,160, 78, 0, 0, 37, 67, 0, 1, 16, 0, 1, 92,
/* 0x1470 */ 1,128,120, 33, 1,108, 88, 35, 3, 12,192, 35, 0, 3, 17, 66,
/* 0x1480 */ 0, 98, 16, 35, 16, 0, 0, 69,164,130, 1,224, 1,100, 88, 35,
/* 0x1490 */ 0, 3, 17, 66, 0, 98, 16, 35,165,194, 1,152, 0,203, 16, 43,
/* 0x14a0 */ 20, 64, 0, 8, 3, 4,192, 35, 17,167, 1, 98, 0, 11, 90, 0,
/* 0x14b0 */ 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37,
/* 0x14c0 */ 37,173, 0, 1,149,195, 1,176, 0, 11, 18,194, 0, 67, 0, 24,
/* 0x14d0 */ 0, 0, 32, 18, 3, 4, 16, 43, 16, 64, 0, 7, 36, 2, 8, 0,
/* 0x14e0 */ 0, 67, 16, 35, 0, 2, 17, 67, 0, 98, 16, 33,165,194, 1,176,
/* 0x14f0 */ 16, 0, 0, 28, 2,128, 16, 33, 1,100, 88, 35, 0, 3, 17, 66,
/* 0x1500 */ 0, 98, 16, 35,165,194, 1,176, 0,203, 16, 43, 20, 64, 0, 8,
/* 0x1510 */ 3, 4,192, 35, 17,167, 1, 71, 0, 11, 90, 0, 0, 24, 26, 0,
/* 0x1520 */ 145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1,
/* 0x1530 */ 149,195, 1,200, 0, 11, 18,194, 0, 67, 0, 24, 0, 0, 32, 18,
/* 0x1540 */ 3, 4, 16, 43, 16, 64, 0, 11, 36, 2, 8, 0, 0, 67, 16, 35,
/* 0x1550 */ 0, 2, 17, 67, 0, 98, 16, 33,165,194, 1,200, 2,224, 16, 33,
/* 0x1560 */ 2,128,184, 33, 2, 32,160, 33, 0, 64,136, 33, 16, 0, 0, 11,
/* 0x1570 */ 0,128, 88, 33, 1,100, 88, 35, 3, 4,192, 35, 0, 3, 17, 66,
/* 0x1580 */ 0, 98, 16, 35,165,194, 1,200,143,162, 0, 0,175,183, 0, 0,
/* 0x1590 */ 2,128,184, 33, 2, 32,160, 33, 0, 64,136, 33, 42, 66, 0, 7,
/* 0x15a0 */ 20, 64, 0, 2, 36, 18, 0, 8, 36, 18, 0, 11, 38, 14, 10,104,
/* 0x15b0 */ 60, 2, 0,255, 52, 76,255,255, 1,139, 16, 43, 20, 64, 0, 8,
/* 0x15c0 */ 0, 0, 0, 0, 17,167, 1, 27, 0, 11, 90, 0, 0, 24, 26, 0,
/* 0x15d0 */ 145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1,
/* 0x15e0 */ 149,195, 0, 0, 0, 11, 18,194, 0, 67, 0, 24, 0, 0, 32, 18,
/* 0x15f0 */ 3, 4, 16, 43, 16, 64, 0, 12, 36, 2, 8, 0, 0, 67, 16, 35,
/* 0x1600 */ 0, 2, 17, 67, 0, 98, 16, 33,165,194, 0, 0, 0, 5, 17, 0,
/* 0x1610 */ 1,194, 16, 33, 36, 69, 0, 4, 0,128,120, 33, 36, 8, 0, 3,
/* 0x1620 */ 16, 0, 0, 41, 0, 0, 48, 33, 1,100, 88, 35, 0, 3, 17, 66,
/* 0x1630 */ 0, 98, 16, 35,165,194, 0, 0, 1,139, 16, 43, 20, 64, 0, 8,
/* 0x1640 */ 3, 4,192, 35, 17,167, 0,251, 0, 11, 90, 0, 0, 24, 26, 0,
/* 0x1650 */ 145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1,
/* 0x1660 */ 149,195, 0, 2, 0, 11, 18,194, 0, 67, 0, 24, 0, 0, 32, 18,
/* 0x1670 */ 3, 4, 16, 43, 16, 64, 0, 12, 36, 2, 8, 0, 0, 67, 16, 35,
/* 0x1680 */ 0, 2, 17, 67, 0, 98, 16, 33,165,194, 0, 2, 0, 5, 17, 0,
/* 0x1690 */ 1,194, 16, 33, 36, 69, 1, 4, 0,128,120, 33, 36, 8, 0, 3,
/* 0x16a0 */ 16, 0, 0, 9, 36, 6, 0, 8, 1,100,120, 35, 3, 4,192, 35,
/* 0x16b0 */ 0, 3, 17, 66, 0, 98, 16, 35,165,194, 0, 2, 37,197, 2, 4,
/* 0x16c0 */ 36, 8, 0, 8, 36, 6, 0, 16, 1, 0,112, 33, 36, 25, 0, 1,
/* 0x16d0 */ 60, 2, 0,255, 52, 66,255,255, 0, 79, 16, 43, 20, 64, 0, 9,
/* 0x16e0 */ 0, 25, 96, 64, 17,167, 0,211, 0, 15,122, 0, 0, 24, 26, 0,
/* 0x16f0 */ 145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1,
/* 0x1700 */ 0, 25, 96, 64, 0,172, 88, 33,149, 99, 0, 0, 0, 15, 18,194,
/* 0x1710 */ 0, 67, 0, 24, 0, 0, 32, 18, 3, 4, 16, 43, 16, 64, 0, 8,
/* 0x1720 */ 36, 2, 8, 0, 0, 67, 16, 35, 0, 2, 17, 67, 0, 98, 16, 33,
/* 0x1730 */ 165, 98, 0, 0, 1,128,200, 33, 16, 0, 0, 8, 0,128,120, 33,
/* 0x1740 */ 1,228,120, 35, 3, 4,192, 35, 0, 3, 17, 66, 0, 98, 16, 35,
/* 0x1750 */ 165, 98, 0, 0, 39, 34, 0, 1, 3, 34,200, 33, 37,206,255,255,
/* 0x1760 */ 21,192,255,220, 60, 2, 0,255, 36, 2, 0, 1, 1, 2, 16, 4,
/* 0x1770 */ 3, 34, 16, 35, 0, 70, 72, 33, 42, 66, 0, 4, 16, 64, 0,134,
/* 0x1780 */ 41, 34, 0, 4, 20, 64, 0, 2, 1, 32, 24, 33, 36, 3, 0, 3,
/* 0x1790 */ 0, 3, 17,192, 2, 2, 16, 33, 36, 70, 3, 96, 36, 14, 0, 1,
/* 0x17a0 */ 36, 25, 0, 6, 60, 2, 0,255, 52, 66,255,255, 0, 79, 16, 43,
/* 0x17b0 */ 20, 64, 0, 9, 0, 14, 96, 64, 17,167, 0,158, 0, 15,122, 0,
/* 0x17c0 */ 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37,
/* 0x17d0 */ 37,173, 0, 1, 0, 14, 96, 64, 0,204, 88, 33,149, 99, 0, 0,
/* 0x17e0 */ 0, 15, 18,194, 0, 67, 0, 24, 0, 0, 32, 18, 3, 4, 16, 43,
/* 0x17f0 */ 16, 64, 0, 8, 36, 2, 8, 0, 0, 67, 16, 35, 0, 2, 17, 67,
/* 0x1800 */ 0, 98, 16, 33,165, 98, 0, 0, 1,128,112, 33, 16, 0, 0, 8,
/* 0x1810 */ 0,128,120, 33, 1,228,120, 35, 3, 4,192, 35, 0, 3, 17, 66,
/* 0x1820 */ 0, 98, 16, 35,165, 98, 0, 0, 37,194, 0, 1, 1,194,112, 33,
/* 0x1830 */ 39, 57,255,255, 23, 32,255,220, 60, 2, 0,255, 37,195,255,192,
/* 0x1840 */ 40, 98, 0, 4, 20, 64, 0, 80, 0, 96,112, 33, 0, 3, 32, 67,
/* 0x1850 */ 48, 98, 0, 1, 52, 75, 0, 2, 40, 98, 0, 14, 16, 64, 0, 8,
/* 0x1860 */ 36,153,255,255, 3, 43,112, 4, 0, 14, 16, 64, 2, 2, 32, 33,
/* 0x1870 */ 0, 3, 16, 64, 0,130, 16, 35, 16, 0, 0, 26, 36, 72, 5, 94,
/* 0x1880 */ 36,132,255,251, 60, 2, 0,255, 52, 66,255,255, 0, 79, 16, 43,
/* 0x1890 */ 20, 64, 0, 8, 0, 0, 0, 0, 17,167, 0,102, 0, 15,122, 0,
/* 0x18a0 */ 0, 24, 26, 0,145,162, 0, 0, 0, 0, 0, 0, 0, 98,192, 37,
/* 0x18b0 */ 37,173, 0, 1, 0, 15,120, 66, 3, 15, 16, 43, 20, 64, 0, 3,
/* 0x18c0 */ 0, 11, 88, 64, 3, 15,192, 35, 53,107, 0, 1, 36,132,255,255,
/* 0x18d0 */ 20,128,255,237, 60, 2, 0,255, 38, 8, 6, 68, 0, 11,113, 0,
/* 0x18e0 */ 36, 25, 0, 4, 36, 6, 0, 1, 36, 5, 0, 1, 60, 2, 0,255,
/* 0x18f0 */ 52, 66,255,255, 0, 79, 16, 43, 20, 64, 0, 9, 0, 5, 96, 64,
/* 0x1900 */ 17,167, 0, 76, 0, 15,122, 0, 0, 24, 26, 0,145,162, 0, 0,
/* 0x1910 */ 0, 0, 0, 0, 0, 98,192, 37, 37,173, 0, 1, 0, 5, 96, 64,
/* 0x1920 */ 1, 12, 88, 33,149, 99, 0, 0, 0, 15, 18,194, 0, 67, 0, 24,
/* 0x1930 */ 0, 0, 32, 18, 3, 4, 16, 43, 16, 64, 0, 8, 36, 2, 8, 0,
/* 0x1940 */ 0, 67, 16, 35, 0, 2, 17, 67, 0, 98, 16, 33,165, 98, 0, 0,
/* 0x1950 */ 1,128, 40, 33, 16, 0, 0, 9, 0,128,120, 33, 1,228,120, 35,
/* 0x1960 */ 3, 4,192, 35, 0, 3, 17, 66, 0, 98, 16, 35,165, 98, 0, 0,
/* 0x1970 */ 36,162, 0, 1, 0,162, 40, 33, 1,198,112, 37, 39, 57,255,255,
/* 0x1980 */ 23, 32,255,218, 0, 6, 48, 64, 37,209, 0, 1, 18, 32, 0, 26,
/* 0x1990 */ 60, 2, 0,255, 38, 82, 0, 7, 1, 81, 16, 43, 20, 64, 0, 38,
/* 0x19a0 */ 36, 2, 0, 1, 1, 81, 16, 35, 2, 98, 88, 33, 2,106, 32, 33,
/* 0x19b0 */ 1, 64, 24, 33,145,110, 0, 0, 36, 99, 0, 1, 1, 73, 16, 33,
/* 0x19c0 */ 36, 66, 0, 2, 16, 98, 0, 6,160,142, 0, 0, 37,107, 0, 1,
/* 0x19d0 */ 143,162, 0, 16, 0, 0, 0, 0, 20, 98,255,246, 36,132, 0, 1,
/* 0x19e0 */ 0, 96, 80, 33,143,163, 0, 16, 0, 0, 0, 0, 1, 67, 16, 43,
/* 0x19f0 */ 20, 64,253,166, 60, 2, 0,255, 52, 66,255,255, 0, 79, 16, 43,
/* 0x1a00 */ 20, 64, 0, 4, 1,181, 40, 35, 17,167, 0, 10, 37,173, 0, 1,
/* 0x1a10 */ 1,181, 40, 35,143,162, 0, 12, 0, 0, 0, 0,172, 69, 0, 0,
/* 0x1a20 */ 143,163, 0, 20, 0, 0, 0, 0,172,106, 0, 0, 16, 0, 0, 2,
/* 0x1a30 */ 0, 0, 16, 33, 36, 2, 0, 1,143,183, 0, 52,143,182, 0, 48,
/* 0x1a40 */ 143,181, 0, 44,143,180, 0, 40,143,179, 0, 36,143,178, 0, 32,
/* 0x1a50 */ 143,177, 0, 28,143,176, 0, 24, 3,224, 0, 8, 39,189, 0, 56,
/* 0x1a60 */ 0, 0, 0, 13, 39,189,255,252,175,191, 0, 0, 0,164, 40, 32,
/* 0x1a70 */ 172,230, 0, 0,140,227, 0, 0, 0,133,192, 35,143,191, 0, 0,
/* 0x1a80 */ 175,184, 0, 0, 0, 96, 32, 33, 0,195, 40, 35,172,229, 0, 0,
/* 0x1a90 */ 36, 6, 0, 3, 36, 2, 16, 51, 0, 0, 0, 12,143,162, 0, 0,
/* 0x1aa0 */ 3,224, 0, 8, 39,189, 0, 4, 36, 6, 0, 30, 4, 17,255,255,
/* 0x1ab0 */ 3,224, 40, 33, 80, 82, 79, 84, 95, 69, 88, 69, 67,124, 80, 82,
/* 0x1ac0 */ 79, 84, 95, 87, 82, 73, 84, 69, 32,102, 97,105,108,101,100, 46,
/* 0x1ad0 */ 10, 0, 36, 4, 0, 2, 36, 2, 15,164, 0, 0, 0, 12, 36, 4,
/* 0x1ae0 */ 0,127, 36, 2, 15,161, 0, 0, 0, 12, 39,189,255,224,142,228,
/* 0x1af0 */ 255,224, 36, 6, 0, 7,142,229,255,228, 36, 7, 8, 18,175,160,
/* 0x1b00 */ 0, 16, 36, 2, 15,250, 0, 0, 0, 12, 20,224, 0, 32, 0, 64,
/* 0x1b10 */ 128, 33,142,228,255,236,142,243,255,232,142,242,255,240,142,241,
/* 0x1b20 */ 255,244, 18, 4, 0, 18, 2, 4, 64, 35, 2,215,160, 35, 2,149,
/* 0x1b30 */ 48, 33, 2,232,184, 33, 2, 0, 40, 33,140,136, 0, 0, 36,165,
/* 0x1b40 */ 0, 8,140,137, 0, 4, 36,198,255,248,172,168,255,248, 36,132,
/* 0x1b50 */ 0, 8, 28,192,255,249,172,169,255,252, 0,160,128, 33, 2,224,
/* 0x1b60 */ 32, 33, 36, 6, 0, 3, 36, 2, 16, 51, 0, 0, 0, 12,142,200,
/* 0x1b70 */ 0, 0, 3,160, 56, 33,175,168, 0, 0, 2, 0, 48, 33,142,197,
/* 0x1b80 */ 0, 4, 38,196, 0, 12, 2,224, 0, 8, 0,192,248, 33, 16, 0,
/* 0x1b90 */ 255,255, 0, 0, 0, 0,142,245,255,220, 4, 17,255,211, 3,224,
/* 0x1ba0 */ 176, 33,102,105,108,101, 32,102,111,114,109, 97,116, 32,101,108,
/* 0x1bb0 */ 102, 51, 50, 45, 98,105,103,109,105,112,115, 10, 10, 83,101, 99,
/* 0x1bc0 */ 116,105,111,110,115, 58, 10, 73,100,120, 32, 78, 97,109,101, 32,
/* 0x1bd0 */ 32, 32, 32, 32, 32, 32, 32, 32, 32, 83,105,122,101, 32, 32, 32,
/* 0x1be0 */ 32, 32, 32, 86, 77, 65, 32, 32, 32, 32, 32, 32, 32, 76, 77, 65,
/* 0x1bf0 */ 32, 32, 32, 32, 32, 32, 32, 70,105,108,101, 32,111,102,102, 32,
/* 0x1c00 */ 32, 65,108,103,110, 32, 32, 70,108, 97,103,115, 10, 32, 32, 48,
/* 0x1c10 */ 32, 69, 76, 70, 77, 65, 73, 78, 88, 32, 32, 32, 32, 32, 32, 48,
/* 0x1c20 */ 48, 48, 48, 48, 48, 50, 48, 32, 32, 48, 48, 48, 48, 48, 48, 48,
/* 0x1c30 */ 48, 32, 32, 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 48, 48, 48,
/* 0x1c40 */ 48, 48, 48, 51, 52, 32, 32, 50, 42, 42, 48, 32, 32, 67, 79, 78,
/* 0x1c50 */ 84, 69, 78, 84, 83, 44, 32, 82, 69, 76, 79, 67, 44, 32, 82, 69,
/* 0x1c60 */ 65, 68, 79, 78, 76, 89, 10, 32, 32, 49, 32, 78, 82, 86, 50, 69,
/* 0x1c70 */ 32, 32, 32, 32, 32, 32, 32, 32, 32, 48, 48, 48, 48, 48, 49, 53,
/* 0x1c80 */ 52, 32, 32, 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 48, 48, 48,
/* 0x1c90 */ 48, 48, 48, 48, 48, 32, 32, 48, 48, 48, 48, 48, 48, 53, 52, 32,
/* 0x1ca0 */ 32, 50, 42, 42, 48, 32, 32, 67, 79, 78, 84, 69, 78, 84, 83, 44,
/* 0x1cb0 */ 32, 82, 69, 76, 79, 67, 44, 32, 82, 69, 65, 68, 79, 78, 76, 89,
/* 0x1cc0 */ 10, 32, 32, 50, 32, 78, 82, 86, 50, 68, 32, 32, 32, 32, 32, 32,
/* 0x1cd0 */ 32, 32, 32, 48, 48, 48, 48, 48, 49, 52, 52, 32, 32, 48, 48, 48,
/* 0x1ce0 */ 48, 48, 48, 48, 48, 32, 32, 48, 48, 48, 48, 48, 48, 48, 48, 32,
/* 0x1cf0 */ 32, 48, 48, 48, 48, 48, 49, 97, 56, 32, 32, 50, 42, 42, 48, 32,
/* 0x1d00 */ 32, 67, 79, 78, 84, 69, 78, 84, 83, 44, 32, 82, 69, 76, 79, 67,
/* 0x1d10 */ 44, 32, 82, 69, 65, 68, 79, 78, 76, 89, 10, 32, 32, 51, 32, 78,
/* 0x1d20 */ 82, 86, 50, 66, 32, 32, 32, 32, 32, 32, 32, 32, 32, 48, 48, 48,
/* 0x1d30 */ 48, 48, 49, 50, 56, 32, 32, 48, 48, 48, 48, 48, 48, 48, 48, 32,
/* 0x1d40 */ 32, 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 48, 48, 48, 48, 48,
/* 0x1d50 */ 50,101, 99, 32, 32, 50, 42, 42, 48, 32, 32, 67, 79, 78, 84, 69,
/* 0x1d60 */ 78, 84, 83, 44, 32, 82, 69, 76, 79, 67, 44, 32, 82, 69, 65, 68,
/* 0x1d70 */ 79, 78, 76, 89, 10, 32, 32, 52, 32, 76, 90, 77, 65, 95, 69, 76,
/* 0x1d80 */ 70, 48, 48, 32, 32, 32, 32, 48, 48, 48, 48, 48, 48, 57, 99, 32,
/* 0x1d90 */ 32, 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 48, 48, 48, 48, 48,
/* 0x1da0 */ 48, 48, 48, 32, 32, 48, 48, 48, 48, 48, 52, 49, 52, 32, 32, 50,
/* 0x1db0 */ 42, 42, 48, 32, 32, 67, 79, 78, 84, 69, 78, 84, 83, 44, 32, 82,
/* 0x1dc0 */ 69, 65, 68, 79, 78, 76, 89, 10, 32, 32, 53, 32, 76, 90, 77, 65,
/* 0x1dd0 */ 95, 68, 69, 67, 50, 48, 32, 32, 32, 32, 48, 48, 48, 48, 48, 97,
/* 0x1de0 */ 100, 56, 32, 32, 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 48, 48,
/* 0x1df0 */ 48, 48, 48, 48, 48, 48, 32, 32, 48, 48, 48, 48, 48, 52, 98, 48,
/* 0x1e00 */ 32, 32, 50, 42, 42, 48, 32, 32, 67, 79, 78, 84, 69, 78, 84, 83,
/* 0x1e10 */ 44, 32, 82, 69, 65, 68, 79, 78, 76, 89, 10, 32, 32, 54, 32, 76,
/* 0x1e20 */ 90, 77, 65, 95, 68, 69, 67, 49, 48, 32, 32, 32, 32, 48, 48, 48,
/* 0x1e30 */ 48, 48, 97,100, 56, 32, 32, 48, 48, 48, 48, 48, 48, 48, 48, 32,
/* 0x1e40 */ 32, 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 48, 48, 48, 48, 48,
/* 0x1e50 */ 102, 56, 56, 32, 32, 50, 42, 42, 48, 32, 32, 67, 79, 78, 84, 69,
/* 0x1e60 */ 78, 84, 83, 44, 32, 82, 69, 65, 68, 79, 78, 76, 89, 10, 32, 32,
/* 0x1e70 */ 55, 32, 76, 90, 77, 65, 95, 68, 69, 67, 51, 48, 32, 32, 32, 32,
/* 0x1e80 */ 48, 48, 48, 48, 48, 48, 48, 52, 32, 32, 48, 48, 48, 48, 48, 48,
/* 0x1e90 */ 48, 48, 32, 32, 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 48, 48,
/* 0x1ea0 */ 48, 48, 49, 97, 54, 48, 32, 32, 50, 42, 42, 48, 32, 32, 67, 79,
/* 0x1eb0 */ 78, 84, 69, 78, 84, 83, 44, 32, 82, 69, 65, 68, 79, 78, 76, 89,
/* 0x1ec0 */ 10, 32, 32, 56, 32, 78, 82, 86, 95, 72, 69, 65, 68, 32, 32, 32,
/* 0x1ed0 */ 32, 32, 32, 48, 48, 48, 48, 48, 48, 49, 48, 32, 32, 48, 48, 48,
/* 0x1ee0 */ 48, 48, 48, 48, 48, 32, 32, 48, 48, 48, 48, 48, 48, 48, 48, 32,
/* 0x1ef0 */ 32, 48, 48, 48, 48, 49, 97, 54, 52, 32, 32, 50, 42, 42, 48, 32,
/* 0x1f00 */ 32, 67, 79, 78, 84, 69, 78, 84, 83, 44, 32, 82, 69, 65, 68, 79,
/* 0x1f10 */ 78, 76, 89, 10, 32, 32, 57, 32, 78, 82, 86, 95, 84, 65, 73, 76,
/* 0x1f20 */ 32, 32, 32, 32, 32, 32, 48, 48, 48, 48, 48, 48, 49, 48, 32, 32,
/* 0x1f30 */ 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 48, 48, 48, 48, 48, 48,
/* 0x1f40 */ 48, 48, 32, 32, 48, 48, 48, 48, 49, 97, 55, 52, 32, 32, 50, 42,
/* 0x1f50 */ 42, 48, 32, 32, 67, 79, 78, 84, 69, 78, 84, 83, 44, 32, 82, 69,
/* 0x1f60 */ 65, 68, 79, 78, 76, 89, 10, 32, 49, 48, 32, 67, 70, 76, 85, 83,
/* 0x1f70 */ 72, 32, 32, 32, 32, 32, 32, 32, 32, 48, 48, 48, 48, 48, 48, 50,
/* 0x1f80 */ 52, 32, 32, 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 48, 48, 48,
/* 0x1f90 */ 48, 48, 48, 48, 48, 32, 32, 48, 48, 48, 48, 49, 97, 56, 52, 32,
/* 0x1fa0 */ 32, 50, 42, 42, 48, 32, 32, 67, 79, 78, 84, 69, 78, 84, 83, 44,
/* 0x1fb0 */ 32, 82, 69, 65, 68, 79, 78, 76, 89, 10, 32, 49, 49, 32, 69, 76,
/* 0x1fc0 */ 70, 77, 65, 73, 78, 89, 32, 32, 32, 32, 32, 32, 48, 48, 48, 48,
/* 0x1fd0 */ 48, 48, 50, 97, 32, 32, 48, 48, 48, 48, 48, 48, 48, 48, 32, 32,
/* 0x1fe0 */ 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 48, 48, 48, 48, 49, 97,
/* 0x1ff0 */ 97, 56, 32, 32, 50, 42, 42, 48, 32, 32, 67, 79, 78, 84, 69, 78,
/* 0x2000 */ 84, 83, 44, 32, 82, 69, 76, 79, 67, 44, 32, 82, 69, 65, 68, 79,
/* 0x2010 */ 78, 76, 89, 10, 32, 49, 50, 32, 69, 76, 70, 77, 65, 73, 78, 90,
/* 0x2020 */ 32, 32, 32, 32, 32, 32, 48, 48, 48, 48, 48, 48,100, 48, 32, 32,
/* 0x2030 */ 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 48, 48, 48, 48, 48, 48,
/* 0x2040 */ 48, 48, 32, 32, 48, 48, 48, 48, 49, 97,100, 50, 32, 32, 50, 42,
/* 0x2050 */ 42, 48, 32, 32, 67, 79, 78, 84, 69, 78, 84, 83, 44, 32, 82, 69,
/* 0x2060 */ 65, 68, 79, 78, 76, 89, 10, 83, 89, 77, 66, 79, 76, 32, 84, 65,
/* 0x2070 */ 66, 76, 69, 58, 10, 48, 48, 48, 48, 48, 48, 48, 48, 32,108, 32,
/* 0x2080 */ 32, 32, 32,100, 32, 32, 78, 82, 86, 95, 84, 65, 73, 76, 9, 48,
/* 0x2090 */ 48, 48, 48, 48, 48, 48, 48, 32, 78, 82, 86, 95, 84, 65, 73, 76,
/* 0x20a0 */ 10, 48, 48, 48, 48, 48, 48, 48, 48, 32,108, 32, 32, 32, 32,100,
/* 0x20b0 */ 32, 32, 69, 76, 70, 77, 65, 73, 78, 90, 9, 48, 48, 48, 48, 48,
/* 0x20c0 */ 48, 48, 48, 32, 69, 76, 70, 77, 65, 73, 78, 90, 10, 48, 48, 48,
/* 0x20d0 */ 48, 48, 48, 48, 48, 32,108, 32, 32, 32, 32,100, 32, 32, 69, 76,
/* 0x20e0 */ 70, 77, 65, 73, 78, 88, 9, 48, 48, 48, 48, 48, 48, 48, 48, 32,
/* 0x20f0 */ 69, 76, 70, 77, 65, 73, 78, 88, 10, 48, 48, 48, 48, 48, 48, 48,
/* 0x2100 */ 48, 32,108, 32, 32, 32, 32,100, 32, 32, 78, 82, 86, 50, 69, 9,
/* 0x2110 */ 48, 48, 48, 48, 48, 48, 48, 48, 32, 78, 82, 86, 50, 69, 10, 48,
/* 0x2120 */ 48, 48, 48, 48, 48, 48, 48, 32,108, 32, 32, 32, 32,100, 32, 32,
/* 0x2130 */ 78, 82, 86, 50, 68, 9, 48, 48, 48, 48, 48, 48, 48, 48, 32, 78,
/* 0x2140 */ 82, 86, 50, 68, 10, 48, 48, 48, 48, 48, 48, 48, 48, 32,108, 32,
/* 0x2150 */ 32, 32, 32,100, 32, 32, 78, 82, 86, 50, 66, 9, 48, 48, 48, 48,
/* 0x2160 */ 48, 48, 48, 48, 32, 78, 82, 86, 50, 66, 10, 48, 48, 48, 48, 48,
/* 0x2170 */ 48, 48, 48, 32,108, 32, 32, 32, 32,100, 32, 32, 76, 90, 77, 65,
/* 0x2180 */ 95, 69, 76, 70, 48, 48, 9, 48, 48, 48, 48, 48, 48, 48, 48, 32,
/* 0x2190 */ 76, 90, 77, 65, 95, 69, 76, 70, 48, 48, 10, 48, 48, 48, 48, 48,
/* 0x21a0 */ 48, 48, 48, 32,108, 32, 32, 32, 32,100, 32, 32, 76, 90, 77, 65,
/* 0x21b0 */ 95, 68, 69, 67, 50, 48, 9, 48, 48, 48, 48, 48, 48, 48, 48, 32,
/* 0x21c0 */ 76, 90, 77, 65, 95, 68, 69, 67, 50, 48, 10, 48, 48, 48, 48, 48,
/* 0x21d0 */ 48, 48, 48, 32,108, 32, 32, 32, 32,100, 32, 32, 76, 90, 77, 65,
/* 0x21e0 */ 95, 68, 69, 67, 49, 48, 9, 48, 48, 48, 48, 48, 48, 48, 48, 32,
/* 0x21f0 */ 76, 90, 77, 65, 95, 68, 69, 67, 49, 48, 10, 48, 48, 48, 48, 48,
/* 0x2200 */ 48, 48, 48, 32,108, 32, 32, 32, 32,100, 32, 32, 76, 90, 77, 65,
/* 0x2210 */ 95, 68, 69, 67, 51, 48, 9, 48, 48, 48, 48, 48, 48, 48, 48, 32,
/* 0x2220 */ 76, 90, 77, 65, 95, 68, 69, 67, 51, 48, 10, 48, 48, 48, 48, 48,
/* 0x2230 */ 48, 48, 48, 32,108, 32, 32, 32, 32,100, 32, 32, 78, 82, 86, 95,
/* 0x2240 */ 72, 69, 65, 68, 9, 48, 48, 48, 48, 48, 48, 48, 48, 32, 78, 82,
/* 0x2250 */ 86, 95, 72, 69, 65, 68, 10, 48, 48, 48, 48, 48, 48, 48, 48, 32,
/* 0x2260 */ 108, 32, 32, 32, 32,100, 32, 32, 67, 70, 76, 85, 83, 72, 9, 48,
/* 0x2270 */ 48, 48, 48, 48, 48, 48, 48, 32, 67, 70, 76, 85, 83, 72, 10, 48,
/* 0x2280 */ 48, 48, 48, 48, 48, 48, 48, 32,108, 32, 32, 32, 32,100, 32, 32,
/* 0x2290 */ 69, 76, 70, 77, 65, 73, 78, 89, 9, 48, 48, 48, 48, 48, 48, 48,
/* 0x22a0 */ 48, 32, 69, 76, 70, 77, 65, 73, 78, 89, 10, 48, 48, 48, 48, 48,
/* 0x22b0 */ 48, 48, 48, 32, 32, 32, 32, 32, 32, 32, 32, 32, 42, 85, 78, 68,
/* 0x22c0 */ 42, 9, 48, 48, 48, 48, 48, 48, 48, 48, 32, 65, 68, 82, 77, 10,
/* 0x22d0 */ 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 32, 32, 32, 32, 32, 32,
/* 0x22e0 */ 32, 42, 85, 78, 68, 42, 9, 48, 48, 48, 48, 48, 48, 48, 48, 32,
/* 0x22f0 */ 76, 69, 78, 77, 10, 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 32,
/* 0x2300 */ 32, 32, 32, 32, 32, 32, 42, 85, 78, 68, 42, 9, 48, 48, 48, 48,
/* 0x2310 */ 48, 48, 48, 48, 32, 65, 68, 82, 85, 10, 48, 48, 48, 48, 48, 48,
/* 0x2320 */ 48, 48, 32, 32, 32, 32, 32, 32, 32, 32, 32, 42, 85, 78, 68, 42,
/* 0x2330 */ 9, 48, 48, 48, 48, 48, 48, 48, 48, 32, 65, 68, 82, 67, 10, 48,
/* 0x2340 */ 48, 48, 48, 48, 48, 48, 48, 32, 32, 32, 32, 32, 32, 32, 32, 32,
/* 0x2350 */ 42, 85, 78, 68, 42, 9, 48, 48, 48, 48, 48, 48, 48, 48, 32, 76,
/* 0x2360 */ 69, 78, 85, 10, 48, 48, 48, 48, 48, 48, 48, 48, 32, 32, 32, 32,
/* 0x2370 */ 32, 32, 32, 32, 32, 42, 85, 78, 68, 42, 9, 48, 48, 48, 48, 48,
/* 0x2380 */ 48, 48, 48, 32, 65, 68, 82, 88, 10, 48, 48, 48, 48, 48, 48, 49,
/* 0x2390 */ 56, 32,103, 32, 32, 32, 32, 32, 79, 32, 69, 76, 70, 77, 65, 73,
/* 0x23a0 */ 78, 88, 9, 48, 48, 48, 48, 48, 48, 48, 48, 32, 95,115,116, 97,
/* 0x23b0 */ 114,116, 10, 10, 82, 69, 76, 79, 67, 65, 84, 73, 79, 78, 32, 82,
/* 0x23c0 */ 69, 67, 79, 82, 68, 83, 32, 70, 79, 82, 32, 91, 69, 76, 70, 77,
/* 0x23d0 */ 65, 73, 78, 88, 93, 58, 10, 79, 70, 70, 83, 69, 84, 32, 32, 32,
/* 0x23e0 */ 84, 89, 80, 69, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
/* 0x23f0 */ 32, 32, 86, 65, 76, 85, 69, 10, 48, 48, 48, 48, 48, 48, 48, 48,
/* 0x2400 */ 32, 82, 95, 77, 73, 80, 83, 95, 51, 50, 32, 32, 32, 32, 32, 32,
/* 0x2410 */ 32, 32, 32, 65, 68, 82, 77, 10, 48, 48, 48, 48, 48, 48, 48, 52,
/* 0x2420 */ 32, 82, 95, 77, 73, 80, 83, 95, 51, 50, 32, 32, 32, 32, 32, 32,
/* 0x2430 */ 32, 32, 32, 76, 69, 78, 77, 10, 48, 48, 48, 48, 48, 48, 48, 56,
/* 0x2440 */ 32, 82, 95, 77, 73, 80, 83, 95, 51, 50, 32, 32, 32, 32, 32, 32,
/* 0x2450 */ 32, 32, 32, 65, 68, 82, 85, 10, 48, 48, 48, 48, 48, 48, 48, 99,
/* 0x2460 */ 32, 82, 95, 77, 73, 80, 83, 95, 51, 50, 32, 32, 32, 32, 32, 32,
/* 0x2470 */ 32, 32, 32, 65, 68, 82, 67, 10, 48, 48, 48, 48, 48, 48, 49, 48,
/* 0x2480 */ 32, 82, 95, 77, 73, 80, 83, 95, 51, 50, 32, 32, 32, 32, 32, 32,
/* 0x2490 */ 32, 32, 32, 76, 69, 78, 85, 10, 48, 48, 48, 48, 48, 48, 49, 52,
/* 0x24a0 */ 32, 82, 95, 77, 73, 80, 83, 95, 51, 50, 32, 32, 32, 32, 32, 32,
/* 0x24b0 */ 32, 32, 32, 65, 68, 82, 88, 10, 48, 48, 48, 48, 48, 48, 49, 56,
/* 0x24c0 */ 32, 82, 95, 77, 73, 80, 83, 95, 80, 67, 49, 54, 32, 32, 32, 32,
/* 0x24d0 */ 32, 32, 32, 69, 76, 70, 77, 65, 73, 78, 90, 10, 10, 82, 69, 76,
/* 0x24e0 */ 79, 67, 65, 84, 73, 79, 78, 32, 82, 69, 67, 79, 82, 68, 83, 32,
/* 0x24f0 */ 70, 79, 82, 32, 91, 78, 82, 86, 50, 69, 93, 58, 10, 79, 70, 70,
/* 0x2500 */ 83, 69, 84, 32, 32, 32, 84, 89, 80, 69, 32, 32, 32, 32, 32, 32,
/* 0x2510 */ 32, 32, 32, 32, 32, 32, 32, 32, 86, 65, 76, 85, 69, 10, 48, 48,
/* 0x2520 */ 48, 48, 48, 48, 55, 99, 32, 82, 95, 77, 73, 80, 83, 95, 80, 67,
/* 0x2530 */ 49, 54, 32, 32, 32, 32, 32, 32, 32, 78, 82, 86, 95, 84, 65, 73,
/* 0x2540 */ 76, 10, 10, 82, 69, 76, 79, 67, 65, 84, 73, 79, 78, 32, 82, 69,
/* 0x2550 */ 67, 79, 82, 68, 83, 32, 70, 79, 82, 32, 91, 78, 82, 86, 50, 68,
/* 0x2560 */ 93, 58, 10, 79, 70, 70, 83, 69, 84, 32, 32, 32, 84, 89, 80, 69,
/* 0x2570 */ 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 86, 65,
/* 0x2580 */ 76, 85, 69, 10, 48, 48, 48, 48, 48, 48, 55, 99, 32, 82, 95, 77,
/* 0x2590 */ 73, 80, 83, 95, 80, 67, 49, 54, 32, 32, 32, 32, 32, 32, 32, 78,
/* 0x25a0 */ 82, 86, 95, 84, 65, 73, 76, 10, 10, 82, 69, 76, 79, 67, 65, 84,
/* 0x25b0 */ 73, 79, 78, 32, 82, 69, 67, 79, 82, 68, 83, 32, 70, 79, 82, 32,
/* 0x25c0 */ 91, 78, 82, 86, 50, 66, 93, 58, 10, 79, 70, 70, 83, 69, 84, 32,
/* 0x25d0 */ 32, 32, 84, 89, 80, 69, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
/* 0x25e0 */ 32, 32, 32, 32, 86, 65, 76, 85, 69, 10, 48, 48, 48, 48, 48, 48,
/* 0x25f0 */ 54, 52, 32, 82, 95, 77, 73, 80, 83, 95, 80, 67, 49, 54, 32, 32,
/* 0x2600 */ 32, 32, 32, 32, 32, 78, 82, 86, 95, 84, 65, 73, 76, 10, 10, 82,
/* 0x2610 */ 69, 76, 79, 67, 65, 84, 73, 79, 78, 32, 82, 69, 67, 79, 82, 68,
/* 0x2620 */ 83, 32, 70, 79, 82, 32, 91, 69, 76, 70, 77, 65, 73, 78, 89, 93,
/* 0x2630 */ 58, 10, 79, 70, 70, 83, 69, 84, 32, 32, 32, 84, 89, 80, 69, 32,
/* 0x2640 */ 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 86, 65, 76,
/* 0x2650 */ 85, 69, 10, 48, 48, 48, 48, 48, 48, 48, 52, 32, 82, 95, 77, 73,
/* 0x2660 */ 80, 83, 95, 80, 67, 49, 54, 32, 32, 32, 32, 32, 32, 32, 69, 76,
/* 0x2670 */ 70, 77, 65, 73, 78, 90, 10
};
|
Distrotech/upx
|
src/stub/mips.r3000-linux.elf-entry.h
|
C
|
gpl-2.0
| 49,509 |
/*
* Caja-Actions
* A Caja extension which offers configurable context menu actions.
*
* Copyright (C) 2005 The GNOME Foundation
* Copyright (C) 2006-2008 Frederic Ruaudel and others (see AUTHORS)
* Copyright (C) 2009-2012 Pierre Wieser and others (see AUTHORS)
*
* Caja-Actions is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* Caja-Actions is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Caja-Actions; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
* Authors:
* Frederic Ruaudel <[email protected]>
* Rodrigo Moya <[email protected]>
* Pierre Wieser <[email protected]>
* ... and many others (see AUTHORS)
*/
#ifndef __CAJA_ACTIONS_API_NA_DATA_TYPES_H__
#define __CAJA_ACTIONS_API_NA_DATA_TYPES_H__
/**
* SECTION: data-type
* @title: NADataType
* @short_description: The Data Factory Type Definitions
* @include: caja-actions/na-data-types.h
*/
#include <glib.h>
G_BEGIN_DECLS
/**
* NADataType:
* @NA_DATA_TYPE_BOOLEAN: a boolean
* can be initialized with "true" or "false" (case insensitive)
* @NA_DATA_TYPE_POINTER: a ( void * ) pointer
* @NA_DATA_TYPE_STRING: an ASCII string
* @NA_DATA_TYPE_STRING_LIST: a list of ASCII strings
* @NA_DATA_TYPE_LOCALE_STRING: a localized UTF-8 string
* @NA_DATA_TYPE_UINT: an unsigned integer
* @NA_DATA_TYPE_UINT_LIST: a list of unsigned integers
*
* Each elementary data which would take advantage of #NABoxed facilities
* should be typed at instanciation time.
*
* #NAIFactoryProvider implementations should provide a primitive for reading
* (resp. writing) a value for each of these elementary data types.
*
* <note>
* <para>
* Please note that this enumeration may be compiled in by the extensions.
* They must so remain fixed, unless you are prepared to see strange effects
* (e.g. an extension has been compiled with %NA_DATA_TYPE_STRING = 2, while you
* have inserted another element, making it to 3 !) - or you know what
* you are doing...
* </para>
* <para>
* So, only add new items at the end of the enum. You have been warned!
* </para>
* </note>
*
* Since: 2.30
*/
typedef enum {
NA_DATA_TYPE_BOOLEAN = 1,
NA_DATA_TYPE_POINTER,
NA_DATA_TYPE_STRING,
NA_DATA_TYPE_STRING_LIST,
NA_DATA_TYPE_LOCALE_STRING,
NA_DATA_TYPE_UINT,
NA_DATA_TYPE_UINT_LIST,
/*< private >*/
/* count of defined types */
NA_DATA_TYPE_N
}
NADataType;
const gchar *na_data_types_get_mateconf_dump_key( guint type );
G_END_DECLS
#endif /* __CAJA_ACTIONS_API_NA_DATA_TYPES_H__ */
|
NiceandGently/caja-actions
|
src/api/na-data-types.h
|
C
|
gpl-2.0
| 3,054 |
<?php if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly ?>
<div id="ab_import_customers_dialog" class="modal hide fade" tabindex=-1 role="dialog" aria-labelledby="importCustomersModalLabel" aria-hidden="true">
<div class="dialog-content">
<form class="form-horizontal" enctype="multipart/form-data" action="?page=ab-customers" method="POST">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="importCustomersModalLabel"><?php _e( 'Import', 'ab' ) ?></h3>
</div>
<div class="modal-body">
<div class="control-group">
<label class="control-label"><?php _e( 'Note' , 'ab' ) ?></label>
<div class="controls">
<?php _e( 'You may import list of clients in CSV format. The file needs to have three columns: Name, Phone and Email.' , 'ab' ) ?>
</div>
</div>
<div class="control-group">
<label class="control-label"><?php _e( 'Select file' , 'ab' ) ?></label>
<div class="controls">
<input name="import_customers_file" type="file">
</div>
</div>
<div class="control-group">
<label class="control-label"><?php _e( 'Delimiter' , 'ab' ) ?></label>
<div class="controls">
<select name="import_customers_delimiter">
<option value=","><?php _e( 'Comma (,)', 'ab' ) ?></option>
<option value=";"><?php _e( 'Semicolon (;)', 'ab' ) ?></option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<div class="ab-modal-button">
<input type="hidden" name="import">
<input type="submit" class="btn btn-info ab-popup-save ab-update-button" value="<?php _e( 'Import' , 'ab' ) ?>" />
<button class="ab-reset-form" data-dismiss="modal" aria-hidden="true"><?php _e( 'Cancel' , 'ab' ) ?></button>
</div>
</div>
</form>
</div>
</div>
|
CooperWhitlow/esr-com
|
wp-content/plugins/appointment-booking/backend/modules/customer/templates/_import.php
|
PHP
|
gpl-2.0
| 2,344 |
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "../qcommon/q_shared.h"
#include "../qcommon/qcommon.h"
#include "sys_local.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <pwd.h>
#include <libgen.h>
#include <signal.h>
qboolean stdinIsATTY;
// Used to determine where to store user-specific files
static char homePath[ MAX_OSPATH ] = { 0 };
/*
==================
Sys_DefaultHomePath
==================
*/
char *Sys_DefaultHomePath(void)
{
char *p;
if( !*homePath )
{
if( ( p = getenv( "HOME" ) ) != NULL )
{
Q_strncpyz( homePath, p, sizeof( homePath ) );
#ifdef MACOS_X
Q_strcat( homePath, sizeof( homePath ), "/Library/Application Support/Quake3" );
#else
Q_strcat( homePath, sizeof( homePath ), "/.q3a" );
#endif
if( mkdir( homePath, 0777 ) )
{
if( errno != EEXIST )
{
Sys_Error( "Unable to create directory \"%s\", error is %s(%d)\n",
homePath, strerror( errno ), errno );
}
}
}
}
return homePath;
}
/*
================
Sys_Milliseconds
================
*/
/* base time in seconds, that's our origin
timeval:tv_sec is an int:
assuming this wraps every 0x7fffffff - ~68 years since the Epoch (1970) - we're safe till 2038
using unsigned long data type to work right with Sys_XTimeToSysTime */
unsigned long sys_timeBase = 0;
/* current time in ms, using sys_timeBase as origin
NOTE: sys_timeBase*1000 + curtime -> ms since the Epoch
0x7fffffff ms - ~24 days
although timeval:tv_usec is an int, I'm not sure wether it is actually used as an unsigned int
(which would affect the wrap period) */
int curtime;
int Sys_Milliseconds (void)
{
struct timeval tp;
gettimeofday(&tp, NULL);
if (!sys_timeBase)
{
sys_timeBase = tp.tv_sec;
return tp.tv_usec/1000;
}
curtime = (tp.tv_sec - sys_timeBase)*1000 + tp.tv_usec/1000;
return curtime;
}
#if !id386
/*
==================
fastftol
==================
*/
long fastftol( float f )
{
return (long)f;
}
/*
==================
Sys_SnapVector
==================
*/
void Sys_SnapVector( float *v )
{
v[0] = rint(v[0]);
v[1] = rint(v[1]);
v[2] = rint(v[2]);
}
#endif
/*
==================
Sys_RandomBytes
==================
*/
qboolean Sys_RandomBytes( byte *string, int len )
{
FILE *fp;
fp = fopen( "/dev/urandom", "r" );
if( !fp )
return qfalse;
if( !fread( string, sizeof( byte ), len, fp ) )
{
fclose( fp );
return qfalse;
}
fclose( fp );
return qtrue;
}
/*
==================
Sys_GetCurrentUser
==================
*/
char *Sys_GetCurrentUser( void )
{
struct passwd *p;
if ( (p = getpwuid( getuid() )) == NULL ) {
return "player";
}
return p->pw_name;
}
/*
==================
Sys_GetClipboardData
==================
*/
char *Sys_GetClipboardData(void)
{
return NULL;
}
#define MEM_THRESHOLD 96*1024*1024
/*
==================
Sys_LowPhysicalMemory
TODO
==================
*/
qboolean Sys_LowPhysicalMemory( void )
{
return qfalse;
}
/*
==================
Sys_Basename
==================
*/
const char *Sys_Basename( char *path )
{
return basename( path );
}
/*
==================
Sys_Dirname
==================
*/
const char *Sys_Dirname( char *path )
{
return dirname( path );
}
/*
==================
Sys_Mkdir
==================
*/
void Sys_Mkdir( const char *path )
{
mkdir( path, 0777 );
}
/*
==================
Sys_Cwd
==================
*/
char *Sys_Cwd( void )
{
static char cwd[MAX_OSPATH];
getcwd( cwd, sizeof( cwd ) - 1 );
cwd[MAX_OSPATH-1] = 0;
return cwd;
}
/*
==============================================================
DIRECTORY SCANNING
==============================================================
*/
#define MAX_FOUND_FILES 0x1000
/*
==================
Sys_ListFilteredFiles
==================
*/
void Sys_ListFilteredFiles( const char *basedir, char *subdirs, char *filter, char **list, int *numfiles )
{
char search[MAX_OSPATH], newsubdirs[MAX_OSPATH];
char filename[MAX_OSPATH];
DIR *fdir;
struct dirent *d;
struct stat st;
if ( *numfiles >= MAX_FOUND_FILES - 1 ) {
return;
}
if (strlen(subdirs)) {
Com_sprintf( search, sizeof(search), "%s/%s", basedir, subdirs );
}
else {
Com_sprintf( search, sizeof(search), "%s", basedir );
}
if ((fdir = opendir(search)) == NULL) {
return;
}
while ((d = readdir(fdir)) != NULL) {
Com_sprintf(filename, sizeof(filename), "%s/%s", search, d->d_name);
if (stat(filename, &st) == -1)
continue;
if (st.st_mode & S_IFDIR) {
if (Q_stricmp(d->d_name, ".") && Q_stricmp(d->d_name, "..")) {
if (strlen(subdirs)) {
Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s/%s", subdirs, d->d_name);
}
else {
Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s", d->d_name);
}
Sys_ListFilteredFiles( basedir, newsubdirs, filter, list, numfiles );
}
}
if ( *numfiles >= MAX_FOUND_FILES - 1 ) {
break;
}
Com_sprintf( filename, sizeof(filename), "%s/%s", subdirs, d->d_name );
if (!Com_FilterPath( filter, filename, qfalse ))
continue;
list[ *numfiles ] = CopyString( filename );
(*numfiles)++;
}
closedir(fdir);
}
/*
==================
Sys_ListFiles
==================
*/
char **Sys_ListFiles( const char *directory, const char *extension, char *filter, int *numfiles, qboolean wantsubs )
{
struct dirent *d;
DIR *fdir;
qboolean dironly = wantsubs;
char search[MAX_OSPATH];
int nfiles;
char **listCopy;
char *list[MAX_FOUND_FILES];
int i;
struct stat st;
int extLen;
if (filter) {
nfiles = 0;
Sys_ListFilteredFiles( directory, "", filter, list, &nfiles );
list[ nfiles ] = NULL;
*numfiles = nfiles;
if (!nfiles)
return NULL;
listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
for ( i = 0 ; i < nfiles ; i++ ) {
listCopy[i] = list[i];
}
listCopy[i] = NULL;
return listCopy;
}
if ( !extension)
extension = "";
if ( extension[0] == '/' && extension[1] == 0 ) {
extension = "";
dironly = qtrue;
}
extLen = strlen( extension );
// search
nfiles = 0;
if ((fdir = opendir(directory)) == NULL) {
*numfiles = 0;
return NULL;
}
while ((d = readdir(fdir)) != NULL) {
Com_sprintf(search, sizeof(search), "%s/%s", directory, d->d_name);
if (stat(search, &st) == -1)
continue;
if ((dironly && !(st.st_mode & S_IFDIR)) ||
(!dironly && (st.st_mode & S_IFDIR)))
continue;
if (*extension) {
if ( strlen( d->d_name ) < strlen( extension ) ||
Q_stricmp(
d->d_name + strlen( d->d_name ) - strlen( extension ),
extension ) ) {
continue; // didn't match
}
}
if ( nfiles == MAX_FOUND_FILES - 1 )
break;
list[ nfiles ] = CopyString( d->d_name );
nfiles++;
}
list[ nfiles ] = NULL;
closedir(fdir);
// return a copy of the list
*numfiles = nfiles;
if ( !nfiles ) {
return NULL;
}
listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
for ( i = 0 ; i < nfiles ; i++ ) {
listCopy[i] = list[i];
}
listCopy[i] = NULL;
return listCopy;
}
/*
==================
Sys_FreeFileList
==================
*/
void Sys_FreeFileList( char **list )
{
int i;
if ( !list ) {
return;
}
for ( i = 0 ; list[i] ; i++ ) {
Z_Free( list[i] );
}
Z_Free( list );
}
#ifdef MACOS_X
/*
=================
Sys_StripAppBundle
Discovers if passed dir is suffixed with the directory structure of a Mac OS X
.app bundle. If it is, the .app directory structure is stripped off the end and
the result is returned. If not, dir is returned untouched.
=================
*/
char *Sys_StripAppBundle( char *dir )
{
static char cwd[MAX_OSPATH];
Q_strncpyz(cwd, dir, sizeof(cwd));
if(strcmp(Sys_Basename(cwd), "MacOS"))
return dir;
Q_strncpyz(cwd, Sys_Dirname(cwd), sizeof(cwd));
if(strcmp(Sys_Basename(cwd), "Contents"))
return dir;
Q_strncpyz(cwd, Sys_Dirname(cwd), sizeof(cwd));
if(!strstr(Sys_Basename(cwd), ".app"))
return dir;
Q_strncpyz(cwd, Sys_Dirname(cwd), sizeof(cwd));
return cwd;
}
#endif // MACOS_X
/*
==================
Sys_Sleep
Block execution for msec or until input is recieved.
==================
*/
void Sys_Sleep( int msec )
{
if( stdinIsATTY )
{
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(STDIN_FILENO, &fdset);
if( msec < 0 )
{
select(STDIN_FILENO + 1, &fdset, NULL, NULL, NULL);
}
else
{
struct timeval timeout;
timeout.tv_sec = msec/1000;
timeout.tv_usec = (msec%1000)*1000;
select(STDIN_FILENO + 1, &fdset, NULL, NULL, &timeout);
}
}
else
{
// With nothing to select() on, we can't wait indefinitely
if( msec < 0 )
msec = 2;
usleep( msec * 1000 );
}
}
/*
==============
Sys_ErrorDialog
Display an error message
==============
*/
void Sys_ErrorDialog( const char *error )
{
char buffer[ 1024 ];
unsigned int size;
fileHandle_t f;
const char *fileName = "crashlog.txt";
Sys_Print( va( "%s\n", error ) );
// Write console log to file
f = FS_FOpenFileWrite( fileName );
if( !f )
{
Com_Printf( "ERROR: couldn't open %s\n", fileName );
return;
}
while( ( size = CON_LogRead( buffer, sizeof( buffer ) ) ) > 0 )
FS_Write( buffer, size, f );
FS_FCloseFile( f );
}
/*
==============
Sys_PlatformInit
Unix specific initialisation
==============
*/
void Sys_PlatformInit( void )
{
const char* term = getenv( "TERM" );
signal( SIGHUP, Sys_SigHandler );
signal( SIGQUIT, Sys_SigHandler );
signal( SIGTRAP, Sys_SigHandler );
signal( SIGIOT, Sys_SigHandler );
signal( SIGBUS, Sys_SigHandler );
stdinIsATTY = isatty( STDIN_FILENO ) &&
!( term && ( !strcmp( term, "raw" ) || !strcmp( term, "dumb" ) ) );
}
|
danielepantaleone/ioq3-UrT
|
code/sys/sys_unix.c
|
C
|
gpl-2.0
| 10,626 |
/home/ollilas1/gromacs/gromacs402/bin/protonate -f TI.mdp -c init2_TI5.gro -p system.top -o topol402.tpr -v
|
NMRLipids/nmrlipids.blogspot.fi
|
scratch/DLPCberger/dehydration/4waterPERpc/make402tpr.sh
|
Shell
|
gpl-2.0
| 107 |
import unittest
from wicd import wnettools
class TestWnettools(unittest.TestCase):
def setUp(self):
self.interface = wnettools.BaseInterface('eth0')
def test_find_wireless_interface(self):
interfaces = wnettools.GetWirelessInterfaces()
# wlan0 may change depending on your system
self.assertTrue('wlan0' in interfaces)
def test_find_wired_interface(self):
interfaces = wnettools.GetWiredInterfaces()
# eth0 may change depending on your system
self.assertTrue('eth0' in interfaces)
def test_wext_is_valid_wpasupplicant_driver(self):
self.assertTrue(wnettools.IsValidWpaSuppDriver('wext'))
def test_needs_external_calls_not_implemented(self):
self.assertRaises(NotImplementedError, wnettools.NeedsExternalCalls)
def test_get_ip_not_implemented(self):
self.assertRaises(NotImplementedError, self.interface.GetIP)
def test_is_up_not_implemented(self):
self.assertRaises(NotImplementedError, self.interface.IsUp)
def test_enable_debug_mode(self):
self.interface.SetDebugMode(True)
self.assertTrue(self.interface.verbose)
def test_disable_debug_mode(self):
self.interface.SetDebugMode(False)
self.assertFalse(self.interface.verbose)
def test_interface_name_sanitation(self):
interface = wnettools.BaseInterface('blahblah; uptime > /tmp/blah | cat')
self.assertEquals(interface.iface, 'blahblahuptimetmpblahcat')
def test_freq_translation_low(self):
freq = '2.412 GHz'
interface = wnettools.BaseWirelessInterface('wlan0')
self.assertEquals(interface._FreqToChannel(freq), 1)
def test_freq_translation_high(self):
freq = '2.484 GHz'
interface = wnettools.BaseWirelessInterface('wlan0')
self.assertEquals(interface._FreqToChannel(freq), 14)
def test_generate_psk(self):
interface = wnettools.BaseWirelessInterface('wlan0')
psk = interface.GeneratePSK({'essid' : 'Network 1', 'key' : 'arandompassphrase'})
self.assertEquals(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9af084b3433f3710e658a7be')
def suite():
suite = unittest.TestSuite()
tests = []
[ tests.append(test) for test in dir(TestWnettools) if test.startswith('test') ]
for test in tests:
suite.addTest(TestWnettools(test))
return suite
if __name__ == '__main__':
unittest.main()
|
HiLiph/wicd
|
tests/testwnettools.py
|
Python
|
gpl-2.0
| 2,242 |
/*!
* log.js
*
* Author: Michael Zelensky http://miha.in
*
* Summary: cross-browser wrapper for Console methods
* License: MIT
* Version: 1.0
*
*/
var log = {};
/* IE9 no console hack */
if (typeof console === 'undefined') {
window.console = {
log : function(){},
debug : function(){},
info : function(){},
warn : function(){},
error : function(){}
}
}
/* IE9 console.log.apply fix */
//init state - no console
log.xlog = function(){},
log.xdebug = function(){},
log.xinfo = function(){},
log.xwarn = function(){},
log.xerror = function(){};
// with console
if (console) {
//modern browsers
if (console.log.apply) {
log.xlog = function() { console.log.apply(console, arguments); };
log.xdebug = function() { console.debug.apply(console, arguments); };
log.xinfo = function() { console.info.apply(console, arguments); };
log.xwarn = function() { console.warn.apply(console, arguments); };
log.xerror = function() { console.error.apply(console, arguments); };
//ie9
} else {
log.xlog = Function.prototype.bind.call(console.log, console);
log.xdebug = function() {console.log('Error: console.debug is not supported by the browser')};
log.xinfo = Function.prototype.bind.call(console.info, console);
log.xwarn = Function.prototype.bind.call(console.warn, console);
log.xerror = Function.prototype.bind.call(console.error, console);
}
// console.time implementation for IE
if (typeof(window.console.time) == "undefined") {
console.time = function(name, reset){
if(!name) { return; }
var time = new Date().getTime();
if(!console.timeCounters) { console.timeCounters = {}; }
var key = "KEY" + name.toString();
if(!reset && console.timeCounters[key]) { return; }
console.timeCounters[key] = time;
};
console.timeEnd = function(name){
var time = new Date().getTime();
if(!console.timeCounters) { return; }
var key = "KEY" + name.toString();
var timeCounter = console.timeCounters[key];
var diff;
if(timeCounter) {
diff = time - timeCounter;
var label = name + ": " + diff + "ms";
console.info(label);
delete console.timeCounters[key];
}
return diff;
};
}
}
log.log = function () {
log.xlog.apply(console, arguments);
};
log.debug = function () {
log.xdebug.apply(console, arguments);
};
log.info = function () {
log.xinfo.apply(console, arguments);
};
log.warn = function () {
log.xwarn.apply(console, arguments);
};
log.error = function () {
log.xerror.apply(console, arguments);
};
log.time = function (label) {
if (console && console.time) {
console.time(label);
}
};
log.timeEnd = function (label) {
if (console && console.timeEnd) {
console.timeEnd(label);
}
};
log.group = function (label) {
if (console && console.group) {
console.group(label);
}
};
log.groupEnd = function (label) {
if (console && console.groupEnd) {
console.groupEnd(label);
}
};
|
maglub/piSnapper
|
public/js/log.js
|
JavaScript
|
gpl-2.0
| 2,972 |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace SETTING
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
//Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new SETTING());
}
}
}
|
Chengxiaozhi/GunArk
|
SETTING V2.0/SETTING/Program.cs
|
C#
|
gpl-2.0
| 453 |
/* packet-vlan.c
* Routines for VLAN 802.1Q ethernet header disassembly
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#define NEW_PROTO_TREE_API
#include "config.h"
#include <epan/packet.h>
#include <epan/capture_dissectors.h>
#include <wsutil/pint.h>
#include <epan/expert.h>
#include "packet-ieee8023.h"
#include "packet-ipx.h"
#include "packet-llc.h"
#include <epan/etypes.h>
#include <epan/prefs.h>
#include <epan/to_str.h>
#include <epan/addr_resolv.h>
void proto_register_vlan(void);
void proto_reg_handoff_vlan(void);
static unsigned int q_in_q_ethertype = 0x9100;
static gboolean vlan_summary_in_tree = TRUE;
static dissector_handle_t vlan_handle;
static dissector_handle_t ethertype_handle;
static header_field_info *hfi_vlan = NULL;
#define VLAN_HFI_INIT HFI_INIT(proto_vlan)
/* From Table G-2 of IEEE standard 802.1D-2004 */
static const value_string pri_vals[] = {
{ 1, "Background" },
{ 2, "Spare" },
{ 0, "Best Effort (default)" },
{ 3, "Excellent Effort" },
{ 4, "Controlled Load" },
{ 5, "Video, < 100ms latency and jitter" },
{ 6, "Voice, < 10ms latency and jitter" },
{ 7, "Network Control" },
{ 0, NULL }
};
static header_field_info hfi_vlan_priority VLAN_HFI_INIT = {
"Priority", "vlan.priority", FT_UINT16, BASE_DEC,
VALS(pri_vals), 0xE000, "Descriptions are recommendations from IEEE standard 802.1D-2004", HFILL };
static const value_string cfi_vals[] = {
{ 0, "Canonical" },
{ 1, "Non-canonical" },
{ 0, NULL }
};
static header_field_info hfi_vlan_cfi VLAN_HFI_INIT = {
"CFI", "vlan.cfi", FT_UINT16, BASE_DEC,
VALS(cfi_vals), 0x1000, "Canonical Format Identifier", HFILL };
static header_field_info hfi_vlan_id VLAN_HFI_INIT = {
"ID", "vlan.id", FT_UINT16, BASE_DEC,
NULL, 0x0FFF, "VLAN ID", HFILL };
static header_field_info hfi_vlan_id_name VLAN_HFI_INIT = {
"Name", "vlan.id_name", FT_STRING, STR_UNICODE,
NULL, 0x0, "VLAN ID Name", HFILL };
static header_field_info hfi_vlan_etype VLAN_HFI_INIT = {
"Type", "vlan.etype", FT_UINT16, BASE_HEX,
VALS(etype_vals), 0x0, "Ethertype", HFILL };
static header_field_info hfi_vlan_len VLAN_HFI_INIT = {
"Length", "vlan.len", FT_UINT16, BASE_DEC,
NULL, 0x0, NULL, HFILL };
static header_field_info hfi_vlan_trailer VLAN_HFI_INIT = {
"Trailer", "vlan.trailer", FT_BYTES, BASE_NONE,
NULL, 0x0, "VLAN Trailer", HFILL };
static gint ett_vlan = -1;
static expert_field ei_vlan_len = EI_INIT;
static gboolean
capture_vlan(const guchar *pd, int offset, int len, capture_packet_info_t *cpinfo, const union wtap_pseudo_header *pseudo_header _U_ ) {
guint16 encap_proto;
if ( !BYTES_ARE_IN_FRAME(offset,len,5) )
return FALSE;
encap_proto = pntoh16( &pd[offset+2] );
if ( encap_proto <= IEEE_802_3_MAX_LEN) {
if ( pd[offset+4] == 0xff && pd[offset+5] == 0xff ) {
return capture_ipx(pd,offset+4,len, cpinfo, pseudo_header);
} else {
return capture_llc(pd,offset+4,len, cpinfo, pseudo_header);
}
}
return try_capture_dissector("ethertype", encap_proto, pd, offset+4, len, cpinfo, pseudo_header);
}
static void
columns_set_vlan(column_info *cinfo, guint16 tci)
{
static const char fast_str[][2] = { "0", "1", "2", "3", "4", "5", "6", "7" };
char id_str[16];
guint32_to_str_buf(tci & 0xFFF, id_str, sizeof(id_str));
col_add_lstr(cinfo, COL_INFO,
"PRI: ", fast_str[(tci >> 13) & 7], " "
"CFI: ", fast_str[(tci >> 12) & 1], " "
"ID: ", id_str,
COL_ADD_LSTR_TERMINATOR);
col_add_str(cinfo, COL_8021Q_VLAN_ID, id_str);
}
static int
dissect_vlan(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
{
proto_item *ti;
guint16 tci, vlan_id;
guint16 encap_proto;
gboolean is_802_2;
proto_tree *vlan_tree;
proto_item *item;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "VLAN");
col_clear(pinfo->cinfo, COL_INFO);
tci = tvb_get_ntohs( tvb, 0 );
vlan_id = tci & 0xFFF;
/* Add the VLAN Id if it's the first one*/
if (pinfo->vlan_id == 0) {
pinfo->vlan_id = vlan_id;
}
columns_set_vlan(pinfo->cinfo, tci);
vlan_tree = NULL;
if (tree) {
ti = proto_tree_add_item(tree, hfi_vlan, tvb, 0, 4, ENC_NA);
if (vlan_summary_in_tree) {
proto_item_append_text(ti, ", PRI: %u, CFI: %u, ID: %u",
(tci >> 13), ((tci >> 12) & 1), vlan_id);
}
vlan_tree = proto_item_add_subtree(ti, ett_vlan);
proto_tree_add_item(vlan_tree, &hfi_vlan_priority, tvb, 0, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(vlan_tree, &hfi_vlan_cfi, tvb, 0, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(vlan_tree, &hfi_vlan_id, tvb, 0, 2, ENC_BIG_ENDIAN);
if (gbl_resolv_flags.vlan_name) {
item = proto_tree_add_string(vlan_tree, &hfi_vlan_id_name, tvb, 0, 2,
get_vlan_name(wmem_packet_scope(), vlan_id));
PROTO_ITEM_SET_GENERATED(item);
}
}
encap_proto = tvb_get_ntohs(tvb, 2);
if (encap_proto <= IEEE_802_3_MAX_LEN) {
/* Is there an 802.2 layer? I can tell by looking at the first 2
bytes after the VLAN header. If they are 0xffff, then what
follows the VLAN header is an IPX payload, meaning no 802.2.
(IPX/SPX is they only thing that can be contained inside a
straight 802.3 packet, so presumably the same applies for
Ethernet VLAN packets). A non-0xffff value means that there's an
802.2 layer inside the VLAN layer */
is_802_2 = TRUE;
/* Don't throw an exception for this check (even a BoundsError) */
if (tvb_captured_length_remaining(tvb, 4) >= 2) {
if (tvb_get_ntohs(tvb, 4) == 0xffff) {
is_802_2 = FALSE;
}
}
dissect_802_3(encap_proto, is_802_2, tvb, 4, pinfo, tree, vlan_tree,
hfi_vlan_len.id, hfi_vlan_trailer.id, &ei_vlan_len, 0);
} else {
ethertype_data_t ethertype_data;
ethertype_data.etype = encap_proto;
ethertype_data.offset_after_ethertype = 4;
ethertype_data.fh_tree = vlan_tree;
ethertype_data.etype_id = hfi_vlan_etype.id;
ethertype_data.trailer_id = hfi_vlan_trailer.id;
ethertype_data.fcs_len = 0;
call_dissector_with_data(ethertype_handle, tvb, pinfo, tree, ðertype_data);
}
return tvb_captured_length(tvb);
}
void
proto_register_vlan(void)
{
#ifndef HAVE_HFI_SECTION_INIT
static header_field_info *hfi[] = {
&hfi_vlan_priority,
&hfi_vlan_cfi,
&hfi_vlan_id,
&hfi_vlan_id_name,
&hfi_vlan_etype,
&hfi_vlan_len,
&hfi_vlan_trailer,
};
#endif /* HAVE_HFI_SECTION_INIT */
static gint *ett[] = {
&ett_vlan
};
static ei_register_info ei[] = {
{ &ei_vlan_len, { "vlan.len.past_end", PI_MALFORMED, PI_ERROR, "Length field value goes past the end of the payload", EXPFILL }},
};
module_t *vlan_module;
expert_module_t* expert_vlan;
int proto_vlan;
proto_vlan = proto_register_protocol("802.1Q Virtual LAN", "VLAN", "vlan");
hfi_vlan = proto_registrar_get_nth(proto_vlan);
proto_register_fields(proto_vlan, hfi, array_length(hfi));
proto_register_subtree_array(ett, array_length(ett));
expert_vlan = expert_register_protocol(proto_vlan);
expert_register_field_array(expert_vlan, ei, array_length(ei));
vlan_module = prefs_register_protocol(proto_vlan, proto_reg_handoff_vlan);
prefs_register_bool_preference(vlan_module, "summary_in_tree",
"Show vlan summary in protocol tree",
"Whether the vlan summary line should be shown in the protocol tree",
&vlan_summary_in_tree);
prefs_register_uint_preference(vlan_module, "qinq_ethertype",
"802.1QinQ Ethertype (in hex)",
"The (hexadecimal) Ethertype used to indicate 802.1QinQ VLAN in VLAN tunneling.",
16, &q_in_q_ethertype);
vlan_handle = create_dissector_handle(dissect_vlan, proto_vlan);
}
void
proto_reg_handoff_vlan(void)
{
static gboolean prefs_initialized = FALSE;
static unsigned int old_q_in_q_ethertype;
if (!prefs_initialized)
{
dissector_add_uint("ethertype", ETHERTYPE_VLAN, vlan_handle);
register_capture_dissector("ethertype", ETHERTYPE_VLAN, capture_vlan, hfi_vlan->id);
prefs_initialized = TRUE;
}
else
{
dissector_delete_uint("ethertype", old_q_in_q_ethertype, vlan_handle);
}
old_q_in_q_ethertype = q_in_q_ethertype;
ethertype_handle = find_dissector_add_dependency("ethertype", hfi_vlan->id);
dissector_add_uint("ethertype", q_in_q_ethertype, vlan_handle);
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local Variables:
* c-basic-offset: 2
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=2 tabstop=8 expandtab:
* :indentSize=2:tabSize=8:noTabs=true:
*/
|
dveeden/wireshark
|
epan/dissectors/packet-vlan.c
|
C
|
gpl-2.0
| 9,717 |
/*
* Renderer.cpp
*
* Created on: 24/03/2014
* Author: remnanjona
*/
#include "../pipeline/Pipeline.h"
#include "../shader/Shader.h"
#include "Renderer.h"
namespace std {
Renderer::Renderer(): buff(GL_ARRAY_BUFFER, false), tree(256) {
vector<texvec> data = {
{glm::vec4(-1,-1,0,1), glm::vec2(0,0)}, {glm::vec4(1,-1,0,1), glm::vec2(t.width,0)},
{glm::vec4(-1,1,0,1), glm::vec2(0,t.height)}, {glm::vec4(1,1,0,1), glm::vec2(t.width,t.height)}
};
buff.insert(data);
// Init Pipeline
Shader test_vert("glsl/test.vert", GL_VERTEX_SHADER);
Shader test_frag("glsl/test.frag", GL_FRAGMENT_SHADER);
tex_pipeline.addStage(test_vert, GL_VERTEX_SHADER_BIT);
tex_pipeline.addStage(test_frag, GL_FRAGMENT_SHADER_BIT);
Shader raytracer("glsl/raytrace.comp", GL_COMPUTE_SHADER);
comp_pipeline.addStage(raytracer, GL_COMPUTE_SHADER_BIT);
}
Renderer::~Renderer() {
// TODO Auto-generated destructor stub
}
void Renderer::draw() {
glBindProgramPipeline(comp_pipeline.name);
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_RECTANGLE_NV, t.texture);
glBindImageTexture(0, t.texture, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8);
tree.bind(1);
glDispatchCompute(t.width/16, t.height/16, 1);
glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT);
glBindProgramPipeline(tex_pipeline.name);
glBindBuffer( GL_ARRAY_BUFFER, buff.location );
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(texvec), 0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(texvec), (GLvoid*)sizeof(glm::vec4));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindTexture(GL_TEXTURE_RECTANGLE_NV, t.texture);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
}
} /* namespace std */
|
Jon0/optix_rt
|
src/render/Renderer.cpp
|
C++
|
gpl-2.0
| 1,795 |
#define TUNE_PROGRAM_BUILD 1
#include "..\..\mpn\generic\inv_divappr_q.c"
|
gnooth/xcl
|
mpir/build.vc10/tune/inv_divappr_q.c
|
C
|
gpl-2.0
| 76 |
/*
* Implementation of revdir.h that saves a lot more space than the original dirpack scheme.
* Designed to be included in revdir.c.
*/
#define REV_DIR_HASH 786433
/* Names are getting confusing. Externally we call things a revdir, where really it's
* just a list of revisions.
* Internally in treepack, we store as a directory of revisions, which each level having
* files and subdirectories. A good name for this would appear to be revdir...
*/
struct _rev_pack {
/* a directory containing a collection of subdirs and a collection of file revisions */
hash_t hash;
serial_t ndirs;
serial_t nfiles;
rev_pack **dirs;
cvs_commit **files;
};
typedef struct _rev_pack_hash {
struct _rev_pack_hash *next;
rev_pack dir;
} rev_pack_hash;
static rev_pack_hash *buckets[REV_DIR_HASH];
typedef struct _pack_frame {
const master_dir *dir;
const rev_pack **dirs;
hash_t hash;
unsigned short ndirs;
unsigned short sdirs;
} pack_frame;
/* variables used by streaming pack interface */
static serial_t sfiles = 0;
static serial_t nfiles = 0;
static const cvs_commit **files = NULL;
static pack_frame *frame;
static pack_frame frames[MAX_DIR_DEPTH];
static const rev_pack *
rev_pack_dir(void)
{
rev_pack_hash **bucket = &buckets[frame->hash % REV_DIR_HASH];
rev_pack_hash *h;
/* avoid packing a file list if we've done it before */
for (h = *bucket; h; h = h->next) {
if (h->dir.hash == frame->hash &&
h->dir.nfiles == nfiles && h->dir.ndirs == frame->ndirs &&
!memcmp(frame->dirs, h->dir.dirs, frame->ndirs * sizeof(rev_pack *)) &&
!memcmp(files, h->dir.files, nfiles * sizeof(cvs_commit *)))
{
return &h->dir;
}
}
h = xmalloc(sizeof(rev_pack_hash), __func__);
h->next = *bucket;
*bucket = h;
h->dir.hash = frame->hash;
h->dir.ndirs = frame->ndirs;
h->dir.dirs = xmalloc(frame->ndirs * sizeof(rev_pack *), __func__);
memcpy(h->dir.dirs, frame->dirs, frame->ndirs * sizeof(rev_pack *));
h->dir.nfiles = nfiles;
h->dir.files = xmalloc(nfiles * sizeof(cvs_commit *), __func__);
memcpy(h->dir.files, files, nfiles * sizeof(cvs_commit *));
return &h->dir;
}
/* Post order tree traversal iterator. */
typedef struct _dir_pos {
const rev_pack *parent;
rev_pack **dir;
rev_pack **dirmax;
} dir_pos;
struct _revdir_iter {
cvs_commit **file;
cvs_commit **filemax;
size_t dirpos; // current dir is dirstack[dirpos]
dir_pos dirstack[MAX_DIR_DEPTH];
};
bool
revdir_iter_same_dir(const revdir_iter *it1, const revdir_iter *it2)
/* Are two file iterators pointing to the same revdir? */
{
return it1->dirstack[it1->dirpos].dir == it2->dirstack[it2->dirpos].dir;
}
cvs_commit *
revdir_iter_next(revdir_iter *it) {
while (1) {
if (it->file != it->filemax)
return *it->file++;
// end of stack
if (!it->dirpos)
return NULL;
// pop the stack
dir_pos *d = &it->dirstack[--it->dirpos];
if (++d->dir != d->dirmax) {
// does new dir have subdirs?
const rev_pack *dir = *d->dir;
while (1) {
d = &it->dirstack[++it->dirpos];
d->parent = dir;
d->dir = dir->dirs;
d->dirmax = dir->dirs + dir->ndirs;
if (dir->ndirs > 0)
dir = dir->dirs[0];
else
break;
}
it->file = dir->files;
it->filemax = dir->files + dir->nfiles;
} else {
// all subdirs done, now do files in this dir
const rev_pack *dir = d->parent;
it->file = dir->files;
it->filemax = dir->files + dir->nfiles;
}
}
}
cvs_commit *
revdir_iter_next_dir(revdir_iter *it)
/* skip the current directory */
{
while(1) {
if (!it->dirpos)
return NULL;
dir_pos *d = &it->dirstack[--it->dirpos];
if (++d->dir != d->dirmax) {
const rev_pack *dir = *d->dir;
while (1) {
d = &it->dirstack[++it->dirpos];
d->parent = dir;
d->dir = dir->dirs;
d->dirmax = dir->dirs + dir->ndirs;
if (dir->ndirs > 0)
dir = dir->dirs[0];
else
break;
}
it->file = dir->files;
it->filemax = dir->files + dir->nfiles;
} else {
const rev_pack *dir = d->parent;
it->file = dir->files;
it->filemax = dir->files + dir->nfiles;
}
if (it->file != it->filemax)
return *it->file++;
}
}
void
revdir_iter_start(revdir_iter *it, const revdir *revdir)
/* post order traversal of rev_dir tree */
{
const rev_pack *dir = revdir->revpack;
it->dirpos = -1;
while (1) {
dir_pos *d = &it->dirstack[++it->dirpos];
d->parent = dir;
d->dir = dir->dirs;
d->dirmax = dir->dirs + dir->ndirs;
if (dir->ndirs > 0)
dir = dir->dirs[0];
else
break;
}
it->file = dir->files;
it->filemax = dir->files + dir->nfiles;
}
revdir_iter *
revdir_iter_alloc(const revdir *revdir)
{
revdir_iter *it = xmalloc(sizeof(revdir_iter), __func__);
revdir_iter_start(it, revdir);
return it;
}
static const master_dir *
first_subdir (const master_dir *child, const master_dir *ancestor)
/* in ancestor/d1/d2/child, return d1 */
{
while (child->parent != ancestor)
child = child->parent;
return child;
}
void
revdir_pack_alloc(const size_t max_size)
{
if (!files) {
files = xmalloc(max_size * sizeof(cvs_commit *), __func__);
sfiles = max_size;
} else if (sfiles < max_size) {
files = xrealloc(files, max_size * sizeof(cvs_commit *), __func__);
sfiles = max_size;
}
}
void
revdir_pack_init(void)
{
frame = frames;
nfiles = 0;
frames[0].dir = root_dir;
frames[0].ndirs = 0;
frames[0].hash = hash_init();
}
static void
push_rev_pack(const rev_pack * const r)
/* Store a revpack in the recursive gathering area */
{
unsigned short *s = &frame->sdirs;
if (*s == frame->ndirs) {
if (!*s)
*s = 16;
else
*s *= 2;
frame->dirs = xrealloc(frame->dirs, *s * sizeof(rev_pack *), __func__);
}
frame->dirs[frame->ndirs++] = r;
}
void
revdir_pack_add(const cvs_commit *file, const master_dir *dir)
{
while (1) {
if (frame->dir == dir) {
/* If you are using TREEPACK then this is the hottest inner
* loop in the application. Avoid dereferencing file
*/
files[nfiles++] = file;
/* Proper FNV1a is a byte at a time, but this is effective
* with the amount of data we're typically mixing into the hash
* and very lightweight
*/
frame->hash = (frame->hash ^ (uintptr_t)file) * 16777619U;
return;
}
if (dir_is_ancestor(dir, frame->dir)) {
if (frame - frames == MAX_DIR_DEPTH)
fatal_error("Directories nested too deep, increase MAX_DIR_DEPTH\n");
const master_dir *parent = frame++->dir;
frame->dir = first_subdir(dir, parent);
frame->ndirs = 0;
frame->hash = hash_init();
continue;
}
const rev_pack * const r = rev_pack_dir();
nfiles = 0;
frame--;
frame->hash = HASH_COMBINE(frame->hash, r->hash);
push_rev_pack(r);
}
}
void
revdir_pack_end(revdir *revdir)
{
const rev_pack * r = NULL;
while (1) {
r = rev_pack_dir();
if (frame == frames)
break;
nfiles = 0;
frame--;
frame->hash = HASH_COMBINE(frame->hash, r->hash);
push_rev_pack(r);
}
revdir->revpack = r;
}
void
revdir_pack_free(void)
{
free(files);
files = NULL;
nfiles = 0;
sfiles = 0;
}
static serial_t
revpack_nfiles(const rev_pack *revpack)
{
serial_t c = 0, i;
for (i = 0; i < revpack->ndirs; i++)
c += revpack_nfiles(revpack->dirs[i]);
return c + revpack->nfiles;
}
serial_t
revdir_nfiles(const revdir *revdir)
{
return revpack_nfiles(revdir->revpack);
}
void
revdir_pack_files(const cvs_commit **files, const size_t nfiles, revdir *revdir)
{
size_t i;
#ifdef ORDERDEBUG
fputs("Packing:\n", stderr);
{
const cvs_commit **s;
for (s = files; s < files + nfiles; s++)
fprintf(stderr, "cvs_commit: %s\n", (*s)->master->name);
}
#endif /* ORDERDEBUG */
/*
* We want the files in directory-path order so we get the longest
* possible runs of common directory prefixes, and thus maximum
* space-saving effect out of the next step. This reduces
* working-set size at the expense of the sort runtime.
*
* That used to be done with a qsort(3) call here, but sorting the
* masters at the input stage causes them to come out in the right
* order here, without multiple additional sorts.
*/
revdir_pack_alloc(nfiles);
revdir_pack_init();
for (i = 0; i < nfiles; i++)
revdir_pack_add(files[i], files[i]->dir);
revdir_pack_end(revdir);
revdir_pack_free();
}
void
revdir_free(void)
{
size_t i;
for (i = 0; i < REV_DIR_HASH; i++) {
rev_pack_hash **bucket = &buckets[i];
rev_pack_hash *h;
while ((h = *bucket)) {
*bucket = h->next;
free(h->dir.dirs);
free(h->dir.files);
free(h);
}
}
}
void
revdir_free_bufs(void)
{
size_t i;
for (i = 0; i < MAX_DIR_DEPTH; i++) {
free(frames[i].dirs);
frames[i].dir = NULL;
frames[i].sdirs = 0;
}
}
|
mirror/cvs-fast-export
|
treepack.c
|
C
|
gpl-2.0
| 9,061 |
#
# Makefile for the Linux network (ethercard) device drivers.
#
obj-$(CONFIG_E1000) += e1000/
obj-$(CONFIG_IBM_EMAC) += ibm_emac/
obj-$(CONFIG_IXGB) += ixgb/
obj-$(CONFIG_CHELSIO_T1) += chelsio/
obj-$(CONFIG_CHELSIO_T3) += cxgb3/
obj-$(CONFIG_EHEA) += ehea/
obj-$(CONFIG_BONDING) += bonding/
obj-$(CONFIG_ATL1) += atl1/
obj-$(CONFIG_GIANFAR) += gianfar_driver.o
gianfar_driver-objs := gianfar.o \
gianfar_ethtool.o \
gianfar_mii.o \
gianfar_sysfs.o
obj-$(CONFIG_UCC_GETH) += ucc_geth_driver.o
ucc_geth_driver-objs := ucc_geth.o ucc_geth_phy.o
#
# link order important here
#
obj-$(CONFIG_PLIP) += plip.o
obj-$(CONFIG_ROADRUNNER) += rrunner.o
obj-$(CONFIG_HAPPYMEAL) += sunhme.o
obj-$(CONFIG_SUNLANCE) += sunlance.o
obj-$(CONFIG_SUNQE) += sunqe.o
obj-$(CONFIG_SUNBMAC) += sunbmac.o
obj-$(CONFIG_MYRI_SBUS) += myri_sbus.o
obj-$(CONFIG_SUNGEM) += sungem.o sungem_phy.o
obj-$(CONFIG_CASSINI) += cassini.o
obj-$(CONFIG_MACE) += mace.o
obj-$(CONFIG_BMAC) += bmac.o
obj-$(CONFIG_DGRS) += dgrs.o
obj-$(CONFIG_VORTEX) += 3c59x.o
obj-$(CONFIG_TYPHOON) += typhoon.o
obj-$(CONFIG_NE2K_PCI) += ne2k-pci.o 8390.o
obj-$(CONFIG_PCNET32) += pcnet32.o
obj-$(CONFIG_EEPRO100) += eepro100.o
obj-$(CONFIG_E100) += e100.o
obj-$(CONFIG_TLAN) += tlan.o
obj-$(CONFIG_EPIC100) += epic100.o
obj-$(CONFIG_SIS190) += sis190.o
obj-$(CONFIG_SIS900) += sis900.o
obj-$(CONFIG_YELLOWFIN) += yellowfin.o
obj-$(CONFIG_ACENIC) += acenic.o
obj-$(CONFIG_ISERIES_VETH) += iseries_veth.o
obj-$(CONFIG_NATSEMI) += natsemi.o
obj-$(CONFIG_NS83820) += ns83820.o
obj-$(CONFIG_STNIC) += stnic.o 8390.o
obj-$(CONFIG_FEALNX) += fealnx.o
obj-$(CONFIG_TIGON3) += tg3.o
obj-$(CONFIG_BNX2) += bnx2.o
spidernet-y += spider_net.o spider_net_ethtool.o
obj-$(CONFIG_SPIDER_NET) += spidernet.o sungem_phy.o
obj-$(CONFIG_TC35815) += tc35815.o
obj-$(CONFIG_SKGE) += skge.o
obj-$(CONFIG_SKY2) += sky2.o
obj-$(CONFIG_SK98LIN) += sk98lin/
obj-$(CONFIG_SKFP) += skfp/
obj-$(CONFIG_VIA_RHINE) += via-rhine.o
obj-$(CONFIG_VIA_VELOCITY) += via-velocity.o
obj-$(CONFIG_ADAPTEC_STARFIRE) += starfire.o
obj-$(CONFIG_RIONET) += rionet.o
#
# end link order section
#
obj-$(CONFIG_MII) += mii.o
obj-$(CONFIG_PHYLIB) += phy/
obj-$(CONFIG_SUNDANCE) += sundance.o
obj-$(CONFIG_HAMACHI) += hamachi.o
obj-$(CONFIG_NET) += Space.o loopback.o
obj-$(CONFIG_SEEQ8005) += seeq8005.o
obj-$(CONFIG_NET_SB1000) += sb1000.o
obj-$(CONFIG_MAC8390) += mac8390.o
obj-$(CONFIG_APNE) += apne.o 8390.o
obj-$(CONFIG_PCMCIA_PCNET) += 8390.o
obj-$(CONFIG_SHAPER) += shaper.o
obj-$(CONFIG_HP100) += hp100.o
obj-$(CONFIG_SMC9194) += smc9194.o
obj-$(CONFIG_FEC) += fec.o
obj-$(CONFIG_68360_ENET) += 68360enet.o
obj-$(CONFIG_WD80x3) += wd.o 8390.o
obj-$(CONFIG_EL2) += 3c503.o 8390.o
obj-$(CONFIG_NE2000) += ne.o 8390.o
obj-$(CONFIG_NE2_MCA) += ne2.o 8390.o
obj-$(CONFIG_HPLAN) += hp.o 8390.o
obj-$(CONFIG_HPLAN_PLUS) += hp-plus.o 8390.o
obj-$(CONFIG_ULTRA) += smc-ultra.o 8390.o
obj-$(CONFIG_ULTRAMCA) += smc-mca.o 8390.o
obj-$(CONFIG_ULTRA32) += smc-ultra32.o 8390.o
obj-$(CONFIG_E2100) += e2100.o 8390.o
obj-$(CONFIG_ES3210) += es3210.o 8390.o
obj-$(CONFIG_LNE390) += lne390.o 8390.o
obj-$(CONFIG_NE3210) += ne3210.o 8390.o
obj-$(CONFIG_NET_SB1250_MAC) += sb1250-mac.o
obj-$(CONFIG_B44) += b44.o
obj-$(CONFIG_FORCEDETH) += forcedeth.o
obj-$(CONFIG_NE_H8300) += ne-h8300.o
obj-$(CONFIG_TSI108_ETH) += tsi108_eth.o
obj-$(CONFIG_MV643XX_ETH) += mv643xx_eth.o
obj-$(CONFIG_QLA3XXX) += qla3xxx.o
obj-$(CONFIG_PPP) += ppp_generic.o
obj-$(CONFIG_PPP_ASYNC) += ppp_async.o
obj-$(CONFIG_PPP_SYNC_TTY) += ppp_synctty.o
obj-$(CONFIG_PPP_DEFLATE) += ppp_deflate.o
obj-$(CONFIG_PPP_BSDCOMP) += bsd_comp.o
obj-$(CONFIG_PPP_MPPE) += ppp_mppe.o
obj-$(CONFIG_PPPOE) += pppox.o pppoe.o
obj-$(CONFIG_SLIP) += slip.o
obj-$(CONFIG_SLHC) += slhc.o
obj-$(CONFIG_DUMMY) += dummy.o
obj-$(CONFIG_IFB) += ifb.o
obj-$(CONFIG_DE600) += de600.o
obj-$(CONFIG_DE620) += de620.o
obj-$(CONFIG_LANCE) += lance.o
obj-$(CONFIG_SUN3_82586) += sun3_82586.o
obj-$(CONFIG_SUN3LANCE) += sun3lance.o
obj-$(CONFIG_DEFXX) += defxx.o
obj-$(CONFIG_SGISEEQ) += sgiseeq.o
obj-$(CONFIG_SGI_O2MACE_ETH) += meth.o
obj-$(CONFIG_AT1700) += at1700.o
obj-$(CONFIG_EL1) += 3c501.o
obj-$(CONFIG_EL16) += 3c507.o
obj-$(CONFIG_ELMC) += 3c523.o
obj-$(CONFIG_IBMLANA) += ibmlana.o
obj-$(CONFIG_ELMC_II) += 3c527.o
obj-$(CONFIG_EL3) += 3c509.o
obj-$(CONFIG_3C515) += 3c515.o
obj-$(CONFIG_EEXPRESS) += eexpress.o
obj-$(CONFIG_EEXPRESS_PRO) += eepro.o
obj-$(CONFIG_8139CP) += 8139cp.o
obj-$(CONFIG_8139TOO) += 8139too.o
obj-$(CONFIG_ZNET) += znet.o
obj-$(CONFIG_LAN_SAA9730) += saa9730.o
obj-$(CONFIG_DEPCA) += depca.o
obj-$(CONFIG_EWRK3) += ewrk3.o
obj-$(CONFIG_ATP) += atp.o
obj-$(CONFIG_NI5010) += ni5010.o
obj-$(CONFIG_NI52) += ni52.o
obj-$(CONFIG_NI65) += ni65.o
obj-$(CONFIG_ELPLUS) += 3c505.o
obj-$(CONFIG_AC3200) += ac3200.o 8390.o
obj-$(CONFIG_APRICOT) += 82596.o
obj-$(CONFIG_LASI_82596) += lasi_82596.o
obj-$(CONFIG_MVME16x_NET) += 82596.o
obj-$(CONFIG_BVME6000_NET) += 82596.o
obj-$(CONFIG_SC92031) += sc92031.o
# This is also a 82596 and should probably be merged
obj-$(CONFIG_LP486E) += lp486e.o
obj-$(CONFIG_ETH16I) += eth16i.o
obj-$(CONFIG_ZORRO8390) += zorro8390.o
obj-$(CONFIG_HPLANCE) += hplance.o 7990.o
obj-$(CONFIG_MVME147_NET) += mvme147.o 7990.o
obj-$(CONFIG_EQUALIZER) += eql.o
obj-$(CONFIG_MIPS_JAZZ_SONIC) += jazzsonic.o
obj-$(CONFIG_MIPS_AU1X00_ENET) += au1000_eth.o
obj-$(CONFIG_MIPS_SIM_NET) += mipsnet.o
obj-$(CONFIG_SGI_IOC3_ETH) += ioc3-eth.o
obj-$(CONFIG_DECLANCE) += declance.o
obj-$(CONFIG_ATARILANCE) += atarilance.o
obj-$(CONFIG_ATARI_BIONET) += atari_bionet.o
obj-$(CONFIG_ATARI_PAMSNET) += atari_pamsnet.o
obj-$(CONFIG_A2065) += a2065.o
obj-$(CONFIG_HYDRA) += hydra.o
obj-$(CONFIG_ARIADNE) += ariadne.o
obj-$(CONFIG_CS89x0) += cs89x0.o
obj-$(CONFIG_MACSONIC) += macsonic.o
obj-$(CONFIG_MACMACE) += macmace.o
obj-$(CONFIG_MAC89x0) += mac89x0.o
obj-$(CONFIG_TUN) += tun.o
obj-$(CONFIG_NET_NETX) += netx-eth.o
obj-$(CONFIG_DL2K) += dl2k.o
obj-$(CONFIG_R8169) += r8169.o
obj-$(CONFIG_AMD8111_ETH) += amd8111e.o
obj-$(CONFIG_IBMVETH) += ibmveth.o
obj-$(CONFIG_S2IO) += s2io.o
obj-$(CONFIG_MYRI10GE) += myri10ge/
obj-$(CONFIG_SMC91X) += smc91x.o
obj-$(CONFIG_SMC911X) += smc911x.o
obj-$(CONFIG_SMSC911X) += smsc911x.o
obj-$(CONFIG_DM9000) += dm9000.o
obj-$(CONFIG_FEC_8XX) += fec_8xx/
obj-$(CONFIG_PASEMI_MAC) += pasemi_mac.o
obj-$(CONFIG_MACB) += macb.o
obj-$(CONFIG_ARM) += arm/
obj-$(CONFIG_DEV_APPLETALK) += appletalk/
obj-$(CONFIG_TR) += tokenring/
obj-$(CONFIG_WAN) += wan/
obj-$(CONFIG_ARCNET) += arcnet/
obj-$(CONFIG_NET_PCMCIA) += pcmcia/
obj-$(CONFIG_NET_RADIO) += wireless/
obj-$(CONFIG_NET_TULIP) += tulip/
obj-$(CONFIG_HAMRADIO) += hamradio/
obj-$(CONFIG_IRDA) += irda/
obj-$(CONFIG_ETRAX_ETHERNET) += cris/
obj-$(CONFIG_ENP2611_MSF_NET) += ixp2000/
obj-$(CONFIG_NETCONSOLE) += netconsole.o
obj-$(CONFIG_FS_ENET) += fs_enet/
obj-$(CONFIG_NETXEN_NIC) += netxen/
|
sdwuyawen/linux2.6.21_helper2416
|
drivers/net/Makefile
|
Makefile
|
gpl-2.0
| 6,874 |
<?php
/**
* Payments Query
*
* @package EDD
* @subpackage Classes/Stats
* @copyright Copyright (c) 2012, Pippin Williamson
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
* @since 1.8
*/
/**
* EDD_Payments_Query Class
*
* This class is for retrieving payments data
*
* Payments can be retrieved for date ranges and pre-defined periods
*
* @since 1.8
*/
class EDD_Payments_Query extends EDD_Stats {
/**
* The args to pass to the edd_get_payments() query
*
* @var array
* @access public
* @since 1.8
*/
public $args = array();
/**
* The payments found based on the criteria set
*
* @var array
* @access public
* @since 1.8
*/
public $payments = array();
/**
* Default query arguments.
*
* Not all of these are valid arguments that can be passed to WP_Query.
* The ones that are not, are modified before the query is run to convert
* them to the proper syntax.
*
* @access public
* @since 1.8
* @return void
*/
public function __construct( $args = array() ) {
$defaults = array(
'output' => 'payments', // Use 'posts' to get standard post objects
'post_type' => array( 'edd_payment' ),
'start_date' => false,
'end_date' => false,
'number' => 20,
'page' => null,
'mode' => 'live',
'orderby' => 'ID',
'order' => 'DESC',
'user' => null,
'status' => 'any',
'meta_key' => null,
'year' => null,
'month' => null,
'day' => null,
's' => null,
'children' => false,
'fields' => null,
'download' => null
);
$this->args = wp_parse_args( $args, $defaults );
$this->init();
}
/**
* Set a query variable.
*
* @access public
* @since 1.8
* @return void
*/
public function __set( $query_var, $value ) {
if ( in_array( $query_var, array( 'meta_query', 'tax_query' ) ) )
$this->args[ $query_var ][] = $value;
else
$this->args[ $query_var ] = $value;
}
/**
* Unset a query variable.
*
* @access public
* @since 1.8
* @return void
*/
public function __unset( $query_var ) {
unset( $this->args[ $query_var ] );
}
/**
* Modify the query/query arguments before we retrieve payments.
*
* @access public
* @since 1.8
* @return void
*/
public function init() {
add_action( 'edd_pre_get_payments', array( $this, 'date_filter_pre' ) );
add_action( 'edd_post_get_payments', array( $this, 'date_filter_post' ) );
add_action( 'edd_pre_get_payments', array( $this, 'orderby' ) );
add_action( 'edd_pre_get_payments', array( $this, 'status' ) );
add_action( 'edd_pre_get_payments', array( $this, 'month' ) );
add_action( 'edd_pre_get_payments', array( $this, 'per_page' ) );
add_action( 'edd_pre_get_payments', array( $this, 'page' ) );
add_action( 'edd_pre_get_payments', array( $this, 'user' ) );
add_action( 'edd_pre_get_payments', array( $this, 'search' ) );
add_action( 'edd_pre_get_payments', array( $this, 'mode' ) );
add_action( 'edd_pre_get_payments', array( $this, 'children' ) );
add_action( 'edd_pre_get_payments', array( $this, 'download' ) );
}
/**
* Retrieve payments.
*
* The query can be modified in two ways; either the action before the
* query is run, or the filter on the arguments (existing mainly for backwards
* compatibility).
*
* @access public
* @since 1.8
* @return object
*/
public function get_payments() {
do_action( 'edd_pre_get_payments', $this );
$query = new WP_Query( $this->args );
if ( 'payments' != $this->args[ 'output' ] )
return $query->posts;
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$details = new stdClass;
$payment_id = get_post()->ID;
$details->ID = $payment_id;
$details->date = get_post()->post_date;
$details->post_status = get_post()->post_status;
$details->total = edd_get_payment_amount( $payment_id );
$details->subtotal = edd_get_payment_subtotal( $payment_id );
$details->tax = edd_get_payment_tax( $payment_id );
$details->fees = edd_get_payment_fees( $payment_id );
$details->key = edd_get_payment_key( $payment_id );
$details->gateway = edd_get_payment_gateway( $payment_id );
$details->user_info = edd_get_payment_meta_user_info( $payment_id );
$details->cart_details = edd_get_payment_meta_cart_details( $payment_id, true );
$this->payments[] = apply_filters( 'edd_payment', $details, $payment_id, $this );
}
}
do_action( 'edd_post_get_payments', $this );
return $this->payments;
}
/**
* If querying a specific date, add the proper filters.
*
* @access public
* @since 1.8
* @return void
*/
public function date_filter_pre() {
if( ! ( $this->args[ 'start_date' ] || $this->args[ 'end_date' ] ) )
return;
$this->setup_dates( $this->args[ 'start_date' ], $this->args[ 'end_date' ] );
add_filter( 'posts_where', array( $this, 'payments_where' ) );
}
/**
* If querying a specific date, remove filters after the query has been run
* to avoid affecting future queries.
*
* @access public
* @since 1.8
* @return void
*/
public function date_filter_post() {
if ( ! ( $this->args[ 'start_date' ] || $this->args[ 'end_date' ] ) )
return;
remove_filter( 'posts_where', array( $this, 'payments_where' ) );
}
/**
* Post Status
*
* @access public
* @since 1.8
* @return void
*/
public function status() {
if ( ! isset ( $this->args[ 'status' ] ) )
return;
$this->__set( 'post_status', $this->args[ 'status' ] );
$this->__unset( 'status' );
}
/**
* Current Page
*
* @access public
* @since 1.8
* @return void
*/
public function page() {
if ( ! isset ( $this->args[ 'page' ] ) )
return;
$this->__set( 'paged', $this->args[ 'page' ] );
$this->__unset( 'page' );
}
/**
* Posts Per Page
*
* @access public
* @since 1.8
* @return void
*/
public function per_page() {
if( ! isset( $this->args[ 'number' ] ) )
return;
if ( $this->args[ 'number' ] == -1 )
$this->__set( 'nopaging', true );
else
$this->__set( 'posts_per_page', $this->args[ 'number' ] );
$this->__unset( 'number' );
}
/**
* Current Month
*
* @access public
* @since 1.8
* @return void
*/
public function month() {
if ( ! isset ( $this->args[ 'month' ] ) )
return;
$this->__set( 'monthnum', $this->args[ 'month' ] );
$this->__unset( 'month' );
}
/**
* Order
*
* @access public
* @since 1.8
* @return void
*/
public function orderby() {
switch ( $this->args[ 'orderby' ] ) {
case 'amount' :
$this->__set( 'orderby', 'meta_value_num' );
$this->__set( 'meta_key', '_edd_payment_total' );
break;
default :
$this->__set( 'orderby', $this->args[ 'orderby' ] );
break;
}
}
/**
* Specific User
*
* @access public
* @since 1.8
* @return void
*/
public function user() {
if ( is_null( $this->args[ 'user' ] ) )
return;
if ( is_numeric( $this->args[ 'user' ] ) ) {
$user_key = '_edd_payment_user_id';
} else {
$user_key = '_edd_payment_user_email';
}
$this->__set( 'meta_query', array(
'key' => $user_key,
'value' => $this->args[ 'user' ]
) );
}
/**
* Search
*
* @access public
* @since 1.8
* @return void
*/
public function search() {
$search = trim( $this->args[ 's' ] );
if( empty( $search ) )
return;
$is_email = is_email( $search ) || strpos( $search, '@' ) !== false;
if ( $is_email || strlen( $search ) == 32 ) {
$key = $is_email ? '_edd_payment_user_email' : '_edd_payment_purchase_key';
$search_meta = array(
'key' => $key,
'value' => $search,
'compare' => 'LIKE'
);
$this->__set( 'meta_query', $search_meta );
$this->__unset( 's' );
} elseif ( is_numeric( $search ) ) {
$search_meta = array(
'key' => '_edd_payment_user_id',
'value' => $search
);
$this->__set( 'meta_query', $search_meta );
$this->__unset( 's' );
} elseif ( '#' == substr( $search, 0, 1 ) ) {
$this->__set( 'download', str_replace( '#', '', $search ) );
$this->__unset( 's' );
} else {
$this->__set( 's', $search );
}
}
/**
* Payment Mode
*
* @access public
* @since 1.8
* @return void
*/
public function mode() {
if ( $this->args[ 'mode' ] == 'all' ) {
$this->__unset( 'mode' );
return;
}
$this->__set( 'meta_query', array(
'key' => '_edd_payment_mode',
'value' => $this->args[ 'mode' ]
) );
}
/**
* Children
*
* @access public
* @since 1.8
* @return void
*/
public function children() {
if ( empty( $this->args[ 'children' ] ) ) {
$this->__set( 'post_parent', 0 );
}
$this->__unset( 'children' );
}
/**
* Specific Download
*
* @access public
* @since 1.8
* @return void
*/
public function download() {
if ( empty( $this->args[ 'download' ] ) )
return;
global $edd_logs;
$sales = $edd_logs->get_connected_logs( array(
'post_parent' => $this->args[ 'download' ],
'log_type' => 'sale',
'post_status' => array( 'publish' ),
'nopaging' => true,
'no_found_rows' => true,
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
'cache_results' => false,
'fields' => 'ids'
) );
if ( ! empty( $sales ) ) {
$payments = array();
foreach ( $sales as $sale ) {
$payments[] = get_post_meta( $sale, '_edd_log_payment_id', true );
}
$this->__set( 'post__in', $payments );
} else {
// Set post_parent to something crazy so it doesn't fin anything
$this->__set( 'post_parent', 999999999999999 );
}
$this->__unset( 'download' );
}
}
|
User1m/fundstarter
|
wp-content/plugins/easy-digital-downloads/includes/payments/class-payments-query.php
|
PHP
|
gpl-2.0
| 9,853 |
package org.ppsspp.ppsspp;
import java.io.File;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Locale;
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.UiModeManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.Point;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.InputDevice;
import android.view.InputEvent;
import android.view.KeyEvent;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnSystemUiVisibilityChangeListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;
public class NativeActivity extends Activity implements SurfaceHolder.Callback {
// Remember to loadLibrary your JNI .so in a static {} block
// Adjust these as necessary
private static String TAG = "NativeActivity";
// Allows us to skip a lot of initialization on secondary calls to onCreate.
private static boolean initialized = false;
// Graphics and audio interfaces
private NativeSurfaceView mSurfaceView;
private Surface mSurface;
private Thread mRenderLoopThread;
private String shortcutParam = "";
public static String runCommand;
public static String commandParameter;
public static String installID;
// Remember settings for best audio latency
private int optimalFramesPerBuffer;
private int optimalSampleRate;
// audioFocusChangeListener to listen to changes in audio state
private AudioFocusChangeListener audioFocusChangeListener;
private AudioManager audioManager;
private Vibrator vibrator;
private boolean isXperiaPlay;
// Allow for multiple connected gamepads but just consider them the same for now.
// Actually this is not entirely true, see the code.
InputDeviceState inputPlayerA;
InputDeviceState inputPlayerB;
InputDeviceState inputPlayerC;
String inputPlayerADesc;
// Functions for the app activity to override to change behaviour.
public native void registerCallbacks();
public native void unregisterCallbacks();
public boolean useLowProfileButtons() {
return true;
}
@TargetApi(17)
private void detectOptimalAudioSettings() {
try {
optimalFramesPerBuffer = Integer.parseInt(this.audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
} catch (NumberFormatException e) {
// Ignore, if we can't parse it it's bogus and zero is a fine value (means we couldn't detect it).
}
try {
optimalSampleRate = Integer.parseInt(this.audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
} catch (NumberFormatException e) {
// Ignore, if we can't parse it it's bogus and zero is a fine value (means we couldn't detect it).
}
}
String getApplicationLibraryDir(ApplicationInfo application) {
String libdir = null;
try {
// Starting from Android 2.3, nativeLibraryDir is available:
Field field = ApplicationInfo.class.getField("nativeLibraryDir");
libdir = (String) field.get(application);
} catch (SecurityException e1) {
} catch (NoSuchFieldException e1) {
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
}
if (libdir == null) {
// Fallback for Android < 2.3:
libdir = application.dataDir + "/lib";
}
return libdir;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
void GetScreenSizeJB(Point size, boolean real) {
WindowManager w = getWindowManager();
if (real) {
w.getDefaultDisplay().getRealSize(size);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
void GetScreenSizeHC(Point size, boolean real) {
WindowManager w = getWindowManager();
if (real && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
GetScreenSizeJB(size, real);
} else {
w.getDefaultDisplay().getSize(size);
}
}
@SuppressWarnings("deprecation")
public void GetScreenSize(Point size) {
boolean real = useImmersive();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
GetScreenSizeHC(size, real);
} else {
WindowManager w = getWindowManager();
Display d = w.getDefaultDisplay();
size.x = d.getWidth();
size.y = d.getHeight();
}
}
public static final int REQUEST_CODE_STORAGE_PERMISSION = 1337;
@TargetApi(23)
public void askForStoragePermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
NativeApp.sendMessage("permission_pending", "storage");
this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_STORAGE_PERMISSION);
} else {
NativeApp.sendMessage("permission_granted", "storage");
}
}
}
@TargetApi(23)
public void sendInitialGrants() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Let's start out granted if it was granted already.
if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
NativeApp.sendMessage("permission_granted", "storage");
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if (requestCode == REQUEST_CODE_STORAGE_PERMISSION && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
NativeApp.sendMessage("permission_granted", "storage");
} else {
NativeApp.sendMessage("permission_denied", "storage");
}
}
public void setShortcutParam(String shortcutParam) {
this.shortcutParam = ((shortcutParam == null) ? "" : shortcutParam);
}
public void Initialize() {
// Initialize audio classes. Do this here since detectOptimalAudioSettings()
// needs audioManager
this.audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
this.audioFocusChangeListener = new AudioFocusChangeListener();
if (Build.VERSION.SDK_INT >= 17) {
// Get the optimal buffer sz
detectOptimalAudioSettings();
}
// Get system information
ApplicationInfo appInfo = null;
PackageManager packMgmr = getPackageManager();
String packageName = getPackageName();
try {
appInfo = packMgmr.getApplicationInfo(packageName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
int deviceType = NativeApp.DEVICE_TYPE_MOBILE;
UiModeManager uiModeManager = (UiModeManager) getSystemService(UI_MODE_SERVICE);
switch (uiModeManager.getCurrentModeType()) {
case Configuration.UI_MODE_TYPE_TELEVISION:
deviceType = NativeApp.DEVICE_TYPE_TV;
Log.i(TAG, "Running on an Android TV Device");
break;
case Configuration.UI_MODE_TYPE_DESK:
deviceType = NativeApp.DEVICE_TYPE_DESKTOP;
Log.i(TAG, "Running on an Android desktop computer (!)");
break;
// All other device types are treated the same.
}
isXperiaPlay = IsXperiaPlay();
String libraryDir = getApplicationLibraryDir(appInfo);
File sdcard = Environment.getExternalStorageDirectory();
String externalStorageDir = sdcard.getAbsolutePath();
String dataDir = this.getFilesDir().getAbsolutePath();
String apkFilePath = appInfo.sourceDir;
String model = Build.MANUFACTURER + ":" + Build.MODEL;
String languageRegion = Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry();
NativeApp.audioConfig(optimalFramesPerBuffer, optimalSampleRate);
NativeApp.init(model, deviceType, languageRegion, apkFilePath, dataDir, externalStorageDir, libraryDir, shortcutParam, installID, Build.VERSION.SDK_INT);
NativeApp.sendMessage("cacheDir", getCacheDir().getAbsolutePath());
sendInitialGrants();
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= 11) {
checkForVibrator();
}
}
@TargetApi(9)
private void updateScreenRotation() {
// Query the native application on the desired rotation.
int rot = 0;
String rotString = NativeApp.queryConfig("screenRotation");
try {
rot = Integer.parseInt(rotString);
} catch (NumberFormatException e) {
Log.e(TAG, "Invalid rotation: " + rotString);
return;
}
Log.i(TAG, "Setting requested rotation: " + rot + " ('" + rotString + "')");
switch (rot) {
case 0:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
break;
case 1:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case 2:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case 3:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
break;
case 4:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
break;
}
}
private boolean useImmersive() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
return false;
String immersive = NativeApp.queryConfig("immersiveMode");
return immersive.equals("1");
}
@SuppressLint("InlinedApi")
@TargetApi(14)
private void updateSystemUiVisibility() {
int flags = 0;
if (useLowProfileButtons()) {
flags |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
}
if (useImmersive()) {
flags |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
}
if (getWindow().getDecorView() != null) {
getWindow().getDecorView().setSystemUiVisibility(flags);
} else {
Log.e(TAG, "updateSystemUiVisibility: decor view not yet created, ignoring");
}
}
// Need API 11 to check for existence of a vibrator? Zany.
@TargetApi(11)
public void checkForVibrator() {
if (Build.VERSION.SDK_INT >= 11) {
if (!vibrator.hasVibrator()) {
vibrator = null;
}
}
}
private Runnable mEmulationRunner = new Runnable() {
@Override
public void run() {
// Bit of a hack - loop until onSurfaceCreated succeeds.
try {
while (mSurface == null)
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, "Starting the render loop: " + mSurface);
// Start emulation using the provided Surface.
if (!runEGLRenderLoop(mSurface)) {
// TODO: Add an alert dialog or something
Log.e(TAG, "Failed to start up OpenGL");
}
Log.i(TAG, "Left the render loop: " + mSurface);
}
};
public native boolean runEGLRenderLoop(Surface surface);
// Tells the render loop thread to exit, so we can restart it.
public native void exitEGLRenderLoop();
void updateDisplayMetrics(Point outSize) {
DisplayMetrics metrics = new DisplayMetrics();
Display display = getWindowManager().getDefaultDisplay();
display.getMetrics(metrics);
float refreshRate = display.getRefreshRate();
if (outSize == null) {
outSize = new Point();
}
GetScreenSize(outSize);
NativeApp.setDisplayParameters(outSize.x, outSize.y, metrics.densityDpi, refreshRate);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerCallbacks();
installID = Installation.id(this);
updateDisplayMetrics(null);
if (!initialized) {
Initialize();
initialized = true;
}
// OK, config should be initialized, we can query for screen rotation.
updateScreenRotation();
// Keep the screen bright - very annoying if it goes dark when tilting away
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
gainAudioFocus(this.audioManager, this.audioFocusChangeListener);
NativeApp.audioInit();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
updateSystemUiVisibility();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setupSystemUiCallback();
}
}
updateDisplayMetrics(null);
NativeApp.computeDesiredBackbufferDimensions();
int bbW = NativeApp.getDesiredBackbufferWidth();
int bbH = NativeApp.getDesiredBackbufferHeight();
mSurfaceView = new NativeSurfaceView(NativeActivity.this, bbW, bbH);
mSurfaceView.getHolder().addCallback(NativeActivity.this);
Log.i(TAG, "setcontentview before");
setContentView(mSurfaceView);
Log.i(TAG, "setcontentview after");
mRenderLoopThread = new Thread(mEmulationRunner);
mRenderLoopThread.start();
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
Log.d(TAG, "Surface created.");
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
Log.w(TAG, "Surface changed. Resolution: " + width + "x" + height + " Format: " + format);
// Make sure we have fresh display metrics so the computations go right.
// This is needed on some very old devices, I guess event order is different or something...
Point sz = new Point();
updateDisplayMetrics(sz);
NativeApp.backbufferResize(width, height, format);
mSurface = holder.getSurface();
if (mRenderLoopThread == null || !mRenderLoopThread.isAlive()) {
mRenderLoopThread = new Thread(mEmulationRunner);
mRenderLoopThread.start();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
mSurface = null;
Log.w(TAG, "Surface destroyed.");
if (mRenderLoopThread != null && mRenderLoopThread.isAlive()) {
// This will wait until the thread has exited.
exitEGLRenderLoop();
try {
mRenderLoopThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@TargetApi(19)
void setupSystemUiCallback() {
getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
if (visibility == 0) {
updateSystemUiVisibility();
}
}
});
}
@Override
protected void onStop() {
exitEGLRenderLoop();
super.onStop();
Log.i(TAG, "onStop - do nothing special");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
mSurfaceView.onDestroy();
NativeApp.audioShutdown();
// Probably vain attempt to help the garbage collector...
mSurfaceView = null;
audioFocusChangeListener = null;
audioManager = null;
unregisterCallbacks();
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause");
loseAudioFocus(this.audioManager, this.audioFocusChangeListener);
NativeApp.pause();
mSurfaceView.onPause();
}
@Override
protected void onResume() {
super.onResume();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
updateSystemUiVisibility();
}
// OK, config should be initialized, we can query for screen rotation.
updateScreenRotation();
Log.i(TAG, "onResume");
if (mSurfaceView != null) {
mSurfaceView.onResume();
} else {
Log.e(TAG, "mGLSurfaceView really shouldn't be null in onResume");
}
gainAudioFocus(this.audioManager, this.audioFocusChangeListener);
NativeApp.resume();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.i(TAG, "onConfigurationChanged");
super.onConfigurationChanged(newConfig);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
updateSystemUiVisibility();
}
updateDisplayMetrics(null);
}
//keep this static so we can call this even if we don't
//instantiate NativeAudioPlayer
public static void gainAudioFocus(AudioManager audioManager, AudioFocusChangeListener focusChangeListener) {
if (audioManager != null) {
audioManager.requestAudioFocus(focusChangeListener,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
}
//keep this static so we can call this even if we don't
//instantiate NativeAudioPlayer
public static void loseAudioFocus(AudioManager audioManager,AudioFocusChangeListener focusChangeListener){
if (audioManager != null) {
audioManager.abandonAudioFocus(focusChangeListener);
}
}
// We simply grab the first input device to produce an event and ignore all others that are connected.
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private InputDeviceState getInputDeviceState(InputEvent event) {
InputDevice device = event.getDevice();
if (device == null) {
return null;
}
if (inputPlayerA == null) {
inputPlayerADesc = getInputDesc(device);
Log.i(TAG, "Input player A registered: desc = " + inputPlayerADesc);
inputPlayerA = new InputDeviceState(device);
}
if (inputPlayerA.getDevice() == device) {
return inputPlayerA;
}
if (inputPlayerB == null) {
Log.i(TAG, "Input player B registered: desc = " + getInputDesc(device));
inputPlayerB = new InputDeviceState(device);
}
if (inputPlayerB.getDevice() == device) {
return inputPlayerB;
}
if (inputPlayerC == null) {
Log.i(TAG, "Input player C registered");
inputPlayerC = new InputDeviceState(device);
}
if (inputPlayerC.getDevice() == device) {
return inputPlayerC;
}
return inputPlayerA;
}
public boolean IsXperiaPlay() {
return android.os.Build.MODEL.equals("R800a") || android.os.Build.MODEL.equals("R800i") || android.os.Build.MODEL.equals("R800x") || android.os.Build.MODEL.equals("R800at") || android.os.Build.MODEL.equals("SO-01D") || android.os.Build.MODEL.equals("zeus");
}
// We grab the keys before onKeyDown/... even see them. This is also better because it lets us
// distinguish devices.
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 && !isXperiaPlay) {
InputDeviceState state = getInputDeviceState(event);
if (state == null) {
return super.dispatchKeyEvent(event);
}
// Let's let back and menu through to dispatchKeyEvent.
boolean passThrough = false;
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BACK:
case KeyEvent.KEYCODE_MENU:
passThrough = true;
break;
default:
break;
}
// Don't passthrough back button if gamepad.
int sources = event.getSource();
switch (sources) {
case InputDevice.SOURCE_GAMEPAD:
case InputDevice.SOURCE_JOYSTICK:
case InputDevice.SOURCE_DPAD:
passThrough = false;
break;
}
if (!passThrough) {
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN:
if (state.onKeyDown(event)) {
return true;
}
break;
case KeyEvent.ACTION_UP:
if (state.onKeyUp(event)) {
return true;
}
break;
}
}
}
// Let's go through the old path (onKeyUp, onKeyDown).
return super.dispatchKeyEvent(event);
}
@TargetApi(16)
static public String getInputDesc(InputDevice input) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return input.getDescriptor();
} else {
List<InputDevice.MotionRange> motions = input.getMotionRanges();
String fakeid = "";
for (InputDevice.MotionRange range : motions)
fakeid += range.getAxis();
return fakeid;
}
}
@Override
@TargetApi(12)
public boolean onGenericMotionEvent(MotionEvent event) {
// Log.d(TAG, "onGenericMotionEvent: " + event);
if ((event.getSource() & InputDevice.SOURCE_JOYSTICK) != 0) {
if (Build.VERSION.SDK_INT >= 12) {
InputDeviceState state = getInputDeviceState(event);
if (state == null) {
Log.w(TAG, "Joystick event but failed to get input device state.");
return super.onGenericMotionEvent(event);
}
state.onJoystickMotion(event);
return true;
}
}
if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
switch (event.getAction()) {
case MotionEvent.ACTION_HOVER_MOVE:
// process the mouse hover movement...
return true;
case MotionEvent.ACTION_SCROLL:
NativeApp.mouseWheelEvent(event.getX(), event.getY());
return true;
}
}
return super.onGenericMotionEvent(event);
}
@SuppressLint("NewApi")
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Eat these keys, to avoid accidental exits / other screwups.
// Maybe there's even more we need to eat on tablets?
boolean repeat = event.getRepeatCount() > 0;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.isAltPressed()) {
NativeApp.keyDown(0, 1004, repeat); // special custom keycode for the O button on Xperia Play
} else if (NativeApp.isAtTopLevel()) {
Log.i(TAG, "IsAtTopLevel returned true.");
// Pass through the back event.
return super.onKeyDown(keyCode, event);
} else {
NativeApp.keyDown(0, keyCode, repeat);
}
return true;
case KeyEvent.KEYCODE_MENU:
case KeyEvent.KEYCODE_SEARCH:
NativeApp.keyDown(0, keyCode, repeat);
return true;
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// Joysticks are supported in Honeycomb MR1 and later via the onGenericMotionEvent method.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 && event.getSource() == InputDevice.SOURCE_JOYSTICK) {
return super.onKeyDown(keyCode, event);
}
// Fall through
default:
// send the rest of the keys through.
// TODO: get rid of the three special cases above by adjusting the native side of the code.
// Log.d(TAG, "Key down: " + keyCode + ", KeyEvent: " + event);
return NativeApp.keyDown(0, keyCode, repeat);
}
}
@SuppressLint("NewApi")
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.isAltPressed()) {
NativeApp.keyUp(0, 1004); // special custom keycode
} else if (NativeApp.isAtTopLevel()) {
Log.i(TAG, "IsAtTopLevel returned true.");
return super.onKeyUp(keyCode, event);
} else {
NativeApp.keyUp(0, keyCode);
}
return true;
case KeyEvent.KEYCODE_MENU:
case KeyEvent.KEYCODE_SEARCH:
// Search probably should also be ignored. We send it to the app.
NativeApp.keyUp(0, keyCode);
return true;
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// Joysticks are supported in Honeycomb MR1 and later via the onGenericMotionEvent method.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 && event.getSource() == InputDevice.SOURCE_JOYSTICK) {
return super.onKeyUp(keyCode, event);
}
// Fall through
default:
// send the rest of the keys through.
// TODO: get rid of the three special cases above by adjusting the native side of the code.
// Log.d(TAG, "Key down: " + keyCode + ", KeyEvent: " + event);
return NativeApp.keyUp(0, keyCode);
}
}
@TargetApi(11)
@SuppressWarnings("deprecation")
private AlertDialog.Builder createDialogBuilderWithTheme() {
return new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_DARK);
}
@TargetApi(14)
@SuppressWarnings("deprecation")
private AlertDialog.Builder createDialogBuilderWithDeviceTheme() {
return new AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_DARK);
}
@TargetApi(23)
private AlertDialog.Builder createDialogBuilderNew() {
return new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_Alert);
}
// The return value is sent elsewhere. TODO in java, in SendMessage in C++.
public void inputBox(String title, String defaultText, String defaultAction) {
final FrameLayout fl = new FrameLayout(this);
final EditText input = new EditText(this);
input.setGravity(Gravity.CENTER);
FrameLayout.LayoutParams editBoxLayout = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
editBoxLayout.setMargins(2, 20, 2, 20);
fl.addView(input, editBoxLayout);
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setText(defaultText);
input.selectAll();
// Lovely!
AlertDialog.Builder bld = null;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
bld = new AlertDialog.Builder(this);
else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH)
bld = createDialogBuilderWithTheme();
else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
bld = createDialogBuilderWithDeviceTheme();
else
bld = createDialogBuilderNew();
AlertDialog dlg = bld
.setView(fl)
.setTitle(title)
.setPositiveButton(defaultAction, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface d, int which) {
NativeApp.sendMessage("inputbox_completed", input.getText().toString());
d.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface d, int which) {
NativeApp.sendMessage("inputbox_failed", "");
d.cancel();
}
}).create();
dlg.setCancelable(true);
dlg.show();
}
public boolean processCommand(String command, String params) {
if (command.equals("launchBrowser")) {
try {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(params));
startActivity(i);
return true;
} catch (Exception e) {
// No browser?
Log.e(TAG, e.toString());
return false;
}
} else if (command.equals("launchEmail")) {
try {
Intent send = new Intent(Intent.ACTION_SENDTO);
String uriText;
uriText = "mailto:[email protected]" + "?subject=Your app is..."
+ "&body=great! Or?";
uriText = uriText.replace(" ", "%20");
Uri uri = Uri.parse(uriText);
send.setData(uri);
startActivity(Intent.createChooser(send, "E-mail the app author!"));
return true;
} catch (Exception e) { // For example, android.content.ActivityNotFoundException
Log.e(TAG, e.toString());
return false;
}
} else if (command.equals("sharejpeg")) {
try {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + params));
startActivity(Intent.createChooser(share, "Share Picture"));
return true;
} catch (Exception e) { // For example, android.content.ActivityNotFoundException
Log.e(TAG, e.toString());
return false;
}
} else if (command.equals("sharetext")) {
try {
Intent sendIntent = new Intent();
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, params);
sendIntent.setAction(Intent.ACTION_SEND);
startActivity(sendIntent);
return true;
} catch (Exception e) { // For example, android.content.ActivityNotFoundException
Log.e(TAG, e.toString());
return false;
}
} else if (command.equals("showTwitter")) {
try {
String twitter_user_name = params;
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("twitter://user?screen_name="
+ twitter_user_name)));
} catch (Exception e) {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("https://twitter.com/#!/" + twitter_user_name)));
}
return true;
} catch (Exception e) { // For example, android.content.ActivityNotFoundException
Log.e(TAG, e.toString());
return false;
}
} else if (command.equals("launchMarket")) {
// Don't need this, can just use launchBrowser with a market:
// http://stackoverflow.com/questions/3442366/android-link-to-market-from-inside-another-app
// http://developer.android.com/guide/publishing/publishing.html#marketintent
return false;
} else if (command.equals("toast")) {
Toast toast = Toast.makeText(this, params, Toast.LENGTH_SHORT);
toast.show();
Log.i(TAG, params);
return true;
} else if (command.equals("showKeyboard") && mSurfaceView != null) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// No idea what the point of the ApplicationWindowToken is or if it
// matters where we get it from...
inputMethodManager.toggleSoftInputFromWindow(
mSurfaceView.getApplicationWindowToken(),
InputMethodManager.SHOW_FORCED, 0);
return true;
} else if (command.equals("hideKeyboard") && mSurfaceView != null) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(
mSurfaceView.getApplicationWindowToken(),
InputMethodManager.SHOW_FORCED, 0);
return true;
} else if (command.equals("inputbox")) {
String title = "Input";
String defString = "";
String[] param = params.split(":");
if (param[0].length() > 0)
title = param[0];
if (param.length > 1)
defString = param[1];
Log.i(TAG, "Launching inputbox: " + title + " " + defString);
inputBox(title, defString, "OK");
return true;
} else if (command.equals("vibrate") && mSurfaceView != null) {
int milliseconds = -1;
if (params != "") {
try {
milliseconds = Integer.parseInt(params);
} catch (NumberFormatException e) {
}
}
// Special parameters to perform standard haptic feedback
// operations
// -1 = Standard keyboard press feedback
// -2 = Virtual key press
// -3 = Long press feedback
// Note that these three do not require the VIBRATE Android
// permission.
switch (milliseconds) {
case -1:
mSurfaceView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
break;
case -2:
mSurfaceView.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
break;
case -3:
mSurfaceView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
break;
default:
if (vibrator != null) {
vibrator.vibrate(milliseconds);
}
break;
}
return true;
} else if (command.equals("finish")) {
finish();
} else if (command.equals("rotate")) {
updateScreenRotation();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
Log.i(TAG, "Must recreate activity on rotation");
}
} else if (command.equals("immersive")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
updateSystemUiVisibility();
}
} else if (command.equals("recreate")) {
exitEGLRenderLoop();
recreate();
} else if (command.equals("ask_permission") && params.equals("storage")) {
askForStoragePermission();
}
return false;
}
@SuppressLint("NewApi")
@Override
public void recreate()
{
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
super.recreate();
}
else
{
startActivity(getIntent());
finish();
}
}
}
|
CarlKenner/ppsspp
|
android/src/org/ppsspp/ppsspp/NativeActivity.java
|
Java
|
gpl-2.0
| 32,239 |
#include <qapplication.h>
#include <qevent.h>
#include <qwhatsthis.h>
#include <qpainter.h>
#include <qwt_plot.h>
#include <qwt_symbol.h>
#include <qwt_scale_map.h>
#include <qwt_plot_canvas.h>
#include <qwt_plot_curve.h>
#include <qwt_plot_directpainter.h>
#include "canvaspicker.h"
CanvasPicker::CanvasPicker( QwtPlot *plot ):
QObject( plot ),
d_selectedCurve( NULL ),
d_selectedPoint( -1 )
{
QwtPlotCanvas *canvas = qobject_cast<QwtPlotCanvas *>( plot->canvas() );
canvas->installEventFilter( this );
// We want the focus, but no focus rect. The
// selected point will be highlighted instead.
canvas->setFocusPolicy( Qt::StrongFocus );
#ifndef QT_NO_CURSOR
canvas->setCursor( Qt::PointingHandCursor );
#endif
canvas->setFocusIndicator( QwtPlotCanvas::ItemFocusIndicator );
canvas->setFocus();
const char *text =
"All points can be moved using the left mouse button "
"or with these keys:\n\n"
"- Up:\t\tSelect next curve\n"
"- Down:\t\tSelect previous curve\n"
"- Left, ´-´:\tSelect next point\n"
"- Right, ´+´:\tSelect previous point\n"
"- 7, 8, 9, 4, 6, 1, 2, 3:\tMove selected point";
canvas->setWhatsThis( text );
shiftCurveCursor( true );
}
QwtPlot *CanvasPicker::plot()
{
return qobject_cast<QwtPlot *>( parent() );
}
const QwtPlot *CanvasPicker::plot() const
{
return qobject_cast<const QwtPlot *>( parent() );
}
bool CanvasPicker::event( QEvent *ev )
{
if ( ev->type() == QEvent::User )
{
showCursor( true );
return true;
}
return QObject::event( ev );
}
bool CanvasPicker::eventFilter( QObject *object, QEvent *event )
{
if ( plot() == NULL || object != plot()->canvas() )
return false;
switch( event->type() )
{
case QEvent::FocusIn:
{
showCursor( true );
break;
}
case QEvent::FocusOut:
{
showCursor( false );
break;
}
case QEvent::Paint:
{
QApplication::postEvent( this, new QEvent( QEvent::User ) );
break;
}
case QEvent::MouseButtonPress:
{
const QMouseEvent *mouseEvent = static_cast<QMouseEvent *>( event );
select( mouseEvent->pos() );
return true;
}
case QEvent::MouseMove:
{
const QMouseEvent *mouseEvent = static_cast<QMouseEvent *>( event );
move( mouseEvent->pos() );
return true;
}
case QEvent::KeyPress:
{
const QKeyEvent *keyEvent = static_cast<QKeyEvent *>( event );
const int delta = 5;
switch( keyEvent->key() )
{
case Qt::Key_Up:
{
shiftCurveCursor( true );
return true;
}
case Qt::Key_Down:
{
shiftCurveCursor( false );
return true;
}
case Qt::Key_Right:
case Qt::Key_Plus:
{
if ( d_selectedCurve )
shiftPointCursor( true );
else
shiftCurveCursor( true );
return true;
}
case Qt::Key_Left:
case Qt::Key_Minus:
{
if ( d_selectedCurve )
shiftPointCursor( false );
else
shiftCurveCursor( true );
return true;
}
// The following keys represent a direction, they are
// organized on the keyboard.
case Qt::Key_1:
{
moveBy( -delta, delta );
break;
}
case Qt::Key_2:
{
moveBy( 0, delta );
break;
}
case Qt::Key_3:
{
moveBy( delta, delta );
break;
}
case Qt::Key_4:
{
moveBy( -delta, 0 );
break;
}
case Qt::Key_6:
{
moveBy( delta, 0 );
break;
}
case Qt::Key_7:
{
moveBy( -delta, -delta );
break;
}
case Qt::Key_8:
{
moveBy( 0, -delta );
break;
}
case Qt::Key_9:
{
moveBy( delta, -delta );
break;
}
default:
break;
}
}
default:
break;
}
return QObject::eventFilter( object, event );
}
// Select the point at a position. If there is no point
// deselect the selected point
void CanvasPicker::select( const QPoint &pos )
{
QwtPlotCurve *curve = NULL;
double dist = 10e10;
int index = -1;
const QwtPlotItemList& itmList = plot()->itemList();
for ( QwtPlotItemIterator it = itmList.begin();
it != itmList.end(); ++it )
{
if ( ( *it )->rtti() == QwtPlotItem::Rtti_PlotCurve )
{
QwtPlotCurve *c = static_cast<QwtPlotCurve *>( *it );
double d;
int idx = c->closestPoint( pos, &d );
if ( d < dist )
{
curve = c;
index = idx;
dist = d;
}
}
}
showCursor( false );
d_selectedCurve = NULL;
d_selectedPoint = -1;
if ( curve && dist < 10 ) // 10 pixels tolerance
{
d_selectedCurve = curve;
d_selectedPoint = index;
showCursor( true );
}
}
// Move the selected point
void CanvasPicker::moveBy( int dx, int dy )
{
if ( dx == 0 && dy == 0 )
return;
if ( !d_selectedCurve )
return;
const QPointF sample =
d_selectedCurve->sample( d_selectedPoint );
const double x = plot()->transform(
d_selectedCurve->xAxis(), sample.x() );
const double y = plot()->transform(
d_selectedCurve->yAxis(), sample.y() );
move( QPoint( qRound( x + dx ), qRound( y + dy ) ) );
}
// Move the selected point
void CanvasPicker::move( const QPoint &pos )
{
if ( !d_selectedCurve )
return;
QVector<double> xData( d_selectedCurve->dataSize() );
QVector<double> yData( d_selectedCurve->dataSize() );
for ( int i = 0;
i < static_cast<int>( d_selectedCurve->dataSize() ); i++ )
{
if ( i == d_selectedPoint )
{
xData[i] = plot()->invTransform(
d_selectedCurve->xAxis(), pos.x() );
yData[i] = plot()->invTransform(
d_selectedCurve->yAxis(), pos.y() );
}
else
{
const QPointF sample = d_selectedCurve->sample( i );
xData[i] = sample.x();
yData[i] = sample.y();
}
}
d_selectedCurve->setSamples( xData, yData );
/*
Enable QwtPlotCanvas::ImmediatePaint, so that the canvas has been
updated before we paint the cursor on it.
*/
QwtPlotCanvas *plotCanvas =
qobject_cast<QwtPlotCanvas *>( plot()->canvas() );
plotCanvas->setPaintAttribute( QwtPlotCanvas::ImmediatePaint, true );
plot()->replot();
plotCanvas->setPaintAttribute( QwtPlotCanvas::ImmediatePaint, false );
showCursor( true );
}
// Hightlight the selected point
void CanvasPicker::showCursor( bool showIt )
{
if ( !d_selectedCurve )
return;
QwtSymbol *symbol = const_cast<QwtSymbol *>( d_selectedCurve->symbol() );
const QBrush brush = symbol->brush();
if ( showIt )
symbol->setBrush( symbol->brush().color().dark( 180 ) );
QwtPlotDirectPainter directPainter;
directPainter.drawSeries( d_selectedCurve, d_selectedPoint, d_selectedPoint );
if ( showIt )
symbol->setBrush( brush ); // reset brush
}
// Select the next/previous curve
void CanvasPicker::shiftCurveCursor( bool up )
{
QwtPlotItemIterator it;
const QwtPlotItemList &itemList = plot()->itemList();
QwtPlotItemList curveList;
for ( it = itemList.begin(); it != itemList.end(); ++it )
{
if ( ( *it )->rtti() == QwtPlotItem::Rtti_PlotCurve )
curveList += *it;
}
if ( curveList.isEmpty() )
return;
it = curveList.begin();
if ( d_selectedCurve )
{
for ( it = curveList.begin(); it != curveList.end(); ++it )
{
if ( d_selectedCurve == *it )
break;
}
if ( it == curveList.end() ) // not found
it = curveList.begin();
if ( up )
{
++it;
if ( it == curveList.end() )
it = curveList.begin();
}
else
{
if ( it == curveList.begin() )
it = curveList.end();
--it;
}
}
showCursor( false );
d_selectedPoint = 0;
d_selectedCurve = static_cast<QwtPlotCurve *>( *it );
showCursor( true );
}
// Select the next/previous neighbour of the selected point
void CanvasPicker::shiftPointCursor( bool up )
{
if ( !d_selectedCurve )
return;
int index = d_selectedPoint + ( up ? 1 : -1 );
index = ( index + d_selectedCurve->dataSize() ) % d_selectedCurve->dataSize();
if ( index != d_selectedPoint )
{
showCursor( false );
d_selectedPoint = index;
showCursor( true );
}
}
|
iclosure/jdataanalyse
|
source/core/3rdpart/qwt/examples/event_filter/canvaspicker.cpp
|
C++
|
gpl-2.0
| 10,211 |
#include <linux/err.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/tcp.h>
#include <linux/rcupdate.h>
#include <linux/rculist.h>
#include <net/inetpeer.h>
#include <net/tcp.h>
int sysctl_tcp_fastopen __read_mostly = TFO_CLIENT_ENABLE;
struct tcp_fastopen_context __rcu *tcp_fastopen_ctx;
static DEFINE_SPINLOCK(tcp_fastopen_ctx_lock);
void tcp_fastopen_init_key_once(bool publish)
{
static u8 key[TCP_FASTOPEN_KEY_LENGTH];
/* tcp_fastopen_reset_cipher publishes the new context
* atomically, so we allow this race happening here.
*
* All call sites of tcp_fastopen_cookie_gen also check
* for a valid cookie, so this is an acceptable risk.
*/
if (net_get_random_once(key, sizeof(key)) && publish)
tcp_fastopen_reset_cipher(key, sizeof(key));
}
static void tcp_fastopen_ctx_free(struct rcu_head *head)
{
struct tcp_fastopen_context *ctx =
container_of(head, struct tcp_fastopen_context, rcu);
crypto_free_cipher(ctx->tfm);
kfree(ctx);
}
int tcp_fastopen_reset_cipher(void *key, unsigned int len)
{
int err;
struct tcp_fastopen_context *ctx, *octx;
ctx = kmalloc(sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->tfm = crypto_alloc_cipher("aes", 0, 0);
if (IS_ERR(ctx->tfm)) {
err = PTR_ERR(ctx->tfm);
error: kfree(ctx);
pr_err("TCP: TFO aes cipher alloc error: %d\n", err);
return err;
}
err = crypto_cipher_setkey(ctx->tfm, key, len);
if (err) {
pr_err("TCP: TFO cipher key error: %d\n", err);
crypto_free_cipher(ctx->tfm);
goto error;
}
memcpy(ctx->key, key, len);
spin_lock(&tcp_fastopen_ctx_lock);
octx = rcu_dereference_protected(tcp_fastopen_ctx,
lockdep_is_held(&tcp_fastopen_ctx_lock));
rcu_assign_pointer(tcp_fastopen_ctx, ctx);
spin_unlock(&tcp_fastopen_ctx_lock);
if (octx)
call_rcu(&octx->rcu, tcp_fastopen_ctx_free);
return err;
}
static bool __tcp_fastopen_cookie_gen(const void *path,
struct tcp_fastopen_cookie *foc)
{
struct tcp_fastopen_context *ctx;
bool ok = false;
tcp_fastopen_init_key_once(true);
rcu_read_lock();
ctx = rcu_dereference(tcp_fastopen_ctx);
if (ctx) {
crypto_cipher_encrypt_one(ctx->tfm, foc->val, path);
foc->len = TCP_FASTOPEN_COOKIE_SIZE;
ok = true;
}
rcu_read_unlock();
return ok;
}
/* Generate the fastopen cookie by doing aes128 encryption on both
* the source and destination addresses. Pad 0s for IPv4 or IPv4-mapped-IPv6
* addresses. For the longer IPv6 addresses use CBC-MAC.
*
* XXX (TFO) - refactor when TCP_FASTOPEN_COOKIE_SIZE != AES_BLOCK_SIZE.
*/
static bool tcp_fastopen_cookie_gen(struct request_sock *req,
struct sk_buff *syn,
struct tcp_fastopen_cookie *foc)
{
if (req->rsk_ops->family == AF_INET) {
const struct iphdr *iph = ip_hdr(syn);
__be32 path[4] = { iph->saddr, iph->daddr, 0, 0 };
return __tcp_fastopen_cookie_gen(path, foc);
}
#if IS_ENABLED(CONFIG_IPV6)
if (req->rsk_ops->family == AF_INET6) {
const struct ipv6hdr *ip6h = ipv6_hdr(syn);
struct tcp_fastopen_cookie tmp;
if (__tcp_fastopen_cookie_gen(&ip6h->saddr, &tmp)) {
struct in6_addr *buf = (struct in6_addr *) tmp.val;
int i;
for (i = 0; i < 4; i++)
buf->s6_addr32[i] ^= ip6h->daddr.s6_addr32[i];
return __tcp_fastopen_cookie_gen(buf, foc);
}
}
#endif
return false;
}
static bool tcp_fastopen_create_child(struct sock *sk,
struct sk_buff *skb,
struct dst_entry *dst,
struct request_sock *req)
{
struct tcp_sock *tp;
struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
struct sock *child;
u32 end_seq;
req->num_retrans = 0;
req->num_timeout = 0;
req->sk = NULL;
child = inet_csk(sk)->icsk_af_ops->syn_recv_sock(sk, skb, req, NULL);
if (child == NULL)
return false;
spin_lock(&queue->fastopenq->lock);
queue->fastopenq->qlen++;
spin_unlock(&queue->fastopenq->lock);
/* Initialize the child socket. Have to fix some values to take
* into account the child is a Fast Open socket and is created
* only out of the bits carried in the SYN packet.
*/
tp = tcp_sk(child);
tp->fastopen_rsk = req;
/* Do a hold on the listner sk so that if the listener is being
* closed, the child that has been accepted can live on and still
* access listen_lock.
*/
sock_hold(sk);
tcp_rsk(req)->listener = sk;
/* RFC1323: The window in SYN & SYN/ACK segments is never
* scaled. So correct it appropriately.
*/
tp->snd_wnd = ntohs(tcp_hdr(skb)->window);
/* Activate the retrans timer so that SYNACK can be retransmitted.
* The request socket is not added to the SYN table of the parent
* because it's been added to the accept queue directly.
*/
inet_csk_reset_xmit_timer(child, ICSK_TIME_RETRANS,
TCP_TIMEOUT_INIT, TCP_RTO_MAX);
/* Add the child socket directly into the accept queue */
inet_csk_reqsk_queue_add(sk, req, child);
/* Now finish processing the fastopen child socket. */
inet_csk(child)->icsk_af_ops->rebuild_header(child);
tcp_init_congestion_control(child);
tcp_mtup_init(child);
tcp_init_metrics(child);
tcp_init_buffer_space(child);
/* Queue the data carried in the SYN packet. We need to first
* bump skb's refcnt because the caller will attempt to free it.
* Note that IPv6 might also have used skb_get() trick
* in tcp_v6_conn_request() to keep this SYN around (treq->pktopts)
* So we need to eventually get a clone of the packet,
* before inserting it in sk_receive_queue.
*
* XXX (TFO) - we honor a zero-payload TFO request for now,
* (any reason not to?) but no need to queue the skb since
* there is no data. How about SYN+FIN?
*/
end_seq = TCP_SKB_CB(skb)->end_seq;
if (end_seq != TCP_SKB_CB(skb)->seq + 1) {
struct sk_buff *skb2;
if (unlikely(skb_shared(skb)))
skb2 = skb_clone(skb, GFP_ATOMIC);
else
skb2 = skb_get(skb);
if (likely(skb2)) {
skb_dst_drop(skb2);
__skb_pull(skb2, tcp_hdrlen(skb));
skb_set_owner_r(skb2, child);
__skb_queue_tail(&child->sk_receive_queue, skb2);
tp->syn_data_acked = 1;
} else {
end_seq = TCP_SKB_CB(skb)->seq + 1;
}
}
tcp_rsk(req)->rcv_nxt = tp->rcv_nxt = end_seq;
sk->sk_data_ready(sk);
bh_unlock_sock(child);
sock_put(child);
WARN_ON(req->sk == NULL);
return true;
}
static bool tcp_fastopen_queue_check(struct sock *sk)
{
struct fastopen_queue *fastopenq;
/* Make sure the listener has enabled fastopen, and we don't
* exceed the max # of pending TFO requests allowed before trying
* to validating the cookie in order to avoid burning CPU cycles
* unnecessarily.
*
* XXX (TFO) - The implication of checking the max_qlen before
* processing a cookie request is that clients can't differentiate
* between qlen overflow causing Fast Open to be disabled
* temporarily vs a server not supporting Fast Open at all.
*/
fastopenq = inet_csk(sk)->icsk_accept_queue.fastopenq;
if (fastopenq == NULL || fastopenq->max_qlen == 0)
return false;
if (fastopenq->qlen >= fastopenq->max_qlen) {
struct request_sock *req1;
spin_lock(&fastopenq->lock);
req1 = fastopenq->rskq_rst_head;
if ((req1 == NULL) || time_after(req1->expires, jiffies)) {
spin_unlock(&fastopenq->lock);
NET_INC_STATS_BH(sock_net(sk),
LINUX_MIB_TCPFASTOPENLISTENOVERFLOW);
return false;
}
fastopenq->rskq_rst_head = req1->dl_next;
fastopenq->qlen--;
spin_unlock(&fastopenq->lock);
reqsk_free(req1);
}
return true;
}
/* Returns true if we should perform Fast Open on the SYN. The cookie (foc)
* may be updated and return the client in the SYN-ACK later. E.g., Fast Open
* cookie request (foc->len == 0).
*/
bool tcp_try_fastopen(struct sock *sk, struct sk_buff *skb,
struct request_sock *req,
struct tcp_fastopen_cookie *foc,
struct dst_entry *dst)
{
struct tcp_fastopen_cookie valid_foc = { .len = -1 };
bool syn_data = TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq + 1;
if (foc->len == 0) /* Client requests a cookie */
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPFASTOPENCOOKIEREQD);
if (!((sysctl_tcp_fastopen & TFO_SERVER_ENABLE) &&
(syn_data || foc->len >= 0) &&
tcp_fastopen_queue_check(sk))) {
foc->len = -1;
return false;
}
if (syn_data && (sysctl_tcp_fastopen & TFO_SERVER_COOKIE_NOT_REQD))
goto fastopen;
if (foc->len >= 0 && /* Client presents or requests a cookie */
tcp_fastopen_cookie_gen(req, skb, &valid_foc) &&
foc->len == TCP_FASTOPEN_COOKIE_SIZE &&
foc->len == valid_foc.len &&
!memcmp(foc->val, valid_foc.val, foc->len)) {
/* Cookie is valid. Create a (full) child socket to accept
* the data in SYN before returning a SYN-ACK to ack the
* data. If we fail to create the socket, fall back and
* ack the ISN only but includes the same cookie.
*
* Note: Data-less SYN with valid cookie is allowed to send
* data in SYN_RECV state.
*/
fastopen:
if (tcp_fastopen_create_child(sk, skb, dst, req)) {
foc->len = -1;
NET_INC_STATS_BH(sock_net(sk),
LINUX_MIB_TCPFASTOPENPASSIVE);
return true;
}
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPFASTOPENPASSIVEFAIL);
} else if (foc->len > 0) /* Client presents an invalid cookie */
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPFASTOPENPASSIVEFAIL);
*foc = valid_foc;
return false;
}
EXPORT_SYMBOL(tcp_try_fastopen);
|
vladzcloudius/net-next
|
net/ipv4/tcp_fastopen.c
|
C
|
gpl-2.0
| 9,282 |
/*
Copyright 1990, 1998, 2005, 2006 by Al Williams ([email protected])
This file is part of Binds
Binds is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Binds is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Binds; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// SCBIND.C The "compiler" part of the AWC Shell Script Compiler
// Written in 1990 by Al Williams
// Updated 1998 for Linux/ANSI
// Updated 2006 for GPL release
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "config.h"
// Assume no lines bigger than 8K
char linebuf[8192];
// User provided encoder and decoder
char *decode(char *,size_t len); // not really used here
char *encode(char *, size_t len, size_t *outlen);
FILE *efopen();
// Users shouldn't call this directly, but if you must
// $1 = input name
// $2 = C program name (output)
// $3 = output name
// $4 = Shell line
// $5 = Shell option
main(int argc,char *argv[])
{
FILE *in,*out;
int first=1;
int linect=0;
int n=0;
char *lp;
/* For now first 4 arguments are required */
if (argc!=5&&argc!=6) help();
in=efopen(argv[1],"r");
out=efopen(argv[2],"w");
// figure out shell name
strcpy(linebuf,argv[4]);
while (isspace(*(linebuf+n))) n++; /* skip spaces */
if (linebuf[n]!='#' || linebuf[n+1]!='!')
strcpy(linebuf,"#!/bin/sh"); // default
else
while (isspace(*(linebuf+n+2))) n++;
fprintf(out,"char *shell=\"%s\";\n",linebuf+n+2);
// figure out arguments
if (argc==6)
fprintf(out,"char *opt=\"%s\";\n",argv[5]);
else
fprintf(out,"char *opt=(char *)0;\n");
// name program
fprintf(out,"char *name=\"%s\";\n\n",argv[3]);
// spit out encoded text
fprintf(out,"char lines[]={\n");
linebuf[0]='\0';
lp=linebuf;
while (!feof(in))
{
size_t result;
// get line of script
lp=fgets(lp,sizeof(linebuf)-strlen(linebuf),in);
if (!lp)
if (feof(in)) break; else error("input file");
lp=strchr(linebuf,'\n');
if (!lp) error("Line too long");
if (lp[-1]=='\\') { *--lp='\0'; continue; }
// encode it
lp=encode(linebuf,strlen(linebuf)+1,&result);
// this is ugly. We assume no line is >8192 so two characters
// can hold it. So even with buffer change 64K line limit!
fprintf(out,"%c%d,%d",first?'\t':',',(int)result/256,(int)(result&0xFF));
first=0;
while(result--)
{
// every 10 lines, output a new line to keep things neat
if (linect++>10) { linect=0; fprintf(out,"\n\t"); }
// output each byte
fprintf(out,",%d",*lp++);
}
// end of line
// fprintf(out,",0");
lp=linebuf;
*linebuf='\0';
}
// write code to compute total
fprintf(out,"\n\t};\n\nunsigned linesize=sizeof(lines);\n");
if (fclose(out)) error("output file");
exit(0);
}
help()
{
fprintf(stderr,"SCBIND " VERSION " -- shell script binder by Al Williams\n");
fprintf(stderr,"Usage: scbind INFILE OUTFILE NAME SHELL [ARG]\n");
exit(1);
}
// some kind of error
error(char *s)
{
perror(s);
exit(2);
}
// Open with error checking
FILE *efopen(char *fn,char *mode)
{
FILE *fp;
if (!(fp=fopen(fn,mode))) error(fn);
return fp;
}
|
ggnull35/scbind
|
scbind.c
|
C
|
gpl-2.0
| 3,792 |
/*
* Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package test.javafx.scene.control;
import com.sun.javafx.scene.control.TableColumnBaseHelper;
import static test.com.sun.javafx.scene.control.infrastructure.ControlTestUtils.assertStyleClassContains;
import static javafx.scene.control.TreeTableColumn.SortType.ASCENDING;
import static javafx.scene.control.TreeTableColumn.SortType.DESCENDING;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import com.sun.javafx.scene.control.behavior.TreeTableCellBehavior;
import javafx.beans.property.ReadOnlyIntegerWrapper;
import javafx.collections.transformation.FilteredList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import test.com.sun.javafx.scene.control.infrastructure.KeyEventFirer;
import test.com.sun.javafx.scene.control.infrastructure.KeyModifier;
import test.com.sun.javafx.scene.control.infrastructure.MouseEventFirer;
import javafx.scene.control.skin.TreeTableCellSkin;
import test.com.sun.javafx.scene.control.test.Data;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyBooleanWrapper;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TreeTableView.TreeTableViewFocusModel;
import javafx.scene.control.cell.*;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Callback;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.sun.javafx.scene.control.TableColumnComparatorBase.TreeTableColumnComparator;
import test.com.sun.javafx.scene.control.infrastructure.ControlTestUtils;
import test.com.sun.javafx.scene.control.infrastructure.StageLoader;
import test.com.sun.javafx.scene.control.infrastructure.VirtualFlowTestUtils;
import com.sun.javafx.scene.control.VirtualScrollBar;
import test.com.sun.javafx.scene.control.test.Person;
import test.com.sun.javafx.scene.control.test.RT_22463_Person;
import com.sun.javafx.tk.Toolkit;
import javafx.scene.control.Button;
import javafx.scene.control.Cell;
import javafx.scene.control.FocusModel;
import javafx.scene.control.IndexedCell;
import javafx.scene.control.MultipleSelectionModel;
import javafx.scene.control.MultipleSelectionModelBaseShim;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumnBaseShim;
import javafx.scene.control.TableSelectionModel;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableCellShim;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTablePosition;
import javafx.scene.control.TreeTableRow;
import javafx.scene.control.TreeTableRowShim;
import javafx.scene.control.TreeTableView;
import javafx.scene.control.TreeTableViewShim;
import javafx.scene.control.TreeView;
public class TreeTableViewTest {
private TreeTableView<String> treeTableView;
private TreeTableView.TreeTableViewSelectionModel sm;
private TreeTableViewFocusModel<String> fm;
// sample data #1
private TreeItem<String> root;
private TreeItem<String> child1;
private TreeItem<String> child2;
private TreeItem<String> child3;
// sample data #1
private TreeItem<String> myCompanyRootNode;
private TreeItem<String> salesDepartment;
private TreeItem<String> ethanWilliams;
private TreeItem<String> emmaJones;
private TreeItem<String> michaelBrown;
private TreeItem<String> annaBlack;
private TreeItem<String> rodgerYork;
private TreeItem<String> susanCollins;
private TreeItem<String> itSupport;
private TreeItem<String> mikeGraham;
private TreeItem<String> judyMayer;
private TreeItem<String> gregorySmith;
@Before public void setup() {
treeTableView = new TreeTableView<String>();
sm = treeTableView.getSelectionModel();
fm = treeTableView.getFocusModel();
// build sample data #2, even though it may not be used...
myCompanyRootNode = new TreeItem<String>("MyCompany Human Resources");
salesDepartment = new TreeItem<String>("Sales Department");
ethanWilliams = new TreeItem<String>("Ethan Williams");
emmaJones = new TreeItem<String>("Emma Jones");
michaelBrown = new TreeItem<String>("Michael Brown");
annaBlack = new TreeItem<String>("Anna Black");
rodgerYork = new TreeItem<String>("Rodger York");
susanCollins = new TreeItem<String>("Susan Collins");
itSupport = new TreeItem<String>("IT Support");
mikeGraham = new TreeItem<String>("Mike Graham");
judyMayer = new TreeItem<String>("Judy Mayer");
gregorySmith = new TreeItem<String>("Gregory Smith");
myCompanyRootNode.getChildren().setAll(
salesDepartment,
itSupport
);
salesDepartment.getChildren().setAll(
ethanWilliams,
emmaJones,
michaelBrown,
annaBlack,
rodgerYork,
susanCollins
);
itSupport.getChildren().setAll(
mikeGraham,
judyMayer,
gregorySmith
);
}
private void installChildren() {
root = new TreeItem<String>("Root");
child1 = new TreeItem<String>("Child 1");
child2 = new TreeItem<String>("Child 2");
child3 = new TreeItem<String>("Child 3");
root.setExpanded(true);
root.getChildren().setAll(child1, child2, child3);
treeTableView.setRoot(root);
}
private String debug() {
StringBuilder sb = new StringBuilder("Selected Cells: [");
List<TreeTablePosition<?,?>> cells = sm.getSelectedCells();
for (TreeTablePosition cell : cells) {
sb.append("(");
sb.append(cell.getRow());
sb.append(",");
sb.append(cell.getColumn());
sb.append("), ");
}
sb.append("] \nFocus: " + fm.getFocusedIndex());
// sb.append(" \nAnchor: " + getAnchor());
return sb.toString();
}
@Test public void ensureCorrectInitialState() {
installChildren();
assertEquals(0, treeTableView.getRow(root));
assertEquals(1, treeTableView.getRow(child1));
assertEquals(2, treeTableView.getRow(child2));
assertEquals(3, treeTableView.getRow(child3));
}
/***************************************************************************
*
*
* Tests taken from TableViewTest
* (scroll down further for the TreeViewTests)
*
*
**************************************************************************/
/*********************************************************************
* Tests for the constructors *
********************************************************************/
@Test public void noArgConstructorSetsNonNullSelectionModel() {
assertNotNull(sm);
}
@Test public void noArgConstructor_selectedItemIsNull() {
assertNull(sm.getSelectedItem());
}
@Test public void noArgConstructor_selectedIndexIsNegativeOne() {
assertEquals(-1, sm.getSelectedIndex());
}
@Test public void noArgConstructorSetsNonNullSortPolicy() {
assertNotNull(treeTableView.getSortPolicy());
}
@Test public void noArgConstructorSetsNullComparator() {
assertNull(treeTableView.getComparator());
}
@Test public void noArgConstructorSetsNullOnSort() {
assertNull(treeTableView.getOnSort());
}
// @Test public void singleArgConstructorSetsNonNullSelectionModel() {
// final TreeTableView<String> b2 = new TreeTableView<String>(FXCollections.observableArrayList("Hi"));
// assertNotNull(b2.getSelectionModel());
// }
//
// @Test public void singleArgConstructorAllowsNullItems() {
// final TreeTableView<String> b2 = new TreeTableView<String>(null);
// assertNull(b2.getItems());
// }
//
// @Test public void singleArgConstructorTakesItems() {
// ObservableList<String> items = FXCollections.observableArrayList("Hi");
// final TreeTableView<String> b2 = new TreeTableView<String>(items);
// assertSame(items, b2.getItems());
// }
//
// @Test public void singleArgConstructor_selectedItemIsNull() {
// final TreeTableView<String> b2 = new TreeTableView<String>(FXCollections.observableArrayList("Hi"));
// assertNull(b2.getSelectionModel().getSelectedItem());
// }
//
// @Test public void singleArgConstructor_selectedIndexIsNegativeOne() {
// final TreeTableView<String> b2 = new TreeTableView<String>(FXCollections.observableArrayList("Hi"));
// assertEquals(-1, b2.getSelectionModel().getSelectedIndex());
// }
/*********************************************************************
* Tests for columns *
********************************************************************/
@Test public void testColumns() {
TreeTableColumn col1 = new TreeTableColumn();
assertNotNull(treeTableView.getColumns());
assertEquals(0, treeTableView.getColumns().size());
treeTableView.getColumns().add(col1);
assertEquals(1, treeTableView.getColumns().size());
treeTableView.getColumns().remove(col1);
assertEquals(0, treeTableView.getColumns().size());
}
@Test public void testVisibleLeafColumns() {
TreeTableColumn col1 = new TreeTableColumn();
assertNotNull(treeTableView.getColumns());
assertEquals(0, treeTableView.getColumns().size());
treeTableView.getColumns().add(col1);
assertEquals(1, treeTableView.getVisibleLeafColumns().size());
treeTableView.getColumns().remove(col1);
assertEquals(0, treeTableView.getVisibleLeafColumns().size());
}
@Test public void testSortOrderCleanup() {
TreeTableView treeTableView = new TreeTableView();
TreeTableColumn<String,String> first = new TreeTableColumn<String,String>("first");
first.setCellValueFactory(new PropertyValueFactory("firstName"));
TreeTableColumn<String,String> second = new TreeTableColumn<String,String>("second");
second.setCellValueFactory(new PropertyValueFactory("lastName"));
treeTableView.getColumns().addAll(first, second);
treeTableView.getSortOrder().setAll(first, second);
treeTableView.getColumns().remove(first);
assertFalse(treeTableView.getSortOrder().contains(first));
}
/*********************************************************************
* Tests for new sorting API in JavaFX 8.0 *
********************************************************************/
private TreeItem<String> apple, orange, banana;
// TODO test for sort policies returning null
// TODO test for changing column sortType out of order
private static final Callback<TreeTableView<String>, Boolean> NO_SORT_FAILED_SORT_POLICY =
treeTableView1 -> false;
private static final Callback<TreeTableView<String>, Boolean> SORT_SUCCESS_ASCENDING_SORT_POLICY =
treeTableView1 -> {
if (treeTableView1.getSortOrder().isEmpty()) return true;
FXCollections.sort(treeTableView1.getRoot().getChildren(), new Comparator<TreeItem<String>>() {
@Override public int compare(TreeItem<String> o1, TreeItem<String> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
return true;
};
private TreeTableColumn<String, String> initSortTestStructure() {
TreeTableColumn<String, String> col = new TreeTableColumn<String, String>("column");
col.setSortType(ASCENDING);
col.setCellValueFactory(param -> new ReadOnlyObjectWrapper<String>(param.getValue().getValue()));
treeTableView.getColumns().add(col);
TreeItem<String> newRoot = new TreeItem<String>("root");
newRoot.setExpanded(true);
newRoot.getChildren().addAll(
apple = new TreeItem("Apple"),
orange = new TreeItem("Orange"),
banana = new TreeItem("Banana"));
treeTableView.setRoot(newRoot);
return col;
}
@Ignore("This test is only valid if sort event consumption should revert changes")
@Test public void testSortEventCanBeConsumedToStopSortOccurring_changeSortOrderList() {
TreeTableColumn<String, String> col = initSortTestStructure();
treeTableView.setOnSort(event -> {
event.consume();
});
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
treeTableView.getSortOrder().add(col);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
// the sort order list should be returned back to its original state
assertTrue(treeTableView.getSortOrder().isEmpty());
}
@Test public void testSortEventCanBeNotConsumedToAllowSortToOccur_changeSortOrderList() {
TreeTableColumn<String, String> col = initSortTestStructure();
treeTableView.setOnSort(event -> {
// do not consume here - this allows the sort to happen
});
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
treeTableView.getSortOrder().add(col);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, banana, orange);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getSortOrder(), col);
}
@Ignore("This test is only valid if sort event consumption should revert changes")
@Test public void testSortEventCanBeConsumedToStopSortOccurring_changeColumnSortType_AscendingToDescending() {
TreeTableColumn<String, String> col = initSortTestStructure();
assertEquals(ASCENDING, col.getSortType());
treeTableView.getSortOrder().add(col);
treeTableView.setOnSort(event -> {
event.consume();
});
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, banana, orange);
// when we change from ASCENDING to DESCENDING we don't expect the sort
// to actually change (and in fact we expect the sort type to resort
// back to being ASCENDING)
col.setSortType(DESCENDING);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, banana, orange);
assertEquals(ASCENDING, col.getSortType());
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getSortOrder(), col);
}
@Test public void testSortEventCanBeNotConsumedToAllowSortToOccur_changeColumnSortType_AscendingToDescending() {
TreeTableColumn<String, String> col = initSortTestStructure();
assertEquals(ASCENDING, col.getSortType());
treeTableView.getSortOrder().add(col);
treeTableView.setOnSort(event -> {
// do not consume here - this allows the sort to happen
});
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, banana, orange);
col.setSortType(DESCENDING);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), orange, banana, apple);
assertEquals(DESCENDING, col.getSortType());
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getSortOrder(), col);
}
@Ignore("This test is only valid if sort event consumption should revert changes")
@Test public void testSortEventCanBeConsumedToStopSortOccurring_changeColumnSortType_DescendingToNull() {
TreeTableColumn<String, String> col = initSortTestStructure();
col.setSortType(DESCENDING);
assertEquals(DESCENDING, col.getSortType());
treeTableView.getSortOrder().add(col);
treeTableView.setOnSort(event -> {
event.consume();
});
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), orange, banana, apple);
col.setSortType(null);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), orange, banana, apple);
assertEquals(DESCENDING, col.getSortType());
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getSortOrder(), col);
}
@Test public void testSortEventCanBeNotConsumedToAllowSortToOccur_changeColumnSortType_DescendingToNull() {
TreeTableColumn<String, String> col = initSortTestStructure();
col.setSortType(DESCENDING);
assertEquals(DESCENDING, col.getSortType());
treeTableView.getSortOrder().add(col);
treeTableView.setOnSort(event -> {
// do not consume here - this allows the sort to happen
});
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), orange, banana, apple);
col.setSortType(null);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), orange, banana, apple);
assertNull(col.getSortType());
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getSortOrder(), col);
}
@Ignore("This test is only valid if sort event consumption should revert changes")
@Test public void testSortEventCanBeConsumedToStopSortOccurring_changeColumnSortType_NullToAscending() {
TreeTableColumn<String, String> col = initSortTestStructure();
col.setSortType(null);
assertNull(col.getSortType());
treeTableView.getSortOrder().add(col);
treeTableView.setOnSort(event -> {
event.consume();
});
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
col.setSortType(ASCENDING);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
assertNull(col.getSortType());
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getSortOrder(), col);
}
@Test public void testSortEventCanBeNotConsumedToAllowSortToOccur_changeColumnSortType_NullToAscending() {
TreeTableColumn<String, String> col = initSortTestStructure();
col.setSortType(null);
assertNull(col.getSortType());
treeTableView.getSortOrder().add(col);
treeTableView.setOnSort(event -> {
// do not consume here - this allows the sort to happen
});
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
col.setSortType(ASCENDING);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, banana, orange);
assertEquals(ASCENDING, col.getSortType());
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getSortOrder(), col);
}
@Test public void testSortMethodWithNullSortPolicy() {
TreeTableColumn<String, String> col = initSortTestStructure();
treeTableView.setSortPolicy(null);
assertNull(treeTableView.getSortPolicy());
treeTableView.sort();
}
@Test public void testChangingSortPolicyUpdatesItemsList() {
TreeTableColumn<String, String> col = initSortTestStructure();
col.setSortType(DESCENDING);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
treeTableView.getSortOrder().add(col);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), orange, banana, apple);
treeTableView.setSortPolicy(SORT_SUCCESS_ASCENDING_SORT_POLICY);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, banana, orange);
}
@Test public void testChangingSortPolicyDoesNotUpdateItemsListWhenTheSortOrderListIsEmpty() {
TreeTableColumn<String, String> col = initSortTestStructure();
col.setSortType(DESCENDING);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
treeTableView.setSortPolicy(SORT_SUCCESS_ASCENDING_SORT_POLICY);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
}
@Test public void testFailedSortPolicyBacksOutLastChange_sortOrderAddition() {
TreeTableColumn<String, String> col = initSortTestStructure();
col.setSortType(DESCENDING);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
treeTableView.setSortPolicy(NO_SORT_FAILED_SORT_POLICY);
treeTableView.getSortOrder().add(col);
// no sort should be run (as we have a custom sort policy), and the
// sortOrder list should be empty as the sortPolicy failed
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
assertTrue(treeTableView.getSortOrder().isEmpty());
}
@Test public void testFailedSortPolicyBacksOutLastChange_sortOrderRemoval() {
TreeTableColumn<String, String> col = initSortTestStructure();
col.setSortType(DESCENDING);
treeTableView.getSortOrder().add(col);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), orange, banana, apple);
treeTableView.setSortPolicy(NO_SORT_FAILED_SORT_POLICY);
// even though we remove the column from the sort order here, because the
// sort policy fails the items list should remain unchanged and the sort
// order list should continue to have the column in it.
treeTableView.getSortOrder().remove(col);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), orange, banana, apple);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getSortOrder(), col);
}
@Test public void testFailedSortPolicyBacksOutLastChange_sortTypeChange_ascendingToDescending() {
TreeTableColumn<String, String> col = initSortTestStructure();
col.setSortType(ASCENDING);
treeTableView.getSortOrder().add(col);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, banana, orange);
treeTableView.setSortPolicy(NO_SORT_FAILED_SORT_POLICY);
col.setSortType(DESCENDING);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, banana, orange);
assertEquals(ASCENDING, col.getSortType());
}
@Test public void testFailedSortPolicyBacksOutLastChange_sortTypeChange_descendingToNull() {
TreeTableColumn<String, String> col = initSortTestStructure();
col.setSortType(DESCENDING);
treeTableView.getSortOrder().add(col);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), orange, banana, apple);
treeTableView.setSortPolicy(NO_SORT_FAILED_SORT_POLICY);
col.setSortType(null);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), orange, banana, apple);
assertEquals(DESCENDING, col.getSortType());
}
@Test public void testFailedSortPolicyBacksOutLastChange_sortTypeChange_nullToAscending() {
TreeTableColumn<String, String> col = initSortTestStructure();
col.setSortType(null);
treeTableView.getSortOrder().add(col);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
treeTableView.setSortPolicy(NO_SORT_FAILED_SORT_POLICY);
col.setSortType(ASCENDING);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
assertNull(col.getSortType());
}
@Test public void testComparatorChangesInSyncWithSortOrder_1() {
TreeTableColumn<String, String> col = initSortTestStructure();
assertNull(treeTableView.getComparator());
assertTrue(treeTableView.getSortOrder().isEmpty());
treeTableView.getSortOrder().add(col);
TreeTableColumnComparator c = (TreeTableColumnComparator)treeTableView.getComparator();
assertNotNull(c);
VirtualFlowTestUtils.assertListContainsItemsInOrder(c.getColumns(), col);
}
@Test public void testComparatorChangesInSyncWithSortOrder_2() {
// same as test above
TreeTableColumn<String, String> col = initSortTestStructure();
assertNull(treeTableView.getComparator());
assertTrue(treeTableView.getSortOrder().isEmpty());
treeTableView.getSortOrder().add(col);
TreeTableColumnComparator c = (TreeTableColumnComparator)treeTableView.getComparator();
assertNotNull(c);
VirtualFlowTestUtils.assertListContainsItemsInOrder(c.getColumns(), col);
// now remove column from sort order, and the comparator should go to
// being null
treeTableView.getSortOrder().remove(col);
assertNull(treeTableView.getComparator());
}
@Test public void testFailedSortPolicyBacksOutComparatorChange_sortOrderAddition() {
TreeTableColumn<String, String> col = initSortTestStructure();
final TreeTableColumnComparator oldComparator = (TreeTableColumnComparator)treeTableView.getComparator();
col.setSortType(DESCENDING);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), apple, orange, banana);
treeTableView.setSortPolicy(NO_SORT_FAILED_SORT_POLICY);
treeTableView.getSortOrder().add(col);
assertEquals(oldComparator, treeTableView.getComparator());
}
@Test public void testFailedSortPolicyBacksOutComparatorChange_sortOrderRemoval() {
TreeTableColumn<String, String> col = initSortTestStructure();
TreeTableColumnComparator oldComparator = (TreeTableColumnComparator)treeTableView.getComparator();
assertNull(oldComparator);
col.setSortType(DESCENDING);
treeTableView.getSortOrder().add(col);
VirtualFlowTestUtils.assertListContainsItemsInOrder(treeTableView.getRoot().getChildren(), orange, banana, apple);
oldComparator = (TreeTableColumnComparator)treeTableView.getComparator();
VirtualFlowTestUtils.assertListContainsItemsInOrder(oldComparator.getColumns(), col);
treeTableView.setSortPolicy(NO_SORT_FAILED_SORT_POLICY);
treeTableView.getSortOrder().remove(col);
assertTrue(treeTableView.getSortOrder().contains(col));
VirtualFlowTestUtils.assertListContainsItemsInOrder(oldComparator.getColumns(), col);
}
@Test public void testFailedSortPolicyBacksOutComparatorChange_sortTypeChange() {
TreeTableColumn<String, String> col = initSortTestStructure();
final TreeTableColumnComparator oldComparator = (TreeTableColumnComparator)treeTableView.getComparator();
assertNull(oldComparator);
treeTableView.setSortPolicy(NO_SORT_FAILED_SORT_POLICY);
treeTableView.getSortOrder().add(col);
col.setSortType(ASCENDING);
assertTrue(treeTableView.getSortOrder().isEmpty());
assertNull(oldComparator);
}
/*********************************************************************
* Tests for specific bugs *
********************************************************************/
// @Test public void test_rt16019() {
// // RT-16019: NodeMemory TableView tests fail with
// // IndexOutOfBoundsException (ObservableListWrapper.java:336)
// TreeTableView treeTableView = new TreeTableView();
// for (int i = 0; i < 1000; i++) {
// treeTableView.getItems().add("data " + i);
// }
// }
//
// @Test public void test_rt15793() {
// // ListView/TableView selectedIndex is 0 although the items list is empty
// final TreeTableView tv = new TreeTableView();
// final ObservableList list = FXCollections.observableArrayList();
// tv.setItems(list);
// list.add("toto");
// tv.getSelectionModel().select(0);
// assertEquals(0, tv.getSelectionModel().getSelectedIndex());
// list.remove(0);
// assertEquals(-1, tv.getSelectionModel().getSelectedIndex());
// }
//
// @Test public void test_rt17522_focusShouldMoveWhenItemAddedAtFocusIndex() {
// final TreeTableView lv = new TreeTableView();
// FocusModel fm = lv.getFocusModel();
// lv.getItems().add("row1");
// fm.focus(0);
// assertTrue(fm.isFocused(0));
//
// lv.getItems().add(0, "row0");
// assertTrue(fm.isFocused(1));
// }
//
// @Test public void test_rt17522_focusShouldMoveWhenItemAddedBeforeFocusIndex() {
// final TreeTableView lv = new TreeTableView();
// FocusModel fm = lv.getFocusModel();
// lv.getItems().addAll("row1", "row2");
// fm.focus(1);
// assertTrue(fm.isFocused(1));
// assertEquals("row2", fm.getFocusedItem());
//
// lv.getItems().add(1, "row0");
// assertTrue(fm.isFocused(2));
// assertEquals("row2", fm.getFocusedItem());
// assertFalse(fm.isFocused(1));
// }
//
// @Test public void test_rt17522_focusShouldNotMoveWhenItemAddedAfterFocusIndex() {
// final TreeTableView lv = new TreeTableView();
// FocusModel fm = lv.getFocusModel();
// lv.getItems().addAll("row1");
// fm.focus(0);
// assertTrue(fm.isFocused(0));
// assertEquals("row1", fm.getFocusedItem());
//
// lv.getItems().add(1, "row2");
// assertTrue(fm.isFocused(0));
// assertEquals("row1", fm.getFocusedItem());
// assertFalse(fm.isFocused(1));
// }
//
// @Test public void test_rt17522_focusShouldBeResetWhenFocusedItemIsRemoved() {
// final TreeTableView lv = new TreeTableView();
// FocusModel fm = lv.getFocusModel();
// lv.getItems().add("row1");
// fm.focus(0);
// assertTrue(fm.isFocused(0));
//
// lv.getItems().remove("row1");
// assertTrue(fm.getFocusedIndex() == -1);
// assertNull(fm.getFocusedItem());
// }
//
// @Test public void test_rt17522_focusShouldMoveWhenItemRemovedBeforeFocusIndex() {
// final TreeTableView lv = new TreeTableView();
// FocusModel fm = lv.getFocusModel();
// lv.getItems().addAll("row1", "row2");
// fm.focus(1);
// assertTrue(fm.isFocused(1));
// assertEquals("row2", fm.getFocusedItem());
//
// lv.getItems().remove("row1");
// assertTrue(fm.isFocused(0));
// assertEquals("row2", fm.getFocusedItem());
// }
//
// @Test public void test_rt17522_focusShouldNotMoveWhenItemRemovedAfterFocusIndex() {
// final TreeTableView lv = new TreeTableView();
// FocusModel fm = lv.getFocusModel();
// lv.getItems().addAll("row1", "row2");
// fm.focus(0);
// assertTrue(fm.isFocused(0));
// assertEquals("row1", fm.getFocusedItem());
//
// lv.getItems().remove("row2");
// assertTrue(fm.isFocused(0));
// assertEquals("row1", fm.getFocusedItem());
// }
//
// @Test public void test_rt18385() {
// treeTableView.getItems().addAll("row1", "row2", "row3");
// sm.select(1);
// treeTableView.getItems().add("Another Row");
// assertEquals(1, sm.getSelectedIndices().size());
// assertEquals(1, sm.getSelectedItems().size());
// assertEquals(1, sm.getSelectedCells().size());
// }
@Test public void test_rt18339_onlyEditWhenTableViewIsEditable_tableEditableIsFalse_columnEditableIsFalse() {
TreeTableColumn<String,String> first = new TreeTableColumn<String,String>("first");
first.setEditable(false);
treeTableView.getColumns().add(first);
treeTableView.setEditable(false);
treeTableView.edit(1, first);
assertEquals(null, treeTableView.getEditingCell());
}
@Test public void test_rt18339_onlyEditWhenTableViewIsEditable_tableEditableIsFalse_columnEditableIsTrue() {
TreeTableColumn<String,String> first = new TreeTableColumn<String,String>("first");
first.setEditable(true);
treeTableView.getColumns().add(first);
treeTableView.setEditable(false);
treeTableView.edit(1, first);
assertEquals(null, treeTableView.getEditingCell());
}
@Test public void test_rt18339_onlyEditWhenTableViewIsEditable_tableEditableIsTrue_columnEditableIsFalse() {
TreeTableColumn<String,String> first = new TreeTableColumn<String,String>("first");
first.setEditable(false);
treeTableView.getColumns().add(first);
treeTableView.setEditable(true);
treeTableView.edit(1, first);
assertEquals(null, treeTableView.getEditingCell());
}
@Test public void test_rt18339_onlyEditWhenTableViewIsEditable_tableEditableIsTrue_columnEditableIsTrue() {
TreeTableColumn<String,String> first = new TreeTableColumn<String,String>("first");
first.setEditable(true);
treeTableView.getColumns().add(first);
treeTableView.setEditable(true);
treeTableView.edit(1, first);
assertEquals(new TreeTablePosition(treeTableView, 1, first), treeTableView.getEditingCell());
}
// @Test public void test_rt14451() {
// treeTableView.getItems().addAll("Apple", "Orange", "Banana");
// sm.setSelectionMode(SelectionMode.MULTIPLE);
// sm.selectRange(0, 2); // select from 0 (inclusive) to 2 (exclusive)
// assertEquals(2, sm.getSelectedIndices().size());
// }
//
// @Test public void test_rt21586() {
// treeTableView.getItems().setAll("Apple", "Orange", "Banana");
// treeTableView.getSelectionModel().select(1);
// assertEquals(1, treeTableView.getSelectionModel().getSelectedIndex());
// assertEquals("Orange", treeTableView.getSelectionModel().getSelectedItem());
//
// treeTableView.getItems().setAll("Kiwifruit", "Pineapple", "Grape");
// assertEquals(-1, treeTableView.getSelectionModel().getSelectedIndex());
// assertNull(treeTableView.getSelectionModel().getSelectedItem());
// }
/***************************************************************************
*
*
* Tests taken from TreeViewTest
*
*
**************************************************************************/
/*********************************************************************
* Tests for the constructors *
********************************************************************/
@Test public void noArgConstructorSetsTheStyleClass() {
assertStyleClassContains(treeTableView, "tree-table-view");
}
@Test public void noArgConstructorSetsNullItems() {
assertNull(treeTableView.getRoot());
}
@Test public void singleArgConstructorSetsTheStyleClass() {
final TreeTableView<String> b2 = new TreeTableView<String>(new TreeItem<String>("Hi"));
assertStyleClassContains(b2, "tree-table-view");
}
/*********************************************************************
* Tests for selection model *
********************************************************************/
@Test public void selectionModelCanBeNull() {
treeTableView.setSelectionModel(null);
assertNull(treeTableView.getSelectionModel());
}
@Test public void selectionModelCanBeBound() {
TableSelectionModel<TreeItem<String>> sm =
TreeTableViewShim.<String>get_TreeTableViewArrayListSelectionModel(treeTableView);
ObjectProperty<TreeTableView.TreeTableViewSelectionModel<String>> other =
new SimpleObjectProperty(sm);
treeTableView.selectionModelProperty().bind(other);
assertSame(sm, treeTableView.getSelectionModel());
}
@Test public void selectionModelCanBeChanged() {
TableSelectionModel<TreeItem<String>> sm =
TreeTableViewShim.<String>get_TreeTableViewArrayListSelectionModel(treeTableView);
TreeTableViewShim.<String>setSelectionModel(treeTableView, sm);
assertSame(sm, treeTableView.getSelectionModel());
}
@Test public void canSetSelectedItemToAnItemEvenWhenThereAreNoItems() {
TreeItem<String> element = new TreeItem<String>("I AM A CRAZY RANDOM STRING");
treeTableView.getSelectionModel().select(element);
assertEquals(-1, treeTableView.getSelectionModel().getSelectedIndex());
assertSame(element, treeTableView.getSelectionModel().getSelectedItem());
}
@Test public void canSetSelectedItemToAnItemNotInTheDataModel() {
installChildren();
TreeItem<String> element = new TreeItem<String>("I AM A CRAZY RANDOM STRING");
treeTableView.getSelectionModel().select(element);
assertEquals(-1, treeTableView.getSelectionModel().getSelectedIndex());
assertSame(element, treeTableView.getSelectionModel().getSelectedItem());
}
@Test public void settingTheSelectedItemToAnItemInItemsResultsInTheCorrectSelectedIndex() {
installChildren();
treeTableView.getSelectionModel().select(child1);
assertEquals(1, treeTableView.getSelectionModel().getSelectedIndex());
assertSame(child1, treeTableView.getSelectionModel().getSelectedItem());
}
@Ignore("Not yet supported")
@Test public void settingTheSelectedItemToANonexistantItemAndThenSettingItemsWhichContainsItResultsInCorrectSelectedIndex() {
treeTableView.getSelectionModel().select(child1);
installChildren();
assertEquals(1, treeTableView.getSelectionModel().getSelectedIndex());
assertSame(child1, treeTableView.getSelectionModel().getSelectedItem());
}
@Ignore("Not yet supported")
@Test public void ensureSelectionClearsWhenAllItemsAreRemoved_selectIndex0() {
installChildren();
treeTableView.getSelectionModel().select(0);
treeTableView.setRoot(null);
assertEquals(-1, treeTableView.getSelectionModel().getSelectedIndex());
assertEquals(null, treeTableView.getSelectionModel().getSelectedItem());
}
@Ignore("Not yet supported")
@Test public void ensureSelectionClearsWhenAllItemsAreRemoved_selectIndex2() {
installChildren();
treeTableView.getSelectionModel().select(2);
treeTableView.setRoot(null);
assertEquals(-1, treeTableView.getSelectionModel().getSelectedIndex());
assertEquals(null, treeTableView.getSelectionModel().getSelectedItem());
}
@Ignore("Not yet supported")
@Test public void ensureSelectedItemRemainsAccurateWhenItemsAreCleared() {
installChildren();
treeTableView.getSelectionModel().select(2);
treeTableView.setRoot(null);
assertNull(treeTableView.getSelectionModel().getSelectedItem());
assertEquals(-1, treeTableView.getSelectionModel().getSelectedIndex());
TreeItem<String> newRoot = new TreeItem<String>("New Root");
TreeItem<String> newChild1 = new TreeItem<String>("New Child 1");
TreeItem<String> newChild2 = new TreeItem<String>("New Child 2");
TreeItem<String> newChild3 = new TreeItem<String>("New Child 3");
newRoot.setExpanded(true);
newRoot.getChildren().setAll(newChild1, newChild2, newChild3);
treeTableView.setRoot(root);
treeTableView.getSelectionModel().select(2);
assertEquals(newChild2, treeTableView.getSelectionModel().getSelectedItem());
}
@Test public void ensureSelectionIsCorrectWhenItemsChange() {
installChildren();
treeTableView.getSelectionModel().select(0);
assertEquals(root, treeTableView.getSelectionModel().getSelectedItem());
TreeItem newRoot = new TreeItem<String>("New Root");
treeTableView.setRoot(newRoot);
assertEquals(-1, treeTableView.getSelectionModel().getSelectedIndex());
assertNull(treeTableView.getSelectionModel().getSelectedItem());
assertEquals(0, treeTableView.getFocusModel().getFocusedIndex());
assertEquals(newRoot, treeTableView.getFocusModel().getFocusedItem());
}
@Test public void ensureSelectionRemainsOnBranchWhenExpanded() {
installChildren();
root.setExpanded(false);
treeTableView.getSelectionModel().select(0);
assertTrue(treeTableView.getSelectionModel().isSelected(0));
root.setExpanded(true);
assertTrue(treeTableView.getSelectionModel().isSelected(0));
assertTrue(treeTableView.getSelectionModel().getSelectedItems().contains(root));
}
/*********************************************************************
* Tests for misc *
********************************************************************/
@Test public void ensureRootIndexIsZeroWhenRootIsShowing() {
installChildren();
assertEquals(0, treeTableView.getRow(root));
}
@Test public void ensureRootIndexIsNegativeOneWhenRootIsNotShowing() {
installChildren();
treeTableView.setShowRoot(false);
assertEquals(-1, treeTableView.getRow(root));
}
@Test public void ensureCorrectIndexWhenRootTreeItemHasParent() {
installChildren();
treeTableView.setRoot(child1);
assertEquals(-1, treeTableView.getRow(root));
assertEquals(0, treeTableView.getRow(child1));
assertEquals(1, treeTableView.getRow(child2));
assertEquals(2, treeTableView.getRow(child3));
}
@Test public void ensureCorrectIndexWhenRootTreeItemHasParentAndRootIsNotShowing() {
installChildren();
treeTableView.setRoot(child1);
treeTableView.setShowRoot(false);
// despite the fact there are children in this tree, in reality none are
// visible as the root node has no children (only siblings), and the
// root node is not visible.
assertEquals(0, treeTableView.getExpandedItemCount());
assertEquals(-1, treeTableView.getRow(root));
assertEquals(-1, treeTableView.getRow(child1));
assertEquals(-1, treeTableView.getRow(child2));
assertEquals(-1, treeTableView.getRow(child3));
}
@Test public void ensureCorrectIndexWhenRootTreeItemIsCollapsed() {
installChildren();
root.setExpanded(false);
assertEquals(0, treeTableView.getRow(root));
// note that the indices are negative, as these children rows are not
// visible in the tree
assertEquals(-1, treeTableView.getRow(child1));
assertEquals(-1, treeTableView.getRow(child2));
assertEquals(-1, treeTableView.getRow(child3));
}
// @Test public void removingLastTest() {
// TreeTableView tree_view = new TreeTableView();
// MultipleSelectionModel sm = tree_view.getSelectionModel();
// TreeItem<String> tree_model = new TreeItem<String>("Root");
// TreeItem node = new TreeItem("Data item");
// tree_model.getChildren().add(node);
// tree_view.setRoot(tree_model);
// tree_model.setExpanded(true);
// // select the 'Data item' in the selection model
// sm.select(tree_model.getChildren().get(0));
// // remove the 'Data item' from the root node
// tree_model.getChildren().remove(sm.getSelectedItem());
// // assert the there are no selected items any longer
// assertTrue("items: " + sm.getSelectedItem(), sm.getSelectedItems().isEmpty());
// }
/*********************************************************************
* Tests from bug reports *
********************************************************************/
@Ignore @Test public void test_rt17112() {
TreeItem<String> root1 = new TreeItem<String>("Root");
root1.setExpanded(true);
addChildren(root1, "child");
for (TreeItem child : root1.getChildren()) {
addChildren(child, (String)child.getValue());
child.setExpanded(true);
}
final TreeTableView treeTableView1 = new TreeTableView();
final MultipleSelectionModel sm = treeTableView1.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
treeTableView1.setRoot(root1);
final TreeItem<String> rt17112_child1 = root1.getChildren().get(1);
final TreeItem<String> rt17112_child1_0 = rt17112_child1.getChildren().get(0);
final TreeItem<String> rt17112_child2 = root1.getChildren().get(2);
sm.getSelectedItems().addListener(new InvalidationListener() {
int count = 0;
@Override public void invalidated(Observable observable) {
if (count == 0) {
assertEquals(rt17112_child1_0, sm.getSelectedItem());
assertEquals(1, sm.getSelectedIndices().size());
assertEquals(6, sm.getSelectedIndex());
assertTrue(treeTableView1.getFocusModel().isFocused(6));
} else if (count == 1) {
assertEquals(rt17112_child1, sm.getSelectedItem());
assertFalse(sm.getSelectedItems().contains(rt17112_child2));
assertEquals(1, sm.getSelectedIndices().size());
assertTrue(treeTableView1.getFocusModel().isFocused(5));
}
count++;
}
});
// this triggers the first callback above, so that count == 0
sm.select(rt17112_child1_0);
// this triggers the second callback above, so that count == 1
rt17112_child1.setExpanded(false);
}
private void addChildren(TreeItem parent, String name) {
for (int i=0; i<3; i++) {
TreeItem<String> ti = new TreeItem<String>(name+"-"+i);
parent.getChildren().add(ti);
}
}
@Test public void test_rt17522_focusShouldMoveWhenItemAddedAtFocusIndex_1() {
installChildren();
FocusModel fm = treeTableView.getFocusModel();
fm.focus(1); // focus on child1
assertTrue(fm.isFocused(1));
assertEquals(child1, fm.getFocusedItem());
TreeItem child0 = new TreeItem("child0");
root.getChildren().add(0, child0); // 0th index == position of child1 in root
assertEquals(child1, fm.getFocusedItem());
assertTrue(fm.isFocused(2));
}
@Test public void test_rt17522_focusShouldMoveWhenItemAddedBeforeFocusIndex_1() {
installChildren();
FocusModel fm = treeTableView.getFocusModel();
fm.focus(1); // focus on child1
assertTrue(fm.isFocused(1));
TreeItem child0 = new TreeItem("child0");
root.getChildren().add(0, child0);
assertTrue("Focused index: " + fm.getFocusedIndex(), fm.isFocused(2));
}
@Test public void test_rt17522_focusShouldNotMoveWhenItemAddedAfterFocusIndex_1() {
installChildren();
FocusModel fm = treeTableView.getFocusModel();
fm.focus(1); // focus on child1
assertTrue(fm.isFocused(1));
TreeItem child4 = new TreeItem("child4");
root.getChildren().add(3, child4);
assertTrue("Focused index: " + fm.getFocusedIndex(), fm.isFocused(1));
}
@Test public void test_rt17522_focusShouldBeMovedWhenFocusedItemIsRemoved_1() {
installChildren();
FocusModel fm = treeTableView.getFocusModel();
fm.focus(1);
assertTrue(fm.isFocused(1));
root.getChildren().remove(child1);
assertEquals(0, fm.getFocusedIndex());
assertEquals(treeTableView.getTreeItem(0), fm.getFocusedItem());
}
@Test public void test_rt17522_focusShouldMoveWhenItemRemovedBeforeFocusIndex_1() {
installChildren();
FocusModel fm = treeTableView.getFocusModel();
fm.focus(2);
assertTrue(fm.isFocused(2));
root.getChildren().remove(child1);
assertTrue(fm.isFocused(1));
assertEquals(child2, fm.getFocusedItem());
}
// This test fails as, in TreeTableView FocusModel, we do not know the index of the
// removed tree items, which means we don't know whether they existed before
// or after the focused item.
// @Test public void test_rt17522_focusShouldNotMoveWhenItemRemovedAfterFocusIndex() {
// installChildren();
// FocusModel fm = treeTableView.getFocusModel();
// fm.focus(1);
// assertTrue(fm.isFocused(1));
//
// root.getChildren().remove(child3);
// assertTrue("Focused index: " + fm.getFocusedIndex(), fm.isFocused(1));
// assertEquals(child1, fm.getFocusedItem());
// }
@Test public void test_rt18385() {
installChildren();
// table.getItems().addAll("row1", "row2", "row3");
treeTableView.getSelectionModel().select(1);
treeTableView.getRoot().getChildren().add(new TreeItem("Another Row"));
assertEquals(1, treeTableView.getSelectionModel().getSelectedIndices().size());
assertEquals(1, treeTableView.getSelectionModel().getSelectedItems().size());
}
@Test public void test_rt18339_onlyEditWhenTreeTableViewIsEditable_editableIsFalse() {
TreeItem root = new TreeItem("root");
root.getChildren().setAll(
new TreeItem(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem(new Person("Emma", "Jones", "[email protected]")),
new TreeItem(new Person("Michael", "Brown", "[email protected]")));
root.setExpanded(true);
TreeTableView<Person> table = new TreeTableView<Person>(root);
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
table.setEditable(false);
table.edit(0,firstNameCol);
assertNull(table.getEditingCell());
}
@Test public void test_rt18339_onlyEditWhenTreeTableViewIsEditable_editableIsTrue() {
TreeItem root = new TreeItem("root");
root.getChildren().setAll(
new TreeItem(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem(new Person("Emma", "Jones", "[email protected]")),
new TreeItem(new Person("Michael", "Brown", "[email protected]")));
root.setExpanded(true);
TreeTableView<Person> table = new TreeTableView<Person>(root);
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
table.setEditable(true);
table.edit(0,firstNameCol);
assertEquals(root, table.getEditingCell().getTreeItem());
}
@Test public void test_rt14451() {
installChildren();
treeTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
treeTableView.getSelectionModel().selectRange(0, 2); // select from 0 (inclusive) to 2 (exclusive)
assertEquals(2, treeTableView.getSelectionModel().getSelectedIndices().size());
}
@Test public void test_rt21586() {
installChildren();
treeTableView.getSelectionModel().select(1);
assertEquals(1, treeTableView.getSelectionModel().getSelectedIndex());
assertEquals(child1, treeTableView.getSelectionModel().getSelectedItem());
TreeItem root = new TreeItem<String>("New Root");
TreeItem child1 = new TreeItem<String>("New Child 1");
TreeItem child2 = new TreeItem<String>("New Child 2");
TreeItem child3 = new TreeItem<String>("New Child 3");
root.setExpanded(true);
root.getChildren().setAll(child1, child2, child3);
treeTableView.setRoot(root);
assertEquals(-1, treeTableView.getSelectionModel().getSelectedIndex());
assertNull(treeTableView.getSelectionModel().getSelectedItem());
assertEquals(0, treeTableView.getFocusModel().getFocusedIndex());
assertEquals(root, treeTableView.getFocusModel().getFocusedItem());
}
@Test public void test_rt27181() {
myCompanyRootNode.setExpanded(true);
treeTableView.setRoot(myCompanyRootNode);
// start test
salesDepartment.setExpanded(true);
treeTableView.getSelectionModel().select(salesDepartment);
assertEquals(1, treeTableView.getFocusModel().getFocusedIndex());
itSupport.setExpanded(true);
assertEquals(1, treeTableView.getFocusModel().getFocusedIndex());
}
@Test public void test_rt27185() {
myCompanyRootNode.setExpanded(true);
treeTableView.setRoot(myCompanyRootNode);
// start test
itSupport.setExpanded(true);
treeTableView.getSelectionModel().select(mikeGraham);
assertEquals(mikeGraham, treeTableView.getFocusModel().getFocusedItem());
salesDepartment.setExpanded(true);
assertEquals(mikeGraham, treeTableView.getFocusModel().getFocusedItem());
}
@Ignore("Bug hasn't been fixed yet")
@Test public void test_rt28114() {
myCompanyRootNode.setExpanded(true);
treeTableView.setRoot(myCompanyRootNode);
// start test
itSupport.setExpanded(true);
treeTableView.getSelectionModel().select(itSupport);
assertEquals(itSupport, treeTableView.getFocusModel().getFocusedItem());
assertEquals(itSupport, treeTableView.getSelectionModel().getSelectedItem());
assertTrue(! itSupport.isLeaf());
assertTrue(itSupport.isExpanded());
itSupport.getChildren().remove(mikeGraham);
assertEquals(itSupport, treeTableView.getFocusModel().getFocusedItem());
assertEquals(itSupport, treeTableView.getSelectionModel().getSelectedItem());
assertTrue(itSupport.isLeaf());
assertTrue(!itSupport.isExpanded());
}
@Test public void test_rt27820_1() {
TreeItem root = new TreeItem("root");
root.setExpanded(true);
TreeItem child = new TreeItem("child");
root.getChildren().add(child);
treeTableView.setRoot(root);
treeTableView.getSelectionModel().select(0);
assertEquals(1, treeTableView.getSelectionModel().getSelectedItems().size());
assertEquals(root, treeTableView.getSelectionModel().getSelectedItem());
treeTableView.setRoot(null);
assertEquals(0, treeTableView.getSelectionModel().getSelectedItems().size());
assertNull(treeTableView.getSelectionModel().getSelectedItem());
}
@Test public void test_rt27820_2() {
TreeItem root = new TreeItem("root");
root.setExpanded(true);
TreeItem child = new TreeItem("child");
root.getChildren().add(child);
treeTableView.setRoot(root);
treeTableView.getSelectionModel().select(1);
assertEquals(1, treeTableView.getSelectionModel().getSelectedItems().size());
assertEquals(child, treeTableView.getSelectionModel().getSelectedItem());
treeTableView.setRoot(null);
assertEquals(0, treeTableView.getSelectionModel().getSelectedItems().size());
assertNull(treeTableView.getSelectionModel().getSelectedItem());
}
@Test public void test_rt28390() {
// There should be no NPE when a TreeTableView is shown and the disclosure
// node is null in a TreeCell
TreeItem root = new TreeItem("root");
treeTableView.setRoot(root);
// install a custom cell factory that forces the disclosure node to be
// null (because by default a null disclosure node will be replaced by
// a non-null one).
treeTableView.setRowFactory(new Callback() {
@Override public Object call(Object p) {
TreeTableRow treeCell = new TreeTableRowShim() {
{
disclosureNodeProperty().addListener((ov, t, t1) -> {
setDisclosureNode(null);
});
}
@Override public void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
setText(item == null ? "" : item.toString());
}
};
treeCell.setDisclosureNode(null);
return treeCell;
}
});
try {
Group group = new Group();
group.getChildren().setAll(treeTableView);
Scene scene = new Scene(group);
Stage stage = new Stage();
stage.setScene(scene);
stage.show();
} catch (NullPointerException e) {
System.out.println("A null disclosure node is valid, so we shouldn't have an NPE here.");
e.printStackTrace();
assertTrue(false);
}
}
@Ignore("This test begun failing when createDefaultCellImpl was removed from TreeTableViewSkin on 28/3/2013")
@Test public void test_rt28534() {
TreeItem root = new TreeItem("root");
root.getChildren().setAll(
new TreeItem(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem(new Person("Emma", "Jones", "[email protected]")),
new TreeItem(new Person("Michael", "Brown", "[email protected]")));
root.setExpanded(true);
TreeTableView<Person> table = new TreeTableView<Person>(root);
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
TreeTableColumn lastNameCol = new TreeTableColumn("Last Name");
lastNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("lastName"));
TreeTableColumn emailCol = new TreeTableColumn("Email");
emailCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("email"));
table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
VirtualFlowTestUtils.assertRowsNotEmpty(table, 0, 6); // rows 0 - 6 should be filled
VirtualFlowTestUtils.assertRowsEmpty(table, 6, -1); // rows 6+ should be empty
// now we replace the data and expect the cells that have no data
// to be empty
root.getChildren().setAll(
new TreeItem(new Person("*_*Emma", "Jones", "[email protected]")),
new TreeItem(new Person("_Michael", "Brown", "[email protected]")));
VirtualFlowTestUtils.assertRowsNotEmpty(table, 0, 3); // rows 0 - 3 should be filled
VirtualFlowTestUtils.assertRowsEmpty(table, 3, -1); // rows 3+ should be empty
}
@Test public void test_rt22463() {
final TreeTableView<RT_22463_Person> table = new TreeTableView<RT_22463_Person>();
table.setTableMenuButtonVisible(true);
TreeTableColumn c1 = new TreeTableColumn("Id");
TreeTableColumn c2 = new TreeTableColumn("Name");
c1.setCellValueFactory(new TreeItemPropertyValueFactory<Person, Long>("id"));
c2.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("name"));
table.getColumns().addAll(c1, c2);
RT_22463_Person rootPerson = new RT_22463_Person();
rootPerson.setName("Root");
TreeItem<RT_22463_Person> root = new TreeItem<RT_22463_Person>(rootPerson);
root.setExpanded(true);
table.setRoot(root);
// before the change things display fine
RT_22463_Person p1 = new RT_22463_Person();
p1.setId(1l);
p1.setName("name1");
RT_22463_Person p2 = new RT_22463_Person();
p2.setId(2l);
p2.setName("name2");
root.getChildren().addAll(
new TreeItem<RT_22463_Person>(p1),
new TreeItem<RT_22463_Person>(p2));
VirtualFlowTestUtils.assertCellTextEquals(table, 1, "1", "name1");
VirtualFlowTestUtils.assertCellTextEquals(table, 2, "2", "name2");
// now we change the persons but they are still equal as the ID's don't
// change - but the items list is cleared so the cells should update
RT_22463_Person new_p1 = new RT_22463_Person();
new_p1.setId(1l);
new_p1.setName("updated name1");
RT_22463_Person new_p2 = new RT_22463_Person();
new_p2.setId(2l);
new_p2.setName("updated name2");
root.getChildren().clear();
root.getChildren().setAll(
new TreeItem<RT_22463_Person>(new_p1),
new TreeItem<RT_22463_Person>(new_p2));
VirtualFlowTestUtils.assertCellTextEquals(table, 1, "1", "updated name1");
VirtualFlowTestUtils.assertCellTextEquals(table, 2, "2", "updated name2");
}
@Test public void test_rt28637() {
TreeItem<String> s1, s2, s3, s4;
ObservableList<TreeItem<String>> items = FXCollections.observableArrayList(
s1 = new TreeItem<String>("String1"),
s2 = new TreeItem<String>("String2"),
s3 = new TreeItem<String>("String3"),
s4 = new TreeItem<String>("String4"));
final TreeTableView<String> treeTableView = new TreeTableView<String>();
TreeItem<String> root = new TreeItem<String>("Root");
root.setExpanded(true);
treeTableView.setRoot(root);
treeTableView.setShowRoot(false);
root.getChildren().addAll(items);
treeTableView.getSelectionModel().select(0);
assertEquals((Object)s1, treeTableView.getSelectionModel().getSelectedItem());
assertEquals((Object)s1, treeTableView.getSelectionModel().getSelectedItems().get(0));
assertEquals(0, treeTableView.getSelectionModel().getSelectedIndex());
root.getChildren().remove(treeTableView.getSelectionModel().getSelectedItem());
assertEquals((Object)s2, treeTableView.getSelectionModel().getSelectedItem());
assertEquals((Object)s2, treeTableView.getSelectionModel().getSelectedItems().get(0));
assertEquals(0, treeTableView.getSelectionModel().getSelectedIndex());
}
@Test public void test_rt24844() {
// p1 == lowest first name
TreeItem<Person> p0, p1, p2, p3, p4;
ObservableList<TreeItem<Person>> persons = FXCollections.observableArrayList(
p3 = new TreeItem<Person>(new Person("Jacob", "Smith", "[email protected]")),
p2 = new TreeItem<Person>(new Person("Isabella", "Johnson", "[email protected]")),
p1 = new TreeItem<Person>(new Person("Ethan", "Williams", "[email protected]")),
p0 = new TreeItem<Person>(new Person("Emma", "Jones", "[email protected]")),
p4 = new TreeItem<Person>(new Person("Michael", "Brown", "[email protected]")));
TreeTableView<Person> table = new TreeTableView<>();
TreeItem<Person> root = new TreeItem<Person>(new Person("Root", null, null));
root.setExpanded(true);
table.setRoot(root);
table.setShowRoot(false);
root.getChildren().setAll(persons);
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
// set dummy comparator to lock items in place until new comparator is set
firstNameCol.setComparator((t, t1) -> 0);
table.getColumns().addAll(firstNameCol);
table.getSortOrder().add(firstNameCol);
// ensure the existing order is as expected
assertEquals(p3, root.getChildren().get(0));
assertEquals(p2, root.getChildren().get(1));
assertEquals(p1, root.getChildren().get(2));
assertEquals(p0, root.getChildren().get(3));
assertEquals(p4, root.getChildren().get(4));
// set a new comparator
firstNameCol.setComparator((t, t1) -> t.toString().compareTo(t1.toString()));
// ensure the new order is as expected
assertEquals(p0, root.getChildren().get(0));
assertEquals(p1, root.getChildren().get(1));
assertEquals(p2, root.getChildren().get(2));
assertEquals(p3, root.getChildren().get(3));
assertEquals(p4, root.getChildren().get(4));
}
@Test public void test_rt29331() {
TreeTableView<Person> table = new TreeTableView<Person>();
// p1 == lowest first name
TreeItem<Person> p0, p1, p2, p3, p4;
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
TreeTableColumn lastNameCol = new TreeTableColumn("Last Name");
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
TreeTableColumn emailCol = new TreeTableColumn("Email");
emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>("email"));
TreeTableColumn parentColumn = new TreeTableColumn<>("Parent");
parentColumn.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
table.getColumns().addAll(parentColumn);
// table is setup, now hide the 'last name' column
emailCol.setVisible(false);
assertFalse(emailCol.isVisible());
// reorder columns inside the parent column
parentColumn.getColumns().setAll(emailCol, firstNameCol, lastNameCol);
// the email column should not become visible after this, but it does
assertFalse(emailCol.isVisible());
}
private int rt29330_count = 0;
@Test public void test_rt29330_1() {
ObservableList<TreeItem<Person>> persons = FXCollections.observableArrayList(
new TreeItem<Person>(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem<Person>(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem<Person>(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem<Person>(new Person("Emma", "Jones", "[email protected]")),
new TreeItem<Person>(new Person("Michael", "Brown", "[email protected]")));
TreeTableView<Person> table = new TreeTableView<>();
TreeItem<Person> root = new TreeItem<Person>(new Person("Root", null, null));
root.setExpanded(true);
table.setRoot(root);
table.setShowRoot(false);
root.getChildren().setAll(persons);
TreeTableColumn parentColumn = new TreeTableColumn<>("Parent");
table.getColumns().addAll(parentColumn);
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
TreeTableColumn lastNameCol = new TreeTableColumn("Last Name");
lastNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("lastName"));
parentColumn.getColumns().addAll(firstNameCol, lastNameCol);
table.setOnSort(event -> {
rt29330_count++;
});
// test preconditions
assertEquals(ASCENDING, lastNameCol.getSortType());
assertEquals(0, rt29330_count);
table.getSortOrder().add(lastNameCol);
assertEquals(1, rt29330_count);
lastNameCol.setSortType(DESCENDING);
assertEquals(2, rt29330_count);
lastNameCol.setSortType(null);
assertEquals(3, rt29330_count);
lastNameCol.setSortType(ASCENDING);
assertEquals(4, rt29330_count);
}
@Test public void test_rt29330_2() {
ObservableList<TreeItem<Person>> persons = FXCollections.observableArrayList(
new TreeItem<Person>(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem<Person>(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem<Person>(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem<Person>(new Person("Emma", "Jones", "[email protected]")),
new TreeItem<Person>(new Person("Michael", "Brown", "[email protected]")));
TreeTableView<Person> table = new TreeTableView<>();
TreeItem<Person> root = new TreeItem<Person>(new Person("Root", null, null));
root.setExpanded(true);
table.setRoot(root);
table.setShowRoot(false);
root.getChildren().setAll(persons);
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
TreeTableColumn lastNameCol = new TreeTableColumn("Last Name");
lastNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("lastName"));
// this test differs from the previous one by installing the parent column
// into the tableview after it has the children added into it
TreeTableColumn parentColumn = new TreeTableColumn<>("Parent");
parentColumn.getColumns().addAll(firstNameCol, lastNameCol);
table.getColumns().addAll(parentColumn);
table.setOnSort(event -> {
rt29330_count++;
});
// test preconditions
assertEquals(ASCENDING, lastNameCol.getSortType());
assertEquals(0, rt29330_count);
table.getSortOrder().add(lastNameCol);
assertEquals(1, rt29330_count);
lastNameCol.setSortType(DESCENDING);
assertEquals(2, rt29330_count);
lastNameCol.setSortType(null);
assertEquals(3, rt29330_count);
lastNameCol.setSortType(ASCENDING);
assertEquals(4, rt29330_count);
}
@Test public void test_rt29313_selectedIndices() {
ObservableList<TreeItem<Person>> persons = FXCollections.observableArrayList(
new TreeItem<Person>(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem<Person>(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem<Person>(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem<Person>(new Person("Emma", "Jones", "[email protected]")),
new TreeItem<Person>(new Person("Michael", "Brown", "[email protected]")));
TreeTableView<Person> table = new TreeTableView<>();
TreeItem<Person> root = new TreeItem<Person>(new Person("Root", null, null));
root.setExpanded(true);
table.setRoot(root);
table.setShowRoot(false);
root.getChildren().setAll(persons);
TableSelectionModel sm = table.getSelectionModel();
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
TreeTableColumn lastNameCol = new TreeTableColumn("Last Name");
lastNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("lastName"));
TreeTableColumn emailCol = new TreeTableColumn("Email");
emailCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("email"));
table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
sm.setCellSelectionEnabled(true);
sm.setSelectionMode(SelectionMode.MULTIPLE);
assertTrue(sm.getSelectedIndices().isEmpty());
// only (0,0) should be selected, so selected indices should be [0]
sm.select(0, firstNameCol);
assertEquals(1, sm.getSelectedIndices().size());
// now (0,0) and (1,0) should be selected, so selected indices should be [0, 1]
sm.select(1, firstNameCol);
assertEquals(2, sm.getSelectedIndices().size());
// now (0,0), (1,0) and (1,1) should be selected, but selected indices
// should remain as [0, 1], as we don't want selected indices to become
// [0,1,1] (which is what RT-29313 is about)
sm.select(1, lastNameCol);
assertEquals(2, sm.getSelectedIndices().size());
assertEquals(0, sm.getSelectedIndices().get(0));
assertEquals(1, sm.getSelectedIndices().get(1));
}
@Test public void test_rt29313_selectedItems() {
TreeItem<Person> p0, p1;
ObservableList<TreeItem<Person>> persons = FXCollections.observableArrayList(
p0 = new TreeItem<Person>(new Person("Jacob", "Smith", "[email protected]")),
p1 = new TreeItem<Person>(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem<Person>(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem<Person>(new Person("Emma", "Jones", "[email protected]")),
new TreeItem<Person>(new Person("Michael", "Brown", "[email protected]")));
TreeTableView<Person> table = new TreeTableView<>();
TreeItem<Person> root = new TreeItem<Person>(new Person("Root", null, null));
root.setExpanded(true);
table.setRoot(root);
table.setShowRoot(false);
root.getChildren().setAll(persons);
TableSelectionModel sm = table.getSelectionModel();
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
TreeTableColumn lastNameCol = new TreeTableColumn("Last Name");
lastNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("lastName"));
TreeTableColumn emailCol = new TreeTableColumn("Email");
emailCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("email"));
table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
sm.setCellSelectionEnabled(true);
sm.setSelectionMode(SelectionMode.MULTIPLE);
assertTrue(sm.getSelectedItems().isEmpty());
// only (0,0) should be selected, so selected items should be [p0]
sm.select(0, firstNameCol);
assertEquals(1, sm.getSelectedItems().size());
// now (0,0) and (1,0) should be selected, so selected items should be [p0, p1]
sm.select(1, firstNameCol);
assertEquals(2, sm.getSelectedItems().size());
// now (0,0), (1,0) and (1,1) should be selected, but selected items
// should remain as [p0, p1], as we don't want selected items to become
// [p0,p1,p1] (which is what RT-29313 is about)
sm.select(1, lastNameCol);
assertEquals(2, sm.getSelectedItems().size());
assertEquals(p0, sm.getSelectedItems().get(0));
assertEquals(p1, sm.getSelectedItems().get(1));
}
@Test public void test_rt29566() {
ObservableList<TreeItem<Person>> persons = FXCollections.observableArrayList(
new TreeItem<Person>(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem<Person>(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem<Person>(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem<Person>(new Person("Emma", "Jones", "[email protected]")),
new TreeItem<Person>(new Person("Michael", "Brown", "[email protected]")));
TreeTableView<Person> table = new TreeTableView<>();
TreeItem<Person> root = new TreeItem<Person>(new Person("Root", null, null));
root.setExpanded(true);
table.setRoot(root);
table.setShowRoot(false);
root.getChildren().setAll(persons);
TableSelectionModel sm = table.getSelectionModel();
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
TreeTableColumn lastNameCol = new TreeTableColumn("Last Name");
lastNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("lastName"));
TreeTableColumn emailCol = new TreeTableColumn("Email");
emailCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("email"));
table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
// test the state before we hide and re-add a column
VirtualFlowTestUtils.assertCellTextEquals(table, 0, "Jacob", "Smith", "[email protected]");
VirtualFlowTestUtils.assertCellTextEquals(table, 1, "Isabella", "Johnson", "[email protected]");
VirtualFlowTestUtils.assertCellTextEquals(table, 2, "Ethan", "Williams", "[email protected]");
VirtualFlowTestUtils.assertCellTextEquals(table, 3, "Emma", "Jones", "[email protected]");
VirtualFlowTestUtils.assertCellTextEquals(table, 4, "Michael", "Brown", "[email protected]");
// hide the last name column, and test cells again
table.getColumns().remove(lastNameCol);
VirtualFlowTestUtils.assertCellTextEquals(table, 0, "Jacob", "[email protected]");
VirtualFlowTestUtils.assertCellTextEquals(table, 1, "Isabella", "[email protected]");
VirtualFlowTestUtils.assertCellTextEquals(table, 2, "Ethan", "[email protected]");
VirtualFlowTestUtils.assertCellTextEquals(table, 3, "Emma", "[email protected]");
VirtualFlowTestUtils.assertCellTextEquals(table, 4, "Michael", "[email protected]");
// re-add the last name column - we should go back to the original state.
// However, what appears to be happening is that, for some reason, some
// of the cells from the removed column do not reappear - meaning in this case
// some of the last name values will not be where we expect them to be.
// This is clearly not ideal!
table.getColumns().add(1, lastNameCol);
VirtualFlowTestUtils.assertCellTextEquals(table, 0, "Jacob", "Smith", "[email protected]");
VirtualFlowTestUtils.assertCellTextEquals(table, 1, "Isabella", "Johnson", "[email protected]");
VirtualFlowTestUtils.assertCellTextEquals(table, 2, "Ethan", "Williams", "[email protected]");
VirtualFlowTestUtils.assertCellTextEquals(table, 3, "Emma", "Jones", "[email protected]");
VirtualFlowTestUtils.assertCellTextEquals(table, 4, "Michael", "Brown", "[email protected]");
}
@Test public void test_rt29390() {
ObservableList<TreeItem<Person>> persons = FXCollections.observableArrayList(
new TreeItem<Person>(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem<Person>(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem<Person>(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem<Person>(new Person("Emma", "Jones", "[email protected]")),
new TreeItem<Person>(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem<Person>(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem<Person>(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem<Person>(new Person("Emma", "Jones", "[email protected]")),
new TreeItem<Person>(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem<Person>(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem<Person>(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem<Person>(new Person("Emma", "Jones", "[email protected]")),
new TreeItem<Person>(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem<Person>(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem<Person>(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem<Person>(new Person("Emma", "Jones", "[email protected]")
));
TreeTableView<Person> table = new TreeTableView<>();
table.setMaxHeight(50);
table.setPrefHeight(50);
TreeItem<Person> root = new TreeItem<Person>(new Person("Root", null, null));
root.setExpanded(true);
table.setRoot(root);
table.setShowRoot(false);
root.getChildren().setAll(persons);
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
table.getColumns().add(firstNameCol);
Toolkit.getToolkit().firePulse();
// we want the vertical scrollbar
VirtualScrollBar scrollBar = VirtualFlowTestUtils.getVirtualFlowVerticalScrollbar(table);
assertNotNull(scrollBar);
assertTrue(scrollBar.isVisible());
assertTrue(scrollBar.getVisibleAmount() > 0.0);
assertTrue(scrollBar.getVisibleAmount() < 1.0);
// this next test is likely to be brittle, but we'll see...If it is the
// cause of failure then it can be commented out
assertEquals(0.0625, scrollBar.getVisibleAmount(), 0.0);
}
@Test public void test_rt29676_withText() {
// set up test
TreeTableView<Data> treeTableView = new TreeTableView<Data>();
treeTableView.setMaxWidth(100);
TreeItem<Data> root = new TreeItem<Data>(new Data("Root"));
treeTableView.setRoot(root);
addLevel(root, 0, 30);
treeTableView.getRoot().setExpanded(true);
TreeTableColumn<Data, String> column = new TreeTableColumn<Data, String>("Items' name");
column.setCellValueFactory(p -> new ReadOnlyStringWrapper(p.getValue().getValue().getData()));
treeTableView.getColumns().add(column);
// show treeTableView
StageLoader sl = new StageLoader(treeTableView);
// expand all collapsed branches
root.setExpanded(true);
for (int i = 0; i < root.getChildren().size(); i++) {
TreeItem<Data> child = root.getChildren().get(i);
child.setExpanded(true);
}
// get all cells and ensure their content is as expected
int cellCount = VirtualFlowTestUtils.getCellCount(treeTableView);
for (int i = 0; i < cellCount; i++) {
// get the TreeTableRow
final TreeTableRow rowCell = (TreeTableRow) VirtualFlowTestUtils.getCell(treeTableView, i);
final TreeItem treeItem = rowCell.getTreeItem();
if (treeItem == null) continue;
final boolean isBranch = ! treeItem.isLeaf();
// then check its children
List<Node> children = rowCell.getChildrenUnmodifiable();
for (int j = 0; j < children.size(); j++) {
final Node child = children.get(j);
assertTrue(child.isVisible());
assertNotNull(child.getParent());
assertNotNull(child.getScene());
if (child.getStyleClass().contains("tree-disclosure-node")) {
// no-op
}
if (child.getStyleClass().contains("tree-table-cell")) {
TreeTableCell cell = (TreeTableCell) child;
assertNotNull(cell.getText());
assertFalse(cell.getText().isEmpty());
}
}
}
sl.dispose();
}
private void addLevel(TreeItem<Data> item, int level, int length) {
for (int i = 0; i < 3; i++) {
StringBuilder builder = new StringBuilder();
builder.append("Level " + level + " Item " + item);
if (length > 0) {
builder.append(" l");
for (int j = 0; j < length; j++) {
builder.append("o");
}
builder.append("ng");
}
String itemString = builder.toString();
TreeItem<Data> child = new TreeItem<Data>(new Data(itemString));
if (level < 3 - 1) {
addLevel(child, level + 1, length);
}
item.getChildren().add(child);
}
}
@Test public void test_rt27180_collapseBranch_childSelected_singleSelection() {
sm.setCellSelectionEnabled(false);
sm.setSelectionMode(SelectionMode.SINGLE);
treeTableView.setRoot(myCompanyRootNode);
myCompanyRootNode.setExpanded(true);
salesDepartment.setExpanded(true);
itSupport.setExpanded(true);
sm.select(2); // ethanWilliams
assertFalse(sm.isSelected(1)); // salesDepartment
assertTrue(sm.isSelected(2)); // ethanWilliams
assertTrue(treeTableView.getFocusModel().isFocused(2));
assertEquals(1, sm.getSelectedCells().size());
// now collapse the salesDepartment, selection should
// not jump down to the itSupport people
salesDepartment.setExpanded(false);
assertTrue(sm.getSelectedIndices().toString(), sm.isSelected(1)); // salesDepartment
assertTrue(treeTableView.getFocusModel().isFocused(1));
assertEquals(1, sm.getSelectedCells().size());
}
@Test public void test_rt27180_collapseBranch_laterSiblingSelected_singleSelection() {
sm.setCellSelectionEnabled(false);
sm.setSelectionMode(SelectionMode.SINGLE);
treeTableView.setRoot(myCompanyRootNode);
myCompanyRootNode.setExpanded(true);
salesDepartment.setExpanded(true);
itSupport.setExpanded(true);
sm.select(8); // itSupport
assertFalse(sm.isSelected(1)); // salesDepartment
assertTrue(sm.isSelected(8)); // itSupport
assertTrue(treeTableView.getFocusModel().isFocused(8));
assertEquals(1, sm.getSelectedIndices().size());
salesDepartment.setExpanded(false);
assertTrue(debug(), sm.isSelected(2)); // itSupport
assertTrue(treeTableView.getFocusModel().isFocused(2));
assertEquals(1, sm.getSelectedIndices().size());
}
@Test public void test_rt27180_collapseBranch_laterSiblingAndChildrenSelected() {
sm.setSelectionMode(SelectionMode.MULTIPLE);
sm.setCellSelectionEnabled(false);
treeTableView.setRoot(myCompanyRootNode);
myCompanyRootNode.setExpanded(true);
salesDepartment.setExpanded(true);
itSupport.setExpanded(true);
sm.clearSelection();
sm.selectIndices(8, 9, 10); // itSupport, and two people
assertFalse(sm.isSelected(1)); // salesDepartment
assertTrue(sm.isSelected(8)); // itSupport
assertTrue(sm.isSelected(9)); // mikeGraham
assertTrue(sm.isSelected(10)); // judyMayer
assertTrue(treeTableView.getFocusModel().isFocused(10));
assertEquals(debug(), 3, sm.getSelectedIndices().size());
salesDepartment.setExpanded(false);
assertTrue(debug(), sm.isSelected(2)); // itSupport
assertTrue(sm.isSelected(3)); // mikeGraham
assertTrue(sm.isSelected(4)); // judyMayer
assertTrue(treeTableView.getFocusModel().isFocused(4));
assertEquals(3, sm.getSelectedIndices().size());
}
@Test public void test_rt27180_expandBranch_laterSiblingSelected_singleSelection() {
sm.setCellSelectionEnabled(false);
sm.setSelectionMode(SelectionMode.SINGLE);
treeTableView.setRoot(myCompanyRootNode);
myCompanyRootNode.setExpanded(true);
salesDepartment.setExpanded(false);
itSupport.setExpanded(true);
sm.select(2); // itSupport
assertFalse(sm.isSelected(1)); // salesDepartment
assertTrue(sm.isSelected(2)); // itSupport
assertTrue(treeTableView.getFocusModel().isFocused(2));
assertEquals(1, sm.getSelectedIndices().size());
salesDepartment.setExpanded(true);
assertTrue(debug(), sm.isSelected(8)); // itSupport
assertTrue(treeTableView.getFocusModel().isFocused(8));
assertEquals(1, sm.getSelectedIndices().size());
}
@Test public void test_rt27180_expandBranch_laterSiblingAndChildrenSelected() {
sm.setSelectionMode(SelectionMode.MULTIPLE);
sm.setCellSelectionEnabled(false);
treeTableView.setRoot(myCompanyRootNode);
myCompanyRootNode.setExpanded(true);
salesDepartment.setExpanded(false);
itSupport.setExpanded(true);
sm.clearSelection();
sm.selectIndices(2,3,4); // itSupport, and two people
assertFalse(sm.isSelected(1)); // salesDepartment
assertTrue(sm.isSelected(2)); // itSupport
assertTrue(sm.isSelected(3)); // mikeGraham
assertTrue(sm.isSelected(4)); // judyMayer
assertTrue(treeTableView.getFocusModel().isFocused(4));
assertEquals(3, sm.getSelectedIndices().size());
salesDepartment.setExpanded(true);
assertTrue(debug(), sm.isSelected(8)); // itSupport
assertTrue(sm.isSelected(9)); // mikeGraham
assertTrue(sm.isSelected(10)); // judyMayer
assertTrue(treeTableView.getFocusModel().isFocused(10));
assertEquals(3, sm.getSelectedIndices().size());
}
@Test public void test_rt30400() {
// create a treetableview that'll render cells using the check box cell factory
TreeItem<String> rootItem = new TreeItem<>("root");
final TreeTableView<String> tableView = new TreeTableView<String>(rootItem);
tableView.setMinHeight(100);
tableView.setPrefHeight(100);
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
firstNameCol.setCellFactory(CheckBoxTreeTableCell.forTreeTableColumn(param -> new ReadOnlyBooleanWrapper(true)));
tableView.getColumns().add(firstNameCol);
// because only the first row has data, all other rows should be
// empty (and not contain check boxes - we just check the first four here)
VirtualFlowTestUtils.assertRowsNotEmpty(tableView, 0, 1);
VirtualFlowTestUtils.assertCellNotEmpty(VirtualFlowTestUtils.getCell(tableView, 0));
VirtualFlowTestUtils.assertCellEmpty(VirtualFlowTestUtils.getCell(tableView, 1));
VirtualFlowTestUtils.assertCellEmpty(VirtualFlowTestUtils.getCell(tableView, 2));
VirtualFlowTestUtils.assertCellEmpty(VirtualFlowTestUtils.getCell(tableView, 3));
}
@Ignore("This bug is not yet fixed")
@Test public void test_rt31165() {
installChildren();
treeTableView.setEditable(true);
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(param -> new ReadOnlyStringWrapper("TEST"));
firstNameCol.setCellFactory(TextFieldTreeTableCell.forTreeTableColumn());
firstNameCol.setEditable(true);
treeTableView.getColumns().add(firstNameCol);
IndexedCell cell = VirtualFlowTestUtils.getCell(treeTableView, 1, 0);
assertEquals("TEST", cell.getText());
assertFalse(cell.isEditing());
treeTableView.edit(1, firstNameCol);
assertEquals(child1, treeTableView.getEditingCell().getTreeItem());
assertTrue(cell.isEditing());
VirtualFlowTestUtils.getVirtualFlow(treeTableView).requestLayout();
Toolkit.getToolkit().firePulse();
assertEquals(child1, treeTableView.getEditingCell().getTreeItem());
assertTrue(cell.isEditing());
}
@Test public void test_rt31404() {
installChildren();
TreeTableColumn<String,String> firstNameCol = new TreeTableColumn<>("First Name");
firstNameCol.setCellValueFactory(param -> new ReadOnlyStringWrapper(param.getValue().getValue()));
treeTableView.getColumns().add(firstNameCol);
IndexedCell cell = VirtualFlowTestUtils.getCell(treeTableView, 0, 0);
assertEquals("Root", cell.getText());
treeTableView.setShowRoot(false);
assertEquals("Child 1", cell.getText());
}
@Test public void test_rt31471() {
installChildren();
TreeTableColumn<String,String> firstNameCol = new TreeTableColumn<>("First Name");
firstNameCol.setCellValueFactory(param -> new ReadOnlyStringWrapper(param.getValue().getValue()));
treeTableView.getColumns().add(firstNameCol);
IndexedCell cell = VirtualFlowTestUtils.getCell(treeTableView, 0);
assertEquals("Root", cell.getItem());
treeTableView.setFixedCellSize(50);
VirtualFlowTestUtils.getVirtualFlow(treeTableView).requestLayout();
Toolkit.getToolkit().firePulse();
assertEquals("Root", cell.getItem());
assertEquals(50, cell.getHeight(), 0.00);
}
@Test public void test_rt30466() {
final Node graphic1 = new Circle(6.75, Color.RED);
final Node graphic2 = new Circle(6.75, Color.GREEN);
installChildren();
TreeTableColumn<String,String> firstNameCol = new TreeTableColumn<>("First Name");
firstNameCol.setCellValueFactory(param -> new ReadOnlyStringWrapper(param.getValue().getValue()));
treeTableView.getColumns().add(firstNameCol);
TreeTableRow cell = (TreeTableRow) VirtualFlowTestUtils.getCell(treeTableView, 0);
assertEquals("Root", cell.getItem());
// set the first graphic - which we expect to see as a child of the cell
root.setGraphic(graphic1);
cell = (TreeTableRow) VirtualFlowTestUtils.getCell(treeTableView, 0);
boolean matchGraphic1 = false;
boolean matchGraphic2 = false;
for (Node n : cell.getChildrenUnmodifiable()) {
if (n == graphic1) {
matchGraphic1 = true;
}
if (n == graphic2) {
matchGraphic2 = true;
}
}
assertTrue(matchGraphic1);
assertFalse(matchGraphic2);
// set the second graphic - which we also expect to see - but of course graphic1 should not be a child any longer
root.setGraphic(graphic2);
cell = (TreeTableRow) VirtualFlowTestUtils.getCell(treeTableView, 0);
matchGraphic1 = false;
matchGraphic2 = false;
for (Node n : cell.getChildrenUnmodifiable()) {
if (n == graphic1) {
matchGraphic1 = true;
}
if (n == graphic2) {
matchGraphic2 = true;
}
}
assertFalse(matchGraphic1);
assertTrue(matchGraphic2);
}
private int rt_31200_count = 0;
@Test public void test_rt_31200_tableCell() {
rt_31200_count = 0;
installChildren();
TreeTableColumn<String,String> firstNameCol = new TreeTableColumn<>("First Name");
firstNameCol.setCellValueFactory(param -> new ReadOnlyStringWrapper(param.getValue().getValue()));
treeTableView.getColumns().add(firstNameCol);
firstNameCol.setCellFactory(new Callback<TreeTableColumn<String, String>, TreeTableCell<String, String>>() {
@Override
public TreeTableCell<String, String> call(TreeTableColumn<String, String> param) {
return new TreeTableCellShim<String, String>() {
ImageView view = new ImageView();
{
setGraphic(view);
}
;
@Override
public void updateItem(String item, boolean empty) {
if (getItem() == null ? item == null : getItem().equals(item)) {
rt_31200_count++;
}
super.updateItem(item, empty);
if (item == null || empty) {
view.setImage(null);
setText(null);
} else {
setText(item);
}
}
};
}
});
StageLoader sl = new StageLoader(treeTableView);
assertEquals(12, rt_31200_count);
// resize the stage
sl.getStage().setHeight(250);
Toolkit.getToolkit().firePulse();
sl.getStage().setHeight(50);
Toolkit.getToolkit().firePulse();
assertEquals(12, rt_31200_count);
sl.dispose();
}
@Test public void test_rt_31200_tableRow() {
rt_31200_count = 0;
installChildren();
TreeTableColumn<String,String> firstNameCol = new TreeTableColumn<>("First Name");
firstNameCol.setCellValueFactory(param -> new ReadOnlyStringWrapper(param.getValue().getValue()));
treeTableView.getColumns().add(firstNameCol);
treeTableView.setRowFactory(new Callback<TreeTableView<String>, TreeTableRow<String>>() {
@Override
public TreeTableRow<String> call(TreeTableView<String> param) {
return new TreeTableRowShim<String>() {
ImageView view = new ImageView();
{
setGraphic(view);
}
;
@Override
public void updateItem(String item, boolean empty) {
if (getItem() == null ? item == null : getItem().equals(item)) {
rt_31200_count++;
}
super.updateItem(item, empty);
if (item == null || empty) {
view.setImage(null);
setText(null);
} else {
setText(item.toString());
}
}
};
}
});
StageLoader sl = new StageLoader(treeTableView);
assertEquals(21, rt_31200_count);
// resize the stage
sl.getStage().setHeight(250);
Toolkit.getToolkit().firePulse();
sl.getStage().setHeight(50);
Toolkit.getToolkit().firePulse();
assertEquals(21, rt_31200_count);
sl.dispose();
}
@Test public void test_rt_31727() {
installChildren();
treeTableView.setEditable(true);
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(param -> new ReadOnlyStringWrapper("TEST"));
firstNameCol.setCellFactory(TextFieldTreeTableCell.forTreeTableColumn());
firstNameCol.setEditable(true);
treeTableView.getColumns().add(firstNameCol);
treeTableView.setEditable(true);
firstNameCol.setEditable(true);
// do a normal edit
treeTableView.edit(0, firstNameCol);
TreeTablePosition editingCell = treeTableView.getEditingCell();
assertNotNull(editingCell);
assertEquals(0, editingCell.getRow());
assertEquals(0, editingCell.getColumn());
assertEquals(firstNameCol, editingCell.getTableColumn());
assertEquals(treeTableView, editingCell.getTreeTableView());
// cancel editing
treeTableView.edit(-1, null);
editingCell = treeTableView.getEditingCell();
assertNull(editingCell);
}
@Test public void test_rt_21517() {
installChildren();
// final TableSelectionModel sm = t.getSelectionModel();
TreeTableColumn<String, String> col = new TreeTableColumn<String, String>("column");
col.setSortType(ASCENDING);
col.setCellValueFactory(param -> new ReadOnlyObjectWrapper<String>(param.getValue().getValue()));
treeTableView.getColumns().add(col);
// test pre-conditions
assertEquals(0, sm.getSelectedCells().size());
assertEquals(0, sm.getSelectedItems().size());
assertEquals(0, sm.getSelectedIndices().size());
// select the 4th row (that is, the third child of the root)
sm.select(3);
assertTrue(sm.isSelected(3));
assertEquals(3, sm.getSelectedIndex());
assertEquals(1, sm.getSelectedIndices().size());
assertTrue(sm.getSelectedIndices().contains(3));
assertEquals(child3, sm.getSelectedItem());
assertEquals(1, sm.getSelectedItems().size());
assertTrue(sm.getSelectedItems().contains(child3));
// we also want to test visually
TreeTableRow rootRow = (TreeTableRow) VirtualFlowTestUtils.getCell(treeTableView, 0);
assertFalse(rootRow.isSelected());
TreeTableRow child3Row = (TreeTableRow) VirtualFlowTestUtils.getCell(treeTableView, 3);
assertTrue(child3Row.isSelected());
// sort tableview by firstname column in ascending (default) order
// (so aaa continues to come first)
treeTableView.getSortOrder().add(col);
// nothing should have changed
assertTrue(sm.isSelected(3));
assertEquals(3, sm.getSelectedIndex());
assertEquals(1, sm.getSelectedIndices().size());
assertTrue(sm.getSelectedIndices().contains(3));
assertEquals(child3, sm.getSelectedItem());
assertEquals(1, sm.getSelectedItems().size());
assertTrue(sm.getSelectedItems().contains(child3));
rootRow = (TreeTableRow) VirtualFlowTestUtils.getCell(treeTableView, 0);
assertFalse(rootRow.isSelected());
child3Row = (TreeTableRow) VirtualFlowTestUtils.getCell(treeTableView, 3);
assertTrue(child3Row.isSelected());
// continue to sort tableview by firstname column, but now in descending
// order, (so ccc to come first)
col.setSortType(TreeTableColumn.SortType.DESCENDING);
// now test to ensure that CCC is still the only selected item, but now
// located in index 1 (as the first child of the root)
assertTrue(debug(), sm.isSelected(1));
assertEquals(1, sm.getSelectedIndex());
assertEquals(1, sm.getSelectedIndices().size());
assertTrue(sm.getSelectedIndices().contains(1));
assertEquals(child3, sm.getSelectedItem());
assertEquals(1, sm.getSelectedItems().size());
assertTrue(sm.getSelectedItems().contains(child3));
// we also want to test visually
rootRow = (TreeTableRow) VirtualFlowTestUtils.getCell(treeTableView, 0);
assertFalse(rootRow.isSelected());
child3Row = (TreeTableRow) VirtualFlowTestUtils.getCell(treeTableView, 1);
assertTrue(child3Row.isSelected());
}
@Test public void test_rt_30484_treeTableCell() {
installChildren();
TreeTableColumn<String, String> col = new TreeTableColumn<String, String>("column");
col.setSortType(ASCENDING);
col.setCellValueFactory(param -> new ReadOnlyObjectWrapper<String>(param.getValue().getValue()));
treeTableView.getColumns().add(col);
col.setCellFactory(new Callback<TreeTableColumn<String, String>, TreeTableCell<String, String>>() {
@Override
public TreeTableCell<String, String> call(TreeTableColumn<String, String> param) {
return new TreeTableCellShim<String, String>() {
Rectangle graphic = new Rectangle(10, 10, Color.RED);
{ setGraphic(graphic); };
@Override public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
graphic.setVisible(false);
setText(null);
} else {
graphic.setVisible(true);
setText(item);
}
}
};
}
});
// First four rows have content, so the graphic should show.
// All other rows have no content, so graphic should not show.
VirtualFlowTestUtils.assertGraphicIsVisible(treeTableView, 0, 0);
VirtualFlowTestUtils.assertGraphicIsVisible(treeTableView, 1, 0);
VirtualFlowTestUtils.assertGraphicIsVisible(treeTableView, 2, 0);
VirtualFlowTestUtils.assertGraphicIsVisible(treeTableView, 3, 0);
VirtualFlowTestUtils.assertGraphicIsNotVisible(treeTableView, 4, 0);
VirtualFlowTestUtils.assertGraphicIsNotVisible(treeTableView, 5, 0);
}
@Test public void test_rt_30484_treeTableRow() {
installChildren();
TreeTableColumn<String, String> col = new TreeTableColumn<String, String>("column");
col.setSortType(ASCENDING);
col.setCellValueFactory(param -> new ReadOnlyObjectWrapper<String>(param.getValue().getValue()));
treeTableView.getColumns().add(col);
treeTableView.setRowFactory(new Callback<TreeTableView<String>, TreeTableRow<String>>() {
@Override public TreeTableRow<String> call(TreeTableView<String> param) {
return new TreeTableRowShim<String>() {
Rectangle graphic = new Rectangle(10, 10, Color.RED);
{ setGraphic(graphic); };
@Override public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
graphic.setVisible(false);
setText(null);
} else {
graphic.setVisible(true);
setText(item.toString());
}
}
};
}
});
// First two rows have content, so the graphic should show.
// All other rows have no content, so graphic should not show.
VirtualFlowTestUtils.assertGraphicIsVisible(treeTableView, 0);
VirtualFlowTestUtils.assertGraphicIsVisible(treeTableView, 1);
VirtualFlowTestUtils.assertGraphicIsVisible(treeTableView, 2);
VirtualFlowTestUtils.assertGraphicIsVisible(treeTableView, 3);
VirtualFlowTestUtils.assertGraphicIsNotVisible(treeTableView, 4);
VirtualFlowTestUtils.assertGraphicIsNotVisible(treeTableView, 5);
}
private int rt_31015_count = 0;
@Test public void test_rt_31015() {
installChildren();
root.getChildren().clear();
treeTableView.setEditable(true);
TreeTableColumn<String, String> col = new TreeTableColumn<String, String>("column");
col.setCellValueFactory(param -> new ReadOnlyObjectWrapper<String>(param.getValue().getValue()));
treeTableView.getColumns().add(col);
//Set cell factory for cells that allow editing
Callback<TreeTableColumn<String,String>, TreeTableCell<String, String>> cellFactory = new Callback<TreeTableColumn<String,String>, TreeTableCell<String, String>>() {
public TreeTableCell<String, String> call(TreeTableColumn<String, String> p) {
return new TreeTableCell<String, String>() {
@Override public void cancelEdit() {
super.cancelEdit();
rt_31015_count++;
}
};
}
};
col.setCellFactory(cellFactory);
StageLoader sl = new StageLoader(treeTableView);
assertEquals(0, rt_31015_count);
treeTableView.edit(0, col);
assertEquals(0, rt_31015_count);
treeTableView.edit(-1, null);
assertEquals(1, rt_31015_count);
sl.dispose();
}
@Test public void test_rt_30688() {
installChildren();
root.getChildren().clear();
treeTableView.setColumnResizePolicy(TreeTableView.CONSTRAINED_RESIZE_POLICY);
TreeTableColumn<String, String> col = new TreeTableColumn<>("column");
col.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().getValue()));
treeTableView.getColumns().add(col);
StageLoader sl = new StageLoader(treeTableView);
assertEquals(TreeTableViewShim.get_contentWidth(treeTableView),
TableColumnBaseShim.getWidth(col), 0.0);
sl.dispose();
}
private int rt_29650_start_count = 0;
private int rt_29650_commit_count = 0;
private int rt_29650_cancel_count = 0;
@Test public void test_rt_29650() {
installChildren();
treeTableView.setEditable(true);
TreeTableColumn<String, String> col = new TreeTableColumn<>("column");
Callback<TreeTableColumn<String, String>, TreeTableCell<String, String>> factory = TextFieldTreeTableCell.forTreeTableColumn();
col.setCellFactory(factory);
col.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().getValue()));
treeTableView.getColumns().add(col);
col.setOnEditStart(t -> {
rt_29650_start_count++;
});
col.setOnEditCommit(t -> {
rt_29650_commit_count++;
});
col.setOnEditCancel(t -> {
rt_29650_cancel_count++;
});
StageLoader sl = new StageLoader(treeTableView);
treeTableView.edit(0, col);
Toolkit.getToolkit().firePulse();
TreeTableCell rootCell = (TreeTableCell) VirtualFlowTestUtils.getCell(treeTableView, 0, 0);
TextField textField = (TextField) rootCell.getGraphic();
textField.setText("Testing!");
KeyEventFirer keyboard = new KeyEventFirer(textField);
keyboard.doKeyPress(KeyCode.ENTER);
// TODO should the following assert be enabled?
// assertEquals("Testing!", listView.getItems().get(0));
assertEquals(1, rt_29650_start_count);
assertEquals(1, rt_29650_commit_count);
assertEquals(0, rt_29650_cancel_count);
sl.dispose();
}
private int rt_29849_start_count = 0;
@Test public void test_rt_29849() {
installChildren();
treeTableView.setEditable(true);
TreeTableColumn<String, String> col = new TreeTableColumn<>("column");
col.setEditable(true);
col.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().getValue()));
treeTableView.getColumns().add(col);
col.setOnEditStart(t -> {
rt_29849_start_count++;
});
// load the table so the default cells are created
StageLoader sl = new StageLoader(treeTableView);
// now replace the cell factory
Callback<TreeTableColumn<String, String>, TreeTableCell<String, String>> factory = TextFieldTreeTableCell.forTreeTableColumn();
col.setCellFactory(factory);
Toolkit.getToolkit().firePulse();
// now start an edit and count the start edit events - it should be just 1
treeTableView.edit(0, col);
assertEquals(1, rt_29849_start_count);
sl.dispose();
}
@Test public void test_rt_34327() {
// by default the comparator is null.
// NOTE: this method (prior to the fix as part of RT-34327) would have
// returned Comparator<String>, but after the fix it correctly returns
// a Comparator<TreeItem<String>>
Comparator nonGenericComparator = treeTableView.getComparator();
Comparator<TreeItem<String>> genericComparator = treeTableView.getComparator();
assertNull(nonGenericComparator);
assertNull(genericComparator);
// add in a column and some data
TreeTableColumn<String, String> col = new TreeTableColumn<>("column");
col.setEditable(true);
col.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().getValue()));
treeTableView.getColumns().add(col);
installChildren();
// sort by that column
treeTableView.getSortOrder().add(col);
// get the new comparator, which should no longer be null
nonGenericComparator = treeTableView.getComparator();
genericComparator = treeTableView.getComparator();
assertNotNull(nonGenericComparator);
assertNotNull(genericComparator);
// now, as noted above, previously we would use the Comparator to compare
// two String instances, which would fail at runtime as the Comparator
// was actually expecting to compare two TreeItem<String>, but the API
// was failing us.
try {
nonGenericComparator.compare("abc", "def");
fail("This should not work!");
} catch (ClassCastException e) {
// if we get the exception, we're happy
}
try {
Object string1 = "abc";
Object string2 = "def";
genericComparator.compare((TreeItem<String>)string1, (TreeItem<String>)string2);
fail("This should not work!");
} catch (ClassCastException e) {
// if we get the exception, we're happy
}
}
@Test public void test_rt26718() {
treeTableView.setRoot(new TreeItem("Root"));
treeTableView.getRoot().setExpanded(true);
for (int i = 0; i < 4; i++) {
TreeItem parent = new TreeItem("item - " + i);
treeTableView.getRoot().getChildren().add(parent);
for (int j = 0; j < 4; j++) {
TreeItem child = new TreeItem("item - " + i + " " + j);
parent.getChildren().add(child);
}
}
treeTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
final TreeItem item0 = treeTableView.getTreeItem(1);
final TreeItem item1 = treeTableView.getTreeItem(2);
assertEquals("item - 0", item0.getValue());
assertEquals("item - 1", item1.getValue());
item0.setExpanded(true);
item1.setExpanded(true);
Toolkit.getToolkit().firePulse();
treeTableView.getSelectionModel().selectRange(0, 8);
assertEquals(8, treeTableView.getSelectionModel().getSelectedIndices().size());
assertEquals(7, treeTableView.getSelectionModel().getSelectedIndex());
assertEquals(7, treeTableView.getFocusModel().getFocusedIndex());
// collapse item0 - but because the selected and focused indices are
// not children of item 0, they should remain where they are (but of
// course be shifted up). The bug was that focus was moving up to item0,
// which makes no sense
item0.setExpanded(false);
Toolkit.getToolkit().firePulse();
assertEquals(3, treeTableView.getSelectionModel().getSelectedIndex());
assertEquals(3, treeTableView.getFocusModel().getFocusedIndex());
}
// @Ignore("Test started intermittently failing, most probably due to RT-36855 changeset")
@Test public void test_rt_34493() {
ObservableList<TreeItem<Person>> persons = FXCollections.observableArrayList(
new TreeItem<Person>(new Person("Jacob", "Smith", "[email protected]"))
);
TreeTableView<Person> table = new TreeTableView<>();
TreeItem<Person> root = new TreeItem<Person>(new Person("Root", null, null));
root.setExpanded(true);
table.setRoot(root);
table.setShowRoot(false);
root.getChildren().setAll(persons);
TreeTableColumn first = new TreeTableColumn("First Name");
first.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
TreeTableColumn last = new TreeTableColumn("Last Name");
last.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("lastName"));
TreeTableColumn email = new TreeTableColumn("Email");
email.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("email"));
table.getColumns().addAll(first, last, email);
// load the table
StageLoader sl = new StageLoader(table);
// resize the last column
TableColumnBaseHelper.setWidth(last, 400);
assertEquals(400, last.getWidth(), 0.0);
// hide the first column
table.getColumns().remove(first);
Toolkit.getToolkit().firePulse();
// the last column should still be 400px, not the default width or any
// other value (based on the width of the content in that column)
assertEquals(400, last.getWidth(), 0.0);
sl.dispose();
}
@Test public void test_rt26721_collapseParent_firstRootChild() {
TreeTableView<String> table = new TreeTableView<>();
table.setRoot(new TreeItem("Root"));
table.getRoot().setExpanded(true);
for (int i = 0; i < 4; i++) {
TreeItem parent = new TreeItem("item - " + i);
table.getRoot().getChildren().add(parent);
for (int j = 0; j < 4; j++) {
TreeItem child = new TreeItem("item - " + i + " " + j);
parent.getChildren().add(child);
}
}
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
final TreeItem<String> item0 = table.getTreeItem(1);
final TreeItem<String> item0child0 = item0.getChildren().get(0);
final TreeItem<String> item1 = table.getTreeItem(2);
assertEquals("item - 0", item0.getValue());
assertEquals("item - 1", item1.getValue());
item0.setExpanded(true);
item1.setExpanded(true);
Toolkit.getToolkit().firePulse();
// select the first child of item0
table.getSelectionModel().select(item0child0);
assertEquals(item0child0, table.getSelectionModel().getSelectedItem());
assertEquals(item0child0, table.getFocusModel().getFocusedItem());
// collapse item0 - we expect the selection / focus to move up to item0
item0.setExpanded(false);
Toolkit.getToolkit().firePulse();
assertEquals(item0, table.getSelectionModel().getSelectedItem());
assertEquals(item0, table.getFocusModel().getFocusedItem());
}
@Test public void test_rt26721_collapseParent_lastRootChild() {
TreeTableView<String> table = new TreeTableView<>();
table.setRoot(new TreeItem("Root"));
table.getRoot().setExpanded(true);
for (int i = 0; i < 4; i++) {
TreeItem parent = new TreeItem("item - " + i);
table.getRoot().getChildren().add(parent);
for (int j = 0; j < 4; j++) {
TreeItem child = new TreeItem("item - " + i + " " + j);
parent.getChildren().add(child);
}
}
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
final TreeItem<String> item3 = table.getTreeItem(4);
final TreeItem<String> item3child0 = item3.getChildren().get(0);
assertEquals("item - 3", item3.getValue());
assertEquals("item - 3 0", item3child0.getValue());
item3.setExpanded(true);
Toolkit.getToolkit().firePulse();
// select the first child of item0
table.getSelectionModel().select(item3child0);
assertEquals(item3child0, table.getSelectionModel().getSelectedItem());
assertEquals(item3child0, table.getFocusModel().getFocusedItem());
// collapse item3 - we expect the selection / focus to move up to item3
item3.setExpanded(false);
Toolkit.getToolkit().firePulse();
assertEquals(item3, table.getSelectionModel().getSelectedItem());
assertEquals(item3, table.getFocusModel().getFocusedItem());
}
@Test public void test_rt26721_collapseGrandParent() {
TreeTableView<String> table = new TreeTableView<>();
table.setRoot(new TreeItem("Root"));
table.getRoot().setExpanded(true);
for (int i = 0; i < 4; i++) {
TreeItem parent = new TreeItem("item - " + i);
table.getRoot().getChildren().add(parent);
for (int j = 0; j < 4; j++) {
TreeItem child = new TreeItem("item - " + i + " " + j);
parent.getChildren().add(child);
}
}
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
final TreeItem<String> item0 = table.getTreeItem(1);
final TreeItem<String> item0child0 = item0.getChildren().get(0);
final TreeItem<String> item1 = table.getTreeItem(2);
assertEquals("item - 0", item0.getValue());
assertEquals("item - 1", item1.getValue());
item0.setExpanded(true);
item1.setExpanded(true);
Toolkit.getToolkit().firePulse();
// select the first child of item0
table.getSelectionModel().select(item0child0);
assertEquals(item0child0, table.getSelectionModel().getSelectedItem());
assertEquals(item0child0, table.getFocusModel().getFocusedItem());
// collapse root - we expect the selection / focus to move up to root
table.getRoot().setExpanded(false);
Toolkit.getToolkit().firePulse();
assertEquals(table.getRoot(), table.getSelectionModel().getSelectedItem());
assertEquals(table.getRoot(), table.getFocusModel().getFocusedItem());
}
@Test public void test_rt_34685_directEditCall_cellSelectionMode() {
test_rt_34685_commitCount = 0;
test_rt_34685(false, true);
}
@Test public void test_rt_34685_directEditCall_rowSelectionMode() {
test_rt_34685_commitCount = 0;
test_rt_34685(false, false);
}
@Test public void test_rt_34685_mouseDoubleClick_cellSelectionMode() {
test_rt_34685_commitCount = 0;
test_rt_34685(true, true);
}
@Test public void test_rt_34685_mouseDoubleClick_rowSelectionMode() {
test_rt_34685_commitCount = 0;
test_rt_34685(true, false);
}
private int test_rt_34685_commitCount = 0;
private void test_rt_34685(boolean useMouseToInitiateEdit, boolean cellSelectionModeEnabled) {
assertEquals(0, test_rt_34685_commitCount);
Person person1;
ObservableList<TreeItem<Person>> persons = FXCollections.observableArrayList(
new TreeItem<>(person1 = new Person("John", "Smith", "[email protected]"))
);
TreeTableView<Person> table = new TreeTableView<>();
table.getSelectionModel().setCellSelectionEnabled(cellSelectionModeEnabled);
table.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
table.setEditable(true);
TreeItem<Person> root = new TreeItem<Person>(new Person("Root", null, null));
root.setExpanded(true);
table.setRoot(root);
table.setShowRoot(false);
root.getChildren().setAll(persons);
TreeTableColumn first = new TreeTableColumn("First Name");
first.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
first.setCellFactory(TextFieldTreeTableCell.forTreeTableColumn());
EventHandler<TreeTableColumn.CellEditEvent<Person, String>> onEditCommit = first.getOnEditCommit();
first.setOnEditCommit(new EventHandler<TreeTableColumn.CellEditEvent<Person, String>>() {
@Override public void handle(TreeTableColumn.CellEditEvent<Person, String> event) {
test_rt_34685_commitCount++;
onEditCommit.handle(event);
}
});
table.getColumns().addAll(first);
// get the cell at (0,0) - we're hiding the root row
VirtualFlowTestUtils.BLOCK_STAGE_LOADER_DISPOSE = true;
TreeTableCell cell = (TreeTableCell) VirtualFlowTestUtils.getCell(table, 0, 0);
VirtualFlowTestUtils.BLOCK_STAGE_LOADER_DISPOSE = false;
assertTrue(cell.getSkin() instanceof TreeTableCellSkin);
assertNull(cell.getGraphic());
assertEquals("John", cell.getText());
assertEquals("John", person1.getFirstName());
// set the table to be editing the first cell at 0,0
if (useMouseToInitiateEdit) {
MouseEventFirer mouse = new MouseEventFirer(cell);
mouse.fireMousePressAndRelease(2, 10, 10); // click 10 pixels in and 10 pixels down
mouse.dispose();
} else {
table.edit(0,first);
}
Toolkit.getToolkit().firePulse();
assertNotNull(cell.getGraphic());
assertTrue(cell.getGraphic() instanceof TextField);
TextField textField = (TextField) cell.getGraphic();
assertEquals("John", textField.getText());
textField.setText("Andrew");
textField.requestFocus();
Toolkit.getToolkit().firePulse();
KeyEventFirer keyboard = new KeyEventFirer(textField);
keyboard.doKeyPress(KeyCode.ENTER);
VirtualFlowTestUtils.getVirtualFlow(table).requestLayout();
Toolkit.getToolkit().firePulse();
VirtualFlowTestUtils.assertTableCellTextEquals(table, 0, 0, "Andrew");
assertEquals("Andrew", cell.getText());
assertEquals("Andrew", person1.getFirstName());
assertEquals(1, test_rt_34685_commitCount);
}
@Test public void test_rt34694() {
TreeItem treeNode = new TreeItem("Controls");
treeNode.getChildren().addAll(
new TreeItem("Button"),
new TreeItem("ButtonBar"),
new TreeItem("LinkBar"),
new TreeItem("LinkButton"),
new TreeItem("PopUpButton"),
new TreeItem("ToggleButtonBar")
);
final TreeTableView<String> table = new TreeTableView<>();
table.setRoot(treeNode);
treeNode.setExpanded(true);
table.getSelectionModel().select(0);
assertTrue(table.getSelectionModel().isSelected(0));
assertTrue(table.getFocusModel().isFocused(0));
treeNode.getChildren().clear();
treeNode.getChildren().addAll(
new TreeItem("Button1"),
new TreeItem("ButtonBar1"),
new TreeItem("LinkBar1"),
new TreeItem("LinkButton1"),
new TreeItem("PopUpButton1"),
new TreeItem("ToggleButtonBar1")
);
Toolkit.getToolkit().firePulse();
assertTrue(table.getSelectionModel().isSelected(0));
assertTrue(table.getFocusModel().isFocused(0));
}
private int test_rt_35213_eventCount = 0;
@Test public void test_rt35213() {
final TreeTableView<String> view = new TreeTableView<>();
TreeItem<String> root = new TreeItem<>("Boss");
view.setRoot(root);
TreeItem<String> group1 = new TreeItem<>("Group 1");
TreeItem<String> group2 = new TreeItem<>("Group 2");
TreeItem<String> group3 = new TreeItem<>("Group 3");
root.getChildren().addAll(group1, group2, group3);
TreeItem<String> employee1 = new TreeItem<>("Employee 1");
TreeItem<String> employee2 = new TreeItem<>("Employee 2");
group2.getChildren().addAll(employee1, employee2);
TreeTableColumn<String, String> nameColumn = new TreeTableColumn<>("Name");
nameColumn.setCellValueFactory(new TreeItemPropertyValueFactory<String, String>("name"));
view.getColumns().add(nameColumn);
view.expandedItemCountProperty().addListener((observableValue, oldCount, newCount) -> {
// DEBUG OUTPUT
// System.out.println("new expanded item count: " + newCount.intValue());
// for (int i = 0; i < newCount.intValue(); i++) {
// TreeItem<String> item = view.getTreeItem(i);
// String text = item.getValue();
// System.out.println("person found at index " + i + " is " + text);
// }
// System.out.println("------------------------------------------");
if (test_rt_35213_eventCount == 0) {
assertEquals(4, newCount);
assertEquals("Boss", view.getTreeItem(0).getValue());
assertEquals("Group 1", view.getTreeItem(1).getValue());
assertEquals("Group 2", view.getTreeItem(2).getValue());
assertEquals("Group 3", view.getTreeItem(3).getValue());
} else if (test_rt_35213_eventCount == 1) {
assertEquals(6, newCount);
assertEquals("Boss", view.getTreeItem(0).getValue());
assertEquals("Group 1", view.getTreeItem(1).getValue());
assertEquals("Group 2", view.getTreeItem(2).getValue());
assertEquals("Employee 1", view.getTreeItem(3).getValue());
assertEquals("Employee 2", view.getTreeItem(4).getValue());
assertEquals("Group 3", view.getTreeItem(5).getValue());
} else if (test_rt_35213_eventCount == 2) {
assertEquals(4, newCount);
assertEquals("Boss", view.getTreeItem(0).getValue());
assertEquals("Group 1", view.getTreeItem(1).getValue());
assertEquals("Group 2", view.getTreeItem(2).getValue());
assertEquals("Group 3", view.getTreeItem(3).getValue());
}
test_rt_35213_eventCount++;
});
StageLoader sl = new StageLoader(view);
root.setExpanded(true);
Toolkit.getToolkit().firePulse();
group2.setExpanded(true);
Toolkit.getToolkit().firePulse();
group2.setExpanded(false);
Toolkit.getToolkit().firePulse();
sl.dispose();
}
@Test public void test_rt23245_itemIsInTree() {
final TreeTableView<String> view = new TreeTableView<String>();
final List<TreeItem<String>> items = new ArrayList<>();
for (int i = 0; i < 10; i++) {
final TreeItem<String> item = new TreeItem<String>("Item" + i);
item.setExpanded(true);
items.add(item);
}
// link the items up so that the next item is the child of the current item
for (int i = 0; i < 9; i++) {
items.get(i).getChildren().add(items.get(i + 1));
}
view.setRoot(items.get(0));
for (int i = 0; i < 10; i++) {
// we expect the level of the tree item at the ith position to be
// 0, as every iteration we are setting the ith item as the root.
assertEquals(0, view.getTreeItemLevel(items.get(i)));
// whilst we are testing, we should also ensure that the ith item
// is indeed the root item, and that the ith item is indeed the item
// at the 0th position
assertEquals(items.get(i), view.getRoot());
assertEquals(items.get(i), view.getTreeItem(0));
// shuffle the next item into the root position (keeping its parent
// chain intact - which is what exposes this issue in the first place).
if (i < 9) {
view.setRoot(items.get(i + 1));
}
}
}
@Test public void test_rt23245_itemIsNotInTree_noRootNode() {
final TreeView<String> view = new TreeView<String>();
final List<TreeItem<String>> items = new ArrayList<>();
for (int i = 0; i < 10; i++) {
final TreeItem<String> item = new TreeItem<String>("Item" + i);
item.setExpanded(true);
items.add(item);
}
// link the items up so that the next item is the child of the current item
for (int i = 0; i < 9; i++) {
items.get(i).getChildren().add(items.get(i + 1));
}
for (int i = 0; i < 10; i++) {
// because we have no root (and we are not changing the root like
// the previous test), we expect the tree item level of the item
// in the ith position to be i.
assertEquals(i, view.getTreeItemLevel(items.get(i)));
// all items requested from the TreeView should be null, as the
// TreeView does not have a root item
assertNull(view.getTreeItem(i));
}
}
@Test public void test_rt23245_itemIsNotInTree_withUnrelatedRootNode() {
final TreeView<String> view = new TreeView<String>();
final List<TreeItem<String>> items = new ArrayList<>();
for (int i = 0; i < 10; i++) {
final TreeItem<String> item = new TreeItem<String>("Item" + i);
item.setExpanded(true);
items.add(item);
}
// link the items up so that the next item is the child of the current item
for (int i = 0; i < 9; i++) {
items.get(i).getChildren().add(items.get(i + 1));
}
view.setRoot(new TreeItem("Unrelated root node"));
for (int i = 0; i < 10; i++) {
// because we have no root (and we are not changing the root like
// the previous test), we expect the tree item level of the item
// in the ith position to be i.
assertEquals(i, view.getTreeItemLevel(items.get(i)));
// all items requested from the TreeView should be null except for
// the root node
assertNull(view.getTreeItem(i + 1));
}
}
@Test public void test_rt35039_setRoot() {
TreeItem aabbaa = new TreeItem("aabbaa");
TreeItem bbc = new TreeItem("bbc");
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().setAll(aabbaa, bbc);
final TreeTableView<String> treeView = new TreeTableView<>();
treeView.setRoot(root);
StageLoader sl = new StageLoader(treeView);
// Selection starts in row -1
assertNull(treeView.getSelectionModel().getSelectedItem());
// select "bbc" and ensure everything is set to that
treeView.getSelectionModel().select(2);
assertEquals("bbc", treeView.getSelectionModel().getSelectedItem().getValue());
// change the items list - but retain the same content. We expect
// that "bbc" remains selected as it is still in the list
treeView.setRoot(root);
assertEquals("bbc", treeView.getSelectionModel().getSelectedItem().getValue());
sl.dispose();
}
@Test public void test_rt35039_resetRootChildren() {
TreeItem aabbaa = new TreeItem("aabbaa");
TreeItem bbc = new TreeItem("bbc");
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().setAll(aabbaa, bbc);
final TreeTableView<String> treeView = new TreeTableView<>();
treeView.setRoot(root);
StageLoader sl = new StageLoader(treeView);
// Selection starts in row -1
assertNull(treeView.getSelectionModel().getSelectedItem());
// select "bbc" and ensure everything is set to that
treeView.getSelectionModel().select(2);
assertEquals("bbc", treeView.getSelectionModel().getSelectedItem().getValue());
// change the items list - but retain the same content. We expect
// that "bbc" remains selected as it is still in the list
root.getChildren().setAll(aabbaa, bbc);
assertEquals("bbc", treeView.getSelectionModel().getSelectedItem().getValue());
sl.dispose();
}
@Test public void test_rt35763() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
TreeItem aaa = new TreeItem("aaa");
TreeItem bbb = new TreeItem("bbb");
root.getChildren().setAll(bbb, aaa);
final TreeTableView<String> treeView = new TreeTableView<>();
TreeTableColumn<String, String> col = new TreeTableColumn<>("Column");
col.setCellValueFactory(param -> param.getValue().valueProperty());
treeView.getColumns().add(col);
treeView.setRoot(root);
assertEquals(root, treeView.getTreeItem(0));
assertEquals(bbb, treeView.getTreeItem(1));
assertEquals(aaa,treeView.getTreeItem(2));
// change sort order - expect items to be sorted
treeView.getSortOrder().setAll(col);
assertEquals(1, treeView.getSortOrder().size());
assertEquals(col, treeView.getSortOrder().get(0));
Toolkit.getToolkit().firePulse();
assertEquals(root, treeView.getTreeItem(0));
assertEquals(bbb, treeView.getTreeItem(2));
assertEquals(aaa,treeView.getTreeItem(1));
// set new items into items list - expect sortOrder list to be reset
// and the items list to remain unsorted
TreeItem<String> root2 = new TreeItem<>("Root");
root2.setExpanded(true);
TreeItem ccc = new TreeItem("ccc");
TreeItem ddd = new TreeItem("ddd");
root2.getChildren().setAll(ddd, ccc);
treeView.setRoot(root2);
assertEquals(root2, treeView.getTreeItem(0));
assertEquals(ddd, treeView.getTreeItem(1));
assertEquals(ccc,treeView.getTreeItem(2));
assertTrue(treeView.getSortOrder().isEmpty());
}
@Test public void test_rt35857() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
TreeItem a = new TreeItem("A");
TreeItem b = new TreeItem("B");
TreeItem c = new TreeItem("C");
root.getChildren().setAll(a, b, c);
final TreeTableView<String> treeTableView = new TreeTableView<String>(root);
treeTableView.getSelectionModel().select(1);
ObservableList<TreeItem<String>> selectedItems = treeTableView.getSelectionModel().getSelectedItems();
assertEquals(1, selectedItems.size());
assertEquals("A", selectedItems.get(0).getValue());
root.getChildren().removeAll(selectedItems);
assertEquals(2, root.getChildren().size());
assertEquals("B", root.getChildren().get(0).getValue());
assertEquals("C", root.getChildren().get(1).getValue());
}
private int rt36452_instanceCount = 0;
@Test public void test_rt36452() {
TreeTableColumn<String, String> myColumn = new TreeTableColumn<String,String>();
myColumn.setCellValueFactory((item)->(new ReadOnlyObjectWrapper<>(item.getValue().getValue())));
myColumn.setCellFactory(column -> new TreeTableCell<String, String>() {
{
rt36452_instanceCount++;
}
});
TreeTableView<String> ttv = new TreeTableView<>();
ttv.setShowRoot(false);
ttv.getColumns().add(myColumn);
TreeItem<String> treeRootItem = new TreeItem<>("root");
treeRootItem.setExpanded(true);
for (int i = 0; i < 100; i++) {
treeRootItem.getChildren().add(new TreeItem<>("Child: " + i));
}
ttv.setRoot(treeRootItem);
ttv.setFixedCellSize(25);
StackPane root = new StackPane();
root.getChildren().add(ttv);
StageLoader sl = new StageLoader(root);
final int cellCountAtStart = rt36452_instanceCount;
// start scrolling
for (int i = 0; i < 100; i++) {
ttv.scrollTo(i);
Toolkit.getToolkit().firePulse();
}
// we don't mind if an extra few cells are created. What we are really
// testing for here is that we don't end up with an order of magnitude
// extra cells.
// On my machine the cellCountAtStart is 16. Before this issue was fixed
// I would end up with 102 instances after running this test. Once the
// bug was fixed, I would consistently see that 17 cells had been
// created in total.
// However, for now, we'll test on the assumption that across all
// platforms we only get one extra cell created, and we can loosen this
// up if necessary.
assertEquals(cellCountAtStart + 1, rt36452_instanceCount);
sl.dispose();
}
@Test public void test_rt25679_rowSelection() {
test_rt25679(true);
}
@Test public void test_rt25679_cellSelection() {
test_rt25679(false);
}
private void test_rt25679(boolean rowSelection) {
Button focusBtn = new Button("Focus here");
TreeItem<String> root = new TreeItem<>("Root");
root.getChildren().setAll(new TreeItem("a"), new TreeItem("b"));
root.setExpanded(true);
final TreeTableView<String> treeView = new TreeTableView<>(root);
TreeTableColumn<String, String> tableColumn = new TreeTableColumn<>();
tableColumn.setCellValueFactory(rowValue -> new SimpleStringProperty(rowValue.getValue().getValue()));
treeView.getColumns().add(tableColumn);
TreeTableView.TreeTableViewSelectionModel<String> sm = treeView.getSelectionModel();
sm.setCellSelectionEnabled(! rowSelection);
VBox vbox = new VBox(focusBtn, treeView);
StageLoader sl = new StageLoader(vbox);
sl.getStage().requestFocus();
focusBtn.requestFocus();
Toolkit.getToolkit().firePulse();
// test initial state
assertEquals(sl.getStage().getScene().getFocusOwner(), focusBtn);
assertTrue(focusBtn.isFocused());
assertEquals(-1, sm.getSelectedIndex());
assertNull(sm.getSelectedItem());
// move focus to the TreeTableView
treeView.requestFocus();
// ensure that there is a selection (where previously there was not one)
assertEquals(sl.getStage().getScene().getFocusOwner(), treeView);
assertTrue(treeView.isFocused());
if (rowSelection) {
assertEquals(0, sm.getSelectedIndices().size());
assertNull(sm.getSelectedItem());
assertFalse(sm.isSelected(0));
assertEquals(0, sm.getSelectedCells().size());
} else {
assertFalse(sm.isSelected(0, tableColumn));
assertEquals(0, sm.getSelectedCells().size());
}
sl.dispose();
}
@Test public void test_rt36885() {
test_rt36885(false);
}
@Test public void test_rt36885_addChildAfterSelection() {
test_rt36885(true);
}
private void test_rt36885(boolean addChildToAAfterSelection) {
TreeItem<String> root = new TreeItem<>("Root"); // 0
TreeItem<String> a = new TreeItem<>("a"); // 1
TreeItem<String> a1 = new TreeItem<>("a1"); // a expanded = 2, a collapsed = -1
TreeItem<String> b = new TreeItem<>("b"); // a expanded = 3, a collapsed = 2
TreeItem<String> b1 = new TreeItem<>("b1"); // a expanded = 4, a collapsed = 3
TreeItem<String> b2 = new TreeItem<>("b2"); // a expanded = 5, a collapsed = 4
root.setExpanded(true);
root.getChildren().setAll(a, b);
a.setExpanded(false);
if (!addChildToAAfterSelection) {
a.getChildren().add(a1);
}
b.setExpanded(true);
b.getChildren().addAll(b1, b2);
final TreeTableView<String> treeView = new TreeTableView<>(root);
TreeTableColumn<String, String> tableColumn = new TreeTableColumn<>();
tableColumn.setCellValueFactory(rowValue -> new SimpleStringProperty(rowValue.getValue().getValue()));
treeView.getColumns().add(tableColumn);
TreeTableView.TreeTableViewSelectionModel<String> sm = treeView.getSelectionModel();
FocusModel<TreeItem<String>> fm = treeView.getFocusModel();
sm.select(b1);
assertEquals(3, sm.getSelectedIndex());
assertEquals(b1, sm.getSelectedItem());
assertEquals(3, fm.getFocusedIndex());
assertEquals(b1, fm.getFocusedItem());
if (addChildToAAfterSelection) {
a.getChildren().add(a1);
}
a.setExpanded(true);
assertEquals(4, sm.getSelectedIndex());
assertEquals(b1, sm.getSelectedItem());
assertEquals(4, fm.getFocusedIndex());
assertEquals(b1, fm.getFocusedItem());
}
private int rt_37061_index_counter = 0;
private int rt_37061_item_counter = 0;
@Test public void test_rt_37061() {
TreeItem<Integer> root = new TreeItem<>(0);
root.setExpanded(true);
TreeTableView<Integer> tv = new TreeTableView<>();
tv.setRoot(root);
tv.getSelectionModel().select(0);
// note we add the listeners after the selection is made, so the counters
// at this point are still both at zero.
tv.getSelectionModel().selectedIndexProperty().addListener((observable, oldValue, newValue) -> {
rt_37061_index_counter++;
});
tv.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
rt_37061_item_counter++;
});
// add a new item. This does not impact the selected index or selected item
// so the counters should remain at zero.
tv.getRoot().getChildren().add(new TreeItem("1"));
assertEquals(0, rt_37061_index_counter);
assertEquals(0, rt_37061_item_counter);
}
@Test public void test_rt_37054_noScroll() {
test_rt_37054(false);
}
@Test public void test_rt_37054_scroll() {
test_rt_37054(true);
}
private void test_rt_37054(boolean scroll) {
ObjectProperty<Integer> offset = new SimpleObjectProperty<Integer>(0);
// create table with a bunch of rows and 1 column...
TreeItem<Integer> root = new TreeItem<>(0);
root.setExpanded(true);
for (int i = 1; i <= 50; i++) {
root.getChildren().add(new TreeItem<>(i));
}
final TreeTableColumn<Integer, Integer> column = new TreeTableColumn<>("Column");
final TreeTableView<Integer> table = new TreeTableView<>(root);
table.getColumns().add( column );
column.setPrefWidth( 150 );
// each cell displays x, where x = "cell row number + offset"
column.setCellValueFactory( cdf -> new ObjectBinding<Integer>() {
{ super.bind( offset ); }
@Override protected Integer computeValue() {
return cdf.getValue().getValue() + offset.get();
}
});
StackPane stack = new StackPane();
stack.getChildren().add(table);
StageLoader sl = new StageLoader(stack);
int index = scroll ? 0 : 25;
if (scroll) {
// we scroll to force the table cells to update the objects they observe
table.scrollTo(index);
Toolkit.getToolkit().firePulse();
}
TreeTableCell cell = (TreeTableCell) VirtualFlowTestUtils.getCell(table, index + 3, 0);
final int initialValue = (Integer) cell.getItem();
// increment the offset value
offset.setValue(offset.get() + 1);
Toolkit.getToolkit().firePulse();
final int incrementedValue = (Integer) cell.getItem();
assertEquals(initialValue + 1, incrementedValue);
sl.dispose();
}
private int rt_37395_index_addCount = 0;
private int rt_37395_index_removeCount = 0;
private int rt_37395_index_permutationCount = 0;
private int rt_37395_item_addCount = 0;
private int rt_37395_item_removeCount = 0;
private int rt_37395_item_permutationCount = 0;
@Test public void test_rt_37395() {
// table items - 3 items, 2nd item has 2 children
TreeItem<String> root = new TreeItem<>();
TreeItem<String> two = new TreeItem<>("two");
two.getChildren().add(new TreeItem<>("childOne"));
two.getChildren().add(new TreeItem<>("childTwo"));
root.getChildren().add(new TreeItem<>("one"));
root.getChildren().add(two);
root.getChildren().add(new TreeItem<>("three"));
// table columns - 1 column; name
TreeTableColumn<String, String> nameColumn = new TreeTableColumn<>("name");
nameColumn.setCellValueFactory(param -> new ReadOnlyObjectWrapper(param.getValue().getValue()));
nameColumn.setPrefWidth(200);
// table
TreeTableView<String> table = new TreeTableView<>();
table.setShowRoot(false);
table.setRoot(root);
table.getColumns().addAll(nameColumn);
TreeTableView.TreeTableViewSelectionModel sm = table.getSelectionModel();
sm.getSelectedIndices().addListener(new ListChangeListener<Integer>() {
@Override public void onChanged(Change<? extends Integer> c) {
while (c.next()) {
if (c.wasRemoved()) {
c.getRemoved().forEach(item -> {
if (item == null) {
fail("Removed index should never be null");
} else {
rt_37395_index_removeCount++;
}
});
}
if (c.wasAdded()) {
c.getAddedSubList().forEach(item -> {
rt_37395_index_addCount++;
});
}
if (c.wasPermutated()) {
rt_37395_index_permutationCount++;
}
}
}
});
sm.getSelectedItems().addListener(new ListChangeListener<TreeItem<String>>() {
@Override public void onChanged(Change<? extends TreeItem<String>> c) {
while (c.next()) {
if (c.wasRemoved()) {
c.getRemoved().forEach(item -> {
if (item == null) {
fail("Removed item should never be null");
} else {
rt_37395_item_removeCount++;
}
});
}
if (c.wasAdded()) {
c.getAddedSubList().forEach(item -> {
rt_37395_item_addCount++;
});
}
if (c.wasPermutated()) {
rt_37395_item_permutationCount++;
}
}
}
});
assertEquals(0, rt_37395_index_removeCount);
assertEquals(0, rt_37395_index_addCount);
assertEquals(0, rt_37395_index_permutationCount);
assertEquals(0, rt_37395_item_removeCount);
assertEquals(0, rt_37395_item_addCount);
assertEquals(0, rt_37395_item_permutationCount);
StageLoader sl = new StageLoader(table);
// step one: select item 'three' in index 2
sm.select(2);
assertEquals(0, rt_37395_index_removeCount);
assertEquals(1, rt_37395_index_addCount);
assertEquals(0, rt_37395_index_permutationCount);
assertEquals(0, rt_37395_item_removeCount);
assertEquals(1, rt_37395_item_addCount);
assertEquals(0, rt_37395_item_permutationCount);
// step two: expand item 'two'
// The first part of the bug report was that we received add/remove
// change events here, when in reality we shouldn't have, so lets enforce
// that. We do expect a permutation event on the index, as it has been
// pushed down, but this should not result in an item permutation event,
// as it remains unchanged
two.setExpanded(true);
assertEquals(1, rt_37395_index_removeCount);
assertEquals(2, rt_37395_index_addCount);
assertEquals(0, rt_37395_index_permutationCount);
assertEquals(0, rt_37395_item_removeCount);
assertEquals(1, rt_37395_item_addCount);
assertEquals(0, rt_37395_item_permutationCount);
// step three: collapse item 'two'
// Same argument as in step two above: no addition or removal, just a
// permutation on the index
two.setExpanded(false);
assertEquals(2, rt_37395_index_removeCount);
assertEquals(3, rt_37395_index_addCount);
assertEquals(0, rt_37395_index_permutationCount);
assertEquals(0, rt_37395_item_removeCount);
assertEquals(1, rt_37395_item_addCount);
assertEquals(0, rt_37395_item_permutationCount);
sl.dispose();
}
@Test public void test_rt_37429() {
// table items - 3 items, 2nd item has 2 children
TreeItem<String> root = new TreeItem<>();
TreeItem<String> two = new TreeItem<>("two");
two.getChildren().add(new TreeItem<>("childOne"));
two.getChildren().add(new TreeItem<>("childTwo"));
two.setExpanded(true);
root.getChildren().add(new TreeItem<>("one"));
root.getChildren().add(two);
root.getChildren().add(new TreeItem<>("three"));
// table columns - 1 column; name
TreeTableColumn<String, String> nameColumn = new TreeTableColumn<>("name");
nameColumn.setCellValueFactory(param -> new ReadOnlyObjectWrapper(param.getValue().getValue()));
nameColumn.setPrefWidth(200);
// table
TreeTableView<String> table = new TreeTableView<>();
table.setShowRoot(false);
table.setRoot(root);
table.getColumns().addAll(nameColumn);
table.getSelectionModel().getSelectedItems().addListener((ListChangeListener<TreeItem<String>>) c -> {
while (c.next()) {
if(c.wasRemoved()) {
// The removed list of items must be iterated or the AIOOBE will
// not be thrown when getAddedSubList is called.
c.getRemoved().forEach(item -> {});
}
if (c.wasAdded()) {
c.getAddedSubList();
}
}
});
StageLoader sl = new StageLoader(table);
ControlTestUtils.runWithExceptionHandler(() -> {
table.getSelectionModel().select(0);
table.getSortOrder().add(nameColumn);
});
sl.dispose();
}
private int rt_37429_items_change_count = 0;
private int rt_37429_cells_change_count = 0;
@Test public void test_rt_37429_sortEventsShouldNotFireExtraChangeEvents() {
// table items - 3 items, 2nd item has 2 children
TreeItem<String> root = new TreeItem<>();
root.getChildren().add(new TreeItem<>("a"));
root.getChildren().add(new TreeItem<>("c"));
root.getChildren().add(new TreeItem<>("b"));
// table columns - 1 column; name
TreeTableColumn<String, String> nameColumn = new TreeTableColumn<>("name");
nameColumn.setCellValueFactory(param -> new ReadOnlyObjectWrapper(param.getValue().getValue()));
nameColumn.setPrefWidth(200);
// table
TreeTableView<String> table = new TreeTableView<>();
table.setShowRoot(false);
table.setRoot(root);
table.getColumns().addAll(nameColumn);
table.getSelectionModel().getSelectedItems().addListener((ListChangeListener<TreeItem<String>>) c -> {
while (c.next()) {
rt_37429_items_change_count++;
}
});
table.getSelectionModel().getSelectedCells().addListener((ListChangeListener<TreeTablePosition<String, ?>>) c -> {
while (c.next()) {
rt_37429_cells_change_count++;
}
});
StageLoader sl = new StageLoader(table);
assertEquals(0, rt_37429_items_change_count);
assertEquals(0, rt_37429_cells_change_count);
table.getSelectionModel().select(0);
assertEquals(1, rt_37429_items_change_count);
assertEquals(1, rt_37429_cells_change_count);
table.getSortOrder().add(nameColumn);
assertEquals(1, rt_37429_items_change_count);
assertEquals(1, rt_37429_cells_change_count);
nameColumn.setSortType(TreeTableColumn.SortType.DESCENDING);
assertEquals(1, rt_37429_items_change_count);
assertEquals(2, rt_37429_cells_change_count);
nameColumn.setSortType(TreeTableColumn.SortType.ASCENDING);
assertEquals(1, rt_37429_items_change_count);
assertEquals(3, rt_37429_cells_change_count);
sl.dispose();
}
private int rt_37538_count = 0;
@Test public void test_rt_37538_noCNextCall() {
test_rt_37538(false, false);
}
@Test public void test_rt_37538_callCNextOnce() {
test_rt_37538(true, false);
}
@Test public void test_rt_37538_callCNextInLoop() {
test_rt_37538(false, true);
}
private void test_rt_37538(boolean callCNextOnce, boolean callCNextInLoop) {
// create table with a bunch of rows and 1 column...
TreeItem<Integer> root = new TreeItem<>(0);
root.setExpanded(true);
for (int i = 1; i <= 50; i++) {
root.getChildren().add(new TreeItem<>(i));
}
final TreeTableColumn<Integer, Integer> column = new TreeTableColumn<>("Column");
column.setCellValueFactory( cdf -> new ReadOnlyObjectWrapper<Integer>(cdf.getValue().getValue()));
final TreeTableView<Integer> table = new TreeTableView<>(root);
table.getColumns().add( column );
table.getSelectionModel().getSelectedItems().addListener((ListChangeListener.Change<? extends TreeItem<Integer>> c) -> {
if (callCNextOnce) {
c.next();
} else if (callCNextInLoop) {
while (c.next()) {
// no-op
}
}
if (rt_37538_count >= 1) {
Thread.dumpStack();
fail("This method should only be called once");
}
rt_37538_count++;
});
StageLoader sl = new StageLoader(table);
assertEquals(0, rt_37538_count);
table.getSelectionModel().select(0);
assertEquals(1, rt_37538_count);
sl.dispose();
}
@Test public void test_rt_37593() {
TreeItem<String> root = new TreeItem<>();
TreeItem<String> one = new TreeItem<>("one");
root.getChildren().add(one);
TreeItem<String> two = new TreeItem<>("two");
two.getChildren().add(new TreeItem<>("childOne"));
two.getChildren().add(new TreeItem<>("childTwo"));
root.getChildren().add(two);
root.getChildren().add(new TreeItem<>("three"));
TreeTableColumn<String, String> nameColumn = new TreeTableColumn<>("name");
nameColumn.setCellValueFactory(param -> new ReadOnlyObjectWrapper(param.getValue().getValue()));
treeTableView.setShowRoot(false);
treeTableView.setRoot(root);
treeTableView.getColumns().addAll(nameColumn);
treeTableView.getSortOrder().add(nameColumn);
nameColumn.setSortType(TreeTableColumn.SortType.DESCENDING);
sm.select(one);
// at this point, the 'one' item should be in row 2
assertTrue(sm.isSelected(2));
assertEquals(one, sm.getSelectedItem());
two.setExpanded(true);
// we should end up with the selection being on index 4, which is the
// final location of the 'one' tree item, after sorting and expanding 'two'
assertEquals(one, sm.getSelectedItem());
assertTrue(debug(), sm.isSelected(4));
// this line would create a NPE
VirtualFlowTestUtils.clickOnRow(treeTableView, 4, true);
// The mouse click should not change selection at all
assertEquals(one, sm.getSelectedItem());
assertTrue(debug(), sm.isSelected(4));
}
@Test public void test_rt_35395_testCell_fixedCellSize() {
test_rt_35395(true, true);
}
@Test public void test_rt_35395_testCell_notFixedCellSize() {
test_rt_35395(true, false);
}
@Ignore("Fix not yet developed for TreeTableView")
@Test public void test_rt_35395_testRow_fixedCellSize() {
test_rt_35395(false, true);
}
@Ignore("Fix not yet developed for TreeTableView")
@Test public void test_rt_35395_testRow_notFixedCellSize() {
test_rt_35395(false, false);
}
private int rt_35395_counter;
private void test_rt_35395(boolean testCell, boolean useFixedCellSize) {
rt_35395_counter = 0;
TreeItem<String> root = new TreeItem<>("green");
root.setExpanded(true);
for (int i = 0; i < 20; i++) {
root.getChildren().addAll(new TreeItem<>("red"), new TreeItem<>("green"), new TreeItem<>("blue"), new TreeItem<>("purple"));
}
TreeTableView<String> treeTableView = new TreeTableView<>(root);
if (useFixedCellSize) {
treeTableView.setFixedCellSize(24);
}
treeTableView.setRowFactory(tv -> new TreeTableRowShim<String>() {
@Override public void updateItem(String color, boolean empty) {
rt_35395_counter += testCell ? 0 : 1;
super.updateItem(color, empty);
}
});
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(param -> new ReadOnlyStringWrapper(param.getValue().getValue()));
column.setCellFactory(tv -> new TreeTableCellShim<String,String>() {
@Override public void updateItem(String color, boolean empty) {
rt_35395_counter += testCell ? 1 : 0;
super.updateItem(color, empty);
setText(null);
if (empty) {
setGraphic(null);
} else {
Rectangle rect = new Rectangle(16, 16);
rect.setStyle("-fx-fill: " + color);
setGraphic(rect);
}
}
});
treeTableView.getColumns().addAll(column);
StageLoader sl = new StageLoader(treeTableView);
Platform.runLater(() -> {
rt_35395_counter = 0;
root.getChildren().set(10, new TreeItem<>("yellow"));
Platform.runLater(() -> {
Toolkit.getToolkit().firePulse();
assertEquals(1, rt_35395_counter);
rt_35395_counter = 0;
root.getChildren().set(30, new TreeItem<>("yellow"));
Platform.runLater(() -> {
Toolkit.getToolkit().firePulse();
assertEquals(0, rt_35395_counter);
rt_35395_counter = 0;
treeTableView.scrollTo(5);
Platform.runLater(() -> {
Toolkit.getToolkit().firePulse();
assertEquals(useFixedCellSize ? 5 : 5, rt_35395_counter);
rt_35395_counter = 0;
treeTableView.scrollTo(55);
Platform.runLater(() -> {
Toolkit.getToolkit().firePulse();
assertEquals(useFixedCellSize ? 7 : 59, rt_35395_counter);
sl.dispose();
});
});
});
});
});
}
@Test public void test_rt_37632() {
final TreeItem<String> rootOne = new TreeItem<>("Root 1");
final TreeItem<String> rootTwo = new TreeItem<>("Root 2");
TreeTableColumn<String,String> tableColumn = new TreeTableColumn("column");
tableColumn.setCellValueFactory(c -> new ReadOnlyStringWrapper(c.getValue().getValue()));
final TreeTableView<String> treeTableView = new TreeTableView<>();
treeTableView.getColumns().addAll(tableColumn);
MultipleSelectionModel<TreeItem<String>> sm = treeTableView.getSelectionModel();
treeTableView.setRoot(rootOne);
treeTableView.getSelectionModel().selectFirst();
assertEquals(0, sm.getSelectedIndex());
assertEquals(rootOne, sm.getSelectedItem());
assertEquals(1, sm.getSelectedIndices().size());
assertEquals(0, (int) sm.getSelectedIndices().get(0));
assertEquals(1, sm.getSelectedItems().size());
assertEquals(rootOne, sm.getSelectedItems().get(0));
treeTableView.setRoot(rootTwo);
assertEquals(-1, sm.getSelectedIndex());
assertNull(sm.getSelectedItem());
assertEquals(0, sm.getSelectedIndices().size());
assertEquals(0, sm.getSelectedItems().size());
}
private TreeTableView<Person> test_rt_38464_createControl() {
ObservableList<TreeItem<Person>> persons = FXCollections.observableArrayList(
new TreeItem<>(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem<>(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem<>(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem<>(new Person("Emma", "Jones", "[email protected]")),
new TreeItem<>(new Person("Michael", "Brown", "[email protected]")));
TreeTableView<Person> table = new TreeTableView<>();
table.setShowRoot(false);
TreeItem<Person> root = new TreeItem<>(new Person("Root", null, null));
root.setExpanded(true);
root.getChildren().setAll(persons);
table.setRoot(root);
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
TreeTableColumn lastNameCol = new TreeTableColumn("Last Name");
lastNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("lastName"));
table.getColumns().addAll(firstNameCol, lastNameCol);
return table;
}
@Test public void test_rt_38464_rowSelection_selectFirstRowOnly() {
TreeTableView<Person> table = test_rt_38464_createControl();
TreeTableView.TreeTableViewSelectionModel<Person> sm = table.getSelectionModel();
sm.setCellSelectionEnabled(false);
sm.setSelectionMode(SelectionMode.MULTIPLE);
sm.select(0);
assertTrue(sm.isSelected(0));
assertTrue(sm.isSelected(0, table.getColumns().get(0)));
assertTrue(sm.isSelected(0, table.getColumns().get(1)));
assertEquals(1, sm.getSelectedIndices().size());
assertEquals(1, sm.getSelectedItems().size());
assertEquals(1, sm.getSelectedCells().size());
}
@Test public void test_rt_38464_rowSelection_selectFirstRowAndThenCallNoOpMethods() {
TreeTableView<Person> table = test_rt_38464_createControl();
TreeTableView.TreeTableViewSelectionModel<Person> sm = table.getSelectionModel();
sm.setCellSelectionEnabled(false);
sm.setSelectionMode(SelectionMode.MULTIPLE);
sm.select(0); // select first row
sm.select(0); // this should be a no-op
sm.select(0, table.getColumns().get(0)); // so should this, as we are in row selection mode
sm.select(0, table.getColumns().get(1)); // and same here
assertTrue(sm.isSelected(0));
assertTrue(sm.isSelected(0, table.getColumns().get(0)));
assertTrue(sm.isSelected(0, table.getColumns().get(1)));
assertEquals(1, sm.getSelectedIndices().size());
assertEquals(1, sm.getSelectedItems().size());
assertEquals(1, sm.getSelectedCells().size());
}
@Test public void test_rt_38464_cellSelection_selectFirstRowOnly() {
TreeTableView<Person> table = test_rt_38464_createControl();
TreeTableView.TreeTableViewSelectionModel<Person> sm = table.getSelectionModel();
sm.setCellSelectionEnabled(true);
sm.setSelectionMode(SelectionMode.MULTIPLE);
// select first row. This should be translated into selection of all
// cells in this row, and (as of JDK 9) _does_ result in the row itself being
// considered selected.
sm.select(0);
assertTrue(sm.isSelected(0));
assertTrue(sm.isSelected(0, table.getColumns().get(0)));
assertTrue(sm.isSelected(0, table.getColumns().get(1)));
assertEquals(1, sm.getSelectedIndices().size());
assertEquals(1, sm.getSelectedItems().size());
assertEquals(2, sm.getSelectedCells().size());
}
@Test public void test_rt_38464_cellSelection_selectFirstRowAndThenCallNoOpMethods() {
TreeTableView<Person> table = test_rt_38464_createControl();
TreeTableView.TreeTableViewSelectionModel<Person> sm = table.getSelectionModel();
sm.setCellSelectionEnabled(true);
sm.setSelectionMode(SelectionMode.MULTIPLE);
// select first row. This should be translated into selection of all
// cells in this row, and (as of JDK 9) _does_ result in the row itself being
// considered selected.
sm.select(0); // select first row
sm.select(0, table.getColumns().get(0)); // This line and the next should be no-ops
sm.select(0, table.getColumns().get(1));
assertTrue(sm.isSelected(0));
assertTrue(sm.isSelected(0, table.getColumns().get(0)));
assertTrue(sm.isSelected(0, table.getColumns().get(1)));
assertEquals(1, sm.getSelectedIndices().size());
assertEquals(1, sm.getSelectedItems().size());
assertEquals(2, sm.getSelectedCells().size());
}
@Test public void test_rt38464_selectCellMultipleTimes() {
TreeTableView<Person> table = test_rt_38464_createControl();
TreeTableView.TreeTableViewSelectionModel<Person> sm = table.getSelectionModel();
sm.setCellSelectionEnabled(true);
sm.setSelectionMode(SelectionMode.MULTIPLE);
// default selection when in cell selection mode
assertEquals(0, sm.getSelectedCells().size());
assertEquals(0, sm.getSelectedItems().size());
assertEquals(0, sm.getSelectedIndices().size());
// select the first cell
sm.select(0, table.getColumns().get(0));
assertEquals(1, sm.getSelectedCells().size());
assertEquals(1, sm.getSelectedItems().size());
assertEquals(1, sm.getSelectedIndices().size());
// select the first cell....again
sm.select(0, table.getColumns().get(0));
assertEquals(1, sm.getSelectedCells().size());
assertEquals(1, sm.getSelectedItems().size());
assertEquals(1, sm.getSelectedIndices().size());
}
@Test public void test_rt38464_selectCellThenRow() {
TreeTableView<Person> table = test_rt_38464_createControl();
TreeTableView.TreeTableViewSelectionModel<Person> sm = table.getSelectionModel();
sm.setCellSelectionEnabled(true);
sm.setSelectionMode(SelectionMode.MULTIPLE);
// default selection when in cell selection mode
assertEquals(0, sm.getSelectedCells().size());
assertEquals(0, sm.getSelectedItems().size());
assertEquals(0, sm.getSelectedIndices().size());
// select the first cell
sm.select(0, table.getColumns().get(0));
assertEquals(1, sm.getSelectedCells().size());
assertEquals(1, sm.getSelectedItems().size());
assertEquals(1, sm.getSelectedIndices().size());
// select the first row
sm.select(0);
// we go to 2 here as all cells in the row become selected. What we do
// not expect is to go to 3, as that would mean duplication
assertEquals(2, sm.getSelectedCells().size());
assertEquals(1, sm.getSelectedItems().size());
assertEquals(1, sm.getSelectedIndices().size());
}
@Test public void test_rt38464_selectRowThenCell() {
TreeTableView<Person> table = test_rt_38464_createControl();
TreeTableView.TreeTableViewSelectionModel<Person> sm = table.getSelectionModel();
sm.setCellSelectionEnabled(true);
sm.setSelectionMode(SelectionMode.MULTIPLE);
// default selection when in cell selection mode
assertEquals(0, sm.getSelectedCells().size());
assertEquals(0, sm.getSelectedItems().size());
assertEquals(0, sm.getSelectedIndices().size());
// select the first row
sm.select(0);
// we go to 2 here as all cells in the row become selected.
assertEquals(2, sm.getSelectedCells().size());
assertEquals(1, sm.getSelectedItems().size());
assertEquals(1, sm.getSelectedIndices().size());
// select the first cell - no change is expected
sm.select(0, table.getColumns().get(0));
assertEquals(2, sm.getSelectedCells().size());
assertEquals(1, sm.getSelectedItems().size());
assertEquals(1, sm.getSelectedIndices().size());
}
@Test public void test_rt38464_selectTests_cellSelection_singleSelection_selectsOneRow() {
test_rt38464_selectTests(true, true, true);
}
@Test public void test_rt38464_selectTests_cellSelection_singleSelection_selectsTwoRows() {
test_rt38464_selectTests(true, true, false);
}
@Test public void test_rt38464_selectTests_cellSelection_multipleSelection_selectsOneRow() {
test_rt38464_selectTests(true, false, true);
}
@Test public void test_rt38464_selectTests_cellSelection_multipleSelection_selectsTwoRows() {
test_rt38464_selectTests(true, false, false);
}
@Test public void test_rt38464_selectTests_rowSelection_singleSelection_selectsOneRow() {
test_rt38464_selectTests(false, true, true);
}
@Test public void test_rt38464_selectTests_rowSelection_singleSelection_selectsTwoRows() {
test_rt38464_selectTests(false, true, false);
}
@Test public void test_rt38464_selectTests_rowSelection_multipleSelection_selectsOneRow() {
test_rt38464_selectTests(false, false, true);
}
@Test public void test_rt38464_selectTests_rowSelection_multipleSelection_selectsTwoRows() {
test_rt38464_selectTests(false, false, false);
}
private void test_rt38464_selectTests(boolean cellSelection, boolean singleSelection, boolean selectsOneRow) {
TreeTableView<Person> table = test_rt_38464_createControl();
TreeTableView.TreeTableViewSelectionModel<Person> sm = table.getSelectionModel();
sm.setCellSelectionEnabled(cellSelection);
sm.setSelectionMode(singleSelection ? SelectionMode.SINGLE : SelectionMode.MULTIPLE);
// default selection when in cell selection mode
assertEquals(0, sm.getSelectedCells().size());
assertEquals(0, sm.getSelectedItems().size());
assertEquals(0, sm.getSelectedIndices().size());
if (selectsOneRow) {
sm.select(0);
} else {
// select the first two rows
sm.selectIndices(0, 1);
}
final int expectedCells = singleSelection ? 1 :
selectsOneRow && cellSelection ? 2 :
selectsOneRow && !cellSelection ? 1 :
!selectsOneRow && cellSelection ? 4 :
/* !selectsOneRow && !cellSelection */ 2;
final int expectedItems = singleSelection ? 1 :
selectsOneRow ? 1 : 2;
assertEquals(expectedCells, sm.getSelectedCells().size());
assertEquals(expectedItems, sm.getSelectedItems().size());
assertEquals(expectedItems, sm.getSelectedIndices().size());
// we expect the table column of all selected cells, in this instance,
// to be null as we have not explicitly stated a column, nor have we clicked
// on a column. The only alternative is to use the first column.
for (TreeTablePosition<?,?> tp : sm.getSelectedCells()) {
if (cellSelection) {
assertNotNull(tp.getTableColumn());
} else {
assertNull(tp.getTableColumn());
}
}
}
@Test public void test_rt_37853_replaceRoot() {
test_rt_37853(true);
}
@Test public void test_rt_37853_replaceRootChildren() {
test_rt_37853(false);
}
private int rt_37853_cancelCount;
private int rt_37853_commitCount;
public void test_rt_37853(boolean replaceRoot) {
TreeTableColumn<String,String> first = new TreeTableColumn<>("first");
first.setEditable(true);
first.setCellFactory(TextFieldTreeTableCell.forTreeTableColumn());
treeTableView.getColumns().add(first);
treeTableView.setEditable(true);
treeTableView.setRoot(new TreeItem<>("Root"));
treeTableView.getRoot().setExpanded(true);
for (int i = 0; i < 10; i++) {
treeTableView.getRoot().getChildren().add(new TreeItem<>("" + i));
}
StageLoader sl = new StageLoader(treeTableView);
first.setOnEditCancel(editEvent -> rt_37853_cancelCount++);
first.setOnEditCommit(editEvent -> rt_37853_commitCount++);
assertEquals(0, rt_37853_cancelCount);
assertEquals(0, rt_37853_commitCount);
treeTableView.edit(1, first);
assertNotNull(treeTableView.getEditingCell());
if (replaceRoot) {
treeTableView.setRoot(new TreeItem<>("New Root"));
} else {
treeTableView.getRoot().getChildren().clear();
for (int i = 0; i < 10; i++) {
treeTableView.getRoot().getChildren().add(new TreeItem<>("new item " + i));
}
}
assertEquals(1, rt_37853_cancelCount);
assertEquals(0, rt_37853_commitCount);
sl.dispose();
}
/**************************************************************************
*
* Tests (and related code) for RT-38892
*
*************************************************************************/
private final Supplier<TreeTableColumn<Person,String>> columnCallable = () -> {
TreeTableColumn<Person,String> column = new TreeTableColumn<>("Last Name");
column.setCellValueFactory(new TreeItemPropertyValueFactory<Person,String>("lastName"));
return column;
};
private TreeTableColumn<Person, String> test_rt_38892_firstNameCol;
private TreeTableColumn<Person, String> test_rt_38892_lastNameCol;
private TreeTableView<Person> init_test_rt_38892() {
ObservableList<TreeItem<Person>> persons = FXCollections.observableArrayList(
new TreeItem<>(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem<>(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem<>(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem<>(new Person("Emma", "Jones", "[email protected]")),
new TreeItem<>(new Person("Michael", "Brown", "[email protected]")));
TreeTableView<Person> table = new TreeTableView<>();
table.setShowRoot(false);
table.getSelectionModel().setCellSelectionEnabled(true);
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
TreeItem<Person> root = new TreeItem<>(new Person("Root", null, null));
root.setExpanded(true);
root.getChildren().setAll(persons);
table.setRoot(root);
test_rt_38892_firstNameCol = new TreeTableColumn<>("First Name");
test_rt_38892_firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<>("firstName"));
test_rt_38892_lastNameCol = columnCallable.get();
table.getColumns().addAll(test_rt_38892_firstNameCol, test_rt_38892_lastNameCol);
return table;
}
@Test public void test_rt_38892_focusMovesToLeftWhenPossible() {
TreeTableView<Person> table = init_test_rt_38892();
TreeTableView.TreeTableViewFocusModel<Person> fm = table.getFocusModel();
fm.focus(0, test_rt_38892_lastNameCol);
// assert pre-conditions
assertEquals(0, fm.getFocusedIndex());
assertEquals(0, fm.getFocusedCell().getRow());
assertEquals(test_rt_38892_lastNameCol, fm.getFocusedCell().getTableColumn());
assertEquals(1, fm.getFocusedCell().getColumn());
// now remove column where focus is and replace it with a new column.
// We expect focus to move to the left one cell.
table.getColumns().remove(1);
table.getColumns().add(columnCallable.get());
assertEquals(0, fm.getFocusedIndex());
assertEquals(0, fm.getFocusedCell().getRow());
assertEquals(test_rt_38892_firstNameCol, fm.getFocusedCell().getTableColumn());
assertEquals(0, fm.getFocusedCell().getColumn());
}
@Test public void test_rt_38892_removeLeftMostColumn() {
TreeTableView<Person> table = init_test_rt_38892();
TreeTableView.TreeTableViewFocusModel<Person> fm = table.getFocusModel();
fm.focus(0, test_rt_38892_firstNameCol);
// assert pre-conditions
assertEquals(0, fm.getFocusedIndex());
assertEquals(0, fm.getFocusedCell().getRow());
assertEquals(test_rt_38892_firstNameCol, fm.getFocusedCell().getTableColumn());
assertEquals(0, fm.getFocusedCell().getColumn());
// now remove column where focus is and replace it with a new column.
// In the current (non-specified) behavior, this results in focus being
// shifted to a cell in the remaining column, even when we add a new column
// as we index based on the column, not on its index.
table.getColumns().remove(0);
TreeTableColumn<Person,String> newColumn = columnCallable.get();
table.getColumns().add(0, newColumn);
assertEquals(0, fm.getFocusedIndex());
assertEquals(0, fm.getFocusedCell().getRow());
assertEquals(test_rt_38892_lastNameCol, fm.getFocusedCell().getTableColumn());
assertEquals(0, fm.getFocusedCell().getColumn());
}
@Test public void test_rt_38892_removeSelectionFromCellsInRemovedColumn() {
TreeTableView<Person> table = init_test_rt_38892();
TreeTableView.TreeTableViewSelectionModel sm = table.getSelectionModel();
sm.select(0, test_rt_38892_firstNameCol);
sm.select(1, test_rt_38892_lastNameCol); // this should go
sm.select(2, test_rt_38892_firstNameCol);
sm.select(3, test_rt_38892_lastNameCol); // so should this
sm.select(4, test_rt_38892_firstNameCol);
assertEquals(5, sm.getSelectedCells().size());
table.getColumns().remove(1);
assertEquals(3, sm.getSelectedCells().size());
assertTrue(sm.isSelected(0, test_rt_38892_firstNameCol));
assertFalse(sm.isSelected(1, test_rt_38892_lastNameCol));
assertTrue(sm.isSelected(2, test_rt_38892_firstNameCol));
assertFalse(sm.isSelected(3, test_rt_38892_lastNameCol));
assertTrue(sm.isSelected(4, test_rt_38892_firstNameCol));
}
@Test public void test_rt_38787_remove_b() {
// Remove 'b', selection moves to 'a'
test_rt_38787("a", 0, 1);
}
@Test public void test_rt_38787_remove_b_c() {
// Remove 'b' and 'c', selection moves to 'a'
test_rt_38787("a", 0, 1, 2);
}
@Test public void test_rt_38787_remove_c_d() {
// Remove 'c' and 'd', selection moves to 'b'
test_rt_38787("b", 1, 2, 3);
}
@Test public void test_rt_38787_remove_a() {
// Remove 'a', selection moves to 'b', now in index 0
test_rt_38787("b", 0, 0);
}
private void test_rt_38787(String expectedItem, int expectedIndex, int... indicesToRemove) {
TreeItem<String> a, b, c, d;
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
a = new TreeItem<String>("a"),
b = new TreeItem<String>("b"),
c = new TreeItem<String>("c"),
d = new TreeItem<String>("d")
);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
stringTreeTableView.setShowRoot(false);
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().add(column);
MultipleSelectionModel<TreeItem<String>> sm = stringTreeTableView.getSelectionModel();
sm.select(b);
// test pre-conditions
assertEquals(1, sm.getSelectedIndex());
assertEquals(1, (int)sm.getSelectedIndices().get(0));
assertEquals(b, sm.getSelectedItem());
assertEquals(b, sm.getSelectedItems().get(0));
assertFalse(sm.isSelected(0));
assertTrue(sm.isSelected(1));
assertFalse(sm.isSelected(2));
// removing items
List<TreeItem<String>> itemsToRemove = new ArrayList<>(indicesToRemove.length);
for (int index : indicesToRemove) {
itemsToRemove.add(root.getChildren().get(index));
}
root.getChildren().removeAll(itemsToRemove);
// testing against expectations
assertEquals(expectedIndex, sm.getSelectedIndex());
assertEquals(expectedIndex, (int)sm.getSelectedIndices().get(0));
assertEquals(expectedItem, sm.getSelectedItem().getValue());
assertEquals(expectedItem, sm.getSelectedItems().get(0).getValue());
}
private int rt_38341_indices_count = 0;
private int rt_38341_items_count = 0;
@Test public void test_rt_38341() {
Callback<Integer, TreeItem<String>> callback = number -> {
final TreeItem<String> root = new TreeItem<>("Root " + number);
final TreeItem<String> child = new TreeItem<>("Child " + number);
root.getChildren().add(child);
return root;
};
final TreeItem<String> root = new TreeItem<String>();
root.setExpanded(true);
root.getChildren().addAll(callback.call(1), callback.call(2));
final TreeTableView<String> treeTableView = new TreeTableView<>(root);
treeTableView.setShowRoot(false);
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
treeTableView.getColumns().add(column);
MultipleSelectionModel<TreeItem<String>> sm = treeTableView.getSelectionModel();
sm.getSelectedIndices().addListener((ListChangeListener<Integer>) c -> rt_38341_indices_count++);
sm.getSelectedItems().addListener((ListChangeListener<TreeItem<String>>) c -> rt_38341_items_count++);
assertEquals(0, rt_38341_indices_count);
assertEquals(0, rt_38341_items_count);
// expand the first child of root, and select it (note: root isn't visible)
root.getChildren().get(0).setExpanded(true);
sm.select(1);
assertEquals(1, sm.getSelectedIndex());
assertEquals(1, sm.getSelectedIndices().size());
assertEquals(1, (int)sm.getSelectedIndices().get(0));
assertEquals(1, sm.getSelectedItems().size());
assertEquals("Child 1", sm.getSelectedItem().getValue());
assertEquals("Child 1", sm.getSelectedItems().get(0).getValue());
assertEquals(1, rt_38341_indices_count);
assertEquals(1, rt_38341_items_count);
// now delete it
root.getChildren().get(0).getChildren().remove(0);
// selection should move to the childs parent in index 0
assertEquals(0, sm.getSelectedIndex());
assertEquals(1, sm.getSelectedIndices().size());
assertEquals(0, (int)sm.getSelectedIndices().get(0));
assertEquals(1, sm.getSelectedItems().size());
assertEquals("Root 1", sm.getSelectedItem().getValue());
assertEquals("Root 1", sm.getSelectedItems().get(0).getValue());
// we also expect there to be an event in the selection model for
// selected indices and selected items
assertEquals(2, rt_38341_indices_count);
assertEquals(2, rt_38341_items_count);
}
private int rt_38943_index_count = 0;
private int rt_38943_item_count = 0;
@Test public void test_rt_38943() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
new TreeItem<>("a"),
new TreeItem<>("b"),
new TreeItem<>("c"),
new TreeItem<>("d")
);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
stringTreeTableView.setShowRoot(false);
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().add(column);
MultipleSelectionModel<TreeItem<String>> sm = stringTreeTableView.getSelectionModel();
sm.selectedIndexProperty().addListener((observable, oldValue, newValue) -> rt_38943_index_count++);
sm.selectedItemProperty().addListener((observable, oldValue, newValue) -> rt_38943_item_count++);
assertEquals(-1, sm.getSelectedIndex());
assertNull(sm.getSelectedItem());
assertEquals(0, rt_38943_index_count);
assertEquals(0, rt_38943_item_count);
sm.select(0);
assertEquals(0, sm.getSelectedIndex());
assertEquals("a", sm.getSelectedItem().getValue());
assertEquals(1, rt_38943_index_count);
assertEquals(1, rt_38943_item_count);
sm.clearSelection(0);
assertEquals(-1, sm.getSelectedIndex());
assertNull(sm.getSelectedItem());
assertEquals(2, rt_38943_index_count);
assertEquals(2, rt_38943_item_count);
}
@Test public void test_rt_38884() {
final TreeItem<String> root = new TreeItem<>("Root");
final TreeItem<String> foo = new TreeItem<>("foo");
TreeTableView<String> treeView = new TreeTableView<>(root);
treeView.setShowRoot(false);
root.setExpanded(true);
treeView.getSelectionModel().getSelectedItems().addListener((ListChangeListener.Change<? extends TreeItem<String>> c) -> {
while (c.next()) {
if (c.wasRemoved()) {
assertTrue(c.getRemovedSize() > 0);
List<? extends TreeItem<String>> removed = c.getRemoved();
TreeItem<String> removedItem = null;
try {
removedItem = removed.get(0);
} catch (Exception e) {
fail();
}
assertEquals(foo, removedItem);
}
}
});
root.getChildren().add(foo);
treeView.getSelectionModel().select(0);
root.getChildren().clear();
}
private int rt_37360_add_count = 0;
private int rt_37360_remove_count = 0;
@Test public void test_rt_37360() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
new TreeItem<>("a"),
new TreeItem<>("b")
);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
stringTreeTableView.setShowRoot(false);
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().add(column);
MultipleSelectionModel<TreeItem<String>> sm = stringTreeTableView.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
sm.getSelectedItems().addListener((ListChangeListener<TreeItem<String>>) c -> {
while (c.next()) {
if (c.wasAdded()) {
rt_37360_add_count += c.getAddedSize();
}
if (c.wasRemoved()) {
rt_37360_remove_count += c.getRemovedSize();
}
}
});
assertEquals(0, sm.getSelectedItems().size());
assertEquals(0, rt_37360_add_count);
assertEquals(0, rt_37360_remove_count);
sm.select(0);
assertEquals(1, sm.getSelectedItems().size());
assertEquals(1, rt_37360_add_count);
assertEquals(0, rt_37360_remove_count);
sm.select(1);
assertEquals(2, sm.getSelectedItems().size());
assertEquals(2, rt_37360_add_count);
assertEquals(0, rt_37360_remove_count);
sm.clearAndSelect(1);
assertEquals(1, sm.getSelectedItems().size());
assertEquals(2, rt_37360_add_count);
assertEquals(1, rt_37360_remove_count);
}
private int rt_37366_count = 0;
@Test public void test_rt_37366() {
final TreeItem<String> treeItem2 = new TreeItem<>("Item 2");
treeItem2.getChildren().addAll(new TreeItem<>("Item 21"), new TreeItem<>("Item 22"));
final TreeItem<String> root1 = new TreeItem<>("Root Node 1");
TreeItem<String> treeItem1 = new TreeItem<>("Item 1");
root1.getChildren().addAll(treeItem1, treeItem2, new TreeItem<>("Item 3"));
root1.setExpanded(true);
final TreeItem<String> root2 = new TreeItem<>("Root Node 2");
final TreeItem<String> hiddenRoot = new TreeItem<>("Hidden Root Node");
hiddenRoot.getChildren().add(root1);
hiddenRoot.getChildren().add(root2);
final TreeTableView<String> treeView = new TreeTableView<>(hiddenRoot);
treeView.setShowRoot(false);
AtomicInteger step = new AtomicInteger();
MultipleSelectionModel<TreeItem<String>> sm = treeView.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
sm.getSelectedItems().addListener((ListChangeListener.Change<? extends TreeItem<String>> c) -> {
switch (step.get()) {
case 0: {
// we expect treeItem1 to be the only item added
while (c.next()) {
assertFalse(c.wasRemoved());
assertTrue(c.wasAdded());
assertEquals(1, c.getAddedSize());
assertTrue(c.getAddedSubList().contains(treeItem1));
}
break;
}
case 1: {
// we expect treeItem2 to be the only item added
while (c.next()) {
assertFalse(c.wasRemoved());
assertTrue(c.wasAdded());
assertEquals(1, c.getAddedSize());
assertTrue(c.getAddedSubList().contains(treeItem2));
}
break;
}
case 2: {
// we expect treeItem1 and treeItem2 to be removed in one separate event,
// and then we expect a separate event for root1 to be added. Therefore,
// once the remove event is received, we will increment the step to test for
// the addition
boolean wasRemoved = false;
while (c.next()) {
if (c.wasAdded()) {
fail("no addition expected yet");
}
if (c.wasRemoved()) {
assertTrue(c.getRemoved().containsAll(FXCollections.observableArrayList(treeItem1, treeItem2)));
wasRemoved = true;
}
}
if (!wasRemoved) {
fail("Expected a remove operation");
}
step.incrementAndGet();
break;
}
case 3: {
boolean wasAdded = false;
while (c.next()) {
if (c.wasAdded()) {
assertEquals(1, c.getAddedSize());
assertTrue(c.getAddedSubList().contains(root1));
wasAdded = true;
}
if (c.wasRemoved()) {
fail("no removal expected now");
}
}
if (!wasAdded) {
fail("Expected an add operation");
}
break;
}
}
rt_37366_count++;
});
assertEquals(0, rt_37366_count);
step.set(0);
sm.select(1); // select "Item 1"
assertEquals(1, rt_37366_count);
assertFalse(sm.isSelected(0));
assertTrue(sm.isSelected(1));
assertFalse(sm.isSelected(2));
step.set(1);
sm.select(2); // select "Item 2"
assertEquals(2, rt_37366_count);
assertFalse(sm.isSelected(0));
assertTrue(sm.isSelected(1));
assertTrue(sm.isSelected(2));
step.set(2);
root1.setExpanded(false); // collapse "Root Node 1" and deselect the two children, moving selection up to "Root Node 1"
assertEquals(4, rt_37366_count);
assertTrue(sm.isSelected(0));
assertFalse(sm.isSelected(1));
assertFalse(sm.isSelected(2));
}
@Test public void test_rt_38491() {
TreeItem<String> a;
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
a = new TreeItem<>("a"),
new TreeItem<>("b")
);
TreeTableView<String> stringTreeView = new TreeTableView<>(root);
stringTreeView.setShowRoot(false);
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeView.getColumns().add(column);
TreeTableView.TreeTableViewSelectionModel<String> sm = stringTreeView.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
TreeTableViewFocusModel<String> fm = stringTreeView.getFocusModel();
StageLoader sl = new StageLoader(stringTreeView);
// test pre-conditions
assertTrue(sm.isEmpty());
assertEquals(a, fm.getFocusedItem());
assertEquals(0, fm.getFocusedIndex());
// click on row 0
// VirtualFlowTestUtils.clickOnRow(stringTreeView, 0);
sm.select(0, column);
assertTrue(sm.isSelected(0));
assertEquals(a, sm.getSelectedItem());
assertTrue(fm.isFocused(0));
assertEquals(a, fm.getFocusedItem());
assertEquals(0, fm.getFocusedIndex());
assertEquals(0, fm.getFocusedCell().getRow());
assertEquals(column, fm.getFocusedCell().getTableColumn());
TreeTablePosition<String, ?> anchor = TreeTableCellBehavior.getAnchor(stringTreeView, null);
assertNotNull(anchor);
assertTrue(TreeTableCellBehavior.hasNonDefaultAnchor(stringTreeView));
assertEquals(0, anchor.getRow());
// now add a new item at row 0. This has the effect of pushing down
// the selected item into row 1.
root.getChildren().add(0, new TreeItem("z"));
// The first bug was that selection and focus were not moving down to
// be on row 1, so we test that now
assertFalse(sm.isSelected(0));
assertFalse(fm.isFocused(0));
assertTrue(sm.isSelected(1));
assertEquals(a, sm.getSelectedItem());
assertTrue(fm.isFocused(1));
assertEquals(a, fm.getFocusedItem());
assertEquals(1, fm.getFocusedIndex());
assertEquals(1, fm.getFocusedCell().getRow());
assertEquals(column, fm.getFocusedCell().getTableColumn());
// The second bug was that the anchor was not being pushed down as well
// (when it should).
anchor = TreeTableCellBehavior.getAnchor(stringTreeView, null);
assertNotNull(anchor);
assertTrue(TreeTableCellBehavior.hasNonDefaultAnchor(stringTreeView));
assertEquals(1, anchor.getRow());
assertEquals(column, anchor.getTableColumn());
sl.dispose();
}
private final ObservableList<TreeItem<String>> rt_39256_list = FXCollections.observableArrayList();
@Test public void test_rt_39256() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
new TreeItem<>("a"),
new TreeItem<>("b"),
new TreeItem<>("c"),
new TreeItem<>("d")
);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
stringTreeTableView.setShowRoot(false);
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().add(column);
MultipleSelectionModel<TreeItem<String>> sm = stringTreeTableView.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
// rt_39256_list.addListener((ListChangeListener<TreeItem<String>>) change -> {
// while (change.next()) {
// System.err.println("number of selected persons (in bound list): " + change.getList().size());
// }
// });
Bindings.bindContent(rt_39256_list, sm.getSelectedItems());
assertEquals(0, sm.getSelectedItems().size());
assertEquals(0, rt_39256_list.size());
sm.selectAll();
assertEquals(4, sm.getSelectedItems().size());
assertEquals(4, rt_39256_list.size());
sm.selectAll();
assertEquals(4, sm.getSelectedItems().size());
assertEquals(4, rt_39256_list.size());
sm.selectAll();
assertEquals(4, sm.getSelectedItems().size());
assertEquals(4, rt_39256_list.size());
}
private final ObservableList<TreeItem<String>> rt_39482_list = FXCollections.observableArrayList();
@Test public void test_rt_39482() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
new TreeItem<>("a"),
new TreeItem<>("b"),
new TreeItem<>("c"),
new TreeItem<>("d")
);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
stringTreeTableView.setShowRoot(false);
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().add(column);
TreeTableView.TreeTableViewSelectionModel<String> sm = stringTreeTableView.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
// rt_39256_list.addListener((ListChangeListener<TreeItem<String>>) change -> {
// while (change.next()) {
// System.err.println("number of selected persons (in bound list): " + change.getList().size());
// }
// });
Bindings.bindContent(rt_39482_list, sm.getSelectedItems());
assertEquals(0, sm.getSelectedItems().size());
assertEquals(0, rt_39482_list.size());
test_rt_39482_selectRow("a", sm, 0, column);
test_rt_39482_selectRow("b", sm, 1, column);
test_rt_39482_selectRow("c", sm, 2, column);
test_rt_39482_selectRow("d", sm, 3, column);
}
private void test_rt_39482_selectRow(String expectedString,
TreeTableView.TreeTableViewSelectionModel<String> sm,
int rowToSelect,
TreeTableColumn<String,String> columnToSelect) {
System.out.println("\nSelect row " + rowToSelect);
sm.selectAll();
assertEquals(4, sm.getSelectedCells().size());
assertEquals(4, sm.getSelectedIndices().size());
assertEquals(4, sm.getSelectedItems().size());
assertEquals(4, rt_39482_list.size());
sm.clearAndSelect(rowToSelect, columnToSelect);
assertEquals(1, sm.getSelectedCells().size());
assertEquals(1, sm.getSelectedIndices().size());
assertEquals(1, sm.getSelectedItems().size());
assertEquals(expectedString, sm.getSelectedItem().getValue());
assertEquals(expectedString, rt_39482_list.get(0).getValue());
assertEquals(1, rt_39482_list.size());
}
@Test public void test_rt_39559_useSM_selectAll() {
test_rt_39559(true);
}
@Test public void test_rt_39559_useKeyboard_selectAll() {
test_rt_39559(false);
}
private void test_rt_39559(boolean useSMSelectAll) {
TreeItem<String> a, b;
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
a = new TreeItem<>("a"),
b = new TreeItem<>("b"),
new TreeItem<>("c"),
new TreeItem<>("d")
);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
stringTreeTableView.setShowRoot(false);
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().add(column);
TreeTableView.TreeTableViewSelectionModel<String> sm = stringTreeTableView.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
StageLoader sl = new StageLoader(stringTreeTableView);
KeyEventFirer keyboard = new KeyEventFirer(stringTreeTableView);
assertEquals(0, sm.getSelectedItems().size());
sm.clearAndSelect(0);
if (useSMSelectAll) {
sm.selectAll();
} else {
keyboard.doKeyPress(KeyCode.A, KeyModifier.getShortcutKey());
}
assertEquals(4, sm.getSelectedItems().size());
assertEquals(0, ((TreeTablePosition) TreeTableCellBehavior.getAnchor(stringTreeTableView, null)).getRow());
keyboard.doKeyPress(KeyCode.DOWN, KeyModifier.SHIFT);
assertEquals(0, ((TreeTablePosition) TreeTableCellBehavior.getAnchor(stringTreeTableView, null)).getRow());
assertEquals(2, sm.getSelectedItems().size());
assertEquals(a, sm.getSelectedItems().get(0));
assertEquals(b, sm.getSelectedItems().get(1));
sl.dispose();
}
@Test public void test_rt_16068_firstElement_selectAndRemoveSameRow() {
// select and then remove the 'a' item, selection and focus should both
// stay at the first row, now 'b'
test_rt_16068(0, 0, 0);
}
@Test public void test_rt_16068_firstElement_selectRowAndRemoveLaterSibling() {
// select row 'a', and remove row 'c', selection and focus should not change
test_rt_16068(0, 2, 0);
}
@Test public void test_rt_16068_middleElement_selectAndRemoveSameRow() {
// select and then remove the 'b' item, selection and focus should both
// move up one row to the 'a' item
test_rt_16068(1, 1, 0);
}
@Test public void test_rt_16068_middleElement_selectRowAndRemoveLaterSibling() {
// select row 'b', and remove row 'c', selection and focus should not change
test_rt_16068(1, 2, 1);
}
@Test public void test_rt_16068_middleElement_selectRowAndRemoveEarlierSibling() {
// select row 'b', and remove row 'a', selection and focus should move up
// one row, remaining on 'b'
test_rt_16068(1, 0, 0);
}
@Test public void test_rt_16068_lastElement_selectAndRemoveSameRow() {
// select and then remove the 'd' item, selection and focus should both
// move up one row to the 'c' item
test_rt_16068(3, 3, 2);
}
@Test public void test_rt_16068_lastElement_selectRowAndRemoveEarlierSibling() {
// select row 'd', and remove row 'a', selection and focus should move up
// one row, remaining on 'd'
test_rt_16068(3, 0, 2);
}
private void test_rt_16068(int indexToSelect, int indexToRemove, int expectedIndex) {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
new TreeItem<>("a"), // 0
new TreeItem<>("b"), // 1
new TreeItem<>("c"), // 2
new TreeItem<>("d") // 3
);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
stringTreeTableView.setShowRoot(false);
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().add(column);
TreeTableView.TreeTableViewSelectionModel<String> sm = stringTreeTableView.getSelectionModel();
FocusModel<TreeItem<String>> fm = stringTreeTableView.getFocusModel();
sm.select(indexToSelect);
assertEquals(indexToSelect, sm.getSelectedIndex());
assertEquals(root.getChildren().get(indexToSelect).getValue(), sm.getSelectedItem().getValue());
assertEquals(indexToSelect, fm.getFocusedIndex());
assertEquals(root.getChildren().get(indexToSelect).getValue(), fm.getFocusedItem().getValue());
root.getChildren().remove(indexToRemove);
assertEquals(expectedIndex, sm.getSelectedIndex());
assertEquals(root.getChildren().get(expectedIndex).getValue(), sm.getSelectedItem().getValue());
assertEquals(debug(), expectedIndex, fm.getFocusedIndex());
assertEquals(root.getChildren().get(expectedIndex).getValue(), fm.getFocusedItem().getValue());
}
@Test public void test_rt_39675() {
TreeItem<String> b;
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
new TreeItem<>("a"),
b = new TreeItem<>("b"),
new TreeItem<>("c"),
new TreeItem<>("d")
);
b.setExpanded(true);
b.getChildren().addAll(
new TreeItem<>("b1"),
new TreeItem<>("b2"),
new TreeItem<>("b3"),
new TreeItem<>("b4")
);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
TreeTableColumn<String,String> column0 = new TreeTableColumn<>("Column1");
column0.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
TreeTableColumn<String,String> column1 = new TreeTableColumn<>("Column2");
column1.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
TreeTableColumn<String,String> column2 = new TreeTableColumn<>("Column3");
column2.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().addAll(column0, column1, column2);
sm = stringTreeTableView.getSelectionModel();
sm.setSelectionMode(SelectionMode.SINGLE);
sm.setCellSelectionEnabled(true);
StageLoader sl = new StageLoader(stringTreeTableView);
assertEquals(0, sm.getSelectedItems().size());
sm.clearAndSelect(4, column0); // select 'b2' in row 4, column 0
assertTrue(sm.isSelected(4, column0));
assertEquals(1, sm.getSelectedCells().size());
assertEquals("b2", ((TreeItem)sm.getSelectedItem()).getValue());
// collapse the 'b' tree item, selection and focus should go to
// the 'b' tree item in row 2, column 0
b.setExpanded(false);
assertTrue(sm.isSelected(2, column0));
assertEquals(1, sm.getSelectedCells().size());
assertEquals("b", ((TreeItem)sm.getSelectedItem()).getValue());
sl.dispose();
}
private ObservableList<String> test_rt_39661_setup() {
ObservableList<String> rawItems = FXCollections.observableArrayList(
"9-item", "8-item", "7-item", "6-item",
"5-item", "4-item", "3-item", "2-item", "1-item");
root = createSubTree("root", rawItems);
root.setExpanded(true);
treeTableView = new TreeTableView(root);
return rawItems;
}
private TreeItem createSubTree(Object item, ObservableList<String> rawItems) {
TreeItem child = new TreeItem(item);
child.getChildren().setAll(rawItems.stream()
.map(rawItem -> new TreeItem(rawItem))
.collect(Collectors.toList()));
return child;
}
@Test public void test_rt_39661_rowLessThanExpandedItemCount() {
ObservableList<String> rawItems = test_rt_39661_setup();
TreeItem child = createSubTree("child", rawItems);
TreeItem grandChild = (TreeItem) child.getChildren().get(rawItems.size() - 1);
root.getChildren().add(child);
assertTrue("row of item must be less than expandedItemCount, but was: " + treeTableView.getRow(grandChild),
treeTableView.getRow(grandChild) < treeTableView.getExpandedItemCount());
}
@Test public void test_rt_39661_rowOfGrandChildParentCollapsedUpdatedOnInsertAbove() {
ObservableList<String> rawItems = test_rt_39661_setup();
int grandIndex = 2;
int childIndex = 3;
TreeItem child = createSubTree("addedChild2", rawItems);
TreeItem grandChild = (TreeItem) child.getChildren().get(grandIndex);
root.getChildren().add(childIndex, child);
int rowOfGrand = treeTableView.getRow(grandChild);
root.getChildren().add(childIndex - 1, createSubTree("other", rawItems));
assertEquals(-1, treeTableView.getRow(grandChild));
}
@Test public void test_rt_39661_rowOfGrandChildParentCollapsedUpdatedOnInsertAboveWithoutAccess() {
ObservableList<String> rawItems = test_rt_39661_setup();
int grandIndex = 2;
int childIndex = 3;
TreeItem child = createSubTree("addedChild2", rawItems);
TreeItem grandChild = (TreeItem) child.getChildren().get(grandIndex);
root.getChildren().add(childIndex, child);
int rowOfGrand = 7; //treeTableView.getRow(grandChild);
root.getChildren().add(childIndex, createSubTree("other", rawItems));
assertEquals(-1, treeTableView.getRow(grandChild));
}
@Test public void test_rt_39661_rowOfGrandChildParentExpandedUpdatedOnInsertAbove() {
ObservableList<String> rawItems = test_rt_39661_setup();
int grandIndex = 2;
int childIndex = 3;
TreeItem child = createSubTree("addedChild2", rawItems);
TreeItem grandChild = (TreeItem) child.getChildren().get(grandIndex);
child.setExpanded(true);
root.getChildren().add(childIndex, child);
int rowOfGrand = treeTableView.getRow(grandChild);
root.getChildren().add(childIndex -1, createSubTree("other", rawItems));
assertEquals(rowOfGrand + 1, treeTableView.getRow(grandChild));
}
/**
* Testing getRow on grandChild: compare collapsed/expanded parent.
*/
@Test public void test_rt_39661_rowOfGrandChildDependsOnParentExpansion() {
ObservableList<String> rawItems = test_rt_39661_setup();
int grandIndex = 2;
int childIndex = 3;
TreeItem collapsedChild = createSubTree("addedChild", rawItems);
TreeItem collapsedGrandChild = (TreeItem) collapsedChild.getChildren().get(grandIndex);
root.getChildren().add(childIndex, collapsedChild);
int collapedGrandIndex = treeTableView.getRow(collapsedGrandChild);
int collapsedRowCount = treeTableView.getExpandedItemCount();
// start again
test_rt_39661_setup();
assertEquals(collapsedRowCount - 1, treeTableView.getExpandedItemCount());
TreeItem expandedChild = createSubTree("addedChild2", rawItems);
TreeItem expandedGrandChild = (TreeItem) expandedChild.getChildren().get(grandIndex);
expandedChild.setExpanded(true);
root.getChildren().add(childIndex, expandedChild);
assertNotSame("getRow must depend on expansionState " + collapedGrandIndex,
collapedGrandIndex, treeTableView.getRow(expandedGrandChild));
}
@Test public void test_rt_39661_rowOfGrandChildInCollapsedChild() {
ObservableList<String> rawItems = test_rt_39661_setup();
// create a collapsed new child to insert into the root
TreeItem newChild = createSubTree("added-child", rawItems);
TreeItem grandChild = (TreeItem) newChild.getChildren().get(2);
root.getChildren().add(6, newChild);
// query the row of a grand-child
int row = treeTableView.getRow(grandChild);
// grandChild not visible, row coordinate in tree is not available
assertEquals("grandChild not visible", -1, row);
// the other way round: if we get a row, expect the item at the row be the grandChild
if (row > -1) {
assertEquals(grandChild, treeTableView.getTreeItem(row));
}
}
@Test public void test_rt_39661_rowOfRootChild() {
ObservableList<String> rawItems = test_rt_39661_setup();
int index = 2;
TreeItem child = (TreeItem) root.getChildren().get(index);
assertEquals(index + 1, treeTableView.getRow(child));
}
@Test public void test_rt_39661_expandedItemCount() {
ObservableList<String> rawItems = test_rt_39661_setup();
int initialRowCount = treeTableView.getExpandedItemCount();
assertEquals(root.getChildren().size() + 1, initialRowCount);
TreeItem collapsedChild = createSubTree("collapsed-child", rawItems);
root.getChildren().add(collapsedChild);
assertEquals(initialRowCount + 1, treeTableView.getExpandedItemCount());
TreeItem expandedChild = createSubTree("expanded-child", rawItems);
expandedChild.setExpanded(true);
root.getChildren().add(0, expandedChild);
assertEquals(2 * initialRowCount + 1, treeTableView.getExpandedItemCount());
}
private int test_rt_39822_count = 0;
@Test public void test_rt_39822() {
// get the current exception handler before replacing with our own,
// as ListListenerHelp intercepts the exception otherwise
final Thread.UncaughtExceptionHandler exceptionHandler = Thread.currentThread().getUncaughtExceptionHandler();
Thread.currentThread().setUncaughtExceptionHandler((t, e) -> {
e.printStackTrace();
if (test_rt_39822_count == 0) {
test_rt_39822_count++;
if (! (e instanceof IllegalStateException)) {
fail("Incorrect exception type - expecting IllegalStateException");
}
} else {
// don't care
test_rt_39822_count++;
}
});
TreeTableView<String> table = new TreeTableView<>();
TreeTableColumn<String, String> col1 = new TreeTableColumn<>("Foo");
table.getColumns().addAll(col1, col1); // add column twice
StageLoader sl = null;
try {
sl = new StageLoader(table);
} finally {
if (sl != null) {
sl.dispose();
}
// reset the exception handler
Thread.currentThread().setUncaughtExceptionHandler(exceptionHandler);
}
}
private int test_rt_39842_count = 0;
@Test public void test_rt_39842_selectLeftDown() {
test_rt_39842(true, false);
}
@Test public void test_rt_39842_selectLeftUp() {
test_rt_39842(true, true);
}
@Test public void test_rt_39842_selectRightDown() {
test_rt_39842(false, false);
}
@Test public void test_rt_39842_selectRightUp() {
test_rt_39842(false, true);
}
private void test_rt_39842(boolean selectToLeft, boolean selectUpwards) {
test_rt_39842_count = 0;
TreeTableColumn firstNameCol = new TreeTableColumn("First Name");
firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("firstName"));
TreeTableColumn lastNameCol = new TreeTableColumn("Last Name");
lastNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person, String>("lastName"));
TreeItem root = new TreeItem("root");
root.getChildren().setAll(
new TreeItem(new Person("Jacob", "Smith", "[email protected]")),
new TreeItem(new Person("Isabella", "Johnson", "[email protected]")),
new TreeItem(new Person("Ethan", "Williams", "[email protected]")),
new TreeItem(new Person("Emma", "Jones", "[email protected]")),
new TreeItem(new Person("Michael", "Brown", "[email protected]")));
root.setExpanded(true);
TreeTableView<Person> table = new TreeTableView<>(root);
table.setShowRoot(false);
table.getColumns().addAll(firstNameCol, lastNameCol);
sm = table.getSelectionModel();
sm.setCellSelectionEnabled(true);
sm.setSelectionMode(SelectionMode.MULTIPLE);
sm.getSelectedCells().addListener((ListChangeListener) c -> test_rt_39842_count++);
StageLoader sl = new StageLoader(table);
assertEquals(0, test_rt_39842_count);
if (selectToLeft) {
if (selectUpwards) {
sm.selectRange(3, lastNameCol, 0, firstNameCol);
} else {
sm.selectRange(0, lastNameCol, 3, firstNameCol);
}
} else {
if (selectUpwards) {
sm.selectRange(3, firstNameCol, 0, lastNameCol);
} else {
sm.selectRange(0, firstNameCol, 3, lastNameCol);
}
}
// test model state
assertEquals(8, sm.getSelectedCells().size());
assertEquals(1, test_rt_39842_count);
// test visual state
for (int row = 0; row <= 3; row++) {
for (int column = 0; column <= 1; column++) {
IndexedCell cell = VirtualFlowTestUtils.getCell(table, row, column);
assertTrue(cell.isSelected());
}
}
sl.dispose();
}
@Test public void test_rt_22599() {
TreeItem<RT22599_DataType> root = new TreeItem<>();
root.getChildren().setAll(
new TreeItem<>(new RT22599_DataType(1, "row1")),
new TreeItem<>(new RT22599_DataType(2, "row2")),
new TreeItem<>(new RT22599_DataType(3, "row3")));
root.setExpanded(true);
TreeTableColumn<RT22599_DataType, String> col = new TreeTableColumn<>("Header");
col.setCellValueFactory(param -> new ReadOnlyStringWrapper(param.getValue().getValue().text));
TreeTableView<RT22599_DataType> table = new TreeTableView<>(root);
table.setShowRoot(false);
table.getColumns().addAll(col);
StageLoader sl = new StageLoader(table);
// testing initial state
assertNotNull(table.getSkin());
assertEquals("row1", VirtualFlowTestUtils.getCell(table, 0, 0).getText());
assertEquals("row2", VirtualFlowTestUtils.getCell(table, 1, 0).getText());
assertEquals("row3", VirtualFlowTestUtils.getCell(table, 2, 0).getText());
// change row 0 (where "row1" currently resides), keeping same id.
// Because 'set' is called, the control should update to the new content
// without any user interaction
TreeItem<RT22599_DataType> data;
root.getChildren().set(0, data = new TreeItem<>(new RT22599_DataType(0, "row1a")));
Toolkit.getToolkit().firePulse();
assertEquals("row1a", VirtualFlowTestUtils.getCell(table, 0, 0).getText());
// change the row 0 (where we currently have "row1a") value directly.
// Because there is no associated property, this won't be observed, so
// the control should still show "row1a" rather than "row1b"
data.getValue().text = "row1b";
Toolkit.getToolkit().firePulse();
assertEquals("row1a", VirtualFlowTestUtils.getCell(table, 0, 0).getText());
// call refresh() to force a refresh of all visible cells
table.refresh();
Toolkit.getToolkit().firePulse();
assertEquals("row1b", VirtualFlowTestUtils.getCell(table, 0, 0).getText());
sl.dispose();
}
private static class RT22599_DataType {
public int id = 0;
public String text = "";
public RT22599_DataType(int id, String text) {
this.id = id;
this.text = text;
}
@Override public boolean equals(Object obj) {
if (obj == null) return false;
return id == ((RT22599_DataType)obj).id;
}
}
private int rt_39966_count = 0;
@Test public void test_rt_39966() {
TreeItem<String> root = new TreeItem<>("Root");
TreeTableView<String> table = new TreeTableView<>(root);
table.setShowRoot(true);
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
table.getColumns().add(column);
StageLoader sl = new StageLoader(table);
// initially there is no selection
assertTrue(table.getSelectionModel().isEmpty());
table.getSelectionModel().selectedItemProperty().addListener((value, s1, s2) -> {
if (rt_39966_count == 0) {
rt_39966_count++;
assertFalse(table.getSelectionModel().isEmpty());
} else {
assertTrue(table.getSelectionModel().isEmpty());
}
});
// our assertion two lines down always succeeds. What fails is our
// assertion above within the listener.
table.getSelectionModel().select(0);
assertFalse(table.getSelectionModel().isEmpty());
table.setRoot(null);
assertTrue(table.getSelectionModel().isEmpty());
sl.dispose();
}
/**
* Bullet 1: selected index must be updated
* Corner case: last selected. Fails for core
*/
@Test public void test_rt_40012_selectedAtLastOnDisjointRemoveItemsAbove() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
new TreeItem<>("0"),
new TreeItem<>("1"),
new TreeItem<>("2"),
new TreeItem<>("3"),
new TreeItem<>("4"),
new TreeItem<>("5")
);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
stringTreeTableView.setShowRoot(false);
TreeTableView.TreeTableViewSelectionModel<String> sm = stringTreeTableView.getSelectionModel();
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().add(column);
int last = root.getChildren().size() - 1;
// selecting item "5"
sm.select(last);
// disjoint remove of 2 elements above the last selected
// Removing "1" and "3"
root.getChildren().removeAll(root.getChildren().get(1), root.getChildren().get(3));
// selection should move up two places such that it remains on item "5",
// but in index (last - 2).
int expected = last - 2;
assertEquals("5", sm.getSelectedItem().getValue());
assertEquals("selected index after disjoint removes above", expected, sm.getSelectedIndex());
}
/**
* Variant of 1: if selectedIndex is not updated,
* the old index is no longer valid
* for accessing the items.
*/
@Test public void test_rt_40012_accessSelectedAtLastOnDisjointRemoveItemsAbove() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
new TreeItem<>("0"),
new TreeItem<>("1"),
new TreeItem<>("2"),
new TreeItem<>("3"),
new TreeItem<>("4"),
new TreeItem<>("5")
);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
stringTreeTableView.setShowRoot(false);
TreeTableView.TreeTableViewSelectionModel<String> sm = stringTreeTableView.getSelectionModel();
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().add(column);
int last = root.getChildren().size() - 1;
// selecting item "5"
sm.select(last);
// disjoint remove of 2 elements above the last selected
root.getChildren().removeAll(root.getChildren().get(1), root.getChildren().get(3));
int selected = sm.getSelectedIndex();
if (selected > -1) {
root.getChildren().get(selected);
}
}
/**
* Bullet 2: selectedIndex notification count
*
* Note that we don't use the corner case of having the last index selected
* (which fails already on updating the index)
*/
private int rt_40012_count = 0;
@Test public void test_rt_40012_selectedIndexNotificationOnDisjointRemovesAbove() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
new TreeItem<>("0"),
new TreeItem<>("1"),
new TreeItem<>("2"),
new TreeItem<>("3"),
new TreeItem<>("4"),
new TreeItem<>("5")
);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
stringTreeTableView.setShowRoot(false);
TreeTableView.TreeTableViewSelectionModel<String> sm = stringTreeTableView.getSelectionModel();
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().add(column);
int last = root.getChildren().size() - 2;
sm.select(last);
assertEquals(last, sm.getSelectedIndex());
rt_40012_count = 0;
sm.selectedIndexProperty().addListener(o -> rt_40012_count++);
// disjoint remove of 2 elements above the last selected
root.getChildren().removeAll(root.getChildren().get(1), root.getChildren().get(3));
assertEquals("sanity: selectedIndex must be shifted by -2", last - 2, sm.getSelectedIndex());
assertEquals("must fire single event on removes above", 1, rt_40012_count);
}
/**
* Bullet 3: unchanged selectedItem must not fire change
*/
@Test
public void test_rt_40012_selectedItemNotificationOnDisjointRemovesAbove() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
new TreeItem<>("0"),
new TreeItem<>("1"),
new TreeItem<>("2"),
new TreeItem<>("3"),
new TreeItem<>("4"),
new TreeItem<>("5")
);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
stringTreeTableView.setShowRoot(false);
TreeTableView.TreeTableViewSelectionModel<String> sm = stringTreeTableView.getSelectionModel();
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().add(column);
int last = root.getChildren().size() - 2;
Object lastItem = root.getChildren().get(last);
sm.select(last);
assertEquals(lastItem, sm.getSelectedItem());
rt_40012_count = 0;
sm.selectedItemProperty().addListener(o -> rt_40012_count++);
// disjoint remove of 2 elements above the last selected
root.getChildren().removeAll(root.getChildren().get(1), root.getChildren().get(3));
assertEquals("sanity: selectedItem unchanged", lastItem, sm.getSelectedItem());
assertEquals("must not fire on unchanged selected item", 0, rt_40012_count);
}
private int rt_40010_count = 0;
@Test public void test_rt_40010() {
TreeItem<String> root = new TreeItem<>("Root");
TreeItem<String> child = new TreeItem<>("child");
root.setExpanded(true);
root.getChildren().addAll(child);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
TreeTableView.TreeTableViewSelectionModel<String> sm = stringTreeTableView.getSelectionModel();
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().add(column);
sm.getSelectedIndices().addListener((ListChangeListener<? super Integer>) l -> rt_40010_count++);
sm.getSelectedItems().addListener((ListChangeListener<? super TreeItem<String>>) l -> rt_40010_count++);
assertEquals(0, rt_40010_count);
sm.select(1);
assertEquals(1, sm.getSelectedIndex());
assertEquals(child, sm.getSelectedItem());
assertEquals(2, rt_40010_count);
root.getChildren().remove(child);
assertEquals(0, sm.getSelectedIndex());
assertEquals(root, sm.getSelectedItem());
assertEquals(4, rt_40010_count);
}
/**
* ClearAndSelect fires invalid change event if selectedIndex is unchanged.
*/
private int rt_40212_count = 0;
@Test public void test_rt_40212() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
new TreeItem<>("0"),
new TreeItem<>("1"),
new TreeItem<>("2"),
new TreeItem<>("3"),
new TreeItem<>("4"),
new TreeItem<>("5")
);
TreeTableView<String> stringTreeTableView = new TreeTableView<>(root);
stringTreeTableView.setShowRoot(false);
TreeTableView.TreeTableViewSelectionModel<String> sm = stringTreeTableView.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
TreeTableColumn<String,String> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
stringTreeTableView.getColumns().add(column);
sm.selectRange(3, 5);
int selected = sm.getSelectedIndex();
sm.getSelectedIndices().addListener((ListChangeListener<Integer>) change -> {
assertEquals("sanity: selectedIndex unchanged", selected, sm.getSelectedIndex());
while(change.next()) {
assertEquals("single event on clearAndSelect already selected", 1, ++rt_40212_count);
boolean type = change.wasAdded() || change.wasRemoved() || change.wasPermutated() || change.wasUpdated();
assertTrue("at least one of the change types must be true", type);
}
});
sm.clearAndSelect(selected);
}
@Test public void test_rt_40280() {
final TreeTableView<String> view = new TreeTableView<>();
StageLoader sl = new StageLoader(view);
MultipleSelectionModelBaseShim.getFocusedIndex(view.getSelectionModel());
view.getFocusModel().getFocusedIndex();
sl.dispose();
}
@Test public void test_rt_40278_showRoot() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(new TreeItem<>("0"),new TreeItem<>("1"));
TreeTableView<String> view = new TreeTableView<>(root);
view.setShowRoot(false);
MultipleSelectionModel<TreeItem<String>> sm = view.getSelectionModel();
assertFalse("sanity: test setup such that root is not showing", view.isShowRoot());
sm.select(0);
assertEquals(0, sm.getSelectedIndex());
assertEquals(view.getTreeItem(sm.getSelectedIndex()), sm.getSelectedItem());
view.setShowRoot(true);
assertEquals(1, sm.getSelectedIndex());
assertEquals(view.getTreeItem(sm.getSelectedIndex()), sm.getSelectedItem());
}
@Test public void test_rt_40278_hideRoot_selectionOnChild() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(new TreeItem<>("0"),new TreeItem<>("1"));
TreeTableView<String> view = new TreeTableView<>(root);
view.setShowRoot(true);
MultipleSelectionModel<TreeItem<String>> sm = view.getSelectionModel();
assertTrue("sanity: test setup such that root is showing", view.isShowRoot());
sm.select(1);
assertEquals(1, sm.getSelectedIndex());
assertEquals(view.getTreeItem(sm.getSelectedIndex()), sm.getSelectedItem());
view.setShowRoot(false);
assertEquals(0, sm.getSelectedIndex());
assertEquals(view.getTreeItem(sm.getSelectedIndex()), sm.getSelectedItem());
}
@Test public void test_rt_40278_hideRoot_selectionOnRoot() {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(new TreeItem<>("0"),new TreeItem<>("1"));
TreeTableView<String> view = new TreeTableView<>(root);
view.setShowRoot(true);
MultipleSelectionModel<TreeItem<String>> sm = view.getSelectionModel();
assertTrue("sanity: test setup such that root is showing", view.isShowRoot());
sm.select(0);
assertEquals(0, sm.getSelectedIndex());
assertEquals(view.getTreeItem(sm.getSelectedIndex()), sm.getSelectedItem());
view.setShowRoot(false);
assertEquals(0, sm.getSelectedIndex());
assertEquals(view.getTreeItem(sm.getSelectedIndex()), sm.getSelectedItem());
}
/**
* Test list change of selectedIndices on setIndices. Fails for core ..
*/
@Test public void test_rt_40263() {
TreeItem<Integer> root = new TreeItem<>(-1);
root.setExpanded(true);
for (int i = 0; i < 10; i++) {
root.getChildren().add(new TreeItem<Integer>(i));
}
final TreeTableView<Integer> view = new TreeTableView<>(root);
TreeTableView.TreeTableViewSelectionModel<Integer> sm = view.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
int[] indices = new int[]{2, 5, 7};
ListChangeListener<Integer> l = c -> {
// firstly, we expect only one change
int subChanges = 0;
while(c.next()) {
subChanges++;
}
assertEquals(1, subChanges);
// secondly, we expect the added size to be three, as that is the
// number of items selected
c.reset();
c.next();
System.out.println("Added items: " + c.getAddedSubList());
assertEquals(indices.length, c.getAddedSize());
assertArrayEquals(indices, c.getAddedSubList().stream().mapToInt(i -> i).toArray());
};
sm.getSelectedIndices().addListener(l);
sm.selectIndices(indices[0], indices);
}
@Test public void test_rt_40319_toRight_toBottom() { test_rt_40319(true, true, false); }
@Test public void test_rt_40319_toRight_toTop() { test_rt_40319(true, false, false); }
@Test public void test_rt_40319_toLeft_toBottom() { test_rt_40319(false, true, false); }
@Test public void test_rt_40319_toLeft_toTop() { test_rt_40319(false, false, false); }
@Test public void test_rt_40319_toRight_toBottom_useMouse() { test_rt_40319(true, true, true); }
@Test public void test_rt_40319_toRight_toTop_useMouse() { test_rt_40319(true, false, true); }
@Test public void test_rt_40319_toLeft_toBottom_useMouse() { test_rt_40319(false, true, true); }
@Test public void test_rt_40319_toLeft_toTop_useMouse() { test_rt_40319(false, false, true); }
private void test_rt_40319(boolean toRight, boolean toBottom, boolean useMouse) {
TreeItem<String> root = new TreeItem<>("Root");
root.setExpanded(true);
root.getChildren().addAll(
new TreeItem<>("0"),
new TreeItem<>("1"),
new TreeItem<>("2"),
new TreeItem<>("3"),
new TreeItem<>("4"),
new TreeItem<>("5")
);
TreeTableView<String> t = new TreeTableView<>(root);
t.setShowRoot(false);
sm = t.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
TreeTableColumn<String,String> c1 = new TreeTableColumn<>("Column");
c1.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
TreeTableColumn<String,String> c2 = new TreeTableColumn<>("Column");
c2.setCellValueFactory(cdf -> new ReadOnlyStringWrapper(cdf.getValue().getValue()));
t.getColumns().addAll(c1, c2);
final int startIndex = toRight ? 0 : 2;
final int endIndex = toRight ? 2 : 0;
final TreeTableColumn<String,String> startColumn = toBottom ? c1 : c2;
final TreeTableColumn<String,String> endColumn = toBottom ? c2 : c1;
sm.select(startIndex, startColumn);
if (useMouse) {
Cell endCell = VirtualFlowTestUtils.getCell(t, endIndex, toRight ? 1 : 0);
MouseEventFirer mouse = new MouseEventFirer(endCell);
mouse.fireMousePressAndRelease(KeyModifier.SHIFT);
} else {
t.getSelectionModel().selectRange(startIndex, startColumn, endIndex, endColumn);
}
assertEquals(3, sm.getSelectedItems().size());
assertEquals(3, sm.getSelectedIndices().size());
assertEquals(3, sm.getSelectedCells().size());
}
@Test public void test_jdk_8147483() {
TreeItem<Number> root = new TreeItem<>(0);
root.setExpanded(true);
final TreeTableView<Number> view = new TreeTableView<>(root);
view.setShowRoot(false);
AtomicInteger cellUpdateCount = new AtomicInteger();
AtomicInteger rowCreateCount = new AtomicInteger();
TreeTableColumn<Number, Number> column = new TreeTableColumn<>("Column");
column.setCellValueFactory(cdf -> new ReadOnlyIntegerWrapper(0));
column.setCellFactory( ttc -> new TreeTableCell<Number,Number>() {
@Override protected void updateItem(Number item, boolean empty) {
cellUpdateCount.incrementAndGet();
super.updateItem(item, empty);
}
});
view.getColumns().add(column);
view.setRowFactory(t -> {
rowCreateCount.incrementAndGet();
return new TreeTableRow<>();
});
assertEquals(0, cellUpdateCount.get());
assertEquals(0, rowCreateCount.get());
StageLoader sl = new StageLoader(view);
// Before the fix, we got cellUpdateCount = 18 and rowCreateCount = 17 for the first add below.
// After the second add, these numbers went to 53 and 17 respectively.
// Because these numbers might differ on other systems, we simply record the values after
// the first add, and then we expect the cellUpdateCount to increase by one, and rowCreateCount to
// not increase at all.
root.getChildren().add(new TreeItem(1));
Toolkit.getToolkit().firePulse();
final int firstCellUpdateCount = cellUpdateCount.get();
final int firstRowCreateCount = rowCreateCount.get();
root.getChildren().add(new TreeItem(2));
Toolkit.getToolkit().firePulse();
assertEquals(firstCellUpdateCount+1, cellUpdateCount.get());
assertEquals(firstRowCreateCount, rowCreateCount.get());
root.getChildren().add(new TreeItem(3));
Toolkit.getToolkit().firePulse();
assertEquals(firstCellUpdateCount+2, cellUpdateCount.get());
assertEquals(firstRowCreateCount, rowCreateCount.get());
sl.dispose();
}
@Test public void test_jdk_8144681_removeColumn() {
TreeTableView<Book> table = new TreeTableView<>();
TreeItem<Book> root = new TreeItem<>();
root.getChildren().addAll(
new TreeItem<>(new Book("Book 1", "Author 1", "Remark 1"))
, new TreeItem<>(new Book("Book 2", "Author 2", "Remark 2"))
, new TreeItem<>(new Book("Book 3", "Author 3", "Remark 3"))
, new TreeItem<>(new Book("Book 4", "Author 4", "Remark 4")));
table.setRoot(root);
String[] columns = { "title", "author", "remark" };
for (String prop : columns) {
TreeTableColumn<Book, String> col = new TreeTableColumn<>(prop);
col.setCellValueFactory(new TreeItemPropertyValueFactory<>(prop));
table.getColumns().add(col);
}
table.setColumnResizePolicy(TreeTableView.UNCONSTRAINED_RESIZE_POLICY);
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
table.getSelectionModel().setCellSelectionEnabled(true);
table.getSelectionModel().selectAll();
ControlTestUtils.runWithExceptionHandler(() -> table.getColumns().remove(2));
}
@Test public void test_jdk_8144681_moveColumn() {
TreeTableView<Book> table = new TreeTableView<>();
TreeItem<Book> root = new TreeItem<>();
root.getChildren().addAll(
new TreeItem<>(new Book("Book 1", "Author 1", "Remark 1"))
, new TreeItem<>(new Book("Book 2", "Author 2", "Remark 2"))
, new TreeItem<>(new Book("Book 3", "Author 3", "Remark 3"))
, new TreeItem<>(new Book("Book 4", "Author 4", "Remark 4")));
table.setRoot(root);
String[] columns = { "title", "author", "remark" };
for (String prop : columns) {
TreeTableColumn<Book, String> col = new TreeTableColumn<>(prop);
col.setCellValueFactory(new TreeItemPropertyValueFactory<>(prop));
table.getColumns().add(col);
}
table.setColumnResizePolicy(TreeTableView.UNCONSTRAINED_RESIZE_POLICY);
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
table.getSelectionModel().setCellSelectionEnabled(true);
table.getSelectionModel().selectAll();
ControlTestUtils.runWithExceptionHandler(() -> {
table.getColumns().setAll(table.getColumns().get(0), table.getColumns().get(2), table.getColumns().get(1));
});
}
private static class Book {
private SimpleStringProperty title = new SimpleStringProperty();
private SimpleStringProperty author = new SimpleStringProperty();
private SimpleStringProperty remark = new SimpleStringProperty();
public Book(String title, String author, String remark) {
super();
setTitle(title);
setAuthor(author);
setRemark(remark);
}
public SimpleStringProperty titleProperty() {
return this.title;
}
public java.lang.String getTitle() {
return this.titleProperty().get();
}
public void setTitle(final java.lang.String title) {
this.titleProperty().set(title);
}
public SimpleStringProperty authorProperty() {
return this.author;
}
public java.lang.String getAuthor() {
return this.authorProperty().get();
}
public void setAuthor(final java.lang.String author) {
this.authorProperty().set(author);
}
public SimpleStringProperty remarkProperty() {
return this.remark;
}
public java.lang.String getRemark() {
return this.remarkProperty().get();
}
public void setRemark(final java.lang.String remark) {
this.remarkProperty().set(remark);
}
@Override
public String toString() {
return String.format("%s(%s) - %s", getTitle(), getAuthor(), getRemark());
}
}
@Test public void test_jdk_8157205() {
final TreeItem<String> childNode1 = new TreeItem<>("Child Node 1");
childNode1.setExpanded(true);
TreeItem<String> item1 = new TreeItem<>("Node 1-1");
TreeItem<String> item2 = new TreeItem<>("Node 1-2");
childNode1.getChildren().addAll(item1, item2);
final TreeItem<String> root = new TreeItem<>("Root node");
root.setExpanded(true);
root.getChildren().add(childNode1);
final TreeTableView<String> view = new TreeTableView<>(root);
MultipleSelectionModel<TreeItem<String>> sm = view.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
AtomicInteger step = new AtomicInteger();
AtomicInteger indicesEventCount = new AtomicInteger();
sm.getSelectedIndices().addListener((ListChangeListener<Integer>)c -> {
switch (step.get()) {
case 0: {
// expect to see [1,2,3] added at index 0
c.next();
assertEquals(3, c.getAddedSize());
assertTrue("added: " + c.getAddedSubList(),
c.getAddedSubList().containsAll(FXCollections.observableArrayList(1,2,3)));
assertEquals(0, c.getFrom());
break;
}
case 1: {
// expect to see [2,3] removed
List<Integer> removed = new ArrayList<>();
while (c.next()) {
if (c.wasRemoved()) {
removed.addAll(c.getRemoved());
} else {
fail("Unexpected state");
}
}
if (!removed.isEmpty()) {
assertTrue(removed.containsAll(FXCollections.observableArrayList(2,3)));
}
break;
}
}
indicesEventCount.incrementAndGet();
});
AtomicInteger itemsEventCount = new AtomicInteger();
sm.getSelectedItems().addListener((ListChangeListener<TreeItem<String>>)c -> {
switch (step.get()) {
case 0: {
// expect to see [1,2,3] added at index 0
c.next();
assertEquals(3, c.getAddedSize());
assertTrue("added: " + c.getAddedSubList(),
c.getAddedSubList().containsAll(FXCollections.observableArrayList(childNode1, item1, item2)));
assertEquals(0, c.getFrom());
break;
}
case 1: {
// expect to see [2,3] removed
List<TreeItem<String>> removed = new ArrayList<>();
while (c.next()) {
if (c.wasRemoved()) {
removed.addAll(c.getRemoved());
} else {
fail("Unexpected state");
}
}
if (!removed.isEmpty()) {
assertTrue(removed.containsAll(FXCollections.observableArrayList(item1, item2)));
}
break;
}
}
itemsEventCount.incrementAndGet();
});
assertEquals(0, indicesEventCount.get());
assertEquals(0, itemsEventCount.get());
step.set(0);
sm.selectIndices(1,2,3); // select Child Node 1 and both children
assertTrue(sm.isSelected(1));
assertTrue(sm.isSelected(2));
assertTrue(sm.isSelected(3));
assertEquals(3, sm.getSelectedIndices().size());
assertEquals(3, sm.getSelectedItems().size());
assertEquals(1, indicesEventCount.get());
assertEquals(1, itemsEventCount.get());
step.set(1);
System.out.println("about to collapse now");
childNode1.setExpanded(false); // collapse Child Node 1 and expect both children to be deselected
assertTrue(sm.isSelected(1));
assertFalse(sm.isSelected(2));
assertFalse(sm.isSelected(3));
assertEquals(1, sm.getSelectedIndices().size());
assertEquals(1, sm.getSelectedItems().size());
assertEquals(2, indicesEventCount.get());
assertEquals(2, itemsEventCount.get());
step.set(2);
childNode1.setExpanded(true); // expand Child Node 1 and expect both children to still be deselected
assertTrue(sm.isSelected(1));
assertFalse(sm.isSelected(2));
assertFalse(sm.isSelected(3));
assertEquals(1, sm.getSelectedIndices().size());
assertEquals(1, sm.getSelectedItems().size());
assertEquals(2, indicesEventCount.get());
assertEquals(2, itemsEventCount.get());
}
@Test public void test_jdk_8157285() {
final TreeItem<String> childNode1 = new TreeItem<>("Child Node 1");
childNode1.setExpanded(true);
TreeItem<String> item1 = new TreeItem<>("Node 1-1");
TreeItem<String> item2 = new TreeItem<>("Node 1-2");
childNode1.getChildren().addAll(item1, item2);
final TreeItem<String> root = new TreeItem<>("Root node");
root.setExpanded(true);
root.getChildren().add(childNode1);
final TreeTableView<String> view = new TreeTableView<>(root);
MultipleSelectionModel<TreeItem<String>> sm = view.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
view.expandedItemCountProperty().addListener((observable, oldCount, newCount) -> {
if (childNode1.isExpanded()) return;
System.out.println(sm.getSelectedIndices());
System.out.println(sm.getSelectedItems());
assertTrue(sm.isSelected(1));
assertFalse(sm.isSelected(2));
assertFalse(sm.isSelected(3));
assertEquals(1, sm.getSelectedIndices().size());
assertEquals(1, sm.getSelectedItems().size());
});
sm.selectIndices(1,2,3); // select Child Node 1 and both children
assertTrue(sm.isSelected(1));
assertTrue(sm.isSelected(2));
assertTrue(sm.isSelected(3));
assertEquals(3, sm.getSelectedIndices().size());
assertEquals(3, sm.getSelectedItems().size());
// collapse Child Node 1 and expect both children to be deselected,
// and that in the expandedItemCount listener that we get the right values
// in the selectedIndices and selectedItems list
childNode1.setExpanded(false);
}
@Test public void test_jdk_8152396() {
final TreeItem<String> childNode1 = new TreeItem<>("Child Node 1");
TreeItem<String> item1 = new TreeItem<>("Node 1-1");
TreeItem<String> item2 = new TreeItem<>("Node 1-2");
childNode1.getChildren().addAll(item1, item2);
final TreeItem<String> root = new TreeItem<>("Root node");
root.setExpanded(true);
root.getChildren().add(childNode1);
final TreeTableView<String> view = new TreeTableView<>(root);
MultipleSelectionModel<TreeItem<String>> sm = view.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
view.expandedItemCountProperty().addListener((observable, oldCount, newCount) -> {
if (newCount.intValue() > oldCount.intValue()) {
for (int index: sm.getSelectedIndices()) {
TreeItem<String> item = view.getTreeItem(index);
if (item != null && item.isExpanded() && !item.getChildren().isEmpty()) {
int startIndex = index + 1;
int maxCount = startIndex + item.getChildren().size();
sm.selectRange(startIndex, maxCount);
}
}
}
});
FilteredList filteredList = sm.getSelectedItems().filtered(Objects::nonNull);
StageLoader sl = new StageLoader(view);
sm.select(1);
childNode1.setExpanded(true);
Toolkit.getToolkit().firePulse();
// collapse Child Node 1 and expect both children to be deselected,
// and that the filtered list does not throw an exception
assertEquals(3, filteredList.size());
ControlTestUtils.runWithExceptionHandler(() -> childNode1.setExpanded(false));
Toolkit.getToolkit().firePulse();
assertEquals(1, filteredList.size());
sl.dispose();
}
@Test public void test_jdk_8160771() {
TreeTableView table = new TreeTableView();
TreeTableColumn first = new TreeTableColumn("First Name");
table.getColumns().add(first);
table.getVisibleLeafColumns().addListener((ListChangeListener) c -> {
c.next();
assertTrue(c.wasAdded());
assertSame(table, ((TreeTableColumn) c.getAddedSubList().get(0)).getTreeTableView());
});
TreeTableColumn last = new TreeTableColumn("Last Name");
table.getColumns().add(0, last);
}
private void test_jdk_8169642(Consumer<TreeTableView.TreeTableViewSelectionModel> before,
Consumer<TreeTableView.TreeTableViewSelectionModel> afterDescending,
Consumer<TreeTableView.TreeTableViewSelectionModel> afterAscending) {
final TreeItem<String> rootItem = new TreeItem<>("root");
rootItem.setExpanded(true);
rootItem.getChildren().addAll(new TreeItem<>("first child"), new TreeItem<>("second child"), new TreeItem<>("third child"));
final TreeTableView<String> tree = new TreeTableView<>(rootItem);
final TreeTableColumn<String, String> column = new TreeTableColumn<>("first column");
column.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getValue()));
tree.getColumns().add(column);
TreeTableView.TreeTableViewSelectionModel sm = tree.getSelectionModel();
sm.setSelectionMode(SelectionMode.MULTIPLE);
assertTrue(sm.isEmpty());
before.accept(sm);
tree.getSortOrder().add(column);
column.setSortType(TreeTableColumn.SortType.DESCENDING);
afterDescending.accept(sm);
column.setSortType(TreeTableColumn.SortType.ASCENDING);
afterAscending.accept(sm);
}
@Test public void test_jdk_8169642_1_only() {
test_jdk_8169642(
sm -> {
// select 'first'
sm.select(1);
assertTrue(sm.isSelected(1));
assertEquals(1, sm.getSelectedCells().size());
},
sm -> {
assertTrue(sm.isSelected(3));
assertEquals(1, sm.getSelectedCells().size());
},
sm -> {
assertTrue(sm.isSelected(1));
assertEquals(1, sm.getSelectedCells().size());
}
);
}
@Test public void test_jdk_8169642_2_only() {
test_jdk_8169642(
sm -> {
// select 'second'
sm.select(2);
assertTrue(sm.isSelected(2));
assertEquals(1, sm.getSelectedCells().size());
},
sm -> {
assertTrue(sm.isSelected(2));
assertEquals(1, sm.getSelectedCells().size());
},
sm -> {
assertTrue(sm.isSelected(2));
assertEquals(1, sm.getSelectedCells().size());
}
);
}
@Test public void test_jdk_8169642_1_and_3() {
test_jdk_8169642(
sm -> {
// select 'first' and 'third', they should flip positions
sm.select(1);
sm.select(3);
assertTrue(sm.isSelected(1));
assertTrue(sm.isSelected(3));
assertEquals(2, sm.getSelectedCells().size());
},
sm -> {
assertTrue(sm.isSelected(1));
assertTrue(sm.isSelected(3));
assertEquals(2, sm.getSelectedCells().size());
},
sm -> {
assertTrue(sm.isSelected(1));
assertTrue(sm.isSelected(3));
assertEquals(2, sm.getSelectedCells().size());
}
);
}
@Test public void test_jdk_8169642_0_and_3() {
test_jdk_8169642(
sm -> {
// select 'root' and 'third'
sm.select(0);
sm.select(3);
assertTrue(sm.isSelected(0));
assertTrue(sm.isSelected(3));
assertEquals(2, sm.getSelectedCells().size());
},
sm -> {
assertTrue(sm.isSelected(0));
assertTrue(sm.isSelected(1));
assertEquals(2, sm.getSelectedCells().size());
},
sm -> {
assertTrue(sm.isSelected(0));
assertTrue(sm.isSelected(3));
assertEquals(2, sm.getSelectedCells().size());
}
);
}
}
|
teamfx/openjfx-9-dev-rt
|
modules/javafx.controls/src/test/java/test/javafx/scene/control/TreeTableViewTest.java
|
Java
|
gpl-2.0
| 266,209 |
/* Translators (2009 onwards):
* - City-busz
* - Glanthor Reviol
*/
/**
* @requires OpenLayers/Lang.js
*/
/**
* Namespace: OpenLayers.Lang["hu"]
* Dictionary for Magyar. Keys for entries are used in calls to
* <OpenLayers.Lang.translate>. Entry bodies are normal strings or
* strings formatted for use with <OpenLayers.String.format> calls.
*/
OpenLayers.Lang["hu"] = OpenLayers.Util.applyDefaults({
'unhandledRequest': "Nem kezelt kérés visszatérése ${statusText}",
'permalink': "Permalink",
'overlays': "Rávetítések",
'baseLayer': "Alapréteg",
'sameProjection': "Az áttekintő térkép csak abban az esetben működik, ha ugyanazon a vetületen van, mint a fő térkép.",
'readNotImplemented': "Olvasás nincs végrehajtva.",
'writeNotImplemented': "Írás nincs végrehajtva.",
'noFID': "Nem frissíthető olyan jellemző, amely nem rendelkezik FID-del.",
'errorLoadingGML': "Hiba GML-fájl betöltésekor ${url}",
'browserNotSupported': "A böngészője nem támogatja a vektoros renderelést. A jelenleg támogatott renderelők:\n${renderers}",
'componentShouldBe': "addFeatures : az összetevőnek ilyen típusúnak kell lennie: ${geomType}",
'getFeatureError': "getFeatureFromEvent réteget hívott meg renderelő nélkül. Ez rendszerint azt jelenti, hogy megsemmisített egy fóliát, de néhány ahhoz társított kezelőt nem.",
'minZoomLevelError': "A minZoomLevel tulajdonságot csak a következővel való használatra szánták: FixedZoomLevels-leszármazott fóliák. Ez azt jelenti, hogy a minZoomLevel wfs fólia jelölőnégyzetei már a múlté. Mi azonban nem távolíthatjuk el annak a veszélye nélkül, hogy az esetlegesen ettől függő OL alapú alkalmazásokat tönkretennénk. Ezért ezt érvénytelenítjük -- a minZoomLevel az alul levő jelölőnégyzet a 3.0-s verzióból el lesz távolítva. Kérjük, helyette használja a min/max felbontás beállítást, amelyről az alábbi helyen talál leírást: http://trac.openlayers.org/wiki/SettingZoomLevels",
'commitSuccess': "WFS tranzakció: SIKERES ${response}",
'commitFailed': "WFS tranzakció: SIKERTELEN ${response}",
'googleWarning': "A Google fólia betöltése sikertelen.\x3cbr\x3e\x3cbr\x3eAhhoz, hogy ez az üzenet eltűnjön, válasszon egy új BaseLayer fóliát a jobb felső sarokban található fóliakapcsoló segítségével.\x3cbr\x3e\x3cbr\x3eNagy valószínűséggel ez azért van, mert a Google Maps könyvtár parancsfájlja nem található, vagy nem tartalmazza az Ön oldalához tartozó megfelelő API-kulcsot.\x3cbr\x3e\x3cbr\x3eFejlesztőknek: A helyes működtetésre vonatkozó segítség az alábbi helyen érhető el, \x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3ekattintson ide\x3c/a\x3e",
'getLayerWarning': "A(z) ${layerType} fólia nem töltődött be helyesen.\x3cbr\x3e\x3cbr\x3eAhhoz, hogy ez az üzenet eltűnjön, válasszon egy új BaseLayer fóliát a jobb felső sarokban található fóliakapcsoló segítségével.\x3cbr\x3e\x3cbr\x3eNagy valószínűséggel ez azért van, mert a(z) ${layerLib} könyvtár parancsfájlja helytelen.\x3cbr\x3e\x3cbr\x3eFejlesztőknek: A helyes működtetésre vonatkozó segítség az alábbi helyen érhető el, \x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3ekattintson ide\x3c/a\x3e",
'scale': "Lépték = 1 : ${scaleDenom}",
'W': "Ny",
'E': "K",
'N': "É",
'S': "D",
'layerAlreadyAdded': "Megpróbálta hozzáadni a(z) ${layerName} fóliát a térképhez, de az már hozzá van adva",
'reprojectDeprecated': "Ön a \'reproject\' beállítást használja a(z) ${layerName} fólián. Ez a beállítás érvénytelen: használata az üzleti alaptérképek fölötti adatok megjelenítésének támogatására szolgált, de ezt a funkció ezentúl a Gömbi Mercator használatával érhető el. További információ az alábbi helyen érhető el: http://trac.openlayers.org/wiki/SphericalMercator",
'methodDeprecated': "Ez a módszer érvénytelenítve lett és a 3.0-s verzióból el lesz távolítva. Használja a(z) ${newMethod} módszert helyette.",
'boundsAddError': "Az x és y értékeknek egyaránt meg kell felelnie, hogy a funkciót hozzáadhassa.",
'lonlatAddError': "A hossz. és szél. értékeknek egyaránt meg kell felelnie, hogy a funkciót hozzáadhassa.",
'pixelAddError': "Az x és y értékeknek egyaránt meg kell felelnie, hogy a funkciót hozzáadhassa.",
'unsupportedGeometryType': "Nem támogatott geometriatípus: ${geomType}",
'pagePositionFailed': "OpenLayers.Util.pagePosition sikertelen: lehetséges, hogy a(z) ${elemId} azonosítójú elem téves helyre került.",
'filterEvaluateNotImplemented': "ennél a szűrőtípusnál kiértékelés nem hajtódik végre."
});
|
blahoink/grassroots
|
phpmyadmin/js/openlayers/src/openlayers/lib/OpenLayers/Lang/hu.js
|
JavaScript
|
gpl-2.0
| 4,996 |
<?php
/*
License: GPLv3
License URI: http://www.gnu.org/licenses/gpl.txt
Copyright 2012-2014 - Jean-Sebastien Morisset - http://surniaulula.com/
*/
if ( ! defined( 'ABSPATH' ) )
die( 'These aren\'t the droids you\'re looking for...' );
if ( ! class_exists( 'NgfbOptionsUpgrade' ) && class_exists( 'NgfbOptions' ) ) {
class NgfbOptionsUpgrade extends NgfbOptions {
private $renamed_site_keys = array(
'plugin_tid_use' => 'plugin_ngfb_tid:use',
'plugin_tid:use' => 'plugin_ngfb_tid:use',
'plugin_tid' => 'plugin_ngfb_tid',
);
private $renamed_keys = array(
'og_def_img' => 'og_def_img_url',
'og_def_home' => 'og_def_img_on_index',
'og_def_on_home' => 'og_def_img_on_index',
'og_def_on_search' => 'og_def_img_on_search',
'buttons_on_home' => 'buttons_on_index',
'buttons_lang' => 'gp_lang',
'ngfb_cache_hours' => 'plugin_file_cache_hrs',
'fb_enable' => 'fb_on_content',
'gp_enable' => 'gp_on_content',
'twitter_enable' => 'twitter_on_content',
'linkedin_enable' => 'linkedin_on_content',
'pin_enable' => 'pin_on_content',
'stumble_enable' => 'stumble_on_content',
'tumblr_enable' => 'tumblr_on_content',
'buttons_location' => 'buttons_pos_content',
'plugin_pro_tid' => 'plugin_ngfb_tid',
'og_admins' => 'fb_admins',
'og_app_id' => 'fb_app_id',
'link_desc_len' => 'seo_desc_len',
'ngfb_version' => 'plugin_version',
'ngfb_opts_ver' => 'options_version',
'ngfb_pro_tid' => 'plugin_ngfb_tid',
'ngfb_preserve' => 'plugin_preserve',
'ngfb_debug' => 'plugin_debug',
'ngfb_enable_shortcode' => 'plugin_shortcodes',
'ngfb_skip_small_img' => 'plugin_ignore_small_img',
'ngfb_filter_content' => 'plugin_filter_content',
'ngfb_filter_excerpt' => 'plugin_filter_excerpt',
'ngfb_add_to_post' => 'plugin_add_to_post',
'ngfb_add_to_page' => 'plugin_add_to_page',
'ngfb_add_to_attachment' => 'plugin_add_to_attachment',
'ngfb_verify_certs' => 'plugin_verify_certs',
'ngfb_file_cache_hrs' => 'plugin_file_cache_hrs',
'ngfb_object_cache_exp' => 'plugin_object_cache_exp',
'ngfb_min_shorten' => 'plugin_min_shorten',
'ngfb_googl_api_key' => 'plugin_google_api_key',
'ngfb_bitly_login' => 'plugin_bitly_login',
'ngfb_bitly_api_key' => 'plugin_bitly_api_key',
'ngfb_cm_fb_name' => 'plugin_cm_fb_name',
'ngfb_cm_fb_label' => 'plugin_cm_fb_label',
'ngfb_cm_fb_enabled' => 'plugin_cm_fb_enabled',
'ngfb_cm_gp_name' => 'plugin_cm_gp_name',
'ngfb_cm_gp_label' => 'plugin_cm_gp_label',
'ngfb_cm_gp_enabled' => 'plugin_cm_gp_enabled',
'ngfb_cm_linkedin_name' => 'plugin_cm_linkedin_name',
'ngfb_cm_linkedin_label' => 'plugin_cm_linkedin_label',
'ngfb_cm_linkedin_enabled' => 'plugin_cm_linkedin_enabled',
'ngfb_cm_pin_name' => 'plugin_cm_pin_name',
'ngfb_cm_pin_label' => 'plugin_cm_pin_label',
'ngfb_cm_pin_enabled' => 'plugin_cm_pin_enabled',
'ngfb_cm_tumblr_name' => 'plugin_cm_tumblr_name',
'ngfb_cm_tumblr_label' => 'plugin_cm_tumblr_label',
'ngfb_cm_tumblr_enabled' => 'plugin_cm_tumblr_enabled',
'ngfb_cm_twitter_name' => 'plugin_cm_twitter_name',
'ngfb_cm_twitter_label' => 'plugin_cm_twitter_label',
'ngfb_cm_twitter_enabled' => 'plugin_cm_twitter_enabled',
'ngfb_cm_yt_name' => 'plugin_cm_yt_name',
'ngfb_cm_yt_label' => 'plugin_cm_yt_label',
'ngfb_cm_yt_enabled' => 'plugin_cm_yt_enabled',
'ngfb_cm_skype_name' => 'plugin_cm_skype_name',
'ngfb_cm_skype_label' => 'plugin_cm_skype_label',
'ngfb_cm_skype_enabled' => 'plugin_cm_skype_enabled',
'plugin_googl_api_key' => 'plugin_google_api_key',
'og_img_resize' => 'plugin_auto_img_resize',
'buttons_css_social' => 'buttons_css_sharing',
'plugin_shortcode_ngfb' => 'plugin_shortcodes',
'buttons_link_css' => 'buttons_use_social_css',
'fb_on_admin_sharing' => 'fb_on_admin_edit',
'gp_on_admin_sharing' => 'gp_on_admin_edit',
'twitter_on_admin_sharing' => 'twitter_on_admin_edit',
'linkedin_on_admin_sharing' => 'linkedin_on_admin_edit',
'managewp_on_admin_sharing' => 'managewp_on_admin_edit',
'stumble_on_admin_sharing' => 'stumble_on_admin_edit',
'pin_on_admin_sharing' => 'pin_on_admin_edit',
'tumblr_on_admin_sharing' => 'tumblr_on_admin_edit',
'buttons_location_the_excerpt' => 'buttons_pos_excerpt',
'buttons_location_the_content' => 'buttons_pos_content',
'fb_on_the_content' => 'fb_on_content',
'fb_on_the_excerpt' => 'fb_on_excerpt',
'gp_on_the_content' => 'gp_on_content',
'gp_on_the_excerpt' => 'gp_on_excerpt',
'twitter_on_the_content' => 'twitter_on_content',
'twitter_on_the_excerpt' => 'twitter_on_excerpt',
'linkedin_on_the_content' => 'linkedin_on_content',
'linkedin_on_the_excerpt' => 'linkedin_on_excerpt',
'managewp_on_the_content' => 'managewp_on_content',
'managewp_on_the_excerpt' => 'managewp_on_excerpt',
'stumble_on_the_content' => 'stumble_on_content',
'stumble_on_the_excerpt' => 'stumble_on_excerpt',
'pin_on_the_content' => 'pin_on_content',
'pin_on_the_excerpt' => 'pin_on_excerpt',
'tumblr_on_the_content' => 'tumblr_on_content',
'tumblr_on_the_excerpt' => 'tumblr_on_excerpt',
'link_def_author_id' => 'seo_def_author_id',
'link_def_author_on_index' => 'seo_def_author_on_index',
'link_def_author_on_search' => 'seo_def_author_on_search',
'plugin_tid' => 'plugin_ngfb_tid',
);
protected $p;
public function __construct( &$plugin ) {
$this->p =& $plugin;
$this->p->debug->mark();
}
// def_opts accepts output from functions, so don't force reference
public function options( $options_name, &$opts = array(), $def_opts = array() ) {
$opts = SucomUtil::rename_keys( $opts, $this->renamed_keys );
// custom value changes for regular options
if ( $options_name == constant( $this->p->cf['uca'].'_OPTIONS_NAME' ) ) {
if ( version_compare( $opts['options_version'], 28, '<=' ) ) {
// upgrade the old og_img_size name into width / height / crop values
if ( array_key_exists( 'og_img_size', $opts ) ) {
if ( ! empty( $opts['og_img_size'] ) && $opts['og_img_size'] !== 'medium' ) {
$size_info = $this->p->media->get_size_info( $opts['og_img_size'] );
if ( $size_info['width'] > 0 && $size_info['height'] > 0 ) {
$opts['og_img_width'] = $size_info['width'];
$opts['og_img_height'] = $size_info['height'];
$opts['og_img_crop'] = $size_info['crop'];
}
}
unset( $opts['og_img_size'] );
}
}
if ( version_compare( $opts['options_version'], 247, '<=' ) ) {
if ( ! empty( $opts['twitter_shorten'] ) ) {
$opts['twitter_shortener'] = 'googl';
unset( $opts['twitter_shorten'] );
}
}
if ( version_compare( $opts['options_version'], 260, '<=' ) ) {
if ( $opts['og_img_width'] == 1200 &&
$opts['og_img_height'] == 630 &&
! empty( $opts['og_img_crop'] ) ) {
$this->p->notice->inf( 'Open Graph Image Dimentions have been updated from '.
$opts['og_img_width'].'x'.$opts['og_img_height'].', '.
( $opts['og_img_crop'] ? '' : 'un' ).'cropped to '.
$def_opts['og_img_width'].'x'.$def_opts['og_img_height'].', '.
( $def_opts['og_img_crop'] ? '' : 'un' ).'cropped.', true );
$opts['og_img_width'] = $def_opts['og_img_width'];
$opts['og_img_height'] = $def_opts['og_img_height'];
$opts['og_img_crop'] = $def_opts['og_img_crop'];
}
}
if ( version_compare( $opts['options_version'], 270, '<=' ) ) {
foreach ( $opts as $key => $val ) {
if ( strpos( $key, 'inc_' ) === 0 ) {
$new_key = '';
switch ( $key ) {
case ( preg_match( '/^inc_(description|twitter:)/', $key ) ? true : false ):
$new_key = preg_replace( '/^inc_/', 'add_meta_name_', $key );
break;
default:
$new_key = preg_replace( '/^inc_/', 'add_meta_property_', $key );
break;
}
if ( ! empty( $new_key ) )
$opts[$new_key] = $val;
unset( $opts[$key] );
}
}
}
if ( version_compare( $opts['options_version'], 296, '<=' ) ) {
if ( $opts['plugin_min_shorten'] < 22 )
$opts['plugin_min_shorten'] = 22;
}
}
$opts = $this->sanitize( $opts, $def_opts ); // cleanup excess options and sanitize
return $opts;
}
}
}
?>
|
Zaturrby/deploykanvas
|
wp-content/plugins/nextgen-facebook/lib/upgrade.php
|
PHP
|
gpl-2.0
| 8,315 |
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
* Other contributors include John Vint
*/
package jsr166;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import junit.framework.Test;
import junit.framework.TestSuite;
public class PhaserTest extends JSR166TestCase {
// android-note: Removed because the CTS runner does a bad job of
// retrying tests that have suite() declarations.
//
// public static void main(String[] args) {
// main(suite(), args);
// }
// public static Test suite() {
// return new TestSuite(...);
// }
private static final int maxParties = 65535;
/** Checks state of unterminated phaser. */
protected void assertState(Phaser phaser,
int phase, int parties, int unarrived) {
assertEquals(phase, phaser.getPhase());
assertEquals(parties, phaser.getRegisteredParties());
assertEquals(unarrived, phaser.getUnarrivedParties());
assertEquals(parties - unarrived, phaser.getArrivedParties());
assertFalse(phaser.isTerminated());
}
/** Checks state of terminated phaser. */
protected void assertTerminated(Phaser phaser, int maxPhase, int parties) {
assertTrue(phaser.isTerminated());
int expectedPhase = maxPhase + Integer.MIN_VALUE;
assertEquals(expectedPhase, phaser.getPhase());
assertEquals(parties, phaser.getRegisteredParties());
assertEquals(expectedPhase, phaser.register());
assertEquals(expectedPhase, phaser.arrive());
assertEquals(expectedPhase, phaser.arriveAndDeregister());
}
protected void assertTerminated(Phaser phaser, int maxPhase) {
assertTerminated(phaser, maxPhase, 0);
}
/**
* Empty constructor builds a new Phaser with no parent, no registered
* parties and initial phase number of 0
*/
public void testConstructorDefaultValues() {
Phaser phaser = new Phaser();
assertNull(phaser.getParent());
assertEquals(0, phaser.getRegisteredParties());
assertEquals(0, phaser.getArrivedParties());
assertEquals(0, phaser.getUnarrivedParties());
assertEquals(0, phaser.getPhase());
}
/**
* Constructing with a negative number of parties throws
* IllegalArgumentException
*/
public void testConstructorNegativeParties() {
try {
new Phaser(-1);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
/**
* Constructing with a negative number of parties throws
* IllegalArgumentException
*/
public void testConstructorNegativeParties2() {
try {
new Phaser(new Phaser(), -1);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
/**
* Constructing with a number of parties > 65535 throws
* IllegalArgumentException
*/
public void testConstructorPartiesExceedsLimit() {
new Phaser(maxParties);
try {
new Phaser(maxParties + 1);
shouldThrow();
} catch (IllegalArgumentException success) {}
new Phaser(new Phaser(), maxParties);
try {
new Phaser(new Phaser(), maxParties + 1);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
/**
* The parent provided to the constructor should be returned from
* a later call to getParent
*/
public void testConstructor3() {
Phaser parent = new Phaser();
assertSame(parent, new Phaser(parent).getParent());
assertNull(new Phaser(null).getParent());
}
/**
* The parent being input into the parameter should equal the original
* parent when being returned
*/
public void testConstructor5() {
Phaser parent = new Phaser();
assertSame(parent, new Phaser(parent, 0).getParent());
assertNull(new Phaser(null, 0).getParent());
}
/**
* register() will increment the number of unarrived parties by
* one and not affect its arrived parties
*/
public void testRegister1() {
Phaser phaser = new Phaser();
assertState(phaser, 0, 0, 0);
assertEquals(0, phaser.register());
assertState(phaser, 0, 1, 1);
}
/**
* Registering more than 65536 parties causes IllegalStateException
*/
public void testRegister2() {
Phaser phaser = new Phaser(0);
assertState(phaser, 0, 0, 0);
assertEquals(0, phaser.bulkRegister(maxParties - 10));
assertState(phaser, 0, maxParties - 10, maxParties - 10);
for (int i = 0; i < 10; i++) {
assertState(phaser, 0, maxParties - 10 + i, maxParties - 10 + i);
assertEquals(0, phaser.register());
}
assertState(phaser, 0, maxParties, maxParties);
try {
phaser.register();
shouldThrow();
} catch (IllegalStateException success) {}
try {
phaser.bulkRegister(Integer.MAX_VALUE);
shouldThrow();
} catch (IllegalStateException success) {}
assertEquals(0, phaser.bulkRegister(0));
assertState(phaser, 0, maxParties, maxParties);
}
/**
* register() correctly returns the current barrier phase number
* when invoked
*/
public void testRegister3() {
Phaser phaser = new Phaser();
assertEquals(0, phaser.register());
assertEquals(0, phaser.arrive());
assertEquals(1, phaser.register());
assertState(phaser, 1, 2, 2);
}
/**
* register causes the next arrive to not increment the phase
* rather retain the phase number
*/
public void testRegister4() {
Phaser phaser = new Phaser(1);
assertEquals(0, phaser.arrive());
assertEquals(1, phaser.register());
assertEquals(1, phaser.arrive());
assertState(phaser, 1, 2, 1);
}
/**
* register on a subphaser that is currently empty succeeds, even
* in the presence of another non-empty subphaser
*/
public void testRegisterEmptySubPhaser() {
Phaser root = new Phaser();
Phaser child1 = new Phaser(root, 1);
Phaser child2 = new Phaser(root, 0);
assertEquals(0, child2.register());
assertState(root, 0, 2, 2);
assertState(child1, 0, 1, 1);
assertState(child2, 0, 1, 1);
assertEquals(0, child2.arriveAndDeregister());
assertState(root, 0, 1, 1);
assertState(child1, 0, 1, 1);
assertState(child2, 0, 0, 0);
assertEquals(0, child2.register());
assertEquals(0, child2.arriveAndDeregister());
assertState(root, 0, 1, 1);
assertState(child1, 0, 1, 1);
assertState(child2, 0, 0, 0);
assertEquals(0, child1.arriveAndDeregister());
assertTerminated(root, 1);
assertTerminated(child1, 1);
assertTerminated(child2, 1);
}
/**
* Invoking bulkRegister with a negative parameter throws an
* IllegalArgumentException
*/
public void testBulkRegister1() {
try {
new Phaser().bulkRegister(-1);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
/**
* bulkRegister should correctly record the number of unarrived
* parties with the number of parties being registered
*/
public void testBulkRegister2() {
Phaser phaser = new Phaser();
assertEquals(0, phaser.bulkRegister(0));
assertState(phaser, 0, 0, 0);
assertEquals(0, phaser.bulkRegister(20));
assertState(phaser, 0, 20, 20);
}
/**
* Registering with a number of parties greater than or equal to 1<<16
* throws IllegalStateException.
*/
public void testBulkRegister3() {
assertEquals(0, new Phaser().bulkRegister((1 << 16) - 1));
try {
new Phaser().bulkRegister(1 << 16);
shouldThrow();
} catch (IllegalStateException success) {}
try {
new Phaser(2).bulkRegister((1 << 16) - 2);
shouldThrow();
} catch (IllegalStateException success) {}
}
/**
* the phase number increments correctly when tripping the barrier
*/
public void testPhaseIncrement1() {
for (int size = 1; size < nine; size++) {
final Phaser phaser = new Phaser(size);
for (int index = 0; index <= (1 << size); index++) {
int phase = phaser.arrive();
assertTrue(index % size == 0 ? (index / size) == phase : index - (phase * size) > 0);
}
}
}
/**
* arrive() on a registered phaser increments phase.
*/
public void testArrive1() {
Phaser phaser = new Phaser(1);
assertState(phaser, 0, 1, 1);
assertEquals(0, phaser.arrive());
assertState(phaser, 1, 1, 1);
}
/**
* arriveAndDeregister does not wait for others to arrive at barrier
*/
public void testArriveAndDeregister() {
final Phaser phaser = new Phaser(1);
for (int i = 0; i < 10; i++) {
assertState(phaser, 0, 1, 1);
assertEquals(0, phaser.register());
assertState(phaser, 0, 2, 2);
assertEquals(0, phaser.arriveAndDeregister());
assertState(phaser, 0, 1, 1);
}
assertEquals(0, phaser.arriveAndDeregister());
assertTerminated(phaser, 1);
}
/**
* arriveAndDeregister does not wait for others to arrive at barrier
*/
public void testArrive2() {
final Phaser phaser = new Phaser();
assertEquals(0, phaser.register());
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < 10; i++) {
assertEquals(0, phaser.register());
threads.add(newStartedThread(new CheckedRunnable() {
public void realRun() {
assertEquals(0, phaser.arriveAndDeregister());
}}));
}
for (Thread thread : threads)
awaitTermination(thread);
assertState(phaser, 0, 1, 1);
assertEquals(0, phaser.arrive());
assertState(phaser, 1, 1, 1);
}
/**
* arrive() returns a negative number if the Phaser is terminated
*/
public void testArrive3() {
Phaser phaser = new Phaser(1);
phaser.forceTermination();
assertTerminated(phaser, 0, 1);
assertEquals(0, phaser.getPhase() + Integer.MIN_VALUE);
assertTrue(phaser.arrive() < 0);
assertTrue(phaser.register() < 0);
assertTrue(phaser.arriveAndDeregister() < 0);
assertTrue(phaser.awaitAdvance(1) < 0);
assertTrue(phaser.getPhase() < 0);
}
/**
* arriveAndDeregister() throws IllegalStateException if number of
* registered or unarrived parties would become negative
*/
public void testArriveAndDeregister1() {
try {
Phaser phaser = new Phaser();
phaser.arriveAndDeregister();
shouldThrow();
} catch (IllegalStateException success) {}
}
/**
* arriveAndDeregister reduces the number of arrived parties
*/
public void testArriveAndDeregister2() {
final Phaser phaser = new Phaser(1);
assertEquals(0, phaser.register());
assertEquals(0, phaser.arrive());
assertState(phaser, 0, 2, 1);
assertEquals(0, phaser.arriveAndDeregister());
assertState(phaser, 1, 1, 1);
}
/**
* arriveAndDeregister arrives at the barrier on a phaser with a parent and
* when a deregistration occurs and causes the phaser to have zero parties
* its parent will be deregistered as well
*/
public void testArriveAndDeregister3() {
Phaser parent = new Phaser();
Phaser child = new Phaser(parent);
assertState(child, 0, 0, 0);
assertState(parent, 0, 0, 0);
assertEquals(0, child.register());
assertState(child, 0, 1, 1);
assertState(parent, 0, 1, 1);
assertEquals(0, child.arriveAndDeregister());
assertTerminated(child, 1);
assertTerminated(parent, 1);
}
/**
* arriveAndDeregister deregisters one party from its parent when
* the number of parties of child is zero after deregistration
*/
public void testArriveAndDeregister4() {
Phaser parent = new Phaser();
Phaser child = new Phaser(parent);
assertEquals(0, parent.register());
assertEquals(0, child.register());
assertState(child, 0, 1, 1);
assertState(parent, 0, 2, 2);
assertEquals(0, child.arriveAndDeregister());
assertState(child, 0, 0, 0);
assertState(parent, 0, 1, 1);
}
/**
* arriveAndDeregister deregisters one party from its parent when
* the number of parties of root is nonzero after deregistration.
*/
public void testArriveAndDeregister5() {
Phaser root = new Phaser();
Phaser parent = new Phaser(root);
Phaser child = new Phaser(parent);
assertState(root, 0, 0, 0);
assertState(parent, 0, 0, 0);
assertState(child, 0, 0, 0);
assertEquals(0, child.register());
assertState(root, 0, 1, 1);
assertState(parent, 0, 1, 1);
assertState(child, 0, 1, 1);
assertEquals(0, child.arriveAndDeregister());
assertTerminated(child, 1);
assertTerminated(parent, 1);
assertTerminated(root, 1);
}
/**
* arriveAndDeregister returns the phase in which it leaves the
* phaser in after deregistration
*/
public void testArriveAndDeregister6() {
final Phaser phaser = new Phaser(2);
Thread t = newStartedThread(new CheckedRunnable() {
public void realRun() {
assertEquals(0, phaser.arrive());
}});
assertEquals(1, phaser.arriveAndAwaitAdvance());
assertState(phaser, 1, 2, 2);
assertEquals(1, phaser.arriveAndDeregister());
assertState(phaser, 1, 1, 1);
assertEquals(1, phaser.arriveAndDeregister());
assertTerminated(phaser, 2);
awaitTermination(t);
}
/**
* awaitAdvance succeeds upon advance
*/
public void testAwaitAdvance1() {
final Phaser phaser = new Phaser(1);
assertEquals(0, phaser.arrive());
assertEquals(1, phaser.awaitAdvance(0));
}
/**
* awaitAdvance with a negative parameter will return without affecting the
* phaser
*/
public void testAwaitAdvance2() {
Phaser phaser = new Phaser();
assertTrue(phaser.awaitAdvance(-1) < 0);
assertState(phaser, 0, 0, 0);
}
/**
* awaitAdvanceInterruptibly blocks interruptibly
*/
public void testAwaitAdvanceInterruptibly_interruptible() throws InterruptedException {
final Phaser phaser = new Phaser(1);
final CountDownLatch pleaseInterrupt = new CountDownLatch(2);
Thread t1 = newStartedThread(new CheckedRunnable() {
public void realRun() {
Thread.currentThread().interrupt();
try {
phaser.awaitAdvanceInterruptibly(0);
shouldThrow();
} catch (InterruptedException success) {}
assertFalse(Thread.interrupted());
pleaseInterrupt.countDown();
try {
phaser.awaitAdvanceInterruptibly(0);
shouldThrow();
} catch (InterruptedException success) {}
assertFalse(Thread.interrupted());
}});
Thread t2 = newStartedThread(new CheckedRunnable() {
public void realRun() throws TimeoutException {
Thread.currentThread().interrupt();
try {
phaser.awaitAdvanceInterruptibly(0, 2*LONG_DELAY_MS, MILLISECONDS);
shouldThrow();
} catch (InterruptedException success) {}
assertFalse(Thread.interrupted());
pleaseInterrupt.countDown();
try {
phaser.awaitAdvanceInterruptibly(0, 2*LONG_DELAY_MS, MILLISECONDS);
shouldThrow();
} catch (InterruptedException success) {}
assertFalse(Thread.interrupted());
}});
await(pleaseInterrupt);
assertState(phaser, 0, 1, 1);
assertThreadsStayAlive(t1, t2);
t1.interrupt();
t2.interrupt();
awaitTermination(t1);
awaitTermination(t2);
assertState(phaser, 0, 1, 1);
assertEquals(0, phaser.arrive());
assertState(phaser, 1, 1, 1);
}
/**
* awaitAdvance continues waiting if interrupted before waiting
*/
public void testAwaitAdvanceAfterInterrupt() {
final Phaser phaser = new Phaser();
assertEquals(0, phaser.register());
final CountDownLatch pleaseArrive = new CountDownLatch(1);
Thread t = newStartedThread(new CheckedRunnable() {
public void realRun() {
Thread.currentThread().interrupt();
assertEquals(0, phaser.register());
assertEquals(0, phaser.arrive());
pleaseArrive.countDown();
assertTrue(Thread.currentThread().isInterrupted());
assertEquals(1, phaser.awaitAdvance(0));
assertTrue(Thread.interrupted());
}});
await(pleaseArrive);
waitForThreadToEnterWaitState(t, SHORT_DELAY_MS);
assertEquals(0, phaser.arrive());
awaitTermination(t);
Thread.currentThread().interrupt();
assertEquals(1, phaser.awaitAdvance(0));
assertTrue(Thread.interrupted());
}
/**
* awaitAdvance continues waiting if interrupted while waiting
*/
public void testAwaitAdvanceBeforeInterrupt() {
final Phaser phaser = new Phaser();
assertEquals(0, phaser.register());
final CountDownLatch pleaseArrive = new CountDownLatch(1);
Thread t = newStartedThread(new CheckedRunnable() {
public void realRun() {
assertEquals(0, phaser.register());
assertEquals(0, phaser.arrive());
assertFalse(Thread.currentThread().isInterrupted());
pleaseArrive.countDown();
assertEquals(1, phaser.awaitAdvance(0));
assertTrue(Thread.interrupted());
}});
await(pleaseArrive);
waitForThreadToEnterWaitState(t, SHORT_DELAY_MS);
t.interrupt();
assertEquals(0, phaser.arrive());
awaitTermination(t);
Thread.currentThread().interrupt();
assertEquals(1, phaser.awaitAdvance(0));
assertTrue(Thread.interrupted());
}
/**
* arriveAndAwaitAdvance continues waiting if interrupted before waiting
*/
public void testArriveAndAwaitAdvanceAfterInterrupt() {
final Phaser phaser = new Phaser();
assertEquals(0, phaser.register());
final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
Thread t = newStartedThread(new CheckedRunnable() {
public void realRun() {
Thread.currentThread().interrupt();
assertEquals(0, phaser.register());
pleaseInterrupt.countDown();
assertTrue(Thread.currentThread().isInterrupted());
assertEquals(1, phaser.arriveAndAwaitAdvance());
assertTrue(Thread.currentThread().isInterrupted());
}});
await(pleaseInterrupt);
waitForThreadToEnterWaitState(t, SHORT_DELAY_MS);
Thread.currentThread().interrupt();
assertEquals(1, phaser.arriveAndAwaitAdvance());
assertTrue(Thread.interrupted());
awaitTermination(t);
}
/**
* arriveAndAwaitAdvance continues waiting if interrupted while waiting
*/
public void testArriveAndAwaitAdvanceBeforeInterrupt() {
final Phaser phaser = new Phaser();
assertEquals(0, phaser.register());
final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
Thread t = newStartedThread(new CheckedRunnable() {
public void realRun() {
assertEquals(0, phaser.register());
assertFalse(Thread.currentThread().isInterrupted());
pleaseInterrupt.countDown();
assertEquals(1, phaser.arriveAndAwaitAdvance());
assertTrue(Thread.currentThread().isInterrupted());
}});
await(pleaseInterrupt);
waitForThreadToEnterWaitState(t, SHORT_DELAY_MS);
t.interrupt();
Thread.currentThread().interrupt();
assertEquals(1, phaser.arriveAndAwaitAdvance());
assertTrue(Thread.interrupted());
awaitTermination(t);
}
/**
* awaitAdvance atomically waits for all parties within the same phase to
* complete before continuing
*/
public void testAwaitAdvance4() {
final Phaser phaser = new Phaser(4);
final AtomicInteger count = new AtomicInteger(0);
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < 4; i++)
threads.add(newStartedThread(new CheckedRunnable() {
public void realRun() {
for (int k = 0; k < 3; k++) {
assertEquals(2*k+1, phaser.arriveAndAwaitAdvance());
count.incrementAndGet();
assertEquals(2*k+1, phaser.arrive());
assertEquals(2*k+2, phaser.awaitAdvance(2*k+1));
assertEquals(4*(k+1), count.get());
}}}));
for (Thread thread : threads)
awaitTermination(thread);
}
/**
* awaitAdvance returns the current phase
*/
public void testAwaitAdvance5() {
final Phaser phaser = new Phaser(1);
assertEquals(1, phaser.awaitAdvance(phaser.arrive()));
assertEquals(1, phaser.getPhase());
assertEquals(1, phaser.register());
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < 8; i++) {
final CountDownLatch latch = new CountDownLatch(1);
final boolean goesFirst = ((i & 1) == 0);
threads.add(newStartedThread(new CheckedRunnable() {
public void realRun() {
if (goesFirst)
latch.countDown();
else
await(latch);
phaser.arrive();
}}));
if (goesFirst)
await(latch);
else
latch.countDown();
assertEquals(i + 2, phaser.awaitAdvance(phaser.arrive()));
assertEquals(i + 2, phaser.getPhase());
}
for (Thread thread : threads)
awaitTermination(thread);
}
/**
* awaitAdvance returns the current phase in child phasers
*/
public void testAwaitAdvanceTieredPhaser() throws Exception {
final Phaser parent = new Phaser();
final List<Phaser> zeroPartyChildren = new ArrayList<Phaser>(3);
final List<Phaser> onePartyChildren = new ArrayList<Phaser>(3);
for (int i = 0; i < 3; i++) {
zeroPartyChildren.add(new Phaser(parent, 0));
onePartyChildren.add(new Phaser(parent, 1));
}
final List<Phaser> phasers = new ArrayList<Phaser>();
phasers.addAll(zeroPartyChildren);
phasers.addAll(onePartyChildren);
phasers.add(parent);
for (Phaser phaser : phasers) {
assertEquals(-42, phaser.awaitAdvance(-42));
assertEquals(-42, phaser.awaitAdvanceInterruptibly(-42));
assertEquals(-42, phaser.awaitAdvanceInterruptibly(-42, SMALL_DELAY_MS, MILLISECONDS));
}
for (Phaser child : onePartyChildren)
assertEquals(0, child.arrive());
for (Phaser phaser : phasers) {
assertEquals(-42, phaser.awaitAdvance(-42));
assertEquals(-42, phaser.awaitAdvanceInterruptibly(-42));
assertEquals(-42, phaser.awaitAdvanceInterruptibly(-42, SMALL_DELAY_MS, MILLISECONDS));
assertEquals(1, phaser.awaitAdvance(0));
assertEquals(1, phaser.awaitAdvanceInterruptibly(0));
assertEquals(1, phaser.awaitAdvanceInterruptibly(0, SMALL_DELAY_MS, MILLISECONDS));
}
for (Phaser child : onePartyChildren)
assertEquals(1, child.arrive());
for (Phaser phaser : phasers) {
assertEquals(-42, phaser.awaitAdvance(-42));
assertEquals(-42, phaser.awaitAdvanceInterruptibly(-42));
assertEquals(-42, phaser.awaitAdvanceInterruptibly(-42, SMALL_DELAY_MS, MILLISECONDS));
assertEquals(2, phaser.awaitAdvance(0));
assertEquals(2, phaser.awaitAdvanceInterruptibly(0));
assertEquals(2, phaser.awaitAdvanceInterruptibly(0, SMALL_DELAY_MS, MILLISECONDS));
assertEquals(2, phaser.awaitAdvance(1));
assertEquals(2, phaser.awaitAdvanceInterruptibly(1));
assertEquals(2, phaser.awaitAdvanceInterruptibly(1, SMALL_DELAY_MS, MILLISECONDS));
}
}
/**
* awaitAdvance returns when the phaser is externally terminated
*/
public void testAwaitAdvance6() {
final Phaser phaser = new Phaser(3);
final CountDownLatch pleaseForceTermination = new CountDownLatch(2);
final List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < 2; i++) {
Runnable r = new CheckedRunnable() {
public void realRun() {
assertEquals(0, phaser.arrive());
pleaseForceTermination.countDown();
assertTrue(phaser.awaitAdvance(0) < 0);
assertTrue(phaser.isTerminated());
assertTrue(phaser.getPhase() < 0);
assertEquals(0, phaser.getPhase() + Integer.MIN_VALUE);
assertEquals(3, phaser.getRegisteredParties());
}};
threads.add(newStartedThread(r));
}
await(pleaseForceTermination);
phaser.forceTermination();
assertTrue(phaser.isTerminated());
assertEquals(0, phaser.getPhase() + Integer.MIN_VALUE);
for (Thread thread : threads)
awaitTermination(thread);
assertEquals(3, phaser.getRegisteredParties());
}
/**
* arriveAndAwaitAdvance throws IllegalStateException with no
* unarrived parties
*/
public void testArriveAndAwaitAdvance1() {
try {
Phaser phaser = new Phaser();
phaser.arriveAndAwaitAdvance();
shouldThrow();
} catch (IllegalStateException success) {}
}
/**
* arriveAndAwaitAdvance waits for all threads to arrive, the
* number of arrived parties is the same number that is accounted
* for when the main thread awaitsAdvance
*/
public void testArriveAndAwaitAdvance3() {
final Phaser phaser = new Phaser(1);
final int THREADS = 3;
final CountDownLatch pleaseArrive = new CountDownLatch(THREADS);
final List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < THREADS; i++)
threads.add(newStartedThread(new CheckedRunnable() {
public void realRun() {
assertEquals(0, phaser.register());
pleaseArrive.countDown();
assertEquals(1, phaser.arriveAndAwaitAdvance());
}}));
await(pleaseArrive);
long startTime = System.nanoTime();
while (phaser.getArrivedParties() < THREADS)
Thread.yield();
assertEquals(THREADS, phaser.getArrivedParties());
assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
for (Thread thread : threads)
waitForThreadToEnterWaitState(thread, SHORT_DELAY_MS);
for (Thread thread : threads)
assertTrue(thread.isAlive());
assertState(phaser, 0, THREADS + 1, 1);
phaser.arriveAndAwaitAdvance();
for (Thread thread : threads)
awaitTermination(thread);
assertState(phaser, 1, THREADS + 1, THREADS + 1);
}
}
|
AdmireTheDistance/android_libcore
|
jsr166-tests/src/test/java/jsr166/PhaserTest.java
|
Java
|
gpl-2.0
| 28,896 |
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
* THIS FILE WAS MODIFIED BY SUN MICROSYSTEMS, INC.
*/
package com.sun.xml.internal.fastinfoset.algorithm;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.sun.xml.internal.org.jvnet.fastinfoset.EncodingAlgorithmException;
import com.sun.xml.internal.fastinfoset.CommonResourceBundle;
public class BASE64EncodingAlgorithm extends BuiltInEncodingAlgorithm {
/* package */ static final char encodeBase64[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
/* package */ static final int decodeBase64[] = {
/*'+'*/ 62,
-1, -1, -1,
/*'/'*/ 63,
/*'0'*/ 52,
/*'1'*/ 53,
/*'2'*/ 54,
/*'3'*/ 55,
/*'4'*/ 56,
/*'5'*/ 57,
/*'6'*/ 58,
/*'7'*/ 59,
/*'8'*/ 60,
/*'9'*/ 61,
-1, -1, -1, -1, -1, -1, -1,
/*'A'*/ 0,
/*'B'*/ 1,
/*'C'*/ 2,
/*'D'*/ 3,
/*'E'*/ 4,
/*'F'*/ 5,
/*'G'*/ 6,
/*'H'*/ 7,
/*'I'*/ 8,
/*'J'*/ 9,
/*'K'*/ 10,
/*'L'*/ 11,
/*'M'*/ 12,
/*'N'*/ 13,
/*'O'*/ 14,
/*'P'*/ 15,
/*'Q'*/ 16,
/*'R'*/ 17,
/*'S'*/ 18,
/*'T'*/ 19,
/*'U'*/ 20,
/*'V'*/ 21,
/*'W'*/ 22,
/*'X'*/ 23,
/*'Y'*/ 24,
/*'Z'*/ 25,
-1, -1, -1, -1, -1, -1,
/*'a'*/ 26,
/*'b'*/ 27,
/*'c'*/ 28,
/*'d'*/ 29,
/*'e'*/ 30,
/*'f'*/ 31,
/*'g'*/ 32,
/*'h'*/ 33,
/*'i'*/ 34,
/*'j'*/ 35,
/*'k'*/ 36,
/*'l'*/ 37,
/*'m'*/ 38,
/*'n'*/ 39,
/*'o'*/ 40,
/*'p'*/ 41,
/*'q'*/ 42,
/*'r'*/ 43,
/*'s'*/ 44,
/*'t'*/ 45,
/*'u'*/ 46,
/*'v'*/ 47,
/*'w'*/ 48,
/*'x'*/ 49,
/*'y'*/ 50,
/*'z'*/ 51
};
public final Object decodeFromBytes(byte[] b, int start, int length) throws EncodingAlgorithmException {
final byte[] data = new byte[length];
System.arraycopy(b, start, data, 0, length);
return data;
}
public final Object decodeFromInputStream(InputStream s) throws IOException {
throw new UnsupportedOperationException(CommonResourceBundle.getInstance().getString("message.notImplemented"));
}
public void encodeToOutputStream(Object data, OutputStream s) throws IOException {
if (!(data instanceof byte[])) {
throw new IllegalArgumentException(CommonResourceBundle.getInstance().getString("message.dataNotByteArray"));
}
s.write((byte[])data);
}
public final Object convertFromCharacters(char[] ch, int start, int length) {
if (length == 0) {
return new byte[0];
}
StringBuffer encodedValue = removeWhitespace(ch, start, length);
int encodedLength = encodedValue.length();
if (encodedLength == 0) {
return new byte[0];
}
int blockCount = encodedLength / 4;
int partialBlockLength = 3;
if (encodedValue.charAt(encodedLength - 1) == '=') {
--partialBlockLength;
if (encodedValue.charAt(encodedLength - 2) == '=') {
--partialBlockLength;
}
}
int valueLength = (blockCount - 1) * 3 + partialBlockLength;
byte[] value = new byte[valueLength];
int idx = 0;
int encodedIdx = 0;
for (int i = 0; i < blockCount; ++i) {
int x1 = decodeBase64[encodedValue.charAt(encodedIdx++) - '+'];
int x2 = decodeBase64[encodedValue.charAt(encodedIdx++) - '+'];
int x3 = decodeBase64[encodedValue.charAt(encodedIdx++) - '+'];
int x4 = decodeBase64[encodedValue.charAt(encodedIdx++) - '+'];
value[idx++] = (byte) ((x1 << 2) | (x2 >> 4));
if (idx < valueLength) {
value[idx++] = (byte) (((x2 & 0x0f) << 4) | (x3 >> 2));
}
if (idx < valueLength) {
value[idx++] = (byte) (((x3 & 0x03) << 6) | x4);
}
}
return value;
}
public final void convertToCharacters(Object data, StringBuffer s) {
if (data == null) {
return;
}
final byte[] value = (byte[]) data;
convertToCharacters(value, 0, value.length, s);
}
public final int getPrimtiveLengthFromOctetLength(int octetLength) throws EncodingAlgorithmException {
return octetLength;
}
public int getOctetLengthFromPrimitiveLength(int primitiveLength) {
return primitiveLength;
}
public final void encodeToBytes(Object array, int astart, int alength, byte[] b, int start) {
System.arraycopy((byte[])array, astart, b, start, alength);
}
public final void convertToCharacters(byte[] data, int offset, int length, StringBuffer s) {
if (data == null) {
return;
}
final byte[] value = data;
if (length == 0) {
return;
}
final int partialBlockLength = length % 3;
final int blockCount = (partialBlockLength != 0) ?
length / 3 + 1 :
length / 3;
final int encodedLength = blockCount * 4;
final int originalBufferSize = s.length();
s.ensureCapacity(encodedLength + originalBufferSize);
int idx = offset;
int lastIdx = offset + length;
for (int i = 0; i < blockCount; ++i) {
int b1 = value[idx++] & 0xFF;
int b2 = (idx < lastIdx) ? value[idx++] & 0xFF : 0;
int b3 = (idx < lastIdx) ? value[idx++] & 0xFF : 0;
s.append(encodeBase64[b1 >> 2]);
s.append(encodeBase64[((b1 & 0x03) << 4) | (b2 >> 4)]);
s.append(encodeBase64[((b2 & 0x0f) << 2) | (b3 >> 6)]);
s.append(encodeBase64[b3 & 0x3f]);
}
switch (partialBlockLength) {
case 1 :
s.setCharAt(originalBufferSize + encodedLength - 1, '=');
s.setCharAt(originalBufferSize + encodedLength - 2, '=');
break;
case 2 :
s.setCharAt(originalBufferSize + encodedLength - 1, '=');
break;
}
}
}
|
samskivert/ikvm-openjdk
|
build/linux-amd64/impsrc/com/sun/xml/internal/fastinfoset/algorithm/BASE64EncodingAlgorithm.java
|
Java
|
gpl-2.0
| 7,853 |
/*
* ncplib_kernel.h
*
* Copyright (C) 1995, 1996 by Volker Lendecke
*
*/
#ifndef _NCPLIB_H
#define _NCPLIB_H
#include <linux/config.h>
#include <linux/fs.h>
#include <linux/ncp.h>
#include <linux/ncp_fs.h>
#include <linux/ncp_fs_sb.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/malloc.h>
#include <linux/stat.h>
#include <linux/fcntl.h>
#include <asm/segment.h>
#include <asm/string.h>
#include <linux/ncp.h>
int
ncp_negotiate_size_and_options(struct ncp_server *server, int size,
int options, int *ret_size, int *ret_options);
int
ncp_negotiate_buffersize(struct ncp_server *server, int size,
int *target);
int
ncp_get_encryption_key(struct ncp_server *server,
char *target);
int
ncp_get_bindery_object_id(struct ncp_server *server,
int object_type, char *object_name,
struct ncp_bindery_object *target);
int
ncp_login_encrypted(struct ncp_server *server,
struct ncp_bindery_object *object,
unsigned char *key,
unsigned char *passwd);
int
ncp_login_user(struct ncp_server *server,
unsigned char *username,
unsigned char *password);
int
ncp_get_volume_info_with_number(struct ncp_server *server, int n,
struct ncp_volume_info *target);
int
ncp_get_volume_number(struct ncp_server *server, const char *name,
int *target);
int
ncp_file_search_init(struct ncp_server *server,
int dir_handle, const char *path,
struct ncp_filesearch_info *target);
int
ncp_file_search_continue(struct ncp_server *server,
struct ncp_filesearch_info *fsinfo,
int attributes, const char *path,
struct ncp_file_info *target);
int
ncp_get_finfo(struct ncp_server *server,
int dir_handle, const char *path, const char *name,
struct ncp_file_info *target);
int
ncp_open_file(struct ncp_server *server,
int dir_handle, const char *path,
int attr, int access,
struct ncp_file_info *target);
int
ncp_close_file(struct ncp_server *server, const char *file_id);
int
ncp_create_newfile(struct ncp_server *server,
int dir_handle, const char *path,
int attr,
struct ncp_file_info *target);
int
ncp_create_file(struct ncp_server *server,
int dir_handle, const char *path,
int attr,
struct ncp_file_info *target);
int
ncp_erase_file(struct ncp_server *server,
int dir_handle, const char *path,
int attr);
int
ncp_rename_file(struct ncp_server *server,
int old_handle, const char *old_path,
int attr,
int new_handle, const char *new_path);
int
ncp_create_directory(struct ncp_server *server,
int dir_handle, const char *path,
int inherit_mask);
int
ncp_delete_directory(struct ncp_server *server,
int dir_handle, const char *path);
int
ncp_rename_directory(struct ncp_server *server,
int dir_handle,
const char *old_path, const char *new_path);
int
ncp_read(struct ncp_server *server, const char *file_id,
__u32 offset, __u16 to_read,
char *target, int *bytes_read);
int
ncp_write(struct ncp_server *server, const char *file_id,
__u32 offset, __u16 to_write,
const char *source, int *bytes_written);
int
ncp_obtain_info(struct ncp_server *server,
__u8 vol_num, __u32 dir_base,
char *path, /* At most 1 component */
struct nw_info_struct *target);
int
ncp_lookup_volume(struct ncp_server *server,
char *volname,
struct nw_info_struct *target);
int
ncp_modify_file_or_subdir_dos_info(struct ncp_server *server,
struct nw_info_struct *file,
__u32 info_mask,
struct nw_modify_dos_info *info);
int
ncp_del_file_or_subdir(struct ncp_server *server,
struct nw_info_struct *dir, char *name);
int
ncp_open_create_file_or_subdir(struct ncp_server *server,
struct nw_info_struct *dir, char *name,
int open_create_mode,
__u32 create_attributes,
int desired_acc_rights,
struct nw_file_info *target);
int
ncp_initialize_search(struct ncp_server *server,
struct nw_info_struct *dir,
struct nw_search_sequence *target);
int
ncp_search_for_file_or_subdir(struct ncp_server *server,
struct nw_search_sequence *seq,
struct nw_info_struct *target);
int
ncp_ren_or_mov_file_or_subdir(struct ncp_server *server,
struct nw_info_struct *old_dir, char *old_name,
struct nw_info_struct *new_dir, char *new_name);
#ifdef CONFIG_NCPFS_IOCTL_LOCKING
int
ncp_LogPhysicalRecord(struct ncp_server *server,
const char *file_id, __u8 locktype,
__u32 offset, __u32 length, __u16 timeout);
int
ncp_ClearPhysicalRecord(struct ncp_server *server,
const char *file_id,
__u32 offset, __u32 length);
#endif /* CONFIG_NCPFS_IOCTL_LOCKING */
#ifdef CONFIG_NCPFS_MOUNT_SUBDIR
int
ncp_mount_subdir(struct ncp_server* server, __u8 volNumber,
__u8 srcNS, __u32 srcDirEntNum);
#endif /* CONFIG_NCPFS_MOUNT_SUBDIR */
#endif /* _NCPLIB_H */
|
carlobar/uclinux_leon3_UD
|
linux-2.0.x/fs/ncpfs/ncplib_kernel.h
|
C
|
gpl-2.0
| 4,911 |
<?php
/*
+---------------------------------------------------------------------------+
| Revive Adserver |
| http://www.revive-adserver.com |
| |
| Copyright: See the COPYRIGHT.txt file. |
| License: GPLv2 or later, see the LICENSE.txt file. |
+---------------------------------------------------------------------------+
*/
require_once(MAX_PATH.'/lib/OA/Upgrade/Migration.php');
/**
* Migration class to deal with converting the encoding of data stored in the database
* The encoding of all data within the database should now be stored in UTF-8 format.
*
*/
class EncodingMigration extends Migration
{
var $extension = false;
/**
* This maps the existing encoding
*
* @var array An array of language (folder) name -> encoding
*/
var $aEncodingMap = array(
'chinese_big5' => 'big5',
'czech' => 'iso-8859-2',
'french' => 'iso-8859-15',
'hebrew' => 'windows-1255',
'hungarian' => 'iso-8859-2',
'korean' => 'EUC-KR',
'polish' => 'iso-8859-2',
'portuguese' => 'iso-8859-15',
'russian_cp1251' => 'windows-1251',
'russian_koi8r' => 'koi8-r',
);
/**
* An array to hold the selected languages' encoding of all agencies in the system
*
* @var array $agencyId => $encoding
*/
var $aEncodingByAgency = array();
/**
* An array to hold all the tables and fields that should be converted
*
* @var array of arrays(
* 'fields' => array: field names that should be converted,
* 'idfields' => array: fields identifying the primary (multi?) key used for the WHERE clause on update
* 'joinon' string: Identifies which field in the table should be used to build the join up (to get the agency ID where applicable)
*/
var $aTableFields = array(
'acls' => array(
'fields' => array('data'),
'idfields' => array('bannerid', 'executionorder'),
'joinon' => 'bannerid',
),
'acls_channel' => array(
'fields' => array('data'),
'idfields' => array('channelid', 'executionorder'),
'joinon' => 'channelid',
),
'affiliates' => array(
'fields' => array('name', 'mnemonic', 'comments', 'contact', 'email', 'website'),
'idfields' => array('affiliateid'),
'joinon' => 'affiliateid',
),
'agency' => array(
'fields' => array('name', 'contact', 'email', 'username', 'logout_url'),
'idfields' => array('agencyid'),
'joinon' => 'agencyid',
),
'application_variable' => array(
'fields' => array('name', 'value'),
'idfields' => array('name'),
'joinon' => 'adminid',
),
'banners' => array(
'fields' => array('htmltemplate','htmlcache','target','url','alt','bannertext','description','append','comments','keyword','statustext'),
'idfields' => array('bannerid'),
'joinon' => 'bannerid',
),
'campaigns' => array(
'fields' => array('campaignname','comments'),
'idfields' => array('campaignid'),
'joinon' => 'campaignid',
),
'channel' => array(
'fields' => array('name','description','comments'),
'idfields' => array('channelid'),
'joinon' => 'agencyid',
),
'clients' => array(
'fields' => array('clientname','contact','email','comments'),
'idfields' => array('clientid'),
'joinon' => 'clientid',
),
'preference' => array(
'fields' => array('name', 'company_name', 'admin', 'admin_fullname'),
'idfields' => array('agencyid'),
'joinon' => 'agencyid',
),
'tracker_append' => array(
'fields' => array('tagcode'),
'idfields' => array('tracker_append_id'),
'joinon' => 'tracker_id',
),
'trackers' => array(
'fields' => array('trackername','description','appendcode'),
'idfields' => array('trackerid'),
'joinon' => 'clientid',
),
'userlog' => array(
'fields' => array('details'),
'idfields' => array('userlogid'),
'joinon' => 'adminid',
),
'variables' => array(
'fields' => array('name','description','variablecode'),
'idfields' => array('variableid'),
'joinon' => 'trackerid',
),
'zones' => array(
'fields' => array('zonename','description','prepend','append','comments','what'),
'idfields' => array('zoneid'),
'joinon' => 'affiliateid',
),
);
function EncodingMigration()
{
}
function _getEncodingForLanguage($language)
{
return !empty($this->aEncodingMap[$language]) ? $this->aEncodingMap[$language] : 'UTF-8';
}
function _getEncodingForAgency($agencyId)
{
return !empty($this->aEncodingByAgency[$agencyId]) ? $this->aEncodingByAgency[$agencyId] : 'UTF-8';
}
function _setEncodingExtension()
{
$this->extension = false;
if (function_exists('mb_convert_encoding'))
{
$this->extension = 'mbstring';
}
else if (function_exists('iconv'))
{
$this->extension = 'iconv';
}
else if (function_exists('utf8_encode'))
{
$this->extension = 'xml';
}
return $this->extension;
}
function convertEncoding()
{
if (!$this->init(OA_DB::singleton()))
{
return false;
}
if (!$this->_setEncodingExtension())
{
$this->_log("convertEncoding will be skipped because no extension was found (iconv, mbstring, xml)");
return true;
}
$this->_log("Starting convertEncoding");
$this->_log('Encoding extension set to '.$this->extension);
$upgradingFrom = $this->getOriginalApplicationVersion();
if (!empty($upgradingFrom)) {
switch ($upgradingFrom) {
case '2.0.11-pr1':
$this->aEncodingMap['chinese_gb2312'] = 'gb2312';
break;
case 'v0.1.29-rc':
$this->aEncodingMap['chinese_gb2312'] = 'gb2312';
$this->aEncodingMap['portuguese'] = 'UTF-8';
break;
}
}
$tblBanners = $this->_getQuotedTableName('banners');
$tblCampaigns = $this->_getQuotedTableName('campaigns');
$tblClients = $this->_getQuotedTableName('clients');
$tblAgency = $this->_getQuotedTableName('agency');
$tblTrackers = $this->_getQuotedTableName('trackers');
$tblAffiliates = $this->_getQuotedTableName('affiliates');
$tblChannel = $this->_getQuotedTableName('channel');
// Get admin language
$query = "
SELECT
agencyid AS id,
language AS language
FROM
" . $this->_getQuotedTableName('preference') . "
WHERE
agencyid = 0
";
$adminLang = $this->oDBH->getAssoc($query);
if (PEAR::isError($adminLang))
{
$this->_logError("Error while retrieving admin language: ".$adminLang->getUserInfo());
return false;
}
// Get agency languages
$query = "
SELECT
agencyid AS id,
language AS language
FROM
" . $tblAgency;
$agencyLang = $this->oDBH->getAssoc($query);
if (PEAR::isError($agencyLang))
{
$this->_logError("Error while retrieving agency language: ".$agencyLang->getUserInfo());
return false;
}
// Set the admin's language for id 0, then set each agencies language as specified, using admins if unset
$this->aEncodingByAgency[0] = !empty($adminLang[0]) ? $this->_getEncodingForLanguage($adminLang[0]) : 'UTF-8';
foreach ($agencyLang as $id => $language) {
if (!empty($language)) {
$this->aEncodingByAgency[$id] = $this->_getEncodingForLanguage($language);
} else {
$this->aEncodingByAgency[$id] = $this->aEncodingByAgency[0];
}
}
foreach ($this->aTableFields as $table => $aTableData)
{
$quotedTablename = $this->_getQuotedTableName($table);
$fields = array_merge($aTableData['fields'], $aTableData['idfields']);
foreach ($fields as $idx => $field)
{
$fields[$idx] = $quotedTablename . '.' . $field;
}
$where = '';
switch ($aTableData['joinon']) {
case 'bannerid':
$where .= ' LEFT JOIN ' . $tblBanners . " AS b ON b.bannerid={$quotedTablename}.bannerid\n";
$where .= ' LEFT JOIN ' . $tblCampaigns . " AS c ON c.campaignid=b.campaignid\n";
$where .= ' LEFT JOIN ' . $tblClients . " AS cl ON c.clientid=cl.clientid\n";
$where .= ' LEFT JOIN ' . $tblAgency . " AS ag ON ag.agencyid=cl.agencyid\n";
break;
case 'campaignid':
$where .= ' LEFT JOIN ' . $tblCampaigns . " AS c ON c.campaignid={$quotedTablename}.campaignid\n";
$where .= ' LEFT JOIN ' . $tblClients . " AS cl ON c.clientid=cl.clientid\n";
$where .= ' LEFT JOIN ' . $tblAgency . " AS ag ON ag.agencyid=cl.agencyid\n";
break;
case 'clientid':
$where .= ' LEFT JOIN ' . $tblClients . " AS cl ON cl.clientid={$quotedTablename}.clientid\n";
$where .= ' LEFT JOIN ' . $tblAgency . " AS ag ON ag.agencyid=cl.agencyid\n";
break;
case 'trackerid':
$where .= ' LEFT JOIN ' . $tblTrackers . " AS tr ON tr.trackerid={$quotedTablename}.trackerid\n";
$where .= ' LEFT JOIN ' . $tblClients . " AS cl ON tr.clientid=cl.clientid\n";
$where .= ' LEFT JOIN ' . $tblAgency . " AS ag ON ag.agencyid=cl.agencyid\n";
break;
case 'tracker_id':
$where .= ' LEFT JOIN ' . $tblTrackers . " AS tr ON tr.trackerid={$quotedTablename}.tracker_id\n";
$where .= ' LEFT JOIN ' . $tblClients . " AS cl ON tr.clientid=cl.clientid\n";
$where .= ' LEFT JOIN ' . $tblAgency . " AS ag ON ag.agencyid=cl.agencyid\n";
break;
case 'affiliateid':
$where .= ' LEFT JOIN ' . $tblAffiliates . " AS af ON af.affiliateid={$quotedTablename}.affiliateid\n";
$where .= ' LEFT JOIN ' . $tblAgency . " AS ag ON ag.agencyid=af.agencyid\n";
break;
case 'channelid':
$where .= ' LEFT JOIN ' . $tblChannel . " AS ch ON ch.channelid={$quotedTablename}.channelid\n";
$where .= ' LEFT JOIN ' . $tblAgency . " AS ag ON ag.agencyid=ch.agencyid\n";
break;
}
$query = "SELECT\n ";
if ($aTableData['joinon'] != 'adminid' && $aTableData['joinon'] != 'agencyid')
{
$query .= "ag.agencyid AS agencyid,\n ";
}
$query .= implode(',' . "\n ", $fields);
$query .= "\nFROM\n " . $quotedTablename . "\n";
$query .= $where;
$rows = $this->oDBH->queryAll($query);
if (PEAR::isError($rows))
{
$this->_log("Error while retrieving data: ".$rows->getUserInfo());
}
else
{
foreach ($rows as $idx => $rowFields)
{
// Set the agency id (to zero by default for admin language)
$agencyId = (isset($rowFields['agencyid'])) ? $rowFields['agencyid'] : 0;
// Look up the probable encoding for that agency
$fromEncoding = $this->_getEncodingForAgency($agencyId);
// Don't bother converting language packs which are already UTF-8
if ($fromEncoding == 'UTF-8')
{
continue;
}
$updateValues = array();
// Convert each required field's encoding
foreach ($rowFields as $k => $v)
{
if (!empty($v))
{
$converted = $this->_convertString($v, 'UTF-8', $fromEncoding);
if ($converted !== $v)
{
$updateValues[$k] = $converted;
}
}
}
// Skip any rows where no fields have actually changed
if (empty($updateValues))
{
continue;
}
// Prepare the update query
$updateQuery = "UPDATE\n " . $quotedTablename . "\nSET\n";
$uFields = array();
foreach ($updateValues as $k => $v)
{
$uFields[] = " {$k} = " . $this->oDBH->quote($v) . "\n";
}
$updateQuery .= implode(', ', $uFields) . " WHERE ";
$uFields = array();
foreach ($aTableData['idfields'] as $idField)
{
$uFields[] = " {$idField} = " . $this->oDBH->quote($rowFields[$idField]);
}
$updateQuery .= implode(' AND ', $uFields);
$this->_log('updating from '.$fromEncoding.' to UTF-8 : '.$updateQuery);
$result = $this->oDBH->exec($updateQuery);
if (PEAR::isError($result))
{
$this->_log("Error while updating data: ".$rows->getUserInfo());
}
}
}
}
$this->_log('Completed convertEncoding');
// Do we want fail the upgrade on encoding issues? I think not...
return true;
}
/**
* This method converts a string's encoding into UTF-8
*
* @todo Before merging this to trunk, this wrapper should be replaced
*
* @param string $string The string to be converted
* @param string $toEncoding The destination encoding
* @param string $fromEncoding The source encoding (if known)
* @return string The converted string
*/
function _convertString($string, $toEncoding, $fromEncoding = 'UTF-8')
{
return MAX_commonConvertEncoding($string, $toEncoding, $fromEncoding, array($this->extension));
}
function getOriginalApplicationVersion()
{
$oUpgrader = new OA_Upgrade();
$oUpgrader->oAuditor->init($this->oDBH);
$aResult = $oUpgrader->seekRecoveryFile();
if (is_array($aResult) && isset($aResult[0]['auditId']))
{
$auditId = $aResult[0]['auditId'];
$aAudit = $oUpgrader->oAuditor->queryAuditByUpgradeId($auditId);
if (is_array($aAudit[0]) && isset($aAudit[0]['version_from']))
{
return $aAudit[0]['version_from'];
}
}
return false;
}
}
?>
|
adqio/revive-adserver
|
etc/changes/EncodingMigration.php
|
PHP
|
gpl-2.0
| 16,148 |
using Server.Engines.Craft;
namespace Server.Items
{
[Alterable(typeof(DefBlacksmithy), typeof(DualPointedSpear))]
[Flipable(0x26BF, 0x26C9)]
public class DoubleBladedStaff : BaseSpear
{
[Constructable]
public DoubleBladedStaff()
: base(0x26BF)
{
Weight = 2.0;
}
public DoubleBladedStaff(Serial serial)
: base(serial)
{
}
public override WeaponAbility PrimaryAbility => WeaponAbility.DoubleStrike;
public override WeaponAbility SecondaryAbility => WeaponAbility.InfectiousStrike;
public override int StrengthReq => 50;
public override int MinDamage => 11;
public override int MaxDamage => 14;
public override float Speed => 2.25f;
public override int InitMinHits => 31;
public override int InitMaxHits => 80;
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
|
zerodowned/ServUO
|
Scripts/Items/Equipment/Weapons/DoubleBladedStaff.cs
|
C#
|
gpl-2.0
| 1,215 |
/*
* Copyright (C) 2008 Emweb bv, Herent, Belgium.
*
* See the LICENSE file for terms of use.
*/
#include <Wt/WPanel.h>
#include "PanelList.h"
using namespace Wt;
PanelList::PanelList()
: WContainerWidget()
{ }
WPanel *PanelList::addWidget(const WString& text, std::unique_ptr<WWidget> w)
{
std::unique_ptr<WPanel> p
= std::make_unique<WPanel>();
WPanel *result = p.get();
p->setTitle(text);
p->setCentralWidget(std::move(w));
addPanel(std::move(p));
return result;
}
void PanelList::addPanel(std::unique_ptr<WPanel> panel)
{
panel->setCollapsible(true);
panel->collapse();
panel->expandedSS().connect(std::bind(&PanelList::onExpand, this, std::placeholders::_1, panel.get()));
WContainerWidget::addWidget(std::move(panel));
}
void PanelList::onExpand(bool notUndo, WPanel *panel)
{
if (notUndo) {
wasExpanded_ = -1;
for (unsigned i = 0; i < children().size(); ++i) {
WPanel *p = dynamic_cast<WPanel *>(children()[i]);
if (p != panel) {
if (!p->isCollapsed())
wasExpanded_ = i;
p->collapse();
}
}
} else {
if (wasExpanded_ != -1) {
WPanel *p = dynamic_cast<WPanel *>(children()[wasExpanded_]);
p->expand();
}
}
}
|
kdeforche/wt
|
examples/charts/PanelList.C
|
C++
|
gpl-2.0
| 1,240 |
<!DOCTYPE html>
<html class="ui-mobile landscape min-width-320px min-width-480px min-width-768px min-width-1024px">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">
<title>performances</title>
<link rel="stylesheet" href="jquery-ui-1.9.2.custom.min.css">
<link rel="stylesheet" href="jquery.mobile-1.2.0.min.css">
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery-ui-1.9.2.min.js"></script>
<script type="text/javascript" src="jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body class="home ui-mobile-viewport">
<div id="net2-loading" style="display: none;"></div>
<div data-role="page" id="page_1" net2-index="1" data-url="page_1" tabindex="0" class="ui-page ui-body-c" style="min-height: 540px;">
<div data-role="content" class="ui-content ui-sortable" role="main">
<ul data-role="listview" data-divider-theme="b" data-inset="true" id="editable1359473981905" net2class="net2-elements" class="Menu1 ui-listview ui-listview-inset ui-corner-all ui-shadow">
<li data-role="list-divider" role="heading" class="ui-li ui-li-divider ui-bar-b ui-corner-top">Divider</li>
<li net2class="net2-elements" data-corners="false" data-shadow="false" data-iconshadow="true" data-wrapperels="div" data-icon="arrow-r" data-iconpos="right" data-theme="c" class="ui-btn ui-btn-up-c ui-btn-icon-right ui-li-has-arrow ui-li" id="editable1359473981931">
<div class="ui-btn-inner ui-li">
<div class="ui-btn-text">
<a class="ui-link-inherit" href="#page_2">page2</a>
</div>
<span class="ui-icon ui-icon-arrow-r ui-icon-shadow"> </span>
</div>
</li>
<li net2class="net2-elements" data-corners="false" data-shadow="false" data-iconshadow="true" data-wrapperels="div" data-icon="arrow-r" data-iconpos="right" data-theme="c" class="ui-btn ui-btn-up-c ui-btn-icon-right ui-li-has-arrow ui-li ui-corner-bottom ui-li-last" id="editable1359473981950">
<div class="ui-btn-inner ui-li">
<div class="ui-btn-text">
<a class="ui-link-inherit">Link 2</a>
</div>
<span class="ui-icon ui-icon-arrow-r ui-icon-shadow"> </span>
</div>
</li>
</ul>
<label for="undefined" id="label1359473972828" net2class="net2-elements">Label</label>
<div class="ui-select">
<div data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span" data-icon="arrow-d" data-iconpos="right" data-theme="c" class="ui-btn ui-btn-up-c ui-shadow ui-btn-corner-all ui-btn-icon-right">
<span class="ui-btn-inner ui-btn-corner-all">
<span class="ui-btn-text">
<span>Default option</span>
</span>
<span class="ui-icon ui-icon-arrow-d ui-icon-shadow"> </span>
</span>
<select id="select1359473972829" net2class="net2-elements">
<option id="option1359473972830" value="o1" net2class="net2-elements">Default option</option>
<option id="option1359473972831" value="o2" net2class="net2-elements">Option 1</option>
</select>
</div>
</div>
</div>
</div>
<div class="ui-loader ui-corner-all ui-body-a ui-loader-default"><span class="ui-icon ui-icon-loading"></span><h1>loading</h1></div><div data-role="page" id="page_2" net2-index="2" tabindex="0" class="ui-page ui-body-c ui-page-active" style="min-height: 540px;"><div data-role="content" class="ui-content ui-sortable" role="main" style=""><div id="Textbox1" class="net2-composant net2-Textbox"><div class="net2-sort-handler"><div class="net2-suppr"></div></div><label for="1359474005787" id="label1359474005786" net2class="net2-elements">Label</label><input type="text" name="name" id="textbox1359474005787" value="Default value" net2class="net2-elements" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset"></div></div></div><style id="Menu1_style">
.Menu1 li{color:red;}</style>
</body>
</html>
|
getteur7/NET2MOBI
|
net2mobi/generated/Nouveau dossier/index.php
|
PHP
|
gpl-2.0
| 4,120 |
/* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <linux/irq.h>
#include <linux/irqdomain.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_platform.h>
#include <linux/of_fdt.h>
#include <linux/of_irq.h>
#include <linux/memory.h>
#include <linux/regulator/qpnp-regulator.h>
#include <linux/msm_tsens.h>
#include <asm/mach/map.h>
#include <asm/hardware/gic.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include <mach/board.h>
#include <mach/gpiomux.h>
#include <mach/msm_iomap.h>
#include <mach/restart.h>
#ifdef CONFIG_ION_MSM
#include <mach/ion.h>
#endif
#include <mach/msm_memtypes.h>
#include <mach/socinfo.h>
#include <mach/board.h>
#include <mach/clk-provider.h>
#include <mach/msm_smd.h>
#include <mach/rpm-smd.h>
#include <mach/rpm-regulator-smd.h>
#include <mach/msm_smem.h>
#include <linux/msm_thermal.h>
#include "board-dt.h"
#include "clock.h"
#include "platsmp.h"
#include "spm.h"
#include "pm.h"
#include "modem_notifier.h"
#ifdef CONFIG_LCD_KCAL
#include <mach/kcal.h>
#include <linux/module.h>
#include "../../../drivers/video/msm/mdss/mdss_fb.h"
#include <linux/input/sweep2wake.h>
extern void update_preset_lcdc_lut(void);
#endif
static struct memtype_reserve msm8226_reserve_table[] __initdata = {
[MEMTYPE_SMI] = {
},
[MEMTYPE_EBI0] = {
.flags = MEMTYPE_FLAGS_1M_ALIGN,
},
[MEMTYPE_EBI1] = {
.flags = MEMTYPE_FLAGS_1M_ALIGN,
},
};
static int msm8226_paddr_to_memtype(unsigned int paddr)
{
return MEMTYPE_EBI1;
}
static struct of_dev_auxdata msm8226_auxdata_lookup[] __initdata = {
OF_DEV_AUXDATA("qcom,msm-sdcc", 0xF9824000, \
"msm_sdcc.1", NULL),
OF_DEV_AUXDATA("qcom,msm-sdcc", 0xF98A4000, \
"msm_sdcc.2", NULL),
OF_DEV_AUXDATA("qcom,msm-sdcc", 0xF9864000, \
"msm_sdcc.3", NULL),
OF_DEV_AUXDATA("qcom,sdhci-msm", 0xF9824900, \
"msm_sdcc.1", NULL),
OF_DEV_AUXDATA("qcom,sdhci-msm", 0xF98A4900, \
"msm_sdcc.2", NULL),
OF_DEV_AUXDATA("qcom,sdhci-msm", 0xF9864900, \
"msm_sdcc.3", NULL),
OF_DEV_AUXDATA("qcom,hsic-host", 0xF9A00000, "msm_hsic_host", NULL),
{}
};
static struct reserve_info msm8226_reserve_info __initdata = {
.memtype_reserve_table = msm8226_reserve_table,
.paddr_to_memtype = msm8226_paddr_to_memtype,
};
static void __init msm8226_early_memory(void)
{
reserve_info = &msm8226_reserve_info;
of_scan_flat_dt(dt_scan_for_memory_hole, msm8226_reserve_table);
}
static void __init msm8226_reserve(void)
{
reserve_info = &msm8226_reserve_info;
of_scan_flat_dt(dt_scan_for_memory_reserve, msm8226_reserve_table);
msm_reserve();
}
#ifdef CONFIG_LCD_KCAL
int g_kcal_r = 255;
int g_kcal_g = 255;
int g_kcal_b = 255;
int g_kcal_min = 35;
extern int down_kcal, up_kcal;
extern void sweep2wake_pwrtrigger(void);
int kcal_set_values(int kcal_r, int kcal_g, int kcal_b)
{
if (kcal_r > 255 || kcal_r < 0)
kcal_r = kcal_r < 0 ? 0 : kcal_r;
kcal_r = kcal_r > 255 ? 255 : kcal_r;
if (kcal_g > 255 || kcal_g < 0)
kcal_g = kcal_g < 0 ? 0 : kcal_g;
kcal_g = kcal_g > 255 ? 255 : kcal_g;
if (kcal_b > 255 || kcal_b < 0)
kcal_b = kcal_b < 0 ? 0 : kcal_b;
kcal_b = kcal_b > 255 ? 255 : kcal_b;
g_kcal_r = kcal_r < g_kcal_min ? g_kcal_min : kcal_r;
g_kcal_g = kcal_g < g_kcal_min ? g_kcal_min : kcal_g;
g_kcal_b = kcal_b < g_kcal_min ? g_kcal_min : kcal_b;
return 0;
}
static int kcal_get_values(int *kcal_r, int *kcal_g, int *kcal_b)
{
*kcal_r = g_kcal_r;
*kcal_g = g_kcal_g;
*kcal_b = g_kcal_b;
return 0;
}
int kcal_set_min(int kcal_min)
{
if (kcal_min > 255 || kcal_min < 0) {
kcal_min = kcal_min < 0 ? 0 : kcal_min;
kcal_min = kcal_min > 255 ? 255 : kcal_min;
}
g_kcal_min = kcal_min;
if (g_kcal_min > g_kcal_r || g_kcal_min > g_kcal_g || g_kcal_min > g_kcal_b) {
g_kcal_r = g_kcal_r < g_kcal_min ? g_kcal_min : g_kcal_r;
g_kcal_g = g_kcal_g < g_kcal_min ? g_kcal_min : g_kcal_g;
g_kcal_b = g_kcal_b < g_kcal_min ? g_kcal_min : g_kcal_b;
update_preset_lcdc_lut();
}
return 0;
}
static int kcal_get_min(int *kcal_min)
{
*kcal_min = g_kcal_min;
return 0;
}
static int kcal_refresh_values(void)
{
update_preset_lcdc_lut();
return 0;
}
void kcal_send_s2d(int set)
{
int r, g, b;
r = g_kcal_r;
g = g_kcal_g;
b = g_kcal_b;
if (set == 1) {
r = r - down_kcal;
g = g - down_kcal;
b = b - down_kcal;
if ((r < g_kcal_min) && (g < g_kcal_min) && (b < g_kcal_min))
sweep2wake_pwrtrigger();
} else if (set == 2) {
if ((r == 255) && (g == 255) && (b == 255))
return;
r = r + up_kcal;
g = g + up_kcal;
b = b + up_kcal;
}
kcal_set_values(r, g, b);
update_preset_lcdc_lut();
return;
}
static struct kcal_platform_data kcal_pdata = {
.set_values = kcal_set_values,
.get_values = kcal_get_values,
.refresh_display = kcal_refresh_values,
.set_min = kcal_set_min,
.get_min = kcal_get_min
};
static struct platform_device kcal_platrom_device = {
.name = "kcal_ctrl",
.dev = {
.platform_data = &kcal_pdata,
}
};
void __init add_lcd_kcal_devices(void)
{
pr_info (" LCD_KCAL_DEBUG : %s \n", __func__);
platform_device_register(&kcal_platrom_device);
};
#endif
/*
* Used to satisfy dependencies for devices that need to be
* run early or in a particular order. Most likely your device doesn't fall
* into this category, and thus the driver should not be added here. The
* EPROBE_DEFER can satisfy most dependency problems.
*/
void __init msm8226_add_drivers(void)
{
msm_smem_init();
msm_init_modem_notifier_list();
msm_smd_init();
msm_rpm_driver_init();
msm_spm_device_init();
msm_pm_sleep_status_init();
rpm_regulator_smd_driver_init();
qpnp_regulator_init();
if (of_board_is_rumi())
msm_clock_init(&msm8226_rumi_clock_init_data);
else
msm_clock_init(&msm8226_clock_init_data);
tsens_tm_init_driver();
msm_thermal_device_init();
#ifdef CONFIG_LCD_KCAL
add_lcd_kcal_devices();
#endif
}
void __init msm8226_init(void)
{
struct of_dev_auxdata *adata = msm8226_auxdata_lookup;
if (socinfo_init() < 0)
pr_err("%s: socinfo_init() failed\n", __func__);
/* Don't do hard-coded muxing for moto platform */
if (!platform_is_msm8226_moto())
msm8226_init_gpiomux();
board_dt_populate(adata);
msm8226_add_drivers();
}
static const char *msm8226_dt_match[] __initconst = {
"qcom,msm8226",
"qcom,msm8926",
"qcom,apq8026",
NULL
};
DT_MACHINE_START(MSM8226_DT, "Qualcomm MSM 8226 (Flattened Device Tree)")
.map_io = msm_map_msm8226_io,
.init_irq = msm_dt_init_irq,
.init_machine = msm8226_init,
.handle_irq = gic_handle_irq,
.timer = &msm_dt_timer,
.dt_compat = msm8226_dt_match,
.reserve = msm8226_reserve,
.init_very_early = msm8226_early_memory,
.restart = msm_restart,
.smp = &arm_smp_ops,
MACHINE_END
|
LiquidSmooth-Devices/android_kernel_motorola_msm8226
|
arch/arm/mach-msm/board-8226.c
|
C
|
gpl-2.0
| 7,278 |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Class to dynamically create an HTML SELECT
*
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to version 3.01 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_01.txt If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to [email protected] so we can mail you a copy immediately.
*
* @category HTML
* @package HTML_QuickForm
* @author Adam Daniel <[email protected]>
* @author Bertrand Mansion <[email protected]>
* @author Alexey Borzov <[email protected]>
* @copyright 2001-2007 The PHP Group
* @license http://www.php.net/license/3_01.txt PHP License 3.01
* @version CVS: $Id: select.php,v 1.33 2007/06/03 15:01:00 avb Exp $
* @link http://pear.php.net/package/HTML_QuickForm
*/
/**
* Base class for form elements
*/
require_once 'HTML/QuickForm/element.php';
/**
* Class to dynamically create an HTML SELECT
*
* @category HTML
* @package HTML_QuickForm
* @author Adam Daniel <[email protected]>
* @author Bertrand Mansion <[email protected]>
* @author Alexey Borzov <[email protected]>
* @version Release: 3.2.10
* @since 1.0
*/
class HTML_QuickForm_select extends HTML_QuickForm_element {
// {{{ properties
/**
* Contains the select options
*
* @var array
* @since 1.0
* @access private
*/
var $_options = array();
/**
* Default values of the SELECT
*
* @var string
* @since 1.0
* @access private
*/
var $_values = null;
// }}}
// {{{ constructor
/**
* Class constructor
*
* @param string Select name attribute
* @param mixed Label(s) for the select
* @param mixed Data to be used to populate options
* @param mixed Either a typical HTML attribute string or an associative array
* @since 1.0
* @access public
* @return void
*/
function HTML_QuickForm_select($elementName=null, $elementLabel=null, $options=null, $attributes=null)
{
HTML_QuickForm_element::HTML_QuickForm_element($elementName, $elementLabel, $attributes);
$this->_persistantFreeze = true;
$this->_type = 'select';
if (isset($options)) {
$this->load($options);
}
} //end constructor
// }}}
// {{{ apiVersion()
/**
* Returns the current API version
*
* @since 1.0
* @access public
* @return double
*/
function apiVersion()
{
return 2.3;
} //end func apiVersion
// }}}
// {{{ setSelected()
/**
* Sets the default values of the select box
*
* @param mixed $values Array or comma delimited string of selected values
* @since 1.0
* @access public
* @return void
*/
function setSelected($values)
{
if (is_string($values) && $this->getMultiple()) {
$values = split("[ ]?,[ ]?", $values);
}
if (is_array($values)) {
$this->_values = array_values($values);
} else {
$this->_values = array($values);
}
} //end func setSelected
// }}}
// {{{ getSelected()
/**
* Returns an array of the selected values
*
* @since 1.0
* @access public
* @return array of selected values
*/
function getSelected()
{
return $this->_values;
} // end func getSelected
// }}}
// {{{ setName()
/**
* Sets the input field name
*
* @param string $name Input field name attribute
* @since 1.0
* @access public
* @return void
*/
function setName($name)
{
$this->updateAttributes(array('name' => $name));
} //end func setName
// }}}
// {{{ getName()
/**
* Returns the element name
*
* @since 1.0
* @access public
* @return string
*/
function getName()
{
return $this->getAttribute('name');
} //end func getName
// }}}
// {{{ getPrivateName()
/**
* Returns the element name (possibly with brackets appended)
*
* @since 1.0
* @access public
* @return string
*/
function getPrivateName()
{
if ($this->getAttribute('multiple')) {
return $this->getName() . '[]';
} else {
return $this->getName();
}
} //end func getPrivateName
// }}}
// {{{ setValue()
/**
* Sets the value of the form element
*
* @param mixed $values Array or comma delimited string of selected values
* @since 1.0
* @access public
* @return void
*/
function setValue($value)
{
$this->setSelected($value);
} // end func setValue
// }}}
// {{{ getValue()
/**
* Returns an array of the selected values
*
* @since 1.0
* @access public
* @return array of selected values
*/
function getValue()
{
return $this->_values;
} // end func getValue
// }}}
// {{{ setSize()
/**
* Sets the select field size, only applies to 'multiple' selects
*
* @param int $size Size of select field
* @since 1.0
* @access public
* @return void
*/
function setSize($size)
{
$this->updateAttributes(array('size' => $size));
} //end func setSize
// }}}
// {{{ getSize()
/**
* Returns the select field size
*
* @since 1.0
* @access public
* @return int
*/
function getSize()
{
return $this->getAttribute('size');
} //end func getSize
// }}}
// {{{ setMultiple()
/**
* Sets the select mutiple attribute
*
* @param bool $multiple Whether the select supports multi-selections
* @since 1.2
* @access public
* @return void
*/
function setMultiple($multiple)
{
if ($multiple) {
$this->updateAttributes(array('multiple' => 'multiple'));
} else {
$this->removeAttribute('multiple');
}
} //end func setMultiple
// }}}
// {{{ getMultiple()
/**
* Returns the select mutiple attribute
*
* @since 1.2
* @access public
* @return bool true if multiple select, false otherwise
*/
function getMultiple()
{
return (bool)$this->getAttribute('multiple');
} //end func getMultiple
// }}}
// {{{ addOption()
/**
* Adds a new OPTION to the SELECT
*
* @param string $text Display text for the OPTION
* @param string $value Value for the OPTION
* @param mixed $attributes Either a typical HTML attribute string
* or an associative array
* @since 1.0
* @access public
* @return void
*/
function addOption($text, $value, $attributes=null)
{
if (null === $attributes) {
$attributes = array('value' => (string)$value);
} else {
$attributes = $this->_parseAttributes($attributes);
if (isset($attributes['selected'])) {
// the 'selected' attribute will be set in toHtml()
$this->_removeAttr('selected', $attributes);
if (is_null($this->_values)) {
$this->_values = array($value);
} elseif (!in_array($value, $this->_values)) {
$this->_values[] = $value;
}
}
$this->_updateAttrArray($attributes, array('value' => (string)$value));
}
$this->_options[] = array('text' => $text, 'attr' => $attributes);
} // end func addOption
// }}}
// {{{ loadArray()
/**
* Loads the options from an associative array
*
* @param array $arr Associative array of options
* @param mixed $values (optional) Array or comma delimited string of selected values
* @since 1.0
* @access public
* @return PEAR_Error on error or true
* @throws PEAR_Error
*/
function loadArray($arr, $values=null)
{
if (!is_array($arr)) {
return PEAR::raiseError('Argument 1 of HTML_Select::loadArray is not a valid array');
}
if (isset($values)) {
$this->setSelected($values);
}
foreach ($arr as $key => $val) {
// Warning: new API since release 2.3
$this->addOption($val, $key);
}
return true;
} // end func loadArray
// }}}
// {{{ loadDbResult()
/**
* Loads the options from DB_result object
*
* If no column names are specified the first two columns of the result are
* used as the text and value columns respectively
* @param object $result DB_result object
* @param string $textCol (optional) Name of column to display as the OPTION text
* @param string $valueCol (optional) Name of column to use as the OPTION value
* @param mixed $values (optional) Array or comma delimited string of selected values
* @since 1.0
* @access public
* @return PEAR_Error on error or true
* @throws PEAR_Error
*/
function loadDbResult(&$result, $textCol=null, $valueCol=null, $values=null)
{
if (!is_object($result) || !is_a($result, 'db_result')) {
return PEAR::raiseError('Argument 1 of HTML_Select::loadDbResult is not a valid DB_result');
}
if (isset($values)) {
$this->setValue($values);
}
$fetchMode = ($textCol && $valueCol) ? DB_FETCHMODE_ASSOC : DB_FETCHMODE_ORDERED;
while (is_array($row = $result->fetchRow($fetchMode)) ) {
if ($fetchMode == DB_FETCHMODE_ASSOC) {
$this->addOption($row[$textCol], $row[$valueCol]);
} else {
$this->addOption($row[0], $row[1]);
}
}
return true;
} // end func loadDbResult
// }}}
// {{{ loadQuery()
/**
* Queries a database and loads the options from the results
*
* @param mixed $conn Either an existing DB connection or a valid dsn
* @param string $sql SQL query string
* @param string $textCol (optional) Name of column to display as the OPTION text
* @param string $valueCol (optional) Name of column to use as the OPTION value
* @param mixed $values (optional) Array or comma delimited string of selected values
* @since 1.1
* @access public
* @return void
* @throws PEAR_Error
*/
function loadQuery(&$conn, $sql, $textCol=null, $valueCol=null, $values=null)
{
if (is_string($conn)) {
require_once('DB.php');
$dbConn = &DB::connect($conn, true);
if (DB::isError($dbConn)) {
return $dbConn;
}
} elseif (is_subclass_of($conn, "db_common")) {
$dbConn = &$conn;
} else {
return PEAR::raiseError('Argument 1 of HTML_Select::loadQuery is not a valid type');
}
$result = $dbConn->query($sql);
if (DB::isError($result)) {
return $result;
}
$this->loadDbResult($result, $textCol, $valueCol, $values);
$result->free();
if (is_string($conn)) {
$dbConn->disconnect();
}
return true;
} // end func loadQuery
// }}}
// {{{ load()
/**
* Loads options from different types of data sources
*
* This method is a simulated overloaded method. The arguments, other than the
* first are optional and only mean something depending on the type of the first argument.
* If the first argument is an array then all arguments are passed in order to loadArray.
* If the first argument is a db_result then all arguments are passed in order to loadDbResult.
* If the first argument is a string or a DB connection then all arguments are
* passed in order to loadQuery.
* @param mixed $options Options source currently supports assoc array or DB_result
* @param mixed $param1 (optional) See function detail
* @param mixed $param2 (optional) See function detail
* @param mixed $param3 (optional) See function detail
* @param mixed $param4 (optional) See function detail
* @since 1.1
* @access public
* @return PEAR_Error on error or true
* @throws PEAR_Error
*/
function load(&$options, $param1=null, $param2=null, $param3=null, $param4=null)
{
switch (true) {
case is_array($options):
return $this->loadArray($options, $param1);
break;
case (is_a($options, 'db_result')):
return $this->loadDbResult($options, $param1, $param2, $param3);
break;
case (is_string($options) && !empty($options) || is_subclass_of($options, "db_common")):
return $this->loadQuery($options, $param1, $param2, $param3, $param4);
break;
}
} // end func load
// }}}
// {{{ toHtml()
/**
* Returns the SELECT in HTML
*
* @since 1.0
* @access public
* @return string
*/
function toHtml()
{
if ($this->_flagFrozen) {
return $this->getFrozenHtml();
} else {
$tabs = $this->_getTabs();
$strHtml = '';
if ($this->getComment() != '') {
$strHtml .= $tabs . '<!-- ' . $this->getComment() . " //-->\n";
}
if (!$this->getMultiple()) {
$attrString = $this->_getAttrString($this->_attributes);
} else {
$myName = $this->getName();
$this->setName($myName . '[]');
$attrString = $this->_getAttrString($this->_attributes);
$this->setName($myName);
}
$strHtml .= $tabs . '<select' . $attrString . ">\n";
$strValues = is_array($this->_values)? array_map('strval', $this->_values): array();
foreach ($this->_options as $option) {
if (!empty($strValues) && in_array($option['attr']['value'], $strValues, true)) {
$option['attr']['selected'] = 'selected';
}
$strHtml .= $tabs . "\t<option" . $this->_getAttrString($option['attr']) . '>' .
$option['text'] . "</option>\n";
}
return $strHtml . $tabs . '</select>';
}
} //end func toHtml
// }}}
// {{{ getFrozenHtml()
/**
* Returns the value of field without HTML tags
*
* @since 1.0
* @access public
* @return string
*/
function getFrozenHtml()
{
$value = array();
if (is_array($this->_values)) {
foreach ($this->_values as $key => $val) {
for ($i = 0, $optCount = count($this->_options); $i < $optCount; $i++) {
if (0 == strcmp($val, $this->_options[$i]['attr']['value'])) {
$value[$key] = $this->_options[$i]['text'];
break;
}
}
}
}
$html = empty($value)? ' ': join('<br />', $value);
if ($this->_persistantFreeze) {
$name = $this->getPrivateName();
// Only use id attribute if doing single hidden input
if (1 == count($value)) {
$id = $this->getAttribute('id');
$idAttr = isset($id)? array('id' => $id): array();
} else {
$idAttr = array();
}
foreach ($value as $key => $item) {
$html .= '<input' . $this->_getAttrString(array(
'type' => 'hidden',
'name' => $name,
'value' => $this->_values[$key]
) + $idAttr) . ' />';
}
}
return $html;
} //end func getFrozenHtml
// }}}
// {{{ exportValue()
/**
* We check the options and return only the values that _could_ have been
* selected. We also return a scalar value if select is not "multiple"
*/
function exportValue(&$submitValues, $assoc = false)
{
$value = $this->_findValue($submitValues);
if (is_null($value)) {
$value = $this->getValue();
} elseif(!is_array($value)) {
$value = array($value);
}
if (is_array($value) && !empty($this->_options)) {
$cleanValue = null;
foreach ($value as $v) {
for ($i = 0, $optCount = count($this->_options); $i < $optCount; $i++) {
if (0 == strcmp($v, $this->_options[$i]['attr']['value'])) {
$cleanValue[] = $v;
break;
}
}
}
} else {
$cleanValue = $value;
}
if (is_array($cleanValue) && !$this->getMultiple()) {
return $this->_prepareValue($cleanValue[0], $assoc);
} else {
return $this->_prepareValue($cleanValue, $assoc);
}
}
// }}}
// {{{ onQuickFormEvent()
function onQuickFormEvent($event, $arg, &$caller)
{
if ('updateValue' == $event) {
$value = $this->_findValue($caller->_constantValues);
if (null === $value) {
$value = $this->_findValue($caller->_submitValues);
// Fix for bug #4465 & #5269
// XXX: should we push this to element::onQuickFormEvent()?
if (null === $value && (!$caller->isSubmitted() || !$this->getMultiple())) {
$value = $this->_findValue($caller->_defaultValues);
}
}
if (null !== $value) {
$this->setValue($value);
}
return true;
} else {
return parent::onQuickFormEvent($event, $arg, $caller);
}
}
// }}}
} //end class HTML_QuickForm_select
?>
|
lucor/ortro
|
lib/Pear/HTML/QuickForm/select.php
|
PHP
|
gpl-2.0
| 19,500 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2011 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Authors: Nicola Baldo <[email protected]>
* Marco Miozzo <[email protected]>
* Manuel Requena <[email protected]>
*/
#include "lte-enb-rrc.h"
#include <ns3/fatal-error.h>
#include <ns3/log.h>
#include <ns3/abort.h>
#include <ns3/pointer.h>
#include <ns3/object-map.h>
#include <ns3/object-factory.h>
#include <ns3/simulator.h>
#include <ns3/lte-radio-bearer-info.h>
#include <ns3/eps-bearer-tag.h>
#include <ns3/packet.h>
#include <ns3/lte-rlc.h>
#include <ns3/lte-rlc-tm.h>
#include <ns3/lte-rlc-um.h>
#include <ns3/lte-rlc-am.h>
#include <ns3/lte-pdcp.h>
NS_LOG_COMPONENT_DEFINE ("LteEnbRrc");
namespace ns3 {
///////////////////////////////////////////
// CMAC SAP forwarder
///////////////////////////////////////////
/**
* \brief Class for forwarding CMAC SAP User functions.
*/
class EnbRrcMemberLteEnbCmacSapUser : public LteEnbCmacSapUser
{
public:
EnbRrcMemberLteEnbCmacSapUser (LteEnbRrc* rrc);
virtual uint16_t AllocateTemporaryCellRnti ();
virtual void NotifyLcConfigResult (uint16_t rnti, uint8_t lcid, bool success);
virtual void RrcConfigurationUpdateInd (UeConfig params);
private:
LteEnbRrc* m_rrc;
};
EnbRrcMemberLteEnbCmacSapUser::EnbRrcMemberLteEnbCmacSapUser (LteEnbRrc* rrc)
: m_rrc (rrc)
{
}
uint16_t
EnbRrcMemberLteEnbCmacSapUser::AllocateTemporaryCellRnti ()
{
return m_rrc->DoAllocateTemporaryCellRnti ();
}
void
EnbRrcMemberLteEnbCmacSapUser::NotifyLcConfigResult (uint16_t rnti, uint8_t lcid, bool success)
{
m_rrc->DoNotifyLcConfigResult (rnti, lcid, success);
}
void
EnbRrcMemberLteEnbCmacSapUser::RrcConfigurationUpdateInd (UeConfig params)
{
m_rrc->DoRrcConfigurationUpdateInd (params);
}
///////////////////////////////////////////
// UeManager
///////////////////////////////////////////
static const std::string g_ueManagerStateName[UeManager::NUM_STATES] =
{
"INITIAL_RANDOM_ACCESS",
"CONNECTION_SETUP",
"CONNECTION_REJECTED",
"CONNECTED_NORMALLY",
"CONNECTION_RECONFIGURATION",
"CONNECTION_REESTABLISHMENT",
"HANDOVER_PREPARATION",
"HANDOVER_JOINING",
"HANDOVER_PATH_SWITCH",
"HANDOVER_LEAVING",
};
static const std::string & ToString (UeManager::State s)
{
return g_ueManagerStateName[s];
}
NS_OBJECT_ENSURE_REGISTERED (UeManager);
UeManager::UeManager ()
{
NS_FATAL_ERROR ("this constructor is not espected to be used");
}
UeManager::UeManager (Ptr<LteEnbRrc> rrc, uint16_t rnti, State s)
: m_lastAllocatedDrbid (0),
m_rnti (rnti),
m_imsi (0),
m_lastRrcTransactionIdentifier (0),
m_rrc (rrc),
m_state (s),
m_pendingRrcConnectionReconfiguration (false),
m_sourceX2apId (0),
m_sourceCellId (0),
m_needTransmissionModeConfiguration (false)
{
NS_LOG_FUNCTION (this);
}
void
UeManager::DoInitialize ()
{
NS_LOG_FUNCTION (this);
m_drbPdcpSapUser = new LtePdcpSpecificLtePdcpSapUser<UeManager> (this);
m_physicalConfigDedicated.haveAntennaInfoDedicated = true;
m_physicalConfigDedicated.antennaInfo.transmissionMode = m_rrc->m_defaultTransmissionMode;
m_physicalConfigDedicated.haveSoundingRsUlConfigDedicated = true;
m_physicalConfigDedicated.soundingRsUlConfigDedicated.srsConfigIndex = m_rrc->GetNewSrsConfigurationIndex ();
m_physicalConfigDedicated.soundingRsUlConfigDedicated.type = LteRrcSap::SoundingRsUlConfigDedicated::SETUP;
m_physicalConfigDedicated.soundingRsUlConfigDedicated.srsBandwidth = 0;
m_rrc->m_cmacSapProvider->AddUe (m_rnti);
m_rrc->m_cphySapProvider->AddUe (m_rnti);
// setup the eNB side of SRB0
{
uint8_t lcid = 0;
Ptr<LteRlc> rlc = CreateObject<LteRlcTm> ()->GetObject<LteRlc> ();
rlc->SetLteMacSapProvider (m_rrc->m_macSapProvider);
rlc->SetRnti (m_rnti);
rlc->SetLcId (lcid);
m_srb0 = CreateObject<LteSignalingRadioBearerInfo> ();
m_srb0->m_rlc = rlc;
m_srb0->m_srbIdentity = 0;
// no need to store logicalChannelConfig as SRB0 is pre-configured
LteEnbCmacSapProvider::LcInfo lcinfo;
lcinfo.rnti = m_rnti;
lcinfo.lcId = lcid;
// leave the rest of lcinfo empty as CCCH (LCID 0) is pre-configured
m_rrc->m_cmacSapProvider->AddLc (lcinfo, rlc->GetLteMacSapUser ());
}
// setup the eNB side of SRB1; the UE side will be set up upon RRC connection establishment
{
uint8_t lcid = 1;
Ptr<LteRlc> rlc = CreateObject<LteRlcAm> ()->GetObject<LteRlc> ();
rlc->SetLteMacSapProvider (m_rrc->m_macSapProvider);
rlc->SetRnti (m_rnti);
rlc->SetLcId (lcid);
Ptr<LtePdcp> pdcp = CreateObject<LtePdcp> ();
pdcp->SetRnti (m_rnti);
pdcp->SetLcId (lcid);
pdcp->SetLtePdcpSapUser (m_drbPdcpSapUser);
pdcp->SetLteRlcSapProvider (rlc->GetLteRlcSapProvider ());
rlc->SetLteRlcSapUser (pdcp->GetLteRlcSapUser ());
m_srb1 = CreateObject<LteSignalingRadioBearerInfo> ();
m_srb1->m_rlc = rlc;
m_srb1->m_pdcp = pdcp;
m_srb1->m_srbIdentity = 1;
m_srb1->m_logicalChannelConfig.priority = 0;
m_srb1->m_logicalChannelConfig.prioritizedBitRateKbps = 100;
m_srb1->m_logicalChannelConfig.bucketSizeDurationMs = 100;
m_srb1->m_logicalChannelConfig.logicalChannelGroup = 0;
LteEnbCmacSapProvider::LcInfo lcinfo;
lcinfo.rnti = m_rnti;
lcinfo.lcId = lcid;
lcinfo.lcGroup = 0; // all SRBs always mapped to LCG 0
lcinfo.qci = EpsBearer::GBR_CONV_VOICE; // not sure why the FF API requires a CQI even for SRBs...
lcinfo.isGbr = true;
lcinfo.mbrUl = 1e6;
lcinfo.mbrDl = 1e6;
lcinfo.gbrUl = 1e4;
lcinfo.gbrDl = 1e4;
m_rrc->m_cmacSapProvider->AddLc (lcinfo, rlc->GetLteMacSapUser ());
}
LteEnbRrcSapUser::SetupUeParameters ueParams;
ueParams.srb0SapProvider = m_srb0->m_rlc->GetLteRlcSapProvider ();
ueParams.srb1SapProvider = m_srb1->m_pdcp->GetLtePdcpSapProvider ();
m_rrc->m_rrcSapUser->SetupUe (m_rnti, ueParams);
// configure MAC (and scheduler)
LteEnbCmacSapProvider::UeConfig req;
req.m_rnti = m_rnti;
req.m_transmissionMode = m_physicalConfigDedicated.antennaInfo.transmissionMode;
m_rrc->m_cmacSapProvider->UeUpdateConfigurationReq (req);
// configure PHY
m_rrc->m_cphySapProvider->SetTransmissionMode (m_rnti, m_physicalConfigDedicated.antennaInfo.transmissionMode);
m_rrc->m_cphySapProvider->SetSrsConfigurationIndex (m_rnti, m_physicalConfigDedicated.soundingRsUlConfigDedicated.srsConfigIndex);
// schedule this UeManager instance to be deleted if the UE does not give any sign of life within a reasonable time
Time maxConnectionDelay;
switch (m_state)
{
case INITIAL_RANDOM_ACCESS:
m_connectionTimeout = Simulator::Schedule (m_rrc->m_connectionTimeoutDuration,
&LteEnbRrc::ConnectionTimeout,
m_rrc, m_rnti);
break;
case HANDOVER_JOINING:
m_handoverJoiningTimeout = Simulator::Schedule (m_rrc->m_handoverJoiningTimeoutDuration,
&LteEnbRrc::HandoverJoiningTimeout,
m_rrc, m_rnti);
break;
default:
NS_FATAL_ERROR ("unexpected state " << ToString (m_state));
break;
}
}
UeManager::~UeManager (void)
{
}
void
UeManager::DoDispose ()
{
delete m_drbPdcpSapUser;
// delete eventual X2-U TEIDs
for (std::map <uint8_t, Ptr<LteDataRadioBearerInfo> >::iterator it = m_drbMap.begin ();
it != m_drbMap.end ();
++it)
{
m_rrc->m_x2uTeidInfoMap.erase (it->second->m_gtpTeid);
}
}
TypeId UeManager::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::UeManager")
.SetParent<Object> ()
.AddConstructor<UeManager> ()
.AddAttribute ("DataRadioBearerMap", "List of UE DataRadioBearerInfo by DRBID.",
ObjectMapValue (),
MakeObjectMapAccessor (&UeManager::m_drbMap),
MakeObjectMapChecker<LteDataRadioBearerInfo> ())
.AddAttribute ("Srb0", "SignalingRadioBearerInfo for SRB0",
PointerValue (),
MakePointerAccessor (&UeManager::m_srb0),
MakePointerChecker<LteSignalingRadioBearerInfo> ())
.AddAttribute ("Srb1", "SignalingRadioBearerInfo for SRB1",
PointerValue (),
MakePointerAccessor (&UeManager::m_srb1),
MakePointerChecker<LteSignalingRadioBearerInfo> ())
.AddAttribute ("C-RNTI",
"Cell Radio Network Temporary Identifier",
TypeId::ATTR_GET, // read-only attribute
UintegerValue (0), // unused, read-only attribute
MakeUintegerAccessor (&UeManager::m_rnti),
MakeUintegerChecker<uint16_t> ())
.AddTraceSource ("StateTransition",
"fired upon every UE state transition seen by the UeManager at the eNB RRC",
MakeTraceSourceAccessor (&UeManager::m_stateTransitionTrace))
;
return tid;
}
void
UeManager::SetSource (uint16_t sourceCellId, uint16_t sourceX2apId)
{
m_sourceX2apId = sourceX2apId;
m_sourceCellId = sourceCellId;
}
void
UeManager::SetImsi (uint64_t imsi)
{
m_imsi = imsi;
}
void
UeManager::SetupDataRadioBearer (EpsBearer bearer, uint8_t bearerId, uint32_t gtpTeid, Ipv4Address transportLayerAddress)
{
NS_LOG_FUNCTION (this << (uint32_t) m_rnti);
Ptr<LteDataRadioBearerInfo> drbInfo = CreateObject<LteDataRadioBearerInfo> ();
uint8_t drbid = AddDataRadioBearerInfo (drbInfo);
uint8_t lcid = Drbid2Lcid (drbid);
uint8_t bid = Drbid2Bid (drbid);
NS_ASSERT_MSG ( bearerId == 0 || bid == bearerId, "bearer ID mismatch (" << (uint32_t) bid << " != " << (uint32_t) bearerId << ", the assumption that ID are allocated in the same way by MME and RRC is not valid any more");
drbInfo->m_epsBearerIdentity = bid;
drbInfo->m_drbIdentity = drbid;
drbInfo->m_logicalChannelIdentity = lcid;
drbInfo->m_gtpTeid = gtpTeid;
drbInfo->m_transportLayerAddress = transportLayerAddress;
if (m_state == HANDOVER_JOINING)
{
// setup TEIDs for receiving data eventually forwarded over X2-U
LteEnbRrc::X2uTeidInfo x2uTeidInfo;
x2uTeidInfo.rnti = m_rnti;
x2uTeidInfo.drbid = drbid;
std::pair<std::map<uint32_t, LteEnbRrc::X2uTeidInfo>::iterator, bool>
ret = m_rrc->m_x2uTeidInfoMap.insert (std::pair<uint32_t, LteEnbRrc::X2uTeidInfo> (gtpTeid, x2uTeidInfo));
NS_ASSERT_MSG (ret.second == true, "overwriting a pre-existing entry in m_x2uTeidInfoMap");
}
TypeId rlcTypeId = m_rrc->GetRlcType (bearer);
ObjectFactory rlcObjectFactory;
rlcObjectFactory.SetTypeId (rlcTypeId);
Ptr<LteRlc> rlc = rlcObjectFactory.Create ()->GetObject<LteRlc> ();
rlc->SetLteMacSapProvider (m_rrc->m_macSapProvider);
rlc->SetRnti (m_rnti);
drbInfo->m_rlc = rlc;
rlc->SetLcId (lcid);
// we need PDCP only for real RLC, i.e., RLC/UM or RLC/AM
// if we are using RLC/SM we don't care of anything above RLC
if (rlcTypeId != LteRlcSm::GetTypeId ())
{
Ptr<LtePdcp> pdcp = CreateObject<LtePdcp> ();
pdcp->SetRnti (m_rnti);
pdcp->SetLcId (lcid);
pdcp->SetLtePdcpSapUser (m_drbPdcpSapUser);
pdcp->SetLteRlcSapProvider (rlc->GetLteRlcSapProvider ());
rlc->SetLteRlcSapUser (pdcp->GetLteRlcSapUser ());
drbInfo->m_pdcp = pdcp;
}
LteEnbCmacSapProvider::LcInfo lcinfo;
lcinfo.rnti = m_rnti;
lcinfo.lcId = lcid;
lcinfo.lcGroup = m_rrc->GetLogicalChannelGroup (bearer);
lcinfo.qci = bearer.qci;
lcinfo.isGbr = bearer.IsGbr ();
lcinfo.mbrUl = bearer.gbrQosInfo.mbrUl;
lcinfo.mbrDl = bearer.gbrQosInfo.mbrDl;
lcinfo.gbrUl = bearer.gbrQosInfo.gbrUl;
lcinfo.gbrDl = bearer.gbrQosInfo.gbrDl;
m_rrc->m_cmacSapProvider->AddLc (lcinfo, rlc->GetLteMacSapUser ());
if (rlcTypeId == LteRlcAm::GetTypeId ())
{
drbInfo->m_rlcConfig.choice = LteRrcSap::RlcConfig::AM;
}
else
{
drbInfo->m_rlcConfig.choice = LteRrcSap::RlcConfig::UM_BI_DIRECTIONAL;
}
drbInfo->m_logicalChannelIdentity = lcid;
drbInfo->m_logicalChannelConfig.priority = m_rrc->GetLogicalChannelPriority (bearer);
drbInfo->m_logicalChannelConfig.logicalChannelGroup = m_rrc->GetLogicalChannelGroup (bearer);
if (bearer.IsGbr ())
{
drbInfo->m_logicalChannelConfig.prioritizedBitRateKbps = bearer.gbrQosInfo.gbrUl;
}
else
{
drbInfo->m_logicalChannelConfig.prioritizedBitRateKbps = 0;
}
drbInfo->m_logicalChannelConfig.bucketSizeDurationMs = 1000;
ScheduleRrcConnectionReconfiguration ();
}
void
UeManager::RecordDataRadioBearersToBeStarted ()
{
NS_LOG_FUNCTION (this << (uint32_t) m_rnti);
for (std::map <uint8_t, Ptr<LteDataRadioBearerInfo> >::iterator it = m_drbMap.begin ();
it != m_drbMap.end ();
++it)
{
m_drbsToBeStarted.push_back (it->first);
}
}
void
UeManager::StartDataRadioBearers ()
{
NS_LOG_FUNCTION (this << (uint32_t) m_rnti);
for (std::list <uint8_t>::iterator drbIdIt = m_drbsToBeStarted.begin ();
drbIdIt != m_drbsToBeStarted.end ();
++drbIdIt)
{
std::map <uint8_t, Ptr<LteDataRadioBearerInfo> >::iterator drbIt = m_drbMap.find (*drbIdIt);
NS_ASSERT (drbIt != m_drbMap.end ());
drbIt->second->m_rlc->Initialize ();
if (drbIt->second->m_pdcp)
{
drbIt->second->m_pdcp->Initialize ();
}
}
m_drbsToBeStarted.clear ();
}
void
UeManager::ReleaseDataRadioBearer (uint8_t drbid)
{
NS_LOG_FUNCTION (this << (uint32_t) m_rnti << (uint32_t) drbid);
uint8_t lcid = Drbid2Lcid (drbid);
std::map <uint8_t, Ptr<LteDataRadioBearerInfo> >::iterator it = m_drbMap.find (drbid);
NS_ASSERT_MSG (it != m_drbMap.end (), "request to remove radio bearer with unknown drbid " << drbid);
// first delete eventual X2-U TEIDs
m_rrc->m_x2uTeidInfoMap.erase (it->second->m_gtpTeid);
m_drbMap.erase (it);
m_rrc->m_cmacSapProvider->ReleaseLc (m_rnti, lcid);
LteRrcSap::RadioResourceConfigDedicated rrcd;
rrcd.havePhysicalConfigDedicated = false;
rrcd.drbToReleaseList.push_back (drbid);
LteRrcSap::RrcConnectionReconfiguration msg;
msg.haveMeasConfig = false;
msg.haveMobilityControlInfo = false;
m_rrc->m_rrcSapUser->SendRrcConnectionReconfiguration (m_rnti, msg);
}
void
UeManager::ScheduleRrcConnectionReconfiguration ()
{
NS_LOG_FUNCTION (this);
switch (m_state)
{
case INITIAL_RANDOM_ACCESS:
case CONNECTION_SETUP:
case CONNECTION_RECONFIGURATION:
case CONNECTION_REESTABLISHMENT:
case HANDOVER_PREPARATION:
case HANDOVER_JOINING:
case HANDOVER_LEAVING:
// a previous reconfiguration still ongoing, we need to wait for it to be finished
m_pendingRrcConnectionReconfiguration = true;
break;
case CONNECTED_NORMALLY:
{
m_pendingRrcConnectionReconfiguration = false;
LteRrcSap::RrcConnectionReconfiguration msg = BuildRrcConnectionReconfiguration ();
m_rrc->m_rrcSapUser->SendRrcConnectionReconfiguration (m_rnti, msg);
RecordDataRadioBearersToBeStarted ();
SwitchToState (CONNECTION_RECONFIGURATION);
}
break;
default:
NS_FATAL_ERROR ("method unexpected in state " << ToString (m_state));
break;
}
}
void
UeManager::PrepareHandover (uint16_t cellId)
{
NS_LOG_FUNCTION (this << cellId);
switch (m_state)
{
case CONNECTED_NORMALLY:
{
m_targetCellId = cellId;
EpcX2SapProvider::HandoverRequestParams params;
params.oldEnbUeX2apId = m_rnti;
params.cause = EpcX2SapProvider::HandoverDesirableForRadioReason;
params.sourceCellId = m_rrc->m_cellId;
params.targetCellId = cellId;
params.mmeUeS1apId = m_imsi;
params.ueAggregateMaxBitRateDownlink = 200 * 1000;
params.ueAggregateMaxBitRateUplink = 100 * 1000;
params.bearers = GetErabList ();
LteRrcSap::HandoverPreparationInfo hpi;
hpi.asConfig.sourceUeIdentity = m_rnti;
hpi.asConfig.sourceDlCarrierFreq = m_rrc->m_dlEarfcn;
hpi.asConfig.sourceMeasConfig = m_rrc->m_ueMeasConfig;
hpi.asConfig.sourceRadioResourceConfig = GetRadioResourceConfigForHandoverPreparationInfo ();
hpi.asConfig.sourceMasterInformationBlock.dlBandwidth = m_rrc->m_dlBandwidth;
hpi.asConfig.sourceMasterInformationBlock.systemFrameNumber = 0;
hpi.asConfig.sourceSystemInformationBlockType1.cellAccessRelatedInfo.plmnIdentityInfo.plmnIdentity = m_rrc->m_sib1.cellAccessRelatedInfo.plmnIdentityInfo.plmnIdentity;
hpi.asConfig.sourceSystemInformationBlockType1.cellAccessRelatedInfo.cellIdentity = m_rrc->m_cellId;
hpi.asConfig.sourceSystemInformationBlockType1.cellAccessRelatedInfo.csgIndication = m_rrc->m_sib1.cellAccessRelatedInfo.csgIndication;
hpi.asConfig.sourceSystemInformationBlockType1.cellAccessRelatedInfo.csgIdentity = m_rrc->m_sib1.cellAccessRelatedInfo.csgIdentity;
LteEnbCmacSapProvider::RachConfig rc = m_rrc->m_cmacSapProvider->GetRachConfig ();
hpi.asConfig.sourceSystemInformationBlockType2.radioResourceConfigCommon.rachConfigCommon.preambleInfo.numberOfRaPreambles = rc.numberOfRaPreambles;
hpi.asConfig.sourceSystemInformationBlockType2.radioResourceConfigCommon.rachConfigCommon.raSupervisionInfo.preambleTransMax = rc.preambleTransMax;
hpi.asConfig.sourceSystemInformationBlockType2.radioResourceConfigCommon.rachConfigCommon.raSupervisionInfo.raResponseWindowSize = rc.raResponseWindowSize;
hpi.asConfig.sourceSystemInformationBlockType2.freqInfo.ulCarrierFreq = m_rrc->m_ulEarfcn;
hpi.asConfig.sourceSystemInformationBlockType2.freqInfo.ulBandwidth = m_rrc->m_ulBandwidth;
params.rrcContext = m_rrc->m_rrcSapUser->EncodeHandoverPreparationInformation (hpi);
NS_LOG_LOGIC ("oldEnbUeX2apId = " << params.oldEnbUeX2apId);
NS_LOG_LOGIC ("sourceCellId = " << params.sourceCellId);
NS_LOG_LOGIC ("targetCellId = " << params.targetCellId);
NS_LOG_LOGIC ("mmeUeS1apId = " << params.mmeUeS1apId);
NS_LOG_LOGIC ("rrcContext = " << params.rrcContext);
m_rrc->m_x2SapProvider->SendHandoverRequest (params);
SwitchToState (HANDOVER_PREPARATION);
}
break;
default:
NS_FATAL_ERROR ("method unexpected in state " << ToString (m_state));
break;
}
}
void
UeManager::RecvHandoverRequestAck (EpcX2SapUser::HandoverRequestAckParams params)
{
NS_LOG_FUNCTION (this);
NS_ASSERT_MSG (params.notAdmittedBearers.empty (), "not admission of some bearers upon handover is not supported");
NS_ASSERT_MSG (params.admittedBearers.size () == m_drbMap.size (), "not enough bearers in admittedBearers");
// note: the Handover command from the target eNB to the source eNB
// is expected to be sent transparently to the UE; however, here we
// decode the message and eventually reencode it. This way we can
// support both a real RRC protocol implementation and an ideal one
// without actual RRC protocol encoding.
Ptr<Packet> encodedHandoverCommand = params.rrcContext;
LteRrcSap::RrcConnectionReconfiguration handoverCommand = m_rrc->m_rrcSapUser->DecodeHandoverCommand (encodedHandoverCommand);
m_rrc->m_rrcSapUser->SendRrcConnectionReconfiguration (m_rnti, handoverCommand);
SwitchToState (HANDOVER_LEAVING);
m_handoverLeavingTimeout = Simulator::Schedule (m_rrc->m_handoverLeavingTimeoutDuration,
&LteEnbRrc::HandoverLeavingTimeout,
m_rrc, m_rnti);
NS_ASSERT (handoverCommand.haveMobilityControlInfo);
m_rrc->m_handoverStartTrace (m_imsi, m_rrc->m_cellId, m_rnti, handoverCommand.mobilityControlInfo.targetPhysCellId);
EpcX2SapProvider::SnStatusTransferParams sst;
sst.oldEnbUeX2apId = params.oldEnbUeX2apId;
sst.newEnbUeX2apId = params.newEnbUeX2apId;
sst.sourceCellId = params.sourceCellId;
sst.targetCellId = params.targetCellId;
for ( std::map <uint8_t, Ptr<LteDataRadioBearerInfo> >::iterator drbIt = m_drbMap.begin ();
drbIt != m_drbMap.end ();
++drbIt)
{
// SN status transfer is only for AM RLC
if (0 != drbIt->second->m_rlc->GetObject<LteRlcAm> ())
{
LtePdcp::Status status = drbIt->second->m_pdcp->GetStatus ();
EpcX2Sap::ErabsSubjectToStatusTransferItem i;
i.dlPdcpSn = status.txSn;
i.ulPdcpSn = status.rxSn;
sst.erabsSubjectToStatusTransferList.push_back (i);
}
}
m_rrc->m_x2SapProvider->SendSnStatusTransfer (sst);
}
LteRrcSap::RadioResourceConfigDedicated
UeManager::GetRadioResourceConfigForHandoverPreparationInfo ()
{
NS_LOG_FUNCTION (this);
return BuildRadioResourceConfigDedicated ();
}
LteRrcSap::RrcConnectionReconfiguration
UeManager::GetRrcConnectionReconfigurationForHandover ()
{
NS_LOG_FUNCTION (this);
return BuildRrcConnectionReconfiguration ();
}
void
UeManager::SendData (uint8_t bid, Ptr<Packet> p)
{
NS_LOG_FUNCTION (this << p << (uint16_t) bid);
switch (m_state)
{
case INITIAL_RANDOM_ACCESS:
case CONNECTION_SETUP:
NS_LOG_WARN ("not connected, discarding packet");
return;
break;
case CONNECTED_NORMALLY:
case CONNECTION_RECONFIGURATION:
case CONNECTION_REESTABLISHMENT:
case HANDOVER_PREPARATION:
case HANDOVER_JOINING:
case HANDOVER_PATH_SWITCH:
{
NS_LOG_LOGIC ("queueing data on PDCP for transmission over the air");
LtePdcpSapProvider::TransmitPdcpSduParameters params;
params.pdcpSdu = p;
params.rnti = m_rnti;
params.lcid = Bid2Lcid (bid);
uint8_t drbid = Bid2Drbid (bid);
LtePdcpSapProvider* pdcpSapProvider = GetDataRadioBearerInfo (drbid)->m_pdcp->GetLtePdcpSapProvider ();
pdcpSapProvider->TransmitPdcpSdu (params);
}
break;
case HANDOVER_LEAVING:
{
NS_LOG_LOGIC ("forwarding data to target eNB over X2-U");
uint8_t drbid = Bid2Drbid (bid);
EpcX2Sap::UeDataParams params;
params.sourceCellId = m_rrc->m_cellId;
params.targetCellId = m_targetCellId;
params.gtpTeid = GetDataRadioBearerInfo (drbid)->m_gtpTeid;
params.ueData = p;
m_rrc->m_x2SapProvider->SendUeData (params);
}
break;
default:
NS_FATAL_ERROR ("method unexpected in state " << ToString (m_state));
break;
}
}
std::vector<EpcX2Sap::ErabToBeSetupItem>
UeManager::GetErabList ()
{
NS_LOG_FUNCTION (this);
std::vector<EpcX2Sap::ErabToBeSetupItem> ret;
for (std::map <uint8_t, Ptr<LteDataRadioBearerInfo> >::iterator it = m_drbMap.begin ();
it != m_drbMap.end ();
++it)
{
EpcX2Sap::ErabToBeSetupItem etbsi;
etbsi.erabId = it->second->m_epsBearerIdentity;
etbsi.erabLevelQosParameters = it->second->m_epsBearer;
etbsi.dlForwarding = false;
etbsi.transportLayerAddress = it->second->m_transportLayerAddress;
etbsi.gtpTeid = it->second->m_gtpTeid;
ret.push_back (etbsi);
}
return ret;
}
void
UeManager::SendUeContextRelease ()
{
NS_LOG_FUNCTION (this);
switch (m_state)
{
case HANDOVER_PATH_SWITCH:
NS_LOG_INFO ("Send UE CONTEXT RELEASE from target eNB to source eNB");
EpcX2SapProvider::UeContextReleaseParams ueCtxReleaseParams;
ueCtxReleaseParams.oldEnbUeX2apId = m_sourceX2apId;
ueCtxReleaseParams.newEnbUeX2apId = m_rnti;
ueCtxReleaseParams.sourceCellId = m_sourceCellId;
m_rrc->m_x2SapProvider->SendUeContextRelease (ueCtxReleaseParams);
SwitchToState (CONNECTED_NORMALLY);
m_rrc->m_handoverEndOkTrace (m_imsi, m_rrc->m_cellId, m_rnti);
break;
default:
NS_FATAL_ERROR ("method unexpected in state " << ToString (m_state));
break;
}
}
void
UeManager::RecvHandoverPreparationFailure (uint16_t cellId)
{
NS_LOG_FUNCTION (this << cellId);
switch (m_state)
{
case HANDOVER_PREPARATION:
NS_ASSERT (cellId == m_targetCellId);
NS_LOG_INFO ("target eNB sent HO preparation failure, aborting HO");
SwitchToState (CONNECTED_NORMALLY);
break;
default:
NS_FATAL_ERROR ("method unexpected in state " << ToString (m_state));
break;
}
}
void
UeManager::RecvSnStatusTransfer (EpcX2SapUser::SnStatusTransferParams params)
{
NS_LOG_FUNCTION (this);
for (std::vector<EpcX2Sap::ErabsSubjectToStatusTransferItem>::iterator erabIt
= params.erabsSubjectToStatusTransferList.begin ();
erabIt != params.erabsSubjectToStatusTransferList.end ();
++erabIt)
{
// LtePdcp::Status status;
// status.txSn = erabIt->dlPdcpSn;
// status.rxSn = erabIt->ulPdcpSn;
// uint8_t drbId = Bid2Drbid (erabIt->erabId);
// std::map <uint8_t, Ptr<LteDataRadioBearerInfo> >::iterator drbIt = m_drbMap.find (drbId);
// NS_ASSERT_MSG (drbIt != m_drbMap.end (), "could not find DRBID " << (uint32_t) drbId);
// drbIt->second->m_pdcp->SetStatus (status);
}
}
void
UeManager::RecvUeContextRelease (EpcX2SapUser::UeContextReleaseParams params)
{
NS_LOG_FUNCTION (this);
NS_ASSERT_MSG (m_state == HANDOVER_LEAVING, "method unexpected in state " << ToString (m_state));
m_handoverLeavingTimeout.Cancel ();
}
// methods forwarded from RRC SAP
void
UeManager::CompleteSetupUe (LteEnbRrcSapProvider::CompleteSetupUeParameters params)
{
NS_LOG_FUNCTION (this);
m_srb0->m_rlc->SetLteRlcSapUser (params.srb0SapUser);
m_srb1->m_pdcp->SetLtePdcpSapUser (params.srb1SapUser);
}
void
UeManager::RecvRrcConnectionRequest (LteRrcSap::RrcConnectionRequest msg)
{
NS_LOG_FUNCTION (this);
switch (m_state)
{
case INITIAL_RANDOM_ACCESS:
{
if (m_rrc->m_admitRrcConnectionRequest == true)
{
m_connectionTimeout.Cancel ();
m_imsi = msg.ueIdentity;
if (m_rrc->m_s1SapProvider != 0)
{
m_rrc->m_s1SapProvider->InitialUeMessage (m_imsi, m_rnti);
}
LteRrcSap::RrcConnectionSetup msg2;
msg2.rrcTransactionIdentifier = GetNewRrcTransactionIdentifier ();
msg2.radioResourceConfigDedicated = BuildRadioResourceConfigDedicated ();
m_rrc->m_rrcSapUser->SendRrcConnectionSetup (m_rnti, msg2);
RecordDataRadioBearersToBeStarted ();
SwitchToState (CONNECTION_SETUP);
}
else
{
m_connectionTimeout.Cancel ();
NS_LOG_INFO ("rejecting connection request for RNTI " << m_rnti);
LteRrcSap::RrcConnectionReject rejectMsg;
rejectMsg.waitTime = 3;
m_rrc->m_rrcSapUser->SendRrcConnectionReject (m_rnti, rejectMsg);
m_connectionRejectedTimeout = Simulator::Schedule (m_rrc->m_connectionRejectedTimeoutDuration,
&LteEnbRrc::ConnectionRejectedTimeout,
m_rrc, m_rnti);
SwitchToState (CONNECTION_REJECTED);
}
}
break;
default:
NS_FATAL_ERROR ("method unexpected in state " << ToString (m_state));
break;
}
}
void
UeManager::RecvRrcConnectionSetupCompleted (LteRrcSap::RrcConnectionSetupCompleted msg)
{
NS_LOG_FUNCTION (this);
switch (m_state)
{
case CONNECTION_SETUP:
StartDataRadioBearers ();
SwitchToState (CONNECTED_NORMALLY);
m_rrc->m_connectionEstablishedTrace (m_imsi, m_rrc->m_cellId, m_rnti);
break;
default:
NS_FATAL_ERROR ("method unexpected in state " << ToString (m_state));
break;
}
}
void
UeManager::RecvRrcConnectionReconfigurationCompleted (LteRrcSap::RrcConnectionReconfigurationCompleted msg)
{
NS_LOG_FUNCTION (this);
switch (m_state)
{
case CONNECTION_RECONFIGURATION:
StartDataRadioBearers ();
if (m_needTransmissionModeConfiguration)
{
// configure MAC (and scheduler)
LteEnbCmacSapProvider::UeConfig req;
req.m_rnti = m_rnti;
req.m_transmissionMode = m_physicalConfigDedicated.antennaInfo.transmissionMode;
m_rrc->m_cmacSapProvider->UeUpdateConfigurationReq (req);
// configure PHY
m_rrc->m_cphySapProvider->SetTransmissionMode (req.m_rnti, req.m_transmissionMode);
m_needTransmissionModeConfiguration = false;
}
SwitchToState (CONNECTED_NORMALLY);
m_rrc->m_connectionReconfigurationTrace (m_imsi, m_rrc->m_cellId, m_rnti);
break;
case HANDOVER_LEAVING:
NS_LOG_INFO ("ignoring RecvRrcConnectionReconfigurationCompleted in state " << ToString (m_state));
break;
case HANDOVER_JOINING:
{
m_handoverJoiningTimeout.Cancel ();
NS_LOG_INFO ("Send PATH SWITCH REQUEST to the MME");
EpcEnbS1SapProvider::PathSwitchRequestParameters params;
params.rnti = m_rnti;
params.cellId = m_rrc->m_cellId;
params.mmeUeS1Id = m_imsi;
SwitchToState (HANDOVER_PATH_SWITCH);
for (std::map <uint8_t, Ptr<LteDataRadioBearerInfo> >::iterator it = m_drbMap.begin ();
it != m_drbMap.end ();
++it)
{
EpcEnbS1SapProvider::BearerToBeSwitched b;
b.epsBearerId = it->second->m_epsBearerIdentity;
b.teid = it->second->m_gtpTeid;
params.bearersToBeSwitched.push_back (b);
}
m_rrc->m_s1SapProvider->PathSwitchRequest (params);
}
break;
default:
NS_FATAL_ERROR ("method unexpected in state " << ToString (m_state));
break;
}
}
void
UeManager::RecvRrcConnectionReestablishmentRequest (LteRrcSap::RrcConnectionReestablishmentRequest msg)
{
NS_LOG_FUNCTION (this);
switch (m_state)
{
case CONNECTED_NORMALLY:
break;
case HANDOVER_LEAVING:
m_handoverLeavingTimeout.Cancel ();
break;
default:
NS_FATAL_ERROR ("method unexpected in state " << ToString (m_state));
break;
}
LteRrcSap::RrcConnectionReestablishment msg2;
msg2.rrcTransactionIdentifier = GetNewRrcTransactionIdentifier ();
msg2.radioResourceConfigDedicated = BuildRadioResourceConfigDedicated ();
m_rrc->m_rrcSapUser->SendRrcConnectionReestablishment (m_rnti, msg2);
SwitchToState (CONNECTION_REESTABLISHMENT);
}
void
UeManager::RecvRrcConnectionReestablishmentComplete (LteRrcSap::RrcConnectionReestablishmentComplete msg)
{
NS_LOG_FUNCTION (this);
SwitchToState (CONNECTED_NORMALLY);
}
void
UeManager::RecvMeasurementReport (LteRrcSap::MeasurementReport msg)
{
uint8_t measId = msg.measResults.measId;
NS_LOG_FUNCTION (this << (uint16_t) measId);
NS_LOG_LOGIC ("measId " << (uint16_t) measId
<< " haveMeasResultNeighCells " << msg.measResults.haveMeasResultNeighCells
<< " measResultListEutra " << msg.measResults.measResultListEutra.size ());
NS_LOG_LOGIC ("serving cellId " << m_rrc->m_cellId
<< " RSRP " << (uint16_t) msg.measResults.rsrpResult
<< " RSRQ " << (uint16_t) msg.measResults.rsrqResult);
for (std::list <LteRrcSap::MeasResultEutra>::iterator it = msg.measResults.measResultListEutra.begin ();
it != msg.measResults.measResultListEutra.end ();
++it)
{
NS_LOG_LOGIC ("neighbour cellId " << it->physCellId
<< " RSRP " << (it->haveRsrpResult ? (uint16_t) it->rsrpResult : 255)
<< " RSRQ " << (it->haveRsrqResult ? (uint16_t) it->rsrqResult : 255));
}
if ((m_rrc->m_handoverManagementSapProvider != 0)
&& (m_rrc->m_handoverMeasIds.find (measId) != m_rrc->m_handoverMeasIds.end ()))
{
// this measurement was requested by the handover algorithm
m_rrc->m_handoverManagementSapProvider->ReportUeMeas (m_rnti,
msg.measResults);
}
if ((m_rrc->m_anrSapProvider != 0)
&& (m_rrc->m_anrMeasIds.find (measId) != m_rrc->m_anrMeasIds.end ()))
{
// this measurement was requested by the ANR function
m_rrc->m_anrSapProvider->ReportUeMeas (msg.measResults);
}
// fire a trace source
m_rrc->m_recvMeasurementReportTrace (m_imsi, m_rrc->m_cellId, m_rnti, msg);
} // end of UeManager::RecvMeasurementReport
// methods forwarded from CMAC SAP
void
UeManager::CmacUeConfigUpdateInd (LteEnbCmacSapUser::UeConfig cmacParams)
{
NS_LOG_FUNCTION (this << m_rnti);
// at this stage used only by the scheduler for updating txMode
m_physicalConfigDedicated.antennaInfo.transmissionMode = cmacParams.m_transmissionMode;
m_needTransmissionModeConfiguration = true;
// reconfigure the UE RRC
ScheduleRrcConnectionReconfiguration ();
}
// methods forwarded from PDCP SAP
void
UeManager::DoReceivePdcpSdu (LtePdcpSapUser::ReceivePdcpSduParameters params)
{
NS_LOG_FUNCTION (this);
if (params.lcid > 2)
{
// data radio bearer
EpsBearerTag tag;
tag.SetRnti (params.rnti);
tag.SetBid (Lcid2Bid (params.lcid));
params.pdcpSdu->AddPacketTag (tag);
m_rrc->m_forwardUpCallback (params.pdcpSdu);
}
}
uint16_t
UeManager::GetRnti (void) const
{
return m_rnti;
}
uint64_t
UeManager::GetImsi (void) const
{
return m_imsi;
}
uint16_t
UeManager::GetSrsConfigurationIndex (void) const
{
return m_physicalConfigDedicated.soundingRsUlConfigDedicated.srsConfigIndex;
}
void
UeManager::SetSrsConfigurationIndex (uint16_t srsConfIndex)
{
NS_LOG_FUNCTION (this);
m_physicalConfigDedicated.soundingRsUlConfigDedicated.srsConfigIndex = srsConfIndex;
m_rrc->m_cphySapProvider->SetSrsConfigurationIndex (m_rnti, srsConfIndex);
switch (m_state)
{
case INITIAL_RANDOM_ACCESS:
// do nothing, srs conf index will be correctly enforced upon
// RRC connection establishment
break;
default:
ScheduleRrcConnectionReconfiguration ();
break;
}
}
UeManager::State
UeManager::GetState (void) const
{
return m_state;
}
uint8_t
UeManager::AddDataRadioBearerInfo (Ptr<LteDataRadioBearerInfo> drbInfo)
{
NS_LOG_FUNCTION (this);
const uint8_t MAX_DRB_ID = 32;
for (uint8_t drbid = (m_lastAllocatedDrbid + 1) % MAX_DRB_ID;
drbid != m_lastAllocatedDrbid;
drbid = (drbid + 1) % MAX_DRB_ID)
{
if (drbid != 0) // 0 is not allowed
{
if (m_drbMap.find (drbid) == m_drbMap.end ())
{
m_drbMap.insert (std::pair<uint8_t, Ptr<LteDataRadioBearerInfo> > (drbid, drbInfo));
drbInfo->m_drbIdentity = drbid;
m_lastAllocatedDrbid = drbid;
return drbid;
}
}
}
NS_FATAL_ERROR ("no more data radio bearer ids available");
return 0;
}
Ptr<LteDataRadioBearerInfo>
UeManager::GetDataRadioBearerInfo (uint8_t drbid)
{
NS_LOG_FUNCTION (this << (uint32_t) drbid);
NS_ASSERT (0 != drbid);
std::map<uint8_t, Ptr<LteDataRadioBearerInfo> >::iterator it = m_drbMap.find (drbid);
NS_ABORT_IF (it == m_drbMap.end ());
return it->second;
}
void
UeManager::RemoveDataRadioBearerInfo (uint8_t drbid)
{
NS_LOG_FUNCTION (this << (uint32_t) drbid);
std::map <uint8_t, Ptr<LteDataRadioBearerInfo> >::iterator it = m_drbMap.find (drbid);
NS_ASSERT_MSG (it != m_drbMap.end (), "request to remove radio bearer with unknown drbid " << drbid);
m_drbMap.erase (it);
}
LteRrcSap::RrcConnectionReconfiguration
UeManager::BuildRrcConnectionReconfiguration ()
{
LteRrcSap::RrcConnectionReconfiguration msg;
msg.rrcTransactionIdentifier = GetNewRrcTransactionIdentifier ();
msg.haveRadioResourceConfigDedicated = true;
msg.radioResourceConfigDedicated = BuildRadioResourceConfigDedicated ();
msg.haveMobilityControlInfo = false;
msg.haveMeasConfig = true;
msg.measConfig = m_rrc->m_ueMeasConfig;
return msg;
}
LteRrcSap::RadioResourceConfigDedicated
UeManager::BuildRadioResourceConfigDedicated ()
{
LteRrcSap::RadioResourceConfigDedicated rrcd;
if (m_srb1 != 0)
{
LteRrcSap::SrbToAddMod stam;
stam.srbIdentity = m_srb1->m_srbIdentity;
stam.logicalChannelConfig = m_srb1->m_logicalChannelConfig;
rrcd.srbToAddModList.push_back (stam);
}
for (std::map <uint8_t, Ptr<LteDataRadioBearerInfo> >::iterator it = m_drbMap.begin ();
it != m_drbMap.end ();
++it)
{
LteRrcSap::DrbToAddMod dtam;
dtam.epsBearerIdentity = it->second->m_epsBearerIdentity;
dtam.drbIdentity = it->second->m_drbIdentity;
dtam.rlcConfig = it->second->m_rlcConfig;
dtam.logicalChannelIdentity = it->second->m_logicalChannelIdentity;
dtam.logicalChannelConfig = it->second->m_logicalChannelConfig;
rrcd.drbToAddModList.push_back (dtam);
}
rrcd.havePhysicalConfigDedicated = true;
rrcd.physicalConfigDedicated = m_physicalConfigDedicated;
return rrcd;
}
uint8_t
UeManager::GetNewRrcTransactionIdentifier ()
{
return ++m_lastRrcTransactionIdentifier;
}
uint8_t
UeManager::Lcid2Drbid (uint8_t lcid)
{
NS_ASSERT (lcid > 2);
return lcid - 2;
}
uint8_t
UeManager::Drbid2Lcid (uint8_t drbid)
{
return drbid + 2;
}
uint8_t
UeManager::Lcid2Bid (uint8_t lcid)
{
NS_ASSERT (lcid > 2);
return lcid - 2;
}
uint8_t
UeManager::Bid2Lcid (uint8_t bid)
{
return bid + 2;
}
uint8_t
UeManager::Drbid2Bid (uint8_t drbid)
{
return drbid;
}
uint8_t
UeManager::Bid2Drbid (uint8_t bid)
{
return bid;
}
void
UeManager::SwitchToState (State newState)
{
NS_LOG_FUNCTION (this << ToString (newState));
State oldState = m_state;
m_state = newState;
NS_LOG_INFO (this << "IMSI " << m_imsi << " RNTI " << m_rnti << " UeManager "
<< ToString (oldState) << " --> " << ToString (newState));
m_stateTransitionTrace (m_imsi, m_rrc->m_cellId, m_rnti, oldState, newState);
switch (newState)
{
case INITIAL_RANDOM_ACCESS:
case HANDOVER_JOINING:
NS_FATAL_ERROR ("cannot switch to an initial state");
break;
case CONNECTION_SETUP:
break;
case CONNECTED_NORMALLY:
{
if (m_pendingRrcConnectionReconfiguration == true)
{
ScheduleRrcConnectionReconfiguration ();
}
}
break;
case CONNECTION_RECONFIGURATION:
break;
case CONNECTION_REESTABLISHMENT:
break;
case HANDOVER_LEAVING:
break;
default:
break;
}
}
///////////////////////////////////////////
// eNB RRC methods
///////////////////////////////////////////
NS_OBJECT_ENSURE_REGISTERED (LteEnbRrc);
LteEnbRrc::LteEnbRrc ()
: m_x2SapProvider (0),
m_cmacSapProvider (0),
m_handoverManagementSapProvider (0),
m_anrSapProvider (0),
m_rrcSapUser (0),
m_macSapProvider (0),
m_s1SapProvider (0),
m_cphySapProvider (0),
m_configured (false),
m_lastAllocatedRnti (0),
m_srsCurrentPeriodicityId (0),
m_lastAllocatedConfigurationIndex (0),
m_reconfigureUes (false)
{
NS_LOG_FUNCTION (this);
m_cmacSapUser = new EnbRrcMemberLteEnbCmacSapUser (this);
m_handoverManagementSapUser = new MemberLteHandoverManagementSapUser<LteEnbRrc> (this);
m_anrSapUser = new MemberLteAnrSapUser<LteEnbRrc> (this);
m_rrcSapProvider = new MemberLteEnbRrcSapProvider<LteEnbRrc> (this);
m_x2SapUser = new EpcX2SpecificEpcX2SapUser<LteEnbRrc> (this);
m_s1SapUser = new MemberEpcEnbS1SapUser<LteEnbRrc> (this);
m_cphySapUser = new MemberLteEnbCphySapUser<LteEnbRrc> (this);
}
LteEnbRrc::~LteEnbRrc ()
{
NS_LOG_FUNCTION (this);
}
void
LteEnbRrc::DoDispose ()
{
NS_LOG_FUNCTION (this);
m_ueMap.clear ();
delete m_cmacSapUser;
delete m_handoverManagementSapUser;
delete m_anrSapUser;
delete m_rrcSapProvider;
delete m_x2SapUser;
delete m_s1SapUser;
delete m_cphySapUser;
}
TypeId
LteEnbRrc::GetTypeId (void)
{
NS_LOG_FUNCTION ("LteEnbRrc::GetTypeId");
static TypeId tid = TypeId ("ns3::LteEnbRrc")
.SetParent<Object> ()
.AddConstructor<LteEnbRrc> ()
.AddAttribute ("UeMap", "List of UeManager by C-RNTI.",
ObjectMapValue (),
MakeObjectMapAccessor (&LteEnbRrc::m_ueMap),
MakeObjectMapChecker<UeManager> ())
.AddAttribute ("DefaultTransmissionMode",
"The default UEs' transmission mode (0: SISO)",
UintegerValue (0), // default tx-mode
MakeUintegerAccessor (&LteEnbRrc::m_defaultTransmissionMode),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("EpsBearerToRlcMapping",
"Specify which type of RLC will be used for each type of EPS bearer. ",
EnumValue (RLC_SM_ALWAYS),
MakeEnumAccessor (&LteEnbRrc::m_epsBearerToRlcMapping),
MakeEnumChecker (RLC_SM_ALWAYS, "RlcSmAlways",
RLC_UM_ALWAYS, "RlcUmAlways",
RLC_AM_ALWAYS, "RlcAmAlways",
PER_BASED, "PacketErrorRateBased"))
.AddAttribute ("SystemInformationPeriodicity",
"The interval for sending system information (Time value)",
TimeValue (MilliSeconds (80)),
MakeTimeAccessor (&LteEnbRrc::m_systemInformationPeriodicity),
MakeTimeChecker ())
// SRS related attributes
.AddAttribute ("SrsPeriodicity",
"The SRS periodicity in milliseconds",
UintegerValue (40),
MakeUintegerAccessor (&LteEnbRrc::SetSrsPeriodicity,
&LteEnbRrc::GetSrsPeriodicity),
MakeUintegerChecker<uint32_t> ())
// Timeout related attributes
.AddAttribute ("ConnectionTimeoutDuration",
"After a RA attempt, if no RRC Connection Request is received before this time, the UE context is destroyed. Must account for reception of RAR and transmission of RRC CONNECTION REQUEST over UL GRANT.",
TimeValue (MilliSeconds (15)),
MakeTimeAccessor (&LteEnbRrc::m_connectionTimeoutDuration),
MakeTimeChecker ())
.AddAttribute ("ConnectionRejectedTimeoutDuration",
"Time to wait between sending a RRC CONNECTION REJECT and destroying the UE context",
TimeValue (MilliSeconds (30)),
MakeTimeAccessor (&LteEnbRrc::m_connectionRejectedTimeoutDuration),
MakeTimeChecker ())
.AddAttribute ("HandoverJoiningTimeoutDuration",
"After accepting a handover request, if no RRC Connection Reconfiguration Completed is received before this time, the UE context is destroyed. Must account for reception of X2 HO REQ ACK by source eNB, transmission of the Handover Command, non-contention-based random access and reception of the RRC Connection Reconfiguration Completed message.",
TimeValue (MilliSeconds (200)),
MakeTimeAccessor (&LteEnbRrc::m_handoverJoiningTimeoutDuration),
MakeTimeChecker ())
.AddAttribute ("HandoverLeavingTimeoutDuration",
"After issuing a Handover Command, if neither RRC Connection Reestablishment nor X2 UE Context Release has been previously received, the UE context is destroyed.",
TimeValue (MilliSeconds (500)),
MakeTimeAccessor (&LteEnbRrc::m_handoverLeavingTimeoutDuration),
MakeTimeChecker ())
// Cell selection related attribute
.AddAttribute ("QRxLevMin",
"One of information transmitted within the SIB1 message, "
"indicating the required minimum RSRP level that any UE must "
"receive from this cell before it is allowed to camp to this "
"cell. The default value -70 corresponds to -140 dBm and is "
"the lowest possible value as defined by Section 6.3.4 of "
"3GPP TS 36.133. This restriction, however, only applies to "
"initial cell selection and EPC-enabled simulation.",
TypeId::ATTR_GET | TypeId::ATTR_CONSTRUCT,
IntegerValue (-70),
MakeIntegerAccessor (&LteEnbRrc::m_qRxLevMin),
MakeIntegerChecker<int8_t> (-70, -22))
// Handover related attributes
.AddAttribute ("AdmitHandoverRequest",
"Whether to admit an X2 handover request from another eNB",
BooleanValue (true),
MakeBooleanAccessor (&LteEnbRrc::m_admitHandoverRequest),
MakeBooleanChecker ())
.AddAttribute ("AdmitRrcConnectionRequest",
"Whether to admit a connection request from a UE",
BooleanValue (true),
MakeBooleanAccessor (&LteEnbRrc::m_admitRrcConnectionRequest),
MakeBooleanChecker ())
// UE measurements related attributes
.AddAttribute ("RsrpFilterCoefficient",
"Determines the strength of smoothing effect induced by "
"layer 3 filtering of RSRP in all attached UE; "
"if set to 0, no layer 3 filtering is applicable",
// i.e. the variable k in 3GPP TS 36.331 section 5.5.3.2
UintegerValue (4),
MakeUintegerAccessor (&LteEnbRrc::m_rsrpFilterCoefficient),
MakeUintegerChecker<uint8_t> (0))
.AddAttribute ("RsrqFilterCoefficient",
"Determines the strength of smoothing effect induced by "
"layer 3 filtering of RSRQ in all attached UE; "
"if set to 0, no layer 3 filtering is applicable",
// i.e. the variable k in 3GPP TS 36.331 section 5.5.3.2
UintegerValue (4),
MakeUintegerAccessor (&LteEnbRrc::m_rsrqFilterCoefficient),
MakeUintegerChecker<uint8_t> (0))
// Trace sources
.AddTraceSource ("NewUeContext",
"trace fired upon creation of a new UE context",
MakeTraceSourceAccessor (&LteEnbRrc::m_newUeContextTrace))
.AddTraceSource ("ConnectionEstablished",
"trace fired upon successful RRC connection establishment",
MakeTraceSourceAccessor (&LteEnbRrc::m_connectionEstablishedTrace))
.AddTraceSource ("ConnectionReconfiguration",
"trace fired upon RRC connection reconfiguration",
MakeTraceSourceAccessor (&LteEnbRrc::m_connectionReconfigurationTrace))
.AddTraceSource ("HandoverStart",
"trace fired upon start of a handover procedure",
MakeTraceSourceAccessor (&LteEnbRrc::m_handoverStartTrace))
.AddTraceSource ("HandoverEndOk",
"trace fired upon successful termination of a handover procedure",
MakeTraceSourceAccessor (&LteEnbRrc::m_handoverEndOkTrace))
.AddTraceSource ("RecvMeasurementReport",
"trace fired when measurement report is received",
MakeTraceSourceAccessor (&LteEnbRrc::m_recvMeasurementReportTrace))
;
return tid;
}
void
LteEnbRrc::SetEpcX2SapProvider (EpcX2SapProvider * s)
{
NS_LOG_FUNCTION (this << s);
m_x2SapProvider = s;
}
EpcX2SapUser*
LteEnbRrc::GetEpcX2SapUser ()
{
NS_LOG_FUNCTION (this);
return m_x2SapUser;
}
void
LteEnbRrc::SetLteEnbCmacSapProvider (LteEnbCmacSapProvider * s)
{
NS_LOG_FUNCTION (this << s);
m_cmacSapProvider = s;
}
LteEnbCmacSapUser*
LteEnbRrc::GetLteEnbCmacSapUser ()
{
NS_LOG_FUNCTION (this);
return m_cmacSapUser;
}
void
LteEnbRrc::SetLteHandoverManagementSapProvider (LteHandoverManagementSapProvider * s)
{
NS_LOG_FUNCTION (this << s);
m_handoverManagementSapProvider = s;
}
LteHandoverManagementSapUser*
LteEnbRrc::GetLteHandoverManagementSapUser ()
{
NS_LOG_FUNCTION (this);
return m_handoverManagementSapUser;
}
void
LteEnbRrc::SetLteAnrSapProvider (LteAnrSapProvider * s)
{
NS_LOG_FUNCTION (this << s);
m_anrSapProvider = s;
}
LteAnrSapUser*
LteEnbRrc::GetLteAnrSapUser ()
{
NS_LOG_FUNCTION (this);
return m_anrSapUser;
}
void
LteEnbRrc::SetLteEnbRrcSapUser (LteEnbRrcSapUser * s)
{
NS_LOG_FUNCTION (this << s);
m_rrcSapUser = s;
}
LteEnbRrcSapProvider*
LteEnbRrc::GetLteEnbRrcSapProvider ()
{
NS_LOG_FUNCTION (this);
return m_rrcSapProvider;
}
void
LteEnbRrc::SetLteMacSapProvider (LteMacSapProvider * s)
{
NS_LOG_FUNCTION (this);
m_macSapProvider = s;
}
void
LteEnbRrc::SetS1SapProvider (EpcEnbS1SapProvider * s)
{
m_s1SapProvider = s;
}
EpcEnbS1SapUser*
LteEnbRrc::GetS1SapUser ()
{
return m_s1SapUser;
}
void
LteEnbRrc::SetLteEnbCphySapProvider (LteEnbCphySapProvider * s)
{
NS_LOG_FUNCTION (this << s);
m_cphySapProvider = s;
}
LteEnbCphySapUser*
LteEnbRrc::GetLteEnbCphySapUser ()
{
NS_LOG_FUNCTION (this);
return m_cphySapUser;
}
Ptr<UeManager>
LteEnbRrc::GetUeManager (uint16_t rnti)
{
NS_LOG_FUNCTION (this << (uint32_t) rnti);
NS_ASSERT (0 != rnti);
std::map<uint16_t, Ptr<UeManager> >::iterator it = m_ueMap.find (rnti);
NS_ASSERT_MSG (it != m_ueMap.end (), "RNTI " << rnti << " not found in eNB with cellId " << m_cellId);
return it->second;
}
uint8_t
LteEnbRrc::AddUeMeasReportConfig (LteRrcSap::ReportConfigEutra config)
{
NS_LOG_FUNCTION (this);
// SANITY CHECK
NS_ASSERT_MSG (m_ueMeasConfig.measIdToAddModList.size () == m_ueMeasConfig.reportConfigToAddModList.size (),
"Measurement identities and reporting configuration should not have different quantity");
if (Simulator::Now () != Seconds (0))
{
NS_FATAL_ERROR ("AddUeMeasReportConfig may not be called after the simulation has run");
}
// INPUT VALIDATION
switch (config.triggerQuantity)
{
case LteRrcSap::ReportConfigEutra::RSRP:
if ((config.eventId == LteRrcSap::ReportConfigEutra::EVENT_A5)
&& (config.threshold2.choice != LteRrcSap::ThresholdEutra::THRESHOLD_RSRP))
{
NS_FATAL_ERROR ("The given triggerQuantity (RSRP) does not match with the given threshold2.choice");
}
if (((config.eventId == LteRrcSap::ReportConfigEutra::EVENT_A1)
|| (config.eventId == LteRrcSap::ReportConfigEutra::EVENT_A2)
|| (config.eventId == LteRrcSap::ReportConfigEutra::EVENT_A4)
|| (config.eventId == LteRrcSap::ReportConfigEutra::EVENT_A5))
&& (config.threshold1.choice != LteRrcSap::ThresholdEutra::THRESHOLD_RSRP))
{
NS_FATAL_ERROR ("The given triggerQuantity (RSRP) does not match with the given threshold1.choice");
}
break;
case LteRrcSap::ReportConfigEutra::RSRQ:
if ((config.eventId == LteRrcSap::ReportConfigEutra::EVENT_A5)
&& (config.threshold2.choice != LteRrcSap::ThresholdEutra::THRESHOLD_RSRQ))
{
NS_FATAL_ERROR ("The given triggerQuantity (RSRQ) does not match with the given threshold2.choice");
}
if (((config.eventId == LteRrcSap::ReportConfigEutra::EVENT_A1)
|| (config.eventId == LteRrcSap::ReportConfigEutra::EVENT_A2)
|| (config.eventId == LteRrcSap::ReportConfigEutra::EVENT_A4)
|| (config.eventId == LteRrcSap::ReportConfigEutra::EVENT_A5))
&& (config.threshold1.choice != LteRrcSap::ThresholdEutra::THRESHOLD_RSRQ))
{
NS_FATAL_ERROR ("The given triggerQuantity (RSRQ) does not match with the given threshold1.choice");
}
break;
default:
NS_FATAL_ERROR ("unsupported triggerQuantity");
break;
}
if (config.purpose != LteRrcSap::ReportConfigEutra::REPORT_STRONGEST_CELLS)
{
NS_FATAL_ERROR ("Only REPORT_STRONGEST_CELLS purpose is supported");
}
if (config.reportQuantity != LteRrcSap::ReportConfigEutra::BOTH)
{
NS_LOG_WARN ("reportQuantity = BOTH will be used instead of the given reportQuantity");
}
uint8_t nextId = m_ueMeasConfig.reportConfigToAddModList.size () + 1;
// create the reporting configuration
LteRrcSap::ReportConfigToAddMod reportConfig;
reportConfig.reportConfigId = nextId;
reportConfig.reportConfigEutra = config;
// create the measurement identity
LteRrcSap::MeasIdToAddMod measId;
measId.measId = nextId;
measId.measObjectId = 1;
measId.reportConfigId = nextId;
// add both to the list of UE measurement configuration
m_ueMeasConfig.reportConfigToAddModList.push_back (reportConfig);
m_ueMeasConfig.measIdToAddModList.push_back (measId);
return nextId;
}
void
LteEnbRrc::ConfigureCell (uint8_t ulBandwidth, uint8_t dlBandwidth,
uint16_t ulEarfcn, uint16_t dlEarfcn, uint16_t cellId)
{
NS_LOG_FUNCTION (this << (uint16_t) ulBandwidth << (uint16_t) dlBandwidth
<< ulEarfcn << dlEarfcn << cellId);
NS_ASSERT (!m_configured);
m_cmacSapProvider->ConfigureMac (ulBandwidth, dlBandwidth);
m_cphySapProvider->SetBandwidth (ulBandwidth, dlBandwidth);
m_cphySapProvider->SetEarfcn (ulEarfcn, dlEarfcn);
m_dlEarfcn = dlEarfcn;
m_ulEarfcn = ulEarfcn;
m_dlBandwidth = dlBandwidth;
m_ulBandwidth = ulBandwidth;
m_cellId = cellId;
m_cphySapProvider->SetCellId (cellId);
/*
* Initializing the list of UE measurement configuration (m_ueMeasConfig).
* Only intra-frequency measurements are supported, so only one measurement
* object is created.
*/
LteRrcSap::MeasObjectToAddMod measObject;
measObject.measObjectId = 1;
measObject.measObjectEutra.carrierFreq = m_dlEarfcn;
measObject.measObjectEutra.allowedMeasBandwidth = m_dlBandwidth;
measObject.measObjectEutra.presenceAntennaPort1 = false;
measObject.measObjectEutra.neighCellConfig = 0;
measObject.measObjectEutra.offsetFreq = 0;
measObject.measObjectEutra.haveCellForWhichToReportCGI = false;
m_ueMeasConfig.measObjectToAddModList.push_back (measObject);
m_ueMeasConfig.haveQuantityConfig = true;
m_ueMeasConfig.quantityConfig.filterCoefficientRSRP = m_rsrpFilterCoefficient;
m_ueMeasConfig.quantityConfig.filterCoefficientRSRQ = m_rsrqFilterCoefficient;
m_ueMeasConfig.haveMeasGapConfig = false;
m_ueMeasConfig.haveSmeasure = false;
m_ueMeasConfig.haveSpeedStatePars = false;
// Enabling MIB transmission
LteRrcSap::MasterInformationBlock mib;
mib.dlBandwidth = m_dlBandwidth;
m_cphySapProvider->SetMasterInformationBlock (mib);
// Enabling SIB1 transmission with default values
m_sib1.cellAccessRelatedInfo.cellIdentity = cellId;
m_sib1.cellAccessRelatedInfo.csgIndication = false;
m_sib1.cellAccessRelatedInfo.csgIdentity = 0;
m_sib1.cellAccessRelatedInfo.plmnIdentityInfo.plmnIdentity = 0; // not used
m_sib1.cellSelectionInfo.qQualMin = -34; // not used, set as minimum value
m_sib1.cellSelectionInfo.qRxLevMin = m_qRxLevMin; // set as minimum value
m_cphySapProvider->SetSystemInformationBlockType1 (m_sib1);
/*
* Enabling transmission of other SIB. The first time System Information is
* transmitted is arbitrarily assumed to be at +0.016s, and then it will be
* regularly transmitted every 80 ms by default (set the
* SystemInformationPeriodicity attribute to configure this).
*/
Simulator::Schedule (MilliSeconds (16), &LteEnbRrc::SendSystemInformation, this);
m_configured = true;
}
void
LteEnbRrc::SetCellId (uint16_t cellId)
{
m_cellId = cellId;
// update SIB1 too
m_sib1.cellAccessRelatedInfo.cellIdentity = cellId;
m_cphySapProvider->SetSystemInformationBlockType1 (m_sib1);
}
bool
LteEnbRrc::SendData (Ptr<Packet> packet)
{
NS_LOG_FUNCTION (this << packet);
EpsBearerTag tag;
bool found = packet->RemovePacketTag (tag);
NS_ASSERT_MSG (found, "no EpsBearerTag found in packet to be sent");
Ptr<UeManager> ueManager = GetUeManager (tag.GetRnti ());
ueManager->SendData (tag.GetBid (), packet);
return true;
}
void
LteEnbRrc::SetForwardUpCallback (Callback <void, Ptr<Packet> > cb)
{
m_forwardUpCallback = cb;
}
void
LteEnbRrc::ConnectionTimeout (uint16_t rnti)
{
NS_LOG_FUNCTION (this << rnti);
NS_ASSERT_MSG (GetUeManager (rnti)->GetState () == UeManager::INITIAL_RANDOM_ACCESS,
"ConnectionTimeout in unexpected state " << ToString (GetUeManager (rnti)->GetState ()));
RemoveUe (rnti);
}
void
LteEnbRrc::ConnectionRejectedTimeout (uint16_t rnti)
{
NS_LOG_FUNCTION (this << rnti);
NS_ASSERT_MSG (GetUeManager (rnti)->GetState () == UeManager::CONNECTION_REJECTED,
"ConnectionTimeout in unexpected state " << ToString (GetUeManager (rnti)->GetState ()));
RemoveUe (rnti);
}
void
LteEnbRrc::HandoverJoiningTimeout (uint16_t rnti)
{
NS_LOG_FUNCTION (this << rnti);
NS_ASSERT_MSG (GetUeManager (rnti)->GetState () == UeManager::HANDOVER_JOINING,
"HandoverJoiningTimeout in unexpected state " << ToString (GetUeManager (rnti)->GetState ()));
RemoveUe (rnti);
}
void
LteEnbRrc::HandoverLeavingTimeout (uint16_t rnti)
{
NS_LOG_FUNCTION (this << rnti);
NS_ASSERT_MSG (GetUeManager (rnti)->GetState () == UeManager::HANDOVER_LEAVING,
"HandoverLeavingTimeout in unexpected state " << ToString (GetUeManager (rnti)->GetState ()));
RemoveUe (rnti);
}
void
LteEnbRrc::SendHandoverRequest (uint16_t rnti, uint16_t cellId)
{
NS_LOG_FUNCTION (this << rnti << cellId);
NS_LOG_LOGIC ("Request to send HANDOVER REQUEST");
NS_ASSERT (m_configured);
Ptr<UeManager> ueManager = GetUeManager (rnti);
ueManager->PrepareHandover (cellId);
}
void
LteEnbRrc::DoCompleteSetupUe (uint16_t rnti, LteEnbRrcSapProvider::CompleteSetupUeParameters params)
{
NS_LOG_FUNCTION (this << rnti);
GetUeManager (rnti)->CompleteSetupUe (params);
}
void
LteEnbRrc::DoRecvRrcConnectionRequest (uint16_t rnti, LteRrcSap::RrcConnectionRequest msg)
{
NS_LOG_FUNCTION (this << rnti);
GetUeManager (rnti)->RecvRrcConnectionRequest (msg);
}
void
LteEnbRrc::DoRecvRrcConnectionSetupCompleted (uint16_t rnti, LteRrcSap::RrcConnectionSetupCompleted msg)
{
NS_LOG_FUNCTION (this << rnti);
GetUeManager (rnti)->RecvRrcConnectionSetupCompleted (msg);
}
void
LteEnbRrc::DoRecvRrcConnectionReconfigurationCompleted (uint16_t rnti, LteRrcSap::RrcConnectionReconfigurationCompleted msg)
{
NS_LOG_FUNCTION (this << rnti);
GetUeManager (rnti)->RecvRrcConnectionReconfigurationCompleted (msg);
}
void
LteEnbRrc::DoRecvRrcConnectionReestablishmentRequest (uint16_t rnti, LteRrcSap::RrcConnectionReestablishmentRequest msg)
{
NS_LOG_FUNCTION (this << rnti);
GetUeManager (rnti)->RecvRrcConnectionReestablishmentRequest (msg);
}
void
LteEnbRrc::DoRecvRrcConnectionReestablishmentComplete (uint16_t rnti, LteRrcSap::RrcConnectionReestablishmentComplete msg)
{
NS_LOG_FUNCTION (this << rnti);
GetUeManager (rnti)->RecvRrcConnectionReestablishmentComplete (msg);
}
void
LteEnbRrc::DoRecvMeasurementReport (uint16_t rnti, LteRrcSap::MeasurementReport msg)
{
NS_LOG_FUNCTION (this << rnti);
GetUeManager (rnti)->RecvMeasurementReport (msg);
}
void
LteEnbRrc::DoDataRadioBearerSetupRequest (EpcEnbS1SapUser::DataRadioBearerSetupRequestParameters request)
{
Ptr<UeManager> ueManager = GetUeManager (request.rnti);
ueManager->SetupDataRadioBearer (request.bearer, request.bearerId, request.gtpTeid, request.transportLayerAddress);
}
void
LteEnbRrc::DoPathSwitchRequestAcknowledge (EpcEnbS1SapUser::PathSwitchRequestAcknowledgeParameters params)
{
Ptr<UeManager> ueManager = GetUeManager (params.rnti);
ueManager->SendUeContextRelease ();
}
void
LteEnbRrc::DoRecvHandoverRequest (EpcX2SapUser::HandoverRequestParams req)
{
NS_LOG_FUNCTION (this);
NS_LOG_LOGIC ("Recv X2 message: HANDOVER REQUEST");
NS_LOG_LOGIC ("oldEnbUeX2apId = " << req.oldEnbUeX2apId);
NS_LOG_LOGIC ("sourceCellId = " << req.sourceCellId);
NS_LOG_LOGIC ("targetCellId = " << req.targetCellId);
NS_LOG_LOGIC ("mmeUeS1apId = " << req.mmeUeS1apId);
NS_ASSERT (req.targetCellId == m_cellId);
if (m_admitHandoverRequest == false)
{
NS_LOG_INFO ("rejecting handover request from cellId " << req.sourceCellId);
EpcX2Sap::HandoverPreparationFailureParams res;
res.oldEnbUeX2apId = req.oldEnbUeX2apId;
res.sourceCellId = req.sourceCellId ;
res.targetCellId = req.targetCellId ;
res.cause = 0;
res.criticalityDiagnostics = 0;
m_x2SapProvider->SendHandoverPreparationFailure (res);
return;
}
uint16_t rnti = AddUe (UeManager::HANDOVER_JOINING);
LteEnbCmacSapProvider::AllocateNcRaPreambleReturnValue anrcrv = m_cmacSapProvider->AllocateNcRaPreamble (rnti);
if (anrcrv.valid == false)
{
NS_LOG_INFO (this << "failed to allocate a preamble for non-contention based RA => cannot accept HO");
RemoveUe (rnti);
NS_FATAL_ERROR ("should trigger HO Preparation Failure, but it is not implemented");
return;
}
Ptr<UeManager> ueManager = GetUeManager (rnti);
ueManager->SetSource (req.sourceCellId, req.oldEnbUeX2apId);
ueManager->SetImsi (req.mmeUeS1apId);
EpcX2SapProvider::HandoverRequestAckParams ackParams;
ackParams.oldEnbUeX2apId = req.oldEnbUeX2apId;
ackParams.newEnbUeX2apId = rnti;
ackParams.sourceCellId = req.sourceCellId;
ackParams.targetCellId = req.targetCellId;
for (std::vector <EpcX2Sap::ErabToBeSetupItem>::iterator it = req.bearers.begin ();
it != req.bearers.end ();
++it)
{
ueManager->SetupDataRadioBearer (it->erabLevelQosParameters, it->erabId, it->gtpTeid, it->transportLayerAddress);
EpcX2Sap::ErabAdmittedItem i;
i.erabId = it->erabId;
ackParams.admittedBearers.push_back (i);
}
LteRrcSap::RrcConnectionReconfiguration handoverCommand = ueManager->GetRrcConnectionReconfigurationForHandover ();
handoverCommand.haveMobilityControlInfo = true;
handoverCommand.mobilityControlInfo.targetPhysCellId = m_cellId;
handoverCommand.mobilityControlInfo.haveCarrierFreq = true;
handoverCommand.mobilityControlInfo.carrierFreq.dlCarrierFreq = m_dlEarfcn;
handoverCommand.mobilityControlInfo.carrierFreq.ulCarrierFreq = m_ulEarfcn;
handoverCommand.mobilityControlInfo.haveCarrierBandwidth = true;
handoverCommand.mobilityControlInfo.carrierBandwidth.dlBandwidth = m_dlBandwidth;
handoverCommand.mobilityControlInfo.carrierBandwidth.ulBandwidth = m_ulBandwidth;
handoverCommand.mobilityControlInfo.newUeIdentity = rnti;
handoverCommand.mobilityControlInfo.haveRachConfigDedicated = true;
handoverCommand.mobilityControlInfo.rachConfigDedicated.raPreambleIndex = anrcrv.raPreambleId;
handoverCommand.mobilityControlInfo.rachConfigDedicated.raPrachMaskIndex = anrcrv.raPrachMaskIndex;
LteEnbCmacSapProvider::RachConfig rc = m_cmacSapProvider->GetRachConfig ();
handoverCommand.mobilityControlInfo.radioResourceConfigCommon.rachConfigCommon.preambleInfo.numberOfRaPreambles = rc.numberOfRaPreambles;
handoverCommand.mobilityControlInfo.radioResourceConfigCommon.rachConfigCommon.raSupervisionInfo.preambleTransMax = rc.preambleTransMax;
handoverCommand.mobilityControlInfo.radioResourceConfigCommon.rachConfigCommon.raSupervisionInfo.raResponseWindowSize = rc.raResponseWindowSize;
Ptr<Packet> encodedHandoverCommand = m_rrcSapUser->EncodeHandoverCommand (handoverCommand);
ackParams.rrcContext = encodedHandoverCommand;
NS_LOG_LOGIC ("Send X2 message: HANDOVER REQUEST ACK");
NS_LOG_LOGIC ("oldEnbUeX2apId = " << ackParams.oldEnbUeX2apId);
NS_LOG_LOGIC ("newEnbUeX2apId = " << ackParams.newEnbUeX2apId);
NS_LOG_LOGIC ("sourceCellId = " << ackParams.sourceCellId);
NS_LOG_LOGIC ("targetCellId = " << ackParams.targetCellId);
m_x2SapProvider->SendHandoverRequestAck (ackParams);
}
void
LteEnbRrc::DoRecvHandoverRequestAck (EpcX2SapUser::HandoverRequestAckParams params)
{
NS_LOG_FUNCTION (this);
NS_LOG_LOGIC ("Recv X2 message: HANDOVER REQUEST ACK");
NS_LOG_LOGIC ("oldEnbUeX2apId = " << params.oldEnbUeX2apId);
NS_LOG_LOGIC ("newEnbUeX2apId = " << params.newEnbUeX2apId);
NS_LOG_LOGIC ("sourceCellId = " << params.sourceCellId);
NS_LOG_LOGIC ("targetCellId = " << params.targetCellId);
uint16_t rnti = params.oldEnbUeX2apId;
Ptr<UeManager> ueManager = GetUeManager (rnti);
ueManager->RecvHandoverRequestAck (params);
}
void
LteEnbRrc::DoRecvHandoverPreparationFailure (EpcX2SapUser::HandoverPreparationFailureParams params)
{
NS_LOG_FUNCTION (this);
NS_LOG_LOGIC ("Recv X2 message: HANDOVER PREPARATION FAILURE");
NS_LOG_LOGIC ("oldEnbUeX2apId = " << params.oldEnbUeX2apId);
NS_LOG_LOGIC ("sourceCellId = " << params.sourceCellId);
NS_LOG_LOGIC ("targetCellId = " << params.targetCellId);
NS_LOG_LOGIC ("cause = " << params.cause);
NS_LOG_LOGIC ("criticalityDiagnostics = " << params.criticalityDiagnostics);
uint16_t rnti = params.oldEnbUeX2apId;
Ptr<UeManager> ueManager = GetUeManager (rnti);
ueManager->RecvHandoverPreparationFailure (params.targetCellId);
}
void
LteEnbRrc::DoRecvSnStatusTransfer (EpcX2SapUser::SnStatusTransferParams params)
{
NS_LOG_FUNCTION (this);
NS_LOG_LOGIC ("Recv X2 message: SN STATUS TRANSFER");
NS_LOG_LOGIC ("oldEnbUeX2apId = " << params.oldEnbUeX2apId);
NS_LOG_LOGIC ("newEnbUeX2apId = " << params.newEnbUeX2apId);
NS_LOG_LOGIC ("erabsSubjectToStatusTransferList size = " << params.erabsSubjectToStatusTransferList.size ());
uint16_t rnti = params.newEnbUeX2apId;
Ptr<UeManager> ueManager = GetUeManager (rnti);
ueManager->RecvSnStatusTransfer (params);
}
void
LteEnbRrc::DoRecvUeContextRelease (EpcX2SapUser::UeContextReleaseParams params)
{
NS_LOG_FUNCTION (this);
NS_LOG_LOGIC ("Recv X2 message: UE CONTEXT RELEASE");
NS_LOG_LOGIC ("oldEnbUeX2apId = " << params.oldEnbUeX2apId);
NS_LOG_LOGIC ("newEnbUeX2apId = " << params.newEnbUeX2apId);
uint16_t rnti = params.oldEnbUeX2apId;
GetUeManager (rnti)->RecvUeContextRelease (params);
RemoveUe (rnti);
}
void
LteEnbRrc::DoRecvLoadInformation (EpcX2SapUser::LoadInformationParams params)
{
NS_LOG_FUNCTION (this);
NS_LOG_LOGIC ("Recv X2 message: LOAD INFORMATION");
NS_LOG_LOGIC ("Number of cellInformationItems = " << params.cellInformationList.size ());
NS_ASSERT ("Processing of LOAD INFORMATION X2 message IS NOT IMPLEMENTED");
}
void
LteEnbRrc::DoRecvResourceStatusUpdate (EpcX2SapUser::ResourceStatusUpdateParams params)
{
NS_LOG_FUNCTION (this);
NS_LOG_LOGIC ("Recv X2 message: RESOURCE STATUS UPDATE");
NS_LOG_LOGIC ("Number of cellMeasurementResultItems = " << params.cellMeasurementResultList.size ());
NS_ASSERT ("Processing of RESOURCE STATUS UPDATE X2 message IS NOT IMPLEMENTED");
}
void
LteEnbRrc::DoRecvUeData (EpcX2SapUser::UeDataParams params)
{
NS_LOG_FUNCTION (this);
NS_LOG_LOGIC ("Recv UE DATA FORWARDING through X2 interface");
NS_LOG_LOGIC ("sourceCellId = " << params.sourceCellId);
NS_LOG_LOGIC ("targetCellId = " << params.targetCellId);
NS_LOG_LOGIC ("gtpTeid = " << params.gtpTeid);
NS_LOG_LOGIC ("ueData = " << params.ueData);
NS_LOG_LOGIC ("ueData size = " << params.ueData->GetSize ());
std::map<uint32_t, X2uTeidInfo>::iterator
teidInfoIt = m_x2uTeidInfoMap.find (params.gtpTeid);
if (teidInfoIt != m_x2uTeidInfoMap.end ())
{
GetUeManager (teidInfoIt->second.rnti)->SendData (teidInfoIt->second.drbid, params.ueData);
}
else
{
NS_FATAL_ERROR ("X2-U data received but no X2uTeidInfo found");
}
}
uint16_t
LteEnbRrc::DoAllocateTemporaryCellRnti ()
{
NS_LOG_FUNCTION (this);
return AddUe (UeManager::INITIAL_RANDOM_ACCESS);
}
void
LteEnbRrc::DoRrcConfigurationUpdateInd (LteEnbCmacSapUser::UeConfig cmacParams)
{
Ptr<UeManager> ueManager = GetUeManager (cmacParams.m_rnti);
ueManager->CmacUeConfigUpdateInd (cmacParams);
}
void
LteEnbRrc::DoNotifyLcConfigResult (uint16_t rnti, uint8_t lcid, bool success)
{
NS_LOG_FUNCTION (this << (uint32_t) rnti);
NS_FATAL_ERROR ("not implemented");
}
uint8_t
LteEnbRrc::DoAddUeMeasReportConfigForHandover (LteRrcSap::ReportConfigEutra reportConfig)
{
NS_LOG_FUNCTION (this);
uint8_t measId = AddUeMeasReportConfig (reportConfig);
m_handoverMeasIds.insert (measId);
return measId;
}
void
LteEnbRrc::DoTriggerHandover (uint16_t rnti, uint16_t targetCellId)
{
NS_LOG_FUNCTION (this << rnti << targetCellId);
bool isHandoverAllowed = true;
if (m_anrSapProvider != 0)
{
// ensure that proper neighbour relationship exists between source and target cells
bool noHo = m_anrSapProvider->GetNoHo (targetCellId);
bool noX2 = m_anrSapProvider->GetNoX2 (targetCellId);
NS_LOG_DEBUG (this << " cellId=" << m_cellId
<< " targetCellId=" << targetCellId
<< " NRT.NoHo=" << noHo << " NRT.NoX2=" << noX2);
if (noHo || noX2)
{
isHandoverAllowed = false;
NS_LOG_LOGIC (this << " handover to cell " << targetCellId
<< " is not allowed by ANR");
}
}
Ptr<UeManager> ueManager = GetUeManager (rnti);
NS_ASSERT_MSG (ueManager != 0, "Cannot find UE context with RNTI " << rnti);
if (ueManager->GetState () != UeManager::CONNECTED_NORMALLY)
{
isHandoverAllowed = false;
NS_LOG_LOGIC (this << " handover is not allowed because the UE"
<< " rnti=" << rnti << " is in "
<< ToString (ueManager->GetState ()) << " state");
}
if (isHandoverAllowed)
{
// initiate handover execution
ueManager->PrepareHandover (targetCellId);
}
}
uint8_t
LteEnbRrc::DoAddUeMeasReportConfigForAnr (LteRrcSap::ReportConfigEutra reportConfig)
{
NS_LOG_FUNCTION (this);
uint8_t measId = AddUeMeasReportConfig (reportConfig);
m_anrMeasIds.insert (measId);
return measId;
}
uint16_t
LteEnbRrc::AddUe (UeManager::State state)
{
NS_LOG_FUNCTION (this);
bool found = false;
uint16_t rnti;
for (rnti = m_lastAllocatedRnti + 1;
(rnti != m_lastAllocatedRnti - 1) && (!found);
++rnti)
{
if ((rnti != 0) && (m_ueMap.find (rnti) == m_ueMap.end ()))
{
found = true;
break;
}
}
NS_ASSERT_MSG (found, "no more RNTIs available (do you have more than 65535 UEs in a cell?)");
m_lastAllocatedRnti = rnti;
Ptr<UeManager> ueManager = CreateObject<UeManager> (this, rnti, state);
m_ueMap.insert (std::pair<uint16_t, Ptr<UeManager> > (rnti, ueManager));
ueManager->Initialize ();
NS_LOG_DEBUG (this << " New UE RNTI " << rnti << " cellId " << m_cellId << " srs CI " << ueManager->GetSrsConfigurationIndex ());
m_newUeContextTrace (m_cellId, rnti);
return rnti;
}
void
LteEnbRrc::RemoveUe (uint16_t rnti)
{
NS_LOG_FUNCTION (this << (uint32_t) rnti);
std::map <uint16_t, Ptr<UeManager> >::iterator it = m_ueMap.find (rnti);
NS_ASSERT_MSG (it != m_ueMap.end (), "request to remove UE info with unknown rnti " << rnti);
uint16_t srsCi = (*it).second->GetSrsConfigurationIndex ();
m_ueMap.erase (it);
m_cmacSapProvider->RemoveUe (rnti);
m_cphySapProvider->RemoveUe (rnti);
if (m_s1SapProvider != 0)
{
m_s1SapProvider->UeContextRelease (rnti);
}
// need to do this after UeManager has been deleted
RemoveSrsConfigurationIndex (srsCi);
}
TypeId
LteEnbRrc::GetRlcType (EpsBearer bearer)
{
switch (m_epsBearerToRlcMapping)
{
case RLC_SM_ALWAYS:
return LteRlcSm::GetTypeId ();
break;
case RLC_UM_ALWAYS:
return LteRlcUm::GetTypeId ();
break;
case RLC_AM_ALWAYS:
return LteRlcAm::GetTypeId ();
break;
case PER_BASED:
if (bearer.GetPacketErrorLossRate () > 1.0e-5)
{
return LteRlcUm::GetTypeId ();
}
else
{
return LteRlcAm::GetTypeId ();
}
break;
default:
return LteRlcSm::GetTypeId ();
break;
}
}
void
LteEnbRrc::AddX2Neighbour (uint16_t cellId)
{
NS_LOG_FUNCTION (this << cellId);
if (m_anrSapProvider != 0)
{
m_anrSapProvider->AddNeighbourRelation (cellId);
}
}
void
LteEnbRrc::SetCsgId (uint32_t csgId, bool csgIndication)
{
NS_LOG_FUNCTION (this << csgId << csgIndication);
m_sib1.cellAccessRelatedInfo.csgIdentity = csgId;
m_sib1.cellAccessRelatedInfo.csgIndication = csgIndication;
m_cphySapProvider->SetSystemInformationBlockType1 (m_sib1);
}
// from 3GPP TS 36.213 table 8.2-1 UE Specific SRS Periodicity
static const uint8_t SRS_ENTRIES = 9;
static const uint16_t g_srsPeriodicity[SRS_ENTRIES] = {0, 2, 5, 10, 20, 40, 80, 160, 320};
static const uint16_t g_srsCiLow[SRS_ENTRIES] = {0, 0, 2, 7, 17, 37, 77, 157, 317};
static const uint16_t g_srsCiHigh[SRS_ENTRIES] = {0, 1, 6, 16, 36, 76, 156, 316, 636};
void
LteEnbRrc::SetSrsPeriodicity (uint32_t p)
{
NS_LOG_FUNCTION (this << p);
for (uint32_t id = 1; id < SRS_ENTRIES; ++id)
{
if (g_srsPeriodicity[id] == p)
{
m_srsCurrentPeriodicityId = id;
return;
}
}
// no match found
std::ostringstream allowedValues;
for (uint32_t id = 1; id < SRS_ENTRIES; ++id)
{
allowedValues << g_srsPeriodicity[id] << " ";
}
NS_FATAL_ERROR ("illecit SRS periodicity value " << p << ". Allowed values: " << allowedValues.str ());
}
uint32_t
LteEnbRrc::GetSrsPeriodicity () const
{
NS_LOG_FUNCTION (this);
NS_ASSERT (m_srsCurrentPeriodicityId > 0);
NS_ASSERT (m_srsCurrentPeriodicityId < SRS_ENTRIES);
return g_srsPeriodicity[m_srsCurrentPeriodicityId];
}
uint16_t
LteEnbRrc::GetNewSrsConfigurationIndex ()
{
NS_LOG_FUNCTION (this << m_ueSrsConfigurationIndexSet.size ());
// SRS
NS_ASSERT (m_srsCurrentPeriodicityId > 0);
NS_ASSERT (m_srsCurrentPeriodicityId < SRS_ENTRIES);
NS_LOG_DEBUG (this << " SRS p " << g_srsPeriodicity[m_srsCurrentPeriodicityId] << " set " << m_ueSrsConfigurationIndexSet.size ());
if (m_ueSrsConfigurationIndexSet.size () >= g_srsPeriodicity[m_srsCurrentPeriodicityId])
{
NS_FATAL_ERROR ("too many UEs (" << m_ueSrsConfigurationIndexSet.size () + 1
<< ") for current SRS periodicity "
<< g_srsPeriodicity[m_srsCurrentPeriodicityId]
<< ", consider increasing the value of ns3::LteEnbRrc::SrsPeriodicity");
}
if (m_ueSrsConfigurationIndexSet.empty ())
{
// first entry
m_lastAllocatedConfigurationIndex = g_srsCiLow[m_srsCurrentPeriodicityId];
m_ueSrsConfigurationIndexSet.insert (m_lastAllocatedConfigurationIndex);
}
else
{
// find a CI from the available ones
std::set<uint16_t>::reverse_iterator rit = m_ueSrsConfigurationIndexSet.rbegin ();
NS_ASSERT (rit != m_ueSrsConfigurationIndexSet.rend ());
NS_LOG_DEBUG (this << " lower bound " << (*rit) << " of " << g_srsCiHigh[m_srsCurrentPeriodicityId]);
if ((*rit) < g_srsCiHigh[m_srsCurrentPeriodicityId])
{
// got it from the upper bound
m_lastAllocatedConfigurationIndex = (*rit) + 1;
m_ueSrsConfigurationIndexSet.insert (m_lastAllocatedConfigurationIndex);
}
else
{
// look for released ones
for (uint16_t srcCi = g_srsCiLow[m_srsCurrentPeriodicityId]; srcCi < g_srsCiHigh[m_srsCurrentPeriodicityId]; srcCi++)
{
std::set<uint16_t>::iterator it = m_ueSrsConfigurationIndexSet.find (srcCi);
if (it==m_ueSrsConfigurationIndexSet.end ())
{
m_lastAllocatedConfigurationIndex = srcCi;
m_ueSrsConfigurationIndexSet.insert (srcCi);
break;
}
}
}
}
return m_lastAllocatedConfigurationIndex;
}
void
LteEnbRrc::RemoveSrsConfigurationIndex (uint16_t srcCi)
{
NS_LOG_FUNCTION (this << srcCi);
std::set<uint16_t>::iterator it = m_ueSrsConfigurationIndexSet.find (srcCi);
NS_ASSERT_MSG (it != m_ueSrsConfigurationIndexSet.end (), "request to remove unkwown SRS CI " << srcCi);
m_ueSrsConfigurationIndexSet.erase (it);
}
uint8_t
LteEnbRrc::GetLogicalChannelGroup (EpsBearer bearer)
{
if (bearer.IsGbr ())
{
return 1;
}
else
{
return 2;
}
}
uint8_t
LteEnbRrc::GetLogicalChannelPriority (EpsBearer bearer)
{
return bearer.qci;
}
void
LteEnbRrc::SendSystemInformation ()
{
// NS_LOG_FUNCTION (this);
/*
* For simplicity, we use the same periodicity for all SIBs. Note that in real
* systems the periodicy of each SIBs could be different.
*/
LteRrcSap::SystemInformation si;
si.haveSib2 = true;
si.sib2.freqInfo.ulCarrierFreq = m_ulEarfcn;
si.sib2.freqInfo.ulBandwidth = m_ulBandwidth;
LteEnbCmacSapProvider::RachConfig rc = m_cmacSapProvider->GetRachConfig ();
LteRrcSap::RachConfigCommon rachConfigCommon;
rachConfigCommon.preambleInfo.numberOfRaPreambles = rc.numberOfRaPreambles;
rachConfigCommon.raSupervisionInfo.preambleTransMax = rc.preambleTransMax;
rachConfigCommon.raSupervisionInfo.raResponseWindowSize = rc.raResponseWindowSize;
si.sib2.radioResourceConfigCommon.rachConfigCommon = rachConfigCommon;
m_rrcSapUser->SendSystemInformation (si);
Simulator::Schedule (m_systemInformationPeriodicity, &LteEnbRrc::SendSystemInformation, this);
}
} // namespace ns3
|
ericjpj/ns-3-dev
|
src/lte/model/lte-enb-rrc.cc
|
C++
|
gpl-2.0
| 78,361 |
# __________ __ ___.
# Open \______ \ ____ ____ | | _\_ |__ _______ ___
# Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
# Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
# Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
# \/ \/ \/ \/ \/
# $Id: Makefile 12058 2007-01-18 00:46:52Z dave $
#
# http://daniel.haxx.se/blog/2007/11/18/free-to-use-compiler-from-ti/
CC = cl500
LD = lnk500
CFLAGS =
# There's more in linker.cmd.
LDFLAGS = -w
OBJDIR=./build
OBJS = arm.obj main.obj vectors.obj dma.obj
ifeq ($(findstring -DCREATIVE_ZV,$(TARGET)), -DCREATIVE_ZV)
OBJS += aic23.obj
else
OBJS += tsc2100.obj
endif
OBJS := $(patsubst %.obj, $(OBJDIR)/%.obj, $(OBJS))
all: dsp-image.h
clean:
$(call PRINTS,cleaning DSP firmware)rm -f $(OBJS) $(OBJDIR)/dsp-image.out $(OBJDIR)/dsp-image.xml
rmdir $(OBJDIR)
dsp-image.h: $(OBJS) linker.cmd
$(call PRINTS,LNK500 dsp-image.out)lnk500 $(LDFLAGS) -o $(OBJDIR)/dsp-image.out $^
$(call PRINTS,OFD500+XML2H $(@F))ofd500 -x -o /dev/stdout $(OBJDIR)/dsp-image.out | python xml2h.py $(OBJDIR)/dsp-image.xml > $@
$(OBJDIR)/%.obj: %.asm
$(SILENT)mkdir -p $(dir $@)
$(call PRINTS,CL500 $<)$(CC) $(CFLAGS) -fr $(dir $@) $<
$(OBJDIR)/%.obj: %.c
$(SILENT)mkdir -p $(dir $@)
$(call PRINTS,CL500 $<)$(CC) $(CFLAGS) -fr $(dir $@) $<
$(OBJDIR)/arm.obj: arm.c arm.h registers.h ipc.h
$(OBJDIR)/main.obj: main.c arm.h registers.h ipc.h dma.h audio.h
$(OBJDIR)/aic23.obj: aic23.c audio.h registers.h
$(OBJDIR)/tsc2100.obj: tsc2100.c audio.h registers.h
$(OBJDIR)/dma.obj: dma.c dma.h registers.h ipc.h
|
realtsiry/rockbox4linux
|
firmware/target/arm/tms320dm320/dsp/Makefile
|
Makefile
|
gpl-2.0
| 1,680 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.