color.module 24.9 KB
Newer Older
1
<?php
2 3 4 5
/**
 * @file
 * Allows users to change the color scheme of themes.
 */
6

7 8
use Drupal\Core\Asset\CssOptimizer;

9
/**
10
 * Implements hook_help().
11 12 13 14
 */
function color_help($path, $arg) {
  switch ($path) {
    case 'admin/help#color':
15
      $output = '<h3>' . t('About') . '</h3>';
16
      $output .= '<p>' . t('The Color module allows users with the <em>Administer site configuration</em> permission to quickly and easily change the color scheme of themes that have been built to be compatible with it. For more information, see the online handbook entry for <a href="@color">Color module</a>.', array('@color' => 'http://drupal.org/documentation/modules/color')) . '</p>';
17 18
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
19
      $output .= '<dt>' . t('Changing colors') . '</dt>';
20
      $output .= '<dd>' . t("Using the Color module allows you to easily change the color of links, backgrounds, text, and other theme elements. To change the color settings for a compatible theme, select the <em>Settings</em> link for your theme on the <a href='@configure'>Themes administration page</a>. If you don't see a color picker on that page, then your theme is not compatible with the color module. If you are sure that the theme does indeed support the color module, but the color picker does not appear, then <a href='@troubleshoot'>follow these troubleshooting procedures</a>.", array('@configure' => url('admin/appearance'), '@troubleshoot' => 'http://drupal.org/node/109457')) . '</dd>';
21 22
      $output .= '<dd>' . t("The Color module saves a modified copy of the theme's specified stylesheets in the files directory. This means that if you make any manual changes to your theme's stylesheet, <em>you must save your color settings again, even if they haven't changed</em>. This step is required because the module stylesheets (in the files directory) need to be recreated to include your changes.") . '</dd>';
      $output .= '</dl>';
23 24 25 26
      return $output;
  }
}

27
/**
28
 * Implements hook_theme().
29 30 31 32
 */
function color_theme() {
  return array(
    'color_scheme_form' => array(
33
      'render element' => 'form',
34
      'template' => 'color-scheme-form',
35 36 37
    ),
  );
}
38

39
/**
40
 * Implements hook_form_FORM_ID_alter().
41
 */
42
function color_form_system_theme_settings_alter(&$form, &$form_state) {
43
  if (isset($form_state['build_info']['args'][0]) && ($theme = $form_state['build_info']['args'][0]) && color_get_info($theme) && function_exists('gd_info')) {
44
    $form['color'] = array(
45
      '#type' => 'details',
46 47 48 49 50
      '#title' => t('Color scheme'),
      '#weight' => -1,
      '#attributes' => array('id' => 'color_scheme_form'),
      '#theme' => 'color_scheme_form',
    );
51
    $form['color'] += color_scheme_form($form, $form_state, $theme);
52
    $form['#validate'][] = 'color_scheme_form_validate';
53
    $form['#submit'][] = 'color_scheme_form_submit';
54
  }
55 56
}

57
/**
58
 * Implements hook_css_alter().
59
 *
60
 * Replaces style sheets with color-altered style sheets.
61
 */
62
function color_css_alter(&$css) {
63
  global $theme_key;
64
  $themes = list_themes();
65 66

  // Override stylesheets.
67
  $color_paths = Drupal::config('color.' . $theme_key)->get('stylesheets');
68 69

  if (!empty($color_paths) && !empty($themes[$theme_key]->stylesheets['all'])) {
70

71
    foreach ($themes[$theme_key]->stylesheets['all'] as $base_filename => $old_path) {
72 73 74 75 76
      // Loop over the path array with recolored CSS files to find matching
      // paths which could replace the non-recolored paths.
      foreach ($color_paths as $color_path) {
        // Color module currently requires unique file names to be used,
        // which allows us to compare different file paths.
77
        if (drupal_basename($old_path) == drupal_basename($color_path)) {
78 79
          // Replace the path to the new css file.
          // This keeps the order of the stylesheets intact.
80
          $css[drupal_basename($old_path)]['data'] = $color_path;
81 82 83
        }
      }
    }
84
  }
85 86 87
}

