Index: libraries.api.php
===================================================================
RCS file: /cvs/drupal/contributions/modules/libraries/libraries.api.php,v
retrieving revision 1.1
diff -u -p -r1.1 libraries.api.php
--- libraries.api.php	3 Apr 2010 18:55:10 -0000	1.1
+++ libraries.api.php	30 May 2010 22:01:29 -0000
@@ -48,7 +48,11 @@
  *     uncompressed/source variant, those can be defined here. Each key should
  *     describe the variant type, e.g. 'minified' or 'source'. Each value is an
  *     associative array of top-level properties that are entirely overridden by
- *     the variant, most often just 'files'. Variants can be version specific.
+ *     the variant, most often just 'files'. Additionally, each variant can
+ *     contain a 'variant callback' and a 'variant arguments' key, which should
+ *     return TRUE or FALSE, depending on whether the variant is available or
+ *     not. If ommitted, the variant is expected to always be available.
+ *     Variants can be version specific.
  *   - versions: (optional) An associative array of supported library versions.
  *     Naturally, external libraries evolve over time and so do their APIs. In
  *     case a library changes between versions, different 'files' may need to be
@@ -62,6 +66,8 @@
  *     the same notion as the top-level 'files' property. Each specified file
  *     should contain the full path to the file.
  *   Additional top-level properties can be registered as needed.
+ *
+ * @see hook_library()
  */
 function hook_libraries_info() {
   // The following is a full explanation of all properties. See below for more
@@ -122,6 +128,10 @@ function hook_libraries_info() {
             'skin/example.css',
           ),
         ),
+        'variant callback' => 'mymodule_check_variant',
+        'variant arguments' => array(
+          'variant' => 'minified',
+        ),
       ),
     ),
     // Optional, but usually required: Override top-level properties for later
