code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA test system for EE658 at USC
*
FPGA test system is a 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.
FPGA test system 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 the FPGA test system. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <iostream>
#include <vector>
#include <map>
#include "Node.h"
#include "Command.h"
#include "global.h"
#include "type.h"
#include "fileRead.h"
#include "fileWrite.h"
#include "preprocess.h"
using namespace std;
int preprocess(){
int i;
e_ntype temp;
char netlistFile[] = "netlist.txt";
char faultListFile[] = "original_fault_list.txt";
cread((char*)netlistFile); //read in circuit netlist
fread((char*)faultListFile); //read in fault list
removeFF(); //strip off flip-flop
lev(); //must levelize circuit after stripping off flip flop
printScanNetlist(); //print out scan netlist file
printLevel(); //print out netlist level
for(i=0;i<NumberNodes;i++){
temp = (e_ntype)NodePointer[i].getType();
if(temp==GATE || temp==PO || temp==PPO){
NodePointer[i].pCubeProcess(); //primitive cube process
NodePointer[i].domProcess();
}
}
printDominance();
printFilteredFault();
return 1;
}
int help(){
cout<<"READ filename - ";
cout<<"read in circuit file and creat all data structures\n";
cout<<"PC - ";
cout<<"print circuit information\n";
cout<<"HELP - ";
cout<<"print this help information\n";
cout<<"QUIT - ";
cout<<"stop and exit\n";
cout<<"LEV - ";
cout<<"levelize circuit\n";
return 1;
}
int quit(){
Done = 1;
return 1;
}
int lev(){
Node* npointer;
int count,i,j,temp;
ReadyList = new Node* [NumberNodes];
initialPI_PPI();
while(!checkPO_PPO()){
count=0;
for(i=0;i<NumberNodes;i++){
npointer=&NodePointer[i];
if(npointer->getNodeReady() == 0){
temp = npointer->getInputReady();
for(j=0;j<npointer->getFanin();j++){
if(npointer->getUpperNodes()[j]->getNodeReady()==1){
npointer->setInputReady(++temp);
}
}
if(npointer->getInputReady() == npointer->getFanin()){
ReadyList[count] = npointer;
count++;
}else{
npointer->setInputReady(0);
}
}
}
for(i=0;i<count;i++){
ReadyList[i]->setLevel(levelComp(ReadyList[i]));
ReadyList[i]->setNodeReady(1);
ReadyList[i]=NULL;
}
}
cout<<"levelizing is complete.\n";
return 1;
}
int levelComp(Node* np){
int level,temp,i;
if(np->getType() == FB){
level = np->getUpperNodes()[0]->getLevel()+1;
}else{
if(np->getType() == GATE || np->getType() == PO || np->getType() == PPO){
level = np->getUpperNodes()[0]->getLevel();
for(i=0; i<np->getFanin(); i++){
temp = np->getUpperNodes()[i]->getLevel();
if(temp > level){
level = temp;
}
}
level++;
}else{
cout<<"level calculation of unknown node type.\n";
}
}
if(level > NumberLevel) NumberLevel = level;
return level;
}
int removeFF(){
int i;
for(i=0;i<NumberPPI;i++){
PPIList[i]->setUpperNodes(NULL);
PPIList[i]->setType(PPI);
PPIList[i]->setFanin(0);
PPIList[i]->setGate(259);
}
for(i=0;i<NumberPPO;i++){
PPOList[i]->setDownNodes(NULL);
PPOList[i]->setType(PPO);
PPOList[i]->setFanout(0);
}
return 1;
}
Node* findNode(int number){
int i;
for(i=0; i<NumberNodes; i++){
if(NodePointer[i].getNumber() == number){
return &NodePointer[i];
}
}
return NULL;
}
int connectPointer(Node* nodePointer, int num){
// cout<<"node="<<nodePointer->getNumber()<<" num="<<num<<"\n";
int upperCounter = nodePointer->getUpperCounter();
Node *temp = findNode(num);
nodePointer->getUpperNodes()[upperCounter] = temp;
nodePointer->setUpperCounter(upperCounter+1);
int downCounter = temp->getDownCounter();
temp->getDownNodes()[downCounter] = nodePointer;
temp->setDownCounter(downCounter+1);
return 1;
}
int allocate(){
NodePointer = new Node [NumberNodes];
if(NodePointer == NULL){
cout<<"Node dynamic allocation fail."<<endl;
return 0;
}
PrimaryInput = new Node* [NumberPI];
if(PrimaryInput == NULL){
cout<<"PI dynamic allocation fail."<<endl;
return 0;
}
PrimaryOutput = new Node* [NumberPO];
if(PrimaryOutput == NULL){
cout<<"PO dynamic allocation fail."<<endl;
return 0;
}
FanoutBranch = new Node* [NumberFB];
if(FanoutBranch == NULL){
cout<<"FB dynamic allocation fail."<<endl;
}
PPIList = new Node* [NumberPPI];
if(PPIList == NULL){
cout<<"PPI dynamic allocation fail."<<endl;
}
PPOList = new Node* [NumberPPO];
if(PPOList == NULL){
cout<<"PPO dynamic allocation fail."<<endl;
}
return 1;
}
int clear(){
int i;
for(i=0; i<NumberNodes; i++){
delete [] NodePointer[i].getUpperNodes();
delete [] NodePointer[i].getDownNodes();
}
delete [] NodePointer;
delete [] PrimaryInput;
delete [] FanoutBranch;
delete [] PrimaryOutput;
delete [] PPIList;
delete [] PPOList;
delete [] ReadyList;
NumberNodes = 0;
NumberPI = 0;
NumberFB = 0;
NumberPO = 0;
NumberPPI = 0;
NumberPPO = 0;
Done = 0;
NumberLevel = 0;
ClockPeriod = 0;
FFInitial.clear();
InputSequence.clear();
FFInitial_comp.clear();
InputSequence_comp.clear();
delete timeHead;
delete timeTail;
delete assignHead;
delete assignTail;
displayBuffer.clear();
compareBuffer.clear();
GlobalState = EXEC;
return 1;
}
int pc(){
int i,j;
for(i=0;i<NumberNodes;i++){
cout<<"number: "<<NodePointer[i].getNumber();
cout<<" level: "<<NodePointer[i].getLevel();
//cout<<" fault: ";
//for(j=0;j<NodePointer[i].getFaultListCount();j++){
// cout<<NodePointer[i].getFaultList(j)<<" ";
//}
//cout<<"inertial: "<<NodePointer[i].getInertialDelay();
//cout<<" rise: "<<NodePointer[i].getRiseDelay();
//cout<<" fall: "<<NodePointer[i].getFallDelay();
//cout<<" logic: "<<NodePointer[i].getLogicValue();
//cout<<" gate: "<<NodePointer[i].getGate();
cout<<" logic: "<<translate(NodePointer[i].getLogicValue_E());
cout<<" logicReady: "<<NodePointer[i].getLogicReady();
cout<<endl;
}
cout<<"Primary inputs: ";
for(i=0;i<NumberPI;i++){
cout<<PrimaryInput[i]->getNumber()<<" ";
}
cout<<endl;
cout<<"Fanout branches: ";
for(i=0;i<NumberFB;i++){
cout<<FanoutBranch[i]->getNumber()<<" ";
}
cout<<endl;
cout<<"Primary outputs: ";
for(i=0;i<NumberPO;i++){
cout<<PrimaryOutput[i]->getNumber()<<" ";
}
cout<<endl;
cout<<"PPI: ";
for(i=0;i<NumberPPI;i++){
cout<<PPIList[i]->getNumber()<<" ";
}
cout<<endl;
cout<<"PPO: ";
for(i=0;i<NumberPPO;i++){
cout<<PPOList[i]->getNumber()<<" ";
}
cout<<endl;
cout<<"Number of nodes = "<<NumberNodes<<endl;
cout<<"Number of primary inputs = "<<NumberPI<<endl;
cout<<"Number of fanout branches = "<<NumberFB<<endl;
cout<<"Number of primary outputs = "<<NumberPO<<endl;
cout<<"Number of PPI = "<<NumberPPI<<endl;
cout<<"Number of PPO = "<<NumberPPO<<endl;
cout<<"Max number of level = "<<NumberLevel<<endl;
cout<<"Clock period = "<<ClockPeriod<<endl;
cout<<"Flipflop initial value = ";
for(i=0;i<FFInitial.size();i++){
cout<<FFInitial[i]<<" ";
}
cout<<endl;
for(i=0;i<InputSequence.size();i++){
for(j=0;j<InputSequence[i].size();j++){
cout<<InputSequence[i][j]<<" ";
}
cout<<endl;
}
return 1;
}
int initialPI_PPI(){
int i;
for(i=0;i<NumberPI;i++){
// PrimaryInput[i]->setLevel(0);
PrimaryInput[i]->setNodeReady(1);
}
for(i=0;i<NumberPPI;i++){
PPIList[i]->setNodeReady(1);
}
return 1;
}
int checkPO_PPO(){
int i;
for(i=0;i<NumberPO;i++){
if(PrimaryOutput[i]->getNodeReady() == 0){
return 0;
}
}
for(i=0;i<NumberPPO;i++){
if(PPOList[i]->getNodeReady() == 0){
return 0;
}
}
return 1;
}
| zzfall2010ee658 | preprocess.cpp | C++ | gpl3 | 9,268 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA test system for EE658 at USC
*
FPGA test system is a 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.
FPGA test system 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 the FPGA test system. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* File: logicSim.h
* Author: zhouzhao
*
* Created on November 23, 2010, 6:00 PM
*/
#ifndef LOGICSIM_H
#define LOGICSIM_H
int simulation();
int comparison();
int logicSim_comp(); //gateway method of logic simulation without delay info
int logicSim_delay(); //gateway method of logic simulation with delay info
int evaluate(Node* np); //evaluate logic output of CLB
int rfDelay(Node* np, int logic); //compute rise or fall delay
int initialSim(int cycle); //initial PI and PPI for logic simulation
int initialSim_comp(int cycle);
int startupSim(int cycle); //timing wheel startup
void queuePush(int time, Node* node, int value); //push an event into the timing wheel
void displayBufferPush(int number, int time, int logic); //push event into waveform data structure
TSTAMP* queuePop(); //pop an event from the timing wheel
TSTAMP* queueFind(int time); //find event in the timing wheel
TSTAMP* queueInsert(int time); //insert event into timing wheel
int fpgaSim_delay();
int fpgaSim_comp();
#endif /* LOGICSIM_H */
| zzfall2010ee658 | logicSim.h | C | gpl3 | 1,770 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA test system for EE658 at USC
*
FPGA test system is a 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.
FPGA test system 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 the FPGA test system. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* File: fileRead.h
* Author: zhouzhao
*
* Created on November 23, 2010, 2:55 PM
*/
using namespace std;
#ifndef FILEREAD_H
#define FILEREAD_H
int cread(char *charPointer); //read in circuit netlist
int fread(char *charPointer); //read in fault list
int dread(char *charPointer); //read in delay info
int seqread(char *charPointer); //read in input sequence
int tread(char *charPointer); //read in ATPG test logic
int vread(char* charPointer); //read in input vector for comparison
int iread(char *charPointer);
int findFilteredNode(int number);
#endif /* FILEREAD_H */
| zzfall2010ee658 | fileRead.h | C++ | gpl3 | 1,325 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA test system for EE658 at USC
*
FPGA test system is a 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.
FPGA test system 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 the FPGA test system. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* File: global.h
* Author: zhouzhao
*
* Created on November 23, 2010, 3:16 PM
*/
#include "type.h"
#include "Node.h"
using namespace std;
#ifndef GLOBAL_H
#define GLOBAL_H
extern Node * NodePointer;
extern Node ** PrimaryInput;
extern Node ** FanoutBranch;
extern Node ** PrimaryOutput;
extern Node ** PPIList;
extern Node ** PPOList;
extern Node ** ReadyList;
extern unsigned int NumberNodes;
extern unsigned int NumberPI;
extern unsigned int NumberFB;
extern unsigned int NumberPO;
extern unsigned int NumberPPI;
extern unsigned int NumberPPO;
extern unsigned int Done;
extern unsigned int NumberLevel;
extern unsigned int ClockPeriod;
extern vector<unsigned int> FFInitial;
extern vector< vector<unsigned int> > InputSequence;
extern vector<unsigned int> FFInitial_comp;
extern vector< vector<unsigned int> > InputSequence_comp;
extern TSTAMP* timeHead;
extern TSTAMP* timeTail;
extern ASSIGN* assignHead;
extern ASSIGN* assignTail;
extern map<int, vector<GEVENT> > displayBuffer;
extern map<int, vector<int> > compareBuffer;
extern map<int, vector<int> > filteredFault;
extern vector< vector<e_logic> > testPattern;
extern e_state GlobalState;
//extern vector<Node*> DFrontier;
//extern vector<Node*> JFrontier;
#endif /* MAIN_H */
| zzfall2010ee658 | global.h | C++ | gpl3 | 2,004 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA test system for EE658 at USC
*
FPGA test system is a 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.
FPGA test system 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 the FPGA test system. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <iostream>
#include <vector>
#include <map>
#include "Node.h"
#include "Command.h"
#include "global.h"
#include "type.h"
#include "logicSim.h"
#include "fileRead.h"
#include "fileWrite.h"
#include "preprocess.h"
#include "atpg.h"
using namespace std;
int simulation(){
char delayFile[] = "delay_values.txt";
char sequenceFile[] = "logic_simulator_input_sequence.txt";
dread((char*)delayFile); //read in delay file
seqread((char*)sequenceFile); //read in input sequence
fpgaSim_delay();
printDisplayBuffer();
printWaveform();
printPO_FF();
printGlitch();
//local ATPG
/*
np=findNode(4);
np->fCubeProcess(np->findFaultNum(13));
for(i=0;i<np->getFanin();i++){
np->getUpperNodes()[i]->setLogicValue_E(np->getDectectDbar()[0][i]);
}
np->setLogicValue_E(DBAR);
implyProcess(4,DBAR);
implyCheck();
*/
// tread(testATPGFile);
// findNode(16)->dCubeProcess(0,D);
return 1;
}
int comparison(){
int i,j;
char vectorFile[] = "input_vectors.txt";
char fileName[] = "PO_FF_state.txt";
FILE* fileID;
vector<int> temp;
vread(vectorFile);
fpgaSim_comp();
fileID = fopen(fileName, "w");
if(fileID==NULL){
cout<<"PO and FF state file can not be opened."<<endl;
return 0;
}
for(i=0;i<NumberPPI;i++){
fprintf(fileID, "%d ", PPIList[i]->getNumber());
temp = (compareBuffer.find(PPIList[i]->getNumber()))->second;
for(j=0;j<temp.size();j++){
fprintf(fileID, "%d ", temp[j]);
}
fprintf(fileID, "\n");
}
for(i=0;i<NumberPO;i++){
fprintf(fileID, "%d ", PrimaryOutput[i]->getNumber());
temp = (compareBuffer.find(PrimaryOutput[i]->getNumber()))->second;
for(j=0;j<temp.size();j++){
fprintf(fileID, "%d ", temp[j]);
}
fprintf(fileID, "\n");
}
fclose(fileID);
return 1;
}
int fpgaSim_delay(){
int i;
//logic simulation with delay
for(i=0;i<InputSequence.size();i++){
cout<<"------------------"<<endl;
cout<<"cycle: "<<i<<endl;
cout<<"------------------"<<endl;
initialSim(i);
startupSim(i);
logicSim_delay();
}
return 1;
}
int fpgaSim_comp(){
int i;
map<int, vector<int> >::iterator it;
for(it=compareBuffer.begin();it!=compareBuffer.end();it++){
(it->second).clear();
}
for(i=0;i<InputSequence_comp.size();i++){
initialSim_comp(i);
logicSim_comp();
}
printCompareBuffer();
return 1;
}
int logicSim_comp(){
int level,i;
for(level=1;level<=NumberLevel;level++){
for(i=0;i<NumberNodes;i++){
if(NodePointer[i].getLevel() == level){
NodePointer[i].setLogicValue(evaluate(&NodePointer[i]));
}
}
}
for(i=0;i<NumberNodes;i++){
compareBuffer.find(NodePointer[i].getNumber())->second.push_back(NodePointer[i].getLogicValue());
}
return 1;
}
int evaluate(Node* np){
int j;
int input;
int weight;
int logic;
if(np->getType()==PI || np->getType()==PPI){
logic = np->getLogicValue();
}else{
if(np->getType()==FB){
logic = np->getUpperNodes()[0]->getLogicValue();
}else{
for(j=2,input=0,weight=1;j>=0;j--){
input += np->getUpperNodes()[j]->getLogicValue() * weight;
weight *=2;
}
logic = np->getLogicOutput(input);
}
}
return logic;
}
//event-driven logic simulation using two-pass strategy as shown in Fig. 3.31 in the textbook
int logicSim_delay(){
int currentTime;
TSTAMP* currentStamp;
LEVENT* ep;
Node* np;
int i;
int logic;
vector<Node*> activatedLine;
while(currentStamp = queuePop()){
currentTime = currentStamp->time;
cout<<"current time = "<<currentTime<<endl;
activatedLine.clear();
//first pass
while(currentStamp->eventHead != NULL){
ep = currentStamp->eventHead;
np = ep->line;
np->setLogicValue(ep->logic);
displayBufferPush(np->getNumber(),currentTime,ep->logic);
cout<<"node "<<np->getNumber()<<" is processed with logic of "<<ep->logic<<endl;
for(i=0;i<np->getFanout();i++){
activatedLine.push_back(np->getDownNodes()[i]); //todo not all fanout are activated
}
currentStamp->eventHead = ep->nextEvent;
delete ep;
}
//second pass
for(i=0;i<activatedLine.size();i++){
logic = evaluate(activatedLine[i]);
if(logic != activatedLine[i]->getLSV()){
queuePush(currentTime+rfDelay(activatedLine[i],logic),activatedLine[i],logic);
activatedLine[i]->setLSV(logic);
cout<<"node "<<activatedLine[i]->getNumber()<<" is scheduled with logic of "<<logic<<endl;
}
}
//release the memory
delete currentStamp;
}
}
void displayBufferPush(int number, int time, int logic){
int count = displayBuffer.find(number)->second.size();
if(count==0 || displayBuffer.find(number)->second[count-1].logic != logic){
GEVENT* gp = new GEVENT;
gp->logic = logic;
gp->time = time;
displayBuffer.find(number)->second.push_back(*gp);
}
}
int rfDelay(Node* np, int logic){
int delay;
if(np->getLogicValue() == logic){
delay = 0;
}else{
if(logic==0){
delay = np->getFallDelay();
}else{
delay = np->getRiseDelay();
}
}
return delay;
}
int initialSim(int cycle){
int i,logic,temp;
if(cycle == 0){
for(i=0;i<NumberPPI;i++){
temp = FFInitial[i];
PPIList[i]->setLogicValue(temp);
displayBufferPush(PPIList[i]->getNumber(),cycle*ClockPeriod,temp);
}
}else{
for(i=0;i<NumberPPI;i++){
temp = PPOList[i]->getLogicValue();
PPIList[i]->setLogicValue(temp);
displayBufferPush(PPIList[i]->getNumber(),cycle*ClockPeriod,temp);
}
}
for(i=0;i<NumberPI;i++){
logic = InputSequence[cycle][i];
PrimaryInput[i]->setLogicValue(logic);
displayBufferPush(PrimaryInput[i]->getNumber(),cycle*ClockPeriod,logic);
}
for(i=0;i<NumberNodes;i++){
NodePointer[i].setLSV(2);
}
return 1;
}
int initialSim_comp(int cycle){
int i,temp,logic;
if(cycle == 0){
for(i=0;i<NumberPPI;i++){
temp = FFInitial_comp[i];
PPIList[i]->setLogicValue(temp);
}
}else{
for(i=0;i<NumberPPI;i++){
temp = PPOList[i]->getLogicValue();
PPIList[i]->setLogicValue(temp);
}
}
for(i=0;i<NumberPI;i++){
logic = InputSequence_comp[cycle][i];
PrimaryInput[i]->setLogicValue(logic);
}
return 1;
}
int startupSim(int cycle){
int i,j;
int logic;
int delay;
for(i=0;i<NumberNodes;i++){
if(NodePointer[i].getLevel()==1){
logic = evaluate(&NodePointer[i]);
// cout<<"logic value = "<<logic<<endl;
delay = rfDelay(&NodePointer[i],logic);
queuePush(cycle*ClockPeriod+delay,&NodePointer[i],logic);
}
}
return 1;
}
void queuePush(int time, Node* node, int value){
LEVENT* ep = new LEVENT; //ep:=event pointer
TSTAMP* temp;
ep->line = node;
ep->logic = value;
ep->nextEvent = NULL;
if(timeHead==NULL && timeTail == NULL){
cout<<"queue of time is empty in the initial push"<<endl;
TSTAMP* tp = new TSTAMP; //tp:=time pointer
tp->eventHead = ep;
tp->eventTail = ep;
tp->nextStamp = NULL;
tp->time = time;
timeHead = tp;
timeTail = tp;
}else{
temp=queueFind(time);
if(temp!=NULL){
temp->eventTail->nextEvent = ep;
temp->eventTail = ep;
}else{
temp=queueInsert(time);
temp->eventHead = ep;
temp->eventTail = ep;
}
}
}
TSTAMP* queuePop(){
TSTAMP* temp;
if(timeHead == NULL && timeTail == NULL){
cout<<"queue of time is empty in the final pop"<<endl;
return NULL;
}
if(timeHead == timeTail){
temp = timeHead;
timeHead = NULL;
timeTail = NULL;
return temp;
}
temp = timeHead;
timeHead = timeHead->nextStamp;
return temp;
}
TSTAMP* queueFind(int time){
TSTAMP* tp = timeHead;
while(tp!=NULL){
if(tp->time == time){
return tp;
}else{
tp=tp->nextStamp;
}
}
return NULL;
}
TSTAMP* queueInsert(int time){
TSTAMP* tp = new TSTAMP;
tp->eventHead = NULL;
tp->eventTail = NULL;
tp->nextStamp = NULL;
tp->time = time;
TSTAMP* pre = timeHead;
TSTAMP* pro = timeHead->nextStamp;
if(time > timeTail->time){
timeTail->nextStamp = tp;
timeTail = tp;
}else{
if(time < timeHead->time){
tp->nextStamp = timeHead;
timeHead = tp;
}else{
while(pro!=NULL){
if(pre->time < time && pro->time > time){
pre->nextStamp = tp;
tp->nextStamp = pro;
return tp;
}else{
pre = pre->nextStamp;
pro = pro->nextStamp;
}
}
}
}
return tp;
}
| zzfall2010ee658 | logicSim.cpp | C++ | gpl3 | 10,401 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA test system for EE658 at USC
*
FPGA test system is a 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.
FPGA test system 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 the FPGA test system. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <vector>
#include <map>
#include "Node.h"
#include "Command.h"
#include "global.h"
using namespace std;
Node * NodePointer = NULL;
Node ** PrimaryInput = NULL;
Node ** FanoutBranch = NULL;
Node ** PrimaryOutput = NULL;
Node ** PPIList = NULL;
Node ** PPOList = NULL;
Node ** ReadyList = NULL;
unsigned int NumberNodes = 0;
unsigned int NumberPI = 0;
unsigned int NumberFB = 0;
unsigned int NumberPO = 0;
unsigned int NumberPPI = 0;
unsigned int NumberPPO = 0;
unsigned int Done = 0;
unsigned int NumberLevel = 0;
unsigned int ClockPeriod = 0;
vector<unsigned int> FFInitial;
vector< vector<unsigned int> > InputSequence;
vector<unsigned int> FFInitial_comp;
vector< vector<unsigned int> > InputSequence_comp;
TSTAMP* timeHead = NULL;
TSTAMP* timeTail = NULL;
ASSIGN* assignHead = NULL;
ASSIGN* assignTail = NULL;
map<int, vector<GEVENT> > displayBuffer;
map<int, vector<int> > compareBuffer;
map<int, vector<int> > filteredFault;
vector< vector<e_logic> > testPattern;
e_state GlobalState = EXEC;
//vector<Node*> DFrontier;
//vector<Node*> JFrontier;
| zzfall2010ee658 | global.cpp | C++ | gpl3 | 1,834 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA test system for EE658 at USC
*
FPGA test system is a 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.
FPGA test system 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 the FPGA test system. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* File: main.cpp
* Author: zhouzhao
*
* Created on October 14, 2010, 9:43 PM
*/
#include <cstdlib>
#include <string>
#include <iostream>
#include <vector>
#include <map>
#include "Node.h"
#include "Command.h"
#include "fileRead.h"
#include "global.h"
#include "type.h"
#include "logicSim.h"
#include "preprocess.h"
#include "fileWrite.h"
#include "atpg.h"
using namespace std;
int main(){
preprocess();
simulation();
// comparison();
// atpg();
// pc();
return (EXIT_SUCCESS);
}
| zzfall2010ee658 | main.cpp | C++ | gpl3 | 1,269 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA test system for EE658 at USC
*
FPGA test system is a 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.
FPGA test system 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 the FPGA test system. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include <iostream>
#include <vector>
#include <map>
#include "Node.h"
#include "Command.h"
#include "global.h"
#include "type.h"
#include "fileRead.h"
#include "preprocess.h"
using namespace std;
int cread(char *charPointer){
char buffer[MAXLINE];
FILE * fileID;
unsigned int type, number, gate, fanout, fanin;
unsigned int i,j;
unsigned int num;
vector<GEVENT> events;
vector<int> result;
sscanf(charPointer, "%s", buffer); //scan name of netlist file
fileID = fopen(buffer, "r");
if(fileID == NULL){
cout<<"netlist file "<<buffer<<" does not exist!"<<endl;
return 0;
}
//first pass to get number of nodes, PI, FB, and PO
while(fgets(buffer, MAXLINE, fileID) != NULL){ //read one line from netlist file
if(sscanf(buffer, "%d %d %d", &type, &number, &gate) == 3){ //scan the first three numbers
NumberNodes++;
switch (type){
case GATE:
if(gate == FLIPFLOP){
NumberPPI++;
NumberPPO++;
}
break;
case PI: NumberPI++; break;
case FB: NumberFB++; break;
case PO: NumberPO++; break;
default: cout<<"unknow node type."<<endl;
}
}
}
cout<<"first pass is complete."<<endl;
//number of PI, FB, PO are determined
if(allocate()){//allocate dynamic memory for nodes
cout<<"memory allocation is complete."<<endl;
}
fseek(fileID, 0L, 0);//reset file pointer
i=0;
//second pass to allocate dynamic memory for fanin and fanout pointers
while(fscanf(fileID, "%d %d %d", &type, &number, &gate) == 3){
NodePointer[i].setIndex(i);
NodePointer[i].setType(type);
NodePointer[i].setNumber(number);
NodePointer[i].setGate(gate);
displayBuffer.insert(make_pair(number,events));
compareBuffer.insert(make_pair(number,result));
switch (type){
case GATE:
if(fscanf(fileID, "%d %d", &fanout, &fanin) == 2){
NodePointer[i].setDownNodes(new Node* [fanout]);
NodePointer[i].setUpperNodes(new Node* [fanin]);
NodePointer[i].setFanout(fanout);
NodePointer[i].setFanin(fanin);
for(j=0;j<fanin;j++){
fscanf(fileID, "%d", &num);
}
}break;
case PI:
if(fscanf(fileID, "%d", &fanout) == 1){
NodePointer[i].setDownNodes(new Node* [fanout]);
NodePointer[i].setFanout(fanout);
fscanf(fileID, "%d", &num);
}break;
case FB:
NodePointer[i].setUpperNodes(new Node*);
NodePointer[i].setDownNodes(new Node*);
NodePointer[i].setFanout(1);
NodePointer[i].setFanin(1);
fscanf(fileID, "%d", &num);
break;
case PO:
if(fscanf(fileID, "%d %d", &fanout, &fanin) == 2){
NodePointer[i].setUpperNodes(new Node* [fanin]);
NodePointer[i].setFanin(fanin);
for(j=0;j<fanin;j++){
fscanf(fileID, "%d", &num);
}
}break;
default: cout<<"unknow node type."<<endl;
}
i++;
}
cout<<"second pass is complete."<<endl;
fseek(fileID, 0L, 0); //reset file pointer
i=0;
//third pass to configure fanin and fanout pointers
while(fscanf(fileID, "%d %d %d", &type, &number, &gate) == 3){
switch (type){
case GATE:
if(fscanf(fileID, "%d %d", &fanout, &fanin) == 2){
for(j=0; j<fanin; j++){
if(fscanf(fileID, "%d", &num) == 1){
connectPointer(&(NodePointer[i]), num);
}
}
}break;
case PI:
if(fscanf(fileID, "%d", &fanout) == 1){
fscanf(fileID, "%d", &fanin);
}break;
case FB:
if(fscanf(fileID, "%d", &num) == 1){
connectPointer(&NodePointer[i], num);
}break;
case PO:
if(fscanf(fileID, "%d %d", &fanout, &fanin) == 2){
for(int j=0; j<fanin; j++){
if(fscanf(fileID, "%d", &num) == 1){
connectPointer(&NodePointer[i], num);
}
}
}break;
default: cout<<"unknow node type."<<endl;
}
i++;
}
cout<<"third pass is complete."<<endl;
for(i=0,j=0;i<NumberNodes;i++){
if(NodePointer[i].getType()==PI){
PrimaryInput[j]=&NodePointer[i];
j++;
}
}
for(i=0,j=0;i<NumberNodes;i++){
if(NodePointer[i].getType()==FB){
FanoutBranch[j]=&NodePointer[i];
j++;
}
}
for(i=0,j=0;i<NumberNodes;i++){
if(NodePointer[i].getType()==PO){
PrimaryOutput[j]=&NodePointer[i];
j++;
}
}
for(i=0,j=0;i<NumberNodes;i++){
if(NodePointer[i].getGate()==FLIPFLOP){
PPIList[j]=&NodePointer[i];
PPOList[j]=NodePointer[i].getUpperNodes()[0];
j++;
}
}
fclose(fileID);
cout<<"circuit read is complete."<<endl;
return 1;
}
int fread(char *charPointer){
char buffer[MAXLINE];
char str[5];
FILE* fileID;
int number, fault;
sscanf(charPointer, "%s", buffer); //scan name of fault list file
fileID = fopen(buffer, "r");
if(fileID == NULL){
cout<<"fault list file "<<buffer<<" does not exist!"<<endl;
return 0;
}
// cout<<"fault file is opened successfully."<<endl;
while(fgets(buffer, MAXLINE, fileID) != NULL){ //read one line from fault list file
if(sscanf(buffer, "%s %d %d", str, &number, &fault) == 3){
findNode(number)->setFaultList(fault);
}
}
fclose(fileID);
cout<<"fault list readin is complete."<<endl;
return 1;
}
int iread(char *charPointer){
char buffer[MAXLINE];
char str[5];
FILE* fileID;
int number, fault;
vector<int> temp;
sscanf(charPointer, "%s", buffer); //scan name of filtered fault file
fileID = fopen(buffer, "r");
if(fileID == NULL){
cout<<"filtered fault file "<<buffer<<" does not exist!"<<endl;
return 0;
}
while(fgets(buffer, MAXLINE, fileID) != NULL){ //read one line from filtered fault file
if(sscanf(buffer, "%s %d %d", str, &number, &fault) == 3){
if(findFilteredNode(number)){
filteredFault.find(number)->second.push_back(fault);
}else{
temp.clear();
temp.push_back(fault);
filteredFault.insert(make_pair(number, temp));
}
}
}
fclose(fileID);
cout<<"filtered fault readin is complete."<<endl;
return 1;
}
int findFilteredNode(int number){
map<int, vector<int> >::iterator i;
for(i=filteredFault.begin();i!=filteredFault.end();i++){
if(i->first == number){
return 1;
}
}
return 0;
}
int tread(char *charPointer){
char buffer[MAXLINE];
FILE* fileID;
int number, logic;
sscanf(charPointer, "%s", buffer); //scan name of ATPG test file
fileID = fopen(buffer, "r");
if(fileID == NULL){
cout<<"ATPG test file "<<buffer<<" does not exist!"<<endl;
return 0;
}
while(fgets(buffer, MAXLINE, fileID) != NULL){ //read one line from ATPG test file
if(sscanf(buffer, "%d %d", &number, &logic) == 2){
findNode(number)->setLogicValue_E((e_logic)logic);
}
}
fclose(fileID);
cout<<"ATPG test file readin is complete."<<endl;
return 1;
}
int dread(char *charPointer){
char buffer[MAXLINE];
FILE* fileID;
int clock;
int number, inertialDelay, riseDelay, fallDelay;
Node* np;
sscanf(charPointer, "%s", buffer); //scan name of delay file
fileID = fopen(buffer, "r");
if(fileID == NULL){
cout<<"delay file "<<buffer<<" does not exist!"<<endl;
return 0;
}
// cout<<"delay file is opened successfully."<<endl;
if(fgets(buffer, MAXLINE, fileID)!= NULL){
if(sscanf(buffer, "%d", &clock) == 1){
ClockPeriod = clock;
}
}
while(fgets(buffer, MAXLINE, fileID) != NULL){ //read one line from delay file
if(sscanf(buffer, "%d %d %d %d", &number, &inertialDelay, &riseDelay, &fallDelay) == 4){
np = findNode(number);
np->setInertialDelay(inertialDelay);
np->setRiseDelay(riseDelay);
np->setFallDelay(fallDelay);
}
}
fclose(fileID);
cout<<"delay file readin is complete."<<endl;
return 1;
}
int seqread(char *charPointer){
char buffer[MAXLINE];
FILE* fileID;
int number, logic;
int i,j;
int counter=0;
vector<unsigned int> temp;
sscanf(charPointer, "%s", buffer); //scan name of input sequence file
fileID = fopen(buffer, "r");
if(fileID == NULL){
cout<<"input sequence file "<<buffer<<" does not exist!"<<endl;
return 0;
}
// cout<<"input sequence file is opened successfully."<<endl;
while(fgets(buffer, MAXLINE, fileID) != NULL){
counter++;
}
fseek(fileID, 0L, 0);
for(i=0;i<NumberPPI;i++){
if(fscanf(fileID, "%d %d", &number, &logic) == 2){
FFInitial.push_back(logic);
}
}
for(i=0;i<counter-1;i++){
for(j=0;j<NumberPI;j++){
if(fscanf(fileID, "%d", &logic) == 1){
temp.push_back(logic);
}
}
InputSequence.push_back(temp);
temp.clear();
}
fclose(fileID);
cout<<"input sequence file readin is complete."<<endl;
return 1;
}
int vread(char* charPointer){
char buffer[MAXLINE];
FILE* fileID;
int number, logic;
int i,j;
int counter=0;
vector<unsigned int> temp;
sscanf(charPointer, "%s", buffer); //scan name of input sequence file
fileID = fopen(buffer, "r");
if(fileID == NULL){
cout<<"input vector file "<<buffer<<" does not exist!"<<endl;
return 0;
}
while(fgets(buffer, MAXLINE, fileID) != NULL){
counter++;
}
fseek(fileID, 0L, 0);
FFInitial_comp.clear();
for(i=0;i<NumberPPI;i++){
if(fscanf(fileID, "%d %d", &number, &logic) == 2){
FFInitial_comp.push_back(logic);
}
}
InputSequence_comp.clear();
for(i=0;i<counter-1;i++){
for(j=0;j<NumberPI;j++){
if(fscanf(fileID, "%d", &logic) == 1){
temp.push_back(logic);
}
}
InputSequence_comp.push_back(temp);
temp.clear();
}
fclose(fileID);
cout<<"input vector file readin is complete."<<endl;
return 1;
}
| zzfall2010ee658 | fileRead.cpp | C++ | gpl3 | 12,250 |
package cn.nju.zyy.ioc;
public class SpringQuizMaster implements QuizMaster {
@Override
public String popQuestion() {
return "Are you new to Spring?";
}
}
| zyy-spring-demo | trunk/src/cn/nju/zyy/ioc/SpringQuizMaster.java | Java | asf20 | 173 |
package cn.nju.zyy.ioc;
public interface QuizMaster {
public String popQuestion();
}
| zyy-spring-demo | trunk/src/cn/nju/zyy/ioc/QuizMaster.java | Java | asf20 | 94 |
package cn.nju.zyy.ioc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class QuizApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
QuizMasterService quizMasterService = (QuizMasterService) context.getBean("quizMasterService");
quizMasterService.askQuestion();
}
}
| zyy-spring-demo | trunk/src/cn/nju/zyy/ioc/QuizApp.java | Java | asf20 | 455 |
package cn.nju.zyy.ioc;
public class QuizMasterService {
private QuizMaster quizMaster;
public void setQuizMaster(QuizMaster quizMaster) {
this.quizMaster = quizMaster;
}
public void askQuestion() {
System.out.println(quizMaster.popQuestion());
}
}
| zyy-spring-demo | trunk/src/cn/nju/zyy/ioc/QuizMasterService.java | Java | asf20 | 280 |
package cn.nju.zyy.ioc;
public class StrutsQuizMaster implements QuizMaster {
@Override
public String popQuestion() {
return "Are you new to Struts?";
}
}
| zyy-spring-demo | trunk/src/cn/nju/zyy/ioc/StrutsQuizMaster.java | Java | asf20 | 173 |
package cn.nju.zyy.hello;
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void display() {
System.out.println(message);
}
}
| zyy-spring-demo | trunk/src/cn/nju/zyy/hello/HelloWorld.java | Java | asf20 | 232 |
package cn.nju.zyy.hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloWorldApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
helloWorld.display();
}
}
| zyy-spring-demo | trunk/src/cn/nju/zyy/hello/HelloWorldApp.java | Java | asf20 | 425 |
package cn.nju.zyy.setterinjection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserApp {
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("user");
System.out.println(user);
}
}
| zyy-spring-demo | trunk/src/cn/nju/zyy/setterinjection/UserApp.java | Java | asf20 | 437 |
package cn.nju.zyy.setterinjection;
public class User {
private String name;
private int age;
private String country;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return name + " is " + age + " years old, living in " +
country;
}
}
| zyy-spring-demo | trunk/src/cn/nju/zyy/setterinjection/User.java | Java | asf20 | 601 |
package cn.nju.zyy.constructorinjection;
public class UserApp {
}
| zyy-spring-demo | trunk/src/cn/nju/zyy/constructorinjection/UserApp.java | Java | asf20 | 73 |
package cn.nju.zyy.constructorinjection;
public class User {
private String name;
private int age;
private String country;
User (String name, int age, String country) {
this.name = name;
this.age = age;
this.country = country;
}
@Override
public String toString() {
return name + " is " + age + " years old, living in " +
country;
}
}
| zyy-spring-demo | trunk/src/cn/nju/zyy/constructorinjection/User.java | Java | asf20 | 381 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA compiler for EE680 USC
*
FPGA compiler 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.
FPGA compiler 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Enumeration constants for color visualization.
*/
package edu.usc.ee.java;
/**
*
* @author Zhou Zhao
* @version 1.0
*/
public enum myColor
{
RED, GREEN, BLUE, YELLOW,
}
| zzspring2010ee680 | myColor.java | Java | gpl3 | 920 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA compiler for EE680 USC
*
FPGA compiler 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.
FPGA compiler 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* In the global routing, each switchbox is modeled in class of "switchBox", which
* has fields of "id", "x", "y" coordinates, "weight" for congestion computation,
* "color" for visualization. Note the field "weightWave" is used for wave
* propagation in weighted grid, so it is cleared after routing each net. In
* addition, boolean field "update" is assigned TRUE once the vertex is computed.
*/
package edu.usc.ee.java;
import java.util.ArrayList;
import java.util.List;
/**
* @author Zhou Zhao
* @version 1.0
*/
public class switchBox {
private int id;
private int x;
private int y;
private int weight;
private int weightWave;
private myColor color;
private boolean update;
private List<Integer> north;
private List<Integer> south;
private List<Integer> east;
private List<Integer> west;
public switchBox()
{}
public switchBox(int id, int x, int y, int row_max, int col_max)
{
this.id = id;
this.x = x;
this.y = y;
this.weight = 1;
this.weightWave = 0;
this.color = myColor.RED;
this.update = false;
this.north = new ArrayList<Integer>(col_max);
this.south = new ArrayList<Integer>(col_max);
this.east = new ArrayList<Integer>(row_max);
this.west = new ArrayList<Integer>(row_max);
}
public switchBox(int id, int x, int y, int weight, myColor color)
{
this.id = id;
this.x = x;
this.y = y;
this.weight = weight;
this.color = color;
}
public int getID()
{
return this.id;
}
public int getx()
{
return this.x;
}
public int gety()
{
return this.y;
}
public int getWeight()
{
return this.weight;
}
public void setWeight(int weight)
{
this.weight = weight;
}
public int getWeightWave()
{
return this.weightWave;
}
public void setWeightWave(int weightWave)
{
this.weightWave = weightWave;
}
public myColor getColor()
{
return this.color;
}
public void setColor(myColor color)
{
this.color = color;
}
public boolean getUpdate()
{
return this.update;
}
public void setUpdate(boolean update)
{
this.update = update;
}
@Override
public String toString()
{
return "V"+id+"("+x+","+y+")";
}
public void addNorth(Integer net){
this.north.add(net);
}
public List<Integer> getNorth(){
return this.north;
}
public void addSouth(Integer net){
this.south.add(net);
}
public List<Integer> getSouth(){
return this.south;
}
public void addEast(Integer net){
this.east.add(net);
}
public List<Integer> getEast(){
return this.east;
}
public void addWest(Integer net){
this.west.add(net);
}
public List<Integer> getWest(){
return this.west;
}
}
| zzspring2010ee680 | switchBox.java | Java | gpl3 | 3,781 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA compiler for EE680 USC
*
FPGA compiler 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.
FPGA compiler 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* The code in the class of XYLayout is used for layout the switchbox and
* track according to their x and y coordinates in Java Swing framework.
*/
package edu.usc.ee.java;
import edu.uci.ics.jung.algorithms.layout.AbstractLayout;
import edu.uci.ics.jung.graph.Graph;
import java.awt.Dimension;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.ListIterator;
import java.util.Map;
import org.apache.commons.collections15.Factory;
import org.apache.commons.collections15.map.LazyMap;
/**
*
* @author Zhou Zhao
* @version 1.0
*/
public class XYLayout extends AbstractLayout<switchBox, track>
{
private List<switchBox> vertex_list;
Map<switchBox, vertexData> vertexMap = LazyMap.decorate(
new HashMap<switchBox, vertexData>(),
new Factory<vertexData>()
{
public vertexData create()
{
return new vertexData();
}
});
public XYLayout(Graph<switchBox, track> g)
{
super(g);
}
public void setVertex(List<switchBox> list)
{
this.vertex_list = list;
}
public void reset()
{
initialize();
}
public void initialize()
{
Dimension d = getSize();
if (d != null)
{
if(vertex_list == null)
{
setVertex(new ArrayList<switchBox>(getGraph().getVertices()));
}
double height = d.getHeight();
double width = d.getWidth();
/*
int i = 0;
for(switchBox v : vertex_list)
{
Point2D coord = transform(v);
coord.setLocation(i,i);
vertexData data = getData(v);
data.setAngle(0);
i=i+100;
}
*/
for(ListIterator<switchBox> it = vertex_list.listIterator(); it.hasNext();)
{
switchBox sbox = it.next();
Point2D coord = transform(sbox);
coord.setLocation(sbox.getx()*100+50, sbox.gety()*100+50);
vertexData data = getData(sbox);
data.setAngle(0);
}
}
}
protected vertexData getData(switchBox v)
{
return vertexMap.get(v);
}
protected class vertexData
{
private double angle;
/* public vertexData()
{
}
*/
protected double getAngle()
{
return angle;
}
protected void setAngle(double angle)
{
this.angle = angle;
}
@Override
public String toString()
{
return "angle = " + angle;
}
}
} | zzspring2010ee680 | XYLayout.java | Java | gpl3 | 3,618 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA compiler for EE680 USC
*
FPGA compiler 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.
FPGA compiler 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* In global routing, the track between two swtichbox is modeled in class of
* track. Each track object has fields of "capacity" for congestion computation.
* It also has x, y coordinates and id.
*/
package edu.usc.ee.java;
/**
* @author zhouzhao
* @version 1.0
*/
public class track {
private int capacity;
private int weight; // weight field is the max capacity of each track
private int id;
private int x;
private int y;
public track(int id, int x, int y)
{
this.id = id;
this.x = x;
this.y = y;
this.weight = 0;
this.capacity = 0;
}
public track(int id, int x, int y, int weight)
{
this.id = id;
this.x = x;
this.y = y;
this.weight = weight;
this.capacity = 0;
}
public int getID()
{
return this.id;
}
public int getx()
{
return this.x;
}
public int gety()
{
return this.y;
}
public int getWeight()
{
return this.weight;
}
public void setWeight(int weight)
{
this.weight = weight;
}
public int getCapacity()
{
return this.capacity;
}
public void setCapacity(int capacity)
{
this.capacity = capacity;
}
@Override
public String toString()
{
return "E"+id+"("+x+","+y+")";
}
}
| zzspring2010ee680 | track.java | Java | gpl3 | 2,131 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA compiler for EE680 USC
*
FPGA compiler 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.
FPGA compiler 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* The code in class of Netlist is used for importing netlist from txt file.
* The code uses regular expression to import netlist, which simplifies the format
* of each statement. Although there are some blanks between signal name and pin
* number, code can also read in the netlist. The output of this importing process
* is a map data structure, which has key and value pair. Each key is a signal
* name with corresponding set of switchboxes stored in value.
*
*/
package edu.usc.ee.java;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.MatchResult;
/**
*
* @author zhouzhao
* @version 1.0
*/
public class Netlist{
private int x;
private int y;
private int n;
private int k;
public Netlist(int n, int k)
{
this.x = 0;
this.y = 0;
this.n = n;
this.k = k;
}
public int getx()
{
return this.x;
}
public void setx(int x)
{
this.x=x;
}
public int gety()
{
return this.y;
}
public void sety(int y)
{
this.y = y;
}
public int getn()
{
return this.n;
}
public int getk()
{
return this.k;
}
public void pin2coord(int n, int k, int pin)
{
if(pin>=1 && pin<=n*k*4){
switch((pin-1)/(n*k)){
case 0: x=((pin-1)/k+1)*2-1; y=0; break;
case 1: x=2*n; y=(((pin-n*k)-1)/k+1)*2-1; break;
case 2: x=2*n-(((pin-n*k*2)-1)/k+1)*2+1; y=2*n; break;
case 3: x=0; y=2*n-(((pin-n*k*3)-1)/k+1)*2+1; break;
default: x=0; y=0;
}
// System.out.println("x="+x+" y="+y);
}else{
System.out.println("Invalid pin number.");
}
}
public void array2coord(int n, int row, int col)
{
if(row>=1 && row<=n){
if(col>=1 && col<=n){
x = col*2-1;
y = row*2-1;
// System.out.println("x="+x+" y="+y);
}else{
System.out.println("Invalid column number");
}
}else{
System.out.println("Invalid row number");
}
}
public Map<Integer, Set<switchBox>> netlistProcess(switchBox[][] array)throws IOException{
// TODO code application logic here
Map<Integer, Set<switchBox>> m = new HashMap<Integer, Set<switchBox>>();
BufferedReader inputStream = null;
PrintWriter outputStream = null;
Integer sig;
Integer node;
Integer input_sig1;
Integer input_sig2;
Integer input_sig3;
Integer input_sig4;
Integer output_sig;
Integer row;
Integer column;
try{
inputStream = new BufferedReader(new FileReader("intraFPGA_Routing_6.txt"));
// outputStream = new PrintWriter(new FileWriter("lineoutput.txt"));
String line;
while((line = inputStream.readLine()) != null){
// outputStream.println(line);
boolean in = line.contains("INPUT_SIGNAL"); //input signal
boolean out = line.contains("OUTPUT_SIGNAL"); //output signal
boolean not = line.contains("NOT"); //one input gate
boolean nand2 = line.contains("NAND2"); //two input gate
boolean nor2 = line.contains("NOR2");
boolean xor2 = line.contains("XOR2");
boolean dff = line.contains("DFF");
boolean nand3 = line.contains("NAND3"); //three input gate
boolean nor3 = line.contains("NOR3");
boolean xor3 = line.contains("XOR3");
boolean nand4 = line.contains("NAND4"); //four input gate
boolean nor4 = line.contains("NOR4");
boolean xor4 = line.contains("XOR4");
if(in){
Scanner sc = new Scanner(line); //INPUT_SIGNAL(G5) 21
sc.findInLine("\\s*INPUT_SIGNAL\\s*\\(\\s*G(\\d+)\\s*\\)\\s*(\\d+)");
MatchResult result = sc.match();
sig = new Integer(result.group(1));
node = new Integer(result.group(2));
pin2coord(n, k, node);
switch(x){
case 0: array[x][y].addWest(sig); break;
case 6: array[x][y].addEast(sig); break;
default: break;
}
switch(y){
case 0: array[x][y].addNorth(sig); break;
case 6: array[x][y].addSouth(sig); break;
default: break;
}
if(m.containsKey(sig)){
m.get(sig).add(array[x][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x][y]);
m.put(sig, nodes);
}
sc.close();
}
if(out){
Scanner sc = new Scanner(line);
//OUTPUT_SIGNAL (G16) 12
sc.findInLine("\\s*OUTPUT_SIGNAL\\s*\\(\\s*G(\\d+)\\s*\\)\\s*(\\d+)");
MatchResult result = sc.match();
sig = new Integer(result.group(1));
node = new Integer(result.group(2));
pin2coord(n, k, node);
switch(x){
case 0: array[x][y].addWest(sig); break;
case 6: array[x][y].addEast(sig); break;
default: break;
}
switch(y){
case 0: array[x][y].addNorth(sig); break;
case 6: array[x][y].addSouth(sig); break;
default: break;
}
if(m.containsKey(sig)){
m.get(sig).add(array[x][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x][y]);
m.put(sig, nodes);
}
sc.close();
// System.out.println(m);
}
if(nand2 || nor2 || xor2 || dff){
Scanner sc = new Scanner(line);
//G8 = NAND(G1, G3) 1 4
sc.findInLine("\\s*G(\\d+)\\s*=\\s*\\w+\\(\\s*G(\\d+)\\s*,\\s*G(\\d+)\\)\\s*(\\d+)\\s*(\\d+)");
MatchResult result = sc.match();
output_sig = new Integer(result.group(1));
input_sig1 = new Integer(result.group(2));
input_sig2 = new Integer(result.group(3));
row = new Integer(result.group(4));
column = new Integer(result.group(5));
array2coord(n, row, column);
array[x+1][y].addWest(output_sig);
array[x-1][y].addEast(input_sig1);
array[x-1][y].addEast(input_sig2);
if(m.containsKey(output_sig)){
m.get(output_sig).add(array[x+1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x+1][y]);
m.put(output_sig, nodes);
}
if(m.containsKey(input_sig1)){
m.get(input_sig1).add(array[x-1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x-1][y]);
m.put(input_sig1, nodes);
}
if(m.containsKey(input_sig2)){
m.get(input_sig2).add(array[x-1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x-1][y]);
m.put(input_sig2, nodes);
}
sc.close();
// System.out.println(m);
}
if(nand3 || nor3 || xor3){
Scanner sc = new Scanner(line);
//G28 = NAND3(G21, G22, G23) 3 2
sc.findInLine("\\s*G(\\d+)\\s*=\\s*\\w+\\(\\s*G(\\d+)\\s*,\\s*G(\\d+)\\s*,\\s*G(\\d+)\\s*\\)\\s*(\\d+)\\s*(\\d+)");
MatchResult result = sc.match();
output_sig = new Integer(result.group(1));
input_sig1 = new Integer(result.group(2));
input_sig2 = new Integer(result.group(3));
input_sig3 = new Integer(result.group(4));
row = new Integer(result.group(5));
column = new Integer(result.group(6));
array2coord(n, row, column);
array[x+1][y].addWest(output_sig);
array[x-1][y].addEast(input_sig1);
array[x-1][y].addEast(input_sig2);
array[x-1][y].addEast(input_sig3);
if(m.containsKey(output_sig)){
m.get(output_sig).add(array[x+1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x+1][y]);
m.put(output_sig, nodes);
}
if(m.containsKey(input_sig1)){
m.get(input_sig1).add(array[x-1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x-1][y]);
m.put(input_sig1, nodes);
}
if(m.containsKey(input_sig2)){
m.get(input_sig2).add(array[x-1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x-1][y]);
m.put(input_sig2, nodes);
}
if(m.containsKey(input_sig3)){
m.get(input_sig3).add(array[x-1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x-1][y]);
m.put(input_sig3, nodes);
}
sc.close();
}
if(nand4 || nor4 || xor4){
Scanner sc = new Scanner(line);
//G33 = NAND4(G6, G29, G28, G27) 3 3
sc.findInLine("\\s*G(\\d+)\\s*=\\s*\\w+\\(\\s*G(\\d+)\\s*,\\s*G(\\d+)\\s*,\\s*G(\\d+)\\s*,\\s*G(\\d+)\\s*\\)\\s*(\\d+)\\s*(\\d+)");
MatchResult result = sc.match();
output_sig = new Integer(result.group(1));
input_sig1 = new Integer(result.group(2));
input_sig2 = new Integer(result.group(3));
input_sig3 = new Integer(result.group(4));
input_sig4 = new Integer(result.group(5));
row = new Integer(result.group(6));
column = new Integer(result.group(7));
array2coord(n, row, column);
array[x+1][y].addWest(output_sig);
array[x-1][y].addEast(input_sig1);
array[x-1][y].addEast(input_sig2);
array[x-1][y].addEast(input_sig3);
array[x-1][y].addEast(input_sig4);
if(m.containsKey(output_sig)){
m.get(output_sig).add(array[x+1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x+1][y]);
m.put(output_sig, nodes);
}
if(m.containsKey(input_sig1)){
m.get(input_sig1).add(array[x-1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x-1][y]);
m.put(input_sig1, nodes);
}
if(m.containsKey(input_sig2)){
m.get(input_sig2).add(array[x-1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x-1][y]);
m.put(input_sig2, nodes);
}
if(m.containsKey(input_sig3)){
m.get(input_sig3).add(array[x-1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x-1][y]);
m.put(input_sig3, nodes);
}
if(m.containsKey(input_sig4)){
m.get(input_sig4).add(array[x-1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x-1][y]);
m.put(input_sig4, nodes);
}
sc.close();
}
if(not){
Scanner sc = new Scanner(line);
//G2 = NOT(G1) 1 2
sc.findInLine("\\s*G(\\d+)\\s*=\\s*\\w+\\(\\s*G(\\d+)\\s*\\)\\s*(\\d+)\\s*(\\d+)");
MatchResult result = sc.match();
output_sig = new Integer(result.group(1));
input_sig1 = new Integer(result.group(2));
row = new Integer(result.group(3));
column = new Integer(result.group(4));
array2coord(n, row, column);
array[x+1][y].addWest(output_sig);
array[x-1][y].addEast(input_sig1);
if(m.containsKey(output_sig)){
m.get(output_sig).add(array[x+1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x+1][y]);
m.put(output_sig, nodes);
}
if(m.containsKey(input_sig1)){
m.get(input_sig1).add(array[x-1][y]);
}
else{
HashSet<switchBox> nodes = new HashSet<switchBox>();
nodes.add(array[x-1][y]);
m.put(input_sig1, nodes);
}
sc.close();
}
}
}
finally{
if(inputStream != null){
inputStream.close();
}
if(outputStream != null){
outputStream.close();
}
}
return m;
}
}
| zzspring2010ee680 | Netlist.java | Java | gpl3 | 17,764 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.usc.ee.java;
/**
*
* @author zhouzhao
*/
public class wire {
private int id;
private int x;
private int y;
private int capacity;
public wire(int id, int x, int y){
this.id = id;
this.x = x;
this.y = y;
this.capacity = 0;
}
public int getid(){
return this.id;
}
public int getx(){
return this.x;
}
public int gety(){
return this.y;
}
public int getCapacity(){
return this.capacity;
}
public void setCapacity(int capacity){
this.capacity = capacity;
}
@Override
public String toString(){
return "Wire"+id+"("+x+","+y+")";
}
}
| zzspring2010ee680 | wire.java | Java | gpl3 | 808 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.usc.ee.java;
import java.io.IOException;
/**
*
* @author zhouzhao
*/
public class fpgaRouter {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
graphTest fpga = new graphTest();
fpga.globalRoute();
}
}
| zzspring2010ee680 | fpgaRouter.java | Java | gpl3 | 463 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.usc.ee.java;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.graph.UndirectedGraph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import edu.uci.ics.jung.visualization.BasicVisualizationServer;
import edu.uci.ics.jung.visualization.renderers.Renderer.VertexLabel.Position;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Paint;
import java.awt.Stroke;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import javax.swing.JFrame;
import org.apache.commons.collections15.Transformer;
/**
*
* @author zhouzhao
* @version 1.0
*/
public class switchboxRouter {
private Integer R; //R = row
private Integer C; //C = column
private Integer Template;
private Integer Xg;
private Integer Yg;
private UndirectedGraph<via, wire> box;
private via[][] v;
private wire[][] w;
private Integer[] north;
private Integer[] south;
private Integer[] east;
private Integer[] west;
private Map<Integer, Set<via>> netlist;
private List<via> vpath;
private List<wire> epath;
private Map<Integer, List<via>> vroute;
private Map<Integer, List<wire>> eroute;
private double temperature = 10;
public switchboxRouter(Integer row, Integer col, Integer template, Integer x, Integer y,
Integer north[], Integer south[], Integer east[], Integer west[]){
this.R = row;
this.C = col;
this.v = new via[C][R];
this.w = new wire[C*2-1][R*2-1];
this.Template = template;
this.Xg = x;
this.Yg = y;
this.north = north;
this.south = south;
this.east = east;
this.west = west;
this.netlist = new HashMap<Integer, Set<via>>();
this.vroute = new HashMap<Integer, List<via>>();
this.eroute = new HashMap<Integer, List<wire>>();
}
public Integer getRow(){
return this.R;
}
public Integer getCol(){
return this.C;
}
public UndirectedGraph<via, wire> getBox(){
return this.box;
}
public Map<Integer, Set<via>> getNetlist(){
return this.netlist;
}
public via getVia(int x, int y){
return this.v[x][y];
}
public wire getWire(int x, int y){
return this.w[x][y];
}
public void graphConstruct()
{
box = new UndirectedSparseGraph<via, wire>();
for(int i=0; i<R; i++){
for(int j=0; j<C; j++){
v[j][i] = new via(C*i+j, j, i);
}
}
for(int i=0; i<R*2-1; i=i+2){
for(int j=1; j<C*2-1; j=j+2){
w[j][i] = new wire((C*2-1)*i+j, j, i);
box.addEdge(w[j][i], v[(j-1)/2][i/2], v[(j+1)/2][i/2]);
}
}
for(int j=0; j<C*2-1; j=j+2){
for(int i=1; i<R*2-1; i=i+2){
w[j][i] = new wire((C*2-1)*i+j, j, i);
// System.out.println("j="+j+" i="+i);
box.addEdge(w[j][i], v[j/2][(i-1)/2], v[j/2][(i+1)/2]);
}
}
}
public void northSearch(Integer net){
Set<via> vset;
Set<Integer> signal;
for(int j=0; j<C; j++){
if(net==north[j]){
signal=netlist.keySet();
if(signal.contains(net)){
netlist.get(net).add(v[j][0]);
}else{
vset = new HashSet<via>();
vset.add(v[j][0]);
netlist.put(net, vset);
}
}
}
}
public void southSearch(Integer net){
Set<via> vset;
Set<Integer> signal;
for(int j=0; j<C; j++){
if(net==south[j]){
signal = netlist.keySet();
if(signal.contains(net)){
netlist.get(net).add(v[j][R-1]);
}else{
vset = new HashSet<via>();
vset.add(v[j][R-1]);
netlist.put(net, vset);
}
}
}
}
public void eastSearch(Integer net){
Set<via> vset;
Set<Integer> signal;
for(int j=0; j<R; j++){
if(net==east[j]){
signal = netlist.keySet();
if(signal.contains(net)){
netlist.get(net).add(v[C-1][j]);
}else{
vset = new HashSet<via>();
vset.add(v[C-1][j]);
netlist.put(net, vset);
}
}
}
}
public void westSearch(Integer net){
Set<via> vset;
Set<Integer> signal;
for(int j=0; j<R; j++){
if(net==west[j]){
signal = netlist.keySet();
if(signal.contains(net)){
netlist.get(net).add(v[0][j]);
}else{
vset = new HashSet<via>();
vset.add(v[0][j]);
netlist.put(net, vset);
}
}
}
}
public void netlistConstruct(){
for(int j=0; j<C; j++){
if(north[j]!=0){
northSearch(north[j]);
southSearch(north[j]);
eastSearch(north[j]);
westSearch(north[j]);
}
if(south[j]!=0){
northSearch(south[j]);
southSearch(south[j]);
eastSearch(south[j]);
westSearch(south[j]);
}
}
for(int i=0; i<R; i++){
if(east[i]!=0){
northSearch(east[i]);
southSearch(east[i]);
eastSearch(east[i]);
westSearch(east[i]);
}
if(west[i]!=0){
northSearch(west[i]);
southSearch(west[i]);
eastSearch(west[i]);
westSearch(west[i]);
}
}
System.out.println(netlist);
}
public void congest(Set<via> vset)
{
int xmin, xmax, ymin, ymax;
int weight;
via[] a = vset.toArray(new via[0]);
xmin = a[0].getx();
xmax = xmin;
ymin = a[0].gety();
ymax = ymin;
for(int i=1; i<a.length; i++){
xmin = a[i].getx()<xmin? a[i].getx():xmin;
xmax = a[i].getx()>xmax? a[i].getx():xmax;
ymin = a[i].gety()<ymin? a[i].gety():ymin;
ymax = a[i].gety()>ymax? a[i].gety():ymax;
}
// System.out.println("xmin:"+xmin+" xmax:"+xmax+" ymin:"+ymin+" ymax:"+ymax);
for(int row = ymin; row <= ymax; row++){
for(int column = xmin; column <= xmax; column++)
{
weight = v[column][row].getWeight();
v[column][row].setWeight(++weight);
// v[column][row].setColor(myColor.YELLOW);
}
}
}
public void congestRoute(){
Set<Integer> signal = vroute.keySet();
for(Integer i: signal){
rightAngle(i, 1);
for(via j: vroute.get(i)){
j.setWeight(j.getWeight()+1);
}
}
}
public void ripup(Integer net){
System.out.println("The signal "+net+" is ripup");
if(vroute.containsKey(net)){
rightAngle(net, -1);
for(via j: vroute.get(net)){
j.setWeight(j.getWeight()-1);
}
}else{
System.out.println("The signal "+net+" is not routed in vroute");
}
if(eroute.containsKey(net)){
for(wire k: eroute.get(net)){
k.setCapacity(k.getCapacity()-1);
}
}else{
System.out.println("The signal "+net+" is not routed in eroute");
}
}
/**
*
* @param parent
* @return
*/
public Map<via, Set<via>> findChildren(via parent){
Set<via> children = new HashSet<via>();
Map<via, Set<via>> group = new HashMap<via, Set<via>>();
int x = parent.getx();
int y = parent.gety();
if(y==0){
if(x==0){
children.add(v[x+1][y]);
children.add(v[x][y+1]);
}else{
if(x==C-1){
children.add(v[x-1][y]);
children.add(v[x][y+1]);
}else{
children.add(v[x-1][y]);
children.add(v[x+1][y]);
children.add(v[x][y+1]);
}
}
}else{
if(y==R-1){
if(x==0){
children.add(v[x+1][y]);
children.add(v[x][y-1]);
}else{
if(x==C-1){
children.add(v[x-1][y]);
children.add(v[x][y-1]);
}else{
children.add(v[x-1][y]);
children.add(v[x+1][y]);
children.add(v[x][y-1]);
}
}
}else{
if(x==0){
children.add(v[x][y-1]);
children.add(v[x][y+1]);
children.add(v[x+1][y]);
}else{
if(x==C-1){
children.add(v[x][y-1]);
children.add(v[x][y+1]);
children.add(v[x-1][y]);
}else{
children.add(v[x-1][y]);
children.add(v[x+1][y]);
children.add(v[x][y-1]);
children.add(v[x][y+1]);
}
}
}
}
group.put(parent, children);
return group;
}
public Map<via, Set<via>> direction1(via parent, via child){
//filter some elements from set
Map<via, Set<via>> grandchild = new HashMap<via, Set<via>>();
Map<via, Set<via>> grand = new HashMap<via, Set<via>>();
grandchild = findChildren(child);
grand = findChildren(child);
Set<via> key = grandchild.keySet();
for(via i: key){
if(!grand.get(i).remove(parent)){
System.out.println("invalid parent or child");
}
for(via j: grandchild.get(i)){
if(j.getUpdate()){
grand.get(i).remove(j);
}
}
}
return grand;
}
public Map<via, Set<via>> direction2(via parent, via child){
//filter some elements from set
Map<via, Set<via>> grandchild = new HashMap<via, Set<via>>();
Map<via, Set<via>> grand = new HashMap<via, Set<via>>();
grandchild = findChildren(child);
grand = findChildren(child);
Set<via> key = grandchild.keySet();
for(via i: key){
if(!grand.get(i).remove(parent)){
System.out.println("invalid parent or child");
}
}
return grand;
}
public void waveCompute(via source, via target)
{
Map<via, Set<via>> group = new HashMap<via, Set<via>>();
Queue<List<via>> q = new LinkedList<List<via>>();
source.setWeightWave(source.getWeight());
group = findChildren(source);
Set<via> key = group.keySet();
weightCompute(group);
for(via i: key){
for(via j: group.get(i)){
List<via> pair = new ArrayList<via>();
pair.add(0, i);
pair.add(1, j);
q.add(pair);
}
}
while(!q.isEmpty()){
List<via> head = q.remove();
via key1 = head.get(0);
via value1 = head.get(1);
if(key1.equals(target)){
q.clear();
}else{
group = direction1(key1, value1);
Set<via> key2 = group.keySet();
for(via i: key2){
for(via j: group.get(i)){
List<via> pair = new ArrayList<via>();
pair.add(0, i);
pair.add(1, j);
q.add(pair);
}
}
group = direction2(key1, value1);
weightCompute(group);
}
}
}
public void weightCompute(Map<via, Set<via>> group){
Set<via> key = group.keySet();
for(via i: key){
for(via j: group.get(i)){
if(!j.getUpdate()){
j.setWeightWave(i.getWeightWave()+j.getWeight()+1);
j.setUpdate(true);
}else{
if(i.getWeightWave()+j.getWeight()+1<j.getWeightWave()){
j.setWeightWave(i.getWeightWave()+j.getWeight()+1);
}
}
// System.out.println(i+" ("+i.getWeight()+","+i.getWeightWave()+") "+j+" ("+j.getWeight()+","+j.getWeightWave()+")");
}
}
}
public void backTrack(via source, via target){
vpath = new ArrayList<via>();
epath = new ArrayList<wire>();
target.setColor(myColor.RED);
via m = recursive(source, target);
m.setColor(myColor.RED);
// System.out.println("the final node is "+m);
vpath.add(m);
vpath.add(target);
epath.add(getWire(m.getx()+target.getx(), m.gety()+target.gety()));
// System.out.println(vpath);
// System.out.println(epath);
}
public via recursive(via source, via target){
Map<via, Set<via>> group = new HashMap<via, Set<via>>();
group = findChildren(target);
via m = minCompute(group);
// System.out.println("Source="+source+" Target="+target);
if(!m.equals(source)){
via r = recursive(source, m);
vpath.add(r);
r.setColor(myColor.RED);
int x = m.getx()+r.getx();
int y = m.gety()+r.gety();
epath.add(getWire(x, y));
return m;
}
return m;
}
public via minCompute(Map<via, Set<via>> group){
Set<via> key = group.keySet();
via [] a;
via min = new via();
for(via i: key){
Set<via> value = group.get(i);
a = value.toArray(new via[0]);
min = a[0];
for(via j: value){
min = j.getWeightWave()<min.getWeightWave()? j:min;
}
//System.out.println("the min vertex around "+i+" is "+min);
}
return min;
}
public void updateWire(List<wire> path){
for(int i=0; i<path.size(); i++){
wire t = path.get(i);
t.setCapacity(t.getCapacity()+1);
}
}
public void updateVia(List<via> path){
for(int i=0; i<path.size(); i++){
via t = path.get(i);
t.setWeight(t.getWeight()+1);
}
}
public void waveClear(){
for(int row = 0; row < R; row++){
for(int column = 0; column < C; column++)
{
v[column][row].setWeightWave(0);
v[column][row].setUpdate(false);
}
}
}
public void weightClear(){
for(int row = 0; row < R; row++){
for(int column = 0; column < C; column++)
{
v[column][row].setWeight(0);
}
}
}
public void route(Integer net){
via[] path;
Map<Integer, List<via>> vcomp = new HashMap<Integer, List<via>>();
Map<Integer, List<wire>> ecomp = new HashMap<Integer, List<wire>>();
Set<Integer> length;
Integer[] len;
boolean swap = false;
Integer temp;
List<via> vbuffer;
List<wire> ebuffer;
System.out.println("The signal "+net+" is routed initially");
if(netlist.containsKey(net)){
Set<via> value = netlist.get(net);
if(value.size()==2){
path = value.toArray(new via[0]);
waveCompute(path[0], path[1]);
backTrack(path[0], path[1]);
vroute.put(net, vpath);
eroute.put(net, epath);
updateWire(epath);
waveClear();
}else{
//multi-node route based on MST without Steiner points
if(value.size()==3){
path = value.toArray(new via[0]);
waveCompute(path[0], path[1]);
backTrack(path[0], path[1]);
vcomp.put(1, vpath);
ecomp.put(1, epath);
waveClear();
waveCompute(path[0], path[2]);
backTrack(path[0], path[2]);
vcomp.put(2, vpath);
ecomp.put(2, epath);
waveClear();
waveCompute(path[1], path[2]);
backTrack(path[1], path[2]);
vcomp.put(3, vpath);
ecomp.put(3, epath);
waveClear();
length = vcomp.keySet();
len = length.toArray(new Integer[0]);
while(!swap){
swap = true;
for(int i=0; i<len.length-2; i++){
if(vcomp.get(len[i]).size() > vcomp.get(len[i+1]).size()){
temp = len[i];
len[i] = len[i+1];
len[i+1] = temp;
swap = false;
}
}
}
vbuffer = new ArrayList<via>();
vbuffer.addAll(vcomp.get(len[0]));
vbuffer.addAll(vcomp.get(len[1]));
vroute.put(net, vbuffer);
System.out.println(vbuffer);
ebuffer = new ArrayList<wire>();
ebuffer.addAll(ecomp.get(len[0]));
ebuffer.addAll(ecomp.get(len[1]));
eroute.put(net, ebuffer);
updateWire(ebuffer);
}
}
}else{
System.out.println("The signal "+net+" is not routable");
}
}
public void initialRoute(){
Set<Integer> keyset = getNetlist().keySet();
for(Integer i: keyset){
Set<via> value = getNetlist().get(i);
congest(value);
}
for(Integer j: keyset){
route(j);
}
System.out.println(vroute);
System.out.println(eroute);
}
public void reRoute(Integer net){
via[] path;
Map<Integer, List<via>> vcomp = new HashMap<Integer, List<via>>();
Map<Integer, List<wire>> ecomp = new HashMap<Integer, List<wire>>();
Set<Integer> length;
Integer[] len;
boolean swap = false;
Integer temp;
List<via> vbuffer = new ArrayList<via>();
List<wire> ebuffer = new ArrayList<wire>();
System.out.println("The signal "+net+" is re-routed");
if(netlist.containsKey(net)){
Set<via> value = netlist.get(net);
if(value.size()==2){
path = value.toArray(new via[0]);
waveCompute(path[0], path[1]);
backTrack(path[0], path[1]);
vroute.put(net, vpath);
eroute.put(net, epath);
updateVia(vpath);
updateWire(epath);
waveClear();
}else{
//multi-point route
if(value.size()==3){
path = value.toArray(new via[0]);
waveCompute(path[0], path[1]);
backTrack(path[0], path[1]);
vcomp.put(1, vpath);
ecomp.put(1, epath);
waveClear();
waveCompute(path[0], path[2]);
backTrack(path[0], path[2]);
vcomp.put(2, vpath);
ecomp.put(2, epath);
waveClear();
waveCompute(path[1], path[2]);
backTrack(path[1], path[2]);
vcomp.put(3, vpath);
ecomp.put(3, epath);
waveClear();
length = vcomp.keySet();
len = length.toArray(new Integer[0]);
while(!swap){
swap = true;
for(int i=0; i<len.length-2; i++){
if(vcomp.get(len[i]).size() > vcomp.get(len[i+1]).size()){
temp = len[i];
len[i] = len[i+1];
len[i+1] = temp;
swap = false;
}
}
}
vbuffer.addAll(vcomp.get(len[0]));
vbuffer.addAll(vcomp.get(len[1]));
vroute.put(net, vbuffer);
updateVia(vbuffer);
System.out.println(vbuffer);
ebuffer.addAll(ecomp.get(len[0]));
ebuffer.addAll(ecomp.get(len[1]));
eroute.put(net, ebuffer);
updateWire(ebuffer);
}
}
}else{
System.out.println("The signal "+net+" is not routable");
}
System.out.println(vroute);
// System.out.println(eroute);
}
public void viaCompare(via vpn, via vc){
switch (vpn.getx()-vc.getx()){
case -1: vc.setWest(1); break;
case 0: break;
case 1: vc.setEast(1); break;
default: System.out.println("invalid x"); break;
}
switch (vpn.gety()-vc.gety()){
case -1: vc.setNorth(1); break;
case 0: break;
case 1: vc.setSouth(1); break;
default: System.out.println("invalid y"); break;
}
if((vc.getNorth()==1 && vc.getEast()==1) ||
(vc.getNorth()==1 && vc.getWest()==1) ||
(vc.getSouth()==1 && vc.getEast()==1) ||
(vc.getSouth()==1 && vc.getWest()==1)){
// vc.setCenter(vc.getCenter()+1);
}
}
public void viaSide(via vh){
int x = vh.getx();
int y = vh.gety();
if(y==0){
vh.setNorth(1);
}
if(y==R-1){
vh.setSouth(1);
}
if(x==0){
vh.setWest(1);
}
if(x==C-1){
vh.setEast(1);
}
}
public void viaConfigure(){
Set<Integer> signal = vroute.keySet();
int k;
for(Integer i: signal){
via[] temp = vroute.get(i).toArray(new via[0]);
k = temp.length;
viaCompare(temp[1], temp[0]);
viaSide(temp[0]);
for(int j=1; j<k-1; j++){
viaCompare(temp[j-1], temp[j]);
viaCompare(temp[j+1], temp[j]);
}
viaCompare(temp[k-2], temp[k-1]);
viaSide(temp[k-1]);
}
}
public void rightAngle(Integer net, Integer delta){
Set<Integer> signal = vroute.keySet();
int len;
if(signal.contains(net)){
via[] temp = vroute.get(net).toArray(new via[0]);
len = temp.length;
for(int j=1; j<len-1; j++){
if(temp[j].getx()==temp[j-1].getx() && temp[j].getx()==temp[j+1].getx()){
}else{
if(temp[j].gety()==temp[j-1].gety() && temp[j].gety()==temp[j+1].gety()){
}else{
temp[j].setCenter(temp[j].getCenter()+delta);
}
}
}
}else{
System.out.println("signal"+net+"can not be processed in right angle");
}
}
public int congestCount(){
int count = 0;
for(int i=0; i<2*R-1; i=i+2){
for(int j=1; j<2*C-1; j=j+2){
if(w[j][i].getCapacity()>1){
count++;
}
}
}
for(int j=0; j<2*C-1; j=j+2){
for(int i=1; i<2*R-1; i=i+2){
if(w[j][i].getCapacity()>1){
count++;
}
}
}
return count;
}
/**
* wireCount method will compute the total wire length of routed nets in unit 1
* @return
*/
public int wireCount(){
int count = 0;
return count;
}
/*
* viaCount will compute the total number of used vias in routing
*/
public int viaFaultCount(){
int count = 0;
for(int i=0; i<R; i++){
for(int j=0; j<C; j++){
if(v[j][i].getCenter()>1){
count++;
}
}
}
return count;
}
public boolean anneal(int d){
if (temperature < 1.0E-4) {
if (d > 0)
return true;
else
return false;
}
if (Math.random() < Math.exp(d / temperature))
return true;
else
return false;
}
/*
* method for simulated annealing
*/
public boolean sa(){
int cycle = 1;
int step = 1;
int sameCount = 0;
int acceptCount = 0;
int rejectCount = 0;
boolean flag; // indicate the routing success or fail
Map<Integer, List<via>> vroute_copy = new HashMap<Integer, List<via>>();
Map<Integer, List<wire>> eroute_copy = new HashMap<Integer, List<wire>>();
Set<Integer> keyset = vroute.keySet();
Integer[] key = keyset.toArray(new Integer[0]);
int len = key.length;
vroute_copy.putAll(vroute);
eroute_copy.putAll(eroute);
int present_congest = congestCount() + viaFaultCount();
int minimum_congest = present_congest;
while (sameCount < 20) {
// update the screen
for (int i = 0; i < len*len; i++){
int signal = (int)Math.floor((double)len * Math.random());
ripup(key[signal]);
reRoute(key[signal]);
rightAngle(key[signal], 1);
int temp1 = congestCount();
int temp2 = viaFaultCount();
System.out.println("The number of congested wires = "+temp1);
System.out.println("The number of faulted vias = "+temp2);
int delta = present_congest - temp1 - temp2;
if (anneal(delta)){
acceptCount++;
vroute_copy.putAll(vroute);
eroute_copy.putAll(eroute);
present_congest = temp1 + temp2;
}else{
rejectCount++;
vroute.putAll(vroute_copy);
eroute.putAll(eroute_copy);
}
step++;
}
// See if this improved anything
int final_congest = present_congest;
if (final_congest < minimum_congest){
minimum_congest = final_congest;
sameCount=0;
}else{
sameCount++;
temperature = 0.9 * temperature;
cycle++;
}
// System.out.println("sameCount="+sameCount+" cycle="+cycle);
}
// the process of simulated annealing is complete
if(congestCount() + viaFaultCount() == 0){
System.out.println("Solution found after " + cycle + " cycles.");
System.out.println("step= "+step+" accept= "+acceptCount+" reject= "+rejectCount);
System.out.println("\n\nThe final routing is:");
System.out.println(vroute);
return true;
}else{
System.out.println("Solution can not be found");
return false;
}
}
public void fileOutput(){
String[][] buffer = new String[R][C];
for(int i=0; i<R; i++){
for(int j=0; j<C; j++){
buffer[i][j] = v[j][i].getNorth()+""+v[j][i].getEast()+""+v[j][i].getWest()+""
+v[j][i].getSouth()+""+v[j][i].getCenter();
}
}
try{
BufferedWriter out = new BufferedWriter(new FileWriter("output.txt", true));
out.write("\nTemplate"+Template+"("+Xg+","+Yg+")=[\n");
for(int i=0; i<R; i++){
for(int j=0; j<C; j++){
out.write(buffer[i][j]+" ");
}
out.write("\n");
}
out.write("]");
out.close();
}catch (IOException e){
}
}
//detail router main method
public void detailRoute() throws IOException{
// TODO code application logic here
graphConstruct();
netlistConstruct();
initialRoute();
weightClear();
congestRoute();
if(sa()){
viaConfigure();
fileOutput();
}else{
System.out.println("Redo global routing");
}
//-----------------------following code is for visualization------------
Layout<via, wire> layout = new XYLayoutBox(getBox());
layout.setSize(new Dimension(C*100, R*100));
BasicVisualizationServer<via, wire> vs = new BasicVisualizationServer
<via, wire>(layout);
vs.setPreferredSize(new Dimension(C*100+50, R*100+50));
Transformer<via, Paint> vertex2paint = new Transformer<via, Paint>() {
public Paint transform(via i) {
switch(i.getColor())
{
case RED: return Color.RED;
case GREEN: return Color.GREEN;
case BLUE: return Color.BLUE;
case YELLOW: return Color.YELLOW;
default: return Color.BLACK;
}
}
};
float dash[] = {10.0f};
final Stroke edgeStroke =
new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10.0f, dash, 0.0f);
Transformer<wire, Stroke> edge2stroke = new Transformer<wire, Stroke>() {
public Stroke transform(wire i) {
return edgeStroke;
}
};
Transformer<via, String> vertex2string = new Transformer<via, String>() {
public String transform(via i) {
return "N"+i.getNorth()+"E"+i.getEast()+"W"+i.getWest()+"S"+i.getSouth()+"C"+i.getCenter();
// return i.getid()+"("+i.getx()+","+i.gety()+")";
// return i.getWeight()+","+i.getWeightWave();
}
};
Transformer<wire, String> edge2string = new Transformer<wire, String>() {
public String transform(wire i) {
// return i.getid()+"("+i.getx()+","+i.gety()+")";
// return "";
return i.getCapacity()+"";
}
};
vs.getRenderContext().setVertexFillPaintTransformer(vertex2paint);
vs.getRenderContext().setVertexLabelTransformer(vertex2string);
vs.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);
vs.getRenderContext().setEdgeLabelTransformer(edge2string);
JFrame frame = new JFrame("FPGA Detail Model at x="+Xg+" y="+Yg);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vs);
frame.pack();
frame.setVisible(true);
}
}
| zzspring2010ee680 | switchboxRouter.java | Java | gpl3 | 32,161 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.usc.ee.java;
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA compiler for EE680 USC
*
FPGA compiler 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.
FPGA compiler 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* The code in class of Netlist is used for importing netlist from txt file.
* The code uses regular expression to import netlist, which simplifies the format
* of each statement. Although there are some blanks between signal name and pin
* number, code can also read in the netlist. The output of this importing process
* is a map data structure, which has key and value pair. Each key is a signal
* name with corresponding set of switchboxes stored in value.
*
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.regex.MatchResult;
/**
*
* @author zhouzhao
* @version 1.0
*/
public class Config{
private Integer liCount;
private Integer siCount;
private Integer li_clb_num_p1;
private Integer li_io_pin_num;
private Integer li_t1_track_num;
private Integer li_t2_track_num;
private Integer li_t3_track_num;
private Integer li_t4_track_num;
public Config(){
}
public Integer getLi(){
return this.liCount;
}
public Integer getSi(){
return this.siCount;
}
public Integer getCLB(){
return this.li_clb_num_p1;
}
public Integer getIO(){
return this.li_io_pin_num;
}
public Integer getT1(){
return this.li_t1_track_num;
}
public Integer getT2(){
return this.li_t2_track_num;
}
public Integer getT3(){
return this.li_t3_track_num;
}
public Integer getT4(){
return this.li_t4_track_num;
}
public void configProcess() throws IOException{
// TODO code application logic here
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try{
inputStream = new BufferedReader(new FileReader("./FPGA_Config.txt"));
String line;
while((line = inputStream.readLine()) != null){
boolean li = line.contains("LICOUNT");
boolean si = line.contains("SICOUNT");
boolean clb = line.contains("LI_CLB_NUM_P1");
boolean io = line.contains("LI_IO_PIN_NUM");
boolean t1 = line.contains("LI_T1_TRACK_NUM");
boolean t2 = line.contains("LI_T2_TRACK_NUM");
boolean t3 = line.contains("LI_T3_TRACK_NUM");
boolean t4 = line.contains("LI_T4_TRACK_NUM");
if(li){
Scanner sc = new Scanner(line);
sc.findInLine("\\s*LICOUNT\\s*=\\s*(\\d+)\\s*\\w*");
MatchResult result = sc.match();
liCount = new Integer(result.group(1));
System.out.println("LICOUNT="+liCount);
sc.close();
}
if(si){
Scanner sc = new Scanner(line);
sc.findInLine("\\s*SICOUNT\\s*=\\s*(\\d+)\\s*\\w*");
MatchResult result = sc.match();
siCount = new Integer(result.group(1));
System.out.println("SICOUNT="+siCount);
sc.close();
}
if(clb){
Scanner sc = new Scanner(line);
sc.findInLine("\\s*LI_CLB_NUM_P1\\s*=\\s*(\\d+)\\s*\\w*");
MatchResult result = sc.match();
li_clb_num_p1 = new Integer(result.group(1));
System.out.println("LI_CLB_NUM_P1="+li_clb_num_p1);
sc.close();
}
if(io){
Scanner sc = new Scanner(line);
sc.findInLine("\\s*LI_IO_PIN_NUM\\s*=\\s*(\\d+)\\s*\\w*");
MatchResult result = sc.match();
li_io_pin_num = new Integer(result.group(1));
System.out.println("LI_IO_PIN_NUM="+li_io_pin_num);
sc.close();
}
if(t1){
Scanner sc = new Scanner(line);
sc.findInLine("\\s*LI_T1_TRACK_NUM\\s*=\\s*(\\d+)\\s*\\w*");
MatchResult result = sc.match();
li_t1_track_num = new Integer(result.group(1));
System.out.println("LI_T1_TRACK_NUM="+li_t1_track_num);
sc.close();
}
if(t2){
Scanner sc = new Scanner(line);
sc.findInLine("\\s*LI_T2_TRACK_NUM\\s*=\\s*(\\d+)\\s*\\w*");
MatchResult result = sc.match();
li_t2_track_num = new Integer(result.group(1));
System.out.println("LI_T2_TRACK_NUM="+li_t2_track_num);
sc.close();
}
if(t3){
Scanner sc = new Scanner(line);
sc.findInLine("\\s*LI_T3_TRACK_NUM\\s*=\\s*(\\d+)\\s*\\w*");
MatchResult result = sc.match();
li_t3_track_num = new Integer(result.group(1));
System.out.println("LI_T3_TRACK_NUM="+li_t3_track_num);
sc.close();
}
if(t4){
Scanner sc = new Scanner(line);
sc.findInLine("\\s*LI_T4_TRACK_NUM\\s*=\\s*(\\d+)\\s*\\w*");
MatchResult result = sc.match();
li_t4_track_num = new Integer(result.group(1));
System.out.println("LI_T4_TRACK_NUM="+li_t4_track_num);
sc.close();
}
}
}
finally{
if(inputStream != null){
inputStream.close();
}
if(outputStream != null){
outputStream.close();
}
}
}
}
| zzspring2010ee680 | Config.java | Java | gpl3 | 6,699 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA compiler for EE680 USC
*
FPGA compiler 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.
FPGA compiler 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* The code in the class of XYLayout is used for layout the via and
* wire according to their x and y coordinates in Java Swing framework.
*/
package edu.usc.ee.java;
import edu.uci.ics.jung.algorithms.layout.AbstractLayout;
import edu.uci.ics.jung.graph.Graph;
import java.awt.Dimension;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.ListIterator;
import java.util.Map;
import org.apache.commons.collections15.Factory;
import org.apache.commons.collections15.map.LazyMap;
/**
*
* @author Zhou Zhao
* @version 1.0
*/
public class XYLayoutBox extends AbstractLayout<via, wire>
{
private List<via> vertex_list;
Map<via, vertexData> vertexMap = LazyMap.decorate(
new HashMap<via, vertexData>(),
new Factory<vertexData>()
{
public vertexData create()
{
return new vertexData();
}
});
public XYLayoutBox(Graph<via, wire> g)
{
super(g);
}
public void setVertex(List<via> list)
{
this.vertex_list = list;
}
public void reset()
{
initialize();
}
public void initialize()
{
Dimension d = getSize();
if (d != null)
{
if(vertex_list == null)
{
setVertex(new ArrayList<via>(getGraph().getVertices()));
}
double height = d.getHeight();
double width = d.getWidth();
/*
int i = 0;
for(via v : vertex_list)
{
Point2D coord = transform(v);
coord.setLocation(i,i);
vertexData data = getData(v);
data.setAngle(0);
i=i+100;
}
*/
for(ListIterator<via> it = vertex_list.listIterator(); it.hasNext();)
{
via sbox = it.next();
Point2D coord = transform(sbox);
coord.setLocation(sbox.getx()*100+50, sbox.gety()*100+50);
vertexData data = getData(sbox);
data.setAngle(0);
}
}
}
protected vertexData getData(via v)
{
return vertexMap.get(v);
}
protected class vertexData
{
private double angle;
/* public vertexData()
{
}
*/
protected double getAngle()
{
return angle;
}
protected void setAngle(double angle)
{
this.angle = angle;
}
@Override
public String toString()
{
return "angle = " + angle;
}
}
} | zzspring2010ee680 | XYLayoutBox.java | Java | gpl3 | 3,549 |
/**
* Copyright 2010 Zhou Zhao
*
* This file is part of FPGA compiler for EE680 USC
*
FPGA compiler 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.
FPGA compiler 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* The class graphTest contains the main function of FPGA compiler.
* The version 1.0 is not generalized and the test case is a 3*3 CLB
* array. The coordinates of top-left and buttom-right switchboxes are
* [0,0] and [6,6], respectively. The capacity of each track is 5. The detail
* comments are above each methods. Note the FPGA compiler is using JAVA
* JUNG2 framework for visualization.
*
*/
package edu.usc.ee.java;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath;
import edu.uci.ics.jung.algorithms.shortestpath.PrimMinimumSpanningTree;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.UndirectedGraph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import edu.uci.ics.jung.visualization.BasicVisualizationServer;
import edu.uci.ics.jung.visualization.renderers.Renderer.VertexLabel.Position;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Paint;
import java.awt.Stroke;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import javax.swing.JFrame;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import org.apache.commons.collections15.Factory;
import org.apache.commons.collections15.Transformer;
/**
* @author Zhou Zhao
* @version 1.0
*/
public class graphTest {
private Integer N;
private Integer M;
private Integer K;
private Integer T1;
private Integer T2;
private Integer T3;
private Integer T4;
private Integer LI;
private Integer SI;
private UndirectedGraph<switchBox, track> fpga;
/*
* TODO generalization start here
*/
private switchBox[][] n; //swtichbox array
private track[][] l; //track array
private Map<Integer, Set<switchBox>> data;
private boolean flag; //flag to indicate global routing of one net is complete
//data structure for internal processing
private List<switchBox> vpath;
private List<track> epath;
private Map<Integer, List<switchBox>> vroute;
private Map<Integer, List<track>> eroute;
private Map<switchBox, Set<switchBox>> relation;
private double temperature = 10;
private Integer[] north;
private Integer[] south;
private Integer[] east;
private Integer[] west;
//constructor function for initialization
public graphTest() throws IOException
{
Config myConfig = new Config();
myConfig.configProcess();
this.N = (myConfig.getCLB()-1)*2+1; //N=9
this.M = 2*N-1; //M=17
this.K = myConfig.getIO();
this.T1 = myConfig.getT1();
this.T2 = myConfig.getT2();
this.T3 = myConfig.getT3();
this.T4 = myConfig.getT4();
this.LI = myConfig.getLi();
this.SI = myConfig.getSi();
this.n = new switchBox[N][N];
this.l = new track[M][M];
this.flag = false;
this.vroute = new HashMap<Integer, List<switchBox>>();
this.eroute = new HashMap<Integer, List<track>>();
this.relation = new HashMap<switchBox, Set<switchBox>>();
}
public Integer getN(){
return this.N;
}
public Integer getK(){
return this.K;
}
public switchBox getVetex(int x, int y)
{
return this.n[x][y];
}
public switchBox[][] getn()
{
return this.n;
}
public track getEdge(int x, int y)
{
return this.l[x][y];
}
public Map<Integer, Set<switchBox>> getData(){
return this.data;
}
public void setData(Map<Integer, Set<switchBox>> map){
this.data = map;
}
public List<switchBox> getvpath(){
return this.vpath;
}
public List<track> getepath(){
return this.epath;
}
public Map<Integer, List<switchBox>> getvroute(){
return this.vroute;
}
public Map<Integer, List<track>> geteroute(){
return this.eroute;
}
//constructor function to build up the test case
public void graphConstruct()
{
fpga = new UndirectedSparseGraph<switchBox, track>();
for(int row = 0; row < N; row++){
for(int column = 0; column < N; column++)
{
if (row ==0 || row == N-1)
{
if(column == 0 || column == N-1){
n[column][row] = new switchBox(row*N+column, column, row, T3, T1);
}else{
if(column%2==0){
n[column][row] = new switchBox(row*N+column, column, row, T3, T2);
}else{
n[column][row] = new switchBox(row*N+column, column, row, T3, K);
}
}
}
else
{
if(row%2==0){
if(column == 0 || column == N-1){
n[column][row] = new switchBox(row*N+column, column, row, T4, T1);
}else{
if(column%2==0){
n[column][row] = new switchBox(row*N+column, column, row, T4, T2);
}
}
}else{
if(column == 0){
n[column][row] = new switchBox(row*N+column, column, row, K+4, T1);
}else{
if(column == N-1){
n[column][row] = new switchBox(row*N+column, column, row, K+2, T1);
}else{
if(column%2==0){
n[column][row] = new switchBox(row*N+column, column, row, 6, T2);
}
}
}
}
}
}
}
for(int i=0; i<M; i=i+4){
if(i==0 || i== M-1){
for(int j=1; j<M; j=j+2){
l[j][i] = new track(i*M+j, j, i, T3);
fpga.addEdge(l[j][i], n[(j-1)/2][i/2], n[(j+1)/2][i/2]);
}
}else{
for(int j=2; j<M; j=j+4){
l[j][i] = new track(i*M+j, j, i, T4);
fpga.addEdge(l[j][i], n[j/2-1][i/2], n[j/2+1][i/2]);
}
}
}
for(int j=0; j<M; j=j+4){
if(j==0 || j==M-1){
for(int i=1; i<M; i=i+2){
l[j][i] = new track(i*M+j, j, i, T1);
fpga.addEdge(l[j][i], n[j/2][(i-1)/2], n[j/2][(i+1)/2]);
}
}else{
for(int i=1; i<M; i=i+2){
l[j][i] = new track(i*M+j, j, i, T2);
fpga.addEdge(l[j][i], n[j/2][(i-1)/2], n[j/2][(i+1)/2]);
}
}
}
}
//The Dijkstra algorithm based method for finding shortest path from source to target
public void shortestPath(switchBox nSource, switchBox nTarget)
{
Transformer<track, Integer> wtTransformer = new Transformer<track, Integer>()
{
public Integer transform(track link)
{
return (Integer)link.getWeight();
}
};
DijkstraShortestPath<switchBox, track> alg =
new DijkstraShortestPath(fpga, wtTransformer);
List<track> ls = alg.getPath(nSource, nTarget);
Number dist = alg.getDistance(nSource, nTarget);
System.out.println("The shortest path from " + nSource.toString()
+ " to " + nTarget.toString() + " is:");
System.out.println(ls.toString());
System.out.println("and the length of the path is: " + dist);
}
//Prim algorithm based method for finding minimum spanning tree for multi-node global routing
public void spanningTree()
{
Transformer<track, Double> treeTransformer = new Transformer<track, Double>()
{
public Double transform(track link)
{
Integer wei = new Integer(link.getWeight());
return new Double(wei.doubleValue());
}
};
Factory<UndirectedGraph<switchBox, track>> treeFactory =
new Factory<UndirectedGraph<switchBox, track>>() {
public UndirectedSparseGraph create()
{
return new UndirectedSparseGraph<switchBox, track>();
}
};
PrimMinimumSpanningTree<switchBox, track> alg = new PrimMinimumSpanningTree
(treeFactory, treeTransformer);
Graph<switchBox, track> prim = alg.transform(fpga);
System.out.println("The minimum spanning tree of FPGA is:");
System.out.println(prim.toString());
}
//congest estimation method between source and target switchboxes
public void congest(switchBox nSource, switchBox nTarget)
{
int xmin = nSource.getx()<=nTarget.getx()? nSource.getx():nTarget.getx();
int xmax = nSource.getx()>=nTarget.getx()? nSource.getx():nTarget.getx();
int ymin = nSource.gety()<=nTarget.gety()? nSource.gety():nTarget.gety();
int ymax = nSource.gety()>=nTarget.gety()? nSource.gety():nTarget.gety();
int weight;
for(int row = ymin; row <= ymax; row++){
for(int column = xmin; column <= xmax; column++)
{
if (row == 0 || row == N-1)
{
weight = n[column][row].getWeight();
n[column][row].setWeight(++weight);
// n[column][row].setColor(myColor.BLUE);
}
else
{
if (column%2 == 0)
{
weight = n[column][row].getWeight();
n[column][row].setWeight(++weight);
// n[column][row].setColor(myColor.BLUE);
}
}
}
}
}
//overloaded congest method which can process the set of switchboxes
public void congest(Set<switchBox> vset)
{
int xmin, xmax, ymin, ymax;
int weight;
switchBox[] a = vset.toArray(new switchBox[0]);
xmin = a[0].getx();
xmax = xmin;
ymin = a[0].gety();
ymax = ymin;
for(int i=1; i<a.length; i++){
xmin = a[i].getx()<xmin? a[i].getx():xmin;
xmax = a[i].getx()>xmax? a[i].getx():xmax;
ymin = a[i].gety()<ymin? a[i].gety():ymin;
ymax = a[i].gety()>ymax? a[i].gety():ymax;
}
// System.out.println("xmin:"+xmin+" xmax:"+xmax+" ymin:"+ymin+" ymax:"+ymax);
for(int row = ymin; row <= ymax; row++){
for(int column = xmin; column <= xmax; column++)
{
if (row == 0 || row == N-1)
{
weight = n[column][row].getWeight();
n[column][row].setWeight(++weight);
// n[column][row].setColor(myColor.BLUE);
}
else
{
if (column%2 == 0)
{
weight = n[column][row].getWeight();
n[column][row].setWeight(++weight);
// n[column][row].setColor(myColor.BLUE);
}
}
}
}
}
//give one parent switchbox, the method can find its adjacent children
public Map<switchBox, Set<switchBox>> findChildren(switchBox parent){
Set<switchBox> children = new HashSet<switchBox>();
Map<switchBox, Set<switchBox>> group = new HashMap<switchBox, Set<switchBox>>();
int x = parent.getx();
int y = parent.gety();
if(y==0){
if(x==0){
children.add(n[x+1][y]);
children.add(n[x][y+1]);
}else{
if(x==N-1){
children.add(n[x-1][y]);
children.add(n[x][y+1]);
}else{
if(x%2==0){
children.add(n[x-1][y]);
children.add(n[x+1][y]);
children.add(n[x][y+1]);
}else{
children.add(n[x-1][y]);
children.add(n[x+1][y]);
}
}
}
}else{
if(y==N-1){
if(x==0){
children.add(n[x+1][y]);
children.add(n[x][y-1]);
}else{
if(x==N-1){
children.add(n[x-1][y]);
children.add(n[x][y-1]);
}else{
if(x%2==0){
children.add(n[x-1][y]);
children.add(n[x+1][y]);
children.add(n[x][y-1]);
}else{
children.add(n[x-1][y]);
children.add(n[x+1][y]);
}
}
}
}else{
if(y%2==0){
if(x==0){
children.add(n[x][y-1]);
children.add(n[x][y+1]);
children.add(n[x+2][y]);
}else{
if(x==N-1){
children.add(n[x][y-1]);
children.add(n[x][y+1]);
children.add(n[x-2][y]);
}else{
if(x%2==0){
children.add(n[x-2][y]);
children.add(n[x+2][y]);
children.add(n[x][y-1]);
children.add(n[x][y+1]);
}else{
System.out.println("invalid x="+x+" y="+y);
}
}
}
}else{
if(x%2==0){
children.add(n[x][y-1]);
children.add(n[x][y+1]);
}else{
System.out.println("invalid x="+x+" y="+y);
}
}
}
}
group.put(parent, children);
return group;
}
//the method compute weight for each switchbox according to the equation
//Label(grid cell) = MIN(weight(parent grid cell)+weight(grid cell))
public void weightCompute(Map<switchBox, Set<switchBox>> group){
Set<switchBox> key = group.keySet();
for(switchBox i: key){
for(switchBox j: group.get(i)){
if(!j.getUpdate()){
j.setWeightWave(i.getWeightWave()+j.getWeight()+1);
j.setUpdate(true);
}else{
if(i.getWeightWave()+j.getWeight()+1<j.getWeightWave()){
j.setWeightWave(i.getWeightWave()+j.getWeight()+1);
}
}
// System.out.println(j);
}
}
}
//method to find the child switchbox with minimum weight around specified parent switchbox
public switchBox minCompute(Map<switchBox, Set<switchBox>> group){
Set<switchBox> key = group.keySet();
switchBox [] a;
switchBox min = new switchBox();
for(switchBox i: key){
Set<switchBox> value = group.get(i);
a = value.toArray(new switchBox[0]);
min = a[0];
for(switchBox j: value){
min = j.getWeightWave()<min.getWeightWave()? j:min;
}
//System.out.println("the min vertex around "+i+" is "+min);
}
return min;
}
//method to propagate the wave in Lee's algorithm without both parent and updated node
public Map<switchBox, Set<switchBox>> direction1(switchBox parent, switchBox child){
//filter some elements from set
Map<switchBox, Set<switchBox>> grandchild = new HashMap<switchBox, Set<switchBox>>();
Map<switchBox, Set<switchBox>> grand = new HashMap<switchBox, Set<switchBox>>();
grandchild = findChildren(child);
grand = findChildren(child);
Set<switchBox> key = grandchild.keySet();
for(switchBox i: key){
if(!grand.get(i).remove(parent)){
System.out.println("invalid parent or child");
}
for(switchBox j: grandchild.get(i)){
if(j.getUpdate()){
grand.get(i).remove(j);
}
}
}
return grand;
}
//another method to propagate the wave in Lee's algorithm without parent
public Map<switchBox, Set<switchBox>> direction2(switchBox parent, switchBox child){
//filter some elements from set
Map<switchBox, Set<switchBox>> grandchild = new HashMap<switchBox, Set<switchBox>>();
Map<switchBox, Set<switchBox>> grand = new HashMap<switchBox, Set<switchBox>>();
grandchild = findChildren(child);
grand = findChildren(child);
Set<switchBox> key = grandchild.keySet();
for(switchBox i: key){
if(!grand.get(i).remove(parent)){
System.out.println("invalid parent or child");
}
}
return grand;
}
//weighted Lee's algorithm to find path between source and target with breadth-first-search
public void waveCompute(switchBox source, switchBox target)
{
Map<switchBox, Set<switchBox>> group = new HashMap<switchBox, Set<switchBox>>();
Queue<List<switchBox>> q = new LinkedList<List<switchBox>>();
source.setWeightWave(source.getWeight());
group = findChildren(source);
Set<switchBox> key = group.keySet();
weightCompute(group);
for(switchBox i: key){
for(switchBox j: group.get(i)){
List<switchBox> pair = new ArrayList<switchBox>();
pair.add(0, i);
pair.add(1, j);
q.add(pair);
}
}
while(!q.isEmpty()){
List<switchBox> head = q.remove();
switchBox key1 = head.get(0);
switchBox value1 = head.get(1);
if(key1.equals(target)){
q.clear();
}else{
group = direction1(key1, value1);
Set<switchBox> key2 = group.keySet();
for(switchBox i: key2){
for(switchBox j: group.get(i)){
List<switchBox> pair = new ArrayList<switchBox>();
pair.add(0, i);
pair.add(1, j);
q.add(pair);
}
}
group = direction2(key1, value1);
weightCompute(group);
}
}
}
//backTrack method is calling recursive method "recursive" to find path with monotonically
//decreasing weight
public void backTrack(switchBox source, switchBox target){
vpath = new ArrayList<switchBox>();
epath = new ArrayList<track>();
switchBox m = recursive(source, target);
vpath.add(m);
vpath.add(target);
epath.add(getEdge(m.getx()+target.getx(), m.gety()+target.gety()));
// System.out.println(vpath);
// System.out.println(epath);
}
public switchBox recursive(switchBox source, switchBox target){
Map<switchBox, Set<switchBox>> group = new HashMap<switchBox, Set<switchBox>>();
group = findChildren(target);
switchBox m = minCompute(group);
if(!m.equals(source)){
switchBox r = recursive(source, m);
vpath.add(r);
int x = m.getx()+r.getx();
int y = m.gety()+r.gety();
epath.add(getEdge(x, y));
}
return m;
}
public void updateSwitchBox(List<switchBox> path){
for(int i=0; i<path.size(); i++){
switchBox t = path.get(i);
t.setWeight(t.getWeight()+1);
}
}
//method to estimate congestion, if track capacity is overflowed
public void updateTrack(List<track> path){
for(int i=0; i<path.size(); i++){
track t = path.get(i);
t.setCapacity(t.getCapacity()+1);
}
}
//clean up method
public void waveClear(){
for(int row = 0; row < N; row++){
for(int column = 0; column < N; column++)
{
if (row == 0 || row == N-1)
{
n[column][row].setWeightWave(0);
n[column][row].setUpdate(false);
}
else
{
if (column%2 == 0)
{
n[column][row].setWeightWave(0);
n[column][row].setUpdate(false);
}
}
}
}
}
public void weightClear(){
for(int row = 0; row < N; row++){
for(int column = 0; column < N; column++)
{
if (row == 0 || row == N-1)
{
n[column][row].setWeight(0);
}
else
{
if (column%2 == 0)
{
n[column][row].setWeight(0);
}
}
}
}
}
public void congestRoute(){
Set<Integer> signal = vroute.keySet();
for(Integer i: signal){
for(switchBox j: vroute.get(i)){
j.setWeight(j.getWeight()+1);
}
}
}
//global initial route
public void initialRoute(){
switchBox[] path;
Set<Integer> keyset = data.keySet();
Map<Integer, List<switchBox>> vcomp = new HashMap<Integer, List<switchBox>>();
Map<Integer, List<track>> ecomp = new HashMap<Integer, List<track>>();
Set<Integer> length;
Integer[] len;
boolean swap = false;
Integer temp;
List<switchBox> vbuffer;
List<track> ebuffer;
for(Integer i: keyset){
Set<switchBox> value = data.get(i);
if(value.size()==2){
// System.out.println("signal "+i+": "+value);
path = value.toArray(new switchBox[0]);
congest(path[0], path[1]);
}else{
congest(value);
}
}
for(Integer j: keyset){
Set<switchBox> value = data.get(j);
if(value.size()==2){
System.out.println("2 node signal "+j+" is routed globally");
path = value.toArray(new switchBox[0]);
waveCompute(path[0], path[1]);
backTrack(path[0], path[1]);
vroute.put(j, vpath);
eroute.put(j, epath);
waveClear();
updateTrack(epath);
}else{
//routine for multi-point global route
if(value.size()==3){
System.out.println("3 node signal "+j+" is routed globally");
path = value.toArray(new switchBox[0]);
waveCompute(path[0], path[1]);
backTrack(path[0], path[1]);
vcomp.put(1, vpath);
ecomp.put(1, epath);
waveClear();
waveCompute(path[0], path[2]);
backTrack(path[0], path[2]);
vcomp.put(2, vpath);
ecomp.put(2, epath);
waveClear();
waveCompute(path[1], path[2]);
backTrack(path[1], path[2]);
vcomp.put(3, vpath);
ecomp.put(3, epath);
waveClear();
length = vcomp.keySet();
len = length.toArray(new Integer[0]);
while(!swap){
swap = true;
for(int i=0; i<len.length-2; i++){
if(vcomp.get(len[i]).size() > vcomp.get(len[i+1]).size()){
temp = len[i];
len[i] = len[i+1];
len[i+1] = temp;
swap = false;
}
}
}
vbuffer = new ArrayList<switchBox>();
vbuffer.addAll(vcomp.get(len[0]));
for(switchBox i: vcomp.get(len[1])){
if(!vbuffer.contains(i)){
vbuffer.add(i);
}
}
vroute.put(j, vbuffer);
System.out.println(vbuffer);
ebuffer = new ArrayList<track>();
ebuffer.addAll(ecomp.get(len[0]));
for(track k: ecomp.get(len[1])){
if(!ebuffer.contains(k)){
ebuffer.add(k);
}
}
eroute.put(j, ebuffer);
updateTrack(ebuffer);
}
}
}
}
public int congestCount(){
int count = 0;
for(int i=0; i<M; i=i+4){
if(i==0 || i== M-1){
for(int j=1; j<M; j=j+2){
if(l[j][i].getCapacity()>l[j][i].getWeight()){
count++;
}
}
}else{
for(int j=2; j<M; j=j+4){
if(l[j][i].getCapacity()>l[j][i].getWeight()){
count++;
}
}
}
}
for(int j=0; j<M; j=j+4){
if(j==0 || j==M-1){
for(int i=1; i<M; i=i+2){
if(l[j][i].getCapacity()>l[j][i].getWeight()){
count++;
}
}
}else{
for(int i=1; i<M; i=i+2){
if(l[j][i].getCapacity()>l[j][i].getWeight()){
count++;
}
}
}
}
return count;
}
public void ripup(Integer net){
System.out.println("The signal "+net+" is ripup");
if(vroute.containsKey(net)){
for(switchBox j: vroute.get(net)){
j.setWeight(j.getWeight()-1);
}
}else{
System.out.println("The signal "+net+" is not routed in vroute");
}
if(eroute.containsKey(net)){
for(track k: eroute.get(net)){
k.setCapacity(k.getCapacity()-1);
}
}else{
System.out.println("The signal "+net+" is not routed in eroute");
}
}
//global re-route
public void reRoute(int r){
switchBox[] path;
Map<Integer, List<switchBox>> vcomp = new HashMap<Integer, List<switchBox>>();
Map<Integer, List<track>> ecomp = new HashMap<Integer, List<track>>();
Set<Integer> length;
Integer[] len;
boolean swap = false;
Integer temp;
List<switchBox> vbuffer = new ArrayList<switchBox>();
List<track> ebuffer = new ArrayList<track>();
if(vroute.containsKey(r)){
Set<switchBox> value = data.get(r);
if(value.size()==2){
System.out.println("2 node signal "+r+" is re-routed");
path = value.toArray(new switchBox[0]);
waveCompute(path[0], path[1]);
backTrack(path[0], path[1]);
vroute.put(r, vpath);
eroute.put(r, epath);
waveClear();
updateSwitchBox(vpath);
updateTrack(epath);
}else{
//routine for multi-point global route
if(value.size()==3){
System.out.println("3 node signal "+r+" is re-routed");
path = value.toArray(new switchBox[0]);
waveCompute(path[0], path[1]);
backTrack(path[0], path[1]);
vcomp.put(1, vpath);
ecomp.put(1, epath);
waveClear();
waveCompute(path[0], path[2]);
backTrack(path[0], path[2]);
vcomp.put(2, vpath);
ecomp.put(2, epath);
waveClear();
waveCompute(path[1], path[2]);
backTrack(path[1], path[2]);
vcomp.put(3, vpath);
ecomp.put(3, epath);
waveClear();
length = vcomp.keySet();
len = length.toArray(new Integer[0]);
while(!swap){
swap = true;
for(int i=0; i<len.length-2; i++){
if(vcomp.get(len[i]).size() > vcomp.get(len[i+1]).size()){
temp = len[i];
len[i] = len[i+1];
len[i+1] = temp;
swap = false;
}
}
}
vbuffer.addAll(vcomp.get(len[0]));
for(switchBox i: vcomp.get(len[1])){
if(!vbuffer.contains(i)){
vbuffer.add(i);
}
}
vroute.put(r, vbuffer);
updateSwitchBox(vbuffer);
System.out.println(vbuffer);
ebuffer.addAll(ecomp.get(len[0]));
for(track k: ecomp.get(len[1])){
if(!ebuffer.contains(k)){
ebuffer.add(k);
}
}
eroute.put(r, ebuffer);
updateTrack(ebuffer);
}
}
}else{
System.out.println("The signal"+r+" is not routed");
}
}
public boolean anneal(int d){
if (temperature < 1.0E-4) {
if (d > 0)
return true;
else
return false;
}
if (Math.random() < Math.exp(d / temperature))
return true;
else
return false;
}
/*
* method for simulated annealing
*/
public boolean sa()
{
int cycle = 1;
int step = 1;
int sameCount = 0;
int acceptCount = 0;
int rejectCount = 0;
Map<Integer, List<switchBox>> vroute_copy = new HashMap<Integer, List<switchBox>>();
Map<Integer, List<track>> eroute_copy = new HashMap<Integer, List<track>>();
Set<Integer> keyset = vroute.keySet();
Integer[] key = keyset.toArray(new Integer[0]);
int len = key.length;
vroute_copy.putAll(vroute);
eroute_copy.putAll(eroute);
int present_congest = congestCount();
int minimum_congest = present_congest;
while (sameCount < 10) {
// update the screen
for (int i = 0; i < len*len; i++){
int signal = (int)Math.floor((double)len * Math.random());
ripup(key[signal]);
reRoute(key[signal]);
int temp = congestCount();
System.out.println("The number of congested wires = "+temp);
int delta = present_congest - temp;
if (anneal(delta)){
acceptCount++;
vroute_copy.putAll(vroute);
eroute_copy.putAll(eroute);
present_congest = temp;
}else{
rejectCount++;
vroute.putAll(vroute_copy);
eroute.putAll(eroute_copy);
}
step++;
}
// See if this improved anything
int final_congest = present_congest;
if (final_congest < minimum_congest){
minimum_congest = final_congest;
sameCount=0;
}else{
sameCount++;
temperature = 0.9 * temperature;
cycle++;
}
System.out.println("sameCount="+sameCount+" cycle="+cycle);
}
// the process of simulated annealing is complete
if(congestCount()==0){
System.out.println("Solution found after " + cycle + " cycles.");
System.out.println("step="+step+" accept="+acceptCount+" reject="+rejectCount);
System.out.println("\nThe global final routing is");
System.out.println(vroute);
// System.out.println(eroute);
return true;
}else{
System.out.println("The netlist can not be routed");
return false;
}
}
public void switchBoxConfig(){
Set<Integer> signal = vroute.keySet();
int k;
for(Integer i: signal){
switchBox[] temp = vroute.get(i).toArray(new switchBox[0]);
k = temp.length;
switchBoxComp(i, temp[1], temp[0]);
for(int j=1; j<k-1; j++){
switchBoxComp(i, temp[j-1], temp[j]);
switchBoxComp(i, temp[j+1], temp[j]);
}
switchBoxComp(i, temp[k-2], temp[k-1]);
}
}
public void switchBoxComp(Integer net, switchBox vpn, switchBox vc){
switch (vpn.getx()-vc.getx()){
case -2: vc.addWest(net); break;
case -1: vc.addWest(net); break;
case 0: break;
case 1: vc.addEast(net); break;
case 2: vc.addEast(net); break;
default: System.out.println("invalid x along signal "+net+" at "+vc); break;
}
switch (vpn.gety()-vc.gety()){
case -1: vc.addNorth(net); break;
case 0: break;
case 1: vc.addSouth(net); break;
default: System.out.println("invalid y along signal "+net+" at "+vc); break;
}
}
public void debug(int row, int column, int row_max, int column_max) throws IOException{
List<Integer> nor = n[column][row].getNorth();
List<Integer> sou = n[column][row].getSouth();
List<Integer> eas = n[column][row].getEast();
List<Integer> wes = n[column][row].getWest();
int count = nor.size();
for(int i=0; i<column_max-count; i++){
nor.add(0);
}
count = sou.size();
for(int i=0; i<column_max-count; i++){
sou.add(0);
}
count = eas.size();
for(int j=0; j<row_max-count; j++){
eas.add(0);
}
count = wes.size();
for(int j=0; j<row_max-count; j++){
wes.add(0);
}
north = nor.toArray(new Integer[0]);
south = sou.toArray(new Integer[0]);
east = eas.toArray(new Integer[0]);
west = wes.toArray(new Integer[0]);
}
public void ouputFile(){
try{
BufferedWriter out = new BufferedWriter(new FileWriter("output.txt", true));
out.write("Setting\n{\nLiCount="+LI+"\nSiCount="+SI+"\nn="+((N-1)/2+1)+"\nk="+K);
out.write("\nT1="+T1+"\nT2="+T2+"\nT3="+T3+"\nT4="+T4+"\n}\n");
out.close();
}catch (IOException e){
}
}
//global routing main method
public void globalRoute() throws IOException{
System.out.println("FPGA config file is processed...");
System.out.println("\n\nFPGA graph model is under constructing...");
Netlist net = new Netlist((N-1)/2, K);
graphConstruct();
System.out.println("\n\nNetlist file is imported...");
setData(net.netlistProcess(getn()));
System.out.println(getData());
System.out.println("\n\nInitial routing is starting...");
initialRoute();
weightClear();
congestRoute();
System.out.println("\n\nAfter initial routing, the number of congested track = "+congestCount());
System.out.println("\n\nSimulated annealing is starting...");
if(sa()){
System.out.println("\n\nSwitchBox is under configuration...");
switchBoxConfig();
ouputFile();
for(int row = 0; row < N; row++){
for(int column = 0; column < N; column++)
{
if (row ==0 || row == N-1)
{
if(column == 0 || column == N-1){
debug(row, column, T3, T1);
switchboxRouter mb = new switchboxRouter(T3, T1, 1, column, row, north, south, east, west);
mb.detailRoute();
}else{
if(column%2==0){
debug(row, column, T3, T2);
switchboxRouter mb = new switchboxRouter(T3, T2, 2, column, row, north, south, east, west);
mb.detailRoute();
}else{
debug(row, column, T3, K);
switchboxRouter mb = new switchboxRouter(T3, K, 3, column, row, north, south, east, west);
mb.detailRoute();
}
}
}
else
{
if(row%2==0){
if(column == 0 || column == N-1){
debug(row, column, T4, T1);
switchboxRouter mb = new switchboxRouter(T4, T1, 7, column, row, north, south, east, west);
mb.detailRoute();
}else{
if(column%2==0){
debug(row, column, T4, T2);
switchboxRouter mb = new switchboxRouter(T4, T2, 8, column, row, north, south, east, west);
mb.detailRoute();
}
}
}else{
if(column == 0){
debug(row, column, K+4, T1);
switchboxRouter mb = new switchboxRouter(K+4, T1, 4, column, row, north, south, east, west);
mb.detailRoute();
}else{
if(column == N-1){
debug(row, column, K+2, T1);
switchboxRouter mb = new switchboxRouter(K+2, T1, 5, column, row, north, south, east, west);
mb.detailRoute();
}else{
if(column%2==0){
debug(row, column, 6, T2);
switchboxRouter mb = new switchboxRouter(6, T2, 6, column, row, north, south, east, west);
mb.detailRoute();
}
}
}
}
}
}
}
}
//-----------------------following code is for visualization--------------------
Layout<switchBox, track> layout = new XYLayout(fpga);
layout.setSize(new Dimension(N*100, N*100));
BasicVisualizationServer<switchBox, track> vs = new BasicVisualizationServer
<switchBox, track>(layout);
vs.setPreferredSize(new Dimension(N*100+50, N*100+50));
Transformer<switchBox, Paint> vertex2paint = new Transformer<switchBox, Paint>() {
public Paint transform(switchBox i) {
switch(i.getColor())
{
case RED: return Color.RED;
case GREEN: return Color.GREEN;
case BLUE: return Color.BLUE;
case YELLOW: return Color.YELLOW;
default: return Color.BLACK;
}
}
};
float dash[] = {10.0f};
final Stroke edgeStroke =
new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10.0f, dash, 0.0f);
Transformer<track, Stroke> edge2stroke = new Transformer<track, Stroke>() {
public Stroke transform(track i) {
return edgeStroke;
}
};
Transformer<switchBox, String> vertex2string = new Transformer<switchBox, String>() {
public String transform(switchBox i) {
// return i.getID()+"("+i.getx()+","+i.gety()+")";
// return i.getWeight()+","+i.getWeightWave();
// return "N"+i.getNorth()+"S"+i.getSouth()+"E"+i.getEast()+"W"+i.getWest();
// return "N"+i.getNorth();
return "E"+i.getEast();
}
};
Transformer<track, String> edge2string = new Transformer<track, String>() {
public String transform(track i) {
// return i.getID()+"("+i.getx()+","+i.gety()+")";
return i.getCapacity()+","+i.getWeight();
}
};
vs.getRenderContext().setVertexFillPaintTransformer(vertex2paint);
// vs.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
vs.getRenderContext().setVertexLabelTransformer(vertex2string);
vs.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);
// vs.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
vs.getRenderContext().setEdgeLabelTransformer(edge2string);
// vs.getRenderContext().setEdgeStrokeTransformer(edge2stroke);
JFrame frame = new JFrame("FPGA Global Model");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vs);
frame.pack();
frame.setVisible(true);
/*
System.out.println("The graph model of fpga: " + myGraph.fpga.toString());
myGraph.shortestPath();
myGraph.spanningTree();
*
*/
}
}
| zzspring2010ee680 | graphTest.java | Java | gpl3 | 43,167 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.usc.ee.java;
/**
*
* @author zhouzhao
*/
public class via {
private int id;
private int x;
private int y;
private myColor color;
private int center;
private int north;
private int south;
private int east;
private int west;
private int weight;
private int weightWave;
private boolean update;
public via(){
}
public via(int id, int x, int y){
this.id = id;
this.x = x;
this.y = y;
this.color = myColor.GREEN;
this.center = 0;
this.north = 0;
this.south = 0;
this.east = 0;
this.west = 0;
this.weight = 0;
this.weightWave = 0;
this.update = false;
}
public int getid(){
return this.id;
}
public int getx(){
return this.x;
}
public int gety(){
return this.y;
}
public myColor getColor(){
return this.color;
}
public void setColor(myColor color){
this.color = color;
}
public int getCenter(){
return this.center;
}
public void setCenter(int center){
this.center = center;
}
public int getNorth(){
return this.north;
}
public void setNorth(int north){
this.north = north;
}
public int getSouth(){
return this.south;
}
public void setSouth(int south){
this.south = south;
}
public int getEast(){
return this.east;
}
public void setEast(int east){
this.east = east;
}
public int getWest(){
return this.west;
}
public void setWest(int west){
this.west = west;
}
public int getWeight(){
return this.weight;
}
public void setWeight(int weight){
this.weight = weight;
}
public int getWeightWave(){
return this.weightWave;
}
public void setWeightWave(int weightWave){
this.weightWave = weightWave;
}
public boolean getUpdate(){
return this.update;
}
public void setUpdate(boolean update){
this.update = update;
}
@Override
public String toString(){
return "Via"+id+"("+x+","+y+")";
}
}
| zzspring2010ee680 | via.java | Java | gpl3 | 2,354 |
#!/usr/bin/env python
# Copyright 2013 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
import os
import sys
import shutil
PACKAGE_NAME = 'com.google.android.apps.dashclock.api'
def main():
root = sys.argv[1]
for path, _, files in os.walk(root):
for f in [f for f in files if f.endswith('.html')]:
fp = open(os.path.join(path, f), 'r')
html = fp.read()
fp.close()
toroot = '.'
if path.startswith(root):
subpath = path[len(root):]
toroot = '../' * (subpath.count('/') + 1)
html = process(toroot, html)
if f.endswith('package-summary.html'):
html = process_package_summary(toroot, html)
fp = open(os.path.join(path, f), 'w')
fp.write(html)
fp.close()
shutil.copy('index.html', root)
def process(toroot, html):
re_flags = re.I | re.M | re.S
html = re.sub(r'<HR>\s+<HR>', '', html, 0, re_flags)
html = re.sub(r'windowTitle\(\);', 'windowTitle();prettyPrint();', html, 0, re_flags)
html = re.sub(r'\s+</PRE>', '</PRE>', html, 0, re_flags)
html = re.sub(PACKAGE_NAME + '</font>', '<A HREF="package-summary.html" STYLE="border:0">' + PACKAGE_NAME + '</A></FONT>', html, 0, re_flags)
html = re.sub(r'<HEAD>', '''<HEAD>
<LINK REL="stylesheet" TYPE="text/css" HREF="http://fonts.googleapis.com/css?family=Roboto:400,700,300|Inconsolata">
<LINK REL="stylesheet" TYPE="text/css" HREF="%(root)sresources/prettify.css">
<SCRIPT SRC="%(root)sresources/prettify.js"></SCRIPT>
''' % dict(root=toroot), html, 0, re_flags)
#html = re.sub(r'<HR>\s+<HR>', '', html, re.I | re.M | re.S)
return html
def process_package_summary(toroot, html):
re_flags = re.I | re.M | re.S
html = re.sub(r'</H2>\s+.*?\n', '</H2>\n', html, 0, re_flags)
html = re.sub(r'<B>See:</B>\n<br>', '\n', html, 0, re_flags)
html = re.sub(r' ( )+[^\n]+\n', '\n', html, 0, re_flags)
html = re.sub(r'\n[^\n]+\s+description\n', '\nDescription\n', html, 0, re_flags)
return html
if __name__ == '__main__':
main()
| zywhlc-dashclock | api/javadoc-scripts/tweak_javadoc_html.py | Python | asf20 | 2,531 |
#!/bin/sh
# Copyright 2013 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
PLATFORM=android-17
OUT_PATH=../build/javadoc
cd `dirname $0`
source _locals.sh
javadoc -linkoffline http://developer.android.com/reference ${ANDROID_SDK}/docs/reference \
-sourcepath ../src/main/java:../build/source/aidl/debug \
-classpath ${ANDROID_SDK}/platforms/${PLATFORM}/android.jar:${ANDROID_SDK}/tools/support/annotations.jar \
-d ${OUT_PATH} \
-notree -nonavbar -noindex -notree -nohelp -nodeprecated \
-stylesheetfile javadoc_stylesheet.css \
-windowtitle "DashClock API" \
-doctitle "DashClock API" \
com.google.android.apps.dashclock.api
cp prettify* ${OUT_PATH}/resources/
python tweak_javadoc_html.py ${OUT_PATH}/
| zywhlc-dashclock | api/javadoc-scripts/generate_javadoc.sh | Shell | asf20 | 1,283 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Javadoc style sheet */
/* Define colors, fonts and other style attributes here to override the defaults */
/* Page background color */
body {
background-color: #fff;
color: #333;
margin: 60px 80px;
font-family: roboto;
font-size: 16px;
line-height: 140%;
}
/* Headings */
h2 {
font-size: 200%;
font-weight: 300;
}
/* Table colors */
/*.TableHeadingColor { background: #CCCCFF; color:#000000 }
.TableSubHeadingColor { background: #EEEEFF; color:#000000 }
.TableRowColor { background: #FFFFFF; color:#000000 }*/
table, td, tr, th {
border:0;
}
hr {
margin: 20px 0;
border: 1px solid #09c;
}
th {
background-color: #eee;
border-bottom: 1px solid #ccc;
}
td {
padding: 6px;
}
table {
margin-top: 20px;
}
td {
border-bottom: 1px solid #eee;
}
pre, code {
font-family: inconsolata;
font-size: 110%;
}
code {
color: #096;
}
pre.prettyprint {
background: #eee;
border: 1px solid #ccc;
border-radius: 4px;
padding: 20px 10px;
}
a, a code {
color: #09c;
text-decoration: none;
}
a {
border-bottom: 1px dotted #09c;
}
a:hover {
border-bottom: 1px solid #09c;
}
| zywhlc-dashclock | api/javadoc-scripts/javadoc_stylesheet.css | CSS | asf20 | 1,732 |
<!doctype html>
<html>
<!--
Copyright 2013 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<head>
<meta http-equiv="refresh" content="0;URL='com/google/android/apps/dashclock/api/package-summary.html'">
</head>
<body>
Redirecting you to the
<a href="com/google/android/apps/dashclock/api/package-summary.html">com.google.android.apps.dashclock.api</a>
package summary…
</body>
</html>
| zywhlc-dashclock | api/javadoc-scripts/index.html | HTML | asf20 | 927 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.api;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
/**
* A parcelable, serializable object representing data related to a {@link DashClockExtension} that
* should be shown to the user.
*
* <p>
* This class follows the <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent
* interface</a> style, using method chaining to provide for more readable code. For example, to set
* the status and visibility of this data, use {@link #status(String)} and {@link #visible(boolean)}
* methods like so:
*
* <pre class="prettyprint">
* ExtensionData data = new ExtensionData();
* data.visible(true).status("hello");
* </pre>
*
* Conversely, to get the status, use {@link #status()}. Setters and getters are thus overloads
* (or overlords?) of the same method.
*
* <h3>Required fields</h3>
*
* While no fields are required, if the data is 'visible' (i.e. {@link #visible(boolean)} has been
* called with <code>true</code>, at least the following fields should be populated:
*
* <ul>
* <li>{@link #icon(int)}</li>
* <li>{@link #status(String)}</li>
* </ul>
*
* Really awesome extensions will also set these fields:
*
* <ul>
* <li>{@link #expandedTitle(String)}</li>
* <li>{@link #expandedBody(String)}</li>
* <li>{@link #clickIntent(android.content.Intent)}</li>
* </ul>
*
* @see DashClockExtension#publishUpdate(ExtensionData)
*/
public class ExtensionData implements Parcelable {
/**
* Since there might be a case where new versions of DashClock use extensions running
* old versions of the protocol (and thus old versions of this class), we need a versioning
* system for the parcels sent between the core app and its extensions.
*/
public static final int PARCELABLE_VERSION = 2;
private static final String KEY_VISIBLE = "visible";
private static final String KEY_ICON = "icon";
private static final String KEY_ICON_URI = "icon_uri";
private static final String KEY_STATUS = "status";
private static final String KEY_EXPANDED_TITLE = "title";
private static final String KEY_EXPANDED_BODY = "body";
private static final String KEY_CLICK_INTENT = "click_intent";
private static final String KEY_CONTENT_DESCRIPTION = "content_description";
/**
* The maximum length for {@link #status(String)}. Enforced by {@link #clean()}.
*/
public static final int MAX_STATUS_LENGTH = 32;
/**
* The maximum length for {@link #expandedTitle(String)}. Enforced by {@link #clean()}.
*/
public static final int MAX_EXPANDED_TITLE_LENGTH = 100;
/**
* The maximum length for {@link #expandedBody(String)}. Enforced by {@link #clean()}.
*/
public static final int MAX_EXPANDED_BODY_LENGTH = 1000;
/**
* The maximum length for {@link #contentDescription(String)}. Enforced by {@link #clean()}.
*/
public static final int MAX_CONTENT_DESCRIPTION_LENGTH = 32 +
MAX_STATUS_LENGTH + MAX_EXPANDED_TITLE_LENGTH + MAX_EXPANDED_BODY_LENGTH;
private boolean mVisible = false;
private int mIcon = 0;
private Uri mIconUri = null;
private String mStatus = null;
private String mExpandedTitle = null;
private String mExpandedBody = null;
private Intent mClickIntent = null;
private String mContentDescription = null;
public ExtensionData() {
}
/**
* Returns whether or not the relevant extension should be visible (whether or not there is
* relevant information to show to the user about the extension). Default false.
*/
public boolean visible() {
return mVisible;
}
/**
* Sets whether or not the relevant extension should be visible (whether or not there is
* relevant information to show to the user about the extension). Default false.
*/
public ExtensionData visible(boolean visible) {
mVisible = visible;
return this;
}
/**
* Returns the ID of the drawable resource within the extension's package that represents this
* data. Default 0.
*/
public int icon() {
return mIcon;
}
/**
* Sets the ID of the drawable resource within the extension's package that represents this
* data. The icon should be entirely white, with alpha, and about 48x48 dp. It will be
* scaled down as needed. If there is no contextual icon representation of the data, simply
* use the extension or app icon. If an {@link #iconUri(Uri) iconUri} is provided, it
* will take precedence over this value. Default 0.
*
* @see #iconUri(Uri)
*/
public ExtensionData icon(int icon) {
mIcon = icon;
return this;
}
/**
* Returns the content:// URI of a bitmap representing this data. Default null.
*
* @since Protocol Version 2 (API r2.x)
*/
public Uri iconUri() {
return mIconUri;
}
/**
* Sets the content:// URI of the bitmap representing this data. This takes precedence over
* the regular {@link #icon(int) icon resource ID} if set. This resource will be loaded
* using {@link android.content.ContentResolver#openFileDescriptor(android.net.Uri, String)} and
* {@link android.graphics.BitmapFactory#decodeFileDescriptor(java.io.FileDescriptor)}. See the
* {@link #icon(int) icon} method for guidelines on the styling of this bitmap.
*
* @since Protocol Version 2 (API r2.x)
*/
public ExtensionData iconUri(Uri iconUri) {
mIconUri = iconUri;
return this;
}
/**
* Returns the short string representing this data, to be shown in DashClock's collapsed form.
* Default null.
*/
public String status() {
return mStatus;
}
/**
* Sets the short string representing this data, to be shown in DashClock's collapsed form.
* Should be no longer than a few characters. For example, if your {@link #expandedTitle()} is
* "45°, Sunny", your status could simply be "45°". Alternatively, if the status contains a
* single newline, DashClock may break it up over two lines and use a smaller font. This should
* be avoided where possible in favor of an {@link #expandedTitle(String)}. Default null.
*/
public ExtensionData status(String status) {
mStatus = status;
return this;
}
/**
* Returns the expanded title representing this data. Generally a longer form of
* {@link #status()}. Default null.
*/
public String expandedTitle() {
return mExpandedTitle;
}
/**
* Sets the expanded title representing this data. Generally a longer form of
* {@link #status()}. Can be multiple lines, although DashClock will cap the number of lines
* shown. If this is not set, DashClock will just use the {@link #status()}.
* Default null.
*/
public ExtensionData expandedTitle(String expandedTitle) {
mExpandedTitle = expandedTitle;
return this;
}
/**
* Returns the expanded body text representing this data. Default null.
*/
public String expandedBody() {
return mExpandedBody;
}
/**
* Sets the expanded body text (below the expanded title), representing this data. Can span
* multiple lines, although DashClock will cap the number of lines shown. Default null.
*/
public ExtensionData expandedBody(String expandedBody) {
mExpandedBody = expandedBody;
return this;
}
/**
* Returns the click intent to start (using
* {@link android.content.Context#startActivity(android.content.Intent)}) when the user clicks
* the status in DashClock. Default null.
*/
public Intent clickIntent() {
return mClickIntent;
}
/**
* Sets the click intent to start (using
* {@link android.content.Context#startActivity(android.content.Intent)}) when the user clicks
* the status in DashClock. The activity represented by this intent will be started in a new
* task and should be exported. Default null.
*/
public ExtensionData clickIntent(Intent clickIntent) {
mClickIntent = clickIntent;
return this;
}
/**
* Returns the content description for this data, used for accessibility purposes.
*
* @since Protocol Version 2 (API r2.x)
*/
public String contentDescription() {
return mContentDescription;
}
/**
* Sets the content description for this data. This content description will replace the
* {@link #status()}, {@link #expandedTitle()} and {@link #expandedBody()} for accessibility
* purposes.
*
* @see android.view.View#setContentDescription(CharSequence)
* @since Protocol Version 2 (API v2.x)
*/
public ExtensionData contentDescription(String contentDescription) {
mContentDescription = contentDescription;
return this;
}
/**
* Serializes the contents of this object to JSON.
*/
public JSONObject serialize() throws JSONException {
JSONObject data = new JSONObject();
data.put(KEY_VISIBLE, mVisible);
data.put(KEY_ICON, mIcon);
data.put(KEY_ICON_URI, (mIconUri == null ? null : mIconUri.toString()));
data.put(KEY_STATUS, mStatus);
data.put(KEY_EXPANDED_TITLE, mExpandedTitle);
data.put(KEY_EXPANDED_BODY, mExpandedBody);
data.put(KEY_CLICK_INTENT, (mClickIntent == null) ? null : mClickIntent.toUri(0));
data.put(KEY_CONTENT_DESCRIPTION, mContentDescription);
return data;
}
/**
* Deserializes the given JSON representation of extension data, populating this
* object.
*/
public void deserialize(JSONObject data) throws JSONException {
this.mVisible = data.optBoolean(KEY_VISIBLE);
this.mIcon = data.optInt(KEY_ICON);
String iconUriString = data.optString(KEY_ICON_URI);
this.mIconUri = TextUtils.isEmpty(iconUriString) ? null : Uri.parse(iconUriString);
this.mStatus = data.optString(KEY_STATUS);
this.mExpandedTitle = data.optString(KEY_EXPANDED_TITLE);
this.mExpandedBody = data.optString(KEY_EXPANDED_BODY);
try {
this.mClickIntent = Intent.parseUri(data.optString(KEY_CLICK_INTENT), 0);
} catch (URISyntaxException ignored) {
}
this.mContentDescription = data.optString(KEY_CONTENT_DESCRIPTION);
}
/**
* Serializes the contents of this object to a {@link Bundle}.
*/
public Bundle toBundle() {
Bundle data = new Bundle();
data.putBoolean(KEY_VISIBLE, mVisible);
data.putInt(KEY_ICON, mIcon);
data.putString(KEY_ICON_URI, (mIconUri == null ? null : mIconUri.toString()));
data.putString(KEY_STATUS, mStatus);
data.putString(KEY_EXPANDED_TITLE, mExpandedTitle);
data.putString(KEY_EXPANDED_BODY, mExpandedBody);
data.putString(KEY_CLICK_INTENT, (mClickIntent == null) ? null : mClickIntent.toUri(0));
data.putString(KEY_CONTENT_DESCRIPTION, mContentDescription);
return data;
}
/**
* Deserializes the given {@link Bundle} representation of extension data, populating this
* object.
*/
public void fromBundle(Bundle src) {
this.mVisible = src.getBoolean(KEY_VISIBLE, true);
this.mIcon = src.getInt(KEY_ICON);
String iconUriString = src.getString(KEY_ICON_URI);
this.mIconUri = TextUtils.isEmpty(iconUriString) ? null : Uri.parse(iconUriString);
this.mStatus = src.getString(KEY_STATUS);
this.mExpandedTitle = src.getString(KEY_EXPANDED_TITLE);
this.mExpandedBody = src.getString(KEY_EXPANDED_BODY);
try {
this.mClickIntent = Intent.parseUri(src.getString(KEY_CLICK_INTENT), 0);
} catch (URISyntaxException ignored) {
}
this.mContentDescription = src.getString(KEY_CONTENT_DESCRIPTION);
}
/**
* @see Parcelable
*/
public static final Creator<ExtensionData> CREATOR
= new Creator<ExtensionData>() {
public ExtensionData createFromParcel(Parcel in) {
return new ExtensionData(in);
}
public ExtensionData[] newArray(int size) {
return new ExtensionData[size];
}
};
private ExtensionData(Parcel in) {
int parcelableVersion = in.readInt();
int parcelableSize = in.readInt();
int startPosition = in.dataPosition();
if (parcelableVersion >= 1) {
this.mVisible = (in.readInt() != 0);
this.mIcon = in.readInt();
this.mStatus = in.readString();
if (TextUtils.isEmpty(this.mStatus)) {
this.mStatus = null;
}
this.mExpandedTitle = in.readString();
if (TextUtils.isEmpty(this.mExpandedTitle)) {
this.mExpandedTitle = null;
}
this.mExpandedBody = in.readString();
if (TextUtils.isEmpty(this.mExpandedBody)) {
this.mExpandedBody = null;
}
try {
this.mClickIntent = Intent.parseUri(in.readString(), 0);
} catch (URISyntaxException ignored) {
}
}
if (parcelableVersion >= 2) {
this.mContentDescription = in.readString();
if (TextUtils.isEmpty(this.mContentDescription)) {
this.mContentDescription = null;
}
String iconUriString = in.readString();
this.mIconUri = TextUtils.isEmpty(iconUriString) ? null : Uri.parse(iconUriString);
}
// Only advance the data position if the parcelable version is >= 2. In v1 of the
// parcelable, there was an awful bug where the parcelableSize was complete nonsense.
if (parcelableVersion >= 2) {
in.setDataPosition(startPosition + parcelableSize);
}
}
@Override
public void writeToParcel(Parcel parcel, int i) {
/**
* NOTE: When adding fields in the process of updating this API, make sure to bump
* {@link #PARCELABLE_VERSION}.
*/
parcel.writeInt(PARCELABLE_VERSION);
// Inject a placeholder that will store the parcel size from this point on
// (not including the size itself).
int sizePosition = parcel.dataPosition();
parcel.writeInt(0);
int startPosition = parcel.dataPosition();
// Version 1 below
parcel.writeInt(mVisible ? 1 : 0);
parcel.writeInt(mIcon);
parcel.writeString(TextUtils.isEmpty(mStatus) ? "" : mStatus);
parcel.writeString(TextUtils.isEmpty(mExpandedTitle) ? "" : mExpandedTitle);
parcel.writeString(TextUtils.isEmpty(mExpandedBody) ? "" : mExpandedBody);
parcel.writeString((mClickIntent == null) ? "" : mClickIntent.toUri(0));
// Version 2 below
parcel.writeString(TextUtils.isEmpty(mContentDescription) ? "" : mContentDescription);
parcel.writeString(mIconUri == null ? "" : mIconUri.toString());
// Go back and write the size
int parcelableSize = parcel.dataPosition() - startPosition;
parcel.setDataPosition(sizePosition);
parcel.writeInt(parcelableSize);
parcel.setDataPosition(startPosition + parcelableSize);
}
@Override
public int describeContents() {
return 0;
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
try {
ExtensionData other = (ExtensionData) o;
return other.mVisible == mVisible
&& other.mIcon == mIcon
&& objectEquals(other.mIconUri, mIconUri)
&& TextUtils.equals(other.mStatus, mStatus)
&& TextUtils.equals(other.mExpandedTitle, mExpandedTitle)
&& TextUtils.equals(other.mExpandedBody, mExpandedBody)
&& objectEquals(other.mClickIntent, mClickIntent)
&& TextUtils.equals(other.mContentDescription, mContentDescription);
} catch (ClassCastException e) {
return false;
}
}
private static boolean objectEquals(Object x, Object y) {
if (x == null || y == null) {
return x == y;
} else {
return x.equals(y);
}
}
/**
* Returns true if the two provided data objects are equal (or both null).
*/
public static boolean equals(ExtensionData x, ExtensionData y) {
if (x == null || y == null) {
return x == y;
} else {
return x.equals(y);
}
}
@Override
public int hashCode() {
throw new UnsupportedOperationException();
}
/**
* Cleans up this object's data according to the size limits described by
* {@link #MAX_STATUS_LENGTH}, {@link #MAX_EXPANDED_TITLE_LENGTH}, etc.
*/
public void clean() {
if (!TextUtils.isEmpty(mStatus)
&& mStatus.length() > MAX_STATUS_LENGTH) {
mStatus = mStatus.substring(0, MAX_STATUS_LENGTH);
}
if (!TextUtils.isEmpty(mExpandedTitle)
&& mExpandedTitle.length() > MAX_EXPANDED_TITLE_LENGTH) {
mExpandedTitle = mExpandedTitle.substring(0, MAX_EXPANDED_TITLE_LENGTH);
}
if (!TextUtils.isEmpty(mExpandedBody)
&& mExpandedBody.length() > MAX_EXPANDED_BODY_LENGTH) {
mExpandedBody = mExpandedBody.substring(0, MAX_EXPANDED_BODY_LENGTH);
}
if (!TextUtils.isEmpty(mContentDescription)
&& mContentDescription.length() > MAX_EXPANDED_BODY_LENGTH) {
mContentDescription = mContentDescription.substring(0, MAX_CONTENT_DESCRIPTION_LENGTH);
}
}
}
| zywhlc-dashclock | api/src/main/java/com/google/android/apps/dashclock/api/ExtensionData.java | Java | asf20 | 18,739 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This package contains API definitions and base classes for the DashClock extension API.
*
* To get started, see the {@link com.google.android.apps.dashclock.api.DashClockExtension} class
* documentation.
*/
package com.google.android.apps.dashclock.api;
| zywhlc-dashclock | api/src/main/java/com/google/android/apps/dashclock/api/package-info.java | Java | asf20 | 861 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.api;
import com.google.android.apps.dashclock.api.internal.IExtension;
import com.google.android.apps.dashclock.api.internal.IExtensionHost;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.content.pm.Signature;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.util.Log;
/**
* Base class for a DashClock extension. Extensions are a way for other apps to show additional
* status information within DashClock widgets that the user may add to the lockscreen or home
* screen. A limited amount of status information is supported. See the {@link ExtensionData} class
* for the types of information that can be displayed.
*
* <h3>Subclassing {@link DashClockExtension}</h3>
*
* Subclasses must implement at least the {@link #onUpdateData(int)} method, which will be called
* when DashClock requests updated data to show for this extension. Once the extension has new
* data to show, call {@link #publishUpdate(ExtensionData)} to pass the data to the main DashClock
* process. {@link #onUpdateData(int)} will by default be called roughly once per hour, but
* extensions can use methods such as {@link #setUpdateWhenScreenOn(boolean)} and
* {@link #addWatchContentUris(String[])} to request more frequent updates.
*
* <p>
* Subclasses can also override the {@link #onInitialize(boolean)} method to perform basic
* initialization each time a connection to DashClock is established or re-established.
*
* <h3>Registering extensions</h3>
* An extension is simply a service that the DashClock process binds to. Subclasses of this
* base {@link DashClockExtension} class should thus be declared as <code><service></code>
* components in the application's <code>AndroidManifest.xml</code> file.
*
* <p>
* The main DashClock app discovers available extensions using Android's {@link Intent} mechanism.
* Ensure that your <code>service</code> definition includes an <code><intent-filter></code>
* with an action of {@link #ACTION_EXTENSION}. Also make sure to require the
* {@link #PERMISSION_READ_EXTENSION_DATA} permission so that only DashClock can bind to your
* service and request updates. Lastly, there are a few <code><meta-data></code> elements that
* you should add to your service definition:
*
* <ul>
* <li><code>protocolVersion</code> (required): should be <strong>1</strong>.</li>
* <li><code>description</code> (required): should be a one- or two-sentence description
* of the extension, as a string.</li>
* <li><code>settingsActivity</code> (optional): if present, should be the qualified
* component name for a configuration activity in the extension's package that DashClock can offer
* to the user for customizing the extension.</li>
* <li><code>worldReadable</code> (optional): if present and true (default is false), will allow
* other apps besides DashClock to read data for this extension.</li>
* </ul>
*
* <h3>Example</h3>
*
* Below is an example extension declaration in the manifest:
*
* <pre class="prettyprint">
* <service android:name=".ExampleExtension"
* android:icon="@drawable/ic_extension_example"
* android:label="@string/extension_title"
* android:permission="com.google.android.apps.dashclock.permission.READ_EXTENSION_DATA">
* <intent-filter>
* <action android:name="com.google.android.apps.dashclock.Extension" />
* </intent-filter>
* <meta-data android:name="protocolVersion" android:value="2" />
* <meta-data android:name="worldReadable" android:value="true" />
* <meta-data android:name="description"
* android:value="@string/extension_description" />
* <!-- A settings activity is optional -->
* <meta-data android:name="settingsActivity"
* android:value=".ExampleSettingsActivity" />
* </service>
* </pre>
*
* If a <code>settingsActivity</code> meta-data element is present, an activity with the given
* component name should be defined and exported in the application's manifest as well. DashClock
* will set the {@link #EXTRA_FROM_DASHCLOCK_SETTINGS} extra to true in the launch intent for this
* activity. An example is shown below:
*
* <pre class="prettyprint">
* <activity android:name=".ExampleSettingsActivity"
* android:label="@string/title_settings"
* android:exported="true" />
* </pre>
*
* Finally, below is a simple example {@link DashClockExtension} subclass that shows static data in
* DashClock:
*
* <pre class="prettyprint">
* public class ExampleExtension extends DashClockExtension {
* protected void onUpdateData(int reason) {
* publishUpdate(new ExtensionData()
* .visible(true)
* .icon(R.drawable.ic_extension_example)
* .status("Hello")
* .expandedTitle("Hello, world!")
* .expandedBody("This is an example.")
* .clickIntent(new Intent(Intent.ACTION_VIEW,
* Uri.parse("http://www.google.com"))));
* }
* }
* </pre>
*/
public abstract class DashClockExtension extends Service {
private static final String TAG = "DashClockExtension";
/**
* Indicates that {@link #onUpdateData(int)} was triggered for an unknown reason. This should
* be treated as a generic update (similar to {@link #UPDATE_REASON_PERIODIC}.
*/
public static final int UPDATE_REASON_UNKNOWN = 0;
/**
* Indicates that this is the first call to {@link #onUpdateData(int)} since the connection to
* the main DashClock app was established. Note that updates aren't requested in response to
* reconnections after a connection is lost.
*/
public static final int UPDATE_REASON_INITIAL = 1;
/**
* Indicates that {@link #onUpdateData(int)} was triggered due to a normal perioidic refresh
* of extension data.
*/
public static final int UPDATE_REASON_PERIODIC = 2;
/**
* Indicates that {@link #onUpdateData(int)} was triggered because settings for this extension
* may have changed.
*/
public static final int UPDATE_REASON_SETTINGS_CHANGED = 3;
/**
* Indicates that {@link #onUpdateData(int)} was triggered because content changed on a content
* URI previously registered with {@link #addWatchContentUris(String[])}.
*/
public static final int UPDATE_REASON_CONTENT_CHANGED = 4;
/**
* Indicates that {@link #onUpdateData(int)} was triggered because the device screen turned on
* and the extension has called
* {@link #setUpdateWhenScreenOn(boolean) setUpdateWhenScreenOn(true)}.
*/
public static final int UPDATE_REASON_SCREEN_ON = 5;
/**
* Indicates that {@link #onUpdateData(int)} was triggered because the user explicitly requested
* that the extension be updated.
*
* @since Protocol Version 2 (API r2.x)
*/
public static final int UPDATE_REASON_MANUAL = 6;
/**
* The {@link Intent} action representing a DashClock extension. This service should
* declare an <code><intent-filter></code> for this action in order to register with
* DashClock.
*/
public static final String ACTION_EXTENSION = "com.google.android.apps.dashclock.Extension";
/**
* Boolean extra that will be set to true when DashClock starts extension settings activities.
* Check for this extra in your settings activity if you need to adjust your UI depending on
* whether or not the user came from DashClock's settings screen.
*
* @since Protocol Version 2 (API r2.x)
*/
public static final String EXTRA_FROM_DASHCLOCK_SETTINGS
= "com.google.android.apps.dashclock.extra.FROM_DASHCLOCK_SETTINGS";
/**
* The permission that DashClock extensions should require callers to have before providing
* any status updates. Permission checks are implemented automatically by the base class.
*/
public static final String PERMISSION_READ_EXTENSION_DATA
= "com.google.android.apps.dashclock.permission.READ_EXTENSION_DATA";
/**
* The protocol version with which the world readability option became available.
*
* @since Protocol Version 2 (API r2.x)
*/
private static final int PROTOCOL_VERSION_WORLD_READABILITY = 2;
private boolean mInitialized = false;
private boolean mIsWorldReadable = false;
private IExtensionHost mHost;
private volatile Looper mServiceLooper;
private volatile Handler mServiceHandler;
protected DashClockExtension() {
super();
}
@Override
public void onCreate() {
super.onCreate();
loadMetaData();
HandlerThread thread = new HandlerThread(
"DashClockExtension:" + getClass().getSimpleName());
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new Handler(mServiceLooper);
}
@Override
public void onDestroy() {
mServiceHandler.removeCallbacksAndMessages(null); // remove all callbacks
mServiceLooper.quit();
}
private void loadMetaData() {
PackageManager pm = getPackageManager();
try {
ServiceInfo si = pm.getServiceInfo(
new ComponentName(this, getClass()),
PackageManager.GET_META_DATA);
Bundle metaData = si.metaData;
if (metaData != null) {
int protocolVersion = metaData.getInt("protocolVersion");
mIsWorldReadable = protocolVersion >= PROTOCOL_VERSION_WORLD_READABILITY
&& metaData.getBoolean("worldReadable");
}
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, "Could not load metadata (e.g. world readable) for extension.");
}
}
@Override
public final IBinder onBind(Intent intent) {
return mBinder;
}
private IExtension.Stub mBinder = new IExtension.Stub() {
@Override
public void onInitialize(IExtensionHost host, boolean isReconnect)
throws RemoteException {
if (!mIsWorldReadable) {
// If not world readable, check the signature of the [first] package with the given
// UID against the known-good official DashClock app signature.
boolean verified = false;
PackageManager pm = getPackageManager();
String[] packages = pm.getPackagesForUid(getCallingUid());
if (packages != null && packages.length > 0) {
try {
PackageInfo pi = pm.getPackageInfo(packages[0],
PackageManager.GET_SIGNATURES);
if (pi.signatures != null
&& pi.signatures.length == 1
&& DASHCLOCK_SIGNATURE.equals(pi.signatures[0])) {
verified = true;
}
} catch (PackageManager.NameNotFoundException ignored) {
}
}
if (!verified) {
Log.e(TAG, "Caller is not official DashClock app and this "
+ "extension is not world-readable.");
throw new SecurityException("Caller is not official DashClock app and this "
+ "extension is not world-readable.");
}
}
mHost = host;
if (!mInitialized) {
DashClockExtension.this.onInitialize(isReconnect);
mInitialized = true;
}
}
@Override
public void onUpdate(final int reason) throws RemoteException {
if (!mInitialized) {
return;
}
// Do this in a separate thread
mServiceHandler.post(new Runnable() {
@Override
public void run() {
DashClockExtension.this.onUpdateData(reason);
}
});
}
};
/**
* Called when a connection with the main DashClock app has been established or re-established
* after a previous one was lost. In this latter case, the parameter <code>isReconnect</code>
* will be true. Override this method to perform basic extension initialization before calls
* to {@link #onUpdateData(int)} are made.
*
* @param isReconnect Whether or not this call is being made after a connection was dropped and
* a new connection has been established.
*/
protected void onInitialize(boolean isReconnect) {
}
/**
* Called when the DashClock app process is requesting that the extension provide updated
* information to show to the user. Implementations can choose to do nothing, or more commonly,
* provide an update using the {@link #publishUpdate(ExtensionData)} method. Note that doing
* nothing doesn't clear existing data. To clear any existing data, call
* {@link #publishUpdate(ExtensionData)} with <code>null</code> data.
*
* @param reason The reason for the update. See {@link #UPDATE_REASON_PERIODIC} and related
* constants for more details.
*/
protected abstract void onUpdateData(int reason);
/**
* Notifies the main DashClock app that new data is available for the extension and should
* potentially be shown to the user. Note that this call does not necessarily need to be made
* from inside the {@link #onUpdateData(int)} method, but can be made only after
* {@link #onInitialize(boolean)} has been called. If you only call this from within
* {@link #onUpdateData(int)} this is already ensured.
*
* @param data The data to show, or <code>null</code> if existing data should be cleared (hiding
* the extension from view).
*/
protected final void publishUpdate(ExtensionData data) {
try {
mHost.publishUpdate(data);
} catch (RemoteException e) {
Log.e(TAG, "Couldn't publish updated extension data.", e);
}
}
/**
* Requests that the main DashClock app watch the given content URIs (using
* {@link android.content.ContentResolver#registerContentObserver(android.net.Uri, boolean,
* android.database.ContentObserver) ContentResolver.registerContentObserver})
* and call this extension's {@link #onUpdateData(int)} method when changes are observed.
* This should generally be called in the {@link #onInitialize(boolean)} method.
*
* @param uris The URIs to watch.
*/
protected final void addWatchContentUris(String[] uris) {
try {
mHost.addWatchContentUris(uris);
} catch (RemoteException e) {
Log.e(TAG, "Couldn't watch content URIs.", e);
}
}
/**
* Requests that the main DashClock app stop watching all content URIs previously registered
* with {@link #addWatchContentUris(String[])} for this extension.
*
* @param uris The URIs to watch.
* @since Protocol Version 2 (API r2.x)
*/
protected final void removeAllWatchContentUris() {
try {
mHost.removeAllWatchContentUris();
} catch (RemoteException e) {
Log.e(TAG, "Couldn't stop watching content URIs.", e);
}
}
/**
* Requests that the main DashClock app call (or not call) this extension's
* {@link #onUpdateData(int)} method when the screen turns on (the phone resumes from idle).
* This should generally be called in the {@link #onInitialize(boolean)} method. By default,
* extensions do not get updated when the screen turns on.
*
* @see Intent#ACTION_SCREEN_ON
* @param updateWhenScreenOn Whether or not a call to {@link #onUpdateData(int)} method when
* the screen turns on.
*/
protected final void setUpdateWhenScreenOn(boolean updateWhenScreenOn) {
try {
mHost.setUpdateWhenScreenOn(updateWhenScreenOn);
} catch (RemoteException e) {
Log.e(TAG, "Couldn't set the extension to update upon ACTION_SCREEN_ON.", e);
}
}
/**
* The signature of the official DashClock app (net.nurik.roman.dashclock). Used to
* compare caller when {@link #mIsWorldReadable} is false.
*/
private static final Signature DASHCLOCK_SIGNATURE = new Signature(""
+ "308203523082023aa00302010202044c1132a9300d06092a864886f70d0101050500306b310b30090603"
+ "550406130255533110300e06035504081307556e6b6e6f776e3110300e06035504071307556e6b6e6f77"
+ "6e3110300e060355040a1307556e6b6e6f776e3110300e060355040b1307556e6b6e6f776e3114301206"
+ "03550403130b526f6d616e204e7572696b301e170d3130303631303138343435375a170d333731303236"
+ "3138343435375a306b310b30090603550406130255533110300e06035504081307556e6b6e6f776e3110"
+ "300e06035504071307556e6b6e6f776e3110300e060355040a1307556e6b6e6f776e3110300e06035504"
+ "0b1307556e6b6e6f776e311430120603550403130b526f6d616e204e7572696b30820122300d06092a86"
+ "4886f70d01010105000382010f003082010a02820101008906222723a4b30dca6f0702b041e6f361e38e"
+ "35105ec530bf43f4f1786737fefe6ccfa3b038a3700ea685dd185112a0a8f96327d3373de28e05859a87"
+ "bde82372baed5618082121d6946e4affbdfb6771abb782147d58a2323518b34efcce144ec3e45fb2556e"
+ "ba1c40b42ccbcc1266c9469b5447edf09d5cf8e2ed62cfb3bd902e47f48a11a815a635c3879c882eae92"
+ "3c7f73bfba4039b7c19930617e3326fa163b924eda398bacc0d6ef8643a32223ce1d767734e866553ad5"
+ "0d11fb22ac3a15ba021a6a3904a95ed65f54142256cb0db90038dd55adfeeb18d3ffb085c4380817268f"
+ "039119ecbdfca843e4b82209947fd88470b3d8c76fc15878fbc4f10203010001300d06092a864886f70d"
+ "0101050500038201010047063efdd5011adb69cca6461a57443fef59243f85e5727ec0d67513bb04b650"
+ "b1144fc1f54e09789c278171c52b9305a7265cafc13b89d91eb37ddce34a5c1f17c8c36f86c957c4e9ca"
+ "cc19e6822e0a5711f2cfba2c5913ba582ab69485548b13072bc736310b9da85a716d0418e6449450ceda"
+ "dfc1c897f93ed6189cfa0a02b893125bd4b1c4e4dd50c1ad33e221120b8488841763a3361817081e7691"
+ "1e76d3adcf94b23c758ceb955f9fdf8ef4a8351fc279867a25729f081b511209e96dfa8520225b810072"
+ "de5e8eefc1a6cc22f46857e2cc4fd1a1eaac76054f34352b63c9d53691515b42cc771f195343e61397cb"
+ "7b04ada2a627410d29c214976d13");
}
| zywhlc-dashclock | api/src/main/java/com/google/android/apps/dashclock/api/DashClockExtension.java | Java | asf20 | 19,581 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.api;
parcelable ExtensionData;
| zywhlc-dashclock | api/src/main/aidl/com/google/android/apps/dashclock/api/ExtensionData.aidl | AIDL | asf20 | 670 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.api.internal;
import com.google.android.apps.dashclock.api.internal.IExtensionHost;
import com.google.android.apps.dashclock.api.ExtensionData;
import android.content.Intent;
interface IExtension {
/**
* Since there might be a case where new versions of DashClock use extensions running
* old versions of the protocol (and thus old versions of this AIDL), there are a few things
* to keep in mind when editing this class:
*
* - Order of functions defined below matters. New methods added in new protocol versions must
* be added below all other methods.
* - Do NOT modify a signature once a protocol version is finalized.
*/
// Protocol version 1 below
oneway void onInitialize(in IExtensionHost host, boolean isReconnect);
oneway void onUpdate(int reason);
// Protocol version 2 below
}
| zywhlc-dashclock | api/src/main/aidl/com/google/android/apps/dashclock/api/internal/IExtension.aidl | AIDL | asf20 | 1,490 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.api.internal;
import com.google.android.apps.dashclock.api.ExtensionData;
interface IExtensionHost {
/**
* Since there might be a case where new versions of DashClock use extensions running
* old versions of the protocol (and thus old versions of this AIDL), there are a few things
* to keep in mind when editing this class:
*
* - Order of functions defined below matters. New methods added in new protocol versions must
* be added below all other methods.
* - Do NOT modify a signature once a protocol version is finalized.
*/
// Protocol version 1 below
oneway void publishUpdate(in ExtensionData data);
oneway void addWatchContentUris(in String[] contentUris);
oneway void setUpdateWhenScreenOn(boolean updateWhenScreenOn);
// Protcol version 2 below
oneway void removeAllWatchContentUris();
// Protcol version 3 below
}
| zywhlc-dashclock | api/src/main/aidl/com/google/android/apps/dashclock/api/internal/IExtensionHost.aidl | AIDL | asf20 | 1,538 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import com.google.android.apps.dashclock.api.internal.IExtension;
import com.google.android.apps.dashclock.api.internal.IExtensionHost;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Pair;
import android.util.SparseArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import static com.google.android.apps.dashclock.LogUtils.LOGE;
/**
* The primary local-process endpoint that deals with extensions. Instances of this class are in
* charge of maintaining a {@link ServiceConnection} with connected extensions. There should
* only be one instance of this class in the app.
* <p>
* This class is intended to be used as part of a containing service. Make sure to call
* {@link #destroy()} in the service's {@link android.app.Service#onDestroy()}.
*/
public class ExtensionHost {
// TODO: this class badly needs inline docs
private static final String TAG = LogUtils.makeLogTag(ExtensionHost.class);
private static final int CURRENT_EXTENSION_PROTOCOL_VERSION = 2;
/**
* The amount of time to wait after something has changed before recognizing it as an individual
* event. Any changes within this time window will be collapsed, and will further delay the
* handling of the event.
*/
public static final int UPDATE_COLLAPSE_TIME_MILLIS = 500;
private Context mContext;
private Handler mClientThreadHandler = new Handler();
private ExtensionManager mExtensionManager;
private Map<ComponentName, Connection> mExtensionConnections
= new HashMap<ComponentName, Connection>();
private final Set<ComponentName> mExtensionsToUpdateWhenScreenOn = new HashSet<ComponentName>();
private boolean mScreenOnReceiverRegistered = false;
private volatile Looper mAsyncLooper;
private volatile Handler mAsyncHandler;
public ExtensionHost(Service context) {
mContext = context;
mExtensionManager = ExtensionManager.getInstance(context);
mExtensionManager.addOnChangeListener(mChangeListener);
HandlerThread thread = new HandlerThread("ExtensionHost");
thread.start();
mAsyncLooper = thread.getLooper();
mAsyncHandler = new Handler(mAsyncLooper);
mChangeListener.onExtensionsChanged();
mExtensionManager.cleanupExtensions();
}
public void destroy() {
mExtensionManager.removeOnChangeListener(mChangeListener);
if (mScreenOnReceiverRegistered) {
mContext.unregisterReceiver(mScreenOnReceiver);
mScreenOnReceiverRegistered = false;
}
establishAndDestroyConnections(new ArrayList<ComponentName>());
mAsyncLooper.quit();
}
private void establishAndDestroyConnections(List<ComponentName> newExtensionNames) {
// Get the list of active extensions
Set<ComponentName> activeSet = new HashSet<ComponentName>();
activeSet.addAll(newExtensionNames);
// Get the list of connected extensions
Set<ComponentName> connectedSet = new HashSet<ComponentName>();
connectedSet.addAll(mExtensionConnections.keySet());
for (final ComponentName cn : activeSet) {
if (connectedSet.contains(cn)) {
continue;
}
// Bind anything not currently connected (this is the initial connection
// to the now-added extension)
Connection conn = createConnection(cn, false);
if (conn != null) {
mExtensionConnections.put(cn, conn);
}
}
// Remove active items from the connected set, leaving only newly-inactive items
// to be disconnected below.
connectedSet.removeAll(activeSet);
for (ComponentName cn : connectedSet) {
Connection conn = mExtensionConnections.get(cn);
// Unbind the now-disconnected extension
destroyConnection(conn);
mExtensionConnections.remove(cn);
}
}
private Connection createConnection(final ComponentName cn, final boolean isReconnect) {
final Connection conn = new Connection();
conn.componentName = cn;
conn.contentObserver = new ContentObserver(mClientThreadHandler) {
@Override
public void onChange(boolean selfChange) {
execute(conn.componentName,
UPDATE_OPERATIONS.get(DashClockExtension.UPDATE_REASON_CONTENT_CHANGED),
UPDATE_COLLAPSE_TIME_MILLIS,
DashClockExtension.UPDATE_REASON_CONTENT_CHANGED);
}
};
conn.hostInterface = makeHostInterface(conn);
conn.serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(final ComponentName componentName, IBinder iBinder) {
conn.ready = true;
conn.binder = IExtension.Stub.asInterface(iBinder);
// Initialize the service
execute(conn, new Operation() {
@Override
public void run(IExtension extension) throws RemoteException {
// Note that this is protected from ANRs since it runs in the
// AsyncHandler thread. Also, since this is a 'oneway' call,
// when used with remote extensions, this call does not block.
try {
extension.onInitialize(conn.hostInterface, isReconnect);
} catch (SecurityException e) {
LOGE(TAG, "Error initializing extension "
+ componentName.toString(), e);
}
}
}, 0, null);
if (!isReconnect) {
execute(conn.componentName,
UPDATE_OPERATIONS.get(DashClockExtension.UPDATE_REASON_INITIAL),
0,
null);
}
// Execute operations that were deferred until the service was available.
// TODO: handle service disruptions that occur here
synchronized (conn.deferredOps) {
if (conn.ready) {
Set<Object> processedCollapsedTokens = new HashSet<Object>();
Iterator<Pair<Object, Operation>> it = conn.deferredOps.iterator();
while (it.hasNext()) {
Pair<Object, Operation> op = it.next();
if (op.first != null) {
if (processedCollapsedTokens.contains(op.first)) {
// An operation with this collapse token has already been
// processed; skip this one.
continue;
}
processedCollapsedTokens.add(op.first);
}
execute(conn, op.second, 0, null);
it.remove();
}
}
}
}
@Override
public void onServiceDisconnected(final ComponentName componentName) {
conn.serviceConnection = null;
conn.binder = null;
conn.ready = false;
mClientThreadHandler.post(new Runnable() {
@Override
public void run() {
mExtensionConnections.remove(componentName);
}
});
}
};
try {
if (!mContext.bindService(new Intent().setComponent(cn), conn.serviceConnection,
Context.BIND_AUTO_CREATE)) {
LOGE(TAG, "Error binding to extension " + cn.flattenToShortString());
return null;
}
} catch (SecurityException e) {
LOGE(TAG, "Error binding to extension " + cn.flattenToShortString(), e);
return null;
}
return conn;
}
private IExtensionHost makeHostInterface(final Connection conn) {
return new IExtensionHost.Stub() {
@Override
public void publishUpdate(ExtensionData data) throws RemoteException {
if (data == null) {
data = new ExtensionData();
}
// TODO: this needs to be thread-safe
mExtensionManager.updateExtensionData(conn.componentName, data);
}
@Override
public void addWatchContentUris(String[] contentUris) throws RemoteException {
if (contentUris != null && contentUris.length > 0 && conn.contentObserver != null) {
ContentResolver resolver = mContext.getContentResolver();
for (String uri : contentUris) {
if (TextUtils.isEmpty(uri)) {
continue;
}
resolver.registerContentObserver(Uri.parse(uri), true,
conn.contentObserver);
}
}
}
@Override
public void removeAllWatchContentUris() throws RemoteException {
ContentResolver resolver = mContext.getContentResolver();
resolver.unregisterContentObserver(conn.contentObserver);
}
@Override
public void setUpdateWhenScreenOn(boolean updateWhenScreenOn) throws RemoteException {
synchronized (mExtensionsToUpdateWhenScreenOn) {
if (updateWhenScreenOn) {
if (mExtensionsToUpdateWhenScreenOn.size() == 0) {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
mContext.registerReceiver(mScreenOnReceiver, filter);
mScreenOnReceiverRegistered = true;
}
mExtensionsToUpdateWhenScreenOn.add(conn.componentName);
} else {
mExtensionsToUpdateWhenScreenOn.remove(conn.componentName);
if (mExtensionsToUpdateWhenScreenOn.size() == 0) {
mContext.unregisterReceiver(mScreenOnReceiver);
mScreenOnReceiverRegistered = false;
}
}
}
}
};
}
private void destroyConnection(Connection conn) {
if (conn.contentObserver != null) {
mContext.getContentResolver().unregisterContentObserver(conn.contentObserver);
conn.contentObserver = null;
}
conn.binder = null;
mContext.unbindService(conn.serviceConnection);
conn.serviceConnection = null;
}
private ExtensionManager.OnChangeListener mChangeListener
= new ExtensionManager.OnChangeListener() {
@Override
public void onExtensionsChanged() {
establishAndDestroyConnections(mExtensionManager.getActiveExtensionNames());
}
};
private void execute(final Connection conn, final Operation operation,
int collapseDelayMillis, final Object collapseToken) {
final Object collapseTokenForConn;
if (collapseDelayMillis > 0 && collapseToken != null) {
collapseTokenForConn = new Pair<ComponentName, Object>(conn.componentName,
collapseToken);
} else {
collapseTokenForConn = null;
}
final Runnable runnable = new Runnable() {
@Override
public void run() {
try {
if (conn.binder == null) {
throw new RemoteException("Binder is unavailable.");
}
operation.run(conn.binder);
} catch (RemoteException e) {
LOGE(TAG, "Couldn't execute operation; scheduling for retry upon service "
+ "reconnection.", e);
// TODO: exponential backoff for retrying the same operation, or fail after
// n attempts (in case the remote service consistently crashes when
// executing this operation)
synchronized (conn.deferredOps) {
conn.deferredOps.add(new Pair<Object, Operation>(
collapseTokenForConn, operation));
}
}
}
};
if (conn.ready) {
if (collapseTokenForConn != null) {
mAsyncHandler.removeCallbacksAndMessages(collapseTokenForConn);
}
if (collapseDelayMillis > 0) {
mAsyncHandler.postAtTime(runnable, collapseTokenForConn,
SystemClock.uptimeMillis() + collapseDelayMillis);
} else {
mAsyncHandler.post(runnable);
}
} else {
mAsyncHandler.post(new Runnable() {
@Override
public void run() {
synchronized (conn.deferredOps) {
conn.deferredOps.add(new Pair<Object, Operation>(
collapseTokenForConn, operation));
}
}
});
}
}
public void execute(ComponentName cn, Operation operation,
int collapseDelayMillis, final Object collapseToken) {
Connection conn = mExtensionConnections.get(cn);
if (conn == null) {
conn = createConnection(cn, true);
if (conn != null) {
mExtensionConnections.put(cn, conn);
} else {
LOGE(TAG, "Couldn't connect to extension to perform operation; operation "
+ "canceled.");
return;
}
}
execute(conn, operation, collapseDelayMillis, collapseToken);
}
private final BroadcastReceiver mScreenOnReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
synchronized (mExtensionsToUpdateWhenScreenOn) {
for (ComponentName cn : mExtensionsToUpdateWhenScreenOn) {
execute(cn, UPDATE_OPERATIONS.get(DashClockExtension.UPDATE_REASON_SCREEN_ON),
0, null);
}
}
}
};
static final SparseArray<Operation> UPDATE_OPERATIONS = new SparseArray<Operation>();
static {
_createUpdateOperation(DashClockExtension.UPDATE_REASON_UNKNOWN);
_createUpdateOperation(DashClockExtension.UPDATE_REASON_INITIAL);
_createUpdateOperation(DashClockExtension.UPDATE_REASON_PERIODIC);
_createUpdateOperation(DashClockExtension.UPDATE_REASON_SETTINGS_CHANGED);
_createUpdateOperation(DashClockExtension.UPDATE_REASON_CONTENT_CHANGED);
_createUpdateOperation(DashClockExtension.UPDATE_REASON_SCREEN_ON);
_createUpdateOperation(DashClockExtension.UPDATE_REASON_MANUAL);
}
private static void _createUpdateOperation(final int reason) {
UPDATE_OPERATIONS.put(reason, new ExtensionHost.Operation() {
@Override
public void run(IExtension extension) throws RemoteException {
// Note that this is protected from ANRs since it runs in the AsyncHandler thread.
// Also, since this is a 'oneway' call, when used with remote extensions, this call
// does not block.
extension.onUpdate(reason);
}
});
}
public static boolean supportsProtocolVersion(int protocolVersion) {
return protocolVersion > 0 && protocolVersion <= CURRENT_EXTENSION_PROTOCOL_VERSION;
}
/**
* Will be run on a worker thread.
*/
public static interface Operation {
void run(IExtension extension) throws RemoteException;
}
private static class Connection {
boolean ready = false;
ComponentName componentName;
ServiceConnection serviceConnection;
IExtension binder;
IExtensionHost hostInterface;
ContentObserver contentObserver;
/**
* Only access on the async thread. The pair is (collapse token, operation)
*/
final Queue<Pair<Object, Operation>> deferredOps
= new LinkedList<Pair<Object, Operation>>();
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/ExtensionHost.java | Java | asf20 | 18,268 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.api;
import android.content.ComponentName;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
public class VisibleExtension implements Parcelable {
// TODO: if this ever becomes a public API, make sure to add parcel versioning.
private ComponentName mComponentName;
private ExtensionData mData;
public VisibleExtension() {
}
public ComponentName componentName() {
return this.mComponentName;
}
public VisibleExtension componentName(final ComponentName mComponentName) {
this.mComponentName = mComponentName;
return this;
}
public ExtensionData data() {
return this.mData;
}
public VisibleExtension data(final ExtensionData mData) {
this.mData = mData;
return this;
}
public static final Creator<VisibleExtension> CREATOR
= new Creator<VisibleExtension>() {
public VisibleExtension createFromParcel(Parcel in) {
return new VisibleExtension(in);
}
public VisibleExtension[] newArray(int size) {
return new VisibleExtension[size];
}
};
private VisibleExtension(Parcel in) {
// Read extension data
boolean dataPresent = in.readInt() == 1;
this.mData = (ExtensionData) (dataPresent
? in.readParcelable(ExtensionData.class.getClassLoader())
: null);
// Read component name
String componentName = in.readString();
if (!TextUtils.isEmpty(componentName)) {
mComponentName = ComponentName.unflattenFromString(componentName);
} else {
mComponentName = null;
}
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt((mData != null) ? 1 : 0);
if (mData != null) {
parcel.writeParcelable(mData, 0);
}
parcel.writeString((mComponentName == null) ? "" : mComponentName.flattenToString());
}
@Override
public int describeContents() {
return 0;
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
try {
VisibleExtension other = (VisibleExtension) o;
return objectEquals(other.mComponentName, mComponentName)
&& objectEquals(other.mData, mData);
} catch (ClassCastException e) {
return false;
}
}
private static boolean objectEquals(Object x, Object y) {
if (x == null || y == null) {
return x == y;
} else {
return x.equals(y);
}
}
@Override
public int hashCode() {
throw new UnsupportedOperationException();
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/api/VisibleExtension.java | Java | asf20 | 3,476 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.render;
import com.google.android.apps.dashclock.ExtensionManager;
import com.google.android.apps.dashclock.LogUtils;
import com.google.android.apps.dashclock.Utils;
import com.google.android.apps.dashclock.WidgetClickProxyActivity;
import com.google.android.apps.dashclock.configuration.AppChooserPreference;
import com.google.android.apps.dashclock.configuration.AppearanceConfig;
import com.google.android.apps.dashclock.configuration.ConfigurationActivity;
import net.nurik.roman.dashclock.R;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import java.util.List;
import java.util.Locale;
import static com.google.android.apps.dashclock.ExtensionManager.ExtensionWithData;
/**
* Abstract helper class in charge of core rendering logic for DashClock widgets.
*/
public abstract class DashClockRenderer {
private static final String TAG = LogUtils.makeLogTag(DashClockRenderer.class);
private static final int MAX_COLLAPSED_EXTENSIONS = 3;
public static final String PREF_CLOCK_SHORTCUT = "pref_clock_shortcut";
public static final String PREF_HIDE_SETTINGS = "pref_hide_settings";
protected Context mContext;
protected Options mOptions;
protected ExtensionManager mExtensionManager;
protected DashClockRenderer(Context context) {
mContext = context;
mExtensionManager = ExtensionManager.getInstance(context);
}
public void setOptions(Options options) {
mOptions = options;
}
public Object renderWidget(Object container) {
ViewBuilder vb = onCreateViewBuilder();
Resources res = mContext.getResources();
// Load data from extensions
List<ExtensionWithData> extensions = mExtensionManager.getActiveExtensionsWithData();
int activeExtensions = extensions.size();
int visibleExtensions = 0;
for (ExtensionWithData ewd : extensions) {
if (!ewd.latestData.visible()) {
continue;
}
++visibleExtensions;
}
// Load some settings
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
boolean hideSettings = sp.getBoolean(PREF_HIDE_SETTINGS, false);
// Determine if we're on a tablet or not (lock screen widgets can't be collapsed on
// tablets).
boolean isTablet = res.getConfiguration().smallestScreenWidthDp >= 600;
// Pull high-level user-defined appearance options.
int shadeColor = AppearanceConfig.getHomescreenBackgroundColor(mContext);
boolean aggressiveCentering = AppearanceConfig.isAggressiveCenteringEnabled(mContext);
int minExpandedHeight = res.getDimensionPixelSize(
mOptions.target == Options.TARGET_LOCK_SCREEN
? R.dimen.min_expanded_height_lock_screen
: R.dimen.min_expanded_height);
boolean isExpanded = (mOptions.minHeightDp
>= minExpandedHeight / res.getDisplayMetrics().density);
// Step 1. Load the root layout
vb.loadRootLayout(container, isExpanded
? (aggressiveCentering
? R.layout.widget_main_expanded_forced_center
: R.layout.widget_main_expanded)
: (aggressiveCentering
? R.layout.widget_main_collapsed_forced_center
: R.layout.widget_main_collapsed));
// Step 2. Configure the shade, if it should exist
vb.setViewBackgroundColor(R.id.shade, shadeColor);
vb.setViewVisibility(R.id.shade,
(mOptions.target != Options.TARGET_HOME_SCREEN || shadeColor == 0)
? View.GONE : View.VISIBLE);
// Step 3. Draw the basic clock face
renderClockFace(vb);
// Step 4. Align the clock face and settings button (if shown)
boolean isPortrait = res.getConfiguration().orientation
== Configuration.ORIENTATION_PORTRAIT;
if (aggressiveCentering) {
// Forced/aggressive centering rules
vb.setViewVisibility(R.id.settings_button_center_displacement,
hideSettings ? View.GONE : View.VISIBLE);
vb.setViewPadding(R.id.clock_row, 0, 0, 0, 0);
vb.setLinearLayoutGravity(R.id.clock_target, Gravity.CENTER_HORIZONTAL);
} else {
// Normal centering rules
boolean forceCentered = isTablet && isPortrait
&& mOptions.target != Options.TARGET_HOME_SCREEN;
int clockInnerGravity = Gravity.CENTER_HORIZONTAL;
if (activeExtensions > 0 && !forceCentered) {
// Extensions are visible, don't center clock
if (mOptions.target == Options.TARGET_LOCK_SCREEN) {
// lock screen doesn't look at expanded state; the UI should
// not jitter across expanded/collapsed states for lock screen
clockInnerGravity = isTablet ? Gravity.LEFT : Gravity.RIGHT;
} else {
// home screen
clockInnerGravity = (isExpanded && isTablet) ? Gravity.LEFT : Gravity.RIGHT;
}
}
vb.setLinearLayoutGravity(R.id.clock_target, clockInnerGravity);
boolean clockCentered = activeExtensions == 0 || forceCentered; // left otherwise
vb.setLinearLayoutGravity(R.id.clock_row,
clockCentered ? Gravity.CENTER_HORIZONTAL : Gravity.LEFT);
vb.setViewVisibility(R.id.settings_button_center_displacement,
hideSettings
? View.GONE
: (clockCentered ? View.INVISIBLE : View.GONE));
int clockLeftMargin = res.getDimensionPixelSize(R.dimen.clock_left_margin);
if (!isExpanded && mOptions.target == Options.TARGET_HOME_SCREEN) {
clockLeftMargin = 0;
}
vb.setViewPadding(R.id.clock_row, clockCentered ? 0 : clockLeftMargin,
0, 0, 0);
}
// Settings button
if (isExpanded) {
vb.setViewVisibility(R.id.settings_button, hideSettings ? View.GONE : View.VISIBLE);
vb.setViewClickIntent(R.id.settings_button,
new Intent(mContext, ConfigurationActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS));
}
// Step 6. Render the extensions (collapsed or expanded)
vb.setViewVisibility(R.id.widget_divider,
(visibleExtensions > 0) ? View.VISIBLE : View.GONE);
if (isExpanded) {
// Expanded style
final Intent onClickTemplateIntent = WidgetClickProxyActivity.getTemplate(mContext);
builderSetExpandedExtensionsAdapter(vb, R.id.expanded_extensions,
onClickTemplateIntent);
} else {
// Collapsed style
vb.setViewVisibility(R.id.collapsed_extensions_container,
activeExtensions > 0 ? View.VISIBLE : View.GONE);
boolean ellipsisVisible = false;
vb.removeAllViews(R.id.collapsed_extensions_container);
int slotIndex = 0;
for (ExtensionWithData ewd : extensions) {
if (!ewd.latestData.visible()) {
continue;
}
if (slotIndex >= MAX_COLLAPSED_EXTENSIONS) {
ellipsisVisible = true;
break;
}
vb.addView(R.id.collapsed_extensions_container,
renderCollapsedExtension(null, ewd));
++slotIndex;
}
if (ellipsisVisible) {
vb.addView(R.id.collapsed_extensions_container,
vb.inflateChildLayout(
R.layout.widget_include_collapsed_ellipsis,
R.id.collapsed_extensions_container));
}
}
return vb.getRoot();
}
public void renderClockFace(ViewBuilder vb) {
vb.removeAllViews(R.id.time_container);
vb.addView(R.id.time_container,
vb.inflateChildLayout(
AppearanceConfig.getCurrentTimeLayout(mContext),
R.id.time_container));
vb.removeAllViews(R.id.date_container);
vb.addView(R.id.date_container,
vb.inflateChildLayout(
AppearanceConfig.getCurrentDateLayout(mContext),
R.id.date_container));
if (mOptions.minWidthDp < 300) {
Resources res = mContext.getResources();
int miniTextSizeLargePx = res.getDimensionPixelSize(R.dimen.mini_clock_text_size_large);
int miniTextSizeSmallPx = res.getDimensionPixelSize(R.dimen.mini_clock_text_size_small);
for (int id : LARGE_TIME_COMPONENT_IDS) {
vb.setTextViewTextSize(id, TypedValue.COMPLEX_UNIT_PX, miniTextSizeLargePx);
}
for (int id : SMALL_TIME_COMPONENT_IDS) {
vb.setTextViewTextSize(id, TypedValue.COMPLEX_UNIT_PX, miniTextSizeSmallPx);
}
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
Intent clockIntent = AppChooserPreference.getIntentValue(
sp.getString(PREF_CLOCK_SHORTCUT, null),
Utils.getDefaultClockIntent(mContext));
if (clockIntent != null) {
vb.setViewClickIntent(R.id.clock_target, clockIntent);
}
}
public Object renderCollapsedExtension(Object container, ExtensionWithData ewd) {
ViewBuilder vb = onCreateViewBuilder();
vb.loadRootLayout(container, R.layout.widget_include_collapsed_extension);
Resources res = mContext.getResources();
int extensionCollapsedTextSizeSingleLine = res
.getDimensionPixelSize(R.dimen.extension_collapsed_text_size_single_line);
int extensionCollapsedTextSizeTwoLine = res
.getDimensionPixelSize(R.dimen.extension_collapsed_text_size_two_line);
String status = ewd.latestData.status();
if (TextUtils.isEmpty(status)) {
status = "";
}
if (status.indexOf("\n") > 0) {
vb.setTextViewSingleLine(R.id.collapsed_extension_text, false);
vb.setTextViewMaxLines(R.id.collapsed_extension_text, 2);
vb.setTextViewTextSize(R.id.collapsed_extension_text,
TypedValue.COMPLEX_UNIT_PX,
extensionCollapsedTextSizeTwoLine);
} else {
vb.setTextViewSingleLine(R.id.collapsed_extension_text, true);
vb.setTextViewMaxLines(R.id.collapsed_extension_text, 1);
vb.setTextViewTextSize(R.id.collapsed_extension_text,
TypedValue.COMPLEX_UNIT_PX,
extensionCollapsedTextSizeSingleLine);
}
vb.setTextViewText(R.id.collapsed_extension_text,
status.toUpperCase(Locale.getDefault()));
String statusContentDescription = ewd.latestData.contentDescription();
if (TextUtils.isEmpty(statusContentDescription)) {
StringBuilder builder = new StringBuilder();
String expandedTitle = Utils.expandedTitleOrStatus(ewd.latestData);
if (!TextUtils.isEmpty(expandedTitle)) {
builder.append(expandedTitle);
}
String expandedBody = ewd.latestData.expandedBody();
if (!TextUtils.isEmpty(expandedBody)) {
builder.append(" ").append(expandedBody);
}
statusContentDescription = builder.toString();
}
vb.setViewContentDescription(R.id.collapsed_extension_text, statusContentDescription);
vb.setImageViewBitmap(R.id.collapsed_extension_icon,
Utils.loadExtensionIcon(mContext, ewd.listing.componentName,
ewd.latestData.icon(), ewd.latestData.iconUri()));
vb.setViewContentDescription(R.id.collapsed_extension_icon, ewd.listing.title);
Intent clickIntent = ewd.latestData.clickIntent();
if (clickIntent != null) {
vb.setViewClickIntent(R.id.collapsed_extension_target,
WidgetClickProxyActivity.wrap(mContext, clickIntent,
ewd.listing.componentName));
}
return vb.getRoot();
}
public Object renderExpandedExtension(Object container, Object convertRoot,
ExtensionWithData ewd) {
ViewBuilder vb = onCreateViewBuilder();
if (convertRoot != null) {
vb.useRoot(convertRoot);
} else {
vb.loadRootLayout(container, R.layout.widget_list_item_expanded_extension);
}
if (ewd == null || ewd.latestData == null) {
vb.setTextViewText(R.id.text1, mContext.getResources()
.getText(R.string.status_none));
vb.setViewVisibility(R.id.text2, View.GONE);
return vb.getRoot();
}
vb.setTextViewText(R.id.text1, Utils.expandedTitleOrStatus(ewd.latestData));
String expandedBody = ewd.latestData.expandedBody();
vb.setViewVisibility(R.id.text2, TextUtils.isEmpty(expandedBody)
? View.GONE : View.VISIBLE);
vb.setTextViewText(R.id.text2, ewd.latestData.expandedBody());
vb.setImageViewBitmap(R.id.icon,
Utils.loadExtensionIcon(mContext, ewd.listing.componentName,
ewd.latestData.icon(), ewd.latestData.iconUri()));
String contentDescription = ewd.latestData.contentDescription();
if (TextUtils.isEmpty(contentDescription)) {
// No specific content description provided. Just set the minimal extra content
// description for the icon.
vb.setViewContentDescription(R.id.icon, ewd.listing.title);
} else {
// Content description for the entire row provided. Use it!
vb.setViewContentDescription(R.id.list_item,
ewd.listing.title + ". " + contentDescription);
vb.setViewContentDescription(R.id.text1, "."); // silence title
vb.setViewContentDescription(R.id.text2, "."); // silence body
}
Intent clickIntent = ewd.latestData.clickIntent();
if (clickIntent != null) {
vb.setViewClickFillInIntent(R.id.list_item,
WidgetClickProxyActivity.getFillIntent(clickIntent,
ewd.listing.componentName));
}
return vb.getRoot();
}
protected abstract ViewBuilder onCreateViewBuilder();
protected abstract void builderSetExpandedExtensionsAdapter(ViewBuilder builder,
int viewId, Intent onClickTemplateIntent);
public static class Options {
public static final int TARGET_HOME_SCREEN = 0;
public static final int TARGET_LOCK_SCREEN = 1;
public static final int TARGET_DAYDREAM = 2;
public int target;
public int minWidthDp;
public int minHeightDp;
// Only used by WidgetRenderer
public int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; // optional
// Only used by SimpleRenderer
public boolean newTaskOnClick;
public OnClickListener onClickListener;
public Intent clickIntentTemplate;
}
public static interface OnClickListener {
void onClick();
}
private static int[] LARGE_TIME_COMPONENT_IDS = {
R.id.large_time_component_1,
R.id.large_time_component_2,
R.id.large_time_component_3,
};
private static int[] SMALL_TIME_COMPONENT_IDS = {
R.id.small_time_component_1,
R.id.small_time_component_2,
R.id.small_time_component_3,
};
private static int[] DATE_COMPONENT_IDS = {
R.id.date_component_1,
R.id.date_component_2,
R.id.date_component_3,
};
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/render/DashClockRenderer.java | Java | asf20 | 17,172 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.render;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.widget.RemoteViews;
/**
* {@link ViewBuilder} implementation for {@link RemoteViews}.
*/
public class WidgetViewBuilder implements ViewBuilder {
private Context mContext;
private RemoteViews mRemoteViews;
public WidgetViewBuilder(Context context) {
mContext = context;
}
@Override
public void loadRootLayout(Object container, int layoutResId) {
mRemoteViews = new RemoteViews(mContext.getPackageName(), layoutResId);
}
@Override
public void useRoot(Object root) {
throw new UnsupportedOperationException("Can't reuse RemoteViews for WidgetViewBuilder.");
}
@Override
public Object inflateChildLayout(int layoutResId, int containerId) {
return new RemoteViews(mContext.getPackageName(), layoutResId);
}
@Override
public void setLinearLayoutGravity(int viewId, int gravity) {
mRemoteViews.setInt(viewId, "setGravity", gravity);
}
@Override
public void setViewPadding(int viewId, int left, int top, int right, int bottom) {
mRemoteViews.setViewPadding(viewId, left, top, right, bottom);
}
@Override
public void addView(int viewId, Object child) {
mRemoteViews.addView(viewId, (RemoteViews) child);
}
@Override
public void removeAllViews(int viewId) {
mRemoteViews.removeAllViews(viewId);
}
@Override
public void setViewVisibility(int viewId, int visibility) {
mRemoteViews.setViewVisibility(viewId, visibility);
}
@Override
public void setViewBackgroundColor(int viewId, int color) {
mRemoteViews.setInt(viewId, "setBackgroundColor", color);
}
@Override
public void setImageViewBitmap(int viewId, Bitmap bitmap) {
mRemoteViews.setImageViewBitmap(viewId, bitmap);
}
@Override
public void setViewContentDescription(int viewId, String contentDescription) {
mRemoteViews.setContentDescription(viewId, contentDescription);
}
@Override
public void setTextViewText(int viewId, CharSequence text) {
mRemoteViews.setTextViewText(viewId, text);
}
@Override
public void setTextViewMaxLines(int viewId, int maxLines) {
mRemoteViews.setInt(viewId, "setMaxLines", maxLines);
}
@Override
public void setTextViewSingleLine(int viewId, boolean singleLine) {
mRemoteViews.setBoolean(viewId, "setSingleLine", singleLine);
}
@Override
public void setTextViewTextSize(int viewId, int unit, float size) {
mRemoteViews.setTextViewTextSize(viewId, unit, size);
}
@Override
public void setViewClickIntent(int viewId, Intent clickIntent) {
mRemoteViews.setOnClickPendingIntent(viewId,
PendingIntent.getActivity(mContext, 0,
clickIntent, PendingIntent.FLAG_UPDATE_CURRENT));
}
@Override
public void setViewClickFillInIntent(int viewId, Intent fillIntent) {
mRemoteViews.setOnClickFillInIntent(viewId, fillIntent);
}
@Override
public Object getRoot() {
return mRemoteViews;
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/render/WidgetViewBuilder.java | Java | asf20 | 3,884 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.render;
import com.google.android.apps.dashclock.ExtensionHost;
import com.google.android.apps.dashclock.ExtensionManager;
import com.google.android.apps.dashclock.Utils;
import com.google.android.apps.dashclock.WidgetClickProxyActivity;
import com.google.android.apps.dashclock.WidgetProvider;
import net.nurik.roman.dashclock.R;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import java.util.ArrayList;
import java.util.List;
/**
* This is the service that provides the factory to be bound to the collection. Basically the
* {@link android.widget.Adapter} for expanded DashClock extensions.
*/
public class WidgetRemoteViewsFactoryService extends RemoteViewsService {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new WidgetRemoveViewsFactory(this);
}
/**
* This is the factory that will provide data to the collection widget. Behaves pretty much like
* an {@link android.widget.Adapter}.
*/
class WidgetRemoveViewsFactory implements RemoteViewsService.RemoteViewsFactory,
ExtensionManager.OnChangeListener {
private Handler mHandler = new Handler();
private Context mContext;
private ExtensionManager mExtensionManager;
private List<ExtensionManager.ExtensionWithData>
mVisibleExtensions = new ArrayList<ExtensionManager.ExtensionWithData>();
public WidgetRemoveViewsFactory(Context context) {
mContext = context;
mExtensionManager = ExtensionManager.getInstance(context);
mExtensionManager.addOnChangeListener(this);
onExtensionsChanged();
}
@Override
public void onExtensionsChanged() {
mHandler.removeCallbacks(mHandleExtensionsChanged);
mHandler.postDelayed(mHandleExtensionsChanged,
ExtensionHost.UPDATE_COLLAPSE_TIME_MILLIS);
}
private Runnable mHandleExtensionsChanged = new Runnable() {
@Override
public void run() {
mVisibleExtensions = mExtensionManager.getVisibleExtensionsWithData();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(
new ComponentName(mContext, WidgetProvider.class));
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds,
R.id.expanded_extensions);
}
};
public void onCreate() {
// Since we reload the cursor in onDataSetChanged() which gets called immediately after
// onCreate(), we do nothing here.
}
public void onDestroy() {
mExtensionManager.removeOnChangeListener(this);
}
public void onDataSetChanged() {
}
public int getViewTypeCount() {
return 1;
}
public long getItemId(int position) {
ExtensionManager.ExtensionWithData ewd = getItemAtProtected(position);
return (ewd != null) ? ewd.listing.componentName.hashCode() : 0;
}
public boolean hasStableIds() {
return true;
}
public int getCount() {
return mVisibleExtensions.size();
}
private ExtensionManager.ExtensionWithData getItemAtProtected(int position) {
return position < mVisibleExtensions.size() ? mVisibleExtensions.get(position) : null;
}
public RemoteViews getViewAt(int position) {
if (position >= mVisibleExtensions.size()) {
// TODO: trap this better
// See note on synchronization below.
return null;
}
WidgetRenderer renderer = new WidgetRenderer(mContext);
renderer.setOptions(new DashClockRenderer.Options());
ExtensionManager.ExtensionWithData ewd = getItemAtProtected(position);
return (RemoteViews) renderer.renderExpandedExtension(null, null, ewd);
}
public RemoteViews getLoadingView() {
return new RemoteViews(mContext.getPackageName(),
R.layout.widget_list_item_expanded_extension_loading);
}
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/render/WidgetRemoteViewsFactoryService.java | Java | asf20 | 5,258 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.render;
import net.nurik.roman.dashclock.R;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.RemoteViews;
/**
* Class in charge of rendering DashClock to {@link android.widget.RemoteViews},
* along with {@link WidgetRemoteViewsFactoryService}.
*/
public class WidgetRenderer extends DashClockRenderer {
protected WidgetRenderer(Context context) {
super(context);
}
@Override
protected ViewBuilder onCreateViewBuilder() {
return new WidgetViewBuilder(mContext);
}
/**
* Renders the DashClock UI to the given app widget IDs.
*/
public static void renderWidgets(Context context, int[] appWidgetIds) {
final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
WidgetRenderer renderer = new WidgetRenderer(context);
for (int appWidgetId : appWidgetIds) {
Options options = new Options();
options.appWidgetId = appWidgetId;
options.target = Options.TARGET_HOME_SCREEN;
options.minWidthDp= Integer.MAX_VALUE;
options.minHeightDp = Integer.MAX_VALUE;
Bundle widgetOptions = appWidgetManager.getAppWidgetOptions(appWidgetId);
if (widgetOptions != null) {
options.minWidthDp = widgetOptions
.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
options.minHeightDp = widgetOptions
.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
options.target = (AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD ==
widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY))
? Options.TARGET_LOCK_SCREEN : Options.TARGET_HOME_SCREEN;
}
renderer.setOptions(options);
appWidgetManager.updateAppWidget(appWidgetId,
(RemoteViews) renderer.renderWidget(null));
// During an update to an existing expanded widget, setRemoteAdapter does nothing,
// so we need to explicitly call notifyAppWidgetViewDataChanged to update data.
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId,
R.id.expanded_extensions);
}
}
@Override
protected void builderSetExpandedExtensionsAdapter(ViewBuilder vb, int viewId,
Intent clickTemplateIntent) {
Intent remoteAdapterIntent = new Intent(mContext, WidgetRemoteViewsFactoryService.class);
if (mOptions.appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
remoteAdapterIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
mOptions.appWidgetId);
}
// TODO: is this setData call really necessary?
remoteAdapterIntent.setData(Uri.parse(remoteAdapterIntent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews root = (RemoteViews) vb.getRoot();
root.setRemoteAdapter(viewId, remoteAdapterIntent);
root.setPendingIntentTemplate(viewId,
PendingIntent.getActivity(mContext, 0,
clickTemplateIntent, PendingIntent.FLAG_UPDATE_CURRENT));
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/render/WidgetRenderer.java | Java | asf20 | 4,024 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.render;
import android.content.Intent;
import android.graphics.Bitmap;
/**
* Abstraction for building up view hierarchies, using either standard framework views or
* RemoteViews.
*/
public interface ViewBuilder {
void loadRootLayout(Object container, int layoutResId);
void useRoot(Object root);
Object inflateChildLayout(int layoutResId, int containerId);
void setViewClickIntent(int viewId, Intent clickIntent);
void setViewClickFillInIntent(int viewId, Intent fillIntent);
void setViewVisibility(int viewId, int visibility);
void setViewPadding(int viewId, int left, int top, int right, int bottom);
void setViewContentDescription(int viewId, String contentDescription);
void setViewBackgroundColor(int viewId, int color);
void setTextViewText(int viewId, CharSequence text);
void setTextViewTextSize(int viewId, int unit, float size);
void setTextViewSingleLine(int viewId, boolean singleLine);
void setTextViewMaxLines(int viewId, int maxLines);
void setImageViewBitmap(int viewId, Bitmap bitmap);
void setLinearLayoutGravity(int viewId, int gravity);
void addView(int viewId, Object child);
void removeAllViews(int viewId);
Object getRoot();
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/render/ViewBuilder.java | Java | asf20 | 1,865 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.render;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* {@link ViewBuilder} implementation for standard framework views.
*/
public class SimpleViewBuilder implements ViewBuilder {
private Context mContext;
private View mRootView;
private Callbacks mCallbacks;
public SimpleViewBuilder(Context context, Callbacks callbacks) {
mContext = context;
mCallbacks = callbacks;
}
@Override
public void useRoot(Object root) {
mRootView = (View) root;
}
@Override
public void loadRootLayout(Object container, int layoutResId) {
mRootView = LayoutInflater.from(mContext).inflate(layoutResId,
(ViewGroup) container, false);
}
@Override
public Object inflateChildLayout(int layoutResId, int containerId) {
return LayoutInflater.from(mContext).inflate(layoutResId,
(containerId != 0) ? (ViewGroup) mRootView.findViewById(containerId) : null, false);
}
@Override
public void setImageViewBitmap(int viewId, Bitmap bitmap) {
((ImageView) mRootView.findViewById(viewId)).setImageBitmap(bitmap);
}
@Override
public void setViewContentDescription(int viewId, String contentDescription) {
mRootView.findViewById(viewId).setContentDescription(contentDescription);
}
@Override
public void setTextViewText(int viewId, CharSequence text) {
((TextView) mRootView.findViewById(viewId)).setText(text);
}
@Override
public void setTextViewMaxLines(int viewId, int maxLines) {
((TextView) mRootView.findViewById(viewId)).setMaxLines(maxLines);
}
@Override
public void setTextViewSingleLine(int viewId, boolean singleLine) {
((TextView) mRootView.findViewById(viewId)).setSingleLine(singleLine);
}
@Override
public void setTextViewTextSize(int viewId, int unit, float size) {
((TextView) mRootView.findViewById(viewId)).setTextSize(unit, size);
}
@Override
public void setLinearLayoutGravity(int viewId, int gravity) {
((LinearLayout) mRootView.findViewById(viewId)).setGravity(gravity);
}
@Override
public void setViewPadding(int viewId, int left, int top, int right, int bottom) {
mRootView.findViewById(viewId).setPadding(left, top, right, bottom);
}
@Override
public void addView(int viewId, Object child) {
((ViewGroup) mRootView.findViewById(viewId)).addView((View) child);
}
@Override
public void removeAllViews(int viewId) {
((ViewGroup) mRootView.findViewById(viewId)).removeAllViews();
}
@Override
public void setViewVisibility(int viewId, int visibility) {
View v = mRootView.findViewById(viewId);
if (v != null) {
v.setVisibility(visibility);
}
}
@Override
public void setViewBackgroundColor(int viewId, int color) {
mRootView.findViewById(viewId).setBackgroundColor(color);
}
@Override
public void setViewClickIntent(final int viewId, final Intent clickIntent) {
if (mCallbacks != null) {
mCallbacks.onModifyClickIntent(clickIntent);
}
mRootView.findViewById(viewId).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mContext.startActivity(clickIntent);
mCallbacks.onClickIntentCalled(viewId);
}
});
}
@Override
public void setViewClickFillInIntent(final int viewId, final Intent fillIntent) {
View targetView = mRootView.findViewById(viewId);
targetView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mCallbacks == null) {
return;
}
Intent intent = mCallbacks.onGetClickIntentTemplate();
intent.fillIn(fillIntent, 0);
mContext.startActivity(intent);
mCallbacks.onClickIntentCalled(viewId);
}
});
}
@Override
public Object getRoot() {
return mRootView;
}
public static interface Callbacks {
Intent onGetClickIntentTemplate();
void onModifyClickIntent(Intent clickIntent);
void onClickIntentCalled(int viewId);
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/render/SimpleViewBuilder.java | Java | asf20 | 5,293 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.render;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.AbsListView;
/**
* Class in charge of rendering DashClock to a normal view hierarchy (i.e. not RemoteViews).
*/
public class SimpleRenderer extends DashClockRenderer implements SimpleViewBuilder.Callbacks {
public SimpleRenderer(Context context) {
super(context);
}
@Override
protected ViewBuilder onCreateViewBuilder() {
return new SimpleViewBuilder(mContext, this);
}
public SimpleViewBuilder createSimpleViewBuilder() {
return (SimpleViewBuilder) onCreateViewBuilder();
}
@Override
protected void builderSetExpandedExtensionsAdapter(ViewBuilder builder,
int viewId, Intent clickTemplateIntent) {
View root = (View) builder.getRoot();
// TODO: create a copy of the options object with the clickIntentTemplate set.
mOptions.clickIntentTemplate = clickTemplateIntent;
// AbsListView listView = (AbsListView) root.findViewById(viewId);
// listView.setAdapter(new SimpleExpandedExtensionsAdapter(mContext, this, mOptions));
}
@Override
public Intent onGetClickIntentTemplate() {
return mOptions.clickIntentTemplate;
}
@Override
public void onModifyClickIntent(Intent clickIntent) {
if (mOptions.newTaskOnClick) {
clickIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
@Override
public void onClickIntentCalled(int viewId) {
mOptions.onClickListener.onClick();
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/render/SimpleRenderer.java | Java | asf20 | 2,227 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.app.backup.BackupManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.android.apps.dashclock.LogUtils.LOGD;
import static com.google.android.apps.dashclock.LogUtils.LOGE;
import static com.google.android.apps.dashclock.LogUtils.LOGW;
/**
* A singleton class in charge of extension registration, activation (change in user-specified
* 'active' extensions), and data caching.
*/
public class ExtensionManager {
private static final String TAG = LogUtils.makeLogTag(ExtensionManager.class);
private static final String PREF_ACTIVE_EXTENSIONS = "active_extensions";
private final Context mApplicationContext;
private final List<ExtensionWithData> mActiveExtensions = new ArrayList<ExtensionWithData>();
private Map<ComponentName, ExtensionWithData> mExtensionInfoMap
= new HashMap<ComponentName, ExtensionWithData>();
private List<OnChangeListener> mOnChangeListeners = new ArrayList<OnChangeListener>();
private SharedPreferences mDefaultPreferences;
private SharedPreferences mValuesPreferences;
private Handler mMainThreadHandler = new Handler(Looper.getMainLooper());
private static ExtensionManager sInstance;
public static ExtensionManager getInstance(Context context) {
if (sInstance == null) {
sInstance = new ExtensionManager(context);
}
return sInstance;
}
private ExtensionManager(Context context) {
mApplicationContext = context.getApplicationContext();
mDefaultPreferences = PreferenceManager.getDefaultSharedPreferences(mApplicationContext);
mValuesPreferences = mApplicationContext.getSharedPreferences("extension_data", 0);
loadActiveExtensionList();
}
/**
* De-activates active extensions that are unsupported or are no longer installed.
*/
public boolean cleanupExtensions() {
Set<ComponentName> availableExtensions = new HashSet<ComponentName>();
for (ExtensionListing listing : getAvailableExtensions()) {
// Ensure the extension protocol version is supported. If it isn't, don't allow its use.
if (!ExtensionHost.supportsProtocolVersion(listing.protocolVersion)) {
LOGW(TAG, "Extension '" + listing.title + "' using unsupported protocol version "
+ listing.protocolVersion + ".");
continue;
}
availableExtensions.add(listing.componentName);
}
boolean cleanupRequired = false;
ArrayList<ComponentName> newActiveExtensions = new ArrayList<ComponentName>();
synchronized (mActiveExtensions) {
for (ExtensionWithData ewd : mActiveExtensions) {
if (availableExtensions.contains(ewd.listing.componentName)) {
newActiveExtensions.add(ewd.listing.componentName);
} else {
cleanupRequired = true;
}
}
}
if (cleanupRequired) {
setActiveExtensions(newActiveExtensions);
return true;
}
return false;
}
private void loadActiveExtensionList() {
List<ComponentName> activeExtensions = new ArrayList<ComponentName>();
String extensions = mDefaultPreferences.getString(PREF_ACTIVE_EXTENSIONS, "");
String[] componentNameStrings = extensions.split(",");
for (String componentNameString : componentNameStrings) {
if (TextUtils.isEmpty(componentNameString)) {
continue;
}
activeExtensions.add(ComponentName.unflattenFromString(componentNameString));
}
setActiveExtensions(activeExtensions, false);
}
private void saveActiveExtensionList() {
StringBuilder sb = new StringBuilder();
synchronized (mActiveExtensions) {
for (ExtensionWithData ci : mActiveExtensions) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(ci.listing.componentName.flattenToString());
}
}
mDefaultPreferences.edit()
.putString(PREF_ACTIVE_EXTENSIONS, sb.toString())
.commit();
new BackupManager(mApplicationContext).dataChanged();
}
/**
* Replaces the set of active extensions with the given list.
*/
public void setActiveExtensions(List<ComponentName> extensions) {
setActiveExtensions(extensions, true);
}
private void setActiveExtensions(List<ComponentName> extensionNames, boolean saveAndNotify) {
Map<ComponentName, ExtensionListing> listings
= new HashMap<ComponentName, ExtensionListing>();
for (ExtensionListing listing : getAvailableExtensions()) {
listings.put(listing.componentName, listing);
}
List<ComponentName> activeExtensionNames = getActiveExtensionNames();
if (activeExtensionNames.equals(extensionNames)) {
LOGD(TAG, "No change to list of active extensions.");
return;
}
// Clear cached data for any no-longer-active extensions.
for (ComponentName cn : activeExtensionNames) {
if (!extensionNames.contains(cn)) {
destroyExtensionData(cn);
}
}
// Set the new list of active extensions, loading cached data if necessary.
List<ExtensionWithData> newActiveExtensions = new ArrayList<ExtensionWithData>();
for (ComponentName cn : extensionNames) {
if (mExtensionInfoMap.containsKey(cn)) {
newActiveExtensions.add(mExtensionInfoMap.get(cn));
} else {
ExtensionWithData ewd = new ExtensionWithData();
ewd.listing = listings.get(cn);
if (ewd.listing == null) {
ewd.listing = new ExtensionListing();
ewd.listing.componentName = cn;
}
ewd.latestData = deserializeExtensionData(ewd.listing.componentName);
newActiveExtensions.add(ewd);
}
}
mExtensionInfoMap.clear();
for (ExtensionWithData ewd : newActiveExtensions) {
mExtensionInfoMap.put(ewd.listing.componentName, ewd);
}
synchronized (mActiveExtensions) {
mActiveExtensions.clear();
mActiveExtensions.addAll(newActiveExtensions);
}
if (saveAndNotify) {
saveActiveExtensionList();
notifyOnChangeListeners();
}
}
/**
* Updates and caches the user-visible data for a given extension.
*/
public boolean updateExtensionData(ComponentName cn, ExtensionData data) {
data.clean();
ExtensionWithData ewd = mExtensionInfoMap.get(cn);
if (ewd != null && !ExtensionData.equals(ewd.latestData, data)) {
ewd.latestData = data;
serializeExtensionData(ewd.listing.componentName, data);
notifyOnChangeListeners();
return true;
}
return false;
}
private ExtensionData deserializeExtensionData(ComponentName componentName) {
ExtensionData extensionData = new ExtensionData();
String val = mValuesPreferences.getString(componentName.flattenToString(), "");
if (!TextUtils.isEmpty(val)) {
try {
extensionData.deserialize((JSONObject) new JSONTokener(val).nextValue());
} catch (JSONException e) {
LOGE(TAG, "Error loading extension data cache for " + componentName + ".",
e);
}
}
return extensionData;
}
private void serializeExtensionData(ComponentName componentName, ExtensionData extensionData) {
try {
mValuesPreferences.edit()
.putString(componentName.flattenToString(),
extensionData.serialize().toString())
.commit();
} catch (JSONException e) {
LOGE(TAG, "Error storing extension data cache for " + componentName + ".", e);
}
}
private void destroyExtensionData(ComponentName componentName) {
mValuesPreferences.edit()
.remove(componentName.flattenToString())
.commit();
}
public List<ExtensionWithData> getActiveExtensionsWithData() {
ArrayList<ExtensionWithData> activeExtensions;
synchronized (mActiveExtensions) {
activeExtensions = new ArrayList<ExtensionWithData>(mActiveExtensions);
}
return activeExtensions;
}
public List<ExtensionWithData> getVisibleExtensionsWithData() {
ArrayList<ExtensionWithData> visibleExtensions = new ArrayList<ExtensionWithData>();
synchronized (mActiveExtensions) {
for (ExtensionManager.ExtensionWithData ewd : mActiveExtensions) {
if (ewd.latestData.visible()) {
visibleExtensions.add(ewd);
}
}
}
return visibleExtensions;
}
public List<ComponentName> getActiveExtensionNames() {
List<ComponentName> list = new ArrayList<ComponentName>();
for (ExtensionWithData ci : mActiveExtensions) {
list.add(ci.listing.componentName);
}
return list;
}
/**
* Returns a listing of all available (installed) extensions.
*/
public List<ExtensionListing> getAvailableExtensions() {
List<ExtensionListing> availableExtensions = new ArrayList<ExtensionListing>();
PackageManager pm = mApplicationContext.getPackageManager();
List<ResolveInfo> resolveInfos = pm.queryIntentServices(
new Intent(DashClockExtension.ACTION_EXTENSION), PackageManager.GET_META_DATA);
for (ResolveInfo resolveInfo : resolveInfos) {
ExtensionListing listing = new ExtensionListing();
listing.componentName = new ComponentName(resolveInfo.serviceInfo.packageName,
resolveInfo.serviceInfo.name);
listing.title = resolveInfo.loadLabel(pm).toString();
Bundle metaData = resolveInfo.serviceInfo.metaData;
if (metaData != null) {
listing.protocolVersion = metaData.getInt("protocolVersion");
listing.worldReadable = metaData.getBoolean("worldReadable", false);
listing.description = metaData.getString("description");
String settingsActivity = metaData.getString("settingsActivity");
if (!TextUtils.isEmpty(settingsActivity)) {
listing.settingsActivity = ComponentName.unflattenFromString(
resolveInfo.serviceInfo.packageName + "/" + settingsActivity);
}
}
listing.icon = resolveInfo.loadIcon(pm);
availableExtensions.add(listing);
}
return availableExtensions;
}
/**
* Registers a listener to be triggered when either the list of active extensions changes or an
* extension's data changes.
*/
public void addOnChangeListener(OnChangeListener onChangeListener) {
mOnChangeListeners.add(onChangeListener);
}
/**
* Removes a listener previously registered with {@link #addOnChangeListener}.
*/
public void removeOnChangeListener(OnChangeListener onChangeListener) {
mOnChangeListeners.remove(onChangeListener);
}
private void notifyOnChangeListeners() {
mMainThreadHandler.post(new Runnable() {
@Override
public void run() {
for (OnChangeListener listener : mOnChangeListeners) {
listener.onExtensionsChanged();
}
}
});
}
public static interface OnChangeListener {
void onExtensionsChanged();
}
public static class ExtensionWithData {
public ExtensionListing listing;
public ExtensionData latestData;
}
public static class ExtensionListing {
public ComponentName componentName;
public int protocolVersion;
public boolean worldReadable;
public String title;
public String description;
public Drawable icon;
public ComponentName settingsActivity;
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/ExtensionManager.java | Java | asf20 | 13,796 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock;
import net.nurik.roman.dashclock.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
/**
* Helper class for showing about dialogs and what not.
*/
public class HelpUtils {
public static void showAboutDialog(Activity activity) {
FragmentManager fm = activity.getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_about");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new AboutDialog().show(ft, "dialog_about");
}
public static class AboutDialog extends DialogFragment {
private static final String VERSION_UNAVAILABLE = "N/A";
public AboutDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get app version
PackageManager pm = getActivity().getPackageManager();
String packageName = getActivity().getPackageName();
String versionName;
try {
PackageInfo info = pm.getPackageInfo(packageName, 0);
versionName = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
versionName = VERSION_UNAVAILABLE;
}
// Build the about body view and append the link to see OSS licenses
LayoutInflater layoutInflater = getActivity().getLayoutInflater();
View rootView = layoutInflater.inflate(R.layout.dialog_about, null);
TextView nameAndVersionView = (TextView) rootView.findViewById(
R.id.app_name_and_version);
nameAndVersionView.setText(Html.fromHtml(
getString(R.string.app_name_and_version, versionName)));
TextView aboutBodyView = (TextView) rootView.findViewById(R.id.about_body);
aboutBodyView.setText(Html.fromHtml(getString(R.string.about_body)));
aboutBodyView.setMovementMethod(new LinkMovementMethod());
return new AlertDialog.Builder(getActivity())
.setView(rootView)
.setPositiveButton(R.string.close,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/HelpUtils.java | Java | asf20 | 3,665 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock;
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
/**
* The backup agent for DashClock. See the developer guide documentation for <a
* href="http://developer.android.com/guide/topics/data/backup.html">Data Backup</a> for details.
*/
public class BackupAgent extends BackupAgentHelper {
private static final String PREFS_BACKUP_KEY = "prefs";
// Allocate a helper and add it to the backup agent
@Override
public void onCreate() {
// Compute the default preferences filename.
String defaultPrefsFilename = getPackageName() + "_preferences";
addHelper(PREFS_BACKUP_KEY,
new SharedPreferencesBackupHelper(this, defaultPrefsFilename));
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/BackupAgent.java | Java | asf20 | 1,392 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.OpenableColumns;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import static com.google.android.apps.dashclock.LogUtils.makeLogTag;
/**
* Content provider for exposing log files as attachments.
*/
public class LogAttachmentProvider extends ContentProvider {
private static final String TAG = makeLogTag(LogAttachmentProvider.class);
static final String AUTHORITY = "com.google.android.apps.dashclock.logs";
@Override
public boolean onCreate() {
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String orderBy) {
// Ensure logfile exists
List<String> pathSegments = uri.getPathSegments();
String fileName = pathSegments.get(0);
File logFile = getContext().getCacheDir();
if (logFile == null) {
LogUtils.LOGE(TAG, "No cache dir.");
return null;
}
logFile = new File(new File(logFile, "logs"), fileName);
if (!logFile.exists()) {
LogUtils.LOGE(TAG, "Requested log file doesn't exist.");
return null;
}
// Create matrix cursor
if (projection == null) {
projection = new String[]{
"_data",
OpenableColumns.DISPLAY_NAME,
OpenableColumns.SIZE,
};
}
MatrixCursor matrixCursor = new MatrixCursor(projection, 1);
Object[] row = new Object[projection.length];
for (int col = 0; col < projection.length; col++) {
if ("_data".equals(projection[col])) {
row[col] = logFile.getAbsolutePath();
} else if (OpenableColumns.DISPLAY_NAME.equals(projection[col])) {
row[col] = fileName;
} else if (OpenableColumns.SIZE.equals(projection[col])) {
row[col] = logFile.length();
}
}
matrixCursor.addRow(row);
return matrixCursor;
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
return openFileHelper(uri, "r");
}
@Override
public String getType(Uri uri) {
return "text/plain";
}
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException("insert not supported");
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException("delete not supported");
}
@Override
public int update(Uri uri, ContentValues contentValues, String selection,
String[] selectionArgs) {
throw new UnsupportedOperationException("update not supported");
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/LogAttachmentProvider.java | Java | asf20 | 3,695 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.nextalarm;
import com.google.android.apps.dashclock.LogUtils;
import com.google.android.apps.dashclock.Utils;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import net.nurik.roman.dashclock.R;
import android.provider.Settings;
import android.text.TextUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Next alarm extension.
*/
public class NextAlarmExtension extends DashClockExtension {
private static final String TAG = LogUtils.makeLogTag(NextAlarmExtension.class);
private static Pattern sDigitPattern = Pattern.compile("\\s[0-9]");
@Override
protected void onInitialize(boolean isReconnect) {
super.onInitialize(isReconnect);
if (!isReconnect) {
addWatchContentUris(new String[]{
Settings.System.getUriFor(Settings.System.NEXT_ALARM_FORMATTED).toString()
});
}
}
@Override
protected void onUpdateData(int reason) {
String nextAlarm = Settings.System.getString(getContentResolver(),
Settings.System.NEXT_ALARM_FORMATTED);
if (!TextUtils.isEmpty(nextAlarm)) {
Matcher m = sDigitPattern.matcher(nextAlarm);
if (m.find() && m.start() > 0) {
nextAlarm = nextAlarm.substring(0, m.start()) + "\n"
+ nextAlarm.substring(m.start() + 1); // +1 to skip whitespace
}
}
publishUpdate(new ExtensionData()
.visible(!TextUtils.isEmpty(nextAlarm))
.icon(R.drawable.ic_extension_next_alarm)
.status(nextAlarm)
.clickIntent(Utils.getDefaultAlarmsIntent(this)));
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/nextalarm/NextAlarmExtension.java | Java | asf20 | 2,391 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock;
import net.nurik.roman.dashclock.BuildConfig;
import net.nurik.roman.dashclock.R;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* Helper methods that make logging more consistent throughout the app.
*/
public class LogUtils {
private static final String TAG = makeLogTag(LogUtils.class);
private static final String LOG_PREFIX = "dashclock_";
private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
private static final int MAX_LOG_TAG_LENGTH = 23;
private LogUtils() {
}
public static String makeLogTag(String str) {
if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
}
return LOG_PREFIX + str;
}
/**
* WARNING: Don't use this when obfuscating class names with Proguard!
*/
public static String makeLogTag(Class cls) {
return makeLogTag(cls.getSimpleName());
}
public static void LOGD(final String tag, String message) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG || Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message);
}
}
public static void LOGD(final String tag, String message, Throwable cause) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG || Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message, cause);
}
}
public static void LOGV(final String tag, String message) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
Log.v(tag, message);
}
}
public static void LOGV(final String tag, String message, Throwable cause) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
Log.v(tag, message, cause);
}
}
public static void LOGI(final String tag, String message) {
Log.i(tag, message);
}
public static void LOGI(final String tag, String message, Throwable cause) {
Log.i(tag, message, cause);
}
public static void LOGW(final String tag, String message) {
Log.w(tag, message);
}
public static void LOGW(final String tag, String message, Throwable cause) {
Log.w(tag, message, cause);
}
public static void LOGE(final String tag, String message) {
Log.e(tag, message);
}
public static void LOGE(final String tag, String message, Throwable cause) {
Log.e(tag, message, cause);
}
/**
* Only for use with debug versions of the app!
*/
public static void sendDebugLog(Context context) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG) {
StringBuilder log = new StringBuilder();
// Append app version name
PackageManager pm = context.getPackageManager();
String packageName = context.getPackageName();
String versionName;
try {
PackageInfo info = pm.getPackageInfo(packageName, 0);
versionName = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
versionName = "??";
}
log.append("App version:\n").append(versionName).append("\n\n");
// Append device build fingerprint
log.append("Device fingerprint:\n").append(Build.FINGERPRINT).append("\n\n");
try {
// Append app's logs
String[] logcatCmd = new String[]{ "logcat", "-v", "threadtime", "-d", };
Process process = Runtime.getRuntime().exec(logcatCmd);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
log.append("\n");
}
// Write everything to a file
File logsDir = context.getCacheDir();
if (logsDir == null) {
throw new IOException("Cache directory inaccessible");
}
logsDir = new File(logsDir, "logs");
deleteRecursive(logsDir);
logsDir.mkdirs();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmm");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String fileName = "DashClock_log_" + sdf.format(new Date()) + ".txt";
File logFile = new File(logsDir, fileName);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(logFile)));
writer.write(log.toString());
writer.close();
// Send the file
Intent sendIntent = new Intent(Intent.ACTION_SENDTO)
.setData(Uri.parse("mailto:dashclock+support@gmail.com"))
.putExtra(Intent.EXTRA_SUBJECT, "DashClock debug log")
.putExtra(Intent.EXTRA_STREAM, Uri.parse(
"content://" + LogAttachmentProvider.AUTHORITY + "/" + fileName));
context.startActivity(Intent.createChooser(sendIntent,
context.getString(R.string.send_logs_chooser_title)));
} catch (IOException e) {
LOGE(TAG, "Error accessing or sending app's logs.", e);
Toast.makeText(context, "Error accessing or sending app's logs.",
Toast.LENGTH_SHORT).show();
}
}
}
private static void deleteRecursive(File file) {
if (file != null) {
File[] children = file.listFiles();
if (children != null && children.length > 0) {
for (File child : children) {
deleteRecursive(child);
}
} else {
file.delete();
}
}
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/LogUtils.java | Java | asf20 | 7,429 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.configuration;
import com.google.android.apps.dashclock.ui.SimplePagedTabsHelper;
import net.nurik.roman.dashclock.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.Preference;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* A preference that allows the user to choose an application or shortcut.
*/
public class AppChooserPreference extends Preference {
private boolean mAllowUseDefault = false;
public AppChooserPreference(Context context, AttributeSet attrs) {
super(context, attrs);
initAttrs(attrs, 0);
}
public AppChooserPreference(Context context) {
super(context);
initAttrs(null, 0);
}
public AppChooserPreference(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
initAttrs(attrs, defStyle);
}
private void initAttrs(AttributeSet attrs, int defStyle) {
TypedArray a = getContext().getTheme().obtainStyledAttributes(
attrs, R.styleable.AppChooserPreference, defStyle, defStyle);
try {
mAllowUseDefault = a.getBoolean(R.styleable.AppChooserPreference_allowUseDefault, true);
} finally {
a.recycle();
}
}
public void setIntentValue(Intent intent) {
setValue(intent == null ? "" : intent.toUri(Intent.URI_INTENT_SCHEME));
}
public void setValue(String value) {
if (callChangeListener(value)) {
persistString(value);
notifyChanged();
}
}
public static Intent getIntentValue(String value, Intent defaultIntent) {
try {
if (TextUtils.isEmpty(value)) {
return defaultIntent;
}
return Intent.parseUri(value, Intent.URI_INTENT_SCHEME);
} catch (URISyntaxException e) {
return defaultIntent;
}
}
public static CharSequence getDisplayValue(Context context, String value) {
if (TextUtils.isEmpty(value)) {
return context.getString(R.string.pref_shortcut_default);
}
Intent intent;
try {
intent = Intent.parseUri(value, Intent.URI_INTENT_SCHEME);
} catch (URISyntaxException e) {
return context.getString(R.string.pref_shortcut_default);
}
PackageManager pm = context.getPackageManager();
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
if (resolveInfos.size() == 0) {
return null;
}
StringBuilder label = new StringBuilder();
label.append(resolveInfos.get(0).loadLabel(pm));
if (intent.getData() != null && intent.getData().getScheme() != null &&
intent.getData().getScheme().startsWith("http")) {
label.append(": ").append(intent.getDataString());
}
return label;
}
@Override
protected void onClick() {
super.onClick();
AppChooserDialogFragment fragment = AppChooserDialogFragment.newInstance();
fragment.setPreference(this);
Activity activity = (Activity) getContext();
activity.getFragmentManager().beginTransaction()
.add(fragment, getFragmentTag())
.commit();
}
@Override
protected void onAttachedToActivity() {
super.onAttachedToActivity();
Activity activity = (Activity) getContext();
AppChooserDialogFragment fragment = (AppChooserDialogFragment) activity
.getFragmentManager().findFragmentByTag(getFragmentTag());
if (fragment != null) {
// re-bind preference to fragment
fragment.setPreference(this);
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
setValue(restoreValue ? getPersistedString("") : (String) defaultValue);
}
public String getFragmentTag() {
return "app_chooser_" + getKey();
}
public static class AppChooserDialogFragment extends DialogFragment {
public static int REQUEST_CREATE_SHORTCUT = 1;
private AppChooserPreference mPreference;
private ActivityListAdapter mAppsAdapter;
private ActivityListAdapter mShortcutsAdapter;
private ListView mAppsList;
private ListView mShortcutsList;
public AppChooserDialogFragment() {
}
public static AppChooserDialogFragment newInstance() {
return new AppChooserDialogFragment();
}
public void setPreference(AppChooserPreference preference) {
mPreference = preference;
tryBindLists();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
tryBindLists();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Force Holo Light since ?android:actionBarXX would use dark action bar
Context layoutContext = new ContextThemeWrapper(getActivity(),
android.R.style.Theme_Holo_Light);
LayoutInflater layoutInflater = LayoutInflater.from(layoutContext);
View rootView = layoutInflater.inflate(R.layout.dialog_app_chooser, null);
final ViewGroup tabWidget = (ViewGroup) rootView.findViewById(android.R.id.tabs);
final ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setPageMargin((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16,
getResources().getDisplayMetrics()));
SimplePagedTabsHelper helper = new SimplePagedTabsHelper(layoutContext,
tabWidget, pager);
helper.addTab(R.string.title_apps, R.id.apps_list);
helper.addTab(R.string.title_shortcuts, R.id.shortcuts_list);
// Set up apps
mAppsList = (ListView) rootView.findViewById(R.id.apps_list);
mAppsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long itemId) {
Intent intent = mAppsAdapter.getIntent(position);
if (intent != null) {
intent = Intent.makeMainActivity(intent.getComponent());
}
mPreference.setIntentValue(intent);
dismiss();
}
});
// Set up shortcuts
mShortcutsList = (ListView) rootView.findViewById(R.id.shortcuts_list);
mShortcutsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long itemId) {
startActivityForResult(mShortcutsAdapter.getIntent(position),
REQUEST_CREATE_SHORTCUT);
}
});
tryBindLists();
return new AlertDialog.Builder(getActivity())
.setView(rootView)
.create();
}
private void tryBindLists() {
if (mPreference == null) {
return;
}
if (isAdded() && mAppsAdapter == null && mShortcutsAdapter == null) {
mAppsAdapter = new ActivityListAdapter(
new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER),
mPreference.mAllowUseDefault);
mShortcutsAdapter = new ActivityListAdapter(
new Intent(Intent.ACTION_CREATE_SHORTCUT)
.addCategory(Intent.CATEGORY_DEFAULT),
false);
}
if (mAppsAdapter != null && mAppsList != null
&& mShortcutsAdapter != null && mShortcutsList != null) {
mAppsList.setAdapter(mAppsAdapter);
mShortcutsList.setAdapter(mShortcutsAdapter);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CREATE_SHORTCUT && resultCode == Activity.RESULT_OK) {
mPreference.setIntentValue(
(Intent) data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT));
dismiss();
}
}
static class ActivityInfo {
CharSequence label;
Drawable icon;
ComponentName componentName;
}
private class ActivityListAdapter extends BaseAdapter {
private Intent mQueryIntent;
private PackageManager mPackageManager;
private List<ActivityInfo> mInfos;
private boolean mAllowUseDefault;
private ActivityListAdapter(Intent queryIntent, boolean allowUseDefault) {
mQueryIntent = queryIntent;
mPackageManager = getActivity().getPackageManager();
mAllowUseDefault = allowUseDefault;
mInfos = new ArrayList<ActivityInfo>();
List<ResolveInfo> resolveInfos = mPackageManager.queryIntentActivities(queryIntent,
0);
for (ResolveInfo ri : resolveInfos) {
ActivityInfo ai = new ActivityInfo();
ai.icon = ri.loadIcon(mPackageManager);
ai.label = ri.loadLabel(mPackageManager);
ai.componentName = new ComponentName(ri.activityInfo.packageName,
ri.activityInfo.name);
mInfos.add(ai);
}
Collections.sort(mInfos, new Comparator<ActivityInfo>() {
@Override
public int compare(ActivityInfo activityInfo, ActivityInfo activityInfo2) {
return activityInfo.label.toString().compareTo(
activityInfo2.label.toString());
}
});
}
@Override
public int getCount() {
return mInfos.size() + (mAllowUseDefault ? 1 : 0);
}
@Override
public Object getItem(int position) {
if (mAllowUseDefault && position == 0) {
return null;
}
return mInfos.get(position - (mAllowUseDefault ? 1 : 0));
}
public Intent getIntent(int position) {
if (mAllowUseDefault && position == 0) {
return null;
}
return new Intent(mQueryIntent)
.setComponent(mInfos.get(position - (mAllowUseDefault ? 1 : 0))
.componentName);
}
@Override
public long getItemId(int position) {
if (mAllowUseDefault && position == 0) {
return -1;
}
return mInfos.get(position - (mAllowUseDefault ? 1 : 0)).componentName.hashCode();
}
@Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
convertView = LayoutInflater.from(getActivity())
.inflate(R.layout.list_item_intent, container, false);
}
if (mAllowUseDefault && position == 0) {
((TextView) convertView.findViewById(android.R.id.text1))
.setText(getString(R.string.pref_shortcut_default));
((ImageView) convertView.findViewById(android.R.id.icon))
.setImageDrawable(null);
} else {
ActivityInfo ai = mInfos.get(position - (mAllowUseDefault ? 1 : 0));
((TextView) convertView.findViewById(android.R.id.text1))
.setText(ai.label);
((ImageView) convertView.findViewById(android.R.id.icon))
.setImageDrawable(ai.icon);
}
return convertView;
}
}
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/configuration/AppChooserPreference.java | Java | asf20 | 14,171 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.configuration;
import android.content.Context;
import android.preference.PreferenceManager;
/**
* Helper class for working with DashClock appearance settings.
*/
public class AppearanceConfig {
static final String COMPONENT_TIME = "time";
static final String COMPONENT_DATE = "date";
static final String PREF_STYLE_TIME = "pref_style_time";
static final String PREF_STYLE_DATE = "pref_style_date";
static final String PREF_HOMESCREEN_BACKGROUND_OPACITY = "pref_homescreen_background_opacity";
static final String PREF_AGGRESSIVE_CENTERING = "pref_aggressive_centering";
static String[] TIME_STYLE_NAMES = new String[]{
"default",
"light",
"alpha",
"stock",
"condensed",
"big_small",
"analog1",
"analog2",
};
static String[] DATE_STYLE_NAMES = new String[]{
"default",
"simple",
"condensed_bold",
};
public static int getCurrentTimeLayout(Context context) {
String currentTimeStyleName = PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_STYLE_TIME, TIME_STYLE_NAMES[0]);
return getLayoutByStyleName(context, COMPONENT_TIME, currentTimeStyleName);
}
public static int getCurrentDateLayout(Context context) {
String currentDateStyleName = PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_STYLE_DATE, DATE_STYLE_NAMES[0]);
return getLayoutByStyleName(context, COMPONENT_DATE, currentDateStyleName);
}
public static int getLayoutByStyleName(Context context, String component, String name) {
return context.getResources().getIdentifier(
"widget_include_" + component + "_style_" + name,
"layout", context.getPackageName());
}
public static boolean isAggressiveCenteringEnabled(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(PREF_AGGRESSIVE_CENTERING, false);
}
public static int getHomescreenBackgroundColor(Context context) {
int opacity = 50;
try {
opacity = Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_HOMESCREEN_BACKGROUND_OPACITY, "50"));
} catch (NumberFormatException ignored) {
}
if (opacity == 100) {
return 0xff000000;
} else {
return (opacity * 256 / 100) << 24;
}
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/configuration/AppearanceConfig.java | Java | asf20 | 3,212 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.configuration;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.text.TextUtils;
import android.view.MenuItem;
import com.google.android.apps.dashclock.weather.WeatherLocationPreference;
/**
* A base activity for extension configuration activities.
*/
public abstract class BaseSettingsActivity extends PreferenceActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setupSimplePreferencesScreen();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
// TODO: if the previous activity on the stack isn't a ConfigurationActivity,
// launch it.
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
protected abstract void setupSimplePreferencesScreen();
/**
* A preference value change listener that updates the preference's summary to reflect its new
* value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener
= new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? (listPreference.getEntries()[index])
.toString().replaceAll("%", "%%")
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
//preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else if (preference instanceof AppChooserPreference) {
preference.setSummary(AppChooserPreference.getDisplayValue(
preference.getContext(), stringValue));
} else if (preference instanceof WeatherLocationPreference) {
preference.setSummary(WeatherLocationPreference.getDisplayValue(
preference.getContext(), stringValue));
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Binds a preference's summary to its value. More specifically, when the preference's value is
* changed, its summary (line of text below the preference title) is updated to reflect the
* value. The summary is also immediately updated upon calling this method. The exact display
* format is dependent on the type of preference.
*/
public static void bindPreferenceSummaryToValue(Preference preference) {
setAndCallPreferenceChangeListener(preference, sBindPreferenceSummaryToValueListener);
}
/**
* When the preference's value is changed, trigger the given listener. The listener is also
* immediately called with the preference's current value upon calling this method.
*/
public static void setAndCallPreferenceChangeListener(Preference preference,
Preference.OnPreferenceChangeListener listener) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(listener);
// Trigger the listener immediately with the preference's
// current value.
listener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/configuration/BaseSettingsActivity.java | Java | asf20 | 6,168 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.configuration;
import net.nurik.roman.dashclock.R;
import android.app.backup.BackupManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.apps.dashclock.DaydreamService;
/**
* Fragment for allowing the user to configure daydream settings, shown within a {@link
* ConfigurationActivity}.
*/
public class ConfigureDaydreamFragment extends PreferenceFragment
implements SharedPreferences.OnSharedPreferenceChangeListener {
public ConfigureDaydreamFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'advanced' preferences.
addPreferencesFromResource(R.xml.pref_daydream);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences to
// their values. When their values change, their summaries are updated
// to reflect the new value, per the Android Design guidelines.
BaseSettingsActivity.bindPreferenceSummaryToValue(
findPreference(DaydreamService.PREF_DAYDREAM_ANIMATION));
}
@Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
super.onPause();
getPreferenceManager().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_configure_advanced, container, false);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
new BackupManager(getActivity()).dataChanged();
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/configuration/ConfigureDaydreamFragment.java | Java | asf20 | 2,672 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.configuration;
import net.nurik.roman.dashclock.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import java.util.ArrayList;
import java.util.List;
/**
* A preference that allows the user to choose an application or shortcut.
*/
public class ColorPreference extends Preference {
private int[] mColorChoices = {};
private int mValue = 0;
private int mItemLayoutId = R.layout.grid_item_color;
private int mNumColumns = 5;
private View mPreviewView;
public ColorPreference(Context context) {
super(context);
initAttrs(null, 0);
}
public ColorPreference(Context context, AttributeSet attrs) {
super(context, attrs);
initAttrs(attrs, 0);
}
public ColorPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initAttrs(attrs, defStyle);
}
private void initAttrs(AttributeSet attrs, int defStyle) {
TypedArray a = getContext().getTheme().obtainStyledAttributes(
attrs, R.styleable.ColorPreference, defStyle, defStyle);
try {
mItemLayoutId = a.getResourceId(R.styleable.ColorPreference_itemLayout, mItemLayoutId);
mNumColumns = a.getInteger(R.styleable.ColorPreference_numColumns, mNumColumns);
int choicesResId = a.getResourceId(R.styleable.ColorPreference_choices,
R.array.default_color_choice_values);
if (choicesResId > 0) {
String[] choices = a.getResources().getStringArray(choicesResId);
mColorChoices = new int[choices.length];
for (int i = 0; i < choices.length; i++) {
mColorChoices[i] = Color.parseColor(choices[i]);
}
}
} finally {
a.recycle();
}
setWidgetLayoutResource(mItemLayoutId);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
mPreviewView = view.findViewById(R.id.color_view);
setColorViewValue(mPreviewView, mValue);
}
public void setValue(int value) {
if (callChangeListener(value)) {
mValue = value;
persistInt(value);
notifyChanged();
}
}
@Override
protected void onClick() {
super.onClick();
ColorDialogFragment fragment = ColorDialogFragment.newInstance();
fragment.setPreference(this);
Activity activity = (Activity) getContext();
activity.getFragmentManager().beginTransaction()
.add(fragment, getFragmentTag())
.commit();
}
@Override
protected void onAttachedToActivity() {
super.onAttachedToActivity();
Activity activity = (Activity) getContext();
ColorDialogFragment fragment = (ColorDialogFragment) activity
.getFragmentManager().findFragmentByTag(getFragmentTag());
if (fragment != null) {
// re-bind preference to fragment
fragment.setPreference(this);
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getInt(index, 0);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
setValue(restoreValue ? getPersistedInt(0) : (Integer) defaultValue);
}
public String getFragmentTag() {
return "color_" + getKey();
}
public int getValue() {
return mValue;
}
public static class ColorDialogFragment extends DialogFragment {
private ColorPreference mPreference;
private ColorGridAdapter mAdapter;
private GridView mColorGrid;
public ColorDialogFragment() {
}
public static ColorDialogFragment newInstance() {
return new ColorDialogFragment();
}
public void setPreference(ColorPreference preference) {
mPreference = preference;
tryBindLists();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
tryBindLists();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View rootView = layoutInflater.inflate(R.layout.dialog_colors, null);
mColorGrid = (GridView) rootView.findViewById(R.id.color_grid);
mColorGrid.setNumColumns(mPreference.mNumColumns);
mColorGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long itemId) {
mPreference.setValue(mAdapter.getItem(position));
dismiss();
}
});
tryBindLists();
return new AlertDialog.Builder(getActivity())
.setView(rootView)
.create();
}
private void tryBindLists() {
if (mPreference == null) {
return;
}
if (isAdded() && mAdapter == null) {
mAdapter = new ColorGridAdapter();
}
if (mAdapter != null && mColorGrid != null) {
mAdapter.setSelectedColor(mPreference.getValue());
mColorGrid.setAdapter(mAdapter);
}
}
private class ColorGridAdapter extends BaseAdapter {
private List<Integer> mChoices = new ArrayList<Integer>();
private int mSelectedColor;
private ColorGridAdapter() {
for (int color : mPreference.mColorChoices) {
mChoices.add(color);
}
}
@Override
public int getCount() {
return mChoices.size();
}
@Override
public Integer getItem(int position) {
return mChoices.get(position);
}
@Override
public long getItemId(int position) {
return mChoices.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
convertView = LayoutInflater.from(getActivity())
.inflate(mPreference.mItemLayoutId, container, false);
}
int color = getItem(position);
setColorViewValue(convertView.findViewById(R.id.color_view), color);
convertView.setBackgroundColor(color == mSelectedColor
? 0x6633b5e5 : 0);
return convertView;
}
public void setSelectedColor(int selectedColor) {
mSelectedColor = selectedColor;
notifyDataSetChanged();
}
}
}
private static void setColorViewValue(View view, int color) {
if (view instanceof ImageView) {
ImageView imageView = (ImageView) view;
Resources res = imageView.getContext().getResources();
Drawable currentDrawable = imageView.getDrawable();
GradientDrawable colorChoiceDrawable;
if (currentDrawable != null && currentDrawable instanceof GradientDrawable) {
// Reuse drawable
colorChoiceDrawable = (GradientDrawable) currentDrawable;
} else {
colorChoiceDrawable = new GradientDrawable();
colorChoiceDrawable.setShape(GradientDrawable.OVAL);
}
// Set stroke to dark version of color
int darkenedColor = Color.rgb(
Color.red(color) * 192 / 256,
Color.green(color) * 192 / 256,
Color.blue(color) * 192 / 256);
colorChoiceDrawable.setColor(color);
colorChoiceDrawable.setStroke((int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 1, res.getDisplayMetrics()), darkenedColor);
imageView.setImageDrawable(colorChoiceDrawable);
} else if (view instanceof TextView) {
((TextView) view).setTextColor(color);
}
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/configuration/ColorPreference.java | Java | asf20 | 9,607 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.configuration;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
/**
* An activity that simply starts {@link ConfigurationActivity} in the daydream section.
*/
public class DaydreamProxyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(this, ConfigurationActivity.class)
.putExtra(ConfigurationActivity.EXTRA_START_SECTION,
ConfigurationActivity.START_SECTION_DAYDREAM)
.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT)
.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
finish();
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/configuration/DaydreamProxyActivity.java | Java | asf20 | 1,430 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.configuration;
import com.google.android.apps.dashclock.ui.PagerPositionStrip;
import net.nurik.roman.dashclock.R;
import android.app.Fragment;
import android.app.backup.BackupManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import java.util.HashMap;
import java.util.Map;
/**
* Fragment for allowing the user to configure widget appearance, shown within a {@link
* ConfigurationActivity}.
*/
public class ConfigureAppearanceFragment extends Fragment {
private static final int AUTO_HIDE_DELAY_MILLIS = 1000;
private Handler mHandler = new Handler();
private Map<View, Runnable> mHidePositionStripRunnables = new HashMap<View, Runnable>();
private Map<String, String> mCurrentStyleNames = new HashMap<String, String>();
private int mAnimationDuration;
private View[] mPositionStrips;
public ConfigureAppearanceFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_configure_appearance, container, false);
rootView.findViewById(R.id.container).setBackgroundColor(
AppearanceConfig.getHomescreenBackgroundColor(getActivity()));
mCurrentStyleNames.put(
AppearanceConfig.PREF_STYLE_TIME,
sp.getString(AppearanceConfig.PREF_STYLE_TIME,
AppearanceConfig.TIME_STYLE_NAMES[0]));
configureStylePager(
(ViewPager) rootView.findViewById(R.id.pager_time_style),
(PagerPositionStrip) rootView.findViewById(R.id.pager_time_position_strip),
AppearanceConfig.TIME_STYLE_NAMES, AppearanceConfig.COMPONENT_TIME,
Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, AppearanceConfig.PREF_STYLE_TIME);
mCurrentStyleNames.put(
AppearanceConfig.PREF_STYLE_DATE,
sp.getString(AppearanceConfig.PREF_STYLE_DATE,
AppearanceConfig.DATE_STYLE_NAMES[0]));
configureStylePager(
(ViewPager) rootView.findViewById(R.id.pager_date_style),
(PagerPositionStrip) rootView.findViewById(R.id.pager_date_position_strip),
AppearanceConfig.DATE_STYLE_NAMES, AppearanceConfig.COMPONENT_DATE,
Gravity.CENTER_HORIZONTAL | Gravity.TOP, AppearanceConfig.PREF_STYLE_DATE);
((ConfigurationActivity) getActivity()).setTranslucentActionBar(true);
return rootView;
}
@Override
public void onResume() {
super.onResume();
View rootView = getView();
if (rootView != null) {
mPositionStrips = new View[] {
rootView.findViewById(R.id.pager_time_position_strip),
rootView.findViewById(R.id.pager_date_position_strip)
};
for (View strip : mPositionStrips) {
strip.setAlpha(0f);
}
showPositionStrips(true, AUTO_HIDE_DELAY_MILLIS);
}
}
@Override
public void onPause() {
super.onPause();
final SharedPreferences.Editor sp = PreferenceManager
.getDefaultSharedPreferences(getActivity()).edit();
for (String key : mCurrentStyleNames.keySet()) {
sp.putString(key, mCurrentStyleNames.get(key));
}
sp.commit();
new BackupManager(getActivity()).dataChanged();
}
@Override
public void onDestroy() {
super.onDestroy();
// remove all scheduled runnables
mHidePositionStripRunnables.clear();
mHandler.removeCallbacksAndMessages(null);
}
private void configureStylePager(final ViewPager pager, final PagerPositionStrip positionStrip,
final String[] styleNames, final String styleComponent,
final int gravity, final String preference) {
String currentStyleName = mCurrentStyleNames.get(preference);
final LayoutInflater inflater = getActivity().getLayoutInflater();
pager.setAdapter(new PagerAdapter() {
@Override
public int getCount() {
return styleNames.length;
}
@Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
FrameLayout wrapper = new FrameLayout(getActivity());
ViewPager.LayoutParams wrapperLp = new ViewPager.LayoutParams();
wrapper.setLayoutParams(wrapperLp);
View v = inflater.inflate(
AppearanceConfig.getLayoutByStyleName(
getActivity(), styleComponent, styleNames[position]),
container, false);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lp.gravity = gravity;
v.setLayoutParams(lp);
wrapper.addView(v);
container.addView(wrapper);
return wrapper;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
});
pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
mCurrentStyleNames.put(preference, styleNames[position]);
}
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
positionStrip.setPosition(position + positionOffset);
}
});
positionStrip.setPageCount(styleNames.length);
pager.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
showPositionStrips(true, -1);
break;
case MotionEvent.ACTION_UP:
showPositionStrips(false, AUTO_HIDE_DELAY_MILLIS);
break;
}
return false;
}
});
for (int i = 0; i < styleNames.length; i++) {
if (currentStyleName.equals(styleNames[i])) {
pager.setCurrentItem(i);
positionStrip.setPosition(i);
break;
}
}
}
private void showPositionStrips(final boolean show, final int hideDelay) {
// remove any currently scheduled runnables
mHandler.removeCallbacks(mHidePositionStripsRunnable);
// if show or hide immediately, take action now
if (show || hideDelay <= 0) {
for (View strip : mPositionStrips) {
strip.animate().cancel();
strip.animate().alpha(show ? 1f : 0f).setDuration(mAnimationDuration);
}
}
// schedule a hide if hideDelay > 0
if (hideDelay > 0) {
mHandler.postDelayed(mHidePositionStripsRunnable, hideDelay);
}
}
private Runnable mHidePositionStripsRunnable = new Runnable() {
@Override
public void run() {
showPositionStrips(false, 0);
}
};
@Override
public void onDetach() {
super.onDetach();
((ConfigurationActivity) getActivity()).setTranslucentActionBar(false);
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/configuration/ConfigureAppearanceFragment.java | Java | asf20 | 9,085 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.configuration;
import com.google.android.apps.dashclock.DashClockService;
import com.google.android.apps.dashclock.HelpUtils;
import com.google.android.apps.dashclock.LogUtils;
import com.google.android.apps.dashclock.Utils;
import com.google.android.apps.dashclock.api.DashClockExtension;
import net.nurik.roman.dashclock.BuildConfig;
import net.nurik.roman.dashclock.R;
import android.app.Activity;
import android.app.Fragment;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import static com.google.android.apps.dashclock.LogUtils.LOGD;
/**
* The primary widget configuration activity. Serves as an interstitial when adding the widget, and
* shows when pressing the settings button in the widget.
*/
public class ConfigurationActivity extends Activity {
private static final String TAG = LogUtils.makeLogTag(ConfigurationActivity.class);
public static final String EXTRA_START_SECTION =
"com.google.android.apps.dashclock.configuration.extra.START_SECTION";
public static final int START_SECTION_EXTENSIONS = 0;
public static final int START_SECTION_APPEARANCE = 1;
public static final int START_SECTION_DAYDREAM = 2;
public static final int START_SECTION_ADVANCED = 3;
private static final int[] SECTION_LABELS = new int[]{
R.string.section_extensions,
R.string.section_appearance,
R.string.section_daydream,
R.string.section_advanced,
};
@SuppressWarnings("unchecked")
private static final Class<? extends Fragment>[] SECTION_FRAGMENTS = new Class[]{
ConfigureExtensionsFragment.class,
ConfigureAppearanceFragment.class,
ConfigureDaydreamFragment.class,
ConfigureAdvancedFragment.class,
};
// only used when adding a new widget
private int mNewWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
private int mStartSection = START_SECTION_EXTENSIONS;
private boolean mBackgroundCleared = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.enableDisablePhoneOnlyExtensions(this);
Intent intent = getIntent();
if (intent != null) {
if (Intent.ACTION_CREATE_SHORTCUT.equals(intent.getAction())) {
Intent.ShortcutIconResource icon = new Intent.ShortcutIconResource();
icon.packageName = getPackageName();
icon.resourceName = getResources().getResourceName(R.drawable.ic_launcher);
setResult(RESULT_OK, new Intent()
.putExtra(Intent.EXTRA_SHORTCUT_NAME,
getString(R.string.shortcut_label_configure))
.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon)
.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
new Intent(this, ConfigurationActivity.class)));
finish();
return;
}
mStartSection = intent.getIntExtra(EXTRA_START_SECTION, 0);
}
setContentView(R.layout.activity_configure);
if (intent != null
&& AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(intent.getAction())) {
mNewWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mNewWidgetId);
// See http://code.google.com/p/android/issues/detail?id=2539
setResult(RESULT_CANCELED, new Intent()
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mNewWidgetId));
}
// Set up UI widgets
setupActionBar();
}
public int getStartSection() {
return mStartSection;
}
@Override
public void onUserInteraction() {
super.onUserInteraction();
showWallpaper();
}
public void setTranslucentActionBar(boolean translucentActionBar) {
findViewById(R.id.actionbar_container).setBackgroundResource(translucentActionBar
? R.drawable.ab_background_translucent : R.drawable.ab_background);
showWallpaper();
}
private void showWallpaper() {
if (!mBackgroundCleared) {
// We initially show a background so that the activity transition (zoom-up animation
// in Android 4.1) doesn't show the system wallpaper (which is needed in the
// appearance configuration fragment). Upon user interaction (i.e. once we know the
// activity transition has finished), clear the background so that the system wallpaper
// can be seen when the appearance configuration fragment is shown.
findViewById(R.id.container).setBackground(null);
mBackgroundCleared = true;
}
}
private void setupActionBar() {
final Context darkThemeContext = new ContextThemeWrapper(this, android.R.style.Theme_Holo);
final LayoutInflater inflater = (LayoutInflater) darkThemeContext
.getSystemService(LAYOUT_INFLATER_SERVICE);
final ViewGroup actionBarContainer = (ViewGroup) findViewById(R.id.actionbar_container);
inflater.inflate(R.layout.include_configure_actionbar, actionBarContainer, true);
actionBarContainer.findViewById(R.id.actionbar_done).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
// "Done"
if (mNewWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
setResult(RESULT_OK, new Intent()
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mNewWidgetId));
}
finish();
}
});
actionBarContainer.findViewById(R.id.action_overflow).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
PopupMenu actionOverflowMenu = new PopupMenu(darkThemeContext, view);
actionOverflowMenu.inflate(R.menu.configure_overflow);
//noinspection PointlessBooleanExpression,ConstantConditions
if (!BuildConfig.DEBUG) {
MenuItem sendLogsItem = actionOverflowMenu.getMenu()
.findItem(R.id.action_send_logs);
if (sendLogsItem != null) {
sendLogsItem.setVisible(false);
}
}
actionOverflowMenu.show();
actionOverflowMenu.setOnMenuItemClickListener(mActionOverflowClickListener);
}
});
Spinner sectionSpinner = (Spinner) actionBarContainer.findViewById(R.id.section_spinner);
sectionSpinner.setAdapter(new BaseAdapter() {
@Override
public int getCount() {
return SECTION_LABELS.length;
}
@Override
public Object getItem(int position) {
return SECTION_LABELS[position];
}
@Override
public long getItemId(int position) {
return position + 1;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_configure_ab_spinner,
parent, false);
}
((TextView) convertView.findViewById(android.R.id.text1)).setText(
getString(SECTION_LABELS[position]));
return convertView;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_configure_ab_spinner_dropdown,
parent, false);
}
((TextView) convertView.findViewById(android.R.id.text1)).setText(
getString(SECTION_LABELS[position]));
return convertView;
}
});
sectionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> spinner, View view, int position, long id) {
Class<? extends Fragment> fragmentClass = SECTION_FRAGMENTS[position];
try {
Fragment newFragment = fragmentClass.newInstance();
getFragmentManager().beginTransaction()
.replace(R.id.content_container, newFragment)
.commitAllowingStateLoss();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public void onNothingSelected(AdapterView<?> spinner) {
}
});
sectionSpinner.setSelection(mStartSection);
}
private PopupMenu.OnMenuItemClickListener mActionOverflowClickListener
= new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_get_more_extensions:
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/search?q=DashClock+Extension"
+ "&c=apps"))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
return true;
case R.id.action_send_logs:
LogUtils.sendDebugLog(ConfigurationActivity.this);
return true;
case R.id.action_about:
HelpUtils.showAboutDialog(
ConfigurationActivity.this);
return true;
}
return false;
}
};
@Override
protected void onStop() {
super.onStop();
// Update extensions (settings may have changed)
// TODO: update only those extensions whose settings have changed
Intent updateExtensionsIntent = new Intent(this, DashClockService.class);
updateExtensionsIntent.setAction(DashClockService.ACTION_UPDATE_EXTENSIONS);
updateExtensionsIntent.putExtra(DashClockService.EXTRA_UPDATE_REASON,
DashClockExtension.UPDATE_REASON_SETTINGS_CHANGED);
startService(updateExtensionsIntent);
// Update all widgets, including a new one if it was just added
// We can't only update the new one because settings affecting all widgets may have
// been changed.
LOGD(TAG, "Updating all widgets");
Intent widgetUpdateIntent = new Intent(this, DashClockService.class);
widgetUpdateIntent.setAction(DashClockService.ACTION_UPDATE_WIDGETS);
startService(widgetUpdateIntent);
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/configuration/ConfigurationActivity.java | Java | asf20 | 12,472 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.configuration;
import com.google.android.apps.dashclock.render.DashClockRenderer;
import net.nurik.roman.dashclock.R;
import android.app.backup.BackupManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Fragment for allowing the user to configure advanced widget settings, shown within a {@link
* com.google.android.apps.dashclock.configuration.ConfigurationActivity}.
*/
public class ConfigureAdvancedFragment extends PreferenceFragment
implements SharedPreferences.OnSharedPreferenceChangeListener {
public ConfigureAdvancedFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'advanced' preferences.
addPreferencesFromResource(R.xml.pref_advanced);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences to
// their values. When their values change, their summaries are updated
// to reflect the new value, per the Android Design guidelines.
BaseSettingsActivity.bindPreferenceSummaryToValue(
findPreference(DashClockRenderer.PREF_CLOCK_SHORTCUT));
BaseSettingsActivity.bindPreferenceSummaryToValue(
findPreference(AppearanceConfig.PREF_HOMESCREEN_BACKGROUND_OPACITY));
}
@Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
super.onPause();
getPreferenceManager().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_configure_advanced, container, false);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
new BackupManager(getActivity()).dataChanged();
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/configuration/ConfigureAdvancedFragment.java | Java | asf20 | 2,879 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.configuration;
import com.google.android.apps.dashclock.ExtensionHost;
import com.google.android.apps.dashclock.ExtensionManager;
import com.google.android.apps.dashclock.Utils;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.ui.SwipeDismissListViewTouchListener;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
import net.nurik.roman.dashclock.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.android.apps.dashclock.ExtensionManager.ExtensionListing;
/**
* Fragment for allowing the user to configure active extensions, shown within a {@link
* ConfigurationActivity}.
*/
public class ConfigureExtensionsFragment extends Fragment implements
ExtensionManager.OnChangeListener,
AdapterView.OnItemClickListener {
private static final String SAVE_KEY_SELECTED_EXTENSIONS = "selected_extensions";
private ExtensionManager mExtensionManager;
private List<ComponentName> mSelectedExtensions = new ArrayList<ComponentName>();
private ExtensionListAdapter mSelectedExtensionsAdapter;
private Map<ComponentName, ExtensionManager.ExtensionListing> mExtensionListings
= new HashMap<ComponentName, ExtensionManager.ExtensionListing>();
private List<ComponentName> mAvailableExtensions = new ArrayList<ComponentName>();
private PopupMenu mAddExtensionPopupMenu;
private BroadcastReceiver mPackageChangedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
repopulateAvailableExtensions();
}
};
private DragSortListView mListView;
public ConfigureExtensionsFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up helper components
mExtensionManager = ExtensionManager.getInstance(getActivity());
mExtensionManager.addOnChangeListener(this);
if (savedInstanceState == null) {
mSelectedExtensions = mExtensionManager.getActiveExtensionNames();
} else {
List<String> selected = savedInstanceState
.getStringArrayList(SAVE_KEY_SELECTED_EXTENSIONS);
for (String s : selected) {
mSelectedExtensions.add(ComponentName.unflattenFromString(s));
}
}
mSelectedExtensionsAdapter = new ExtensionListAdapter();
repopulateAvailableExtensions();
IntentFilter packageChangeIntentFilter = new IntentFilter();
packageChangeIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
packageChangeIntentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
packageChangeIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
packageChangeIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
packageChangeIntentFilter.addDataScheme("package");
getActivity().registerReceiver(mPackageChangedReceiver, packageChangeIntentFilter);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_configure_extensions, container, false);
mListView = (DragSortListView) rootView.findViewById(android.R.id.list);
mListView.setAdapter(mSelectedExtensionsAdapter);
mListView.setEmptyView(rootView.findViewById(android.R.id.empty));
final DragSortController dragSortController = new ConfigurationDragSortController();
mListView.setFloatViewManager(dragSortController);
mListView.setDropListener(new DragSortListView.DropListener() {
@Override
public void drop(int from, int to) {
ComponentName name = mSelectedExtensions.remove(from);
mSelectedExtensions.add(to, name);
mSelectedExtensionsAdapter.notifyDataSetChanged();
}
});
final SwipeDismissListViewTouchListener swipeDismissTouchListener =
new SwipeDismissListViewTouchListener(
mListView,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
public boolean canDismiss(int position) {
return position < mSelectedExtensionsAdapter.getCount() - 1;
}
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
mSelectedExtensions.remove(position);
}
repopulateAvailableExtensions();
mSelectedExtensionsAdapter.notifyDataSetChanged();
}
});
mListView.setOnItemClickListener(this);
mListView.setOnScrollListener(swipeDismissTouchListener.makeScrollListener());
mListView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return dragSortController.onTouch(view, motionEvent)
|| (!dragSortController.isDragging()
&& swipeDismissTouchListener.onTouch(view, motionEvent));
}
});
mListView.setItemsCanFocus(true);
rootView.findViewById(R.id.empty_add_extension_button).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
showAddExtensionMenu(view);
}
});
return rootView;
}
@Override
public void onPause() {
super.onPause();
mExtensionManager.setActiveExtensions(mSelectedExtensions);
}
@Override
public void onDestroy() {
super.onDestroy();
getActivity().unregisterReceiver(mPackageChangedReceiver);
mExtensionManager.removeOnChangeListener(this);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
ArrayList<String> selectedExtensions = new ArrayList<String>();
for (ComponentName cn : mSelectedExtensions) {
selectedExtensions.add(cn.flattenToString());
}
outState.putStringArrayList(SAVE_KEY_SELECTED_EXTENSIONS, selectedExtensions);
}
private void repopulateAvailableExtensions() {
Set<ComponentName> selectedExtensions = new HashSet<ComponentName>();
selectedExtensions.addAll(mSelectedExtensions);
boolean selectedExtensionsDirty = false;
for (ExtensionListing listing : mExtensionListings.values()) {
if (listing.icon != null) {
//listing.icon.recycle();
// TODO: recycling causes crashes with the ListView :-(
listing.icon = null;
}
}
mExtensionListings.clear();
mAvailableExtensions.clear();
Resources res = getResources();
for (ExtensionListing listing : mExtensionManager.getAvailableExtensions()) {
mExtensionListings.put(listing.componentName, listing);
if (listing.icon != null) {
Bitmap icon = Utils.flattenExtensionIcon(listing.icon,
res.getColor(R.color.extension_list_item_color));
listing.icon = (icon != null) ? new BitmapDrawable(res, icon) : null;
}
if (selectedExtensions.contains(listing.componentName)) {
if (!ExtensionHost.supportsProtocolVersion(listing.protocolVersion)) {
// If the extension is selected and its protocol isn't supported,
// then make it available but remove it from the selection.
mSelectedExtensions.remove(listing.componentName);
selectedExtensionsDirty = true;
} else {
// If it's selected and supported, don't add it to the list of available
// extensions.
continue;
}
}
mAvailableExtensions.add(listing.componentName);
}
Collections.sort(mAvailableExtensions, new Comparator<ComponentName>() {
@Override
public int compare(ComponentName cn1, ComponentName cn2) {
ExtensionListing listing1 = mExtensionListings.get(cn1);
ExtensionListing listing2 = mExtensionListings.get(cn2);
return listing1.title.compareToIgnoreCase(listing2.title);
}
});
if (selectedExtensionsDirty && mSelectedExtensionsAdapter != null) {
mSelectedExtensionsAdapter.notifyDataSetChanged();
}
if (mAddExtensionPopupMenu != null) {
mAddExtensionPopupMenu.dismiss();
mAddExtensionPopupMenu = null;
}
}
@Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
if (id == -1) {
showAddExtensionMenu(view.findViewById(R.id.add_extension_label));
}
}
private void showAddExtensionMenu(View anchorView) {
if (mAddExtensionPopupMenu != null) {
mAddExtensionPopupMenu.dismiss();
}
mAddExtensionPopupMenu = new PopupMenu(getActivity(), anchorView);
for (int i = 0; i < mAvailableExtensions.size(); i++) {
ComponentName cn = mAvailableExtensions.get(i);
ExtensionListing listing = mExtensionListings.get(cn);
String label = (listing == null) ? null : listing.title;
if (TextUtils.isEmpty(label)) {
label = cn.flattenToShortString();
}
if (listing != null
&& !ExtensionHost.supportsProtocolVersion(listing.protocolVersion)) {
label = getString(R.string.incompatible_extension_menu_template, label);
}
mAddExtensionPopupMenu.getMenu().add(Menu.NONE, i, Menu.NONE, label);
}
mAddExtensionPopupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
mAddExtensionPopupMenu.dismiss();
mAddExtensionPopupMenu = null;
ComponentName cn = mAvailableExtensions.get(menuItem.getItemId());
ExtensionListing extensionListing = mExtensionListings.get(cn);
if (extensionListing == null
|| !ExtensionHost.supportsProtocolVersion(
extensionListing.protocolVersion)) {
String title = cn.getShortClassName();
if (extensionListing != null) {
title = extensionListing.title;
}
CantAddExtensionDialog
.createInstance(cn.getPackageName(), title)
.show(getFragmentManager(), "cantaddextension");
return true;
}
// Item id == position for this popup menu.
mSelectedExtensions.add(cn);
repopulateAvailableExtensions();
mSelectedExtensionsAdapter.notifyDataSetChanged();
mListView.smoothScrollToPosition(mSelectedExtensionsAdapter.getCount() - 1);
return true;
}
});
mAddExtensionPopupMenu.show();
}
private class ConfigurationDragSortController extends DragSortController {
private int mPos;
public ConfigurationDragSortController() {
super(ConfigureExtensionsFragment.this.mListView, R.id.drag_handle,
DragSortController.ON_DOWN, 0);
setRemoveEnabled(false);
}
@Override
public int startDragPosition(MotionEvent ev) {
int res = super.dragHandleHitPosition(ev);
if (res >= mSelectedExtensionsAdapter.getCount() - 1) {
return DragSortController.MISS;
}
return res;
}
@Override
public View onCreateFloatView(int position) {
mPos = position;
return mSelectedExtensionsAdapter.getView(position, null, mListView);
}
private int origHeight = -1;
@Override
public void onDragFloatView(View floatView, Point floatPoint, Point touchPoint) {
final int addPos = mSelectedExtensionsAdapter.getCount() - 1;
final int first = mListView.getFirstVisiblePosition();
final int lvDivHeight = mListView.getDividerHeight();
if (origHeight == -1) {
origHeight = floatView.getHeight();
}
View div = mListView.getChildAt(addPos - first);
if (touchPoint.x > mListView.getWidth() / 2) {
float scale = touchPoint.x - mListView.getWidth() / 2;
scale /= (float) (mListView.getWidth() / 5);
ViewGroup.LayoutParams lp = floatView.getLayoutParams();
lp.height = Math.max(origHeight, (int) (scale * origHeight));
//Log.d("mobeta", "setting height " + lp.height);
floatView.setLayoutParams(lp);
}
if (div != null) {
if (mPos > addPos) {
// don't allow floating View to go above
// section divider
final int limit = div.getBottom() + lvDivHeight;
if (floatPoint.y < limit) {
floatPoint.y = limit;
}
} else {
// don't allow floating View to go below
// section divider
final int limit = div.getTop() - lvDivHeight - floatView.getHeight();
if (floatPoint.y > limit) {
floatPoint.y = limit;
}
}
}
}
@Override
public void onDestroyFloatView(View floatView) {
//do nothing; block super from crashing
}
}
@Override
public void onExtensionsChanged() {
repopulateAvailableExtensions();
}
public class ExtensionListAdapter extends BaseAdapter {
private static final int VIEW_TYPE_ITEM = 0;
private static final int VIEW_TYPE_ADD = 1;
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public int getCount() {
int numItems = mSelectedExtensions.size();
// Hide add row to show empty view if there are no items.
return (numItems == 0) ? 0 : (numItems + 1);
}
@Override
public int getItemViewType(int position) {
return (position == getCount() - 1)
? VIEW_TYPE_ADD
: VIEW_TYPE_ITEM;
}
@Override
public Object getItem(int position) {
return (getItemViewType(position) == VIEW_TYPE_ADD)
? null
: mSelectedExtensions.get(position);
}
@Override
public long getItemId(int position) {
return (getItemViewType(position) == VIEW_TYPE_ADD)
? -1
: mSelectedExtensions.get(position).hashCode();
}
@Override
public boolean isEnabled(int position) {
return (getItemViewType(position) == VIEW_TYPE_ADD) && mAvailableExtensions.size() > 0;
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
switch (getItemViewType(position)) {
case VIEW_TYPE_ADD: {
if (convertView == null) {
convertView = getActivity().getLayoutInflater()
.inflate(R.layout.list_item_add_extension, parent, false);
}
convertView.setEnabled(isEnabled(position));
return convertView;
}
case VIEW_TYPE_ITEM: {
ComponentName cn = (ComponentName) getItem(position);
if (convertView == null) {
convertView = getActivity().getLayoutInflater()
.inflate(R.layout.list_item_extension, parent, false);
}
TextView titleView = (TextView) convertView.findViewById(android.R.id.text1);
TextView descriptionView = (TextView) convertView
.findViewById(android.R.id.text2);
ImageView iconView = (ImageView) convertView.findViewById(android.R.id.icon1);
View settingsButton = convertView.findViewById(R.id.settings_button);
final ExtensionListing listing = mExtensionListings.get(cn);
if (listing == null || TextUtils.isEmpty(listing.title)) {
iconView.setImageBitmap(null);
titleView.setText(cn.flattenToShortString());
descriptionView.setVisibility(View.GONE);
settingsButton.setVisibility(View.GONE);
} else {
iconView.setImageDrawable(listing.icon);
titleView.setText(listing.title);
descriptionView.setVisibility(
TextUtils.isEmpty(listing.description) ? View.GONE : View.VISIBLE);
descriptionView.setText(listing.description);
settingsButton.setVisibility(
listing.settingsActivity == null ? View.GONE : View.VISIBLE);
settingsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
startActivity(new Intent()
.setComponent(listing.settingsActivity)
.putExtra(DashClockExtension
.EXTRA_FROM_DASHCLOCK_SETTINGS, true));
} catch (ActivityNotFoundException e) {
// TODO: show error to user
} catch (SecurityException e) {
// TODO: show error to user
}
}
});
}
return convertView;
}
}
return null;
}
}
public static class CantAddExtensionDialog extends DialogFragment {
private static final String ARG_EXTENSION_TITLE = "title";
private static final String ARG_EXTENSION_PACKAGE_NAME = "package_name";
public static CantAddExtensionDialog createInstance(String extensionPackageName,
String extensionTitle) {
CantAddExtensionDialog fragment = new CantAddExtensionDialog();
Bundle args = new Bundle();
args.putString(ARG_EXTENSION_TITLE, extensionTitle);
args.putString(ARG_EXTENSION_PACKAGE_NAME, extensionPackageName);
fragment.setArguments(args);
return fragment;
}
public CantAddExtensionDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String extensionTitle = getArguments().getString(ARG_EXTENSION_TITLE);
final String extensionPackageName = getArguments().getString(ARG_EXTENSION_PACKAGE_NAME);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.incompatible_extension_title)
.setMessage(Html.fromHtml(getString(
R.string.incompatible_extension_message_search_play_template,
extensionTitle)))
.setPositiveButton(R.string.search_play,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent playIntent = new Intent(Intent.ACTION_VIEW);
playIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
playIntent.setData(Uri.parse(
"https://play.google.com/store/apps/details?id="
+ extensionPackageName));
try {
startActivity(playIntent);
} catch (ActivityNotFoundException ignored) {
}
dialog.dismiss();
}
}
)
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/configuration/ConfigureExtensionsFragment.java | Java | asf20 | 24,011 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.phone;
import com.google.android.apps.dashclock.LogUtils;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import net.nurik.roman.dashclock.R;
import android.content.Intent;
import android.database.Cursor;
import android.provider.CallLog;
import android.text.TextUtils;
import java.util.SortedSet;
import java.util.TreeSet;
import static com.google.android.apps.dashclock.LogUtils.LOGE;
/**
* Number of missed calls extension.
*/
public class MissedCallsExtension extends DashClockExtension {
private static final String TAG = LogUtils.makeLogTag(MissedCallsExtension.class);
@Override
protected void onInitialize(boolean isReconnect) {
super.onInitialize(isReconnect);
if (!isReconnect) {
addWatchContentUris(new String[]{
CallLog.Calls.CONTENT_URI.toString()
});
}
}
@Override
protected void onUpdateData(int reason) {
Cursor cursor = tryOpenMissedCallsCursor();
if (cursor == null) {
LOGE(TAG, "Null missed calls cursor, short-circuiting.");
return;
}
int missedCalls = 0;
SortedSet<String> names = new TreeSet<String>();
while (cursor.moveToNext()) {
++missedCalls;
String name = cursor.getString(MissedCallsQuery.CACHED_NAME);
if (TextUtils.isEmpty(name)) {
name = cursor.getString(MissedCallsQuery.NUMBER);
long parsedNumber = 0;
try {
parsedNumber = Long.parseLong(name);
} catch (Exception ignored) {
}
if (parsedNumber < 0) {
// Unknown or private number
name = getString(R.string.missed_calls_unknown);
}
}
names.add(name);
}
cursor.close();
publishUpdate(new ExtensionData()
.visible(missedCalls > 0)
.icon(R.drawable.ic_extension_missed_calls)
.status(Integer.toString(missedCalls))
.expandedTitle(
getResources().getQuantityString(
R.plurals.missed_calls_title_template, missedCalls, missedCalls))
.expandedBody(getString(R.string.missed_calls_body_template,
TextUtils.join(", ", names)))
.clickIntent(new Intent(Intent.ACTION_VIEW, CallLog.Calls.CONTENT_URI)));
}
private Cursor tryOpenMissedCallsCursor() {
try {
return getContentResolver().query(
CallLog.Calls.CONTENT_URI,
MissedCallsQuery.PROJECTION,
CallLog.Calls.TYPE + "=" + CallLog.Calls.MISSED_TYPE + " AND "
+ CallLog.Calls.NEW + "!=0",
null,
null);
} catch (Exception e) {
LOGE(TAG, "Error opening missed calls cursor", e);
return null;
}
}
private interface MissedCallsQuery {
String[] PROJECTION = {
CallLog.Calls._ID,
CallLog.Calls.CACHED_NAME,
CallLog.Calls.NUMBER,
};
int ID = 0;
int CACHED_NAME = 1;
int NUMBER = 2;
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/phone/MissedCallsExtension.java | Java | asf20 | 4,023 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.phone;
import com.google.android.apps.dashclock.LogUtils;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import net.nurik.roman.dashclock.R;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;
import java.util.HashSet;
import java.util.Set;
import static com.google.android.apps.dashclock.LogUtils.LOGD;
import static com.google.android.apps.dashclock.LogUtils.LOGE;
import static com.google.android.apps.dashclock.LogUtils.LOGW;
/**
* Unread SMS and MMS's extension.
*/
public class SmsExtension extends DashClockExtension {
private static final String TAG = LogUtils.makeLogTag(SmsExtension.class);
@Override
protected void onInitialize(boolean isReconnect) {
super.onInitialize(isReconnect);
if (!isReconnect) {
addWatchContentUris(new String[]{
TelephonyProviderConstants.MmsSms.CONTENT_URI.toString(),
});
}
}
@Override
protected void onUpdateData(int reason) {
long lastUnreadThreadId = 0;
Set<Long> unreadThreadIds = new HashSet<Long>();
Set<String> unreadThreadParticipantNames = new HashSet<String>();
boolean showingAllConversationParticipants = false;
Cursor cursor = tryOpenSimpleThreadsCursor();
if (cursor != null) {
while (cursor.moveToNext()) {
if (cursor.getInt(SimpleThreadsQuery.READ) == 0) {
long threadId = cursor.getLong(SimpleThreadsQuery._ID);
unreadThreadIds.add(threadId);
lastUnreadThreadId = threadId;
// Some devices will fail on tryOpenMmsSmsCursor below, so
// store a list of participants on unread threads as a fallback.
String recipientIdsStr = cursor.getString(SimpleThreadsQuery.RECIPIENT_IDS);
if (!TextUtils.isEmpty(recipientIdsStr)) {
String[] recipientIds = TextUtils.split(recipientIdsStr, " ");
for (String recipientId : recipientIds) {
Cursor canonAddrCursor = tryOpenCanonicalAddressCursorById(
Long.parseLong(recipientId));
if (canonAddrCursor == null) {
continue;
}
if (canonAddrCursor.moveToFirst()) {
String address = canonAddrCursor.getString(
CanonicalAddressQuery.ADDRESS);
String displayName = getDisplayNameForContact(0, address);
if (!TextUtils.isEmpty(displayName)) {
unreadThreadParticipantNames.add(displayName);
}
}
canonAddrCursor.close();
}
}
}
}
cursor.close();
LOGD(TAG, "Unread thread IDs: [" + TextUtils.join(", ", unreadThreadIds) + "]");
}
int unreadConversations = 0;
StringBuilder names = new StringBuilder();
cursor = tryOpenMmsSmsCursor();
if (cursor != null) {
// Most devices will hit this code path.
while (cursor.moveToNext()) {
// Get display name. SMS's are easy; MMS's not so much.
long id = cursor.getLong(MmsSmsQuery._ID);
long contactId = cursor.getLong(MmsSmsQuery.PERSON);
String address = cursor.getString(MmsSmsQuery.ADDRESS);
long threadId = cursor.getLong(MmsSmsQuery.THREAD_ID);
if (unreadThreadIds != null && !unreadThreadIds.contains(threadId)) {
// We have the list of all thread IDs (same as what the messaging app uses), and
// this supposedly unread message's thread isn't in the list. This message is
// likely an orphaned message whose thread was deleted. Not skipping it is
// likely the cause of http://code.google.com/p/dashclock/issues/detail?id=8
LOGD(TAG, "Skipping probably orphaned message " + id + " with thread ID "
+ threadId);
continue;
}
++unreadConversations;
lastUnreadThreadId = threadId;
if (contactId == 0 && TextUtils.isEmpty(address) && id != 0) {
// Try MMS addr query
Cursor addrCursor = tryOpenMmsAddrCursor(id);
if (addrCursor != null) {
if (addrCursor.moveToFirst()) {
contactId = addrCursor.getLong(MmsAddrQuery.CONTACT_ID);
address = addrCursor.getString(MmsAddrQuery.ADDRESS);
}
addrCursor.close();
}
}
String displayName = getDisplayNameForContact(contactId, address);
if (names.length() > 0) {
names.append(", ");
}
names.append(displayName);
}
cursor.close();
} else {
// In case the cursor is null (some Samsung devices like the Galaxy S4), use the
// fall back on the list of participants in unread threads.
unreadConversations = unreadThreadIds.size();
names.append(TextUtils.join(", ", unreadThreadParticipantNames));
showingAllConversationParticipants = true;
}
Intent clickIntent;
if (unreadConversations == 1 && lastUnreadThreadId > 0) {
clickIntent = new Intent(Intent.ACTION_VIEW,
TelephonyProviderConstants.MmsSms.CONTENT_CONVERSATIONS_URI.buildUpon()
.appendPath(Long.toString(lastUnreadThreadId)).build());
} else {
clickIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
Intent.CATEGORY_APP_MESSAGING);
}
publishUpdate(new ExtensionData()
.visible(unreadConversations > 0)
.icon(R.drawable.ic_extension_sms)
.status(Integer.toString(unreadConversations))
.expandedTitle(
getResources().getQuantityString(
R.plurals.sms_title_template, unreadConversations,
unreadConversations))
.expandedBody(getString(showingAllConversationParticipants
? R.string.sms_body_all_participants_template
: R.string.sms_body_template,
names.toString()))
.clickIntent(clickIntent));
}
/**
* Returns the display name for the contact with the given ID and/or the given address
* (phone number). One or both parameters should be provided.
*/
private String getDisplayNameForContact(long contactId, String address) {
String displayName = address;
if (contactId > 0) {
Cursor contactCursor = tryOpenContactsCursorById(contactId);
if (contactCursor != null) {
if (contactCursor.moveToFirst()) {
displayName = contactCursor.getString(RawContactsQuery.DISPLAY_NAME);
} else {
contactId = 0;
}
contactCursor.close();
}
}
if (contactId <= 0) {
Cursor contactCursor = tryOpenContactsCursorByAddress(address);
if (contactCursor != null) {
if (contactCursor.moveToFirst()) {
displayName = contactCursor.getString(ContactsQuery.DISPLAY_NAME);
}
contactCursor.close();
}
}
return displayName;
}
private Cursor tryOpenMmsSmsCursor() {
try {
return getContentResolver().query(
TelephonyProviderConstants.MmsSms.CONTENT_CONVERSATIONS_URI,
MmsSmsQuery.PROJECTION,
TelephonyProviderConstants.Mms.READ + "=0 AND "
+ TelephonyProviderConstants.Mms.THREAD_ID + "!=0 AND ("
+ TelephonyProviderConstants.Mms.MESSAGE_BOX + "="
+ TelephonyProviderConstants.Mms.MESSAGE_BOX_INBOX + " OR "
+ TelephonyProviderConstants.Sms.TYPE + "="
+ TelephonyProviderConstants.Sms.MESSAGE_TYPE_INBOX + ")",
null,
null);
} catch (Exception e) {
// Catch all exceptions because the SMS provider is crashy
// From developer console: "SQLiteException: table spam_filter already exists"
LOGE(TAG, "Error accessing conversations cursor in SMS/MMS provider", e);
return null;
}
}
private Cursor tryOpenSimpleThreadsCursor() {
try {
return getContentResolver().query(
TelephonyProviderConstants.Threads.CONTENT_URI
.buildUpon()
.appendQueryParameter("simple", "true")
.build(),
SimpleThreadsQuery.PROJECTION,
null,
null,
null);
} catch (Exception e) {
LOGW(TAG, "Error accessing simple SMS threads cursor", e);
return null;
}
}
private Cursor tryOpenCanonicalAddressCursorById(long id) {
try {
return getContentResolver().query(
TelephonyProviderConstants.CanonicalAddresses.CONTENT_URI.buildUpon()
.build(),
CanonicalAddressQuery.PROJECTION,
TelephonyProviderConstants.CanonicalAddresses._ID + "=?",
new String[]{Long.toString(id)},
null);
} catch (Exception e) {
LOGE(TAG, "Error accessing canonical addresses cursor", e);
return null;
}
}
private Cursor tryOpenMmsAddrCursor(long mmsMsgId) {
try {
return getContentResolver().query(
TelephonyProviderConstants.Mms.CONTENT_URI.buildUpon()
.appendPath(Long.toString(mmsMsgId))
.appendPath("addr")
.build(),
MmsAddrQuery.PROJECTION,
TelephonyProviderConstants.Mms.Addr.MSG_ID + "=?",
new String[]{Long.toString(mmsMsgId)},
null);
} catch (Exception e) {
// Catch all exceptions because the SMS provider is crashy
// From developer console: "SQLiteException: table spam_filter already exists"
LOGE(TAG, "Error accessing MMS addresses cursor", e);
return null;
}
}
private Cursor tryOpenContactsCursorById(long contactId) {
try {
return getContentResolver().query(
ContactsContract.RawContacts.CONTENT_URI.buildUpon()
.appendPath(Long.toString(contactId))
.build(),
RawContactsQuery.PROJECTION,
null,
null,
null);
} catch (Exception e) {
LOGE(TAG, "Error accessing contacts provider", e);
return null;
}
}
private Cursor tryOpenContactsCursorByAddress(String phoneNumber) {
try {
return getContentResolver().query(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI.buildUpon()
.appendPath(Uri.encode(phoneNumber)).build(),
ContactsQuery.PROJECTION,
null,
null,
null);
} catch (Exception e) {
// Can be called by the content provider (from Google Play crash/ANR console)
// java.lang.IllegalArgumentException: URI: content://com.android.contacts/phone_lookup/
LOGW(TAG, "Error looking up contact name", e);
return null;
}
}
private interface SimpleThreadsQuery {
String[] PROJECTION = {
TelephonyProviderConstants.Threads._ID,
TelephonyProviderConstants.Threads.READ,
TelephonyProviderConstants.Threads.RECIPIENT_IDS,
};
int _ID = 0;
int READ = 1;
int RECIPIENT_IDS = 2;
}
private interface CanonicalAddressQuery {
String[] PROJECTION = {
TelephonyProviderConstants.CanonicalAddresses._ID,
TelephonyProviderConstants.CanonicalAddresses.ADDRESS,
};
int _ID = 0;
int ADDRESS = 1;
}
private interface MmsSmsQuery {
String[] PROJECTION = {
TelephonyProviderConstants.Sms._ID,
TelephonyProviderConstants.Sms.ADDRESS,
TelephonyProviderConstants.Sms.PERSON,
TelephonyProviderConstants.Sms.THREAD_ID,
};
int _ID = 0;
int ADDRESS = 1;
int PERSON = 2;
int THREAD_ID = 3;
}
private interface MmsAddrQuery {
String[] PROJECTION = {
TelephonyProviderConstants.Mms.Addr.ADDRESS,
TelephonyProviderConstants.Mms.Addr.CONTACT_ID,
};
int ADDRESS = 0;
int CONTACT_ID = 1;
}
private interface RawContactsQuery {
String[] PROJECTION = {
ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY,
};
int DISPLAY_NAME = 0;
}
private interface ContactsQuery {
String[] PROJECTION = {
ContactsContract.Contacts.DISPLAY_NAME,
};
int DISPLAY_NAME = 0;
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/phone/SmsExtension.java | Java | asf20 | 14,953 |
/*
* Copyright 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.phone;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Patterns;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Private API. Will likely break in the future.
*
* Excerpt from frameworks/base/core/java/android/provider/Telephony.java.
*/
public final class TelephonyProviderConstants {
private TelephonyProviderConstants() {
}
/**
* Base columns for tables that contain text based SMSs.
*/
public interface TextBasedSmsColumns {
/**
* The type of the message
* <P>Type: INTEGER</P>
*/
public static final String TYPE = "type";
public static final int MESSAGE_TYPE_ALL = 0;
public static final int MESSAGE_TYPE_INBOX = 1;
public static final int MESSAGE_TYPE_SENT = 2;
public static final int MESSAGE_TYPE_DRAFT = 3;
public static final int MESSAGE_TYPE_OUTBOX = 4;
public static final int MESSAGE_TYPE_FAILED = 5; // for failed outgoing messages
public static final int MESSAGE_TYPE_QUEUED = 6; // for messages to send later
/**
* The thread ID of the message
* <P>Type: INTEGER</P>
*/
public static final String THREAD_ID = "thread_id";
/**
* The address of the other party
* <P>Type: TEXT</P>
*/
public static final String ADDRESS = "address";
/**
* The person ID of the sender
* <P>Type: INTEGER (long)</P>
*/
public static final String PERSON_ID = "person";
/**
* The date the message was received
* <P>Type: INTEGER (long)</P>
*/
public static final String DATE = "date";
/**
* The date the message was sent
* <P>Type: INTEGER (long)</P>
*/
public static final String DATE_SENT = "date_sent";
/**
* Has the message been read
* <P>Type: INTEGER (boolean)</P>
*/
public static final String READ = "read";
/**
* Indicates whether this message has been seen by the user. The "seen" flag will be
* used to figure out whether we need to throw up a statusbar notification or not.
*/
public static final String SEEN = "seen";
/**
* The TP-Status value for the message, or -1 if no status has
* been received
*/
public static final String STATUS = "status";
public static final int STATUS_NONE = -1;
public static final int STATUS_COMPLETE = 0;
public static final int STATUS_PENDING = 32;
public static final int STATUS_FAILED = 64;
/**
* The subject of the message, if present
* <P>Type: TEXT</P>
*/
public static final String SUBJECT = "subject";
/**
* The body of the message
* <P>Type: TEXT</P>
*/
public static final String BODY = "body";
/**
* The id of the sender of the conversation, if present
* <P>Type: INTEGER (reference to item in content://contacts/people)</P>
*/
public static final String PERSON = "person";
/**
* The protocol identifier code
* <P>Type: INTEGER</P>
*/
public static final String PROTOCOL = "protocol";
/**
* Whether the <code>TP-Reply-Path</code> bit was set on this message
* <P>Type: BOOLEAN</P>
*/
public static final String REPLY_PATH_PRESENT = "reply_path_present";
/**
* The service center (SC) through which to send the message, if present
* <P>Type: TEXT</P>
*/
public static final String SERVICE_CENTER = "service_center";
/**
* Has the message been locked?
* <P>Type: INTEGER (boolean)</P>
*/
public static final String LOCKED = "locked";
/**
* Error code associated with sending or receiving this message
* <P>Type: INTEGER</P>
*/
public static final String ERROR_CODE = "error_code";
/**
* Meta data used externally.
* <P>Type: TEXT</P>
*/
public static final String META_DATA = "meta_data";
}
/**
* Contains all text based SMS messages.
*/
public static final class Sms implements BaseColumns, TextBasedSmsColumns {
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI =
Uri.parse("content://sms");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "date DESC";
/**
* Returns true iff the folder (message type) identifies an
* outgoing message.
*/
public static boolean isOutgoingFolder(int messageType) {
return (messageType == MESSAGE_TYPE_FAILED)
|| (messageType == MESSAGE_TYPE_OUTBOX)
|| (messageType == MESSAGE_TYPE_SENT)
|| (messageType == MESSAGE_TYPE_QUEUED);
}
/**
* Contains all text based SMS messages in the SMS app's inbox.
*/
public static final class Inbox implements BaseColumns, TextBasedSmsColumns {
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI =
Uri.parse("content://sms/inbox");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "date DESC";
}
/**
* Contains all sent text based SMS messages in the SMS app's.
*/
public static final class Sent implements BaseColumns, TextBasedSmsColumns {
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI =
Uri.parse("content://sms/sent");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "date DESC";
}
/**
* Contains all sent text based SMS messages in the SMS app's.
*/
public static final class Draft implements BaseColumns, TextBasedSmsColumns {
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI =
Uri.parse("content://sms/draft");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "date DESC";
}
/**
* Contains all pending outgoing text based SMS messages.
*/
public static final class Outbox implements BaseColumns, TextBasedSmsColumns {
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI =
Uri.parse("content://sms/outbox");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "date DESC";
}
/**
* Contains all sent text-based SMS messages in the SMS app's.
*/
public static final class Conversations
implements BaseColumns, TextBasedSmsColumns {
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI =
Uri.parse("content://sms/conversations");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "date DESC";
/**
* The first 45 characters of the body of the message
* <P>Type: TEXT</P>
*/
public static final String SNIPPET = "snippet";
/**
* The number of messages in the conversation
* <P>Type: INTEGER</P>
*/
public static final String MESSAGE_COUNT = "msg_count";
}
/**
* Contains info about SMS related Intents that are broadcast.
*/
public static final class Intents {
/**
* Set by BroadcastReceiver. Indicates the message was handled
* successfully.
*/
public static final int RESULT_SMS_HANDLED = 1;
/**
* Set by BroadcastReceiver. Indicates a generic error while
* processing the message.
*/
public static final int RESULT_SMS_GENERIC_ERROR = 2;
/**
* Set by BroadcastReceiver. Indicates insufficient memory to store
* the message.
*/
public static final int RESULT_SMS_OUT_OF_MEMORY = 3;
/**
* Set by BroadcastReceiver. Indicates the message, while
* possibly valid, is of a format or encoding that is not
* supported.
*/
public static final int RESULT_SMS_UNSUPPORTED = 4;
/**
* Broadcast Action: A new text based SMS message has been received
* by the device. The intent will have the following extra
* values:</p>
*
* <ul>
* <li><em>pdus</em> - An Object[] od byte[]s containing the PDUs
* that make up the message.</li>
* </ul>
*
* <p>The extra values can be extracted using
* {@link #getMessagesFromIntent(android.content.Intent)}.</p>
*
* <p>If a BroadcastReceiver encounters an error while processing
* this intent it should set the result code appropriately.</p>
*/
public static final String SMS_RECEIVED_ACTION =
"android.provider.Telephony.SMS_RECEIVED";
/**
* Broadcast Action: A new data based SMS message has been received
* by the device. The intent will have the following extra
* values:</p>
*
* <ul>
* <li><em>pdus</em> - An Object[] of byte[]s containing the PDUs
* that make up the message.</li>
* </ul>
*
* <p>The extra values can be extracted using
* {@link #getMessagesFromIntent(android.content.Intent)}.</p>
*
* <p>If a BroadcastReceiver encounters an error while processing
* this intent it should set the result code appropriately.</p>
*/
public static final String DATA_SMS_RECEIVED_ACTION =
"android.intent.action.DATA_SMS_RECEIVED";
/**
* Broadcast Action: A new WAP PUSH message has been received by the
* device. The intent will have the following extra
* values:</p>
*
* <ul>
* <li><em>transactionId (Integer)</em> - The WAP transaction ID</li>
* <li><em>pduType (Integer)</em> - The WAP PDU type</li>
* <li><em>header (byte[])</em> - The header of the message</li>
* <li><em>data (byte[])</em> - The data payload of the message</li>
* <li><em>contentTypeParameters (HashMap<String,String>)</em>
* - Any parameters associated with the content type
* (decoded from the WSP Content-Type header)</li>
* </ul>
*
* <p>If a BroadcastReceiver encounters an error while processing
* this intent it should set the result code appropriately.</p>
*
* <p>The contentTypeParameters extra value is map of content parameters keyed by
* their names.</p>
*
* <p>If any unassigned well-known parameters are encountered, the key of the map will
* be 'unassigned/0x...', where '...' is the hex value of the unassigned parameter. If
* a parameter has No-Value the value in the map will be null.</p>
*/
public static final String WAP_PUSH_RECEIVED_ACTION =
"android.provider.Telephony.WAP_PUSH_RECEIVED";
/**
* Broadcast Action: A new Cell Broadcast message has been received
* by the device. The intent will have the following extra
* values:</p>
*
* <ul>
* <li><em>message</em> - An SmsCbMessage object containing the broadcast message
* data. This is not an emergency alert, so ETWS and CMAS data will be null.</li>
* </ul>
*
* <p>The extra values can be extracted using
* {@link #getMessagesFromIntent(android.content.Intent)}.</p>
*
* <p>If a BroadcastReceiver encounters an error while processing
* this intent it should set the result code appropriately.</p>
*/
public static final String SMS_CB_RECEIVED_ACTION =
"android.provider.Telephony.SMS_CB_RECEIVED";
/**
* Broadcast Action: A new Emergency Broadcast message has been received
* by the device. The intent will have the following extra
* values:</p>
*
* <ul>
* <li><em>message</em> - An SmsCbMessage object containing the broadcast message
* data, including ETWS or CMAS warning notification info if present.</li>
* </ul>
*
* <p>The extra values can be extracted using
* {@link #getMessagesFromIntent(android.content.Intent)}.</p>
*
* <p>If a BroadcastReceiver encounters an error while processing
* this intent it should set the result code appropriately.</p>
*/
public static final String SMS_EMERGENCY_CB_RECEIVED_ACTION =
"android.provider.Telephony.SMS_EMERGENCY_CB_RECEIVED";
/**
* Broadcast Action: A new CDMA SMS has been received containing Service Category
* Program Data (updates the list of enabled broadcast channels). The intent will
* have the following extra values:</p>
*
* <ul>
* <li><em>operations</em> - An array of CdmaSmsCbProgramData objects containing
* the service category operations (add/delete/clear) to perform.</li>
* </ul>
*
* <p>The extra values can be extracted using
* {@link #getMessagesFromIntent(android.content.Intent)}.</p>
*
* <p>If a BroadcastReceiver encounters an error while processing
* this intent it should set the result code appropriately.</p>
*/
public static final String SMS_SERVICE_CATEGORY_PROGRAM_DATA_RECEIVED_ACTION =
"android.provider.Telephony.SMS_SERVICE_CATEGORY_PROGRAM_DATA_RECEIVED";
/**
* Broadcast Action: The SIM storage for SMS messages is full. If
* space is not freed, messages targeted for the SIM (class 2) may
* not be saved.
*/
public static final String SIM_FULL_ACTION =
"android.provider.Telephony.SIM_FULL";
/**
* Broadcast Action: An incoming SMS has been rejected by the
* telephony framework. This intent is sent in lieu of any
* of the RECEIVED_ACTION intents. The intent will have the
* following extra value:</p>
*
* <ul>
* <li><em>result</em> - An int result code, eg,
* <code>{@link #RESULT_SMS_OUT_OF_MEMORY}</code>,
* indicating the error returned to the network.</li>
* </ul>
*/
public static final String SMS_REJECTED_ACTION =
"android.provider.Telephony.SMS_REJECTED";
}
}
/**
* Base columns for tables that contain MMSs.
*/
public interface BaseMmsColumns extends BaseColumns {
public static final int MESSAGE_BOX_ALL = 0;
public static final int MESSAGE_BOX_INBOX = 1;
public static final int MESSAGE_BOX_SENT = 2;
public static final int MESSAGE_BOX_DRAFTS = 3;
public static final int MESSAGE_BOX_OUTBOX = 4;
/**
* The date the message was received.
* <P>Type: INTEGER (long)</P>
*/
public static final String DATE = "date";
/**
* The date the message was sent.
* <P>Type: INTEGER (long)</P>
*/
public static final String DATE_SENT = "date_sent";
/**
* The box which the message belong to, for example, MESSAGE_BOX_INBOX.
* <P>Type: INTEGER</P>
*/
public static final String MESSAGE_BOX = "msg_box";
/**
* Has the message been read.
* <P>Type: INTEGER (boolean)</P>
*/
public static final String READ = "read";
/**
* Indicates whether this message has been seen by the user. The "seen" flag will be
* used to figure out whether we need to throw up a statusbar notification or not.
*/
public static final String SEEN = "seen";
/**
* The Message-ID of the message.
* <P>Type: TEXT</P>
*/
public static final String MESSAGE_ID = "m_id";
/**
* The subject of the message, if present.
* <P>Type: TEXT</P>
*/
public static final String SUBJECT = "sub";
/**
* The character set of the subject, if present.
* <P>Type: INTEGER</P>
*/
public static final String SUBJECT_CHARSET = "sub_cs";
/**
* The Content-Type of the message.
* <P>Type: TEXT</P>
*/
public static final String CONTENT_TYPE = "ct_t";
/**
* The Content-Location of the message.
* <P>Type: TEXT</P>
*/
public static final String CONTENT_LOCATION = "ct_l";
/**
* The address of the sender.
* <P>Type: TEXT</P>
*/
public static final String FROM = "from";
/**
* The address of the recipients.
* <P>Type: TEXT</P>
*/
public static final String TO = "to";
/**
* The address of the cc. recipients.
* <P>Type: TEXT</P>
*/
public static final String CC = "cc";
/**
* The address of the bcc. recipients.
* <P>Type: TEXT</P>
*/
public static final String BCC = "bcc";
/**
* The expiry time of the message.
* <P>Type: INTEGER</P>
*/
public static final String EXPIRY = "exp";
/**
* The class of the message.
* <P>Type: TEXT</P>
*/
public static final String MESSAGE_CLASS = "m_cls";
/**
* The type of the message defined by MMS spec.
* <P>Type: INTEGER</P>
*/
public static final String MESSAGE_TYPE = "m_type";
/**
* The version of specification that this message conform.
* <P>Type: INTEGER</P>
*/
public static final String MMS_VERSION = "v";
/**
* The size of the message.
* <P>Type: INTEGER</P>
*/
public static final String MESSAGE_SIZE = "m_size";
/**
* The priority of the message.
* <P>Type: TEXT</P>
*/
public static final String PRIORITY = "pri";
/**
* The read-report of the message.
* <P>Type: TEXT</P>
*/
public static final String READ_REPORT = "rr";
/**
* Whether the report is allowed.
* <P>Type: TEXT</P>
*/
public static final String REPORT_ALLOWED = "rpt_a";
/**
* The response-status of the message.
* <P>Type: INTEGER</P>
*/
public static final String RESPONSE_STATUS = "resp_st";
/**
* The status of the message.
* <P>Type: INTEGER</P>
*/
public static final String STATUS = "st";
/**
* The transaction-id of the message.
* <P>Type: TEXT</P>
*/
public static final String TRANSACTION_ID = "tr_id";
/**
* The retrieve-status of the message.
* <P>Type: INTEGER</P>
*/
public static final String RETRIEVE_STATUS = "retr_st";
/**
* The retrieve-text of the message.
* <P>Type: TEXT</P>
*/
public static final String RETRIEVE_TEXT = "retr_txt";
/**
* The character set of the retrieve-text.
* <P>Type: TEXT</P>
*/
public static final String RETRIEVE_TEXT_CHARSET = "retr_txt_cs";
/**
* The read-status of the message.
* <P>Type: INTEGER</P>
*/
public static final String READ_STATUS = "read_status";
/**
* The content-class of the message.
* <P>Type: INTEGER</P>
*/
public static final String CONTENT_CLASS = "ct_cls";
/**
* The delivery-report of the message.
* <P>Type: INTEGER</P>
*/
public static final String DELIVERY_REPORT = "d_rpt";
/**
* The delivery-time-token of the message.
* <P>Type: INTEGER</P>
*/
public static final String DELIVERY_TIME_TOKEN = "d_tm_tok";
/**
* The delivery-time of the message.
* <P>Type: INTEGER</P>
*/
public static final String DELIVERY_TIME = "d_tm";
/**
* The response-text of the message.
* <P>Type: TEXT</P>
*/
public static final String RESPONSE_TEXT = "resp_txt";
/**
* The sender-visibility of the message.
* <P>Type: TEXT</P>
*/
public static final String SENDER_VISIBILITY = "s_vis";
/**
* The reply-charging of the message.
* <P>Type: INTEGER</P>
*/
public static final String REPLY_CHARGING = "r_chg";
/**
* The reply-charging-deadline-token of the message.
* <P>Type: INTEGER</P>
*/
public static final String REPLY_CHARGING_DEADLINE_TOKEN = "r_chg_dl_tok";
/**
* The reply-charging-deadline of the message.
* <P>Type: INTEGER</P>
*/
public static final String REPLY_CHARGING_DEADLINE = "r_chg_dl";
/**
* The reply-charging-id of the message.
* <P>Type: TEXT</P>
*/
public static final String REPLY_CHARGING_ID = "r_chg_id";
/**
* The reply-charging-size of the message.
* <P>Type: INTEGER</P>
*/
public static final String REPLY_CHARGING_SIZE = "r_chg_sz";
/**
* The previously-sent-by of the message.
* <P>Type: TEXT</P>
*/
public static final String PREVIOUSLY_SENT_BY = "p_s_by";
/**
* The previously-sent-date of the message.
* <P>Type: INTEGER</P>
*/
public static final String PREVIOUSLY_SENT_DATE = "p_s_d";
/**
* The store of the message.
* <P>Type: TEXT</P>
*/
public static final String STORE = "store";
/**
* The mm-state of the message.
* <P>Type: INTEGER</P>
*/
public static final String MM_STATE = "mm_st";
/**
* The mm-flags-token of the message.
* <P>Type: INTEGER</P>
*/
public static final String MM_FLAGS_TOKEN = "mm_flg_tok";
/**
* The mm-flags of the message.
* <P>Type: TEXT</P>
*/
public static final String MM_FLAGS = "mm_flg";
/**
* The store-status of the message.
* <P>Type: TEXT</P>
*/
public static final String STORE_STATUS = "store_st";
/**
* The store-status-text of the message.
* <P>Type: TEXT</P>
*/
public static final String STORE_STATUS_TEXT = "store_st_txt";
/**
* The stored of the message.
* <P>Type: TEXT</P>
*/
public static final String STORED = "stored";
/**
* The totals of the message.
* <P>Type: TEXT</P>
*/
public static final String TOTALS = "totals";
/**
* The mbox-totals of the message.
* <P>Type: TEXT</P>
*/
public static final String MBOX_TOTALS = "mb_t";
/**
* The mbox-totals-token of the message.
* <P>Type: INTEGER</P>
*/
public static final String MBOX_TOTALS_TOKEN = "mb_t_tok";
/**
* The quotas of the message.
* <P>Type: TEXT</P>
*/
public static final String QUOTAS = "qt";
/**
* The mbox-quotas of the message.
* <P>Type: TEXT</P>
*/
public static final String MBOX_QUOTAS = "mb_qt";
/**
* The mbox-quotas-token of the message.
* <P>Type: INTEGER</P>
*/
public static final String MBOX_QUOTAS_TOKEN = "mb_qt_tok";
/**
* The message-count of the message.
* <P>Type: INTEGER</P>
*/
public static final String MESSAGE_COUNT = "m_cnt";
/**
* The start of the message.
* <P>Type: INTEGER</P>
*/
public static final String START = "start";
/**
* The distribution-indicator of the message.
* <P>Type: TEXT</P>
*/
public static final String DISTRIBUTION_INDICATOR = "d_ind";
/**
* The element-descriptor of the message.
* <P>Type: TEXT</P>
*/
public static final String ELEMENT_DESCRIPTOR = "e_des";
/**
* The limit of the message.
* <P>Type: INTEGER</P>
*/
public static final String LIMIT = "limit";
/**
* The recommended-retrieval-mode of the message.
* <P>Type: INTEGER</P>
*/
public static final String RECOMMENDED_RETRIEVAL_MODE = "r_r_mod";
/**
* The recommended-retrieval-mode-text of the message.
* <P>Type: TEXT</P>
*/
public static final String RECOMMENDED_RETRIEVAL_MODE_TEXT = "r_r_mod_txt";
/**
* The status-text of the message.
* <P>Type: TEXT</P>
*/
public static final String STATUS_TEXT = "st_txt";
/**
* The applic-id of the message.
* <P>Type: TEXT</P>
*/
public static final String APPLIC_ID = "apl_id";
/**
* The reply-applic-id of the message.
* <P>Type: TEXT</P>
*/
public static final String REPLY_APPLIC_ID = "r_apl_id";
/**
* The aux-applic-id of the message.
* <P>Type: TEXT</P>
*/
public static final String AUX_APPLIC_ID = "aux_apl_id";
/**
* The drm-content of the message.
* <P>Type: TEXT</P>
*/
public static final String DRM_CONTENT = "drm_c";
/**
* The adaptation-allowed of the message.
* <P>Type: TEXT</P>
*/
public static final String ADAPTATION_ALLOWED = "adp_a";
/**
* The replace-id of the message.
* <P>Type: TEXT</P>
*/
public static final String REPLACE_ID = "repl_id";
/**
* The cancel-id of the message.
* <P>Type: TEXT</P>
*/
public static final String CANCEL_ID = "cl_id";
/**
* The cancel-status of the message.
* <P>Type: INTEGER</P>
*/
public static final String CANCEL_STATUS = "cl_st";
/**
* The thread ID of the message
* <P>Type: INTEGER</P>
*/
public static final String THREAD_ID = "thread_id";
/**
* Has the message been locked?
* <P>Type: INTEGER (boolean)</P>
*/
public static final String LOCKED = "locked";
/**
* Meta data used externally.
* <P>Type: TEXT</P>
*/
public static final String META_DATA = "meta_data";
}
/**
* Helper functions for the "threads" table used by MMS and SMS.
* Added by Roman.
*/
public static final class CanonicalAddresses implements CanonicalAddressesColumns {
public static final Uri CONTENT_URI = Uri.withAppendedPath(
MmsSms.CONTENT_URI, "canonical-addresses");
public static final Uri OBSOLETE_THREADS_URI = Uri.withAppendedPath(
CONTENT_URI, "obsolete");
// No one should construct an instance of this class.
private CanonicalAddresses() {
}
}
/**
* Columns for the "canonical_addresses" table used by MMS and
* SMS."
*/
public interface CanonicalAddressesColumns extends BaseColumns {
/**
* An address used in MMS or SMS. Email addresses are
* converted to lower case and are compared by string
* equality. Other addresses are compared using
* PHONE_NUMBERS_EQUAL.
* <P>Type: TEXT</P>
*/
public static final String ADDRESS = "address";
}
/**
* Columns for the "threads" table used by MMS and SMS.
*/
public interface ThreadsColumns extends BaseColumns {
/**
* The date at which the thread was created.
*
* <P>Type: INTEGER (long)</P>
*/
public static final String DATE = "date";
/**
* A string encoding of the recipient IDs of the recipients of
* the message, in numerical order and separated by spaces.
* <P>Type: TEXT</P>
*/
public static final String RECIPIENT_IDS = "recipient_ids";
/**
* The message count of the thread.
* <P>Type: INTEGER</P>
*/
public static final String MESSAGE_COUNT = "message_count";
/**
* Indicates whether all messages of the thread have been read.
* <P>Type: INTEGER</P>
*/
public static final String READ = "read";
/**
* The snippet of the latest message in the thread.
* <P>Type: TEXT</P>
*/
public static final String SNIPPET = "snippet";
/**
* The charset of the snippet.
* <P>Type: INTEGER</P>
*/
public static final String SNIPPET_CHARSET = "snippet_cs";
/**
* Type of the thread, either Threads.COMMON_THREAD or
* Threads.BROADCAST_THREAD.
* <P>Type: INTEGER</P>
*/
public static final String TYPE = "type";
/**
* Indicates whether there is a transmission error in the thread.
* <P>Type: INTEGER</P>
*/
public static final String ERROR = "error";
/**
* Indicates whether this thread contains any attachments.
* <P>Type: INTEGER</P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
}
/**
* Helper functions for the "threads" table used by MMS and SMS.
*/
public static final class Threads implements ThreadsColumns {
private static final String[] ID_PROJECTION = { BaseColumns._ID };
private static final String STANDARD_ENCODING = "UTF-8";
private static final Uri THREAD_ID_CONTENT_URI = Uri.parse(
"content://mms-sms/threadID");
public static final Uri CONTENT_URI = Uri.withAppendedPath(
MmsSms.CONTENT_URI, "conversations");
public static final Uri OBSOLETE_THREADS_URI = Uri.withAppendedPath(
CONTENT_URI, "obsolete");
public static final int COMMON_THREAD = 0;
public static final int BROADCAST_THREAD = 1;
// No one should construct an instance of this class.
private Threads() {
}
}
/**
* Contains all MMS messages.
*/
public static final class Mms implements BaseMmsColumns {
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI = Uri.parse("content://mms");
public static final Uri REPORT_REQUEST_URI = Uri.withAppendedPath(
CONTENT_URI, "report-request");
public static final Uri REPORT_STATUS_URI = Uri.withAppendedPath(
CONTENT_URI, "report-status");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "date DESC";
/**
* mailbox = name-addr
* name-addr = [display-name] angle-addr
* angle-addr = [CFWS] "<" addr-spec ">" [CFWS]
*/
public static final Pattern NAME_ADDR_EMAIL_PATTERN =
Pattern.compile("\\s*(\"[^\"]*\"|[^<>\"]+)\\s*<([^<>]+)>\\s*");
/**
* quoted-string = [CFWS]
* DQUOTE *([FWS] qcontent) [FWS] DQUOTE
* [CFWS]
*/
public static final Pattern QUOTED_STRING_PATTERN =
Pattern.compile("\\s*\"([^\"]*)\"\\s*");
public static final String getMessageBoxName(int msgBox) {
switch (msgBox) {
case MESSAGE_BOX_ALL:
return "all";
case MESSAGE_BOX_INBOX:
return "inbox";
case MESSAGE_BOX_SENT:
return "sent";
case MESSAGE_BOX_DRAFTS:
return "drafts";
case MESSAGE_BOX_OUTBOX:
return "outbox";
default:
throw new IllegalArgumentException("Invalid message box: " + msgBox);
}
}
public static String extractAddrSpec(String address) {
Matcher match = NAME_ADDR_EMAIL_PATTERN.matcher(address);
if (match.matches()) {
return match.group(2);
}
return address;
}
/**
* Returns true if the address is an email address
*
* @param address the input address to be tested
* @return true if address is an email address
*/
public static boolean isEmailAddress(String address) {
if (TextUtils.isEmpty(address)) {
return false;
}
String s = extractAddrSpec(address);
Matcher match = Patterns.EMAIL_ADDRESS.matcher(s);
return match.matches();
}
/**
* Returns true if the number is a Phone number
*
* @param number the input number to be tested
* @return true if number is a Phone number
*/
public static boolean isPhoneNumber(String number) {
if (TextUtils.isEmpty(number)) {
return false;
}
Matcher match = Patterns.PHONE.matcher(number);
return match.matches();
}
/**
* Contains all MMS messages in the MMS app's inbox.
*/
public static final class Inbox implements BaseMmsColumns {
/**
* The content:// style URL for this table
*/
public static final Uri
CONTENT_URI = Uri.parse("content://mms/inbox");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "date DESC";
}
/**
* Contains all MMS messages in the MMS app's sent box.
*/
public static final class Sent implements BaseMmsColumns {
/**
* The content:// style URL for this table
*/
public static final Uri
CONTENT_URI = Uri.parse("content://mms/sent");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "date DESC";
}
/**
* Contains all MMS messages in the MMS app's drafts box.
*/
public static final class Draft implements BaseMmsColumns {
/**
* The content:// style URL for this table
*/
public static final Uri
CONTENT_URI = Uri.parse("content://mms/drafts");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "date DESC";
}
/**
* Contains all MMS messages in the MMS app's outbox.
*/
public static final class Outbox implements BaseMmsColumns {
/**
* The content:// style URL for this table
*/
public static final Uri
CONTENT_URI = Uri.parse("content://mms/outbox");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "date DESC";
}
public static final class Addr implements BaseColumns {
/**
* The ID of MM which this address entry belongs to.
*/
public static final String MSG_ID = "msg_id";
/**
* The ID of contact entry in Phone Book.
*/
public static final String CONTACT_ID = "contact_id";
/**
* The address text.
*/
public static final String ADDRESS = "address";
/**
* Type of address, must be one of PduHeaders.BCC,
* PduHeaders.CC, PduHeaders.FROM, PduHeaders.TO.
*/
public static final String TYPE = "type";
/**
* Character set of this entry.
*/
public static final String CHARSET = "charset";
}
public static final class Part implements BaseColumns {
/**
* The identifier of the message which this part belongs to.
* <P>Type: INTEGER</P>
*/
public static final String MSG_ID = "mid";
/**
* The order of the part.
* <P>Type: INTEGER</P>
*/
public static final String SEQ = "seq";
/**
* The content type of the part.
* <P>Type: TEXT</P>
*/
public static final String CONTENT_TYPE = "ct";
/**
* The name of the part.
* <P>Type: TEXT</P>
*/
public static final String NAME = "name";
/**
* The charset of the part.
* <P>Type: TEXT</P>
*/
public static final String CHARSET = "chset";
/**
* The file name of the part.
* <P>Type: TEXT</P>
*/
public static final String FILENAME = "fn";
/**
* The content disposition of the part.
* <P>Type: TEXT</P>
*/
public static final String CONTENT_DISPOSITION = "cd";
/**
* The content ID of the part.
* <P>Type: INTEGER</P>
*/
public static final String CONTENT_ID = "cid";
/**
* The content location of the part.
* <P>Type: INTEGER</P>
*/
public static final String CONTENT_LOCATION = "cl";
/**
* The start of content-type of the message.
* <P>Type: INTEGER</P>
*/
public static final String CT_START = "ctt_s";
/**
* The type of content-type of the message.
* <P>Type: TEXT</P>
*/
public static final String CT_TYPE = "ctt_t";
/**
* The location(on filesystem) of the binary data of the part.
* <P>Type: INTEGER</P>
*/
public static final String _DATA = "_data";
public static final String TEXT = "text";
}
public static final class Rate {
public static final Uri CONTENT_URI = Uri.withAppendedPath(
Mms.CONTENT_URI, "rate");
/**
* When a message was successfully sent.
* <P>Type: INTEGER</P>
*/
public static final String SENT_TIME = "sent_time";
}
public static final class Intents {
private Intents() {
// Non-instantiatable.
}
/**
* The extra field to store the contents of the Intent,
* which should be an array of Uri.
*/
public static final String EXTRA_CONTENTS = "contents";
/**
* The extra field to store the type of the contents,
* which should be an array of String.
*/
public static final String EXTRA_TYPES = "types";
/**
* The extra field to store the 'Cc' addresses.
*/
public static final String EXTRA_CC = "cc";
/**
* The extra field to store the 'Bcc' addresses;
*/
public static final String EXTRA_BCC = "bcc";
/**
* The extra field to store the 'Subject'.
*/
public static final String EXTRA_SUBJECT = "subject";
/**
* Indicates that the contents of specified URIs were changed.
* The application which is showing or caching these contents
* should be updated.
*/
public static final String
CONTENT_CHANGED_ACTION = "android.intent.action.CONTENT_CHANGED";
/**
* An extra field which stores the URI of deleted contents.
*/
public static final String DELETED_CONTENTS = "deleted_contents";
}
}
/**
* Contains all MMS and SMS messages.
*/
public static final class MmsSms implements BaseColumns {
/**
* The column to distinguish SMS & MMS messages in query results.
*/
public static final String TYPE_DISCRIMINATOR_COLUMN =
"transport_type";
public static final Uri CONTENT_URI = Uri.parse("content://mms-sms/");
public static final Uri CONTENT_CONVERSATIONS_URI = Uri.parse(
"content://mms-sms/conversations");
public static final Uri CONTENT_FILTER_BYPHONE_URI = Uri.parse(
"content://mms-sms/messages/byphone");
public static final Uri CONTENT_UNDELIVERED_URI = Uri.parse(
"content://mms-sms/undelivered");
public static final Uri CONTENT_DRAFT_URI = Uri.parse(
"content://mms-sms/draft");
public static final Uri CONTENT_LOCKED_URI = Uri.parse(
"content://mms-sms/locked");
/***
* Pass in a query parameter called "pattern" which is the text
* to search for.
* The sort order is fixed to be thread_id ASC,date DESC.
*/
public static final Uri SEARCH_URI = Uri.parse(
"content://mms-sms/search");
// Constants for message protocol types.
public static final int SMS_PROTO = 0;
public static final int MMS_PROTO = 1;
// Constants for error types of pending messages.
public static final int NO_ERROR = 0;
public static final int ERR_TYPE_GENERIC = 1;
public static final int ERR_TYPE_SMS_PROTO_TRANSIENT = 2;
public static final int ERR_TYPE_MMS_PROTO_TRANSIENT = 3;
public static final int ERR_TYPE_TRANSPORT_FAILURE = 4;
public static final int ERR_TYPE_GENERIC_PERMANENT = 10;
public static final int ERR_TYPE_SMS_PROTO_PERMANENT = 11;
public static final int ERR_TYPE_MMS_PROTO_PERMANENT = 12;
public static final class PendingMessages implements BaseColumns {
public static final Uri CONTENT_URI = Uri.withAppendedPath(
MmsSms.CONTENT_URI, "pending");
/**
* The type of transport protocol(MMS or SMS).
* <P>Type: INTEGER</P>
*/
public static final String PROTO_TYPE = "proto_type";
/**
* The ID of the message to be sent or downloaded.
* <P>Type: INTEGER</P>
*/
public static final String MSG_ID = "msg_id";
/**
* The type of the message to be sent or downloaded.
* This field is only valid for MM. For SM, its value is always
* set to 0.
*/
public static final String MSG_TYPE = "msg_type";
/**
* The type of the error code.
* <P>Type: INTEGER</P>
*/
public static final String ERROR_TYPE = "err_type";
/**
* The error code of sending/retrieving process.
* <P>Type: INTEGER</P>
*/
public static final String ERROR_CODE = "err_code";
/**
* How many times we tried to send or download the message.
* <P>Type: INTEGER</P>
*/
public static final String RETRY_INDEX = "retry_index";
/**
* The time to do next retry.
*/
public static final String DUE_TIME = "due_time";
/**
* The time we last tried to send or download the message.
*/
public static final String LAST_TRY = "last_try";
}
public static final class WordsTable {
public static final String ID = "_id";
public static final String SOURCE_ROW_ID = "source_id";
public static final String TABLE_ID = "table_to_use";
public static final String INDEXED_TEXT = "index_text";
}
}
public static final class Carriers implements BaseColumns {
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI =
Uri.parse("content://telephony/carriers");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "name ASC";
public static final String NAME = "name";
public static final String APN = "apn";
public static final String PROXY = "proxy";
public static final String PORT = "port";
public static final String MMSPROXY = "mmsproxy";
public static final String MMSPORT = "mmsport";
public static final String SERVER = "server";
public static final String USER = "user";
public static final String PASSWORD = "password";
public static final String MMSC = "mmsc";
public static final String MCC = "mcc";
public static final String MNC = "mnc";
public static final String NUMERIC = "numeric";
public static final String AUTH_TYPE = "authtype";
public static final String TYPE = "type";
public static final String INACTIVE_TIMER = "inactivetimer";
// Only if enabled try Data Connection.
public static final String ENABLED = "enabled";
// Rules apply based on class.
public static final String CLASS = "class";
/**
* The protocol to be used to connect to this APN.
*
* One of the PDP_type values in TS 27.007 section 10.1.1.
* For example, "IP", "IPV6", "IPV4V6", or "PPP".
*/
public static final String PROTOCOL = "protocol";
/**
* The protocol to be used to connect to this APN when roaming.
*
* The syntax is the same as protocol.
*/
public static final String ROAMING_PROTOCOL = "roaming_protocol";
public static final String CURRENT = "current";
/**
* Current status of APN
* true : enabled APN, false : disabled APN.
*/
public static final String CARRIER_ENABLED = "carrier_enabled";
/**
* Radio Access Technology info
* To check what values can hold, refer to ServiceState.java.
* This should be spread to other technologies,
* but currently only used for LTE(14) and EHRPD(13).
*/
public static final String BEARER = "bearer";
}
/**
* Contains received SMS cell broadcast messages.
*/
public static final class CellBroadcasts implements BaseColumns {
/** Not instantiable. */
private CellBroadcasts() {}
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI =
Uri.parse("content://cellbroadcasts");
/**
* Message geographical scope.
* <P>Type: INTEGER</P>
*/
public static final String GEOGRAPHICAL_SCOPE = "geo_scope";
/**
* Message serial number.
* <P>Type: INTEGER</P>
*/
public static final String SERIAL_NUMBER = "serial_number";
/**
* PLMN of broadcast sender. (SERIAL_NUMBER + PLMN + LAC + CID) uniquely identifies a
* broadcast for duplicate detection purposes.
* <P>Type: TEXT</P>
*/
public static final String PLMN = "plmn";
/**
* Location Area (GSM) or Service Area (UMTS) of broadcast sender. Unused for CDMA.
* Only included if Geographical Scope of message is not PLMN wide (01).
* <P>Type: INTEGER</P>
*/
public static final String LAC = "lac";
/**
* Cell ID of message sender (GSM/UMTS). Unused for CDMA. Only included when the
* Geographical Scope of message is cell wide (00 or 11).
* <P>Type: INTEGER</P>
*/
public static final String CID = "cid";
/**
* Message code (OBSOLETE: merged into SERIAL_NUMBER).
* <P>Type: INTEGER</P>
*/
public static final String V1_MESSAGE_CODE = "message_code";
/**
* Message identifier (OBSOLETE: renamed to SERVICE_CATEGORY).
* <P>Type: INTEGER</P>
*/
public static final String V1_MESSAGE_IDENTIFIER = "message_id";
/**
* Service category (GSM/UMTS message identifier, CDMA service category).
* <P>Type: INTEGER</P>
*/
public static final String SERVICE_CATEGORY = "service_category";
/**
* Message language code.
* <P>Type: TEXT</P>
*/
public static final String LANGUAGE_CODE = "language";
/**
* Message body.
* <P>Type: TEXT</P>
*/
public static final String MESSAGE_BODY = "body";
/**
* Message delivery time.
* <P>Type: INTEGER (long)</P>
*/
public static final String DELIVERY_TIME = "date";
/**
* Has the message been viewed?
* <P>Type: INTEGER (boolean)</P>
*/
public static final String MESSAGE_READ = "read";
/**
* Message format (3GPP or 3GPP2).
* <P>Type: INTEGER</P>
*/
public static final String MESSAGE_FORMAT = "format";
/**
* Message priority (including emergency).
* <P>Type: INTEGER</P>
*/
public static final String MESSAGE_PRIORITY = "priority";
/**
* ETWS warning type (ETWS alerts only).
* <P>Type: INTEGER</P>
*/
public static final String ETWS_WARNING_TYPE = "etws_warning_type";
/**
* CMAS message class (CMAS alerts only).
* <P>Type: INTEGER</P>
*/
public static final String CMAS_MESSAGE_CLASS = "cmas_message_class";
/**
* CMAS category (CMAS alerts only).
* <P>Type: INTEGER</P>
*/
public static final String CMAS_CATEGORY = "cmas_category";
/**
* CMAS response type (CMAS alerts only).
* <P>Type: INTEGER</P>
*/
public static final String CMAS_RESPONSE_TYPE = "cmas_response_type";
/**
* CMAS severity (CMAS alerts only).
* <P>Type: INTEGER</P>
*/
public static final String CMAS_SEVERITY = "cmas_severity";
/**
* CMAS urgency (CMAS alerts only).
* <P>Type: INTEGER</P>
*/
public static final String CMAS_URGENCY = "cmas_urgency";
/**
* CMAS certainty (CMAS alerts only).
* <P>Type: INTEGER</P>
*/
public static final String CMAS_CERTAINTY = "cmas_certainty";
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = DELIVERY_TIME + " DESC";
/**
* Query columns for instantiating {@link android.telephony.CellBroadcastMessage} objects.
*/
public static final String[] QUERY_COLUMNS = {
_ID,
GEOGRAPHICAL_SCOPE,
PLMN,
LAC,
CID,
SERIAL_NUMBER,
SERVICE_CATEGORY,
LANGUAGE_CODE,
MESSAGE_BODY,
DELIVERY_TIME,
MESSAGE_READ,
MESSAGE_FORMAT,
MESSAGE_PRIORITY,
ETWS_WARNING_TYPE,
CMAS_MESSAGE_CLASS,
CMAS_CATEGORY,
CMAS_RESPONSE_TYPE,
CMAS_SEVERITY,
CMAS_URGENCY,
CMAS_CERTAINTY
};
}
public static final class Intents {
private Intents() {
// Not instantiable
}
/**
* Broadcast Action: A "secret code" has been entered in the dialer. Secret codes are
* of the form *#*#<code>#*#*. The intent will have the data URI:</p>
*
* <p><code>android_secret_code://<code></code></p>
*/
public static final String SECRET_CODE_ACTION =
"android.provider.Telephony.SECRET_CODE";
/**
* Broadcast Action: The Service Provider string(s) have been updated. Activities or
* services that use these strings should update their display.
* The intent will have the following extra values:</p>
* <ul>
* <li><em>showPlmn</em> - Boolean that indicates whether the PLMN should be shown.</li>
* <li><em>plmn</em> - The operator name of the registered network, as a string.</li>
* <li><em>showSpn</em> - Boolean that indicates whether the SPN should be shown.</li>
* <li><em>spn</em> - The service provider name, as a string.</li>
* </ul>
* Note that <em>showPlmn</em> may indicate that <em>plmn</em> should be displayed, even
* though the value for <em>plmn</em> is null. This can happen, for example, if the phone
* has not registered to a network yet. In this case the receiver may substitute an
* appropriate placeholder string (eg, "No service").
*
* It is recommended to display <em>plmn</em> before / above <em>spn</em> if
* both are displayed.
*
* <p>Note this is a protected intent that can only be sent
* by the system.
*/
public static final String SPN_STRINGS_UPDATED_ACTION =
"android.provider.Telephony.SPN_STRINGS_UPDATED";
public static final String EXTRA_SHOW_PLMN = "showPlmn";
public static final String EXTRA_PLMN = "plmn";
public static final String EXTRA_SHOW_SPN = "showSpn";
public static final String EXTRA_SPN = "spn";
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/phone/TelephonyProviderConstants.java | Java | asf20 | 57,588 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.calendar;
import com.google.android.apps.dashclock.LogUtils;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import net.nurik.roman.dashclock.R;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.CalendarContract;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Pair;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
import static com.google.android.apps.dashclock.LogUtils.LOGD;
import static com.google.android.apps.dashclock.LogUtils.LOGE;
/**
* Calendar "upcoming appointment" extension.
*/
public class CalendarExtension extends DashClockExtension {
private static final String TAG = LogUtils.makeLogTag(CalendarExtension.class);
public static final String PREF_CUSTOM_VISIBILITY = "pref_calendar_custom_visibility";
public static final String PREF_SELECTED_CALENDARS = "pref_calendar_selected";
public static final String PREF_LOOK_AHEAD_HOURS = "pref_calendar_look_ahead_hours";
public static final String PREF_SHOW_ALL_DAY = "pref_calendar_show_all_day";
private static final String SQL_TAUTOLOGY = "1=1";
private static final long MINUTE_MILLIS = 60 * 1000;
private static final long HOUR_MILLIS = 60 * MINUTE_MILLIS;
// Show events happening "now" if they started under 5 minutes ago
public static final long NOW_BUFFER_TIME_MILLIS = 5 * MINUTE_MILLIS;
private static final int DEFAULT_LOOK_AHEAD_HOURS = 6;
private int mLookAheadHours = DEFAULT_LOOK_AHEAD_HOURS;
static List<Pair<String, Boolean>> getAllCalendars(Context context) {
// Only return calendars that are marked as synced to device.
// (This is different from the display flag)
List<Pair<String, Boolean>> calendars = new ArrayList<Pair<String, Boolean>>();
try {
Cursor cursor = context.getContentResolver().query(
CalendarContract.Calendars.CONTENT_URI,
CalendarsQuery.PROJECTION,
CalendarContract.Calendars.SYNC_EVENTS + "=1",
null,
null);
if (cursor != null) {
while (cursor.moveToNext()) {
calendars.add(new Pair<String, Boolean>(
cursor.getString(CalendarsQuery.ID),
cursor.getInt(CalendarsQuery.VISIBLE) == 1));
}
cursor.close();
}
} catch (SecurityException e) {
LOGE(TAG, "Error querying calendar API", e);
return null;
}
return calendars;
}
private Set<String> getSelectedCalendars() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean customVisibility = sp.getBoolean(PREF_CUSTOM_VISIBILITY, false);
Set<String> selectedCalendars = sp.getStringSet(PREF_SELECTED_CALENDARS, null);
if (!customVisibility || selectedCalendars == null) {
final List<Pair<String, Boolean>> allCalendars = getAllCalendars(this);
// Build a set of all visible calendars in case we don't have a selection set in
// the preferences.
selectedCalendars = new HashSet<String>();
for (Pair<String, Boolean> pair : allCalendars) {
if (pair.second) {
selectedCalendars.add(pair.first);
}
}
}
return selectedCalendars;
}
@Override
protected void onInitialize(boolean isReconnect) {
super.onInitialize(isReconnect);
if (!isReconnect) {
addWatchContentUris(new String[]{
CalendarContract.Events.CONTENT_URI.toString()
});
}
setUpdateWhenScreenOn(true);
}
@Override
protected void onUpdateData(int reason) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean showAllDay = sp.getBoolean(PREF_SHOW_ALL_DAY, false);
try {
mLookAheadHours = Integer.parseInt(sp.getString(PREF_LOOK_AHEAD_HOURS,
Integer.toString(mLookAheadHours)));
} catch (NumberFormatException e) {
mLookAheadHours = DEFAULT_LOOK_AHEAD_HOURS;
}
Cursor cursor = tryOpenEventsCursor(showAllDay);
if (cursor == null) {
LOGE(TAG, "Null events cursor, short-circuiting.");
return;
}
long currentTimestamp = getCurrentTimestamp();
long nextTimestamp = 0;
long endTimestamp = 0;
long timeUntilNextAppointent = 0;
boolean allDay = false;
int allDayPosition = -1;
long allDayTimestampLocalMidnight = 0;
while (cursor.moveToNext()) {
nextTimestamp = cursor.getLong(EventsQuery.BEGIN);
int tzOffset = TimeZone.getDefault().getOffset(nextTimestamp);
allDay = cursor.getInt(EventsQuery.ALL_DAY) != 0;
if (allDay) {
endTimestamp = cursor.getLong(EventsQuery.END) - tzOffset;
if (showAllDay && allDayPosition < 0 && endTimestamp > currentTimestamp) {
// Store the position of this all day event. If no regular events are found
// and the user wanted to see all day events, then show this all day event.
allDayPosition = cursor.getPosition();
// For all day events (if the user wants to see them), convert the begin
// timestamp, which is the midnight UTC time, to local time. That is,
// allDayTimestampLocalMidnight will be midnight in local time since that's a
// more relevant representation of that day to the user.
allDayTimestampLocalMidnight = nextTimestamp - tzOffset;
}
continue;
}
timeUntilNextAppointent = nextTimestamp - currentTimestamp;
if (timeUntilNextAppointent >= -NOW_BUFFER_TIME_MILLIS) {
// Use this event even if it's already started, a few minutes in
break;
}
// Skip over events that are not ALL_DAY but span multiple days, including
// the next 6 hours. An example is an event that starts at 4pm yesterday
// day and ends 6pm tomorrow.
LOGD(TAG, "Skipping over event with start timestamp " + nextTimestamp + ". "
+ "Current timestamp " + currentTimestamp);
}
if (allDayPosition >= 0) {
// Only show all day events if there's no regular event (cursor is after last)
// or if the all day event is tomorrow or later and the all day event is earlier than
// the regular event.
if (cursor.isAfterLast()
|| ((allDayTimestampLocalMidnight - currentTimestamp) > 0
&& allDayTimestampLocalMidnight < nextTimestamp)) {
cursor.moveToPosition(allDayPosition);
allDay = true;
nextTimestamp = allDayTimestampLocalMidnight;
timeUntilNextAppointent = nextTimestamp - currentTimestamp;
LOGD(TAG, "Showing an all day event because either no regular event was found or "
+ "it's a full day later than the all-day event.");
}
}
if (cursor.isAfterLast()) {
LOGD(TAG, "No upcoming appointments found.");
cursor.close();
publishUpdate(new ExtensionData());
return;
}
Calendar nextEventCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
nextEventCalendar.setTimeInMillis(nextTimestamp);
int minutesUntilNextAppointment = (int) (timeUntilNextAppointent / MINUTE_MILLIS);
String untilString;
if (allDay) {
if (timeUntilNextAppointent <= 0) {
// All day event happening today (its start time is past today's midnight
// offset.
untilString = getString(R.string.today);
} else {
untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime());
}
} else if (minutesUntilNextAppointment < 2) {
untilString = getResources().getString(R.string.now);
} else if (minutesUntilNextAppointment < 60) {
untilString = getResources().getQuantityString(
R.plurals.calendar_template_mins,
minutesUntilNextAppointment,
minutesUntilNextAppointment);
} else {
int hours = Math.round(minutesUntilNextAppointment / 60f);
if (hours < 24) {
untilString = getResources().getQuantityString(
R.plurals.calendar_template_hours, hours, hours);
} else {
untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime());
}
}
String eventTitle = cursor.getString(EventsQuery.TITLE);
String eventLocation = cursor.getString(EventsQuery.EVENT_LOCATION);
long eventId = cursor.getLong(EventsQuery.EVENT_ID);
long eventBegin = cursor.getLong(EventsQuery.BEGIN);
long eventEnd = cursor.getLong(EventsQuery.END);
cursor.close();
String expandedTime = null;
StringBuilder expandedTimeFormat = new StringBuilder();
if (allDay) {
if (timeUntilNextAppointent <= 0) {
// All day event happening today (its start time is past today's midnight
// offset.
expandedTimeFormat.setLength(0);
expandedTime = getString(R.string.today);
} else {
expandedTimeFormat.append("EEEE, MMM dd");
}
} else if (minutesUntilNextAppointment < 2) {
// Event happening right now!
expandedTimeFormat.setLength(0);
expandedTime = getString(R.string.now);
} else {
if (timeUntilNextAppointent > 24 * HOUR_MILLIS) {
expandedTimeFormat.append("EEEE, ");
}
if (DateFormat.is24HourFormat(this)) {
expandedTimeFormat.append("HH:mm");
} else {
expandedTimeFormat.append("h:mm a");
}
}
if (expandedTimeFormat.length() > 0) {
expandedTime = new SimpleDateFormat(expandedTimeFormat.toString())
.format(nextEventCalendar.getTime());
}
String expandedBody = expandedTime;
if (!TextUtils.isEmpty(eventLocation)) {
expandedBody = getString(R.string.calendar_with_location_template,
expandedTime, eventLocation);
}
publishUpdate(new ExtensionData()
.visible(allDay || (timeUntilNextAppointent >= -NOW_BUFFER_TIME_MILLIS
&& timeUntilNextAppointent <= mLookAheadHours * HOUR_MILLIS))
.icon(R.drawable.ic_extension_calendar)
.status(untilString)
.expandedTitle(eventTitle)
.expandedBody(expandedBody)
.clickIntent(new Intent(Intent.ACTION_VIEW)
.setData(Uri.withAppendedPath(CalendarContract.Events.CONTENT_URI,
Long.toString(eventId)))
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, eventBegin)
.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, eventEnd)));
}
private static long getCurrentTimestamp() {
return Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis();
}
private Cursor tryOpenEventsCursor(boolean showAllDay) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean customVisibility = sp.getBoolean(PREF_CUSTOM_VISIBILITY, false);
// Filter out all day events unless the user expressly requested to show all day events
String allDaySelection = SQL_TAUTOLOGY;
if (!showAllDay) {
allDaySelection = CalendarContract.Instances.ALL_DAY + "=0";
}
// Only filter on visible calendars if there isn't custom visibility
String visibleCalendarsSelection = SQL_TAUTOLOGY;
if (!customVisibility) {
allDaySelection = CalendarContract.Instances.VISIBLE + "!=0";
}
String calendarSelection = generateCalendarSelection();
Set<String> calendarSet = getSelectedCalendars();
String[] calendarsSelectionArgs = calendarSet.toArray(new String[calendarSet.size()]);
long now = getCurrentTimestamp();
try {
return getContentResolver().query(
CalendarContract.Instances.CONTENT_URI.buildUpon()
.appendPath(Long.toString(now - NOW_BUFFER_TIME_MILLIS))
.appendPath(Long.toString(now + mLookAheadHours * HOUR_MILLIS))
.build(),
EventsQuery.PROJECTION,
allDaySelection + " AND "
+ CalendarContract.Instances.SELF_ATTENDEE_STATUS + "!="
+ CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED + " AND "
+ "IFNULL(" + CalendarContract.Instances.STATUS + ",0)!="
+ CalendarContract.Instances.STATUS_CANCELED + " AND "
+ visibleCalendarsSelection + " AND ("
+ calendarSelection + ")",
calendarsSelectionArgs,
CalendarContract.Instances.BEGIN);
} catch (Exception e) {
LOGE(TAG, "Error querying calendar API", e);
return null;
}
}
private String generateCalendarSelection() {
Set<String> calendars = getSelectedCalendars();
int count = calendars.size();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
if (i != 0) {
sb.append(" OR ");
}
sb.append(CalendarContract.Events.CALENDAR_ID);
sb.append(" = ?");
}
if (sb.length() == 0) {
sb.append(SQL_TAUTOLOGY); // constant expression to prevent returning null
}
return sb.toString();
}
private interface EventsQuery {
String[] PROJECTION = {
CalendarContract.Instances.EVENT_ID,
CalendarContract.Instances.BEGIN,
CalendarContract.Instances.END,
CalendarContract.Instances.TITLE,
CalendarContract.Instances.EVENT_LOCATION,
CalendarContract.Instances.ALL_DAY,
};
int EVENT_ID = 0;
int BEGIN = 1;
int END = 2;
int TITLE = 3;
int EVENT_LOCATION = 4;
int ALL_DAY = 5;
}
private interface CalendarsQuery {
String[] PROJECTION = {
CalendarContract.Calendars._ID,
CalendarContract.Calendars.VISIBLE,
};
int ID = 0;
int VISIBLE = 1;
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/calendar/CalendarExtension.java | Java | asf20 | 16,269 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.calendar;
import com.google.android.apps.dashclock.configuration.BaseSettingsActivity;
import net.nurik.roman.dashclock.R;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.util.Pair;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CalendarSettingsActivity extends BaseSettingsActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setIcon(R.drawable.ic_extension_calendar);
}
@Override
protected void setupSimplePreferencesScreen() {
// Add 'general' preferences.
addPreferencesFromResource(R.xml.pref_calendar);
bindSelectedCalendarsPreference();
// Bind the summaries of EditText/List/Dialog/Ringtone preferences to
// their values. When their values change, their summaries are updated
// to reflect the new value, per the Android Design guidelines.
bindPreferenceSummaryToValue(findPreference(CalendarExtension.PREF_LOOK_AHEAD_HOURS));
}
private void bindSelectedCalendarsPreference() {
CalendarSelectionPreference preference = (CalendarSelectionPreference) findPreference(
CalendarExtension.PREF_SELECTED_CALENDARS);
final List<Pair<String, Boolean>> allCalendars = CalendarExtension.getAllCalendars(this);
Set<String> allVisibleCalendarsSet = new HashSet<String>();
for (Pair<String, Boolean> pair : allCalendars) {
if (pair.second) {
allVisibleCalendarsSet.add(pair.first);
}
}
Preference.OnPreferenceChangeListener calendarsChangeListener
= new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
int numSelected = 0;
int numTotal = allCalendars.size();
try {
//noinspection check,unchecked
Set<String> selectedCalendars = (Set<String>) value;
if (selectedCalendars != null) {
numSelected = selectedCalendars.size();
}
} catch (ClassCastException ignored) {
}
preference.setSummary(getResources().getQuantityString(
R.plurals.pref_calendar_selected_summary_template,
numTotal, numSelected, numTotal));
return true;
}
};
preference.setOnPreferenceChangeListener(calendarsChangeListener);
calendarsChangeListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(this)
.getStringSet(preference.getKey(), allVisibleCalendarsSet));
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/calendar/CalendarSettingsActivity.java | Java | asf20 | 3,582 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.calendar;
import net.nurik.roman.dashclock.R;
import android.app.AlertDialog.Builder;
import android.content.AsyncQueryHandler;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.preference.MultiSelectListPreference;
import android.preference.PreferenceManager;
import android.provider.CalendarContract;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CalendarSelectionPreference extends MultiSelectListPreference {
private CalendarListAdapter mAdapter;
private QueryHandler mQueryHandler;
private Set<String> mSelectedCalendars;
public CalendarSelectionPreference(Context context) {
this(context, null);
}
public CalendarSelectionPreference(Context context, AttributeSet attrs) {
super(context, attrs);
List<Pair<String, Boolean>> allCalendars = CalendarExtension.getAllCalendars(context);
Set<String> allVisibleCalendarsSet = new HashSet<String>();
for (Pair<String, Boolean> pair : allCalendars) {
if (pair.second) {
allVisibleCalendarsSet.add(pair.first);
}
}
mSelectedCalendars = new HashSet<String>(PreferenceManager
.getDefaultSharedPreferences(context)
.getStringSet(CalendarExtension.PREF_SELECTED_CALENDARS, allVisibleCalendarsSet));
mAdapter = new CalendarListAdapter(context);
mQueryHandler = new QueryHandler(context, mAdapter);
mQueryHandler.startQuery(0,
null,
CalendarContract.Calendars.CONTENT_URI,
CalendarQuery.PROJECTION,
CalendarContract.Calendars.SYNC_EVENTS + "=1",
null,
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME);
}
@Override
protected void onPrepareDialogBuilder(Builder builder) {
builder.setAdapter(mAdapter, null);
builder.setTitle(R.string.pref_calendar_selected_title);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
sp.edit().putStringSet(CalendarExtension.PREF_SELECTED_CALENDARS,
mSelectedCalendars).commit();
// since we have extended the list preference, it is our responsibility to inform the change listener.
if (getOnPreferenceChangeListener() != null) {
getOnPreferenceChangeListener()
.onPreferenceChange(CalendarSelectionPreference.this,
mSelectedCalendars);
}
}
});
}
static class QueryHandler extends AsyncQueryHandler {
private final CalendarListAdapter mAdapter;
public QueryHandler(Context context, CalendarListAdapter adapter) {
super(context.getContentResolver());
mAdapter = adapter;
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
mAdapter.swapCursor(cursor);
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
// No support for default value attribute
return null;
}
public class CalendarListAdapter extends ResourceCursorAdapter {
public CalendarListAdapter(Context context) {
super(context, R.layout.list_item_calendar, null, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView calendarNameView = (TextView) view.findViewById(android.R.id.text1);
calendarNameView.setText(cursor.getString(CalendarQuery.CALENDAR_DISPLAY_NAME));
TextView accountNameView = (TextView) view.findViewById(android.R.id.text2);
accountNameView.setText(cursor.getString(CalendarQuery.ACCOUNT_NAME));
final String calendarId = cursor.getString(CalendarQuery.ID);
final CheckBox checkBox = (CheckBox) view.findViewById(R.id.calendar_checkbox);
checkBox.setChecked(mSelectedCalendars.contains(calendarId));
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mSelectedCalendars.contains(calendarId)) {
mSelectedCalendars.remove(calendarId);
checkBox.setChecked(false);
} else {
mSelectedCalendars.add(calendarId);
checkBox.setChecked(true);
}
}
});
}
}
interface CalendarQuery {
public String[] PROJECTION = new String[] {
CalendarContract.Calendars._ID,
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
CalendarContract.Calendars.ACCOUNT_NAME,
};
public int ID = 0;
public int CALENDAR_DISPLAY_NAME = 1;
public int ACCOUNT_NAME = 2;
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/calendar/CalendarSelectionPreference.java | Java | asf20 | 6,189 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.gmail;
import com.google.android.apps.dashclock.configuration.BaseSettingsActivity;
import net.nurik.roman.dashclock.R;
import android.os.Bundle;
import android.preference.MultiSelectListPreference;
import android.preference.Preference;
import android.preference.PreferenceManager;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class GmailSettingsActivity extends BaseSettingsActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setIcon(R.drawable.ic_extension_gmail);
}
@Override
protected void setupSimplePreferencesScreen() {
// In the simplified UI, fragments are not used at all and we instead
// use the older PreferenceActivity APIs.
// Add 'general' preferences.
addPreferencesFromResource(R.xml.pref_gmail);
addAccountsPreference();
// Bind the summaries of EditText/List/Dialog/Ringtone preferences to
// their values. When their values change, their summaries are updated
// to reflect the new value, per the Android Design guidelines.
bindPreferenceSummaryToValue(findPreference(GmailExtension.PREF_LABEL));
}
private void addAccountsPreference() {
final String[] accounts = GmailExtension.getAllAccountNames(this);
Set<String> allAccountsSet = new HashSet<String>();
allAccountsSet.addAll(Arrays.asList(accounts));
MultiSelectListPreference accountsPreference = new MultiSelectListPreference(this);
accountsPreference.setKey(GmailExtension.PREF_ACCOUNTS);
accountsPreference.setTitle(R.string.pref_gmail_accounts_title);
accountsPreference.setEntries(accounts);
accountsPreference.setEntryValues(accounts);
accountsPreference.setDefaultValue(allAccountsSet);
getPreferenceScreen().addPreference(accountsPreference);
Preference.OnPreferenceChangeListener accountsChangeListener
= new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
int numSelected = 0;
int numTotal = accounts.length;
try {
//noinspection unchecked
Set<String> selectedAccounts = (Set<String>) value;
if (selectedAccounts != null) {
numSelected = selectedAccounts.size();
}
} catch (ClassCastException ignored) {
}
preference.setSummary(getResources().getQuantityString(
R.plurals.pref_gmail_accounts_summary_template,
numTotal, numSelected, numTotal));
return true;
}
};
accountsPreference.setOnPreferenceChangeListener(accountsChangeListener);
accountsChangeListener.onPreferenceChange(accountsPreference,
PreferenceManager
.getDefaultSharedPreferences(this)
.getStringSet(accountsPreference.getKey(), allAccountsSet));
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/gmail/GmailSettingsActivity.java | Java | asf20 | 3,850 |
/*
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.gmail;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PermissionInfo;
import android.content.pm.ProviderInfo;
import android.net.Uri;
import android.text.TextUtils;
/**
* <p>Contract for use with the Gmail content provider.</p>
*
* <p>Developers can use this content provider to display label information to the user.
* <br/>
* The label information includes:
* <ul>
* <li>Label name</li>
* <li>Total number of conversations</li>
* <li>Number of unread conversations</li>
* <li>Label text color</li>
* <li>Label background color</li>
* </ul></p>
*
* <p>This content provider is available in Gmail version 2.3.6 or newer for Froyo/Gingerbread
* and version 4.0.5 and newer for Honeycomb and Ice Cream Sandwich</p>
* <p>An application can query the
* <a href="http://developer.android.com/reference/android/content/ContentResolver.html">
* Content Resolver</a> directly
* (or use a <a href="http://developer.android.com/guide/topics/fundamentals/loaders.html"
* target="_blank">Loader</a>)
* to obtain a Cursor with information for all labels on an account</p>
* <code>Cursor labelsCursor = getContentResolver().query(GmailContract.Labels.getLabelsUri(
* selectedAccount), null, null, null, null);</code>
*/
public final class GmailContract {
private GmailContract() {}
/**
* Permission required to access this {@link android.content.ContentProvider}
*/
public static final String PERMISSION =
"com.google.android.gm.permission.READ_CONTENT_PROVIDER";
/**
* Authority for the Gmail content provider.
*/
public static final String AUTHORITY = "com.google.android.gm";
static final String LABELS_PARAM = "/labels";
static final String LABEL_PARAM = "/label/";
static final String BASE_URI_STRING = "content://" + AUTHORITY;
static final String PACKAGE = "com.google.android.gm";
/**
* Check if the installed Gmail app supports querying for label information.
*
* @param c an application Context
* @return true if it's safe to make label API queries
*/
public static boolean canReadLabels(Context c) {
boolean supported = false;
try {
final PackageInfo info = c.getPackageManager().getPackageInfo(PACKAGE,
PackageManager.GET_PROVIDERS | PackageManager.GET_PERMISSIONS);
boolean allowRead = false;
if (info.permissions != null) {
for (int i = 0, len = info.permissions.length; i < len; i++) {
final PermissionInfo perm = info.permissions[i];
if (PERMISSION.equals(perm.name)
&& perm.protectionLevel < PermissionInfo.PROTECTION_SIGNATURE) {
allowRead = true;
break;
}
}
}
if (allowRead && info.providers != null) {
for (int i = 0, len = info.providers.length; i < len; i++) {
final ProviderInfo provider = info.providers[i];
if (AUTHORITY.equals(provider.authority) &&
TextUtils.equals(PERMISSION, provider.readPermission)) {
supported = true;
}
}
}
} catch (NameNotFoundException e) {
// Gmail app not found
}
return supported;
}
/**
* Table containing label information.
*/
public static final class Labels {
/**
* Label canonical names for default Gmail system labels.
*/
public static final class LabelCanonicalNames {
/**
* Canonical name for the Inbox label
*/
public static final String CANONICAL_NAME_INBOX = "^i";
/**
* Canonical name for the Priority Inbox label
*/
public static final String CANONICAL_NAME_PRIORITY_INBOX = "^iim";
/**
* Canonical name for the Starred label
*/
public static final String CANONICAL_NAME_STARRED = "^t";
/**
* Canonical name for the Sent label
*/
public static final String CANONICAL_NAME_SENT = "^f";
/**
* Canonical name for the Drafts label
*/
public static final String CANONICAL_NAME_DRAFTS = "^r";
/**
* Canonical name for the All Mail label
*/
public static final String CANONICAL_NAME_ALL_MAIL = "^all";
/**
* Canonical name for the Spam label
*/
public static final String CANONICAL_NAME_SPAM = "^s";
/**
* Canonical name for the Trash label
*/
public static final String CANONICAL_NAME_TRASH = "^k";
private LabelCanonicalNames() {}
}
/**
* The MIME-type of uri providing a directory of
* label items.
*/
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.com.google.android.gm.label";
/**
* The MIME-type of a label item.
*/
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.com.google.android.gm.label";
/**
* This string value is the canonical name of a label. Canonical names are not localized and
* are not user-facing.
*
* <p>Type: TEXT</p>
*/
public static final String CANONICAL_NAME = "canonicalName";
/**
* This string value is the user-visible name of a label. Names of system labels
* (Inbox, Sent, Drafts...) are localized.
*
* <p>Type: TEXT</p>
*/
public static final String NAME = "name";
/**
* This integer value is the number of conversations in this label.
*
* <p>Type: INTEGER</p>
*/
public static final String NUM_CONVERSATIONS = "numConversations";
/**
* This integer value is the number of unread conversations in this label.
*
* <p>Type: INTEGER</p>
*/
public static final String NUM_UNREAD_CONVERSATIONS = "numUnreadConversations";
/**
* This integer value is the label's foreground text color in 32-bit 0xAARRGGBB format.
*
* <p>Type: INTEGER</p>
*/
public static final String TEXT_COLOR = "text_color";
/**
* This integer value is the label's background color in 32-bit 0xAARRGGBB format.
*
* <p>Type: INTEGER</p>
*/
public static final String BACKGROUND_COLOR = "background_color";
/**
* This string column value is the uri that can be used in subsequent calls to
* {@link android.content.ContentProvider#query()} to query for information on the single
* label represented by this row.
*
* <p>Type: TEXT</p>
*/
public static final String URI = "labelUri";
/**
* Returns a URI that, when queried, will return the list of labels for an
* account.
* <p>
* To use the Labels API, an app must first find the email address of a
* valid Gmail account to query for label information. The <a href=
* "http://developer.android.com/reference/android/accounts/AccountManager.html"
* target="_blank">AccountManager</a> can return this information (<a
* href="https://developers.google.com/gmail/android">example</a>).
* </p>
*
* @param account Name of a valid Google account.
* @return The URL that can be queried to retrieve the the label list.
*/
public static Uri getLabelsUri(String account) {
return Uri.parse(BASE_URI_STRING + "/" + account + LABELS_PARAM);
}
private Labels() {}
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/gmail/GmailContract.java | Java | asf20 | 8,889 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.gmail;
import com.google.android.apps.dashclock.LogUtils;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import net.nurik.roman.dashclock.R;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Pair;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.google.android.apps.dashclock.LogUtils.LOGD;
import static com.google.android.apps.dashclock.LogUtils.LOGE;
/**
* Gmail unread count extension.
*/
public class GmailExtension extends DashClockExtension {
private static final String TAG = LogUtils.makeLogTag(GmailExtension.class);
public static final String PREF_ACCOUNTS = "pref_gmail_accounts";
public static final String PREF_LABEL = "pref_gmail_label";
private static final String ACCOUNT_TYPE_GOOGLE = "com.google";
private static final String SECTIONED_INBOX_CANONICAL_NAME_PREFIX = "^sq_ig_i_";
//private static final String[] FEATURES_MAIL = {"service_mail"};
static String[] getAllAccountNames(Context context) {
final Account[] accounts = AccountManager.get(context).getAccountsByType(
GmailExtension.ACCOUNT_TYPE_GOOGLE);
final String[] accountNames = new String[accounts.length];
for (int i = 0; i < accounts.length; i++) {
accountNames[i] = accounts[i].name;
}
return accountNames;
}
private Set<String> getSelectedAccounts() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
final String[] accounts = GmailExtension.getAllAccountNames(this);
Set<String> allAccountsSet = new HashSet<String>();
allAccountsSet.addAll(Arrays.asList(accounts));
return sp.getStringSet(PREF_ACCOUNTS, allAccountsSet);
}
@Override
protected void onInitialize(boolean isReconnect) {
super.onInitialize(isReconnect);
if (!isReconnect) {
Set<String> selectedAccounts = getSelectedAccounts();
String[] uris = new String[selectedAccounts.size()];
int i = 0;
for (String account : selectedAccounts) {
uris[i++] = GmailContract.Labels.getLabelsUri(account).toString();
// TODO: only watch the individual label's URI (GmailContract.Labels.URI)
}
addWatchContentUris(uris);
}
}
@Override
protected void onUpdateData(int reason) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String labelCanonical = sp.getString(PREF_LABEL, "i");
Set<String> selectedAccounts = getSelectedAccounts();
if ("i".equals(labelCanonical)) {
labelCanonical = GmailContract.Labels.LabelCanonicalNames.CANONICAL_NAME_INBOX;
} else if ("p".equals(labelCanonical)) {
labelCanonical = GmailContract.Labels.LabelCanonicalNames.CANONICAL_NAME_PRIORITY_INBOX;
}
int unread = 0;
List<Pair<String, Integer>> unreadPerAccount = new ArrayList<Pair<String, Integer>>();
for (String account : selectedAccounts) {
Cursor cursor = tryOpenLabelsCursor(account);
if (cursor == null || cursor.isAfterLast()) {
LOGD(TAG, "No Gmail inbox information found for account.");
if (cursor != null) {
cursor.close();
}
continue;
}
int accountUnread = 0;
while (cursor.moveToNext()) {
int thisUnread = cursor.getInt(LabelsQuery.NUM_UNREAD_CONVERSATIONS);
String thisCanonicalName = cursor.getString(LabelsQuery.CANONICAL_NAME);
if (labelCanonical.equals(thisCanonicalName)) {
accountUnread = thisUnread;
break;
} else if (!TextUtils.isEmpty(thisCanonicalName)
&& thisCanonicalName.startsWith(SECTIONED_INBOX_CANONICAL_NAME_PREFIX)) {
accountUnread += thisUnread;
}
}
if (accountUnread > 0) {
unreadPerAccount.add(new Pair<String, Integer>(account, accountUnread));
unread += accountUnread;
}
cursor.close();
}
StringBuilder body = new StringBuilder();
for (Pair<String, Integer> pair : unreadPerAccount) {
if (pair.second == 0) {
continue;
}
if (body.length() > 0) {
body.append("\n");
}
body.append(pair.first).append(" (").append(pair.second).append(")");
}
publishUpdate(new ExtensionData()
.visible(unread > 0)
.status(Integer.toString(unread))
.expandedTitle(getResources().getQuantityString(
R.plurals.gmail_title_template, unread, unread))
.icon(R.drawable.ic_extension_gmail)
.expandedBody(body.toString())
.clickIntent(new Intent(Intent.ACTION_MAIN)
.setPackage("com.google.android.gm")
.addCategory(Intent.CATEGORY_LAUNCHER)));
}
private Cursor tryOpenLabelsCursor(String account) {
try {
return getContentResolver().query(
GmailContract.Labels.getLabelsUri(account),
LabelsQuery.PROJECTION,
null, // NOTE: the Labels API doesn't allow selections here
null,
null);
} catch (Exception e) {
// From developer console: "Permission Denial: opening provider com.google.android.gsf..
// From developer console: "SQLiteException: no such table: labels"
// From developer console: "NullPointerException"
LOGE(TAG, "Error opening Gmail labels", e);
return null;
}
}
private interface LabelsQuery {
String[] PROJECTION = {
GmailContract.Labels.NUM_UNREAD_CONVERSATIONS,
GmailContract.Labels.URI,
GmailContract.Labels.CANONICAL_NAME,
};
int NUM_UNREAD_CONVERSATIONS = 0;
int URI = 1;
int CANONICAL_NAME = 2;
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/gmail/GmailExtension.java | Java | asf20 | 7,277 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.weather;
import android.location.Location;
import android.text.TextUtils;
import android.util.Pair;
import com.google.android.apps.dashclock.LogUtils;
import com.google.android.apps.dashclock.Utils;
import net.nurik.roman.dashclock.R;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import static com.google.android.apps.dashclock.LogUtils.LOGD;
import static com.google.android.apps.dashclock.LogUtils.LOGE;
import static com.google.android.apps.dashclock.LogUtils.LOGW;
/**
* Client code for the Yahoo! Weather RSS feeds and GeoPlanet API.
*/
class YahooWeatherApiClient {
private static final String TAG = LogUtils.makeLogTag(YahooWeatherApiClient.class);
private static String sWeatherUnits;
private static XmlPullParserFactory sXmlPullParserFactory;
private static final int MAX_SEARCH_RESULTS = 10;
static {
try {
sXmlPullParserFactory = XmlPullParserFactory.newInstance();
sXmlPullParserFactory.setNamespaceAware(true);
} catch (XmlPullParserException e) {
LOGE(TAG, "Could not instantiate XmlPullParserFactory", e);
}
}
public static void setWeatherUnits(String weatherUnits) {
sWeatherUnits = weatherUnits;
}
public static WeatherData getWeatherForLocationInfo(LocationInfo locationInfo)
throws CantGetWeatherException {
// Loop through the woeids (they're in descending precision order) until weather data
// is found.
for (String woeid : locationInfo.woeids) {
LOGD(TAG, "Trying WOEID: " + woeid);
WeatherData data = YahooWeatherApiClient.getWeatherForWoeid(woeid, locationInfo.town);
if (data != null
&& data.conditionCode != WeatherData.INVALID_CONDITION
&& data.temperature != WeatherData.INVALID_TEMPERATURE) {
return data;
}
}
// No weather could be found :(
throw new CantGetWeatherException(true, R.string.no_weather_data);
}
public static WeatherData getWeatherForWoeid(String woeid, String town)
throws CantGetWeatherException {
HttpURLConnection connection = null;
try {
connection = Utils.openUrlConnection(buildWeatherQueryUrl(woeid));
XmlPullParser xpp = sXmlPullParserFactory.newPullParser();
xpp.setInput(new InputStreamReader(connection.getInputStream()));
WeatherData data = new WeatherData();
boolean hasTodayForecast = false;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG
&& "condition".equals(xpp.getName())) {
for (int i = xpp.getAttributeCount() - 1; i >= 0; i--) {
if ("temp".equals(xpp.getAttributeName(i))) {
data.temperature = Integer.parseInt(xpp.getAttributeValue(i));
} else if ("code".equals(xpp.getAttributeName(i))) {
data.conditionCode = Integer.parseInt(xpp.getAttributeValue(i));
} else if ("text".equals(xpp.getAttributeName(i))) {
data.conditionText = xpp.getAttributeValue(i);
}
}
} else if (eventType == XmlPullParser.START_TAG
&& "forecast".equals(xpp.getName())
&& !hasTodayForecast) {
// TODO: verify this is the forecast for today (this currently assumes the
// first forecast is today's forecast)
hasTodayForecast = true;
for (int i = xpp.getAttributeCount() - 1; i >= 0; i--) {
if ("code".equals(xpp.getAttributeName(i))) {
data.todayForecastConditionCode
= Integer.parseInt(xpp.getAttributeValue(i));
} else if ("low".equals(xpp.getAttributeName(i))) {
data.low = Integer.parseInt(xpp.getAttributeValue(i));
} else if ("high".equals(xpp.getAttributeName(i))) {
data.high = Integer.parseInt(xpp.getAttributeValue(i));
} else if ("text".equals(xpp.getAttributeName(i))) {
data.forecastText = xpp.getAttributeValue(i);
}
}
} else if (eventType == XmlPullParser.START_TAG
&& "location".equals(xpp.getName())) {
String cityOrVillage = "--";
String region = null;
String country = "--";
for (int i = xpp.getAttributeCount() - 1; i >= 0; i--) {
if ("city".equals(xpp.getAttributeName(i))) {
cityOrVillage = xpp.getAttributeValue(i);
} else if ("region".equals(xpp.getAttributeName(i))) {
region = xpp.getAttributeValue(i);
} else if ("country".equals(xpp.getAttributeName(i))) {
country = xpp.getAttributeValue(i);
}
}
if (TextUtils.isEmpty(region)) {
// If no region is available, show the country. Otherwise, don't
// show country information.
region = country;
}
if (!TextUtils.isEmpty(town) && !town.equals(cityOrVillage)) {
// If a town is available and it's not equivalent to the city name,
// show it.
cityOrVillage = cityOrVillage + ", " + town;
}
data.location = cityOrVillage + ", " + region;
}
eventType = xpp.next();
}
if (TextUtils.isEmpty(data.location)) {
data.location = town;
}
return data;
} catch (IOException e) {
throw new CantGetWeatherException(true, R.string.no_weather_data,
"Error parsing weather feed XML.", e);
} catch (NumberFormatException e) {
throw new CantGetWeatherException(true, R.string.no_weather_data,
"Error parsing weather feed XML.", e);
} catch (XmlPullParserException e) {
throw new CantGetWeatherException(true, R.string.no_weather_data,
"Error parsing weather feed XML.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
public static LocationInfo getLocationInfo(Location location) throws CantGetWeatherException {
LocationInfo li = new LocationInfo();
// first=tagname (admin1, locality3) second=woeid
String primaryWoeid = null;
List<Pair<String,String>> alternateWoeids = new ArrayList<Pair<String, String>>();
HttpURLConnection connection = null;
try {
connection = Utils.openUrlConnection(buildPlaceSearchUrl(location));
XmlPullParser xpp = sXmlPullParserFactory.newPullParser();
xpp.setInput(new InputStreamReader(connection.getInputStream()));
boolean inWoe = false;
boolean inTown = false;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagName = xpp.getName();
if (eventType == XmlPullParser.START_TAG && "woeid".equals(tagName)) {
inWoe = true;
} else if (eventType == XmlPullParser.TEXT && inWoe) {
primaryWoeid = xpp.getText();
}
if (eventType == XmlPullParser.START_TAG &&
(tagName.startsWith("locality") || tagName.startsWith("admin"))) {
for (int i = xpp.getAttributeCount() - 1; i >= 0; i--) {
String attrName = xpp.getAttributeName(i);
if ("type".equals(attrName)
&& "Town".equals(xpp.getAttributeValue(i))) {
inTown = true;
} else if ("woeid".equals(attrName)) {
String woeid = xpp.getAttributeValue(i);
if (!TextUtils.isEmpty(woeid)) {
alternateWoeids.add(
new Pair<String, String>(tagName, woeid));
}
}
}
} else if (eventType == XmlPullParser.TEXT && inTown) {
li.town = xpp.getText();
}
if (eventType == XmlPullParser.END_TAG) {
inWoe = false;
inTown = false;
}
eventType = xpp.next();
}
// Add the primary woeid if it was found.
if (!TextUtils.isEmpty(primaryWoeid)) {
li.woeids.add(primaryWoeid);
}
// Sort by descending tag name to order by decreasing precision
// (locality3, locality2, locality1, admin3, admin2, admin1, etc.)
Collections.sort(alternateWoeids, new Comparator<Pair<String, String>>() {
@Override
public int compare(Pair<String, String> pair1, Pair<String, String> pair2) {
return pair1.first.compareTo(pair2.first);
}
});
for (Pair<String, String> pair : alternateWoeids) {
li.woeids.add(pair.second);
}
if (li.woeids.size() > 0) {
return li;
}
throw new CantGetWeatherException(true, R.string.no_weather_data,
"No WOEIDs found nearby.");
} catch (IOException e) {
throw new CantGetWeatherException(true, R.string.no_weather_data,
"Error parsing place search XML", e);
} catch (XmlPullParserException e) {
throw new CantGetWeatherException(true, R.string.no_weather_data,
"Error parsing place search XML", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private static final int PARSE_STATE_NONE = 0;
private static final int PARSE_STATE_PLACE = 1;
private static final int PARSE_STATE_WOEID = 2;
private static final int PARSE_STATE_NAME = 3;
private static final int PARSE_STATE_COUNTRY = 4;
private static final int PARSE_STATE_ADMIN1 = 5;
public static List<LocationSearchResult> findLocationsAutocomplete(String startsWith) {
LOGD(TAG, "Autocompleting locations starting with '" + startsWith + "'");
List<LocationSearchResult> results = new ArrayList<LocationSearchResult>();
HttpURLConnection connection = null;
try {
connection = Utils.openUrlConnection(buildPlaceSearchStartsWithUrl(startsWith));
XmlPullParser xpp = sXmlPullParserFactory.newPullParser();
xpp.setInput(new InputStreamReader(connection.getInputStream()));
LocationSearchResult result = null;
String name = null, country = null, admin1 = null;
StringBuilder sb = new StringBuilder();
int state = PARSE_STATE_NONE;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagName = xpp.getName();
if (eventType == XmlPullParser.START_TAG) {
switch (state) {
case PARSE_STATE_NONE:
if ("place".equals(tagName)) {
state = PARSE_STATE_PLACE;
result = new LocationSearchResult();
name = country = admin1 = null;
}
break;
case PARSE_STATE_PLACE:
if ("name".equals(tagName)) {
state = PARSE_STATE_NAME;
} else if ("woeid".equals(tagName)) {
state = PARSE_STATE_WOEID;
} else if ("country".equals(tagName)) {
state = PARSE_STATE_COUNTRY;
} else if ("admin1".equals(tagName)) {
state = PARSE_STATE_ADMIN1;
}
break;
}
} else if (eventType == XmlPullParser.TEXT) {
switch (state) {
case PARSE_STATE_WOEID:
result.woeid = xpp.getText();
break;
case PARSE_STATE_NAME:
name = xpp.getText();
break;
case PARSE_STATE_COUNTRY:
country = xpp.getText();
break;
case PARSE_STATE_ADMIN1:
admin1 = xpp.getText();
break;
}
} else if (eventType == XmlPullParser.END_TAG) {
if ("place".equals(tagName)) {
// // Sort by descending tag name to order by decreasing precision
// // (locality3, locality2, locality1, admin3, admin2, admin1, etc.)
// Collections.sort(alternateWoeids, new Comparator<Pair<String, String>>() {
// @Override
// public int compare(Pair<String, String> pair1,
// Pair<String, String> pair2) {
// return pair1.first.compareTo(pair2.first);
// }
// });
sb.setLength(0);
if (!TextUtils.isEmpty(name)) {
sb.append(name);
}
if (!TextUtils.isEmpty(admin1)) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(admin1);
}
result.displayName = sb.toString();
result.country = country;
results.add(result);
state = PARSE_STATE_NONE;
} else if (state != PARSE_STATE_NONE) {
state = PARSE_STATE_PLACE;
}
}
eventType = xpp.next();
}
} catch (IOException e) {
LOGW(TAG, "Error parsing place search XML");
} catch (XmlPullParserException e) {
LOGW(TAG, "Error parsing place search XML");
} finally {
if (connection != null) {
connection.disconnect();
}
}
return results;
}
private static String buildWeatherQueryUrl(String woeid) {
// http://developer.yahoo.com/weather/
return "http://weather.yahooapis.com/forecastrss?w=" + woeid + "&u=" + sWeatherUnits;
}
private static String buildPlaceSearchUrl(Location l) {
// GeoPlanet API
return "http://where.yahooapis.com/v1/places.q('"
+ l.getLatitude() + "," + l.getLongitude() + "')"
+ "?appid=" + YahooWeatherApiConfig.APP_ID;
}
private static String buildPlaceSearchStartsWithUrl(String startsWith) {
// GeoPlanet API
startsWith = startsWith.replaceAll("[^\\w ]+", "").replaceAll(" ", "%20");
return "http://where.yahooapis.com/v1/places.q('" + startsWith + "%2A');"
+ "count=" + MAX_SEARCH_RESULTS
+ "?appid=" + YahooWeatherApiConfig.APP_ID;
}
public static class LocationInfo {
// Sorted by decreasing precision
// (point of interest, locality3, locality2, locality1, admin3, admin2, admin1, etc.)
List<String> woeids = new ArrayList<String>();
String town;
}
public static class LocationSearchResult {
String woeid;
String displayName;
String country;
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/weather/YahooWeatherApiClient.java | Java | asf20 | 17,734 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.weather;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.LoaderManager;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.content.Loader;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.Preference;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import net.nurik.roman.dashclock.R;
import java.util.ArrayList;
import java.util.List;
import static com.google.android.apps.dashclock.weather.YahooWeatherApiClient.LocationSearchResult;
/**
* A preference that allows the user to choose a location, using the Yahoo! GeoPlanet API.
*/
public class WeatherLocationPreference extends Preference {
public WeatherLocationPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public WeatherLocationPreference(Context context) {
super(context);
}
public WeatherLocationPreference(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public void setValue(String value) {
if (value == null) {
value = "";
}
if (callChangeListener(value)) {
persistString(value);
notifyChanged();
}
}
public static CharSequence getDisplayValue(Context context, String value) {
if (TextUtils.isEmpty(value) || value.indexOf(',') < 0) {
return context.getString(R.string.pref_weather_location_automatic);
}
String[] woeidAndDisplayName = value.split(",", 2);
return woeidAndDisplayName[1];
}
public static String getWoeidFromValue(String value) {
if (TextUtils.isEmpty(value) || value.indexOf(',') < 0) {
return null;
}
String[] woeidAndDisplayName = value.split(",", 2);
return woeidAndDisplayName[0];
}
@Override
protected void onClick() {
super.onClick();
LocationChooserDialogFragment fragment = LocationChooserDialogFragment.newInstance();
fragment.setPreference(this);
Activity activity = (Activity) getContext();
activity.getFragmentManager().beginTransaction()
.add(fragment, getFragmentTag())
.commit();
}
@Override
protected void onAttachedToActivity() {
super.onAttachedToActivity();
Activity activity = (Activity) getContext();
LocationChooserDialogFragment fragment = (LocationChooserDialogFragment) activity
.getFragmentManager().findFragmentByTag(getFragmentTag());
if (fragment != null) {
// re-bind preference to fragment
fragment.setPreference(this);
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
setValue(restoreValue ? getPersistedString("") : (String) defaultValue);
}
public String getFragmentTag() {
return "location_chooser_" + getKey();
}
/**
* Dialog fragment that pops up when touching the preference.
*/
public static class LocationChooserDialogFragment extends DialogFragment implements
TextWatcher,
LoaderManager.LoaderCallbacks<List<LocationSearchResult>> {
/**
* Time between search queries while typing.
*/
private static final int QUERY_DELAY_MILLIS = 500;
private WeatherLocationPreference mPreference;
private SearchResultsListAdapter mSearchResultsAdapter;
private ListView mSearchResultsList;
public LocationChooserDialogFragment() {
}
public static LocationChooserDialogFragment newInstance() {
return new LocationChooserDialogFragment();
}
public void setPreference(WeatherLocationPreference preference) {
mPreference = preference;
tryBindList();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
tryBindList();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Force Holo Light since ?android:actionBarXX would use dark action bar
Context layoutContext = new ContextThemeWrapper(getActivity(),
android.R.style.Theme_Holo_Light);
LayoutInflater layoutInflater = LayoutInflater.from(layoutContext);
View rootView = layoutInflater.inflate(R.layout.dialog_weather_location_chooser, null);
TextView searchView = (TextView) rootView.findViewById(R.id.location_query);
searchView.addTextChangedListener(this);
// Set up apps
mSearchResultsList = (ListView) rootView.findViewById(android.R.id.list);
mSearchResultsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long itemId) {
String value = mSearchResultsAdapter.getPrefValueAt(position);
mPreference.setValue(value);
dismiss();
}
});
tryBindList();
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setView(rootView)
.create();
dialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
return dialog;
}
private void tryBindList() {
if (mPreference == null) {
return;
}
if (isAdded() && mSearchResultsAdapter == null) {
mSearchResultsAdapter = new SearchResultsListAdapter();
}
if (mSearchResultsAdapter != null && mSearchResultsList != null) {
mSearchResultsList.setAdapter(mSearchResultsAdapter);
}
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
mQuery = charSequence.toString();
if (mRestartLoaderHandler.hasMessages(0)) {
return;
}
mRestartLoaderHandler.sendMessageDelayed(
mRestartLoaderHandler.obtainMessage(0),
QUERY_DELAY_MILLIS);
}
@Override
public void afterTextChanged(Editable editable) {
}
private String mQuery;
private Handler mRestartLoaderHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle args = new Bundle();
args.putString("query", mQuery);
getLoaderManager().restartLoader(0, args, LocationChooserDialogFragment.this);
}
};
@Override
public Loader<List<LocationSearchResult>> onCreateLoader(int id, Bundle args) {
final String query = args.getString("query");
return new ResultsLoader(query, getActivity());
}
@Override
public void onLoadFinished(Loader<List<LocationSearchResult>> loader,
List<LocationSearchResult> results) {
mSearchResultsAdapter.changeArray(results);
}
@Override
public void onLoaderReset(Loader<List<LocationSearchResult>> loader) {
mSearchResultsAdapter.changeArray(null);
}
private class SearchResultsListAdapter extends BaseAdapter {
private List<LocationSearchResult> mResults;
private SearchResultsListAdapter() {
mResults = new ArrayList<LocationSearchResult>();
}
public void changeArray(List<LocationSearchResult> results) {
if (results == null) {
results = new ArrayList<LocationSearchResult>();
}
mResults = results;
notifyDataSetChanged();
}
@Override
public int getCount() {
return Math.max(1, mResults.size());
}
@Override
public Object getItem(int position) {
if (position == 0 && mResults.size() == 0) {
return null;
}
return mResults.get(position);
}
public String getPrefValueAt(int position) {
if (position == 0 && mResults.size() == 0) {
return "";
}
LocationSearchResult result = mResults.get(position);
return result.woeid + "," + result.displayName;
}
@Override
public long getItemId(int position) {
if (position == 0 && mResults.size() == 0) {
return -1;
}
return mResults.get(position).woeid.hashCode();
}
@Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
convertView = LayoutInflater.from(getActivity())
.inflate(R.layout.list_item_weather_location_result, container, false);
}
if (position == 0 && mResults.size() == 0) {
((TextView) convertView.findViewById(android.R.id.text1))
.setText(R.string.pref_weather_location_automatic);
((TextView) convertView.findViewById(android.R.id.text2))
.setText(R.string.pref_weather_location_automatic_description);
} else {
LocationSearchResult result = mResults.get(position);
((TextView) convertView.findViewById(android.R.id.text1))
.setText(result.displayName);
((TextView) convertView.findViewById(android.R.id.text2))
.setText(result.country);
}
return convertView;
}
}
}
/**
* Loader that fetches location search results from {@link YahooWeatherApiClient}.
*/
private static class ResultsLoader extends AsyncTaskLoader<List<LocationSearchResult>> {
private String mQuery;
private List<LocationSearchResult> mResults;
public ResultsLoader(String query, Context context) {
super(context);
mQuery = query;
}
@Override
public List<LocationSearchResult> loadInBackground() {
return YahooWeatherApiClient.findLocationsAutocomplete(mQuery);
}
@Override
public void deliverResult(List<LocationSearchResult> apps) {
mResults = apps;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(apps);
}
}
@Override
protected void onStartLoading() {
if (mResults != null) {
deliverResult(mResults);
}
if (takeContentChanged() || mResults == null) {
// If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad();
}
}
@Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
@Override
protected void onReset() {
super.onReset();
onStopLoading();
}
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/weather/WeatherLocationPreference.java | Java | asf20 | 13,200 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.weather;
import com.google.android.apps.dashclock.LogUtils;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import com.google.android.apps.dashclock.configuration.AppChooserPreference;
import net.nurik.roman.dashclock.R;
import android.app.AlarmManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import java.util.Arrays;
import java.util.Locale;
import static com.google.android.apps.dashclock.LogUtils.LOGD;
import static com.google.android.apps.dashclock.LogUtils.LOGE;
import static com.google.android.apps.dashclock.LogUtils.LOGW;
import static com.google.android.apps.dashclock.weather.YahooWeatherApiClient.*;
/**
* A local weather and forecast extension.
*/
public class WeatherExtension extends DashClockExtension {
private static final String TAG = LogUtils.makeLogTag(WeatherExtension.class);
public static final String PREF_WEATHER_UNITS = "pref_weather_units";
public static final String PREF_WEATHER_SHORTCUT = "pref_weather_shortcut";
public static final String PREF_WEATHER_LOCATION = "pref_weather_location";
public static final Intent DEFAULT_WEATHER_INTENT = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.google.com/search?q=weather"));
public static final String STATE_WEATHER_LAST_BACKOFF_MILLIS
= "state_weather_last_backoff_millis";
public static final String STATE_WEATHER_LAST_UPDATE_ELAPSED_MILLIS
= "state_weather_last_update_elapsed_millis";
private static final int UPDATE_THROTTLE_MILLIS = 10 * 3600000; // At least 10 min b/w updates
private static final long STALE_LOCATION_NANOS = 10l * 60000000000l; // 10 minutes
private static final int INITIAL_BACKOFF_MILLIS = 30000; // 30 seconds for first error retry
private static final int LOCATION_TIMEOUT_MILLIS = 60000; // 60 sec timeout for location attempt
private static final Criteria sLocationCriteria;
private static String sWeatherUnits = "f";
private static Intent sWeatherIntent;
private boolean mOneTimeLocationListenerActive = false;
private Handler mTimeoutHandler = new Handler();
static {
sLocationCriteria = new Criteria();
sLocationCriteria.setPowerRequirement(Criteria.POWER_LOW);
sLocationCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
sLocationCriteria.setCostAllowed(false);
}
private void resetAndCancelRetries() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().remove(STATE_WEATHER_LAST_BACKOFF_MILLIS).apply();
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(WeatherRetryReceiver.getPendingIntent(this));
}
private void scheduleRetry() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
int lastBackoffMillis = sp.getInt(STATE_WEATHER_LAST_BACKOFF_MILLIS, 0);
int backoffMillis = (lastBackoffMillis > 0)
? lastBackoffMillis * 2
: INITIAL_BACKOFF_MILLIS;
sp.edit().putInt(STATE_WEATHER_LAST_BACKOFF_MILLIS, backoffMillis).apply();
LOGD(TAG, "Scheduling weather retry in " + (backoffMillis / 1000) + " second(s)");
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + backoffMillis,
WeatherRetryReceiver.getPendingIntent(this));
}
@Override
protected void onUpdateData(int reason) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sWeatherUnits = sp.getString(PREF_WEATHER_UNITS, sWeatherUnits);
sWeatherIntent = AppChooserPreference.getIntentValue(
sp.getString(PREF_WEATHER_SHORTCUT, null), DEFAULT_WEATHER_INTENT);
setWeatherUnits(sWeatherUnits);
long lastUpdateElapsedMillis = sp.getLong(STATE_WEATHER_LAST_UPDATE_ELAPSED_MILLIS,
-UPDATE_THROTTLE_MILLIS);
long nowElapsedMillis = SystemClock.elapsedRealtime();
if (reason != UPDATE_REASON_INITIAL && reason != UPDATE_REASON_MANUAL &&
nowElapsedMillis < lastUpdateElapsedMillis + UPDATE_THROTTLE_MILLIS) {
LOGD(TAG, "Throttling weather update attempt.");
return;
}
LOGD(TAG, "Attempting weather update; reason=" + reason);
NetworkInfo ni = ((ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (ni == null || !ni.isConnected()) {
LOGD(TAG, "No network connection; not attempting to update weather.");
return;
}
String manualLocationWoeid = WeatherLocationPreference.getWoeidFromValue(
sp.getString(PREF_WEATHER_LOCATION, null));
if (!TextUtils.isEmpty(manualLocationWoeid)) {
// WOEIDs
// Honolulu = 2423945
// Paris = 615702
// London = 44418
// New York = 2459115
// San Francisco = 2487956
LocationInfo locationInfo = new LocationInfo();
locationInfo.woeids = Arrays.asList(manualLocationWoeid);
tryPublishWeatherUpdateFromLocationInfo(locationInfo);
return;
}
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = lm.getBestProvider(sLocationCriteria, true);
if (TextUtils.isEmpty(provider)) {
publishErrorUpdate(new CantGetWeatherException(false, R.string.no_location_data,
"No available location providers matching criteria."));
return;
}
final Location lastLocation = lm.getLastKnownLocation(provider);
if (lastLocation == null ||
(SystemClock.elapsedRealtimeNanos() - lastLocation.getElapsedRealtimeNanos())
>= STALE_LOCATION_NANOS) {
LOGW(TAG, "Stale or missing last-known location; requesting single coarse location "
+ "update.");
disableOneTimeLocationListener();
mOneTimeLocationListenerActive = true;
lm.requestSingleUpdate(provider, mOneTimeLocationListener, null);
// Time-out single location update request
mTimeoutHandler.removeCallbacksAndMessages(null);
mTimeoutHandler.postDelayed(new Runnable() {
@Override
public void run() {
LOGE(TAG, "Location request timed out.");
disableOneTimeLocationListener();
scheduleRetry();
}
}, LOCATION_TIMEOUT_MILLIS);
} else {
tryPublishWeatherUpdateFromGeolocation(lastLocation);
}
}
private void disableOneTimeLocationListener() {
if (mOneTimeLocationListenerActive) {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.removeUpdates(mOneTimeLocationListener);
mOneTimeLocationListenerActive = false;
}
}
private LocationListener mOneTimeLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
LOGD(TAG, "Got network location update");
mTimeoutHandler.removeCallbacksAndMessages(null);
tryPublishWeatherUpdateFromGeolocation(location);
disableOneTimeLocationListener();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
LOGD(TAG, "Network location provider status change: " + status);
if (status == LocationProvider.TEMPORARILY_UNAVAILABLE) {
scheduleRetry();
disableOneTimeLocationListener();
}
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
@Override
public void onDestroy() {
super.onDestroy();
disableOneTimeLocationListener();
}
private void tryPublishWeatherUpdateFromGeolocation(Location location) {
try {
LOGD(TAG, "Using location: " + location.getLatitude() + "," + location.getLongitude());
tryPublishWeatherUpdateFromLocationInfo(getLocationInfo(location));
} catch (CantGetWeatherException e) {
publishErrorUpdate(e);
if (e.isRetryable()) {
scheduleRetry();
}
}
}
private void tryPublishWeatherUpdateFromLocationInfo(LocationInfo locationInfo) {
try {
publishWeatherUpdate(getWeatherForLocationInfo(locationInfo));
} catch (CantGetWeatherException e) {
publishErrorUpdate(e);
if (e.isRetryable()) {
scheduleRetry();
}
}
}
private void publishErrorUpdate(CantGetWeatherException e) {
LOGE(TAG, "Showing a weather extension error", e);
publishUpdate(new ExtensionData()
.visible(true)
.clickIntent(sWeatherIntent)
.icon(R.drawable.ic_weather_clear)
.status(getString(R.string.status_none))
.expandedBody(getString(e.getUserFacingErrorStringId())));
}
private void publishWeatherUpdate(WeatherData weatherData) {
String temperature = (weatherData.temperature != WeatherData.INVALID_TEMPERATURE)
? getString(R.string.temperature_template, weatherData.temperature)
: getString(R.string.status_none);
StringBuilder expandedBody = new StringBuilder();
if (weatherData.low != WeatherData.INVALID_TEMPERATURE
&& weatherData.high != WeatherData.INVALID_TEMPERATURE) {
expandedBody.append(getString(R.string.weather_low_high_template,
getString(R.string.temperature_template, weatherData.low),
getString(R.string.temperature_template, weatherData.high)));
}
int conditionIconId = WeatherData.getConditionIconId(weatherData.conditionCode);
if (WeatherData.getConditionIconId(weatherData.todayForecastConditionCode)
== R.drawable.ic_weather_raining) {
// Show rain if it will rain today.
conditionIconId = R.drawable.ic_weather_raining;
if (expandedBody.length() > 0) {
expandedBody.append(", ");
}
expandedBody.append(
getString(R.string.later_forecast_template, weatherData.forecastText));
}
if (expandedBody.length() > 0) {
expandedBody.append("\n");
}
expandedBody.append(weatherData.location);
publishUpdate(new ExtensionData()
.visible(true)
.clickIntent(sWeatherIntent)
.status(temperature)
.expandedTitle(getString(R.string.weather_expanded_title_template,
temperature + sWeatherUnits.toUpperCase(Locale.US),
weatherData.conditionText))
.icon(conditionIconId)
.expandedBody(expandedBody.toString()));
// Mark that a successful weather update has been pushed
resetAndCancelRetries();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().putLong(STATE_WEATHER_LAST_UPDATE_ELAPSED_MILLIS,
SystemClock.elapsedRealtime()).commit();
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/weather/WeatherExtension.java | Java | asf20 | 12,861 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.weather;
import net.nurik.roman.dashclock.R;
/**
* A helper class representing weather data, for use with {@link WeatherExtension}.
*/
public class WeatherData {
public static final int INVALID_TEMPERATURE = Integer.MIN_VALUE;
public static final int INVALID_CONDITION = -1;
public int temperature = INVALID_TEMPERATURE;
public int low = INVALID_TEMPERATURE;
public int high = INVALID_TEMPERATURE;
public int conditionCode = INVALID_CONDITION;
public int todayForecastConditionCode = INVALID_CONDITION;
public String conditionText;
public String forecastText;
public String location;
public WeatherData() {
}
public static int getConditionIconId(int conditionCode) {
// http://developer.yahoo.com/weather/
switch (conditionCode) {
case 19: // dust or sand
case 20: // foggy
case 21: // haze
case 22: // smoky
return R.drawable.ic_weather_foggy;
case 23: // blustery
case 24: // windy
return R.drawable.ic_weather_windy;
case 25: // cold
case 26: // cloudy
case 27: // mostly cloudy (night)
case 28: // mostly cloudy (day)
return R.drawable.ic_weather_cloudy;
case 29: // partly cloudy (night)
case 30: // partly cloudy (day)
case 44: // partly cloudy
return R.drawable.ic_weather_partly_cloudy;
case 31: // clear (night)
case 33: // fair (night)
case 34: // fair (day)
return R.drawable.ic_weather_clear;
case 32: // sunny
case 36: // hot
return R.drawable.ic_weather_sunny;
case 0: // tornado
case 1: // tropical storm
case 2: // hurricane
case 3: // severe thunderstorms
case 4: // thunderstorms
case 5: // mixed rain and snow
case 6: // mixed rain and sleet
case 7: // mixed snow and sleet
case 8: // freezing drizzle
case 9: // drizzle
case 10: // freezing rain
case 11: // showers
case 12: // showers
case 17: // hail
case 18: // sleet
case 35: // mixed rain and hail
case 37: // isolated thunderstorms
case 38: // scattered thunderstorms
case 39: // scattered thunderstorms
case 40: // scattered showers
case 45: // thundershowers
case 47: // isolated thundershowers
return R.drawable.ic_weather_raining;
case 13: // snow flurries
case 14: // light snow showers
case 15: // blowing snow
case 16: // snow
case 41: // heavy snow
case 42: // scattered snow showers
case 43: // heavy snow
case 46: // snow showers
return R.drawable.ic_weather_snow;
}
return R.drawable.ic_weather_clear;
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/weather/WeatherData.java | Java | asf20 | 3,731 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.weather;
import com.google.android.apps.dashclock.configuration.BaseSettingsActivity;
import net.nurik.roman.dashclock.R;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class WeatherSettingsActivity extends BaseSettingsActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setIcon(R.drawable.ic_weather_sunny);
}
@Override
protected void setupSimplePreferencesScreen() {
// In the simplified UI, fragments are not used at all and we instead
// use the older PreferenceActivity APIs.
// Add 'general' preferences.
addPreferencesFromResource(R.xml.pref_weather);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences to
// their values. When their values change, their summaries are updated
// to reflect the new value, per the Android Design guidelines.
bindPreferenceSummaryToValue(findPreference(WeatherExtension.PREF_WEATHER_UNITS));
bindPreferenceSummaryToValue(findPreference(WeatherExtension.PREF_WEATHER_SHORTCUT));
bindPreferenceSummaryToValue(findPreference(WeatherExtension.PREF_WEATHER_LOCATION));
}
@Override
protected void onStop() {
super.onStop();
// Clear out the throttle since settings may have changed.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().remove(WeatherExtension.STATE_WEATHER_LAST_UPDATE_ELAPSED_MILLIS).apply();
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/weather/WeatherSettingsActivity.java | Java | asf20 | 2,251 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.weather;
/**
* Yahoo API Configuration information.
*/
class YahooWeatherApiConfig {
public static final String APP_ID
= "kGO140TV34HVTae_DDS93fM_w3AJmtmI23gxUFnHKWyrOGcRzoFjYpw8Ato6BxhvbTg-";
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/weather/YahooWeatherApiConfig.java | Java | asf20 | 852 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.weather;
/**
* Generic exception indicating that for some reason, weather information was not obtainable.
*/
public class CantGetWeatherException extends Exception {
private int mUserFacingErrorStringId;
private boolean mRetryable;
public CantGetWeatherException(boolean retryable, int userFacingErrorStringId) {
this(retryable, userFacingErrorStringId, null, null);
}
public CantGetWeatherException(boolean retryable, int userFacingErrorStringId,
String detailMessage) {
this(retryable, userFacingErrorStringId, detailMessage, null);
}
public CantGetWeatherException(boolean retryable, int userFacingErrorStringId,
String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
mUserFacingErrorStringId = userFacingErrorStringId;
mRetryable = retryable;
}
public int getUserFacingErrorStringId() {
return mUserFacingErrorStringId;
}
public boolean isRetryable() {
return mRetryable;
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/weather/CantGetWeatherException.java | Java | asf20 | 1,676 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.weather;
import com.google.android.apps.dashclock.DashClockService;
import com.google.android.apps.dashclock.api.DashClockExtension;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
/**
* Broadcast receiver that's a target of the retry-update alarm from {@link WeatherExtension}.
*/
public class WeatherRetryReceiver extends BroadcastReceiver {
static PendingIntent getPendingIntent(Context context) {
return PendingIntent.getBroadcast(context, 0,
new Intent(context, WeatherRetryReceiver.class),
PendingIntent.FLAG_CANCEL_CURRENT);
}
@Override
public void onReceive(Context context, Intent intent) {
// Update weather
// TODO: there should be a way for an extension to request an update through the API
// See issue 292.
context.startService(new Intent(context, DashClockService.class)
.setAction(DashClockService.ACTION_UPDATE_EXTENSIONS)
.putExtra(DashClockService.EXTRA_UPDATE_REASON,
DashClockExtension.UPDATE_REASON_UNKNOWN) // TODO: UPDATE_REASON_RETRY
.putExtra(DashClockService.EXTRA_COMPONENT_NAME,
new ComponentName(context, WeatherExtension.class)
.flattenToShortString()));
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/weather/WeatherRetryReceiver.java | Java | asf20 | 2,084 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock;
import com.google.android.apps.dashclock.api.DashClockExtension;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import java.net.URISyntaxException;
import static com.google.android.apps.dashclock.LogUtils.LOGE;
/**
* A basic proxy activity for handling widget clicks.
*/
public class WidgetClickProxyActivity extends Activity {
private static final String TAG = LogUtils.makeLogTag(WidgetClickProxyActivity.class);
/**
* If present, the component name of the extension to update upon being clicked.
*/
private static final String EXTRA_UPDATE_EXTENSION
= "com.google.android.apps.dashclock.extra.UPDATE_EXTENSION";
@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (hasFocus) {
if (getIntent().hasExtra(EXTRA_UPDATE_EXTENSION)) {
// Update extensions
Intent extensionUpdateIntent = new Intent(this, DashClockService.class);
extensionUpdateIntent.setAction(DashClockService.ACTION_UPDATE_EXTENSIONS);
extensionUpdateIntent.putExtra(DashClockService.EXTRA_COMPONENT_NAME,
getIntent().getStringExtra(EXTRA_UPDATE_EXTENSION));
extensionUpdateIntent.putExtra(DashClockService.EXTRA_UPDATE_REASON,
DashClockExtension.UPDATE_REASON_MANUAL);
startService(extensionUpdateIntent);
}
try {
startActivity(
Intent.parseUri(getIntent().getData().toString(), Intent.URI_INTENT_SCHEME)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_TASK_ON_HOME
| Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_FORWARD_RESULT));
} catch (URISyntaxException e) {
LOGE(TAG, "Error parsing URI.", e);
} catch (ActivityNotFoundException e) {
LOGE(TAG, "Proxy'd activity not found.", e);
} catch (SecurityException e) {
LOGE(TAG, "Don't have permission to launch proxy'd activity.", e);
}
finish();
}
super.onWindowFocusChanged(hasFocus);
}
public static Intent wrap(Context context, Intent intent) {
return wrap(context, intent, null);
}
public static Intent wrap(Context context, Intent intent, ComponentName alsoUpdateExtension) {
return new Intent(context, WidgetClickProxyActivity.class)
.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)))
.putExtra(EXTRA_UPDATE_EXTENSION, (alsoUpdateExtension == null)
? null
: alsoUpdateExtension.flattenToString())
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
}
public static Intent getTemplate(Context context) {
return new Intent(context, WidgetClickProxyActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
}
public static Intent getFillIntent(Intent clickIntent) {
return getFillIntent(clickIntent, null);
}
public static Intent getFillIntent(Intent clickIntent, ComponentName alsoUpdateExtension) {
return new Intent()
.setData(Uri.parse(clickIntent.toUri(Intent.URI_INTENT_SCHEME)))
.putExtra(EXTRA_UPDATE_EXTENSION, (alsoUpdateExtension == null)
? null
: alsoUpdateExtension.flattenToString());
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/WidgetClickProxyActivity.java | Java | asf20 | 4,530 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.service.dreams.DreamService;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Property;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ScrollView;
import com.google.android.apps.dashclock.render.DashClockRenderer;
import com.google.android.apps.dashclock.render.SimpleRenderer;
import com.google.android.apps.dashclock.render.SimpleViewBuilder;
import net.nurik.roman.dashclock.R;
import java.util.List;
import static com.google.android.apps.dashclock.ExtensionManager.ExtensionWithData;
/**
* Daydream for DashClock.
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public class DaydreamService extends DreamService implements
ExtensionManager.OnChangeListener,
DashClockRenderer.OnClickListener {
public static final String PREF_DAYDREAM_COLOR = "pref_daydream_color";
public static final String PREF_DAYDREAM_NIGHT_MODE = "pref_daydream_night_mode";
public static final String PREF_DAYDREAM_ANIMATION = "pref_daydream_animation";
private static final int DEFAULT_FOREGROUND_COLOR = 0xffffffff;
private static final int ANIMATION_HAS_ROTATE = 0x1;
private static final int ANIMATION_HAS_SLIDE = 0x2;
private static final int ANIMATION_HAS_FADE = 0x4;
private static final int ANIMATION_NONE = 0;
private static final int ANIMATION_FADE = ANIMATION_HAS_FADE;
private static final int ANIMATION_SLIDE = ANIMATION_FADE | ANIMATION_HAS_SLIDE;
private static final int ANIMATION_PENDULUM = ANIMATION_SLIDE | ANIMATION_HAS_ROTATE;
private static final int CYCLE_INTERVAL_MILLIS = 20000;
private static final int FADE_MILLIS = 5000;
private static final int TRAVEL_ROTATE_DEGREES = 3;
private static final float SCALE_WHEN_MOVING = 0.85f;
private Handler mHandler = new Handler();
private ExtensionManager mExtensionManager;
private int mTravelDistance;
private int mForegroundColor;
private int mAnimation;
private ViewGroup mDaydreamContainer;
private ViewGroup mExtensionsContainer;
private AnimatorSet mSingleCycleAnimator;
private boolean mAttached;
private boolean mNeedsRelayout;
private boolean mMovingLeft;
@Override
public void onDreamingStarted() {
super.onDreamingStarted();
mExtensionManager = ExtensionManager.getInstance(this);
mExtensionManager.addOnChangeListener(this);
}
@Override
public void onDreamingStopped() {
super.onDreamingStopped();
mExtensionManager.removeOnChangeListener(this);
mExtensionManager = null;
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
mAttached = true;
setInteractive(true);
setFullscreen(true);
// Read preferences
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
mForegroundColor = sp.getInt(PREF_DAYDREAM_COLOR, DEFAULT_FOREGROUND_COLOR);
String animation = sp.getString(PREF_DAYDREAM_ANIMATION, "");
if ("none".equals(animation)) {
mAnimation = ANIMATION_NONE;
} else if ("slide".equals(animation)) {
mAnimation = ANIMATION_SLIDE;
} else if ("fade".equals(animation)) {
mAnimation = ANIMATION_FADE;
} else {
mAnimation = ANIMATION_PENDULUM;
}
setScreenBright(!sp.getBoolean(PREF_DAYDREAM_NIGHT_MODE, true));
// Begin daydream
layoutDream();
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
mHandler.removeCallbacksAndMessages(null);
mAttached = false;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mHandler.removeCallbacks(mCycleRunnable);
layoutDream();
}
@Override
public void onExtensionsChanged() {
mHandler.removeCallbacks(mHandleExtensionsChanged);
mHandler.postDelayed(mHandleExtensionsChanged,
ExtensionHost.UPDATE_COLLAPSE_TIME_MILLIS);
}
private Runnable mHandleExtensionsChanged = new Runnable() {
@Override
public void run() {
renderDaydream(false);
}
};
private void layoutDream() {
setContentView(R.layout.daydream);
mNeedsRelayout = true;
renderDaydream(true);
mHandler.removeCallbacks(mCycleRunnable);
mHandler.postDelayed(mCycleRunnable, CYCLE_INTERVAL_MILLIS - FADE_MILLIS);
}
private void renderDaydream(final boolean restartAnimation) {
if (!mAttached) {
return;
}
if (restartAnimation) {
// Only modify fullscreen state if this render will restart an animation (enter a new
// cycle)
setFullscreen(true);
}
final Resources res = getResources();
mDaydreamContainer = (ViewGroup) findViewById(R.id.daydream_container);
RootLayout rootContainer = (RootLayout)
findViewById(R.id.daydream_root);
if (mTravelDistance == 0) {
mTravelDistance = rootContainer.getWidth() / 4;
}
rootContainer.setRootLayoutListener(new RootLayout.RootLayoutListener() {
@Override
public void onAwake() {
setFullscreen(false);
mHandler.removeCallbacks(mCycleRunnable);
mHandler.postDelayed(mCycleRunnable, CYCLE_INTERVAL_MILLIS);
mDaydreamContainer.animate()
.alpha(1f)
.rotation(0)
.scaleX(1f)
.scaleY(1f)
.translationX(0f)
.translationY(0f)
.setDuration(res.getInteger(android.R.integer.config_shortAnimTime));
mSingleCycleAnimator.cancel();
}
@Override
public void onSizeChanged(int width, int height) {
mTravelDistance = width / 4;
}
});
DisplayMetrics displayMetrics = res.getDisplayMetrics();
int screenWidthDp = (int) (displayMetrics.widthPixels * 1f / displayMetrics.density);
int screenHeightDp = (int) (displayMetrics.heightPixels * 1f / displayMetrics.density);
// Set up rendering
SimpleRenderer renderer = new SimpleRenderer(this);
DashClockRenderer.Options options = new DashClockRenderer.Options();
options.target = DashClockRenderer.Options.TARGET_DAYDREAM;
options.minWidthDp = screenWidthDp;
options.minHeightDp = screenHeightDp;
options.newTaskOnClick = true;
options.onClickListener = this;
options.clickIntentTemplate = WidgetClickProxyActivity.getTemplate(this);
renderer.setOptions(options);
// Render the clock face
SimpleViewBuilder vb = renderer.createSimpleViewBuilder();
vb.useRoot(mDaydreamContainer);
renderer.renderClockFace(vb);
vb.setLinearLayoutGravity(R.id.clock_target, Gravity.CENTER_HORIZONTAL);
// Render extensions
mExtensionsContainer = (ViewGroup) findViewById(R.id.extensions_container);
mExtensionsContainer.removeAllViews();
List<ExtensionWithData> visibleExtensions
= ExtensionManager.getInstance(this).getVisibleExtensionsWithData();
for (ExtensionWithData ewd : visibleExtensions) {
mExtensionsContainer.addView(
(View) renderer.renderExpandedExtension(mExtensionsContainer, null, ewd));
}
if (mDaydreamContainer.getHeight() == 0 || mNeedsRelayout) {
ViewTreeObserver vto = mDaydreamContainer.getViewTreeObserver();
if (vto.isAlive()) {
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewTreeObserver vto = mDaydreamContainer.getViewTreeObserver();
if (vto.isAlive()) {
vto.removeOnGlobalLayoutListener(this);
}
postLayoutRender(restartAnimation);
}
});
}
mDaydreamContainer.requestLayout();
mNeedsRelayout = false;
} else {
postLayoutRender(restartAnimation);
}
}
/**
* Post-layout render code.
*/
public void postLayoutRender(boolean restartAnimation) {
Resources res = getResources();
// Adjust the ScrollView
ExposedScrollView scrollView = (ExposedScrollView) findViewById(R.id.extensions_scroller);
int maxScroll = scrollView.computeVerticalScrollRange() - scrollView.getHeight();
if (maxScroll < 0) {
ViewGroup.LayoutParams lp = scrollView.getLayoutParams();
lp.height = mExtensionsContainer.getHeight();
scrollView.setLayoutParams(lp);
mDaydreamContainer.requestLayout();
}
// Recolor widget
Utils.traverseAndRecolor(mDaydreamContainer, mForegroundColor, true);
if (restartAnimation) {
int x = 0;
int deg = 0;
if ((mAnimation & ANIMATION_HAS_SLIDE) != 0) {
x = (mMovingLeft ? 1 : -1) * mTravelDistance;
}
if ((mAnimation & ANIMATION_HAS_ROTATE) != 0) {
deg = (mMovingLeft ? 1 : -1) * TRAVEL_ROTATE_DEGREES;
}
mMovingLeft = !mMovingLeft;
mDaydreamContainer.animate().cancel();
if ((mAnimation & ANIMATION_HAS_SLIDE) != 0) {
// Only use small size when moving
mDaydreamContainer.setScaleX(SCALE_WHEN_MOVING);
mDaydreamContainer.setScaleY(SCALE_WHEN_MOVING);
}
if (mSingleCycleAnimator != null) {
mSingleCycleAnimator.cancel();
}
Animator scrollDownAnimator = ObjectAnimator.ofInt(scrollView,
ExposedScrollView.SCROLL_POS, 0, maxScroll);
scrollDownAnimator.setDuration(CYCLE_INTERVAL_MILLIS / 5);
scrollDownAnimator.setStartDelay(CYCLE_INTERVAL_MILLIS / 5);
Animator scrollUpAnimator = ObjectAnimator.ofInt(scrollView,
ExposedScrollView.SCROLL_POS, 0);
scrollUpAnimator.setDuration(CYCLE_INTERVAL_MILLIS / 5);
scrollUpAnimator.setStartDelay(CYCLE_INTERVAL_MILLIS / 5);
AnimatorSet scrollAnimator = new AnimatorSet();
scrollAnimator.playSequentially(scrollDownAnimator, scrollUpAnimator);
Animator moveAnimator = ObjectAnimator.ofFloat(mDaydreamContainer,
View.TRANSLATION_X, x, -x).setDuration(CYCLE_INTERVAL_MILLIS);
moveAnimator.setInterpolator(new LinearInterpolator());
Animator rotateAnimator = ObjectAnimator.ofFloat(mDaydreamContainer,
View.ROTATION, deg, -deg).setDuration(CYCLE_INTERVAL_MILLIS);
moveAnimator.setInterpolator(new LinearInterpolator());
mSingleCycleAnimator = new AnimatorSet();
mSingleCycleAnimator.playTogether(scrollAnimator, moveAnimator, rotateAnimator);
mSingleCycleAnimator.start();
}
}
public Runnable mCycleRunnable = new Runnable() {
@Override
public void run() {
float outAlpha = 1f;
if ((mAnimation & ANIMATION_HAS_FADE) != 0) {
outAlpha = 0f;
}
mDaydreamContainer.animate().alpha(outAlpha).setDuration(FADE_MILLIS)
.withEndAction(new Runnable() {
@Override
public void run() {
renderDaydream(true);
mHandler.removeCallbacks(mCycleRunnable);
mHandler.postDelayed(mCycleRunnable,
CYCLE_INTERVAL_MILLIS - FADE_MILLIS);
mDaydreamContainer.animate().alpha(1f).setDuration(FADE_MILLIS);
}
});
}
};
@Override
public void onClick() {
// Any time anything in DashClock is clicked
finish();
}
/**
* FrameLayout that can notify listeners of ACTION_DOWN events.
*/
public static class RootLayout extends FrameLayout {
private RootLayoutListener mRootLayoutListener;
public RootLayout(Context context) {
super(context);
}
public RootLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RootLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
if (mRootLayoutListener != null) {
mRootLayoutListener.onAwake();
}
break;
// ACTION_UP doesn't seem to reliably get called. Otherwise
// should postDelayed on ACTION_UP instead of ACTION_DOWN.
}
return false;
}
public void setRootLayoutListener(RootLayoutListener rootLayoutListener) {
mRootLayoutListener = rootLayoutListener;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mRootLayoutListener != null) {
mRootLayoutListener.onSizeChanged(w, h);
}
}
public static interface RootLayoutListener {
void onAwake();
void onSizeChanged(int width, int height);
}
}
/**
* ScrollView that exposes its scroll range.
*/
public static class ExposedScrollView extends ScrollView {
public ExposedScrollView(Context context) {
super(context);
}
public ExposedScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExposedScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public int computeVerticalScrollRange() {
return super.computeVerticalScrollRange();
}
public static final Property<ScrollView, Integer> SCROLL_POS
= new Property<ScrollView, Integer>(Integer.class, "scrollPos") {
@Override
public void set(ScrollView object, Integer value) {
object.scrollTo(0, value);
}
@Override
public Integer get(ScrollView object) {
return object.getScrollY();
}
};
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/DaydreamService.java | Java | asf20 | 16,379 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import java.util.List;
import static com.google.android.apps.dashclock.LogUtils.LOGD;
/**
* Broadcast receiver used to watch for changes to installed packages on the device. This triggers
* a cleanup of extensions (in case one was uninstalled), or a data update request to an extension
* if it was updated (its package was replaced).
*/
public class ExtensionPackageChangeReceiver extends BroadcastReceiver {
private static final String TAG = LogUtils.makeLogTag(ExtensionPackageChangeReceiver.class);
@Override
public void onReceive(Context context, Intent intent) {
ExtensionManager extensionManager = ExtensionManager.getInstance(context);
if (extensionManager.cleanupExtensions()) {
LOGD(TAG, "Extension cleanup performed and action taken.");
Intent widgetUpdateIntent = new Intent(context, DashClockService.class);
widgetUpdateIntent.setAction(DashClockService.ACTION_UPDATE_WIDGETS);
context.startService(widgetUpdateIntent);
}
// If this is a replacement or change in the package, update all active extensions from
// this package.
String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
String packageName = intent.getData().getSchemeSpecificPart();
if (TextUtils.isEmpty(packageName)) {
return;
}
List<ComponentName> activeExtensions = extensionManager.getActiveExtensionNames();
for (ComponentName cn : activeExtensions) {
if (packageName.equals(cn.getPackageName())) {
Intent extensionUpdateIntent = new Intent(context, DashClockService.class);
extensionUpdateIntent.setAction(DashClockService.ACTION_UPDATE_EXTENSIONS);
// TODO: UPDATE_REASON_PACKAGE_CHANGED
extensionUpdateIntent.putExtra(DashClockService.EXTRA_COMPONENT_NAME,
cn.flattenToShortString());
context.startService(extensionUpdateIntent);
}
}
}
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/ExtensionPackageChangeReceiver.java | Java | asf20 | 3,022 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.IDashClockDataProvider;
import com.google.android.apps.dashclock.api.VisibleExtension;
import com.google.android.apps.dashclock.render.WidgetRenderer;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.List;
import static com.google.android.apps.dashclock.LogUtils.LOGD;
/**
* The primary service for DashClock. This service is in charge of updating widget UI (see {@link
* #ACTION_UPDATE_WIDGETS}) and updating extension data via an internal instance of {@link
* ExtensionHost} (see {@link #ACTION_UPDATE_EXTENSIONS}).
*/
public class DashClockService extends Service implements ExtensionManager.OnChangeListener {
private static final String TAG = LogUtils.makeLogTag(DashClockService.class);
/**
* Intent action for updating widget views. If {@link #EXTRA_APPWIDGET_ID} is provided, updates
* only that widget. Otherwise, updates all widgets.
*/
public static final String ACTION_UPDATE_WIDGETS =
"com.google.android.apps.dashclock.action.UPDATE_WIDGETS";
public static final String EXTRA_APPWIDGET_ID =
"com.google.android.apps.dashclock.extra.APPWIDGET_ID";
/**
* Intent action for telling extensions to update their data. If {@link #EXTRA_COMPONENT_NAME}
* is provided, updates only that extension. Otherwise, updates all active extensions. Also
* optional is {@link #EXTRA_UPDATE_REASON} (see {@link DashClockExtension} for update reasons).
*/
public static final String ACTION_UPDATE_EXTENSIONS =
"com.google.android.apps.dashclock.action.UPDATE_EXTENSIONS";
public static final String EXTRA_COMPONENT_NAME =
"com.google.android.apps.dashclock.extra.COMPONENT_NAME";
public static final String EXTRA_UPDATE_REASON =
"com.google.android.apps.dashclock.extra.UPDATE_REASON";
/**
* Broadcast intent action that's triggered when the set of visible extensions or their
* data change.
*/
public static final String ACTION_EXTENSIONS_CHANGED =
"com.google.android.apps.dashclock.action.EXTENSIONS_CHANGED";
/**
* Private Read API
*/
public static final String ACTION_BIND_DASHCLOCK_SERVICE
= "com.google.android.apps.dashclock.action.BIND_SERVICE";
private ExtensionManager mExtensionManager;
private ExtensionHost mExtensionHost;
private Handler mUpdateHandler = new Handler();
@Override
public void onCreate() {
super.onCreate();
mExtensionManager = ExtensionManager.getInstance(this);
mExtensionManager.addOnChangeListener(this);
mExtensionHost = new ExtensionHost(this);
}
@Override
public void onDestroy() {
super.onDestroy();
mUpdateHandler.removeCallbacksAndMessages(null);
mExtensionManager.removeOnChangeListener(this);
mExtensionHost.destroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
if (ACTION_UPDATE_WIDGETS.equals(action)) {
handleUpdateWidgets(intent);
} else if (ACTION_UPDATE_EXTENSIONS.equals(action)) {
handleUpdateExtensions(intent);
}
}
return START_STICKY;
}
@Override
public void onExtensionsChanged() {
mUpdateHandler.removeCallbacks(mExtensionsChangedRunnable);
mUpdateHandler.postDelayed(mExtensionsChangedRunnable,
ExtensionHost.UPDATE_COLLAPSE_TIME_MILLIS);
}
private Runnable mExtensionsChangedRunnable = new Runnable() {
@Override
public void run() {
sendBroadcast(new Intent(ACTION_EXTENSIONS_CHANGED));
handleUpdateWidgets(new Intent());
}
};
/**
* Updates a widget's UI.
*/
private void handleUpdateWidgets(Intent intent) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
// Either update all app widgets, or only those which were requested.
int appWidgetIds[];
if (intent.hasExtra(EXTRA_APPWIDGET_ID)) {
appWidgetIds = new int[]{intent.getIntExtra(EXTRA_APPWIDGET_ID, -1)};
} else {
appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(
this, WidgetProvider.class));
}
StringBuilder sb = new StringBuilder();
for (int appWidgetId : appWidgetIds) {
sb.append(appWidgetId).append(" ");
}
LOGD(TAG, "Rendering widgets with appWidgetId(s): " + sb);
WidgetRenderer.renderWidgets(this, appWidgetIds);
}
/**
* Asks extensions to provide data updates.
*/
private void handleUpdateExtensions(Intent intent) {
int reason = intent.getIntExtra(EXTRA_UPDATE_REASON,
DashClockExtension.UPDATE_REASON_UNKNOWN);
// Either update all extensions, or only the requested one.
String updateExtension = intent.getStringExtra(EXTRA_COMPONENT_NAME);
if (!TextUtils.isEmpty(updateExtension)) {
ComponentName cn = ComponentName.unflattenFromString(updateExtension);
mExtensionHost.execute(cn, ExtensionHost.UPDATE_OPERATIONS.get(reason),
ExtensionHost.UPDATE_COLLAPSE_TIME_MILLIS, reason);
} else {
for (ComponentName cn : mExtensionManager.getActiveExtensionNames()) {
mExtensionHost.execute(cn, ExtensionHost.UPDATE_OPERATIONS.get(reason),
ExtensionHost.UPDATE_COLLAPSE_TIME_MILLIS, reason);
}
}
}
@Override
public IBinder onBind(Intent intent) {
if (ACTION_BIND_DASHCLOCK_SERVICE.equals(intent.getAction())) {
// Private Read API
return new IDashClockDataProvider.Stub() {
@Override
public List<VisibleExtension> getVisibleExtensionData() throws RemoteException {
List<VisibleExtension> visibleExtensions = new ArrayList<VisibleExtension>();
for (ExtensionManager.ExtensionWithData extension :
mExtensionManager.getVisibleExtensionsWithData()) {
if (!extension.listing.worldReadable) {
// Enforce permissions. This private 'read API' only exposes
// data from world-readable extensions.
continue;
}
visibleExtensions.add(new VisibleExtension()
.data(extension.latestData)
.componentName(extension.listing.componentName));
}
return visibleExtensions;
}
@Override
public void updateExtensions() {
handleUpdateExtensions(new Intent());
}
};
}
return null;
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/DashClockService.java | Java | asf20 | 8,020 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.apps.dashclock.api.ExtensionData;
import com.google.android.apps.dashclock.phone.MissedCallsExtension;
import com.google.android.apps.dashclock.phone.SmsExtension;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import static com.google.android.apps.dashclock.LogUtils.LOGE;
/**
* Because every project needs a Utils class.
*/
public class Utils {
private static final String TAG = LogUtils.makeLogTag(Utils.class);
private static final String USER_AGENT = "DashClock/0.0";
public static final int EXTENSION_ICON_SIZE = 128;
private static final String[] CLOCK_PACKAGES = new String[] {
"com.google.android.deskclock",
"com.android.deskclock",
};
// TODO: Let's use a *real* HTTP library, eh?
public static HttpURLConnection openUrlConnection(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setUseCaches(false);
conn.setChunkedStreamingMode(0);
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.connect();
return conn;
}
public static Bitmap flattenExtensionIcon(Drawable baseIcon, int color) {
if (baseIcon == null) {
return null;
}
Bitmap outBitmap = Bitmap.createBitmap(EXTENSION_ICON_SIZE, EXTENSION_ICON_SIZE,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(outBitmap);
baseIcon.setBounds(0, 0, EXTENSION_ICON_SIZE, EXTENSION_ICON_SIZE);
baseIcon.setColorFilter(color,
PorterDuff.Mode.SRC_IN);
baseIcon.draw(canvas);
baseIcon.setColorFilter(null);
baseIcon.setCallback(null); // free up any references
return outBitmap;
}
public static Bitmap flattenExtensionIcon(Context context, Bitmap baseIcon, int color) {
return flattenExtensionIcon(new BitmapDrawable(context.getResources(), baseIcon), color);
}
public static Intent getDefaultClockIntent(Context context) {
PackageManager pm = context.getPackageManager();
for (String packageName : CLOCK_PACKAGES) {
try {
pm.getPackageInfo(packageName, 0);
return pm.getLaunchIntentForPackage(packageName);
} catch (PackageManager.NameNotFoundException ignored) {
}
}
return null;
}
public static Intent getDefaultAlarmsIntent(Context context) {
// TODO: consider using AlarmClock.ACTION_SET_ALARM, although it requires a permission
PackageManager pm = context.getPackageManager();
for (String packageName : CLOCK_PACKAGES) {
try {
ComponentName cn = new ComponentName(packageName,
"com.android.deskclock.AlarmClock");
pm.getActivityInfo(cn, 0);
return Intent.makeMainActivity(cn);
} catch (PackageManager.NameNotFoundException ignored) {
}
}
return getDefaultClockIntent(context);
}
public static Bitmap loadExtensionIcon(Context context, ComponentName extension,
int icon, Uri iconUri) {
if (iconUri != null) {
return loadExtensionIconFromUri(context, iconUri);
}
if (icon <= 0) {
return null;
}
String packageName = extension.getPackageName();
try {
Context packageContext = context.createPackageContext(packageName, 0);
Resources packageRes = packageContext.getResources();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(packageRes, icon, options);
// Cut down the icon to a smaller size.
int sampleSize = 1;
while (true) {
if (options.outHeight / (sampleSize * 2) > Utils.EXTENSION_ICON_SIZE / 2) {
sampleSize *= 2;
} else {
break;
}
}
options.inJustDecodeBounds = false;
options.inSampleSize = sampleSize;
return Utils.flattenExtensionIcon(
context,
BitmapFactory.decodeResource(packageRes, icon, options),
0xffffffff);
} catch (PackageManager.NameNotFoundException e) {
LOGE(TAG, "Couldn't access extension's package while loading icon data.");
}
return null;
}
public static Bitmap loadExtensionIconFromUri(Context context, Uri iconUri) {
try {
ParcelFileDescriptor pfd = context.getContentResolver()
.openFileDescriptor(iconUri, "r");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor(), null, options);
// Cut down the icon to a smaller size.
int sampleSize = 1;
while (true) {
if (options.outHeight / (sampleSize * 2) > Utils.EXTENSION_ICON_SIZE / 2) {
sampleSize *= 2;
} else {
break;
}
}
options.inJustDecodeBounds = false;
options.inSampleSize = sampleSize;
return Utils.flattenExtensionIcon(
context,
BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor(), null, options),
0xffffffff);
} catch (IOException e) {
LOGE(TAG, "Couldn't read icon from content URI.", e);
} catch (SecurityException e) {
LOGE(TAG, "Couldn't read icon from content URI.", e);
}
return null;
}
public static String expandedTitleOrStatus(ExtensionData data) {
String expandedTitle = data.expandedTitle();
if (TextUtils.isEmpty(expandedTitle)) {
expandedTitle = data.status();
if (!TextUtils.isEmpty(expandedTitle)) {
expandedTitle = expandedTitle.replace("\n", " ");
}
}
return expandedTitle;
}
public static void traverseAndRecolor(View root, int color, boolean withStates) {
if (root instanceof ViewGroup) {
ViewGroup parent = (ViewGroup) root;
for (int i = 0; i < parent.getChildCount(); i++) {
traverseAndRecolor(parent.getChildAt(i), color, withStates);
}
} else if (root instanceof ImageView) {
ImageView imageView = (ImageView) root;
Drawable sourceDrawable = imageView.getDrawable();
if (withStates && sourceDrawable != null && sourceDrawable instanceof BitmapDrawable) {
BitmapDrawable sourceBitmapDrawable = (BitmapDrawable) sourceDrawable;
Bitmap newBitmap = Bitmap.createBitmap(sourceBitmapDrawable.getBitmap());
Canvas newCanvas = new Canvas(newBitmap);
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
paint.setColor(color);
newCanvas.drawRect(0, 0, newBitmap.getWidth(), newBitmap.getHeight(), paint);
BitmapDrawable recoloredDrawable = new BitmapDrawable(
root.getContext().getResources(), newBitmap);
StateListDrawable stateDrawable = new StateListDrawable();
stateDrawable.addState(new int[]{android.R.attr.state_pressed},
sourceDrawable);
stateDrawable.addState(new int[]{android.R.attr.state_focused},
sourceDrawable);
stateDrawable.addState(new int[]{}, recoloredDrawable);
imageView.setImageDrawable(stateDrawable);
} else {
imageView.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
}
} else if (root instanceof TextView) {
TextView textView = (TextView) root;
if (withStates) {
int sourceColor = textView.getCurrentTextColor();
ColorStateList colorStateList = new ColorStateList(new int[][]{
new int[]{android.R.attr.state_pressed},
new int[]{android.R.attr.state_focused},
new int[]{}
}, new int[]{
sourceColor,
sourceColor,
color
});
textView.setTextColor(colorStateList);
} else {
textView.setTextColor(color);
}
}
}
private static Class[] sPhoneOnlyExtensions = {
SmsExtension.class,
MissedCallsExtension.class,
};
public static void enableDisablePhoneOnlyExtensions(Context context) {
PackageManager pm = context.getPackageManager();
boolean hasTelephony = pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
for (Class ext : sPhoneOnlyExtensions) {
pm.setComponentEnabledSetting(new ComponentName(context, ext), hasTelephony
? PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/Utils.java | Java | asf20 | 10,877 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock;
import com.google.android.apps.dashclock.api.DashClockExtension;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import static com.google.android.apps.dashclock.LogUtils.LOGD;
/**
* The DashClock {@link AppWidgetProvider}, which just forwards commands to {@link
* DashClockService}.
*/
public class WidgetProvider extends AppWidgetProvider {
private static final String TAG = LogUtils.makeLogTag(WidgetProvider.class);
@Override
public void onUpdate(final Context context, final AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
// Update extensions
Intent extensionUpdateIntent = new Intent(context, DashClockService.class);
extensionUpdateIntent.setAction(DashClockService.ACTION_UPDATE_EXTENSIONS);
extensionUpdateIntent.putExtra(DashClockService.EXTRA_UPDATE_REASON,
DashClockExtension.UPDATE_REASON_PERIODIC);
context.startService(extensionUpdateIntent);
// Update widgets
for (final int appWidgetId : appWidgetIds) {
Intent widgetUpdateIntent = new Intent(context, DashClockService.class);
widgetUpdateIntent.setAction(DashClockService.ACTION_UPDATE_WIDGETS);
widgetUpdateIntent.putExtra(DashClockService.EXTRA_APPWIDGET_ID, appWidgetId);
context.startService(widgetUpdateIntent);
}
StringBuilder sb = new StringBuilder();
for (int appWidgetId : appWidgetIds) {
sb.append(appWidgetId).append(" ");
}
LOGD(TAG, "onUpdate for appWidgetId(s): " + sb);
}
@Override
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager,
int appWidgetId, Bundle newOptions) {
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
LOGD(TAG, "onAppWidgetOptionsChanged for appWidgetId: " + appWidgetId);
Intent widgetUpdateIntent = new Intent(context, DashClockService.class);
widgetUpdateIntent.setAction(DashClockService.ACTION_UPDATE_WIDGETS);
widgetUpdateIntent.putExtra(DashClockService.EXTRA_APPWIDGET_ID, appWidgetId);
context.startService(widgetUpdateIntent);
}
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
LOGD(TAG, "onDisabled; stopping DashClockService.");
context.stopService(new Intent(context, DashClockService.class));
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
int[] remainingIds = AppWidgetManager.getInstance(context).getAppWidgetIds(
new ComponentName(context, WidgetProvider.class));
if (remainingIds == null || remainingIds.length == 0) {
LOGD(TAG, "Widget deleted, none remaining; stopping DashClockService.");
context.stopService(new Intent(context, DashClockService.class));
} else {
LOGD(TAG, "Widget deleted, " + remainingIds.length + " remaining.");
}
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/WidgetProvider.java | Java | asf20 | 3,940 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// THIS IS A BETA! I DON'T RECOMMEND USING IT IN PRODUCTION CODE JUST YET
package com.google.android.apps.dashclock.ui;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A {@link android.view.View.OnTouchListener} that makes the list items in a {@link ListView}
* dismissable. {@link ListView} is given special treatment because by default it handles touches
* for its list items... i.e. it's in charge of drawing the pressed state (the list selector),
* handling list item clicks, etc.
*
* <p>After creating the listener, the caller should also call {@link
* ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener)}, passing in the scroll
* listener returned by {@link #makeScrollListener()}. If a scroll listener is already assigned, the
* caller should still pass scroll changes through to this listener. This will ensure that this
* {@link SwipeDismissListViewTouchListener} is paused during list view scrolling.</p>
*
* <p>Example usage:</p>
*
* <pre>
* SwipeDismissListViewTouchListener touchListener =
* new SwipeDismissListViewTouchListener(
* listView,
* new SwipeDismissListViewTouchListener.OnDismissCallback() {
* public void onDismiss(ListView listView, int[] reverseSortedPositions) {
* for (int position : reverseSortedPositions) {
* adapter.remove(adapter.getItem(position));
* }
* adapter.notifyDataSetChanged();
* }
* });
* listView.setOnTouchListener(touchListener);
* listView.setOnScrollListener(touchListener.makeScrollListener());
* </pre>
*
* <p>This class Requires API level 12 or later due to use of {@link
* android.view.ViewPropertyAnimator}.</p>
*/
public class SwipeDismissListViewTouchListener implements View.OnTouchListener {
// Cached ViewConfiguration and system-wide constant values
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
private ListView mListView;
private DismissCallbacks mCallbacks;
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
// Transient properties
private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>();
private int mDismissAnimationRefCount = 0;
private float mDownX;
private boolean mSwiping;
private VelocityTracker mVelocityTracker;
private int mDownPosition;
private View mDownView;
private boolean mPaused;
/**
* The callback interface used by {@link SwipeDismissListViewTouchListener} to inform its client
* about a successful dismissal of one or more list item positions.
*/
public interface DismissCallbacks {
/**
* Called to determine whether the given position can be dismissed.
*/
boolean canDismiss(int position);
/**
* Called when the user has indicated they she would like to dismiss one or more list item
* positions.
*
* @param listView The originating {@link ListView}.
* @param reverseSortedPositions An array of positions to dismiss, sorted in descending
* order for convenience.
*/
void onDismiss(ListView listView, int[] reverseSortedPositions);
}
/**
* Constructs a new swipe-to-dismiss touch listener for the given list view.
*
* @param listView The list view whose items should be dismissable.
* @param callbacks The callback to trigger when the user has indicated that she would like to
* dismiss one or more list items.
*/
public SwipeDismissListViewTouchListener(ListView listView, DismissCallbacks callbacks) {
ViewConfiguration vc = ViewConfiguration.get(listView.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mAnimationTime = listView.getContext().getResources().getInteger(
android.R.integer.config_shortAnimTime);
mListView = listView;
mCallbacks = callbacks;
}
/**
* Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures.
*
* @param enabled Whether or not to watch for gestures.
*/
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
/**
* Returns an {@link android.widget.AbsListView.OnScrollListener} to be added to the {@link
* ListView} using {@link ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener)}.
* If a scroll listener is already assigned, the caller should still pass scroll changes through
* to this listener. This will ensure that this {@link SwipeDismissListViewTouchListener} is
* paused during list view scrolling.</p>
*
* @see SwipeDismissListViewTouchListener
*/
public AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
@Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
};
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (mViewWidth < 2) {
mViewWidth = mListView.getWidth();
}
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
if (mPaused) {
return false;
}
// TODO: ensure this is a finger, and set a flag
// Find the child view that was touched (perform a hit test)
Rect rect = new Rect();
int childCount = mListView.getChildCount();
int[] listViewCoords = new int[2];
mListView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child;
for (int i = 0; i < childCount; i++) {
child = mListView.getChildAt(i);
child.getHitRect(rect);
if (rect.contains(x, y)) {
mDownView = child;
break;
}
}
if (mDownView != null) {
mDownX = motionEvent.getRawX();
mDownPosition = mListView.getPositionForView(mDownView);
if (mCallbacks.canDismiss(mDownPosition)) {
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
} else {
mDownView = null;
}
}
view.onTouchEvent(motionEvent);
return true;
}
case MotionEvent.ACTION_UP: {
if (mVelocityTracker == null) {
break;
}
float deltaX = motionEvent.getRawX() - mDownX;
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = mVelocityTracker.getXVelocity();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
boolean dismiss = false;
boolean dismissRight = false;
if (Math.abs(deltaX) > mViewWidth / 2) {
dismiss = true;
dismissRight = deltaX > 0;
} else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
&& absVelocityY < absVelocityX) {
// dismiss only if flinging in the same direction as dragging
dismiss = (velocityX < 0) == (deltaX < 0);
dismissRight = mVelocityTracker.getXVelocity() > 0;
}
if (dismiss) {
// dismiss
final View downView = mDownView; // mDownView gets null'd before animation ends
final int downPosition = mDownPosition;
++mDismissAnimationRefCount;
mDownView.animate()
.translationX(dismissRight ? mViewWidth : -mViewWidth)
.alpha(0)
.setDuration(mAnimationTime)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
performDismiss(downView, downPosition);
}
});
} else {
// cancel
mDownView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
break;
}
case MotionEvent.ACTION_MOVE: {
if (mVelocityTracker == null || mPaused) {
break;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
if (Math.abs(deltaX) > mSlop) {
mSwiping = true;
mListView.requestDisallowInterceptTouchEvent(true);
// Cancel ListView's touch (un-highlighting the item)
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
(motionEvent.getActionIndex()
<< MotionEvent.ACTION_POINTER_INDEX_SHIFT));
mListView.onTouchEvent(cancelEvent);
cancelEvent.recycle();
}
if (mSwiping) {
mDownView.setTranslationX(deltaX);
mDownView.setAlpha(Math.max(0f, Math.min(1f,
1f - 2f * Math.abs(deltaX) / mViewWidth)));
return true;
}
break;
}
}
return false;
}
class PendingDismissData implements Comparable<PendingDismissData> {
public int position;
public View view;
public PendingDismissData(int position, View view) {
this.position = position;
this.view = view;
}
@Override
public int compareTo(PendingDismissData other) {
// Sort by descending position
return other.position - position;
}
}
private void performDismiss(final View dismissView, final int dismissPosition) {
// Animate the dismissed list item to zero-height and fire the dismiss callback when
// all dismissed list item animations have completed. This triggers layout on each animation
// frame; in the future we may want to do something smarter and more performant.
final ViewGroup.LayoutParams lp = dismissView.getLayoutParams();
final int originalHeight = dismissView.getHeight();
ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
--mDismissAnimationRefCount;
if (mDismissAnimationRefCount == 0) {
// No active animations, process all pending dismisses.
// Sort by descending position
Collections.sort(mPendingDismisses);
int[] dismissPositions = new int[mPendingDismisses.size()];
for (int i = mPendingDismisses.size() - 1; i >= 0; i--) {
dismissPositions[i] = mPendingDismisses.get(i).position;
}
mCallbacks.onDismiss(mListView, dismissPositions);
ViewGroup.LayoutParams lp;
for (PendingDismissData pendingDismiss : mPendingDismisses) {
// Reset view presentation
pendingDismiss.view.setAlpha(1f);
pendingDismiss.view.setTranslationX(0);
lp = pendingDismiss.view.getLayoutParams();
lp.height = originalHeight;
pendingDismiss.view.setLayoutParams(lp);
}
mPendingDismisses.clear();
}
}
});
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
lp.height = (Integer) valueAnimator.getAnimatedValue();
dismissView.setLayoutParams(lp);
}
});
mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
animator.start();
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/ui/SwipeDismissListViewTouchListener.java | Java | asf20 | 15,050 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.ui;
import net.nurik.roman.dashclock.R;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
public class DragGripView extends View {
private static final int[] ATTRS = new int[]{
android.R.attr.gravity,
android.R.attr.color,
};
private static final int HORIZ_RIDGES = 2;
private int mGravity = Gravity.START;
private int mColor = 0x33333333;
private Paint mRidgePaint;
private float mRidgeSize;
private float mRidgeGap;
private int mWidth;
private int mHeight;
public DragGripView(Context context) {
this(context, null, 0);
}
public DragGripView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DragGripView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);
mGravity = a.getInteger(0, mGravity);
mColor = a.getColor(1, mColor);
a.recycle();
final Resources res = getResources();
mRidgeSize = res.getDimensionPixelSize(R.dimen.drag_grip_ridge_size);
mRidgeGap = res.getDimensionPixelSize(R.dimen.drag_grip_ridge_gap);
mRidgePaint = new Paint();
mRidgePaint.setColor(mColor);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(
View.resolveSize(
(int) (HORIZ_RIDGES * (mRidgeSize + mRidgeGap) - mRidgeGap)
+ getPaddingLeft() + getPaddingRight(),
widthMeasureSpec),
View.resolveSize(
(int) mRidgeSize,
heightMeasureSpec));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float drawWidth = HORIZ_RIDGES * (mRidgeSize + mRidgeGap) - mRidgeGap;
float drawLeft;
switch (Gravity.getAbsoluteGravity(mGravity, getLayoutDirection())
& Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
drawLeft = getPaddingLeft()
+ ((mWidth - getPaddingLeft() - getPaddingRight()) - drawWidth) / 2;
break;
case Gravity.RIGHT:
drawLeft = getWidth() - getPaddingRight() - drawWidth;
break;
default:
drawLeft = getPaddingLeft();
}
int vertRidges = (int) ((mHeight - getPaddingTop() - getPaddingBottom() + mRidgeGap)
/ (mRidgeSize + mRidgeGap));
float drawHeight = vertRidges * (mRidgeSize + mRidgeGap) - mRidgeGap;
float drawTop = getPaddingTop()
+ ((mHeight - getPaddingTop() - getPaddingBottom()) - drawHeight) / 2;
for (int y = 0; y < vertRidges; y++) {
for (int x = 0; x < HORIZ_RIDGES; x++) {
canvas.drawRect(
drawLeft + x * (mRidgeSize + mRidgeGap),
drawTop + y * (mRidgeSize + mRidgeGap),
drawLeft + x * (mRidgeSize + mRidgeGap) + mRidgeSize,
drawTop + y * (mRidgeSize + mRidgeGap) + mRidgeSize,
mRidgePaint);
}
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mHeight = h;
mWidth = w;
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/ui/DragGripView.java | Java | asf20 | 4,366 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.ui;
import net.nurik.roman.dashclock.R;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A helper class for creating swipeable tabs without the use of {@link android.app.ActionBar} APIs.
*/
public class SimplePagedTabsHelper {
private Context mContext;
private ViewGroup mTabContainer;
private ViewPager mPager;
private Map<View, Integer> mTabPositions = new HashMap<View, Integer>();
private List<Integer> mTabContentIds = new ArrayList<Integer>();
public SimplePagedTabsHelper(Context context, ViewGroup tabContainer, ViewPager pager) {
mContext = context;
mTabContainer = tabContainer;
mPager = pager;
pager.setAdapter(mAdapter);
pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
for (int i = 0; i < mTabContainer.getChildCount(); i++) {
mTabContainer.getChildAt(i).setSelected(i == position);
}
}
});
}
public void addTab(int labelResId, int contentViewId) {
addTab(mContext.getString(labelResId), contentViewId);
}
public void addTab(CharSequence label, int contentViewId) {
View tabView = LayoutInflater.from(mContext).inflate(R.layout.tab, mTabContainer, false);
((TextView) tabView.findViewById(R.id.tab)).setText(label);
tabView.setOnClickListener(mTabClickListener);
int position = mTabContentIds.size();
tabView.setSelected(mPager.getCurrentItem() == position);
mTabPositions.put(tabView, position);
mTabContainer.addView(tabView);
mTabContentIds.add(contentViewId);
mAdapter.notifyDataSetChanged();
}
private View.OnClickListener mTabClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
mPager.setCurrentItem(mTabPositions.get(view));
}
};
private PagerAdapter mAdapter = new PagerAdapter() {
@Override
public int getCount() {
return mTabContentIds.size();
}
@Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
return mPager.findViewById(mTabContentIds.get(position));
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// No-op
}
};
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/ui/SimplePagedTabsHelper.java | Java | asf20 | 3,517 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.ui;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class PagerPositionStrip extends View {
private static final int[] ATTRS = new int[]{
android.R.attr.color,
};
private int mPageCount;
private float mPosition;
private int mColor = 0xff000000;
private float mIndicatorWidth;
private Paint mIndicatorPaint;
private RectF mTempRectF = new RectF();
private int mWidth;
private int mHeight;
public PagerPositionStrip(Context context) {
this(context, null, 0);
}
public PagerPositionStrip(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PagerPositionStrip(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);
mColor = a.getColor(0, mColor);
a.recycle();
mIndicatorPaint = new Paint();
mIndicatorPaint.setColor(mColor);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mPageCount == 0) {
return;
}
mTempRectF.top = 0;
mTempRectF.bottom = mHeight;
mTempRectF.left = mPosition / mPageCount * (mWidth);
mTempRectF.right = mTempRectF.left + mIndicatorWidth;
canvas.drawRect(mTempRectF, mIndicatorPaint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(
View.resolveSize(0, widthMeasureSpec),
View.resolveSize(0, heightMeasureSpec));
}
public void setPosition(float currentPosition) {
mPosition = currentPosition;
postInvalidateOnAnimation();
}
public void setPageCount(int count) {
mPageCount = count;
recalculateIndicatorWidth();
postInvalidateOnAnimation();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mHeight = h;
mWidth = w;
recalculateIndicatorWidth();
}
private void recalculateIndicatorWidth() {
mIndicatorWidth = (mPageCount > 0) ? (mWidth * 1f / mPageCount) : 0;
}
}
| zywhlc-dashclock | main/src/main/java/com/google/android/apps/dashclock/ui/PagerPositionStrip.java | Java | asf20 | 3,088 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.api;
parcelable VisibleExtension;
| zywhlc-dashclock | main/src/main/aidl/com/google/android/apps/dashclock/api/VisibleExtension.aidl | AIDL | asf20 | 673 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.api;
import com.google.android.apps.dashclock.api.VisibleExtension;
// Private API for now.
interface IDashClockDataProvider {
// Gets the visible extension data.
List<VisibleExtension> getVisibleExtensionData();
oneway void updateExtensions();
}
| zywhlc-dashclock | main/src/main/aidl/com/google/android/apps/dashclock/api/IDashClockDataProvider.aidl | AIDL | asf20 | 899 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dashclock.exampleextension;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.text.TextUtils;
import android.view.MenuItem;
public class ExampleSettingsActivity extends PreferenceActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setIcon(R.drawable.ic_extension_example);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setupSimplePreferencesScreen();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
// TODO: if the previous activity on the stack isn't a ConfigurationActivity,
// launch it.
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupSimplePreferencesScreen() {
// In the simplified UI, fragments are not used at all and we instead
// use the older PreferenceActivity APIs.
// Add 'general' preferences.
addPreferencesFromResource(R.xml.pref_example);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences to
// their values. When their values change, their summaries are updated
// to reflect the new value, per the Android Design guidelines.
bindPreferenceSummaryToValue(findPreference(ExampleExtension.PREF_NAME));
}
/**
* A preference value change listener that updates the preference's summary to reflect its new
* value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener
= new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
//preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Binds a preference's summary to its value. More specifically, when the preference's value is
* changed, its summary (line of text below the preference title) is updated to reflect the
* value. The summary is also immediately updated upon calling this method. The exact display
* format is dependent on the type of preference.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
}
| zywhlc-dashclock | example-extension/src/main/java/com/example/dashclock/exampleextension/ExampleSettingsActivity.java | Java | asf20 | 5,779 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dashclock.exampleextension;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
public class ExampleExtension extends DashClockExtension {
private static final String TAG = "ExampleExtension";
public static final String PREF_NAME = "pref_name";
@Override
protected void onUpdateData(int reason) {
// Get preference value.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString(PREF_NAME, getString(R.string.pref_name_default));
// Publish the extension data update.
publishUpdate(new ExtensionData()
.visible(true)
.icon(R.drawable.ic_extension_example)
.status("Hello")
.expandedTitle("Hello, " + name + "!")
.expandedBody("Thanks for checking out this example extension for DashClock.")
.contentDescription("Completely different text for accessibility if needed.")
.clickIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"))));
}
}
| zywhlc-dashclock | example-extension/src/main/java/com/example/dashclock/exampleextension/ExampleExtension.java | Java | asf20 | 1,911 |
// Helper program to generate a new secret for use in two-factor
// authentication.
//
// Copyright 2010 Google Inc.
// Author: Markus Gutschke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <getopt.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "base32.h"
#include "hmac.h"
#include "sha1.h"
#define SECRET "/.google_authenticator"
#define SECRET_BITS 80 // Must be divisible by eight
#define VERIFICATION_CODE_MODULUS (1000*1000) // Six digits
#define SCRATCHCODES 5 // Number of initial scratchcodes
#define SCRATCHCODE_LENGTH 8 // Eight digits per scratchcode
#define BYTES_PER_SCRATCHCODE 4 // 32bit of randomness is enough
#define BITS_PER_BASE32_CHAR 5 // Base32 expands space by 8/5
static enum { QR_UNSET=0, QR_NONE, QR_ANSI, QR_UTF8 } qr_mode = QR_UNSET;
static int generateCode(const char *key, unsigned long tm) {
uint8_t challenge[8];
for (int i = 8; i--; tm >>= 8) {
challenge[i] = tm;
}
// Estimated number of bytes needed to represent the decoded secret. Because
// of white-space and separators, this is an upper bound of the real number,
// which we later get as a return-value from base32_decode()
int secretLen = (strlen(key) + 7)/8*BITS_PER_BASE32_CHAR;
// Sanity check, that our secret will fixed into a reasonably-sized static
// array.
if (secretLen <= 0 || secretLen > 100) {
return -1;
}
// Decode secret from Base32 to a binary representation, and check that we
// have at least one byte's worth of secret data.
uint8_t secret[100];
if ((secretLen = base32_decode((const uint8_t *)key, secret, secretLen))<1) {
return -1;
}
// Compute the HMAC_SHA1 of the secrete and the challenge.
uint8_t hash[SHA1_DIGEST_LENGTH];
hmac_sha1(secret, secretLen, challenge, 8, hash, SHA1_DIGEST_LENGTH);
// Pick the offset where to sample our hash value for the actual verification
// code.
int offset = hash[SHA1_DIGEST_LENGTH - 1] & 0xF;
// Compute the truncated hash in a byte-order independent loop.
unsigned int truncatedHash = 0;
for (int i = 0; i < 4; ++i) {
truncatedHash <<= 8;
truncatedHash |= hash[offset + i];
}
// Truncate to a smaller number of digits.
truncatedHash &= 0x7FFFFFFF;
truncatedHash %= VERIFICATION_CODE_MODULUS;
return truncatedHash;
}
static const char *getUserName(uid_t uid) {
struct passwd pwbuf, *pw;
char *buf;
#ifdef _SC_GETPW_R_SIZE_MAX
int len = sysconf(_SC_GETPW_R_SIZE_MAX);
if (len <= 0) {
len = 4096;
}
#else
int len = 4096;
#endif
buf = malloc(len);
char *user;
if (getpwuid_r(uid, &pwbuf, buf, len, &pw) || !pw) {
user = malloc(32);
snprintf(user, 32, "%d", uid);
} else {
user = strdup(pw->pw_name);
if (!user) {
perror("malloc()");
_exit(1);
}
}
free(buf);
return user;
}
static const char *urlEncode(const char *s) {
char *ret = malloc(3*strlen(s) + 1);
char *d = ret;
do {
switch (*s) {
case '%':
case '&':
case '?':
case '=':
encode:
sprintf(d, "%%%02X", (unsigned char)*s);
d += 3;
break;
default:
if ((*s && *s <= ' ') || *s >= '\x7F') {
goto encode;
}
*d++ = *s;
break;
}
} while (*s++);
ret = realloc(ret, strlen(ret) + 1);
return ret;
}
static const char *getURL(const char *secret, const char *label,
char **encoderURL, const int use_totp) {
const char *encodedLabel = urlEncode(label);
char *url = malloc(strlen(encodedLabel) + strlen(secret) + 80);
char totp = 'h';
if (use_totp) {
totp = 't';
}
sprintf(url, "otpauth://%cotp/%s?secret=%s", totp, encodedLabel, secret);
if (encoderURL) {
const char *encoder = "https://www.google.com/chart?chs=200x200&"
"chld=M|0&cht=qr&chl=";
const char *encodedURL = urlEncode(url);
*encoderURL = strcat(strcpy(malloc(strlen(encoder) +
strlen(encodedURL) + 1),
encoder), encodedURL);
free((void *)encodedURL);
}
free((void *)encodedLabel);
return url;
}
#define ANSI_RESET "\x1B[0m"
#define ANSI_BLACKONGREY "\x1B[30;47;27m"
#define ANSI_WHITE "\x1B[27m"
#define ANSI_BLACK "\x1B[7m"
#define UTF8_BOTH "\xE2\x96\x88"
#define UTF8_TOPHALF "\xE2\x96\x80"
#define UTF8_BOTTOMHALF "\xE2\x96\x84"
static void displayQRCode(const char *secret, const char *label,
const int use_totp) {
if (qr_mode == QR_NONE) {
return;
}
char *encoderURL;
const char *url = getURL(secret, label, &encoderURL, use_totp);
puts(encoderURL);
// Only newer systems have support for libqrencode. So, instead of requiring
// it at build-time, we look for it at run-time. If it cannot be found, the
// user can still type the code in manually, or he can copy the URL into
// his browser.
if (isatty(1)) {
void *qrencode = dlopen("libqrencode.so.2", RTLD_NOW | RTLD_LOCAL);
if (!qrencode) {
qrencode = dlopen("libqrencode.so.3", RTLD_NOW | RTLD_LOCAL);
}
if (qrencode) {
typedef struct {
int version;
int width;
unsigned char *data;
} QRcode;
QRcode *(*QRcode_encodeString8bit)(const char *, int, int) =
(QRcode *(*)(const char *, int, int))
dlsym(qrencode, "QRcode_encodeString8bit");
void (*QRcode_free)(QRcode *qrcode) =
(void (*)(QRcode *))dlsym(qrencode, "QRcode_free");
if (QRcode_encodeString8bit && QRcode_free) {
QRcode *qrcode = QRcode_encodeString8bit(url, 0, 1);
char *ptr = (char *)qrcode->data;
// Output QRCode using ANSI colors. Instead of black on white, we
// output black on grey, as that works independently of whether the
// user runs his terminals in a black on white or white on black color
// scheme.
// But this requires that we print a border around the entire QR Code.
// Otherwise, readers won't be able to recognize it.
if (qr_mode != QR_UTF8) {
for (int i = 0; i < 2; ++i) {
printf(ANSI_BLACKONGREY);
for (int x = 0; x < qrcode->width + 4; ++x) printf(" ");
puts(ANSI_RESET);
}
for (int y = 0; y < qrcode->width; ++y) {
printf(ANSI_BLACKONGREY" ");
int isBlack = 0;
for (int x = 0; x < qrcode->width; ++x) {
if (*ptr++ & 1) {
if (!isBlack) {
printf(ANSI_BLACK);
}
isBlack = 1;
} else {
if (isBlack) {
printf(ANSI_WHITE);
}
isBlack = 0;
}
printf(" ");
}
if (isBlack) {
printf(ANSI_WHITE);
}
puts(" "ANSI_RESET);
}
for (int i = 0; i < 2; ++i) {
printf(ANSI_BLACKONGREY);
for (int x = 0; x < qrcode->width + 4; ++x) printf(" ");
puts(ANSI_RESET);
}
} else {
// Drawing the QRCode with Unicode block elements is desirable as
// it makes the code much smaller, which is often easier to scan.
// Unfortunately, many terminal emulators do not display these
// Unicode characters properly.
printf(ANSI_BLACKONGREY);
for (int i = 0; i < qrcode->width + 4; ++i) {
printf(" ");
}
puts(ANSI_RESET);
for (int y = 0; y < qrcode->width; y += 2) {
printf(ANSI_BLACKONGREY" ");
for (int x = 0; x < qrcode->width; ++x) {
int top = qrcode->data[y*qrcode->width + x] & 1;
int bottom = 0;
if (y+1 < qrcode->width) {
bottom = qrcode->data[(y+1)*qrcode->width + x] & 1;
}
if (top) {
if (bottom) {
printf(UTF8_BOTH);
} else {
printf(UTF8_TOPHALF);
}
} else {
if (bottom) {
printf(UTF8_BOTTOMHALF);
} else {
printf(" ");
}
}
}
puts(" "ANSI_RESET);
}
printf(ANSI_BLACKONGREY);
for (int i = 0; i < qrcode->width + 4; ++i) {
printf(" ");
}
puts(ANSI_RESET);
}
QRcode_free(qrcode);
}
dlclose(qrencode);
}
}
free((char *)url);
free(encoderURL);
}
static int maybe(const char *msg) {
printf("\n%s (y/n) ", msg);
fflush(stdout);
char ch;
do {
ch = getchar();
} while (ch == ' ' || ch == '\r' || ch == '\n');
if (ch == 'y' || ch == 'Y') {
return 1;
}
return 0;
}
static char *addOption(char *buf, size_t nbuf, const char *option) {
assert(strlen(buf) + strlen(option) < nbuf);
char *scratchCodes = strchr(buf, '\n');
assert(scratchCodes);
scratchCodes++;
memmove(scratchCodes + strlen(option), scratchCodes,
strlen(scratchCodes) + 1);
memcpy(scratchCodes, option, strlen(option));
return buf;
}
static char *maybeAddOption(const char *msg, char *buf, size_t nbuf,
const char *option) {
if (maybe(msg)) {
buf = addOption(buf, nbuf, option);
}
return buf;
}
static void usage(void) {
puts(
"google-authenticator [<options>]\n"
" -h, --help Print this message\n"
" -c, --counter-based Set up counter-based (HOTP) verification\n"
" -t, --time-based Set up time-based (TOTP) verification\n"
" -d, --disallow-reuse Disallow reuse of previously used TOTP tokens\n"
" -D, --allow-reuse Allow reuse of previously used TOTP tokens\n"
" -f, --force Write file without first confirming with user\n"
" -l, --label=<label> Override the default label in \"otpauth://\" URL\n"
" -q, --quiet Quiet mode\n"
" -Q, --qr-mode={NONE,ANSI,UTF8}\n"
" -r, --rate-limit=N Limit logins to N per every M seconds\n"
" -R, --rate-time=M Limit logins to N per every M seconds\n"
" -u, --no-rate-limit Disable rate-limiting\n"
" -s, --secret=<file> Specify a non-standard file location\n"
" -w, --window-size=W Set window of concurrently valid codes\n"
" -W, --minimal-window Disable window of concurrently valid codes");
}
int main(int argc, char *argv[]) {
uint8_t buf[SECRET_BITS/8 + SCRATCHCODES*BYTES_PER_SCRATCHCODE];
static const char hotp[] = "\" HOTP_COUNTER 1\n";
static const char totp[] = "\" TOTP_AUTH\n";
static const char disallow[] = "\" DISALLOW_REUSE\n";
static const char window[] = "\" WINDOW_SIZE 17\n";
static const char ratelimit[] = "\" RATE_LIMIT 3 30\n";
char secret[(SECRET_BITS + BITS_PER_BASE32_CHAR-1)/BITS_PER_BASE32_CHAR +
1 /* newline */ +
sizeof(hotp) + // hotp and totp are mutually exclusive.
sizeof(disallow) +
sizeof(window) +
sizeof(ratelimit) + 5 + // NN MMM (total of five digits)
SCRATCHCODE_LENGTH*(SCRATCHCODES + 1 /* newline */) +
1 /* NUL termination character */];
enum { ASK_MODE, HOTP_MODE, TOTP_MODE } mode = ASK_MODE;
enum { ASK_REUSE, DISALLOW_REUSE, ALLOW_REUSE } reuse = ASK_REUSE;
int force = 0, quiet = 0;
int r_limit = 0, r_time = 0;
char *secret_fn = NULL;
char *label = NULL;
int window_size = 0;
int idx;
for (;;) {
static const char optstring[] = "+hctdDfl:qQ:r:R:us:w:W";
static struct option options[] = {
{ "help", 0, 0, 'h' },
{ "counter-based", 0, 0, 'c' },
{ "time-based", 0, 0, 't' },
{ "disallow-reuse", 0, 0, 'd' },
{ "allow-reuse", 0, 0, 'D' },
{ "force", 0, 0, 'f' },
{ "label", 1, 0, 'l' },
{ "quiet", 0, 0, 'q' },
{ "qr-mode", 1, 0, 'Q' },
{ "rate-limit", 1, 0, 'r' },
{ "rate-time", 1, 0, 'R' },
{ "no-rate-limit", 0, 0, 'u' },
{ "secret", 1, 0, 's' },
{ "window-size", 1, 0, 'w' },
{ "minimal-window", 0, 0, 'W' },
{ 0, 0, 0, 0 }
};
idx = -1;
int c = getopt_long(argc, argv, optstring, options, &idx);
if (c > 0) {
for (int i = 0; options[i].name; i++) {
if (options[i].val == c) {
idx = i;
break;
}
}
} else if (c < 0) {
break;
}
if (idx-- <= 0) {
// Help (or invalid argument)
err:
usage();
if (idx < -1) {
fprintf(stderr, "Failed to parse command line\n");
_exit(1);
}
exit(0);
} else if (!idx--) {
// counter-based
if (mode != ASK_MODE) {
fprintf(stderr, "Duplicate -c and/or -t option detected\n");
_exit(1);
}
if (reuse != ASK_REUSE) {
reuse_err:
fprintf(stderr, "Reuse of tokens is not a meaningful parameter "
"when in counter-based mode\n");
_exit(1);
}
mode = HOTP_MODE;
} else if (!idx--) {
// time-based
if (mode != ASK_MODE) {
fprintf(stderr, "Duplicate -c and/or -t option detected\n");
_exit(1);
}
mode = TOTP_MODE;
} else if (!idx--) {
// disallow-reuse
if (reuse != ASK_REUSE) {
fprintf(stderr, "Duplicate -d and/or -D option detected\n");
_exit(1);
}
if (mode == HOTP_MODE) {
goto reuse_err;
}
reuse = DISALLOW_REUSE;
} else if (!idx--) {
// allow-reuse
if (reuse != ASK_REUSE) {
fprintf(stderr, "Duplicate -d and/or -D option detected\n");
_exit(1);
}
if (mode == HOTP_MODE) {
goto reuse_err;
}
reuse = ALLOW_REUSE;
} else if (!idx--) {
// force
if (force) {
fprintf(stderr, "Duplicate -f option detected\n");
_exit(1);
}
force = 1;
} else if (!idx--) {
// label
if (label) {
fprintf(stderr, "Duplicate -l option detected\n");
_exit(1);
}
label = strdup(optarg);
} else if (!idx--) {
// quiet
if (quiet) {
fprintf(stderr, "Duplicate -q option detected\n");
_exit(1);
}
quiet = 1;
} else if (!idx--) {
// qr-mode
if (qr_mode != QR_UNSET) {
fprintf(stderr, "Duplicate -Q option detected\n");
_exit(1);
}
if (!strcasecmp(optarg, "none")) {
qr_mode = QR_NONE;
} else if (!strcasecmp(optarg, "ansi")) {
qr_mode = QR_ANSI;
} else if (!strcasecmp(optarg, "utf8")) {
qr_mode = QR_UTF8;
} else {
fprintf(stderr, "Invalid qr-mode \"%s\"\n", optarg);
_exit(1);
}
} else if (!idx--) {
// rate-limit
if (r_limit > 0) {
fprintf(stderr, "Duplicate -r option detected\n");
_exit(1);
} else if (r_limit < 0) {
fprintf(stderr, "-u is mutually exclusive with -r\n");
_exit(1);
}
char *endptr;
errno = 0;
long l = strtol(optarg, &endptr, 10);
if (errno || endptr == optarg || *endptr || l < 1 || l > 10) {
fprintf(stderr, "-r requires an argument in the range 1..10\n");
_exit(1);
}
r_limit = (int)l;
} else if (!idx--) {
// rate-time
if (r_time > 0) {
fprintf(stderr, "Duplicate -R option detected\n");
_exit(1);
} else if (r_time < 0) {
fprintf(stderr, "-u is mutually exclusive with -R\n");
_exit(1);
}
char *endptr;
errno = 0;
long l = strtol(optarg, &endptr, 10);
if (errno || endptr == optarg || *endptr || l < 15 || l > 600) {
fprintf(stderr, "-R requires an argument in the range 15..600\n");
_exit(1);
}
r_time = (int)l;
} else if (!idx--) {
// no-rate-limit
if (r_limit > 0 || r_time > 0) {
fprintf(stderr, "-u is mutually exclusive with -r/-R\n");
_exit(1);
}
if (r_limit < 0) {
fprintf(stderr, "Duplicate -u option detected\n");
_exit(1);
}
r_limit = r_time = -1;
} else if (!idx--) {
// secret
if (secret_fn) {
fprintf(stderr, "Duplicate -s option detected\n");
_exit(1);
}
if (!*optarg) {
fprintf(stderr, "-s must be followed by a filename\n");
_exit(1);
}
secret_fn = strdup(optarg);
if (!secret_fn) {
perror("malloc()");
_exit(1);
}
} else if (!idx--) {
// window-size
if (window_size) {
fprintf(stderr, "Duplicate -w/-W option detected\n");
_exit(1);
}
char *endptr;
errno = 0;
long l = strtol(optarg, &endptr, 10);
if (errno || endptr == optarg || *endptr || l < 1 || l > 21) {
fprintf(stderr, "-w requires an argument in the range 1..21\n");
_exit(1);
}
window_size = (int)l;
} else if (!idx--) {
// minimal-window
if (window_size) {
fprintf(stderr, "Duplicate -w/-W option detected\n");
_exit(1);
}
window_size = -1;
} else {
fprintf(stderr, "Error\n");
_exit(1);
}
}
idx = -1;
if (optind != argc) {
goto err;
}
if (reuse != ASK_REUSE && mode != TOTP_MODE) {
fprintf(stderr, "Must select time-based mode, when using -d or -D\n");
_exit(1);
}
if ((r_time && !r_limit) || (!r_time && r_limit)) {
fprintf(stderr, "Must set -r when setting -R, and vice versa\n");
_exit(1);
}
if (!label) {
uid_t uid = getuid();
const char *user = getUserName(uid);
char hostname[128] = { 0 };
if (gethostname(hostname, sizeof(hostname)-1)) {
strcpy(hostname, "unix");
}
label = strcat(strcat(strcpy(malloc(strlen(user) + strlen(hostname) + 2),
user), "@"), hostname);
free((char *)user);
}
int fd = open("/dev/urandom", O_RDONLY);
if (fd < 0) {
perror("Failed to open \"/dev/urandom\"");
return 1;
}
if (read(fd, buf, sizeof(buf)) != sizeof(buf)) {
urandom_failure:
perror("Failed to read from \"/dev/urandom\"");
return 1;
}
base32_encode(buf, SECRET_BITS/8, (uint8_t *)secret, sizeof(secret));
int use_totp;
if (mode == ASK_MODE) {
use_totp = maybe("Do you want authentication tokens to be time-based");
} else {
use_totp = mode == TOTP_MODE;
}
if (!quiet) {
displayQRCode(secret, label, use_totp);
printf("Your new secret key is: %s\n", secret);
printf("Your verification code is %06d\n", generateCode(secret, 0));
printf("Your emergency scratch codes are:\n");
}
free(label);
strcat(secret, "\n");
if (use_totp) {
strcat(secret, totp);
} else {
strcat(secret, hotp);
}
for (int i = 0; i < SCRATCHCODES; ++i) {
new_scratch_code:;
int scratch = 0;
for (int j = 0; j < BYTES_PER_SCRATCHCODE; ++j) {
scratch = 256*scratch + buf[SECRET_BITS/8 + BYTES_PER_SCRATCHCODE*i + j];
}
int modulus = 1;
for (int j = 0; j < SCRATCHCODE_LENGTH; j++) {
modulus *= 10;
}
scratch = (scratch & 0x7FFFFFFF) % modulus;
if (scratch < modulus/10) {
// Make sure that scratch codes are always exactly eight digits. If they
// start with a sequence of zeros, just generate a new scratch code.
if (read(fd, buf + (SECRET_BITS/8 + BYTES_PER_SCRATCHCODE*i),
BYTES_PER_SCRATCHCODE) != BYTES_PER_SCRATCHCODE) {
goto urandom_failure;
}
goto new_scratch_code;
}
if (!quiet) {
printf(" %08d\n", scratch);
}
snprintf(strrchr(secret, '\000'), sizeof(secret) - strlen(secret),
"%08d\n", scratch);
}
close(fd);
if (!secret_fn) {
char *home = getenv("HOME");
if (!home || *home != '/') {
fprintf(stderr, "Cannot determine home directory\n");
return 1;
}
secret_fn = malloc(strlen(home) + strlen(SECRET) + 1);
if (!secret_fn) {
perror("malloc()");
_exit(1);
}
strcat(strcpy(secret_fn, home), SECRET);
}
if (!force) {
printf("\nDo you want me to update your \"%s\" file (y/n) ", secret_fn);
fflush(stdout);
char ch;
do {
ch = getchar();
} while (ch == ' ' || ch == '\r' || ch == '\n');
if (ch != 'y' && ch != 'Y') {
exit(0);
}
}
secret_fn = realloc(secret_fn, 2*strlen(secret_fn) + 3);
if (!secret_fn) {
perror("malloc()");
_exit(1);
}
char *tmp_fn = strrchr(secret_fn, '\000') + 1;
strcat(strcpy(tmp_fn, secret_fn), "~");
// Add optional flags.
if (use_totp) {
if (reuse == ASK_REUSE) {
maybeAddOption("Do you want to disallow multiple uses of the same "
"authentication\ntoken? This restricts you to one login "
"about every 30s, but it increases\nyour chances to "
"notice or even prevent man-in-the-middle attacks",
secret, sizeof(secret), disallow);
} else if (reuse == DISALLOW_REUSE) {
addOption(secret, sizeof(secret), disallow);
}
if (!window_size) {
maybeAddOption("By default, tokens are good for 30 seconds and in order "
"to compensate for\npossible time-skew between the "
"client and the server, we allow an extra\ntoken before "
"and after the current time. If you experience problems "
"with poor\ntime synchronization, you can increase the "
"window from its default\nsize of 1:30min to about 4min. "
"Do you want to do so",
secret, sizeof(secret), window);
} else {
char buf[80];
sprintf(buf, "\" WINDOW_SIZE %d\n", window_size);
addOption(secret, sizeof(secret), buf);
}
} else {
if (!window_size) {
maybeAddOption("By default, three tokens are valid at any one time. "
"This accounts for\ngenerated-but-not-used tokens and "
"failed login attempts. In order to\ndecrease the "
"likelihood of synchronization problems, this window "
"can be\nincreased from its default size of 3 to 17. Do "
"you want to do so",
secret, sizeof(secret), window);
} else {
char buf[80];
sprintf(buf, "\" WINDOW_SIZE %d\n",
window_size > 0 ? window_size : use_totp ? 3 : 1);
addOption(secret, sizeof(secret), buf);
}
}
if (!r_limit && !r_time) {
maybeAddOption("If the computer that you are logging into isn't hardened "
"against brute-force\nlogin attempts, you can enable "
"rate-limiting for the authentication module.\nBy default, "
"this limits attackers to no more than 3 login attempts "
"every 30s.\nDo you want to enable rate-limiting",
secret, sizeof(secret), ratelimit);
} else if (r_limit > 0 && r_time > 0) {
char buf[80];
sprintf(buf, "\"RATE_LIMIT %d %d\n", r_limit, r_time);
addOption(secret, sizeof(secret), buf);
}
fd = open(tmp_fn, O_WRONLY|O_EXCL|O_CREAT|O_NOFOLLOW|O_TRUNC, 0400);
if (fd < 0) {
fprintf(stderr, "Failed to create \"%s\" (%s)",
secret_fn, strerror(errno));
free(secret_fn);
return 1;
}
if (write(fd, secret, strlen(secret)) != (ssize_t)strlen(secret) ||
rename(tmp_fn, secret_fn)) {
perror("Failed to write new secret");
unlink(secret_fn);
close(fd);
free(secret_fn);
return 1;
}
free(secret_fn);
close(fd);
return 0;
}
| zy19820306-google-authenticator | libpam/google-authenticator.c | C | asf20 | 24,608 |
// Unittest for the PAM module. This is part of the Google Authenticator
// project.
//
// Copyright 2010 Google Inc.
// Author: Markus Gutschke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <assert.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <security/pam_appl.h>
#include <security/pam_modules.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "base32.h"
#include "hmac.h"
#if !defined(PAM_BAD_ITEM)
// FreeBSD does not know about PAM_BAD_ITEM. And PAM_SYMBOL_ERR is an "enum",
// we can't test for it at compile-time.
#define PAM_BAD_ITEM PAM_SYMBOL_ERR
#endif
static const char pw[] = "0123456789";
static char *response = "";
static void *pam_module;
static enum { TWO_PROMPTS, COMBINED_PASSWORD, COMBINED_PROMPT } conv_mode;
static int num_prompts_shown = 0;
static int conversation(int num_msg, const struct pam_message **msg,
struct pam_response **resp, void *appdata_ptr) {
// Keep track of how often the conversation callback is executed.
++num_prompts_shown;
if (conv_mode == COMBINED_PASSWORD) {
return PAM_CONV_ERR;
}
if (num_msg == 1 && msg[0]->msg_style == PAM_PROMPT_ECHO_OFF) {
*resp = malloc(sizeof(struct pam_response));
assert(*resp);
(*resp)->resp = conv_mode == TWO_PROMPTS
? strdup(response)
: strcat(strcpy(malloc(sizeof(pw) + strlen(response)), pw), response);
(*resp)->resp_retcode = 0;
return PAM_SUCCESS;
}
return PAM_CONV_ERR;
}
#ifdef sun
#define PAM_CONST
#else
#define PAM_CONST const
#endif
int pam_get_item(const pam_handle_t *pamh, int item_type,
PAM_CONST void **item)
__attribute__((visibility("default")));
int pam_get_item(const pam_handle_t *pamh, int item_type,
PAM_CONST void **item) {
switch (item_type) {
case PAM_SERVICE: {
static const char *service = "google_authenticator_unittest";
memcpy(item, &service, sizeof(&service));
return PAM_SUCCESS;
}
case PAM_USER: {
char *user = getenv("USER");
memcpy(item, &user, sizeof(&user));
return PAM_SUCCESS;
}
case PAM_CONV: {
static struct pam_conv conv = { .conv = conversation }, *p_conv = &conv;
memcpy(item, &p_conv, sizeof(p_conv));
return PAM_SUCCESS;
}
case PAM_AUTHTOK: {
static char *authtok = NULL;
if (conv_mode == COMBINED_PASSWORD) {
authtok = realloc(authtok, sizeof(pw) + strlen(response));
*item = strcat(strcpy(authtok, pw), response);
} else {
*item = pw;
}
return PAM_SUCCESS;
}
default:
return PAM_BAD_ITEM;
}
}
int pam_set_item(pam_handle_t *pamh, int item_type,
PAM_CONST void *item)
__attribute__((visibility("default")));
int pam_set_item(pam_handle_t *pamh, int item_type,
PAM_CONST void *item) {
switch (item_type) {
case PAM_AUTHTOK:
if (strcmp((char *)item, pw)) {
return PAM_BAD_ITEM;
}
return PAM_SUCCESS;
default:
return PAM_BAD_ITEM;
}
}
static const char *get_error_msg(void) {
const char *(*get_error_msg)(void) =
(const char *(*)(void))dlsym(pam_module, "get_error_msg");
return get_error_msg ? get_error_msg() : "";
}
static void print_diagnostics(int signo) {
if (*get_error_msg()) {
fprintf(stderr, "%s\n", get_error_msg());
}
_exit(1);
}
static void verify_prompts_shown(int expected_prompts_shown) {
assert(num_prompts_shown == expected_prompts_shown);
// Reset for the next count.
num_prompts_shown = 0;
}
int main(int argc, char *argv[]) {
// Testing Base32 encoding
puts("Testing base32 encoding");
static const uint8_t dat[] = "Hello world...";
uint8_t enc[((sizeof(dat) + 4)/5)*8 + 1];
assert(base32_encode(dat, sizeof(dat), enc, sizeof(enc)) == sizeof(enc)-1);
assert(!strcmp((char *)enc, "JBSWY3DPEB3W64TMMQXC4LQA"));
puts("Testing base32 decoding");
uint8_t dec[sizeof(dat)];
assert(base32_decode(enc, dec, sizeof(dec)) == sizeof(dec));
assert(!memcmp(dat, dec, sizeof(dat)));
// Testing HMAC_SHA1
puts("Testing HMAC_SHA1");
uint8_t hmac[20];
hmac_sha1((uint8_t *)"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C"
"\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19"
"\x1A\x1B\x1C\x1D\x1E\x1F !\"#$%&'()*+,-./0123456789:"
";<=>?", 64,
(uint8_t *)"Sample #1", 9,
hmac, sizeof(hmac));
assert(!memcmp(hmac,
(uint8_t []) { 0x4F, 0x4C, 0xA3, 0xD5, 0xD6, 0x8B, 0xA7, 0xCC,
0x0A, 0x12, 0x08, 0xC9, 0xC6, 0x1E, 0x9C, 0x5D,
0xA0, 0x40, 0x3C, 0x0A },
sizeof(hmac)));
hmac_sha1((uint8_t *)"0123456789:;<=>?@ABC", 20,
(uint8_t *)"Sample #2", 9,
hmac, sizeof(hmac));
assert(!memcmp(hmac,
(uint8_t []) { 0x09, 0x22, 0xD3, 0x40, 0x5F, 0xAA, 0x3D, 0x19,
0x4F, 0x82, 0xA4, 0x58, 0x30, 0x73, 0x7D, 0x5C,
0xC6, 0xC7, 0x5D, 0x24 },
sizeof(hmac)));
hmac_sha1((uint8_t *)"PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
"\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A"
"\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96"
"\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2"
"\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE"
"\xAF\xB0\xB1\xB2\xB3", 100,
(uint8_t *)"Sample #3", 9,
hmac, sizeof(hmac));
assert(!memcmp(hmac,
(uint8_t []) { 0xBC, 0xF4, 0x1E, 0xAB, 0x8B, 0xB2, 0xD8, 0x02,
0xF3, 0xD0, 0x5C, 0xAF, 0x7C, 0xB0, 0x92, 0xEC,
0xF8, 0xD1, 0xA3, 0xAA },
sizeof(hmac)));
hmac_sha1((uint8_t *)"pqrstuvwxyz{|}~\x7F\x80\x81\x82\x83\x84\x85\x86\x87"
"\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94"
"\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0", 49,
(uint8_t *)"Sample #4", 9,
hmac, sizeof(hmac));
assert(!memcmp(hmac,
(uint8_t []) { 0x9E, 0xA8, 0x86, 0xEF, 0xE2, 0x68, 0xDB, 0xEC,
0xCE, 0x42, 0x0C, 0x75, 0x24, 0xDF, 0x32, 0xE0,
0x75, 0x1A, 0x2A, 0x26 },
sizeof(hmac)));
// Load the PAM module
puts("Loading PAM module");
pam_module = dlopen("./pam_google_authenticator_testing.so",
RTLD_LAZY | RTLD_GLOBAL);
assert(pam_module != NULL);
signal(SIGABRT, print_diagnostics);
// Look up public symbols
int (*pam_sm_open_session)(pam_handle_t *, int, int, const char **) =
(int (*)(pam_handle_t *, int, int, const char **))
dlsym(pam_module, "pam_sm_open_session");
assert(pam_sm_open_session != NULL);
// Look up private test-only API
void (*set_time)(time_t t) =
(void (*)(time_t))dlsym(pam_module, "set_time");
assert(set_time);
int (*compute_code)(uint8_t *, int, unsigned long) =
(int (*)(uint8_t*, int, unsigned long))dlsym(pam_module, "compute_code");
assert(compute_code);
for (int otp_mode = 0; otp_mode < 8; ++otp_mode) {
// Create a secret file with a well-known test vector
char fn[] = "/tmp/.google_authenticator_XXXXXX";
int fd = mkstemp(fn);
assert(fd >= 0);
static const uint8_t secret[] = "2SH3V3GDW7ZNMGYE";
assert(write(fd, secret, sizeof(secret)-1) == sizeof(secret)-1);
assert(write(fd, "\n\" TOTP_AUTH", 12) == 12);
close(fd);
uint8_t binary_secret[sizeof(secret)];
size_t binary_secret_len = base32_decode(secret, binary_secret,
sizeof(binary_secret));
// Set up test argc/argv parameters to let the PAM module know where to
// find our secret file
const char *targv[] = { malloc(strlen(fn) + 8), NULL, NULL, NULL, NULL };
strcat(strcpy((char *)targv[0], "secret="), fn);
int targc;
int expected_good_prompts_shown;
int expected_bad_prompts_shown;
switch (otp_mode) {
case 0:
puts("\nRunning tests, querying for verification code");
conv_mode = TWO_PROMPTS;
targc = 1;
expected_good_prompts_shown = expected_bad_prompts_shown = 1;
break;
case 1:
puts("\nRunning tests, querying for verification code, "
"forwarding system pass");
conv_mode = COMBINED_PROMPT;
targv[1] = strdup("forward_pass");
targc = 2;
expected_good_prompts_shown = expected_bad_prompts_shown = 1;
break;
case 2:
puts("\nRunning tests with use_first_pass");
conv_mode = COMBINED_PASSWORD;
targv[1] = strdup("use_first_pass");
targc = 2;
expected_good_prompts_shown = expected_bad_prompts_shown = 0;
break;
case 3:
puts("\nRunning tests with use_first_pass, forwarding system pass");
conv_mode = COMBINED_PASSWORD;
targv[1] = strdup("use_first_pass");
targv[2] = strdup("forward_pass");
targc = 3;
expected_good_prompts_shown = expected_bad_prompts_shown = 0;
break;
case 4:
puts("\nRunning tests with try_first_pass, combining codes");
conv_mode = COMBINED_PASSWORD;
targv[1] = strdup("try_first_pass");
targc = 2;
expected_good_prompts_shown = 0;
expected_bad_prompts_shown = 2;
break;
case 5:
puts("\nRunning tests with try_first_pass, combining codes, "
"forwarding system pass");
conv_mode = COMBINED_PASSWORD;
targv[1] = strdup("try_first_pass");
targv[2] = strdup("forward_pass");
targc = 3;
expected_good_prompts_shown = 0;
expected_bad_prompts_shown = 2;
break;
case 6:
puts("\nRunning tests with try_first_pass, querying for codes");
conv_mode = TWO_PROMPTS;
targv[1] = strdup("try_first_pass");
targc = 2;
expected_good_prompts_shown = expected_bad_prompts_shown = 1;
break;
default:
assert(otp_mode == 7);
puts("\nRunning tests with try_first_pass, querying for codes, "
"forwarding system pass");
conv_mode = COMBINED_PROMPT;
targv[1] = strdup("try_first_pass");
targv[2] = strdup("forward_pass");
targc = 3;
expected_good_prompts_shown = expected_bad_prompts_shown = 1;
break;
}
// Make sure num_prompts_shown is still 0.
verify_prompts_shown(0);
// Set the timestamp that this test vector needs
set_time(10000*30);
response = "123456";
// Check if we can log in when using an invalid verification code
puts("Testing failed login attempt");
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR);
verify_prompts_shown(expected_bad_prompts_shown);
// Check required number of digits
if (conv_mode == TWO_PROMPTS) {
puts("Testing required number of digits");
response = "50548";
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR);
verify_prompts_shown(expected_bad_prompts_shown);
response = "0050548";
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR);
verify_prompts_shown(expected_bad_prompts_shown);
response = "00050548";
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR);
verify_prompts_shown(expected_bad_prompts_shown);
}
// Test a blank response
puts("Testing a blank response");
response = "";
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR);
verify_prompts_shown(expected_bad_prompts_shown);
// Set the response that we should send back to the authentication module
response = "050548";
// Test handling of missing state files
puts("Test handling of missing state files");
const char *old_secret = targv[0];
targv[0] = "secret=/NOSUCHFILE";
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR);
verify_prompts_shown(0);
targv[targc++] = "nullok";
targv[targc] = NULL;
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS);
verify_prompts_shown(0);
targv[--targc] = NULL;
targv[0] = old_secret;
// Check if we can log in when using a valid verification code
puts("Testing successful login");
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS);
verify_prompts_shown(expected_good_prompts_shown);
// Test the WINDOW_SIZE option
puts("Testing WINDOW_SIZE option");
for (int *tm = (int []){ 9998, 9999, 10001, 10002, 10000, -1 },
*res = (int []){ PAM_SESSION_ERR, PAM_SUCCESS, PAM_SUCCESS,
PAM_SESSION_ERR, PAM_SUCCESS };
*tm >= 0;) {
set_time(*tm++ * 30);
assert(pam_sm_open_session(NULL, 0, targc, targv) == *res++);
verify_prompts_shown(expected_good_prompts_shown);
}
assert(!chmod(fn, 0600));
assert((fd = open(fn, O_APPEND | O_WRONLY)) >= 0);
assert(write(fd, "\n\" WINDOW_SIZE 6\n", 17) == 17);
close(fd);
for (int *tm = (int []){ 9996, 9997, 10002, 10003, 10000, -1 },
*res = (int []){ PAM_SESSION_ERR, PAM_SUCCESS, PAM_SUCCESS,
PAM_SESSION_ERR, PAM_SUCCESS };
*tm >= 0;) {
set_time(*tm++ * 30);
assert(pam_sm_open_session(NULL, 0, targc, targv) == *res++);
verify_prompts_shown(expected_good_prompts_shown);
}
// Test the DISALLOW_REUSE option
puts("Testing DISALLOW_REUSE option");
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS);
verify_prompts_shown(expected_good_prompts_shown);
assert(!chmod(fn, 0600));
assert((fd = open(fn, O_APPEND | O_WRONLY)) >= 0);
assert(write(fd, "\" DISALLOW_REUSE\n", 17) == 17);
close(fd);
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS);
verify_prompts_shown(expected_good_prompts_shown);
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR);
verify_prompts_shown(expected_good_prompts_shown);
// Test that DISALLOW_REUSE expires old entries from the re-use list
char *old_response = response;
for (int i = 10001; i < 10008; ++i) {
set_time(i * 30);
char buf[7];
response = buf;
sprintf(response, "%06d", compute_code(binary_secret,
binary_secret_len, i));
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS);
verify_prompts_shown(expected_good_prompts_shown);
}
set_time(10000 * 30);
response = old_response;
assert((fd = open(fn, O_RDONLY)) >= 0);
char state_file_buf[4096] = { 0 };
assert(read(fd, state_file_buf, sizeof(state_file_buf)-1) > 0);
close(fd);
const char *disallow = strstr(state_file_buf, "\" DISALLOW_REUSE ");
assert(disallow);
assert(!memcmp(disallow + 17,
"10002 10003 10004 10005 10006 10007\n", 36));
// Test the RATE_LIMIT option
puts("Testing RATE_LIMIT option");
assert(!chmod(fn, 0600));
assert((fd = open(fn, O_APPEND | O_WRONLY)) >= 0);
assert(write(fd, "\" RATE_LIMIT 4 120\n", 19) == 19);
close(fd);
for (int *tm = (int []){ 20000, 20001, 20002, 20003, 20004, 20006, -1 },
*res = (int []){ PAM_SUCCESS, PAM_SUCCESS, PAM_SUCCESS,
PAM_SUCCESS, PAM_SESSION_ERR, PAM_SUCCESS, -1 };
*tm >= 0;) {
set_time(*tm * 30);
char buf[7];
response = buf;
sprintf(response, "%06d",
compute_code(binary_secret, binary_secret_len, *tm++));
assert(pam_sm_open_session(NULL, 0, targc, targv) == *res);
verify_prompts_shown(
*res != PAM_SUCCESS ? 0 : expected_good_prompts_shown);
++res;
}
set_time(10000 * 30);
response = old_response;
assert(!chmod(fn, 0600));
assert((fd = open(fn, O_RDWR)) >= 0);
memset(state_file_buf, 0, sizeof(state_file_buf));
assert(read(fd, state_file_buf, sizeof(state_file_buf)-1) > 0);
const char *rate_limit = strstr(state_file_buf, "\" RATE_LIMIT ");
assert(rate_limit);
assert(!memcmp(rate_limit + 13,
"4 120 600060 600090 600120 600180\n", 35));
// Test trailing space in RATE_LIMIT. This is considered a file format
// error.
char *eol = strchr(rate_limit, '\n');
*eol = ' ';
assert(!lseek(fd, 0, SEEK_SET));
assert(write(fd, state_file_buf, strlen(state_file_buf)) ==
strlen(state_file_buf));
close(fd);
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR);
verify_prompts_shown(0);
assert(!strncmp(get_error_msg(),
"Invalid list of timestamps in RATE_LIMIT", 40));
*eol = '\n';
assert(!chmod(fn, 0600));
assert((fd = open(fn, O_WRONLY)) >= 0);
assert(write(fd, state_file_buf, strlen(state_file_buf)) ==
strlen(state_file_buf));
close(fd);
// Test TIME_SKEW option
puts("Testing TIME_SKEW");
for (int i = 0; i < 4; ++i) {
set_time((12000 + i)*30);
char buf[7];
response = buf;
sprintf(response, "%06d",
compute_code(binary_secret, binary_secret_len, 11000 + i));
assert(pam_sm_open_session(NULL, 0, targc, targv) ==
(i >= 2 ? PAM_SUCCESS : PAM_SESSION_ERR));
verify_prompts_shown(expected_good_prompts_shown);
}
set_time(12010 * 30);
char buf[7];
response = buf;
sprintf(response, "%06d", compute_code(binary_secret,
binary_secret_len, 11010));
assert(pam_sm_open_session(NULL, 0, 1,
(const char *[]){ "noskewadj", 0 }) ==
PAM_SESSION_ERR);
verify_prompts_shown(0);
set_time(10000*30);
// Test scratch codes
puts("Testing scratch codes");
response = "12345678";
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR);
verify_prompts_shown(expected_bad_prompts_shown);
assert(!chmod(fn, 0600));
assert((fd = open(fn, O_APPEND | O_WRONLY)) >= 0);
assert(write(fd, "12345678\n", 9) == 9);
close(fd);
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS);
verify_prompts_shown(expected_good_prompts_shown);
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR);
verify_prompts_shown(expected_bad_prompts_shown);
// Set up secret file for counter-based codes.
assert(!chmod(fn, 0600));
assert((fd = open(fn, O_TRUNC | O_WRONLY)) >= 0);
assert(write(fd, secret, sizeof(secret)-1) == sizeof(secret)-1);
assert(write(fd, "\n\" HOTP_COUNTER 1\n", 18) == 18);
close(fd);
response = "293240";
// Check if we can log in when using a valid verification code
puts("Testing successful counter-based login");
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS);
verify_prompts_shown(expected_good_prompts_shown);
// Verify that the hotp counter incremented
assert((fd = open(fn, O_RDONLY)) >= 0);
memset(state_file_buf, 0, sizeof(state_file_buf));
assert(read(fd, state_file_buf, sizeof(state_file_buf)-1) > 0);
close(fd);
const char *hotp_counter = strstr(state_file_buf, "\" HOTP_COUNTER ");
assert(hotp_counter);
assert(!memcmp(hotp_counter + 15, "2\n", 2));
// Check if we can log in when using an invalid verification code
// (including the same code a second time)
puts("Testing failed counter-based login attempt");
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR);
verify_prompts_shown(expected_bad_prompts_shown);
// Verify that the hotp counter incremented
assert((fd = open(fn, O_RDONLY)) >= 0);
memset(state_file_buf, 0, sizeof(state_file_buf));
assert(read(fd, state_file_buf, sizeof(state_file_buf)-1) > 0);
close(fd);
hotp_counter = strstr(state_file_buf, "\" HOTP_COUNTER ");
assert(hotp_counter);
assert(!memcmp(hotp_counter + 15, "3\n", 2));
response = "932068";
// Check if we can log in using a future valid verification code (using
// default window_size of 3)
puts("Testing successful future counter-based login");
assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS);
verify_prompts_shown(expected_good_prompts_shown);
// Verify that the hotp counter incremented
assert((fd = open(fn, O_RDONLY)) >= 0);
memset(state_file_buf, 0, sizeof(state_file_buf));
assert(read(fd, state_file_buf, sizeof(state_file_buf)-1) > 0);
close(fd);
hotp_counter = strstr(state_file_buf, "\" HOTP_COUNTER ");
assert(hotp_counter);
assert(!memcmp(hotp_counter + 15, "6\n", 2));
// Remove the temporarily created secret file
unlink(fn);
// Release memory for the test arguments
for (int i = 0; i < targc; ++i) {
free((void *)targv[i]);
}
}
// Unload the PAM module
dlclose(pam_module);
puts("DONE");
return 0;
}
| zy19820306-google-authenticator | libpam/pam_google_authenticator_unittest.c | C | asf20 | 21,734 |
/*
* Copyright 2010 Google Inc.
* Author: Markus Gutschke
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* An earlier version of this file was originally released into the public
* domain by its authors. It has been modified to make the code compile and
* link as part of the Google Authenticator project. These changes are
* copyrighted by Google Inc. and released under the Apache License,
* Version 2.0.
*
* The previous authors' terms are included below:
*/
/*****************************************************************************
*
* File: sha1.c
*
* Purpose: Implementation of the SHA1 message-digest algorithm.
*
* NIST Secure Hash Algorithm
* Heavily modified by Uwe Hollerbach <uh@alumni.caltech edu>
* from Peter C. Gutmann's implementation as found in
* Applied Cryptography by Bruce Schneier
* Further modifications to include the "UNRAVEL" stuff, below
*
* This code is in the public domain
*
*****************************************************************************
*/
#define _BSD_SOURCE
#include <sys/types.h> // Defines BYTE_ORDER, iff _BSD_SOURCE is defined
#include <string.h>
#include "sha1.h"
#if !defined(BYTE_ORDER)
#if defined(_BIG_ENDIAN)
#define BYTE_ORDER 4321
#elif defined(_LITTLE_ENDIAN)
#define BYTE_ORDER 1234
#else
#error Need to define BYTE_ORDER
#endif
#endif
#ifndef TRUNC32
#define TRUNC32(x) ((x) & 0xffffffffL)
#endif
/* SHA f()-functions */
#define f1(x,y,z) ((x & y) | (~x & z))
#define f2(x,y,z) (x ^ y ^ z)
#define f3(x,y,z) ((x & y) | (x & z) | (y & z))
#define f4(x,y,z) (x ^ y ^ z)
/* SHA constants */
#define CONST1 0x5a827999L
#define CONST2 0x6ed9eba1L
#define CONST3 0x8f1bbcdcL
#define CONST4 0xca62c1d6L
/* truncate to 32 bits -- should be a null op on 32-bit machines */
#define T32(x) ((x) & 0xffffffffL)
/* 32-bit rotate */
#define R32(x,n) T32(((x << n) | (x >> (32 - n))))
/* the generic case, for when the overall rotation is not unraveled */
#define FG(n) \
T = T32(R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n); \
E = D; D = C; C = R32(B,30); B = A; A = T
/* specific cases, for when the overall rotation is unraveled */
#define FA(n) \
T = T32(R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n); B = R32(B,30)
#define FB(n) \
E = T32(R32(T,5) + f##n(A,B,C) + D + *WP++ + CONST##n); A = R32(A,30)
#define FC(n) \
D = T32(R32(E,5) + f##n(T,A,B) + C + *WP++ + CONST##n); T = R32(T,30)
#define FD(n) \
C = T32(R32(D,5) + f##n(E,T,A) + B + *WP++ + CONST##n); E = R32(E,30)
#define FE(n) \
B = T32(R32(C,5) + f##n(D,E,T) + A + *WP++ + CONST##n); D = R32(D,30)
#define FT(n) \
A = T32(R32(B,5) + f##n(C,D,E) + T + *WP++ + CONST##n); C = R32(C,30)
static void
sha1_transform(SHA1_INFO *sha1_info)
{
int i;
uint8_t *dp;
uint32_t T, A, B, C, D, E, W[80], *WP;
dp = sha1_info->data;
#undef SWAP_DONE
#if BYTE_ORDER == 1234
#define SWAP_DONE
for (i = 0; i < 16; ++i) {
T = *((uint32_t *) dp);
dp += 4;
W[i] =
((T << 24) & 0xff000000) |
((T << 8) & 0x00ff0000) |
((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff);
}
#endif
#if BYTE_ORDER == 4321
#define SWAP_DONE
for (i = 0; i < 16; ++i) {
T = *((uint32_t *) dp);
dp += 4;
W[i] = TRUNC32(T);
}
#endif
#if BYTE_ORDER == 12345678
#define SWAP_DONE
for (i = 0; i < 16; i += 2) {
T = *((uint32_t *) dp);
dp += 8;
W[i] = ((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) |
((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff);
T >>= 32;
W[i+1] = ((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) |
((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff);
}
#endif
#if BYTE_ORDER == 87654321
#define SWAP_DONE
for (i = 0; i < 16; i += 2) {
T = *((uint32_t *) dp);
dp += 8;
W[i] = TRUNC32(T >> 32);
W[i+1] = TRUNC32(T);
}
#endif
#ifndef SWAP_DONE
#define SWAP_DONE
for (i = 0; i < 16; ++i) {
T = *((uint32_t *) dp);
dp += 4;
W[i] = TRUNC32(T);
}
#endif /* SWAP_DONE */
for (i = 16; i < 80; ++i) {
W[i] = W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16];
W[i] = R32(W[i], 1);
}
A = sha1_info->digest[0];
B = sha1_info->digest[1];
C = sha1_info->digest[2];
D = sha1_info->digest[3];
E = sha1_info->digest[4];
WP = W;
#ifdef UNRAVEL
FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1); FC(1); FD(1);
FE(1); FT(1); FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1);
FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2); FE(2); FT(2);
FA(2); FB(2); FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2);
FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3); FA(3); FB(3);
FC(3); FD(3); FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3);
FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4); FC(4); FD(4);
FE(4); FT(4); FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4);
sha1_info->digest[0] = T32(sha1_info->digest[0] + E);
sha1_info->digest[1] = T32(sha1_info->digest[1] + T);
sha1_info->digest[2] = T32(sha1_info->digest[2] + A);
sha1_info->digest[3] = T32(sha1_info->digest[3] + B);
sha1_info->digest[4] = T32(sha1_info->digest[4] + C);
#else /* !UNRAVEL */
#ifdef UNROLL_LOOPS
FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1);
FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1);
FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2);
FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2);
FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3);
FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3);
FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4);
FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4);
#else /* !UNROLL_LOOPS */
for (i = 0; i < 20; ++i) { FG(1); }
for (i = 20; i < 40; ++i) { FG(2); }
for (i = 40; i < 60; ++i) { FG(3); }
for (i = 60; i < 80; ++i) { FG(4); }
#endif /* !UNROLL_LOOPS */
sha1_info->digest[0] = T32(sha1_info->digest[0] + A);
sha1_info->digest[1] = T32(sha1_info->digest[1] + B);
sha1_info->digest[2] = T32(sha1_info->digest[2] + C);
sha1_info->digest[3] = T32(sha1_info->digest[3] + D);
sha1_info->digest[4] = T32(sha1_info->digest[4] + E);
#endif /* !UNRAVEL */
}
/* initialize the SHA digest */
void
sha1_init(SHA1_INFO *sha1_info)
{
sha1_info->digest[0] = 0x67452301L;
sha1_info->digest[1] = 0xefcdab89L;
sha1_info->digest[2] = 0x98badcfeL;
sha1_info->digest[3] = 0x10325476L;
sha1_info->digest[4] = 0xc3d2e1f0L;
sha1_info->count_lo = 0L;
sha1_info->count_hi = 0L;
sha1_info->local = 0;
}
/* update the SHA digest */
void
sha1_update(SHA1_INFO *sha1_info, const uint8_t *buffer, int count)
{
int i;
uint32_t clo;
clo = T32(sha1_info->count_lo + ((uint32_t) count << 3));
if (clo < sha1_info->count_lo) {
++sha1_info->count_hi;
}
sha1_info->count_lo = clo;
sha1_info->count_hi += (uint32_t) count >> 29;
if (sha1_info->local) {
i = SHA1_BLOCKSIZE - sha1_info->local;
if (i > count) {
i = count;
}
memcpy(((uint8_t *) sha1_info->data) + sha1_info->local, buffer, i);
count -= i;
buffer += i;
sha1_info->local += i;
if (sha1_info->local == SHA1_BLOCKSIZE) {
sha1_transform(sha1_info);
} else {
return;
}
}
while (count >= SHA1_BLOCKSIZE) {
memcpy(sha1_info->data, buffer, SHA1_BLOCKSIZE);
buffer += SHA1_BLOCKSIZE;
count -= SHA1_BLOCKSIZE;
sha1_transform(sha1_info);
}
memcpy(sha1_info->data, buffer, count);
sha1_info->local = count;
}
static void
sha1_transform_and_copy(unsigned char digest[20], SHA1_INFO *sha1_info)
{
sha1_transform(sha1_info);
digest[ 0] = (unsigned char) ((sha1_info->digest[0] >> 24) & 0xff);
digest[ 1] = (unsigned char) ((sha1_info->digest[0] >> 16) & 0xff);
digest[ 2] = (unsigned char) ((sha1_info->digest[0] >> 8) & 0xff);
digest[ 3] = (unsigned char) ((sha1_info->digest[0] ) & 0xff);
digest[ 4] = (unsigned char) ((sha1_info->digest[1] >> 24) & 0xff);
digest[ 5] = (unsigned char) ((sha1_info->digest[1] >> 16) & 0xff);
digest[ 6] = (unsigned char) ((sha1_info->digest[1] >> 8) & 0xff);
digest[ 7] = (unsigned char) ((sha1_info->digest[1] ) & 0xff);
digest[ 8] = (unsigned char) ((sha1_info->digest[2] >> 24) & 0xff);
digest[ 9] = (unsigned char) ((sha1_info->digest[2] >> 16) & 0xff);
digest[10] = (unsigned char) ((sha1_info->digest[2] >> 8) & 0xff);
digest[11] = (unsigned char) ((sha1_info->digest[2] ) & 0xff);
digest[12] = (unsigned char) ((sha1_info->digest[3] >> 24) & 0xff);
digest[13] = (unsigned char) ((sha1_info->digest[3] >> 16) & 0xff);
digest[14] = (unsigned char) ((sha1_info->digest[3] >> 8) & 0xff);
digest[15] = (unsigned char) ((sha1_info->digest[3] ) & 0xff);
digest[16] = (unsigned char) ((sha1_info->digest[4] >> 24) & 0xff);
digest[17] = (unsigned char) ((sha1_info->digest[4] >> 16) & 0xff);
digest[18] = (unsigned char) ((sha1_info->digest[4] >> 8) & 0xff);
digest[19] = (unsigned char) ((sha1_info->digest[4] ) & 0xff);
}
/* finish computing the SHA digest */
void
sha1_final(SHA1_INFO *sha1_info, uint8_t digest[20])
{
int count;
uint32_t lo_bit_count, hi_bit_count;
lo_bit_count = sha1_info->count_lo;
hi_bit_count = sha1_info->count_hi;
count = (int) ((lo_bit_count >> 3) & 0x3f);
((uint8_t *) sha1_info->data)[count++] = 0x80;
if (count > SHA1_BLOCKSIZE - 8) {
memset(((uint8_t *) sha1_info->data) + count, 0, SHA1_BLOCKSIZE - count);
sha1_transform(sha1_info);
memset((uint8_t *) sha1_info->data, 0, SHA1_BLOCKSIZE - 8);
} else {
memset(((uint8_t *) sha1_info->data) + count, 0,
SHA1_BLOCKSIZE - 8 - count);
}
sha1_info->data[56] = (uint8_t)((hi_bit_count >> 24) & 0xff);
sha1_info->data[57] = (uint8_t)((hi_bit_count >> 16) & 0xff);
sha1_info->data[58] = (uint8_t)((hi_bit_count >> 8) & 0xff);
sha1_info->data[59] = (uint8_t)((hi_bit_count >> 0) & 0xff);
sha1_info->data[60] = (uint8_t)((lo_bit_count >> 24) & 0xff);
sha1_info->data[61] = (uint8_t)((lo_bit_count >> 16) & 0xff);
sha1_info->data[62] = (uint8_t)((lo_bit_count >> 8) & 0xff);
sha1_info->data[63] = (uint8_t)((lo_bit_count >> 0) & 0xff);
sha1_transform_and_copy(digest, sha1_info);
}
/***EOF***/
| zy19820306-google-authenticator | libpam/sha1.c | C | asf20 | 11,201 |