/**
88
 * Implements hook_preprocess_page().
89
 *
90
 * Replace the logo with the colored version if available.
91
 */
92
function color_preprocess_page(&$variables) {
93
  global $theme_key;
94

95
  // Override logo.
96
  $logo = Drupal::config('color.' . $theme_key)->get('logo');
97 98
  if ($logo && $variables['logo'] && preg_match('!' . $theme_key . '/logo.png$!', $variables['logo'])) {
    $variables['logo'] = file_create_url($logo);
99 100 101 102
  }
}

/**
103
 * Retrieves the Color module information for a particular theme.
104 105
 */
function color_get_info($theme) {
106 107 108 109 110 111
  static $theme_info = array();

  if (isset($theme_info[$theme])) {
    return $theme_info[$theme];
  }

112
  $path = drupal_get_path('theme', $theme);
113
  $file = DRUPAL_ROOT . '/' . $path . '/color/color.inc';
114 115
  if ($path && file_exists($file)) {
    include $file;
116
    $theme_info[$theme] = $info;
117 118 119 120 121
    return $info;
  }
}

/**
122
 * Retrieves the color palette for a particular theme.
123
 */
124
function color_get_palette($theme, $default = FALSE) {
125
  // Fetch and expand default palette.
126
  $info = color_get_info($theme);
127
  $palette = $info['schemes']['default']['colors'];
128

129 130 131 132
  if ($default) {
    return $palette;
  }

133
  // Load variable.
134
  // @todo Default color config should be moved to yaml in the theme.
135
  return Drupal::config('color.' . $theme)->get('palette') ?: $palette;
136 137 138
}

/**
139 140 141 142 143 144 145 146
 * Form constructor for the color configuration form for a particular theme.
 *
 * @param $theme
 *   The machine name of the theme whose color settings are being configured.
 *
 * @see color_scheme_form_validate()
 * @see color_scheme_form_submit()
 * @ingroup forms
147
 */
148
function color_scheme_form($complete_form, &$form_state, $theme) {
149 150 151
  $base = drupal_get_path('module', 'color');
  $info = color_get_info($theme);

152 153 154 155 156 157 158 159 160
  $info['schemes'][''] = array('title' => t('Custom'), 'colors' => array());
  $color_sets = array();
  $schemes = array();
  foreach ($info['schemes'] as $key => $scheme) {
    $color_sets[$key] = $scheme['title'];
    $schemes[$key] = $scheme['colors'];
    $schemes[$key] += $info['schemes']['default']['colors'];
  }

161
  // See if we're using a predefined scheme.
162
  // Note: we use the original theme when the default scheme is chosen.
163
  $current_scheme = Drupal::config('color.' . $theme)->get('palette');
164 165 166 167 168 169 170 171 172 173 174 175 176 177
  foreach ($schemes as $key => $scheme) {
    if ($current_scheme == $scheme) {
      $scheme_name = $key;
      break;
    }
  }
  if (empty($scheme_name)) {
    if (empty($current_scheme)) {
      $scheme_name = 'default';
    }
    else {
      $scheme_name = '';
    }
  }
178

179
  // Add scheme selector.
180 181 182
  $form['scheme'] = array(
    '#type' => 'select',
    '#title' => t('Color set'),
183 184
    '#options' => $color_sets,
    '#default_value' => $scheme_name,
185 186
    '#attached' => array(
      'library' => array(
187
        array('color', 'drupal.color'),
188 189 190
      ),
      // Add custom CSS.
      'css' => array(
191
        $base . '/css/color.admin.css' => array(),
192 193 194 195 196
      ),
      // Add custom JavaScript.
      'js' => array(
        array(
          'data' => array(
197 198 199 200 201
            'color' => array(
              'reference' => color_get_palette($theme, TRUE),
              'schemes' => $schemes,
            ),
            'gradients' => $info['gradients'],
202 203 204
          ),
          'type' => 'setting',
        ),
205 206
      ),
    ),
207 208
  );

209
  // Add palette fields.
210
  $palette = color_get_palette($theme);
211
  $names = $info['fields'];
212
  $form['palette']['#tree'] = TRUE;
213
  foreach ($palette as $name => $value) {
214 215 216
    if (isset($names[$name])) {
      $form['palette'][$name] = array(
        '#type' => 'textfield',
217
        '#title' => check_plain($names[$name]),
218 219
        '#default_value' => $value,
        '#size' => 8,
220
        '#attributes' => array('dir' => 'ltr'),
221 222
      );
    }
223
  }
224
  $form['theme'] = array('#type' => 'value', '#value' => $theme);
225 226 227 228 229 230
  $form['info'] = array('#type' => 'value', '#value' => $info);

  return $form;
}

