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 |
|---|---|---|---|---|---|
<?php
/**
* Smarty Internal Plugin Compile If
*
* Compiles the {if} {else} {elseif} {/if} tags
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile If Class
*/
class Smarty_Internal_Compile_If extends Smarty_Internal_CompileBase {
/**
* Compiles code for the {if} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
// check and get attributes
$_attr = $this->_get_attributes($args);
$this->_open_tag('if',array(1,$this->compiler->nocache));
// must whole block be nocache ?
$this->compiler->nocache = $this->compiler->nocache | $this->compiler->tag_nocache;
if (is_array($parameter['if condition'])) {
if ($this->compiler->nocache) {
$_nocache = ',true';
// create nocache var to make it know for further compiling
if (is_array($parameter['if condition']['var'])) {
$this->compiler->template->tpl_vars[trim($parameter['if condition']['var']['var'], "'")] = new Smarty_variable(null, true);
} else {
$this->compiler->template->tpl_vars[trim($parameter['if condition']['var'], "'")] = new Smarty_variable(null, true);
}
} else {
$_nocache = '';
}
if (is_array($parameter['if condition']['var'])) {
$_output = "<?php if (!isset(\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']['var']."]) || !is_array(\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']['var']."]->value)) \$_smarty_tpl->createLocalArrayVariable(".$parameter['if condition']['var']['var']."$_nocache2);\n";
$_output .= "if (\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']['var']."]->value".$parameter['if condition']['var']['smarty_internal_index']." = ".$parameter['if condition']['value']."){?>";
} else {
$_output = "<?php \$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']."] = new Smarty_Variable(\$_smarty_tpl->getVariable(".$parameter['if condition']['var'].",null,true,false)->value{$_nocache});";
$_output .= "if (\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']."]->value = ".$parameter['if condition']['value']."){?>";
}
return $_output;
} else {
return "<?php if ({$parameter['if condition']}){?>";
}
}
}
/**
* Smarty Internal Plugin Compile Else Class
*/
class Smarty_Internal_Compile_Else extends Smarty_Internal_CompileBase {
/**
* Compiles code for the {else} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
list($nesting, $compiler->tag_nocache) = $this->_close_tag(array('if', 'elseif'));
$this->_open_tag('else',array($nesting,$compiler->tag_nocache));
return "<?php }else{ ?>";
}
}
/**
* Smarty Internal Plugin Compile ElseIf Class
*/
class Smarty_Internal_Compile_Elseif extends Smarty_Internal_CompileBase {
/**
* Compiles code for the {elseif} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
// check and get attributes
$_attr = $this->_get_attributes($args);
list($nesting, $compiler->tag_nocache) = $this->_close_tag(array('if', 'elseif'));
if (is_array($parameter['if condition'])) {
$condition_by_assign = true;
if ($this->compiler->nocache) {
$_nocache = ',true';
// create nocache var to make it know for further compiling
if (is_array($parameter['if condition']['var'])) {
$this->compiler->template->tpl_vars[trim($parameter['if condition']['var']['var'], "'")] = new Smarty_variable(null, true);
} else {
$this->compiler->template->tpl_vars[trim($parameter['if condition']['var'], "'")] = new Smarty_variable(null, true);
}
} else {
$_nocache = '';
}
} else {
$condition_by_assign = false;
}
if (empty($this->compiler->prefix_code)) {
if ($condition_by_assign) {
$this->_open_tag('elseif', array($nesting + 1, $compiler->tag_nocache));
if (is_array($parameter['if condition']['var'])) {
$_output = "<?php }else{ if (!isset(\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']['var']."]) || !is_array(\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']['var']."]->value)) \$_smarty_tpl->createLocalArrayVariable(".$parameter['if condition']['var']['var']."$_nocache2);\n";
$_output .= "if (\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']['var']."]->value".$parameter['if condition']['var']['smarty_internal_index']." = ".$parameter['if condition']['value']."){?>";
} else {
$_output = "<?php }else{ \$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']."] = new Smarty_Variable(\$_smarty_tpl->getVariable(".$parameter['if condition']['var'].",null,true,false)->value{$_nocache});";
$_output .= "if (\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']."]->value = ".$parameter['if condition']['value']."){?>";
}
return $_output;
} else {
$this->_open_tag('elseif', array($nesting, $compiler->tag_nocache));
return "<?php }elseif({$parameter['if condition']}){?>";
}
} else {
$tmp = '';
foreach ($this->compiler->prefix_code as $code) $tmp .= $code;
$this->compiler->prefix_code = array();
$this->_open_tag('elseif', array($nesting + 1, $compiler->tag_nocache));
if ($condition_by_assign) {
if (is_array($parameter['if condition']['var'])) {
$_output = "<?php }else{?>{$tmp}<?php if (!isset(\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']['var']."]) || !is_array(\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']['var']."]->value)) \$_smarty_tpl->createLocalArrayVariable(".$parameter['if condition']['var']['var']."$_nocache2);\n";
$_output .= "if (\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']['var']."]->value".$parameter['if condition']['var']['smarty_internal_index']." = ".$parameter['if condition']['value']."){?>";
} else {
$_output = "<?php }else{?>{$tmp}<?php \$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']."] = new Smarty_Variable(\$_smarty_tpl->getVariable(".$parameter['if condition']['var'].",null,true,false)->value{$_nocache});";
$_output .= "if (\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']."]->value = ".$parameter['if condition']['value']."){?>";
}
return $_output;
} else {
return "<?php }else{?>{$tmp}<?php if ({$parameter['if condition']}){?>";
}
}
}
}
/**
* Smarty Internal Plugin Compile Ifclose Class
*/
class Smarty_Internal_Compile_Ifclose extends Smarty_Internal_CompileBase {
/**
* Compiles code for the {/if} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
// must endblock be nocache?
if ($this->compiler->nocache) {
$this->compiler->tag_nocache = true;
}
list($nesting, $this->compiler->nocache) = $this->_close_tag(array('if', 'else', 'elseif'));
$tmp = '';
for ($i = 0; $i < $nesting ; $i++) $tmp .= '}';
return "<?php {$tmp}?>";
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_compile_if.php | PHP | asf20 | 8,471 |
<?php
/**
* Smarty Internal Plugin Compile Registered Block
*
* Compiles code for the execution of a registered block function
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Registered Block Class
*/
class Smarty_Internal_Compile_Private_Registered_Block extends Smarty_Internal_CompileBase {
// attribute definitions
public $optional_attributes = array('_any');
/**
* Compiles code for the execution of a block function
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @param string $tag name of block function
* @return string compiled code
*/
public function compile($args, $compiler, $parameter, $tag)
{
$this->compiler = $compiler;
if (strlen($tag) < 6 || substr($tag,-5) != 'close') {
// opening tag of block plugin
// check and get attributes
$_attr = $this->_get_attributes($args);
if ($_attr['nocache']) {
$this->compiler->tag_nocache = true;
}
unset($_attr['nocache']);
// convert attributes into parameter array string
$_paramsArray = array();
foreach ($_attr as $_key => $_value) {
if (is_int($_key)) {
$_paramsArray[] = "$_key=>$_value";
} else {
$_paramsArray[] = "'$_key'=>$_value";
}
}
$_params = 'array(' . implode(",", $_paramsArray) . ')';
$this->_open_tag($tag, array($_params, $this->compiler->nocache));
// maybe nocache because of nocache variables or nocache plugin
$this->compiler->nocache = !$compiler->smarty->registered_plugins[Smarty::PLUGIN_BLOCK][$tag][1] | $this->compiler->nocache | $this->compiler->tag_nocache;
$function = $compiler->smarty->registered_plugins[Smarty::PLUGIN_BLOCK][$tag][0];
// compile code
if (!is_array($function)) {
$output = "<?php \$_smarty_tpl->smarty->_tag_stack[] = array('{$tag}', {$_params}); \$_block_repeat=true; {$function}({$_params}, null, \$_smarty_tpl, \$_block_repeat);while (\$_block_repeat) { ob_start();?>";
} else if (is_object($function[0])) {
$output = "<?php \$_smarty_tpl->smarty->_tag_stack[] = array('{$tag}', {$_params}); \$_block_repeat=true; \$_smarty_tpl->smarty->registered_plugins['block']['{$tag}'][0][0]->{$function[1]}({$_params}, null, \$_smarty_tpl, \$_block_repeat);while (\$_block_repeat) { ob_start();?>";
} else {
$output = "<?php \$_smarty_tpl->smarty->_tag_stack[] = array('{$tag}', {$_params}); \$_block_repeat=true; {$function[0]}::{$function[1]}({$_params}, null, \$_smarty_tpl, \$_block_repeat);while (\$_block_repeat) { ob_start();?>";
}
} else {
// must endblock be nocache?
if ($this->compiler->nocache) {
$this->compiler->tag_nocache = true;
}
$base_tag = substr($tag, 0, -5);
// closing tag of block plugin, restore nocache
list($_params, $this->compiler->nocache) = $this->_close_tag($base_tag);
// This tag does create output
$this->compiler->has_output = true;
$function = $compiler->smarty->registered_plugins[Smarty::PLUGIN_BLOCK][$base_tag][0];
// compile code
if (!isset($parameter['modifier_list'])) {
$mod_pre = $mod_post ='';
} else {
$mod_pre = ' ob_start(); ';
$mod_post = 'echo '.$this->compiler->compileTag('private_modifier',array(),array('modifierlist'=>$parameter['modifier_list'],'value'=>'ob_get_clean()')).';';
}
if (!is_array($function)) {
$output = "<?php \$_block_content = ob_get_clean(); \$_block_repeat=false;".$mod_pre." echo {$function}({$_params}, \$_block_content, \$_smarty_tpl, \$_block_repeat);".$mod_post." } array_pop(\$_smarty_tpl->smarty->_tag_stack);?>";
} else if (is_object($function[0])) {
$output = "<?php \$_block_content = ob_get_clean(); \$_block_repeat=false;".$mod_pre." echo \$_smarty_tpl->smarty->registered_plugins['block']['{$base_tag}'][0][0]->{$function[1]}({$_params}, \$_block_content, \$_smarty_tpl, \$_block_repeat); ".$mod_post."} array_pop(\$_smarty_tpl->smarty->_tag_stack);?>";
} else {
$output = "<?php \$_block_content = ob_get_clean(); \$_block_repeat=false;".$mod_pre." echo {$function[0]}::{$function[1]}({$_params}, \$_block_content, \$_smarty_tpl, \$_block_repeat); ".$mod_post."} array_pop(\$_smarty_tpl->smarty->_tag_stack);?>";
}
}
return $output."\n";
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_compile_private_registered_block.php | PHP | asf20 | 5,009 |
<?php
/**
* Smarty Internal Plugin Compile Foreach
*
* Compiles the {foreach} {foreachelse} {/foreach} tags
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Foreach Class
*/
class Smarty_Internal_Compile_Foreach extends Smarty_Internal_CompileBase {
// attribute definitions
public $required_attributes = array('from', 'item');
public $optional_attributes = array('name', 'key');
public $shorttag_order = array('from','item','key','name');
/**
* Compiles code for the {foreach} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
$tpl = $compiler->template;
// check and get attributes
$_attr = $this->_get_attributes($args);
$from = $_attr['from'];
$item = $_attr['item'];
if (substr_compare("\$_smarty_tpl->getVariable($item)", $from,0, strlen("\$_smarty_tpl->getVariable($item)")) == 0) {
$this->compiler->trigger_template_error("item variable {$item} may not be the same variable as at 'from'", $this->compiler->lex->taglineno);
}
if (isset($_attr['key'])) {
$key = $_attr['key'];
} else {
$key = null;
}
$this->_open_tag('foreach', array('foreach', $this->compiler->nocache, $item, $key));
// maybe nocache because of nocache variables
$this->compiler->nocache = $this->compiler->nocache | $this->compiler->tag_nocache;
if (isset($_attr['name'])) {
$name = $_attr['name'];
$has_name = true;
$SmartyVarName = '$smarty.foreach.' . trim($name, '\'"') . '.';
} else {
$name = null;
$has_name = false;
}
$ItemVarName = '$' . trim($item, '\'"') . '@';
// evaluates which Smarty variables and properties have to be computed
if ($has_name) {
$usesSmartyFirst = strpos($tpl->template_source, $SmartyVarName . 'first') !== false;
$usesSmartyLast = strpos($tpl->template_source, $SmartyVarName . 'last') !== false;
$usesSmartyIndex = strpos($tpl->template_source, $SmartyVarName . 'index') !== false;
$usesSmartyIteration = strpos($tpl->template_source, $SmartyVarName . 'iteration') !== false;
$usesSmartyShow = strpos($tpl->template_source, $SmartyVarName . 'show') !== false;
$usesSmartyTotal = strpos($tpl->template_source, $SmartyVarName . 'total') !== false;
} else {
$usesSmartyFirst = false;
$usesSmartyLast = false;
$usesSmartyTotal = false;
$usesSmartyShow = false;
}
$usesPropFirst = $usesSmartyFirst || strpos($tpl->template_source, $ItemVarName . 'first') !== false;
$usesPropLast = $usesSmartyLast || strpos($tpl->template_source, $ItemVarName . 'last') !== false;
$usesPropIndex = $usesPropFirst || strpos($tpl->template_source, $ItemVarName . 'index') !== false;
$usesPropIteration = $usesPropLast || strpos($tpl->template_source, $ItemVarName . 'iteration') !== false;
$usesPropShow = strpos($tpl->template_source, $ItemVarName . 'show') !== false;
$usesPropTotal = $usesSmartyTotal || $usesSmartyShow || $usesPropShow || $usesPropLast || strpos($tpl->template_source, $ItemVarName . 'total') !== false;
// generate output code
$output = "<?php ";
$output .= " \$_smarty_tpl->tpl_vars[$item] = new Smarty_Variable;\n";
$compiler->local_var[$item] = true;
if ($key != null) {
$output .= " \$_smarty_tpl->tpl_vars[$key] = new Smarty_Variable;\n";
$compiler->local_var[$key] = true;
}
$output .= " \$_from = $from; if (!is_array(\$_from) && !is_object(\$_from)) { settype(\$_from, 'array');}\n";
if ($usesPropTotal) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->total= \$_smarty_tpl->_count(\$_from);\n";
}
if ($usesPropIteration) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->iteration=0;\n";
}
if ($usesPropIndex) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->index=-1;\n";
}
if ($usesPropShow) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->show = (\$_smarty_tpl->tpl_vars[$item]->total > 0);\n";
}
if ($has_name) {
if ($usesSmartyTotal) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['total'] = \$_smarty_tpl->tpl_vars[$item]->total;\n";
}
if ($usesSmartyIteration) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['iteration']=0;\n";
}
if ($usesSmartyIndex) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['index']=-1;\n";
}
if ($usesSmartyShow) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['show']=(\$_smarty_tpl->tpl_vars[$item]->total > 0);\n";
}
}
if ($usesPropTotal) {
$output .= "if (\$_smarty_tpl->tpl_vars[$item]->total > 0){\n";
} else {
$output .= "if (\$_smarty_tpl->_count(\$_from) > 0){\n";
}
$output .= " foreach (\$_from as \$_smarty_tpl->tpl_vars[$item]->key => \$_smarty_tpl->tpl_vars[$item]->value){\n";
if ($key != null) {
$output .= " \$_smarty_tpl->tpl_vars[$key]->value = \$_smarty_tpl->tpl_vars[$item]->key;\n";
}
if ($usesPropIteration) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->iteration++;\n";
}
if ($usesPropIndex) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->index++;\n";
}
if ($usesPropFirst) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->first = \$_smarty_tpl->tpl_vars[$item]->index === 0;\n";
}
if ($usesPropLast) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->last = \$_smarty_tpl->tpl_vars[$item]->iteration === \$_smarty_tpl->tpl_vars[$item]->total;\n";
}
if ($has_name) {
if ($usesSmartyFirst) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['first'] = \$_smarty_tpl->tpl_vars[$item]->first;\n";
}
if ($usesSmartyIteration) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['iteration']++;\n";
}
if ($usesSmartyIndex) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['index']++;\n";
}
if ($usesSmartyLast) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['last'] = \$_smarty_tpl->tpl_vars[$item]->last;\n";
}
}
$output .= "?>";
return $output;
}
}
/**
* Smarty Internal Plugin Compile Foreachelse Class
*/
class Smarty_Internal_Compile_Foreachelse extends Smarty_Internal_CompileBase {
/**
* Compiles code for the {foreachelse} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
// check and get attributes
$_attr = $this->_get_attributes($args);
list($_open_tag, $nocache, $item, $key) = $this->_close_tag(array('foreach'));
$this->_open_tag('foreachelse', array('foreachelse', $nocache, $item, $key));
return "<?php }} else { ?>";
}
}
/**
* Smarty Internal Plugin Compile Foreachclose Class
*/
class Smarty_Internal_Compile_Foreachclose extends Smarty_Internal_CompileBase {
/**
* Compiles code for the {/foreach} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
// check and get attributes
$_attr = $this->_get_attributes($args);
// must endblock be nocache?
if ($this->compiler->nocache) {
$this->compiler->tag_nocache = true;
}
list($_open_tag, $this->compiler->nocache, $item, $key) = $this->_close_tag(array('foreach', 'foreachelse'));
unset($compiler->local_var[$item]);
if ($key != null) {
unset($compiler->local_var[$key]);
}
if ($_open_tag == 'foreachelse')
return "<?php } ?>";
else
return "<?php }} ?>";
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_compile_foreach.php | PHP | asf20 | 9,137 |
<?php
/**
* Smarty Internal Plugin Resource File
*
* Implements the file system as resource for Smarty templates
*
* @package Smarty
* @subpackage TemplateResources
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Resource File
*/
class Smarty_Internal_Resource_File {
public function __construct($smarty)
{
$this->smarty = $smarty;
}
// classes used for compiling Smarty templates from file resource
public $compiler_class = 'Smarty_Internal_SmartyTemplateCompiler';
public $template_lexer_class = 'Smarty_Internal_Templatelexer';
public $template_parser_class = 'Smarty_Internal_Templateparser';
// properties
public $usesCompiler = true;
public $isEvaluated = false;
/**
* Return flag if template source is existing
*
* @return boolean true
*/
public function isExisting($template)
{
if ($template->getTemplateFilepath() === false) {
return false;
} else {
return true;
}
}
/**
* Get filepath to template source
*
* @param object $_template template object
* @return string filepath to template source file
*/
public function getTemplateFilepath($_template)
{
$_filepath = $_template->buildTemplateFilepath ();
if ($_filepath !== false) {
if (is_object($_template->smarty->security_policy)) {
$_template->smarty->security_policy->isTrustedResourceDir($_filepath);
}
}
$_template->templateUid = sha1($_filepath);
return $_filepath;
}
/**
* Get timestamp to template source
*
* @param object $_template template object
* @return integer timestamp of template source file
*/
public function getTemplateTimestamp($_template)
{
return filemtime($_template->getTemplateFilepath());
}
/**
* Read template source from file
*
* @param object $_template template object
* @return string content of template source file
*/
public function getTemplateSource($_template)
{
// read template file
if (file_exists($_tfp = $_template->getTemplateFilepath())) {
$_template->template_source = file_get_contents($_tfp);
return true;
} else {
return false;
}
}
/**
* Get filepath to compiled template
*
* @param object $_template template object
* @return string return path to compiled template
*/
public function getCompiledFilepath($_template)
{
$_compile_id = isset($_template->compile_id) ? preg_replace('![^\w\|]+!', '_', $_template->compile_id) : null;
// calculate Uid if not already done
if ($_template->templateUid == '') {
$_template->getTemplateFilepath();
}
$_filepath = $_template->templateUid;
// if use_sub_dirs, break file into directories
if ($_template->smarty->use_sub_dirs) {
$_filepath = substr($_filepath, 0, 2) . DS
. substr($_filepath, 2, 2) . DS
. substr($_filepath, 4, 2) . DS
. $_filepath;
}
$_compile_dir_sep = $_template->smarty->use_sub_dirs ? DS : '^';
if (isset($_compile_id)) {
$_filepath = $_compile_id . $_compile_dir_sep . $_filepath;
}
if ($_template->caching) {
$_cache = '.cache';
} else {
$_cache = '';
}
$_compile_dir = $_template->smarty->compile_dir;
if (strpos('/\\', substr($_compile_dir, -1)) === false) {
$_compile_dir .= DS;
}
return $_compile_dir . $_filepath . '.' . $_template->resource_type . '.' . basename($_template->resource_name) . $_cache . '.php';
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_resource_file.php | PHP | asf20 | 3,852 |
<?php
/**
* Smarty Internal Plugin Resource PHP
*
* Implements the file system as resource for PHP templates
*
* @package Smarty
* @subpackage TemplateResources
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Resource PHP
*/
class Smarty_Internal_Resource_PHP {
/**
* Class constructor, enable short open tags
*/
public function __construct($smarty)
{
$this->smarty = $smarty;
ini_set('short_open_tag', '1');
}
// properties
public $usesCompiler = false;
public $isEvaluated = false;
/**
* Return flag if template source is existing
*
* @return boolean true
*/
public function isExisting($template)
{
if ($template->getTemplateFilepath() === false) {
return false;
} else {
return true;
}
}
/**
* Get filepath to template source
*
* @param object $_template template object
* @return string filepath to template source file
*/
public function getTemplateFilepath($_template)
{
$_filepath = $_template->buildTemplateFilepath ();
if (is_object($_template->smarty->security_policy)) {
$_template->smarty->security_policy->isTrustedResourceDir($_filepath);
}
$_template->templateUid = sha1($_filepath);
return $_filepath;
}
/**
* Get timestamp to template source
*
* @param object $_template template object
* @return integer timestamp of template source file
*/
public function getTemplateTimestamp($_template)
{
return filemtime($_template->getTemplateFilepath());
}
/**
* Read template source from file
*
* @param object $_template template object
* @return string content of template source file
*/
public function getTemplateSource($_template)
{
if (file_exists($_tfp = $_template->getTemplateFilepath())) {
$_template->template_source = file_get_contents($_tfp);
return true;
} else {
return false;
}
}
/**
* Get filepath to compiled template
*
* @param object $_template template object
* @return boolean return false as compiled template is not stored
*/
public function getCompiledFilepath($_template)
{
// no filepath for PHP templates
return false;
}
/**
* renders the PHP template
*/
public function renderUncompiled($_smarty_template)
{
if (!$this->smarty->allow_php_templates) {
throw new SmartyException("PHP templates are disabled");
}
if ($this->getTemplateFilepath($_smarty_template) === false) {
throw new SmartyException("Unable to load template \"{$_smarty_template->resource_type} : {$_smarty_template->resource_name}\"");
}
// prepare variables
$_smarty_ptr = $_smarty_template;
do {
foreach ($_smarty_ptr->tpl_vars as $_smarty_var => $_smarty_var_object) {
if (isset($_smarty_var_object->value)) {
$$_smarty_var = $_smarty_var_object->value;
}
}
$_smarty_ptr = $_smarty_ptr->parent;
} while ($_smarty_ptr != null);
unset ($_smarty_var, $_smarty_var_object, $_smarty_ptr);
// include PHP template
include($this->getTemplateFilepath($_smarty_template));
return;
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_resource_php.php | PHP | asf20 | 3,506 |
<?php
/**
* Smarty Internal Plugin Compile Include PHP
*
* Compiles the {include_php} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Insert Class
*/
class Smarty_Internal_Compile_Include_Php extends Smarty_Internal_CompileBase {
// attribute definitions
public $required_attributes = array('file');
public $shorttag_order = array('file');
public $optional_attributes = array('once', 'assign');
/**
* Compiles code for the {include_php} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @return string compiled code
*/
public function compile($args, $compiler)
{
if (!$compiler->smarty->allow_php_tag) {
throw new SmartyException("{include_php} is deprecated, set allow_php_tag = true to enable");
}
$this->compiler = $compiler;
// check and get attributes
$_attr = $this->_get_attributes($args);
$_output = '<?php ';
$_smarty_tpl = $compiler->template;
$_filepath = false;
eval('$_file = ' . $_attr['file'] . ';');
if (!isset($this->compiler->smarty->security_policy) && file_exists($_file)) {
$_filepath = $_file;
} else {
if (isset($this->compiler->smarty->security_policy)) {
$_dir = $this->compiler->smarty->security_policy->trusted_dir;
} else {
$_dir = $this->compiler->smarty->trusted_dir;
}
if (!empty($_dir)) {
foreach((array)$_dir as $_script_dir) {
if (strpos('/\\', substr($_script_dir, -1)) === false) {
$_script_dir .= DS;
}
if (file_exists($_script_dir . $_file)) {
$_filepath = $_script_dir . $_file;
break;
}
}
}
}
if ($_filepath == false) {
$this->compiler->trigger_template_error("{include_php} file '{$_file}' is not readable", $this->compiler->lex->taglineno);
}
if (isset($this->compiler->smarty->security_policy)) {
$this->compiler->smarty->security_policy->isTrustedPHPDir($_filepath);
}
if (isset($_attr['assign'])) {
// output will be stored in a smarty variable instead of being displayed
$_assign = $_attr['assign'];
}
$_once = '_once';
if (isset($_attr['once'])) {
if ($_attr['once'] == 'false') {
$_once = '';
}
}
if (isset($_assign)) {
return "<?php ob_start(); include{$_once} ('{$_filepath}'); \$_smarty_tpl->assign({$_assign},ob_get_contents()); ob_end_clean();?>";
} else {
return "<?php include{$_once} ('{$_filepath}');?>\n";
}
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_compile_include_php.php | PHP | asf20 | 2,979 |
<?php
/**
* Smarty Internal Plugin Configfileparser
*
* This is the config file parser.
* It is generated from the internal.configfileparser.y file
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
class TPC_yyToken implements ArrayAccess
{
public $string = '';
public $metadata = array();
function __construct($s, $m = array())
{
if ($s instanceof TPC_yyToken) {
$this->string = $s->string;
$this->metadata = $s->metadata;
} else {
$this->string = (string) $s;
if ($m instanceof TPC_yyToken) {
$this->metadata = $m->metadata;
} elseif (is_array($m)) {
$this->metadata = $m;
}
}
}
function __toString()
{
return $this->_string;
}
function offsetExists($offset)
{
return isset($this->metadata[$offset]);
}
function offsetGet($offset)
{
return $this->metadata[$offset];
}
function offsetSet($offset, $value)
{
if ($offset === null) {
if (isset($value[0])) {
$x = ($value instanceof TPC_yyToken) ?
$value->metadata : $value;
$this->metadata = array_merge($this->metadata, $x);
return;
}
$offset = count($this->metadata);
}
if ($value === null) {
return;
}
if ($value instanceof TPC_yyToken) {
if ($value->metadata) {
$this->metadata[$offset] = $value->metadata;
}
} elseif ($value) {
$this->metadata[$offset] = $value;
}
}
function offsetUnset($offset)
{
unset($this->metadata[$offset]);
}
}
class TPC_yyStackEntry
{
public $stateno; /* The state-number */
public $major; /* The major token value. This is the code
** number for the token at this stack level */
public $minor; /* The user-supplied minor token value. This
** is the value of the token */
};
#line 12 "smarty_internal_configfileparser.y"
class Smarty_Internal_Configfileparser#line 79 "smarty_internal_configfileparser.php"
{
#line 14 "smarty_internal_configfileparser.y"
// states whether the parse was successful or not
public $successful = true;
public $retvalue = 0;
private $lex;
private $internalError = false;
function __construct($lex, $compiler) {
// set instance object
self::instance($this);
$this->lex = $lex;
$this->smarty = $compiler->smarty;
$this->compiler = $compiler;
}
public static function &instance($new_instance = null)
{
static $instance = null;
if (isset($new_instance) && is_object($new_instance))
$instance = $new_instance;
return $instance;
}
private function parse_bool($str) {
if (in_array(strtolower($str) ,array('on','yes','true'))) {
$res = true;
} else {
assert(in_array(strtolower($str), array('off','no','false')));
$res = false;
}
return $res;
}
private static $escapes_single = Array('\\' => '\\',
'\'' => '\'');
private static function parse_single_quoted_string($qstr) {
$escaped_string = substr($qstr, 1, strlen($qstr)-2); //remove outer quotes
$ss = preg_split('/(\\\\.)/', $escaped_string, -1, PREG_SPLIT_DELIM_CAPTURE);
$str = "";
foreach ($ss as $s) {
if (strlen($s) === 2 && $s[0] === '\\') {
if (isset(self::$escapes_single[$s[1]])) {
$s = self::$escapes_single[$s[1]];
}
}
$str .= $s;
}
return $str;
}
private static function parse_double_quoted_string($qstr) {
$inner_str = substr($qstr, 1, strlen($qstr)-2);
return stripcslashes($inner_str);
}
private static function parse_tripple_double_quoted_string($qstr) {
$inner_str = substr($qstr, 3, strlen($qstr)-6);
return stripcslashes($inner_str);
}
private function set_var(Array $var, Array &$target_array) {
$key = $var["key"];
$value = $var["value"];
if ($this->smarty->config_overwrite || !isset($target_array['vars'][$key])) {
$target_array['vars'][$key] = $value;
} else {
settype($target_array['vars'][$key], 'array');
$target_array['vars'][$key][] = $value;
}
}
private function add_global_vars(Array $vars) {
if (!isset($this->compiler->config_data['vars'])) {
$this->compiler->config_data['vars'] = Array();
}
foreach ($vars as $var) {
$this->set_var($var, $this->compiler->config_data);
}
}
private function add_section_vars($section_name, Array $vars) {
if (!isset($this->compiler->config_data['sections'][$section_name]['vars'])) {
$this->compiler->config_data['sections'][$section_name]['vars'] = Array();
}
foreach ($vars as $var) {
$this->set_var($var, $this->compiler->config_data['sections'][$section_name]);
}
}
#line 175 "smarty_internal_configfileparser.php"
const TPC_OPENB = 1;
const TPC_SECTION = 2;
const TPC_CLOSEB = 3;
const TPC_DOT = 4;
const TPC_ID = 5;
const TPC_EQUAL = 6;
const TPC_FLOAT = 7;
const TPC_INT = 8;
const TPC_BOOL = 9;
const TPC_SINGLE_QUOTED_STRING = 10;
const TPC_DOUBLE_QUOTED_STRING = 11;
const TPC_TRIPPLE_DOUBLE_QUOTED_STRING = 12;
const TPC_NAKED_STRING = 13;
const TPC_NEWLINE = 14;
const TPC_COMMENTSTART = 15;
const YY_NO_ACTION = 54;
const YY_ACCEPT_ACTION = 53;
const YY_ERROR_ACTION = 52;
const YY_SZ_ACTTAB = 35;
static public $yy_action = array(
/* 0 */ 26, 27, 21, 30, 29, 28, 31, 16, 53, 8,
/* 10 */ 19, 2, 20, 11, 24, 23, 20, 11, 17, 15,
/* 20 */ 3, 14, 13, 18, 4, 6, 5, 1, 12, 22,
/* 30 */ 9, 47, 10, 25, 7,
);
static public $yy_lookahead = array(
/* 0 */ 7, 8, 9, 10, 11, 12, 13, 5, 17, 18,
/* 10 */ 14, 20, 14, 15, 22, 23, 14, 15, 2, 2,
/* 20 */ 20, 4, 13, 14, 6, 3, 3, 20, 1, 24,
/* 30 */ 22, 25, 22, 21, 19,
);
const YY_SHIFT_USE_DFLT = -8;
const YY_SHIFT_MAX = 17;
static public $yy_shift_ofst = array(
/* 0 */ -8, 2, 2, 2, -7, -2, -2, 27, -8, -8,
/* 10 */ -8, 9, 17, -4, 16, 23, 18, 22,
);
const YY_REDUCE_USE_DFLT = -10;
const YY_REDUCE_MAX = 10;
static public $yy_reduce_ofst = array(
/* 0 */ -9, -8, -8, -8, 5, 10, 8, 12, 15, 0,
/* 10 */ 7,
);
static public $yyExpectedTokens = array(
/* 0 */ array(),
/* 1 */ array(5, 14, 15, ),
/* 2 */ array(5, 14, 15, ),
/* 3 */ array(5, 14, 15, ),
/* 4 */ array(7, 8, 9, 10, 11, 12, 13, ),
/* 5 */ array(14, 15, ),
/* 6 */ array(14, 15, ),
/* 7 */ array(1, ),
/* 8 */ array(),
/* 9 */ array(),
/* 10 */ array(),
/* 11 */ array(13, 14, ),
/* 12 */ array(2, 4, ),
/* 13 */ array(14, ),
/* 14 */ array(2, ),
/* 15 */ array(3, ),
/* 16 */ array(6, ),
/* 17 */ array(3, ),
/* 18 */ array(),
/* 19 */ array(),
/* 20 */ array(),
/* 21 */ array(),
/* 22 */ array(),
/* 23 */ array(),
/* 24 */ array(),
/* 25 */ array(),
/* 26 */ array(),
/* 27 */ array(),
/* 28 */ array(),
/* 29 */ array(),
/* 30 */ array(),
/* 31 */ array(),
);
static public $yy_default = array(
/* 0 */ 40, 36, 33, 37, 52, 52, 52, 32, 35, 40,
/* 10 */ 40, 52, 52, 52, 52, 52, 52, 52, 50, 51,
/* 20 */ 49, 44, 41, 39, 38, 34, 42, 43, 47, 46,
/* 30 */ 45, 48,
);
const YYNOCODE = 26;
const YYSTACKDEPTH = 100;
const YYNSTATE = 32;
const YYNRULE = 20;
const YYERRORSYMBOL = 16;
const YYERRSYMDT = 'yy0';
const YYFALLBACK = 0;
static public $yyFallback = array(
);
static function Trace($TraceFILE, $zTracePrompt)
{
if (!$TraceFILE) {
$zTracePrompt = 0;
} elseif (!$zTracePrompt) {
$TraceFILE = 0;
}
self::$yyTraceFILE = $TraceFILE;
self::$yyTracePrompt = $zTracePrompt;
}
static function PrintTrace()
{
self::$yyTraceFILE = fopen('php://output', 'w');
self::$yyTracePrompt = '<br>';
}
static public $yyTraceFILE;
static public $yyTracePrompt;
public $yyidx; /* Index of top element in stack */
public $yyerrcnt; /* Shifts left before out of the error */
public $yystack = array(); /* The parser's stack */
public $yyTokenName = array(
'$', 'OPENB', 'SECTION', 'CLOSEB',
'DOT', 'ID', 'EQUAL', 'FLOAT',
'INT', 'BOOL', 'SINGLE_QUOTED_STRING', 'DOUBLE_QUOTED_STRING',
'TRIPPLE_DOUBLE_QUOTED_STRING', 'NAKED_STRING', 'NEWLINE', 'COMMENTSTART',
'error', 'start', 'global_vars', 'sections',
'var_list', 'section', 'newline', 'var',
'value',
);
static public $yyRuleName = array(
/* 0 */ "start ::= global_vars sections",
/* 1 */ "global_vars ::= var_list",
/* 2 */ "sections ::= sections section",
/* 3 */ "sections ::=",
/* 4 */ "section ::= OPENB SECTION CLOSEB newline var_list",
/* 5 */ "section ::= OPENB DOT SECTION CLOSEB newline var_list",
/* 6 */ "var_list ::= var_list newline",
/* 7 */ "var_list ::= var_list var",
/* 8 */ "var_list ::=",
/* 9 */ "var ::= ID EQUAL value",
/* 10 */ "value ::= FLOAT",
/* 11 */ "value ::= INT",
/* 12 */ "value ::= BOOL",
/* 13 */ "value ::= SINGLE_QUOTED_STRING",
/* 14 */ "value ::= DOUBLE_QUOTED_STRING",
/* 15 */ "value ::= TRIPPLE_DOUBLE_QUOTED_STRING",
/* 16 */ "value ::= NAKED_STRING",
/* 17 */ "newline ::= NEWLINE",
/* 18 */ "newline ::= COMMENTSTART NEWLINE",
/* 19 */ "newline ::= COMMENTSTART NAKED_STRING NEWLINE",
);
function tokenName($tokenType)
{
if ($tokenType === 0) {
return 'End of Input';
}
if ($tokenType > 0 && $tokenType < count($this->yyTokenName)) {
return $this->yyTokenName[$tokenType];
} else {
return "Unknown";
}
}
static function yy_destructor($yymajor, $yypminor)
{
switch ($yymajor) {
default: break; /* If no destructor action specified: do nothing */
}
}
function yy_pop_parser_stack()
{
if (!count($this->yystack)) {
return;
}
$yytos = array_pop($this->yystack);
if (self::$yyTraceFILE && $this->yyidx >= 0) {
fwrite(self::$yyTraceFILE,
self::$yyTracePrompt . 'Popping ' . $this->yyTokenName[$yytos->major] .
"\n");
}
$yymajor = $yytos->major;
self::yy_destructor($yymajor, $yytos->minor);
$this->yyidx--;
return $yymajor;
}
function __destruct()
{
while ($this->yystack !== Array()) {
$this->yy_pop_parser_stack();
}
if (is_resource(self::$yyTraceFILE)) {
fclose(self::$yyTraceFILE);
}
}
function yy_get_expected_tokens($token)
{
$state = $this->yystack[$this->yyidx]->stateno;
$expected = self::$yyExpectedTokens[$state];
if (in_array($token, self::$yyExpectedTokens[$state], true)) {
return $expected;
}
$stack = $this->yystack;
$yyidx = $this->yyidx;
do {
$yyact = $this->yy_find_shift_action($token);
if ($yyact >= self::YYNSTATE && $yyact < self::YYNSTATE + self::YYNRULE) {
// reduce action
$done = 0;
do {
if ($done++ == 100) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
// too much recursion prevents proper detection
// so give up
return array_unique($expected);
}
$yyruleno = $yyact - self::YYNSTATE;
$this->yyidx -= self::$yyRuleInfo[$yyruleno]['rhs'];
$nextstate = $this->yy_find_reduce_action(
$this->yystack[$this->yyidx]->stateno,
self::$yyRuleInfo[$yyruleno]['lhs']);
if (isset(self::$yyExpectedTokens[$nextstate])) {
$expected = array_merge($expected, self::$yyExpectedTokens[$nextstate]);
if (in_array($token,
self::$yyExpectedTokens[$nextstate], true)) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
return array_unique($expected);
}
}
if ($nextstate < self::YYNSTATE) {
// we need to shift a non-terminal
$this->yyidx++;
$x = new TPC_yyStackEntry;
$x->stateno = $nextstate;
$x->major = self::$yyRuleInfo[$yyruleno]['lhs'];
$this->yystack[$this->yyidx] = $x;
continue 2;
} elseif ($nextstate == self::YYNSTATE + self::YYNRULE + 1) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
// the last token was just ignored, we can't accept
// by ignoring input, this is in essence ignoring a
// syntax error!
return array_unique($expected);
} elseif ($nextstate === self::YY_NO_ACTION) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
// input accepted, but not shifted (I guess)
return $expected;
} else {
$yyact = $nextstate;
}
} while (true);
}
break;
} while (true);
$this->yyidx = $yyidx;
$this->yystack = $stack;
return array_unique($expected);
}
function yy_is_expected_token($token)
{
if ($token === 0) {
return true; // 0 is not part of this
}
$state = $this->yystack[$this->yyidx]->stateno;
if (in_array($token, self::$yyExpectedTokens[$state], true)) {
return true;
}
$stack = $this->yystack;
$yyidx = $this->yyidx;
do {
$yyact = $this->yy_find_shift_action($token);
if ($yyact >= self::YYNSTATE && $yyact < self::YYNSTATE + self::YYNRULE) {
// reduce action
$done = 0;
do {
if ($done++ == 100) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
// too much recursion prevents proper detection
// so give up
return true;
}
$yyruleno = $yyact - self::YYNSTATE;
$this->yyidx -= self::$yyRuleInfo[$yyruleno]['rhs'];
$nextstate = $this->yy_find_reduce_action(
$this->yystack[$this->yyidx]->stateno,
self::$yyRuleInfo[$yyruleno]['lhs']);
if (isset(self::$yyExpectedTokens[$nextstate]) &&
in_array($token, self::$yyExpectedTokens[$nextstate], true)) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
return true;
}
if ($nextstate < self::YYNSTATE) {
// we need to shift a non-terminal
$this->yyidx++;
$x = new TPC_yyStackEntry;
$x->stateno = $nextstate;
$x->major = self::$yyRuleInfo[$yyruleno]['lhs'];
$this->yystack[$this->yyidx] = $x;
continue 2;
} elseif ($nextstate == self::YYNSTATE + self::YYNRULE + 1) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
if (!$token) {
// end of input: this is valid
return true;
}
// the last token was just ignored, we can't accept
// by ignoring input, this is in essence ignoring a
// syntax error!
return false;
} elseif ($nextstate === self::YY_NO_ACTION) {
$this->yyidx = $yyidx;
$this->yystack = $stack;
// input accepted, but not shifted (I guess)
return true;
} else {
$yyact = $nextstate;
}
} while (true);
}
break;
} while (true);
$this->yyidx = $yyidx;
$this->yystack = $stack;
return true;
}
function yy_find_shift_action($iLookAhead)
{
$stateno = $this->yystack[$this->yyidx]->stateno;
/* if ($this->yyidx < 0) return self::YY_NO_ACTION; */
if (!isset(self::$yy_shift_ofst[$stateno])) {
// no shift actions
return self::$yy_default[$stateno];
}
$i = self::$yy_shift_ofst[$stateno];
if ($i === self::YY_SHIFT_USE_DFLT) {
return self::$yy_default[$stateno];
}
if ($iLookAhead == self::YYNOCODE) {
return self::YY_NO_ACTION;
}
$i += $iLookAhead;
if ($i < 0 || $i >= self::YY_SZ_ACTTAB ||
self::$yy_lookahead[$i] != $iLookAhead) {
if (count(self::$yyFallback) && $iLookAhead < count(self::$yyFallback)
&& ($iFallback = self::$yyFallback[$iLookAhead]) != 0) {
if (self::$yyTraceFILE) {
fwrite(self::$yyTraceFILE, self::$yyTracePrompt . "FALLBACK " .
$this->yyTokenName[$iLookAhead] . " => " .
$this->yyTokenName[$iFallback] . "\n");
}
return $this->yy_find_shift_action($iFallback);
}
return self::$yy_default[$stateno];
} else {
return self::$yy_action[$i];
}
}
function yy_find_reduce_action($stateno, $iLookAhead)
{
/* $stateno = $this->yystack[$this->yyidx]->stateno; */
if (!isset(self::$yy_reduce_ofst[$stateno])) {
return self::$yy_default[$stateno];
}
$i = self::$yy_reduce_ofst[$stateno];
if ($i == self::YY_REDUCE_USE_DFLT) {
return self::$yy_default[$stateno];
}
if ($iLookAhead == self::YYNOCODE) {
return self::YY_NO_ACTION;
}
$i += $iLookAhead;
if ($i < 0 || $i >= self::YY_SZ_ACTTAB ||
self::$yy_lookahead[$i] != $iLookAhead) {
return self::$yy_default[$stateno];
} else {
return self::$yy_action[$i];
}
}
function yy_shift($yyNewState, $yyMajor, $yypMinor)
{
$this->yyidx++;
if ($this->yyidx >= self::YYSTACKDEPTH) {
$this->yyidx--;
if (self::$yyTraceFILE) {
fprintf(self::$yyTraceFILE, "%sStack Overflow!\n", self::$yyTracePrompt);
}
while ($this->yyidx >= 0) {
$this->yy_pop_parser_stack();
}
#line 127 "smarty_internal_configfileparser.y"
$this->internalError = true;
$this->compiler->trigger_config_file_error("Stack overflow in configfile parser");
#line 586 "smarty_internal_configfileparser.php"
return;
}
$yytos = new TPC_yyStackEntry;
$yytos->stateno = $yyNewState;
$yytos->major = $yyMajor;
$yytos->minor = $yypMinor;
array_push($this->yystack, $yytos);
if (self::$yyTraceFILE && $this->yyidx > 0) {
fprintf(self::$yyTraceFILE, "%sShift %d\n", self::$yyTracePrompt,
$yyNewState);
fprintf(self::$yyTraceFILE, "%sStack:", self::$yyTracePrompt);
for($i = 1; $i <= $this->yyidx; $i++) {
fprintf(self::$yyTraceFILE, " %s",
$this->yyTokenName[$this->yystack[$i]->major]);
}
fwrite(self::$yyTraceFILE,"\n");
}
}
static public $yyRuleInfo = array(
array( 'lhs' => 17, 'rhs' => 2 ),
array( 'lhs' => 18, 'rhs' => 1 ),
array( 'lhs' => 19, 'rhs' => 2 ),
array( 'lhs' => 19, 'rhs' => 0 ),
array( 'lhs' => 21, 'rhs' => 5 ),
array( 'lhs' => 21, 'rhs' => 6 ),
array( 'lhs' => 20, 'rhs' => 2 ),
array( 'lhs' => 20, 'rhs' => 2 ),
array( 'lhs' => 20, 'rhs' => 0 ),
array( 'lhs' => 23, 'rhs' => 3 ),
array( 'lhs' => 24, 'rhs' => 1 ),
array( 'lhs' => 24, 'rhs' => 1 ),
array( 'lhs' => 24, 'rhs' => 1 ),
array( 'lhs' => 24, 'rhs' => 1 ),
array( 'lhs' => 24, 'rhs' => 1 ),
array( 'lhs' => 24, 'rhs' => 1 ),
array( 'lhs' => 24, 'rhs' => 1 ),
array( 'lhs' => 22, 'rhs' => 1 ),
array( 'lhs' => 22, 'rhs' => 2 ),
array( 'lhs' => 22, 'rhs' => 3 ),
);
static public $yyReduceMap = array(
0 => 0,
2 => 0,
3 => 0,
17 => 0,
18 => 0,
19 => 0,
1 => 1,
4 => 4,
5 => 5,
6 => 6,
7 => 7,
8 => 8,
9 => 9,
10 => 10,
11 => 11,
12 => 12,
13 => 13,
14 => 14,
15 => 15,
16 => 16,
);
#line 133 "smarty_internal_configfileparser.y"
function yy_r0(){ $this->_retvalue = null; }
#line 653 "smarty_internal_configfileparser.php"
#line 136 "smarty_internal_configfileparser.y"
function yy_r1(){ $this->add_global_vars($this->yystack[$this->yyidx + 0]->minor); $this->_retvalue = null; }
#line 656 "smarty_internal_configfileparser.php"
#line 142 "smarty_internal_configfileparser.y"
function yy_r4(){ $this->add_section_vars($this->yystack[$this->yyidx + -3]->minor, $this->yystack[$this->yyidx + 0]->minor); $this->_retvalue = null; }
#line 659 "smarty_internal_configfileparser.php"
#line 143 "smarty_internal_configfileparser.y"
function yy_r5(){ if ($this->smarty->config_read_hidden) { $this->add_section_vars($this->yystack[$this->yyidx + -3]->minor, $this->yystack[$this->yyidx + 0]->minor); } $this->_retvalue = null; }
#line 662 "smarty_internal_configfileparser.php"
#line 146 "smarty_internal_configfileparser.y"
function yy_r6(){ $this->_retvalue = $this->yystack[$this->yyidx + -1]->minor; }
#line 665 "smarty_internal_configfileparser.php"
#line 147 "smarty_internal_configfileparser.y"
function yy_r7(){ $this->_retvalue = array_merge($this->yystack[$this->yyidx + -1]->minor, Array($this->yystack[$this->yyidx + 0]->minor)); }
#line 668 "smarty_internal_configfileparser.php"
#line 148 "smarty_internal_configfileparser.y"
function yy_r8(){ $this->_retvalue = Array(); }
#line 671 "smarty_internal_configfileparser.php"
#line 152 "smarty_internal_configfileparser.y"
function yy_r9(){ $this->_retvalue = Array("key" => $this->yystack[$this->yyidx + -2]->minor, "value" => $this->yystack[$this->yyidx + 0]->minor); }
#line 674 "smarty_internal_configfileparser.php"
#line 154 "smarty_internal_configfileparser.y"
function yy_r10(){ $this->_retvalue = (float) $this->yystack[$this->yyidx + 0]->minor; }
#line 677 "smarty_internal_configfileparser.php"
#line 155 "smarty_internal_configfileparser.y"
function yy_r11(){ $this->_retvalue = (int) $this->yystack[$this->yyidx + 0]->minor; }
#line 680 "smarty_internal_configfileparser.php"
#line 156 "smarty_internal_configfileparser.y"
function yy_r12(){ $this->_retvalue = $this->parse_bool($this->yystack[$this->yyidx + 0]->minor); }
#line 683 "smarty_internal_configfileparser.php"
#line 157 "smarty_internal_configfileparser.y"
function yy_r13(){ $this->_retvalue = self::parse_single_quoted_string($this->yystack[$this->yyidx + 0]->minor); }
#line 686 "smarty_internal_configfileparser.php"
#line 158 "smarty_internal_configfileparser.y"
function yy_r14(){ $this->_retvalue = self::parse_double_quoted_string($this->yystack[$this->yyidx + 0]->minor); }
#line 689 "smarty_internal_configfileparser.php"
#line 159 "smarty_internal_configfileparser.y"
function yy_r15(){ $this->_retvalue = self::parse_tripple_double_quoted_string($this->yystack[$this->yyidx + 0]->minor); }
#line 692 "smarty_internal_configfileparser.php"
#line 160 "smarty_internal_configfileparser.y"
function yy_r16(){ $this->_retvalue = $this->yystack[$this->yyidx + 0]->minor; }
#line 695 "smarty_internal_configfileparser.php"
private $_retvalue;
function yy_reduce($yyruleno)
{
$yymsp = $this->yystack[$this->yyidx];
if (self::$yyTraceFILE && $yyruleno >= 0
&& $yyruleno < count(self::$yyRuleName)) {
fprintf(self::$yyTraceFILE, "%sReduce (%d) [%s].\n",
self::$yyTracePrompt, $yyruleno,
self::$yyRuleName[$yyruleno]);
}
$this->_retvalue = $yy_lefthand_side = null;
if (array_key_exists($yyruleno, self::$yyReduceMap)) {
// call the action
$this->_retvalue = null;
$this->{'yy_r' . self::$yyReduceMap[$yyruleno]}();
$yy_lefthand_side = $this->_retvalue;
}
$yygoto = self::$yyRuleInfo[$yyruleno]['lhs'];
$yysize = self::$yyRuleInfo[$yyruleno]['rhs'];
$this->yyidx -= $yysize;
for($i = $yysize; $i; $i--) {
// pop all of the right-hand side parameters
array_pop($this->yystack);
}
$yyact = $this->yy_find_reduce_action($this->yystack[$this->yyidx]->stateno, $yygoto);
if ($yyact < self::YYNSTATE) {
if (!self::$yyTraceFILE && $yysize) {
$this->yyidx++;
$x = new TPC_yyStackEntry;
$x->stateno = $yyact;
$x->major = $yygoto;
$x->minor = $yy_lefthand_side;
$this->yystack[$this->yyidx] = $x;
} else {
$this->yy_shift($yyact, $yygoto, $yy_lefthand_side);
}
} elseif ($yyact == self::YYNSTATE + self::YYNRULE + 1) {
$this->yy_accept();
}
}
function yy_parse_failed()
{
if (self::$yyTraceFILE) {
fprintf(self::$yyTraceFILE, "%sFail!\n", self::$yyTracePrompt);
}
while ($this->yyidx >= 0) {
$this->yy_pop_parser_stack();
}
}
function yy_syntax_error($yymajor, $TOKEN)
{
#line 120 "smarty_internal_configfileparser.y"
$this->internalError = true;
$this->yymajor = $yymajor;
$this->compiler->trigger_config_file_error();
#line 758 "smarty_internal_configfileparser.php"
}
function yy_accept()
{
if (self::$yyTraceFILE) {
fprintf(self::$yyTraceFILE, "%sAccept!\n", self::$yyTracePrompt);
}
while ($this->yyidx >= 0) {
$stack = $this->yy_pop_parser_stack();
}
#line 112 "smarty_internal_configfileparser.y"
$this->successful = !$this->internalError;
$this->internalError = false;
$this->retvalue = $this->_retvalue;
//echo $this->retvalue."\n\n";
#line 776 "smarty_internal_configfileparser.php"
}
function doParse($yymajor, $yytokenvalue)
{
$yyerrorhit = 0; /* True if yymajor has invoked an error */
if ($this->yyidx === null || $this->yyidx < 0) {
$this->yyidx = 0;
$this->yyerrcnt = -1;
$x = new TPC_yyStackEntry;
$x->stateno = 0;
$x->major = 0;
$this->yystack = array();
array_push($this->yystack, $x);
}
$yyendofinput = ($yymajor==0);
if (self::$yyTraceFILE) {
fprintf(self::$yyTraceFILE, "%sInput %s\n",
self::$yyTracePrompt, $this->yyTokenName[$yymajor]);
}
do {
$yyact = $this->yy_find_shift_action($yymajor);
if ($yymajor < self::YYERRORSYMBOL &&
!$this->yy_is_expected_token($yymajor)) {
// force a syntax error
$yyact = self::YY_ERROR_ACTION;
}
if ($yyact < self::YYNSTATE) {
$this->yy_shift($yyact, $yymajor, $yytokenvalue);
$this->yyerrcnt--;
if ($yyendofinput && $this->yyidx >= 0) {
$yymajor = 0;
} else {
$yymajor = self::YYNOCODE;
}
} elseif ($yyact < self::YYNSTATE + self::YYNRULE) {
$this->yy_reduce($yyact - self::YYNSTATE);
} elseif ($yyact == self::YY_ERROR_ACTION) {
if (self::$yyTraceFILE) {
fprintf(self::$yyTraceFILE, "%sSyntax Error!\n",
self::$yyTracePrompt);
}
if (self::YYERRORSYMBOL) {
if ($this->yyerrcnt < 0) {
$this->yy_syntax_error($yymajor, $yytokenvalue);
}
$yymx = $this->yystack[$this->yyidx]->major;
if ($yymx == self::YYERRORSYMBOL || $yyerrorhit ){
if (self::$yyTraceFILE) {
fprintf(self::$yyTraceFILE, "%sDiscard input token %s\n",
self::$yyTracePrompt, $this->yyTokenName[$yymajor]);
}
$this->yy_destructor($yymajor, $yytokenvalue);
$yymajor = self::YYNOCODE;
} else {
while ($this->yyidx >= 0 &&
$yymx != self::YYERRORSYMBOL &&
($yyact = $this->yy_find_shift_action(self::YYERRORSYMBOL)) >= self::YYNSTATE
){
$this->yy_pop_parser_stack();
}
if ($this->yyidx < 0 || $yymajor==0) {
$this->yy_destructor($yymajor, $yytokenvalue);
$this->yy_parse_failed();
$yymajor = self::YYNOCODE;
} elseif ($yymx != self::YYERRORSYMBOL) {
$u2 = 0;
$this->yy_shift($yyact, self::YYERRORSYMBOL, $u2);
}
}
$this->yyerrcnt = 3;
$yyerrorhit = 1;
} else {
if ($this->yyerrcnt <= 0) {
$this->yy_syntax_error($yymajor, $yytokenvalue);
}
$this->yyerrcnt = 3;
$this->yy_destructor($yymajor, $yytokenvalue);
if ($yyendofinput) {
$this->yy_parse_failed();
}
$yymajor = self::YYNOCODE;
}
} else {
$this->yy_accept();
$yymajor = self::YYNOCODE;
}
} while ($yymajor != self::YYNOCODE && $this->yyidx >= 0);
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_configfileparser.php | PHP | asf20 | 32,674 |
<?php
/**
* Smarty Internal Plugin Resource Registered
*
* Implements the registered resource for Smarty template
*
* @package Smarty
* @subpackage TemplateResources
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Resource Registered
*/
class Smarty_Internal_Resource_Registered {
public function __construct($template, $resource_type = null)
{
$this->smarty = $template->smarty;
if (isset($resource_type)) {
$template->smarty->registerResource($resource_type,
array("smarty_resource_{$resource_type}_source",
"smarty_resource_{$resource_type}_timestamp",
"smarty_resource_{$resource_type}_secure",
"smarty_resource_{$resource_type}_trusted"));
}
}
// classes used for compiling Smarty templates from file resource
public $compiler_class = 'Smarty_Internal_SmartyTemplateCompiler';
public $template_lexer_class = 'Smarty_Internal_Templatelexer';
public $template_parser_class = 'Smarty_Internal_Templateparser';
// properties
public $usesCompiler = true;
public $isEvaluated = false;
/**
* Return flag if template source is existing
*
* @return boolean true
*/
public function isExisting($_template)
{
if (is_integer($_template->getTemplateTimestamp())) {
return true;
} else {
return false;
}
}
/**
* Get filepath to template source
*
* @param object $_template template object
* @return string return 'string' as template source is not a file
*/
public function getTemplateFilepath($_template)
{
$_filepath = $_template->resource_type .':'.$_template->resource_name;
$_template->templateUid = sha1($_filepath);
return $_filepath;
}
/**
* Get timestamp of template source
*
* @param object $_template template object
* @return int timestamp
*/
public function getTemplateTimestamp($_template)
{
// return timestamp
$time_stamp = false;
call_user_func_array($this->smarty->registered_resources[$_template->resource_type][0][1],
array($_template->resource_name, &$time_stamp, $this->smarty));
return is_numeric($time_stamp) ? (int)$time_stamp : $time_stamp;
}
/**
* Get timestamp of template source by type and name
*
* @param object $_template template object
* @return int timestamp
*/
public function getTemplateTimestampTypeName($_resource_type, $_resource_name)
{
// return timestamp
$time_stamp = false;
call_user_func_array($this->smarty->registered_resources[$_resource_type][0][1],
array($_resource_name, &$time_stamp, $this->smarty));
return is_numeric($time_stamp) ? (int)$time_stamp : $time_stamp;
}
/**
* Retuen template source from resource name
*
* @param object $_template template object
* @return string content of template source
*/
public function getTemplateSource($_template)
{
// return template string
return call_user_func_array($this->smarty->registered_resources[$_template->resource_type][0][0],
array($_template->resource_name, &$_template->template_source, $this->smarty));
}
/**
* Get filepath to compiled template
*
* @param object $_template template object
* @return boolean return false as compiled template is not stored
*/
public function getCompiledFilepath($_template)
{
$_compile_id = isset($_template->compile_id) ? preg_replace('![^\w\|]+!','_',$_template->compile_id) : null;
// calculate Uid if not already done
if ($_template->templateUid == '') {
$_template->getTemplateFilepath();
}
$_filepath = $_template->templateUid;
// if use_sub_dirs, break file into directories
if ($_template->smarty->use_sub_dirs) {
$_filepath = substr($_filepath, 0, 2) . DS
. substr($_filepath, 2, 2) . DS
. substr($_filepath, 4, 2) . DS
. $_filepath;
}
$_compile_dir_sep = $_template->smarty->use_sub_dirs ? DS : '^';
if (isset($_compile_id)) {
$_filepath = $_compile_id . $_compile_dir_sep . $_filepath;
}
if ($_template->caching) {
$_cache = '.cache';
} else {
$_cache = '';
}
$_compile_dir = $_template->smarty->compile_dir;
if (strpos('/\\', substr($_compile_dir, -1)) === false) {
$_compile_dir .= DS;
}
return $_compile_dir . $_filepath . '.' . $_template->resource_type . '.' . basename($_template->resource_name) . $_cache . '.php';
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_resource_registered.php | PHP | asf20 | 4,845 |
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage Security
* @author Uwe Tews
*/
/**
* This class does contain the security settings
*/
class Smarty_Security {
/**
* This determines how Smarty handles "<?php ... ?>" tags in templates.
* possible values:
* <ul>
* <li>Smarty::PHP_PASSTHRU -> echo PHP tags as they are</li>
* <li>Smarty::PHP_QUOTE -> escape tags as entities</li>
* <li>Smarty::PHP_REMOVE -> remove php tags</li>
* <li>Smarty::PHP_ALLOW -> execute php tags</li>
* </ul>
*
* @var integer
*/
public $php_handling = Smarty::PHP_PASSTHRU;
/**
* This is the list of template directories that are considered secure.
* $template_dir is in this list implicitly.
*
* @var array
*/
public $secure_dir = array();
/**
* This is an array of directories where trusted php scripts reside.
* {@link $security} is disabled during their inclusion/execution.
*
* @var array
*/
public $trusted_dir = array();
/**
* This is an array of trusted static classes.
*
* If empty access to all static classes is allowed.
* If set to 'none' none is allowed.
* @var array
*/
public $static_classes = array();
/**
* This is an array of trusted PHP functions.
*
* If empty all functions are allowed.
* To disable all PHP functions set $php_functions = null.
* @var array
*/
public $php_functions = array('isset', 'empty',
'count', 'sizeof','in_array', 'is_array','time','nl2br');
/**
* This is an array of trusted PHP modifers.
*
* If empty all modifiers are allowed.
* To disable all modifier set $modifiers = null.
* @var array
*/
public $php_modifiers = array('escape','count');
/**
* This is an array of trusted streams.
*
* If empty all streams are allowed.
* To disable all streams set $streams = null.
* @var array
*/
public $streams = array('file');
/**
* + flag if constants can be accessed from template
*/
public $allow_constants = true;
/**
* + flag if super globals can be accessed from template
*/
public $allow_super_globals = true;
/**
* + flag if the {php} and {include_php} tag can be executed
*/
public $allow_php_tag = false;
public function __construct($smarty)
{
$this->smarty = $smarty;
}
/**
* Check if PHP function is trusted.
*
* @param string $function_name
* @param object $compiler compiler object
* @return boolean true if function is trusted
*/
function isTrustedPhpFunction($function_name, $compiler)
{
if (isset($this->php_functions) && (empty($this->php_functions) || in_array($function_name, $this->php_functions))) {
return true;
} else {
$compiler->trigger_template_error ("PHP function '{$function_name}' not allowed by security setting");
return false;
}
}
/**
* Check if static class is trusted.
*
* @param string $class_name
* @param object $compiler compiler object
* @return boolean true if class is trusted
*/
function isTrustedStaticClass($class_name, $compiler)
{
if (isset($this->static_classes) && (empty($this->static_classes) || in_array($class_name, $this->static_classes))) {
return true;
} else {
$compiler->trigger_template_error ("access to static class '{$class_name}' not allowed by security setting");
return false;
}
}
/**
* Check if modifier is trusted.
*
* @param string $modifier_name
* @param object $compiler compiler object
* @return boolean true if modifier is trusted
*/
function isTrustedModifier($modifier_name, $compiler)
{
if (isset($this->php_modifiers) && (empty($this->php_modifiers) || in_array($modifier_name, $this->php_modifiers))) {
return true;
} else {
$compiler->trigger_template_error ("modifier '{$modifier_name}' not allowed by security setting");
return false;
}
}
/**
* Check if stream is trusted.
*
* @param string $stream_name
* @param object $compiler compiler object
* @return boolean true if stream is trusted
*/
function isTrustedStream($stream_name)
{
if (isset($this->streams) && (empty($this->streams) || in_array($stream_name, $this->streams))) {
return true;
} else {
throw new SmartyException ("stream '{$stream_name}' not allowed by security setting");
return false;
}
}
/**
* Check if directory of file resource is trusted.
*
* @param string $filepath
* @param object $compiler compiler object
* @return boolean true if directory is trusted
*/
function isTrustedResourceDir($filepath)
{
$_rp = realpath($filepath);
if (isset($this->smarty->template_dir)) {
foreach ((array)$this->smarty->template_dir as $curr_dir) {
if (($_cd = realpath($curr_dir)) !== false &&
strncmp($_rp, $_cd, strlen($_cd)) == 0 &&
(strlen($_rp) == strlen($_cd) || substr($_rp, strlen($_cd), 1) == DS)) {
return true;
}
}
}
if (!empty($this->smarty->security_policy->secure_dir)) {
foreach ((array)$this->smarty->security_policy->secure_dir as $curr_dir) {
if (($_cd = realpath($curr_dir)) !== false) {
if ($_cd == $_rp) {
return true;
} elseif (strncmp($_rp, $_cd, strlen($_cd)) == 0 &&
(strlen($_rp) == strlen($_cd) || substr($_rp, strlen($_cd), 1) == DS)) {
return true;
}
}
}
}
throw new SmartyException ("directory '{$_rp}' not allowed by security setting");
return false;
}
/**
* Check if directory of file resource is trusted.
*
* @param string $filepath
* @param object $compiler compiler object
* @return boolean true if directory is trusted
*/
function isTrustedPHPDir($filepath)
{
$_rp = realpath($filepath);
if (!empty($this->trusted_dir)) {
foreach ((array)$this->trusted_dir as $curr_dir) {
if (($_cd = realpath($curr_dir)) !== false) {
if ($_cd == $_rp) {
return true;
} elseif (strncmp($_rp, $_cd, strlen($_cd)) == 0 &&
substr($_rp, strlen($_cd), 1) == DS) {
return true;
}
}
}
}
throw new SmartyException ("directory '{$_rp}' not allowed by security setting");
return false;
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_security.php | PHP | asf20 | 7,140 |
<?php
/**
* Smarty Internal Plugin CompileBase
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* This class does extend all internal compile plugins
*/
// abstract class Smarty_Internal_CompileBase implements TagCompilerInterface
class Smarty_Internal_CompileBase {
public $required_attributes = array();
public $optional_attributes = array();
public $shorttag_order = array();
public $option_flags = array('nocache');
/**
* This function checks if the attributes passed are valid
*
* The attributes passed for the tag to compile are checked against the list of required and
* optional attributes. Required attributes must be present. Optional attributes are check against
* against the corresponding list. The keyword '_any' specifies that any attribute will be accepted
* as valid
*
* @param array $attributes attributes applied to the tag
* @return array of mapped attributes for further processing
*/
function _get_attributes ($attributes)
{
$_indexed_attr = array();
// loop over attributes
foreach ($attributes as $key => $mixed) {
// shorthand ?
if (!is_array($mixed)) {
// option flag ?
if (in_array(trim($mixed, '\'"'), $this->option_flags)) {
$_indexed_attr[trim($mixed, '\'"')] = true;
// shorthand attribute ?
} else if (isset($this->shorttag_order[$key])) {
$_indexed_attr[$this->shorttag_order[$key]] = $mixed;
} else {
// too many shorthands
$this->compiler->trigger_template_error('too many shorthand attributes', $this->compiler->lex->taglineno);
}
// named attribute
} else {
$kv = each($mixed);
// option flag?
if (in_array($kv['key'], $this->option_flags)) {
if (is_bool($kv['value'])) {
$_indexed_attr[$kv['key']] = $kv['value'];
} else if (is_string($kv['value']) && in_array(trim($kv['value'], '\'"'), array('true', 'false'))) {
if (trim($kv['value']) == 'true') {
$_indexed_attr[$kv['key']] = true;
} else {
$_indexed_attr[$kv['key']] = false;
}
} else if (is_numeric($kv['value']) && in_array($kv['value'], array(0, 1))) {
if ($kv['value'] == 1) {
$_indexed_attr[$kv['key']] = true;
} else {
$_indexed_attr[$kv['key']] = false;
}
} else {
$this->compiler->trigger_template_error("illegal value of option flag \"{$kv['key']}\"", $this->compiler->lex->taglineno);
}
// must be named attribute
} else {
reset($mixed);
$_indexed_attr[key($mixed)] = $mixed[key($mixed)];
}
}
}
// check if all required attributes present
foreach ($this->required_attributes as $attr) {
if (!array_key_exists($attr, $_indexed_attr)) {
$this->compiler->trigger_template_error("missing \"" . $attr . "\" attribute", $this->compiler->lex->taglineno);
}
}
// check for unallowed attributes
if ($this->optional_attributes != array('_any')) {
$tmp_array = array_merge($this->required_attributes, $this->optional_attributes, $this->option_flags);
foreach ($_indexed_attr as $key => $dummy) {
if (!in_array($key, $tmp_array) && $key !== 0) {
$this->compiler->trigger_template_error("unexpected \"" . $key . "\" attribute", $this->compiler->lex->taglineno);
}
}
}
// default 'false' for all option flags not set
foreach ($this->option_flags as $flag) {
if (!isset($_indexed_attr[$flag])) {
$_indexed_attr[$flag] = false;
}
}
return $_indexed_attr;
}
/**
* Push opening tag name on stack
*
* Optionally additional data can be saved on stack
*
* @param string $open_tag the opening tag's name
* @param anytype $data optional data which shall be saved on stack
*/
function _open_tag($open_tag, $data = null)
{
array_push($this->compiler->_tag_stack, array($open_tag, $data));
}
/**
* Pop closing tag
*
* Raise an error if this stack-top doesn't match with expected opening tags
*
* @param array $ |string $expected_tag the expected opening tag names
* @return anytype the opening tag's name or saved data
*/
function _close_tag($expected_tag)
{
if (count($this->compiler->_tag_stack) > 0) {
// get stacked info
list($_open_tag, $_data) = array_pop($this->compiler->_tag_stack);
// open tag must match with the expected ones
if (in_array($_open_tag, (array)$expected_tag)) {
if (is_null($_data)) {
// return opening tag
return $_open_tag;
} else {
// return restored data
return $_data;
}
}
// wrong nesting of tags
$this->compiler->trigger_template_error("unclosed {" . $_open_tag . "} tag");
return;
}
// wrong nesting of tags
$this->compiler->trigger_template_error("unexpected closing tag", $this->compiler->lex->taglineno);
return;
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_compilebase.php | PHP | asf20 | 5,922 |
<?php
/**
* Smarty Internal Plugin Compile Insert
*
* Compiles the {insert} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Insert Class
*/
class Smarty_Internal_Compile_Insert extends Smarty_Internal_CompileBase {
// attribute definitions
public $required_attributes = array('name');
public $shorttag_order = array('name');
public $optional_attributes = array('_any');
/**
* Compiles code for the {insert} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @return string compiled code
*/
public function compile($args, $compiler)
{
$this->compiler = $compiler;
// check and get attributes
$_attr = $this->_get_attributes($args);
// never compile as nocache code
$this->compiler->suppressNocacheProcessing = true;
$this->compiler->tag_nocache = true;
$_smarty_tpl = $compiler->template;
$_name = null;
$_script = null;
$_output = '<?php ';
// save posible attributes
eval('$_name = ' . $_attr['name'] . ';');
if (isset($_attr['assign'])) {
// output will be stored in a smarty variable instead of being displayed
$_assign = $_attr['assign'];
// create variable to make shure that the compiler knows about its nocache status
$this->compiler->template->tpl_vars[trim($_attr['assign'], "'")] = new Smarty_Variable(null, true);
}
if (isset($_attr['script'])) {
// script which must be included
$_function = "smarty_insert_{$_name}";
$_smarty_tpl = $compiler->template;
$_filepath = false;
eval('$_script = ' . $_attr['script'] . ';');
if (!isset($this->compiler->smarty->security_policy) && file_exists($_script)) {
$_filepath = $_script;
} else {
if (isset($this->compiler->smarty->security_policy)) {
$_dir = $this->compiler->smarty->security_policy->trusted_dir;
} else {
$_dir = $this->compiler->smarty->trusted_dir;
}
if (!empty($_dir)) {
foreach((array)$_dir as $_script_dir) {
if (strpos('/\\', substr($_script_dir, -1)) === false) {
$_script_dir .= DS;
}
if (file_exists($_script_dir . $_script)) {
$_filepath = $_script_dir . $_script;
break;
}
}
}
}
if ($_filepath == false) {
$this->compiler->trigger_template_error("{insert} missing script file '{$_script}'", $this->compiler->lex->taglineno);
}
// code for script file loading
$_output .= "require_once '{$_filepath}' ;";
require_once $_filepath;
if (!is_callable($_function)) {
$this->compiler->trigger_template_error(" {insert} function '{$_function}' is not callable in script file '{$_script}'", $this->compiler->lex->taglineno);
}
} else {
$_filepath = 'null';
$_function = "insert_{$_name}";
// function in PHP script ?
if (!is_callable($_function)) {
// try plugin
if (!$_function = $this->compiler->getPlugin($_name, 'insert')) {
$this->compiler->trigger_template_error("{insert} no function or plugin found for '{$_name}'", $this->compiler->lex->taglineno);
}
}
}
// delete {insert} standard attributes
unset($_attr['name'], $_attr['assign'], $_attr['script'], $_attr['nocache']);
// convert attributes into parameter array string
$_paramsArray = array();
foreach ($_attr as $_key => $_value) {
$_paramsArray[] = "'$_key' => $_value";
}
$_params = 'array(' . implode(", ", $_paramsArray) . ')';
// call insert
if (isset($_assign)) {
if ($_smarty_tpl->caching) {
$_output .= "echo Smarty_Internal_Nocache_Insert::compile ('{$_function}',{$_params}, \$_smarty_tpl, '{$_filepath}',{$_assign});?>";
} else {
$_output .= "\$_smarty_tpl->assign({$_assign} , {$_function} ({$_params},\$_smarty_tpl), true);?>";
}
} else {
$this->compiler->has_output = true;
if ($_smarty_tpl->caching) {
$_output .= "echo Smarty_Internal_Nocache_Insert::compile ('{$_function}',{$_params}, \$_smarty_tpl, '{$_filepath}');?>";
} else {
$_output .= "echo {$_function}({$_params},\$_smarty_tpl);?>";
}
}
return $_output;
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_compile_insert.php | PHP | asf20 | 5,020 |
<?php
/**
* Smarty Internal Plugin Compile Break
*
* Compiles the {break} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Break Class
*/
class Smarty_Internal_Compile_Break extends Smarty_Internal_CompileBase {
// attribute definitions
public $optional_attributes = array('levels');
public $shorttag_order = array('levels');
/**
* Compiles code for the {break} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
$this->smarty = $compiler->smarty;
// check and get attributes
$_attr = $this->_get_attributes($args);
if ($_attr['nocache'] === true) {
$this->compiler->trigger_template_error('nocache option not allowed', $this->compiler->lex->taglineno);
}
if (isset($_attr['levels'])) {
if (!is_numeric($_attr['levels'])) {
$this->compiler->trigger_template_error('level attribute must be a numeric constant', $this->compiler->lex->taglineno);
}
$_levels = $_attr['levels'];
} else {
$_levels = 1;
}
$level_count = $_levels;
$stack_count = count($compiler->_tag_stack) - 1;
while ($level_count > 0 && $stack_count >= 0) {
if (in_array($compiler->_tag_stack[$stack_count][0], array('for', 'foreach', 'while', 'section'))) {
$level_count--;
}
$stack_count--;
}
if ($level_count != 0) {
$this->compiler->trigger_template_error("cannot break {$_levels} level(s)", $this->compiler->lex->taglineno);
}
// this tag does not return compiled code
$this->compiler->has_code = true;
return "<?php break {$_levels}?>";
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_compile_break.php | PHP | asf20 | 2,137 |
<?php
/**
* Smarty Internal Plugin Compile Object Block Function
*
* Compiles code for registered objects as block function
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Object Block Function Class
*/
class Smarty_Internal_Compile_Private_Object_Block_Function extends Smarty_Internal_CompileBase {
// attribute definitions
public $required_attributes = array();
public $optional_attributes = array('_any');
/**
* Compiles code for the execution of block plugin
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @param string $tag name of block object
* @param string $methode name of methode to call
* @return string compiled code
*/
public function compile($args, $compiler, $parameter, $tag, $methode)
{
$this->compiler = $compiler;
if (strlen($tag) < 5 || substr($tag, -5) != 'close') {
// opening tag of block plugin
// check and get attributes
$_attr = $this->_get_attributes($args);
if ($_attr['nocache'] === true) {
$this->compiler->tag_nocache = true;
}
unset($_attr['nocache']);
// convert attributes into parameter array string
$_paramsArray = array();
foreach ($_attr as $_key => $_value) {
if (is_int($_key)) {
$_paramsArray[] = "$_key=>$_value";
} else {
$_paramsArray[] = "'$_key'=>$_value";
}
}
$_params = 'array(' . implode(",", $_paramsArray) . ')';
$this->_open_tag($tag . '->' . $methode, array($_params, $this->compiler->nocache));
// maybe nocache because of nocache variables or nocache plugin
$this->compiler->nocache = $this->compiler->nocache | $this->compiler->tag_nocache;
// compile code
$output = "<?php \$_smarty_tpl->smarty->_tag_stack[] = array('{$tag}->{$methode}', {$_params}); \$_block_repeat=true; \$_smarty_tpl->smarty->registered_objects['{$tag}'][0]->{$methode}({$_params}, null, \$_smarty_tpl, \$_block_repeat);while (\$_block_repeat) { ob_start();?>";
} else {
$base_tag = substr($tag, 0, -5);
// must endblock be nocache?
if ($this->compiler->nocache) {
$this->compiler->tag_nocache = true;
}
// closing tag of block plugin, restore nocache
list($_params, $this->compiler->nocache) = $this->_close_tag($base_tag . '->' . $methode);
// This tag does create output
$this->compiler->has_output = true;
// compile code
if (!isset($parameter['modifier_list'])) {
$mod_pre = $mod_post ='';
} else {
$mod_pre = ' ob_start(); ';
$mod_post = 'echo '.$this->compiler->compileTag('private_modifier',array(),array('modifierlist'=>$parameter['modifier_list'],'value'=>'ob_get_clean()')).';';
}
$output = "<?php \$_block_content = ob_get_contents(); ob_end_clean(); \$_block_repeat=false;".$mod_pre." echo \$_smarty_tpl->smarty->registered_objects['{$base_tag}'][0]->{$methode}({$_params}, \$_block_content, \$_smarty_tpl, \$_block_repeat); ".$mod_post." } array_pop(\$_smarty_tpl->smarty->_tag_stack);?>";
}
return $output."\n";
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_compile_private_object_block_function.php | PHP | asf20 | 3,562 |
<?php
/**
* Smarty Internal Plugin Register
*
* External Smarty methods register/unregister
*
* @package Smarty
* @author Uwe Tews
*/
/**
* Class for register/unregister methods
*/
class Smarty_Internal_Register {
function __construct($smarty)
{
$this->smarty = $smarty;
}
/**
* Registers plugin to be used in templates
*
* @param string $type plugin type
* @param string $tag name of template tag
* @param callback $callback PHP callback to register
* @param boolean $cacheable if true (default) this fuction is cachable
* @param array $cache_attr caching attributes if any
*/
public function registerPlugin($type, $tag, $callback, $cacheable = true, $cache_attr = null)
{
if (isset($this->smarty->registered_plugins[$type][$tag])) {
throw new Exception("Plugin tag \"{$tag}\" already registered");
} elseif (!is_callable($callback)) {
throw new Exception("Plugin \"{$tag}\" not callable");
} else {
$this->smarty->registered_plugins[$type][$tag] = array($callback, (bool) $cacheable);
if (isset($cache_attr)&&in_array($type, array(Smarty::PLUGIN_BLOCK, Smarty::PLUGIN_FUNCTION))) {
$this->smarty->registered_plugins[$type][$tag][] = (array) $cache_attr;
}
}
}
/**
* Unregister Plugin
*
* @param string $type of plugin
* @param string $tag name of plugin
*/
function unregisterPlugin($type, $tag)
{
if (isset($this->smarty->registered_plugins[$type][$tag])) {
unset($this->smarty->registered_plugins[$type][$tag]);
}
}
/**
* Registers a resource to fetch a template
*
* @param string $type name of resource type
* @param array $callback array of callbacks to handle resource
*/
public function registerResource($type, $callback)
{
$this->smarty->registered_resources[$type] = array($callback, false);
}
/**
* Unregisters a resource
*
* @param string $type name of resource type
*/
function unregisterResource($type)
{
if (isset($this->smarty->registered_resources[$type])) {
unset($this->smarty->registered_resources[$type]);
}
}
/**
* Registers object to be used in templates
*
* @param string $object name of template object
* @param object $ &$object_impl the referenced PHP object to register
* @param mixed $ null | array $allowed list of allowed methods (empty = all)
* @param boolean $smarty_args smarty argument format, else traditional
* @param mixed $ null | array $block_functs list of methods that are block format
*/
function registerObject($object_name, $object_impl, $allowed = array(), $smarty_args = true, $block_methods = array())
{
// test if allowed methodes callable
if (!empty($allowed)) {
foreach ((array)$allowed as $method) {
if (!is_callable(array($object_impl, $method))) {
throw new SmartyException("Undefined method '$method' in registered object");
}
}
}
// test if block methodes callable
if (!empty($block_methods)) {
foreach ((array)$block_methods as $method) {
if (!is_callable(array($object_impl, $method))) {
throw new SmartyException("Undefined method '$method' in registered object");
}
}
}
// register the object
$this->smarty->registered_objects[$object_name] =
array($object_impl, (array)$allowed, (boolean)$smarty_args, (array)$block_methods);
}
/**
* Registers static classes to be used in templates
*
* @param string $class name of template class
* @param string $class_impl the referenced PHP class to register
*/
function registerClass($class_name, $class_impl)
{
// test if exists
if (!class_exists($class_impl)) {
throw new SmartyException("Undefined class '$class_impl' in register template class");
}
// register the class
$this->smarty->registered_classes[$class_name] = $class_impl;
}
/**
* Registers a default plugin handler
*
* @param $callback mixed string | array $plugin class/methode name
*/
function registerDefaultPluginHandler($callback)
{
if (is_callable($callback)) {
$this->smarty->default_plugin_handler_func = $callback;
} else {
throw new SmartyException("Default plugin handler '$callback' not callable");
}
}
/**
* Registers a default template handler
*
* @param $callback mixed string | array class/method name
*/
function registerDefaultTemplateHandler($callback)
{
if (is_callable($callback)) {
$this->smarty->default_template_handler_func = $callback;
} else {
throw new SmartyException("Default template handler '$callback' not callable");
}
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_register.php | PHP | asf20 | 5,140 |
<?php
/**
* Smarty Internal Plugin Compile Function_Call
*
* Compiles the calls of user defined tags defined by {function}
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Function_Call Class
*/
class Smarty_Internal_Compile_Call extends Smarty_Internal_CompileBase {
// attribute definitions
public $required_attributes = array('name');
public $shorttag_order = array('name');
public $optional_attributes = array('_any');
/**
* Compiles the calls of user defined tags defined by {function}
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler)
{
$this->compiler = $compiler;
$this->smarty = $compiler->smarty;
// check and get attributes
$_attr = $this->_get_attributes($args);
// save possible attributes
if (isset($_attr['assign'])) {
// output will be stored in a smarty variable instead of beind displayed
$_assign = $_attr['assign'];
}
$_name = $_attr['name'];
unset($_attr['name'], $_attr['assign'], $_attr['nocache']);
// set flag (compiled code of {function} must be included in cache file
if ($compiler->nocache || $compiler->tag_nocache) {
$_nocache = 'true';
} else {
$_nocache = 'false';
}
$_paramsArray = array();
foreach ($_attr as $_key => $_value) {
if (is_int($_key)) {
$_paramsArray[] = "$_key=>$_value";
} else {
$_paramsArray[] = "'$_key'=>$_value";
}
}
if (isset($compiler->template->properties['function'][$_name]['parameter'])) {
foreach ($compiler->template->properties['function'][$_name]['parameter'] as $_key => $_value) {
if (!isset($_attr[$_key])) {
if (is_int($_key)) {
$_paramsArray[] = "$_key=>$_value";
} else {
$_paramsArray[] = "'$_key'=>$_value";
}
}
}
} elseif (isset($this->smarty->template_functions[$_name]['parameter'])) {
foreach ($this->smarty->template_functions[$_name]['parameter'] as $_key => $_value) {
if (!isset($_attr[$_key])) {
if (is_int($_key)) {
$_paramsArray[] = "$_key=>$_value";
} else {
$_paramsArray[] = "'$_key'=>$_value";
}
}
}
}
//varibale name?
if (!(strpos($_name,'$')===false)) {
$call_cache = $_name;
$call_function = '$tmp = "smarty_template_function_".'.$_name.'; $tmp';
} else {
$_name = trim($_name, "'\"");
$call_cache = "'{$_name}'";
$call_function = 'smarty_template_function_'.$_name;
}
$_params = 'array(' . implode(",", $_paramsArray) . ')';
$_hash = str_replace('-','_',$compiler->template->properties['nocache_hash']);
// was there an assign attribute
if (isset($_assign)) {
if ($compiler->template->caching) {
$_output = "<?php ob_start(); Smarty_Internal_Function_Call_Handler::call ({$call_cache},\$_smarty_tpl,{$_params},'{$_hash}',{$_nocache}); \$_smarty_tpl->assign({$_assign}, ob_get_clean());?>\n";
} else {
$_output = "<?php ob_start(); {$call_function}(\$_smarty_tpl,{$_params}); \$_smarty_tpl->assign({$_assign}, ob_get_clean());?>\n";
}
} else {
if ($compiler->template->caching) {
$_output = "<?php Smarty_Internal_Function_Call_Handler::call ({$call_cache},\$_smarty_tpl,{$_params},'{$_hash}',{$_nocache});?>\n";
} else {
$_output = "<?php {$call_function}(\$_smarty_tpl,{$_params});?>\n";
}
}
return $_output;
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_compile_call.php | PHP | asf20 | 4,213 |
<?php
/**
* Smarty Internal Plugin Compile Assign
*
* Compiles the {assign} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Assign Class
*/
class Smarty_Internal_Compile_Assign extends Smarty_Internal_CompileBase {
/**
* Compiles code for the {assign} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
$this->required_attributes = array('var', 'value');
$this->shorttag_order = array('var', 'value');
$this->optional_attributes = array('scope');
$_nocache = 'null';
$_scope = 'null';
// check and get attributes
$_attr = $this->_get_attributes($args);
// nocache ?
if ($this->compiler->tag_nocache || $this->compiler->nocache) {
$_nocache = 'true';
// create nocache var to make it know for further compiling
$compiler->template->tpl_vars[trim($_attr['var'], "'")] = new Smarty_variable(null, true);
}
// scope setup
if (isset($_attr['scope'])) {
$_attr['scope'] = trim($_attr['scope'], "'\"");
if ($_attr['scope'] == 'parent') {
$_scope = Smarty::SCOPE_PARENT;
} elseif ($_attr['scope'] == 'root') {
$_scope = Smarty::SCOPE_ROOT;
} elseif ($_attr['scope'] == 'global') {
$_scope = Smarty::SCOPE_GLOBAL;
} else {
$this->compiler->trigger_template_error('illegal value for "scope" attribute', $this->compiler->lex->taglineno);
}
}
// compiled output
if (isset($parameter['smarty_internal_index'])) {
return "<?php if (!isset(\$_smarty_tpl->tpl_vars[$_attr[var]]) || !is_array(\$_smarty_tpl->tpl_vars[$_attr[var]]->value)) \$_smarty_tpl->createLocalArrayVariable($_attr[var], $_nocache, $_scope);\n\$_smarty_tpl->tpl_vars[$_attr[var]]->value$parameter[smarty_internal_index] = $_attr[value];?>";
} else {
return "<?php \$_smarty_tpl->tpl_vars[$_attr[var]] = new Smarty_variable($_attr[value], $_nocache, $_scope);?>";
}
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_compile_assign.php | PHP | asf20 | 2,424 |
<?php
/**
* Smarty Internal Plugin Compile While
*
* Compiles the {while} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile While Class
*/
class Smarty_Internal_Compile_While extends Smarty_Internal_CompileBase {
/**
* Compiles code for the {while} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
// check and get attributes
$_attr = $this->_get_attributes($args);
$this->_open_tag('while', $this->compiler->nocache);
// maybe nocache because of nocache variables
$this->compiler->nocache = $this->compiler->nocache | $this->compiler->tag_nocache;
if (is_array($parameter['if condition'])) {
if ($this->compiler->nocache) {
$_nocache = ',true';
// create nocache var to make it know for further compiling
if (is_array($parameter['if condition']['var'])) {
$this->compiler->template->tpl_vars[trim($parameter['if condition']['var']['var'], "'")] = new Smarty_variable(null, true);
} else {
$this->compiler->template->tpl_vars[trim($parameter['if condition']['var'], "'")] = new Smarty_variable(null, true);
}
} else {
$_nocache = '';
$_nocache2 = '';
}
if (is_array($parameter['if condition']['var'])) {
$_output = "<?php if (!isset(\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']['var']."]) || !is_array(\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']['var']."]->value)) \$_smarty_tpl->createLocalArrayVariable(".$parameter['if condition']['var']['var']."$_nocache2);\n";
$_output .= "while (\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']['var']."]->value".$parameter['if condition']['var']['smarty_internal_index']." = ".$parameter['if condition']['value']."){?>";
} else {
$_output = "<?php \$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']."] = new Smarty_Variable(\$_smarty_tpl->getVariable(".$parameter['if condition']['var'].")->value{$_nocache},null,true,false);";
$_output .= "while (\$_smarty_tpl->tpl_vars[".$parameter['if condition']['var']."]->value = ".$parameter['if condition']['value']."){?>";
}
return $_output;
} else {
return "<?php while ({$parameter['if condition']}){?>";
}
}
}
/**
* Smarty Internal Plugin Compile Whileclose Class
*/
class Smarty_Internal_Compile_Whileclose extends Smarty_Internal_CompileBase {
/**
* Compiles code for the {/while} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @return string compiled code
*/
public function compile($args, $compiler)
{
$this->compiler = $compiler;
// must endblock be nocache?
if ($this->compiler->nocache) {
$this->compiler->tag_nocache = true;
}
$this->compiler->nocache = $this->_close_tag(array('while'));
return "<?php }?>";
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_compile_while.php | PHP | asf20 | 3,402 |
<?php
/**
* Smarty Internal Plugin Compile extend
*
* Compiles the {extends} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile extend Class
*/
class Smarty_Internal_Compile_Extends extends Smarty_Internal_CompileBase {
// attribute definitions
public $required_attributes = array('file');
public $shorttag_order = array('file');
/**
* Compiles code for the {extends} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @return string compiled code
*/
public function compile($args, $compiler)
{
$this->compiler = $compiler;
$this->smarty = $compiler->smarty;
$this->_rdl = preg_quote($this->smarty->right_delimiter);
$this->_ldl = preg_quote($this->smarty->left_delimiter);
$filepath = $compiler->template->getTemplateFilepath();
// check and get attributes
$_attr = $this->_get_attributes($args);
if ($_attr['nocache'] === true) {
$this->compiler->trigger_template_error('nocache option not allowed', $this->compiler->lex->taglineno);
}
$_smarty_tpl = $compiler->template;
$include_file = null;
if (strpos($_attr['file'],'$_tmp') !== false) {
$this->compiler->trigger_template_error('illegal value for file attribute', $this->compiler->lex->taglineno);
}
eval('$include_file = ' . $_attr['file'] . ';');
// create template object
$_template = new $compiler->smarty->template_class($include_file, $this->smarty, $compiler->template);
// save file dependency
if (in_array($_template->resource_type,array('eval','string'))) {
$template_sha1 = sha1($include_file);
} else {
$template_sha1 = sha1($_template->getTemplateFilepath());
}
if (isset($compiler->template->properties['file_dependency'][$template_sha1])) {
$this->compiler->trigger_template_error("illegal recursive call of \"{$include_file}\"",$compiler->lex->line-1);
}
$compiler->template->properties['file_dependency'][$template_sha1] = array($_template->getTemplateFilepath(), $_template->getTemplateTimestamp(),$_template->resource_type);
$_content = substr($compiler->template->template_source,$compiler->lex->counter-1);
if (preg_match_all("!({$this->_ldl}block\s(.+?){$this->_rdl})!", $_content, $s) !=
preg_match_all("!({$this->_ldl}/block{$this->_rdl})!", $_content, $c)) {
$this->compiler->trigger_template_error('unmatched {block} {/block} pairs');
}
preg_match_all("!{$this->_ldl}block\s(.+?){$this->_rdl}|{$this->_ldl}/block{$this->_rdl}!", $_content, $_result, PREG_OFFSET_CAPTURE);
$_result_count = count($_result[0]);
$_start = 0;
while ($_start < $_result_count) {
$_end = 0;
$_level = 1;
while ($_level != 0) {
$_end++;
if (!strpos($_result[0][$_start + $_end][0], '/')) {
$_level++;
} else {
$_level--;
}
}
$_block_content = str_replace($this->smarty->left_delimiter . '$smarty.block.parent' . $this->smarty->right_delimiter, '%%%%SMARTY_PARENT%%%%',
substr($_content, $_result[0][$_start][1] + strlen($_result[0][$_start][0]), $_result[0][$_start + $_end][1] - $_result[0][$_start][1] - + strlen($_result[0][$_start][0])));
Smarty_Internal_Compile_Block::saveBlockData($_block_content, $_result[0][$_start][0], $compiler->template, $filepath);
$_start = $_start + $_end + 1;
}
$compiler->template->template_source = $_template->getTemplateSource();
$compiler->template->template_filepath = $_template->getTemplateFilepath();
$compiler->abort_and_recompile = true;
return '';
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_compile_extends.php | PHP | asf20 | 4,005 |
<?php
/**
* Smarty Internal Plugin Templatelexer
*
* This is the lexer to break the template source into tokens
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Templatelexer
*/
class Smarty_Internal_Templatelexer
{
public $data;
public $counter;
public $token;
public $value;
public $node;
public $line;
public $taglineno;
public $state = 1;
public $strip = false;
private $heredoc_id_stack = Array();
public $smarty_token_names = array ( // Text for parser error messages
'IDENTITY' => '===',
'NONEIDENTITY' => '!==',
'EQUALS' => '==',
'NOTEQUALS' => '!=',
'GREATEREQUAL' => '(>=,ge)',
'LESSEQUAL' => '(<=,le)',
'GREATERTHAN' => '(>,gt)',
'LESSTHAN' => '(<,lt)',
'MOD' => '(%,mod)',
'NOT' => '(!,not)',
'LAND' => '(&&,and)',
'LOR' => '(||,or)',
'LXOR' => 'xor',
'OPENP' => '(',
'CLOSEP' => ')',
'OPENB' => '[',
'CLOSEB' => ']',
'PTR' => '->',
'APTR' => '=>',
'EQUAL' => '=',
'NUMBER' => 'number',
'UNIMATH' => '+" , "-',
'MATH' => '*" , "/" , "%',
'INCDEC' => '++" , "--',
'SPACE' => ' ',
'DOLLAR' => '$',
'SEMICOLON' => ';',
'COLON' => ':',
'DOUBLECOLON' => '::',
'AT' => '@',
'HATCH' => '#',
'QUOTE' => '"',
'BACKTICK' => '`',
'VERT' => '|',
'DOT' => '.',
'COMMA' => '","',
'ANDSYM' => '"&"',
'QMARK' => '"?"',
'ID' => 'identifier',
'OTHER' => 'text',
'LINEBREAK' => 'newline',
'FAKEPHPSTARTTAG' => 'Fake PHP start tag',
'PHPSTARTTAG' => 'PHP start tag',
'PHPENDTAG' => 'PHP end tag',
'LITERALSTART' => 'Literal start',
'LITERALEND' => 'Literal end',
'LDELSLASH' => 'closing tag',
'COMMENT' => 'comment',
'LITERALEND' => 'literal close',
'AS' => 'as',
'TO' => 'to',
);
function __construct($data,$compiler)
{
// set instance object
self::instance($this);
// $this->data = preg_replace("/(\r\n|\r|\n)/", "\n", $data);
$this->data = $data;
$this->counter = 0;
$this->line = 1;
$this->smarty = $compiler->smarty;
$this->compiler = $compiler;
$this->ldel = preg_quote($this->smarty->left_delimiter,'/');
$this->ldel_length = strlen($this->smarty->left_delimiter);
$this->rdel = preg_quote($this->smarty->right_delimiter,'/');
$this->smarty_token_names['LDEL'] = $this->smarty->left_delimiter;
$this->smarty_token_names['RDEL'] = $this->smarty->right_delimiter;
}
public static function &instance($new_instance = null)
{
static $instance = null;
if (isset($new_instance) && is_object($new_instance))
$instance = $new_instance;
return $instance;
}
private $_yy_state = 1;
private $_yy_stack = array();
function yylex()
{
return $this->{'yylex' . $this->_yy_state}();
}
function yypushstate($state)
{
array_push($this->_yy_stack, $this->_yy_state);
$this->_yy_state = $state;
}
function yypopstate()
{
$this->_yy_state = array_pop($this->_yy_stack);
}
function yybegin($state)
{
$this->_yy_state = $state;
}
function yylex1()
{
$tokenMap = array (
1 => 0,
2 => 0,
3 => 1,
5 => 0,
6 => 0,
7 => 0,
8 => 0,
9 => 0,
10 => 0,
11 => 0,
12 => 1,
14 => 0,
15 => 0,
16 => 0,
17 => 0,
18 => 0,
19 => 0,
20 => 0,
21 => 0,
22 => 0,
23 => 2,
26 => 0,
);
if ($this->counter >= strlen($this->data)) {
return false; // end of input
}
$yy_global_pattern = "/^(".$this->ldel."[$]smarty\\.block\\.child".$this->rdel.")|^(\\{\\})|^(".$this->ldel."\\*([\S\s]*?)\\*".$this->rdel.")|^([\t ]*[\r\n]+[\t ]*)|^(".$this->ldel."strip".$this->rdel.")|^(".$this->ldel."\\s{1,}strip\\s{1,}".$this->rdel.")|^(".$this->ldel."\/strip".$this->rdel.")|^(".$this->ldel."\\s{1,}\/strip\\s{1,}".$this->rdel.")|^(".$this->ldel."\\s*literal\\s*".$this->rdel.")|^(".$this->ldel."\\s{1,}\/)|^(".$this->ldel."\\s*(if|elseif|else if|while)(?![^\s]))|^(".$this->ldel."\\s*for(?![^\s]))|^(".$this->ldel."\\s*foreach(?![^\s]))|^(".$this->ldel."\\s{1,})|^(".$this->ldel."\/)|^(".$this->ldel.")|^(<\\?(?:php\\w+|=|[a-zA-Z]+)?)|^(\\?>)|^(<%)|^(%>)|^(([\S\s]*?)(?=([\t ]*[\r\n]+[\t ]*|".$this->ldel."|<\\?|\\?>|<%|%>)))|^([\S\s]+)/";
do {
if (preg_match($yy_global_pattern, substr($this->data, $this->counter), $yymatches)) {
$yysubmatches = $yymatches;
$yymatches = array_filter($yymatches, 'strlen'); // remove empty sub-patterns
if (!count($yymatches)) {
throw new Exception('Error: lexing failed because a rule matched' .
'an empty string. Input "' . substr($this->data,
$this->counter, 5) . '... state TEXT');
}
next($yymatches); // skip global match
$this->token = key($yymatches); // token number
if ($tokenMap[$this->token]) {
// extract sub-patterns for passing to lex function
$yysubmatches = array_slice($yysubmatches, $this->token + 1,
$tokenMap[$this->token]);
} else {
$yysubmatches = array();
}
$this->value = current($yymatches); // token value
$r = $this->{'yy_r1_' . $this->token}($yysubmatches);
if ($r === null) {
$this->counter += strlen($this->value);
$this->line += substr_count($this->value, "\n");
// accept this token
return true;
} elseif ($r === true) {
// we have changed state
// process this token in the new state
return $this->yylex();
} elseif ($r === false) {
$this->counter += strlen($this->value);
$this->line += substr_count($this->value, "\n");
if ($this->counter >= strlen($this->data)) {
return false; // end of input
}
// skip this token
continue;
} } else {
throw new Exception('Unexpected input at line' . $this->line .
': ' . $this->data[$this->counter]);
}
break;
} while (true);
} // end function
const TEXT = 1;
function yy_r1_1($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_SMARTYBLOCKCHILD;
}
function yy_r1_2($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
}
function yy_r1_3($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_COMMENT;
}
function yy_r1_5($yy_subpatterns)
{
if ($this->strip) {
return false;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LINEBREAK;
}
}
function yy_r1_6($yy_subpatterns)
{
$this->strip = true;
return false;
}
function yy_r1_7($yy_subpatterns)
{
if ($this->smarty->auto_literal) {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->strip = true;
return false;
}
}
function yy_r1_8($yy_subpatterns)
{
$this->strip = false;
return false;
}
function yy_r1_9($yy_subpatterns)
{
if ($this->smarty->auto_literal) {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->strip = false;
return false;
}
}
function yy_r1_10($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LITERALSTART;
$this->yypushstate(self::LITERAL);
}
function yy_r1_11($yy_subpatterns)
{
if ($this->smarty->auto_literal) {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDELSLASH;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r1_12($yy_subpatterns)
{
if ($this->smarty->auto_literal && trim(substr($this->value,$this->ldel_length,1)) == '') {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDELIF;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r1_14($yy_subpatterns)
{
if ($this->smarty->auto_literal && trim(substr($this->value,$this->ldel_length,1)) == '') {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDELFOR;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r1_15($yy_subpatterns)
{
if ($this->smarty->auto_literal && trim(substr($this->value,$this->ldel_length,1)) == '') {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDELFOREACH;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r1_16($yy_subpatterns)
{
if ($this->smarty->auto_literal) {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDEL;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r1_17($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LDELSLASH;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
function yy_r1_18($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LDEL;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
function yy_r1_19($yy_subpatterns)
{
if (in_array($this->value, Array('<?', '<?=', '<?php'))) {
$this->token = Smarty_Internal_Templateparser::TP_PHPSTARTTAG;
} elseif ($this->value == '<?xml') {
$this->token = Smarty_Internal_Templateparser::TP_XMLTAG;
} else {
$this->token = Smarty_Internal_Templateparser::TP_FAKEPHPSTARTTAG;
$this->value = substr($this->value, 0, 2);
}
}
function yy_r1_20($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_PHPENDTAG;
}
function yy_r1_21($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ASPSTARTTAG;
}
function yy_r1_22($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ASPENDTAG;
}
function yy_r1_23($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
}
function yy_r1_26($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
}
function yylex2()
{
$tokenMap = array (
1 => 0,
2 => 0,
3 => 1,
5 => 0,
6 => 0,
7 => 0,
8 => 0,
9 => 0,
10 => 0,
11 => 0,
12 => 0,
13 => 1,
15 => 1,
17 => 1,
19 => 0,
20 => 0,
21 => 0,
22 => 1,
24 => 1,
26 => 1,
28 => 1,
30 => 1,
32 => 1,
34 => 1,
36 => 1,
38 => 1,
40 => 1,
42 => 1,
44 => 0,
45 => 0,
46 => 0,
47 => 0,
48 => 0,
49 => 0,
50 => 0,
51 => 0,
52 => 0,
53 => 0,
54 => 3,
58 => 0,
59 => 0,
60 => 0,
61 => 0,
62 => 0,
63 => 0,
64 => 0,
65 => 0,
66 => 1,
68 => 1,
70 => 0,
71 => 0,
72 => 0,
73 => 0,
74 => 0,
75 => 0,
76 => 0,
77 => 0,
78 => 0,
79 => 0,
80 => 0,
81 => 0,
82 => 0,
83 => 0,
84 => 0,
85 => 0,
86 => 0,
87 => 0,
);
if ($this->counter >= strlen($this->data)) {
return false; // end of input
}
$yy_global_pattern = "/^('[^'\\\\]*(?:\\\\.[^'\\\\]*)*')|^(".$this->ldel."\\s{1,}\/)|^(".$this->ldel."\\s*(if|elseif|else if|while)(?![^\s]))|^(".$this->ldel."\\s*for(?![^\s]))|^(".$this->ldel."\\s*foreach(?![^\s]))|^(".$this->ldel."\\s{1,})|^(\\s{1,}".$this->rdel.")|^(".$this->ldel."\/)|^(".$this->ldel.")|^(".$this->rdel.")|^(\\s+is\\s+in\\s+)|^(\\s+(AS|as)\\s+)|^(\\s+(to)\\s+)|^(\\s+(step)\\s+)|^(\\s+instanceof\\s+)|^(\\s*===\\s*)|^(\\s*!==\\s*)|^(\\s*==\\s*|\\s+(EQ|eq)\\s+)|^(\\s*!=\\s*|\\s*<>\\s*|\\s+(NE|NEQ|ne|neq)\\s+)|^(\\s*>=\\s*|\\s+(GE|GTE|ge|gte)\\s+)|^(\\s*<=\\s*|\\s+(LE|LTE|le|lte)\\s+)|^(\\s*>\\s*|\\s+(GT|gt)\\s+)|^(\\s*<\\s*|\\s+(LT|lt)\\s+)|^(\\s+(MOD|mod)\\s+)|^(!\\s*|(NOT|not)\\s+)|^(\\s*&&\\s*|\\s*(AND|and)\\s+)|^(\\s*\\|\\|\\s*|\\s*(OR|or)\\s+)|^(\\s*(XOR|xor)\\s+)|^(\\s+is\\s+odd\\s+by\\s+)|^(\\s+is\\s+not\\s+odd\\s+by\\s+)|^(\\s+is\\s+odd)|^(\\s+is\\s+not\\s+odd)|^(\\s+is\\s+even\\s+by\\s+)|^(\\s+is\\s+not\\s+even\\s+by\\s+)|^(\\s+is\\s+even)|^(\\s+is\\s+not\\s+even)|^(\\s+is\\s+div\\s+by\\s+)|^(\\s+is\\s+not\\s+div\\s+by\\s+)|^(\\((int(eger)?|bool(ean)?|float|double|real|string|binary|array|object)\\)\\s*)|^(\\(\\s*)|^(\\s*\\))|^(\\[\\s*)|^(\\s*\\])|^(\\s*->\\s*)|^(\\s*=>\\s*)|^(\\s*=\\s*)|^(\\+\\+|--)|^(\\s*(\\+|-)\\s*)|^(\\s*(\\*|\/|%)\\s*)|^(\\$)|^(\\s*;)|^(::)|^(\\s*:\\s*)|^(@)|^(#)|^(\")|^(`)|^(\\|)|^(\\.)|^(\\s*,\\s*)|^(\\s*&\\s*)|^(\\s*\\?\\s*)|^(0[xX][0-9a-fA-F]+)|^([0-9]*[a-zA-Z_]\\w*)|^(\\d+)|^(\\s+)|^(.)/";
do {
if (preg_match($yy_global_pattern, substr($this->data, $this->counter), $yymatches)) {
$yysubmatches = $yymatches;
$yymatches = array_filter($yymatches, 'strlen'); // remove empty sub-patterns
if (!count($yymatches)) {
throw new Exception('Error: lexing failed because a rule matched' .
'an empty string. Input "' . substr($this->data,
$this->counter, 5) . '... state SMARTY');
}
next($yymatches); // skip global match
$this->token = key($yymatches); // token number
if ($tokenMap[$this->token]) {
// extract sub-patterns for passing to lex function
$yysubmatches = array_slice($yysubmatches, $this->token + 1,
$tokenMap[$this->token]);
} else {
$yysubmatches = array();
}
$this->value = current($yymatches); // token value
$r = $this->{'yy_r2_' . $this->token}($yysubmatches);
if ($r === null) {
$this->counter += strlen($this->value);
$this->line += substr_count($this->value, "\n");
// accept this token
return true;
} elseif ($r === true) {
// we have changed state
// process this token in the new state
return $this->yylex();
} elseif ($r === false) {
$this->counter += strlen($this->value);
$this->line += substr_count($this->value, "\n");
if ($this->counter >= strlen($this->data)) {
return false; // end of input
}
// skip this token
continue;
} } else {
throw new Exception('Unexpected input at line' . $this->line .
': ' . $this->data[$this->counter]);
}
break;
} while (true);
} // end function
const SMARTY = 2;
function yy_r2_1($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_SINGLEQUOTESTRING;
}
function yy_r2_2($yy_subpatterns)
{
if ($this->smarty->auto_literal) {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDELSLASH;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r2_3($yy_subpatterns)
{
if ($this->smarty->auto_literal && trim(substr($this->value,$this->ldel_length,1)) == '') {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDELIF;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r2_5($yy_subpatterns)
{
if ($this->smarty->auto_literal && trim(substr($this->value,$this->ldel_length,1)) == '') {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDELFOR;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r2_6($yy_subpatterns)
{
if ($this->smarty->auto_literal && trim(substr($this->value,$this->ldel_length,1)) == '') {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDELFOREACH;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r2_7($yy_subpatterns)
{
if ($this->smarty->auto_literal) {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDEL;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r2_8($yy_subpatterns)
{
if ($this->smarty->auto_literal) {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_RDEL;
$this->yypopstate();
}
}
function yy_r2_9($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LDELSLASH;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
function yy_r2_10($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LDEL;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
function yy_r2_11($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_RDEL;
$this->yypopstate();
}
function yy_r2_12($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ISIN;
}
function yy_r2_13($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_AS;
}
function yy_r2_15($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_TO;
}
function yy_r2_17($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_STEP;
}
function yy_r2_19($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_INSTANCEOF;
}
function yy_r2_20($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_IDENTITY;
}
function yy_r2_21($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_NONEIDENTITY;
}
function yy_r2_22($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_EQUALS;
}
function yy_r2_24($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_NOTEQUALS;
}
function yy_r2_26($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_GREATEREQUAL;
}
function yy_r2_28($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LESSEQUAL;
}
function yy_r2_30($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_GREATERTHAN;
}
function yy_r2_32($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LESSTHAN;
}
function yy_r2_34($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_MOD;
}
function yy_r2_36($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_NOT;
}
function yy_r2_38($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LAND;
}
function yy_r2_40($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LOR;
}
function yy_r2_42($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LXOR;
}
function yy_r2_44($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ISODDBY;
}
function yy_r2_45($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ISNOTODDBY;
}
function yy_r2_46($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ISODD;
}
function yy_r2_47($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ISNOTODD;
}
function yy_r2_48($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ISEVENBY;
}
function yy_r2_49($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ISNOTEVENBY;
}
function yy_r2_50($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ISEVEN;
}
function yy_r2_51($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ISNOTEVEN;
}
function yy_r2_52($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ISDIVBY;
}
function yy_r2_53($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ISNOTDIVBY;
}
function yy_r2_54($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_TYPECAST;
}
function yy_r2_58($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_OPENP;
}
function yy_r2_59($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_CLOSEP;
}
function yy_r2_60($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_OPENB;
}
function yy_r2_61($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_CLOSEB;
}
function yy_r2_62($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_PTR;
}
function yy_r2_63($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_APTR;
}
function yy_r2_64($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_EQUAL;
}
function yy_r2_65($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_INCDEC;
}
function yy_r2_66($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_UNIMATH;
}
function yy_r2_68($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_MATH;
}
function yy_r2_70($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_DOLLAR;
}
function yy_r2_71($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_SEMICOLON;
}
function yy_r2_72($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_DOUBLECOLON;
}
function yy_r2_73($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_COLON;
}
function yy_r2_74($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_AT;
}
function yy_r2_75($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_HATCH;
}
function yy_r2_76($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_QUOTE;
$this->yypushstate(self::DOUBLEQUOTEDSTRING);
}
function yy_r2_77($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_BACKTICK;
$this->yypopstate();
}
function yy_r2_78($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_VERT;
}
function yy_r2_79($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_DOT;
}
function yy_r2_80($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_COMMA;
}
function yy_r2_81($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ANDSYM;
}
function yy_r2_82($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_QMARK;
}
function yy_r2_83($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_HEX;
}
function yy_r2_84($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ID;
}
function yy_r2_85($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_INTEGER;
}
function yy_r2_86($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_SPACE;
}
function yy_r2_87($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
}
function yylex3()
{
$tokenMap = array (
1 => 0,
2 => 0,
3 => 0,
4 => 0,
5 => 0,
6 => 0,
7 => 0,
8 => 2,
11 => 0,
);
if ($this->counter >= strlen($this->data)) {
return false; // end of input
}
$yy_global_pattern = "/^(".$this->ldel."\\s*literal\\s*".$this->rdel.")|^(".$this->ldel."\\s*\/literal\\s*".$this->rdel.")|^([\t ]*[\r\n]+[\t ]*)|^(<\\?(?:php\\w+|=|[a-zA-Z]+)?)|^(\\?>)|^(<%)|^(%>)|^(([\S\s]*?)(?=([\t ]*[\r\n]+[\t ]*|".$this->ldel."\/?literal".$this->rdel."|<\\?|<%)))|^([\S\s]+)/";
do {
if (preg_match($yy_global_pattern, substr($this->data, $this->counter), $yymatches)) {
$yysubmatches = $yymatches;
$yymatches = array_filter($yymatches, 'strlen'); // remove empty sub-patterns
if (!count($yymatches)) {
throw new Exception('Error: lexing failed because a rule matched' .
'an empty string. Input "' . substr($this->data,
$this->counter, 5) . '... state LITERAL');
}
next($yymatches); // skip global match
$this->token = key($yymatches); // token number
if ($tokenMap[$this->token]) {
// extract sub-patterns for passing to lex function
$yysubmatches = array_slice($yysubmatches, $this->token + 1,
$tokenMap[$this->token]);
} else {
$yysubmatches = array();
}
$this->value = current($yymatches); // token value
$r = $this->{'yy_r3_' . $this->token}($yysubmatches);
if ($r === null) {
$this->counter += strlen($this->value);
$this->line += substr_count($this->value, "\n");
// accept this token
return true;
} elseif ($r === true) {
// we have changed state
// process this token in the new state
return $this->yylex();
} elseif ($r === false) {
$this->counter += strlen($this->value);
$this->line += substr_count($this->value, "\n");
if ($this->counter >= strlen($this->data)) {
return false; // end of input
}
// skip this token
continue;
} } else {
throw new Exception('Unexpected input at line' . $this->line .
': ' . $this->data[$this->counter]);
}
break;
} while (true);
} // end function
const LITERAL = 3;
function yy_r3_1($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LITERALSTART;
$this->yypushstate(self::LITERAL);
}
function yy_r3_2($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LITERALEND;
$this->yypopstate();
}
function yy_r3_3($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LITERAL;
}
function yy_r3_4($yy_subpatterns)
{
if (in_array($this->value, Array('<?', '<?=', '<?php'))) {
$this->token = Smarty_Internal_Templateparser::TP_PHPSTARTTAG;
} else {
$this->token = Smarty_Internal_Templateparser::TP_FAKEPHPSTARTTAG;
$this->value = substr($this->value, 0, 2);
}
}
function yy_r3_5($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_PHPENDTAG;
}
function yy_r3_6($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ASPSTARTTAG;
}
function yy_r3_7($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_ASPENDTAG;
}
function yy_r3_8($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LITERAL;
}
function yy_r3_11($yy_subpatterns)
{
$this->compiler->trigger_template_error ("missing or misspelled literal closing tag");
}
function yylex4()
{
$tokenMap = array (
1 => 0,
2 => 1,
4 => 0,
5 => 0,
6 => 0,
7 => 0,
8 => 0,
9 => 0,
10 => 0,
11 => 0,
12 => 0,
13 => 3,
17 => 0,
);
if ($this->counter >= strlen($this->data)) {
return false; // end of input
}
$yy_global_pattern = "/^(".$this->ldel."\\s{1,}\/)|^(".$this->ldel."\\s*(if|elseif|else if|while)(?![^\s]))|^(".$this->ldel."\\s*for(?![^\s]))|^(".$this->ldel."\\s*foreach(?![^\s]))|^(".$this->ldel."\\s{1,})|^(".$this->ldel."\/)|^(".$this->ldel.")|^(\")|^(`\\$)|^(\\$[0-9]*[a-zA-Z_]\\w*)|^(\\$)|^(([^\"\\\\]*?)((?:\\\\.[^\"\\\\]*?)*?)(?=(".$this->ldel."|\\$|`\\$|\")))|^([\S\s]+)/";
do {
if (preg_match($yy_global_pattern, substr($this->data, $this->counter), $yymatches)) {
$yysubmatches = $yymatches;
$yymatches = array_filter($yymatches, 'strlen'); // remove empty sub-patterns
if (!count($yymatches)) {
throw new Exception('Error: lexing failed because a rule matched' .
'an empty string. Input "' . substr($this->data,
$this->counter, 5) . '... state DOUBLEQUOTEDSTRING');
}
next($yymatches); // skip global match
$this->token = key($yymatches); // token number
if ($tokenMap[$this->token]) {
// extract sub-patterns for passing to lex function
$yysubmatches = array_slice($yysubmatches, $this->token + 1,
$tokenMap[$this->token]);
} else {
$yysubmatches = array();
}
$this->value = current($yymatches); // token value
$r = $this->{'yy_r4_' . $this->token}($yysubmatches);
if ($r === null) {
$this->counter += strlen($this->value);
$this->line += substr_count($this->value, "\n");
// accept this token
return true;
} elseif ($r === true) {
// we have changed state
// process this token in the new state
return $this->yylex();
} elseif ($r === false) {
$this->counter += strlen($this->value);
$this->line += substr_count($this->value, "\n");
if ($this->counter >= strlen($this->data)) {
return false; // end of input
}
// skip this token
continue;
} } else {
throw new Exception('Unexpected input at line' . $this->line .
': ' . $this->data[$this->counter]);
}
break;
} while (true);
} // end function
const DOUBLEQUOTEDSTRING = 4;
function yy_r4_1($yy_subpatterns)
{
if ($this->smarty->auto_literal) {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDELSLASH;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r4_2($yy_subpatterns)
{
if ($this->smarty->auto_literal && trim(substr($this->value,$this->ldel_length,1)) == '') {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDELIF;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r4_4($yy_subpatterns)
{
if ($this->smarty->auto_literal && trim(substr($this->value,$this->ldel_length,1)) == '') {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDELFOR;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r4_5($yy_subpatterns)
{
if ($this->smarty->auto_literal && trim(substr($this->value,$this->ldel_length,1)) == '') {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDELFOREACH;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r4_6($yy_subpatterns)
{
if ($this->smarty->auto_literal) {
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
} else {
$this->token = Smarty_Internal_Templateparser::TP_LDEL;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
}
function yy_r4_7($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LDELSLASH;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
function yy_r4_8($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_LDEL;
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
function yy_r4_9($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_QUOTE;
$this->yypopstate();
}
function yy_r4_10($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_BACKTICK;
$this->value = substr($this->value,0,-1);
$this->yypushstate(self::SMARTY);
$this->taglineno = $this->line;
}
function yy_r4_11($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_DOLLARID;
}
function yy_r4_12($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
}
function yy_r4_13($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
}
function yy_r4_17($yy_subpatterns)
{
$this->token = Smarty_Internal_Templateparser::TP_OTHER;
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_templatelexer.php | PHP | asf20 | 36,196 |
<?php
/**
* Project: Smarty: the PHP compiling template engine
* File: smarty_internal_wrapper.php
* SVN: $Id: $
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For questions, help, comments, discussion, etc., please join the
* Smarty mailing list. Send a blank e-mail to
* smarty-discussion-subscribe@googlegroups.com
*
* @link http://www.smarty.net/
* @copyright 2008 New Digital Group, Inc.
* @author Monte Ohrt <monte at ohrt dot com>
* @author Uwe Tews
* @package Smarty
* @subpackage PluginsInternal
* @version 3-SVN$Rev: 3286 $
*/
/*
* Smarty Backward Compatability Wrapper
*/
class Smarty_Internal_Wrapper {
protected $smarty;
function __construct($smarty) {
$this->smarty = $smarty;
}
/**
* Converts smarty2-style function call to smarty 3-style function call
* This is expensive, be sure to port your code to Smarty 3!
*
* @param string $name Smarty 2 function name
* @param array $args Smarty 2 function args
*/
function convert($name, $args) {
// throw notice about deprecated function
if($this->smarty->deprecation_notices)
trigger_error("function call '$name' is unknown or deprecated.",E_USER_NOTICE);
// get first and last part of function name
$name_parts = explode('_',$name,2);
switch($name_parts[0]) {
case 'register':
case 'unregister':
switch($name_parts[1]) {
case 'object':
return call_user_func_array(array($this->smarty,"{$name_parts[0]}Object"),$args);
case 'compiler_function':
return call_user_func_array(array($this->smarty,"{$name_parts[0]}Plugin"),array_merge(array('compiler'),$args));
case 'prefilter':
return call_user_func_array(array($this->smarty,"{$name_parts[0]}Filter"),array_merge(array('pre'),$args));
case 'postfilter':
return call_user_func_array(array($this->smarty,"{$name_parts[0]}Filter"),array_merge(array('post'),$args));
case 'outputfilter':
return call_user_func_array(array($this->smarty,"{$name_parts[0]}Filter"),array_merge(array('output'),$args));
case 'resource':
return call_user_func_array(array($this->smarty,"{$name_parts[0]}Resource"),$args);
default:
return call_user_func_array(array($this->smarty,"{$name_parts[0]}Plugin"),array_merge(array($name_parts[1]),$args));
}
case 'get':
switch($name_parts[1]) {
case 'template_vars':
return call_user_func_array(array($this->smarty,'getTemplateVars'),$args);
case 'config_vars':
return call_user_func_array(array($this->smarty,'getConfigVars'),$args);
default:
return call_user_func_array(array($myobj,$name_parts[1]),$args);
}
case 'clear':
switch($name_parts[1]) {
case 'all_assign':
return call_user_func_array(array($this->smarty,'clearAllAssign'),$args);
case 'assign':
return call_user_func_array(array($this->smarty,'clearAssign'),$args);
case 'all_cache':
return call_user_func_array(array($this->smarty,'clearAllCache'),$args);
case 'cache':
return call_user_func_array(array($this->smarty,'clearCache'),$args);
case 'compiled_template':
return call_user_func_array(array($this->smarty,'clearCompiledTemplate'),$args);
}
case 'config':
switch($name_parts[1]) {
case 'load':
return call_user_func_array(array($this->smarty,'configLoad'),$args);
}
case 'trigger':
switch($name_parts[1]) {
case 'error':
return call_user_func_array('trigger_error',$args);
}
case 'load':
switch($name_parts[1]) {
case 'filter':
return call_user_func_array(array($this->smarty,'loadFilter'),$args);
}
}
throw new SmartyException("unknown method '$name'");
}
/**
* trigger Smarty error
*
* @param string $error_msg
* @param integer $error_type
*/
function trigger_error($error_msg, $error_type = E_USER_WARNING)
{
trigger_error("Smarty error: $error_msg", $error_type);
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_wrapper.php | PHP | asf20 | 5,254 |
<?php
/**
* Smarty Internal Plugin Config
*
* Main class for config variables
*
* @ignore
* @package Smarty
* @subpackage Config
* @author Uwe Tews
*/
class Smarty_Internal_Config {
static $config_objects = array();
public function __construct($config_resource, $smarty, $data = null)
{
$this->data = $data;
$this->smarty = $smarty;
$this->config_resource = $config_resource;
$this->config_resource_type = null;
$this->config_resource_name = null;
$this->config_filepath = null;
$this->config_timestamp = null;
$this->config_source = null;
$this->compiled_config = null;
$this->compiled_filepath = null;
$this->compiled_timestamp = null;
$this->mustCompile = null;
$this->compiler_object = null;
// parse config resource name
if (!$this->parseConfigResourceName ($config_resource)) {
throw new SmartyException ("Unable to parse config resource '{$config_resource}'");
}
}
public function getConfigFilepath ()
{
return $this->config_filepath === null ?
$this->config_filepath = $this->buildConfigFilepath() :
$this->config_filepath;
}
public function getTimestamp ()
{
return $this->config_timestamp === null ?
$this->config_timestamp = filemtime($this->getConfigFilepath()) :
$this->config_timestamp;
}
private function parseConfigResourceName($config_resource)
{
if (empty($config_resource))
return false;
if (strpos($config_resource, ':') === false) {
// no resource given, use default
$this->config_resource_type = $this->smarty->default_config_type;
$this->config_resource_name = $config_resource;
} else {
// get type and name from path
list($this->config_resource_type, $this->config_resource_name) = explode(':', $config_resource, 2);
if (strlen($this->config_resource_type) == 1) {
// 1 char is not resource type, but part of filepath
$this->config_resource_type = $this->smarty->default_config_type;
$this->config_resource_name = $config_resource;
} else {
$this->config_resource_type = strtolower($this->config_resource_type);
}
}
return true;
}
/*
* get system filepath to config
*/
public function buildConfigFilepath ()
{
foreach((array)$this->smarty->config_dir as $_config_dir) {
if (strpos('/\\', substr($_config_dir, -1)) === false) {
$_config_dir .= DS;
}
$_filepath = $_config_dir . $this->config_resource_name;
if (file_exists($_filepath))
return $_filepath;
}
// check for absolute path
if (file_exists($this->config_resource_name))
return $this->config_resource_name;
// no tpl file found
throw new SmartyException("Unable to load config file \"{$this->config_resource_name}\"");
return false;
}
/**
* Read config file source
*
* @return string content of source file
*/
/**
* Returns the template source code
*
* The template source is being read by the actual resource handler
*
* @return string the template source
*/
public function getConfigSource ()
{
if ($this->config_source === null) {
if ($this->readConfigSource($this) === false) {
throw new SmartyException("Unable to load config file \"{$this->config_resource_name}\"");
}
}
return $this->config_source;
}
public function readConfigSource()
{
// read source file
if (file_exists($this->getConfigFilepath())) {
$this->config_source = file_get_contents($this->getConfigFilepath());
return true;
} else {
return false;
}
}
/**
* Returns the compiled filepath
*
* @return string the compiled filepath
*/
public function getCompiledFilepath ()
{
return $this->compiled_filepath === null ?
($this->compiled_filepath = $this->buildCompiledFilepath()) :
$this->compiled_filepath;
}
public function buildCompiledFilepath()
{
$_compile_id = isset($this->smarty->compile_id) ? preg_replace('![^\w\|]+!', '_', $this->smarty->compile_id) : null;
$_flag = (int)$this->smarty->config_read_hidden + (int)$this->smarty->config_booleanize * 2 +
(int)$this->smarty->config_overwrite * 4;
$_filepath = sha1($this->config_resource_name . $_flag);
// if use_sub_dirs, break file into directories
if ($this->smarty->use_sub_dirs) {
$_filepath = substr($_filepath, 0, 2) . DS
. substr($_filepath, 2, 2) . DS
. substr($_filepath, 4, 2) . DS
. $_filepath;
}
$_compile_dir_sep = $this->smarty->use_sub_dirs ? DS : '^';
if (isset($_compile_id)) {
$_filepath = $_compile_id . $_compile_dir_sep . $_filepath;
}
$_compile_dir = $this->smarty->compile_dir;
if (substr($_compile_dir, -1) != DS) {
$_compile_dir .= DS;
}
return $_compile_dir . $_filepath . '.' . basename($this->config_resource_name) . '.config' . '.php';
}
/**
* Returns the timpestamp of the compiled file
*
* @return integer the file timestamp
*/
public function getCompiledTimestamp ()
{
return $this->compiled_timestamp === null ?
($this->compiled_timestamp = (file_exists($this->getCompiledFilepath())) ? filemtime($this->getCompiledFilepath()) : false) :
$this->compiled_timestamp;
}
/**
* Returns if the current config file must be compiled
*
* It does compare the timestamps of config source and the compiled config and checks the force compile configuration
*
* @return boolean true if the file must be compiled
*/
public function mustCompile ()
{
return $this->mustCompile === null ?
$this->mustCompile = ($this->smarty->force_compile || $this->getCompiledTimestamp () === false || $this->smarty->compile_check && $this->getCompiledTimestamp () < $this->getTimestamp ()):
$this->mustCompile;
}
/**
* Returns the compiled config file
*
* It checks if the config file must be compiled or just read the compiled version
*
* @return string the compiled config file
*/
public function getCompiledConfig ()
{
if ($this->compiled_config === null) {
// see if template needs compiling.
if ($this->mustCompile()) {
$this->compileConfigSource();
} else {
$this->compiled_config = file_get_contents($this->getCompiledFilepath());
}
}
return $this->compiled_config;
}
/**
* Compiles the config files
*/
public function compileConfigSource ()
{
// compile template
if (!is_object($this->compiler_object)) {
// load compiler
$this->compiler_object = new Smarty_Internal_Config_File_Compiler($this->smarty);
}
// compile locking
if ($this->smarty->compile_locking) {
if ($saved_timestamp = $this->getCompiledTimestamp()) {
touch($this->getCompiledFilepath());
}
}
// call compiler
try {
$this->compiler_object->compileSource($this);
}
catch (Exception $e) {
// restore old timestamp in case of error
if ($this->smarty->compile_locking && $saved_timestamp) {
touch($this->getCompiledFilepath(), $saved_timestamp);
}
throw $e;
}
// compiling succeded
// write compiled template
Smarty_Internal_Write_File::writeFile($this->getCompiledFilepath(), $this->getCompiledConfig(), $this->smarty);
}
/*
* load config variables
*
* @param mixed $sections array of section names, single section or null
* @param object $scope global,parent or local
*/
public function loadConfigVars ($sections = null, $scope = 'local')
{
if ($this->data instanceof Smarty_Internal_Template) {
$this->data->properties['file_dependency'][sha1($this->getConfigFilepath())] = array($this->getConfigFilepath(), $this->getTimestamp(),'file');
}
if ($this->mustCompile()) {
$this->compileConfigSource();
}
// pointer to scope
if ($scope == 'local') {
$scope_ptr = $this->data;
} elseif ($scope == 'parent') {
if (isset($this->data->parent)) {
$scope_ptr = $this->data->parent;
} else {
$scope_ptr = $this->data;
}
} elseif ($scope == 'root' || $scope == 'global') {
$scope_ptr = $this->data;
while (isset($scope_ptr->parent)) {
$scope_ptr = $scope_ptr->parent;
}
}
$_config_vars = array();
include($this->getCompiledFilepath ());
// copy global config vars
foreach ($_config_vars['vars'] as $variable => $value) {
if ($this->smarty->config_overwrite || !isset($scope_ptr->config_vars[$variable])) {
$scope_ptr->config_vars[$variable] = $value;
} else {
$scope_ptr->config_vars[$variable] = array_merge((array)$scope_ptr->config_vars[$variable], (array)$value);
}
}
// scan sections
foreach ($_config_vars['sections'] as $this_section => $dummy) {
if ($sections == null || in_array($this_section, (array)$sections)) {
foreach ($_config_vars['sections'][$this_section]['vars'] as $variable => $value) {
if ($this->smarty->config_overwrite || !isset($scope_ptr->config_vars[$variable])) {
$scope_ptr->config_vars[$variable] = $value;
} else {
$scope_ptr->config_vars[$variable] = array_merge((array)$scope_ptr->config_vars[$variable], (array)$value);
}
}
}
}
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_config.php | PHP | asf20 | 10,510 |
<?php
/**
* Smarty Internal Plugin Compile Append
*
* Compiles the {append} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Append Class
*/
class Smarty_Internal_Compile_Append extends Smarty_Internal_Compile_Assign {
// attribute definitions
public $required_attributes = array('var', 'value');
public $shorttag_order = array('var', 'value');
public $optional_attributes = array('scope', 'index');
/**
* Compiles code for the {append} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
// check and get attributes
$_attr = $this->_get_attributes($args);
// map to compile assign attributes
if (isset($_attr['index'])) {
$_params['smarty_internal_index'] = '[' . $_attr['index'] . ']';
unset($_attr['index']);
} else {
$_params['smarty_internal_index'] = '[]';
}
$_new_attr = array();
foreach ($_attr as $key => $value) {
$_new_attr[] = array($key => $value);
}
// call compile assign
return parent::compile($_new_attr, $compiler, $_params);
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_compile_append.php | PHP | asf20 | 1,466 |
<?php
/**
* Smarty Internal Plugin Nocache Insert
*
* Compiles the {insert} tag into the cache file
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Insert Class
*/
class Smarty_Internal_Nocache_Insert {
/**
* Compiles code for the {insert} tag into cache file
*
* @param string $_function insert function name
* @param array $_attr array with paramter
* @param object $template template object
* @param string $_script script name to load or 'null'
* @param string $_assign soptinal variable name
* @return string compiled code
*/
static function compile($_function, $_attr, $_template, $_script, $_assign = null)
{
$_output = '<?php ';
if ($_script != 'null') {
// script which must be included
// code for script file loading
$_output .= "require_once '{$_script}';";
}
// call insert
if (isset($_assign)) {
$_output .= "\$_smarty_tpl->assign('{$_assign}' , {$_function} (" . var_export($_attr, true) . ",\$_smarty_tpl), true);?>";
} else {
$_output .= "echo {$_function}(" . var_export($_attr, true) . ",\$_smarty_tpl);?>";
}
$_tpl = $_template;
while ($_tpl->parent instanceof Smarty_Internal_Template) {
$_tpl = $_tpl->parent;
}
return "/*%%SmartyNocache:{$_tpl->properties['nocache_hash']}%%*/" . $_output . "/*/%%SmartyNocache:{$_tpl->properties['nocache_hash']}%%*/";
}
}
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/smarty/sysplugins/smarty_internal_nocache_insert.php | PHP | asf20 | 1,627 |
<?php
/**
* Description of Util
*
* @author Magno
*/
class Util {
public static function searchPosWordInBlankSpace($string){
for ($i = 0; $i < strlen($string); $i++) {
if(strcmp($string, " ") != 0)
return $i;
}
return -1;
}
public static function isType($types, $type){
$type = strtoupper(trim($type));
for ($i = 0; $i < count($types); $i++) {
if(stripos($types[$i], $type))
return true;
}
return false;
}
public static function isTypeNumeric($type){
$types = array("#INT","DECIMAL","DOUBLE","FLOAT","NUMERIC");
return Util::isType($types, $type);
}
public static function isTypeText($type){
$types = array("CHAR","TEXT");
return Util::isType($types, $type);
}
public static function isTypeTime($type){
$types = array("DATE","TIME");
return Util::isType($types, $type);
}
public static function isTypeEspecial($type){
$types = array("#ARRAY","#OBJECT");
return Util::isType($types, $type);
}
public static function getInitValue($type, $default, $isFK){
$value = '""';
if(Util::isTypeNumeric($type)){
$value = "-1";
if(strlen($default))
$value = $default;
}else if(Util::isTypeText($type) || Util::isTypeTime($type)){
$value = "\"\"";
}
if($isFK || Util::isTypeEspecial($type)){
$value = "null";
}
return $value;
}
public static function xmlHighlight($s){
$s = htmlspecialchars($s);
$s = preg_replace("#<([/]*?)(.*)([\s]*?)>#sU",
"<font color=\"blue\"><\\1\\2\\3></font>",$s);
$s = preg_replace("#<([\?])(.*)([\?])>#sU",
"<font color=\"#800000\"><\\1\\2\\3></font>",$s);
$s = preg_replace("#<([^\s\?/=])(.*)([\[\s/]|>)#iU",
"<<font color=\"blue\">\\1\\2</font>\\3",$s);
$s = preg_replace("#<([/])([^\s]*?)([\s\]]*?)>#iU",
"<\\1<font color=\"blue\">\\2</font>\\3>",$s);
$s = preg_replace("#([^\s]*?)\=("|')(.*)("|')#isU",
"<font color=\"red\">\\1</font>=<font color=\"purple\">\\2\\3\\4</font>",$s);
$s = preg_replace("#<(.*)(\[)(.*)(\])>#isU",
"<\\1<font color=\"red\">\\2\\3\\4</font>>",$s);
$s = str_replace("\t", " ", $s);
return nl2br($s);
}
}
?>
| 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/Util.class.php | PHP | asf20 | 2,566 |
<?php
/**
* Description of Constantes
*
* @author Magno
*/
class Constantes {
public static $URL_CRIPTOGRAFADA = false;
public static $RES_WORDS_COLUMNS = array("PRIMARY KEY","INDEX","UNIQUE","CONSTRAINT");
public static $PRIMARY_KEY = "PRIMARY KEY";
public static $INDEX = "INDEX";
public static $UNIQUE = "UNIQUE";
public static $CONSTRAINT = "CONSTRAINT";
public static $NOT_NULL = "NOT NULL";
public static $DEFAULT = "DEFAULT";
public static $REFERENCES = "REFERENCES";
public static $FOREIGNKEY = "FOREIGNKEY";
public static $TEMPLATES_DIR = "templates/";
public static $TEMPLATES_BEAN_DIR = "templates/bean/";
public static $TEMPLATES_DAO_DIR = "templates/dao/";
public static $TEMPLATES_SERVICE_DIR = "templates/service/";
public static $TEMPLATES_ACTION_DIR = "templates/action/";
public static $TEMPLATES_VIEW_DIR = "templates/view/";
/** CONSTANTES DAS FK_REFERENCE_META **/
public static $CARDINALITY_1 = '1';
public static $CARDINALITY_M = 'm';
public static $TYPE_FORM_COMBO = 'combo';
public static $TYPE_FORM_HIDDEN_ID = 'hidID';
public static $TYPE_FORM_INCLUDE = 'form';
public static $TYPE_FORM_NO = 'no';
public static $SIDE_OBJ_FK = 1;
public static $SIDE_OBJ_REF = 2;
/** CONSTANTES TIPO DE ATRIBUTO ESPECIAL **/
public static $TYPE_ARRAY = 'ARRAY';
public static $TYPE_OBJ = 'OBJECT';
/** CONSTANTES DO TEMPLATE BEAN **/
public static $TPL_BEAN_NAME_UPPER = ":Name";
public static $TPL_BEAN_NAME_LOWER = ":name";
public static $TPL_BEAN_NAME_TO_UPPER = ":NAME";
public static $TPL_BEAN_EXTENDS = ":extends";
public static $TPL_BEAN_CONSTRUCT_PARENT = ":constructParent";
public static $TPL_BEAN_VAR = ":var";
public static $TPL_BEAN_CONSTRUCT_VAR = ":constructVar";
public static $TPL_BEAN_INIT_VAR = ":initVar";
public static $TPL_BEAN_ARRAY_VAR = ":arrayVar";
public static $TPL_BEAN_GETTERS = ":get";
public static $TPL_BEAN_SETTERS = ":set";
/** CONSTANTES COMUNS AOS TEMPLATE **/
public static $TPL_LIST_PARAM_INIT = ":listParamInit";
public static $TPL_LIST_PARAM = ":listParam";
/** CONSTANTES DO TEMPLATE DAO **/
public static $TPL_DAO_UPDATE_COLUMNS = ":updateColumns";
public static $TPL_DAO_INSERT_COLUMNS = ":insertColumns";
public static $TPL_DAO_INSERT_VALUES = ":insertValues";
public static $TPL_DAO_SET_VALUES = ":setValues";
public static $TPL_DAO_REL_EXTERNAL = ":relExternal";
public static $TPL_DAO_DAOS_EXTERNAL = ":daosExternal";
public static $TPL_DAO_INIT_DAOS_EXTERNAL = ":initDaosExternal";
public static $TPL_DAO_WHERE_TEST = ":whereTest";
public static $TPL_DAO_PK_WHERE = ":pkWhere";
public static $TPL_DAO_PK_BUSCAR = ":pkBuscar";
public static $TPL_DAO_PK_INIT_PARAM = ":pkInitParam";
public static $TPL_DAO_PK_BIND = ":pkBind";
public static $TPL_DAO_PK_TOTAL = ":pkTotal";
public static $TPL_DAO_PK_IF_UPDATE = ":pkIfUpdate";
public static $TPL_DAO_PK_IF_NOT_EXIST = ":pkIfNotExist";
public static $TPL_DAO_PK_SET_LAST_INSERTED = ":pkSetLastInserted";
public static $TPL_DAO_BEGIN_IF_LAST_INSERTED = ":beginIfLastInserted";
public static $TPL_DAO_END_IF_LAST_INSERTED = ":endIfLastInserted";
public static $TPL_DAO_SAVE_PARENT = ":saveParent";
public static $TPL_DAO_JOIN_PARENT = ":joinParent";
public static $TPL_DAO_SET_PARENT = ":setParent";
public static $TPL_DAO_RETURN_UPDATE = ":returnUpdate";
public static $TPL_DAO_BEGIN_UPDATE = ":beginUpdate";
public static $TPL_DAO_END_UPDATE = ":endUpdate";
public static $TPL_DAO_BEGIN_DELETE = ":beginDelete";
public static $TPL_DAO_END_DELETE = ":endDelete";
public static $TPL_DAO_PARENT_DELETE = ":parentDelete";
/** CONSTANTES DO TEMPLATE SERVICE **/
public static $TPL_SERVICE_PK_IF_TEST = ":pkIfTest";
public static $TPL_SERVICE_PK_INIT_PARAM = ":pkInitParam";
public static $TPL_SERVICE_PK_LIST = ":pkList";
public static $TPL_SERVICE_PK_TOTAL = ":pkTotal";
/** CONSTANTES DO TEMPLATE ACTION **/
public static $TPL_ACTION_PK_IF_TEST = ":pkIfTest";
public static $TPL_ACTION_PK_INIT_PARAM = ":pkInitParam";
public static $TPL_ACTION_PK_LIST = ":pkList";
public static $TPL_ACTION_PK_TOTAL = ":pkTotal";
public static $TPL_ACTION_PK_URL_PARAM = ":pkUrlParam";
public static $TPL_ACTION_FKS_COMBO = ":fksCombo";
public static $TPL_ACTION_FKS_BUSCAR_SALVAR = ":fksBuscarSalvar";
public static $TPL_ACTION_FKS_SET_SALVAR = ":fksSetSalvar";
public static $TPL_ACTION_FKS_SERVICE = ":fksService";
public static $TPL_ACTION_FKS_INIT_SERVICE = ":fksInitService";
public static $TPL_ACTION_FKS_OUTPUT = ":fksOutput";
/** CONSTANTES DO TEMPLATE VIEW **/
public static $TPL_VIEW_PK_URL_PARAM = ":pkUrlParam";
/** CONSTANTES DO TEMPLATE VIEW-CADASTRO **/
public static $TPL_VIEW_CADASTRO_PK_INPUT_HIDDEN = ":pkInputHiden";
public static $TPL_VIEW_CADASTRO_IF_INC_VALIDADE = ":ifIncValidate";
public static $TPL_VIEW_CADASTRO_END_IF_INC_VALIDADE = ":EndIfIncValidate";
public static $TPL_VIEW_CADASTRO_JS_VALIDADE = ":jsValidate";
public static $TPL_VIEW_CADASTRO_END_JS_VALIDADE = ":EndJsValidate";
public static $TPL_VIEW_CADASTRO_ATT_JS_VALIDADE = ":attJsValidate";
public static $TPL_VIEW_CADASTRO_ATT_INPUTS = ":attInputs";
public static $TPL_VIEW_CADASTRO_FK_INPUTS = ":fkInputs";
/** CONSTANTES DO TEMPLATE VIEW-DETALHES **/
public static $TPL_VIEW_DETALHES_ATT_DETALHE = ":attDetalhe";
public static $TPL_VIEW_DETALHES_FK_DETALHE = ":fkDetalhe";
public static $TPL_VIEW_DETALHES_ATT_DETALHE_SIMPLES = ":attDetalheSimples";
/** CONSTANTES DO TEMPLATE VIEW-FORM **/
public static $TPL_VIEW_FORM_ATT_BUSCA_FORM = ":attBuscaForm";
public static $TPL_VIEW_FORM_ATT_INPUT_FORM_INCLUDE = ":attInputFormInclude";
/** CONSTANTES DO TEMPLATE VIEW-LISTAR **/
public static $TPL_VIEW_LISTAR_ATT_BUSCA_JS = ":attBuscaJs";
public static $TPL_VIEW_LISTAR_ATT_BUSCA_JS_PARAM = ":attBuscaJsParam";
public static $TPL_VIEW_LISTAR_ATT_HEAD_TABLE = ":attHeadTable";
public static $TPL_VIEW_LISTAR_ATT_ROW_TABLE = ":attRowTable";
/** CONSTANTES DO TEMPLATE VIEW-LISTAR **/
public static $TPL_VIEW_MENU_ACTION = ":menuAction";
/** CONSTANTES DE DEFINICOES DAS PAGINAS **/
public static $PARAM_INCLUDE_VALIDADE = "incValidate";
public static $PARAM_INCLUDE_CSS = "incCss";
public static $PARAM_INCLUDE_MENU = "incMenu";
public static $PARAM_PROJECT_NAME = "projectName";
}
?>
| 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/Constantes.class.php | PHP | asf20 | 6,690 |
<?php
$dirBase = 'temp_gen';
// the name of your zip archive to be created
$zipfile = $dirBase."/".$name.'.zip';
// DO NOT TOUCH BELOW IF YOU DONT KNOW WHAT IT IS
// all the process below
$filenames = array();
// function that browse the directory and all subdirectories inside
function browse($dir) {
global $filenames;
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && is_file($dir.'/'.$file)) {
$filenames[] = $dir.'/'.$file;
}
else if ($file != "." && $file != ".." && is_dir($dir.'/'.$file)) {
browse($dir.'/'.$file);
}
}
closedir($handle);
}
return $filenames;
}
$filenames = browse($directory);
// creating zip archive, adding browsed files
$zip = new ZipArchive();
if ($zip->open($zipfile, ZIPARCHIVE::CREATE)!==TRUE) {
die("cannot open <$zipfile>\n");
}
foreach ($filenames as $filename) {
# echo "Adding " . $filename . "<br/>";
$zip->addFile($filename,$filename);
}
#echo "numfiles: " . $zip->numFiles . "\n";
#echo "status:" . $zip->status . "\n";
$zip->close();
echo '<p class="align-center" style="padding: 0"><a href="'.$zipfile.'" class="big-button" style="padding: 30px; font-size: x-large;">Baixe o Seu Projeto Aki!!!</a></p>';
?> | 0a1b2c3d4e5 | trunk/BloumGenerator/include/php/compactador.php | PHP | asf20 | 1,360 |
/**
* Styles for tables and grid view
*/
.table, .with-head {
margin-bottom: 1.667em;
border: 1px solid #999999;
}
.table {
border-collapse: separate;
}
.table:last-child,
.with-head:last-child {
margin-bottom: 0;
}
/* IE class */
.table.last-child,
.with-head.last-child {
margin-bottom: 0;
}
.no-margin .table,
.content-columns .table,
.with-head.no-margin,
.content-columns .with-head {
border: none;
}
.no-margin .table + .no-margin,
.with-head.no-margin + .no-margin {
margin-top: -1.667em;
}
.no-margin .table.last-child + .no-margin,
.with-head.no-margin.last-child + .no-margin {
margin-top: 0;
}
.content-columns .table:first-child,
.content-columns .with-head:first-child {
border: none;
}
/* IE class */
.content-columns .table.first-child,
.content-columns .with-head.first-child {
border: none;
}
.content-columns .table,
.content-columns .with-head {
margin-bottom: 0;
}
.table thead th,
.table thead td,
.head {
background: #a4a4a4 url(../images/old-browsers-bg/planning-header-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#cccccc,
#a4a4a4
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#cccccc),
to(#a4a4a4)
);
color: white;
-moz-text-shadow: 0 1px 2px rgba(0, 0, 0, 0.7);
-webkit-text-shadow: 0 1px 2px rgba(0, 0, 0, 0.7);
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.7);
border-top: 1px solid white;
border-left: 1px solid #dddddd;
border-right: 1px solid #999999;
border-bottom: 1px solid #828282;
}
.table thead th,
.table thead td {
vertical-align: middle;
text-align: left;
padding: 0.5em 0.75em;
}
.table thead th.sorting, .table thead th.sorting_asc, .table thead th.sorting_desc,
.table thead td.sorting, .table thead td.sorting_asc, .table thead td.sorting_desc {
cursor: pointer;
}
.head {
font-weight: bold;
line-height: 1.5em;
}
.head > div {
float: left;
padding: 0.5em 2em 0.5em 0.75em;
border-left: 1px solid #dddddd;
border-right: 1px solid #999999;
color: white;
margin: -1px 0 0 0;
-moz-text-shadow: 0 1px 2px rgba(0, 0, 0, 0.7);
-webkit-text-shadow: 0 1px 2px rgba(0, 0, 0, 0.7);
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.7);
}
.head > div:first-child {
margin-left: -1px;
}
/* IE class */
.head > div.first-child {
margin-left: -1px;
}
.head > div:last-of-type {
border-right: none;
}
/* IE class */
.head > div.last-of-type {
border-right: none;
}
.head .button {
float: right;
margin: 0.25em 0.5em 0 0;
}
.head > div .button {
float: left;
margin: -0.167em 0.5em -0.333em 0;
}
.head > div .button:last-child {
margin-right: 0;
}
/* IE class */
.head > div .button.last-child {
margin-right: 0;
}
.table tbody th,
.table tbody td,
.table tfoot th,
.table tfoot td {
vertical-align: top;
text-align: left;
padding: 0.75em;
border-left: 1px dotted #333333;
}
.table tbody th,
.table tbody .th { /* Compatibility with DataTables */
background: #e6e6e6;
}
.table tbody td {
background: #f2f2f2;
}
.table tfoot th,
.table tfoot td {
border-top: 1px solid #FF9900;
background: #999999 url(../images/old-browsers-bg/tfoot-bg.png) repeat-x top;
-o-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-webkit-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#333333,
#999999
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#333333),
to(#999999)
);
color: white;
}
.table tbody th:first-child,
.table tbody .th:first-child,
.table tbody td:first-child,
.table tfoot th:first-child,
.table tfoot td:first-child {
border-left: none;
}
/* IE class */
.table tbody th.first-child,
.table tbody .th.first-child,
.table tbody td.first-child,
.table tfoot th.first-child,
.table tfoot td.first-child {
border-left: none;
}
.table tbody tr:nth-child(even) th,
.table tbody tr:nth-child(even) .th {
background: #d9d9d9;
}
/* IE class */
.table tbody tr.even th
.table tbody tr.even .th {
background: #d9d9d9;
}
.table tbody tr:nth-child(even) td {
background: #e6e6e6;
}
/* IE class */
.table tbody tr.even td {
background: #e6e6e6;
}
.table tbody tr:hover th,
.table tbody tr:hover .th,
.table tbody tr:hover td {
background: #d1e5ef;
}
.table .black-cell,
.head .black-cell {
background: #242424 url(../images/old-browsers-bg/black-cell-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#4c4c4c,
#242424
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#4c4c4c),
to(#242424)
);
border-top-color: #7f7f7f;
border-left: none;
border-right-color: #191919;
min-width: 1.333em;
padding: 0.5em 0.583em;
}
/* IE class */
.ie7 .head .black-cell {
height: 1.5em;
position: relative;
z-index: 89;
}
.head .black-cell.with-gap {
border-right-color: white;
margin-right: 0.25em
}
.head .black-cell.with-gap + .black-cell {
border-left: 1px solid #999999;
}
.table .black-cell span,
.head .black-cell span {
display: block;
height: 2.5em;
background-repeat: no-repeat;
background-position: center;
margin: -0.5em -0.75em;
}
/* IE class */
.ie7 .head .black-cell span {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
height: auto;
padding: 0;
}
.table .black-cell span.loading, .with-head .black-cell span.loading { background-image: url(../images/table-loader.gif); }
.table .black-cell span.error, .with-head .black-cell span.error { background-image: url(../images/icons/fugue/cross-circle.png); }
.table .black-cell span.success, .with-head .black-cell span.success { background-image: url(../images/icons/fugue/tick-circle-blue.png); }
.table-actions a img {
margin: -2px 0;
}
/************ Sort arrows ************/
.column-sort {
display: block;
float: left;
width: 14px;
margin: -0.583em 0.5em -0.583em -0.75em;
border-right: 1px solid #dddddd;
}
.head .column-sort {
margin: -0.5em 0.5em -0.5em -0.75em;
}
.sorting_disabled .column-sort {
display: none;
}
.column-sort .sort-up,
.column-sort .sort-down {
display: block;
width: 13px;
height: 14px;
background: url(../images/table-sort-arrows.png) no-repeat;
border-right: 1px solid #999999;
}
.column-sort .sort-up {
background-position: 0 1px;
border-bottom: 1px solid #828282;
}
.column-sort .sort-down {
background-position: 0 bottom;
border-top: 1px solid white;
}
.column-sort .sort-up:hover { background-position: -15px 1px; }
.column-sort .sort-down:hover { background-position: -15px bottom; }
.column-sort .sort-up:active, .column-sort .sort-up.active, .sorting_asc .column-sort .sort-up { background-position: -30px 1px; }
.column-sort .sort-down:active, .column-sort .sort-down.active, .sorting_desc .column-sort .sort-down { background-position: -30px bottom; }
/************ Cell styles ************/
.table-check-cell {
width: 1em;
}
/* http://perishablepress.com/press/2008/02/05/lessons-learned-concerning-the-clearfix-css-hack */
.head:after,
ul.grid:after {
clear: both;
content: ' ';
display: block;
font-size: 0;
line-height: 0;
visibility: hidden;
width: 0;
height: 0;
}
.head,
ul.grid {
display: inline-block;
}
* html .head,
* html ul.grid {
height: 1%;
}
.head,
ul.grid {
display: block;
} | 0a1b2c3d4e5 | trunk/BloumGenerator/include/css/table.css | CSS | asf20 | 8,175 |
/* Custom styles for the special pages */
html {
height: 100%;
}
.login-bg,
.wizard-bg {
background: url(../images/bg.png) no-repeat center -200px;
min-height: 100%;
}
.error-bg,
.code-page {
background: url(../images/old-browsers-bg/login-radial-bg.png) no-repeat center center;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-radial-gradient(center, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0)), #70828f;
background: -webkit-gradient(radial, 50% 50%, 10, 50% 50%, 500, from(rgba(255, 255, 255, 0.8)), to(rgba(255, 255, 255, 0))), #70828f;
min-height: 100%;
}
.login-bg section,
.wizard-bg section,
.error-bg section,
.code-page section {
position: absolute;
z-index: 89;
left: 50%;
top: 50%;
}
.login-bg section,
.error-bg section {
width: 34em;
margin-left: -17em;
margin-top: -15em;
}
.login-bg section#message {
margin-top: -23.5em;
}
.error-bg section {
-moz-transition: all 200ms;
-webkit-transition: all 200ms;
-o-transition: all 200ms;
transition: all 200ms;
}
.error-bg section#error-log {
z-index: 88;
opacity: 0;
filter: alpha(opacity=0);
}
.error-bg.with-log section {
margin-top: -19em;
}
.error-bg.with-log section#error-desc {
margin-left: -36em;
}
.error-bg.with-log section#error-log {
margin-left: 2em;
opacity: 100;
filter: none;
}
.wizard-bg section {
width: 64em;
margin-left: -32em;
margin-top: -23em;
}
.login-bg .block-content,
.wizard-bg .block-content,
.error-bg .block-content {
-moz-box-shadow: 0 0 8px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 0 8px rgba(0, 0, 0, 0.5);
box-shadow: 0 0 8px rgba(0, 0, 0, 0.5);
}
.login-bg .block-border,
.wizard-bg .block-border,
.error-bg .block-border {
-moz-box-shadow: 0 0 8px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 0 8px rgba(0, 0, 0, 0.5);
box-shadow: 0 0 8px rgba(0, 0, 0, 0.5);
}
.login-bg .block-border .block-content,
.wizard-bg .block-border .block-content,
.error-bg .block-border .block-content {
-moz-box-shadow: 0 0 0.8em rgba(255, 255, 255, 0.5);
-webkit-box-shadow: 0 0 0.8em rgba(255, 255, 255, 0.5);
box-shadow: 0 0 0.8em rgba(255, 255, 255, 0.5);
}
.error-bg #send-report p {
padding-left: 10em;
}
.error-bg #send-report p .float-left {
margin-left: -10em;
width: 8em;
}
/******** Page for code errors : 404... *********/
.code-page {
text-align: center;
}
.code-page h1 {
position: absolute;
left: 0;
right: 0;
top: 50%;
margin-top: -1em;
text-align: center;
font-size: 16em;
color: #A1A8AB;
-moz-text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.35), 1px 1px 1px rgba(255, 255, 255, 0.75);
-webkit-text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.35), 1px 1px 1px rgba(255, 255, 255, 0.75);
text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.35), 1px 1px 1px rgba(255, 255, 255, 0.75);
}
.code-page p {
position: absolute;
left: 0;
right: 0;
top: 50%;
text-align: center;
font-size: 3em;
font-weight: bold;
text-transform: uppercase;
-moz-text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.35), 1px 1px 1px rgba(255, 255, 255, 0.75);
-webkit-text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.35), 1px 1px 1px rgba(255, 255, 255, 0.75);
text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.35), 1px 1px 1px rgba(255, 255, 255, 0.75);
}
.code-page section {
margin-top: 5em;
width: 28em;
margin-left: -14em;
}
.code-page section .action-tabs {
padding-top: 1em;
}
.code-page section .action-tabs.on-form {
padding-top: 1.75em;
}
.code-page section form.block-content {
padding-left: 0;
padding-right: 0;
}
.code-page section form.block-content #s {
width: 15em;
}
/************* Mobile customization *************/
@media only screen and (max-device-width: 480px) {
.login-bg,
.wizard-bg {
background: #70828f url(../images/bg-mobile.png) no-repeat center -200px;
}
.login-bg,
.error-bg {
padding: 1em;
}
.login-bg section,
.wizard-bg section,
.error-bg section {
position: static;
width: auto;
margin-top: 0;
margin-left: 0;
left: auto;
top: auto;
}
.error-bg section#error-log {
opacity: 100;
filter: none;
}
.error-bg,
.code-page {
background: #70828f url(../images/old-browsers-bg/login-radial-bg-mobile.png) no-repeat center center;
background: -moz-radial-gradient(center, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0)), #70828f;
background: -webkit-gradient(radial, 50% 50%, 10, 50% 50%, 240, from(rgba(255, 255, 255, 0.8)), to(rgba(255, 255, 255, 0))), #70828f;
}
.error-bg #send-report p {
padding: 0;
}
.error-bg #send-report p .float-left {
margin-left: 0;
width: auto;
}
.error-bg #send-report p span.float-left {
float: right;
width: 40%;
}
.error-bg #send-report p #sender {
width: 50%;
}
/******** Page for code errors : 404... *********/
.code-page h1 {
font-size: 10em;
}
.code-page p {
font-size: 1.75em;
}
.code-page section {
width: auto;
top: auto;
left: 0;
right: 0;
bottom: 0;
margin: 0;
}
.code-page section .action-tabs {
display: none;
}
} | 0a1b2c3d4e5 | trunk/BloumGenerator/include/css/special-pages.css | CSS | asf20 | 5,471 |
<?php
/**
* Simple script to combine and compress CSS files, to reduce the number of file request the server has to handle.
* For more options/flexibility, see Minify : http://code.google.com/p/minify/
*/
// If no file requested
if (!isset($_GET['files']) or strlen($_GET['files']) == 0)
{
header('Status: 404 Not Found');
exit();
}
// Cache folder
$cachePath = 'cache/';
if (!file_exists($cachePath))
{
mkdir($cachePath);
}
// Tell the browser what kind of data to expect
header('Content-type: text/css');
// Enable compression
/*if (extension_loaded('zlib'))
{
ini_set('zlib.output_compression', 'On');
}*/
/**
* Add file extension if needed
* @var string $file the file name
*/
function addExtension($file)
{
if (substr($file, -3) !== '.css')
{
$file .= '.css';
}
return $file;
}
// Calculate an unique ID of requested files & their change time
$files = array_map('addExtension', explode(',', $_GET['files']));
$md5 = '';
foreach ($files as $file)
{
$filemtime = @filemtime($file);
$md5 .= date('YmdHis', $filemtime ? $filemtime : NULL).$file;
}
$md5 = md5($md5);
// If cache exists of this files/time ID
if (file_exists($cachePath.$md5))
{
readfile($cachePath.$md5);
}
else
{
// Load files
error_reporting(0);
$content = '';
foreach ($files as $file)
{
$content .= file_get_contents($file);
}
// Remove comments
$content = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $content);
// Remove tabs, spaces, newlines, etc...
$content = str_replace(array("\r", "\n", "\t", ' ', ' '), '', $content);
// Delete cache files older than an hour
$oldDate = time()-3600;
$cachedFiles = scandir($cachePath);
foreach ($cachedFiles as $file)
{
$filemtime = @filemtime($cachePath.$file);
if (strlen($file) == 32 and ($filemtime === false or $filemtime < $oldDate))
{
unlink($cachePath.$file);
}
}
// Write cache file
file_put_contents($cachePath.$md5, $content);
// Output
echo $content;
} | 0a1b2c3d4e5 | trunk/BloumGenerator/include/css/mini.php | PHP | asf20 | 2,043 |
/**
* Styles for the standard template
*/
html {
min-height: 100%;
overflow-x: hidden;
}
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
background: url(../images/bg.png) no-repeat center top;
min-height: 100%;
}
textarea, input {
font-family: Verdana, Arial, Helvetica, sans-serif;
}
/**************** Generic classes ***************/
h2.bigger, h3.bigger,
h2.big, h3.big {
font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Sans", Arial, Helvetica, sans-serif;
}
/******************* Columns ********************/
.columns {
margin-bottom: 1.667em;
position: relative;
}
.columns:last-child {
margin-bottom: 0;
}
/** IE class **/
.columns.last-child {
margin-bottom: 0;
}
/* 2 columns */
.colx2-left {
width: 48%;
float: left;
margin-bottom: 0;
}
.colx2-right {
width: 48%;
float: right;
margin-bottom: 0;
}
/* 3 columns */
.colx3-left {
width: 31%;
float: left;
margin-bottom: 0;
}
.colx3-left-double {
width: 65.5%;
float: left;
margin-bottom: 0;
}
.colx3-center {
width: 31%;
float: left;
margin-left: 3.5%;
margin-bottom: 0;
}
.colx3-right {
width: 31%;
float: right;
margin-bottom: 0;
}
.colx3-right-double {
width: 65.5%;
float: right;
margin-bottom: 0;
}
/* 200px fixed-width left column */
.col200pxL-left {
width: 200px;
float: left;
}
.col200pxL-bottom {
position: absolute;
bottom: 0;
left: 0;
width: 180px;
}
.col200pxL-right {
margin-left: 200px;
}
/* 200px fixed-width right column */
.col200pxR-left {
margin-right: 200px;
}
.col200pxR-bottom {
position: absolute;
bottom: 0;
right: 0;
width: 180px;
}
.col200pxR-right {
width: 200px;
float: right;
}
/************* Button-style images **************/
.button img,
.form legend img,
.legend img,
.mini-menu img {
margin-bottom: -4px;
}
/******************** Header ********************/
header {
color: #666666;
text-transform: uppercase;
position: absolute;
z-index: 88;
top: 0;
left: 0;
width: 100%;
white-space: nowrap;
text-align: right;
}
header .server-info {
display: inline-block;
border-top: 0;
padding: 0 1em;
color: white;
background: url(../images/old-browsers-bg/server-status-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
rgba(64,64,64,0.3),
rgba(255,255,255,0.2)
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(rgba(64,64,64,0.3)),
to(rgba(255,255,255,0.2))
);
margin-left: 0.5em;
height: 2.6em;
line-height: 2.6em;
vertical-align: top;
font-size: 0.833em;
-moz-box-shadow: 0 0 5px rgba(0, 0, 0, 0.65);
-webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.65);
box-shadow: 0 0 5px rgba(0, 0, 0, 0.65);
-moz-border-radius: 0 0 0.4em 0.4em;
-webkit-border-radius: 0.4em;
-webkit-background-clip: padding-box;
-webkit-border-top-left-radius: 0;
-webkit-border-top-right-radius: 0;
border-radius: 0 0 0.4em 0.4em;
}
.ie7 header .server-info {
display: inline;
zoom: 1;
}
#skin-name {
display: inline-block;
margin: 0 0.7em 0 0;
color: #B0B0B0;
color: rgba(255, 255, 255, 0.75);
}
.ie7 #skin-name {
display: inline;
zoom: 1;
}
#skin-name small {
float: left;
font-size: 0.75em;
line-height: 1.111em;
text-transform: uppercase;
color: #B0B0B0;
color: rgba(255, 255, 255, 0.75);
padding-top: 0.555em;
text-align: right;
}
#skin-name strong {
font-size: 2em;
line-height: 1.333em;
margin-left: 0.167em;
font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Sans", Arial, Helvetica, sans-serif;
letter-spacing: -0.09em;
}
.ie #skin-name strong {
padding-right: 0.083em;
}
nav {
height: 69px;
padding-top: 1.25em;
background: #3399cc url(../images/old-browsers-bg/main-nav-bg.png) repeat-x bottom;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(top, #014a7d, #3399cc);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#014a7d), to(#3399cc));
-moz-box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.5);
box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.5);
}
nav > ul {
padding-top: 4px;
position: relative;
z-index: 100;
}
nav > ul > li {
width: 64px;
height: 69px;
float: left;
background-position: center -54px;
background-repeat: no-repeat;
}
nav > ul > li > a {
display: block;
height: 69px;
background-repeat: no-repeat;
background-position: 8px 14px;
overflow: hidden;
text-indent: 200px;
white-space: nowrap;
opacity: 0;
filter: alpha(opacity=0);
-moz-transition: opacity 2s;
-webkit-transition: opacity 2s;
-o-transition: opacity 2s;
transition: opacity 2s;
}
nav > ul > li.home, nav > ul > li.home > a { background-image: url(../images/icons/home_2states.png); }
nav > ul > li.write, nav > ul > li.write > a { background-image: url(../images/icons/write_2states.png); }
nav > ul > li.comments, nav > ul > li.comments > a { background-image: url(../images/icons/comments_2states.png); }
nav > ul > li.medias, nav > ul > li.medias > a { background-image: url(../images/icons/medias_2states.png); }
nav > ul > li.users, nav > ul > li.users > a { background-image: url(../images/icons/users_2states.png); }
nav > ul > li.stats, nav > ul > li.stats > a { background-image: url(../images/icons/stats_2states.png); }
nav > ul > li.settings, nav > ul > li.settings > a { background-image: url(../images/icons/settings_2states.png); }
nav > ul > li.backup, nav > ul > li.backup > a { background-image: url(../images/icons/backup_2states.png); }
nav > ul > li.current {
padding: 0 8px 13px 8px;
margin: 0 -8px -13px -8px;
background: url(../images/tab-bg.png) no-repeat;
}
nav > ul > li.current > a,
nav > ul > li > a:hover {
opacity: 1;
filter: none;
-moz-transition: all 100ms;
-webkit-transition: all 100ms;
-o-transition: all 100ms;
transition: all 100ms;
}
nav > ul > li > ul {
position: absolute;
left: 0;
top: 70px;
display: none;
padding-top: 0.333em;
background: none;
}
nav > ul > li.current > ul {
display: block;
}
nav > ul > li > ul > li,
#sub-nav a.nav-button {
display: block;
float: left;
height: 2.2em;
font-size: 0.833em;
line-height: 2.2em;
padding: 0.1em;
width: auto;
background: #465a6e url(../images/old-browsers-bg/subnav-bt-border-bg.png) repeat-x;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(top, #9faab6, #465a6e);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#9faab6), to(#465a6e));
margin-right: 0.5em;
-moz-border-radius: 0.417em;
-webkit-border-radius: 0.417em;
-webkit-background-clip: padding-box;
border-radius: 0.417em;
color: white;
text-transform: uppercase;
-moz-box-shadow: 0 0 7px #000000;
-webkit-box-shadow: 0 0 7px #000000;
box-shadow: 0 0 7px #000000;
text-decoration: none;
-moz-transition: all 1s;
-webkit-transition: all 1s;
-o-transition: all 1s;
transition: all 1s;
}
nav > ul > li > ul > li.current {
height: 3.1em;
line-height: 3.1em;
color: #333;
padding: 0;
-moz-border-radius-bottomleft: 0;
-moz-border-radius-bottomright: 0;
-webkit-border-bottom-left-radius: 0;
-webkit-border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
background: #dadada url(../images/old-browsers-bg/subnav-current-bt-border-bg.png) repeat-x;
background: -moz-linear-gradient(
top,
white,
#dadada 7%,
#dadada
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#dadada),
color-stop(0.07, #dadada)
);
}
nav > ul > li > ul > li > a,
#sub-nav a.nav-button > b {
display: block;
height: 2.2em;
line-height: 2.2em;
width: auto;
padding: 0 1em;
color: white;
text-indent: 0;
text-decoration: none;
-moz-border-radius: 0.3em;
-webkit-border-radius: 0.3em;
-webkit-background-clip: padding-box;
border-radius: 0.3em;
font-weight: normal;
-moz-transition: all 1s;
-webkit-transition: all 1s;
-o-transition: all 1s;
transition: all 1s;
}
nav > ul > li > ul > li > a,
#sub-nav a.nav-button > b,
nav > ul > li > ul > li.with-menu .menu,
nav > ul > li > ul > li.menu-opener .menu-arrow {
background: #1d2a36 url(../images/old-browsers-bg/subnav-bt-bg.png) repeat-x !important;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(top, #858d95, #46505b 50%, #38424d 50%, #1c2733) !important;
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#858d95), to(#1c2733), color-stop(.5, #46505b), color-stop(.5, #38424d)) !important;
}
nav > ul > li > ul > li.current > a {
background: none !important;
height: 2.8em;
line-height: 2.8em;
color: #333;
}
nav > ul > li > ul > li:hover,
#sub-nav a.nav-button:hover {
background: #6dc0e5 url(../images/old-browsers-bg/subnav-bt-hover-border-bg.png) repeat-x;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(top, #cbe9f7, #6dc0e5);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#cbe9f7), to(#6dc0e5));
-moz-transition: all 100ms;
-webkit-transition: all 100ms;
-o-transition: all 100ms;
transition: all 100ms;
}
nav > ul > li > ul > li.current:hover {
background: #dadada url(../images/old-browsers-bg/subnav-current-bt-border-bg.png) repeat-x;
background: -moz-linear-gradient(
top,
white,
#dadada 7%,
#dadada
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#dadada),
color-stop(0.07, #dadada)
);
}
nav > ul > li > ul > li > a:hover,
#sub-nav a.nav-button:hover > b,
nav > ul > li > ul > li.with-menu .menu:hover,
nav > ul > li > ul > li.menu-opener:hover .menu-arrow {
background: #305d79 url(../images/old-browsers-bg/subnav-bt-hover-bg.png) repeat-x !important;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(left, rgba(109, 192, 229, 0), rgba(109, 192, 229, 0.2) 25%, rgba(109, 192, 229, 0.4) 50%, rgba(109, 192, 229, 0.3) 75%, rgba(109, 192, 229, 0)),
-moz-linear-gradient(top, #afc2cf, #537288 50%, #45667c 50%, #2c526b) !important;
background: -webkit-gradient(linear, 0% 0%, 100% 0%, from(rgba(109, 192, 229, 0)), to(rgba(109, 192, 229, 0)), color-stop(.25, rgba(109, 192, 229, 0.3)), color-stop(.5, rgba(109, 192, 229, 0.4)), color-stop(.75, rgba(109, 192, 229, 0.3))),
-webkit-gradient(linear, 0% 0%, 0% 100%, from(#afc2cf), to(#2c526b), color-stop(.5, #537288), color-stop(.5, #45667c)) !important;
-moz-box-shadow: 0 0 7px #cbe9f7;
-webkit-box-shadow: 0 0 7px #cbe9f7;
box-shadow: 0 0 7px #cbe9f7;
-moz-transition: all 100ms;
-webkit-transition: all 100ms;
-o-transition: all 100ms;
transition: all 100ms;
}
nav > ul > li > ul > li.current > a:hover {
background: none !important;
color: #666;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
}
#sub-nav {
border-top: 1px solid #ff6500;
height: 2.667em;
line-height: 2.667em;
background: black url(../images/old-browsers-bg/subnav-bg.png) repeat-x;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(top, #303135, #3c3d42 6%, #404447 18%, #34383b 50%, #25292c 50%, #1a1b1f 63%, black);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#303135), to(black), color-stop(.06, #3c3d42), color-stop(.18, #404447), color-stop(.5, #34383b), color-stop(.5, #25292c), color-stop(.63, #1a1b1f));
text-align: right;
color: white;
}
#sub-nav a.nav-button {
float: right;
margin: 0.417em 0 0 1em;
}
/* IE class */
.ie7 #sub-nav a.nav-button {
margin-top: 0.333em;
}
#status-bar {
height: 3.25em;
line-height: 3.167em;
background: white url(../images/old-browsers-bg/status-bar-bg.png) repeat-x;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(top, white, #dadada 6%, white 92%, #cfcfcf);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(white), to(#cfcfcf), color-stop(.05, #dadada), color-stop(.92, white));
border-bottom: 1px solid #969696;
text-align: right;
color: #7b7b7b;
}
#status-infos {
float: right;
margin-bottom: 0;
}
#status-infos > li {
float: left;
margin-left: 0.5em;
position: relative;
z-index: 90;
}
#status-infos > li.spaced {
padding-right: 0.5em;
}
#breadcrumb {
float: left;
border: 1px solid;
border-color: #0099cc #006699 #003366;
-moz-border-radius: 0.417em;
-webkit-border-radius: 0.417em;
-webkit-background-clip: padding-box;
border-radius: 0.417em;
-moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
height: 1.75em;
line-height: 1.5em;
margin: 0.667em 1em 0 0;
background: #0c5fa5 url(../images/old-browsers-bg/breadcrumb-bg.png) repeat-x;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
white,
#72c6e4 5%,
#0c5fa5
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#0c5fa5),
color-stop(0.05, #72c6e4)
);
}
#breadcrumb li {
float: left;
color: white;
height: 1.75em;
padding: 0.083em 1em 0 0;
background: url(../images/breadcrumb-sep.png) no-repeat right center;
}
#breadcrumb li:last-child {
padding-right: 0;
background: none;
}
/* IE class */
#breadcrumb li.last-child {
padding-right: 0;
background: none;
}
#breadcrumb li a,
#breadcrumb li span {
display: block;
height: 1.667em;
color: white;
text-decoration: none;
padding: 0 0.75em 0 0.667em;
-moz-transition-duration: 1s;
-webkit-transition-duration: 1s;
transition-duration: 1s;
}
#breadcrumb li a:hover {
background: -moz-linear-gradient(left, rgba(109, 192, 229, 0), rgba(109, 192, 229, 0.8) 25%, rgba(109, 192, 229, 1) 50%, rgba(109, 192, 229, 0.8) 75%, rgba(109, 192, 229, 0));
background: -webkit-gradient(linear, 0% 0%, 100% 0%, from(rgba(109, 192, 229, 0)), to(rgba(109, 192, 229, 0)), color-stop(.25, rgba(109, 192, 229, 0.8)), color-stop(.5, rgba(109, 192, 229, 1)), color-stop(.75, rgba(109, 192, 229, 0.8)));
-moz-transition-duration: 100ms;
-webkit-transition-duration: 100ms;
transition-duration: 100ms;
}
#breadcrumb li img {
margin-bottom: -4px;
}
#header-shadow {
background: url(../images/old-browsers-bg/status-bar-shadow.png) repeat-x;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
height: 0.75em;
position: absolute;
z-index: 87;
left: 0;
width: 100%;
background: -moz-linear-gradient(top, rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.1) 30%, rgba(0, 0, 0, 0));
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(rgba(0, 0, 0, 0.3)), to(rgba(0, 0, 0, 0)), color-stop(.3, rgba(0, 0, 0, 0.1)));
}
/***************** Result block *****************/
.result-block {
position: absolute;
z-index: 90;
top: 1.667em;
right: -0.25em;
min-width: 20em;
background: white;
-moz-border-radius: 0.5em;
-webkit-border-radius: 0.5em;
-webkit-background-clip: padding-box;
border-radius: 0.5em;
-moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.5);
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.5);
padding: 1em;
line-height: 1em;
text-align: left;
color: #333333;
}
/* IE class */
.ie .result-block {
border: 1px solid #ccc;
}
#status-infos .result-block {
top: 2.667em;
display: none;
}
#status-infos > li:hover .result-block {
display: block;
}
.result-block h2 {
float: left;
color: black;
}
.result-block div {
margin-bottom: 1.667em;
}
.result-block div:last-child {
margin-bottom: 0;
}
/* IE class */
.result-block div.last-child {
margin-bottom: 0;
}
.result-block .arrow {
font-size: 0;
line-height: 0;
width: 0;
position: absolute;
z-index: 89;
right: 20px;
top: -5px;
border-bottom: 5px solid #666666;
border-left: 3px solid transparent;
border-right: 3px solid transparent;
}
.result-block .arrow span {
width: 0;
position: absolute;
z-index: 89;
left: -2px;
bottom: -5px;
border-bottom: 4px solid white;
border-left: 2px solid transparent;
border-right: 2px solid transparent;
}
.result-block .results-count {
float: right;
text-transform: uppercase;
color: #b0b0b0;
font-size: 0.75em;
white-space: nowrap;
margin-left: 1em;
}
.result-block .results-count strong {
color: #999999;
}
.result-block ul {
clear: both;
}
.result-block ul li {
white-space: nowrap;
}
.search-more,
.search-less {
display: block;
color: #999999;
font-size: 0.75em;
text-transform: uppercase;
padding: 0.333em 0;
text-align: center;
background: url(../images/old-browsers-bg/search-more-shadow.png) no-repeat center bottom;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
rgba(255, 255, 255, 1),
rgba(255, 255, 255, 0)
), -moz-linear-gradient(
left,
#ffffff,
#ebebeb 50%,
#ffffff
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(rgba(255, 255, 255, 1)),
to(rgba(255, 255, 255, 0))
), -webkit-gradient(
linear,
left top, right top,
from(#ffffff),
to(#ffffff),
color-stop(0.5, #ebebeb)
);
}
.search-more:hover,
.search-less:hover {
color: #3399cc;
}
ul + .search-more,
ul + .search-less {
margin-top: -1.333em;
}
ul.small-pagination + .search-more,
ul.small-pagination + .search-less {
margin-top: -0.667em;
}
.search-more:before {
content: url(../images/search-more-arrow.png);
padding-right: 0.556em;
}
.search-more:hover:before {
content: url(../images/search-more-arrow-hover.png);
}
.search-more:after {
content: url(../images/search-more-arrow.png);
padding-left: 0.556em;
}
.search-more:hover:after {
content: url(../images/search-more-arrow-hover.png);
}
.search-less:before {
content: url(../images/search-less-arrow.png);
padding-right: 0.556em;
}
.search-less:hover:before {
content: url(../images/search-less-arrow-hover.png);
}
.search-less:after {
content: url(../images/search-less-arrow.png);
padding-left: 0.556em;
}
.search-less:hover:after {
content: url(../images/search-less-arrow-hover.png);
}
.result-block hr {
height: 1px;
line-height: 1px;
border: 0;
margin-top: 0;
clear: both;
background: #ffffff url(../images/old-browsers-bg/search-sep-bg.png) repeat-y left;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
left,
#ffffff,
#cccccc 50%,
#ffffff
);
background: -webkit-gradient(
linear,
left top, right top,
from(#ffffff),
to(#ffffff),
color-stop(0.5, #cccccc)
);
}
.result-block .result-info {
background: #333333;
color: white;
padding: 0.417em 0.75em 0.583em;
margin: 0 -1em -1em -1em;
-moz-border-radius: 0 0 0.5em 0.5em;
-webkit-border-bottom-right-radius: 0.5em;
-webkit-border-bottom-left-radius: 0.5em;
border-radius: 0 0 0.5em 0.5em;
white-space: nowrap;
}
.result-block .result-info a {
color: #77ccff;
}
.result-block .arrow:first-child + .result-info:last-child {
margin-top: -1em;
border-top: 1px solid #999999;
-moz-border-radius: 0.5em;
-webkit-border-radius: 0.5em;
-webkit-background-clip: padding-box;
border-radius: 0.5em;
}
/* IE class */
.result-block .result-info.first-last-child {
margin-top: -1em;
border-top: 1px solid #999999;
}
.result-block div + .result-info,
.result-block p + .result-info,
.result-block ul + .result-info {
margin-top: -0.5em;
}
.result-block .result-info.loading {
padding-left: 2.667em;
background: #333333 url(../images/table-loader.gif) no-repeat 0.75em center;
}
/***************** Search block *****************/
#search-form {
display: inline;
position: relative;
z-index: 91;
}
/********** Always visible control bar **********/
#control-bar {
padding: 1em 0;
text-align: center;
}
#control-bar.grey-bg {
border-bottom: 1px solid #efefef;
border-bottom: 1px solid rgba(255, 255, 255, 0.65);
background: url(../images/old-browsers-bg/control-bar-bg.png) repeat-x;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
rgba(0, 0, 0, 0.2),
rgba(0, 0, 0, 0.1)
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(rgba(0, 0, 0, 0.2)),
to(rgba(0, 0, 0, 0.1))
);
-moz-box-shadow: inset 0 1px 5px rgba(0, 0, 0, 0.35);
-webkit-box-shadow: inset 0 1px 5px rgba(0, 0, 0, 0.35);
box-shadow: inset 0 1px 5px rgba(0, 0, 0, 0.35);
}
#cb-place-holder {
display: none;
}
#control-bar.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
margin: 0;
z-index: 999950;
background: url(../images/old-browsers-bg/black50.png);
background: rgba(0, 0, 0, 0.5);
}
#control-bar.fixed.grey-bg {
border: 0;
-moz-border-radius: 0;
-webkit-border-radius: 0;
-webkit-background-clip: padding-box;
border-radius: 0;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
}
/**************** Standard block ****************/
article {
margin-top: 3em;
}
#control-bar + article,
#cb-place-holder + article {
margin-top: 2em;
}
.block-content h1,
.block-content .h1 {
position: absolute;
left: 0.5em;
top: -0.444em;
margin: 0;
z-index: 100;
-moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
-moz-border-radius: 0.278em;
-webkit-border-radius: 0.278em;
-webkit-background-clip: padding-box;
border-radius: 0.278em;
}
/* IE class */
.ie .block-content h1,
.ie .block-content .h1 {
padding: 0.333em 0.444em;
}
.block-content .h1 h1 {
position: relative;
left: 0;
top: 0;
z-index: 1;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
-moz-border-radius: 0;
-webkit-border-radius: 0;
-webkit-background-clip: padding-box;
border-radius: 0;
padding: 0;
}
.block-content h1 > a,
.block-content .h1 > a {
display: block;
position: absolute;
top: -1px;
left: 100%;
margin-left: 0.5em;
font-size: 0.778em;
text-transform: uppercase;
color: #cccccc;
border: 1px solid;
border-color: #7e9098 #61727b #2b373d;
background: #40535c url(../images/old-browsers-bg/title-link-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
white,
#9eb1ba 4%,
#40535c
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#40535c),
color-stop(0.03, #9eb1ba)
);
-moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
-moz-border-radius: 0.286em;
-webkit-border-radius: 0.286em;
-webkit-background-clip: padding-box;
border-radius: 0.286em;
line-height: 1.143em;
padding: 0.5em 0.571em;
white-space: nowrap;
}
/* IE class */
.ie7 .block-content h1 > a,
.ie7 .block-content .h1 > a {
padding: 0.429em 0.571em;
}
.block-content h1 > a:hover,
.block-content .h1 > a:hover {
color: white;
border-color: #1eafdc #1193d5 #035592;
background: #057fdb url(../images/old-browsers-bg/title-link-hover-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
white,
#2bcef3 4%,
#057fdb
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#057fdb),
color-stop(0.03, #2bcef3)
);
}
.block-content h1 > a img,
.block-content .h1 > a img {
margin-bottom: -3px;
}
.red .block-content h1 > a:hover,
.red .block-content .h1 > a:hover,
.block-content.red h1 > a:hover,
.block-content.red .h1 > a:hover,
.block-content .red h1 > a:hover,
.block-content .red .h1 > a:hover,
.block-content h1.red > a:hover,
.block-content .h1.red > a:hover {
border-color: #c24949 #9d3d3d #590909;
background: #9d0404 url(../images/old-browsers-bg/button-element-red-hover-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
white,
#fe6565 4%,
#9d0404
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#9d0404),
color-stop(0.03, #fe6565)
);
}
.block-content {
padding-top: 2.833em;
}
.block-content.no-title {
padding-top: 1.667em;
}
.block-content.no-padding.no-title {
padding-top: 0;
}
/***************** Block header *****************/
.block-header {
font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Sans", Arial, Helvetica, sans-serif;
}
.block-content .block-header:first-child,
.block-content h1:first-child + .block-header,
.block-content .h1:first-child + .block-header {
margin-top: -1.417em;
-moz-border-radius: 0.083em 0.083em 0 0;
-webkit-border-top-left-radius: 0.083em;
-webkit-border-top-right-radius: 0.083em;
border-radius: 0.083em 0.083em 0 0;
}
/* IE class */
.block-content .block-header.first-child,
.block-content .block-header.after-h1 {
margin-top: -1.417em;
}
.block-content.no-title .block-header:first-child {
margin-top: -0.833em;
}
/* IE class */
.block-content.no-title .block-header.first-child {
margin-top: -0.833em;
}
.block-content.no-padding .block-header:first-child {
margin-top: 0;
}
/* IE class */
.block-content.no-padding .block-header.first-child {
margin-top: 0;
}
/***************** Wizard tweak *****************/
.block-content .wizard-steps:first-child,
.block-content h1:first-child + .wizard-steps,
.block-content .h1:first-child + .wizard-steps {
margin-top: -2.833em;
-moz-border-radius: 0.167em 0.167em 0 0;
-webkit-border-top-left-radius: 0.167em;
-webkit-border-top-right-radius: 0.167em;
border-radius: 0.167em 0.167em 0 0;
}
/* IE class */
.block-content .wizard-steps.first-child,
.block-content .wizard-steps.after-h1 {
margin-top: -2.833em;
}
.block-content.no-title .wizard-steps:first-child {
margin-top: -1.667em;
}
/* IE class */
.block-content.no-title .wizard-steps.first-child {
margin-top: -1.667em;
}
.block-content.no-padding .wizard-steps:first-child {
margin-top: 0;
}
/* IE class */
.block-content.no-padding .wizard-steps.first-child {
margin-top: 0;
}
/**************** Block controls ****************/
.block-content .block-controls:first-child,
.block-content h1:first-child + .block-controls,
.block-content .h1:first-child + .block-controls {
margin-top: -2.833em;
-moz-border-radius-topleft: 0.2em;
-moz-border-radius-topright: 0.2em;
-webkit-border-top-left-radius: 0.2em;
-webkit-border-top-right-radius: 0.2em;
border-top-left-radius: 0.2em;
border-top-right-radius: 0.2em;
}
/* IE class */
.block-content .block-controls.first-child,
.block-content .block-controls.after-h1 {
margin-top: -2.833em;
}
.block-content.no-title .block-controls:first-child {
margin-top: -1.667em;
}
/* IE class */
.block-content.no-title .block-controls.first-child {
margin-top: -1.667em;
}
.block-content.no-padding .block-controls:first-child {
margin-top: 0;
}
/* IE class */
.block-content.no-padding .block-controls.first-child {
margin-top: 0;
}
.block-content .block-controls:first-child ul.controls-tabs li:last-child a,
.block-content h1:first-child + .block-controls ul.controls-tabs li:last-child a,
.block-content .h1:first-child + .block-controls ul.controls-tabs li:last-child a {
-moz-border-radius-topright: 0.2em;
-webkit-border-top-right-radius: 0.2em;
border-top-right-radius: 0.2em;
}
/* IE class */
.block-content .block-controls.first-child ul.controls-tabs li.last-child a,
.block-content .block-controls.after-h1 ul.controls-tabs li.last-child a {
-moz-border-radius-topright: 0.2em;
-webkit-border-top-right-radius: 0.2em;
border-top-right-radius: 0.2em;
}
.block-content.no-padding .block-controls:last-child {
-moz-border-radius-bottomleft: 0.2em;
-moz-border-radius-bottomright: 0.2em;
-webkit-border-bottom-left-radius: 0.2em;
-webkit-border-bottom-right-radius: 0.2em;
border-bottom-left-radius: 0.2em;
border-bottom-right-radius: 0.2em;
}
/****************** Action tabs *****************/
.action-tabs {
position: absolute;
z-index: 89;
right: 100%;
width: 3em;
overflow: hidden;
padding-top: 2em;
}
.block-border > .action-tabs,
.block-content > .action-tabs {
margin-right: 1px;
}
.action-tabs.right {
right: auto;
left: 100%;
}
.block-border > .action-tabs.right,
.block-content > .action-tabs.right {
margin-right: 0;
margin-left: 1px;
}
.action-tabs li {
float: right;
width: 1.5em;
padding: 0.667em 0.417em 0.667em 0.667em;
-moz-border-radius: 0.5em 0 0 0.5em;
-webkit-border-top-left-radius: 0.5em;
-webkit-border-bottom-left-radius: 0.5em;
border-radius: 0.5em 0 0 0.5em;
background: url(../images/old-browsers-bg/white20.png);
background: rgba(255, 255, 255, 0.2);
-moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
margin: 0 -0.167em 0.5em 0;
-moz-transition: all 300ms;
-webkit-transition: all 300ms;
-o-transition: all 300ms;
transition: all 300ms;
}
.action-tabs.right li {
float: left;
padding: 0.667em 0.667em 0.667em 0.417em;
margin: 0 0 0.5em -0.167em;
-moz-border-radius: 0 0.5em 0.5em 0;
-webkit-border-top-left-radius: 0;
-webkit-border-bottom-left-radius: 0;
-webkit-border-top-right-radius: 0.5em;
-webkit-border-bottom-right-radius: 0.5em;
border-radius: 0 0.5em 0.5em 0;
text-align: right;
}
.action-tabs li:hover {
margin-right: 0;
-moz-transition: all 100ms;
-webkit-transition: all 100ms;
-o-transition: all 100ms;
transition: all 100ms;
}
.action-tabs.right li:hover {
margin-left: 0;
}
.action-tabs li a {
display: block;
margin: -0.667em -0.5em -0.667em -0.667em;
padding: 0.583em 0.5em 0.583em 0.583em;
border: 0.083em solid;
border-color: #c8cacc white #777a7d #aeb0b4;
border-right: 0;
-moz-border-radius: 0.5em 0 0 0.5em;
-webkit-border-top-left-radius: 0.5em;
-webkit-border-bottom-left-radius: 0.5em;
border-radius: 0.5em 0 0 0.5em;
background: #9a9ea3 url(../images/old-browsers-bg/action-tab-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#82858b,
#9a9ea3
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#82858b),
to(#9a9ea3)
);
}
.action-tabs.right li a {
margin: -0.667em -0.667em -0.667em -0.5em;
padding: 0.583em 0.583em 0.583em 0.5em;
border-left: 0;
border-right: 0.083em solid;
border-color: #c8cacc #77797e #777a7d white;
-moz-border-radius: 0 0.5em 0.5em 0;
-webkit-border-top-left-radius: 0;
-webkit-border-bottom-left-radius: 0;
-webkit-border-top-right-radius: 0.5em;
-webkit-border-bottom-right-radius: 0.5em;
border-radius: 0 0.5em 0.5em 0;
text-align: right;
}
.action-tabs li:hover a {
border-color: #dcddde white #999a9d #cfd0d3;
background: #c7c9cd url(../images/old-browsers-bg/action-tab-hover-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#afb0b4,
#c7c9cd
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#afb0b4),
to(#c7c9cd)
);
}
.action-tabs.right li:hover a {
border-color: #dcddde #9b9da0 #999a9d white;
}
/****************** Messages ********************/
.message {
margin-bottom: 2.5em;
}
section .message {
margin-bottom: 1.667em;
}
/**************** Content columns ***************/
.content-columns {
position: relative;
z-index: 89;
margin: 0 -1.417em;
}
.content-columns:last-child {
margin-bottom: -1.667em;
}
/* IE class */
.content-columns.last-child {
margin-bottom: -1.667em;
}
.block-controls + .content-columns {
margin-top: -1.667em;
}
.block-content.no-title .content-columns:first-child {
margin-top: -1.667em;
}
/* IE class */
.block-content.no-title .content-columns.first-child {
margin-top: -1.667em;
}
.block-content.no-padding .content-columns:first-child {
margin-top: 0;
}
/* IE class */
.block-content.no-padding .content-columns.first-child {
margin-top: 0;
}
.content-left {
float: left;
width: 50%;
margin-left: -0.25em;
}
.content-right {
float: right;
width: 50%;
margin-right: -0.25em;
}
.content-columns .content-columns-sep {
position: absolute;
z-index: 88;
top: 0;
bottom: 0;
width: 0.417em;
left: 50%;
margin-left: -0.25em;
background: #c4c4c4 url(../images/old-browsers-bg/content-columns-sep-bg.png) repeat-y left;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
left,
#e6e6e6,
#c4c4c4
);
background: -webkit-gradient(
linear,
left top, right top,
from(#e6e6e6),
to(#c4c4c4)
);
border-left: 0.1em solid #999999;
border-right: 0.1em solid #999999;
}
/* Left column of 30% */
.content-columns.left30 .content-left { width: 30%; }
.content-columns.left30 .content-right { width: 70%; }
.content-columns.left30 .content-columns-sep { left: 30%; }
/* right column of 30% */
.content-columns.right30 .content-left { width: 70%; }
.content-columns.right30 .content-right { width: 30%; }
.content-columns.right30 .content-columns-sep { left: 70%; }
.content-columns .message {
margin: 0 !important;
border-width: 1px 0;
}
.content-columns .message:last-child {
-moz-border-radius: 0;
-webkit-border-radius: 0;
-webkit-background-clip: padding-box;
border-radius: 0;
border-bottom: 0;
}
/* IE class */
.content-columns .message.last-child {
margin-bottom: 0;
border-bottom: 0;
}
.content-columns:last-child .content-left > :last-child {
-moz-border-radius-bottomleft: 0.167em;
-webkit-border-bottom-left-radius: 0.167em;
border-bottom-left-radius: 0.167em;
}
.content-columns:last-child .content-right > :last-child {
-moz-border-radius-bottomright: 0.167em;
-webkit-border-bottom-right-radius: 0.167em;
border-bottom-right-radius: 0.167em;
}
.block-content.no-title .content-columns:first-child .content-left > :first-child {
-moz-border-radius-topleft: 0.167em;
-webkit-border-top-left-radius: 0.167em;
border-top-left-radius: 0.167em;
}
.block-content.no-title .content-columns:first-child .content-right > :last-child {
-moz-border-radius-topright: 0.167em;
-webkit-border-top-right-radius: 0.167em;
border-top-right-radius: 0.167em;
}
/**************** Drop-down menu ****************/
.with-menu,
.menu-opener {
padding-right: 1.75em;
position: relative;
z-index: 98;
}
/* IE class */
.ie .block-content .with-menu,
.ie .block-content .menu-opener {
padding-right: 1.75em;
}
.with-menu:hover,
.menu-opener:hover {
z-index: 99;
}
.button.with-menu, .button.menu-opener,
.form legend.with-menu, .form legend.menu-opener,
.mini-menu.with-menu, .mini-menu.menu-opener {
padding-right: 2.25em;
}
/* IE class */
.ie .block-content .button.with-menu,
.ie .block-content .button.menu-opener,
.ie .block-content .mini-menu.with-menu,
.ie .block-content .mini-menu.menu-opener {
padding-right: 2.25em;
}
.menu,
.menu-opener .menu-arrow {
position: absolute;
z-index: 99;
top: 0;
right: 0;
bottom: 0;
font-weight: normal;
line-height: 1.25em;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
.with-menu .menu,
.menu-opener .menu-arrow {
width: 1.75em;
background: url(../images/menu-border.png) no-repeat left center;
background-size: 2px 100%;
-moz-background-size: 2px 100%;
-webkit-background-size: 2px 100%;
}
.menu-opener .menu {
left: 0;
background: url(../images/trans.png);
}
.with-menu .menu > img,
.menu-opener .menu-arrow > img {
position: absolute;
left: 50%;
top: 50%;
margin: -8px 0 0 -7px;
}
.menu ul {
position: absolute;
z-index: 999910;
top: 100%;
left: 1px;
background: #cccccc url(../images/menu-bg.png) repeat-y;
border: 1px solid white;
padding: 0.25em 0;
margin: 0;
width: 15em;
display: none;
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.6);
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.6);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.6);
-moz-border-radius: 0 0.25em 0.25em 0.25em;
-webkit-border-radius: 0.25em;
-webkit-background-clip: padding-box;
-webkit-border-top-left-radius: 0;
border-radius: 0 0.25em 0.25em 0.25em;
}
.menu-opener .menu > ul {
left: -1px;
}
.menu ul.reverted {
-moz-border-radius: 0.25em 0 0.25em 0.25em;
-webkit-border-radius: 0.25em;
-webkit-background-clip: padding-box;
-webkit-border-top-right-radius: 0;
border-radius: 0.25em 0 0.25em 0.25em;
}
.menu > ul.reverted {
left: auto;
right: 1px;
}
.menu-opener .menu > ul.reverted {
right: -1px;
}
.menu:hover > ul,
.menu :hover > ul {
display: block;
}
.menu ul li ul {
display: block;
top: 0.6em;
left: 94%;
width: 4px;
height: 6px;
border: none;
background: url(../images/menu-arrow.png) no-repeat;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
-moz-border-radius: 0;
-webkit-border-radius: 0;
-webkit-background-clip: padding-box;
border-radius: 0;
}
.menu ul li ul li {
display: none;
}
.menu ul li:hover > ul {
top: -0.167em;
left: 98%;
width: 15em;
height: auto;
border: 1px solid white;
background: #cccccc url(../images/menu-bg.png) repeat-y;
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.6);
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.6);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.6);
}
.menu ul li:hover > ul.reverted {
left: auto;
right: 98%;
}
.menu ul li:hover > ul > li {
display: block;
}
.menu ul li {
position: relative;
z-index: 999911;
padding: 0.333em 0.833em 0.417em 35px;
margin: 0;
color: #999999;
-moz-text-shadow: 1px 1px 0 white;
-webkit-text-shadow: 1px 1px 0 white;
text-shadow: 1px 1px 0 white;
background-repeat: no-repeat;
background-position: 5px 3px;
}
/* IE class */
.ie7 .menu > ul > li,
.ie7 .menu ul li:hover > ul > li {
display: inline-block;
padding-left: 0;
padding-right: 0;
text-indent: 35px;
}
.menu ul li.sep {
height: 0;
font-size: 0;
line-height: 0;
padding: 0;
margin: 2px 0;
border-top: 1px solid #adadad;
border-bottom: 1px solid white;
}
/* IE class */
.ie7 .menu ul li.sep {
z-index: 999910;
}
.menu ul li a {
display: block;
margin: -0.333em -0.833em -0.417em -9px;
padding: 0.333em 0.833em 0.417em 9px;
color: #1e343f;
-moz-text-shadow: none;
-webkit-text-shadow: none;
text-shadow: none;
}
/* IE class */
.ie7 .menu ul li a {
margin-right: 0;
margin-left: 26px;
text-indent: 0;
}
.menu ul li:hover {
z-index: 999912;
background-color: #c0c0c0;
}
.menu ul li.sep:hover {
z-index: 999911;
}
.menu ul li:hover > a {
background: #4d4d4d;
color: white;
}
.menu .icon_address { background-image: url(../images/icons/fugue/address-book.png); }
.menu .icon_alarm { background-image: url(../images/icons/fugue/alarm-clock-blue.png); }
.menu .icon_blog { background-image: url(../images/icons/fugue/application-blog.png); }
.menu .icon_terminal { background-image: url(../images/icons/fugue/application-terminal.png); }
.menu .icon_battery { background-image: url(../images/icons/fugue/battery-full.png); }
.menu .icon_building { background-image: url(../images/icons/fugue/building.png); }
.menu .icon_calendar { background-image: url(../images/icons/fugue/calendar-day.png); }
.menu .icon_cards { background-image: url(../images/icons/fugue/cards-address.png); }
.menu .icon_chart { background-image: url(../images/icons/fugue/chart.png); }
.menu .icon_computer { background-image: url(../images/icons/fugue/computer.png); }
.menu .icon_database { background-image: url(../images/icons/fugue/database.png); }
.menu .icon_delete { background-image: url(../images/icons/fugue/cross-circle.png); }
.menu .icon_doc_excel { background-image: url(../images/icons/fugue/document-excel.png); }
.menu .icon_doc_pdf { background-image: url(../images/icons/fugue/document-pdf.png); }
.menu .icon_doc_csv { background-image: url(../images/icons/fugue/document-excel-csv.png); }
.menu .icon_doc_image { background-image: url(../images/icons/fugue/document-image.png); }
.menu .icon_doc_web { background-image: url(../images/icons/fugue/document-globe.png); }
.menu .icon_down { background-image: url(../images/icons/fugue/arrow-270.png); }
.menu .icon_edit { background-image: url(../images/icons/fugue/pencil.png); }
.menu .icon_film { background-image: url(../images/icons/fugue/film.png); }
.menu .icon_security { background-image: url(../images/icons/fugue/hard-hat.png); }
.menu .icon_images { background-image: url(../images/icons/fugue/images.png); }
.menu .icon_mail { background-image: url(../images/icons/fugue/mail.png); }
.menu .icon_monitor { background-image: url(../images/icons/fugue/monitor.png); }
.menu .icon_newspaper { background-image: url(../images/icons/fugue/newspaper.png); }
.menu .icon_search { background-image: url(../images/icons/fugue/magnifier.png); }
.menu .icon_network { background-image: url(../images/icons/fugue/globe-network.png); }
.menu .icon_server { background-image: url(../images/icons/fugue/server.png); }
.menu .icon_export { background-image: url(../images/icons/fugue/application-export.png); }
.menu .icon_refresh { background-image: url(../images/icons/fugue/arrow-circle.png); }
.menu .icon_reset { background-image: url(../images/icons/fugue/counter-reset.png); }
.menu .icon_up { background-image: url(../images/icons/fugue/arrow-090.png); }
nav > ul > li > ul > li.with-menu,
nav > ul > li > ul > li.menu-opener {
padding-right: 2.3em;
}
nav > ul > li > ul > li.with-menu > a,
nav > ul > li > ul > li.menu-opener > a {
-moz-border-radius-topright: 0;
-moz-border-radius-bottomright: 0;
-webkit-border-top-right-radius: 0;
-webkit-border-bottom-right-radius: 0;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
padding-right: 0.8em;
}
nav > ul > li > ul > li.with-menu .menu,
nav > ul > li > ul > li.menu-opener .menu-arrow {
width: 1.75em;
font-size: 1.2em;
height: 1.834em; /* Chrome 5 is one pixel short with 0.833, dunno why... */
line-height: 1.833em;
text-transform: none;
top: 1px;
right: 1px;
-moz-border-radius-topright: 0.3em;
-moz-border-radius-bottomright: 0.3em;
-webkit-border-top-right-radius: 0.3em;
-webkit-border-bottom-right-radius: 0.3em;
border-top-right-radius: 0.3em;
border-bottom-right-radius: 0.3em;
}
nav > ul > li > ul > li.menu-opener .menu {
font-size: 1.2em;
line-height: 1.25em;
text-transform: none;
}
nav > ul > li > ul > li.with-menu.current .menu,
nav > ul > li > ul > li.menu-opener.current .menu-arrow {
-moz-border-radius-bottomright: 0;
-webkit-border-bottom-right-radius: 0;
border-bottom-right-radius: 0;
background: none !important;
height: 2.333em;
line-height: 2.333em;
border-left: 1px solid #ccc;
}
nav > ul > li > ul > li.with-menu.current .menu:hover,
nav > ul > li > ul > li.menu-opener.current .menu-arrow:hover {
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
}
nav > ul > li > ul > li.with-menu .menu > img,
nav > ul > li > ul > li.menu-opener .menu-arrow > img {
margin-top: -9px;
margin-left: -8px;
}
nav > ul > li > ul > li.with-menu .menu > ul {
line-height: 1.2em;
left: -1px;
}
nav > ul > li > ul > li .menu > ul,
nav > ul > li > ul > li .menu ul li:hover > ul {
background-image: url(../images/main-menu-bg.png);
background-color: #1c1e20;
border-color: #b3b3b3;
}
nav > ul > li > ul > li .menu ul li {
color: #666666;
-moz-text-shadow: none;
-webkit-text-shadow: none;
text-shadow: none;
}
nav > ul > li > ul > li .menu ul li a {
color: white;
}
nav > ul > li > ul > li .menu ul li.sep {
border-top-color: black;
border-bottom-color: #666666;
}
section h1.with-menu,
section .h1.with-menu,
section h1.menu-opener,
section .h1.menu-opener {
padding-right: 1.667em;
}
section h1 .menu,
section .h1 .menu {
font-size: 0.667em;
-moz-border-radius: 0 0.278em 0.278em 0;
-webkit-border-top-right-radius: 0.278em;
-webkit-border-bottom-right-radius: 0.278em;
border-radius: 0 0.278em 0.278em 0;
}
.ie section h1 .menu,
.ie section .h1 .menu {
background: url(../images/trans.png);
}
section h1 .menu:hover,
section .h1 .menu:hover {
background: url(../images/menu-border.png) no-repeat left center,
-moz-linear-gradient(
top,
white,
#2bcef3 5%,
#057fdb
);
background: url(../images/menu-border.png) no-repeat left center,
-webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#057fdb),
color-stop(0.05, #2bcef3)
);
}
section h1.menu-opener .menu:hover,
section .h1.menu-opener .menu:hover {
background: none;
}
section h1 .menu-arrow,
section .h1 .menu-arrow {
font-size: 0.667em;
}
section h1 .menu > ul,
section h1 .menu ul li:hover > ul,
section .h1 .menu > ul,
section .h1 .menu ul li:hover > ul {
background-image: url(../images/h1-menu-bg.png);
background-color: #006699;
border-color: #99ccff;
}
section h1 .menu ul li,
section .h1 .menu ul li {
color: #3399cc;
-moz-text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.3);
-webkit-text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.3);
text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.3);
}
section h1 .menu ul li a,
section .h1 .menu ul li a {
color: white;
}
section h1 .menu ul li:hover,
section .h1 .menu ul li:hover {
background-color: #70b7db;
-moz-text-shadow: none;
-webkit-text-shadow: none;
text-shadow: none;
}
section h1 .menu ul li:hover > a,
section .h1 .menu ul li:hover > a {
background-color: #004a6f;
}
section h1 .menu ul li.sep,
section .h1 .menu ul li.sep {
border-top-color: #004a6f;
border-bottom-color: #84c8e1;
}
section h1 .menu ul li ul,
section .h1 .menu ul li ul {
background-image: url(../images/menu-arrow-white.png);
}
.button.with-menu .menu:hover,
.button.menu-opener:hover .menu-arrow {
background: url(../images/menu-border.png) no-repeat left center,
-moz-linear-gradient(
top,
#dff3fc,
#98d2f3
);
background: url(../images/menu-border.png) no-repeat left center,
-webkit-gradient(
linear,
left top, left bottom,
from(#dff3fc),
to(#98d2f3)
);
}
#contextMenu.menu {
top: 0;
left: 0;
bottom: auto;
width: 0;
display: none;
padding: 1em;
margin: -1em 0 0 -1em;
-moz-border-radius: 1em;
-webkit-border-radius: 1em;
-webkit-background-clip: padding-box;
border-radius: 1em;
background: rgba(255, 255, 255, 0.5);
}
#contextMenu.menu > ul {
display: block;
top: 50%;
left: 50%;
}
/***************** Notifications ****************/
#notifications {
position: fixed;
z-index: 999990;
top: 1em;
right: 1em;
width: 20em;
}
#notifications li {
position: relative;
background: url(../images/old-browsers-bg/black80.png);
background: rgba(0, 0, 0, 0.8);
padding: 1.25em;
color: white;
margin-bottom: 1em;
-moz-border-radius: 0.417em;
-webkit-border-radius: 0.417em;
-webkit-background-clip: padding-box;
border-radius: 0.417em;
-moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
}
/********************* Footer *******************/
footer {
text-align: center;
position: fixed;
z-index: 100;
left: 0;
right: 0;
bottom: 0;
}
footer .float-left,
footer .float-right {
position: absolute;
bottom: 0;
}
footer .float-left {
left: 0;
}
footer .float-right {
right: 0;
}
footer .float-left .button,
footer .float-right .button {
-moz-border-radius: 0;
-webkit-border-radius: 0;
-webkit-background-clip: padding-box;
border-radius: 0;
margin: 0;
display: block;
float: left;
border-bottom: 0;
}
footer .float-left .button:first-child {
border-left: 0;
}
/* IE class */
footer .float-left .button.first-child {
border-left: 0;
}
footer .float-left .button:last-child {
-moz-border-radius-topright: 0.417em;
-webkit-border-top-right-radius: 0.417em;
border-top-right-radius: 0.417em;
}
footer .float-right .button:last-child {
border-right: 0;
}
/* IE class */
footer .float-right .button.last-child {
border-right: 0;
}
footer .float-right .button:first-child {
-moz-border-radius-topleft: 0.417em;
-webkit-border-top-left-radius: 0.417em;
border-top-left-radius: 0.417em;
}
/****************** Modal window ****************/
#modal {
background: url(../images/old-browsers-bg/black50.png);
background: rgba(0, 0, 0, 0.5);
position: fixed;
z-index: 999980;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
div.modal-window {
position: absolute;
left: 0;
top: 0;
-moz-box-shadow: 0 1px 7px rgba(0, 0, 0, 0.75);
-webkit-box-shadow: 0 1px 7px rgba(0, 0, 0, 0.75);
box-shadow: 0 1px 7px rgba(0, 0, 0, 0.75);
}
.modal-content {
overflow: hidden;
margin: -2.833em -1.667em -1.667em;
padding: 2.833em 1.667em 1.667em;
}
.no-title .modal-content {
margin-top: -1.667em;
padding-top: 1.667em;
}
.modal-content + .block-footer {
margin-top: 1.667em;
}
.modal-content.modal-scroll {
overflow: auto;
}
#modal > .block-border > .block-content {
z-index: 90;
}
#modal h1 {
cursor: move;
-webkit-user-select:none;
-moz-user-select:none;
}
.modal-loading {
background: url(../images/arbo-loader.gif) no-repeat center 3em;
height: 4em;
padding-top: 4.5em;
color: #999999;
text-align: center;
}
#modal .block-border > .action-tabs.right {
padding-top: 1em;
}
#modal .block-content > .action-tabs.right {
padding-top: 0;
margin-top: -2em;
}
/* Resizing zones */
.modal-resize-tl,
.modal-resize-t,
.modal-resize-tr,
.modal-resize-r,
.modal-resize-br,
.modal-resize-b,
.modal-resize-bl,
.modal-resize-l {
background: url(../images/trans.png);
position: absolute;
z-index: 89;
}
.modal-resize-tl {
top: 0;
left: 0;
width: 2em;
height: 1em;
cursor: nw-resize;
}
.modal-resize-t {
top: 0;
left: 2em;
right: 2em;
height: 1em;
cursor: n-resize;
}
.modal-resize-tr {
top: 0;
right: 0;
width: 2em;
height: 1em;
cursor: ne-resize;
}
.modal-resize-r {
top: 1em;
right: 0;
width: 1em;
bottom: 1em;
cursor: e-resize;
}
.modal-resize-br {
bottom: 0;
right: 0;
width: 2em;
height: 1em;
cursor: se-resize;
}
.modal-resize-b {
bottom: 0;
left: 2em;
right: 2em;
height: 1em;
cursor: s-resize;
}
.modal-resize-bl {
bottom: 0;
left: 0;
width: 2em;
height: 1em;
cursor: sw-resize;
}
.modal-resize-l {
top: 1em;
left: 0;
width: 1em;
bottom: 1em;
cursor: w-resize;
}
/* http://perishablepress.com/press/2008/02/05/lessons-learned-concerning-the-clearfix-css-hack */
#control-bar:after,
.columns:after,
.content-columns:after,
article:after {
clear: both;
content: ' ';
display: block;
font-size: 0;
line-height: 0;
visibility: hidden;
width: 0;
height: 0;
}
#control-bar,
.columns,
.content-columns,
article {
display: inline-block;
}
* html #control-bar,
* html .columns,
* html .content-columns,
* html article {
height: 1%;
}
#control-bar,
.columns,
.content-columns,
article {
display: block;
} | 0a1b2c3d4e5 | trunk/BloumGenerator/include/css/standard.css | CSS | asf20 | 56,622 |
/*
* Global reset
* Based on Eric Meyer's : http://meyerweb.com/eric/thoughts/2008/01/15/resetting-again/
*/
a, abbr, acronym, address, applet, article, aside, audio,
b, big, blockquote, body,
canvas, caption, center, cite, code, command,
datalist, dd, del, details, dfn, div, dl, dt,
em, embed,
fieldset, figcaption, figure, font, footer, form,
h1, h2, h3, h4, h5, h6, header, hgroup, html,
i, iframe, img, ins,
kbd, keygen,
label, legend, li,
meter,
nav,
object, ol, output,
p, pre, progress,
q,
s, samp, section, small, source, span, strike, strong, sub, sup,
table, tbody, td, tfoot, th, thead, tr, tt,
u, ul,
var, video {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
z-index: 1;
}
/*
* Default HTML5 behaviour for older browsers
*/
article, aside, audio, canvas, command, datalist,
details, embed, figcaption, figure, footer, header,
hgroup, keygen, meter, nav, output, progress,
section, source, video { display: block; }
mark, rp, rt, ruby, summary, time{ display: inline }
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
:focus {
outline: 0;
}
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
a {
text-decoration: none;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: collapse;
border-spacing: 0;
} | 0a1b2c3d4e5 | trunk/BloumGenerator/include/css/reset.css | CSS | asf20 | 1,467 |
/**
* Common styles for all variants (standard or mobile)
* z-index hierachy :
* 88, 89 or 90 : Positioned elements at normal level
* 98 or 99 : Positioned for menu
* 100 : footer
* 999900 : tooltip
* 999910 : menu
* 999950 : fixed control bar
* 999980 : modal windows
* 999990 : notifications
*/
html {
background: #d5d8db;
}
body {
color: #333333;
font-size: 75%;
}
body.dark {
background-color: #70828f;
}
.white-text {
color: white;
}
p, th, td {
line-height: 1.25em;
}
p, ul, ol, dl, .with-margin {
margin-bottom: 1.667em;
}
.small-margin {
margin-bottom: 0.5em;
}
.medium-margin {
margin-bottom: 1em;
}
.large-margin {
margin-bottom: 2.417em;
}
a {
color: #3399cc;
text-decoration: none;
}
strong {
color: #3399cc;
}
small {
color: #808080;
font-size: 0.833em;
text-transform: uppercase;
font-weight: normal;
}
small strong {
color: #808080;
}
h2 {
color: #3399cc;
font-size: 1.25em;
line-height: 1.267em;
margin-bottom: 1.267em;
}
h3 {
color: #3399cc;
font-size: 1.25em;
line-height: 1.267em;
}
h5 {
font-weigth: bold;
color: #333;
}
hr {
height: 0;
line-height: 0;
border: 0;
border-top: 1px dotted #cccccc;
margin-bottom: 1.667em;
}
a.red, .red a
h2.red, .red h2,
h3.red, .red h3 {
color: #cc3333;
}
h2:last-child,
p:last-child,
ul:last-child,
ol:last-child,
dl:last-child,
hr:last-child {
margin-bottom: 0;
}
/* IE class */
h2.last-child,
p.last-child,
ul.last-child,
ol.last-child,
dl.last-child,
hr.last-child {
margin-bottom: 0;
}
/**************** Generic classes ***************/
.align-left {
text-align: left;
}
.align-center {
text-align: center;
}
.align-right {
text-align: right;
}
.margin-left {
margin-left: 1em;
}
.margin-right {
margin-right: 1em;
}
.gutter-left {
margin-left: 2em;
}
.gutter-right {
margin-right: 2em;
}
.float-left {
float: left;
}
.float-right {
float: right;
}
.relative {
position: relative;
z-index: 89;
}
.absolute {
position: absolute;
z-index: 89;
}
.upper-index {
z-index: 90 !important;
}
.with-padding {
padding: 1em;
}
.no-bottom-margin {
margin-bottom: 0 !important;
}
.box {
-moz-border-radius: 0.25em;
-webkit-border-radius: 0.25em;
-webkit-background-clip: padding-box;
border-radius: 0.25em;
-moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
padding: 0.75em;
margin-bottom: 1.667em;
background: white;
}
/* IE class */
.ie .box {
border: 1px solid #cccccc;
}
.infos {
background-image: url(../images/icons/web-app/48/Info.png);
background-repeat: no-repeat;
padding-left: 5em;
margin-bottom: 1em;
min-height: 4em;
}
.mini-infos {
background-image: url(../images/icons/web-app/24/Info.png);
background-repeat: no-repeat;
padding: 0.167em 0 0.167em 2.5em;
margin-bottom: 1em;
min-height: 1.5em;
}
.info:last-child,
.mini-infos:last-child {
margin-bottom: 0;
}
/* IE class */
.info.last-child,
.mini-infos.last-child {
margin-bottom: 0;
}
.infos p,
.mini-infos p {
color: #808080;
}
.picto {
margin-bottom: -4px;
}
.empty {
color: #999999 !important;
font-style: italic;
}
.number {
display: block;
float: left;
min-width: 1em;
padding: 0.25em;
font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Sans", Arial, Helvetica, sans-serif;
font-weight: bold;
color: white;
text-align: center;
-moz-border-radius: 0.25em;
-webkit-border-radius: 0.25em;
-webkit-background-clip: padding-box;
border-radius: 0.25em;
margin-right: 0.5em;
background: #3399cc;
}
.number.red,
.red .number {
background-color: #cc3333;
}
.bigger {
font-size: 2.5em;
}
h2.bigger {
margin-bottom: 0.8em;
}
.big {
font-size: 1.5em;
}
.small {
font-size: 0.833em;
}
.smaller {
font-size: 0.75em;
}
/**************** Generic styles ***************/
.grey {
color: #666666;
}
.white-bg {
background-color: white;
}
.grey-bg {
background-color: #c1c8cb;
}
.block-content .grey-bg {
background-color: #e6e6e6;
}
p.grey-bg {
padding: 0.417em 0.5em;
-moz-border-radius: 0.333em;
-webkit-border-radius: 0.333em;
-webkit-background-clip: padding-box;
border-radius: 0.333em;
}
.dark-grey-gradient {
background: #666666 url(../images/old-browsers-bg/dark-grey-gradient-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#3d3d3d,
#484848 2%,
#585858 8%,
#666666
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#3d3d3d),
to(#666666),
color-stop(0.02, #484848),
color-stop(0.08, #585858)
);
color: white;
}
.lite-grey-gradient {
background: white url(../images/old-browsers-bg/lite-grey-gradient-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#d5d5d5,
white
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#d5d5d5),
to(white)
);
}
/****************** Main title ******************/
article h1 {
color: #3f525f;
font-size: 1.5em;
-moz-text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.3);
-webkit-text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.3);
text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.3);
margin-bottom: 1em;
}
.block-content h1,
.block-content .h1 {
color: white;
font-size: 1.5em;
font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Sans", Arial, Helvetica, sans-serif;
border: 1px solid;
border-color: #50a3c8 #297cb4 #083f6f;
background: #0c5fa5 url(../images/old-browsers-bg/title-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
white,
#72c6e4 4%,
#0c5fa5
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#0c5fa5),
color-stop(0.03, #72c6e4)
);
-moz-text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.2);
-webkit-text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.2);
text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.2);
padding: 0.278em 0.444em 0.389em;
}
.block-content .h1 h1 {
font-size: 1em;
border: 0;
background: none;
-moz-text-shadow: none;
-webkit-text-shadow: none;
text-shadow: none;
padding: 0;
}
.block-content h1.red,
.block-content .h1.red,
.block-content .red h1,
.block-content .red .h1,
.block-content.red h1,
.block-content.red .h1,
.red .block-content h1,
.red .block-content .h1 {
border-color: #bf3636 #5d0000 #0a0000;
background: #790000 url(../images/old-browsers-bg/title-red-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
white,
#ca3535 4%,
#790000
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#790000),
color-stop(0.03, #ca3535)
);
}
/************** Button-style links **************/
.button,
.form legend,
.legend,
.mini-menu {
line-height: 1.333em;
padding: 0.167em 0.5em 0.25em;
border: 1px solid white;
-moz-border-radius: 0.417em;
-webkit-border-radius: 0.417em;
-webkit-background-clip: padding-box;
border-radius: 0.417em;
-moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
text-decoration: none;
font-weight: normal;
-moz-text-shadow: none;
-webkit-text-shadow: none;
text-shadow: none;
outline: 0;
}
.button {
display: inline-block;
}
/* IE class */
.ie .button,
.ie .form legend,
.ie .legend,
.ie .mini-menu {
border-color: #cccccc;
}
.button {
color: #666666;
background: #dfdfdf url(../images/old-browsers-bg/button-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#f6f6f6,
#dfdfdf
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#f6f6f6),
to(#dfdfdf)
);
}
.button.red,
.red .button {
color: white;
background: #790000 url(../images/old-browsers-bg/button-red-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#ca3535,
#790000
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#ca3535),
to(#790000)
);
}
.button.red a,
.red .button a {
color: white;
}
a.button:hover,
.mini-menu > li > a:hover {
color: #115577;
background: #98d2f3 url(../images/old-browsers-bg/button-hover-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#dff3fc,
#98d2f3
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#dff3fc),
to(#98d2f3)
);
}
a.button.red:hover,
.red a.button:hover {
color: white;
background: #9d0404 url(../images/old-browsers-bg/button-red-hover-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#fe6565,
#9d0404
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(fe6565),
to(#9d0404)
);
}
.form legend,
.legend,
.mini-menu {
color: #666666;
background: #e7e7e7 url(../images/old-browsers-bg/legend-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#f8f8f8,
#e7e7e7
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#f8f8f8),
to(#e7e7e7)
);
}
.button img,
.form legend img,
.legend img,
.mini-menu img {
margin-bottom: -2px;
}
/******************** Button ********************/
button,
.big-button {
display: inline-block;
border: 1px solid;
border-color: #50a3c8 #297cb4 #083f6f;
background: #0c5fa5 url(../images/old-browsers-bg/button-element-bg.png) repeat-x left top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
white,
#72c6e4 4%,
#0c5fa5
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#0c5fa5),
color-stop(0.03, #72c6e4)
);
-moz-border-radius: 0.333em;
-webkit-border-radius: 0.333em;
-webkit-background-clip: padding-box;
border-radius: 0.333em;
color: white;
-moz-text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
-webkit-text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);
font-size: 1.167em;
padding: 0.286em 1em 0.357em;
line-height: 1.429em;
cursor: pointer;
font-weight: bold;
}
/* IE class */
.ie button {
overflow: visible;
}
/* IE class */
.ie7 button {
padding-top: 0.357em;
padding-bottom: 0.214em;
line-height: 1.143em;
}
button img,
.big-button img {
margin-bottom: -3px;
}
button:hover,
.big-button:hover {
border-color: #1eafdc #1193d5 #035592;
background: #057fdb url(../images/old-browsers-bg/button-element-hover-bg.png) repeat-x left top;
background: -moz-linear-gradient(
top,
white,
#2bcef3 4%,
#057fdb
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#057fdb),
color-stop(0.03, #2bcef3)
);
}
button:active,
.big-button:active {
border-color: #5b848b #b2def1 #b2def1 #68a6ba;
background: #3dbfed url(../images/old-browsers-bg/button-element-active-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#89e7f9,
#3dbfed
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#89e7f9),
to(#3dbfed)
);
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
}
button.red,
.red button,
.big-button.red,
.red .big-button {
color: white;
border-color: #bf3636 #5d0000 #0a0000;
background: #790000 url(../images/old-browsers-bg/button-element-red-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
white,
#ca3535 4%,
#790000
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#790000),
color-stop(0.03, #ca3535)
);
}
button.red:hover,
.red button:hover,
.big-button.red:hover,
.red .big-button:hover {
border-color: #c24949 #9d3d3d #590909;
background: #9d0404 url(../images/old-browsers-bg/button-element-red-hover-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
white,
#fe6565 4%,
#9d0404
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#9d0404),
color-stop(0.03, #fe6565)
);
}
button.red:active,
.red button:active,
.big-button.red:active,
.red .big-button:active {
border-color: #7c5656 #f7cbcb #f7cbcb #a15151;
background: #ff5252 url(../images/old-browsers-bg/button-element-red-active-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#ff9d9d,
#ff5252
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#ff9d9d),
to(#ff5252)
);
}
button:disabled,
button:disabled:hover,
.big-button.disabled,
.big-button.disabled:hover {
color: #bfbfbf;
border-color: #e9f2f6 #c4c3c3 #a2a2a2 #e3e2e2;
background: #c8c8c8 url(../images/old-browsers-bg/button-element-disabled-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#f0f2f2,
#c8c8c8
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#f0f2f2),
to(#c8c8c8)
);
-moz-text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.75);
-webkit-text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.75);
text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.75);
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
cursor: auto;
}
/* IE class */
button.disabled,
button.disabled:hover {
color: #bfbfbf;
border-color: #e9f2f6 #c4c3c3 #a2a2a2 #e3e2e2;
background: #c8c8c8 url(../images/old-browsers-bg/button-element-disabled-bg.png) repeat-x top;
cursor: auto;
}
button.grey,
.big-button.grey {
color: white;
border-color: #a1a7ae #909498 #6b7076;
background: #9fa7b0 url(../images/old-browsers-bg/button-element-grey-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
white,
#c5cbce 5%,
#9fa7b0
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#9fa7b0),
color-stop(0.05, #c5cbce)
);
-moz-text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
-webkit-text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
}
button.grey:hover,
.big-button.grey:hover {
border-color: #a1a7b0 #939798 #6e7275;
background: #b1b5ba url(../images/old-browsers-bg/button-element-grey-hover-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
white,
#d6dadc 4%,
#b1b5ba
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#b1b5ba),
color-stop(0.03, #d6dadc)
);
}
button.grey:active
.big-button.grey:active {
border-color: #666666 #ffffff #ffffff #979898;
background: #dddddd url(../images/old-browsers-bg/button-element-grey-active-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#f1f1f1,
#dddddd
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#f1f1f1),
to(#dddddd)
);
}
button.small,
.big-button.small {
font-size: 0.833em;
padding: 0.2em 0.3em 0.3em 0.2em;
vertical-align: 0.2em;
}
/* IE class */
.ie button.small {
padding: 0.5em 0.3em;
vertical-align: 0.1em;
}
.ie7 button + button {
margin-left: 0.25em;
}
/**************** Standard block ****************/
section {
margin-bottom: 3em;
}
.block-content {
border: 1px solid #999999;
-moz-border-radius: 0.25em;
-webkit-border-radius: 0.25em;
-webkit-background-clip: padding-box;
border-radius: 0.25em;
padding: 1.667em;
background: white;
-moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
position: relative;
}
.block-content.dark-bg {
border-color: #aaa #333 #000 #666;
background: #555 url(../images/old-browsers-bg/content-dark-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#555,
#222
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#222),
to(#555)
);
color: white;
}
.block-border {
padding: 0.833em;
border: 1px solid white;
border-color: rgba(255, 255, 255, 0.75);
background: url(../images/old-browsers-bg/white20.png);
background: rgba(255, 255, 255, 0.2);
-moz-border-radius: 0.8em;
-webkit-border-radius: 0.8em;
-webkit-background-clip: padding-box;
border-radius: 0.8em;
-moz-box-shadow: 0 0 4px rgba(50, 50, 50, 0.5);
-webkit-box-shadow: 0 0 4px rgba(50, 50, 50, 0.5);
box-shadow: 0 0 4px rgba(50, 50, 50, 0.5);
}
.block-border .block-content {
-moz-box-shadow: 0 0 0.8em rgba(255, 255, 255, 0.5);
-webkit-box-shadow: 0 0 0.8em rgba(255, 255, 255, 0.5);
box-shadow: 0 0 0.8em rgba(255, 255, 255, 0.5);
}
.block-border .block-content + .block-content {
margin-top: 0.833em;
}
.block-content .no-margin {
margin-left: -1.667em;
margin-right: -1.667em;
}
.block-content p.no-margin + .no-margin,
.block-content ul.no-margin + .no-margin,
.block-content ol.no-margin + .no-margin,
.block-content dl.no-margin + .no-margin {
margin-top: -1.667em;
}
/* Recursion prevention */
.block-content .no-margin > .no-margin {
margin-left: 0;
margin-right: 0;
}
.block-content .no-margin:last-child {
margin-bottom: -1.667em;
-moz-border-radius-bottomleft: 0.167em;
-moz-border-radius-bottomright: 0.167em;
-webkit-border-bottom-left-radius: 0.167em;
-webkit-border-bottom-right-radius: 0.167em;
border-bottom-left-radius: 0.167em;
border-bottom-right-radius: 0.167em;
}
/* Recursion prevention */
.block-content .no-margin > .no-margin:last-child {
margin-bottom: 0;
-moz-border-radius-bottomleft: 0;
-moz-border-radius-bottomright: 0;
-webkit-border-bottom-left-radius: 0;
-webkit-border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
/* IE class */
.block-content .no-margin.last-child {
margin-bottom: -1.667em;
}
/* Recursion prevention */
.block-content .no-margin > .no-margin.last-child {
margin-bottom: 0;
}
.block-content hr.no-margin {
margin-bottom: 1.667em;
}
.block-content.no-padding {
padding: 0;
}
.block-content.no-padding .no-margin {
margin-left: 0;
margin-right: 0;
}
.block-content p.no-margin + .no-margin,
.block-content ul.no-margin + .no-margin,
.block-content ol.no-margin + .no-margin,
.block-content dl.no-margin + .no-margin {
margin-top: -1.667em;
}
.block-content.no-padding .no-margin:last-child {
margin-bottom: 0;
}
/* IE class */
.block-content.no-padding .no-margin.last-child {
margin-bottom: 0;
}
/***************** Block header *****************/
.block-header {
font-size: 2em;
font-weight: bold;
height: 3em;
line-height: 3em;
border-top: 1px solid #9bd2ee;
border-bottom: 1px solid #b5b3b4;
background: #0c5fa3 url(../images/old-browsers-bg/block-header-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#6dc3e6,
#0c5fa3
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#6dc3e6),
to(#0c5fa3)
);
text-align: center;
color: white;
-moz-text-shadow: 0 1px 3px rgba(0, 0, 0, 0.75);
-webkit-text-shadow: 0 1px 3px rgba(0, 0, 0, 0.75);
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.75);
margin: 0 -0.833em 0.833em -0.833em;
}
.block-header:first-child {
margin-top: -0.833em;
}
/* IE class */
.block-header.first-child {
margin-top: -0.833em;
}
.block-header + .no-margin {
margin-top: -1.667em;
}
.block-header.red,
.red .block-header {
border-top-color: #e46f6f;
background: #790000 url(../images/old-browsers-bg/block-header-red-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#ca3535,
#790000
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#790000),
to(#ca3535)
);
}
/**************** Block controls ****************/
.block-controls {
text-align: right;
border-bottom: 1px solid #999999;
background: white url(../images/old-browsers-bg/block-controls-bg.png) repeat-x bottom;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
white,
#e5e5e5 88%,
#d8d8d8
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#d8d8d8),
color-stop(0.88, #e5e5e5)
);
margin: 0 -1.667em 1.667em -1.667em;
padding: 1em;
}
.no-margin .block-controls:first-child {
margin-left: 0;
margin-right: 0;
}
.block-controls:first-child {
margin-top: -1.667em;
}
/* IE class */
.block-controls.first-child {
margin-top: -1.667em;
}
.block-controls + .no-margin {
margin-top: -1.667em;
}
.block-content.no-padding .block-controls {
margin: 0 !important;
border-bottom: 0;
}
ul.controls-buttons,
div.controls-buttons {
float: right;
}
ul.controls-buttons li,
div.controls-buttons > div,
div.controls-buttons > span,
div.controls-buttons > a {
display: block;
float: left;
margin: -1px 0 -1px 0.5em;
line-height: 1.333em;
padding: 0.333em 0.25em;
}
ul.controls-buttons li.sep,
div.controls-buttons > div.sep,
div.controls-buttons > span.sep {
padding: 0;
width: 2px;
min-width: 2px;
height: 4em;
margin: -1em 0.25em -1em 0.75em;
border: none;
background: url(../images/controls-bt-sep.png) no-repeat bottom;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
-moz-border-radius: 0;
-webkit-border-radius: 0;
-webkit-background-clip: padding-box;
border-radius: 0;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
}
ul.controls-buttons li.controls-block,
ul.controls-buttons li a,
div.controls-buttons > div,
div.controls-buttons > span,
div.controls-buttons > a {
display: block;
color: #333333;
min-width: 1.083em;
padding: 0.333em 0.5em;
text-align: center;
border: 1px solid white;
-moz-border-radius: 0.5em;
-webkit-border-radius: 0.5em;
-webkit-background-clip: padding-box;
border-radius: 0.5em;
background: #e7e7e7 url(../images/old-browsers-bg/controls-bt-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#f8f8f8,
#e7e7e7
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#f8f8f8),
to(#e7e7e7)
);
-moz-box-shadow: 0 0 0.25em rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 0 0.25em rgba(0, 0, 0, 0.5);
box-shadow: 0 0 0.25em rgba(0, 0, 0, 0.5);
text-transform: uppercase;
}
ul.controls-buttons li a {
margin: -0.333em -0.25em;
line-height: 1.333em;
}
div.controls-buttons > div div,
div.controls-buttons > div span,
div.controls-buttons > div a {
color: #333333;
display: block;
height: 1.333em;
line-height: 1.333em;
float: left;
min-width: 1.083em;
padding: 0.333em 0.5em;
margin: -0.333em 0;
text-align: center;
text-transform: uppercase;
}
div.controls-buttons > div:hover div,
div.controls-buttons > div:hover span,
div.controls-buttons > div:hover a {
color: white;
}
div.controls-buttons > div div:first-child,
div.controls-buttons > div span:first-child,
div.controls-buttons > div a:first-child {
margin-left: -0.5em;
}
/* IE class */
div.controls-buttons > div div.first-child,
div.controls-buttons > div span.first-child,
div.controls-buttons > div a.first-child {
margin-left: -0.5em;
}
div.controls-buttons > div > div:first-child,
div.controls-buttons > div > span:first-child,
div.controls-buttons > div > a:first-child {
-moz-border-radius-topleft: 0.417em;
-moz-border-radius-bottomleft: 0.417em;
-webkit-border-top-left-radius: 0.417em;
-webkit-border-bottom-left-radius: 0.417em;
-webkit-background-clip: padding-box;
border-top-left-radius: 0.417em;
border-bottom-left-radius: 0.417em;
}
div.controls-buttons > div div:last-child,
div.controls-buttons > div span:last-child,
div.controls-buttons > div a:last-child {
margin-right: -0.5em;
}
/* IE class */
div.controls-buttons > div div.last-child,
div.controls-buttons > div span.last-child,
div.controls-buttons > div a.last-child {
margin-right: -0.5em;
}
div.controls-buttons > div > div:last-child,
div.controls-buttons > div > span:last-child,
div.controls-buttons > div > a:last-child {
-moz-border-radius-topright: 0.417em;
-moz-border-radius-bottomright: 0.417em;
-webkit-border-top-right-radius: 0.417em;
-webkit-border-bottom-right-radius: 0.417em;
-webkit-background-clip: padding-box;
border-top-right-radius: 0.417em;
border-bottom-right-radius: 0.417em;
}
div.controls-buttons > div .control-first,
div.controls-buttons > div .control-prev,
div.controls-buttons > div .control-next,
div.controls-buttons > div .control-last {
min-width: auto;
width: 16px;
overflow: hidden;
text-indent: 100px;
background-repeat: no-repeat;
background-position: center;
}
div.controls-buttons > div .control-first {
background-image: url(../images/icons/fugue/control-double-180.png);
}
div.controls-buttons > div .control-prev {
background-image: url(../images/icons/fugue/control-180.png);
}
div.controls-buttons > div .control-next {
background-image: url(../images/icons/fugue/control.png);
}
div.controls-buttons > div .control-last {
background-image: url(../images/icons/fugue/control-double.png);
}
/* IE class */
.ie ul.controls-buttons li.controls-block,
.ie ul.controls-buttons li a,
.ie div.controls-buttons > div,
.ie div.controls-buttons > span,
.ie div.controls-buttons > a {
border-color: #cccccc;
}
ul.controls-buttons li a:hover,
ul.controls-buttons li a.current,
div.controls-buttons > div:hover,
div.controls-buttons > span:hover,
div.controls-buttons > a:hover,
div.controls-buttons > .current {
border-color: #1eafdc #1193d5 #035592;
background: #057fdb url(../images/old-browsers-bg/block-control-hover-bg.png) repeat-x;
background: -moz-linear-gradient(
top,
white,
#2bcef3 5%,
#057fdb
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(white),
to(#057fdb),
color-stop(0.05, #2bcef3)
);
color: white;
}
div.controls-buttons > div:hover a,
div.controls-buttons > span:hover a {
color: white;
}
div.controls-buttons > span.sep:hover {
background: url(../images/controls-bt-sep.png) no-repeat bottom;
}
ul.controls-buttons li a:hover strong,
ul.controls-buttons li a.current strong,
div.controls-buttons > div:hover strong,
div.controls-buttons > span:hover strong,
div.controls-buttons > a:hover strong,
div.controls-buttons > .current strong {
color: white;
}
div.controls-buttons > div.sub-hover:hover {
border: 1px solid white;
background: #e7e7e7 url(../images/old-browsers-bg/controls-bt-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#f8f8f8,
#e7e7e7
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#f8f8f8),
to(#e7e7e7)
);
color: #333333;
}
div.controls-buttons > div.sub-hover:hover strong {
color: #333333;
}
div.controls-buttons > div.sub-hover:hover div,
div.controls-buttons > div.sub-hover:hover span,
div.controls-buttons > div.sub-hover:hover a {
color: #333333;
}
div.controls-buttons > div div:hover,
div.controls-buttons > div span:hover,
div.controls-buttons > div a:hover {
background-color: #e0e0e0;
background-color: rgba(0, 0, 0, 0.1);
color: white;
}
div.controls-buttons > div.sub-hover div:hover,
div.controls-buttons > div.sub-hover span:hover,
div.controls-buttons > div.sub-hover a:hover {
color: #333333;
}
/* DataTables specific style */
div.controls-buttons > div.sub-hover.paging_full_numbers span:hover {
background-color: none;
color: #333333;
}
div.controls-buttons > div.sub-hover.paging_full_numbers span.paginate_button:hover,
div.controls-buttons > div.sub-hover.paging_full_numbers span.paginate_active:hover {
background-color: #e0e0e0;
background-color: rgba(0, 0, 0, 0.1);
color: white;
}
div.controls-buttons > div .disabled {
opacity: 0.5;
filter: alpha(opacity=50);
}
div.controls-buttons > div .disabled:hover {
background-color: transparent;
}
.controls-buttons img {
margin: -0.25em 0;
}
/* IE class */
.ie7 .controls-buttons img {
margin: 0;
vertical-align: middle;
}
.controls-buttons img:first-child {
margin-left: -0.085em;
}
/* IE class */
.controls-buttons img.first-child {
margin-left: -0.085em;
}
.controls-buttons img:last-child {
margin-right: -0.085em;
}
/* IE class */
.controls-buttons img.last-child {
margin-right: -0.085em;
}
.controls-buttons .progress-bar {
margin: -0.25em 0;
}
.controls-buttons input[type=text],
.controls-buttons input[type=password],
.controls-buttons .input-type-text,
.controls-buttons select {
margin-top: -0.5em;
margin-bottom: -0.5em;
}
ul.controls-tabs {
height: 47px;
float: right;
margin: -1em;
padding-left: 1px;
background: url(../images/controls-tabs-bg.png) no-repeat -48px 0;
}
ul.controls-tabs li {
height: 48px;
width: 49px;
float: left;
}
ul.controls-tabs li:last-child {
width: 48px;
}
/* IE class */
ul.controls-tabs li.last-child {
width: 48px;
}
ul.controls-tabs li a {
display: block;
height: 100%;
background: url(../images/controls-tabs-bg.png) no-repeat;
line-height: 48px;
text-align: center;
text-decoration: none;
color: #666666;
position: relative;
}
ul.controls-tabs li a:hover {
background-position: 0 -48px;
}
ul.controls-tabs li.current a,
ul.controls-tabs li.current a:hover {
background-position: 0 -96px;
}
ul.controls-tabs li a img {
position: absolute;
left: 50%;
top: 50%;
margin: -11px 0 0 -12px;
}
/***************** Block footer *****************/
.block-footer {
background: #bfbfbf url(../images/old-browsers-bg/block-footer-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#8b8b8b,
#a9a9a9 10%,
#bdbdbd 30%,
#bfbfbf
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#8b8b8b),
to(#bfbfbf),
color-stop(0.1, #a9a9a9),
color-stop(0.3, #bdbdbd)
);
margin: 0 -1.667em -1.667em -1.667em;
-moz-border-radius: 0 0 0.167em 0.167em;
-webkit-border-bottom-left-radius: 0.167em;
-webkit-border-bottom-right-radius: 0.167em;
border-radius: 0 0 0.167em 0.167em;
padding: 0.5em 0.75em;
line-height: 2em;
color: #4d4d4d;
}
section .no-margin > .block-footer {
margin-right: 0;
margin-left: 0;
margin-bottom: 0;
-moz-border-radius: 0;
-webkit-border-radius: ;
border-radius: 0;
}
section .no-margin:last-child > .block-footer:last-child {
-moz-border-radius: 0 0 0.167em 0.167em;
-webkit-border-bottom-left-radius: 0.167em;
-webkit-border-bottom-right-radius: 0.167em;
border-radius: 0 0 0.167em 0.167em;
}
section .block-header + .block-footer,
section .message.no-margin + .block-footer,
section .with-head.no-margin + .block-footer {
margin-top: -1.667em;
}
.block-footer .sep {
display: inline-block;
width: 2px;
height: 3em;
vertical-align: -0.667em;
margin: -0.5em 0.25em;
background: url(../images/controls-bt-sep.png) no-repeat bottom;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
}
/****************** Switches ********************/
.switch-replace {
display: inline-block;
width: 70px;
height: 30px;
background: url(../images/switch-bg.png) no-repeat 0 -34px;
vertical-align: middle;
cursor: pointer;
}
.switch:checked + .switch-replace {
background-position: 0 0;
}
.switch:disabled + .switch-replace {
background-position: 0 -68px;
}
/** IE class **/
.switch-replace-checked {
background-position: 0 0;
}
.switch-replace-disabled {
background-position: 0 -68px;
}
.mini-switch-replace {
display: inline-block;
width: 40px;
height: 20px;
background: url(../images/mini-switch-bg.png) no-repeat 0 -24px;
vertical-align: middle;
cursor: pointer;
}
.mini-switch:checked + .mini-switch-replace {
background-position: 0 0;
}
.mini-switch:disabled + .mini-switch-replace {
background-position: 0 -48px;
}
/** IE class **/
.mini-switch-replace-checked {
background-position: 0 0;
}
.mini-switch-replace-disabled {
background-position: 0 -48px;
}
/****************** Messages ********************/
.message {
line-height: 1.25em;
margin-bottom: 2.5em;
border: 1px solid #999999;
background: #F0F0F0;
-moz-border-radius: 0.333em;
-webkit-border-radius: 0.333em;
-webkit-background-clip: padding-box;
border-radius: 0.333em;
-moz-box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
position: relative;
z-index: 89;
}
ul.message {
padding: 0.583em 0 0.083em 0;
}
ul.message li {
text-transform: uppercase;
font-size: 0.833em;
line-height: 1.3em;
padding: 0.2em 1em 0.8em 3em;
background-repeat: no-repeat;
background-position: 0.8em 0.1em;
}
div.message,
p.message {
padding: 0.583em 0.833em 0.75em 2.5em;
background-repeat: no-repeat;
background-position: 0.667em 0.583em;
}
section .message {
margin-bottom: 1.667em;
}
.message:last-child {
margin-bottom: 0;
}
/* IE class */
.message.last-child {
margin-bottom: 0;
}
.block-content .message {
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
}
.block-content .message.no-margin {
margin: 0 -1.667em 1.667em -1.667em;
}
.block-content.no-padding .message.no-margin,
.block-content .no-margin > .message.no-margin {
margin-left: 0;
margin-right: 0;
}
.block-content .message.no-margin,
.block-content.no-padding .message {
-moz-border-radius: 0;
-webkit-border-radius: 0;
-webkit-background-clip: padding-box;
border-radius: 0;
border-width: 1px 0;
}
.block-content.no-title > .message.no-margin:first-child {
margin-top: -1.667em;
}
/* IE class */
.block-content.no-title > .message.no-margin.first-child {
margin-top: -1.667em;
}
.block-content.no-title > .message.no-margin:first-child,
.block-content.no-padding > .message:first-child {
border-top: none;
-moz-border-radius-topleft: 0.167em;
-moz-border-radius-topright: 0.167em;
-webkit-border-top-left-radius: 0.167em;
-webkit-border-top-right-radius: 0.167em;
border-top-left-radius: 0.167em;
border-top-right-radius: 0.167em;
}
/* IE class */
.block-content.no-title > .message.no-margin.first-child,
.block-content.no-padding > .message.first-child {
border-top: none;
}
.block-content > .message.no-margin:last-child {
margin-bottom: -1.667em;
}
/* IE class */
.block-content > .message.no-margin.last-child {
margin-bottom: -1.667em;
}
.block-content > .message.no-margin:last-child,
.block-content.no-padding > .message:last-child {
border-bottom: none;
-moz-border-radius-bottomleft: 0.167em;
-moz-border-radius-bottomright: 0.167em;
-webkit-border-bottom-left-radius: 0.167em;
-webkit-border-bottom-right-radius: 0.167em;
border-bottom-left-radius: 0.167em;
border-bottom-right-radius: 0.167em;
}
/* IE class */
.block-content > .message.no-margin.last-child,
.block-content.no-padding > .message.last-child {
border-bottom: none;
}
section .block-controls + .message.no-margin,
section .block-header + .message.no-margin,
section .message.no-margin + .message.no-margin {
margin-top: -1.667em;
border-top: none;
}
.message {
background-color: #e4e4dc;
border-color: #999999;
}
.message.warning {
background-color: #ffffcc;
border-color: #c3c39e;
}
.message.error {
background-color: #fff3f2;
border-color: #c00000;
}
.message.success {
background-color: #ddebdf;
border-color: #339933;
}
.message.loading {
background-color: #dcebf2;
border-color: #3399cc;
}
.message li,
div.message,
p.message {
background-image: url(../images/icons/fugue/information-ocre.png);
color: #576a73;
}
.message li strong,
div.message strong,
p.message strong {
color: #576a73;
}
.message.warning li,
div.message.warning,
p.message.warning {
background-image: url(../images/icons/fugue/balloon.png);
color: #56563e;
}
.message.warning li strong,
div.message.warning strong,
p.message.warning strong {
color: #56563e;
}
.message.error li,
div.message.error,
p.message.error {
background-image: url(../images/icons/fugue/cross-circle.png);
color: #563f3e;
}
.message.error li strong,
div.message.error strong,
p.message.error strong {
color: #563f3e;
}
.message.success li,
div.message.success,
p.message.success {
background-image: url(../images/icons/fugue/tick-circle.png);
color: #194a19;
}
.message.success li strong,
p.message.success strong {
color: #194a19;
}
.message.loading li,
div.message.loading,
p.message.loading {
background-image: url(../images/info-loader.gif);
color: #1e5774;
}
.message.loading li {
background-position: 0.8em 0.4em;
}
div.message.loading,
p.message.loading {
background-position: 0.667em 0.917em;
}
.message.loading li strong,
div.message.loading strong,
p.message.loading strong {
color: #1e5774;
}
/**************** Close button ******************/
.close-bt,
ul li.close-bt,
ul.message li.close-bt {
display: block;
position: absolute;
top: 0.083em;
right: 0.083em;
font-size: 1em;
line-height: 1em;
width: 1em;
height: 1em;
padding: 0;
margin: 0;
background: url(../images/icons/fugue/cross-small.png) no-repeat center center;
cursor: pointer;
-moz-border-radius: 0.333em;
-webkit-border-radius: 0.333em;
-webkit-background-clip: padding-box;
border-radius: 0.333em;
opacity: 0.5;
filter: alpha(opacity=0.5);
}
.close-bt:hover,
ul li.close-bt:hover {
opacity: 1;
filter: none;
}
/****************** Mini-menu *******************/
.mini-menu {
position: absolute;
z-index: 89;
right: 2em;
top: 0;
padding: 0;
height: 1.833em;
display: none;
margin: -1.083em 0 -1.083em;
white-space: nowrap;
}
td > .mini-menu {
position: relative;
right: 0;
top: 0;
float: right;
margin-right: 1em;
}
:hover > .mini-menu {
display: block;
}
.mini-menu > li {
float: left;
color: #999999;
font-style: normal;
height: 1.833em;
}
.mini-menu > li > a {
display: block;
line-height: 1.333em;
height: 1.333em;
padding: 0.25em 0.417em;
border-left: 1px solid white;
border-right: 1px solid #CCCCCC;
color: #999;
}
/* IE class */
.ie7 .mini-menu > li > a {
display: table-cell;
vertical-align: middle;
}
.mini-menu > li:first-child > a {
border-left: none;
-moz-border-radius-topleft: 0.25em;
-moz-border-radius-bottomleft: 0.25em;
-webkit-border-top-left-radius: 0.25em;
-webkit-border-bottom-left-radius: 0.25em;
border-top-left-radius: 0.25em;
border-bottom-left-radius: 0.25em;
}
/* IE class */
.mini-menu > li.first-child > a {
border-left: none;
}
.mini-menu > li:last-child > a {
border-right: none;
-moz-border-radius-topright: 0.25em;
-moz-border-radius-bottomright: 0.25em;
-webkit-border-top-right-radius: 0.25em;
-webkit-border-bottom-right-radius: 0.25em;
border-top-right-radius: 0.25em;
border-bottom-right-radius: 0.25em;
}
/* IE class */
.mini-menu > li.last-child > a {
border-right: none;
}
.mini-menu > li > a img {
margin: 0 0 -3px;
}
/* IE class */
.ie7 .mini-menu > li > a img {
margin: 0;
vertical-align: middle;
}
/********************* Tabs *********************/
ul.tabs li > a,
ul.side-tabs li > a,
ul.tabs li > span,
ul.side-tabs li > span {
display: block;
background: #eeeeee url(../images/old-browsers-bg/tabs-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#ffffff,
#eeeeee
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#ffffff),
to(#eeeeee)
);
padding: 0.583em;
color: #808080;
font-weight: bold;
border: 1px solid #b3b3b3;
text-decoration: none;
}
ul.tabs li > span,
ul.side-tabs li > span {
color: #bfbfbf;
}
ul.tabs li.current > a,
ul.side-tabs li.current > a,
ul.tabs li.current > span,
ul.side-tabs li.current > span {
background: white;
}
ul.tabs li > a:hover,
ul.side-tabs li > a:hover {
color: #3399cc;
border-color: #3399cc;
}
ul.tabs li > a img,
ul.side-tabs li > a img,
ul.tabs li > span img,
ul.side-tabs li > span img {
margin: -2px 0 -3px 0;
}
/* IE class */
.ie7 ul.tabs li > a img,
.ie7 ul.side-tabs > li a img,
.ie7 ul.tabs li > span img,
.ie7 ul.side-tabs > li span img {
margin-bottom: -2px;
}
ul.tabs {
margin-bottom: 1px;
height: 2.167em;
clear: none;
}
ul.tabs li {
float: left;
margin-right: 0.417em;
}
ul.tabs li > a,
ul.tabs li > span {
border-bottom: none;
-moz-border-radius: 0.25em 0.25em 0 0;
-webkit-border-top-left-radius: 0.25em;
-webkit-border-top-right-radius: 0.25em;
border-radius: 0.25em 0.25em 0 0;
margin-right: 0.083em;
}
ul.tabs li.current > a,
ul.tabs li.current > span {
padding-bottom: 0.667em;
}
ul.tabs li.with-margin {
margin-bottom: 0;
margin-left: 1em;
}
ul.side-tabs {
padding-top: 0.417em;
}
ul.side-tabs li > a,
ul.side-tabs li > span {
border-right: none;
-moz-border-radius: 0.25em 0 0 0.25em;
-webkit-border-top-left-radius: 0.25em;
-webkit-border-bottom-left-radius: 0.25em;
border-radius: 0.25em 0 0 0.25em;
margin-bottom: 0.417em;
}
ul.side-tabs li.current > a,
ul.side-tabs li.current > span {
margin-right: -1px;
}
ul.side-tabs li.icon-tab {
float: right;
}
ul.side-tabs li.icon-tab > a,
ul.side-tabs li.icon-tab > span {
padding-right: 0.5em;
}
ul.side-tabs li.with-margin {
margin-bottom: 0;
margin-top: 1em;
}
.tabs-content {
background-color: white;
border: 1px solid #b3b3b3;
-moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);
box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);
-moz-border-radius: 0.25em;
-webkit-border-radius: 0.25em;
-webkit-background-clip: padding-box;
border-radius: 0.25em;
padding: 1.667em;
}
ul.tabs + .tabs-content {
-moz-border-radius-topleft: 0;
-webkit-border-top-left-radius: 0;
border-top-left-radius: 0;
}
.mini-tabs {
border: 1px solid #b3b3b3;
border-width: 1px 0;
margin-bottom: 1.667em;
padding: 0.583em 0 0 0.5em;
height: 1.833em;
background: #dbdbdb url(../images/old-browsers-bg/mini-tabs-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#fafafa,
#dbdbdb
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#fafafa),
to(#dbdbdb)
);
}
.mini-tabs.no-margin {
margin: 0 -1.667em 1.667em -1.667em;
}
.mini-tabs.no-margin:first-child {
margin-top: -1.667em;
border-top: 0;
-moz-border-radius: 0.167em 0.167em 0 0;
-webkit-border-top-left-radius: 0.167em;
-webkit-border-top-right-radius: 0.167em;
border-radius: 0.167em 0.167em 0 0;
}
.mini-tabs li {
float: left;
height: 1.833em;
line-height: 1.833em;
margin-right: 0.5em;
}
.mini-tabs li > a {
display: block;
height: 1.333em;
line-height: 1.333em;
margin-top: -1px;
padding: 0.25em 0.583em;
border: 1px solid #b3b3b3;
border-bottom: 0;
-moz-border-radius: 0.25em 0.25em 0 0;
-webkit-border-top-left-radius: 0.25em;
-webkit-border-top-right-radius: 0.25em;
border-radius: 0.25em 0.25em 0 0;
background: #dddddd url(../images/old-browsers-bg/mini-tabs-tab-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#ffffff,
#dddddd
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#ffffff),
to(#dddddd)
);
color: #666666;
text-decoration: none;
}
.mini-tabs li > a img {
margin-bottom: -1px;
}
/* IE class */
.ie7 .mini-tabs li > a img {
vertical-align: middle;
}
.mini-tabs li.current > a {
background: white;
padding-bottom: 0.333em;
}
.mini-tabs li > a:hover {
color: #3399cc;
border-color: #3399cc;
}
/********************* Tips *********************/
#tips {
z-index: 999900;
position: absolute;
top: 0;
left: 0;
pointer-events: none;
}
#tips div {
position: absolute;
background: #ffffcc;
border: 1px solid #a6a6a6;
-moz-border-radius: 0.333em;
-webkit-border-radius: 0.333em;
-webkit-background-clip: padding-box;
border-radius: 0.333em;
font-family: Arial, Helvetica, sans-serif;
font-size: 0.75em;
line-height: 1.222em;
text-transform: uppercase;
color: #333333;
padding: 0.222em 0.444em;
min-width: 5em;
text-align: center;
white-space: nowrap;
}
#tips div .arrow {
font-size: 0;
line-height: 0;
width: 0;
position: absolute;
z-index: 89;
left: 50%;
margin-left: -6px;
bottom: -7px;
border-top: 7px solid #a6a6a6;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
}
#tips div.tip-right .arrow {
bottom: auto;
left: -7px;
top: 50%;
margin-left: 0;
margin-top: -6px;
border-right: 7px solid #a6a6a6;
border-top: 6px solid transparent;
border-bottom: 6px solid transparent;
border-left: 0;
}
#tips div.tip-bottom .arrow {
bottom: auto;
top: -7px;
border-top: 0;
border-bottom: 7px solid #a6a6a6;
}
#tips div.tip-left .arrow {
bottom: auto;
left: auto;
top: 50%;
right: -7px;
margin-left: 0;
margin-top: -6px;
border-left: 7px solid #a6a6a6;
border-top: 6px solid transparent;
border-bottom: 6px solid transparent;
border-right: 0;
}
#tips div .arrow span {
width: 0;
position: absolute;
z-index: 89;
margin-left: -5px;
top: -7px;
border-top: 6px solid #ffffcc;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
}
#tips div.tip-right .arrow span {
border-right: 6px solid #ffffcc;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-left: 0;
margin-left: 0;
left: 1px;
top: auto;
margin-top: -5px;
}
#tips div.tip-bottom .arrow span {
top: 1px;
border-top: 0;
border-bottom: 6px solid #ffffcc;
}
#tips div.tip-left .arrow span {
border-left: 6px solid #ffffcc;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-right: 0;
margin-left: 0;
right: 1px;
top: auto;
margin-top: -5px;
}
/***************** Loading tab ******************/
.loading-tab {
background: #8e8e8e url(../images/old-browsers-bg/loading-tab-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#636363,
#898989 25%,
#8e8e8e
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#636363),
to(#8e8e8e),
color-stop(0.25, #898989)
);
border: 1px solid #b6b6b6;
-moz-border-radius: 0.25em;
-webkit-border-radius: 0.25em;
-webkit-background-clip: padding-box;
border-radius: 0.25em;
color: white;
padding: 0.5em 0.75em;
line-height: 2em;
margin-bottom: 1.667em;
-moz-box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);
box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);
}
.loading-tab.no-margin {
border-width: 1px 0;
-moz-border-radius: 0;
-webkit-border-radius: 0;
-webkit-background-clip: padding-box;
border-radius: 0;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
}
.block-controls + .loading-tab.no-margin {
border-top: 0;
}
.with-padding .loading-tab.stick-to-top {
border-top: 0;
-moz-border-radius: 0 0 0.25em 0.25em;
-webkit-border-bottom-left-radius: 0.25em;
-webkit-border-bottom-right-radius: 0.25em;
border-radius: 0 0 0.25em 0.25em;
margin-top: -1em;
margin-bottom: 0;
}
/**************** Loading mask ******************/
.loading-mask {
position: absolute;
z-index: 89;
top: 0;
left: 0;
padding: 0;
margin: 0;
width: 100%;
height: 100%;
background: url(../images/old-browsers-bg/black50.png);
background: rgba(0, 0, 0, 0.5);
overflow: hidden;
}
.loading-mask span {
position: absolute;
z-index: 89;
left: 50%;
top: 50%;
margin-top: -3.5em;
margin-left: -4.5em;
padding: 60px 1em 1em;
min-width: 7em;
line-height: 1.25em;
text-align: center;
color: white;
background: black url(../images/mask-loader.gif) no-repeat center 17px;
-moz-border-radius: 0.5em;
-webkit-border-radius: 0.5em;
-webkit-background-clip: padding-box;
border-radius: 0.5em;
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
}
.loading-mask span.error {
background-image: url(../images/icons/web-app/32/Delete.png);
color: red;
cursor: pointer;
}
.loading-mask span a {
color: white;
font-weight: bold;
}
/**************** Progress bar ******************/
.progress-bar {
display: inline-block;
position: relative;
z-index: 89;
height: 1.167em;
margin: 0 0.25em;
width: 6em;
padding: 0;
-moz-border-radius: 0.167em;
-webkit-border-radius: 0.167em;
-webkit-background-clip: padding-box;
border-radius: 0.167em;
color: #333333;
border: 1px solid #808080;
min-width: auto;
text-transform: none;
background: #a5a5a5 url(../images/old-browsers-bg/progress-bar-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
left,
rgba(0, 0, 0, 0.2),
rgba(0, 0, 0, 0) 3%,
rgba(0, 0, 0, 0) 97%,
rgba(0, 0, 0, 0.2)
), -moz-linear-gradient(
top,
#808080,
#9b9b9b 15%,
#c3c3c3 85%,
#a5a5a5
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(rgba(0, 0, 0, 0.2)),
to(rgba(0, 0, 0, 0.2)),
color-stop(0.03, rgba(0, 0, 0, 0)),
color-stop(0.97, rgba(0, 0, 0, 0))
), -webkit-gradient(
linear,
left top, left bottom,
from(#808080),
to(#a5a5a5),
color-stop(0.15, #9b9b9b),
color-stop(0.85, #c3c3c3)
);
text-align: center;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
vertical-align: -0.083em;
}
/* IE class */
.ie7 .progress-bar {
vertical-align: middle;
margin-bottom: -0.083em;
}
.button .progress-bar {
vertical-align: -0.333em;
}
.progress-bar:first-child {
margin-left: 0;
}
/* IE class */
.progress-bar.first-child {
margin-left: 0;
}
.progress-bar:last-child {
margin-right: 0;
}
/* IE class */
.progress-bar.last-child {
margin-right: 0;
}
.progress-bar > span,
.progress-bar > span.blue {
display: block;
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 100%;
font-size: 0.75em;
line-height: 1.333em;
color: white;
padding: 0;
margin: 0;
-moz-border-radius: 0.11em;
-webkit-border-radius: 0.11em;
-webkit-background-clip: padding-box;
-moz-text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
-webkit-text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0 0 1px black;
-webkit-box-shadow: 0 0 1px black;
box-shadow: 0 0 1px black;
background: #4398c9 url(../images/old-browsers-bg/planning-bar-blue-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#b0cde5,
#6ec3e3 15%,
#0e62a8 73%,
#4398c9
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#b0cde5),
to(#4398c9),
color-stop(0.15, #6ec3e3),
color-stop(0.73, #0e62a8)
);
}
.progress-bar > span.with-stripes,
.progress-bar > span.blue.with-stripes {
background: #3399cc url(../images/loading-stripes.gif);
background-size: auto;
-moz-background-size: auto;
-webkit-background-size: auto;
background: url(../images/loading-stripes.png), -moz-linear-gradient(
top,
#b0cde5,
#6ec3e3 15%,
#0e62a8 73%,
#4398c9
);
background: url(../images/loading-stripes.gif), -webkit-gradient(
linear,
left top, left bottom,
from(#b0cde5),
to(#4398c9),
color-stop(0.15, #6ec3e3),
color-stop(0.73, #0e62a8)
);
}
.progress-bar > span.green {
border-color: #15a80e;
background: #56c943 url(../images/old-browsers-bg/planning-bar-green-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#b3e6b1,
#8ae46f 15%,
#15a80e 73%,
#56c943
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#b3e6b1),
to(#56c943),
color-stop(0.15, #8ae46f),
color-stop(0.73, #15a80e)
);
}
.progress-bar > span.green.with-stripes {
background: #33cc33 url(../images/loading-stripes.gif);
background-size: auto;
-moz-background-size: auto;
-webkit-background-size: auto;
background: url(../images/loading-stripes.png), -moz-linear-gradient(
top,
#b3e6b1,
#8ae46f 15%,
#15a80e 73%,
#56c943
);
background: url(../images/loading-stripes.gif), -webkit-gradient(
linear,
left top, left bottom,
from(#b3e6b1),
to(#56c943),
color-stop(0.15, #8ae46f),
color-stop(0.73, #15a80e)
);
}
.progress-bar > span.orange {
border-color: #a8750e;
background: #c99c43 url(../images/old-browsers-bg/planning-bar-orange-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#e6d4b1,
#e4bd6f 15%,
#a8750e 73%,
#c99c43
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#e6d4b1),
to(#c99c43),
color-stop(0.15, #e4bd6f),
color-stop(0.73, #a8750e)
);
}
.progress-bar > span.orange.with-stripes {
background: #ff9900 url(../images/loading-stripes.gif);
background-size: auto;
-moz-background-size: auto;
-webkit-background-size: auto;
background: url(../images/loading-stripes.png), -moz-linear-gradient(
top,
#e6d4b1,
#e4bd6f 15%,
#a8750e 73%,
#c99c43
);
background: url(../images/loading-stripes.gif), -webkit-gradient(
linear,
left top, left bottom,
from(#e6d4b1),
to(#c99c43),
color-stop(0.15, #e4bd6f),
color-stop(0.73, #a8750e)
);
}
.progress-bar > span.purple {
border-color: #a10ea8;
background: #b543c9 url(../images/old-browsers-bg/planning-bar-purple-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#e3b1e6,
#c86fe4 15%,
#a10ea8 73%,
#b543c9
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#e3b1e6),
to(#b543c9),
color-stop(0.15, #c86fe4),
color-stop(0.73, #a10ea8)
);
}
.progress-bar > span.purple.with-stripes {
background: #9933cc url(../images/loading-stripes.gif);
background-size: auto;
-moz-background-size: auto;
-webkit-background-size: auto;
background: url(../images/loading-stripes.png), -moz-linear-gradient(
top,
#e3b1e6,
#c86fe4 15%,
#a10ea8 73%,
#b543c9
);
background: url(../images/loading-stripes.gif), -webkit-gradient(
linear,
left top, left bottom,
from(#e3b1e6),
to(#b543c9),
color-stop(0.15, #c86fe4),
color-stop(0.73, #a10ea8)
);
}
/* Clear Floated Elements
----------------------------------------------------------------------------------------------------*/
/* http://sonspring.com/journal/clearing-floats */
.clear {
clear: both;
display: block;
overflow: hidden;
visibility: hidden;
width: 0;
height: 0;
}
/* http://perishablepress.com/press/2008/02/05/lessons-learned-concerning-the-clearfix-css-hack */
.clearfix:after,
.block-controls:after,
.side-tabs:after {
clear: both;
content: ' ';
display: block;
font-size: 0;
line-height: 0;
visibility: hidden;
width: 0;
height: 0;
}
.clearfix,
.block-controls,
.side-tabs {
display: inline-block;
}
* html .clearfix,
* html .block-controls,
* html .side-tabs {
height: 1%;
}
.clearfix,
.block-controls,
.side-tabs {
display: block;
} | 0a1b2c3d4e5 | trunk/BloumGenerator/include/css/common.css | CSS | asf20 | 61,487 |
/**
* Wizard styles
*/
.wizard-steps {
height: 6em;
line-height: 5.5em;
border: 1px solid #b5b3b4;
border-width: 1px 0;
border-top: 1px solid #9bd2ee;
background: #0c5fa3 url(../images/old-browsers-bg/block-header-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#6dc3e6,
#0c5fa3
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#6dc3e6),
to(#0c5fa3)
);
text-align: center;
margin-left: -1.667em;
margin-right: -1.667em;
}
.block-controls + .wizard-steps,
.no-margin + .wizard-steps {
margin-top: -1.667em;
}
.wizard-steps li {
display: inline-block;
height: 100%;
color: white;
font-size: 1.3em;
font-weight: bold;
font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Sans", Arial, Helvetica, sans-serif;
-moz-text-shadow: 0 1px 3px rgba(0, 0, 0, 0.75);
-webkit-text-shadow: 0 1px 3px rgba(0, 0, 0, 0.75);
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.75);
background: url(../images/wizard-head-effect.png) no-repeat right center;
padding: 0 1.25em 0 0.75em;
position: relative;
z-index: 89;
}
/* IE class */
.ie7 .wizard-steps li {
display: inline;
}
.wizard-steps li:last-child {
background: none;
padding-right: 0.75em;
}
/* IE class */
.wizard-steps li.last-child {
background: none;
padding-right: 0.75em;
}
.wizard-steps li.disabled {
-moz-text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.25);
-webkit-text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.25);
text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.25);
color: rgba(255, 255, 255, 0.5);
}
.wizard-steps li a {
color: white;
}
.wizard-steps li.disabled a {
color: rgba(255, 255, 255, 0.5);
}
.wizard-steps li .number {
font-size: 0.583em;
line-height: 1em;
width: 1.571em;
text-indent: 0;
padding: 0.286em 0;
position: absolute;
float: none;
z-index: 89;
left: 50%;
margin: 0 0 0 -1.143em;
bottom: -0.786em;
background: #0c5fa5 url(../images/old-browsers-bg/number-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#72c6e4,
#0c5fa5
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#72c6e4),
to(#0c5fa5)
);
border: 1px solid white;
-moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
-moz-text-shadow: none;
-webkit-text-shadow: none;
text-shadow: none;
-moz-transition: all 100ms;
-webkit-transition: all 100ms;
-o-transition: all 100ms;
transition: all 100ms;
}
.wizard-steps li:last-child .number {
margin-left: -0.786em;
}
/* IE class */
.wizard-steps li.last-child .number {
margin-left: -0.786em;
}
.wizard-steps li a:hover .number {
margin-bottom: 0.286em;
}
.wizard-steps li.disabled .number {
background: #dfdfdf url(../images/old-browsers-bg/button-bg.png) repeat-x top;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size: 100% 100%;
background: -moz-linear-gradient(
top,
#f6f6f6,
#dfdfdf
);
background: -webkit-gradient(
linear,
left top, left bottom,
from(#f6f6f6),
to(#dfdfdf)
);
color: #333333;
}
.wizard-steps li .number .status-ok,
.wizard-steps li .number .status-error,
.wizard-steps li .number .status-warning {
position: absolute;
z-index: 89;
width: 16px;
height: 16px;
background-repeat: no-repeat;
right: -8px;
top: -8px;
}
.wizard-steps li .number .status-ok { background-image: url(../images/icons/fugue/tick-circle.png); }
.wizard-steps li .number .status-error { background-image: url(../images/icons/fugue/cross-circle.png); }
.wizard-steps li .number .status-warning { background-image: url(../images/icons/fugue/exclamation-diamond.png); }
.block-content .wizard-steps + .no-margin {
margin-top: -1.667em;
}
.block-content .wizard-steps + .message.no-margin {
margin-top: -1.667em;
border-top: none;
} | 0a1b2c3d4e5 | trunk/BloumGenerator/include/css/wizard.css | CSS | asf20 | 4,541 |
/************** Forms & pseudo-form **************/
.form fieldset,
.fieldset {
border: 1px solid #d9d9d9;
padding: 1em 1.667em 1.667em 1.667em;
-moz-border-radius: 0.25em;
-webkit-border-radius: 0.25em;
-webkit-background-clip: padding-box;
border-radius: 0.25em;
margin-bottom: 1.667em;
}
/* IE class */
.ie7 .block-content .form fieldset.no-margin,
.ie7 .form.block-content fieldset.no-margin,
.ie7 .form .block-content fieldset.no-margin {
display: block;
width: 100%;
}
.fieldset {
position: relative;
z-index: 89;
padding-top: 1.667em;
}
.with-legend {
margin-top: 1em;
}
/* IE class */
.ie .form fieldset {
padding-top: 0;
}
.ie .form fieldset.no-legend {
padding-top: 1.667em;
}
.form legend,
.legend {
margin-left: -0.833em;
}
.legend {
position: absolute;
left: 1.667em;
top: -1.083em;
}
/* IE class */
.ie .form legend {
margin-bottom: 1em;
margin-top: -1em;
}
.ie .form .fieldset-with-legend {
margin-top: 2em;
}
.ie .form .fieldset-with-legend-first-child {
margin-top: 1em;
}
.form legend a,
.legend a {
display: block;
margin: -0.25em -0.333em -0.333em -0.5em;
padding: 0.25em 20px 0.333em 0.5em;
color: #666;
background: url(../images/icons/fugue/chevron-off.png) no-repeat right 60%;
}
.form legend a:hover,
.legend a:hover {
color: #3399cc;
background-image: url(../images/icons/fugue/chevron.png);
}
.form fieldset.collapsed,
.fieldset.collapsed {
border: none;
padding: 0;
background: none;
}
.form fieldset.no-margin.collapsed,
.fieldset.no-margin.collapsed {
padding-left: 1.667em;
}
.form fieldset.no-margin.collapsed:last-child,
.fieldset.no-margin.collapsed:last-child {
padding-bottom: 1.667em;
}
/* IE class */
.form fieldset.no-margin.collapsed.last-child,
.fieldset.no-margin.collapsed.last-child {
padding-bottom: 0.667em;
}
.form fieldset.collapsed > *,
.fieldset.collapsed > * {
display: none;
}
.form fieldset.collapsed legend,
.fieldset.collapsed .legend {
display: block;
margin-left: 0;
}
.ie7 .form fieldset.collapsed legend,
.ie7 .fieldset.collapsed .legend {
display: inline-block;
}
.form fieldset.collapsed legend a,
.fieldset.collapsed .legend a {
background-image: url(../images/icons/fugue/chevron-expand-off.png);
}
.form fieldset.collapsed legend a:hover,
.fieldset.collapsed .legend a:hover {
background-image: url(../images/icons/fugue/chevron-expand.png);
}
fieldset legend .show-expanded, .fieldset .legend .show-expanded { display: inline; }
fieldset legend .show-collapsed, .fieldset .legend .show-collapsed { display: none; }
fieldset.collapsed legend .show-expanded, .fieldset.collapsed .legend .show-expanded { display: none; }
fieldset.collapsed legend .show-collapsed, .fieldset.collapsed .legend .show-collapsed { display: inline; }
.block-content .form fieldset.no-margin,
.block-content.form fieldset.no-margin,
.form .block-content fieldset.no-margin,
.block-content .fieldset.no-margin {
border-color: #999999;
border-width: 1px 0 1px 0;
-moz-border-radius: 0;
-webkit-border-radius: 0;
-webkit-background-clip: padding-box;
border-radius: 0;
}
.form fieldset.no-margin legend,
.fieldset.no-margin .legend {
margin-left: 0;
}
/* IE class */
.ie7 .form fieldset.no-margin legend {
margin-left: -0.667em;
}
.form fieldset:last-child,
.fieldset:last-child {
margin-bottom: 0;
}
/* IE class */
.form fieldset.last-child,
.fieldset.last-child {
margin-bottom: 0;
}
.block-content .form fieldset.no-margin:last-child,
.block-content.form fieldset.no-margin:last-child,
.form .block-content fieldset.no-margin:last-child,
section .fieldset.no-margin:last-child {
border-bottom: 0;
-moz-border-radius: 0 0 0.167em 0.167em;
-webkit-border-bottom-left-radius: 0.167em;
-webkit-border-bottom-right-radius: 0.167em;
border-radius: 0 0 0.167em 0.167em;
}
/* IE class */
.block-content .form fieldset.no-margin.last-child,
.block-content.form fieldset.no-margin.last-child,
.form .block-content fieldset.no-margin.last-child,
.fieldset.no-margin.last-child {
border-bottom: 0;
}
.form label,
.form .label {
color: #808080;
font-weight: bold;
display: block;
margin-bottom: 0.5em;
}
.form label.light,
.form .label.light {
font-weight: normal;
color: #777;
}
.form label.inline,
.form .label.inline {
display: inline;
float: none;
margin: 0;
font-weight: normal;
}
.form .required label,
.form .required .label,
.form label.required,
.form .label.required,
.form label.inline.required,
.form .label.inline.required {
color: black;
}
.form .required label:before,
.form .required .label:before,
.form label.required:before,
.form .label.required:before {
color: red;
content: "* ";
}
/** IE class **/
.form .required-label-before {
color: red;
}
p.inline-label,
.inline-label p {
padding-left: 20em;
}
p.inline-mini-label,
.inline-mini-label p {
padding-left: 5em;
}
p.inline-small-label,
.inline-small-label p {
padding-left: 11em;
}
p.inline-medium-label,
.inline-medium-label p {
padding-left: 15em;
}
.inline-label label,
.inline-label .label,
.inline-mini-label label,
.inline-mini-label .label,
.inline-small-label label,
.inline-small-label .label,
.inline-medium-label label,
.inline-medium-label .label {
display: block;
float: left;
color: #333333;
padding: 0.667em 0 0.583em;
}
.inline-label label,
.inline-label .label {
width: 19em;
margin-left: -20em;
}
.inline-mini-label label,
.inline-mini-label .label {
width: 4em;
margin-left: -5em;
}
.inline-small-label label,
.inline-small-label .label {
width: 10em;
margin-left: -11em;
}
.inline-medium-label label,
.inline-medium-label .label {
width: 14em;
margin-left: -15em;
}
/** IE class **/
.form input[type=text],
.form input[type=password],
.form .input-type-text {
font-size: 1em;
line-height: 1em;
color: #333333;
padding: 0.5em;
border: 1px solid #89bad3;
background: white url(../images/old-browsers-bg/input-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#d4d4d4,
#ebebeb 3px,
white 27px
), white;
background: -webkit-gradient(
linear,
left 0px, left 27px,
from(#d4d4d4),
to(white),
color-stop(0.12, #ebebeb)
), white;
-moz-border-radius: 0.417em;
-webkit-border-radius: 0.417em;
-webkit-background-clip: padding-box;
border-radius: 0.417em;
}
.form input[type=text],
.form input[type=password] {
padding-bottom: 0.583em;
}
.form input[type=text]:focus,
.form input[type=password]:focus,
.form .input-type-text:focus,
.form select:focus,
.form textarea:focus {
border-color: #3399cc;
}
/** IE selector **/
.form .input-focus {
border-color: #3399cc;
}
.form span.input-type-text {
display: inline-block;
}
/** IE class **/
.ie7 .form p.input-type-text {
display: inline-block;
}
.form .input-type-text input[type=text],
.form .input-type-text input[type=password] {
padding: 0;
border: none;
background: none;
-moz-border-radius: 0;
-webkit-border-radius: 0;
-webkit-background-clip: padding-box;
border-radius: 0;
margin: 0 0 1px 0;
}
/** IE class **/
.ie7 .form .input-type-text input[type=text] {
float: left;
}
.form .input-type-text img {
margin: 0 0 -3px 0.2em;
}
.form select,
.form textarea {
color: #333333;
font-size: 1em;
padding: 0.417em;
border: 1px solid #89bad3;
-moz-border-radius: 0.417em;
-webkit-border-radius: 0.417em;
-webkit-background-clip: padding-box;
border-radius: 0.417em;
}
.form textarea {
background: white url(../images/old-browsers-bg/input-bg.png) repeat-x top;
background: -moz-linear-gradient(
top,
#d4d4d4,
#ebebeb 3px,
white 27px
), white;
background: -webkit-gradient(
linear,
left 0px, left 27px,
from(#d4d4d4),
to(white),
color-stop(0.12, #ebebeb)
), white;
}
.form select {
font-size: 1.083em;
padding: 0.385em;
}
.form input[type=text].small,
.form input[type=password].small,
.form select.small,
.form textarea.small {
font-size: 1em;
padding: 0.167em;
-moz-border-radius: 0.25em;
-webkit-border-radius: 0.25em;
-webkit-background-clip: padding-box;
border-radius: 0.25em;
}
.form input[type=text].small,
.form input[type=password].small {
padding: 0.25em;
}
.form input[type=text].smaller,
.form input[type=password].smaller,
.form select.smaller,
.form textarea.smaller {
font-size: 1em;
padding: 0;
-moz-border-radius: 0;
-webkit-border-radius: 0;
-webkit-background-clip: padding-box;
border-radius: 0;
}
.form input[type=text].big,
.form input[type=password].big,
.form select.big,
.form textarea.big {
font-size: 1.5em;
}
.form input[type=text].bigger,
.form input[type=password].bigger,
.form select.bigger,
.form textarea.bigger {
font-size: 2.5em;
}
.form input[type=radio],
.form input[type=checkbox] {
vertical-align: -9%;
margin: 0;
padding: 0;
}
/** IE class **/
.form .input-type-check {
vertical-align: -7%;
}
.form input[type=radio] + label,
.form input[type=checkbox] + label {
color: #333333;
font-weight: normal;
display: inline;
margin-bottom: 0;
padding-right: 0.5em;
}
/** IE class **/
.form .input-type-check-label {
color: #333333;
font-weight: normal;
display: inline;
margin-bottom: 0;
padding-right: 0.5em;
}
.form input[type=radio] + label:last-child,
.form input[type=checkbox] + label:last-child {
padding-right: 0;
}
/** IE class **/
.form .input-type-check-label-last-child {
padding-right: 0;
}
.checkable-list {
padding-top: 0.333em;
line-height: 1.25em;
}
.checkable-list li {
padding: 0 0 0.75em 1.25em;
}
.checkable-list li:last-child {
padding-bottom: 0;
}
/** IE class **/
.checkable-list li.last-child {
padding-bottom: 0;
}
.checkable-list li input[type=radio],
.checkable-list li input[type=checkbox] {
float: left;
vertical-align: baseline;
margin: 1px 0 0 -1.167em;
}
/** IE class **/
.ie .checkable-list li input[type=radio],
.ie .checkable-list li input[type=checkbox] {
margin: -3px 0 0 -1.25em;
}
.checkable-list li .input-type-radio,
.checkable-list li .input-type-checkbox {
float: left;
margin: -3px 0 0 -1.25em;
}
.full-width {
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
width: 100%;
}
.ie7 .full-width {
width: 93%;
}
.ie7 select.full-width {
width: 100%;
}
.input-with-button input[type=text] {
width: 65%;
margin-right: 3%;
}
/** IE class **/
.input-with-button .input-type-text {
width: 65%;
margin-right: 3%;
}
.input-with-button select {
width: 70%;
margin-right: 3%;
}
.input-with-button button {
width: 25%;
}
.input-height {
display: block;
line-height: 1em;
padding: 0.583em 0 0.75em;
border: 1px solid transparent;
}
.input-height.grey-bg {
background: #cccccc;
border: 1px solid #cccccc;
-moz-border-radius: 0.25em;
-webkit-border-radius: 0.25em;
-webkit-background-clip: padding-box;
border-radius: 0.25em;
padding-left: 0.75em;
padding-right: 0.75em;
}
p.input-height,
p.input-height.grey-bg {
line-height: 1.25em;
padding-top: 0.5em;
padding-bottom: 0.583em;
}
.one-line-input {
text-align: right;
}
.one-line-input label {
float: left;
margin: 0.2em 0 0 0;
}
.form input[type=text].error,
.form input[type=password].error,
.form .input-type-text.error {
border-color: #CC0000;
}
.check-ok,
.check-error,
.check-warning {
display: block;
position: absolute;
z-index: 89;
width: 16px;
height: 16px;
right: -8px;
top: -8px;
}
.check-ok { background: url(../images/icons/fugue/tick-circle-blue.png) no-repeat; }
.check-error { background: url(../images/icons/fugue/cross-circle.png) no-repeat; }
.check-warning { background: url(../images/icons/fugue/exclamation-diamond.png) no-repeat; }
span.relative > input + .check-ok,
span.relative > select + .check-ok,
span.relative > input + .check-error,
span.relative > select + .check-error,
span.relative > input + .check-warning,
span.relative > select + .check-warning {
margin-top: -0.667em;
right: -4px;
}
p span.relative > input + .check-ok,
p span.relative > select + .check-ok,
p span.relative > input + .check-error,
p span.relative > select + .check-error,
p span.relative > input + .check-warning,
p span.relative > select + .check-warning {
margin-top: -0.583em;
} | 0a1b2c3d4e5 | trunk/BloumGenerator/include/css/form.css | CSS | asf20 | 13,524 |
<?php
set_time_limit(0);
/**
* Description of GenerateAction
*
* @author Magno
*/
class GeneratorAction extends BaseAction{
public static $VIEW_GENERATOR = 'view/steps/';
public function GeneratorAction(){
parent::__construct();
}
public function getView(){
return GeneratorAction::$VIEW_GENERATOR;
}
public function index() {
parent::show('view/index.tpl');
}
public function isLastStep($step){
if($step == 9)
return true;
return false;
}
/**
* Salva o arquivo (.sql) e gera os Objetos Metadados,
* Redirecionando para o primeiro passo
*/
public function saveFile(){
if(!isset ($_FILES["file"]))
throw new Exception("Arquivo Não Encontrado!!!");
$params = parent::getValueSession('params');
if($params == null)
$params = array();
$params[Constantes::$PARAM_PROJECT_NAME] = str_replace(" ", "", parent::getValueInput('projectName'));
$fileString = file_get_contents($_FILES["file"]["tmp_name"]);
$fileString = str_replace("`", "", $fileString);
$tbStManager = new TableStringManager($fileString);
$tablesMeta = $tbStManager->generateAllTableMeta();
parent::setValueSession('tablesMeta', $tablesMeta);
parent::setValueSession('params', $params);
parent::redirect('GeneratorAction.steps');
}
/**
* Avança para o próximo passo
* @param int $step - Passo Atual
*/
public function nextStep($step){
$execute = "executeStep$step";
$this->$execute();
$step = intval($step)+1;
if(!$this->isLastStep($step)){
$this->loadStep($step);
}else{
parent::setValueOutput('step', $step);
echo parent::getHtml(GeneratorAction::$VIEW_GENERATOR.'lastStep.tpl');
}
}
/**
* Carrega um determinado passo (função preparada para usar ajax)
* @param int $step - Passo a ser carregado
*/
public function loadStep($step){
$prepare = "prepareStep$step";
parent::setValueOutput('step', $step);
echo $this->$prepare();
}
/**
* Carrega uma Classe para pré-visualização
* @param String $type - Tipo de classe (bean, dao, service)
* @param String $table - Nome da Tabela correspondente a classe
*/
public function loadClass($type, $table){
$tablesMeta = parent::getValueSession('tablesMeta');
$params = parent::getValueSession('params');
$phpCode = true;
switch ($type) {
case "bean":
$generator = new BeanGenerator($tablesMeta[$table],$params);
break;
case "dao":
$generator = new DAOGenerator($tablesMeta[$table],$params);
break;
case "service":
$generator = new ServiceGenerator($tablesMeta[$table],$params);
break;
case "action":
$generator = new ActionGenerator($tablesMeta[$table],$params);
break;
case "view":
$view = ucfirst(parent::getValueInput('view'))."ViewGenerator";
$generator = new $view($tablesMeta[$table], $params);
$phpCode = false;
break;
}
$code = $generator->generate();
if($phpCode)
echo highlight_string($code,true);
else
echo Util::xmlHighlight($code);
}
/**
* Só redireciona para o primeiro passo
*/
public function steps(){
if(parent::getValueSession('tablesMeta') == null){
parent::redirect('GeneratorAction.index');
return '';
}
$params = parent::getValueSession('params');
parent::setValueOutput('projectName', $params[Constantes::$PARAM_PROJECT_NAME]);
$this->prepareStep1();
parent::setValueOutput('step', 1);
parent::show(GeneratorAction::$VIEW_GENERATOR.'index.tpl');
}
/**
* Prepara o 1º Passo:
* - Prepara o formulario, para q sejam informados, caso exista,
* heranças entre as tabelas
*
*/
public function prepareStep1(){
$tablesMeta = parent::getValueSession('tablesMeta');
$fksHeranca = array();
foreach ($tablesMeta as $tb) {
$heranca = false;
foreach ($tb->getFKReferences() as $fk){
foreach ($fk->getAttributes() as $att){
if($att->isPrimaryKey()){
$heranca = true;
break;
}else{
$heranca = false;
break;
}
}
if($heranca)
$fksHeranca[] = $fk;
}
}
parent::setValueOutput('fksHeranca', $fksHeranca);
return parent::getHtml(GeneratorAction::$VIEW_GENERATOR.'step1.tpl');
}
/**
* Salva as heranças informadas
*/
public function executeStep1(){
$tablesMeta = parent::getValueSession('tablesMeta');
foreach ($tablesMeta as $tb) {
$tbName = $tb->getName();
foreach ($tb->getFKReferences() as $fk){
foreach ($fk->getAttributes() as $att){
if($att->isPrimaryKey()){
$valForm = parent::getValueInput($tbName.':'.$fk->getName());
if(isset ($valForm) && strcmp($valForm, "true") == 0){
$fk->setExtends(true);
break;
}
}
}
}
}
parent::setValueSession('tablesMeta', $tablesMeta);
}
/**
* Prepara o 2º Passo:
* - Prepara o formulario, para q sejam informados os atributos mais
* importantes de cada tabela
*/
public function prepareStep2(){
$tablesMeta = parent::getValueSession('tablesMeta');
parent::setValueOutput('tablesMeta', $tablesMeta);
return parent::getHtml(GeneratorAction::$VIEW_GENERATOR.'step2.tpl');
}
/**
* Salva os atributos mais importantes de cada tabela
*/
public function executeStep2(){
$tablesMeta = parent::getValueSession('tablesMeta');
foreach ($tablesMeta as $tb) {
$tbName = $tb->getName();
foreach ($tb->getAttributes() as $att){
$valForm = parent::getValueInput($tbName.':'.$att->getName());
if($att->isPrimaryKey() || (isset ($valForm) && strcmp($valForm, "true") == 0)){
$att->setImportant(true);
}else{
$att->setImportant(false);
}
}
}
parent::setValueSession('tablesMeta', $tablesMeta);
}
/**
* Prepara o 3º Passo - Pré visualização das Classes
*/
public function prepareStep3(){
$tablesMeta = parent::getValueSession('tablesMeta');
parent::setValueOutput('tablesMeta', $tablesMeta);
return parent::getHtml(GeneratorAction::$VIEW_GENERATOR.'step3.tpl');
}
public function executeStep3(){
}
/**
* Prepara o 4º Passo:
* - Prepara o formulario, para q sejam informados os cadastros
*/
public function prepareStep4(){
$tablesMeta = parent::getValueSession('tablesMeta');
parent::setValueOutput('tablesMeta', $tablesMeta);
return parent::getHtml(GeneratorAction::$VIEW_GENERATOR.'step4.tpl');
}
/**
* Salvando Tabelas q irão ter CRUD
*/
public function executeStep4(){
$tablesMeta = parent::getValueSession('tablesMeta');
foreach ($tablesMeta as $tb) {
$valForm = parent::getValueInput($tb->getName());
if(isset ($valForm) && strcmp($valForm, "true") == 0){
$tb->setCrud(true);
}else{
$tb->setCrud(false);
}
}
parent::setValueSession('tablesMeta', $tablesMeta);
}
/**
* Prepara o 5º Passo:
* - Prepara o formulario, para q sejam informados os relacionametos
* combo ou incluir form da fk
*/
public function prepareStep5(){
$tablesMeta = parent::getValueSession('tablesMeta');
parent::setValueOutput('tablesMeta', $tablesMeta);
return parent::getHtml(GeneratorAction::$VIEW_GENERATOR.'step5.tpl');
}
/**
* Salvando se o relacionamento é combo ou form incluir form da fk
*/
public function executeStep5(){
$tablesMeta = parent::getValueSession('tablesMeta');
foreach ($tablesMeta as $tb) {
if(count($tb->getFKReferences()) > 0){
$tbName = $tb->getName();
foreach ($tb->getFKReferences() as $fk){
$valForm = parent::getValueInput($tbName.':'.$fk->getName());
if(isset ($valForm))
$fk->setTypeForm($valForm);
}
}
}
parent::setValueSession('tablesMeta', $tablesMeta);
}
/**
* Prepara o 6º Passo:
* - Prepara o formulario, para q sejam informados os atributos display dos
* possiveis combos
*/
public function prepareStep6(){
$tablesMeta = parent::getValueSession('tablesMeta');
$tablesCombo = array();
foreach ($tablesMeta as $tb) {
foreach ($tb->getFKReferences() as $fk) {
if(strcmp($fk->getTypeForm(), Constantes::$TYPE_FORM_COMBO) == 0){
$tablesCombo[$fk->getTableReference()->getName()] = $fk->getTableReference();
}
}
}
if(count($tablesCombo) > 0){
parent::setValueOutput('tablesMeta', $tablesCombo);
return parent::getHtml(GeneratorAction::$VIEW_GENERATOR.'step6.tpl');
}
else{
return $this->loadStep(7);
}
}
/**
* Salvando os atributos display do combo
*/
public function executeStep6(){
$tablesMeta = parent::getValueSession('tablesMeta');
foreach ($tablesMeta as $tb) {
$value = parent::getValueInput($tb->getName());
if($value != null){
$value = explode(":", $value);
foreach ($tb->getAttributes() as $attCb) {
if(strcmp($value[1], $attCb->getName()) == 0)
$attCb->setComboDisplay(true);
else
$attCb->setComboDisplay(false);
}
}
}
parent::setValueSession('tablesMeta', $tablesMeta);
}
/**
* Prepara o 7º Passo:
* - Prepara o formulario, para q sejam informados os relacionametos
* combo ou incluir form da fk
*/
public function prepareStep7(){
parent::setValueOutput('params', parent::getValueSession('params'));
return parent::getHtml(GeneratorAction::$VIEW_GENERATOR.'step7.tpl');
}
/**
* Salvando se o relacionamento é combo ou form incluir form da fk
*/
public function executeStep7(){
$params = parent::getValueSession('params');
if($params == null)
$params = array();
$incValidate = parent::getValueInput('incValidate');
if($incValidate != null && strcmp($incValidate, "true") == 0)
$incValidate = true;
else
$incValidate = false;
$incCss = parent::getValueInput('incCss');
if($incCss != null && strcmp($incCss, "true") == 0)
$incCss = true;
else
$incCss = false;
$incMenu = parent::getValueInput('incMenu');
if($incMenu != null && strcmp($incMenu, "true") == 0)
$incMenu = true;
else
$incMenu = false;
$params[Constantes::$PARAM_INCLUDE_VALIDADE] = $incValidate;
$params[Constantes::$PARAM_INCLUDE_CSS] = $incCss;
$params[Constantes::$PARAM_INCLUDE_MENU] = $incMenu;
parent::setValueSession('params', $params);
}
/**
* Prepara o 8º Passo - Pré visualização das Actions e Views
*/
public function prepareStep8(){
$tablesMeta = parent::getValueSession('tablesMeta');
parent::setValueOutput('tablesMeta', $tablesMeta);
return parent::getHtml(GeneratorAction::$VIEW_GENERATOR.'step8.tpl');
}
public function executeStep8(){
}
public function prepareProjectDownload(){
$tablesMeta = parent::getValueSession('tablesMeta');
$params = parent::getValueSession('params');
foreach ($tablesMeta as $tableMeta) {
$beanGenerator = new BeanGenerator($tableMeta,$params);
$daoGenerator = new DAOGenerator($tableMeta,$params);
$serviceGenerator = new ServiceGenerator($tableMeta,$params);
/** ViewsGenerators Comuns a Todos **/
$formComboViewGenerator = new FormComboViewGenerator($tableMeta, $params);
$formIncludeViewGenerator = new FormIncludeViewGenerator($tableMeta, $params);
$detalhesIncludeViewGenerator = new DetalhesIncludeViewGenerator($tableMeta, $params);
$beanGenerator->generateFile();
$daoGenerator->generateFile();
$serviceGenerator->generateFile();
$formComboViewGenerator->generateFile();
$formIncludeViewGenerator->generateFile();
$detalhesIncludeViewGenerator->generateFile();
if($tableMeta->isCrud()){
$actionGenerator = new ActionGenerator($tableMeta,$params);
/** ViewsGenerators Soh Pra quem tem Cadastro **/
$cadastroViewGenerator = new CadastroViewGenerator($tableMeta, $params);
$detalhesViewGenerator = new DetalhesViewGenerator($tableMeta, $params);
$listarViewGenerator = new ListarViewGenerator($tableMeta, $params);
$tabelaViewGenerator = new TabelaViewGenerator($tableMeta, $params);
$formBuscaViewGenerator = new FormBuscaViewGenerator($tableMeta, $params);
$actionGenerator->generateFile();
$cadastroViewGenerator->generateFile();
$detalhesViewGenerator->generateFile();
$listarViewGenerator->generateFile();
$tabelaViewGenerator->generateFile();
$formBuscaViewGenerator->generateFile();
}
}
if($params[Constantes::$PARAM_INCLUDE_MENU]){
$menuViewGenerator = new MenuViewGenerator($tablesMeta, $params);
$menuViewGenerator->generateFile();
}
$name = $params[Constantes::$PARAM_PROJECT_NAME];
$directory = 'temp_gen/'.$name;
$this->copyIncludeDir('temp_gen/include','temp_gen/'.$name);
$this->replaceHtaccess('temp_gen/'.$name.'/.htaccess', $name);
include 'include/php/compactador.php';
}
private function copyIncludeDir($diretorio, $destino){
if ($destino{strlen($destino) - 1} == '/') {
$destino = substr($destino, 0, -1);
}
if (!is_dir($destino))
mkdir($destino, 0755, true);
$folder = opendir($diretorio);
while ($item = readdir($folder)) {
if ($item == '.' || $item == '..') {
continue;
}
if (is_dir("{$diretorio}/{$item}")) {
$this->copyIncludeDir("{$diretorio}/{$item}", "{$destino}/{$item}");
} else {
copy("{$diretorio}/{$item}", "{$destino}/{$item}");
}
}
}
private function replaceHtaccess($dir, $projectName){
$htaccess = file_get_contents($dir);
$htaccess = str_replace(":projectName", $projectName, $htaccess);
$fp = fopen($dir, "w+");
fwrite($fp, $htaccess);
fclose($fp);
}
}
?>
| 0a1b2c3d4e5 | trunk/BloumGenerator/action/GeneratorAction.class.php | PHP | asf20 | 16,817 |
<?php
/**
* Description of SystemAction
*
* Classe Principal das Actions :
*
* Quebra a url, montando a classe action passada e seu metodo
* e depois o executa
* Tambem separa a string com os parametros
*
* @author Magno
*/
class SystemAction {
private $url;
private $actionClass;
private $actionMetodo;
private $params;
private $subAction;
function __construct() {
$this->setUrl();
$this->setParams();
}
public function getUrl() {
return $this->url;
}
/**
* Seta a url q vem pelo GET
*/
private function setUrl() {
$url = $_SERVER['PHP_SELF'];
$url = substr($url, stripos($url, "bloumMvc.php/")+strlen("bloumMvc.php/"));
$paramGet = explode($url, $_SERVER ['REQUEST_URI']);
if(count($paramGet) > 1)
$paramGet = $paramGet[1];
else
$paramGet = '';
$this->url = $url.$paramGet;
$this->explodeUrl();
}
/**
* Explode a Url - Dividindo em Action (Classe e Metodo)
* e Parametros
* @deprecated
*/
private function explodeUrl() {
$this->explodeAction();
}
/**
* Explode a String da Action em Classe e Metodo
*/
private function explodeAction() {
if (strpos($this->url, ".") === FALSE)
$this->url .= ".index";
$arrayUrl = explode(".", $this->url);
$method = explode("?", $arrayUrl[1]);
$this->setActionClass($arrayUrl[0]);
$this->setActionMetodo($method[0]);
}
/**
* Monta a String com os Parametros
* @deprecated
*/
private function explodeParams() {
$arrayUrl = explode("!", $this->url);
if (count($arrayUrl) > 1)
$explodeParams = $arrayUrl[1];
else
$explodeParams = "";
#$this->setParams($explodeParams);
}
public function getActionClass() {
return $this->actionClass;
}
private function setActionClass($actionClass) {
$this->actionClass = $actionClass;
}
public function getActionMetodo() {
return $this->actionMetodo;
}
private function setActionMetodo($actionMetodo) {
$this->actionMetodo = $actionMetodo;
}
public function getParams() {
return $this->params;
}
/**
* Explode os parametros, montando um ARRAY
*/
public function setParams() {
$this->params = array();
if (count($_GET) > 0) {
$this->params = $_GET;
$keys = array_keys($this->params);
for ($i = 0; $i < count($keys); $i++) {
if (Constantes::$URL_CRIPTOGRAFADA) {
$_GET[$keys[$i]] = Seguranca::descriptografaLink($_GET[$keys[$i]]);
}
$this->params[addslashes(trim($keys[$i]))] = addslashes(trim($_GET[$keys[$i]]));
}
} else if (count($_POST) > 0) {
$this->params = $_POST;
$keys = array_keys($this->params);
for ($i = 0; $i < count($keys); $i++) {
$this->params[addslashes(trim($keys[$i]))] = addslashes(trim($_POST[$keys[$i]]));
}
}
}
public function isAjax() {
return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strcmp(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']),'xmlhttprequest') == 0);
}
public function getSubAction() {
return $this->subAction;
}
public function setSubAction($subAction) {
$this->subAction = $subAction;
}
/**
* Instancia a Action passada e executa o metodo
*/
public function run() {
$isAjax = false;
$this->subAction = new $this->actionClass();
$metodo = $this->actionMetodo;
if (!method_exists($this->subAction, $metodo)){
$this->showErro("Funcionalidade Não Encontrada!!!");
return;
}
$this->subAction->setInput($this->params);
if (!$this->isAjax())
$this->subAction->setUrlAtual($this->url);
else
$isAjax = true;
try {
//Verificando Autorizaçao
/* $autorizacao = new AuthorizationAction();
if(!$autorizacao->isAutorizado($this->subAction->getUserSession(), $this->actionClass, $metodo)){
$this->subAction->redirect('index2.php?url=AdministracaoAction.acessoNegado');
return;
} */
$refMetodo = new ReflectionMethod($this->actionClass, $metodo);
$metParametros = $refMetodo->getParameters();
$paramValues = array();
foreach ($metParametros as $metPar) {
$name = $metPar->getName();
if (stripos($name, "Bean"))
$paramValues[$name] = $this->subAction->getObjectInput(ucfirst($name));
else
$paramValues[$name] = $this->subAction->getValueInput($name);
}
$rs = $refMetodo->invokeArgs($this->subAction, $paramValues);
//coloca o retorno da action chamada no output
if(isset ($rs))
$this->subAction->setValueOutput("rs".$metodo,$rs);
//se não chamou o método show redireciona para o tpl com o mesmo nome do método chamado
if (!$this->subAction->isCallShow() && !$isAjax) {
$uri = $this->subAction->getView() . $metodo . ".tpl";
$this->subAction->show($uri);
}
} catch (ValidatorException $ex) {
//QUANDO OCORRE ERRO DE VALIDAÇÃO VOLTA PRO PRA PAGINA ANTERIOR
$this->subAction->voltar();
}/*catch (Exception $ex) {
//QUANDO OCORRE ALGUM ERRO INESPERADO VAI PARA PAGINA DE ERROS
$this->showErro($ex->getMessage(), $ex->getTraceAsString(), $ex->getFile());
}*/
}
public function showErro($mensagem, $pilha = "", $arquivo = ""){
$this->subAction->setValueOutput('classe', $this->url);
$this->subAction->setValueOutput('mensagem', $mensagem);
$this->subAction->setValueOutput('pilha', $pilha);
$this->subAction->setValueOutput('arquivo', $arquivo);
$this->subAction->show("view/erros/error.tpl");
}
}
?>
| 0a1b2c3d4e5 | trunk/BloumGenerator/action/SystemAction.class.php | PHP | asf20 | 6,496 |
<?php
#define('SMARTY_SPL_AUTOLOAD',1);
require dirname(__FILE__).'/../include/php/smarty/Smarty.class.php';
/**
* Description of BaseAction
*
* Classe Base para as outras Actions que fore existir
*
* @author Magno
*/
class BaseAction {
private $input;
private $output;
private $callShow = false;//indica se o metodo show foi chamado ou não
private static $USER = "user";
private static $SESSION_PARAMS = "session_params";
private static $SESSION_URL_ANTERIOR = "urlAnterior";
private static $SESSION_URL_ATUAL = "urlAtual";
public static $ERROS_VALIDACAO = "errosValidacao";
function __construct() {
$this->init();
}
/**
* Inicializa a sessão,
* Seta os parametros do output (SMARTY),
* e procura parametros na sessao (Para o caso de Actions-Chain)
*/
private function init(){
session_start();
$this->setOutput();
$this->setOutputFromSession();
}
public function isCallShow() {
return $this->callShow;
}
public function getSession() {
return $_SESSION;
}
/**
* Seta um Valor (objeto ou nao) na Sessão
* @param String $chave - identificação do valor
* @param Mixed $valor - valor
*/
public function setValueSession($chave, $valor){
$_SESSION[$chave] = $valor;
}
/**
* Pega um Valor (objeto ou nao) ga Sessão
* @param String $chave - identificação do valor
*/
public function getValueSession($chave){
return isset ($_SESSION[$chave]) ? $_SESSION[$chave] : null;
}
/**
* Seta um Usuario na Sessão
* @param UsuarioBean $user - objeto Usuario
*/
public function setUserSession($user){
$_SESSION[BaseAction::$USER] = $user;
}
public function getUserSession(){
if(isset ($_SESSION[BaseAction::$USER]))
return $_SESSION[BaseAction::$USER];
return null;
}
public function isLogged(){
if( isset ($_SESSION[BaseAction::$USER]) &&
$_SESSION[BaseAction::$USER] instanceof UsuarioBean &&
$_SESSION[BaseAction::$USER]->getUsuarioID() > 0 )
return true;
return false;
}
public function setUrlAtual($url){
if(isset ($_SESSION[BaseAction::$SESSION_URL_ATUAL]) &&
strlen($_SESSION[BaseAction::$SESSION_URL_ATUAL]) > 0){
//Evitando de perder a anterior se ocorrer um Refresh
if(strcmp($_SESSION[BaseAction::$SESSION_URL_ATUAL], $url) != 0)
$_SESSION[BaseAction::$SESSION_URL_ANTERIOR] = $_SESSION[BaseAction::$SESSION_URL_ATUAL];
}
$_SESSION[BaseAction::$SESSION_URL_ATUAL] = $url;
}
public function getInput() {
return $this->input;
}
public function setInput($input) {
$this->input = $input;
}
/**
* Seta no Output os parametros existentes na sessão,
* metodo utilizado quando ocorrer um Encadeamento de Actions,
* ou seja o valor de output de uma action e passado para outra
*/
private function setOutputFromSession(){
$sessionParams = @$_SESSION[BaseAction::$SESSION_PARAMS];
if(isset ($sessionParams) && count($sessionParams) > 0){
$keys = array_keys($sessionParams);
for($i = 0; $i < count($keys); $i++){
$this->setValueOutput($keys[$i], $sessionParams[$keys[$i]]);
}
$_SESSION[BaseAction::$SESSION_PARAMS] = null;
unset ($_SESSION[BaseAction::$SESSION_PARAMS]);
}
}
/**
* Pega um valor do input (passados como parametro na url ou post)
* @param String $nome - chave do atributo
* @return Mixed Retorna o valor para a chave do atributo
*/
public function getValueInput($nome = ""){
if(strlen($nome) > 0 && isset ($this->input[$nome])){
return $this->input[$nome];
}else
return null;
}
/**
* Pega um objeto do input:
* Popula o objeto de acordo com suas propriedades e os nomes encontrados no INPUT
* @param String $className - Nome da Classe do Objeto que deseja Popular
* @param String $prefix - Caso exista algum prefixo nos formulario (Ex.: usuarioEmail, usuarioLogin)
* @param String $sufix - Caso exista algum sufixo nos formulario (Ex.: emailUsuario, loginUsuario)
* @return Retorna o objeto populado
*/
public function getObjectInput($className = "", $prefix = "", $sufix = ""){
$reflec = new ReflectionClass($className);
$objeto = $reflec->newInstance();
foreach($reflec->getProperties() as $att){
$atributo = $att->getName();
$set = "set".strtoupper($atributo[0]).substr($atributo, 1);
if(method_exists($objeto, $set)){
$chave = $atributo;
if(strlen($prefix) > 0)
$chave = $prefix.$chave;
if(strlen($sufix) > 0)
$chave = $chave.$sufix;
@$this->input[$chave];
$objeto->$set(@$this->input[$chave]);
}
}
/** VALIDANDO O OBJETO POPULADO **/
$validador = new ValidatorAction($objeto);
$errosValidacao = $validador->validateAll();
if(count($errosValidacao) > 0){
$this->setValueOutput(BaseAction::$ERROS_VALIDACAO, $errosValidacao);
throw new ValidatorException("Erros de Validação");
}
return $objeto;
}
public function getOutput() {
return $this->output;
}
/**
* Seta as configurações do SMARTY
*/
private function setOutput(){
$this->output = new Smarty();
$this->output->cache_dir = dirname(__FILE__)."/../include/php/smarty/cache";
$this->output->config_dir = dirname(__FILE__)."/../include/php/smarty/configs";
$this->output->compile_dir = dirname(__FILE__)."/../include/php/smarty/templates_c";
$this->output->plugins_dir = dirname(__FILE__)."/../include/php/smarty/plugins";
$this->output->template_dir = "view/";
#$this->output->debugging = true;
}
/**
* Seta um objeto no output:
* Percorre as propriedades do objeto e joga no OUTPUT
* @param Object $objeto - Objeto a ser injetado
* @param String $prefix - Caso queria identificar as propriedades com algum prefixo (Ex.: usuarioEmail, usuarioLogin)
* @param String $sufix - Caso queria identificar as propriedades com algum sufixo (Ex.: emailUsuario, loginUsuario)
*/
public function setObjectOutput($objeto = null, $prefix = "", $sufix = ""){
$reflec = new ReflectionClass( $objeto );
foreach($reflec->getProperties() as $att){
$atributo = $att->getName();
$get = "get".strtoupper($atributo[0]).substr($atributo, 1);
if(method_exists($objeto, $get)){
$chave = $atributo;
if(strlen($prefix) > 0)
$chave = $prefix.$chave;
if(strlen($sufix) > 0)
$chave = $chave.$sufix;
$this->output->assign($chave,$objeto->$get());
}
}
}
/**
* Joga um valor no output
* @param String $chave - nome de idenficação do valor
* @param Mixed $valor - valor a ser injetado (pode ser qualquer tipo de dado: String, int, array, etc)
*/
public function setValueOutput($chave,$valor){
$this->output->assign($chave,$valor);
}
/**
* Abre uma pagina (template)
* Usa-se no final da execução dos metodos nas actions
* @param String $tpl - Pagina (template) a ser aberta
*/
public function show($tpl){
$this->callShow = true;
$this->output->display($tpl);
}
/**
* Retorna o conteudo de uma pagina (template)
* @param String $tpl - Pagina (template) a ser retornada
*/
public function getHtml($tpl){
return $this->output->fetch($tpl);
}
/**
* Redireciona para uma página
* Detalhe: Caso, ocorra um ecadeamento de ações (ex.: de salvar, chama listar)
* os parametros da primeira serão pertido ,caso não seja desejado use
* a function chain
* @param String $url - url de redirecionamento (Ex.: UsuarioActioin.listar)
*/
public function redirect($url){
header("Location: $url");
}
/**
* Redirecona para uma página sem perder os parametros,
* deve ser usada quando ocorre encadeamento de ações (ex.: de salvar, chama listar)
* os parametros da primeira não serão pertidos, caso não seja desejado use
* a function redirect
* @param String $url - url de redirecionamento (Ex.: UsuarioActioin.listar)
*/
public function chain($url){
$_SESSION[BaseAction::$SESSION_PARAMS] = $this->output->getTemplateVars();
header("Location: $url");
}
/**
* Redirecona para a úlima página visitada sem perder os parametros,
* pode ser usada quando ocorre algum erro esperado ou não na Action
* os parametros da primeira não serão pertidos, caso não seja desejado use
* a function redirect
* @param String $url - url de redirecionamento (Ex.: UsuarioActioin.listar)
*/
public function voltar(){
$valores = array_merge($this->input, $this->output->getTemplateVars());
$_SESSION[BaseAction::$SESSION_PARAMS] = $valores;
header("Location: ".$_SESSION[BaseAction::$SESSION_URL_ANTERIOR]);
}
}
?>
| 0a1b2c3d4e5 | trunk/BloumGenerator/action/BaseAction.class.php | PHP | asf20 | 10,213 |
<?php
/**
* Description of TabelaMeta
*
* @author Magno
*/
class TableMeta {
private $name;
private $attributes;
private $FKReferences;
private $FKReferenciadas;
private $crud;
function __construct($name = "", $attributes = null, $FKReferences = null, $FKReferenciadas = null, $crud = true) {
$this->name = $name;
$this->attributes = $attributes;
$this->FKReferences = $FKReferences;
$this->FKReferenciadas = $FKReferenciadas;
$this->FKReferenciadas = array();
$this->crud = $crud;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getAttributes() {
return $this->attributes;
}
public function setAttributes($attributes) {
$this->attributes = $attributes;
}
public function getFKReferences() {
return $this->FKReferences;
}
public function setFKReferences($FKReferences) {
$this->FKReferences = $FKReferences;
}
public function getFKReferenciadas() {
return $this->FKReferenciadas;
}
public function setFKReferenciadas($FKReferenciadas) {
$this->FKReferenciadas = $FKReferenciadas;
}
public function addFKReferenciada($FKReference){
if($this->FKReferenciadas == null || !isset ($this->FKReferenciadas))
$this->FKReferenciadas = array();
$this->FKReferenciadas[$FKReference->getName()] = $FKReference;
}
public function isCrud() {
return $this->crud;
}
public function setCrud($crud) {
$this->crud = $crud;
}
}
?>
| 0a1b2c3d4e5 | trunk/BloumGenerator/meta/TableMeta.class.php | PHP | asf20 | 1,693 |
<?php
/**
* Description of AtributoMeta
*
* @author Magno
*/
class AttributeMeta {
private $name;
private $type;
private $notNull;
private $primaryKey;
private $foreignKey;
private $default;
private $important;
private $comboDisplay;
function __construct($name, $type, $notNull, $primaryKey, $foreignKey, $default, $important, $comboDisplay) {
$this->name = $name;
$this->type = $type;
$this->notNull = $notNull;
$this->primaryKey = $primaryKey;
$this->foreignKey = $foreignKey;
$this->default = $default;
$this->important = $important;
$this->comboDisplay = $comboDisplay;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getType() {
return $this->type;
}
public function setType($type) {
$this->type = $type;
}
public function isNotNull() {
return $this->notNull;
}
public function setNotNull($notNull) {
$this->notNull = $notNull;
}
public function isPrimaryKey() {
return $this->primaryKey;
}
public function setPrimaryKey($primaryKey) {
$this->primaryKey = $primaryKey;
}
public function getDefault() {
return $this->default;
}
public function setDefault($default) {
$this->default = $default;
}
public function isForeignKey() {
return $this->foreignKey;
}
public function setForeignKey($foreignKey) {
$this->foreignKey = $foreignKey;
}
public function isImportant() {
return $this->important;
}
public function setImportant($important) {
$this->important = $important;
}
public function isComboDisplay() {
return $this->comboDisplay;
}
public function setComboDisplay($comboDisplay) {
$this->comboDisplay = $comboDisplay;
}
public function toArray(){
$attr = array();
$attr['name'] = $this->name;
$attr['type'] = $this->type;
$attr['default'] = $this->default;
$attr['primaryKey'] = $this->primaryKey;
$attr['notNull'] = $this->notNull;
$attr['foreignKey'] = $this->foreignKey;
return $attr;
}
}
?>
| 0a1b2c3d4e5 | trunk/BloumGenerator/meta/AttributeMeta.class.php | PHP | asf20 | 2,376 |
<?php
/**
* Description of FKReferenceMeta
*
* @author Magno
*/
class FKReferenceMeta {
private $name;
private $attributes;
private $tableFK;
private $tableReference;
private $references;
private $cardinality;
private $sideObject;
private $extends;
private $typeForm;
function __construct($name, $attributes, $tableFK, $tableReference, $references, $cardinality, $sideObject, $extends, $typeForm) {
$this->name = $name;
$this->attributes = $attributes;
$this->tableFK = $tableFK;
$this->tableReference = $tableReference;
$this->references = $references;
$this->cardinality = $cardinality;
$this->sideObject = $sideObject;
$this->extends = $extends;
$this->typeForm = $typeForm;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getAttributes() {
return $this->attributes;
}
public function setAttributes($attributes) {
$this->attributes = $attributes;
}
public function getTableFK() {
return $this->tableFK;
}
public function setTableFK($tableFK) {
$this->tableFK = $tableFK;
}
public function getTableReference() {
return $this->tableReference;
}
public function setTableReference($tableReference) {
$this->tableReference = $tableReference;
}
public function getReferences() {
return $this->references;
}
public function setReferences($references) {
$this->references = $references;
}
public function getCardinality() {
return $this->cardinality;
}
public function setCardinality($cardinality) {
$this->cardinality = $cardinality;
}
public function getSideObject() {
return $this->sideObject;
}
public function setSideObject($sideObject) {
$this->sideObject = $sideObject;
}
public function isExtends() {
return $this->extends;
}
public function setExtends($extends) {
$this->extends = $extends;
}
public function getTypeForm() {
return $this->typeForm;
}
public function setTypeForm($typeForm) {
$this->typeForm = $typeForm;
}
}
?>
| 0a1b2c3d4e5 | trunk/BloumGenerator/meta/FKReferenceMeta.class.php | PHP | asf20 | 2,340 |
<?php
?>
| 0a1b2c3d4e5 | trunk/BloumGenerator/index.php | PHP | asf20 | 13 |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.ui.module.MyTextView;
public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//禁止横屏
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
// TODO: is this a hack?
setResult(RESULT_OK);
addPreferencesFromResource(R.xml.preferences);
}
@Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if ( key.equalsIgnoreCase(Preferences.NETWORK_TYPE) ) {
HttpClient httpClient = TwitterApplication.mApi.getHttpClient();
String type = sharedPreferences.getString(Preferences.NETWORK_TYPE, "");
if (type.equalsIgnoreCase(getString(R.string.pref_network_type_cmwap))) {
Log.d("LDS", "Set proxy for cmwap mode.");
httpClient.setProxy("10.0.0.172", 80, "http");
} else {
Log.d("LDS", "No proxy.");
httpClient.removeProxy();
}
} else if ( key.equalsIgnoreCase(Preferences.UI_FONT_SIZE)) {
MyTextView.setFontSizeChanged(true);
}
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/PreferencesActivity.java | Java | asf20 | 3,039 |
package com.ch_linghu.fanfoudroid.app;
import java.util.HashMap;
import android.graphics.Bitmap;
public class MemoryImageCache implements ImageCache {
private HashMap<String, Bitmap> mCache;
public MemoryImageCache() {
mCache = new HashMap<String, Bitmap>();
}
@Override
public Bitmap get(String url) {
synchronized(this) {
Bitmap bitmap = mCache.get(url);
if (bitmap == null){
return mDefaultBitmap;
}else{
return bitmap;
}
}
}
@Override
public void put(String url, Bitmap bitmap) {
synchronized(this) {
mCache.put(url, bitmap);
}
}
public void putAll(MemoryImageCache imageCache) {
synchronized(this) {
// TODO: is this thread safe?
mCache.putAll(imageCache.mCache);
}
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/app/MemoryImageCache.java | Java | asf20 | 831 |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid.app;
public class Preferences {
public static final String USERNAME_KEY = "username";
public static final String PASSWORD_KEY = "password";
public static final String CHECK_UPDATES_KEY = "check_updates";
public static final String CHECK_UPDATE_INTERVAL_KEY = "check_update_interval";
public static final String VIBRATE_KEY = "vibrate";
public static final String TIMELINE_ONLY_KEY = "timeline_only";
public static final String REPLIES_ONLY_KEY = "replies_only";
public static final String DM_ONLY_KEY = "dm_only";
public static String RINGTONE_KEY = "ringtone";
public static final String RINGTONE_DEFAULT_KEY = "content://settings/system/notification_sound";
public static final String LAST_TWEET_REFRESH_KEY = "last_tweet_refresh";
public static final String LAST_DM_REFRESH_KEY = "last_dm_refresh";
public static final String LAST_FOLLOWERS_REFRESH_KEY = "last_followers_refresh";
public static final String TWITTER_ACTIVITY_STATE_KEY = "twitter_activity_state";
public static final String USE_PROFILE_IMAGE = "use_profile_image";
public static final String PHOTO_PREVIEW = "photo_preview";
public static final String FORCE_SHOW_ALL_IMAGE = "force_show_all_image";
public static final String RT_PREFIX_KEY = "rt_prefix";
public static final String RT_INSERT_APPEND = "rt_insert_append"; // 转发时光标放置在开始还是结尾
public static final String NETWORK_TYPE = "network_type";
// DEBUG标记
public static final String DEBUG = "debug";
// 当前用户相关信息
public static final String CURRENT_USER_ID = "current_user_id";
public static final String CURRENT_USER_SCREEN_NAME = "current_user_screenname";
public static final String UI_FONT_SIZE = "ui_font_size";
public static final String USE_ENTER_SEND = "use_enter_send";
public static final String USE_GESTRUE = "use_gestrue";
public static final String USE_SHAKE = "use_shake";
public static final String FORCE_SCREEN_ORIENTATION_PORTRAIT = "force_screen_orientation_portrait";
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/app/Preferences.java | Java | asf20 | 2,782 |
package com.ch_linghu.fanfoudroid.app;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.view.MotionEvent;
import android.widget.TextView;
public class TestMovementMethod extends LinkMovementMethod {
private double mY;
private boolean mIsMoving = false;
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer,
MotionEvent event) {
/*
int action = event.getAction();
if (action == MotionEvent.ACTION_MOVE) {
double deltaY = mY - event.getY();
mY = event.getY();
Log.d("foo", deltaY + "");
if (Math.abs(deltaY) > 1) {
mIsMoving = true;
}
} else if (action == MotionEvent.ACTION_DOWN) {
mIsMoving = false;
mY = event.getY();
} else if (action == MotionEvent.ACTION_UP) {
boolean wasMoving = mIsMoving;
mIsMoving = false;
if (wasMoving) {
return true;
}
}
*/
return super.onTouchEvent(widget, buffer, event);
}
public static MovementMethod getInstance() {
if (sInstance == null)
sInstance = new TestMovementMethod();
return sInstance;
}
private static TestMovementMethod sInstance;
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/app/TestMovementMethod.java | Java | asf20 | 1,336 |
package com.ch_linghu.fanfoudroid.app;
import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.LoginActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.fanfou.RefuseError;
import com.ch_linghu.fanfoudroid.http.HttpAuthException;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.HttpRefusedException;
import com.ch_linghu.fanfoudroid.http.HttpServerException;
public class ExceptionHandler {
private Activity mActivity;
public ExceptionHandler(Activity activity) {
mActivity = activity;
}
public void handle(HttpException e) {
Throwable cause = e.getCause();
if (null == cause) return;
// Handle Different Exception
if (cause instanceof HttpAuthException) {
// 用户名/密码错误
Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show();
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent); // redirect to the login activity
} else if (cause instanceof HttpServerException) {
// 服务器暂时无法响应
Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show();
} else if (cause instanceof HttpAuthException) {
//FIXME: 集中处理用户名/密码验证错误,返回到登录界面
} else if (cause instanceof HttpRefusedException) {
// 服务器拒绝请求,如没有权限查看某用户信息
RefuseError error = ((HttpRefusedException) cause).getError();
switch (error.getErrorCode()) {
// TODO: finish it
case -1:
default:
Toast.makeText(mActivity, error.getMessage(), Toast.LENGTH_LONG).show();
break;
}
}
}
private void handleCause() {
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/app/ExceptionHandler.java | Java | asf20 | 2,064 |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid.app;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* Manages retrieval and storage of icon images. Use the put method to download
* and store images. Use the get method to retrieve images from the manager.
*/
public class ImageManager implements ImageCache {
private static final String TAG = "ImageManager";
// 饭否目前最大宽度支持596px, 超过则同比缩小
// 最大高度为1192px, 超过从中截取
public static final int DEFAULT_COMPRESS_QUALITY = 90;
public static final int IMAGE_MAX_WIDTH = 596;
public static final int IMAGE_MAX_HEIGHT = 1192;
private Context mContext;
// In memory cache.
private Map<String, SoftReference<Bitmap>> mCache;
// MD5 hasher.
private MessageDigest mDigest;
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
public ImageManager(Context context) {
mContext = context;
mCache = new HashMap<String, SoftReference<Bitmap>>();
try {
mDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// This shouldn't happen.
throw new RuntimeException("No MD5 algorithm.");
}
}
public void setContext(Context context) {
mContext = context;
}
private String getHashString(MessageDigest digest) {
StringBuilder builder = new StringBuilder();
for (byte b : digest.digest()) {
builder.append(Integer.toHexString((b >> 4) & 0xf));
builder.append(Integer.toHexString(b & 0xf));
}
return builder.toString();
}
// MD5 hases are used to generate filenames based off a URL.
private String getMd5(String url) {
mDigest.update(url.getBytes());
return getHashString(mDigest);
}
// Looks to see if an image is in the file system.
private Bitmap lookupFile(String url) {
String hashedUrl = getMd5(url);
FileInputStream fis = null;
try {
fis = mContext.openFileInput(hashedUrl);
return BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
// Not there.
return null;
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// Ignore.
}
}
}
}
/**
* Downloads a file
* @param url
* @return
* @throws HttpException
*/
public Bitmap downloadImage(String url) throws HttpException {
Log.d(TAG, "Fetching image: " + url);
Response res = TwitterApplication.mApi.getHttpClient().get(url);
return BitmapFactory.decodeStream(new BufferedInputStream(res.asStream()));
}
public Bitmap downloadImage2(String url) throws HttpException {
Log.d(TAG, "[NEW]Fetching image: " + url);
final Response res = TwitterApplication.mApi.getHttpClient().get(url);
String file = writeToFile(res.asStream(), getMd5(url));
return BitmapFactory.decodeFile(file);
}
/**
* 下载远程图片 -> 转换为Bitmap -> 写入缓存器.
* @param url
* @param quality image quality 1~100
* @throws HttpException
*/
public void put(String url, int quality, boolean forceOverride) throws HttpException {
if (!forceOverride && contains(url)) {
// Image already exists.
return;
// TODO: write to file if not present.
}
Bitmap bitmap = downloadImage(url);
if (bitmap != null) {
put(url, bitmap, quality); // file cache
} else {
Log.w(TAG, "Retrieved bitmap is null.");
}
}
/**
* 重载 put(String url, int quality)
* @param url
* @throws HttpException
*/
public void put(String url) throws HttpException {
put(url, DEFAULT_COMPRESS_QUALITY, false);
}
/**
* 将本地File -> 转换为Bitmap -> 写入缓存器.
* 如果图片大小超过MAX_WIDTH/MAX_HEIGHT, 则将会对图片缩放.
*
* @param file
* @param quality 图片质量(0~100)
* @param forceOverride
* @throws IOException
*/
public void put(File file, int quality, boolean forceOverride) throws IOException {
if (!file.exists()) {
Log.w(TAG, file.getName() + " is not exists.");
return;
}
if (!forceOverride && contains(file.getPath())) {
// Image already exists.
Log.d(TAG, file.getName() + " is exists");
return;
// TODO: write to file if not present.
}
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
//bitmap = resizeBitmap(bitmap, MAX_WIDTH, MAX_HEIGHT);
if (bitmap == null) {
Log.w(TAG, "Retrieved bitmap is null.");
} else {
put(file.getPath(), bitmap, quality);
}
}
/**
* 将Bitmap写入缓存器.
* @param filePath file path
* @param bitmap
* @param quality 1~100
*/
public void put(String file, Bitmap bitmap, int quality) {
synchronized (this) {
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
writeFile(file, bitmap, quality);
}
/**
* 重载 put(String file, Bitmap bitmap, int quality)
* @param filePath file path
* @param bitmap
* @param quality 1~100
*/
@Override
public void put(String file, Bitmap bitmap) {
put(file, bitmap, DEFAULT_COMPRESS_QUALITY);
}
/**
* 将Bitmap写入本地缓存文件.
* @param file URL/PATH
* @param bitmap
* @param quality
*/
private void writeFile(String file, Bitmap bitmap, int quality) {
if (bitmap == null) {
Log.w(TAG, "Can't write file. Bitmap is null.");
return;
}
BufferedOutputStream bos = null;
try {
String hashedUrl = getMd5(file);
bos = new BufferedOutputStream(
mContext.openFileOutput(hashedUrl, Context.MODE_PRIVATE));
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos); // PNG
Log.d(TAG, "Writing file: " + file);
} catch (IOException ioe) {
Log.e(TAG, ioe.getMessage());
} finally {
try {
if (bos != null) {
bitmap.recycle();
bos.flush();
bos.close();
}
//bitmap.recycle();
} catch (IOException e) {
Log.e(TAG, "Could not close file.");
}
}
}
private String writeToFile(InputStream is, String filename) {
Log.d("LDS", "new write to file");
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(is);
out = new BufferedOutputStream(
mContext.openFileOutput(filename, Context.MODE_PRIVATE));
byte[] buffer = new byte[1024];
int l;
while ((l = in.read(buffer)) != -1) {
out.write(buffer, 0, l);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (in != null) in.close();
if (out != null) {
Log.d("LDS", "new write to file to -> " + filename);
out.flush();
out.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return mContext.getFilesDir() + "/" + filename;
}
public Bitmap get(File file) {
return get(file.getPath());
}
/**
* 判断缓存着中是否存在该文件对应的bitmap
*/
public boolean isContains(String file) {
return mCache.containsKey(file);
}
/**
* 获得指定file/URL对应的Bitmap,首先找本地文件,如果有直接使用,否则去网上获取
* @param file file URL/file PATH
* @param bitmap
* @param quality
* @throws HttpException
*/
public Bitmap safeGet(String file) throws HttpException {
Bitmap bitmap = lookupFile(file); // first try file.
if (bitmap != null) {
synchronized (this) { // memory cache
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
return bitmap;
} else { //get from web
String url = file;
bitmap = downloadImage2(url);
// 注释掉以测试新的写入文件方法
//put(file, bitmap); // file Cache
return bitmap;
}
}
/**
* 从缓存器中读取文件
* @param file file URL/file PATH
* @param bitmap
* @param quality
*/
public Bitmap get(String file) {
SoftReference<Bitmap> ref;
Bitmap bitmap;
// Look in memory first.
synchronized (this) {
ref = mCache.get(file);
}
if (ref != null) {
bitmap = ref.get();
if (bitmap != null) {
return bitmap;
}
}
// Now try file.
bitmap = lookupFile(file);
if (bitmap != null) {
synchronized (this) {
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
return bitmap;
}
//TODO: why?
//upload: see profileImageCacheManager line 96
Log.w(TAG, "Image is missing: " + file);
// return the default photo
return mDefaultBitmap;
}
public boolean contains(String url) {
return get(url) != mDefaultBitmap;
}
public void clear() {
String[] files = mContext.fileList();
for (String file : files) {
mContext.deleteFile(file);
}
synchronized (this) {
mCache.clear();
}
}
public void cleanup(HashSet<String> keepers) {
String[] files = mContext.fileList();
HashSet<String> hashedUrls = new HashSet<String>();
for (String imageUrl : keepers) {
hashedUrls.add(getMd5(imageUrl));
}
for (String file : files) {
if (!hashedUrls.contains(file)) {
Log.d(TAG, "Deleting unused file: " + file);
mContext.deleteFile(file);
}
}
}
/**
* Compress and resize the Image
*
* <br />
* 因为不论图片大小和尺寸如何, 饭否都会对图片进行一次有损压缩, 所以本地压缩应该
* 考虑图片将会被二次压缩所造成的图片质量损耗
*
* @param targetFile
* @param quality, 0~100, recommend 100
* @return
* @throws IOException
*/
public File compressImage(File targetFile, int quality) throws IOException {
String filepath = targetFile.getAbsolutePath();
// 1. Calculate scale
int scale = 1;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filepath, o);
if (o.outWidth > IMAGE_MAX_WIDTH || o.outHeight > IMAGE_MAX_HEIGHT) {
scale = (int) Math.pow( 2.0,
(int) Math.round(Math.log(IMAGE_MAX_WIDTH
/ (double) Math.max(o.outHeight, o.outWidth))
/ Math.log(0.5)));
//scale = 2;
}
Log.d(TAG, scale + " scale");
// 2. File -> Bitmap (Returning a smaller image)
o.inJustDecodeBounds = false;
o.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filepath, o);
// 2.1. Resize Bitmap
//bitmap = resizeBitmap(bitmap, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT);
// 3. Bitmap -> File
writeFile(filepath, bitmap, quality);
// 4. Get resized Image File
String filePath = getMd5(targetFile.getPath());
File compressedImage = mContext.getFileStreamPath(filePath);
return compressedImage;
}
/**
* 保持长宽比缩小Bitmap
*
* @param bitmap
* @param maxWidth
* @param maxHeight
* @param quality 1~100
* @return
*/
public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
int originWidth = bitmap.getWidth();
int originHeight = bitmap.getHeight();
// no need to resize
if (originWidth < maxWidth && originHeight < maxHeight) {
return bitmap;
}
int newWidth = originWidth;
int newHeight = originHeight;
// 若图片过宽, 则保持长宽比缩放图片
if (originWidth > maxWidth) {
newWidth = maxWidth;
double i = originWidth * 1.0 / maxWidth;
newHeight = (int) Math.floor(originHeight / i);
bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}
// 若图片过长, 则从中部截取
if (newHeight > maxHeight) {
newHeight = maxHeight;
int half_diff = (int)((originHeight - maxHeight) / 2.0);
bitmap = Bitmap.createBitmap(bitmap, 0, half_diff, newWidth, newHeight);
}
Log.d(TAG, newWidth + " width");
Log.d(TAG, newHeight + " height");
return bitmap;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/app/ImageManager.java | Java | asf20 | 16,006 |
package com.ch_linghu.fanfoudroid.app;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
public class SimpleImageLoader {
public static void display(final ImageView imageView, String url) {
imageView.setTag(url);
imageView.setImageBitmap(TwitterApplication.mImageLoader
.get(url, createImageViewCallback(imageView, url)));
}
public static ImageLoaderCallback createImageViewCallback(final ImageView imageView, String url)
{
return new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
if (url.equals(imageView.getTag())) {
imageView.setImageBitmap(bitmap);
}
}
};
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/app/SimpleImageLoader.java | Java | asf20 | 912 |
package com.ch_linghu.fanfoudroid.app;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.http.HttpException;
public class LazyImageLoader {
private static final String TAG = "ProfileImageCacheManager";
public static final int HANDLER_MESSAGE_ID = 1;
public static final String EXTRA_BITMAP = "extra_bitmap";
public static final String EXTRA_IMAGE_URL = "extra_image_url";
private ImageManager mImageManager = new ImageManager(
TwitterApplication.mContext);
private BlockingQueue<String> mUrlList = new ArrayBlockingQueue<String>(50);
private CallbackManager mCallbackManager = new CallbackManager();
private GetImageTask mTask = new GetImageTask();
/**
* 取图片, 可能直接从cache中返回, 或下载图片后返回
*
* @param url
* @param callback
* @return
*/
public Bitmap get(String url, ImageLoaderCallback callback) {
Bitmap bitmap = ImageCache.mDefaultBitmap;
if (mImageManager.isContains(url)) {
bitmap = mImageManager.get(url);
} else {
// bitmap不存在,启动Task进行下载
mCallbackManager.put(url, callback);
startDownloadThread(url);
}
return bitmap;
}
private void startDownloadThread(String url) {
if (url != null) {
addUrlToDownloadQueue(url);
}
// Start Thread
State state = mTask.getState();
if (Thread.State.NEW == state) {
mTask.start(); // first start
} else if (Thread.State.TERMINATED == state) {
mTask = new GetImageTask(); // restart
mTask.start();
}
}
private void addUrlToDownloadQueue(String url) {
if (!mUrlList.contains(url)) {
try {
mUrlList.put(url);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// Low-level interface to get ImageManager
public ImageManager getImageManager() {
return mImageManager;
}
private class GetImageTask extends Thread {
private volatile boolean mTaskTerminated = false;
private static final int TIMEOUT = 3 * 60;
private boolean isPermanent = true;
@Override
public void run() {
try {
while (!mTaskTerminated) {
String url;
if (isPermanent) {
url = mUrlList.take();
} else {
url = mUrlList.poll(TIMEOUT, TimeUnit.SECONDS); // waiting
if (null == url) {
break;
} // no more, shutdown
}
// Bitmap bitmap = ImageCache.mDefaultBitmap;
final Bitmap bitmap = mImageManager.safeGet(url);
// use handler to process callback
final Message m = handler.obtainMessage(HANDLER_MESSAGE_ID);
Bundle bundle = m.getData();
bundle.putString(EXTRA_IMAGE_URL, url);
bundle.putParcelable(EXTRA_BITMAP, bitmap);
handler.sendMessage(m);
}
} catch (HttpException ioe) {
Log.e(TAG, "Get Image failed, " + ioe.getMessage());
} catch (InterruptedException e) {
Log.w(TAG, e.getMessage());
} finally {
Log.v(TAG, "Get image task terminated.");
mTaskTerminated = true;
}
}
@SuppressWarnings("unused")
public boolean isPermanent() {
return isPermanent;
}
@SuppressWarnings("unused")
public void setPermanent(boolean isPermanent) {
this.isPermanent = isPermanent;
}
@SuppressWarnings("unused")
public void shutDown() throws InterruptedException {
mTaskTerminated = true;
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case HANDLER_MESSAGE_ID:
final Bundle bundle = msg.getData();
String url = bundle.getString(EXTRA_IMAGE_URL);
Bitmap bitmap = (Bitmap) (bundle.get(EXTRA_BITMAP));
// callback
mCallbackManager.call(url, bitmap);
break;
default:
// do nothing.
}
}
};
public interface ImageLoaderCallback {
void refresh(String url, Bitmap bitmap);
}
public static class CallbackManager {
private static final String TAG = "CallbackManager";
private ConcurrentHashMap<String, List<ImageLoaderCallback>> mCallbackMap;
public CallbackManager() {
mCallbackMap = new ConcurrentHashMap<String, List<ImageLoaderCallback>>();
}
public void put(String url, ImageLoaderCallback callback) {
Log.v(TAG, "url=" + url);
if (!mCallbackMap.containsKey(url)) {
Log.v(TAG, "url does not exist, add list to map");
mCallbackMap.put(url, new ArrayList<ImageLoaderCallback>());
//mCallbackMap.put(url, Collections.synchronizedList(new ArrayList<ImageLoaderCallback>()));
}
mCallbackMap.get(url).add(callback);
Log.v(TAG, "Add callback to list, count(url)=" + mCallbackMap.get(url).size());
}
public void call(String url, Bitmap bitmap) {
Log.v(TAG, "call url=" + url);
List<ImageLoaderCallback> callbackList = mCallbackMap.get(url);
if (callbackList == null) {
// FIXME: 有时会到达这里,原因我还没想明白
Log.e(TAG, "callbackList=null");
return;
}
for (ImageLoaderCallback callback : callbackList) {
if (callback != null) {
callback.refresh(url, bitmap);
}
}
callbackList.clear();
mCallbackMap.remove(url);
}
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/app/LazyImageLoader.java | Java | asf20 | 6,721 |
package com.ch_linghu.fanfoudroid.app;
import android.graphics.Bitmap;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
public interface ImageCache {
public static Bitmap mDefaultBitmap = ImageManager.drawableToBitmap(TwitterApplication.mContext.getResources().getDrawable(R.drawable.user_default_photo));
public Bitmap get(String url);
public void put(String url, Bitmap bitmap);
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/app/ImageCache.java | Java | asf20 | 443 |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid.data;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class Tweet extends Message implements Parcelable {
private static final String TAG = "Tweet";
public com.ch_linghu.fanfoudroid.fanfou.User user;
public String source;
public String prevId;
private int statusType = -1; // @see StatusTable#TYPE_*
public void setStatusType(int type) {
statusType = type;
}
public int getStatusType() {
return statusType;
}
public Tweet(){}
public static Tweet create(Status status){
Tweet tweet = new Tweet();
tweet.id = status.getId();
//转义符放到getSimpleTweetText里去处理,这里不做处理
tweet.text = status.getText();
tweet.createdAt = status.getCreatedAt();
tweet.favorited = status.isFavorited()?"true":"false";
tweet.truncated = status.isTruncated()?"true":"false";
tweet.inReplyToStatusId = status.getInReplyToStatusId();
tweet.inReplyToUserId = status.getInReplyToUserId();
tweet.inReplyToScreenName = status.getInReplyToScreenName();
tweet.screenName = TextHelper.getSimpleTweetText(status.getUser().getScreenName());
tweet.profileImageUrl = status.getUser().getProfileImageURL().toString();
tweet.userId = status.getUser().getId();
tweet.user = status.getUser();
tweet.thumbnail_pic = status.getThumbnail_pic();
tweet.bmiddle_pic = status.getBmiddle_pic();
tweet.original_pic = status.getOriginal_pic();
tweet.source = TextHelper.getSimpleTweetText(status.getSource());
return tweet;
}
public static Tweet createFromSearchApi(JSONObject jsonObject) throws JSONException {
Tweet tweet = new Tweet();
tweet.id = jsonObject.getString("id") + "";
//转义符放到getSimpleTweetText里去处理,这里不做处理
tweet.text = jsonObject.getString("text");
tweet.createdAt = DateTimeHelper.parseSearchApiDateTime(jsonObject.getString("created_at"));
tweet.favorited = jsonObject.getString("favorited");
tweet.truncated = jsonObject.getString("truncated");
tweet.inReplyToStatusId = jsonObject.getString("in_reply_to_status_id");
tweet.inReplyToUserId = jsonObject.getString("in_reply_to_user_id");
tweet.inReplyToScreenName = jsonObject.getString("in_reply_to_screen_name");
tweet.screenName = TextHelper.getSimpleTweetText(jsonObject.getString("from_user"));
tweet.profileImageUrl = jsonObject.getString("profile_image_url");
tweet.userId = jsonObject.getString("from_user_id");
tweet.source = TextHelper.getSimpleTweetText(jsonObject.getString("source"));
return tweet;
}
public static String buildMetaText(StringBuilder builder,
Date createdAt, String source, String replyTo) {
builder.setLength(0);
builder.append(DateTimeHelper.getRelativeDate(createdAt));
builder.append(" ");
builder.append(TwitterApplication.mContext.getString(R.string.tweet_source_prefix));
builder.append(source);
if (!TextUtils.isEmpty(replyTo)) {
builder.append(" " + TwitterApplication.mContext.getString(R.string.tweet_reply_to_prefix));
builder.append(replyTo);
builder.append(TwitterApplication.mContext.getString(R.string.tweet_reply_to_suffix));
}
return builder.toString();
}
// For interface Parcelable
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(id);
out.writeString(text);
out.writeValue(createdAt); //Date
out.writeString(screenName);
out.writeString(favorited);
out.writeString(inReplyToStatusId);
out.writeString(inReplyToUserId);
out.writeString(inReplyToScreenName);
out.writeString(screenName);
out.writeString(profileImageUrl);
out.writeString(thumbnail_pic);
out.writeString(bmiddle_pic);
out.writeString(original_pic);
out.writeString(userId);
out.writeString(source);
}
public static final Parcelable.Creator<Tweet> CREATOR
= new Parcelable.Creator<Tweet>() {
public Tweet createFromParcel(Parcel in) {
return new Tweet(in);
}
public Tweet[] newArray(int size) {
// return new Tweet[size];
throw new UnsupportedOperationException();
}
};
public Tweet(Parcel in) {
id = in.readString();
text = in.readString();
createdAt = (Date) in.readValue(Date.class.getClassLoader());
screenName = in.readString();
favorited = in.readString();
inReplyToStatusId = in.readString();
inReplyToUserId = in.readString();
inReplyToScreenName = in.readString();
screenName = in.readString();
profileImageUrl = in.readString();
thumbnail_pic = in.readString();
bmiddle_pic = in.readString();
original_pic = in.readString();
userId = in.readString();
source = in.readString();
}
@Override
public String toString() {
return "Tweet [source=" + source + ", id=" + id + ", screenName="
+ screenName + ", text=" + text + ", profileImageUrl="
+ profileImageUrl + ", createdAt=" + createdAt + ", userId="
+ userId + ", favorited=" + favorited + ", inReplyToStatusId="
+ inReplyToStatusId + ", inReplyToUserId=" + inReplyToUserId
+ ", inReplyToScreenName=" + inReplyToScreenName + "]";
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/data/Tweet.java | Java | asf20 | 6,410 |
package com.ch_linghu.fanfoudroid.data;
import android.database.Cursor;
public interface BaseContent {
long insert();
int delete();
int update();
Cursor select();
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/data/BaseContent.java | Java | asf20 | 184 |
package com.ch_linghu.fanfoudroid.data;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class Dm extends Message {
@SuppressWarnings("unused")
private static final String TAG = "Dm";
public boolean isSent;
public static Dm create(DirectMessage directMessage, boolean isSent){
Dm dm = new Dm();
dm.id = directMessage.getId();
dm.text = directMessage.getText();
dm.createdAt = directMessage.getCreatedAt();
dm.isSent = isSent;
User user = dm.isSent ? directMessage.getRecipient()
: directMessage.getSender();
dm.screenName = TextHelper.getSimpleTweetText(user.getScreenName());
dm.userId = user.getId();
dm.profileImageUrl = user.getProfileImageURL().toString();
return dm;
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/data/Dm.java | Java | asf20 | 884 |
package com.ch_linghu.fanfoudroid.data;
import java.util.Date;
import android.os.Parcel;
import android.os.Parcelable;
public class User implements Parcelable {
public String id;
public String name;
public String screenName;
public String location;
public String description;
public String profileImageUrl;
public String url;
public boolean isProtected;
public int followersCount;
public String lastStatus;
public int friendsCount;
public int favoritesCount;
public int statusesCount;
public Date createdAt;
public boolean isFollowing;
// public boolean notifications;
// public utc_offset
public User() {}
public static User create(com.ch_linghu.fanfoudroid.fanfou.User u) {
User user = new User();
user.id = u.getId();
user.name = u.getName();
user.screenName = u.getScreenName();
user.location = u.getLocation();
user.description = u.getDescription();
user.profileImageUrl = u.getProfileImageURL().toString();
if (u.getURL() != null) {
user.url = u.getURL().toString();
}
user.isProtected = u.isProtected();
user.followersCount = u.getFollowersCount();
user.lastStatus = u.getStatusText();
user.friendsCount = u.getFriendsCount();
user.favoritesCount = u.getFavouritesCount();
user.statusesCount = u.getStatusesCount();
user.createdAt = u.getCreatedAt();
user.isFollowing = u.isFollowing();
return user;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
boolean[] boolArray = new boolean[] { isProtected, isFollowing };
out.writeString(id);
out.writeString(name);
out.writeString(screenName);
out.writeString(location);
out.writeString(description);
out.writeString(profileImageUrl);
out.writeString(url);
out.writeBooleanArray(boolArray);
out.writeInt(friendsCount);
out.writeInt(followersCount);
out.writeInt(statusesCount);
}
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
public User createFromParcel(Parcel in) {
return new User(in);
}
public User[] newArray(int size) {
// return new User[size];
throw new UnsupportedOperationException();
}
};
public User(Parcel in){
boolean[] boolArray = new boolean[]{isProtected, isFollowing};
id = in.readString();
name = in.readString();
screenName = in.readString();
location = in.readString();
description = in.readString();
profileImageUrl = in.readString();
url = in.readString();
in.readBooleanArray(boolArray);
friendsCount = in.readInt();
followersCount = in.readInt();
statusesCount = in.readInt();
isProtected = boolArray[0];
isFollowing = boolArray[1];
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/data/User.java | Java | asf20 | 2,793 |
package com.ch_linghu.fanfoudroid.data;
import java.util.Date;
public class Message {
public String id;
public String screenName;
public String text;
public String profileImageUrl;
public Date createdAt;
public String userId;
public String favorited;
public String truncated;
public String inReplyToStatusId;
public String inReplyToUserId;
public String inReplyToScreenName;
public String thumbnail_pic;
public String bmiddle_pic;
public String original_pic;
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/data/Message.java | Java | asf20 | 517 |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.hardware.SensorManager;
import android.util.Log;
import android.widget.RemoteViews;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.service.TwitterService;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class FanfouWidget extends AppWidgetProvider {
public final String TAG = "FanfouWidget";
public final String NEXTACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.NEXT";
public final String PREACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.PREV";
private static List<Tweet> tweets;
private SensorManager sensorManager;
private static int position = 0;
class CacheCallback implements ImageLoaderCallback {
private RemoteViews updateViews;
CacheCallback(RemoteViews updateViews) {
this.updateViews = updateViews;
}
@Override
public void refresh(String url, Bitmap bitmap) {
updateViews.setImageViewBitmap(R.id.status_image, bitmap);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appwidgetmanager,
int[] appWidgetIds) {
Log.d(TAG, "onUpdate");
TwitterService.setWidgetStatus(true);
// if (!isRunning(context, WidgetService.class.getName())) {
// Intent i = new Intent(context, WidgetService.class);
// context.startService(i);
// }
update(context);
}
private void update(Context context) {
fetchMessages();
position = 0;
refreshView(context, NEXTACTION);
}
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public String getUserId() {
return TwitterApplication.getMyselfId();
}
private void fetchMessages() {
if (tweets == null) {
tweets = new ArrayList<Tweet>();
} else {
tweets.clear();
}
Cursor cursor = getDb().fetchAllTweets(getUserId(),
StatusTable.TYPE_HOME);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Tweet tweet = StatusTable.parseCursor(cursor);
tweets.add(tweet);
} while (cursor.moveToNext());
}
}
Log.d(TAG, "Tweets size " + tweets.size());
}
private void refreshView(Context context) {
ComponentName fanfouWidget = new ComponentName(context,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(fanfouWidget, buildLogin(context));
}
private RemoteViews buildLogin(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
updateViews.setTextViewText(R.id.status_text,
TextHelper.getSimpleTweetText("请登录"));
updateViews.setTextViewText(R.id.status_screen_name,"");
updateViews.setTextViewText(R.id.tweet_source,"");
updateViews.setTextViewText(R.id.tweet_created_at,
"");
return updateViews;
}
private void refreshView(Context context, String action) {
// 某些情况下,tweets会为null
if (tweets == null) {
fetchMessages();
}
// 防止引发IndexOutOfBoundsException
if (tweets.size() != 0) {
if (action.equals(NEXTACTION)) {
--position;
} else if (action.equals(PREACTION)) {
++position;
}
// Log.d(TAG, "Tweets size =" + tweets.size());
if (position >= tweets.size() || position < 0) {
position = 0;
}
// Log.d(TAG, "position=" + position);
ComponentName fanfouWidget = new ComponentName(context,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(fanfouWidget, buildUpdate(context));
}
}
public RemoteViews buildUpdate(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
Tweet t = tweets.get(position);
Log.d(TAG, "tweet=" + t);
updateViews.setTextViewText(R.id.status_screen_name, t.screenName);
updateViews.setTextViewText(R.id.status_text,
TextHelper.getSimpleTweetText(t.text));
updateViews.setTextViewText(R.id.tweet_source,
context.getString(R.string.tweet_source_prefix) + t.source);
updateViews.setTextViewText(R.id.tweet_created_at,
DateTimeHelper.getRelativeDate(t.createdAt));
updateViews.setImageViewBitmap(R.id.status_image,
TwitterApplication.mImageLoader.get(
t.profileImageUrl, new CacheCallback(updateViews)));
Intent inext = new Intent(context, FanfouWidget.class);
inext.setAction(NEXTACTION);
PendingIntent pinext = PendingIntent.getBroadcast(context, 0, inext,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.btn_next, pinext);
Intent ipre = new Intent(context, FanfouWidget.class);
ipre.setAction(PREACTION);
PendingIntent pipre = PendingIntent.getBroadcast(context, 0, ipre,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.btn_pre, pipre);
Intent write = WriteActivity.createNewTweetIntent("");
PendingIntent piwrite = PendingIntent.getActivity(context, 0, write,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.write_message, piwrite);
Intent home = TwitterActivity.createIntent(context);
PendingIntent pihome = PendingIntent.getActivity(context, 0, home,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.logo_image, pihome);
Intent status = StatusActivity.createIntent(t);
PendingIntent pistatus = PendingIntent.getActivity(context, 0, status,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.main_body, pistatus);
return updateViews;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "OnReceive");
// FIXME: NullPointerException
Log.i(TAG, context.getApplicationContext().toString());
if (!TwitterApplication.mApi.isLoggedIn()) {
refreshView(context);
} else {
super.onReceive(context, intent);
String action = intent.getAction();
if (NEXTACTION.equals(action) || PREACTION.equals(action)) {
refreshView(context, intent.getAction());
} else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
update(context);
}
}
}
/**
*
* @param c
* @param serviceName
* @return
*/
@Deprecated
public boolean isRunning(Context c, String serviceName) {
ActivityManager myAM = (ActivityManager) c
.getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<RunningServiceInfo> runningServices = (ArrayList<RunningServiceInfo>) myAM
.getRunningServices(40);
// 获取最多40个当前正在运行的服务,放进ArrList里,以现在手机的处理能力,要是超过40个服务,估计已经卡死,所以不用考虑超过40个该怎么办
int servicesSize = runningServices.size();
for (int i = 0; i < servicesSize; i++)// 循环枚举对比
{
if (runningServices.get(i).service.getClassName().toString()
.equals(serviceName)) {
return true;
}
}
return false;
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
Log.d(TAG, "onDeleted");
}
@Override
public void onEnabled(Context context) {
Log.d(TAG, "onEnabled");
TwitterService.setWidgetStatus(true);
}
@Override
public void onDisabled(Context context) {
Log.d(TAG, "onDisabled");
TwitterService.setWidgetStatus(false);
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/FanfouWidget.java | Java | asf20 | 8,105 |
package com.ch_linghu.fanfoudroid;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.db.MessageTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class DmActivity extends BaseActivity implements Refreshable {
private static final String TAG = "DmActivity";
// Views.
private ListView mTweetList;
private Adapter mAdapter;
private Adapter mInboxAdapter;
private Adapter mSendboxAdapter;
Button inbox;
Button sendbox;
Button newMsg;
private int mDMType;
private static final int DM_TYPE_ALL = 0;
private static final int DM_TYPE_INBOX = 1;
private static final int DM_TYPE_SENDBOX = 2;
private TextView mProgressText;
private NavBar mNavbar;
private Feedback mFeedback;
// Tasks.
private GenericTask mRetrieveTask;
private GenericTask mDeleteTask;
private TaskListener mDeleteTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
updateProgress(getString(R.string.page_status_deleting));
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mAdapter.refresh();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "DmDeleteTask";
}
};
private TaskListener mRetrieveTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
updateProgress(getString(R.string.page_status_refreshing));
}
@Override
public void onProgressUpdate(GenericTask task, Object params) {
draw();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putLong(Preferences.LAST_DM_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
draw();
goTop();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "DmRetrieve";
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
private static final String EXTRA_USER = "user";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMS";
public static Intent createIntent() {
return createIntent("");
}
public static Intent createIntent(String user) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (!TextUtils.isEmpty(user)) {
intent.putExtra(EXTRA_USER, user);
}
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState))
{
setContentView(R.layout.dm);
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mNavbar.setHeaderTitle("我的私信");
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
bindFooterButtonEvent();
mTweetList = (ListView) findViewById(R.id.tweet_list);
mProgressText = (TextView) findViewById(R.id.progress_text);
TwitterDatabase db = getDb();
// Mark all as read.
db.markAllDmsRead();
setupAdapter(); // Make sure call bindFooterButtonEvent first
boolean shouldRetrieve = false;
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_DM_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
if (diff > REFRESH_THRESHOLD) {
shouldRetrieve = true;
} else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) {
// Check to see if it was running a send or retrieve task.
// It makes no sense to resend the send request (don't want dupes)
// so we instead retrieve (refresh) to see if the message has
// posted.
Log.d(TAG,
"Was last running a retrieve or send task. Let's refresh.");
shouldRetrieve = true;
}
if (shouldRetrieve) {
doRetrieve();
}
// Want to be able to focus on the items with the trackball.
// That way, we can navigate up and down by changing item focus.
mTweetList.setItemsCanFocus(true);
return true;
}else{
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
private static final String SIS_RUNNING_KEY = "running";
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
mDeleteTask.cancel(true);
}
super.onDestroy();
}
// UI helpers.
private void bindFooterButtonEvent() {
inbox = (Button) findViewById(R.id.inbox);
sendbox = (Button) findViewById(R.id.sendbox);
newMsg = (Button) findViewById(R.id.new_message);
inbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mDMType != DM_TYPE_INBOX) {
mDMType = DM_TYPE_INBOX;
inbox.setEnabled(false);
sendbox.setEnabled(true);
mTweetList.setAdapter(mInboxAdapter);
mInboxAdapter.refresh();
}
}
});
sendbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mDMType != DM_TYPE_SENDBOX) {
mDMType = DM_TYPE_SENDBOX;
inbox.setEnabled(true);
sendbox.setEnabled(false);
mTweetList.setAdapter(mSendboxAdapter);
mSendboxAdapter.refresh();
}
}
});
newMsg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(DmActivity.this, WriteDmActivity.class);
intent.putExtra("reply_to_id", 0); // TODO: 传入实际的reply_to_id
startActivity(intent);
}
});
}
private void setupAdapter() {
Cursor cursor = getDb().fetchAllDms(-1);
startManagingCursor(cursor);
mAdapter = new Adapter(this, cursor);
Cursor inboxCursor = getDb().fetchInboxDms();
startManagingCursor(inboxCursor);
mInboxAdapter = new Adapter(this, inboxCursor);
Cursor sendboxCursor = getDb().fetchSendboxDms();
startManagingCursor(sendboxCursor);
mSendboxAdapter = new Adapter(this, sendboxCursor);
mTweetList.setAdapter(mInboxAdapter);
registerForContextMenu(mTweetList);
inbox.setEnabled(false);
}
private class DmRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams...params) {
List<DirectMessage> dmList;
ArrayList<Dm> dms = new ArrayList<Dm>();
TwitterDatabase db = getDb();
//ImageManager imageManager = getImageManager();
String maxId = db.fetchMaxDmId(false);
HashSet<String> imageUrls = new HashSet<String>();
try {
if (maxId != null) {
Paging paging = new Paging(maxId);
dmList = getApi().getDirectMessages(paging);
} else {
dmList = getApi().getDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, dmList));
for (DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, false);
dms.add(dm);
imageUrls.add(dm.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
maxId = db.fetchMaxDmId(true);
try {
if (maxId != null) {
Paging paging = new Paging(maxId);
dmList = getApi().getSentDirectMessages(paging);
} else {
dmList = getApi().getSentDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, true);
dms.add(dm);
imageUrls.add(dm.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
db.addDms(dms, false);
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
//
// publishProgress(null);
//
// for (String imageUrl : imageUrls) {
// if (!Utils.isEmpty(imageUrl)) {
// // Fetch image to cache.
// try {
// imageManager.put(imageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
//
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
// }
return TaskResult.OK;
}
}
private static class Adapter extends CursorAdapter {
public Adapter(Context context, Cursor cursor) {
super(context, cursor);
mInflater = LayoutInflater.from(context);
// TODO: 可使用:
//DM dm = MessageTable.parseCursor(cursor);
mUserTextColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_USER_SCREEN_NAME);
mTextColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_TEXT);
mProfileImageUrlColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_PROFILE_IMAGE_URL);
mCreatedAtColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_CREATED_AT);
mIsSentColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_IS_SENT);
}
private LayoutInflater mInflater;
private int mUserTextColumn;
private int mTextColumn;
private int mProfileImageUrlColumn;
private int mIsSentColumn;
private int mCreatedAtColumn;
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.direct_message, parent,
false);
ViewHolder holder = new ViewHolder();
holder.userText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view
.findViewById(R.id.profile_image);
holder.metaText = (TextView) view
.findViewById(R.id.tweet_meta_text);
view.setTag(holder);
return view;
}
class ViewHolder {
public TextView userText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
int isSent = cursor.getInt(mIsSentColumn);
String user = cursor.getString(mUserTextColumn);
if (0 == isSent) {
holder.userText.setText(context
.getString(R.string.direct_message_label_from_prefix)
+ user);
} else {
holder.userText.setText(context
.getString(R.string.direct_message_label_to_prefix)
+ user);
}
TextHelper.setTweetText(holder.tweetText, cursor.getString(mTextColumn));
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage
.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, new ImageLoaderCallback(){
@Override
public void refresh(String url,
Bitmap bitmap) {
Adapter.this.refresh();
}
}));
}
try {
holder.metaText.setText(DateTimeHelper
.getRelativeDate(TwitterDatabase.DB_DATE_FORMATTER
.parse(cursor.getString(mCreatedAtColumn))));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
}
public void refresh() {
getCursor().requery();
}
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// FIXME: 将刷新功能绑定到顶部的刷新按钮上,主菜单中的刷新选项已删除
// case OPTIONS_MENU_ID_REFRESH:
// doRetrieve();
// return true;
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
}
return super.onOptionsItemSelected(item);
}
private static final int CONTEXT_REPLY_ID = 0;
private static final int CONTEXT_DELETE_ID = 1;
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply);
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Cursor cursor = (Cursor) mAdapter.getItem(info.position);
if (cursor == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTEXT_REPLY_ID:
String user_id = cursor.getString(cursor
.getColumnIndexOrThrow(MessageTable.FIELD_USER_ID));
Intent intent = WriteDmActivity.createIntent(user_id);
startActivity(intent);
return true;
case CONTEXT_DELETE_ID:
int idIndex = cursor.getColumnIndexOrThrow(MessageTable._ID);
String id = cursor.getString(idIndex);
doDestroy(id);
return true;
default:
return super.onContextItemSelected(item);
}
}
private void doDestroy(String id) {
Log.d(TAG, "Attempting delete.");
if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mDeleteTask = new DmDeleteTask();
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
private class DmDeleteTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams...params) {
TaskParams param = params[0];
try {
String id = param.getString("id");
DirectMessage directMessage = getApi().destroyDirectMessage(id);
Dm.create(directMessage, false);
getDb().deleteDm(id);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mRetrieveTask = new DmRetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
}
}
public void goTop() {
mTweetList.setSelection(0);
}
public void draw() {
mAdapter.refresh();
mInboxAdapter.refresh();
mSendboxAdapter.refresh();
}
private void updateProgress(String msg) {
mProgressText.setText(msg);
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/DmActivity.java | Java | asf20 | 17,720 |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
//TODO: 数据来源换成 getFavorites()
public class FavoritesActivity extends TwitterCursorBaseActivity {
private static final String TAG = "FavoritesActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FAVORITES";
private static final String USER_ID = "userid";
private static final String USER_NAME = "userName";
private static final int DIALOG_WRITE_ID = 0;
private String userId = null;
private String userName = null;
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)){
mNavbar.setHeaderTitle(getActivityTitle());
return true;
}else{
return false;
}
}
public static Intent createNewTaskIntent(String userId, String userName) {
Intent intent = createIntent(userId, userName);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
protected Cursor fetchMessages() {
// TODO Auto-generated method stub
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
String template = getString(R.string.page_title_favorites);
String who;
if (getUserId().equals(TwitterApplication.getMyselfId())){
who = "我";
}else{
who = getUserName();
}
return MessageFormat.format(template, who);
}
@Override
protected void markAllRead() {
// TODO Auto-generated method stub
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_FAVORITE);
}
// hasRetrieveListTask interface
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_FAVORITE, isUnread);
}
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
if (maxId != null){
return getApi().getFavorites(getUserId(), new Paging(maxId));
}else{
return getApi().getFavorites(getUserId());
}
}
@Override
public String fetchMinId() {
return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
public List<Status> getMoreMessageFromId(String minId)
throws HttpException {
Paging paging = new Paging(1, 20);
paging.setMaxId(minId);
return getApi().getFavorites(getUserId(), paging);
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_FAVORITE;
}
@Override
public String getUserId() {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null){
userId = extras.getString(USER_ID);
} else {
userId = TwitterApplication.getMyselfId();
}
return userId;
}
public String getUserName(){
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null){
userName = extras.getString(USER_NAME);
} else {
userName = TwitterApplication.getMyselfName();
}
return userName;
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/FavoritesActivity.java | Java | asf20 | 4,543 |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
public class FollowingActivity extends UserArrayBaseActivity {
private ListView mUserList;
private UserArrayAdapter mAdapter;
private String userId;
private String userName;
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWING";
private static final String USER_ID = "userId";
private static final String USER_NAME = "userName";
private int currentPage=1;
String myself="";
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
// 获取登录用户id
userId=TwitterApplication.getMyselfId();
userName = TwitterApplication.getMyselfName();
}
if(super._onCreate(savedInstanceState)){
myself = TwitterApplication.getMyselfId();
if(getUserId()==myself){
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_friends_count_title), "我"));
} else {
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_friends_count_title), userName));
}
return true;
}else{
return false;
}
}
/*
* 添加取消关注按钮
* @see com.ch_linghu.fanfoudroid.ui.base.UserListBaseActivity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(getUserId()==myself){
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
User user = getContextItemUser(info.position);
menu.add(0,CONTENT_DEL_FRIEND,0,getResources().getString(R.string.cmenu_user_addfriend_prefix)+user.screenName+getResources().getString(R.string.cmenu_user_friend_suffix));
}
}
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
public Paging getNextPage() {
currentPage+=1;
return new Paging(currentPage);
}
@Override
protected String getUserId() {
return this.userId;
}
@Override
public Paging getCurrentPage() {
return new Paging(this.currentPage);
}
@Override
protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException {
return getApi().getFriendsStatuses(userId, page);
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/FollowingActivity.java | Java | asf20 | 3,315 |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
/**
*
* @author Dino 2011-02-26
*/
// public class ProfileActivity extends WithHeaderActivity {
public class ProfileActivity extends BaseActivity {
private static final String TAG = "ProfileActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.PROFILE";
private static final String STATUS_COUNT = "status_count";
private static final String EXTRA_USER = "user";
private static final String FANFOUROOT = "http://fanfou.com/";
private static final String USER_ID = "userid";
private static final String USER_NAME = "userName";
private GenericTask profileInfoTask;// 获取用户信息
private GenericTask setFollowingTask;
private GenericTask cancelFollowingTask;
private String userId;
private String userName;
private String myself;
private User profileInfo;// 用户信息
private ImageView profileImageView;// 头像
private TextView profileName;// 名称
private TextView profileScreenName;// 昵称
private TextView userLocation;// 地址
private TextView userUrl;// url
private TextView userInfo;// 自述
private TextView friendsCount;// 好友
private TextView followersCount;// 收听
private TextView statusCount;// 消息
private TextView favouritesCount;// 收藏
private TextView isFollowingText;// 是否关注
private Button followingBtn;// 收听/取消关注按钮
private Button sendMentionBtn;// 发送留言按钮
private Button sendDmBtn;// 发送私信按钮
private ProgressDialog dialog; // 请稍候
private RelativeLayout friendsLayout;
private LinearLayout followersLayout;
private LinearLayout statusesLayout;
private LinearLayout favouritesLayout;
private NavBar mNavBar;
private Feedback mFeedback;
private TwitterDatabase db;
public static Intent createIntent(String userId) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(USER_ID, userId);
return intent;
}
private ImageLoaderCallback callback = new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
profileImageView.setImageBitmap(bitmap);
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "OnCreate start");
if (super._onCreate(savedInstanceState)) {
setContentView(R.layout.profile);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
myself = TwitterApplication.getMyselfId();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
this.userId = myself;
this.userName = TwitterApplication.getMyselfName();
}
Uri data = intent.getData();
if (data != null) {
userId = data.getLastPathSegment();
}
// 初始化控件
initControls();
Log.d(TAG, "the userid is " + userId);
db = this.getDb();
draw();
return true;
} else {
return false;
}
}
private void initControls() {
mNavBar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mNavBar.setHeaderTitle("");
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
sendMentionBtn = (Button) findViewById(R.id.sendmetion_btn);
sendDmBtn = (Button) findViewById(R.id.senddm_btn);
profileImageView = (ImageView) findViewById(R.id.profileimage);
profileName = (TextView) findViewById(R.id.profilename);
profileScreenName = (TextView) findViewById(R.id.profilescreenname);
userLocation = (TextView) findViewById(R.id.user_location);
userUrl = (TextView) findViewById(R.id.user_url);
userInfo = (TextView) findViewById(R.id.tweet_user_info);
friendsCount = (TextView) findViewById(R.id.friends_count);
followersCount = (TextView) findViewById(R.id.followers_count);
TextView friendsCountTitle = (TextView) findViewById(R.id.friends_count_title);
TextView followersCountTitle = (TextView) findViewById(R.id.followers_count_title);
String who;
if (userId.equals(myself)) {
who = "我";
} else {
who = "ta";
}
friendsCountTitle.setText(MessageFormat.format(
getString(R.string.profile_friends_count_title), who));
followersCountTitle.setText(MessageFormat.format(
getString(R.string.profile_followers_count_title), who));
statusCount = (TextView) findViewById(R.id.statuses_count);
favouritesCount = (TextView) findViewById(R.id.favourites_count);
friendsLayout = (RelativeLayout) findViewById(R.id.friendsLayout);
followersLayout = (LinearLayout) findViewById(R.id.followersLayout);
statusesLayout = (LinearLayout) findViewById(R.id.statusesLayout);
favouritesLayout = (LinearLayout) findViewById(R.id.favouritesLayout);
isFollowingText = (TextView) findViewById(R.id.isfollowing_text);
followingBtn = (Button) findViewById(R.id.following_btn);
// 为按钮面板添加事件
friendsLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = FollowingActivity
.createIntent(userId, showName);
intent.setClass(ProfileActivity.this, FollowingActivity.class);
startActivity(intent);
}
});
followersLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = FollowersActivity
.createIntent(userId, showName);
intent.setClass(ProfileActivity.this, FollowersActivity.class);
startActivity(intent);
}
});
statusesLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = UserTimelineActivity.createIntent(
profileInfo.getId(), showName);
launchActivity(intent);
}
});
favouritesLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
Intent intent = FavoritesActivity.createIntent(userId,
profileInfo.getName());
intent.setClass(ProfileActivity.this, FavoritesActivity.class);
startActivity(intent);
}
});
// 刷新
View.OnClickListener refreshListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
doGetProfileInfo();
}
};
mNavBar.getRefreshButton().setOnClickListener(refreshListener);
}
private void draw() {
Log.d(TAG, "draw");
bindProfileInfo();
// doGetProfileInfo();
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
/**
* 从数据库获取,如果数据库不存在则创建
*/
private void bindProfileInfo() {
dialog = ProgressDialog.show(ProfileActivity.this, "请稍候", "正在加载信息...");
if (null != db && db.existsUser(userId)) {
Cursor cursor = db.getUserInfoById(userId);
profileInfo = User.parseUser(cursor);
cursor.close();
if (profileInfo == null) {
Log.w(TAG, "cannot get userinfo from userinfotable the id is"
+ userId);
}
bindControl();
if (dialog != null) {
dialog.dismiss();
}
} else {
doGetProfileInfo();
}
}
private void doGetProfileInfo() {
mFeedback.start("");
if (profileInfoTask != null
&& profileInfoTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
profileInfoTask = new GetProfileTask();
profileInfoTask.setListener(profileInfoTaskListener);
TaskParams params = new TaskParams();
profileInfoTask.execute(params);
}
}
private void bindControl() {
if (profileInfo.getId().equals(myself)) {
sendMentionBtn.setVisibility(View.GONE);
sendDmBtn.setVisibility(View.GONE);
} else {
// 发送留言
sendMentionBtn.setVisibility(View.VISIBLE);
sendMentionBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewTweetIntent(String
.format("@%s ", profileInfo.getScreenName()));
startActivity(intent);
}
});
// 发送私信
sendDmBtn.setVisibility(View.VISIBLE);
sendDmBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteDmActivity.createIntent(profileInfo
.getId());
startActivity(intent);
}
});
}
if (userId.equals(myself)) {
mNavBar.setHeaderTitle("我"
+ getString(R.string.cmenu_user_profile_prefix));
} else {
mNavBar.setHeaderTitle(profileInfo.getScreenName()
+ getString(R.string.cmenu_user_profile_prefix));
}
profileImageView
.setImageBitmap(TwitterApplication.mImageLoader
.get(profileInfo.getProfileImageURL().toString(),
callback));
profileName.setText(profileInfo.getId());
profileScreenName.setText(profileInfo.getScreenName());
if (profileInfo.getId().equals(myself)) {
isFollowingText.setText(R.string.profile_isyou);
followingBtn.setVisibility(View.GONE);
} else if (profileInfo.isFollowing()) {
isFollowingText.setText(R.string.profile_isfollowing);
followingBtn.setVisibility(View.VISIBLE);
followingBtn.setText(R.string.user_label_unfollow);
followingBtn.setOnClickListener(cancelFollowingListener);
followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources()
.getDrawable(R.drawable.ic_unfollow), null, null, null);
} else {
isFollowingText.setText(R.string.profile_notfollowing);
followingBtn.setVisibility(View.VISIBLE);
followingBtn.setText(R.string.user_label_follow);
followingBtn.setOnClickListener(setfollowingListener);
followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources()
.getDrawable(R.drawable.ic_follow), null, null, null);
}
String location = profileInfo.getLocation();
if (location == null || location.length() == 0) {
location = getResources().getString(R.string.profile_location_null);
}
userLocation.setText(location);
if (profileInfo.getURL() != null) {
userUrl.setText(profileInfo.getURL().toString());
} else {
userUrl.setText(FANFOUROOT + profileInfo.getId());
}
String description = profileInfo.getDescription();
if (description == null || description.length() == 0) {
description = getResources().getString(
R.string.profile_description_null);
}
userInfo.setText(description);
friendsCount.setText(String.valueOf(profileInfo.getFriendsCount()));
followersCount.setText(String.valueOf(profileInfo.getFollowersCount()));
statusCount.setText(String.valueOf(profileInfo.getStatusesCount()));
favouritesCount
.setText(String.valueOf(profileInfo.getFavouritesCount()));
}
private TaskListener profileInfoTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
// 加载成功
if (result == TaskResult.OK) {
mFeedback.success("");
// 绑定控件
bindControl();
if (dialog != null) {
dialog.dismiss();
}
}
}
@Override
public String getName() {
return "GetProfileInfo";
}
};
/**
* 更新数据库中的用户
*
* @return
*/
private boolean updateUser() {
ContentValues v = new ContentValues();
v.put(BaseColumns._ID, profileInfo.getName());
v.put(UserInfoTable.FIELD_USER_NAME, profileInfo.getName());
v.put(UserInfoTable.FIELD_USER_SCREEN_NAME, profileInfo.getScreenName());
v.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, profileInfo
.getProfileImageURL().toString());
v.put(UserInfoTable.FIELD_LOCALTION, profileInfo.getLocation());
v.put(UserInfoTable.FIELD_DESCRIPTION, profileInfo.getDescription());
v.put(UserInfoTable.FIELD_PROTECTED, profileInfo.isProtected());
v.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
profileInfo.getFollowersCount());
v.put(UserInfoTable.FIELD_LAST_STATUS, profileInfo.getStatusSource());
v.put(UserInfoTable.FIELD_FRIENDS_COUNT, profileInfo.getFriendsCount());
v.put(UserInfoTable.FIELD_FAVORITES_COUNT,
profileInfo.getFavouritesCount());
v.put(UserInfoTable.FIELD_STATUSES_COUNT,
profileInfo.getStatusesCount());
v.put(UserInfoTable.FIELD_FOLLOWING, profileInfo.isFollowing());
if (profileInfo.getURL() != null) {
v.put(UserInfoTable.FIELD_URL, profileInfo.getURL().toString());
}
return db.updateUser(profileInfo.getId(), v);
}
/**
* 获取用户信息task
*
* @author Dino
*
*/
private class GetProfileTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.v(TAG, "get profile task");
try {
profileInfo = getApi().showUser(userId);
mFeedback.update(80);
if (profileInfo != null) {
if (null != db && !db.existsUser(userId)) {
com.ch_linghu.fanfoudroid.data.User userinfodb = profileInfo
.parseUser();
db.createUserInfo(userinfodb);
} else {
// 更新用户
updateUser();
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage());
return TaskResult.FAILED;
}
mFeedback.update(99);
return TaskResult.OK;
}
}
/**
* 设置关注监听
*/
private OnClickListener setfollowingListener = new OnClickListener() {
@Override
public void onClick(View v) {
Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
};
/*
* 取消关注监听
*/
private OnClickListener cancelFollowingListener = new OnClickListener() {
@Override
public void onClick(View v) {
Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
};
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
followingBtn.setText("取消关注");
isFollowingText.setText(getResources().getString(
R.string.profile_isfollowing));
followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
followingBtn.setText("添加关注");
isFollowingText.setText(getResources().getString(
R.string.profile_notfollowing));
followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ProfileActivity.java | Java | asf20 | 24,896 |
package com.ch_linghu.fanfoudroid.dao;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.dao.SQLiteTemplate.RowMapper;
import com.ch_linghu.fanfoudroid.data2.Photo;
import com.ch_linghu.fanfoudroid.data2.Status;
import com.ch_linghu.fanfoudroid.data2.User;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db2.FanContent;
import com.ch_linghu.fanfoudroid.db2.FanContent.StatusesPropertyTable;
import com.ch_linghu.fanfoudroid.db2.FanDatabase;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.db2.FanContent.*;
public class StatusDAO {
private static final String TAG = "StatusDAO";
private SQLiteTemplate mSqlTemplate;
public StatusDAO(Context context) {
mSqlTemplate = new SQLiteTemplate(FanDatabase.getInstance(context)
.getSQLiteOpenHelper());
}
/**
* Insert a Status
*
* 若报 SQLiteconstraintexception 异常, 检查是否某not null字段为空
*
* @param status
* @param isUnread
* @return
*/
public long insertStatus(Status status) {
if (!isExists(status)) {
return mSqlTemplate.getDb(true).insert(StatusesTable.TABLE_NAME, null,
statusToContentValues(status));
} else {
Log.e(TAG, status.getId() + " is exists.");
return -1;
}
}
// TODO:
public int insertStatuses(List<Status> statuses) {
int result = 0;
SQLiteDatabase db = mSqlTemplate.getDb(true);
try {
db.beginTransaction();
for (int i = statuses.size() - 1; i >= 0; i--) {
Status status = statuses.get(i);
long id = db.insertWithOnConflict(StatusesTable.TABLE_NAME, null,
statusToContentValues(status),
SQLiteDatabase.CONFLICT_IGNORE);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + status.toString());
} else {
++result;
Log.v(TAG, String.format(
"Insert a status into database : %s",
status.toString()));
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return result;
}
/**
* Delete a status
*
* @param statusId
* @param owner_id
* owner id
* @param type
* status type
* @return
* @see StatusDAO#deleteStatus(Status)
*/
public int deleteStatus(String statusId, String owner_id, int type) {
//FIXME: 数据模型改变后这里的逻辑需要完全重写,目前仅保证编译可通过
String where = StatusesTable.Columns.ID + " =? ";
String[] binds;
if (!TextUtils.isEmpty(owner_id)) {
where += " AND " + StatusesPropertyTable.Columns.OWNER_ID + " = ? ";
binds = new String[] { statusId, owner_id };
} else {
binds = new String[] { statusId };
}
if (-1 != type) {
where += " AND " + StatusesPropertyTable.Columns.TYPE + " = " + type;
}
return mSqlTemplate.getDb(true).delete(StatusesTable.TABLE_NAME, where.toString(),
binds);
}
/**
* Delete a Status
*
* @param status
* @return
* @see StatusDAO#deleteStatus(String, String, int)
*/
public int deleteStatus(Status status) {
return deleteStatus(status.getId(), status.getOwnerId(),
status.getType());
}
/**
* Find a status by status ID
*
* @param statusId
* @return
*/
public Status fetchStatus(String statusId) {
return mSqlTemplate.queryForObject(mRowMapper, StatusesTable.TABLE_NAME, null,
StatusesTable.Columns.ID + " = ?", new String[] { statusId }, null,
null, "created_at DESC", "1");
}
/**
* Find user's statuses
*
* @param userId
* user id
* @param statusType
* status type, see {@link StatusTable#TYPE_USER}...
* @return list of statuses
*/
public List<Status> fetchStatuses(String userId, int statusType) {
return mSqlTemplate.queryForList(mRowMapper, FanContent.StatusesTable.TABLE_NAME, null,
StatusesPropertyTable.Columns.OWNER_ID + " = ? AND " + StatusesPropertyTable.Columns.TYPE
+ " = " + statusType, new String[] { userId }, null,
null, "created_at DESC", null);
}
/**
* @see StatusDAO#fetchStatuses(String, int)
*/
public List<Status> fetchStatuses(String userId, String statusType) {
return fetchStatuses(userId, Integer.parseInt(statusType));
}
/**
* Update by using {@link ContentValues}
*
* @param statusId
* @param newValues
* @return
*/
public int updateStatus(String statusId, ContentValues values) {
return mSqlTemplate.updateById(FanContent.StatusesTable.TABLE_NAME, statusId, values);
}
/**
* Update by using {@link Status}
*
* @param status
* @return
*/
public int updateStatus(Status status) {
return updateStatus(status.getId(), statusToContentValues(status));
}
/**
* Check if status exists
*
* FIXME: 取消使用Query
*
* @param status
* @return
*/
public boolean isExists(Status status) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT COUNT(*) FROM ").append(FanContent.StatusesTable.TABLE_NAME)
.append(" WHERE ").append(StatusesTable.Columns.ID).append(" =? AND ")
.append(StatusesPropertyTable.Columns.OWNER_ID).append(" =? AND ")
.append(StatusesPropertyTable.Columns.TYPE).append(" = ")
.append(status.getType());
return mSqlTemplate.isExistsBySQL(sql.toString(),
new String[] { status.getId(), status.getUser().getId() });
}
/**
* Status -> ContentValues
*
* @param status
* @param isUnread
* @return
*/
private ContentValues statusToContentValues(Status status) {
final ContentValues v = new ContentValues();
v.put(StatusesTable.Columns.ID, status.getId());
v.put(StatusesPropertyTable.Columns.TYPE, status.getType());
v.put(StatusesTable.Columns.TEXT, status.getText());
v.put(StatusesPropertyTable.Columns.OWNER_ID, status.getOwnerId());
v.put(StatusesTable.Columns.FAVORITED, status.isFavorited() + "");
v.put(StatusesTable.Columns.TRUNCATED, status.isTruncated()); // TODO:
v.put(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID, status.getInReplyToStatusId());
v.put(StatusesTable.Columns.IN_REPLY_TO_USER_ID, status.getInReplyToUserId());
// v.put(StatusTable.Columns.IN_REPLY_TO_SCREEN_NAME,
// status.getInReplyToScreenName());
// v.put(IS_REPLY, status.isReply());
v.put(StatusesTable.Columns.CREATED_AT,
TwitterDatabase.DB_DATE_FORMATTER.format(status.getCreatedAt()));
v.put(StatusesTable.Columns.SOURCE, status.getSource());
// v.put(StatusTable.Columns.IS_UNREAD, status.isUnRead());
final User user = status.getUser();
if (user != null) {
v.put(UserTable.Columns.USER_ID, user.getId());
v.put(UserTable.Columns.SCREEN_NAME, user.getScreenName());
v.put(UserTable.Columns.PROFILE_IMAGE_URL, user.getProfileImageUrl());
}
final Photo photo = status.getPhotoUrl();
/*if (photo != null) {
v.put(StatusTable.Columns.PIC_THUMB, photo.getThumburl());
v.put(StatusTable.Columns.PIC_MID, photo.getImageurl());
v.put(StatusTable.Columns.PIC_ORIG, photo.getLargeurl());
}*/
return v;
}
private static final RowMapper<Status> mRowMapper = new RowMapper<Status>() {
@Override
public Status mapRow(Cursor cursor, int rowNum) {
Photo photo = new Photo();
/*photo.setImageurl(cursor.getString(cursor
.getColumnIndex(StatusTable.Columns.PIC_MID)));
photo.setLargeurl(cursor.getString(cursor
.getColumnIndex(StatusTable.Columns.PIC_ORIG)));
photo.setThumburl(cursor.getString(cursor
.getColumnIndex(StatusTable.Columns.PIC_THUMB)));
*/
User user = new User();
user.setScreenName(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.SCREEN_NAME)));
user.setId(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.USER_ID)));
user.setProfileImageUrl(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.PROFILE_IMAGE_URL)));
Status status = new Status();
status.setPhotoUrl(photo);
status.setUser(user);
status.setOwnerId(cursor.getString(cursor
.getColumnIndex(StatusesPropertyTable.Columns.OWNER_ID)));
// TODO: 将数据库中的statusType改成Int类型
status.setType(cursor.getInt(cursor
.getColumnIndex(StatusesPropertyTable.Columns.TYPE)));
status.setId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.ID)));
status.setCreatedAt(DateTimeHelper.parseDateTimeFromSqlite(cursor
.getString(cursor.getColumnIndex(StatusesTable.Columns.CREATED_AT))));
// TODO: 更改favorite 在数据库类型为boolean后改为 " != 0 "
status.setFavorited(cursor.getString(
cursor.getColumnIndex(StatusesTable.Columns.FAVORITED))
.equals("true"));
status.setText(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.TEXT)));
status.setSource(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.SOURCE)));
// status.setInReplyToScreenName(cursor.getString(cursor
// .getColumnIndex(StatusTable.IN_REPLY_TO_SCREEN_NAME)));
status.setInReplyToStatusId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID)));
status.setInReplyToUserId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_USER_ID)));
status.setTruncated(cursor.getInt(cursor
.getColumnIndex(StatusesTable.Columns.TRUNCATED)) != 0);
// status.setUnRead(cursor.getInt(cursor
// .getColumnIndex(StatusTable.Columns.IS_UNREAD)) != 0);
return status;
}
};
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/dao/StatusDAO.java | Java | asf20 | 11,168 |
package com.ch_linghu.fanfoudroid.dao;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Database Helper
*
* @see SQLiteDatabase
*/
public class SQLiteTemplate {
/**
* Default Primary key
*/
protected String mPrimaryKey = "_id";
/**
* SQLiteDatabase Open Helper
*/
protected SQLiteOpenHelper mDatabaseOpenHelper;
/**
* Construct
*
* @param databaseOpenHelper
*/
public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper) {
mDatabaseOpenHelper = databaseOpenHelper;
}
/**
* Construct
*
* @param databaseOpenHelper
* @param primaryKey
*/
public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper, String primaryKey) {
this(databaseOpenHelper);
setPrimaryKey(primaryKey);
}
/**
* 根据某一个字段和值删除一行数据, 如 name="jack"
*
* @param table
* @param field
* @param value
* @return
*/
public int deleteByField(String table, String field, String value) {
return getDb(true).delete(table, field + "=?", new String[] { value });
}
/**
* 根据主键删除一行数据
*
* @param table
* @param id
* @return
*/
public int deleteById(String table, String id) {
return deleteByField(table, mPrimaryKey, id);
}
/**
* 根据主键更新一行数据
*
* @param table
* @param id
* @param values
* @return
*/
public int updateById(String table, String id, ContentValues values) {
return getDb(true).update(table, values, mPrimaryKey + "=?",
new String[] { id });
}
/**
* 根据主键查看某条数据是否存在
*
* @param table
* @param id
* @return
*/
public boolean isExistsById(String table, String id) {
return isExistsByField(table, mPrimaryKey, id);
}
/**
* 根据某字段/值查看某条数据是否存在
*
* @param status
* @return
*/
public boolean isExistsByField(String table, String field, String value) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT COUNT(*) FROM ").append(table).append(" WHERE ")
.append(field).append(" =?");
return isExistsBySQL(sql.toString(), new String[] { value });
}
/**
* 使用SQL语句查看某条数据是否存在
*
* @param sql
* @param selectionArgs
* @return
*/
public boolean isExistsBySQL(String sql, String[] selectionArgs) {
boolean result = false;
final Cursor c = getDb(false).rawQuery(sql, selectionArgs);
try {
if (c.moveToFirst()) {
result = (c.getInt(0) > 0);
}
} finally {
c.close();
}
return result;
}
/**
* Query for cursor
*
* @param <T>
* @param rowMapper
* @return a cursor
*
* @see SQLiteDatabase#query(String, String[], String, String[], String,
* String, String, String)
*/
public <T> T queryForObject(RowMapper<T> rowMapper, String table,
String[] columns, String selection, String[] selectionArgs,
String groupBy, String having, String orderBy, String limit) {
T object = null;
final Cursor c = getDb(false).query(table, columns, selection, selectionArgs,
groupBy, having, orderBy, limit);
try {
if (c.moveToFirst()) {
object = rowMapper.mapRow(c, c.getCount());
}
} finally {
c.close();
}
return object;
}
/**
* Query for list
*
* @param <T>
* @param rowMapper
* @return list of object
*
* @see SQLiteDatabase#query(String, String[], String, String[], String,
* String, String, String)
*/
public <T> List<T> queryForList(RowMapper<T> rowMapper, String table,
String[] columns, String selection, String[] selectionArgs,
String groupBy, String having, String orderBy, String limit) {
List<T> list = new ArrayList<T>();
final Cursor c = getDb(false).query(table, columns, selection, selectionArgs,
groupBy, having, orderBy, limit);
try {
while (c.moveToNext()) {
list.add(rowMapper.mapRow(c, 1));
}
} finally {
c.close();
}
return list;
}
/**
* Get Primary Key
*
* @return
*/
public String getPrimaryKey() {
return mPrimaryKey;
}
/**
* Set Primary Key
*
* @param primaryKey
*/
public void setPrimaryKey(String primaryKey) {
this.mPrimaryKey = primaryKey;
}
/**
* Get Database Connection
*
* @param writeable
* @return
* @see SQLiteOpenHelper#getWritableDatabase();
* @see SQLiteOpenHelper#getReadableDatabase();
*/
public SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mDatabaseOpenHelper.getWritableDatabase();
} else {
return mDatabaseOpenHelper.getReadableDatabase();
}
}
/**
* Some as Spring JDBC RowMapper
*
* @see org.springframework.jdbc.core.RowMapper
* @see com.ch_linghu.fanfoudroid.db.dao.SqliteTemplate
* @param <T>
*/
public interface RowMapper<T> {
public T mapRow(Cursor cursor, int rowNum);
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/dao/SQLiteTemplate.java | Java | asf20 | 5,766 |
package com.ch_linghu.fanfoudroid.db2;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.ch_linghu.fanfoudroid.db2.FanContent.*;
public class FanDatabase {
private static final String TAG = FanDatabase.class.getSimpleName();
/**
* SQLite Database file name
*/
private static final String DATABASE_NAME = "fanfoudroid.db";
/**
* Database Version
*/
public static final int DATABASE_VERSION = 2;
/**
* self instance
*/
private static FanDatabase sInstance = null;
/**
* SQLiteDatabase Open Helper
*/
private DatabaseHelper mOpenHelper = null;
/**
* SQLiteOpenHelper
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
// Construct
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "Create Database.");
// TODO: create tables
createAllTables(db);
createAllIndexes(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Upgrade Database.");
// TODO: DROP TABLE
onCreate(db);
}
}
/**
* Construct
*
* @param context
*/
private FanDatabase(Context context) {
mOpenHelper = new DatabaseHelper(context);
}
/**
* Get Database
*
* @param context
* @return
*/
public static synchronized FanDatabase getInstance(Context context) {
if (null == sInstance) {
sInstance = new FanDatabase(context);
}
return sInstance;
}
/**
* Get SQLiteDatabase Open Helper
*
* @return
*/
public SQLiteOpenHelper getSQLiteOpenHelper() {
return mOpenHelper;
}
/**
* Get Database Connection
*
* @param writeable
* @return
*/
public SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mOpenHelper.getWritableDatabase();
} else {
return mOpenHelper.getReadableDatabase();
}
}
/**
* Close Database
*/
public void close() {
if (null != sInstance) {
mOpenHelper.close();
sInstance = null;
}
}
// Create All tables
private static void createAllTables(SQLiteDatabase db) {
db.execSQL(StatusesTable.getCreateSQL());
db.execSQL(StatusesPropertyTable.getCreateSQL());
db.execSQL(UserTable.getCreateSQL());
db.execSQL(DirectMessageTable.getCreateSQL());
db.execSQL(FollowRelationshipTable.getCreateSQL());
db.execSQL(TrendTable.getCreateSQL());
db.execSQL(SavedSearchTable.getCreateSQL());
}
private static void dropAllTables(SQLiteDatabase db) {
db.execSQL(StatusesTable.getDropSQL());
db.execSQL(StatusesPropertyTable.getDropSQL());
db.execSQL(UserTable.getDropSQL());
db.execSQL(DirectMessageTable.getDropSQL());
db.execSQL(FollowRelationshipTable.getDropSQL());
db.execSQL(TrendTable.getDropSQL());
db.execSQL(SavedSearchTable.getDropSQL());
}
private static void resetAllTables(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
dropAllTables(db);
} catch (SQLException e) {
Log.e(TAG, "resetAllTables ERROR!");
}
createAllTables(db);
}
//indexes
private static void createAllIndexes(SQLiteDatabase db) {
db.execSQL(StatusesTable.getCreateIndexSQL());
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/db2/FanDatabase.java | Java | asf20 | 3,885 |
package com.ch_linghu.fanfoudroid.db2;
import java.util.zip.CheckedOutputStream;
import android.R.color;
public abstract class FanContent {
/**
* 消息表 消息表存放消息本身
*
* @author phoenix
*
*/
public static class StatusesTable {
public static final String TABLE_NAME = "t_statuses";
public static class Columns {
public static final String ID = "_id";
public static final String STATUS_ID = "status_id";
public static final String AUTHOR_ID = "author_id";
public static final String TEXT = "text";
public static final String SOURCE = "source";
public static final String CREATED_AT = "created_at";
public static final String TRUNCATED = "truncated";
public static final String FAVORITED = "favorited";
public static final String PHOTO_URL = "photo_url";
public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.STATUS_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.AUTHOR_ID + " TEXT, "
+ Columns.TEXT + " TEXT, " + Columns.SOURCE + " TEXT, "
+ Columns.CREATED_AT + " INT, " + Columns.TRUNCATED
+ " INT DEFAULT 0, " + Columns.FAVORITED
+ " INT DEFAULT 0, " + Columns.PHOTO_URL + " TEXT, "
+ Columns.IN_REPLY_TO_STATUS_ID + " TEXT, "
+ Columns.IN_REPLY_TO_USER_ID + " TEXT, "
+ Columns.IN_REPLY_TO_SCREEN_NAME + " TEXT " + ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.STATUS_ID,
Columns.AUTHOR_ID, Columns.TEXT, Columns.SOURCE,
Columns.CREATED_AT, Columns.TRUNCATED, Columns.FAVORITED,
Columns.PHOTO_URL, Columns.IN_REPLY_TO_STATUS_ID,
Columns.IN_REPLY_TO_USER_ID,
Columns.IN_REPLY_TO_SCREEN_NAME };
}
public static String getCreateIndexSQL() {
String createIndexSQL = "CREATE INDEX " + TABLE_NAME + "_idx ON "
+ TABLE_NAME + " ( " + getIndexColumns()[1] + " );";
return createIndexSQL;
}
}
/**
* 消息属性表 每一条消息所属类别、所有者等信息 消息ID(外键) 所有者(随便看看的所有者为空)
* 消息类别(随便看看/首页(自己及自己好友)/个人(仅自己)/收藏/照片)
*
* @author phoenix
*
*/
public static class StatusesPropertyTable {
public static final String TABLE_NAME = "t_statuses_property";
public static class Columns {
public static final String ID = "_id";
public static final String STATUS_ID = "status_id";
public static final String OWNER_ID = "owner_id";
public static final String TYPE = "type";
public static final String SEQUENCE_FLAG = "sequence_flag";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.STATUS_ID
+ " TEXT NOT NULL, " + Columns.OWNER_ID + " TEXT, "
+ Columns.TYPE + " INT, " + Columns.SEQUENCE_FLAG
+ " INT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.STATUS_ID,
Columns.OWNER_ID, Columns.TYPE, Columns.SEQUENCE_FLAG,
Columns.LOAD_TIME };
}
}
/**
* User表 包括User的基本信息和扩展信息(每次获得最新User信息都update进User表)
* 每次更新User表时希望能更新LOAD_TIME,记录最后更新时间
*
* @author phoenix
*
*/
public static class UserTable {
public static final String TABLE_NAME = "t_user";
public static class Columns {
public static final String ID = "_id";
public static final String USER_ID = "user_id";
public static final String USER_NAME = "user_name";
public static final String SCREEN_NAME = "screen_name";
public static final String LOCATION = "location";
public static final String DESCRIPTION = "description";
public static final String URL = "url";
public static final String PROTECTED = "protected";
public static final String PROFILE_IMAGE_URL = "profile_image_url";
public static final String FOLLOWERS_COUNT = "followers_count";
public static final String FRIENDS_COUNT = "friends_count";
public static final String FAVOURITES_COUNT = "favourites_count";
public static final String STATUSES_COUNT = "statuses_count";
public static final String CREATED_AT = "created_at";
public static final String FOLLOWING = "following";
public static final String NOTIFICATIONS = "notifications";
public static final String UTC_OFFSET = "utc_offset";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.USER_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.USER_NAME
+ " TEXT UNIQUE NOT NULL, " + Columns.SCREEN_NAME
+ " TEXT, " + Columns.LOCATION + " TEXT, "
+ Columns.DESCRIPTION + " TEXT, " + Columns.URL + " TEXT, "
+ Columns.PROTECTED + " INT DEFAULT 0, "
+ Columns.PROFILE_IMAGE_URL + " TEXT "
+ Columns.FOLLOWERS_COUNT + " INT, "
+ Columns.FRIENDS_COUNT + " INT, "
+ Columns.FAVOURITES_COUNT + " INT, "
+ Columns.STATUSES_COUNT + " INT, " + Columns.CREATED_AT
+ " INT, " + Columns.FOLLOWING + " INT DEFAULT 0, "
+ Columns.NOTIFICATIONS + " INT DEFAULT 0, "
+ Columns.UTC_OFFSET + " TEXT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.USER_ID,
Columns.USER_NAME, Columns.SCREEN_NAME, Columns.LOCATION,
Columns.DESCRIPTION, Columns.URL, Columns.PROTECTED,
Columns.PROFILE_IMAGE_URL, Columns.FOLLOWERS_COUNT,
Columns.FRIENDS_COUNT, Columns.FAVOURITES_COUNT,
Columns.STATUSES_COUNT, Columns.CREATED_AT,
Columns.FOLLOWING, Columns.NOTIFICATIONS,
Columns.UTC_OFFSET, Columns.LOAD_TIME };
}
}
/**
* 私信表 私信的基本信息
*
* @author phoenix
*
*/
public static class DirectMessageTable {
public static final String TABLE_NAME = "t_direct_message";
public static class Columns {
public static final String ID = "_id";
public static final String MSG_ID = "msg_id";
public static final String TEXT = "text";
public static final String SENDER_ID = "sender_id";
public static final String RECIPINET_ID = "recipinet_id";
public static final String CREATED_AT = "created_at";
public static final String LOAD_TIME = "load_time";
public static final String SEQUENCE_FLAG = "sequence_flag";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.MSG_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.TEXT + " TEXT, "
+ Columns.SENDER_ID + " TEXT, " + Columns.RECIPINET_ID
+ " TEXT, " + Columns.CREATED_AT + " INT, "
+ Columns.SEQUENCE_FLAG + " INT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.MSG_ID, Columns.TEXT,
Columns.SENDER_ID, Columns.RECIPINET_ID,
Columns.CREATED_AT, Columns.SEQUENCE_FLAG,
Columns.LOAD_TIME };
}
}
/**
* Follow关系表 某个特定用户的Follow关系(User1 following User2,
* 查找关联某人好友只需限定User1或者User2)
*
* @author phoenix
*
*/
public static class FollowRelationshipTable {
public static final String TABLE_NAME = "t_follow_relationship";
public static class Columns {
public static final String USER1_ID = "user1_id";
public static final String USER2_ID = "user2_id";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.USER1_ID
+ " TEXT, " + Columns.USER2_ID + " TEXT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.USER1_ID, Columns.USER2_ID,
Columns.LOAD_TIME };
}
}
/**
* 热门话题表 记录每次查询得到的热词
*
* @author phoenix
*
*/
public static class TrendTable {
public static final String TABLE_NAME = "t_trend";
public static class Columns {
public static final String NAME = "name";
public static final String QUERY = "query";
public static final String URL = "url";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.NAME + " TEXT, "
+ Columns.QUERY + " TEXT, " + Columns.URL + " TEXT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.NAME, Columns.QUERY, Columns.URL,
Columns.LOAD_TIME };
}
}
/**
* 保存搜索表 QUERY_ID(这个ID在API删除保存搜索词时使用)
*
* @author phoenix
*
*/
public static class SavedSearchTable {
public static final String TABLE_NAME = "t_saved_search";
public static class Columns {
public static final String QUERY_ID = "query_id";
public static final String QUERY = "query";
public static final String NAME = "name";
public static final String CREATED_AT = "created_at";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.QUERY_ID
+ " INT, " + Columns.QUERY + " TEXT, " + Columns.NAME
+ " TEXT, " + Columns.CREATED_AT + " INT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.QUERY_ID, Columns.QUERY,
Columns.NAME, Columns.CREATED_AT, Columns.LOAD_TIME };
}
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/db2/FanContent.java | Java | asf20 | 13,587 |
package com.ch_linghu.fanfoudroid.db2;
import java.util.ArrayList;
import java.util.Arrays;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/**
* Wrapper of SQliteDatabse#query, OOP style.
*
* Usage:
* ------------------------------------------------
* Query select = new Query(SQLiteDatabase);
*
* // SELECT
* query.from("tableName", new String[] { "colName" })
* .where("id = ?", 123456)
* .where("name = ?", "jack")
* .orderBy("created_at DESC")
* .limit(1);
* Cursor cursor = query.select();
*
* // DELETE
* query.from("tableName")
* .where("id = ?", 123455);
* .delete();
*
* // UPDATE
* query.setTable("tableName")
* .values(contentValues)
* .update();
*
* // INSERT
* query.into("tableName")
* .values(contentValues)
* .insert();
* ------------------------------------------------
*
* @see SQLiteDatabase#query(String, String[], String, String[], String, String, String, String)
*/
public class Query
{
private static final String TAG = "Query-Builder";
/** TEMP list for selctionArgs */
private ArrayList<String> binds = new ArrayList<String>();
private SQLiteDatabase mDb = null;
private String mTable;
private String[] mColumns;
private String mSelection = null;
private String[] mSelectionArgs = null;
private String mGroupBy = null;
private String mHaving = null;
private String mOrderBy = null;
private String mLimit = null;
private ContentValues mValues = null;
private String mNullColumnHack = null;
public Query() { }
/**
* Construct
*
* @param db
*/
public Query(SQLiteDatabase db) {
this.setDb(db);
}
/**
* Query the given table, returning a Cursor over the result set.
*
* @param db SQLitedatabase
* @return A Cursor object, which is positioned before the first entry, or NULL
*/
public Cursor select() {
if ( preCheck() ) {
buildQuery();
return mDb.query(mTable, mColumns, mSelection, mSelectionArgs,
mGroupBy, mHaving, mOrderBy, mLimit);
} else {
//throw new SelectException("Cann't build the query . " + toString());
Log.e(TAG, "Cann't build the query " + toString());
return null;
}
}
/**
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
public int delete() {
if ( preCheck() ) {
buildQuery();
return mDb.delete(mTable, mSelection, mSelectionArgs);
} else {
Log.e(TAG, "Cann't build the query " + toString());
return -1;
}
}
/**
* Set FROM
*
* @param table
* The table name to compile the query against.
* @param columns
* A list of which columns to return. Passing null will return
* all columns, which is discouraged to prevent reading data from
* storage that isn't going to be used.
* @return self
*
*/
public Query from(String table, String[] columns) {
mTable = table;
mColumns = columns;
return this;
}
/**
* @see Query#from(String table, String[] columns)
* @param table
* @return self
*/
public Query from(String table) {
return from(table, null); // all columns
}
/**
* Add WHERE
*
* @param selection
* A filter declaring which rows to return, formatted as an SQL
* WHERE clause (excluding the WHERE itself). Passing null will
* return all rows for the given table.
* @param selectionArgs
* You may include ?s in selection, which will be replaced by the
* values from selectionArgs, in order that they appear in the
* selection. The values will be bound as Strings.
* @return self
*/
public Query where(String selection, String[] selectionArgs) {
addSelection(selection);
binds.addAll(Arrays.asList(selectionArgs));
return this;
}
/**
* @see Query#where(String selection, String[] selectionArgs)
*/
public Query where(String selection, String selectionArg) {
addSelection(selection);
binds.add(selectionArg);
return this;
}
/**
* @see Query#where(String selection, String[] selectionArgs)
*/
public Query where(String selection) {
addSelection(selection);
return this;
}
/**
* add selection part
*
* @param selection
*/
private void addSelection(String selection) {
if (null == mSelection) {
mSelection = selection;
} else {
mSelection += " AND " + selection;
}
}
/**
* set HAVING
*
* @param having
* A filter declare which row groups to include in the cursor, if
* row grouping is being used, formatted as an SQL HAVING clause
* (excluding the HAVING itself). Passing null will cause all row
* groups to be included, and is required when row grouping is
* not being used.
* @return self
*/
public Query having(String having) {
this.mHaving = having;
return this;
}
/**
* Set GROUP BY
*
* @param groupBy
* A filter declaring how to group rows, formatted as an SQL
* GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @return self
*/
public Query groupBy(String groupBy) {
this.mGroupBy = groupBy;
return this;
}
/**
* Set ORDER BY
*
* @param orderBy
* How to order the rows, formatted as an SQL ORDER BY clause
* (excluding the ORDER BY itself). Passing null will use the
* default sort order, which may be unordered.
* @return self
*/
public Query orderBy(String orderBy) {
this.mOrderBy = orderBy;
return this;
}
/**
* @param limit
* Limits the number of rows returned by the query, formatted as
* LIMIT clause. Passing null denotes no LIMIT clause.
* @return self
*/
public Query limit(String limit) {
this.mLimit = limit;
return this;
}
/**
* @see Query#limit(String limit)
*/
public Query limit(int limit) {
return limit(limit + "");
}
/**
* Merge selectionArgs
*/
private void buildQuery() {
mSelectionArgs = new String[binds.size()];
binds.toArray(mSelectionArgs);
Log.v(TAG, toString());
}
private boolean preCheck() {
return (mTable != null && mDb != null);
}
// For Insert
/**
* set insert table
*
* @param table table name
* @return self
*/
public Query into(String table) {
return setTable(table);
}
/**
* Set new values
*
* @param values new values
* @return self
*/
public Query values(ContentValues values) {
mValues = values;
return this;
}
/**
* Insert a row
*
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long insert() {
return mDb.insert(mTable, mNullColumnHack, mValues);
}
// For update
/**
* Set target table
*
* @param table table name
* @return self
*/
public Query setTable(String table) {
mTable = table;
return this;
}
/**
* Update a row
*
* @return the number of rows affected, or -1 if an error occurred
*/
public int update() {
if ( preCheck() ) {
buildQuery();
return mDb.update(mTable, mValues, mSelection, mSelectionArgs);
} else {
Log.e(TAG, "Cann't build the query " + toString());
return -1;
}
}
/**
* Set back-end database
* @param db
*/
public void setDb(SQLiteDatabase db) {
if (null == this.mDb) {
this.mDb = db;
}
}
@Override
public String toString() {
return "Query [table=" + mTable + ", columns="
+ Arrays.toString(mColumns) + ", selection=" + mSelection
+ ", selectionArgs=" + Arrays.toString(mSelectionArgs)
+ ", groupBy=" + mGroupBy + ", having=" + mHaving + ", orderBy="
+ mOrderBy + "]";
}
/** for debug */
public ContentValues getContentValues() {
return mValues;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/db2/Query.java | Java | asf20 | 9,118 |
package com.ch_linghu.fanfoudroid.http;
import java.util.HashMap;
import java.util.Map;
public class HTMLEntity {
public static String escape(String original) {
StringBuffer buf = new StringBuffer(original);
escape(buf);
return buf.toString();
}
public static void escape(StringBuffer original) {
int index = 0;
String escaped;
while (index < original.length()) {
escaped = entityEscapeMap.get(original.substring(index, index + 1));
if (null != escaped) {
original.replace(index, index + 1, escaped);
index += escaped.length();
} else {
index++;
}
}
}
public static String unescape(String original) {
StringBuffer buf = new StringBuffer(original);
unescape(buf);
return buf.toString();
}
public static void unescape(StringBuffer original) {
int index = 0;
int semicolonIndex = 0;
String escaped;
String entity;
while (index < original.length()) {
index = original.indexOf("&", index);
if (-1 == index) {
break;
}
semicolonIndex = original.indexOf(";", index);
if (-1 != semicolonIndex && 10 > (semicolonIndex - index)) {
escaped = original.substring(index, semicolonIndex + 1);
entity = escapeEntityMap.get(escaped);
if (null != entity) {
original.replace(index, semicolonIndex + 1, entity);
}
index++;
} else {
break;
}
}
}
private static Map<String, String> entityEscapeMap = new HashMap<String, String>();
private static Map<String, String> escapeEntityMap = new HashMap<String, String>();
static {
String[][] entities =
{{" ", " "/* no-break space = non-breaking space */, "\u00A0"}
, {"¡", "¡"/* inverted exclamation mark */, "\u00A1"}
, {"¢", "¢"/* cent sign */, "\u00A2"}
, {"£", "£"/* pound sign */, "\u00A3"}
, {"¤", "¤"/* currency sign */, "\u00A4"}
, {"¥", "¥"/* yen sign = yuan sign */, "\u00A5"}
, {"¦", "¦"/* broken bar = broken vertical bar */, "\u00A6"}
, {"§", "§"/* section sign */, "\u00A7"}
, {"¨", "¨"/* diaeresis = spacing diaeresis */, "\u00A8"}
, {"©", "©"/* copyright sign */, "\u00A9"}
, {"ª", "ª"/* feminine ordinal indicator */, "\u00AA"}
, {"«", "«"/* left-pointing double angle quotation mark = left pointing guillemet */, "\u00AB"}
, {"¬", "¬"/* not sign = discretionary hyphen */, "\u00AC"}
, {"­", "­"/* soft hyphen = discretionary hyphen */, "\u00AD"}
, {"®", "®"/* registered sign = registered trade mark sign */, "\u00AE"}
, {"¯", "¯"/* macron = spacing macron = overline = APL overbar */, "\u00AF"}
, {"°", "°"/* degree sign */, "\u00B0"}
, {"±", "±"/* plus-minus sign = plus-or-minus sign */, "\u00B1"}
, {"²", "²"/* superscript two = superscript digit two = squared */, "\u00B2"}
, {"³", "³"/* superscript three = superscript digit three = cubed */, "\u00B3"}
, {"´", "´"/* acute accent = spacing acute */, "\u00B4"}
, {"µ", "µ"/* micro sign */, "\u00B5"}
, {"¶", "¶"/* pilcrow sign = paragraph sign */, "\u00B6"}
, {"·", "·"/* middle dot = Georgian comma = Greek middle dot */, "\u00B7"}
, {"¸", "¸"/* cedilla = spacing cedilla */, "\u00B8"}
, {"¹", "¹"/* superscript one = superscript digit one */, "\u00B9"}
, {"º", "º"/* masculine ordinal indicator */, "\u00BA"}
, {"»", "»"/* right-pointing double angle quotation mark = right pointing guillemet */, "\u00BB"}
, {"¼", "¼"/* vulgar fraction one quarter = fraction one quarter */, "\u00BC"}
, {"½", "½"/* vulgar fraction one half = fraction one half */, "\u00BD"}
, {"¾", "¾"/* vulgar fraction three quarters = fraction three quarters */, "\u00BE"}
, {"¿", "¿"/* inverted question mark = turned question mark */, "\u00BF"}
, {"À", "À"/* latin capital letter A with grave = latin capital letter A grave */, "\u00C0"}
, {"Á", "Á"/* latin capital letter A with acute */, "\u00C1"}
, {"Â", "Â"/* latin capital letter A with circumflex */, "\u00C2"}
, {"Ã", "Ã"/* latin capital letter A with tilde */, "\u00C3"}
, {"Ä", "Ä"/* latin capital letter A with diaeresis */, "\u00C4"}
, {"Å", "Å"/* latin capital letter A with ring above = latin capital letter A ring */, "\u00C5"}
, {"Æ", "Æ"/* latin capital letter AE = latin capital ligature AE */, "\u00C6"}
, {"Ç", "Ç"/* latin capital letter C with cedilla */, "\u00C7"}
, {"È", "È"/* latin capital letter E with grave */, "\u00C8"}
, {"É", "É"/* latin capital letter E with acute */, "\u00C9"}
, {"Ê", "Ê"/* latin capital letter E with circumflex */, "\u00CA"}
, {"Ë", "Ë"/* latin capital letter E with diaeresis */, "\u00CB"}
, {"Ì", "Ì"/* latin capital letter I with grave */, "\u00CC"}
, {"Í", "Í"/* latin capital letter I with acute */, "\u00CD"}
, {"Î", "Î"/* latin capital letter I with circumflex */, "\u00CE"}
, {"Ï", "Ï"/* latin capital letter I with diaeresis */, "\u00CF"}
, {"Ð", "Ð"/* latin capital letter ETH */, "\u00D0"}
, {"Ñ", "Ñ"/* latin capital letter N with tilde */, "\u00D1"}
, {"Ò", "Ò"/* latin capital letter O with grave */, "\u00D2"}
, {"Ó", "Ó"/* latin capital letter O with acute */, "\u00D3"}
, {"Ô", "Ô"/* latin capital letter O with circumflex */, "\u00D4"}
, {"Õ", "Õ"/* latin capital letter O with tilde */, "\u00D5"}
, {"Ö", "Ö"/* latin capital letter O with diaeresis */, "\u00D6"}
, {"×", "×"/* multiplication sign */, "\u00D7"}
, {"Ø", "Ø"/* latin capital letter O with stroke = latin capital letter O slash */, "\u00D8"}
, {"Ù", "Ù"/* latin capital letter U with grave */, "\u00D9"}
, {"Ú", "Ú"/* latin capital letter U with acute */, "\u00DA"}
, {"Û", "Û"/* latin capital letter U with circumflex */, "\u00DB"}
, {"Ü", "Ü"/* latin capital letter U with diaeresis */, "\u00DC"}
, {"Ý", "Ý"/* latin capital letter Y with acute */, "\u00DD"}
, {"Þ", "Þ"/* latin capital letter THORN */, "\u00DE"}
, {"ß", "ß"/* latin small letter sharp s = ess-zed */, "\u00DF"}
, {"à", "à"/* latin small letter a with grave = latin small letter a grave */, "\u00E0"}
, {"á", "á"/* latin small letter a with acute */, "\u00E1"}
, {"â", "â"/* latin small letter a with circumflex */, "\u00E2"}
, {"ã", "ã"/* latin small letter a with tilde */, "\u00E3"}
, {"ä", "ä"/* latin small letter a with diaeresis */, "\u00E4"}
, {"å", "å"/* latin small letter a with ring above = latin small letter a ring */, "\u00E5"}
, {"æ", "æ"/* latin small letter ae = latin small ligature ae */, "\u00E6"}
, {"ç", "ç"/* latin small letter c with cedilla */, "\u00E7"}
, {"è", "è"/* latin small letter e with grave */, "\u00E8"}
, {"é", "é"/* latin small letter e with acute */, "\u00E9"}
, {"ê", "ê"/* latin small letter e with circumflex */, "\u00EA"}
, {"ë", "ë"/* latin small letter e with diaeresis */, "\u00EB"}
, {"ì", "ì"/* latin small letter i with grave */, "\u00EC"}
, {"í", "í"/* latin small letter i with acute */, "\u00ED"}
, {"î", "î"/* latin small letter i with circumflex */, "\u00EE"}
, {"ï", "ï"/* latin small letter i with diaeresis */, "\u00EF"}
, {"ð", "ð"/* latin small letter eth */, "\u00F0"}
, {"ñ", "ñ"/* latin small letter n with tilde */, "\u00F1"}
, {"ò", "ò"/* latin small letter o with grave */, "\u00F2"}
, {"ó", "ó"/* latin small letter o with acute */, "\u00F3"}
, {"ô", "ô"/* latin small letter o with circumflex */, "\u00F4"}
, {"õ", "õ"/* latin small letter o with tilde */, "\u00F5"}
, {"ö", "ö"/* latin small letter o with diaeresis */, "\u00F6"}
, {"÷", "÷"/* division sign */, "\u00F7"}
, {"ø", "ø"/* latin small letter o with stroke = latin small letter o slash */, "\u00F8"}
, {"ù", "ù"/* latin small letter u with grave */, "\u00F9"}
, {"ú", "ú"/* latin small letter u with acute */, "\u00FA"}
, {"û", "û"/* latin small letter u with circumflex */, "\u00FB"}
, {"ü", "ü"/* latin small letter u with diaeresis */, "\u00FC"}
, {"ý", "ý"/* latin small letter y with acute */, "\u00FD"}
, {"þ", "þ"/* latin small letter thorn with */, "\u00FE"}
, {"ÿ", "ÿ"/* latin small letter y with diaeresis */, "\u00FF"}
, {"ƒ", "ƒ"/* latin small f with hook = function = florin */, "\u0192"}
/* Greek */
, {"Α", "Α"/* greek capital letter alpha */, "\u0391"}
, {"Β", "Β"/* greek capital letter beta */, "\u0392"}
, {"Γ", "Γ"/* greek capital letter gamma */, "\u0393"}
, {"Δ", "Δ"/* greek capital letter delta */, "\u0394"}
, {"Ε", "Ε"/* greek capital letter epsilon */, "\u0395"}
, {"Ζ", "Ζ"/* greek capital letter zeta */, "\u0396"}
, {"Η", "Η"/* greek capital letter eta */, "\u0397"}
, {"Θ", "Θ"/* greek capital letter theta */, "\u0398"}
, {"Ι", "Ι"/* greek capital letter iota */, "\u0399"}
, {"Κ", "Κ"/* greek capital letter kappa */, "\u039A"}
, {"Λ", "Λ"/* greek capital letter lambda */, "\u039B"}
, {"Μ", "Μ"/* greek capital letter mu */, "\u039C"}
, {"Ν", "Ν"/* greek capital letter nu */, "\u039D"}
, {"Ξ", "Ξ"/* greek capital letter xi */, "\u039E"}
, {"Ο", "Ο"/* greek capital letter omicron */, "\u039F"}
, {"Π", "Π"/* greek capital letter pi */, "\u03A0"}
, {"Ρ", "Ρ"/* greek capital letter rho */, "\u03A1"}
/* there is no Sigmaf and no \u03A2 */
, {"Σ", "Σ"/* greek capital letter sigma */, "\u03A3"}
, {"Τ", "Τ"/* greek capital letter tau */, "\u03A4"}
, {"Υ", "Υ"/* greek capital letter upsilon */, "\u03A5"}
, {"Φ", "Φ"/* greek capital letter phi */, "\u03A6"}
, {"Χ", "Χ"/* greek capital letter chi */, "\u03A7"}
, {"Ψ", "Ψ"/* greek capital letter psi */, "\u03A8"}
, {"Ω", "Ω"/* greek capital letter omega */, "\u03A9"}
, {"α", "α"/* greek small letter alpha */, "\u03B1"}
, {"β", "β"/* greek small letter beta */, "\u03B2"}
, {"γ", "γ"/* greek small letter gamma */, "\u03B3"}
, {"δ", "δ"/* greek small letter delta */, "\u03B4"}
, {"ε", "ε"/* greek small letter epsilon */, "\u03B5"}
, {"ζ", "ζ"/* greek small letter zeta */, "\u03B6"}
, {"η", "η"/* greek small letter eta */, "\u03B7"}
, {"θ", "θ"/* greek small letter theta */, "\u03B8"}
, {"ι", "ι"/* greek small letter iota */, "\u03B9"}
, {"κ", "κ"/* greek small letter kappa */, "\u03BA"}
, {"λ", "λ"/* greek small letter lambda */, "\u03BB"}
, {"μ", "μ"/* greek small letter mu */, "\u03BC"}
, {"ν", "ν"/* greek small letter nu */, "\u03BD"}
, {"ξ", "ξ"/* greek small letter xi */, "\u03BE"}
, {"ο", "ο"/* greek small letter omicron */, "\u03BF"}
, {"π", "π"/* greek small letter pi */, "\u03C0"}
, {"ρ", "ρ"/* greek small letter rho */, "\u03C1"}
, {"ς", "ς"/* greek small letter final sigma */, "\u03C2"}
, {"σ", "σ"/* greek small letter sigma */, "\u03C3"}
, {"τ", "τ"/* greek small letter tau */, "\u03C4"}
, {"υ", "υ"/* greek small letter upsilon */, "\u03C5"}
, {"φ", "φ"/* greek small letter phi */, "\u03C6"}
, {"χ", "χ"/* greek small letter chi */, "\u03C7"}
, {"ψ", "ψ"/* greek small letter psi */, "\u03C8"}
, {"ω", "ω"/* greek small letter omega */, "\u03C9"}
, {"ϑ", "ϑ"/* greek small letter theta symbol */, "\u03D1"}
, {"ϒ", "ϒ"/* greek upsilon with hook symbol */, "\u03D2"}
, {"ϖ", "ϖ"/* greek pi symbol */, "\u03D6"}
/* General Punctuation */
, {"•", "•"/* bullet = black small circle */, "\u2022"}
/* bullet is NOT the same as bullet operator ,"\u2219*/
, {"…", "…"/* horizontal ellipsis = three dot leader */, "\u2026"}
, {"′", "′"/* prime = minutes = feet */, "\u2032"}
, {"″", "″"/* double prime = seconds = inches */, "\u2033"}
, {"‾", "‾"/* overline = spacing overscore */, "\u203E"}
, {"⁄", "⁄"/* fraction slash */, "\u2044"}
/* Letterlike Symbols */
, {"℘", "℘"/* script capital P = power set = Weierstrass p */, "\u2118"}
, {"ℑ", "ℑ"/* blackletter capital I = imaginary part */, "\u2111"}
, {"ℜ", "ℜ"/* blackletter capital R = real part symbol */, "\u211C"}
, {"™", "™"/* trade mark sign */, "\u2122"}
, {"ℵ", "ℵ"/* alef symbol = first transfinite cardinal */, "\u2135"}
/* alef symbol is NOT the same as hebrew letter alef ,"\u05D0"}*/
/* Arrows */
, {"←", "←"/* leftwards arrow */, "\u2190"}
, {"↑", "↑"/* upwards arrow */, "\u2191"}
, {"→", "→"/* rightwards arrow */, "\u2192"}
, {"↓", "↓"/* downwards arrow */, "\u2193"}
, {"↔", "↔"/* left right arrow */, "\u2194"}
, {"↵", "↵"/* downwards arrow with corner leftwards = carriage return */, "\u21B5"}
, {"⇐", "⇐"/* leftwards double arrow */, "\u21D0"}
/* Unicode does not say that lArr is the same as the 'is implied by' arrow but also does not have any other character for that function. So ? lArr can be used for 'is implied by' as ISOtech suggests */
, {"⇑", "⇑"/* upwards double arrow */, "\u21D1"}
, {"⇒", "⇒"/* rightwards double arrow */, "\u21D2"}
/* Unicode does not say this is the 'implies' character but does not have another character with this function so ? rArr can be used for 'implies' as ISOtech suggests */
, {"⇓", "⇓"/* downwards double arrow */, "\u21D3"}
, {"⇔", "⇔"/* left right double arrow */, "\u21D4"}
/* Mathematical Operators */
, {"∀", "∀"/* for all */, "\u2200"}
, {"∂", "∂"/* partial differential */, "\u2202"}
, {"∃", "∃"/* there exists */, "\u2203"}
, {"∅", "∅"/* empty set = null set = diameter */, "\u2205"}
, {"∇", "∇"/* nabla = backward difference */, "\u2207"}
, {"∈", "∈"/* element of */, "\u2208"}
, {"∉", "∉"/* not an element of */, "\u2209"}
, {"∋", "∋"/* contains as member */, "\u220B"}
/* should there be a more memorable name than 'ni'? */
, {"∏", "∏"/* n-ary product = product sign */, "\u220F"}
/* prod is NOT the same character as ,"\u03A0"}*/
, {"∑", "∑"/* n-ary sumation */, "\u2211"}
/* sum is NOT the same character as ,"\u03A3"}*/
, {"−", "−"/* minus sign */, "\u2212"}
, {"∗", "∗"/* asterisk operator */, "\u2217"}
, {"√", "√"/* square root = radical sign */, "\u221A"}
, {"∝", "∝"/* proportional to */, "\u221D"}
, {"∞", "∞"/* infinity */, "\u221E"}
, {"∠", "∠"/* angle */, "\u2220"}
, {"∧", "∧"/* logical and = wedge */, "\u2227"}
, {"∨", "∨"/* logical or = vee */, "\u2228"}
, {"∩", "∩"/* intersection = cap */, "\u2229"}
, {"∪", "∪"/* union = cup */, "\u222A"}
, {"∫", "∫"/* integral */, "\u222B"}
, {"∴", "∴"/* therefore */, "\u2234"}
, {"∼", "∼"/* tilde operator = varies with = similar to */, "\u223C"}
/* tilde operator is NOT the same character as the tilde ,"\u007E"}*/
, {"≅", "≅"/* approximately equal to */, "\u2245"}
, {"≈", "≈"/* almost equal to = asymptotic to */, "\u2248"}
, {"≠", "≠"/* not equal to */, "\u2260"}
, {"≡", "≡"/* identical to */, "\u2261"}
, {"≤", "≤"/* less-than or equal to */, "\u2264"}
, {"≥", "≥"/* greater-than or equal to */, "\u2265"}
, {"⊂", "⊂"/* subset of */, "\u2282"}
, {"⊃", "⊃"/* superset of */, "\u2283"}
/* note that nsup 'not a superset of ,"\u2283"}*/
, {"⊆", "⊆"/* subset of or equal to */, "\u2286"}
, {"⊇", "⊇"/* superset of or equal to */, "\u2287"}
, {"⊕", "⊕"/* circled plus = direct sum */, "\u2295"}
, {"⊗", "⊗"/* circled times = vector product */, "\u2297"}
, {"⊥", "⊥"/* up tack = orthogonal to = perpendicular */, "\u22A5"}
, {"⋅", "⋅"/* dot operator */, "\u22C5"}
/* dot operator is NOT the same character as ,"\u00B7"}
/* Miscellaneous Technical */
, {"⌈", "⌈"/* left ceiling = apl upstile */, "\u2308"}
, {"⌉", "⌉"/* right ceiling */, "\u2309"}
, {"⌊", "⌊"/* left floor = apl downstile */, "\u230A"}
, {"⌋", "⌋"/* right floor */, "\u230B"}
, {"⟨", "〈"/* left-pointing angle bracket = bra */, "\u2329"}
/* lang is NOT the same character as ,"\u003C"}*/
, {"⟩", "〉"/* right-pointing angle bracket = ket */, "\u232A"}
/* rang is NOT the same character as ,"\u003E"}*/
/* Geometric Shapes */
, {"◊", "◊"/* lozenge */, "\u25CA"}
/* Miscellaneous Symbols */
, {"♠", "♠"/* black spade suit */, "\u2660"}
/* black here seems to mean filled as opposed to hollow */
, {"♣", "♣"/* black club suit = shamrock */, "\u2663"}
, {"♥", "♥"/* black heart suit = valentine */, "\u2665"}
, {"♦", "♦"/* black diamond suit */, "\u2666"}
, {""", """ /* quotation mark = APL quote */, "\""}
, {"&", "&" /* ampersand */, "\u0026"}
, {"<", "<" /* less-than sign */, "\u003C"}
, {">", ">" /* greater-than sign */, "\u003E"}
/* Latin Extended-A */
, {"Œ", "Œ" /* latin capital ligature OE */, "\u0152"}
, {"œ", "œ" /* latin small ligature oe */, "\u0153"}
/* ligature is a misnomer this is a separate character in some languages */
, {"Š", "Š" /* latin capital letter S with caron */, "\u0160"}
, {"š", "š" /* latin small letter s with caron */, "\u0161"}
, {"Ÿ", "Ÿ" /* latin capital letter Y with diaeresis */, "\u0178"}
/* Spacing Modifier Letters */
, {"ˆ", "ˆ" /* modifier letter circumflex accent */, "\u02C6"}
, {"˜", "˜" /* small tilde */, "\u02DC"}
/* General Punctuation */
, {" ", " "/* en space */, "\u2002"}
, {" ", " "/* em space */, "\u2003"}
, {" ", " "/* thin space */, "\u2009"}
, {"‌", "‌"/* zero width non-joiner */, "\u200C"}
, {"‍", "‍"/* zero width joiner */, "\u200D"}
, {"‎", "‎"/* left-to-right mark */, "\u200E"}
, {"‏", "‏"/* right-to-left mark */, "\u200F"}
, {"–", "–"/* en dash */, "\u2013"}
, {"—", "—"/* em dash */, "\u2014"}
, {"‘", "‘"/* left single quotation mark */, "\u2018"}
, {"’", "’"/* right single quotation mark */, "\u2019"}
, {"‚", "‚"/* single low-9 quotation mark */, "\u201A"}
, {"“", "“"/* left double quotation mark */, "\u201C"}
, {"”", "”"/* right double quotation mark */, "\u201D"}
, {"„", "„"/* double low-9 quotation mark */, "\u201E"}
, {"†", "†"/* dagger */, "\u2020"}
, {"‡", "‡"/* double dagger */, "\u2021"}
, {"‰", "‰"/* per mille sign */, "\u2030"}
, {"‹", "‹"/* single left-pointing angle quotation mark */, "\u2039"}
/* lsaquo is proposed but not yet ISO standardized */
, {"›", "›"/* single right-pointing angle quotation mark */, "\u203A"}
/* rsaquo is proposed but not yet ISO standardized */
, {"€", "€" /* euro sign */, "\u20AC"}};
for (String[] entity : entities) {
entityEscapeMap.put(entity[2], entity[0]);
escapeEntityMap.put(entity[0], entity[2]);
escapeEntityMap.put(entity[1], entity[2]);
}
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/http/HTMLEntity.java | Java | asf20 | 26,524 |
package com.ch_linghu.fanfoudroid.http;
/**
* HTTP StatusCode is not 200
*/
public class HttpException extends Exception {
private int statusCode = -1;
public HttpException(String msg) {
super(msg);
}
public HttpException(Exception cause) {
super(cause);
}
public HttpException(String msg, int statusCode) {
super(msg);
this.statusCode = statusCode;
}
public HttpException(String msg, Exception cause) {
super(msg, cause);
}
public HttpException(String msg, Exception cause, int statusCode) {
super(msg, cause);
this.statusCode = statusCode;
}
public int getStatusCode() {
return this.statusCode;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/http/HttpException.java | Java | asf20 | 741 |
package com.ch_linghu.fanfoudroid.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.CharArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import android.util.Log;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
public class Response {
private final HttpResponse mResponse;
private boolean mStreamConsumed = false;
public Response(HttpResponse res) {
mResponse = res;
}
/**
* Convert Response to inputStream
*
* @return InputStream or null
* @throws ResponseException
*/
public InputStream asStream() throws ResponseException {
try {
final HttpEntity entity = mResponse.getEntity();
if (entity != null) {
return entity.getContent();
}
} catch (IllegalStateException e) {
throw new ResponseException(e.getMessage(), e);
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
return null;
}
/**
* @deprecated use entity.getContent();
* @param entity
* @return
* @throws ResponseException
*/
private InputStream asStream(HttpEntity entity) throws ResponseException {
if (null == entity) {
return null;
}
InputStream is = null;
try {
is = entity.getContent();
} catch (IllegalStateException e) {
throw new ResponseException(e.getMessage(), e);
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
//mResponse = null;
return is;
}
/**
* Convert Response to Context String
*
* @return response context string or null
* @throws ResponseException
*/
public String asString() throws ResponseException {
try {
return entityToString(mResponse.getEntity());
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
}
/**
* EntityUtils.toString(entity, "UTF-8");
*
* @param entity
* @return
* @throws IOException
* @throws ResponseException
*/
private String entityToString(final HttpEntity entity) throws IOException, ResponseException {
DebugTimer.betweenStart("AS STRING");
if (null == entity) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
//InputStream instream = asStream(entity);
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int) entity.getContentLength();
if (i < 0) {
i = 4096;
}
Log.i("LDS", i + " content length");
Reader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
CharArrayBuffer buffer = new CharArrayBuffer(i);
try {
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
} finally {
reader.close();
}
DebugTimer.betweenEnd("AS STRING");
return buffer.toString();
}
/**
* @deprecated use entityToString()
* @param in
* @return
* @throws ResponseException
*/
private String inputStreamToString(final InputStream in) throws IOException {
if (null == in) {
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuffer buf = new StringBuffer();
try {
char[] buffer = new char[1024];
while ((reader.read(buffer)) != -1) {
buf.append(buffer);
}
return buf.toString();
} finally {
if (reader != null) {
reader.close();
setStreamConsumed(true);
}
}
}
public JSONObject asJSONObject() throws ResponseException {
try {
return new JSONObject(asString());
} catch (JSONException jsone) {
throw new ResponseException(jsone.getMessage() + ":"
+ asString(), jsone);
}
}
public JSONArray asJSONArray() throws ResponseException {
try {
return new JSONArray(asString());
} catch (Exception jsone) {
throw new ResponseException(jsone.getMessage(), jsone);
}
}
private void setStreamConsumed(boolean mStreamConsumed) {
this.mStreamConsumed = mStreamConsumed;
}
public boolean isStreamConsumed() {
return mStreamConsumed;
}
/**
* @deprecated
* @return
*/
public Document asDocument() {
// TODO Auto-generated method stub
return null;
}
private static Pattern escaped = Pattern.compile("&#([0-9]{3,5});");
/**
* Unescape UTF-8 escaped characters to string.
* @author pengjianq...@gmail.com
*
* @param original The string to be unescaped.
* @return The unescaped string
*/
public static String unescape(String original) {
Matcher mm = escaped.matcher(original);
StringBuffer unescaped = new StringBuffer();
while (mm.find()) {
mm.appendReplacement(unescaped, Character.toString(
(char) Integer.parseInt(mm.group(1), 10)));
}
mm.appendTail(unescaped);
return unescaped.toString();
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/http/Response.java | Java | asf20 | 6,106 |
package com.ch_linghu.fanfoudroid.http;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpVersion;
import org.apache.http.NoHttpResponseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.fanfou.Configuration;
import com.ch_linghu.fanfoudroid.fanfou.RefuseError;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
/**
* Wrap of org.apache.http.impl.client.DefaultHttpClient
*
* @author lds
*
*/
public class HttpClient {
private static final String TAG = "HttpClient";
private final static boolean DEBUG = Configuration.getDebug();
/** OK: Success! */
public static final int OK = 200;
/** Not Modified: There was no new data to return. */
public static final int NOT_MODIFIED = 304;
/** Bad Request: The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting. */
public static final int BAD_REQUEST = 400;
/** Not Authorized: Authentication credentials were missing or incorrect. */
public static final int NOT_AUTHORIZED = 401;
/** Forbidden: The request is understood, but it has been refused. An accompanying error message will explain why. */
public static final int FORBIDDEN = 403;
/** Not Found: The URI requested is invalid or the resource requested, such as a user, does not exists. */
public static final int NOT_FOUND = 404;
/** Not Acceptable: Returned by the Search API when an invalid format is specified in the request. */
public static final int NOT_ACCEPTABLE = 406;
/** Internal Server Error: Something is broken. Please post to the group so the Weibo team can investigate. */
public static final int INTERNAL_SERVER_ERROR = 500;
/** Bad Gateway: Weibo is down or being upgraded. */
public static final int BAD_GATEWAY = 502;
/** Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited. */
public static final int SERVICE_UNAVAILABLE = 503;
private static final int CONNECTION_TIMEOUT_MS = 30 * 1000;
private static final int SOCKET_TIMEOUT_MS = 30 * 1000;
public static final int RETRIEVE_LIMIT = 20;
public static final int RETRIED_TIME = 3;
private static final String SERVER_HOST = "api.fanfou.com";
private DefaultHttpClient mClient;
private AuthScope mAuthScope;
private BasicHttpContext localcontext;
private String mUserId;
private String mPassword;
private static boolean isAuthenticationEnabled = false;
public HttpClient() {
prepareHttpClient();
}
/**
* @param user_id auth user
* @param password auth password
*/
public HttpClient(String user_id, String password) {
prepareHttpClient();
setCredentials(user_id, password);
}
/**
* Empty the credentials
*/
public void reset() {
setCredentials("", "");
}
/**
* @return authed user id
*/
public String getUserId() {
return mUserId;
}
/**
* @return authed user password
*/
public String getPassword() {
return mPassword;
}
/**
* @param hostname the hostname (IP or DNS name)
* @param port the port number. -1 indicates the scheme default port.
* @param scheme the name of the scheme. null indicates the default scheme
*/
public void setProxy(String host, int port, String scheme) {
HttpHost proxy = new HttpHost(host, port, scheme);
mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
public void removeProxy() {
mClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY);
}
private void enableDebug() {
Log.d(TAG, "enable apache.http debug");
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.FINEST);
java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(java.util.logging.Level.FINER);
java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(java.util.logging.Level.OFF);
/*
System.setProperty("log.tag.org.apache.http", "VERBOSE");
System.setProperty("log.tag.org.apache.http.wire", "VERBOSE");
System.setProperty("log.tag.org.apache.http.headers", "VERBOSE");
在这里使用System.setProperty设置不会生效, 原因不明, 必须在终端上输入以下命令方能开启http调试信息:
> adb shell setprop log.tag.org.apache.http VERBOSE
> adb shell setprop log.tag.org.apache.http.wire VERBOSE
> adb shell setprop log.tag.org.apache.http.headers VERBOSE
*/
}
/**
* Setup DefaultHttpClient
*
* Use ThreadSafeClientConnManager.
*
*/
private void prepareHttpClient() {
if (DEBUG) {
enableDebug();
}
// Create and initialize HTTP parameters
HttpParams params = new BasicHttpParams();
ConnManagerParams.setMaxTotalConnections(params, 10);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// Create an HttpClient with the ThreadSafeClientConnManager.
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params,
schemeRegistry);
mClient = new DefaultHttpClient(cm, params);
// Setup BasicAuth
BasicScheme basicScheme = new BasicScheme();
mAuthScope = new AuthScope(SERVER_HOST, AuthScope.ANY_PORT);
// mClient.setAuthSchemes(authRegistry);
mClient.setCredentialsProvider(new BasicCredentialsProvider());
// Generate BASIC scheme object and stick it to the local
// execution context
localcontext = new BasicHttpContext();
localcontext.setAttribute("preemptive-auth", basicScheme);
// first request interceptor
mClient.addRequestInterceptor(preemptiveAuth, 0);
// Support GZIP
mClient.addResponseInterceptor(gzipResponseIntercepter);
// TODO: need to release this connection in httpRequest()
// cm.releaseConnection(conn, validDuration, timeUnit);
//httpclient.getConnectionManager().shutdown();
}
/**
* HttpRequestInterceptor for DefaultHttpClient
*/
private static HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
@Override
public void process(final HttpRequest request, final HttpContext context) {
AuthState authState = (AuthState) context
.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(),
targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
private static HttpResponseInterceptor gzipResponseIntercepter =
new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext context)
throws org.apache.http.HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
};
static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent()
throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
// length of ungzipped content is not known
return -1;
}
}
/**
* Setup Credentials for HTTP Basic Auth
*
* @param username
* @param password
*/
public void setCredentials(String username, String password) {
mUserId = username;
mPassword = password;
mClient.getCredentialsProvider().setCredentials(mAuthScope,
new UsernamePasswordCredentials(username, password));
isAuthenticationEnabled = true;
}
public Response post(String url, ArrayList<BasicNameValuePair> postParams,
boolean authenticated) throws HttpException {
if (null == postParams) {
postParams = new ArrayList<BasicNameValuePair>();
}
return httpRequest(url, postParams, authenticated, HttpPost.METHOD_NAME);
}
public Response post(String url, ArrayList<BasicNameValuePair> params)
throws HttpException {
return httpRequest(url, params, false, HttpPost.METHOD_NAME);
}
public Response post(String url, boolean authenticated)
throws HttpException {
return httpRequest(url, null, authenticated, HttpPost.METHOD_NAME);
}
public Response post(String url) throws HttpException {
return httpRequest(url, null, false, HttpPost.METHOD_NAME);
}
public Response post(String url, File file) throws HttpException {
return httpRequest(url, null, file, false, HttpPost.METHOD_NAME);
}
/**
* POST一个文件
*
* @param url
* @param file
* @param authenticate
* @return
* @throws HttpException
*/
public Response post(String url, File file, boolean authenticate)
throws HttpException {
return httpRequest(url, null, file, authenticate, HttpPost.METHOD_NAME);
}
public Response get(String url, ArrayList<BasicNameValuePair> params,
boolean authenticated) throws HttpException {
return httpRequest(url, params, authenticated, HttpGet.METHOD_NAME);
}
public Response get(String url, ArrayList<BasicNameValuePair> params)
throws HttpException {
return httpRequest(url, params, false, HttpGet.METHOD_NAME);
}
public Response get(String url) throws HttpException {
return httpRequest(url, null, false, HttpGet.METHOD_NAME);
}
public Response get(String url, boolean authenticated)
throws HttpException {
return httpRequest(url, null, authenticated, HttpGet.METHOD_NAME);
}
public Response httpRequest(String url,
ArrayList<BasicNameValuePair> postParams, boolean authenticated,
String httpMethod) throws HttpException {
return httpRequest(url, postParams, null, authenticated, httpMethod);
}
/**
* Execute the DefaultHttpClient
*
* @param url
* target
* @param postParams
* @param file
* can be NULL
* @param authenticated
* need or not
* @param httpMethod
* HttpPost.METHOD_NAME
* HttpGet.METHOD_NAME
* HttpDelete.METHOD_NAME
* @return Response from server
* @throws HttpException 此异常包装了一系列底层异常 <br /><br />
* 1. 底层异常, 可使用getCause()查看: <br />
* <li>URISyntaxException, 由`new URI` 引发的.</li>
* <li>IOException, 由`createMultipartEntity` 或 `UrlEncodedFormEntity` 引发的.</li>
* <li>IOException和ClientProtocolException, 由`HttpClient.execute` 引发的.</li><br />
*
* 2. 当响应码不为200时报出的各种子类异常:
* <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常,
* 首先检查request log, 确认不是人为错误导致请求失败</li>
* <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li>
* <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因
* 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li>
* <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li>
* <li>HttpException, 其他未知错误.</li>
*/
public Response httpRequest(String url, ArrayList<BasicNameValuePair> postParams,
File file, boolean authenticated, String httpMethod) throws HttpException {
Log.d(TAG, "Sending " + httpMethod + " request to " + url);
if (TwitterApplication.DEBUG){
DebugTimer.betweenStart("HTTP");
}
URI uri = createURI(url);
HttpResponse response = null;
Response res = null;
HttpUriRequest method = null;
// Create POST, GET or DELETE METHOD
method = createMethod(httpMethod, uri, file, postParams);
// Setup ConnectionParams, Request Headers
SetupHTTPConnectionParams(method);
// Execute Request
try {
response = mClient.execute(method, localcontext);
res = new Response(response);
} catch (ClientProtocolException e) {
Log.e(TAG, e.getMessage(), e);
throw new HttpException(e.getMessage(), e);
} catch (IOException ioe) {
throw new HttpException(ioe.getMessage(), ioe);
}
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
// It will throw a weiboException while status code is not 200
HandleResponseStatusCode(statusCode, res);
} else {
Log.e(TAG, "response is null");
}
if (TwitterApplication.DEBUG){
DebugTimer.betweenEnd("HTTP");
}
return res;
}
/**
* CreateURI from URL string
*
* @param url
* @return request URI
* @throws HttpException
* Cause by URISyntaxException
*/
private URI createURI(String url) throws HttpException {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
Log.e(TAG, e.getMessage(), e);
throw new HttpException("Invalid URL.");
}
return uri;
}
/**
* 创建可带一个File的MultipartEntity
*
* @param filename
* 文件名
* @param file
* 文件
* @param postParams
* 其他POST参数
* @return 带文件和其他参数的Entity
* @throws UnsupportedEncodingException
*/
private MultipartEntity createMultipartEntity(String filename, File file,
ArrayList<BasicNameValuePair> postParams)
throws UnsupportedEncodingException {
MultipartEntity entity = new MultipartEntity();
// Don't try this. Server does not appear to support chunking.
// entity.addPart("media", new InputStreamBody(imageStream, "media"));
entity.addPart(filename, new FileBody(file));
for (BasicNameValuePair param : postParams) {
entity.addPart(param.getName(), new StringBody(param.getValue()));
}
return entity;
}
/**
* Setup HTTPConncetionParams
*
* @param method
*/
private void SetupHTTPConnectionParams(HttpUriRequest method) {
HttpConnectionParams.setConnectionTimeout(method.getParams(),
CONNECTION_TIMEOUT_MS);
HttpConnectionParams
.setSoTimeout(method.getParams(), SOCKET_TIMEOUT_MS);
mClient.setHttpRequestRetryHandler(requestRetryHandler);
method.addHeader("Accept-Encoding", "gzip, deflate");
method.addHeader("Accept-Charset", "UTF-8,*;q=0.5");
}
/**
* Create request method, such as POST, GET, DELETE
*
* @param httpMethod
* "GET","POST","DELETE"
* @param uri
* 请求的URI
* @param file
* 可为null
* @param postParams
* POST参数
* @return httpMethod Request implementations for the various HTTP methods
* like GET and POST.
* @throws HttpException
* createMultipartEntity 或 UrlEncodedFormEntity引发的IOException
*/
private HttpUriRequest createMethod(String httpMethod, URI uri, File file,
ArrayList<BasicNameValuePair> postParams) throws HttpException {
HttpUriRequest method;
if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
// POST METHOD
HttpPost post = new HttpPost(uri);
// See this: http://groups.google.com/group/twitter-development-talk/browse_thread/thread/e178b1d3d63d8e3b
post.getParams().setBooleanParameter("http.protocol.expect-continue", false);
try {
HttpEntity entity = null;
if (null != file) {
entity = createMultipartEntity("photo", file, postParams);
post.setEntity(entity);
} else if (null != postParams) {
entity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8);
}
post.setEntity(entity);
} catch (IOException ioe) {
throw new HttpException(ioe.getMessage(), ioe);
}
method = post;
} else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
method = new HttpDelete(uri);
} else {
method = new HttpGet(uri);
}
return method;
}
/**
* 解析HTTP错误码
*
* @param statusCode
* @return
*/
private static String getCause(int statusCode) {
String cause = null;
switch (statusCode) {
case NOT_MODIFIED:
break;
case BAD_REQUEST:
cause = "The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting.";
break;
case NOT_AUTHORIZED:
cause = "Authentication credentials were missing or incorrect.";
break;
case FORBIDDEN:
cause = "The request is understood, but it has been refused. An accompanying error message will explain why.";
break;
case NOT_FOUND:
cause = "The URI requested is invalid or the resource requested, such as a user, does not exists.";
break;
case NOT_ACCEPTABLE:
cause = "Returned by the Search API when an invalid format is specified in the request.";
break;
case INTERNAL_SERVER_ERROR:
cause = "Something is broken. Please post to the group so the Weibo team can investigate.";
break;
case BAD_GATEWAY:
cause = "Weibo is down or being upgraded.";
break;
case SERVICE_UNAVAILABLE:
cause = "Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited.";
break;
default:
cause = "";
}
return statusCode + ":" + cause;
}
public boolean isAuthenticationEnabled() {
return isAuthenticationEnabled;
}
public static void log(String msg) {
if (DEBUG) {
Log.d(TAG, msg);
}
}
/**
* Handle Status code
*
* @param statusCode
* 响应的状态码
* @param res
* 服务器响应
* @throws HttpException
* 当响应码不为200时都会报出此异常:<br />
* <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常,
* 首先检查request log, 确认不是人为错误导致请求失败</li>
* <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li>
* <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因
* 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li>
* <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li>
* <li>HttpException, 其他未知错误.</li>
*/
private void HandleResponseStatusCode(int statusCode, Response res)
throws HttpException {
String msg = getCause(statusCode) + "\n";
RefuseError error = null;
switch (statusCode) {
// It's OK, do nothing
case OK:
break;
// Mine mistake, Check the Log
case NOT_MODIFIED:
case BAD_REQUEST:
case NOT_FOUND:
case NOT_ACCEPTABLE:
throw new HttpException(msg + res.asString(), statusCode);
// UserName/Password incorrect
case NOT_AUTHORIZED:
throw new HttpAuthException(msg + res.asString(), statusCode);
// Server will return a error message, use
// HttpRefusedException#getError() to see.
case FORBIDDEN:
throw new HttpRefusedException(msg, statusCode);
// Something wrong with server
case INTERNAL_SERVER_ERROR:
case BAD_GATEWAY:
case SERVICE_UNAVAILABLE:
throw new HttpServerException(msg, statusCode);
// Others
default:
throw new HttpException(msg + res.asString(), statusCode);
}
}
public static String encode(String value) throws HttpException {
try {
return URLEncoder.encode(value, HTTP.UTF_8);
} catch (UnsupportedEncodingException e_e) {
throw new HttpException(e_e.getMessage(), e_e);
}
}
public static String encodeParameters(ArrayList<BasicNameValuePair> params)
throws HttpException {
StringBuffer buf = new StringBuffer();
for (int j = 0; j < params.size(); j++) {
if (j != 0) {
buf.append("&");
}
try {
buf.append(URLEncoder.encode(params.get(j).getName(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(params.get(j).getValue(),
"UTF-8"));
} catch (java.io.UnsupportedEncodingException neverHappen) {
throw new HttpException(neverHappen.getMessage(), neverHappen);
}
}
return buf.toString();
}
/**
* 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复
*/
private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
// 自定义的恢复策略
public boolean retryRequest(IOException exception, int executionCount,
HttpContext context) {
// 设置恢复策略,在发生异常时候将自动重试N次
if (executionCount >= RETRIED_TIME) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
}
if (exception instanceof SSLHandshakeException) {
// Do not retry on SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context
.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
if (!idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}
};
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/http/HttpClient.java | Java | asf20 | 28,093 |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.IDs;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.FlingGestureListener;
import com.ch_linghu.fanfoudroid.ui.module.MyActivityFlipper;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.TweetCursorAdapter;
import com.ch_linghu.fanfoudroid.ui.module.Widget;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
import com.hlidskialf.android.hardware.ShakeListener;
/**
* TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现
*/
public abstract class TwitterCursorBaseActivity extends TwitterListBaseActivity {
static final String TAG = "TwitterCursorBaseActivity";
// Views.
protected ListView mTweetList;
protected TweetCursorAdapter mTweetAdapter;
protected View mListHeader;
protected View mListFooter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
protected static int lastPosition = 0;
protected ShakeListener mShaker = null;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;
private int mRetrieveCount = 0;
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
mFeedback.failed("登录信息出错");
logout();
} else if (result == TaskResult.OK) {
// TODO: XML处理, GC压力
SharedPreferences.Editor editor = getPreferences().edit();
editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
// TODO: 1. StatusType(DONE) ;
if (mRetrieveCount >= StatusTable.MAX_ROW_NUM) {
// 只有在取回的数据大于MAX时才做GC, 因为小于时可以保证数据的连续性
getDb().gc(getUserId(), getDatabaseType()); // GC
}
draw();
if (task == mRetrieveTask) {
goTop();
}
} else if (result == TaskResult.IO_ERROR) {
// FIXME: bad smell
if (task == mRetrieveTask) {
mFeedback.failed(((RetrieveTask) task).getErrorMsg());
} else if (task == mGetMoreTask) {
mFeedback.failed(((GetMoreTask) task).getErrorMsg());
}
} else {
// do nothing
}
// 刷新按钮停止旋转
loadMoreGIFTop.setVisibility(View.GONE);
loadMoreGIF.setVisibility(View.GONE);
// DEBUG
if (TwitterApplication.DEBUG) {
DebugTimer.stop();
Log.v("DEBUG", DebugTimer.getProfileAsString());
}
}
@Override
public void onPreExecute(GenericTask task) {
mRetrieveCount = 0;
if (TwitterApplication.DEBUG) {
DebugTimer.start();
}
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FollowerRetrieve";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences sp = getPreferences();
SharedPreferences.Editor editor = sp.edit();
editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
} else {
// Do nothing.
}
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
// Refresh followers if last refresh was this long ago or greater.
private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000;
abstract protected void markAllRead();
abstract protected Cursor fetchMessages();
public abstract int getDatabaseType();
public abstract String getUserId();
public abstract String fetchMaxId();
public abstract String fetchMinId();
public abstract int addMessages(ArrayList<Tweet> tweets, boolean isUnread);
public abstract List<Status> getMessageSinceId(String maxId)
throws HttpException;
public abstract List<Status> getMoreMessageFromId(String minId)
throws HttpException;
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
@Override
protected void setupState() {
Cursor cursor;
cursor = fetchMessages(); // getDb().fetchMentions();
setTitle(getActivityTitle());
startManagingCursor(cursor);
mTweetList = (ListView) findViewById(R.id.tweet_list);
// TODO: 需处理没有数据时的情况
Log.d("LDS", cursor.getCount() + " cursor count");
setupListHeader(true);
mTweetAdapter = new TweetCursorAdapter(this, cursor);
mTweetList.setAdapter(mTweetAdapter);
// ? registerOnClickListener(mTweetList);
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add Header to ListView
mListHeader = View.inflate(this, R.layout.listview_header, null);
mTweetList.addHeaderView(mListHeader, null, true);
// Add Footer to ListView
mListFooter = View.inflate(this, R.layout.listview_footer, null);
mTweetList.addFooterView(mListFooter, null, true);
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
loadMoreBtnTop = (TextView) findViewById(R.id.ask_for_more_header);
loadMoreGIFTop = (ProgressBar) findViewById(R.id.rectangleProgressBar_header);
}
@Override
protected void specialItemClicked(int position) {
// 注意 mTweetAdapter.getCount 和 mTweetList.getCount的区别
// 前者仅包含数据的数量(不包括foot和head),后者包含foot和head
// 因此在同时存在foot和head的情况下,list.count = adapter.count + 2
if (position == 0) {
// 第一个Item(header)
loadMoreGIFTop.setVisibility(View.VISIBLE);
doRetrieve();
} else if (position == mTweetList.getCount() - 1) {
// 最后一个Item(footer)
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
@Override
protected int getLayoutId() {
return R.layout.main;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected TweetAdapter getTweetAdapter() {
return mTweetAdapter;
}
@Override
protected boolean useBasicMenu() {
return true;
}
@Override
protected Tweet getContextItemTweet(int position) {
position = position - 1;
// 因为List加了Header和footer,所以要跳过第一个以及忽略最后一个
if (position >= 0 && position < mTweetAdapter.getCount()) {
Cursor cursor = (Cursor) mTweetAdapter.getItem(position);
if (cursor == null) {
return null;
} else {
return StatusTable.parseCursor(cursor);
}
} else {
return null;
}
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO: updateTweet() 在哪里调用的? 目前尚只支持:
// updateTweet(String tweetId, ContentValues values)
// setFavorited(String tweetId, String isFavorited)
// 看是否还需要增加updateTweet(Tweet tweet)方法
// 对所有相关表的对应消息都进行刷新(如果存在的话)
// getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet);
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
goTop(); // skip the header
// Mark all as read.
// getDb().markAllMentionsRead();
markAllRead();
boolean shouldRetrieve = false;
// FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_TWEET_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
if (diff > REFRESH_THRESHOLD) {
shouldRetrieve = true;
} else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) {
// Check to see if it was running a send or retrieve task.
// It makes no sense to resend the send request (don't want
// dupes)
// so we instead retrieve (refresh) to see if the message has
// posted.
Log.d(TAG,
"Was last running a retrieve or send task. Let's refresh.");
shouldRetrieve = true;
}
if (shouldRetrieve) {
doRetrieve();
}
long lastFollowersRefreshTime = mPreferences.getLong(
Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0);
diff = nowTime - lastFollowersRefreshTime;
Log.d(TAG, "Last followers refresh was " + diff + " ms ago.");
// FIXME: 目前还没有对Followers列表做逻辑处理,因此暂时去除对Followers的获取。
// 未来需要实现@用户提示时,对Follower操作需要做一次review和refactoring
// 现在频繁会出现主键冲突的问题。
//
// Should Refresh Followers
// if (diff > FOLLOWERS_REFRESH_THRESHOLD
// && (mRetrieveTask == null || mRetrieveTask.getStatus() !=
// GenericTask.Status.RUNNING)) {
// Log.d(TAG, "Refresh followers.");
// doRetrieveFollowers();
// }
// 手势识别
registerGestureListener();
//晃动刷新
registerShakeListener();
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
Log.d(TAG, "onResume.");
if (lastPosition != 0) {
mTweetList.setSelection(lastPosition);
}
if (mShaker != null){
mShaker.resume();
}
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
// mTweetEdit.updateCharsRemain();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
super.onDestroy();
taskManager.cancelAll();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause.");
if (mShaker != null){
mShaker.pause();
}
super.onPause();
lastPosition = mTweetList.getFirstVisiblePosition();
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart.");
super.onRestart();
}
@Override
protected void onStart() {
Log.d(TAG, "onStart.");
super.onStart();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop.");
super.onStop();
}
// UI helpers.
@Override
protected String getActivityTitle() {
return null;
}
@Override
protected void adapterRefresh() {
mTweetAdapter.notifyDataSetChanged();
mTweetAdapter.refresh();
}
// Retrieve interface
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void draw() {
mTweetAdapter.refresh();
}
public void goTop() {
Log.d(TAG, "goTop.");
mTweetList.setSelection(1);
}
private void doRetrieveFollowers() {
Log.d(TAG, "Attempting followers retrieve.");
if (mFollowersRetrieveTask != null
&& mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFollowersRetrieveTask = new FollowersRetrieveTask();
mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener);
mFollowersRetrieveTask.execute();
taskManager.addTask(mFollowersRetrieveTask);
// Don't need to cancel FollowersTask (assuming it ends properly).
mFollowersRetrieveTask.setCancelable(false);
}
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
private class RetrieveTask extends GenericTask {
private String _errorMsg;
public String getErrorMsg() {
return _errorMsg;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
String maxId = fetchMaxId(); // getDb().fetchMaxMentionId();
statusList = getMessageSinceId(maxId);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
_errorMsg = e.getMessage();
return TaskResult.IO_ERROR;
}
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
tweets.add(Tweet.create(status));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets));
mRetrieveCount = addMessages(tweets, false);
return TaskResult.OK;
}
}
private class FollowersRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
// TODO: 目前仅做新API兼容性改动,待完善Follower处理
IDs followers = getApi().getFollowersIDs();
List<String> followerIds = Arrays.asList(followers.getIDs());
getDb().syncFollowers(followerIds);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
// GET MORE TASK
private class GetMoreTask extends GenericTask {
private String _errorMsg;
public String getErrorMsg() {
return _errorMsg;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
String minId = fetchMinId(); // getDb().fetchMaxMentionId();
if (minId == null) {
return TaskResult.FAILED;
}
try {
statusList = getMoreMessageFromId(minId);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
_errorMsg = e.getMessage();
return TaskResult.IO_ERROR;
}
if (statusList == null) {
return TaskResult.FAILED;
}
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets));
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
tweets.add(Tweet.create(status));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addMessages(tweets, false); // getDb().addMentions(tweets, false);
return TaskResult.OK;
}
}
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setFeedback(mFeedback);
mGetMoreTask.setListener(mRetrieveTaskListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
//////////////////// Gesture test /////////////////////////////////////
private static boolean useGestrue;
{
useGestrue = TwitterApplication.mPref.getBoolean(
Preferences.USE_GESTRUE, false);
if (useGestrue) {
Log.v(TAG, "Using Gestrue!");
} else {
Log.v(TAG, "Not Using Gestrue!");
}
}
//////////////////// Gesture test /////////////////////////////////////
private static boolean useShake;
{
useShake = TwitterApplication.mPref.getBoolean(
Preferences.USE_SHAKE, false);
if (useShake) {
Log.v(TAG, "Using Shake to refresh!");
} else {
Log.v(TAG, "Not Using Shake!");
}
}
protected FlingGestureListener myGestureListener = null;
@Override
public boolean onTouchEvent(MotionEvent event) {
if (useGestrue && myGestureListener != null) {
return myGestureListener.getDetector().onTouchEvent(event);
}
return super.onTouchEvent(event);
}
// use it in _onCreate
private void registerGestureListener() {
if (useGestrue) {
myGestureListener = new FlingGestureListener(this,
MyActivityFlipper.create(this));
getTweetList().setOnTouchListener(myGestureListener);
}
}
// use it in _onCreate
private void registerShakeListener() {
if (useShake){
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener() {
@Override
public void onShake() {
doRetrieve();
}
});
}
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/base/TwitterCursorBaseActivity.java | Java | asf20 | 22,549 |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.List;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.UserCursorAdapter;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
/**
* TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现
*/
public abstract class UserCursorBaseActivity extends UserListBaseActivity {
/**
* 第一种方案:(采取第一种) 暂不放在数据库中,直接从Api读取。
*
* 第二种方案: 麻烦的是api数据与数据库同步,当收听人数比较多的时候,一次性读取太费流量 按照饭否api每次分页100人
* 当收听数<100时先从数据库一次性根据API返回的ID列表读取数据,如果数据库中的收听数<总数,那么从API中读取所有用户信息并同步到数据库中。
* 当收听数>100时采取分页加载,先按照id
* 获取数据库里前100用户,如果用户数量<100则从api中加载,从page=1开始下载,同步到数据库中,单击更多继续从数据库中加载
* 当数据库中的数据读取到最后一页后,则从api中加载并更新到数据库中。 单击刷新按钮则从api加载并同步到数据库中
*
*/
static final String TAG = "UserCursorBaseActivity";
// Views.
protected ListView mUserList;
protected UserCursorAdapter mUserListAdapter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
protected static int lastPosition = 0;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;// 每次十个用户
protected abstract String getUserId();// 获得用户id
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
SharedPreferences.Editor editor = getPreferences().edit();
editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
// TODO: 1. StatusType(DONE) ; 2. 只有在取回的数据大于MAX时才做GC,
// 因为小于时可以保证数据的连续性
// FIXME: gc需要带owner
// getDb().gc(getDatabaseType()); // GC
draw();
goTop();
} else {
// Do nothing.
}
// loadMoreGIFTop.setVisibility(View.GONE);
updateProgress("");
}
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FollowerRetrieve";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences sp = getPreferences();
SharedPreferences.Editor editor = sp.edit();
editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
} else {
// Do nothing.
}
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
// Refresh followers if last refresh was this long ago or greater.
private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000;
abstract protected Cursor fetchUsers();
public abstract int getDatabaseType();
public abstract String fetchMaxId();
public abstract String fetchMinId();
public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers()
throws HttpException;
public abstract void addUsers(
ArrayList<com.ch_linghu.fanfoudroid.data.User> tusers);
// public abstract List<Status> getMessageSinceId(String maxId)
// throws WeiboException;
public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUserSinceId(
String maxId) throws HttpException;
public abstract List<Status> getMoreMessageFromId(String minId)
throws HttpException;
public abstract Paging getNextPage();// 下一页数
public abstract Paging getCurrentPage();// 当前页数
protected abstract String[] getIds();
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
@Override
protected void setupState() {
Cursor cursor;
cursor = fetchUsers(); //
setTitle(getActivityTitle());
startManagingCursor(cursor);
mUserList = (ListView) findViewById(R.id.follower_list);
// TODO: 需处理没有数据时的情况
Log.d("LDS", cursor.getCount() + " cursor count");
setupListHeader(true);
mUserListAdapter = new UserCursorAdapter(this, cursor);
mUserList.setAdapter(mUserListAdapter);
// ? registerOnClickListener(mTweetList);
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add footer to Listview
View footer = View.inflate(this, R.layout.listview_footer, null);
mUserList.addFooterView(footer, null, true);
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
// loadMoreBtnTop = (TextView)findViewById(R.id.ask_for_more_header);
// loadMoreGIFTop =
// (ProgressBar)findViewById(R.id.rectangleProgressBar_header);
// loadMoreAnimation = (AnimationDrawable)
// loadMoreGIF.getIndeterminateDrawable();
}
@Override
protected void specialItemClicked(int position) {
if (position == mUserList.getCount() - 1) {
// footer
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
@Override
protected int getLayoutId() {
return R.layout.follower;
}
@Override
protected ListView getUserList() {
return mUserList;
}
@Override
protected TweetAdapter getUserAdapter() {
return mUserListAdapter;
}
@Override
protected boolean useBasicMenu() {
return true;
}
protected User getContextItemUser(int position) {
// position = position - 1;
// 加入footer跳过footer
if (position < mUserListAdapter.getCount()) {
Cursor cursor = (Cursor) mUserListAdapter.getItem(position);
if (cursor == null) {
return null;
} else {
return UserInfoTable.parseCursor(cursor);
}
} else {
return null;
}
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO: updateTweet() 在哪里调用的? 目前尚只支持:
// updateTweet(String tweetId, ContentValues values)
// setFavorited(String tweetId, String isFavorited)
// 看是否还需要增加updateTweet(Tweet tweet)方法
// 对所有相关表的对应消息都进行刷新(如果存在的话)
// getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet);
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
goTop(); // skip the header
boolean shouldRetrieve = false;
// FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_TWEET_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
/*
* if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if
* (Utils.isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to
* see if it was running a send or retrieve task. // It makes no
* sense to resend the send request (don't want dupes) // so we
* instead retrieve (refresh) to see if the message has // posted.
* Log.d(TAG,
* "Was last running a retrieve or send task. Let's refresh.");
* shouldRetrieve = true; }
*/
shouldRetrieve = true;
if (shouldRetrieve) {
doRetrieve();
}
long lastFollowersRefreshTime = mPreferences.getLong(
Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0);
diff = nowTime - lastFollowersRefreshTime;
Log.d(TAG, "Last followers refresh was " + diff + " ms ago.");
/*
* if (diff > FOLLOWERS_REFRESH_THRESHOLD && (mRetrieveTask == null
* || mRetrieveTask.getStatus() != GenericTask.Status.RUNNING)) {
* Log.d(TAG, "Refresh followers."); doRetrieveFollowers(); }
*/
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
Log.d(TAG, "onResume.");
if (lastPosition != 0) {
mUserList.setSelection(lastPosition);
}
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
// mTweetEdit.updateCharsRemain();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
super.onDestroy();
taskManager.cancelAll();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause.");
super.onPause();
lastPosition = mUserList.getFirstVisiblePosition();
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart.");
super.onRestart();
}
@Override
protected void onStart() {
Log.d(TAG, "onStart.");
super.onStart();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop.");
super.onStop();
}
// UI helpers.
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
return null;
}
@Override
protected void adapterRefresh() {
mUserListAdapter.notifyDataSetChanged();
mUserListAdapter.refresh();
}
// Retrieve interface
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void draw() {
mUserListAdapter.refresh();
}
public void goTop() {
Log.d(TAG, "goTop.");
mUserList.setSelection(1);
}
private void doRetrieveFollowers() {
Log.d(TAG, "Attempting followers retrieve.");
if (mFollowersRetrieveTask != null
&& mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFollowersRetrieveTask = new FollowersRetrieveTask();
mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener);
mFollowersRetrieveTask.execute();
taskManager.addTask(mFollowersRetrieveTask);
// Don't need to cancel FollowersTask (assuming it ends properly).
mFollowersRetrieveTask.setCancelable(false);
}
}
public void onRetrieveBegin() {
updateProgress(getString(R.string.page_status_refreshing));
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
/**
* TODO:从API获取当前Followers,并同步到数据库
*
* @author Dino
*
*/
private class RetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getApi().getFollowersList(getUserId(),
getCurrentPage());
} catch (HttpException e) {
e.printStackTrace();
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
ArrayList<User> users = new ArrayList<User>();
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
users.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addUsers(users);
return TaskResult.OK;
}
}
private class FollowersRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
Log.d(TAG, "load FollowersErtrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> t_users = getUsers();
getDb().syncWeiboUsers(t_users);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
/**
* TODO:需要重写,获取下一批用户,按页分100页一次
*
* @author Dino
*
*/
private class GetMoreTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getApi().getFollowersList(getUserId(),
getNextPage());
} catch (HttpException e) {
e.printStackTrace();
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
ArrayList<User> users = new ArrayList<User>();
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
users.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addUsers(users);
return TaskResult.OK;
}
}
private TaskListener getMoreListener = new TaskAdapter() {
@Override
public String getName() {
return "getMore";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
super.onPostExecute(task, result);
draw();
loadMoreGIF.setVisibility(View.GONE);
}
};
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setFeedback(mFeedback);
mGetMoreTask.setListener(getMoreListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/base/UserCursorBaseActivity.java | Java | asf20 | 19,270 |
/*
* Copyright (C) 2009 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.
*/
/**
* AbstractTwitterListBaseLine用于抽象tweets List的展现
* UI基本元素要求:一个ListView用于tweet列表
* 一个ProgressText用于提示信息
*/
package com.ch_linghu.fanfoudroid.ui.base;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.ProfileActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.StatusActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.WriteDmActivity;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
public abstract class TwitterListBaseActivity extends BaseActivity
implements Refreshable {
static final String TAG = "TwitterListBaseActivity";
protected TextView mProgressText;
protected Feedback mFeedback;
protected NavBar mNavbar;
protected static final int STATE_ALL = 0;
protected static final String SIS_RUNNING_KEY = "running";
// Tasks.
protected GenericTask mFavTask;
private TaskListener mFavTaskListener = new TaskAdapter(){
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
static final int DIALOG_WRITE_ID = 0;
abstract protected int getLayoutId();
abstract protected ListView getTweetList();
abstract protected TweetAdapter getTweetAdapter();
abstract protected void setupState();
abstract protected String getActivityTitle();
abstract protected boolean useBasicMenu();
abstract protected Tweet getContextItemTweet(int position);
abstract protected void updateTweet(Tweet tweet);
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
/**
* 如果增加了Context Menu常量的数量,则必须重载此方法,
* 以保证其他人使用常量时不产生重复
* @return 最大的Context Menu常量
*/
protected int getLastContextMenuId(){
return CONTEXT_DEL_FAV_ID;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState){
if (super._onCreate(savedInstanceState)){
setContentView(getLayoutId());
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL);
// 提示栏
mProgressText = (TextView) findViewById(R.id.progress_text);
setupState();
registerForContextMenu(getTweetList());
registerOnClickListener(getTweetList());
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
Log.d("FLING", "onContextItemSelected");
super.onCreateContextMenu(menu, v, menuInfo);
if (useBasicMenu()){
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Tweet tweet = getContextItemTweet(info.position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
return;
}
menu.add(0, CONTEXT_MORE_ID, 0, tweet.screenName + getResources().getString(R.string.cmenu_user_profile_prefix));
menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply);
menu.add(0, CONTEXT_RETWEET_ID, 0, R.string.cmenu_retweet);
menu.add(0, CONTEXT_DM_ID, 0, R.string.cmenu_direct_message);
if (tweet.favorited.equals("true")) {
menu.add(0, CONTEXT_DEL_FAV_ID, 0, R.string.cmenu_del_fav);
} else {
menu.add(0, CONTEXT_ADD_FAV_ID, 0, R.string.cmenu_add_fav);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Tweet tweet = getContextItemTweet(info.position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTEXT_MORE_ID:
launchActivity(ProfileActivity.createIntent(tweet.userId));
return true;
case CONTEXT_REPLY_ID: {
// TODO: this isn't quite perfect. It leaves extra empty spaces if
// you perform the reply action again.
Intent intent = WriteActivity.createNewReplyIntent(tweet.text, tweet.screenName, tweet.id);
startActivity(intent);
return true;
}
case CONTEXT_RETWEET_ID:
Intent intent = WriteActivity.createNewRepostIntent(this,
tweet.text, tweet.screenName, tweet.id);
startActivity(intent);
return true;
case CONTEXT_DM_ID:
launchActivity(WriteDmActivity.createIntent(tweet.userId));
return true;
case CONTEXT_ADD_FAV_ID:
doFavorite("add", tweet.id);
return true;
case CONTEXT_DEL_FAV_ID:
doFavorite("del", tweet.id);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_DM:
launchActivity(DmActivity.createIntent());
return true;
}
return super.onOptionsItemSelected(item);
}
protected void draw() {
getTweetAdapter().refresh();
}
protected void goTop() {
getTweetList().setSelection(1);
}
protected void adapterRefresh(){
getTweetAdapter().refresh();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (!TextUtils.isEmpty(id)) {
if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setListener(mFavTaskListener);
TaskParams params = new TaskParams();
params.put("action", action);
params.put("id", id);
mFavTask.execute(params);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
adapterRefresh();
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
protected void specialItemClicked(int position){
}
protected void registerOnClickListener(ListView listView) {
listView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Tweet tweet = getContextItemTweet(position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
specialItemClicked(position);
}else{
launchActivity(StatusActivity.createIntent(tweet));
}
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/base/TwitterListBaseActivity.java | Java | asf20 | 9,533 |
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.ListActivity;
/**
* TODO: 准备重构现有的几个ListActivity
*
* 目前几个ListActivity存在的问题是 :
* 1. 因为要实现[刷新]这些功能, 父类设定了子类继承时必须要实现的方法,
* 而刷新/获取其实更多的时候可以理解成是ListView的层面, 这在于讨论到底是一个"可刷新的Activity"
* 还是一个拥有"可刷新的ListView"的Activity, 如果改成后者, 则只要在父类拥有一个实现了可刷新接口的ListView即可,
* 而无需强制要求子类去直接实现某些方法.
* 2. 父类过于专制, 比如getLayoutId()等抽象方法的存在只是为了在父类进行setContentView, 而此类方法可以下放到子类去自行实现,
* 诸如此类的, 应该下放给子类更自由的空间. 理想状态为不使用抽象类.
* 3. 随着功能扩展, 需要将几个不同的ListActivity子类重复的部分重新抽象到父类来, 已减少代码重复.
* 4. TwitterList和UserList代码存在重复现象, 可抽象.
* 5. TwitterList目前过于依赖Cursor类型的List, 而没有Array类型的抽象类.
*
*/
public class BaseListActivity extends ListActivity {
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/base/BaseListActivity.java | Java | asf20 | 1,243 |
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.ch_linghu.fanfoudroid.AboutActivity;
import com.ch_linghu.fanfoudroid.LoginActivity;
import com.ch_linghu.fanfoudroid.PreferencesActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.service.TwitterService;
/**
* A BaseActivity has common routines and variables for an Activity that
* contains a list of tweets and a text input field.
*
* Not the cleanest design, but works okay for several Activities in this app.
*/
public class BaseActivity extends Activity {
private static final String TAG = "BaseActivity";
protected SharedPreferences mPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_onCreate(savedInstanceState);
}
// 因为onCreate方法无法返回状态,因此无法进行状态判断,
// 为了能对上层返回的信息进行判断处理,我们使用_onCreate代替真正的
// onCreate进行工作。onCreate仅在顶层调用_onCreate。
protected boolean _onCreate(Bundle savedInstanceState) {
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
if (!checkIsLogedIn()) {
return false;
} else {
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
mPreferences = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(this);
return true;
}
}
protected void handleLoggedOut() {
if (isTaskRoot()) {
showLogin();
} else {
setResult(RESULT_LOGOUT);
}
finish();
}
public TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public Weibo getApi() {
return TwitterApplication.mApi;
}
public SharedPreferences getPreferences() {
return mPreferences;
}
@Override
protected void onDestroy() {
super.onDestroy();
}
protected boolean isLoggedIn() {
return getApi().isLoggedIn();
}
private static final int RESULT_LOGOUT = RESULT_FIRST_USER + 1;
// Retrieve interface
// public ImageManager getImageManager() {
// return TwitterApplication.mImageManager;
// }
private void _logout() {
TwitterService.unschedule(BaseActivity.this);
getDb().clearData();
getApi().reset();
// Clear SharedPreferences
SharedPreferences.Editor editor = mPreferences.edit();
editor.clear();
editor.commit();
// TODO: 提供用户手动情况所有缓存选项
TwitterApplication.mImageLoader.getImageManager().clear();
// TODO: cancel notifications.
TwitterService.unschedule(BaseActivity.this);
handleLoggedOut();
}
public void logout() {
Dialog dialog = new AlertDialog.Builder(BaseActivity.this)
.setTitle("提示").setMessage("确实要注销吗?")
.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
_logout();
}
}).setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create();
dialog.show();
}
protected void showLogin() {
Intent intent = new Intent(this, LoginActivity.class);
// TODO: might be a hack?
intent.putExtra(Intent.EXTRA_INTENT, getIntent());
startActivity(intent);
}
protected void manageUpdateChecks() {
//检查后台更新状态设置
boolean isUpdateEnabled = mPreferences.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
if (isUpdateEnabled) {
TwitterService.schedule(this);
} else if (!TwitterService.isWidgetEnabled()) {
TwitterService.unschedule(this);
}
//检查强制竖屏设置
boolean isOrientationPortrait = mPreferences.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false);
if (isOrientationPortrait) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
// Menus.
protected static final int OPTIONS_MENU_ID_LOGOUT = 1;
protected static final int OPTIONS_MENU_ID_PREFERENCES = 2;
protected static final int OPTIONS_MENU_ID_ABOUT = 3;
protected static final int OPTIONS_MENU_ID_SEARCH = 4;
protected static final int OPTIONS_MENU_ID_REPLIES = 5;
protected static final int OPTIONS_MENU_ID_DM = 6;
protected static final int OPTIONS_MENU_ID_TWEETS = 7;
protected static final int OPTIONS_MENU_ID_TOGGLE_REPLIES = 8;
protected static final int OPTIONS_MENU_ID_FOLLOW = 9;
protected static final int OPTIONS_MENU_ID_UNFOLLOW = 10;
protected static final int OPTIONS_MENU_ID_IMAGE_CAPTURE = 11;
protected static final int OPTIONS_MENU_ID_PHOTO_LIBRARY = 12;
protected static final int OPTIONS_MENU_ID_EXIT = 13;
/**
* 如果增加了Option Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复
*
* @return 最大的Option Menu常量
*/
protected int getLastOptionMenuId() {
return OPTIONS_MENU_ID_EXIT;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// SubMenu submenu =
// menu.addSubMenu(R.string.write_label_insert_picture);
// submenu.setIcon(android.R.drawable.ic_menu_gallery);
//
// submenu.add(0, OPTIONS_MENU_ID_IMAGE_CAPTURE, 0,
// R.string.write_label_take_a_picture);
// submenu.add(0, OPTIONS_MENU_ID_PHOTO_LIBRARY, 0,
// R.string.write_label_choose_a_picture);
//
// MenuItem item = menu.add(0, OPTIONS_MENU_ID_SEARCH, 0,
// R.string.omenu_search);
// item.setIcon(android.R.drawable.ic_search_category_default);
// item.setAlphabeticShortcut(SearchManager.MENU_KEY);
MenuItem item;
item = menu.add(0, OPTIONS_MENU_ID_PREFERENCES, 0,
R.string.omenu_settings);
item.setIcon(android.R.drawable.ic_menu_preferences);
item = menu.add(0, OPTIONS_MENU_ID_LOGOUT, 0, R.string.omenu_signout);
item.setIcon(android.R.drawable.ic_menu_revert);
item = menu.add(0, OPTIONS_MENU_ID_ABOUT, 0, R.string.omenu_about);
item.setIcon(android.R.drawable.ic_menu_info_details);
item = menu.add(0, OPTIONS_MENU_ID_EXIT, 0, R.string.omenu_exit);
item.setIcon(android.R.drawable.ic_menu_rotate);
return true;
}
protected static final int REQUEST_CODE_LAUNCH_ACTIVITY = 0;
protected static final int REQUEST_CODE_PREFERENCES = 1;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_ID_LOGOUT:
logout();
return true;
case OPTIONS_MENU_ID_SEARCH:
onSearchRequested();
return true;
case OPTIONS_MENU_ID_PREFERENCES:
Intent launchPreferencesIntent = new Intent().setClass(this,
PreferencesActivity.class);
startActivityForResult(launchPreferencesIntent,
REQUEST_CODE_PREFERENCES);
return true;
case OPTIONS_MENU_ID_ABOUT:
//AboutDialog.show(this);
Intent intent = new Intent().setClass(this, AboutActivity.class);
startActivity(intent);
return true;
case OPTIONS_MENU_ID_EXIT:
exit();
return true;
}
return super.onOptionsItemSelected(item);
}
protected void exit() {
TwitterService.unschedule(this);
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
protected void launchActivity(Intent intent) {
// TODO: probably don't need this result chaining to finish upon logout.
// since the subclasses have to check in onResume.
startActivityForResult(intent, REQUEST_CODE_LAUNCH_ACTIVITY);
}
protected void launchDefaultActivity() {
Intent intent = new Intent();
intent.setClass(this, TwitterActivity.class);
startActivity(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PREFERENCES && resultCode == RESULT_OK) {
manageUpdateChecks();
} else if (requestCode == REQUEST_CODE_LAUNCH_ACTIVITY
&& resultCode == RESULT_LOGOUT) {
Log.d(TAG, "Result logout.");
handleLoggedOut();
}
}
protected boolean checkIsLogedIn() {
if (!getApi().isLoggedIn()) {
Log.d(TAG, "Not logged in.");
handleLoggedOut();
return false;
}
return true;
}
public static boolean isTrue(Bundle bundle, String key) {
return bundle != null && bundle.containsKey(key)
&& bundle.getBoolean(key);
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/base/BaseActivity.java | Java | asf20 | 10,752 |
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.SearchActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.MenuDialog;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
/**
* @deprecated 使用 {@link NavBar} 代替
*/
public class WithHeaderActivity extends BaseActivity {
private static final String TAG = "WithHeaderActivity";
public static final int HEADER_STYLE_HOME = 1;
public static final int HEADER_STYLE_WRITE = 2;
public static final int HEADER_STYLE_BACK = 3;
public static final int HEADER_STYLE_SEARCH = 4;
protected ImageView refreshButton;
protected ImageButton searchButton;
protected ImageButton writeButton;
protected TextView titleButton;
protected Button backButton;
protected ImageButton homeButton;
protected MenuDialog dialog;
protected EditText searchEdit;
protected Feedback mFeedback;
// FIXME: 刷新动画二选一, DELETE ME
protected AnimationDrawable mRefreshAnimation;
protected ProgressBar mProgress = null;
protected ProgressBar mLoadingProgress = null;
//搜索硬按键行为
@Override
public boolean onSearchRequested() {
Intent intent = new Intent();
intent.setClass(this, SearchActivity.class);
startActivity(intent);
return true;
}
// LOGO按钮
protected void addTitleButton() {
titleButton = (TextView) findViewById(R.id.title);
titleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int top = titleButton.getTop();
int height = titleButton.getHeight();
int x = top + height;
if (null == dialog) {
Log.d(TAG, "Create menu dialog.");
dialog = new MenuDialog(WithHeaderActivity.this);
dialog.bindEvent(WithHeaderActivity.this);
dialog.setPosition(-1, x);
}
// toggle dialog
if (dialog.isShowing()) {
dialog.dismiss(); //没机会触发
} else {
dialog.show();
}
}
});
}
protected void setHeaderTitle(String title) {
titleButton.setBackgroundDrawable( new BitmapDrawable());
titleButton.setText(title);
LayoutParams lp = new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(3, 12, 0, 0);
titleButton.setLayoutParams(lp);
// 中文粗体
TextPaint tp = titleButton.getPaint();
tp.setFakeBoldText(true);
}
protected void setHeaderTitle(int resource) {
titleButton.setBackgroundResource(resource);
}
// 刷新
protected void addRefreshButton() {
final Activity that = this;
refreshButton = (ImageView) findViewById(R.id.top_refresh);
// FIXME: 暂时取消旋转效果, 测试ProgressBar
//refreshButton.setBackgroundResource(R.drawable.top_refresh);
//mRefreshAnimation = (AnimationDrawable) refreshButton.getBackground();
// FIXME: DELETE ME
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
mLoadingProgress = (ProgressBar) findViewById(R.id.top_refresh_progressBar);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
refreshButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (that instanceof Refreshable) {
((Refreshable) that).doRetrieve();
} else {
Log.e(TAG, "The current view " + that.getClass().getName() + " cann't be retrieved");
}
}
});
}
/**
* @param v
* @deprecated use {@link WithHeaderActivity#setRefreshAnimation(boolean)}
*/
protected void animRotate(View v) {
setRefreshAnimation(true);
}
/**
* @param progress 0~100
* @deprecated use feedback
*/
public void setGlobalProgress(int progress) {
if ( null != mProgress) {
mProgress.setProgress(progress);
}
}
/**
* Start/Stop Top Refresh Button's Animation
*
* @param animate start or stop
* @deprecated use feedback
*/
public void setRefreshAnimation(boolean animate) {
if (mRefreshAnimation != null) {
if (animate) {
mRefreshAnimation.start();
} else {
mRefreshAnimation.setVisible(true, true); // restart
mRefreshAnimation.start(); // goTo frame 0
mRefreshAnimation.stop();
}
} else {
Log.w(TAG, "mRefreshAnimation is null");
}
}
// 搜索
protected void addSearchButton() {
searchButton = (ImageButton) findViewById(R.id.search);
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// // 旋转动画
// Animation anim = AnimationUtils.loadAnimation(v.getContext(),
// R.anim.scale_lite);
// v.startAnimation(anim);
//go to SearchActivity
startSearch();
}
});
}
// 这个方法会在SearchActivity里重写
protected boolean startSearch() {
Intent intent = new Intent();
intent.setClass(this, SearchActivity.class);
startActivity(intent);
return true;
}
//搜索框
protected void addSearchBox() {
searchEdit = (EditText) findViewById(R.id.search_edit);
}
// 撰写
protected void addWriteButton() {
writeButton = (ImageButton) findViewById(R.id.writeMessage);
writeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 动画
Animation anim = AnimationUtils.loadAnimation(v.getContext(),
R.anim.scale_lite);
v.startAnimation(anim);
// forward to write activity
Intent intent = new Intent();
intent.setClass(v.getContext(), WriteActivity.class);
v.getContext().startActivity(intent);
}
});
}
// 回首页
protected void addHomeButton() {
homeButton = (ImageButton) findViewById(R.id.home);
homeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 动画
Animation anim = AnimationUtils.loadAnimation(v.getContext(),
R.anim.scale_lite);
v.startAnimation(anim);
// forward to TwitterActivity
Intent intent = new Intent();
intent.setClass(v.getContext(), TwitterActivity.class);
v.getContext().startActivity(intent);
}
});
}
// 返回
protected void addBackButton() {
backButton = (Button) findViewById(R.id.top_back);
// 中文粗体
// TextPaint tp = backButton.getPaint();
// tp.setFakeBoldText(true);
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Go back to previous activity
finish();
}
});
}
protected void initHeader(int style) {
//FIXME: android 1.6似乎不支持addHeaderView中使用的方法
// 来增加header,造成header无法显示和使用。
// 改用在layout xml里include的方法来确保显示
switch (style) {
case HEADER_STYLE_HOME:
//addHeaderView(R.layout.header);
addTitleButton();
addWriteButton();
addSearchButton();
addRefreshButton();
break;
case HEADER_STYLE_BACK:
//addHeaderView(R.layout.header_back);
addBackButton();
addWriteButton();
addSearchButton();
addRefreshButton();
break;
case HEADER_STYLE_WRITE:
//addHeaderView(R.layout.header_write);
addBackButton();
//addHomeButton();
break;
case HEADER_STYLE_SEARCH:
//addHeaderView(R.layout.header_search);
addBackButton();
addSearchBox();
addSearchButton();
break;
}
}
private void addHeaderView(int resource) {
// find content root view
ViewGroup root = (ViewGroup) getWindow().getDecorView();
ViewGroup content = (ViewGroup) root.getChildAt(0);
View header = View.inflate(WithHeaderActivity.this, resource, null);
// LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
content.addView(header, 0);
}
@Override
protected void onDestroy() {
// dismiss dialog before destroy
// to avoid android.view.WindowLeaked Exception
if (dialog != null){
dialog.dismiss();
}
super.onDestroy();
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/base/WithHeaderActivity.java | Java | asf20 | 8,811 |
package com.ch_linghu.fanfoudroid.ui.base;
public interface Refreshable {
void doRetrieve();
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/base/Refreshable.java | Java | asf20 | 97 |
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.ProfileActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.UserTimelineActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.WriteDmActivity;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
public abstract class UserListBaseActivity extends BaseActivity implements
Refreshable {
static final String TAG = "TwitterListBaseActivity";
protected TextView mProgressText;
protected NavBar mNavbar;
protected Feedback mFeedback;
protected static final int STATE_ALL = 0;
protected static final String SIS_RUNNING_KEY = "running";
private static final String USER_ID = "userId";
// Tasks.
protected GenericTask mFavTask;
private TaskListener mFavTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
static final int DIALOG_WRITE_ID = 0;
abstract protected int getLayoutId();
abstract protected ListView getUserList();
abstract protected TweetAdapter getUserAdapter();
abstract protected void setupState();
abstract protected String getActivityTitle();
abstract protected boolean useBasicMenu();
abstract protected User getContextItemUser(int position);
abstract protected void updateTweet(Tweet tweet);
protected abstract String getUserId();// 获得用户id
public static final int CONTENT_PROFILE_ID = Menu.FIRST + 1;
public static final int CONTENT_STATUS_ID = Menu.FIRST + 2;
public static final int CONTENT_DEL_FRIEND = Menu.FIRST + 3;
public static final int CONTENT_ADD_FRIEND = Menu.FIRST + 4;
public static final int CONTENT_SEND_DM = Menu.FIRST + 5;
public static final int CONTENT_SEND_MENTION = Menu.FIRST + 6;
/**
* 如果增加了Context Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复
*
* @return 最大的Context Menu常量
*/
// protected int getLastContextMenuId(){
// return CONTEXT_DEL_FAV_ID;
// }
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
setContentView(getLayoutId());
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY,
STATE_ALL);
mProgressText = (TextView) findViewById(R.id.progress_text);
setupState();
registerForContextMenu(getUserList());
registerOnClickListener(getUserList());
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (useBasicMenu()) {
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
User user = getContextItemUser(info.position);
if (user == null) {
Log.w(TAG, "Selected item not available.");
return;
}
menu.add(0, CONTENT_PROFILE_ID, 0,
user.screenName + getResources().getString(
R.string.cmenu_user_profile_prefix));
menu.add(0, CONTENT_STATUS_ID, 0, user.screenName
+ getResources().getString(R.string.cmenu_user_status));
menu.add(0, CONTENT_SEND_MENTION, 0,
getResources().getString(R.string.cmenu_user_send_prefix)
+ user.screenName
+ getResources().getString(
R.string.cmenu_user_sendmention_suffix));
menu.add(0, CONTENT_SEND_DM, 0,
getResources().getString(R.string.cmenu_user_send_prefix)
+ user.screenName
+ getResources().getString(
R.string.cmenu_user_senddm_suffix));
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
User user = getContextItemUser(info.position);
if (user == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTENT_PROFILE_ID:
launchActivity(ProfileActivity.createIntent(user.id));
return true;
case CONTENT_STATUS_ID:
launchActivity(UserTimelineActivity
.createIntent(user.id, user.name));
return true;
case CONTENT_DEL_FRIEND:
delFriend(user.id);
return true;
case CONTENT_ADD_FRIEND:
addFriend(user.id);
return true;
case CONTENT_SEND_MENTION:
launchActivity(WriteActivity.createNewTweetIntent(String.format(
"@%s ", user.screenName)));
return true;
case CONTENT_SEND_DM:
launchActivity(WriteDmActivity.createIntent(user.id));
return true;
default:
return super.onContextItemSelected(item);
}
}
/**
* 取消关注
*
* @param id
*/
private void delFriend(final String id) {
Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
params.put(USER_ID, id);
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
private GenericTask cancelFollowingTask;
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
// TODO:userid
String userId = params[0].getString(USER_ID);
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("添加关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_notfollowing));
// followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
private GenericTask setFollowingTask;
/**
* 设置关注
*
* @param id
*/
private void addFriend(String id) {
Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String userId = params[0].getString(USER_ID);
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("取消关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_isfollowing));
// followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_DM:
launchActivity(DmActivity.createIntent());
return true;
}
return super.onOptionsItemSelected(item);
}
private void draw() {
getUserAdapter().refresh();
}
private void goTop() {
getUserList().setSelection(0);
}
protected void adapterRefresh() {
getUserAdapter().refresh();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (!TextUtils.isEmpty(id)) {
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setFeedback(mFeedback);
mFavTask.setListener(mFavTaskListener);
TaskParams params = new TaskParams();
params.put("action", action);
params.put("id", id);
mFavTask.execute(params);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
adapterRefresh();
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
protected void specialItemClicked(int position) {
}
/*
* TODO:单击列表项
*/
protected void registerOnClickListener(ListView listView) {
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(getBaseContext(), "选择第"+position+"个列表",Toast.LENGTH_SHORT).show();
User user = getContextItemUser(position);
if (user == null) {
Log.w(TAG, "selected item not available");
specialItemClicked(position);
} else {
launchActivity(ProfileActivity.createIntent(user.id));
}
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/base/UserListBaseActivity.java | Java | asf20 | 17,159 |
package com.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
public abstract class UserArrayBaseActivity extends UserListBaseActivity {
static final String TAG = "UserArrayBaseActivity";
// Views.
protected ListView mUserList;
protected UserArrayAdapter mUserListAdapter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
protected static int lastPosition = 0;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;// 每次100用户
public abstract Paging getCurrentPage();// 加载
public abstract Paging getNextPage();// 加载
// protected abstract String[] getIds();
protected abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException;
private ArrayList<com.ch_linghu.fanfoudroid.data.User> allUserList;
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
doRetrieve();// 加载第一页
return true;
} else {
return false;
}
}
@Override
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
draw();
}
updateProgress("");
}
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void onRetrieveBegin() {
updateProgress(getString(R.string.page_status_refreshing));
}
/**
* TODO:从API获取当前Followers
*
* @author Dino
*
*/
private class RetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getUsers(getUserId(), getCurrentPage());
} catch (HttpException e) {
e.printStackTrace();
return TaskResult.IO_ERROR;
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
allUserList.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
return TaskResult.OK;
}
}
@Override
protected int getLayoutId() {
return R.layout.follower;
}
@Override
protected void setupState() {
setTitle(getActivityTitle());
mUserList = (ListView) findViewById(R.id.follower_list);
setupListHeader(true);
mUserListAdapter = new UserArrayAdapter(this);
mUserList.setAdapter(mUserListAdapter);
allUserList = new ArrayList<com.ch_linghu.fanfoudroid.data.User>();
}
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
return null;
}
@Override
protected boolean useBasicMenu() {
return true;
}
@Override
protected User getContextItemUser(int position) {
// position = position - 1;
// 加入footer跳过footer
if (position < mUserListAdapter.getCount()) {
User item = (User) mUserListAdapter.getItem(position);
if (item == null) {
return null;
} else {
return item;
}
} else {
return null;
}
}
/**
* TODO:不知道啥用
*/
@Override
protected void updateTweet(Tweet tweet) {
// TODO Auto-generated method stub
}
@Override
protected ListView getUserList() {
return mUserList;
}
@Override
protected TweetAdapter getUserAdapter() {
return mUserListAdapter;
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add footer to Listview
View footer = View.inflate(this, R.layout.listview_footer, null);
mUserList.addFooterView(footer, null, true);
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
}
@Override
protected void specialItemClicked(int position) {
if (position == mUserList.getCount() - 1) {
// footer
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
mFeedback.start("");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setListener(getMoreListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
private TaskListener getMoreListener = new TaskAdapter() {
@Override
public String getName() {
return "getMore";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
super.onPostExecute(task, result);
draw();
mFeedback.success("");
loadMoreGIF.setVisibility(View.GONE);
}
};
/**
* TODO:需要重写,获取下一批用户,按页分100页一次
*
* @author Dino
*
*/
private class GetMoreTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getUsers(getUserId(), getNextPage());
mFeedback.update(60);
} catch (HttpException e) {
e.printStackTrace();
return TaskResult.IO_ERROR;
}
// 将获取到的数据(保存/更新)到数据库
getDb().syncWeiboUsers(usersList);
mFeedback.update(100 - (int) Math.floor(usersList.size() * 2));
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
allUserList.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
mFeedback.update(99);
return TaskResult.OK;
}
}
public void draw() {
mUserListAdapter.refresh(allUserList);
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/base/UserArrayBaseActivity.java | Java | asf20 | 9,608 |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TweetArrayAdapter extends BaseAdapter implements TweetAdapter {
private static final String TAG = "TweetArrayAdapter";
protected ArrayList<Tweet> mTweets;
private Context mContext;
protected LayoutInflater mInflater;
protected StringBuilder mMetaBuilder;
private ImageLoaderCallback callback = new ImageLoaderCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
TweetArrayAdapter.this.refresh();
}
};
public TweetArrayAdapter(Context context) {
mTweets = new ArrayList<Tweet>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
mMetaBuilder = new StringBuilder();
}
@Override
public int getCount() {
return mTweets.size();
}
@Override
public Object getItem(int position) {
return mTweets.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder {
public TextView tweetUserText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
public ImageView fav;
public ImageView has_image;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
if (convertView == null) {
view = mInflater.inflate(R.layout.tweet, parent, false);
ViewHolder holder = new ViewHolder();
holder.tweetUserText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view
.findViewById(R.id.profile_image);
holder.metaText = (TextView) view
.findViewById(R.id.tweet_meta_text);
holder.fav = (ImageView) view.findViewById(R.id.tweet_fav);
holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image);
view.setTag(holder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
Tweet tweet = mTweets.get(position);
holder.tweetUserText.setText(tweet.screenName);
TextHelper.setSimpleTweetText(holder.tweetText, tweet.text);
// holder.tweetText.setText(tweet.text, BufferType.SPANNABLE);
String profileImageUrl = tweet.profileImageUrl;
if (useProfileImage){
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, callback));
}
}else{
holder.profileImage.setVisibility(View.GONE);
}
holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder,
tweet.createdAt, tweet.source, tweet.inReplyToScreenName));
if (tweet.favorited.equals("true")) {
holder.fav.setVisibility(View.VISIBLE);
} else {
holder.fav.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(tweet.thumbnail_pic)) {
holder.has_image.setVisibility(View.VISIBLE);
} else {
holder.has_image.setVisibility(View.GONE);
}
return view;
}
public void refresh(ArrayList<Tweet> tweets) {
mTweets = tweets;
notifyDataSetChanged();
}
@Override
public void refresh() {
notifyDataSetChanged();
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/TweetArrayAdapter.java | Java | asf20 | 4,073 |
package com.ch_linghu.fanfoudroid.ui.module;
import android.widget.ListAdapter;
public interface TweetAdapter extends ListAdapter{
void refresh();
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/TweetAdapter.java | Java | asf20 | 152 |
package com.ch_linghu.fanfoudroid.ui.module;
import android.app.Activity;
import android.view.MotionEvent;
import com.ch_linghu.fanfoudroid.BrowseActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
/**
* MyActivityFlipper 利用左右滑动手势切换Activity
*
* 1. 切换Activity, 继承与 {@link ActivityFlipper} 2. 手势识别, 实现接口
* {@link Widget.OnGestureListener}
*
*/
public class MyActivityFlipper extends ActivityFlipper implements
Widget.OnGestureListener {
public MyActivityFlipper() {
super();
}
public MyActivityFlipper(Activity activity) {
super(activity);
// TODO Auto-generated constructor stub
}
// factory
public static MyActivityFlipper create(Activity activity) {
MyActivityFlipper flipper = new MyActivityFlipper(activity);
flipper.addActivity(BrowseActivity.class);
flipper.addActivity(TwitterActivity.class);
flipper.addActivity(MentionActivity.class);
flipper.setToastResource(new int[] { R.drawable.point_left,
R.drawable.point_center, R.drawable.point_right });
flipper.setInAnimation(R.anim.push_left_in);
flipper.setOutAnimation(R.anim.push_left_out);
flipper.setPreviousInAnimation(R.anim.push_right_in);
flipper.setPreviousOutAnimation(R.anim.push_right_out);
return flipper;
}
@Override
public boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false; // do nothing
}
@Override
public boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false; // do nothing
}
@Override
public boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
autoShowNext();
return true;
}
@Override
public boolean onFlingRight(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
autoShowPrevious();
return true;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/MyActivityFlipper.java | Java | asf20 | 2,183 |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.AbsListView;
import android.widget.ListView;
public class MyListView extends ListView implements ListView.OnScrollListener {
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
setOnScrollListener(this);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean result = super.onInterceptTouchEvent(event);
if (mScrollState == OnScrollListener.SCROLL_STATE_FLING) {
return true;
}
return result;
}
private OnNeedMoreListener mOnNeedMoreListener;
public static interface OnNeedMoreListener {
public void needMore();
}
public void setOnNeedMoreListener(OnNeedMoreListener onNeedMoreListener) {
mOnNeedMoreListener = onNeedMoreListener;
}
private int mFirstVisibleItem;
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mOnNeedMoreListener == null) {
return;
}
if (firstVisibleItem != mFirstVisibleItem) {
if (firstVisibleItem + visibleItemCount >= totalItemCount) {
mOnNeedMoreListener.needMore();
}
} else {
mFirstVisibleItem = firstVisibleItem;
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/MyListView.java | Java | asf20 | 1,620 |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.text.Layout;
import android.text.Spannable;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
public class MyTextView extends TextView {
private static float mFontSize = 15;
private static boolean mFontSizeChanged = true;
public MyTextView(Context context) {
super(context, null);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setLinksClickable(false);
Resources res = getResources();
int color = res.getColor(R.color.link_color);
setLinkTextColor(color);
initFontSize();
}
public void initFontSize() {
if ( mFontSizeChanged ) {
mFontSize = getFontSizeFromPreferences(mFontSize);
setFontSizeChanged(false); // reset
}
setTextSize(mFontSize);
}
private float getFontSizeFromPreferences(float defaultValue) {
SharedPreferences preferences = TwitterApplication.mPref;
if (preferences.contains(Preferences.UI_FONT_SIZE)) {
Log.v("DEBUG", preferences.getString(Preferences.UI_FONT_SIZE, "null") + " CHANGE FONT SIZE");
return Float.parseFloat(preferences.getString(
Preferences.UI_FONT_SIZE, "14"));
}
return defaultValue;
}
private URLSpan mCurrentLink;
private ForegroundColorSpan mLinkFocusStyle = new ForegroundColorSpan(
Color.RED);
@Override
public boolean onTouchEvent(MotionEvent event) {
CharSequence text = getText();
int action = event.getAction();
if (!(text instanceof Spannable)) {
return super.onTouchEvent(event);
}
Spannable buffer = (Spannable) text;
if (action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_MOVE) {
TextView widget = this;
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
if (mCurrentLink == link[0]) {
link[0].onClick(widget);
}
mCurrentLink = null;
buffer.removeSpan(mLinkFocusStyle);
} else if (action == MotionEvent.ACTION_DOWN) {
mCurrentLink = link[0];
buffer.setSpan(mLinkFocusStyle,
buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return true;
}
}
mCurrentLink = null;
buffer.removeSpan(mLinkFocusStyle);
return super.onTouchEvent(event);
}
public static void setFontSizeChanged(boolean isChanged) {
mFontSizeChanged = isChanged;
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/MyTextView.java | Java | asf20 | 4,155 |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.util.Log;
public class FeedbackFactory {
private static final String TAG = "FeedbackFactory";
public static enum FeedbackType {
DIALOG, PROGRESS, REFRESH
};
public static Feedback create(Context context, FeedbackType type) {
Feedback feedback = null;
switch (type) {
case PROGRESS:
feedback = new SimpleFeedback(context);
break;
}
if (null == feedback || !feedback.isAvailable()) {
feedback = new FeedbackAdapter(context);
Log.e(TAG, type + " feedback is not available.");
}
return feedback;
}
public static class FeedbackAdapter implements Feedback {
public FeedbackAdapter(Context context) {}
@Override
public void start(CharSequence text) {}
@Override
public void cancel(CharSequence text) {}
@Override
public void success(CharSequence text) {}
@Override
public void failed(CharSequence text) {}
@Override
public void update(Object arg0) {}
@Override
public boolean isAvailable() { return true; }
@Override
public void setIndeterminate(boolean indeterminate) {}
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/FeedbackFactory.java | Java | asf20 | 1,347 |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.R;
public class SimpleFeedback implements Feedback, Widget {
private static final String TAG = "SimpleFeedback";
public static final int MAX = 100;
private ProgressBar mProgress = null;
private ProgressBar mLoadingProgress = null;
public SimpleFeedback(Context context) {
mProgress = (ProgressBar) ((Activity) context)
.findViewById(R.id.progress_bar);
mLoadingProgress = (ProgressBar) ((Activity) context)
.findViewById(R.id.top_refresh_progressBar);
}
@Override
public void start(CharSequence text) {
mProgress.setProgress(20);
mLoadingProgress.setVisibility(View.VISIBLE);
}
@Override
public void success(CharSequence text) {
mProgress.setProgress(100);
mLoadingProgress.setVisibility(View.GONE);
resetProgressBar();
}
@Override
public void failed(CharSequence text) {
resetProgressBar();
showMessage(text);
}
@Override
public void cancel(CharSequence text) {
}
@Override
public void update(Object arg0) {
if (arg0 instanceof Integer) {
mProgress.setProgress((Integer) arg0);
} else if (arg0 instanceof CharSequence) {
showMessage((String) arg0);
}
}
@Override
public void setIndeterminate(boolean indeterminate) {
mProgress.setIndeterminate(indeterminate);
}
@Override
public Context getContext() {
if (mProgress != null) {
return mProgress.getContext();
}
if (mLoadingProgress != null) {
return mLoadingProgress.getContext();
}
return null;
}
@Override
public boolean isAvailable() {
if (null == mProgress) {
Log.e(TAG, "R.id.progress_bar is missing");
return false;
}
if (null == mLoadingProgress) {
Log.e(TAG, "R.id.top_refresh_progressBar is missing");
return false;
}
return true;
}
/**
* @param total 0~100
* @param maxSize max size of list
* @param list
* @return
*/
public static int calProgressBySize(int total, int maxSize, List<?> list) {
if (null != list) {
return (MAX - (int)Math.floor(list.size() * (total/maxSize)));
}
return MAX;
}
private void resetProgressBar() {
if (mProgress.isIndeterminate()) {
//TODO: 第二次不会出现
mProgress.setIndeterminate(false);
}
mProgress.setProgress(0);
}
private void showMessage(CharSequence text) {
Toast.makeText(getContext(), text, Toast.LENGTH_LONG).show();
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/SimpleFeedback.java | Java | asf20 | 3,029 |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
//TODO:
/*
* 用于用户的Adapter
*/
public class UserArrayAdapter extends BaseAdapter implements TweetAdapter{
private static final String TAG = "UserArrayAdapter";
private static final String USER_ID="userId";
protected ArrayList<User> mUsers;
private Context mContext;
protected LayoutInflater mInflater;
public UserArrayAdapter(Context context) {
mUsers = new ArrayList<User>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return mUsers.size();
}
@Override
public Object getItem(int position) {
return mUsers.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder {
public ImageView profileImage;
public TextView screenName;
public TextView userId;
public TextView lastStatus;
public TextView followBtn;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
if (convertView == null) {
view = mInflater.inflate(R.layout.follower_item, parent, false);
ViewHolder holder = new ViewHolder();
holder.profileImage = (ImageView) view.findViewById(R.id.profile_image);
holder.screenName = (TextView) view.findViewById(R.id.screen_name);
holder.userId = (TextView) view.findViewById(R.id.user_id);
//holder.lastStatus = (TextView) view.findViewById(R.id.last_status);
holder.followBtn = (TextView) view.findViewById(R.id.follow_btn);
view.setTag(holder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
final User user = mUsers.get(position);
String profileImageUrl = user.profileImageUrl;
if (useProfileImage){
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, callback));
}
}else{
holder.profileImage.setVisibility(View.GONE);
}
//holder.profileImage.setImageBitmap(ImageManager.mDefaultBitmap);
holder.screenName.setText(user.screenName);
holder.userId.setText(user.id);
//holder.lastStatus.setText(user.lastStatus);
holder.followBtn.setText(user.isFollowing ? mContext
.getString(R.string.general_del_friend) : mContext
.getString(R.string.general_add_friend));
holder.followBtn.setOnClickListener(user.isFollowing?new OnClickListener(){
@Override
public void onClick(View v) {
//Toast.makeText(mContext, user.name+"following", Toast.LENGTH_SHORT).show();
delFriend(user.id);
}}:new OnClickListener(){
@Override
public void onClick(View v) {
//Toast.makeText(mContext, user.name+"not following", Toast.LENGTH_SHORT).show();
addFriend(user.id);
}});
return view;
}
public void refresh(ArrayList<User> users) {
mUsers = users;
notifyDataSetChanged();
}
@Override
public void refresh() {
notifyDataSetChanged();
}
private ImageLoaderCallback callback = new ImageLoaderCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
UserArrayAdapter.this.refresh();
}
};
/**
* 取消关注
* @param id
*/
private void delFriend(final String id) {
Builder diaBuilder = new AlertDialog.Builder(mContext)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
params.put(USER_ID, id);
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
private GenericTask cancelFollowingTask;
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
//TODO:userid
String userId=params[0].getString(USER_ID);
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("添加关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_notfollowing));
// followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(mContext, "取消关注成功", Toast.LENGTH_SHORT).show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(mContext, "取消关注失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
private GenericTask setFollowingTask;
/**
* 设置关注
* @param id
*/
private void addFriend(String id){
Builder diaBuilder = new AlertDialog.Builder(mContext)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String userId=params[0].getString(USER_ID);
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("取消关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_isfollowing));
// followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(mContext, "关注成功", Toast.LENGTH_SHORT).show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(mContext, "关注失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
public Weibo getApi() {
return TwitterApplication.mApi;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/UserArrayAdapter.java | Java | asf20 | 9,395 |
package com.ch_linghu.fanfoudroid.ui.module;
public interface IFlipper {
void showNext();
void showPrevious();
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/IFlipper.java | Java | asf20 | 122 |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
public interface Widget {
Context getContext();
// TEMP
public static interface OnGestureListener {
/**
* @param e1
* The first down motion event that started the fling.
* @param e2
* The move motion event that triggered the current onFling.
* @param velocityX
* The velocity of this fling measured in pixels per second
* along the x axis.
* @param velocityY
* The velocity of this fling measured in pixels per second
* along the y axis.
* @return true if the event is consumed, else false
*
* @see SimpleOnGestureListener#onFling
*/
boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
boolean onFlingRight(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
}
public static interface OnRefreshListener {
void onRefresh();
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/Widget.java | Java | asf20 | 1,456 |
package com.ch_linghu.fanfoudroid.ui.module;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.SearchActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
public class NavBar implements Widget {
private static final String TAG = "NavBar";
public static final int HEADER_STYLE_HOME = 1;
public static final int HEADER_STYLE_WRITE = 2;
public static final int HEADER_STYLE_BACK = 3;
public static final int HEADER_STYLE_SEARCH = 4;
private ImageView mRefreshButton;
private ImageButton mSearchButton;
private ImageButton mWriteButton;
private TextView mTitleButton;
private Button mBackButton;
private ImageButton mHomeButton;
private MenuDialog mDialog;
private EditText mSearchEdit;
/** @deprecated 已废弃 */
protected AnimationDrawable mRefreshAnimation;
private ProgressBar mProgressBar = null; // 进度条(横)
private ProgressBar mLoadingProgress = null; // 旋转图标
public NavBar(int style, Context context) {
initHeader(style, (Activity) context);
}
private void initHeader(int style, final Activity activity) {
switch (style) {
case HEADER_STYLE_HOME:
addTitleButtonTo(activity);
addWriteButtonTo(activity);
addSearchButtonTo(activity);
addRefreshButtonTo(activity);
break;
case HEADER_STYLE_BACK:
addBackButtonTo(activity);
addWriteButtonTo(activity);
addSearchButtonTo(activity);
addRefreshButtonTo(activity);
break;
case HEADER_STYLE_WRITE:
addBackButtonTo(activity);
break;
case HEADER_STYLE_SEARCH:
addBackButtonTo(activity);
addSearchBoxTo(activity);
addSearchButtonTo(activity);
break;
}
}
/**
* 搜索硬按键行为
* @deprecated 这个不晓得还有没有用, 已经是已经被新的搜索替代的吧 ?
*/
public boolean onSearchRequested() {
/*
Intent intent = new Intent();
intent.setClass(this, SearchActivity.class);
startActivity(intent);
*/
return true;
}
/**
* 添加[LOGO/标题]按钮
* @param acticity
*/
private void addTitleButtonTo(final Activity acticity) {
mTitleButton = (TextView) acticity.findViewById(R.id.title);
mTitleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int top = mTitleButton.getTop();
int height = mTitleButton.getHeight();
int x = top + height;
if (null == mDialog) {
Log.d(TAG, "Create menu dialog.");
mDialog = new MenuDialog(acticity);
mDialog.bindEvent(acticity);
mDialog.setPosition(-1, x);
}
// toggle dialog
if (mDialog.isShowing()) {
mDialog.dismiss(); // 没机会触发
} else {
mDialog.show();
}
}
});
}
/**
* 设置标题
* @param title
*/
public void setHeaderTitle(String title) {
if (null != mTitleButton) {
mTitleButton.setText(title);
TextPaint tp = mTitleButton.getPaint();
tp.setFakeBoldText(true); // 中文粗体
}
}
/**
* 设置标题
* @param resource R.string.xxx
*/
public void setHeaderTitle(int resource) {
if (null != mTitleButton) {
mTitleButton.setBackgroundResource(resource);
}
}
/**
* 添加[刷新]按钮
* @param activity
*/
private void addRefreshButtonTo(final Activity activity) {
mRefreshButton = (ImageView) activity.findViewById(R.id.top_refresh);
// FIXME: DELETE ME 暂时取消旋转效果, 测试ProgressBar
// refreshButton.setBackgroundResource(R.drawable.top_refresh);
// mRefreshAnimation = (AnimationDrawable)
// refreshButton.getBackground();
mProgressBar = (ProgressBar) activity.findViewById(R.id.progress_bar);
mLoadingProgress = (ProgressBar) activity
.findViewById(R.id.top_refresh_progressBar);
mRefreshButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (activity instanceof Refreshable) {
((Refreshable) activity).doRetrieve();
} else {
Log.e(TAG, "The current view "
+ activity.getClass().getName()
+ " cann't be retrieved");
}
}
});
}
/**
* Start/Stop Top Refresh Button's Animation
*
* @param animate
* start or stop
* @deprecated use feedback
*/
public void setRefreshAnimation(boolean animate) {
if (mRefreshAnimation != null) {
if (animate) {
mRefreshAnimation.start();
} else {
mRefreshAnimation.setVisible(true, true); // restart
mRefreshAnimation.start(); // goTo frame 0
mRefreshAnimation.stop();
}
} else {
Log.w(TAG, "mRefreshAnimation is null");
}
}
/**
* 添加[搜索]按钮
* @param activity
*/
private void addSearchButtonTo(final Activity activity) {
mSearchButton = (ImageButton) activity.findViewById(R.id.search);
mSearchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startSearch(activity);
}
});
}
// 这个方法会在SearchActivity里重写
protected boolean startSearch(final Activity activity) {
Intent intent = new Intent();
intent.setClass(activity, SearchActivity.class);
activity.startActivity(intent);
return true;
}
/**
* 添加[搜索框]
* @param activity
*/
private void addSearchBoxTo(final Activity activity) {
mSearchEdit = (EditText) activity.findViewById(R.id.search_edit);
}
/**
* 添加[撰写]按钮
* @param activity
*/
private void addWriteButtonTo(final Activity activity) {
mWriteButton = (ImageButton) activity.findViewById(R.id.writeMessage);
mWriteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// forward to write activity
Intent intent = new Intent();
intent.setClass(v.getContext(), WriteActivity.class);
v.getContext().startActivity(intent);
}
});
}
/**
* 添加[回首页]按钮
* @param activity
*/
@SuppressWarnings("unused")
private void addHomeButton(final Activity activity) {
mHomeButton = (ImageButton) activity.findViewById(R.id.home);
mHomeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 动画
Animation anim = AnimationUtils.loadAnimation(v.getContext(),
R.anim.scale_lite);
v.startAnimation(anim);
// forward to TwitterActivity
Intent intent = new Intent();
intent.setClass(v.getContext(), TwitterActivity.class);
v.getContext().startActivity(intent);
}
});
}
/**
* 添加[返回]按钮
* @param activity
*/
private void addBackButtonTo(final Activity activity) {
mBackButton = (Button) activity.findViewById(R.id.top_back);
// 中文粗体
// TextPaint tp = backButton.getPaint();
// tp.setFakeBoldText(true);
mBackButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Go back to previous activity
activity.finish();
}
});
}
public void destroy() {
// dismiss dialog before destroy
// to avoid android.view.WindowLeaked Exception
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
mRefreshButton = null;
mSearchButton = null;
mWriteButton = null;
mTitleButton = null;
mBackButton = null;
mHomeButton = null;
mSearchButton = null;
mSearchEdit = null;
mProgressBar = null;
mLoadingProgress = null;
}
public ImageView getRefreshButton() {
return mRefreshButton;
}
public ImageButton getSearchButton() {
return mSearchButton;
}
public ImageButton getWriteButton() {
return mWriteButton;
}
public TextView getTitleButton() {
return mTitleButton;
}
public Button getBackButton() {
return mBackButton;
}
public ImageButton getHomeButton() {
return mHomeButton;
}
public MenuDialog getDialog() {
return mDialog;
}
public EditText getSearchEdit() {
return mSearchEdit;
}
/** @deprecated 已废弃 */
public AnimationDrawable getRefreshAnimation() {
return mRefreshAnimation;
}
public ProgressBar getProgressBar() {
return mProgressBar;
}
public ProgressBar getLoadingProgress() {
return mLoadingProgress;
}
@Override
public Context getContext() {
if (null != mDialog) {
return mDialog.getContext();
}
if (null != mTitleButton) {
return mTitleButton.getContext();
}
return null;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/NavBar.java | Java | asf20 | 10,493 |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
import com.ch_linghu.fanfoudroid.R;
/**
* ActivityFlipper, 和 {@link ViewFactory} 类似, 只是设计用于切换activity.
*
* 切换的前后顺序取决与注册时的先后顺序
*
* USAGE: <code>
* ActivityFlipper mFlipper = new ActivityFlipper(this);
* mFlipper.addActivity(TwitterActivity.class);
* mFlipper.addActivity(MentionActivity.class);
* mFlipper.addActivity(DmActivity.class);
*
* // switch activity
* mFlipper.setCurrentActivity(TwitterActivity.class);
* mFlipper.showNext();
* mFlipper.showPrevious();
*
* // or without set current activity
* mFlipper.showNextOf(TwitterActivity.class);
* mFlipper.showPreviousOf(TwitterActivity.class);
*
* // or auto mode, use the context as current activity
* mFlipper.autoShowNext();
* mFlipper.autoShowPrevious();
*
* // set toast
* mFlipper.setToastResource(new int[] {
* R.drawable.point_left,
* R.drawable.point_center,
* R.drawable.point_right
* });
*
* // set Animation
* mFlipper.setInAnimation(R.anim.push_left_in);
* mFlipper.setOutAnimation(R.anim.push_left_out);
* mFlipper.setPreviousInAnimation(R.anim.push_right_in);
* mFlipper.setPreviousOutAnimation(R.anim.push_right_out);
* </code>
*
*/
public class ActivityFlipper implements IFlipper {
private static final String TAG = "ActivityFlipper";
private static final int SHOW_NEXT = 0;
private static final int SHOW_PROVIOUS = 1;
private int mDirection = SHOW_NEXT;
private boolean mToastEnabled = false;
private int[] mToastResourcesMap = new int[]{};
private boolean mAnimationEnabled = false;
private int mNextInAnimation = -1;
private int mNextOutAnimation = -1;
private int mPreviousInAnimation = -1;
private int mPreviousOutAnimation = -1;
private Activity mActivity;
private List<Class<?>> mActivities = new ArrayList<Class<?>>();;
private int mWhichActivity = 0;
public ActivityFlipper() {
}
public ActivityFlipper(Activity activity) {
mActivity = activity;
}
/**
* Launch Activity
*
* @param cls
* class of activity
*/
public void launchActivity(Class<?> cls) {
Log.v(TAG, "launch activity :" + cls.getName());
Intent intent = new Intent();
intent.setClass(mActivity, cls);
mActivity.startActivity(intent);
}
public void setToastResource(int[] resourceIds) {
mToastEnabled = true;
mToastResourcesMap = resourceIds;
}
private void maybeShowToast(int whichActicity) {
if (mToastEnabled && whichActicity < mToastResourcesMap.length) {
final Toast myToast = new Toast(mActivity);
final ImageView myView = new ImageView(mActivity);
myView.setImageResource(mToastResourcesMap[whichActicity]);
myToast.setView(myView);
myToast.setDuration(Toast.LENGTH_SHORT);
myToast.setGravity(Gravity.BOTTOM | Gravity.CENTER, 0, 0);
myToast.show();
}
}
private void maybeShowAnimation(int whichActivity) {
if (mAnimationEnabled) {
boolean showPrevious = (mDirection == SHOW_PROVIOUS);
if (showPrevious && mPreviousInAnimation != -1
&& mPreviousOutAnimation != -1) {
mActivity.overridePendingTransition(
mPreviousInAnimation, mPreviousOutAnimation);
return; // use Previous Animation
}
if (mNextInAnimation != -1 && mNextOutAnimation != -1) {
mActivity.overridePendingTransition(
mNextInAnimation, mNextOutAnimation);
}
}
}
/**
* Launch Activity by index
*
* @param whichActivity
* the index of Activity
*/
private void launchActivity(int whichActivity) {
launchActivity(mActivities.get(whichActivity));
maybeShowToast(whichActivity);
maybeShowAnimation(whichActivity);
}
/**
* Add Activity NOTE: 添加的顺序很重要
*
* @param cls
* class of activity
*/
public void addActivity(Class<?> cls) {
mActivities.add(cls);
}
/**
* Get index of the Activity
*
* @param cls
* class of activity
* @return
*/
private int getIndexOf(Class<?> cls) {
int index = mActivities.indexOf(cls);
if (-1 == index) {
Log.e(TAG, "No such activity: " + cls.getName());
}
return index;
}
@SuppressWarnings("unused")
private Class<?> getActivityAt(int index) {
if (index > 0 && index < mActivities.size()) {
return mActivities.get(index);
}
return null;
}
/**
* Show next activity(already setCurrentActivity)
*/
@Override
public void showNext() {
mDirection = SHOW_NEXT;
setDisplayedActivity(mWhichActivity + 1, true);
}
/**
* Show next activity of
*
* @param cls
* class of activity
*/
public void showNextOf(Class<?> cls) {
setCurrentActivity(cls);
showNext();
}
/**
* Show next activity(use current context as a activity)
*/
public void autoShowNext() {
showNextOf(mActivity.getClass());
}
/**
* Show previous activity(already setCurrentActivity)
*/
@Override
public void showPrevious() {
mDirection = SHOW_PROVIOUS;
setDisplayedActivity(mWhichActivity - 1, true);
}
/**
* Show previous activity of
*
* @param cls
* class of activity
*/
public void showPreviousOf(Class<?> cls) {
setCurrentActivity(cls);
showPrevious();
}
/**
* Show previous activity(use current context as a activity)
*/
public void autoShowPrevious() {
showPreviousOf(mActivity.getClass());
}
/**
* Sets which child view will be displayed
*
* @param whichActivity
* the index of the child view to display
* @param display
* display immediately
*/
public void setDisplayedActivity(int whichActivity, boolean display) {
mWhichActivity = whichActivity;
if (whichActivity >= getCount()) {
mWhichActivity = 0;
} else if (whichActivity < 0) {
mWhichActivity = getCount() - 1;
}
if (display) {
launchActivity(mWhichActivity);
}
}
/**
* Set current Activity
*
* @param cls
* class of activity
*/
public void setCurrentActivity(Class<?> cls) {
setDisplayedActivity(getIndexOf(cls), false);
}
public void setInAnimation(int resourceId) {
setEnableAnimation(true);
mNextInAnimation = resourceId;
}
public void setOutAnimation(int resourceId) {
setEnableAnimation(true);
mNextOutAnimation = resourceId;
}
public void setPreviousInAnimation(int resourceId) {
mPreviousInAnimation = resourceId;
}
public void setPreviousOutAnimation(int resourceId) {
mPreviousOutAnimation = resourceId;
}
public void setEnableAnimation(boolean enable) {
mAnimationEnabled = enable;
}
/**
* Count activities
*
* @return the number of activities
*/
public int getCount() {
return mActivities.size();
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/ActivityFlipper.java | Java | asf20 | 7,900 |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.BrowseActivity;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.FavoritesActivity;
import com.ch_linghu.fanfoudroid.FollowersActivity;
import com.ch_linghu.fanfoudroid.FollowingActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.ProfileActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.UserTimelineActivity;
/**
* 顶部主菜单切换浮动层
*
* @author lds
*
*/
public class MenuDialog extends Dialog {
private static final int PAGE_MINE = 0;
private static final int PAGE_PROFILE = 1;
private static final int PAGE_FOLLOWERS = 2;
private static final int PAGE_FOLLOWING = 3;
private static final int PAGE_HOME = 4;
private static final int PAGE_MENTIONS = 5;
private static final int PAGE_BROWSE = 6;
private static final int PAGE_FAVORITES = 7;
private static final int PAGE_MESSAGE = 8;
private List<int[]> pages = new ArrayList<int[]>();
{
pages.add(new int[] { R.drawable.menu_tweets,
R.string.pages_mine });
pages.add(new int[] { R.drawable.menu_profile,
R.string.pages_profile });
pages.add(new int[] { R.drawable.menu_followers,
R.string.pages_followers });
pages.add(new int[] { R.drawable.menu_following,
R.string.pages_following });
pages.add(new int[] { R.drawable.menu_list,
R.string.pages_home });
pages.add(new int[] { R.drawable.menu_mentions,
R.string.pages_mentions });
pages.add(new int[] { R.drawable.menu_listed,
R.string.pages_browse });
pages.add(new int[] { R.drawable.menu_favorites,
R.string.pages_search });
pages.add(new int[] { R.drawable.menu_create_list,
R.string.pages_message });
};
private GridView gridview;
public MenuDialog(Context context, boolean cancelable,
OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
// TODO Auto-generated constructor stub
}
public MenuDialog(Context context, int theme) {
super(context, theme);
// TODO Auto-generated constructor stub
}
public MenuDialog(Context context) {
super(context, R.style.Theme_Transparent);
setContentView(R.layout.menu_dialog);
// setTitle("Custom Dialog");
setCanceledOnTouchOutside(true);
// 设置window属性
LayoutParams a = getWindow().getAttributes();
a.gravity = Gravity.TOP;
a.dimAmount = 0; // 去背景遮盖
getWindow().setAttributes(a);
initMenu();
}
public void setPosition(int x, int y) {
LayoutParams a = getWindow().getAttributes();
if (-1 != x)
a.x = x;
if (-1 != y)
a.y = y;
getWindow().setAttributes(a);
}
private void goTo(Class<?> cls, Intent intent) {
if (getOwnerActivity().getClass() != cls) {
dismiss();
intent.setClass(getContext(), cls);
getContext().startActivity(intent);
} else {
String msg = getContext().getString(R.string.page_status_same_page);
Toast.makeText(getContext(), msg,
Toast.LENGTH_SHORT).show();
}
}
private void goTo(Class<?> cls){
Intent intent = new Intent();
goTo(cls, intent);
}
private void initMenu() {
// 准备要添加的数据条目
List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
for (int[] item : pages) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("image", item[0]);
map.put("title", getContext().getString(item[1]) );
items.add(map);
}
// 实例化一个适配器
SimpleAdapter adapter = new SimpleAdapter(getContext(),
items, // data
R.layout.menu_item, // grid item layout
new String[] { "title", "image" }, // data's key
new int[] { R.id.item_text, R.id.item_image }); // item view id
// 获得GridView实例
gridview = (GridView) findViewById(R.id.mygridview);
// 将GridView和数据适配器关联
gridview.setAdapter(adapter);
}
public void bindEvent(Activity activity) {
setOwnerActivity(activity);
// 绑定监听器
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
switch (position) {
case PAGE_MINE:
String user = TwitterApplication.getMyselfId();
String name = TwitterApplication.getMyselfName();
Intent intent = UserTimelineActivity.createIntent(user, name);
goTo(UserTimelineActivity.class, intent);
break;
case PAGE_PROFILE:
goTo(ProfileActivity.class);
break;
case PAGE_FOLLOWERS:
goTo(FollowersActivity.class);
break;
case PAGE_FOLLOWING:
goTo(FollowingActivity.class);
break;
case PAGE_HOME:
goTo(TwitterActivity.class);
break;
case PAGE_MENTIONS:
goTo(MentionActivity.class);
break;
case PAGE_BROWSE:
goTo(BrowseActivity.class);
break;
case PAGE_FAVORITES:
goTo(FavoritesActivity.class);
break;
case PAGE_MESSAGE:
goTo(DmActivity.class);
break;
}
}
});
Button close_button = (Button) findViewById(R.id.close_menu);
close_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/MenuDialog.java | Java | asf20 | 6,885 |
package com.ch_linghu.fanfoudroid.ui.module;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
public class TweetEdit {
private EditText mEditText;
private TextView mCharsRemainText;
private int originTextColor;
public TweetEdit(EditText editText, TextView charsRemainText) {
mEditText = editText;
mCharsRemainText = charsRemainText;
originTextColor = mCharsRemainText.getTextColors().getDefaultColor();
mEditText.addTextChangedListener(mTextWatcher);
mEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
MAX_TWEET_INPUT_LENGTH) });
}
private static final int MAX_TWEET_LENGTH = 140;
private static final int MAX_TWEET_INPUT_LENGTH = 400;
public void setTextAndFocus(String text, boolean start) {
setText(text);
Editable editable = mEditText.getText();
if (!start){
Selection.setSelection(editable, editable.length());
}else{
Selection.setSelection(editable, 0);
}
mEditText.requestFocus();
}
public void setText(String text) {
mEditText.setText(text);
updateCharsRemain();
}
private TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable e) {
updateCharsRemain();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
public void updateCharsRemain() {
int remaining = MAX_TWEET_LENGTH - mEditText.length();
if (remaining < 0 ) {
mCharsRemainText.setTextColor(Color.RED);
} else {
mCharsRemainText.setTextColor(originTextColor);
}
mCharsRemainText.setText(remaining + "");
}
public String getText() {
return mEditText.getText().toString();
}
public void setEnabled(boolean b) {
mEditText.setEnabled(b);
}
public void setOnKeyListener(OnKeyListener listener) {
mEditText.setOnKeyListener(listener);
}
public void addTextChangedListener(TextWatcher watcher){
mEditText.addTextChangedListener(watcher);
}
public void requestFocus() {
mEditText.requestFocus();
}
public EditText getEditText() {
return mEditText;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/TweetEdit.java | Java | asf20 | 2,607 |
package com.ch_linghu.fanfoudroid.ui.module;
public interface Feedback {
public boolean isAvailable();
public void start(CharSequence text);
public void cancel(CharSequence text);
public void success(CharSequence text);
public void failed(CharSequence text);
public void update(Object arg0);
public void setIndeterminate (boolean indeterminate);
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/Feedback.java | Java | asf20 | 377 |
/**
*
*/
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
public class UserCursorAdapter extends CursorAdapter implements TweetAdapter {
private static final String TAG = "TweetCursorAdapter";
private Context mContext;
public UserCursorAdapter(Context context, Cursor cursor) {
super(context, cursor);
mContext = context;
if (context != null) {
mInflater = LayoutInflater.from(context);
}
if (cursor != null) {
mScreenNametColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_USER_SCREEN_NAME);
mUserIdColumn=cursor.getColumnIndexOrThrow(UserInfoTable._ID);
mProfileImageUrlColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_PROFILE_IMAGE_URL);
// mLastStatusColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_LAST_STATUS);
}
mMetaBuilder = new StringBuilder();
}
private LayoutInflater mInflater;
private int mScreenNametColumn;
private int mUserIdColumn;
private int mProfileImageUrlColumn;
//private int mLastStatusColumn;
private StringBuilder mMetaBuilder;
private ImageLoaderCallback callback = new ImageLoaderCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
UserCursorAdapter.this.refresh();
}
};
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.follower_item, parent, false);
Log.d(TAG,"load newView");
UserCursorAdapter.ViewHolder holder = new ViewHolder();
holder.screenName=(TextView) view.findViewById(R.id.screen_name);
holder.profileImage=(ImageView)view.findViewById(R.id.profile_image);
//holder.lastStatus=(TextView) view.findViewById(R.id.last_status);
holder.userId=(TextView) view.findViewById(R.id.user_id);
view.setTag(holder);
return view;
}
private static class ViewHolder {
public TextView screenName;
public TextView userId;
public TextView lastStatus;
public ImageView profileImage;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
UserCursorAdapter.ViewHolder holder = (UserCursorAdapter.ViewHolder) view
.getTag();
Log.d(TAG, "cursor count="+cursor.getCount());
Log.d(TAG,"holder is null?"+(holder==null?"yes":"no"));
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);;
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (useProfileImage){
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, callback));
}
}else{
holder.profileImage.setVisibility(View.GONE);
}
holder.screenName.setText(cursor.getString(mScreenNametColumn));
holder.userId.setText(cursor.getString(mUserIdColumn));
}
@Override
public void refresh() {
getCursor().requery();
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/UserCursorAdapter.java | Java | asf20 | 3,566 |
package com.ch_linghu.fanfoudroid.ui.module;
import com.ch_linghu.fanfoudroid.R;
import android.app.Activity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
/**
* FlingGestureLIstener, 封装 {@link SimpleOnGestureListener} .
* 主要用于识别类似向上下或向左右滑动等基本手势.
*
* 该类主要解决了与ListView自带的上下滑动冲突问题.
* 解决方法为将listView的onTouchListener进行覆盖:<code>
* FlingGestureListener gListener = new FlingGestureListener(this,
* MyActivityFlipper.create(this));
* myListView.setOnTouchListener(gListener);
* </code>
*
* 该类一般和实现了 {@link Widget.OnGestureListener} 接口的类共同协作.
* 在识别到手势后会自动调用其相关的回调方法, 以实现手势触发事件效果.
*
* @see Widget.OnGestureListener
*
*/
public class FlingGestureListener extends SimpleOnGestureListener implements
OnTouchListener {
private static final String TAG = "FlipperGestureListener";
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_DISTANCE = 400;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private Widget.OnGestureListener mListener;
private GestureDetector gDetector;
private Activity activity;
public FlingGestureListener(Activity activity,
Widget.OnGestureListener listener) {
this(activity, listener, null);
}
public FlingGestureListener(Activity activity,
Widget.OnGestureListener listener, GestureDetector gDetector) {
if (gDetector == null) {
gDetector = new GestureDetector(activity, this);
}
this.gDetector = gDetector;
mListener = listener;
this.activity = activity;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
Log.d(TAG, "On fling");
boolean result = super.onFling(e1, e2, velocityX, velocityY);
float xDistance = Math.abs(e1.getX() - e2.getX());
float yDistance = Math.abs(e1.getY() - e2.getY());
velocityX = Math.abs(velocityX);
velocityY = Math.abs(velocityY);
try {
if (xDistance > SWIPE_MAX_DISTANCE
|| yDistance > SWIPE_MAX_DISTANCE) {
Log.d(TAG, "OFF_PATH");
return result;
}
if (velocityX > SWIPE_THRESHOLD_VELOCITY
&& xDistance > SWIPE_MIN_DISTANCE) {
if (e1.getX() > e2.getX()) {
Log.d(TAG, "<------");
result = mListener.onFlingLeft(e1, e1, velocityX, velocityY);
activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
} else {
Log.d(TAG, "------>");
result = mListener.onFlingRight(e1, e1, velocityX, velocityY);
activity.overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
} else if (velocityY > SWIPE_THRESHOLD_VELOCITY
&& yDistance > SWIPE_MIN_DISTANCE) {
if (e1.getY() > e2.getY()) {
Log.d(TAG, "up");
result = mListener.onFlingUp(e1, e1, velocityX, velocityY);
} else {
Log.d(TAG, "down");
result = mListener.onFlingDown(e1, e1, velocityX, velocityY);
}
} else {
Log.d(TAG, "not hint");
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "onFling error " + e.getMessage());
}
return result;
}
@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
super.onLongPress(e);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d(TAG, "On Touch");
// Within the MyGestureListener class you can now manage the
// event.getAction() codes.
// Note that we are now calling the gesture Detectors onTouchEvent.
// And given we've set this class as the GestureDetectors listener
// the onFling, onSingleTap etc methods will be executed.
return gDetector.onTouchEvent(event);
}
public GestureDetector getDetector() {
return gDetector;
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/FlingGestureListener.java | Java | asf20 | 4,636 |
/**
*
*/
package com.ch_linghu.fanfoudroid.ui.module;
import java.text.ParseException;
import java.util.Date;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.app.SimpleImageLoader;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TweetCursorAdapter extends CursorAdapter implements TweetAdapter {
private static final String TAG = "TweetCursorAdapter";
private Context mContext;
public TweetCursorAdapter(Context context, Cursor cursor) {
super(context, cursor);
mContext = context;
if (context != null) {
mInflater = LayoutInflater.from(context);
}
if (cursor != null) {
//TODO: 可使用:
//Tweet tweet = StatusTable.parseCursor(cursor);
mUserTextColumn = cursor
.getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME);
mTextColumn = cursor.getColumnIndexOrThrow(StatusTable.TEXT);
mProfileImageUrlColumn = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
mCreatedAtColumn = cursor
.getColumnIndexOrThrow(StatusTable.CREATED_AT);
mSourceColumn = cursor.getColumnIndexOrThrow(StatusTable.SOURCE);
mInReplyToScreenName = cursor
.getColumnIndexOrThrow(StatusTable.IN_REPLY_TO_SCREEN_NAME);
mFavorited = cursor.getColumnIndexOrThrow(StatusTable.FAVORITED);
mThumbnailPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_THUMB);
mMiddlePic = cursor.getColumnIndexOrThrow(StatusTable.PIC_MID);
mOriginalPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_ORIG);
}
mMetaBuilder = new StringBuilder();
}
private LayoutInflater mInflater;
private int mUserTextColumn;
private int mTextColumn;
private int mProfileImageUrlColumn;
private int mCreatedAtColumn;
private int mSourceColumn;
private int mInReplyToScreenName;
private int mFavorited;
private int mThumbnailPic;
private int mMiddlePic;
private int mOriginalPic;
private StringBuilder mMetaBuilder;
/*
private ProfileImageCacheCallback callback = new ProfileImageCacheCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
TweetCursorAdapter.this.refresh();
}
};
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.tweet, parent, false);
TweetCursorAdapter.ViewHolder holder = new ViewHolder();
holder.tweetUserText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view.findViewById(R.id.profile_image);
holder.metaText = (TextView) view.findViewById(R.id.tweet_meta_text);
holder.fav = (ImageView) view.findViewById(R.id.tweet_fav);
holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image);
view.setTag(holder);
return view;
}
private static class ViewHolder {
public TextView tweetUserText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
public ImageView fav;
public ImageView has_image;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TweetCursorAdapter.ViewHolder holder = (TweetCursorAdapter.ViewHolder) view
.getTag();
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);;
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
holder.tweetUserText.setText(cursor.getString(mUserTextColumn));
TextHelper.setSimpleTweetText(holder.tweetText, cursor.getString(mTextColumn));
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (useProfileImage && !TextUtils.isEmpty(profileImageUrl)) {
SimpleImageLoader.display(holder.profileImage, profileImageUrl);
} else {
holder.profileImage.setVisibility(View.GONE);
}
if (cursor.getString(mFavorited).equals("true")) {
holder.fav.setVisibility(View.VISIBLE);
} else {
holder.fav.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(cursor.getString(mThumbnailPic))) {
holder.has_image.setVisibility(View.VISIBLE);
} else {
holder.has_image.setVisibility(View.GONE);
}
try {
Date createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor
.getString(mCreatedAtColumn));
holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder,
createdAt, cursor.getString(mSourceColumn), cursor
.getString(mInReplyToScreenName)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
}
@Override
public void refresh() {
getCursor().requery();
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/ui/module/TweetCursorAdapter.java | Java | asf20 | 5,303 |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* This broadcast receiver is awoken after boot and registers the service that
* checks for new tweets.
*/
public class BootReceiver extends BroadcastReceiver {
private static final String TAG = "BootReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Twitta BootReceiver is receiving.");
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
TwitterService.schedule(context);
}
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/service/BootReceiver.java | Java | asf20 | 1,245 |
package com.ch_linghu.fanfoudroid.service;
import java.util.List;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
/**
* Location Service
*
* AndroidManifest.xml <code>
* <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
* </code>
*
* TODO: 使用DDMS对模拟器GPS位置进行更新时, 会造成死机现象
*
*/
public class LocationService implements IService {
private static final String TAG = "LocationService";
private LocationManager mLocationManager;
private LocationListener mLocationListener = new MyLocationListener();
private String mLocationProvider;
private boolean running = false;
public LocationService(Context context) {
initLocationManager(context);
}
private void initLocationManager(Context context) {
// Acquire a reference to the system Location Manager
mLocationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
mLocationProvider = mLocationManager.getBestProvider(new Criteria(),
false);
}
public void startService() {
if (!running) {
Log.v(TAG, "START LOCATION SERVICE, PROVIDER:" + mLocationProvider);
running = true;
mLocationManager.requestLocationUpdates(mLocationProvider, 0, 0,
mLocationListener);
}
}
public void stopService() {
if (running) {
Log.v(TAG, "STOP LOCATION SERVICE");
running = false;
mLocationManager.removeUpdates(mLocationListener);
}
}
/**
* @return the last known location for the provider, or null
*/
public Location getLastKnownLocation() {
return mLocationManager.getLastKnownLocation(mLocationProvider);
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.v(TAG, "LOCATION CHANGED TO: " + location.toString());
}
@Override
public void onProviderDisabled(String provider) {
Log.v(TAG, "PROVIDER DISABLED " + provider);
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
Log.v(TAG, "PROVIDER ENABLED " + provider);
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.v(TAG, "STATUS CHANGED: " + provider + " " + status);
}
}
// Only for debug
public void logAllProviders() {
// List all providers:
List<String> providers = mLocationManager.getAllProviders();
Log.v(TAG, "LIST ALL PROVIDERS:");
for (String provider : providers) {
boolean isEnabled = mLocationManager.isProviderEnabled(provider);
Log.v(TAG, "Provider " + provider + ": " + isEnabled);
}
}
// only for debug
public static LocationService test(Context context) {
LocationService ls = new LocationService(context);
ls.startService();
ls.logAllProviders();
Location local = ls.getLastKnownLocation();
if (local != null) {
Log.v("LDS", ls.getLastKnownLocation().toString());
}
return ls;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/service/LocationService.java | Java | asf20 | 3,675 |
package com.ch_linghu.fanfoudroid.service;
public interface IService {
void startService();
void stopService();
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/service/IService.java | Java | asf20 | 123 |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid.service;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.FanfouWidget;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TwitterService extends Service {
private static final String TAG = "TwitterService";
private NotificationManager mNotificationManager;
private ArrayList<Tweet> mNewTweets;
private ArrayList<Tweet> mNewMentions;
private ArrayList<Dm> mNewDms;
private GenericTask mRetrieveTask;
public String getUserId() {
return TwitterApplication.getMyselfId();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// fetchMessages();
// handler.postDelayed(mTask, 10000);
Log.d(TAG, "Start Once");
return super.onStartCommand(intent, flags, startId);
}
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences preferences = TwitterApplication.mPref;
boolean needCheck = preferences.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
boolean timeline_only = preferences.getBoolean(
Preferences.TIMELINE_ONLY_KEY, false);
boolean replies_only = preferences.getBoolean(
Preferences.REPLIES_ONLY_KEY, true);
boolean dm_only = preferences.getBoolean(
Preferences.DM_ONLY_KEY, true);
if (needCheck) {
if (timeline_only) {
processNewTweets();
}
if (replies_only) {
processNewMentions();
}
if (dm_only) {
processNewDms();
}
}
}
try {
Intent intent = new Intent(TwitterService.this,
FanfouWidget.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
PendingIntent pi = PendingIntent.getBroadcast(
TwitterService.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
pi.send();
} catch (CanceledException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
stopSelf();
}
@Override
public String getName() {
return "ServiceRetrieveTask";
}
};
private WakeLock mWakeLock;
@Override
public IBinder onBind(Intent intent) {
return null;
}
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
private Weibo getApi() {
return TwitterApplication.mApi;
}
@Override
public void onCreate() {
Log.v(TAG, "Server Created");
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
mWakeLock.acquire();
boolean needCheck = TwitterApplication.mPref.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
boolean widgetIsEnabled = TwitterService.widgetIsEnabled;
Log.v(TAG, "Check Updates is " + needCheck + "/wg:" + widgetIsEnabled);
if (!needCheck && !widgetIsEnabled) {
Log.d(TAG, "Check update preference is false.");
stopSelf();
return;
}
if (!getApi().isLoggedIn()) {
Log.d(TAG, "Not logged in.");
stopSelf();
return;
}
schedule(TwitterService.this);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNewTweets = new ArrayList<Tweet>();
mNewMentions = new ArrayList<Tweet>();
mNewDms = new ArrayList<Dm>();
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute((TaskParams[]) null);
}
}
private void processNewTweets() {
int count = mNewTweets.size();
if (count <= 0) {
return;
}
Tweet latestTweet = mNewTweets.get(0);
String title;
String text;
if (count == 1) {
title = latestTweet.screenName;
text = TextHelper.getSimpleTweetText(latestTweet.text);
} else {
title = getString(R.string.service_new_twitter_updates);
text = getString(R.string.service_x_new_tweets);
text = MessageFormat.format(text, count);
}
PendingIntent intent = PendingIntent.getActivity(this, 0,
TwitterActivity.createIntent(this), 0);
notify(intent, TWEET_NOTIFICATION_ID, R.drawable.notify_tweet,
TextHelper.getSimpleTweetText(latestTweet.text), title, text);
}
private void processNewMentions() {
int count = mNewMentions.size();
if (count <= 0) {
return;
}
Tweet latestTweet = mNewMentions.get(0);
String title;
String text;
if (count == 1) {
title = latestTweet.screenName;
text = TextHelper.getSimpleTweetText(latestTweet.text);
} else {
title = getString(R.string.service_new_mention_updates);
text = getString(R.string.service_x_new_mentions);
text = MessageFormat.format(text, count);
}
PendingIntent intent = PendingIntent.getActivity(this, 0,
MentionActivity.createIntent(this), 0);
notify(intent, MENTION_NOTIFICATION_ID, R.drawable.notify_mention,
TextHelper.getSimpleTweetText(latestTweet.text), title, text);
}
private static int TWEET_NOTIFICATION_ID = 0;
private static int DM_NOTIFICATION_ID = 1;
private static int MENTION_NOTIFICATION_ID = 2;
private void notify(PendingIntent intent, int notificationId,
int notifyIconId, String tickerText, String title, String text) {
Notification notification = new Notification(notifyIconId, tickerText,
System.currentTimeMillis());
notification.setLatestEventInfo(this, title, text, intent);
notification.flags = Notification.FLAG_AUTO_CANCEL
| Notification.FLAG_ONLY_ALERT_ONCE
| Notification.FLAG_SHOW_LIGHTS;
notification.ledARGB = 0xFF84E4FA;
notification.ledOnMS = 5000;
notification.ledOffMS = 5000;
String ringtoneUri = TwitterApplication.mPref.getString(
Preferences.RINGTONE_KEY, null);
if (ringtoneUri == null) {
notification.defaults |= Notification.DEFAULT_SOUND;
} else {
notification.sound = Uri.parse(ringtoneUri);
}
if (TwitterApplication.mPref.getBoolean(Preferences.VIBRATE_KEY, false)) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
mNotificationManager.notify(notificationId, notification);
}
private void processNewDms() {
int count = mNewDms.size();
if (count <= 0) {
return;
}
Dm latest = mNewDms.get(0);
String title;
String text;
if (count == 1) {
title = latest.screenName;
text = TextHelper.getSimpleTweetText(latest.text);
} else {
title = getString(R.string.service_new_direct_message_updates);
text = getString(R.string.service_x_new_direct_messages);
text = MessageFormat.format(text, count);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
DmActivity.createIntent(), 0);
notify(pendingIntent, DM_NOTIFICATION_ID, R.drawable.notify_dm,
TextHelper.getSimpleTweetText(latest.text), title, text);
}
@Override
public void onDestroy() {
Log.d(TAG, "Service Destroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
mWakeLock.release();
super.onDestroy();
}
public static void schedule(Context context) {
SharedPreferences preferences = TwitterApplication.mPref;
boolean needCheck = preferences.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
boolean widgetIsEnabled = TwitterService.widgetIsEnabled;
if (!needCheck && !widgetIsEnabled) {
Log.d(TAG, "Check update preference is false.");
return;
}
String intervalPref = preferences
.getString(
Preferences.CHECK_UPDATE_INTERVAL_KEY,
context.getString(R.string.pref_check_updates_interval_default));
int interval = Integer.parseInt(intervalPref);
// interval = 1; //for debug
Intent intent = new Intent(context, TwitterService.class);
PendingIntent pending = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar c = new GregorianCalendar();
c.add(Calendar.MINUTE, interval);
DateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
Log.d(TAG, "Schedule, next run at " + df.format(c.getTime()));
AlarmManager alarm = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
if (needCheck) {
alarm.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pending);
} else {
// only for widget
alarm.set(AlarmManager.RTC, c.getTimeInMillis(), pending);
}
}
public static void unschedule(Context context) {
Intent intent = new Intent(context, TwitterService.class);
PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
AlarmManager alarm = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Log.d(TAG, "Cancelling alarms.");
alarm.cancel(pending);
}
private static boolean widgetIsEnabled = false;
public static void setWidgetStatus(boolean isEnabled) {
widgetIsEnabled = isEnabled;
}
public static boolean isWidgetEnabled() {
return widgetIsEnabled;
}
private class RetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
SharedPreferences preferences = TwitterApplication.mPref;
boolean timeline_only = preferences.getBoolean(
Preferences.TIMELINE_ONLY_KEY, false);
boolean replies_only = preferences.getBoolean(
Preferences.REPLIES_ONLY_KEY, true);
boolean dm_only = preferences.getBoolean(Preferences.DM_ONLY_KEY,
true);
Log.d(TAG, "Widget Is Enabled? " + TwitterService.widgetIsEnabled);
if (timeline_only || TwitterService.widgetIsEnabled) {
String maxId = getDb()
.fetchMaxTweetId(TwitterApplication.getMyselfId(),
StatusTable.TYPE_HOME);
Log.d(TAG, "Max id is:" + maxId);
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
if (maxId != null) {
statusList = getApi().getFriendsTimeline(
new Paging(maxId));
} else {
statusList = getApi().getFriendsTimeline();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mNewTweets.add(tweet);
Log.d(TAG, mNewTweets.size() + " new tweets.");
int count = getDb().addNewTweetsAndCountUnread(mNewTweets,
TwitterApplication.getMyselfId(),
StatusTable.TYPE_HOME);
if (count <= 0) {
return TaskResult.FAILED;
}
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
if (replies_only) {
String maxMentionId = getDb().fetchMaxTweetId(
TwitterApplication.getMyselfId(),
StatusTable.TYPE_MENTION);
Log.d(TAG, "Max mention id is:" + maxMentionId);
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
if (maxMentionId != null) {
statusList = getApi().getMentions(
new Paging(maxMentionId));
} else {
statusList = getApi().getMentions();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
int unReadMentionsCount = 0;
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet = Tweet.create(status);
mNewMentions.add(tweet);
unReadMentionsCount = getDb().addNewTweetsAndCountUnread(
mNewMentions, TwitterApplication.getMyselfId(),
StatusTable.TYPE_MENTION);
if (unReadMentionsCount <= 0) {
return TaskResult.FAILED;
}
}
Log.v(TAG, "Got mentions " + unReadMentionsCount + "/"
+ mNewMentions.size());
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
if (dm_only) {
String maxId = getDb().fetchMaxDmId(false);
Log.d(TAG, "Max DM id is:" + maxId);
List<com.ch_linghu.fanfoudroid.fanfou.DirectMessage> dmList;
try {
if (maxId != null) {
dmList = getApi().getDirectMessages(new Paging(maxId));
} else {
dmList = getApi().getDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (com.ch_linghu.fanfoudroid.fanfou.DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, false);
mNewDms.add(dm);
Log.d(TAG, mNewDms.size() + " new DMs.");
int count = 0;
TwitterDatabase db = getDb();
if (db.fetchDmCount() > 0) {
count = db.addNewDmsAndCountUnread(mNewDms);
} else {
Log.d(TAG, "No existing DMs. Don't notify.");
db.addDms(mNewDms, false);
}
if (count <= 0) {
return TaskResult.FAILED;
}
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
return TaskResult.OK;
}
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/service/TwitterService.java | Java | asf20 | 19,229 |