@@ -203,9 +213,9 @@ function hook_libraries_info() {
     'download url' => 'http://tinymce.moxiecode.com/download.php',
     'path' => 'jscripts/tiny_mce',
     'version arguments' => array(
-      // It can be easier to parse the first chars of a minified file instead of
-      // doing a multi-line pattern matching in a source file. See 'lines' and
-      // 'cols' below.
+      // It can be easier to parse the first characters of a minified file
+      // instead of doing a multi-line pattern matching in a source file. See
+      // 'lines' and 'cols' below.
       'file' => 'jscripts/tiny_mce/tiny_mce.js',
       // Best practice: Document the actual version strings for later reference.
       // 2.x: this.majorVersion="2";this.minorVersion="1.3"
Index: libraries.module
===================================================================
RCS file: /cvs/drupal/contributions/modules/libraries/libraries.module,v
retrieving revision 1.4
diff -u -p -r1.4 libraries.module
--- libraries.module	3 Apr 2010 18:55:10 -0000	1.4
+++ libraries.module	30 May 2010 22:01:30 -0000
@@ -188,7 +188,7 @@ function libraries_info($library = NULL)
  */
 function libraries_detect($libraries) {
   foreach ($libraries as $name => $library) {
-    libraries_detect_library(&$libraries[$name]);
+    libraries_detect_library($libraries[$name]);
   }
   return $libraries;
 }
@@ -210,18 +210,20 @@ function libraries_detect_library(&$libr
   }
   if (!file_exists($library['library path'])) {
     $library['error'] = t('%library could not be found.', array('%library' => $library['title']));
-    continue;
+    return;
   }
 
-  // Detect library version.
-  // Special handling for named arguments (single array).
-  if (!isset($library['version arguments'][0])) {
-    $library['version arguments'] = array($library['version arguments']);
+  // Since libraries_get_version() is library-agnostic, we need to pass
+  // the full filepath.
+  if ($library['version callback'] == 'libraries_get_version') {
+    $library['version arguments']['file'] = $library['library path'] . '/' . $library['version arguments']['file'];
   }
+
+  // Detect library version.
   $library['version'] = call_user_func_array($library['version callback'], $library['version arguments']);
   if (empty($library['version'])) {
     $library['error'] = t('The version of %library could not be detected.', array('%library' => $library['title']));
-    continue;
+    return;
   }
 
   // Determine to which supported version the installed version maps.
@@ -229,13 +231,13 @@ function libraries_detect_library(&$libr
     ksort($library['versions']);
     $version = 0;
     foreach ($library['versions'] as $supported_version => $version_properties) {
-      if (version_compare($library['installed version'], $supported_version, '>=')) {
+      if (version_compare($library['version'], $supported_version, '>=')) {
         $version = $supported_version;
       }
     }
     if (!$version) {
-      $library['error'] = t('The installed version %version of %library is not supported.', array('%version' => $library['installed version'], '%library' => $library['title']));
-      continue;
+      $library['error'] = t('The installed version %version of %library is not supported.', array('%version' => $library['version'], '%library' => $library['title']));
+      return;
     }
 
     // Apply version specific definitions and overrides.
@@ -243,10 +245,137 @@ function libraries_detect_library(&$libr
     unset($library['versions']);
   }
 
+  // Check each variant if it is installed.
+  if (!empty($library['variants'])) {
+    foreach ($library['variants'] as $variant => $info) {
+      // If no variant callback has been set, assume the variant to be
+      // installed.
+      $library['variants'][$variant]['installed'] = TRUE;
+      if (!empty($info['variant callback'])) {
+        $library['variants'][$variant]['installed'] = call_user_func_array($info['variant callback'], $info['version arguments']);
+        if (empty($library['variants'][$variant]['installed'])) {
+          $library['variants'][$variant]['error'] = t('The %variant variant of %library could not be found.', array('%variant' => $variant, '%library' => $library['title']));
+        }
+      }
+    }
+  }
+
   // If we end up here, the library should be usable.
   $library['installed'] = TRUE;
-  if (!empty($library['path'])) {
-    $library['library path'] .= '/' . $library['path'];
+}
+
+/**
+ * Loads a library.
+ *
+ * @param $library
+ *   The name of the library to load.
+ * @param $variant
+ *   The name of the variant to load.
+ */
+function libraries_load($library, $variant = NULL) {
+  $library = libraries_info($library);
+  libraries_detect_library($library);
+  libraries_load_files($library, $variant);
+}
+
+/**
+ * Loads a library's files.
+ *
+ * @param $library
+ *   The name of the library to load.
+ * @param $variant
+ *   The name of the variant to load.
+ */
+function libraries_load_files($library, $variant = NULL) {
+
+  if (!empty($variant)) {
+    if (!empty($library['variants'][$variant]['installed'])) {
+      $library = array_merge($library, $library['variants'][$variant]);
+    }
+  }
+
+  // Load integration files.
+  if (!empty($library['integration files'])) {
+    foreach ($library['integration files'] as $module => $files) {
+      libraries_load_files(array(
+        'files' => $files,
+        'library path' => drupal_get_path('module', $module),
+      ));
+    }
+  }
+
+  // Load both the JavaScript and the CSS files.
+  // The parameters for drupal_add_js() and drupal_add_css() require special
+  // handling.
+  foreach (array('js', 'css') as $type) {
+    foreach ($library['files'][$type] as $data => $options) {
+      // If the value is not an array, it's a filename and passed as first
+      // (and only) argument.
+      if (!is_array($options)) {
+        $data = $options;
+        $options = NULL;
+      }
+      // In some cases, the first parameter ($data) is an array. Arrays can't be
+      // passed as keys in PHP, so we have to get $data from the value array.
+      if (is_numeric($data)) {
+        $data = $options['data'];
+        unset($options['data']);
+      }
+      // Apply the default weight if the weight isn't explicitly given.
+      if (!isset($options['weight'])) {
+        $options['weight'] = ($type == 'js') ? JS_DEFAULT : CSS_DEFAULT;
+      }
+      call_user_func('drupal_add_' . $type, $data, $options);
+    }
+  }
+
+
+  // Load PHP files.
+  if ($files = $library['files']['php']) {
+    foreach ($files as $file) {
+      $file_path = isset($library['path']) ? $library['library path'] . '/' . $library['path'] . '/' . $file : $library['library path'] . '/' . $file;
+      if (file_exists($file_path)) {
+        require_once($file_path);
+      }
+    }
+  }
+}
+
+/**
+ * Gets the version information from an arbitrary library.
+ *
+ * @param $file
+ *   The filename to parse for the version, relative to the Drupal root
+ *   directory.
+ * @param $pattern
+ *   A string containing a regular expression (PCRE) to match the library
+ *   version. For example: '/@version (\d+)\.(\d+)/'.
+ * @param $lines
+ *   The maximum number of lines to search the pattern in. For example: 20.
+ * @param $cols
+ *   (optional) The maximum number of characters per line to take into account.
+ *   For example: 40. Defaults to unlimited. To be used if the file containing
+ *   the library version is minified/compressed, i.e. reading a single line
+ *   would read the entire library into memory.
+ *
+ * @return
+ *   A string containing the version of the library.
+ *
+ * @see libraries_get_path()
+ */
+function libraries_get_version($file, $pattern, $lines, $cols = NULL) {
+  if (!file_exists($file)) {
+    return;
+  }
+  $file = fopen($file, 'r');
+  $args = !empty($cols) ? array('handle' => $file, 'length' => $cols) : array('handle' => $file);
+  while ($lines && $line = call_user_func_array('fgets', $args)) {
+    if (preg_match($pattern, $line, $version)) {
+      fclose($file);
+      return $version[1];
+    } 
+    $lines--;
   }
+  fclose($file);
 }
 
Index: tests/example_installed.txt
===================================================================
RCS file: tests/example_installed.txt
diff -N tests/example_installed.txt
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ tests/example_installed.txt	30 May 2010 22:01:30 -0000
@@ -0,0 +1,6 @@
+; $Id$
+
+Example library
+
+Version 2
+
Index: tests/example_installed_2.css
===================================================================
RCS file: tests/example_installed_2.css
diff -N tests/example_installed_2.css
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ tests/example_installed_2.css	30 May 2010 22:01:30 -0000
@@ -0,0 +1 @@
+/* $Id$ */
Index: tests/example_installed_2.js
===================================================================
RCS file: tests/example_installed_2.js
diff -N tests/example_installed_2.js
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ tests/example_installed_2.js	30 May 2010 22:01:30 -0000
@@ -0,0 +1,2 @@
+<?php
+// $Id$
Index: tests/example_installed_2.php
===================================================================
RCS file: tests/example_installed_2.php
diff -N tests/example_installed_2.php
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ tests/example_installed_2.php	30 May 2010 22:01:30 -0000
@@ -0,0 +1,6 @@
+<?php
+// $Id$
+
+// Define a dummy function to see if this file was loaded.
+function example_installed_2() {
+}
Index: tests/example_installed_variant.css
===================================================================
RCS file: tests/example_installed_variant.css
diff -N tests/example_installed_variant.css
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ tests/example_installed_variant.css	30 May 2010 22:01:30 -0000
@@ -0,0 +1 @@
+/* $Id$ */
Index: tests/example_installed_variant.js
===================================================================
RCS file: tests/example_installed_variant.js
diff -N tests/example_installed_variant.js
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ tests/example_installed_variant.js	30 May 2010 22:01:30 -0000
@@ -0,0 +1,2 @@
+<?php
+// $Id$
Index: tests/example_installed_variant.php
===================================================================
RCS file: tests/example_installed_variant.php
diff -N tests/example_installed_variant.php
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ tests/example_installed_variant.php	30 May 2010 22:01:30 -0000
@@ -0,0 +1,6 @@
+<?php
+// $Id$
+
+// Define a dummy function to see if this file was loaded.
+function example_installed_variant() {
+}
Index: tests/libraries.test
===================================================================
RCS file: tests/libraries.test
diff -N tests/libraries.test
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ tests/libraries.test	30 May 2010 22:01:30 -0000
@@ -0,0 +1,73 @@
+<?php
+// $Id: libraries.test,v 1.1 2010/04/03 18:55:10 sun Exp $
+
+/**
+ * @file
+ * Unit tests for Libraries API.
+ */
+
+class LibrariesTestCase extends DrupalWebTestCase {
+
+  public static function getInfo() {
+    return array(
+      'name' => 'Libraries API tests',
+      'description' => 'Test the detection and loading of libraries',
+      'group' => 'Libraries API',
+    );
+  }
+
+  public function setUp() {
+    parent::setUp('libraries', 'libraries_test');
+  }
+
+  public function testLibraries() {
+    // Test the correct behaviour for a missing library.
+    $library = libraries_info('example_missing');
+    libraries_detect_library($library);
+    $error = t('%library could not be found.', array('%library' => $library['title']));
+    $this->assertEqual($library['error'], $error, 'A missing library is detected correctly');
+    // Test the correct behaviour for an undetected version.
+    $library = libraries_info('example_undetected_version');
+    libraries_detect_library($library);
+    $error = t('The version of %library could not be detected.', array('%library' => $library['title']));
+    $this->assertEqual($library['error'], $error, 'A library with an undetected version is detected correctly.');
+    // Test the correct behaviour for an unsupported version.
+    $library = libraries_info('example_unsupported_version');
+    libraries_detect_library($library);
+    $error = t('The installed version %version of %library is not supported.', array('%version' => $library['version'], '%library' => $library['title']));
+    $this->assertEqual($library['error'], $error, 'A library with an unsupported version is detected correctly.');
+
+    // Test libraries_get_version().
+    $library = libraries_info('example_installed');
+    libraries_detect_library($library);
+    $version = '2';
+    $this->assertEqual($library['version'], $version, 'The default version callback functions correctly.' . $library['version']);
+    // Test version-overloading.    
+    $files = array(
+          'js' => array('example_installed_2.js'),
+          'css' => array('example_installed_2.css'),
+          'php' => array('example_installed_2.php'),
+    );
+    $this->assertEqual($library['files'], $files, 'Version-specific overrides are applied correctly.');
+
+    // Test library loading.
+    $this->drupalGet('libraries_test');
+    $this->assertRaw('example_installed_2.js', 'The JavaScript file is loaded.');
+    $this->assertRaw('example_installed_2.css', 'The CSS file is loaded.');
+    $this->assertText('example_installed_2.php', 'The PHP file is loaded.');
+    $this->assertRaw('libraries_test.js', 'The JavaScript integration file is loaded.');
+    $this->assertRaw('libraries_test.css', 'The CSS integration file is loaded.');
+    $this->assertText('libraries_test.inc', 'The PHP integration file is loaded.');
+    // Test variant loading.
+    $this->drupalGet('libraries_test_variant');
+    $this->assertRaw('example_installed_variant.js', 'The JavaScript file is loaded.');
+    $this->assertRaw('example_installed_variant.css', 'The CSS file is loaded.');
+    $this->assertText('example_installed_variant.php', 'The PHP file is loaded.');
+    $this->assertRaw('libraries_test.js', 'The JavaScript integration file is loaded.');
+    $this->assertRaw('libraries_test.css', 'The CSS integration file is loaded.');
+    $this->assertText('libraries_test.inc', 'The PHP integration file is loaded.');
+
+  }
+
+}
+
Index: tests/libraries_test.css
===================================================================
RCS file: tests/libraries_test.css
diff -N tests/libraries_test.css
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ tests/libraries_test.css	30 May 2010 22:01:30 -0000
@@ -0,0 +1 @@
+/* $Id$ */
Index: tests/libraries_test.inc
===================================================================
RCS file: tests/libraries_test.inc
diff -N tests/libraries_test.inc
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ tests/libraries_test.inc	30 May 2010 22:01:30 -0000
@@ -0,0 +1,6 @@
+<?php
+// $Id$
+
+// Define a dummy function to see if this file was loaded.
+function libraries_test_1() {
+}
Index: tests/libraries_test.info
===================================================================
RCS file: tests/libraries_test.info
diff -N tests/libraries_test.info
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ tests/libraries_test.info	30 May 2010 22:01:30 -0000
@@ -0,0 +1,7 @@
+; $Id$
+name = Libraries test module
+description = Tests library detection and loading.
+core = 7.x
+dependencies[] = libraries
+files[] = libraries_test.module
+hidden = TRUE
Index: tests/libraries_test.js
===================================================================
RCS file: tests/libraries_test.js
diff -N tests/libraries_test.js
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ tests/libraries_test.js	30 May 2010 22:01:30 -0000
@@ -0,0 +1,2 @@
+<?php
+// $Id$
Index: tests/libraries_test.module
===================================================================
RCS file: tests/libraries_test.module
diff -N tests/libraries_test.module
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ tests/libraries_test.module	30 May 2010 22:01:30 -0000
@@ -0,0 +1,182 @@
+<?php
+// $Id$
+
+/**
+ * @file
+ * Tests the library detection and loading.
+ */
+
+/**
+ * Implements hook_libraries_info().
+ */
+function libraries_test_libraries_info() {
+  // Test library detection.
+  $libraries['example_missing'] = array(
+    'library path' => drupal_get_path('module', 'libraries') . '/tests/missing',
+    'version callback' => 'libraries_test_get_version',
+    'version arguments' => array(
+      'version' => '1',
+    ),
+  );
+  $libraries['example_undetected_version'] = array(
+    'library path' => drupal_get_path('module', 'libraries') . '/tests',
+    'version callback' => 'libraries_test_get_version',
+    'version arguments' => array(
+      'version' => 'undetected',
+    ),
+  );
+  $libraries['example_unsupported_version'] = array(
+    'library path' => drupal_get_path('module', 'libraries') . '/tests',
+    'version callback' => 'libraries_test_get_version',
+    'version arguments' => array(
+      'version' => '1',
+    ),
+    'versions' => array(
+      '2' => array(),
+    ),
+  );
+  // Test version- and variant-overloading, default version callback and library
+  // loading.
+  $libraries['example_installed'] = array(
+    'library path' => drupal_get_path('module', 'libraries') . '/tests',
+    'version arguments' => array(
+      'file' => 'example_installed.txt',
+      // Version 2
+      'pattern' => '/Version (\d+)/',
+      'lines' => 5,
+    ),
+    'files' => array(
+      'js' => array(
+        'example_installed.js',
+      ),
+      'css' => array(
+        'example_installed.css',
+      ),
+      'php' => array(
+        'example_installed.php'
+      ),
+    ),
+    'versions' => array(
+      '1' => array(
+        'files' => array(
+          'js' => array(
+            'example_installed_1.js',
+          ),
+          'css' => array(
+            'example_installed_1.css',
+          ),
+          'php' => array(
+            'example_installed_1.php',
+          ),
+        ),
+      ),
+      '2' => array(
+        'files' => array(
+          'js' => array(
+            'example_installed_2.js',
+          ),
+          'css' => array(
+            'example_installed_2.css',
+          ),
+          'php' => array(
+            'example_installed_2.php',
+          ),
+        ),
+      ),
+    ),
+    'variants' => array(
+      'variant' => array(
+        'files' => array(
+          'js' => array(
+            'example_installed_variant.js',
+          ),
+          'css' => array(
+            'example_installed_variant.css',
+          ),
+          'php' => array(
+            'example_installed_variant.php',
+          ),
+        ),
+      ),
+    ),
+    'integration files' => array(
+      'libraries_test' => array(
+        'js' => array(
+          'libraries_test.js',
+        ),
+        'css' => array(
+          'libraries_test.css',
+        ),
+        'php' => array(
+          'libraries_test.inc',
+        ),
+      ),
+    ),
+  );
+  return $libraries;
+}
+
+/**
+ * Gets the version of an example library.
+ *
+ * Returns exactly the version string entered as the $version parameter, unless
+ * you specify 'undetected', in which case it returns nothing.
+ */
+function libraries_test_get_version($version) {
+  if ($version != 'undetected') {
+    return $version;
+  }
+}
+
+/**
+ * Implements hook_menu().
+ */
+function libraries_test_menu() {
+  $items['libraries_test'] = array(
+    'title' => 'Libraries loading test',
+    'page callback' => 'libraries_test_load',
+    'access callback' => TRUE,
+  );
+  $items['libraries_test_variant'] = array(
+    'title' => 'Libraries variant loading test',
+    'page callback' => 'libraries_test_load_variant',
+    'access callback' => TRUE,
+  );
+  return $items;
+}
+
+/**
+ * Loads the test library.
+ */
+function libraries_test_load() {
+  libraries_load('example_installed');
+  // JavaScript and CSS files can be checked directly by SimpleTest, so we only
+  // need to manually check for PHP files.
+  $output = '';
+  if (function_exists('example_installed_2')) {
+    $output .= 'example_installed_2.php';
+  }
+  // Check for the PHP integration file.
+  if (function_exists('libraries_test_1')) {
+    $output .= 'libraries_test.inc';
+  }
+  return $output;
+}
+
+/**
+ * Loads the test variant of the test library.
+ */
+function libraries_test_load_variant() {
+  libraries_load('example_installed', 'variant');
+  // JavaScript and CSS files can be checked directly by SimpleTest, so we only
+  // need to manually check for PHP files.
+  $output = '';
+  if (function_exists('example_installed_variant')) {
+    $output .= 'example_installed_variant.php';
+  }
+  // Check for the PHP integration file.
+  if (function_exists('libraries_test_1')) {
+    $output .= 'libraries_test.inc';
+  }
+  return $output;
+}