/**
231
 * Prepares variables for color scheme form templates.
232
 *
233 234 235
 * Default template: color-scheme-form.html.twig.
 *
 * @param array $variables
236 237
 *   An associative array containing:
 *   - form: A render element representing the form.
238
 */
239
function template_preprocess_color_scheme_form(&$variables) {
240
  $form = &$variables['form'];
241

242 243
  $theme = $form['theme']['#value'];
  $info = $form['info']['#value'];
244
  $path = drupal_get_path('theme', $theme) . '/';
245

246
  $preview_css_path = $path . $info['preview_css'];
247
  $preview_js_path = isset($info['preview_js']) ? $path . $info['preview_js'] : drupal_get_path('module', 'color') . '/' . 'preview.js';
248
  $form['scheme']['#attached']['css'][$preview_css_path] = array();
249
  // Add the JS at a weight below color.js.
250
  $form['scheme']['#attached']['js'][$preview_js_path] = array('weight' => -1);
251

252 253
  // Attempt to load preview HTML if the theme provides it.
  $preview_html_path = DRUPAL_ROOT . '/' . (isset($info['preview_html']) ? drupal_get_path('theme', $theme) . '/' . $info['preview_html'] : drupal_get_path('module', 'color') . '/preview.html');
254
  $variables['html_preview'] = file_get_contents($preview_html_path);
255 256
}

257
/**
258 259 260
 * Form validation handler for color_scheme_form().
 *
 * @see color_scheme_form_submit()
261 262 263 264 265 266 267 268 269 270
 */
function color_scheme_form_validate($form, &$form_state) {
  // Only accept hexadecimal CSS color strings to avoid XSS upon use.
  foreach ($form_state['values']['palette'] as $key => $color) {
    if (!preg_match('/^#([a-f0-9]{3}){1,2}$/iD', $color)) {
      form_set_error('palette][' . $key, t('You must enter a valid hexadecimal color value for %name.', array('%name' => $form['color']['palette'][$key]['#title'])));
    }
  }
}

271
/**
272 273 274
 * Form submission handler for color_scheme_form().
 *
 * @see color_scheme_form_validate()
275
 */
