PageRenderTime 72ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 1ms

/scss.inc.php

https://bitbucket.org/Pathou/template
PHP | 3759 lines | 3079 code | 565 blank | 115 comment | 633 complexity | 4ea5a15e81cc8d4b90a4177aaf6f3605 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // http://leafo.net/scssphp/docs/
  3. class scssc {
  4. static public $VERSION = "v0.0.4";
  5. static protected $operatorNames = array(
  6. '+' => "add",
  7. '-' => "sub",
  8. '*' => "mul",
  9. '/' => "div",
  10. '%' => "mod",
  11. '==' => "eq",
  12. '!=' => "neq",
  13. '<' => "lt",
  14. '>' => "gt",
  15. '<=' => "lte",
  16. '>=' => "gte",
  17. );
  18. static protected $namespaces = array(
  19. "special" => "%",
  20. "mixin" => "@",
  21. "function" => "^",
  22. );
  23. static protected $numberPrecision = 3;
  24. static protected $unitTable = array(
  25. "in" => array(
  26. "in" => 1,
  27. "pt" => 72,
  28. "pc" => 6,
  29. "cm" => 2.54,
  30. "mm" => 25.4,
  31. "px" => 96,
  32. )
  33. );
  34. static public $true = array("keyword", "true");
  35. static public $false = array("keyword", "false");
  36. static public $defaultValue = array("keyword", "");
  37. static public $selfSelector = array("self");
  38. protected $importPaths = array("");
  39. protected $importCache = array();
  40. protected $userFunctions = array();
  41. protected $formatter = "scss_formatter_nested";
  42. function compile($code, $name=null) {
  43. $this->indentLevel = -1;
  44. $this->commentsSeen = array();
  45. $this->extends = array();
  46. $this->extendsMap = array();
  47. $locale = setlocale(LC_NUMERIC, 0);
  48. setlocale(LC_NUMERIC, "C");
  49. $this->parsedFiles = array();
  50. $this->parser = new scss_parser($name);
  51. $tree = $this->parser->parse($code);
  52. $this->formatter = new $this->formatter();
  53. $this->env = null;
  54. $this->scope = null;
  55. $this->compileRoot($tree);
  56. $this->flattenSelectors($this->scope);
  57. ob_start();
  58. $this->formatter->block($this->scope);
  59. $out = ob_get_clean();
  60. setlocale(LC_NUMERIC, $locale);
  61. return $out;
  62. }
  63. protected function pushExtends($target, $origin) {
  64. $i = count($this->extends);
  65. $this->extends[] = array($target, $origin);
  66. foreach ($target as $part) {
  67. if (isset($this->extendsMap[$part])) {
  68. $this->extendsMap[$part][] = $i;
  69. } else {
  70. $this->extendsMap[$part] = array($i);
  71. }
  72. }
  73. }
  74. protected function makeOutputBlock($type, $selectors = null) {
  75. $out = new stdclass;
  76. $out->type = $type;
  77. $out->lines = array();
  78. $out->children = array();
  79. $out->parent = $this->scope;
  80. $out->selectors = $selectors;
  81. $out->depth = $this->env->depth;
  82. return $out;
  83. }
  84. protected function matchExtendsSingle($single, &$out_origin, &$out_rem) {
  85. $counts = array();
  86. foreach ($single as $part) {
  87. if (!is_string($part)) return false; // hmm
  88. if (isset($this->extendsMap[$part])) {
  89. foreach ($this->extendsMap[$part] as $idx) {
  90. $counts[$idx] =
  91. isset($counts[$idx]) ? $counts[$idx] + 1 : 1;
  92. }
  93. }
  94. }
  95. foreach ($counts as $idx => $count) {
  96. list($target, $origin) = $this->extends[$idx];
  97. // check count
  98. if ($count != count($target)) continue;
  99. // check if target is subset of single
  100. if (array_diff(array_intersect($single, $target), $target)) continue;
  101. $out_origin = $origin;
  102. $out_rem = array_diff($single, $target);
  103. return true;
  104. }
  105. return false;
  106. }
  107. protected function combineSelectorSingle($base, $other) {
  108. $tag = null;
  109. $out = array();
  110. foreach (array($base, $other) as $single) {
  111. foreach ($single as $part) {
  112. if (preg_match('/^[^.#:]/', $part)) {
  113. $tag = $part;
  114. } else {
  115. $out[] = $part;
  116. }
  117. }
  118. }
  119. if ($tag) {
  120. array_unshift($out, $tag);
  121. }
  122. return $out;
  123. }
  124. protected function matchExtends($selector, &$out, $from = 0, $initial=true) {
  125. foreach ($selector as $i => $part) {
  126. if ($i < $from) continue;
  127. if ($this->matchExtendsSingle($part, $origin, $rem)) {
  128. $before = array_slice($selector, 0, $i);
  129. $after = array_slice($selector, $i + 1);
  130. foreach ($origin as $new) {
  131. $new[count($new) - 1] =
  132. $this->combineSelectorSingle(end($new), $rem);
  133. $k = 0;
  134. // remove shared parts
  135. if ($initial) {
  136. foreach ($before as $k => $val) {
  137. if (!isset($new[$k]) || $val != $new[$k]) {
  138. break;
  139. }
  140. }
  141. }
  142. $result = array_merge(
  143. $before,
  144. $k > 0 ? array_slice($new, $k) : $new,
  145. $after);
  146. if ($result == $selector) continue;
  147. $out[] = $result;
  148. // recursively check for more matches
  149. $this->matchExtends($result, $out, $i, false);
  150. // selector sequence merging
  151. if (!empty($before) && count($new) > 1) {
  152. $result2 = array_merge(
  153. array_slice($new, 0, -1),
  154. $k > 0 ? array_slice($before, $k) : $before,
  155. array_slice($new, -1),
  156. $after);
  157. $out[] = $result2;
  158. }
  159. }
  160. }
  161. }
  162. }
  163. protected function flattenSelectors($block) {
  164. if ($block->selectors) {
  165. $selectors = array();
  166. foreach ($block->selectors as $s) {
  167. $selectors[] = $s;
  168. if (!is_array($s)) continue;
  169. // check extends
  170. if (!empty($this->extendsMap)) {
  171. $this->matchExtends($s, $selectors);
  172. }
  173. }
  174. $selectors = array_map(array($this, "compileSelector"), $selectors);
  175. $block->selectors = $selectors;
  176. }
  177. foreach ($block->children as $child) {
  178. $this->flattenSelectors($child);
  179. }
  180. }
  181. protected function compileRoot($rootBlock) {
  182. $this->pushEnv($rootBlock);
  183. $this->scope = $this->makeOutputBlock("root");
  184. $this->compileChildren($rootBlock->children, $this->scope);
  185. $this->popEnv();
  186. }
  187. protected function compileMedia($media) {
  188. $this->pushEnv($media);
  189. $parentScope = $this->mediaParent($this->scope);
  190. $this->scope = $this->makeOutputBlock("media", array(
  191. $this->compileMediaQuery($this->multiplyMedia($this->env)))
  192. );
  193. $parentScope->children[] = $this->scope;
  194. $this->compileChildren($media->children, $this->scope);
  195. $this->scope = $this->scope->parent;
  196. $this->popEnv();
  197. }
  198. protected function mediaParent($scope) {
  199. while (!empty($scope->parent)) {
  200. if (!empty($scope->type) && $scope->type != "media") {
  201. break;
  202. }
  203. $scope = $scope->parent;
  204. }
  205. return $scope;
  206. }
  207. // TODO refactor compileNestedBlock and compileMedia into same thing
  208. protected function compileNestedBlock($block, $selectors) {
  209. $this->pushEnv($block);
  210. $this->scope = $this->makeOutputBlock($block->type, $selectors);
  211. $this->scope->parent->children[] = $this->scope;
  212. $this->compileChildren($block->children, $this->scope);
  213. $this->scope = $this->scope->parent;
  214. $this->popEnv();
  215. }
  216. protected function compileBlock($block) {
  217. $env = $this->pushEnv($block);
  218. $env->selectors =
  219. array_map(array($this, "evalSelector"), $block->selectors);
  220. $out = $this->makeOutputBlock(null, $this->multiplySelectors($env));
  221. $this->scope->children[] = $out;
  222. $this->compileChildren($block->children, $out);
  223. $this->popEnv();
  224. }
  225. // joins together .classes and #ids
  226. protected function flattenSelectorSingle($single) {
  227. $joined = array();
  228. foreach ($single as $part) {
  229. if (empty($joined) ||
  230. !is_string($part) ||
  231. preg_match('/[.:#]/', $part))
  232. {
  233. $joined[] = $part;
  234. continue;
  235. }
  236. if (is_array(end($joined))) {
  237. $joined[] = $part;
  238. } else {
  239. $joined[count($joined) - 1] .= $part;
  240. }
  241. }
  242. return $joined;
  243. }
  244. // replaces all the interpolates
  245. protected function evalSelector($selector) {
  246. return array_map(array($this, "evalSelectorPart"), $selector);
  247. }
  248. protected function evalSelectorPart($piece) {
  249. foreach ($piece as &$p) {
  250. if (!is_array($p)) continue;
  251. switch ($p[0]) {
  252. case "interpolate":
  253. $p = $this->compileValue($p);
  254. break;
  255. }
  256. }
  257. return $this->flattenSelectorSingle($piece);
  258. }
  259. // compiles to string
  260. // self(&) should have been replaced by now
  261. protected function compileSelector($selector) {
  262. if (!is_array($selector)) return $selector; // media and the like
  263. return implode(" ", array_map(
  264. array($this, "compileSelectorPart"), $selector));
  265. }
  266. protected function compileSelectorPart($piece) {
  267. foreach ($piece as &$p) {
  268. if (!is_array($p)) continue;
  269. switch ($p[0]) {
  270. case "self":
  271. $p = "&";
  272. break;
  273. default:
  274. $p = $this->compileValue($p);
  275. break;
  276. }
  277. }
  278. return implode($piece);
  279. }
  280. protected function compileChildren($stms, $out) {
  281. foreach ($stms as $stm) {
  282. $ret = $this->compileChild($stm, $out);
  283. if (!is_null($ret)) return $ret;
  284. }
  285. }
  286. protected function compileMediaQuery($queryList) {
  287. $out = "@media";
  288. $first = true;
  289. foreach ($queryList as $query){
  290. $parts = array();
  291. foreach ($query as $q) {
  292. switch ($q[0]) {
  293. case "mediaType":
  294. $parts[] = implode(" ", array_slice($q, 1));
  295. break;
  296. case "mediaExp":
  297. if (isset($q[2])) {
  298. $parts[] = "($q[1]" . $this->formatter->assignSeparator . $this->compileValue($q[2]) . ")";
  299. } else {
  300. $parts[] = "($q[1])";
  301. }
  302. break;
  303. }
  304. }
  305. if (!empty($parts)) {
  306. if ($first) {
  307. $first = false;
  308. $out .= " ";
  309. } else {
  310. $out .= $this->formatter->tagSeparator;
  311. }
  312. $out .= implode(" and ", $parts);
  313. }
  314. }
  315. return $out;
  316. }
  317. // returns true if the value was something that could be imported
  318. protected function compileImport($rawPath, $out) {
  319. if ($rawPath[0] == "string") {
  320. $path = $this->compileStringContent($rawPath);
  321. if ($path = $this->findImport($path)) {
  322. $this->importFile($path, $out);
  323. return true;
  324. }
  325. return false;
  326. } if ($rawPath[0] == "list") {
  327. // handle a list of strings
  328. if (count($rawPath[2]) == 0) return false;
  329. foreach ($rawPath[2] as $path) {
  330. if ($path[0] != "string") return false;
  331. }
  332. foreach ($rawPath[2] as $path) {
  333. $this->compileImport($path, $out);
  334. }
  335. return true;
  336. }
  337. return false;
  338. }
  339. // return a value to halt execution
  340. protected function compileChild($child, $out) {
  341. switch ($child[0]) {
  342. case "import":
  343. list(,$rawPath) = $child;
  344. $rawPath = $this->reduce($rawPath);
  345. if (!$this->compileImport($rawPath, $out)) {
  346. $out->lines[] = "@import " . $this->compileValue($rawPath) . ";";
  347. }
  348. break;
  349. case "directive":
  350. list(, $directive) = $child;
  351. $s = "@" . $directive->name;
  352. if (!empty($directive->value)) {
  353. $s .= " " . $this->compileValue($directive->value);
  354. }
  355. $this->compileNestedBlock($directive, array($s));
  356. break;
  357. case "media":
  358. $this->compileMedia($child[1]);
  359. break;
  360. case "block":
  361. $this->compileBlock($child[1]);
  362. break;
  363. case "charset":
  364. $out->lines[] = "@charset ".$this->compileValue($child[1]).";";
  365. break;
  366. case "assign":
  367. list(,$name, $value) = $child;
  368. if ($name[0] == "var") {
  369. $isDefault = !empty($child[3]);
  370. if (!$isDefault || $this->get($name[1], true) === true) {
  371. $this->set($name[1], $this->reduce($value));
  372. }
  373. break;
  374. }
  375. $out->lines[] = $this->formatter->property(
  376. $this->compileValue($child[1]),
  377. $this->compileValue($child[2]));
  378. break;
  379. case "comment":
  380. $out->lines[] = $child[1];
  381. break;
  382. case "mixin":
  383. case "function":
  384. list(,$block) = $child;
  385. $this->set(self::$namespaces[$block->type] . $block->name, $block);
  386. break;
  387. case "extend":
  388. list(, $selectors) = $child;
  389. foreach ($selectors as $sel) {
  390. // only use the first one
  391. $sel = current($this->evalSelector($sel));
  392. $this->pushExtends($sel, $out->selectors);
  393. }
  394. break;
  395. case "if":
  396. list(, $if) = $child;
  397. if ($this->reduce($if->cond, true) != self::$false) {
  398. return $this->compileChildren($if->children, $out);
  399. } else {
  400. foreach ($if->cases as $case) {
  401. if ($case->type == "else" ||
  402. $case->type == "elseif" && ($this->reduce($case->cond) != self::$false))
  403. {
  404. return $this->compileChildren($case->children, $out);
  405. }
  406. }
  407. }
  408. break;
  409. case "return":
  410. return $this->reduce($child[1], true);
  411. case "each":
  412. list(,$each) = $child;
  413. $list = $this->reduce($this->coerceList($each->list));
  414. foreach ($list[2] as $item) {
  415. $this->pushEnv();
  416. $this->set($each->var, $item);
  417. // TODO: allow return from here
  418. $this->compileChildren($each->children, $out);
  419. $this->popEnv();
  420. }
  421. break;
  422. case "while":
  423. list(,$while) = $child;
  424. while ($this->reduce($while->cond, true) != self::$false) {
  425. $ret = $this->compileChildren($while->children, $out);
  426. if ($ret) return $ret;
  427. }
  428. break;
  429. case "for":
  430. list(,$for) = $child;
  431. $start = $this->reduce($for->start, true);
  432. $start = $start[1];
  433. $end = $this->reduce($for->end, true);
  434. $end = $end[1];
  435. $d = $start < $end ? 1 : -1;
  436. while (true) {
  437. if ((!$for->until && $start - $d == $end) ||
  438. ($for->until && $start == $end))
  439. {
  440. break;
  441. }
  442. $this->set($for->var, array("number", $start, ""));
  443. $start += $d;
  444. $ret = $this->compileChildren($for->children, $out);
  445. if ($ret) return $ret;
  446. }
  447. break;
  448. case "nestedprop":
  449. list(,$prop) = $child;
  450. $prefixed = array();
  451. $prefix = $this->compileValue($prop->prefix) . "-";
  452. foreach ($prop->children as $child) {
  453. if ($child[0] == "assign") {
  454. array_unshift($child[1][2], $prefix);
  455. }
  456. if ($child[0] == "nestedprop") {
  457. array_unshift($child[1]->prefix[2], $prefix);
  458. }
  459. $prefixed[] = $child;
  460. }
  461. $this->compileChildren($prefixed, $out);
  462. break;
  463. case "include": // including a mixin
  464. list(,$name, $argValues, $content) = $child;
  465. $mixin = $this->get(self::$namespaces["mixin"] . $name, false);
  466. if (!$mixin) break; // throw error?
  467. $callingScope = $this->env;
  468. // push scope, apply args
  469. $this->pushEnv();
  470. if (!is_null($content)) {
  471. $content->scope = $callingScope;
  472. $this->setRaw(self::$namespaces["special"] . "content", $content);
  473. }
  474. if (!is_null($mixin->args)) {
  475. $this->applyArguments($mixin->args, $argValues);
  476. }
  477. foreach ($mixin->children as $child) {
  478. $this->compileChild($child, $out);
  479. }
  480. $this->popEnv();
  481. break;
  482. case "mixin_content":
  483. $content = $this->get(self::$namespaces["special"] . "content");
  484. if (is_null($content)) {
  485. throw new Exception("Unexpected @content inside of mixin");
  486. }
  487. $this->storeEnv = $content->scope;
  488. foreach ($content->children as $child) {
  489. $this->compileChild($child, $out);
  490. }
  491. unset($this->storeEnv);
  492. break;
  493. case "debug":
  494. list(,$value, $pos) = $child;
  495. $line = $this->parser->getLineNo($pos);
  496. $value = $this->compileValue($this->reduce($value, true));
  497. fwrite(STDERR, "Line $line DEBUG: $value\n");
  498. break;
  499. default:
  500. throw new exception("unknown child type: $child[0]");
  501. }
  502. }
  503. protected function expToString($exp) {
  504. list(, $op, $left, $right, $inParens, $whiteLeft, $whiteRight) = $exp;
  505. $content = array($left);
  506. if ($whiteLeft) $content[] = " ";
  507. $content[] = $op;
  508. if ($whiteRight) $content[] = " ";
  509. $content[] = $right;
  510. return array("string", "", $content);
  511. }
  512. // should $value cause its operand to eval
  513. protected function shouldEval($value) {
  514. switch ($value[0]) {
  515. case "exp":
  516. if ($value[1] == "/") {
  517. return $this->shouldEval($value[2], $value[3]);
  518. }
  519. case "var":
  520. case "fncall":
  521. return true;
  522. }
  523. return false;
  524. }
  525. protected function reduce($value, $inExp = false) {
  526. list($type) = $value;
  527. switch ($type) {
  528. case "exp":
  529. list(, $op, $left, $right, $inParens) = $value;
  530. $opName = isset(self::$operatorNames[$op]) ? self::$operatorNames[$op] : $op;
  531. $inExp = $inExp || $this->shouldEval($left) || $this->shouldEval($right);
  532. $left = $this->reduce($left, true);
  533. $right = $this->reduce($right, true);
  534. // only do division in special cases
  535. if ($opName == "div" && !$inParens && !$inExp) {
  536. if ($left[0] != "color" && $right[0] != "color") {
  537. return $this->expToString($value);
  538. }
  539. }
  540. $left = $this->coerceForExpression($left);
  541. $right = $this->coerceForExpression($right);
  542. $ltype = $left[0];
  543. $rtype = $right[0];
  544. // this tries:
  545. // 1. op_[op name]_[left type]_[right type]
  546. // 2. op_[left type]_[right type] (passing the op as first arg
  547. // 3. op_[op name]
  548. $fn = "op_${opName}_${ltype}_${rtype}";
  549. if (is_callable(array($this, $fn)) ||
  550. (($fn = "op_${ltype}_${rtype}") &&
  551. is_callable(array($this, $fn)) &&
  552. $passOp = true) ||
  553. (($fn = "op_${opName}") &&
  554. is_callable(array($this, $fn)) &&
  555. $genOp = true))
  556. {
  557. $unitChange = false;
  558. if (!isset($genOp) &&
  559. $left[0] == "number" && $right[0] == "number")
  560. {
  561. if ($opName == "mod" && $right[2] != "") {
  562. throw new Exception(sprintf('Cannot modulo by a number with units: %s%s.', $right[1], $right[2]));
  563. }
  564. $unitChange = true;
  565. $emptyUnit = $left[2] == "" || $right[2] == "";
  566. $targetUnit = "" != $left[2] ? $left[2] : $right[2];
  567. if ($opName != "mul") {
  568. $left[2] = "" != $left[2] ? $left[2] : $targetUnit;
  569. $right[2] = "" != $right[2] ? $right[2] : $targetUnit;
  570. }
  571. if ($opName != "mod") {
  572. $left = $this->normalizeNumber($left);
  573. $right = $this->normalizeNumber($right);
  574. }
  575. if ($opName == "div" && !$emptyUnit && $left[2] == $right[2]) {
  576. $targetUnit = "";
  577. }
  578. if ($opName == "mul") {
  579. $left[2] = "" != $left[2] ? $left[2] : $right[2];
  580. $right[2] = "" != $right[2] ? $right[2] : $left[2];
  581. } elseif ($opName == "div" && $left[2] == $right[2]) {
  582. $left[2] = "";
  583. $right[2] = "";
  584. }
  585. }
  586. $shouldEval = $inParens || $inExp;
  587. if (isset($passOp)) {
  588. $out = $this->$fn($op, $left, $right, $shouldEval);
  589. } else {
  590. $out = $this->$fn($left, $right, $shouldEval);
  591. }
  592. if (!is_null($out)) {
  593. if ($unitChange && $out[0] == "number") {
  594. $out = $this->coerceUnit($out, $targetUnit);
  595. }
  596. return $out;
  597. }
  598. }
  599. return $this->expToString($value);
  600. case "unary":
  601. list(, $op, $exp, $inParens) = $value;
  602. $inExp = $inExp || $this->shouldEval($exp);
  603. $exp = $this->reduce($exp);
  604. if ($exp[0] == "number") {
  605. switch ($op) {
  606. case "+":
  607. return $exp;
  608. case "-":
  609. $exp[1] *= -1;
  610. return $exp;
  611. }
  612. }
  613. if ($op == "not") {
  614. if ($inExp || $inParens) {
  615. if ($exp == self::$false) {
  616. return self::$true;
  617. } else {
  618. return self::$false;
  619. }
  620. } else {
  621. $op = $op . " ";
  622. }
  623. }
  624. return array("string", "", array($op, $exp));
  625. case "var":
  626. list(, $name) = $value;
  627. return $this->reduce($this->get($name));
  628. case "list":
  629. foreach ($value[2] as &$item) {
  630. $item = $this->reduce($item);
  631. }
  632. return $value;
  633. case "string":
  634. foreach ($value[2] as &$item) {
  635. if (is_array($item)) {
  636. $item = $this->reduce($item);
  637. }
  638. }
  639. return $value;
  640. case "interpolate":
  641. $value[1] = $this->reduce($value[1]);
  642. return $value;
  643. case "fncall":
  644. list(,$name, $argValues) = $value;
  645. // user defined function?
  646. $func = $this->get(self::$namespaces["function"] . $name, false);
  647. if ($func) {
  648. $this->pushEnv();
  649. // set the args
  650. if (isset($func->args)) {
  651. $this->applyArguments($func->args, $argValues);
  652. }
  653. // throw away lines and children
  654. $tmp = (object)array(
  655. "lines" => array(),
  656. "children" => array()
  657. );
  658. $ret = $this->compileChildren($func->children, $tmp);
  659. $this->popEnv();
  660. return is_null($ret) ? self::$defaultValue : $ret;
  661. }
  662. // built in function
  663. if ($this->callBuiltin($name, $argValues, $returnValue)) {
  664. return $returnValue;
  665. }
  666. // need to flatten the arguments into a list
  667. $listArgs = array();
  668. foreach ((array)$argValues as $arg) {
  669. if (empty($arg[0])) {
  670. $listArgs[] = $this->reduce($arg[1]);
  671. }
  672. }
  673. return array("function", $name, array("list", ",", $listArgs));
  674. default:
  675. return $value;
  676. }
  677. }
  678. // just does physical lengths for now
  679. protected function normalizeNumber($number) {
  680. list(, $value, $unit) = $number;
  681. if (isset(self::$unitTable["in"][$unit])) {
  682. $conv = self::$unitTable["in"][$unit];
  683. return array("number", $value / $conv, "in");
  684. }
  685. return $number;
  686. }
  687. // $number should be normalized
  688. protected function coerceUnit($number, $unit) {
  689. list(, $value, $baseUnit) = $number;
  690. if (isset(self::$unitTable[$baseUnit][$unit])) {
  691. $value = $value * self::$unitTable[$baseUnit][$unit];
  692. }
  693. return array("number", $value, $unit);
  694. }
  695. protected function op_add_number_number($left, $right) {
  696. return array("number", $left[1] + $right[1], $left[2]);
  697. }
  698. protected function op_mul_number_number($left, $right) {
  699. return array("number", $left[1] * $right[1], $left[2]);
  700. }
  701. protected function op_sub_number_number($left, $right) {
  702. return array("number", $left[1] - $right[1], $left[2]);
  703. }
  704. protected function op_div_number_number($left, $right) {
  705. return array("number", $left[1] / $right[1], $left[2]);
  706. }
  707. protected function op_mod_number_number($left, $right) {
  708. return array("number", $left[1] % $right[1], $left[2]);
  709. }
  710. // adding strings
  711. protected function op_add($left, $right) {
  712. if ($strLeft = $this->coerceString($left)) {
  713. if ($right[0] == "string") {
  714. $right[1] = "";
  715. }
  716. $strLeft[2][] = $right;
  717. return $strLeft;
  718. }
  719. if ($strRight = $this->coerceString($right)) {
  720. if ($left[0] == "string") {
  721. $left[1] = "";
  722. }
  723. array_unshift($strRight[2], $left);
  724. return $strRight;
  725. }
  726. }
  727. protected function op_and($left, $right, $shouldEval) {
  728. if (!$shouldEval) return;
  729. if ($left != self::$false) return $right;
  730. return $left;
  731. }
  732. protected function op_or($left, $right, $shouldEval) {
  733. if (!$shouldEval) return;
  734. if ($left != self::$false) return $left;
  735. return $right;
  736. }
  737. protected function op_color_color($op, $left, $right) {
  738. $out = array('color');
  739. foreach (range(1, 3) as $i) {
  740. $lval = isset($left[$i]) ? $left[$i] : 0;
  741. $rval = isset($right[$i]) ? $right[$i] : 0;
  742. switch ($op) {
  743. case '+':
  744. $out[] = $lval + $rval;
  745. break;
  746. case '-':
  747. $out[] = $lval - $rval;
  748. break;
  749. case '*':
  750. $out[] = $lval * $rval;
  751. break;
  752. case '%':
  753. $out[] = $lval % $rval;
  754. break;
  755. case '/':
  756. if ($rval == 0) {
  757. throw new exception("color: Can't divide by zero");
  758. }
  759. $out[] = $lval / $rval;
  760. break;
  761. default:
  762. throw new exception("color: unknow op $op");
  763. }
  764. }
  765. if (isset($left[4])) $out[4] = $left[4];
  766. elseif (isset($right[4])) $out[4] = $right[4];
  767. return $this->fixColor($out);
  768. }
  769. protected function op_color_number($op, $left, $right) {
  770. $value = $right[1];
  771. return $this->op_color_color($op, $left,
  772. array("color", $value, $value, $value));
  773. }
  774. protected function op_number_color($op, $left, $right) {
  775. $value = $left[1];
  776. return $this->op_color_color($op,
  777. array("color", $value, $value, $value), $right);
  778. }
  779. protected function op_eq($left, $right) {
  780. if (($lStr = $this->coerceString($left)) && ($rStr = $this->coerceString($right))) {
  781. $lStr[1] = "";
  782. $rStr[1] = "";
  783. return $this->toBool($this->compileValue($lStr) == $this->compileValue($rStr));
  784. }
  785. return $this->toBool($left == $right);
  786. }
  787. protected function op_neq($left, $right) {
  788. return $this->toBool($left != $right);
  789. }
  790. protected function op_gte_number_number($left, $right) {
  791. return $this->toBool($left[1] >= $right[1]);
  792. }
  793. protected function op_gt_number_number($left, $right) {
  794. return $this->toBool($left[1] > $right[1]);
  795. }
  796. protected function op_lte_number_number($left, $right) {
  797. return $this->toBool($left[1] <= $right[1]);
  798. }
  799. protected function op_lt_number_number($left, $right) {
  800. return $this->toBool($left[1] < $right[1]);
  801. }
  802. protected function toBool($thing) {
  803. return $thing ? self::$true : self::$false;
  804. }
  805. protected function compileValue($value) {
  806. $value = $this->reduce($value);
  807. list($type) = $value;
  808. switch ($type) {
  809. case "keyword":
  810. return $value[1];
  811. case "color":
  812. // [1] - red component (either number for a %)
  813. // [2] - green component
  814. // [3] - blue component
  815. // [4] - optional alpha component
  816. list(, $r, $g, $b) = $value;
  817. $r = round($r);
  818. $g = round($g);
  819. $b = round($b);
  820. if (count($value) == 5 && $value[4] != 1) { // rgba
  821. return 'rgba('.$r.', '.$g.', '.$b.', '.$value[4].')';
  822. }
  823. $h = sprintf("#%02x%02x%02x", $r, $g, $b);
  824. // Converting hex color to short notation (e.g. #003399 to #039)
  825. if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
  826. $h = '#' . $h[1] . $h[3] . $h[5];
  827. }
  828. return $h;
  829. case "number":
  830. return round($value[1], self::$numberPrecision) . $value[2];
  831. case "string":
  832. return $value[1] . $this->compileStringContent($value) . $value[1];
  833. case "function":
  834. $args = !empty($value[2]) ? $this->compileValue($value[2]) : "";
  835. return "$value[1]($args)";
  836. case "list":
  837. $value = $this->extractInterpolation($value);
  838. if ($value[0] != "list") return $this->compileValue($value);
  839. list(, $delim, $items) = $value;
  840. foreach ($items as &$item) {
  841. $item = $this->compileValue($item);
  842. }
  843. return implode("$delim ", $items);
  844. case "interpolated": # node created by extractInterpolation
  845. list(, $interpolate, $left, $right) = $value;
  846. list(,, $whiteLeft, $whiteRight) = $interpolate;
  847. $left = count($left[2]) > 0 ?
  848. $this->compileValue($left).$whiteLeft : "";
  849. $right = count($right[2]) > 0 ?
  850. $whiteRight.$this->compileValue($right) : "";
  851. return $left.$this->compileValue($interpolate).$right;
  852. case "interpolate": # raw parse node
  853. list(, $exp) = $value;
  854. // strip quotes if it's a string
  855. $reduced = $this->reduce($exp);
  856. if ($reduced[0] == "string") {
  857. $reduced = array("keyword",
  858. $this->compileStringContent($reduced));
  859. }
  860. return $this->compileValue($reduced);
  861. default:
  862. throw new exception("unknown value type: $type");
  863. }
  864. }
  865. protected function compileStringContent($string) {
  866. $parts = array();
  867. foreach ($string[2] as $part) {
  868. if (is_array($part)) {
  869. $parts[] = $this->compileValue($part);
  870. } else {
  871. $parts[] = $part;
  872. }
  873. }
  874. return implode($parts);
  875. }
  876. // doesn't need to be recursive, compileValue will handle that
  877. protected function extractInterpolation($list) {
  878. $items = $list[2];
  879. foreach ($items as $i => $item) {
  880. if ($item[0] == "interpolate") {
  881. $before = array("list", $list[1], array_slice($items, 0, $i));
  882. $after = array("list", $list[1], array_slice($items, $i + 1));
  883. return array("interpolated", $item, $before, $after);
  884. }
  885. }
  886. return $list;
  887. }
  888. // find the final set of selectors
  889. protected function multiplySelectors($env, $childSelectors = null) {
  890. if (is_null($env)) {
  891. return $childSelectors;
  892. }
  893. // skip env, has no selectors
  894. if (empty($env->selectors)) {
  895. return $this->multiplySelectors($env->parent, $childSelectors);
  896. }
  897. if (is_null($childSelectors)) {
  898. $selectors = $env->selectors;
  899. } else {
  900. $selectors = array();
  901. foreach ($env->selectors as $parent) {
  902. foreach ($childSelectors as $child) {
  903. $selectors[] = $this->joinSelectors($parent, $child);
  904. }
  905. }
  906. }
  907. return $this->multiplySelectors($env->parent, $selectors);
  908. }
  909. // looks for & to replace, or append parent before child
  910. protected function joinSelectors($parent, $child) {
  911. $setSelf = false;
  912. $out = array();
  913. foreach ($child as $part) {
  914. $newPart = array();
  915. foreach ($part as $p) {
  916. if ($p == self::$selfSelector) {
  917. $setSelf = true;
  918. foreach ($parent as $i => $parentPart) {
  919. if ($i > 0) {
  920. $out[] = $newPart;
  921. $newPart = array();
  922. }
  923. foreach ($parentPart as $pp) {
  924. $newPart[] = $pp;
  925. }
  926. }
  927. } else {
  928. $newPart[] = $p;
  929. }
  930. }
  931. $out[] = $newPart;
  932. }
  933. return $setSelf ? $out : array_merge($parent, $child);
  934. }
  935. protected function multiplyMedia($env, $childQueries = null) {
  936. if (is_null($env) ||
  937. !empty($env->block->type) && $env->block->type != "media")
  938. {
  939. return $childQueries;
  940. }
  941. // plain old block, skip
  942. if (empty($env->block->type)) {
  943. return $this->multiplyMedia($env->parent, $childQueries);
  944. }
  945. $parentQueries = $env->block->queryList;
  946. if ($childQueries == null) {
  947. $childQueries = $parentQueries;
  948. } else {
  949. $originalQueries = $childQueries;
  950. $childQueries = array();
  951. foreach ($parentQueries as $parentQuery){
  952. foreach ($originalQueries as $childQuery) {
  953. $childQueries []= array_merge($parentQuery, $childQuery);
  954. }
  955. }
  956. }
  957. return $this->multiplyMedia($env->parent, $childQueries);
  958. }
  959. // convert something to list
  960. protected function coerceList($item, $delim = ",") {
  961. if (!is_null($item) && $item[0] == "list") {
  962. return $item;
  963. }
  964. return array("list", $delim, is_null($item) ? array(): array($item));
  965. }
  966. protected function applyArguments($argDef, $argValues) {
  967. $argValues = (array)$argValues;
  968. $keywordArgs = array();
  969. $remaining = array();
  970. // assign the keyword args
  971. foreach ($argValues as $arg) {
  972. if (!empty($arg[0])) {
  973. $keywordArgs[$arg[0][1]] = $arg[1];
  974. } else {
  975. $remaining[] = $arg[1];
  976. }
  977. }
  978. foreach ($argDef as $i => $arg) {
  979. list($name, $default) = $arg;
  980. if (isset($remaining[$i])) {
  981. $val = $remaining[$i];
  982. } elseif (isset($keywordArgs[$name])) {
  983. $val = $keywordArgs[$name];
  984. } elseif (!empty($default)) {
  985. $val = $default;
  986. } else {
  987. $val = self::$defaultValue;
  988. }
  989. $this->set($name, $this->reduce($val, true), true);
  990. }
  991. }
  992. protected function pushEnv($block=null) {
  993. $env = new stdclass;
  994. $env->parent = $this->env;
  995. $env->store = array();
  996. $env->block = $block;
  997. $env->depth = isset($this->env->depth) ? $this->env->depth + 1 : 0;
  998. $this->env = $env;
  999. return $env;
  1000. }
  1001. protected function normalizeName($name) {
  1002. return str_replace("-", "_", $name);
  1003. }
  1004. protected function getStoreEnv() {
  1005. return isset($this->storeEnv) ? $this->storeEnv : $this->env;
  1006. }
  1007. protected function set($name, $value, $shadow=false) {
  1008. $name = $this->normalizeName($name);
  1009. if ($shadow) {
  1010. $this->setRaw($name, $value);
  1011. } else {
  1012. $this->setExisting($name, $value);
  1013. }
  1014. }
  1015. // todo: this is bugged?
  1016. protected function setExisting($name, $value, $env = null) {
  1017. if (is_null($env)) $env = $this->getStoreEnv();
  1018. if (isset($env->store[$name])) {
  1019. $env->store[$name] = $value;
  1020. } elseif (!is_null($env->parent)) {
  1021. $this->setExisting($name, $value, $env->parent);
  1022. } else {
  1023. $this->env->store[$name] = $value;
  1024. }
  1025. }
  1026. protected function setRaw($name, $value) {
  1027. $this->env->store[$name] = $value;
  1028. }
  1029. protected function get($name, $defaultValue = null, $env = null) {
  1030. $name = $this->normalizeName($name);
  1031. if (is_null($env)) $env = $this->getStoreEnv();
  1032. if (is_null($defaultValue)) $defaultValue = self::$defaultValue;
  1033. if (isset($env->store[$name])) {
  1034. return $env->store[$name];
  1035. } elseif (!is_null($env->parent)) {
  1036. return $this->get($name, $defaultValue, $env->parent);
  1037. }
  1038. return $defaultValue; // found nothing
  1039. }
  1040. protected function popEnv() {
  1041. $env = $this->env;
  1042. $this->env = $this->env->parent;
  1043. return $env;
  1044. }
  1045. public function getParsedFiles() {
  1046. return $this->parsedFiles;
  1047. }
  1048. public function addImportPath($path) {
  1049. $this->importPaths[] = $path;
  1050. }
  1051. public function setImportPaths($path) {
  1052. $this->importPaths = (array)$path;
  1053. }
  1054. public function setFormatter($formatterName) {
  1055. $this->formatter = $formatterName;
  1056. }
  1057. public function registerFunction($name, $func) {
  1058. $this->userFunctions[$this->normalizeName($name)] = $func;
  1059. }
  1060. public function unregisterFunction($name) {
  1061. unset($this->userFunctions[$this->normalizeName($name)]);
  1062. }
  1063. protected function importFile($path, $out) {
  1064. // see if tree is cached
  1065. $realPath = realpath($path);
  1066. if (isset($this->importCache[$realPath])) {
  1067. $tree = $this->importCache[$realPath];
  1068. } else {
  1069. $code = file_get_contents($path);
  1070. $parser = new scss_parser($path);
  1071. $tree = $parser->parse($code);
  1072. $this->parsedFiles[] = $path;
  1073. $this->importCache[$realPath] = $tree;
  1074. }
  1075. $pi = pathinfo($path);
  1076. array_unshift($this->importPaths, $pi['dirname']);
  1077. $this->compileChildren($tree->children, $out);
  1078. array_shift($this->importPaths);
  1079. }
  1080. // results the file path for an import url if it exists
  1081. protected function findImport($url) {
  1082. $urls = array();
  1083. // for "normal" scss imports (ignore vanilla css and external requests)
  1084. if (!preg_match('/\.css|^http:\/\/$/', $url)) {
  1085. // try both normal and the _partial filename
  1086. $urls = array($url, preg_replace('/[^\/]+$/', '_\0', $url));
  1087. }
  1088. foreach ($this->importPaths as $dir) {
  1089. if (is_string($dir)) {
  1090. // check urls for normal import paths
  1091. foreach ($urls as $full) {
  1092. $full = $dir .
  1093. (!empty($dir) && substr($dir, -1) != '/' ? '/' : '') .
  1094. $full;
  1095. if ($this->fileExists($file = $full.'.scss') ||
  1096. $this->fileExists($file = $full))
  1097. {
  1098. return $file;
  1099. }
  1100. }
  1101. } else {
  1102. // check custom callback for import path
  1103. $file = call_user_func($dir,$url,$this);
  1104. if ($file !== null) {
  1105. return $file;
  1106. }
  1107. }
  1108. }
  1109. return null;
  1110. }
  1111. protected function fileExists($name) {
  1112. return is_file($name);
  1113. }
  1114. protected function callBuiltin($name, $args, &$returnValue) {
  1115. // try a lib function
  1116. $name = $this->normalizeName($name);
  1117. $libName = "lib_".$name;
  1118. $f = array($this, $libName);
  1119. $prototype = isset(self::$$libName) ? self::$$libName : null;
  1120. if (is_callable($f)) {
  1121. $sorted = $this->sortArgs($prototype, $args);
  1122. foreach ($sorted as &$val) {
  1123. $val = $this->reduce($val, true);
  1124. }
  1125. $returnValue = call_user_func($f, $sorted, $this);
  1126. } else if (isset($this->userFunctions[$name])) {
  1127. // see if we can find a user function
  1128. $fn = $this->userFunctions[$name];
  1129. foreach ($args as &$val) {
  1130. $val = $this->reduce($val[1], true);
  1131. }
  1132. $returnValue = call_user_func($fn, $args, $this);
  1133. }
  1134. if (isset($returnValue)) {
  1135. // coerce a php value into a scss one
  1136. if (is_numeric($returnValue)) {
  1137. $returnValue = array('number', $returnValue, "");
  1138. } elseif (is_bool($returnValue)) {
  1139. $returnValue = $returnValue ? self::$true : self::$false;
  1140. } elseif (!is_array($returnValue)) {
  1141. $returnValue = array('keyword', $returnValue);
  1142. }
  1143. return true;
  1144. }
  1145. return false;
  1146. }
  1147. // sorts any keyword arguments
  1148. // TODO: merge with apply arguments
  1149. protected function sortArgs($prototype, $args) {
  1150. $keyArgs = array();
  1151. $posArgs = array();
  1152. foreach ($args as $arg) {
  1153. list($key, $value) = $arg;
  1154. $key = $key[1];
  1155. if (empty($key)) {
  1156. $posArgs[] = $value;
  1157. } else {
  1158. $keyArgs[$key] = $value;
  1159. }
  1160. }
  1161. if (is_null($prototype)) return $posArgs;
  1162. $finalArgs = array();
  1163. foreach ($prototype as $i => $names) {
  1164. if (isset($posArgs[$i])) {
  1165. $finalArgs[] = $posArgs[$i];
  1166. continue;
  1167. }
  1168. $set = false;
  1169. foreach ((array)$names as $name) {
  1170. if (isset($keyArgs[$name])) {
  1171. $finalArgs[] = $keyArgs[$name];
  1172. $set = true;
  1173. break;
  1174. }
  1175. }
  1176. if (!$set) {
  1177. $finalArgs[] = null;
  1178. }
  1179. }
  1180. return $finalArgs;
  1181. }
  1182. protected function coerceForExpression($value) {
  1183. if ($color = $this->coerceColor($value)) {
  1184. return $color;
  1185. }
  1186. return $value;
  1187. }
  1188. protected function coerceColor($value) {
  1189. switch ($value[0]) {
  1190. case "color": return $value;
  1191. case "keyword":
  1192. $name = $value[1];
  1193. if (isset(self::$cssColors[$name])) {
  1194. list($r, $g, $b) = explode(',', self::$cssColors[$name]);
  1195. return array('color', $r, $g, $b);
  1196. }
  1197. return null;
  1198. }
  1199. return null;
  1200. }
  1201. protected function coerceString($value) {
  1202. switch ($value[0]) {
  1203. case "string":
  1204. return $value;
  1205. case "keyword":
  1206. return array("string", "", array($value[1]));
  1207. }
  1208. return null;
  1209. }
  1210. protected function assertColor($value) {
  1211. if ($color = $this->coerceColor($value)) return $color;
  1212. throw new exception("expecting color");
  1213. }
  1214. protected function assertNumber($value) {
  1215. if ($value[0] != "number")
  1216. throw new exception("expecting number");
  1217. return $value[1];
  1218. }
  1219. protected function coercePercent($value) {
  1220. if ($value[0] == "number") {
  1221. if ($value[2] == "%") {
  1222. return $value[1] / 100;
  1223. }
  1224. return $value[1];
  1225. }
  1226. return 0;
  1227. }
  1228. // make sure a color's components don't go out of bounds
  1229. protected function fixColor($c) {
  1230. foreach (range(1, 3) as $i) {
  1231. if ($c[$i] < 0) $c[$i] = 0;
  1232. if ($c[$i] > 255) $c[$i] = 255;
  1233. }
  1234. return $c;
  1235. }
  1236. function toHSL($r, $g, $b) {
  1237. $r = $r / 255;
  1238. $g = $g / 255;
  1239. $b = $b / 255;
  1240. $min = min($r, $g, $b);
  1241. $max = max($r, $g, $b);
  1242. $L = ($min + $max) / 2;
  1243. if ($min == $max) {
  1244. $S = $H = 0;
  1245. } else {
  1246. if ($L < 0.5)
  1247. $S = ($max - $min)/($max + $min);
  1248. else
  1249. $S = ($max - $min)/(2.0 - $max - $min);
  1250. if ($r == $max) $H = ($g - $b)/($max - $min);
  1251. elseif ($g == $max) $H = 2.0 + ($b - $r)/($max - $min);
  1252. elseif ($b == $max) $H = 4.0 + ($r - $g)/($max - $min);
  1253. }
  1254. return array('hsl',
  1255. ($H < 0 ? $H + 6 : $H)*60,
  1256. $S*100,
  1257. $L*100,
  1258. );
  1259. }
  1260. function toRGB_helper($comp, $temp1, $temp2) {
  1261. if ($comp < 0) $comp += 1.0;
  1262. elseif ($comp > 1) $comp -= 1.0;
  1263. if (6 * $comp < 1) return $temp1 + ($temp2 - $temp1) * 6 * $comp;
  1264. if (2 * $comp < 1) return $temp2;
  1265. if (3 * $comp < 2) return $temp1 + ($temp2 - $temp1)*((2/3) - $comp) * 6;
  1266. return $temp1;
  1267. }
  1268. // H from 0 to 360, S and L from 0 to 100
  1269. function toRGB($H, $S, $L) {
  1270. $H = $H % 360;
  1271. if ($H < 0) $H += 360;
  1272. $S = min(100, max(0, $S));
  1273. $L = min(100, max(0, $L));
  1274. $H = $H / 360;
  1275. $S = $S / 100;
  1276. $L = $L / 100;
  1277. if ($S == 0) {
  1278. $r = $g = $b = $L;
  1279. } else {
  1280. $temp2 = $L < 0.5 ?
  1281. $L*(1.0 + $S) :
  1282. $L + $S - $L * $S;
  1283. $temp1 = 2.0 * $L - $temp2;
  1284. $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2);
  1285. $g = $this->toRGB_helper($H, $temp1, $temp2);
  1286. $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
  1287. }
  1288. $out = array('color', $r*255, $g*255, $b*255);
  1289. return $out;
  1290. }
  1291. // Built in functions
  1292. protected static $lib_if = array("condition", "if-true", "if-false");
  1293. protected function lib_if($args) {
  1294. list($cond,$t, $f) = $args;
  1295. if ($cond == self::$false) return $f;
  1296. return $t;
  1297. }
  1298. protected static $lib_rgb = array("red", "green", "blue");
  1299. protected function lib_rgb($args) {
  1300. list($r,$g,$b) = $args;
  1301. return array("color", $r[1], $g[1], $b[1]);
  1302. }
  1303. protected static $lib_rgba = array(
  1304. array("red", "color"),
  1305. "green", "blue", "alpha");
  1306. protected function lib_rgba($args) {
  1307. if ($color = $this->coerceColor($args[0])) {
  1308. $num = is_null($args[1]) ? $args[3] : $args[1];
  1309. $alpha = $this->assertNumber($num);
  1310. $color[4] = $alpha;
  1311. return $color;
  1312. }
  1313. list($r,$g,$b, $a) = $args;
  1314. return array("color", $r[1], $g[1], $b[1], $a[1]);
  1315. }
  1316. // helper function for adjust_color, change_color, and scale_color
  1317. protected function alter_color($args, $fn) {
  1318. $color = $this->assertColor($args[0]);
  1319. foreach (array(1,2,3,7) as $i) {
  1320. if (!is_null($args[$i])) {
  1321. $val = $this->assertNumber($args[$i]);
  1322. $ii = $i == 7 ? 4 : $i; // alpha
  1323. $color[$ii] =
  1324. $this->$fn(isset($color[$ii]) ? $color[$ii] : 0, $val, $i);
  1325. }
  1326. }
  1327. if (!is_null($args[4]) || !is_null($args[5]) || !is_null($args[6])) {
  1328. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1329. foreach (array(4,5,6) as $i) {
  1330. if (!is_null($args[$i])) {
  1331. $val = $this->assertNumber($args[$i]);
  1332. $hsl[$i - 3] = $this->$fn($hsl[$i - 3], $val, $i);
  1333. }
  1334. }
  1335. $rgb = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
  1336. if (isset($color[4])) $rgb[4] = $color[4];
  1337. $color = $rgb;
  1338. }
  1339. return $color;
  1340. }
  1341. protected static $lib_adjust_color = array(
  1342. "color", "red", "green", "blue",
  1343. "hue", "saturation", "lightness", "alpha"
  1344. );
  1345. protected function adjust_color_helper($base, $alter, $i) {
  1346. return $base += $alter;
  1347. }
  1348. protected function lib_adjust_color($args) {
  1349. return $this->alter_color($args, "adjust_color_helper");
  1350. }
  1351. protected static $lib_change_color = array(
  1352. "color", "red", "green", "blue",
  1353. "hue", "saturation", "lightness", "alpha"
  1354. );
  1355. protected function change_color_helper($base, $alter, $i) {
  1356. return $alter;
  1357. }
  1358. protected function lib_change_color($args) {
  1359. return $this->alter_color($args, "change_color_helper");
  1360. }
  1361. protected static $lib_scale_color = array(
  1362. "color", "red", "green", "blue",
  1363. "hue", "saturation", "lightness", "alpha"
  1364. );
  1365. protected function scale_color_helper($base, $scale, $i) {
  1366. // 1,2,3 - rgb
  1367. // 4, 5, 6 - hsl
  1368. // 7 - a
  1369. switch ($i) {
  1370. case 1:
  1371. case 2:
  1372. case 3:
  1373. $max = 255; break;
  1374. case 4:
  1375. $max = 360; break;
  1376. case 7:
  1377. $max = 1; break;
  1378. default:
  1379. $max = 100;
  1380. }
  1381. $scale = $scale / 100;
  1382. if ($scale < 0) {
  1383. return $base * $scale + $base;
  1384. } else {
  1385. return ($max - $base) * $scale + $base;
  1386. }
  1387. }
  1388. protected function lib_scale_color($args) {
  1389. return $this->alter_color($args, "scale_color_helper");
  1390. }
  1391. protected static $lib_ie_hex_str = array("color");
  1392. protected function lib_ie_hex_str($args) {
  1393. $color = $this->coerceColor($args[0]);
  1394. $color[4] = isset($color[4]) ? round(255*$color[4]) : 255;
  1395. return sprintf('#%02X%02X%02X%02X', $color[4], $color[1], $color[2], $color[3]);
  1396. }
  1397. protected static $lib_red = array("color");
  1398. protected function lib_red($args) {
  1399. list($color) = $args;
  1400. return $color[1];
  1401. }
  1402. protected static $lib_green = array("color");
  1403. protected function lib_green($args) {
  1404. list($color) = $args;
  1405. return $color[2];
  1406. }
  1407. protected static $lib_blue = array("color");
  1408. protected function lib_blue($args) {
  1409. list($color) = $args;
  1410. return $color[3];
  1411. }
  1412. protected static $lib_alpha = array("color");
  1413. protected function lib_alpha($args) {
  1414. if ($color = $this->coerceColor($args[0])) {
  1415. return isset($color[4]) ? $color[4] : 1;
  1416. }
  1417. // this might be the IE function, so return value unchanged
  1418. return array("function", "alpha", array("list", ",", $args));
  1419. }
  1420. protected static $lib_opacity = array("color");
  1421. protected function lib_opacity($args) {
  1422. return $this->lib_alpha($args);
  1423. }
  1424. // mix two colors
  1425. protected static $lib_mix = array("color-1", "color-2", "weight");
  1426. protected function lib_mix($args) {
  1427. list($first, $second, $weight) = $args;
  1428. $first = $this->assertColor($first);
  1429. $second = $this->assertColor($second);
  1430. if (is_null($weight)) {
  1431. $weight = 0.5;
  1432. } else {
  1433. $weight = $this->coercePercent($weight);
  1434. }
  1435. $first_a = isset($first[4]) ? $first[4] : 1;
  1436. $second_a = isset($second[4]) ? $second[4] : 1;
  1437. $w = $weight * 2 - 1;
  1438. $a = $first_a - $second_a;
  1439. $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0;
  1440. $w2 = 1.0 - $w1;
  1441. $new = array('color',
  1442. $w1 * $first[1] + $w2 * $second[1],
  1443. $w1 * $first[2] + $w2 * $second[2],
  1444. $w1 * $first[3] + $w2 * $second[3],
  1445. );
  1446. if ($first_a != 1.0 || $second_a != 1.0) {
  1447. $new[] = $first_a * $weight + $second_a * ($weight - 1);
  1448. }
  1449. return $this->fixColor($new);
  1450. }
  1451. protected static $lib_hsl = array("hue", "saturation", "lightness");
  1452. protected function lib_hsl($args) {
  1453. list($h, $s, $l) = $args;
  1454. return $this->toRGB($h[1], $s[1], $l[1]);
  1455. }
  1456. protected static $lib_hsla = array("hue", "saturation",
  1457. "lightness", "alpha");
  1458. protected function lib_hsla($args) {
  1459. list($h, $s, $l, $a) = $args;
  1460. $color = $this->toRGB($h[1], $s[1], $l[1]);
  1461. $color[4] = $a[1];
  1462. return $color;
  1463. }
  1464. protected static $lib_hue = array("color");
  1465. protected function lib_hue($args) {
  1466. $color = $this->assertColor($args[0]);
  1467. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1468. return array("number", $hsl[1], "deg");
  1469. }
  1470. protected static $lib_saturation = array("color");
  1471. protected function lib_saturation($args) {
  1472. $color = $this->assertColor($args[0]);
  1473. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1474. return array("number", $hsl[2], "%");
  1475. }
  1476. protected static $lib_lightness = array("color");
  1477. protected function lib_lightness($args) {
  1478. $color = $this->assertColor($args[0]);
  1479. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1480. return array("number", $hsl[3], "%");
  1481. }
  1482. protected function adjustHsl($color, $idx, $amount) {
  1483. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1484. $hsl[$idx] += $amount;
  1485. $out = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
  1486. if (isset($color[4])) $out[4] = $color[4];
  1487. return $out;
  1488. }
  1489. protected static $lib_adjust_hue = array("color", "degrees");
  1490. protected function lib_adjust_hue($args) {
  1491. $color = $this->assertColor($args[0]);
  1492. $degrees = $this->assertNumber($args[1]);
  1493. return $this->adjustHsl($color, 1, $degrees);
  1494. }
  1495. protected static $lib_lighten = array("color", "amount");
  1496. protected function lib_lighten($args) {
  1497. $color = $this->assertColor($args[0]);
  1498. $amount = 100*$this->coercePercent($args[1]);
  1499. return $this->adjustHsl($color, 3, $amount);
  1500. }
  1501. protected static $lib_darken = array("color", "amount");
  1502. protected function lib_darken($args) {
  1503. $color = $this->assertColor($args[0]);
  1504. $amount = 100*$this->coercePercent($args[1]);
  1505. return $this->adjustHsl($color, 3, -$amount);
  1506. }
  1507. protected static $lib_saturate = array("color", "amount");
  1508. protected function lib_saturate($args) {
  1509. $color = $this->assertColor($args[0]);
  1510. $amount = 100*$this->coercePercent($args[1]);
  1511. return $this->adjustHsl($color, 2, $amount);
  1512. }
  1513. protected static $lib_desaturate = array("color", "amount");
  1514. protected function lib_desaturate($args) {
  1515. $color = $this->assertColor($args[0]);
  1516. $amount = 100*$this->coercePercent($args[1]);
  1517. return $this->adjustHsl($color, 2, -$amount);
  1518. }
  1519. protected static $lib_grayscale = array("color");
  1520. protected function lib_grayscale($args) {
  1521. return $this->adjustHsl($this->assertColor($args[0]), 2, -100);
  1522. }
  1523. protected static $lib_complement = array("color");
  1524. protected function lib_complement($args) {
  1525. return $this->adjustHsl($this->assertColor($args[0]), 1, 180);
  1526. }
  1527. protected static $lib_invert = array("color");
  1528. protected function lib_invert($args) {
  1529. $color = $this->assertColor($args[0]);
  1530. $color[1] = 255 - $color[1];
  1531. $color[2] = 255 - $color[2];
  1532. $color[3] = 255 - $color[3];
  1533. return $color;
  1534. }
  1535. // increases opacity by amount
  1536. protected static $lib_opacify = array("color", "amount");
  1537. protected function lib_opacify($args) {
  1538. $color = $this->assertColor($args[0]);
  1539. $amount = $this->coercePercent($args[1]);
  1540. $color[4] = (isset($color[4]) ? $color[4] : 1) + $amount;
  1541. $color[4] = min(1, max(0, $color[4]));
  1542. return $color;
  1543. }
  1544. protected static $lib_fade_in = array("color", "amount");
  1545. protected function lib_fade_in($args) {
  1546. return $this->lib_opacify($args);
  1547. }
  1548. // decreases opacity by amount
  1549. protected static $lib_transparentize = array("color", "amount");
  1550. protected function lib_transparentize($args) {
  1551. $color = $this->assertColor($args[0]);
  1552. $amount = $this->coercePercent($args[1]);
  1553. $color[4] = (isset($color[4]) ? $color[4] : 1) - $amount;
  1554. $color[4] = min(1, max(0, $color[4]));
  1555. return $color;
  1556. }
  1557. protected static $lib_fade_out = array("color", "amount");
  1558. protected function lib_fade_out($args) {
  1559. return $this->lib_transparentize($args);
  1560. }
  1561. protected static $lib_unquote = array("string");
  1562. protected function lib_unquote($args) {
  1563. $str = $args[0];
  1564. if ($str[0] == "string") $str[1] = "";
  1565. return $str;
  1566. }
  1567. protected static $lib_quote = array("string");
  1568. protected function lib_quote($args) {
  1569. $value = $args[0];
  1570. if ($value[0] == "string" && !empty($value[1]))
  1571. return $value;
  1572. return array("string", '"', array($value));
  1573. }
  1574. protected static $lib_percentage = array("value");
  1575. protected function lib_percentage($args) {
  1576. return array("number",
  1577. $this->coercePercent($args[0]) * 100,
  1578. "%");
  1579. }
  1580. protected static $lib_round = array("value");
  1581. protected function lib_round($args) {
  1582. $num = $args[0];
  1583. $num[1] = round($num[1]);
  1584. return $num;
  1585. }
  1586. protected static $lib_floor = array("value");
  1587. protected function lib_floor($args) {
  1588. $num = $args[0];
  1589. $num[1] = floor($num[1]);
  1590. return $num;
  1591. }
  1592. protected static $lib_ceil = array("value");
  1593. protected function lib_ceil($args) {
  1594. $num = $args[0];
  1595. $num[1] = ceil($num[1]);
  1596. return $num;
  1597. }
  1598. protected static $lib_abs = array("value");
  1599. protected function lib_abs($args) {
  1600. $num = $args[0];
  1601. $num[1] = abs($num[1]);
  1602. return $num;
  1603. }
  1604. protected function lib_min($args) {
  1605. $numbers = $this->getNormalizedNumbers($args);
  1606. $min = null;
  1607. foreach ($numbers as $key => $number) {
  1608. if (null === $min || $number <= $min[1]) {
  1609. $min = array($key, $number);
  1610. }
  1611. }
  1612. return $args[$min[0]];
  1613. }
  1614. protected function lib_max($args) {
  1615. $numbers = $this->getNormalizedNumbers($args);
  1616. $max = null;
  1617. foreach ($numbers as $key => $number) {

Large files files are truncated, but you can click here to view the full file