276
function color_scheme_form_submit($form, &$form_state) {
277

278
  // Get theme coloring info.
279
  if (!isset($form_state['values']['info'])) {
280 281
    return;
  }
282 283
  $theme = $form_state['values']['theme'];
  $info = $form_state['values']['info'];
284

285
  $config = Drupal::config('color.' . $theme);
286

287
  // Resolve palette.
288 289
  $palette = $form_state['values']['palette'];
  if ($form_state['values']['scheme'] != '') {
290 291 292 293
    foreach ($palette as $key => $color) {
      if (isset($info['schemes'][$form_state['values']['scheme']]['colors'][$key])) {
        $palette[$key] = $info['schemes'][$form_state['values']['scheme']]['colors'][$key];
      }
294
    }
295
    $palette += $info['schemes']['default']['colors'];
296 297
  }

298 299 300
  // Make sure enough memory is available, if PHP's memory limit is compiled in.
  if (function_exists('memory_get_usage')) {
    // Fetch source image dimensions.
301
    $source = drupal_get_path('theme', $theme) . '/' . $info['base_image'];
302 303 304 305 306
    list($width, $height) = getimagesize($source);

    // We need at least a copy of the source and a target buffer of the same
    // size (both at 32bpp).
    $required = $width * $height * 8;
307
    // We intend to prevent color scheme changes if there isn't enough memory
308 309 310 311
    // available.  memory_get_usage(TRUE) returns a more accurate number than
    // memory_get_usage(), therefore we won't inadvertently reject a color
    // scheme change based on a faulty memory calculation.
    $usage = memory_get_usage(TRUE);
312 313 314 315
    $memory_limit = ini_get('memory_limit');
    $size = parse_size($memory_limit);
    if (!drupal_check_memory_limit($usage + $required, $memory_limit)) {
      drupal_set_message(t('There is not enough memory available to PHP to change this theme\'s color scheme. You need at least %size more. Check the <a href="@url">PHP documentation</a> for more information.', array('%size' => format_size($usage + $required - $size), '@url' => 'http://www.php.net/manual/ini.core.php#ini.sect.resource-limits')), 'error');
316 317 318 319
      return;
    }
  }

320
  // Delete old files.
321 322 323 324 325
  $files = $config->get('files');
  if (isset($files)) {
    foreach ($files as $file) {
      @drupal_unlink($file);
    }
326
  }
327
  if (isset($file) && $file = dirname($file)) {
328
    @drupal_rmdir($file);
329 330
  }

331
  // No change in color config, use the standard theme from color.inc.
332
  if (implode(',', color_get_palette($theme, TRUE)) == implode(',', $palette)) {
333
    $config->delete();
334 335 336
    return;
  }

337
  // Prepare target locations for generated files.
338
  $id = $theme . '-' . substr(hash('sha256', serialize($palette) . microtime()), 0, 8);
339
  $paths['color'] = 'public://color';
340
  $paths['target'] = $paths['color'] . '/' . $id;
341
  foreach ($paths as $path) {
342
    file_prepare_directory($path, FILE_CREATE_DIRECTORY);
343
  }
344
  $paths['target'] = $paths['target'] . '/';
345
  $paths['id'] = $id;
346
  $paths['source'] = drupal_get_path('theme', $theme) . '/';
347 348
  $paths['files'] = $paths['map'] = array();

349
  // Save palette and logo location.
350 351 352 353
  $config
    ->set('palette', $palette)
    ->set('logo', $paths['target'] . 'logo.png')
    ->save();
354

355
  // Copy over neutral images.
356
  foreach ($info['copy'] as $file) {
357
    $base = drupal_basename($file);
358
    $source = $paths['source'] . $file;
359
    $filepath = file_unmanaged_copy($source, $paths['target'] . $base);
360
    $paths['map'][$file] = $base;
361
    $paths['files'][] = $filepath;
362 363
  }

364
  // Render new images, if image has been provided.
365 366 367
  if ($info['base_image']) {
    _color_render_images($theme, $info, $paths, $palette);
  }
368

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
  // Rewrite theme stylesheets.
  $css = array();
  foreach ($info['css'] as $stylesheet) {
    // Build a temporary array with LTR and RTL files.
    $files = array();
    if (file_exists($paths['source'] . $stylesheet)) {
      $files[] = $stylesheet;

      $rtl_file = str_replace('.css', '-rtl.css', $stylesheet);
      if (file_exists($paths['source'] . $rtl_file)) {
        $files[] = $rtl_file;
      }
    }

    foreach ($files as $file) {
384
      $css_optimizer = new CssOptimizer();
385 386
      // Aggregate @imports recursively for each configured top level CSS file
      // without optimization. Aggregation and optimization will be
387
      // handled by drupal_build_css_cache() only.
388
      $style = $css_optimizer->loadFile($paths['source'] . $file, FALSE);
389 390 391

      // Return the path to where this CSS file originated from, stripping
      // off the name of the file at the end of the path.
392
      $css_optimizer->rewriteFileURIBasePath = base_path() . dirname($paths['source'] . $file) . '/';
393 394

      // Prefix all paths within this CSS file, ignoring absolute paths.
395
      $style = preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', array($css_optimizer, 'rewriteFileURI'), $style);
396 397 398

      // Rewrite stylesheet with new colors.
      $style = _color_rewrite_stylesheet($theme, $info, $paths, $palette, $style);
399
      $base_file = drupal_basename($file);
400 401
      $css[] = $paths['target'] . $base_file;
      _color_save_stylesheet($paths['target'] . $base_file, $style, $paths);
402
    }
403
  }
404

405
  // Maintain list of files.
406 407 408 409
  $config
    ->set('stylesheets', $css)
    ->set('files', $paths['files'])
    ->save();
410 411 412
}

/**
413
 * Rewrites the stylesheet to match the colors in the palette.
414
 */
415
function _color_rewrite_stylesheet($theme, &$info, &$paths, $palette, $style) {
416
  $themes = list_themes();
417
  // Prepare color conversion table.
418 419 420 421
  $conversion = $palette;
  foreach ($conversion as $k => $v) {
    $conversion[$k] = drupal_strtolower($v);
  }
422
  $default = color_get_palette($theme, TRUE);
423 424

  // Split off the "Don't touch" section of the stylesheet.
425
  $split = "Color Module: Don't touch";
426
  if (strpos($style, $split) !== FALSE) {
427 428
    list($style, $fixed) = explode($split, $style);
  }
429 430 431

  // Find all colors in the stylesheet and the chunks in between.
  $style = preg_split('/(#[0-9a-f]{6}|#[0-9a-f]{3})/i', $style, -1, PREG_SPLIT_DELIM_CAPTURE);
432
  $is_color = FALSE;
433 434 435
  $output = '';
  $base = 'base';

436
  // Iterate over all the parts.
437 438 439
  foreach ($style as $chunk) {
    if ($is_color) {
      $chunk = drupal_strtolower($chunk);
440
      // Check if this is one of the colors in the default palette.
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
      if ($key = array_search($chunk, $default)) {
        $chunk = $conversion[$key];
      }
      // Not a pre-set color. Extrapolate from the base.
      else {
        $chunk = _color_shift($palette[$base], $default[$base], $chunk, $info['blend_target']);
      }
    }
    else {
      // Determine the most suitable base color for the next color.

      // 'a' declarations. Use link.
      if (preg_match('@[^a-z0-9_-](a)[^a-z0-9_-][^/{]*{[^{]+$@i', $chunk)) {
        $base = 'link';
      }
      // 'color:' styles. Use text.
457
      elseif (preg_match('/(?<!-)color[^{:]*:[^{#]*$/i', $chunk)) {
458 459 460 461 462 463 464 465 466 467
        $base = 'text';
      }
      // Reset back to base.
      else {
        $base = 'base';
      }
    }
    $output .= $chunk;
    $is_color = !$is_color;
  }
468 469 470 471
  // Append fixed colors segment.
  if (isset($fixed)) {
    $output .= $fixed;
  }
472

473
  // Replace paths to images.
474
  foreach ($paths['map'] as $before => $after) {
475 476
    $before = base_path() . $paths['source'] . $before;
    $before = preg_replace('`(^|/)(?!../)([^/]+)/../`', '$1', $before);
477 478 479
    $output = str_replace($before, $after, $output);
  }

480
  return $output;
481 482 483
}

/**
484
 * Saves the rewritten stylesheet to disk.
485
 */
486
function _color_save_stylesheet($file, $style, &$paths) {
487
  $filepath = file_unmanaged_save_data($style, $file, FILE_EXISTS_REPLACE);
488
  $paths['files'][] = $filepath;
489 490

  // Set standard file permissions for webserver-generated files.
491
  drupal_chmod($file);
492 493 494
}

/**
495
 * Renders images that match a given palette.
496 497
 */
function _color_render_images($theme, &$info, &$paths, $palette) {
Steven Wittens's avatar
Steven Wittens committed
498
  // Prepare template image.
499
  $source = $paths['source'] . '/' . $info['base_image'];
500 501 502
  $source = imagecreatefrompng($source);
  $width = imagesx($source);
  $height = imagesy($source);
Steven Wittens's avatar
Steven Wittens committed
503 504

  // Prepare target buffer.
505
  $target = imagecreatetruecolor($width, $height);
506
  imagealphablending($target, TRUE);
507 508 509 510 511 512

  // Fill regions of solid color.
  foreach ($info['fill'] as $color => $fill) {
    imagefilledrectangle($target, $fill[0], $fill[1], $fill[0] + $fill[2], $fill[1] + $fill[3], _color_gd($target, $palette[$color]));
  }

513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
  // Render gradients.
  foreach ($info['gradients'] as $gradient) {
    // Get direction of the gradient.
    if (isset($gradient['direction']) && $gradient['direction'] == 'horizontal') {
      // Horizontal gradient.
      for ($x = 0; $x < $gradient['dimension'][2]; $x++) {
        $color = _color_blend($target, $palette[$gradient['colors'][0]], $palette[$gradient['colors'][1]], $x / ($gradient['dimension'][2] - 1));
        imagefilledrectangle($target, ($gradient['dimension'][0] + $x), $gradient['dimension'][1], ($gradient['dimension'][0] + $x + 1), ($gradient['dimension'][1] + $gradient['dimension'][3]), $color);
      }
    }
    else {
      // Vertical gradient.
      for ($y = 0; $y < $gradient['dimension'][3]; $y++) {
        $color = _color_blend($target, $palette[$gradient['colors'][0]], $palette[$gradient['colors'][1]], $y / ($gradient['dimension'][3] - 1));
        imagefilledrectangle($target, $gradient['dimension'][0], $gradient['dimension'][1] + $y, $gradient['dimension'][0] + $gradient['dimension'][2], $gradient['dimension'][1] + $y + 1, $color);
      }
    }
530 531
  }

Steven Wittens's avatar
Steven Wittens committed
532
  // Blend over template.
533 534
  imagecopy($target, $source, 0, 0, 0, 0, $width, $height);

Steven Wittens's avatar
Steven Wittens committed
535
  // Clean up template image.
536 537
  imagedestroy($source);

Steven Wittens's avatar
Steven Wittens committed
538
  // Cut out slices.
539 540
  foreach ($info['slices'] as $file => $coord) {
    list($x, $y, $width, $height) = $coord;
541
    $base = drupal_basename($file);
542
    $image = drupal_realpath($paths['target'] . $base);
543

Steven Wittens's avatar
Steven Wittens committed
544
    // Cut out slice.
545 546 547
    if ($file == 'screenshot.png') {
      $slice = imagecreatetruecolor(150, 90);
      imagecopyresampled($slice, $target, 0, 0, $x, $y, 150, 90, $width, $height);
548
      Drupal::config('color.' . $theme)
549 550
        ->set('screenshot', $image)
        ->save();
551 552 553 554 555 556
    }
    else {
      $slice = imagecreatetruecolor($width, $height);
      imagecopy($slice, $target, 0, 0, $x, $y, $width, $height);
    }

Steven Wittens's avatar
Steven Wittens committed
557
    // Save image.
558 559 560 561
    imagepng($slice, $image);
    imagedestroy($slice);
    $paths['files'][] = $image;

562
    // Set standard file permissions for webserver-generated files
563
    drupal_chmod($image);
564

565 566 567 568
    // Build before/after map of image paths.
    $paths['map'][$file] = $base;
  }

Steven Wittens's avatar
Steven Wittens committed
569
  // Clean up target buffer.
570 571 572 573
  imagedestroy($target);
}

/**
574
 * Shifts a given color, using a reference pair and a target blend color.
575 576 577 578
 *
 * Note: this function is significantly different from the JS version, as it
 * is written to match the blended images perfectly.
 *
579 580
 * Constraint: if (ref2 == target + (ref1 - target) * delta) for some fraction
 * delta then (return == target + (given - target) * delta).
581 582
 *
 * Loose constraint: Preserve relative positions in saturation and luminance
583
 * space.
584 585 586
 */
function _color_shift($given, $ref1, $ref2, $target) {
  // We assume that ref2 is a blend of ref1 and target and find
587
  // delta based on the length of the difference vectors.
588 589

  // delta = 1 - |ref2 - ref1| / |white - ref1|
590 591 592
  $target = _color_unpack($target, TRUE);
  $ref1 = _color_unpack($ref1, TRUE);
  $ref2 = _color_unpack($ref2, TRUE);
593 594
  $numerator = 0;
  $denominator = 0;
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
  for ($i = 0; $i < 3; ++$i) {
    $numerator += ($ref2[$i] - $ref1[$i]) * ($ref2[$i] - $ref1[$i]);
    $denominator += ($target[$i] - $ref1[$i]) * ($target[$i] - $ref1[$i]);
  }
  $delta = ($denominator > 0) ? (1 - sqrt($numerator / $denominator)) : 0;

  // Calculate the color that ref2 would be if the assumption was true.
  for ($i = 0; $i < 3; ++$i) {
    $ref3[$i] = $target[$i] + ($ref1[$i] - $target[$i]) * $delta;
  }

  // If the assumption is not true, there is a difference between ref2 and ref3.
  // We measure this in HSL space. Notation: x' = hsl(x).
  $ref2 = _color_rgb2hsl($ref2);
  $ref3 = _color_rgb2hsl($ref3);
  for ($i = 0; $i < 3; ++$i) {
    $shift[$i] = $ref2[$i] - $ref3[$i];
  }

  // Take the given color, and blend it towards the target.
615
  $given = _color_unpack($given, TRUE);
616 617 618 619 620 621 622 623 624 625 626 627 628
  for ($i = 0; $i < 3; ++$i) {
    $result[$i] = $target[$i] + ($given[$i] - $target[$i]) * $delta;
  }

  // Finally, we apply the extra shift in HSL space.
  // Note: if ref2 is a pure blend of ref1 and target, then |shift| = 0.
  $result = _color_rgb2hsl($result);
  for ($i = 0; $i < 3; ++$i) {
    $result[$i] = min(1, max(0, $result[$i] + $shift[$i]));
  }
  $result = _color_hsl2rgb($result);

  // Return hex color.
629
  return _color_pack($result, TRUE);
630 631 632
}

/**
633
 * Converts a hex triplet into a GD color.
634 635 636 637 638 639 640
 */
function _color_gd($img, $hex) {
  $c = array_merge(array($img), _color_unpack($hex));
  return call_user_func_array('imagecolorallocate', $c);
}

/**
641
 * Blends two hex colors and returns the GD color.
642 643 644 645 646 647 648 649
 */
function _color_blend($img, $hex1, $hex2, $alpha) {
  $in1 = _color_unpack($hex1);
  $in2 = _color_unpack($hex2);
  $out = array($img);
  for ($i = 0; $i < 3; ++$i) {
    $out[] = $in1[$i] + ($in2[$i] - $in1[$i]) * $alpha;
  }
650

651 652 653 654
  return call_user_func_array('imagecolorallocate', $out);
}

/**
655
 * Converts a hex color into an RGB triplet.
656
 */
657
function _color_unpack($hex, $normalize = FALSE) {
658 659 660 661 662 663 664
  if (strlen($hex) == 4) {
    $hex = $hex[1] . $hex[1] . $hex[2] . $hex[2] . $hex[3] . $hex[3];
  }
  $c = hexdec($hex);
  for ($i = 16; $i >= 0; $i -= 8) {
    $out[] = (($c >> $i) & 0xFF) / ($normalize ? 255 : 1);
  }
665

666 667 668 669
  return $out;
}

/**
670
 * Converts an RGB triplet to a hex color.
671
 */
672
function _color_pack($rgb, $normalize = FALSE) {
673
  $out = 0;
674 675 676
  foreach ($rgb as $k => $v) {
    $out |= (($v * ($normalize ? 255 : 1)) << (16 - $k * 8));
  }
677

678
  return '#' . str_pad(dechex($out), 6, 0, STR_PAD_LEFT);
679 680 681
}

/**
682
 * Converts an HSL triplet into RGB.
683 684 685 686 687 688 689
 */
function _color_hsl2rgb($hsl) {
  $h = $hsl[0];
  $s = $hsl[1];
  $l = $hsl[2];
  $m2 = ($l <= 0.5) ? $l * ($s + 1) : $l + $s - $l*$s;
  $m1 = $l * 2 - $m2;
690

691 692 693 694 695
  return array(
    _color_hue2rgb($m1, $m2, $h + 0.33333),
    _color_hue2rgb($m1, $m2, $h),
    _color_hue2rgb($m1, $m2, $h - 0.33333),
  );
696 697 698 699 700 701 702 703 704 705
}

/**
 * Helper function for _color_hsl2rgb().
 */
function _color_hue2rgb($m1, $m2, $h) {
  $h = ($h < 0) ? $h + 1 : (($h > 1) ? $h - 1 : $h);
  if ($h * 6 < 1) return $m1 + ($m2 - $m1) * $h * 6;
  if ($h * 2 < 1) return $m2;
  if ($h * 3 < 2) return $m1 + ($m2 - $m1) * (0.66666 - $h) * 6;
706

707 708 709 710
  return $m1;
}

/**
711
 * Converts an RGB triplet to HSL.
712 713 714 715 716 717 718 719 720 721
 */
function _color_rgb2hsl($rgb) {
  $r = $rgb[0];
  $g = $rgb[1];
  $b = $rgb[2];
  $min = min($r, min($g, $b));
  $max = max($r, max($g, $b));
  $delta = $max - $min;
  $l = ($min + $max) / 2;
  $s = 0;
722

723
  if ($l > 0 && $l < 1) {
Steven Wittens's avatar
Steven Wittens committed
724
    $s = $delta / ($l < 0.5 ? (2 * $l) : (2 - 2 * $l));
725
  }
726

727 728
  $h = 0;
  if ($delta > 0) {
Steven Wittens's avatar
Steven Wittens committed
729 730 731 732
    if ($max == $r && $max != $g) $h += ($g - $b) / $delta;
    if ($max == $g && $max != $b) $h += (2 + ($b - $r) / $delta);
    if ($max == $b && $max != $r) $h += (4 + ($r - $g) / $delta);
    $h /= 6;
733
  }
734

735
  return array($h, $s, $l);
736
}
737 738 739 740 741 742 743

/**
 * Implements hook_library_info().
 */
function color_library_info() {
  $libraries['drupal.color'] = array(
    'title' => 'Color',
744
    'version' => Drupal::VERSION,
745 746 747 748 749 750 751 752 753 754 755 756 757
    'js' => array(
      drupal_get_path('module', 'color') . '/color.js' => array(),
    ),
    'dependencies' => array(
      array('system', 'jquery'),
      array('system', 'drupal'),
      array('system', 'jquery.once'),
      array('system', 'jquery.farbtastic'),
      array('color', 'drupal.color.preview'),
    ),
  );
  $libraries['drupal.color.preview'] = array(
    'title' => 'Color preview',
758
    'version' => Drupal::VERSION,
759 760 761 762 763 764
    'js' => array(
      drupal_get_path('module', 'color') . '/preview.js' => array(),
    ),
    'dependencies' => array(
      array('system', 'jquery'),
      array('system', 'drupal'),
765
      array('system', 'drupalSettings'),
766 767 768 769 770 771
      array('system', 'jquery.once'),
    ),
  );

  return $libraries;
}