Imported Upstream version 2.8.12.2
[platform/upstream/cmake.git] / Source / cmFindPackageCommand.cxx
1 /*============================================================================
2   CMake - Cross Platform Makefile Generator
3   Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
4
5   Distributed under the OSI-approved BSD License (the "License");
6   see accompanying file Copyright.txt for details.
7
8   This software is distributed WITHOUT ANY WARRANTY; without even the
9   implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10   See the License for more information.
11 ============================================================================*/
12 #include "cmFindPackageCommand.h"
13
14 #include <cmsys/Directory.hxx>
15 #include <cmsys/RegularExpression.hxx>
16
17 #ifdef CMAKE_BUILD_WITH_CMAKE
18 #include "cmVariableWatch.h"
19 #endif
20
21 #if defined(__HAIKU__)
22 #include <StorageKit.h>
23 #endif
24
25 void cmFindPackageNeedBackwardsCompatibility(const std::string& variable,
26   int access_type, void*, const char* newValue,
27   const cmMakefile*)
28 {
29   (void)newValue;
30 #ifdef CMAKE_BUILD_WITH_CMAKE
31   if(access_type == cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS)
32     {
33     std::string message = "An attempt was made to access a variable: ";
34     message += variable;
35     message +=
36       " that has not been defined. This variable is created by the "
37       "FIND_PACKAGE command. CMake version 1.6 always converted the "
38       "variable name to upper-case, but this behavior is no longer the "
39       "case.  To fix this you might need to set the cache value of "
40       "CMAKE_BACKWARDS_COMPATIBILITY to 1.6 or less.  If you are writing a "
41       "CMake listfile, you should change the variable reference to use "
42       "the case of the argument to FIND_PACKAGE.";
43     cmSystemTools::Error(message.c_str());
44     }
45 #else
46   (void)variable;
47   (void)access_type;
48 #endif
49 }
50
51 //----------------------------------------------------------------------------
52 cmFindPackageCommand::cmFindPackageCommand()
53 {
54   this->CMakePathName = "PACKAGE";
55   this->Quiet = false;
56   this->Required = false;
57   this->NoUserRegistry = false;
58   this->NoSystemRegistry = false;
59   this->NoBuilds = false;
60   this->UseConfigFiles = true;
61   this->UseFindModules = true;
62   this->DebugMode = false;
63   this->UseLib64Paths = false;
64   this->PolicyScope = true;
65   this->VersionMajor = 0;
66   this->VersionMinor = 0;
67   this->VersionPatch = 0;
68   this->VersionTweak = 0;
69   this->VersionCount = 0;
70   this->VersionExact = false;
71   this->VersionFoundMajor = 0;
72   this->VersionFoundMinor = 0;
73   this->VersionFoundPatch = 0;
74   this->VersionFoundTweak = 0;
75   this->VersionFoundCount = 0;
76   this->RequiredCMakeVersion = 0;
77 }
78
79 //----------------------------------------------------------------------------
80 void cmFindPackageCommand::GenerateDocumentation()
81 {
82   this->cmFindCommon::GenerateDocumentation();
83   cmSystemTools::ReplaceString(this->GenericDocumentationRootPath,
84                                "CMAKE_FIND_ROOT_PATH_MODE_XXX",
85                                "CMAKE_FIND_ROOT_PATH_MODE_PACKAGE");
86   cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder,
87                                "FIND_ARGS_XXX", "<package>");
88   cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder,
89                                "FIND_XXX", "find_package");
90   this->CommandDocumentation =
91     "  find_package(<package> [version] [EXACT] [QUIET] [MODULE]\n"
92     "               [REQUIRED] [[COMPONENTS] [components...]]\n"
93     "               [OPTIONAL_COMPONENTS components...]\n"
94     "               [NO_POLICY_SCOPE])\n"
95     "Finds and loads settings from an external project.  "
96     "<package>_FOUND will be set to indicate whether the package was found.  "
97     "When the package is found package-specific information is provided "
98     "through variables and imported targets documented by the package "
99     "itself.  "
100     "The QUIET option disables messages if the package cannot be found.  "
101     "The MODULE option disables the second signature documented below.  "
102     "The REQUIRED option stops processing with an error message if the "
103     "package cannot be found."
104     "\n"
105     "A package-specific list of required components may be listed after the "
106     "COMPONENTS option (or after the REQUIRED option if present).  "
107     "Additional optional components may be listed after OPTIONAL_COMPONENTS.  "
108     "Available components and their influence on whether a package is "
109     "considered to be found are defined by the target package."
110     "\n"
111     "The [version] argument requests a version with which the package found "
112     "should be compatible (format is major[.minor[.patch[.tweak]]]).  "
113     "The EXACT option requests that the version be matched exactly.  "
114     "If no [version] and/or component list is given to a recursive "
115     "invocation inside a find-module, the corresponding arguments "
116     "are forwarded automatically from the outer call (including the "
117     "EXACT flag for [version]).  "
118     "Version support is currently provided only on a package-by-package "
119     "basis (details below).\n"
120     "User code should generally look for packages using the above simple "
121     "signature.  The remainder of this command documentation specifies the "
122     "full command signature and details of the search process.  Project "
123     "maintainers wishing to provide a package to be found by this command "
124     "are encouraged to read on.\n"
125     "The command has two modes by which it searches for packages: "
126     "\"Module\" mode and \"Config\" mode.  "
127     "Module mode is available when the command is invoked with the above "
128     "reduced signature.  "
129     "CMake searches for a file called \"Find<package>.cmake\" in "
130     "the CMAKE_MODULE_PATH followed by the CMake installation.  "
131     "If the file is found, it is read and processed by CMake.  "
132     "It is responsible for finding the package, checking the version, "
133     "and producing any needed messages.  "
134     "Many find-modules provide limited or no support for versioning; "
135     "check the module documentation.  "
136     "If no module is found and the MODULE option is not given the command "
137     "proceeds to Config mode.\n"
138     "The complete Config mode command signature is:\n"
139     "  find_package(<package> [version] [EXACT] [QUIET]\n"
140     "               [REQUIRED] [[COMPONENTS] [components...]]\n"
141     "               [CONFIG|NO_MODULE]\n"
142     "               [NO_POLICY_SCOPE]\n"
143     "               [NAMES name1 [name2 ...]]\n"
144     "               [CONFIGS config1 [config2 ...]]\n"
145     "               [HINTS path1 [path2 ... ]]\n"
146     "               [PATHS path1 [path2 ... ]]\n"
147     "               [PATH_SUFFIXES suffix1 [suffix2 ...]]\n"
148     "               [NO_DEFAULT_PATH]\n"
149     "               [NO_CMAKE_ENVIRONMENT_PATH]\n"
150     "               [NO_CMAKE_PATH]\n"
151     "               [NO_SYSTEM_ENVIRONMENT_PATH]\n"
152     "               [NO_CMAKE_PACKAGE_REGISTRY]\n"
153     "               [NO_CMAKE_BUILDS_PATH]\n"
154     "               [NO_CMAKE_SYSTEM_PATH]\n"
155     "               [NO_CMAKE_SYSTEM_PACKAGE_REGISTRY]\n"
156     "               [CMAKE_FIND_ROOT_PATH_BOTH |\n"
157     "                ONLY_CMAKE_FIND_ROOT_PATH |\n"
158     "                NO_CMAKE_FIND_ROOT_PATH])\n"
159     "The CONFIG option may be used to skip Module mode explicitly and "
160     "switch to Config mode.  It is synonymous to using NO_MODULE.  "
161     "Config mode is also implied by use of options not specified in the "
162     "reduced signature.  "
163     "\n"
164     "Config mode attempts to locate a configuration file provided by the "
165     "package to be found.  A cache entry called <package>_DIR is created to "
166     "hold the directory containing the file.  "
167     "By default the command searches for a package with the name <package>.  "
168     "If the NAMES option is given the names following it are used instead "
169     "of <package>.  "
170     "The command searches for a file called \"<name>Config.cmake\" or "
171     "\"<lower-case-name>-config.cmake\" for each name specified.  "
172     "A replacement set of possible configuration file names may be given "
173     "using the CONFIGS option.  "
174     "The search procedure is specified below.  Once found, the configuration "
175     "file is read and processed by CMake.  Since the file is provided by the "
176     "package it already knows the location of package contents.  "
177     "The full path to the configuration file is stored in the cmake "
178     "variable <package>_CONFIG."
179     "\n"
180     "All configuration files which have been considered by CMake while "
181     "searching for an installation of the package with an appropriate "
182     "version are stored in the cmake variable <package>_CONSIDERED_CONFIGS, "
183     "the associated versions in <package>_CONSIDERED_VERSIONS. "
184     "\n"
185     "If the package configuration file cannot be found CMake "
186     "will generate an error describing the problem unless the QUIET "
187     "argument is specified.  If REQUIRED is specified and the package "
188     "is not found a fatal error is generated and the configure step stops "
189     "executing.  If <package>_DIR has been set to a directory not containing "
190     "a configuration file CMake will ignore it and search from scratch."
191     "\n"
192     "When the [version] argument is given Config mode will only find a "
193     "version of the package that claims compatibility with the requested "
194     "version (format is major[.minor[.patch[.tweak]]]).  "
195     "If the EXACT option is given only a version of the package claiming "
196     "an exact match of the requested version may be found.  "
197     "CMake does not establish any convention for the meaning of version "
198     "numbers.  "
199     "Package version numbers are checked by \"version\" files provided by "
200     "the packages themselves.  "
201     "For a candidate package configuration file \"<config-file>.cmake\" the "
202     "corresponding version file is located next to it and named either "
203     "\"<config-file>-version.cmake\" or \"<config-file>Version.cmake\".  "
204     "If no such version file is available then the configuration file "
205     "is assumed to not be compatible with any requested version.  "
206     "A basic version file containing generic version matching code can be "
207     "created using the macro write_basic_package_version_file(), see its "
208     "documentation for more details.  "
209     "When a version file is found it is loaded to check the requested "
210     "version number.  "
211     "The version file is loaded in a nested scope in which the following "
212     "variables have been defined:\n"
213     "  PACKAGE_FIND_NAME          = the <package> name\n"
214     "  PACKAGE_FIND_VERSION       = full requested version string\n"
215     "  PACKAGE_FIND_VERSION_MAJOR = major version if requested, else 0\n"
216     "  PACKAGE_FIND_VERSION_MINOR = minor version if requested, else 0\n"
217     "  PACKAGE_FIND_VERSION_PATCH = patch version if requested, else 0\n"
218     "  PACKAGE_FIND_VERSION_TWEAK = tweak version if requested, else 0\n"
219     "  PACKAGE_FIND_VERSION_COUNT = number of version components, 0 to 4\n"
220     "The version file checks whether it satisfies the requested version "
221     "and sets these variables:\n"
222     "  PACKAGE_VERSION            = full provided version string\n"
223     "  PACKAGE_VERSION_EXACT      = true if version is exact match\n"
224     "  PACKAGE_VERSION_COMPATIBLE = true if version is compatible\n"
225     "  PACKAGE_VERSION_UNSUITABLE = true if unsuitable as any version\n"
226     "These variables are checked by the find_package command to determine "
227     "whether the configuration file provides an acceptable version.  "
228     "They are not available after the find_package call returns.  "
229     "If the version is acceptable the following variables are set:\n"
230     "  <package>_VERSION       = full provided version string\n"
231     "  <package>_VERSION_MAJOR = major version if provided, else 0\n"
232     "  <package>_VERSION_MINOR = minor version if provided, else 0\n"
233     "  <package>_VERSION_PATCH = patch version if provided, else 0\n"
234     "  <package>_VERSION_TWEAK = tweak version if provided, else 0\n"
235     "  <package>_VERSION_COUNT = number of version components, 0 to 4\n"
236     "and the corresponding package configuration file is loaded.  "
237     "When multiple package configuration files are available whose version "
238     "files claim compatibility with the version requested it is unspecified "
239     "which one is chosen.  "
240     "No attempt is made to choose a highest or closest version number."
241     "\n"
242     "Config mode provides an elaborate interface and search procedure.  "
243     "Much of the interface is provided for completeness and for use "
244     "internally by find-modules loaded by Module mode.  "
245     "Most user code should simply call\n"
246     "  find_package(<package> [major[.minor]] [EXACT] [REQUIRED|QUIET])\n"
247     "in order to find a package.  Package maintainers providing CMake "
248     "package configuration files are encouraged to name and install "
249     "them such that the procedure outlined below will find them "
250     "without requiring use of additional options."
251     "\n"
252     "CMake constructs a set of possible installation prefixes for the "
253     "package.  Under each prefix several directories are searched for a "
254     "configuration file.  The tables below show the directories searched.  "
255     "Each entry is meant for installation trees following Windows (W), "
256     "UNIX (U), or Apple (A) conventions.\n"
257     "  <prefix>/                                               (W)\n"
258     "  <prefix>/(cmake|CMake)/                                 (W)\n"
259     "  <prefix>/<name>*/                                       (W)\n"
260     "  <prefix>/<name>*/(cmake|CMake)/                         (W)\n"
261     "  <prefix>/(lib/<arch>|lib|share)/cmake/<name>*/          (U)\n"
262     "  <prefix>/(lib/<arch>|lib|share)/<name>*/                (U)\n"
263     "  <prefix>/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/  (U)\n"
264     "On systems supporting OS X Frameworks and Application Bundles "
265     "the following directories are searched for frameworks or bundles "
266     "containing a configuration file:\n"
267     "  <prefix>/<name>.framework/Resources/                    (A)\n"
268     "  <prefix>/<name>.framework/Resources/CMake/              (A)\n"
269     "  <prefix>/<name>.framework/Versions/*/Resources/         (A)\n"
270     "  <prefix>/<name>.framework/Versions/*/Resources/CMake/   (A)\n"
271     "  <prefix>/<name>.app/Contents/Resources/                 (A)\n"
272     "  <prefix>/<name>.app/Contents/Resources/CMake/           (A)\n"
273     "In all cases the <name> is treated as case-insensitive and corresponds "
274     "to any of the names specified (<package> or names given by NAMES).  "
275     "Paths with lib/<arch> are enabled if CMAKE_LIBRARY_ARCHITECTURE is set.  "
276     "If PATH_SUFFIXES is specified the suffixes are appended to each "
277     "(W) or (U) directory entry one-by-one.\n"
278     "This set of directories is intended to work in cooperation with "
279     "projects that provide configuration files in their installation trees.  "
280     "Directories above marked with (W) are intended for installations on "
281     "Windows where the prefix may point at the top of an application's "
282     "installation directory.  Those marked with (U) are intended for "
283     "installations on UNIX platforms where the prefix is shared by "
284     "multiple packages.  This is merely a convention, so all (W) and (U) "
285     "directories are still searched on all platforms.  "
286     "Directories marked with (A) are intended for installations on "
287     "Apple platforms.  The cmake variables CMAKE_FIND_FRAMEWORK and "
288     "CMAKE_FIND_APPBUNDLE determine the order of preference "
289     "as specified below.\n"
290     "The set of installation prefixes is constructed using the following "
291     "steps.  If NO_DEFAULT_PATH is specified all NO_* options are enabled.\n"
292     "1. Search paths specified in cmake-specific cache variables.  "
293     "These are intended to be used on the command line with a -DVAR=value.  "
294     "This can be skipped if NO_CMAKE_PATH is passed.\n"
295     "   CMAKE_PREFIX_PATH\n"
296     "   CMAKE_FRAMEWORK_PATH\n"
297     "   CMAKE_APPBUNDLE_PATH\n"
298     "2. Search paths specified in cmake-specific environment variables.  "
299     "These are intended to be set in the user's shell configuration.  "
300     "This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed.\n"
301     "   <package>_DIR\n"
302     "   CMAKE_PREFIX_PATH\n"
303     "   CMAKE_FRAMEWORK_PATH\n"
304     "   CMAKE_APPBUNDLE_PATH\n"
305     "3. Search paths specified by the HINTS option.  "
306     "These should be paths computed by system introspection, such as a "
307     "hint provided by the location of another item already found.  "
308     "Hard-coded guesses should be specified with the PATHS option.\n"
309     "4. Search the standard system environment variables. "
310     "This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is passed.  "
311     "Path entries ending in \"/bin\" or \"/sbin\" are automatically "
312     "converted to their parent directories.\n"
313     "   PATH\n"
314     "5. Search project build trees recently configured in a CMake GUI.  "
315     "This can be skipped if NO_CMAKE_BUILDS_PATH is passed.  "
316     "It is intended for the case when a user is building multiple "
317     "dependent projects one after another.\n"
318     "6. Search paths stored in the CMake user package registry.  "
319     "This can be skipped if NO_CMAKE_PACKAGE_REGISTRY is passed.  "
320     "On Windows a <package> may appear under registry key\n"
321     "  HKEY_CURRENT_USER\\Software\\Kitware\\CMake\\Packages\\<package>\n"
322     "as a REG_SZ value, with arbitrary name, that specifies the directory "
323     "containing the package configuration file.  "
324     "On UNIX platforms a <package> may appear under the directory\n"
325     "  ~/.cmake/packages/<package>\n"
326     "as a file, with arbitrary name, whose content specifies the directory "
327     "containing the package configuration file.  "
328     "See the export(PACKAGE) command to create user package registry entries "
329     "for project build trees."
330     "\n"
331     "7. Search cmake variables defined in the Platform files "
332     "for the current system.  This can be skipped if NO_CMAKE_SYSTEM_PATH "
333     "is passed.\n"
334     "   CMAKE_SYSTEM_PREFIX_PATH\n"
335     "   CMAKE_SYSTEM_FRAMEWORK_PATH\n"
336     "   CMAKE_SYSTEM_APPBUNDLE_PATH\n"
337     "8. Search paths stored in the CMake system package registry.  "
338     "This can be skipped if NO_CMAKE_SYSTEM_PACKAGE_REGISTRY is passed.  "
339     "On Windows a <package> may appear under registry key\n"
340     "  HKEY_LOCAL_MACHINE\\Software\\Kitware\\CMake\\Packages\\<package>\n"
341     "as a REG_SZ value, with arbitrary name, that specifies the directory "
342     "containing the package configuration file.  "
343     "There is no system package registry on non-Windows platforms."
344     "\n"
345     "9. Search paths specified by the PATHS option.  "
346     "These are typically hard-coded guesses.\n"
347     ;
348   this->CommandDocumentation += this->GenericDocumentationMacPolicy;
349   this->CommandDocumentation += this->GenericDocumentationRootPath;
350   this->CommandDocumentation += this->GenericDocumentationPathsOrder;
351   this->CommandDocumentation +=
352     "\n"
353     "Every non-REQUIRED find_package() call can be disabled by setting the "
354     "variable CMAKE_DISABLE_FIND_PACKAGE_<package> to TRUE. See the "
355     "documentation for the CMAKE_DISABLE_FIND_PACKAGE_<package> variable for "
356     "more information.\n"
357     "When loading a find module or package configuration file find_package "
358     "defines variables to provide information about the call arguments "
359     "(and restores their original state before returning):\n"
360     " <package>_FIND_REQUIRED      = true if REQUIRED option was given\n"
361     " <package>_FIND_QUIETLY       = true if QUIET option was given\n"
362     " <package>_FIND_VERSION       = full requested version string\n"
363     " <package>_FIND_VERSION_MAJOR = major version if requested, else 0\n"
364     " <package>_FIND_VERSION_MINOR = minor version if requested, else 0\n"
365     " <package>_FIND_VERSION_PATCH = patch version if requested, else 0\n"
366     " <package>_FIND_VERSION_TWEAK = tweak version if requested, else 0\n"
367     " <package>_FIND_VERSION_COUNT = number of version components, 0 to 4\n"
368     " <package>_FIND_VERSION_EXACT = true if EXACT option was given\n"
369     " <package>_FIND_COMPONENTS    = list of requested components\n"
370     " <package>_FIND_REQUIRED_<c>  = true if component <c> is required\n"
371     "                                false if component <c> is optional\n"
372     "In Module mode the loaded find module is responsible to honor the "
373     "request detailed by these variables; see the find module for details.  "
374     "In Config mode find_package handles REQUIRED, QUIET, and version "
375     "options automatically but leaves it to the package configuration file "
376     "to handle components in a way that makes sense for the package.  "
377     "The package configuration file may set <package>_FOUND to false "
378     "to tell find_package that component requirements are not satisfied."
379     "\n"
380     "See the cmake_policy() command documentation for discussion of the "
381     "NO_POLICY_SCOPE option."
382     ;
383 }
384
385 //----------------------------------------------------------------------------
386 const char* cmFindPackageCommand::GetFullDocumentation() const
387 {
388   if(this->CommandDocumentation.empty())
389     {
390     const_cast<cmFindPackageCommand *>(this)->GenerateDocumentation();
391     }
392   return this->CommandDocumentation.c_str();
393 }
394
395 //----------------------------------------------------------------------------
396 bool cmFindPackageCommand
397 ::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
398 {
399   if(args.size() < 1)
400     {
401     this->SetError("called with incorrect number of arguments");
402     return false;
403     }
404
405   // Lookup required version of CMake.
406   if(const char* rv =
407      this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION"))
408     {
409     unsigned int v[3] = {0,0,0};
410     sscanf(rv, "%u.%u.%u", &v[0], &v[1], &v[2]);
411     this->RequiredCMakeVersion = CMake_VERSION_ENCODE(v[0],v[1],v[2]);
412     }
413
414   // Check for debug mode.
415   this->DebugMode = this->Makefile->IsOn("CMAKE_FIND_DEBUG_MODE");
416
417   // Lookup target architecture, if any.
418   if(const char* arch =
419      this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE"))
420     {
421     this->LibraryArchitecture = arch;
422     }
423
424   // Lookup whether lib64 paths should be used.
425   if(this->Makefile->PlatformIs64Bit() &&
426      this->Makefile->GetCMakeInstance()
427      ->GetPropertyAsBool("FIND_LIBRARY_USE_LIB64_PATHS"))
428     {
429     this->UseLib64Paths = true;
430     }
431
432   // Find the current root path mode.
433   this->SelectDefaultRootPathMode();
434
435   // Find the current bundle/framework search policy.
436   this->SelectDefaultMacMode();
437
438   // Record options.
439   this->Name = args[0];
440   std::string components;
441   const char* components_sep = "";
442   std::set<std::string> requiredComponents;
443   std::set<std::string> optionalComponents;
444
445   // Check ancient compatibility.
446   this->Compatibility_1_6 =
447     this->Makefile->GetLocalGenerator()
448     ->NeedBackwardsCompatibility(1, 6);
449
450   // Always search directly in a generated path.
451   this->SearchPathSuffixes.push_back("");
452
453   // Parse the arguments.
454   enum Doing { DoingNone, DoingComponents, DoingOptionalComponents, DoingNames,
455                DoingPaths, DoingPathSuffixes, DoingConfigs, DoingHints };
456   Doing doing = DoingNone;
457   cmsys::RegularExpression version("^[0-9.]+$");
458   bool haveVersion = false;
459   std::set<unsigned int> configArgs;
460   std::set<unsigned int> moduleArgs;
461   for(unsigned int i=1; i < args.size(); ++i)
462     {
463     if(args[i] == "QUIET")
464       {
465       this->Quiet = true;
466       doing = DoingNone;
467       }
468     else if(args[i] == "EXACT")
469       {
470       this->VersionExact = true;
471       this->Compatibility_1_6 = false;
472       doing = DoingNone;
473       }
474     else if(args[i] == "MODULE")
475       {
476       moduleArgs.insert(i);
477       doing = DoingNone;
478       }
479     else if(args[i] == "CONFIG")
480       {
481       configArgs.insert(i);
482       doing = DoingNone;
483       }
484     else if(args[i] == "NO_MODULE")
485       {
486       configArgs.insert(i);
487       doing = DoingNone;
488       }
489     else if(args[i] == "REQUIRED")
490       {
491       this->Required = true;
492       doing = DoingComponents;
493       }
494     else if(args[i] == "COMPONENTS")
495       {
496       this->Compatibility_1_6 = false;
497       doing = DoingComponents;
498       }
499     else if(args[i] == "OPTIONAL_COMPONENTS")
500       {
501       this->Compatibility_1_6 = false;
502       doing = DoingOptionalComponents;
503       }
504     else if(args[i] == "NAMES")
505       {
506       configArgs.insert(i);
507       this->Compatibility_1_6 = false;
508       doing = DoingNames;
509       }
510     else if(args[i] == "PATHS")
511       {
512       configArgs.insert(i);
513       this->Compatibility_1_6 = false;
514       doing = DoingPaths;
515       }
516     else if(args[i] == "HINTS")
517       {
518       configArgs.insert(i);
519       this->Compatibility_1_6 = false;
520       doing = DoingHints;
521       }
522     else if(args[i] == "PATH_SUFFIXES")
523       {
524       configArgs.insert(i);
525       this->Compatibility_1_6 = false;
526       doing = DoingPathSuffixes;
527       }
528     else if(args[i] == "CONFIGS")
529       {
530       configArgs.insert(i);
531       this->Compatibility_1_6 = false;
532       doing = DoingConfigs;
533       }
534     else if(args[i] == "NO_POLICY_SCOPE")
535       {
536       this->PolicyScope = false;
537       this->Compatibility_1_6 = false;
538       doing = DoingNone;
539       }
540     else if(args[i] == "NO_CMAKE_PACKAGE_REGISTRY")
541       {
542       this->NoUserRegistry = true;
543       configArgs.insert(i);
544       this->Compatibility_1_6 = false;
545       doing = DoingNone;
546       }
547     else if(args[i] == "NO_CMAKE_SYSTEM_PACKAGE_REGISTRY")
548       {
549       this->NoSystemRegistry = true;
550       configArgs.insert(i);
551       this->Compatibility_1_6 = false;
552       doing = DoingNone;
553       }
554     else if(args[i] == "NO_CMAKE_BUILDS_PATH")
555       {
556       this->NoBuilds = true;
557       configArgs.insert(i);
558       this->Compatibility_1_6 = false;
559       doing = DoingNone;
560       }
561     else if(this->CheckCommonArgument(args[i]))
562       {
563       configArgs.insert(i);
564       this->Compatibility_1_6 = false;
565       doing = DoingNone;
566       }
567     else if((doing == DoingComponents) || (doing == DoingOptionalComponents))
568       {
569       // Set a variable telling the find script whether this component
570       // is required.
571       const char* isRequired = "1";
572       if (doing == DoingOptionalComponents)
573         {
574         isRequired = "0";
575         optionalComponents.insert(args[i]);
576         }
577       else
578         {
579         requiredComponents.insert(args[i]);
580         }
581
582       std::string req_var = this->Name + "_FIND_REQUIRED_" + args[i];
583       this->AddFindDefinition(req_var.c_str(), isRequired);
584
585       // Append to the list of required components.
586       components += components_sep;
587       components += args[i];
588       components_sep = ";";
589       }
590     else if(doing == DoingNames)
591       {
592       this->Names.push_back(args[i]);
593       }
594     else if(doing == DoingPaths)
595       {
596       this->AddUserPath(args[i], this->UserPaths);
597       }
598     else if(doing == DoingHints)
599       {
600       this->AddUserPath(args[i], this->UserHints);
601       }
602     else if(doing == DoingPathSuffixes)
603       {
604       this->AddPathSuffix(args[i]);
605       }
606     else if(doing == DoingConfigs)
607       {
608       if(args[i].find_first_of(":/\\") != args[i].npos ||
609          cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake")
610         {
611         cmOStringStream e;
612         e << "given CONFIGS option followed by invalid file name \""
613           << args[i] << "\".  The names given must be file names without "
614           << "a path and with a \".cmake\" extension.";
615         this->SetError(e.str().c_str());
616         return false;
617         }
618       this->Configs.push_back(args[i]);
619       }
620     else if(!haveVersion && version.find(args[i].c_str()))
621       {
622       haveVersion = true;
623       this->Version = args[i];
624       }
625     else
626       {
627       cmOStringStream e;
628       e << "called with invalid argument \"" << args[i].c_str() << "\"";
629       this->SetError(e.str().c_str());
630       return false;
631       }
632     }
633
634   std::vector<std::string> doubledComponents;
635   std::set_intersection(requiredComponents.begin(), requiredComponents.end(),
636                         optionalComponents.begin(), optionalComponents.end(),
637                         std::back_inserter(doubledComponents));
638   if(!doubledComponents.empty())
639     {
640     cmOStringStream e;
641     e << "called with components that are both required and optional:\n";
642     for(unsigned int i=0; i<doubledComponents.size(); ++i)
643       {
644       e << "  " << doubledComponents[i] << "\n";
645       }
646     this->SetError(e.str().c_str());
647     return false;
648     }
649
650   // Maybe choose one mode exclusively.
651   this->UseFindModules = configArgs.empty();
652   this->UseConfigFiles = moduleArgs.empty();
653   if(!this->UseFindModules && !this->UseConfigFiles)
654     {
655     cmOStringStream e;
656     e << "given options exclusive to Module mode:\n";
657     for(std::set<unsigned int>::const_iterator si = moduleArgs.begin();
658         si != moduleArgs.end(); ++si)
659       {
660       e << "  " << args[*si] << "\n";
661       }
662     e << "and options exclusive to Config mode:\n";
663     for(std::set<unsigned int>::const_iterator si = configArgs.begin();
664         si != configArgs.end(); ++si)
665       {
666       e << "  " << args[*si] << "\n";
667       }
668     e << "The options are incompatible.";
669     this->SetError(e.str().c_str());
670     return false;
671     }
672
673   // Ignore EXACT with no version.
674   if(this->Version.empty() && this->VersionExact)
675     {
676     this->VersionExact = false;
677     this->Makefile->IssueMessage(
678       cmake::AUTHOR_WARNING, "Ignoring EXACT since no version is requested.");
679     }
680
681   if(this->Version.empty() || components.empty())
682     {
683     // Check whether we are recursing inside "Find<name>.cmake" within
684     // another find_package(<name>) call.
685     std::string mod = this->Name;
686     mod += "_FIND_MODULE";
687     if(this->Makefile->IsOn(mod.c_str()))
688       {
689       if(this->Version.empty())
690         {
691         // Get version information from the outer call if necessary.
692         // Requested version string.
693         std::string ver = this->Name;
694         ver += "_FIND_VERSION";
695         this->Version = this->Makefile->GetSafeDefinition(ver.c_str());
696
697         // Whether an exact version is required.
698         std::string exact = this->Name;
699         exact += "_FIND_VERSION_EXACT";
700         this->VersionExact = this->Makefile->IsOn(exact.c_str());
701         }
702       if(components.empty())
703         {
704         std::string components_var = this->Name + "_FIND_COMPONENTS";
705         components = this->Makefile->GetSafeDefinition(components_var.c_str());
706         }
707       }
708     }
709
710   if(!this->Version.empty())
711     {
712     // Try to parse the version number and store the results that were
713     // successfully parsed.
714     unsigned int parsed_major;
715     unsigned int parsed_minor;
716     unsigned int parsed_patch;
717     unsigned int parsed_tweak;
718     this->VersionCount = sscanf(this->Version.c_str(), "%u.%u.%u.%u",
719                                 &parsed_major, &parsed_minor,
720                                 &parsed_patch, &parsed_tweak);
721     switch(this->VersionCount)
722       {
723       case 4: this->VersionTweak = parsed_tweak; // no break!
724       case 3: this->VersionPatch = parsed_patch; // no break!
725       case 2: this->VersionMinor = parsed_minor; // no break!
726       case 1: this->VersionMajor = parsed_major; // no break!
727       default: break;
728       }
729     }
730
731   std::string disableFindPackageVar = "CMAKE_DISABLE_FIND_PACKAGE_";
732   disableFindPackageVar += this->Name;
733   if(this->Makefile->IsOn(disableFindPackageVar.c_str()))
734     {
735     if (this->Required)
736       {
737       cmOStringStream e;
738       e << "for module " << this->Name << " called with REQUIRED, but "
739         << disableFindPackageVar
740         << " is enabled. A REQUIRED package cannot be disabled.";
741       this->SetError(e.str().c_str());
742       return false;
743       }
744
745     return true;
746     }
747
748
749   this->SetModuleVariables(components);
750
751   // See if there is a Find<package>.cmake module.
752   if(this->UseFindModules)
753     {
754     bool foundModule = false;
755     if(!this->FindModule(foundModule))
756       {
757       this->AppendSuccessInformation();
758       return false;
759       }
760     if(foundModule)
761       {
762       this->AppendSuccessInformation();
763       return true;
764       }
765     }
766
767   if(this->UseFindModules && this->UseConfigFiles &&
768      this->Makefile->IsOn("CMAKE_FIND_PACKAGE_WARN_NO_MODULE"))
769     {
770     cmOStringStream aw;
771     if(this->RequiredCMakeVersion >= CMake_VERSION_ENCODE(2,8,8))
772       {
773       aw << "find_package called without either MODULE or CONFIG option and "
774         "no Find" << this->Name << ".cmake module is in CMAKE_MODULE_PATH.  "
775         "Add MODULE to exclusively request Module mode and fail if "
776         "Find" << this->Name << ".cmake is missing.  "
777         "Add CONFIG to exclusively request Config mode and search for a "
778         "package configuration file provided by " << this->Name <<
779         " (" << this->Name << "Config.cmake or " <<
780         cmSystemTools::LowerCase(this->Name) << "-config.cmake).  ";
781       }
782     else
783       {
784       aw << "find_package called without NO_MODULE option and no "
785         "Find" << this->Name << ".cmake module is in CMAKE_MODULE_PATH.  "
786         "Add NO_MODULE to exclusively request Config mode and search for a "
787         "package configuration file provided by " << this->Name <<
788         " (" << this->Name << "Config.cmake or " <<
789         cmSystemTools::LowerCase(this->Name) << "-config.cmake).  "
790         "Otherwise make Find" << this->Name << ".cmake available in "
791         "CMAKE_MODULE_PATH.";
792       }
793     aw << "\n"
794       "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this warning.)";
795     this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, aw.str());
796     }
797
798   // No find module.  Assume the project has a CMake config file.  Use
799   // a <package>_DIR cache variable to locate it.
800   this->Variable = this->Name;
801   this->Variable += "_DIR";
802
803   // Add the default name.
804   if(this->Names.empty())
805     {
806     this->Names.push_back(this->Name);
807     }
808
809   // Add the default configs.
810   if(this->Configs.empty())
811     {
812     for(std::vector<std::string>::const_iterator ni = this->Names.begin();
813         ni != this->Names.end(); ++ni)
814       {
815       std::string config = *ni;
816       config += "Config.cmake";
817       this->Configs.push_back(config);
818
819       config = cmSystemTools::LowerCase(*ni);
820       config += "-config.cmake";
821       this->Configs.push_back(config);
822       }
823     }
824
825   // get igonored paths from vars and reroot them.
826   std::vector<std::string> ignored;
827   this->GetIgnoredPaths(ignored);
828   this->RerootPaths(ignored);
829
830   // Construct a set of ignored paths
831   this->IgnoredPaths.clear();
832   this->IgnoredPaths.insert(ignored.begin(), ignored.end());
833
834   // Find and load the package.
835   bool result = this->HandlePackageMode();
836   this->AppendSuccessInformation();
837   return result;
838 }
839
840
841 //----------------------------------------------------------------------------
842 void cmFindPackageCommand::SetModuleVariables(const std::string& components)
843 {
844   this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name.c_str());
845
846   // Store the list of components.
847   std::string components_var = this->Name + "_FIND_COMPONENTS";
848   this->AddFindDefinition(components_var.c_str(), components.c_str());
849
850   if(this->Quiet)
851     {
852     // Tell the module that is about to be read that it should find
853     // quietly.
854     std::string quietly = this->Name;
855     quietly += "_FIND_QUIETLY";
856     this->AddFindDefinition(quietly.c_str(), "1");
857     }
858
859   if(this->Required)
860     {
861     // Tell the module that is about to be read that it should report
862     // a fatal error if the package is not found.
863     std::string req = this->Name;
864     req += "_FIND_REQUIRED";
865     this->AddFindDefinition(req.c_str(), "1");
866     }
867
868   if(!this->Version.empty())
869     {
870     // Tell the module that is about to be read what version of the
871     // package has been requested.
872     std::string ver = this->Name;
873     ver += "_FIND_VERSION";
874     this->AddFindDefinition(ver.c_str(), this->Version.c_str());
875     char buf[64];
876     sprintf(buf, "%u", this->VersionMajor);
877     this->AddFindDefinition((ver+"_MAJOR").c_str(), buf);
878     sprintf(buf, "%u", this->VersionMinor);
879     this->AddFindDefinition((ver+"_MINOR").c_str(), buf);
880     sprintf(buf, "%u", this->VersionPatch);
881     this->AddFindDefinition((ver+"_PATCH").c_str(), buf);
882     sprintf(buf, "%u", this->VersionTweak);
883     this->AddFindDefinition((ver+"_TWEAK").c_str(), buf);
884     sprintf(buf, "%u", this->VersionCount);
885     this->AddFindDefinition((ver+"_COUNT").c_str(), buf);
886
887     // Tell the module whether an exact version has been requested.
888     std::string exact = this->Name;
889     exact += "_FIND_VERSION_EXACT";
890     this->AddFindDefinition(exact.c_str(), this->VersionExact? "1":"0");
891    }
892 }
893
894 //----------------------------------------------------------------------------
895 void cmFindPackageCommand::AddFindDefinition(const char* var, const char* val)
896 {
897   if(const char* old = this->Makefile->GetDefinition(var))
898     {
899     this->OriginalDefs[var].exists = true;
900     this->OriginalDefs[var].value = old;
901     }
902   else
903     {
904     this->OriginalDefs[var].exists = false;
905     }
906   this->Makefile->AddDefinition(var, val);
907 }
908
909 //----------------------------------------------------------------------------
910 void cmFindPackageCommand::RestoreFindDefinitions()
911 {
912   for(std::map<cmStdString, OriginalDef>::iterator
913         i = this->OriginalDefs.begin(); i != this->OriginalDefs.end(); ++i)
914     {
915     OriginalDef const& od = i->second;
916     if(od.exists)
917       {
918       this->Makefile->AddDefinition(i->first.c_str(), od.value.c_str());
919       }
920     else
921       {
922       this->Makefile->RemoveDefinition(i->first.c_str());
923       }
924     }
925 }
926
927 //----------------------------------------------------------------------------
928 bool cmFindPackageCommand::FindModule(bool& found)
929 {
930   std::string module = "Find";
931   module += this->Name;
932   module += ".cmake";
933   std::string mfile = this->Makefile->GetModulesFile(module.c_str());
934   if ( mfile.size() )
935     {
936     // Load the module we found, and set "<name>_FIND_MODULE" to true
937     // while inside it.
938     found = true;
939     std::string var = this->Name;
940     var += "_FIND_MODULE";
941     this->Makefile->AddDefinition(var.c_str(), "1");
942     bool result = this->ReadListFile(mfile.c_str(), DoPolicyScope);
943     this->Makefile->RemoveDefinition(var.c_str());
944     return result;
945     }
946   return true;
947 }
948
949 //----------------------------------------------------------------------------
950 bool cmFindPackageCommand::HandlePackageMode()
951 {
952   this->ConsideredConfigs.clear();
953
954   // Support old capitalization behavior.
955   std::string upperDir = cmSystemTools::UpperCase(this->Name);
956   std::string upperFound = cmSystemTools::UpperCase(this->Name);
957   upperDir += "_DIR";
958   upperFound += "_FOUND";
959   if(upperDir == this->Variable)
960     {
961     this->Compatibility_1_6 = false;
962     }
963
964   // Try to find the config file.
965   const char* def = this->Makefile->GetDefinition(this->Variable.c_str());
966   if(this->Compatibility_1_6 && cmSystemTools::IsOff(def))
967     {
968     // Use the setting of the old name of the variable to provide the
969     // value of the new.
970     const char* oldDef = this->Makefile->GetDefinition(upperDir.c_str());
971     if(!cmSystemTools::IsOff(oldDef))
972       {
973       this->Makefile->AddDefinition(this->Variable.c_str(), oldDef);
974       def = this->Makefile->GetDefinition(this->Variable.c_str());
975       }
976     }
977
978   // Try to load the config file if the directory is known
979   bool fileFound = false;
980   if (this->UseConfigFiles)
981     {
982     if(!cmSystemTools::IsOff(def))
983       {
984       // Get the directory from the variable value.
985       std::string dir = def;
986       cmSystemTools::ConvertToUnixSlashes(dir);
987
988       // Treat relative paths with respect to the current source dir.
989       if(!cmSystemTools::FileIsFullPath(dir.c_str()))
990         {
991         dir = "/" + dir;
992         dir = this->Makefile->GetCurrentDirectory() + dir;
993         }
994       // The file location was cached.  Look for the correct file.
995       std::string file;
996       if (this->FindConfigFile(dir, file))
997         {
998         this->FileFound = file;
999         fileFound = true;
1000         }
1001       def = this->Makefile->GetDefinition(this->Variable.c_str());
1002       }
1003
1004     // Search for the config file if it is not already found.
1005     if(cmSystemTools::IsOff(def) || !fileFound)
1006       {
1007       fileFound = this->FindConfig();
1008       def = this->Makefile->GetDefinition(this->Variable.c_str());
1009       }
1010
1011     // Sanity check.
1012     if(fileFound && this->FileFound.empty())
1013       {
1014       this->Makefile->IssueMessage(
1015         cmake::INTERNAL_ERROR, "fileFound is true but FileFound is empty!");
1016       fileFound = false;
1017       }
1018     }
1019
1020   std::string foundVar = this->Name;
1021   foundVar += "_FOUND";
1022   std::string notFoundMessageVar = this->Name;
1023   notFoundMessageVar += "_NOT_FOUND_MESSAGE";
1024   std::string notFoundMessage;
1025
1026   // If the directory for the config file was found, try to read the file.
1027   bool result = true;
1028   bool found = false;
1029   bool configFileSetFOUNDFalse = false;
1030
1031   if(fileFound)
1032     {
1033     if ((this->Makefile->IsDefinitionSet(foundVar.c_str()))
1034       && (this->Makefile->IsOn(foundVar.c_str()) == false))
1035       {
1036       // by removing Foo_FOUND here if it is FALSE, we don't really change
1037       // the situation for the Config file which is about to be included,
1038       // but we make it possible to detect later on whether the Config file
1039       // has set Foo_FOUND to FALSE itself:
1040       this->Makefile->RemoveDefinition(foundVar.c_str());
1041       }
1042     this->Makefile->RemoveDefinition(notFoundMessageVar.c_str());
1043
1044     // Set the version variables before loading the config file.
1045     // It may override them.
1046     this->StoreVersionFound();
1047
1048     // Parse the configuration file.
1049     if(this->ReadListFile(this->FileFound.c_str(), DoPolicyScope))
1050       {
1051       // The package has been found.
1052       found = true;
1053
1054       // Check whether the Config file has set Foo_FOUND to FALSE:
1055       if ((this->Makefile->IsDefinitionSet(foundVar.c_str()))
1056            && (this->Makefile->IsOn(foundVar.c_str()) == false))
1057         {
1058         // we get here if the Config file has set Foo_FOUND actively to FALSE
1059         found = false;
1060         configFileSetFOUNDFalse = true;
1061         notFoundMessage = this->Makefile->GetSafeDefinition(
1062                                                    notFoundMessageVar.c_str());
1063         }
1064       }
1065     else
1066       {
1067       // The configuration file is invalid.
1068       result = false;
1069       }
1070     }
1071
1072   if (result && !found && (!this->Quiet || this->Required))
1073     {
1074     // The variable is not set.
1075     cmOStringStream e;
1076     cmOStringStream aw;
1077     if (configFileSetFOUNDFalse)
1078       {
1079       e << "Found package configuration file:\n"
1080         "  " << this->FileFound << "\n"
1081         "but it set " << foundVar << " to FALSE so package \"" <<
1082         this->Name << "\" is considered to be NOT FOUND.";
1083       if (!notFoundMessage.empty())
1084         {
1085         e << " Reason given by package: \n" << notFoundMessage << "\n";
1086         }
1087       }
1088     // If there are files in ConsideredConfigs, it means that FooConfig.cmake
1089     // have been found, but they didn't have appropriate versions.
1090     else if (this->ConsideredConfigs.size() > 0)
1091       {
1092       e << "Could not find a configuration file for package \""
1093         << this->Name << "\" that "
1094         << (this->VersionExact? "exactly matches" : "is compatible with")
1095         << " requested version \"" << this->Version << "\".\n"
1096         << "The following configuration files were considered but not "
1097            "accepted:\n";
1098       for(std::vector<ConfigFileInfo>::size_type i=0;
1099           i<this->ConsideredConfigs.size(); i++)
1100         {
1101         e << "  " << this->ConsideredConfigs[i].filename
1102           << ", version: " << this->ConsideredConfigs[i].version << "\n";
1103         }
1104       }
1105     else
1106       {
1107       std::string requestedVersionString;
1108       if(!this->Version.empty())
1109         {
1110         requestedVersionString = " (requested version ";
1111         requestedVersionString += this->Version;
1112         requestedVersionString += ")";
1113         }
1114
1115       if (this->UseConfigFiles)
1116         {
1117         if(this->UseFindModules)
1118           {
1119           e << "By not providing \"Find" << this->Name << ".cmake\" in "
1120                "CMAKE_MODULE_PATH this project has asked CMake to find a "
1121                "package configuration file provided by \""<<this->Name<< "\", "
1122                "but CMake did not find one.\n";
1123           }
1124
1125         if(this->Configs.size() == 1)
1126           {
1127           e << "Could not find a package configuration file named \""
1128             << this->Configs[0] << "\" provided by package \""
1129             << this->Name << "\"" << requestedVersionString <<".\n";
1130           }
1131         else
1132           {
1133           e << "Could not find a package configuration file provided by \""
1134             << this->Name << "\"" << requestedVersionString
1135             << " with any of the following names:\n";
1136           for(std::vector<std::string>::const_iterator ci =
1137                 this->Configs.begin();
1138               ci != this->Configs.end(); ++ci)
1139             {
1140             e << "  " << *ci << "\n";
1141             }
1142           }
1143
1144         e << "Add the installation prefix of \"" << this->Name << "\" to "
1145           "CMAKE_PREFIX_PATH or set \"" << this->Variable << "\" to a "
1146           "directory containing one of the above files. "
1147           "If \"" << this->Name << "\" provides a separate development "
1148           "package or SDK, be sure it has been installed.";
1149         }
1150       else // if(!this->UseFindModules && !this->UseConfigFiles)
1151         {
1152         e << "No \"Find" << this->Name << ".cmake\" found in "
1153           << "CMAKE_MODULE_PATH.";
1154
1155         aw<< "Find"<< this->Name <<".cmake must either be part of this "
1156              "project itself, in this case adjust CMAKE_MODULE_PATH so that "
1157              "it points to the correct location inside its source tree.\n"
1158              "Or it must be installed by a package which has already been "
1159              "found via find_package().  In this case make sure that "
1160              "package has indeed been found and adjust CMAKE_MODULE_PATH to "
1161              "contain the location where that package has installed "
1162              "Find" << this->Name << ".cmake.  This must be a location "
1163              "provided by that package.  This error in general means that "
1164              "the buildsystem of this project is relying on a Find-module "
1165              "without ensuring that it is actually available.\n";
1166         }
1167       }
1168
1169
1170     this->Makefile->IssueMessage(
1171       this->Required? cmake::FATAL_ERROR : cmake::WARNING, e.str());
1172     if (this->Required)
1173       {
1174       cmSystemTools::SetFatalErrorOccured();
1175       }
1176
1177     if (!aw.str().empty())
1178       {
1179       this->Makefile->IssueMessage(cmake::AUTHOR_WARNING,aw.str());
1180       }
1181     }
1182
1183   // Set a variable marking whether the package was found.
1184   this->Makefile->AddDefinition(foundVar.c_str(), found? "1":"0");
1185
1186   // Set a variable naming the configuration file that was found.
1187   std::string fileVar = this->Name;
1188   fileVar += "_CONFIG";
1189   if(found)
1190     {
1191     this->Makefile->AddDefinition(fileVar.c_str(), this->FileFound.c_str());
1192     }
1193   else
1194     {
1195     this->Makefile->RemoveDefinition(fileVar.c_str());
1196     }
1197
1198   // Handle some ancient compatibility stuff.
1199   if(this->Compatibility_1_6)
1200     {
1201     // Listfiles will be looking for the capitalized version of the
1202     // name.  Provide it.
1203     this->Makefile->AddDefinition
1204       (upperDir.c_str(),
1205        this->Makefile->GetDefinition(this->Variable.c_str()));
1206     this->Makefile->AddDefinition
1207       (upperFound.c_str(),
1208        this->Makefile->GetDefinition(foundVar.c_str()));
1209     }
1210
1211 #ifdef CMAKE_BUILD_WITH_CMAKE
1212   if(!(upperDir == this->Variable))
1213     {
1214     if(this->Compatibility_1_6)
1215       {
1216       // Listfiles may use the capitalized version of the name.
1217       // Remove any previously added watch.
1218       this->Makefile->GetVariableWatch()->RemoveWatch(
1219         upperDir.c_str(),
1220         cmFindPackageNeedBackwardsCompatibility
1221         );
1222       }
1223     else
1224       {
1225       // Listfiles should not be using the capitalized version of the
1226       // name.  Add a watch to warn the user.
1227       this->Makefile->GetVariableWatch()->AddWatch(
1228         upperDir.c_str(),
1229         cmFindPackageNeedBackwardsCompatibility
1230         );
1231       }
1232     }
1233 #endif
1234
1235   std::string consideredConfigsVar = this->Name;
1236   consideredConfigsVar += "_CONSIDERED_CONFIGS";
1237   std::string consideredVersionsVar = this->Name;
1238   consideredVersionsVar += "_CONSIDERED_VERSIONS";
1239
1240   std::string consideredConfigFiles;
1241   std::string consideredVersions;
1242
1243   const char* sep = "";
1244   for(std::vector<ConfigFileInfo>::size_type i=0;
1245       i<this->ConsideredConfigs.size(); i++)
1246     {
1247     consideredConfigFiles += sep;
1248     consideredVersions += sep;
1249     consideredConfigFiles += this->ConsideredConfigs[i].filename;
1250     consideredVersions += this->ConsideredConfigs[i].version;
1251     sep = ";";
1252     }
1253
1254   this->Makefile->AddDefinition(consideredConfigsVar.c_str(),
1255                                 consideredConfigFiles.c_str());
1256
1257   this->Makefile->AddDefinition(consideredVersionsVar.c_str(),
1258                                 consideredVersions.c_str());
1259
1260   return result;
1261 }
1262
1263 //----------------------------------------------------------------------------
1264 bool cmFindPackageCommand::FindConfig()
1265 {
1266   // Compute the set of search prefixes.
1267   this->ComputePrefixes();
1268
1269   // Look for the project's configuration file.
1270   bool found = false;
1271
1272   // Search for frameworks.
1273   if(!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly))
1274     {
1275     found = this->FindFrameworkConfig();
1276     }
1277
1278   // Search for apps.
1279   if(!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly))
1280     {
1281     found = this->FindAppBundleConfig();
1282     }
1283
1284   // Search prefixes.
1285   if(!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly))
1286     {
1287     found = this->FindPrefixedConfig();
1288     }
1289
1290   // Search for frameworks.
1291   if(!found && this->SearchFrameworkLast)
1292     {
1293     found = this->FindFrameworkConfig();
1294     }
1295
1296   // Search for apps.
1297   if(!found && this->SearchAppBundleLast)
1298     {
1299     found = this->FindAppBundleConfig();
1300     }
1301
1302   // Store the entry in the cache so it can be set by the user.
1303   std::string init;
1304   if(found)
1305     {
1306     init = cmSystemTools::GetFilenamePath(this->FileFound);
1307     }
1308   else
1309     {
1310     init = this->Variable + "-NOTFOUND";
1311     }
1312   std::string help =
1313     "The directory containing a CMake configuration file for ";
1314   help += this->Name;
1315   help += ".";
1316   // We force the value since we do not get here if it was already set.
1317   this->Makefile->AddCacheDefinition(this->Variable.c_str(),
1318                                      init.c_str(), help.c_str(),
1319                                      cmCacheManager::PATH, true);
1320   return found;
1321 }
1322
1323 //----------------------------------------------------------------------------
1324 bool cmFindPackageCommand::FindPrefixedConfig()
1325 {
1326   std::vector<std::string>& prefixes = this->SearchPaths;
1327   for(std::vector<std::string>::const_iterator pi = prefixes.begin();
1328       pi != prefixes.end(); ++pi)
1329     {
1330     if(this->SearchPrefix(*pi))
1331       {
1332       return true;
1333       }
1334     }
1335   return false;
1336 }
1337
1338 //----------------------------------------------------------------------------
1339 bool cmFindPackageCommand::FindFrameworkConfig()
1340 {
1341   std::vector<std::string>& prefixes = this->SearchPaths;
1342   for(std::vector<std::string>::const_iterator i = prefixes.begin();
1343       i != prefixes.end(); ++i)
1344     {
1345     if(this->SearchFrameworkPrefix(*i))
1346       {
1347       return true;
1348       }
1349     }
1350   return false;
1351 }
1352
1353 //----------------------------------------------------------------------------
1354 bool cmFindPackageCommand::FindAppBundleConfig()
1355 {
1356   std::vector<std::string>& prefixes = this->SearchPaths;
1357   for(std::vector<std::string>::const_iterator i = prefixes.begin();
1358       i != prefixes.end(); ++i)
1359     {
1360     if(this->SearchAppBundlePrefix(*i))
1361       {
1362       return true;
1363       }
1364     }
1365   return false;
1366 }
1367
1368 //----------------------------------------------------------------------------
1369 bool cmFindPackageCommand::ReadListFile(const char* f, PolicyScopeRule psr)
1370 {
1371   if(this->Makefile->ReadListFile(this->Makefile->GetCurrentListFile(), f, 0,
1372                                   !this->PolicyScope || psr == NoPolicyScope))
1373     {
1374     return true;
1375     }
1376   std::string e = "Error reading CMake code from \"";
1377   e += f;
1378   e += "\".";
1379   this->SetError(e.c_str());
1380   return false;
1381 }
1382
1383 //----------------------------------------------------------------------------
1384 void cmFindPackageCommand::AppendToFoundProperty(bool found)
1385 {
1386   std::vector<std::string> foundContents;
1387   const char *foundProp =
1388              this->Makefile->GetCMakeInstance()->GetProperty("PACKAGES_FOUND");
1389   if (foundProp && *foundProp)
1390     {
1391     std::string tmp = foundProp;
1392
1393     cmSystemTools::ExpandListArgument(tmp, foundContents, false);
1394     std::vector<std::string>::iterator nameIt = std::find(
1395                        foundContents.begin(), foundContents.end(), this->Name);
1396     if(nameIt != foundContents.end())
1397       {
1398       foundContents.erase(nameIt);
1399       }
1400     }
1401
1402   std::vector<std::string> notFoundContents;
1403   const char *notFoundProp =
1404          this->Makefile->GetCMakeInstance()->GetProperty("PACKAGES_NOT_FOUND");
1405   if (notFoundProp && *notFoundProp)
1406     {
1407     std::string tmp = notFoundProp;
1408
1409     cmSystemTools::ExpandListArgument(tmp, notFoundContents, false);
1410     std::vector<std::string>::iterator nameIt = std::find(
1411                  notFoundContents.begin(), notFoundContents.end(), this->Name);
1412     if(nameIt != notFoundContents.end())
1413       {
1414       notFoundContents.erase(nameIt);
1415       }
1416     }
1417
1418   if(found)
1419     {
1420     foundContents.push_back(this->Name);
1421     }
1422   else
1423     {
1424     notFoundContents.push_back(this->Name);
1425     }
1426
1427
1428   std::string tmp;
1429   const char* sep ="";
1430   for(size_t i=0; i<foundContents.size(); i++)
1431     {
1432     tmp += sep;
1433     tmp += foundContents[i];
1434     sep = ";";
1435     }
1436
1437   this->Makefile->GetCMakeInstance()->SetProperty("PACKAGES_FOUND",
1438                                                   tmp.c_str());
1439
1440   tmp = "";
1441   sep = "";
1442   for(size_t i=0; i<notFoundContents.size(); i++)
1443     {
1444     tmp += sep;
1445     tmp += notFoundContents[i];
1446     sep = ";";
1447     }
1448   this->Makefile->GetCMakeInstance()->SetProperty("PACKAGES_NOT_FOUND",
1449                                                   tmp.c_str());
1450 }
1451
1452 //----------------------------------------------------------------------------
1453 void cmFindPackageCommand::AppendSuccessInformation()
1454 {
1455   std::string found = this->Name;
1456   found += "_FOUND";
1457   std::string upperFound = cmSystemTools::UpperCase(found);
1458
1459   const char* upperResult = this->Makefile->GetDefinition(upperFound.c_str());
1460   const char* result = this->Makefile->GetDefinition(found.c_str());
1461   bool packageFound = ((cmSystemTools::IsOn(result))
1462                                         || (cmSystemTools::IsOn(upperResult)));
1463
1464   this->AppendToFoundProperty(packageFound);
1465
1466   // Record whether the find was quiet or not, so this can be used
1467   // e.g. in FeatureSummary.cmake
1468   std::string quietInfoPropName = "_CMAKE_";
1469   quietInfoPropName += this->Name;
1470   quietInfoPropName += "_QUIET";
1471   this->Makefile->GetCMakeInstance()->SetProperty(quietInfoPropName.c_str(),
1472                                                this->Quiet ? "TRUE" : "FALSE");
1473
1474   // set a global property to record the required version of this package
1475   std::string versionInfoPropName = "_CMAKE_";
1476   versionInfoPropName += this->Name;
1477   versionInfoPropName += "_REQUIRED_VERSION";
1478   std::string versionInfo;
1479   if(!this->Version.empty())
1480     {
1481     versionInfo = this->VersionExact ? "==" : ">=";
1482     versionInfo += " ";
1483     versionInfo += this->Version;
1484     }
1485   this->Makefile->GetCMakeInstance()->SetProperty(versionInfoPropName.c_str(),
1486                                                   versionInfo.c_str());
1487   if (this->Required)
1488     {
1489     std::string requiredInfoPropName = "_CMAKE_";
1490     requiredInfoPropName += this->Name;
1491     requiredInfoPropName += "_TYPE";
1492     this->Makefile->GetCMakeInstance()->SetProperty(
1493                                      requiredInfoPropName.c_str(), "REQUIRED");
1494     }
1495
1496
1497   // Restore original state of "_FIND_" variables we set.
1498   this->RestoreFindDefinitions();
1499 }
1500
1501 //----------------------------------------------------------------------------
1502 void cmFindPackageCommand::ComputePrefixes()
1503 {
1504   this->AddPrefixesCMakeVariable();
1505   this->AddPrefixesCMakeEnvironment();
1506   this->AddPrefixesUserHints();
1507   this->AddPrefixesSystemEnvironment();
1508   this->AddPrefixesUserRegistry();
1509   this->AddPrefixesBuilds();
1510   this->AddPrefixesCMakeSystemVariable();
1511   this->AddPrefixesSystemRegistry();
1512   this->AddPrefixesUserGuess();
1513   this->ComputeFinalPaths();
1514 }
1515
1516 //----------------------------------------------------------------------------
1517 void cmFindPackageCommand::AddPrefixesCMakeEnvironment()
1518 {
1519   if(!this->NoCMakeEnvironmentPath && !this->NoDefaultPath)
1520     {
1521     // Check the environment variable with the same name as the cache
1522     // entry.
1523     std::string env;
1524     if(cmSystemTools::GetEnv(this->Variable.c_str(), env) && env.length() > 0)
1525       {
1526       cmSystemTools::ConvertToUnixSlashes(env);
1527       this->AddPathInternal(env, EnvPath);
1528       }
1529
1530     this->AddEnvPath("CMAKE_PREFIX_PATH");
1531     this->AddEnvPath("CMAKE_FRAMEWORK_PATH");
1532     this->AddEnvPath("CMAKE_APPBUNDLE_PATH");
1533     }
1534 }
1535
1536 //----------------------------------------------------------------------------
1537 void cmFindPackageCommand::AddPrefixesCMakeVariable()
1538 {
1539   if(!this->NoCMakePath && !this->NoDefaultPath)
1540     {
1541     this->AddCMakePath("CMAKE_PREFIX_PATH");
1542     this->AddCMakePath("CMAKE_FRAMEWORK_PATH");
1543     this->AddCMakePath("CMAKE_APPBUNDLE_PATH");
1544     }
1545 }
1546
1547 //----------------------------------------------------------------------------
1548 void cmFindPackageCommand::AddPrefixesSystemEnvironment()
1549 {
1550   if(!this->NoSystemEnvironmentPath && !this->NoDefaultPath)
1551     {
1552     // Use the system search path to generate prefixes.
1553     // Relative paths are interpreted with respect to the current
1554     // working directory.
1555     std::vector<std::string> tmp;
1556     cmSystemTools::GetPath(tmp);
1557     for(std::vector<std::string>::iterator i = tmp.begin();
1558         i != tmp.end(); ++i)
1559       {
1560       std::string const& d = *i;
1561
1562       // If the path is a PREFIX/bin case then add its parent instead.
1563       if((d.size() >= 4 && strcmp(d.c_str()+d.size()-4, "/bin") == 0) ||
1564          (d.size() >= 5 && strcmp(d.c_str()+d.size()-5, "/sbin") == 0))
1565         {
1566         this->AddPathInternal(cmSystemTools::GetFilenamePath(d), EnvPath);
1567         }
1568       else
1569         {
1570         this->AddPathInternal(d, EnvPath);
1571         }
1572       }
1573     }
1574 }
1575
1576 //----------------------------------------------------------------------------
1577 void cmFindPackageCommand::AddPrefixesUserRegistry()
1578 {
1579   if(this->NoUserRegistry || this->NoDefaultPath)
1580     {
1581     return;
1582     }
1583
1584 #if defined(_WIN32) && !defined(__CYGWIN__)
1585   this->LoadPackageRegistryWinUser();
1586 #elif defined(__HAIKU__)
1587   BPath dir;
1588   if (find_directory(B_USER_SETTINGS_DIRECTORY, &dir) == B_OK)
1589     {
1590     dir.Append("cmake/packages");
1591     dir.Append(this->Name.c_str());
1592     this->LoadPackageRegistryDir(dir.Path());
1593     }
1594 #else
1595   if(const char* home = cmSystemTools::GetEnv("HOME"))
1596     {
1597     std::string dir = home;
1598     dir += "/.cmake/packages/";
1599     dir += this->Name;
1600     this->LoadPackageRegistryDir(dir);
1601     }
1602 #endif
1603 }
1604
1605 //----------------------------------------------------------------------------
1606 void cmFindPackageCommand::AddPrefixesSystemRegistry()
1607 {
1608   if(this->NoSystemRegistry || this->NoDefaultPath)
1609     {
1610     return;
1611     }
1612
1613 #if defined(_WIN32) && !defined(__CYGWIN__)
1614   this->LoadPackageRegistryWinSystem();
1615 #endif
1616 }
1617
1618 #if defined(_WIN32) && !defined(__CYGWIN__)
1619 # include <windows.h>
1620 # undef GetCurrentDirectory
1621   // http://msdn.microsoft.com/en-us/library/aa384253%28v=vs.85%29.aspx
1622 # if !defined(KEY_WOW64_32KEY)
1623 #  define KEY_WOW64_32KEY 0x0200
1624 # endif
1625 # if !defined(KEY_WOW64_64KEY)
1626 #  define KEY_WOW64_64KEY 0x0100
1627 # endif
1628 //----------------------------------------------------------------------------
1629 void cmFindPackageCommand::LoadPackageRegistryWinUser()
1630 {
1631   // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
1632   this->LoadPackageRegistryWin(true, 0);
1633 }
1634
1635 //----------------------------------------------------------------------------
1636 void cmFindPackageCommand::LoadPackageRegistryWinSystem()
1637 {
1638   // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
1639   // Prefer the target platform view first.
1640   if(this->Makefile->PlatformIs64Bit())
1641     {
1642     this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY);
1643     this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY);
1644     }
1645   else
1646     {
1647     this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY);
1648     this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY);
1649     }
1650 }
1651
1652 //----------------------------------------------------------------------------
1653 void cmFindPackageCommand::LoadPackageRegistryWin(bool user,
1654                                                   unsigned int view)
1655 {
1656   std::string key = "Software\\Kitware\\CMake\\Packages\\";
1657   key += this->Name;
1658   std::set<cmStdString> bad;
1659   HKEY hKey;
1660   if(RegOpenKeyEx(user? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
1661                   0, KEY_QUERY_VALUE|view, &hKey) == ERROR_SUCCESS)
1662     {
1663     DWORD valueType = REG_NONE;
1664     char name[16384];
1665     std::vector<char> data(512);
1666     bool done = false;
1667     DWORD index = 0;
1668     while(!done)
1669       {
1670       DWORD nameSize = static_cast<DWORD>(sizeof(name));
1671       DWORD dataSize = static_cast<DWORD>(data.size()-1);
1672       switch(RegEnumValue(hKey, index, name, &nameSize,
1673                           0, &valueType, (BYTE*)&data[0], &dataSize))
1674         {
1675         case ERROR_SUCCESS:
1676           ++index;
1677           if(valueType == REG_SZ)
1678             {
1679             data[dataSize] = 0;
1680             cmsys_ios::stringstream ss(&data[0]);
1681             if(!this->CheckPackageRegistryEntry(ss))
1682               {
1683               // The entry is invalid.
1684               bad.insert(name);
1685               }
1686             }
1687           break;
1688         case ERROR_MORE_DATA:
1689           data.resize(dataSize+1);
1690           break;
1691         case ERROR_NO_MORE_ITEMS: default: done = true; break;
1692         }
1693       }
1694     RegCloseKey(hKey);
1695     }
1696
1697   // Remove bad values if possible.
1698   if(user && !bad.empty() &&
1699      RegOpenKeyEx(HKEY_CURRENT_USER, key.c_str(),
1700                   0, KEY_SET_VALUE|view, &hKey) == ERROR_SUCCESS)
1701     {
1702     for(std::set<cmStdString>::const_iterator vi = bad.begin();
1703         vi != bad.end(); ++vi)
1704       {
1705       RegDeleteValue(hKey, vi->c_str());
1706       }
1707     RegCloseKey(hKey);
1708     }
1709 }
1710 #else
1711 //----------------------------------------------------------------------------
1712 class cmFindPackageCommandHoldFile
1713 {
1714   const char* File;
1715 public:
1716   cmFindPackageCommandHoldFile(const char* f): File(f) {}
1717   ~cmFindPackageCommandHoldFile()
1718     { if(this->File) { cmSystemTools::RemoveFile(this->File); } }
1719   void Release() { this->File = 0; }
1720 };
1721
1722 //----------------------------------------------------------------------------
1723 void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir)
1724 {
1725   cmsys::Directory files;
1726   if(!files.Load(dir.c_str()))
1727     {
1728     return;
1729     }
1730
1731   std::string fname;
1732   for(unsigned long i=0; i < files.GetNumberOfFiles(); ++i)
1733     {
1734     fname = dir;
1735     fname += "/";
1736     fname += files.GetFile(i);
1737
1738     if(!cmSystemTools::FileIsDirectory(fname.c_str()))
1739       {
1740       // Hold this file hostage until it behaves.
1741       cmFindPackageCommandHoldFile holdFile(fname.c_str());
1742
1743       // Load the file.
1744       std::ifstream fin(fname.c_str(), std::ios::in | cmsys_ios_binary);
1745       if(fin && this->CheckPackageRegistryEntry(fin))
1746         {
1747         // The file references an existing package, so release it.
1748         holdFile.Release();
1749         }
1750       }
1751     }
1752
1753   // TODO: Wipe out the directory if it is empty.
1754 }
1755 #endif
1756
1757 //----------------------------------------------------------------------------
1758 bool cmFindPackageCommand::CheckPackageRegistryEntry(std::istream& is)
1759 {
1760   // Parse the content of one package registry entry.
1761   std::string fname;
1762   if(cmSystemTools::GetLineFromStream(is, fname) &&
1763      cmSystemTools::FileIsFullPath(fname.c_str()))
1764     {
1765     // The first line in the stream is the full path to a file or
1766     // directory containing the package.
1767     if(cmSystemTools::FileExists(fname.c_str()))
1768       {
1769       // The path exists.  Look for the package here.
1770       if(!cmSystemTools::FileIsDirectory(fname.c_str()))
1771         {
1772         fname = cmSystemTools::GetFilenamePath(fname);
1773         }
1774       this->AddPathInternal(fname, FullPath);
1775       return true;
1776       }
1777     else
1778       {
1779       // The path does not exist.  Assume the stream content is
1780       // associated with an old package that no longer exists, and
1781       // delete it to keep the package registry clean.
1782       return false;
1783       }
1784     }
1785   else
1786     {
1787     // The first line in the stream is not the full path to a file or
1788     // directory.  Assume the stream content was created by a future
1789     // version of CMake that uses a different format, and leave it.
1790     return true;
1791     }
1792 }
1793
1794 //----------------------------------------------------------------------------
1795 void cmFindPackageCommand::AddPrefixesBuilds()
1796 {
1797   if(!this->NoBuilds && !this->NoDefaultPath)
1798     {
1799     // It is likely that CMake will have recently built the project.
1800     for(int i=0; i <= 10; ++i)
1801       {
1802       cmOStringStream r;
1803       r <<
1804         "[HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\"
1805         "Settings\\StartPath;WhereBuild" << i << "]";
1806       std::string f = r.str();
1807       cmSystemTools::ExpandRegistryValues(f);
1808       cmSystemTools::ConvertToUnixSlashes(f);
1809       if(cmSystemTools::FileIsFullPath(f.c_str()) &&
1810          cmSystemTools::FileIsDirectory(f.c_str()))
1811         {
1812         this->AddPathInternal(f, FullPath);
1813         }
1814       }
1815     }
1816 }
1817
1818 //----------------------------------------------------------------------------
1819 void cmFindPackageCommand::AddPrefixesCMakeSystemVariable()
1820 {
1821   if(!this->NoCMakeSystemPath && !this->NoDefaultPath)
1822     {
1823     this->AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
1824     this->AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
1825     this->AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
1826     }
1827 }
1828
1829 //----------------------------------------------------------------------------
1830 void cmFindPackageCommand::AddPrefixesUserGuess()
1831 {
1832   // Add guesses specified by the caller.
1833   this->AddPathsInternal(this->UserPaths, CMakePath);
1834 }
1835
1836 //----------------------------------------------------------------------------
1837 void cmFindPackageCommand::AddPrefixesUserHints()
1838 {
1839   // Add hints specified by the caller.
1840   this->AddPathsInternal(this->UserHints, CMakePath);
1841 }
1842
1843 //----------------------------------------------------------------------------
1844 bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
1845 {
1846   assert(!dir.empty() && dir[dir.size()-1] == '/');
1847
1848   // Check each path suffix on this directory.
1849   for(std::vector<std::string>::const_iterator
1850         si = this->SearchPathSuffixes.begin();
1851       si != this->SearchPathSuffixes.end(); ++si)
1852     {
1853     std::string d = dir;
1854     if(!si->empty())
1855       {
1856       d += *si;
1857       d += "/";
1858       }
1859     if(this->CheckDirectory(d))
1860       {
1861       return true;
1862       }
1863     }
1864   return false;
1865 }
1866
1867 //----------------------------------------------------------------------------
1868 bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
1869 {
1870   assert(!dir.empty() && dir[dir.size()-1] == '/');
1871
1872   // Look for the file in this directory.
1873   std::string d = dir.substr(0, dir.size()-1);
1874   if(this->FindConfigFile(d, this->FileFound))
1875     {
1876     // Remove duplicate slashes.
1877     cmSystemTools::ConvertToUnixSlashes(this->FileFound);
1878     return true;
1879     }
1880   return false;
1881 }
1882
1883 //----------------------------------------------------------------------------
1884 bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
1885                                           std::string& file)
1886 {
1887   if (this->IgnoredPaths.count(dir))
1888     {
1889     return false;
1890     }
1891
1892   for(std::vector<std::string>::const_iterator ci = this->Configs.begin();
1893       ci != this->Configs.end(); ++ci)
1894     {
1895     file = dir;
1896     file += "/";
1897     file += *ci;
1898     if(this->DebugMode)
1899       {
1900       fprintf(stderr, "Checking file [%s]\n", file.c_str());
1901       }
1902     if(cmSystemTools::FileExists(file.c_str(), true) &&
1903        this->CheckVersion(file))
1904       {
1905       return true;
1906       }
1907     }
1908   return false;
1909 }
1910
1911 //----------------------------------------------------------------------------
1912 bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
1913 {
1914   bool result = false; // by default, assume the version is not ok.
1915   bool haveResult = false;
1916   std::string version = "unknown";
1917
1918   // Get the filename without the .cmake extension.
1919   std::string::size_type pos = config_file.rfind('.');
1920   std::string version_file_base = config_file.substr(0, pos);
1921
1922   // Look for foo-config-version.cmake
1923   std::string version_file = version_file_base;
1924   version_file += "-version.cmake";
1925   if ((haveResult == false)
1926        && (cmSystemTools::FileExists(version_file.c_str(), true)))
1927     {
1928     result = this->CheckVersionFile(version_file, version);
1929     haveResult = true;
1930     }
1931
1932   // Look for fooConfigVersion.cmake
1933   version_file = version_file_base;
1934   version_file += "Version.cmake";
1935   if ((haveResult == false)
1936        && (cmSystemTools::FileExists(version_file.c_str(), true)))
1937     {
1938     result = this->CheckVersionFile(version_file, version);
1939     haveResult = true;
1940     }
1941
1942
1943   // If no version was requested a versionless package is acceptable.
1944   if ((haveResult == false) && (this->Version.empty()))
1945     {
1946     result = true;
1947     haveResult = true;
1948     }
1949
1950   ConfigFileInfo configFileInfo;
1951   configFileInfo.filename = config_file;
1952   configFileInfo.version = version;
1953   this->ConsideredConfigs.push_back(configFileInfo);
1954
1955   return result;
1956 }
1957
1958 //----------------------------------------------------------------------------
1959 bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
1960                                             std::string& result_version)
1961 {
1962   // The version file will be loaded in an isolated scope.
1963   cmMakefile::ScopePushPop varScope(this->Makefile);
1964   cmMakefile::PolicyPushPop polScope(this->Makefile);
1965   static_cast<void>(varScope);
1966   static_cast<void>(polScope);
1967
1968   // Clear the output variables.
1969   this->Makefile->RemoveDefinition("PACKAGE_VERSION");
1970   this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
1971   this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
1972   this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
1973
1974   // Set the input variables.
1975   this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name.c_str());
1976   this->Makefile->AddDefinition("PACKAGE_FIND_VERSION",
1977                                 this->Version.c_str());
1978   char buf[64];
1979   sprintf(buf, "%u", this->VersionMajor);
1980   this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MAJOR", buf);
1981   sprintf(buf, "%u", this->VersionMinor);
1982   this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MINOR", buf);
1983   sprintf(buf, "%u", this->VersionPatch);
1984   this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_PATCH", buf);
1985   sprintf(buf, "%u", this->VersionTweak);
1986   this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_TWEAK", buf);
1987   sprintf(buf, "%u", this->VersionCount);
1988   this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COUNT", buf);
1989
1990   // Load the version check file.  Pass NoPolicyScope because we do
1991   // our own policy push/pop independent of CMP0011.
1992   bool suitable = false;
1993   if(this->ReadListFile(version_file.c_str(), NoPolicyScope))
1994     {
1995     // Check the output variables.
1996     bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
1997     bool unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
1998     if(!okay && !this->VersionExact)
1999       {
2000       okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
2001       }
2002
2003     // The package is suitable if the version is okay and not
2004     // explicitly unsuitable.
2005     suitable = !unsuitable && (okay || this->Version.empty());
2006     if(suitable)
2007       {
2008       // Get the version found.
2009       this->VersionFound =
2010         this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
2011
2012       // Try to parse the version number and store the results that were
2013       // successfully parsed.
2014       unsigned int parsed_major;
2015       unsigned int parsed_minor;
2016       unsigned int parsed_patch;
2017       unsigned int parsed_tweak;
2018       this->VersionFoundCount =
2019         sscanf(this->VersionFound.c_str(), "%u.%u.%u.%u",
2020                &parsed_major, &parsed_minor,
2021                &parsed_patch, &parsed_tweak);
2022       switch(this->VersionFoundCount)
2023         {
2024         case 4: this->VersionFoundTweak = parsed_tweak; // no break!
2025         case 3: this->VersionFoundPatch = parsed_patch; // no break!
2026         case 2: this->VersionFoundMinor = parsed_minor; // no break!
2027         case 1: this->VersionFoundMajor = parsed_major; // no break!
2028         default: break;
2029         }
2030       }
2031     }
2032
2033   result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
2034   if (result_version.empty())
2035     {
2036     result_version = "unknown";
2037     }
2038
2039   // Succeed if the version is suitable.
2040   return suitable;
2041 }
2042
2043 //----------------------------------------------------------------------------
2044 void cmFindPackageCommand::StoreVersionFound()
2045 {
2046   // Store the whole version string.
2047   std::string ver = this->Name;
2048   ver += "_VERSION";
2049   if(this->VersionFound.empty())
2050     {
2051     this->Makefile->RemoveDefinition(ver.c_str());
2052     }
2053   else
2054     {
2055     this->Makefile->AddDefinition(ver.c_str(), this->VersionFound.c_str());
2056     }
2057
2058   // Store the version components.
2059   char buf[64];
2060   sprintf(buf, "%u", this->VersionFoundMajor);
2061   this->Makefile->AddDefinition((ver+"_MAJOR").c_str(), buf);
2062   sprintf(buf, "%u", this->VersionFoundMinor);
2063   this->Makefile->AddDefinition((ver+"_MINOR").c_str(), buf);
2064   sprintf(buf, "%u", this->VersionFoundPatch);
2065   this->Makefile->AddDefinition((ver+"_PATCH").c_str(), buf);
2066   sprintf(buf, "%u", this->VersionFoundTweak);
2067   this->Makefile->AddDefinition((ver+"_TWEAK").c_str(), buf);
2068   sprintf(buf, "%u", this->VersionFoundCount);
2069   this->Makefile->AddDefinition((ver+"_COUNT").c_str(), buf);
2070 }
2071
2072 //----------------------------------------------------------------------------
2073 #include <cmsys/Glob.hxx>
2074 #include <cmsys/String.h>
2075 #include <cmsys/auto_ptr.hxx>
2076
2077 class cmFileList;
2078 class cmFileListGeneratorBase
2079 {
2080 public:
2081   virtual ~cmFileListGeneratorBase() {}
2082 protected:
2083   bool Consider(std::string const& fullPath, cmFileList& listing);
2084 private:
2085   bool Search(cmFileList&);
2086   virtual bool Search(std::string const& parent, cmFileList&) = 0;
2087   virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const = 0;
2088   friend class cmFileList;
2089   cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
2090   cmsys::auto_ptr<cmFileListGeneratorBase> Next;
2091 };
2092
2093 class cmFileList
2094 {
2095 public:
2096   cmFileList(): First(), Last(0) {}
2097   virtual ~cmFileList() {}
2098   cmFileList& operator/(cmFileListGeneratorBase const& rhs)
2099     {
2100     if(this->Last)
2101       {
2102       this->Last = this->Last->SetNext(rhs);
2103       }
2104     else
2105       {
2106       this->First = rhs.Clone();
2107       this->Last = this->First.get();
2108       }
2109     return *this;
2110     }
2111   bool Search()
2112     {
2113     if(this->First.get())
2114       {
2115       return this->First->Search(*this);
2116       }
2117     return false;
2118     }
2119 private:
2120   virtual bool Visit(std::string const& fullPath) = 0;
2121   friend class cmFileListGeneratorBase;
2122   cmsys::auto_ptr<cmFileListGeneratorBase> First;
2123   cmFileListGeneratorBase* Last;
2124 };
2125
2126 class cmFindPackageFileList: public cmFileList
2127 {
2128 public:
2129   cmFindPackageFileList(cmFindPackageCommand* fpc,
2130                         bool use_suffixes = true):
2131     cmFileList(), FPC(fpc), UseSuffixes(use_suffixes) {}
2132 private:
2133   bool Visit(std::string const& fullPath)
2134     {
2135     if(this->UseSuffixes)
2136       {
2137       return this->FPC->SearchDirectory(fullPath);
2138       }
2139     else
2140       {
2141       return this->FPC->CheckDirectory(fullPath);
2142       }
2143     }
2144   cmFindPackageCommand* FPC;
2145   bool UseSuffixes;
2146 };
2147
2148 bool cmFileListGeneratorBase::Search(cmFileList& listing)
2149 {
2150   return this->Search("", listing);
2151 }
2152
2153 cmFileListGeneratorBase*
2154 cmFileListGeneratorBase::SetNext(cmFileListGeneratorBase const& next)
2155 {
2156   this->Next = next.Clone();
2157   return this->Next.get();
2158 }
2159
2160 bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
2161                                        cmFileList& listing)
2162 {
2163   if(this->Next.get())
2164     {
2165     return this->Next->Search(fullPath + "/", listing);
2166     }
2167   else
2168     {
2169     return listing.Visit(fullPath + "/");
2170     }
2171 }
2172
2173 class cmFileListGeneratorFixed: public cmFileListGeneratorBase
2174 {
2175 public:
2176   cmFileListGeneratorFixed(std::string const& str):
2177     cmFileListGeneratorBase(), String(str) {}
2178   cmFileListGeneratorFixed(cmFileListGeneratorFixed const& r):
2179     cmFileListGeneratorBase(), String(r.String) {}
2180 private:
2181   std::string String;
2182   virtual bool Search(std::string const& parent, cmFileList& lister)
2183     {
2184     std::string fullPath = parent + this->String;
2185     return this->Consider(fullPath, lister);
2186     }
2187   virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
2188     {
2189     cmsys::auto_ptr<cmFileListGeneratorBase>
2190       g(new cmFileListGeneratorFixed(*this));
2191     return g;
2192     }
2193 };
2194
2195 class cmFileListGeneratorEnumerate: public cmFileListGeneratorBase
2196 {
2197 public:
2198   cmFileListGeneratorEnumerate(std::vector<std::string> const& v):
2199     cmFileListGeneratorBase(), Vector(v) {}
2200   cmFileListGeneratorEnumerate(cmFileListGeneratorEnumerate const& r):
2201     cmFileListGeneratorBase(), Vector(r.Vector) {}
2202 private:
2203   std::vector<std::string> const& Vector;
2204   virtual bool Search(std::string const& parent, cmFileList& lister)
2205     {
2206     for(std::vector<std::string>::const_iterator i = this->Vector.begin();
2207         i != this->Vector.end(); ++i)
2208       {
2209       if(this->Consider(parent + *i, lister))
2210         {
2211         return true;
2212         }
2213       }
2214     return false;
2215     }
2216   virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
2217     {
2218     cmsys::auto_ptr<cmFileListGeneratorBase>
2219       g(new cmFileListGeneratorEnumerate(*this));
2220     return g;
2221     }
2222 };
2223
2224 class cmFileListGeneratorProject: public cmFileListGeneratorBase
2225 {
2226 public:
2227   cmFileListGeneratorProject(std::vector<std::string> const& names):
2228     cmFileListGeneratorBase(), Names(names) {}
2229   cmFileListGeneratorProject(cmFileListGeneratorProject const& r):
2230     cmFileListGeneratorBase(), Names(r.Names) {}
2231 private:
2232   std::vector<std::string> const& Names;
2233   virtual bool Search(std::string const& parent, cmFileList& lister)
2234     {
2235     // Construct a list of matches.
2236     std::vector<std::string> matches;
2237     cmsys::Directory d;
2238     d.Load(parent.c_str());
2239     for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
2240       {
2241       const char* fname = d.GetFile(i);
2242       if(strcmp(fname, ".") == 0 ||
2243          strcmp(fname, "..") == 0)
2244         {
2245         continue;
2246         }
2247       for(std::vector<std::string>::const_iterator ni = this->Names.begin();
2248           ni != this->Names.end(); ++ni)
2249         {
2250         if(cmsysString_strncasecmp(fname, ni->c_str(),
2251                                    ni->length()) == 0)
2252           {
2253           matches.push_back(fname);
2254           }
2255         }
2256       }
2257
2258     for(std::vector<std::string>::const_iterator i = matches.begin();
2259         i != matches.end(); ++i)
2260       {
2261       if(this->Consider(parent + *i, lister))
2262         {
2263         return true;
2264         }
2265       }
2266     return false;
2267     }
2268   virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
2269     {
2270     cmsys::auto_ptr<cmFileListGeneratorBase>
2271       g(new cmFileListGeneratorProject(*this));
2272     return g;
2273     }
2274 };
2275
2276 class cmFileListGeneratorMacProject: public cmFileListGeneratorBase
2277 {
2278 public:
2279   cmFileListGeneratorMacProject(std::vector<std::string> const& names,
2280                                 const char* ext):
2281     cmFileListGeneratorBase(), Names(names), Extension(ext) {}
2282   cmFileListGeneratorMacProject(cmFileListGeneratorMacProject const& r):
2283     cmFileListGeneratorBase(), Names(r.Names), Extension(r.Extension) {}
2284 private:
2285   std::vector<std::string> const& Names;
2286   std::string Extension;
2287   virtual bool Search(std::string const& parent, cmFileList& lister)
2288     {
2289     // Construct a list of matches.
2290     std::vector<std::string> matches;
2291     cmsys::Directory d;
2292     d.Load(parent.c_str());
2293     for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
2294       {
2295       const char* fname = d.GetFile(i);
2296       if(strcmp(fname, ".") == 0 ||
2297          strcmp(fname, "..") == 0)
2298         {
2299         continue;
2300         }
2301       for(std::vector<std::string>::const_iterator ni = this->Names.begin();
2302           ni != this->Names.end(); ++ni)
2303         {
2304         std::string name = *ni;
2305         name += this->Extension;
2306         if(cmsysString_strcasecmp(fname, name.c_str()) == 0)
2307           {
2308           matches.push_back(fname);
2309           }
2310         }
2311       }
2312
2313     for(std::vector<std::string>::const_iterator i = matches.begin();
2314         i != matches.end(); ++i)
2315       {
2316       if(this->Consider(parent + *i, lister))
2317         {
2318         return true;
2319         }
2320       }
2321     return false;
2322     }
2323   virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
2324     {
2325     cmsys::auto_ptr<cmFileListGeneratorBase>
2326       g(new cmFileListGeneratorMacProject(*this));
2327     return g;
2328     }
2329 };
2330
2331 class cmFileListGeneratorCaseInsensitive: public cmFileListGeneratorBase
2332 {
2333 public:
2334   cmFileListGeneratorCaseInsensitive(std::string const& str):
2335     cmFileListGeneratorBase(), String(str) {}
2336   cmFileListGeneratorCaseInsensitive(
2337     cmFileListGeneratorCaseInsensitive const& r):
2338     cmFileListGeneratorBase(), String(r.String) {}
2339 private:
2340   std::string String;
2341   virtual bool Search(std::string const& parent, cmFileList& lister)
2342     {
2343     // Look for matching files.
2344     std::vector<std::string> matches;
2345     cmsys::Directory d;
2346     d.Load(parent.c_str());
2347     for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
2348       {
2349       const char* fname = d.GetFile(i);
2350       if(strcmp(fname, ".") == 0 ||
2351          strcmp(fname, "..") == 0)
2352         {
2353         continue;
2354         }
2355       if(cmsysString_strcasecmp(fname, this->String.c_str()) == 0)
2356         {
2357         if(this->Consider(parent + fname, lister))
2358           {
2359           return true;
2360           }
2361         }
2362       }
2363     return false;
2364     }
2365   virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
2366     {
2367     cmsys::auto_ptr<cmFileListGeneratorBase>
2368       g(new cmFileListGeneratorCaseInsensitive(*this));
2369     return g;
2370     }
2371 };
2372
2373 class cmFileListGeneratorGlob: public cmFileListGeneratorBase
2374 {
2375 public:
2376   cmFileListGeneratorGlob(std::string const& str):
2377     cmFileListGeneratorBase(), Pattern(str) {}
2378   cmFileListGeneratorGlob(cmFileListGeneratorGlob const& r):
2379     cmFileListGeneratorBase(), Pattern(r.Pattern) {}
2380 private:
2381   std::string Pattern;
2382   virtual bool Search(std::string const& parent, cmFileList& lister)
2383     {
2384     // Glob the set of matching files.
2385     std::string expr = parent;
2386     expr += this->Pattern;
2387     cmsys::Glob g;
2388     if(!g.FindFiles(expr))
2389       {
2390       return false;
2391       }
2392     std::vector<std::string> const& files = g.GetFiles();
2393
2394     // Look for directories among the matches.
2395     for(std::vector<std::string>::const_iterator fi = files.begin();
2396         fi != files.end(); ++fi)
2397       {
2398       if(cmSystemTools::FileIsDirectory(fi->c_str()))
2399         {
2400         if(this->Consider(*fi, lister))
2401           {
2402           return true;
2403           }
2404         }
2405       }
2406     return false;
2407     }
2408   virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
2409     {
2410     cmsys::auto_ptr<cmFileListGeneratorBase>
2411       g(new cmFileListGeneratorGlob(*this));
2412     return g;
2413     }
2414 };
2415
2416 //----------------------------------------------------------------------------
2417 bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
2418 {
2419   assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
2420   if(this->DebugMode)
2421     {
2422     fprintf(stderr, "Checking prefix [%s]\n", prefix_in.c_str());
2423     }
2424
2425   // Skip this if the prefix does not exist.
2426   if(!cmSystemTools::FileIsDirectory(prefix_in.c_str()))
2427     {
2428     return false;
2429     }
2430
2431   //  PREFIX/ (useful on windows or in build trees)
2432   if(this->SearchDirectory(prefix_in))
2433     {
2434     return true;
2435     }
2436
2437   // Strip the trailing slash because the path generator is about to
2438   // add one.
2439   std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
2440
2441   //  PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
2442   {
2443   cmFindPackageFileList lister(this);
2444   lister
2445     / cmFileListGeneratorFixed(prefix)
2446     / cmFileListGeneratorCaseInsensitive("cmake");
2447   if(lister.Search())
2448     {
2449     return true;
2450     }
2451   }
2452
2453   //  PREFIX/(Foo|foo|FOO).*/
2454   {
2455   cmFindPackageFileList lister(this);
2456   lister
2457     / cmFileListGeneratorFixed(prefix)
2458     / cmFileListGeneratorProject(this->Names);
2459   if(lister.Search())
2460     {
2461     return true;
2462     }
2463   }
2464
2465   //  PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
2466   {
2467   cmFindPackageFileList lister(this);
2468   lister
2469     / cmFileListGeneratorFixed(prefix)
2470     / cmFileListGeneratorProject(this->Names)
2471     / cmFileListGeneratorCaseInsensitive("cmake");
2472   if(lister.Search())
2473     {
2474     return true;
2475     }
2476   }
2477
2478   // Construct list of common install locations (lib and share).
2479   std::vector<std::string> common;
2480   if(!this->LibraryArchitecture.empty())
2481     {
2482     common.push_back("lib/"+this->LibraryArchitecture);
2483     }
2484   if(this->UseLib64Paths)
2485     {
2486     common.push_back("lib64");
2487     }
2488   common.push_back("lib");
2489   common.push_back("share");
2490
2491   //  PREFIX/(lib/ARCH|lib|share)/cmake/(Foo|foo|FOO).*/
2492   {
2493   cmFindPackageFileList lister(this);
2494   lister
2495     / cmFileListGeneratorFixed(prefix)
2496     / cmFileListGeneratorEnumerate(common)
2497     / cmFileListGeneratorFixed("cmake")
2498     / cmFileListGeneratorProject(this->Names);
2499   if(lister.Search())
2500     {
2501     return true;
2502     }
2503   }
2504
2505   //  PREFIX/(lib/ARCH|lib|share)/(Foo|foo|FOO).*/
2506   {
2507   cmFindPackageFileList lister(this);
2508   lister
2509     / cmFileListGeneratorFixed(prefix)
2510     / cmFileListGeneratorEnumerate(common)
2511     / cmFileListGeneratorProject(this->Names);
2512   if(lister.Search())
2513     {
2514     return true;
2515     }
2516   }
2517
2518   //  PREFIX/(lib/ARCH|lib|share)/(Foo|foo|FOO).*/(cmake|CMake)/
2519   {
2520   cmFindPackageFileList lister(this);
2521   lister
2522     / cmFileListGeneratorFixed(prefix)
2523     / cmFileListGeneratorEnumerate(common)
2524     / cmFileListGeneratorProject(this->Names)
2525     / cmFileListGeneratorCaseInsensitive("cmake");
2526   if(lister.Search())
2527     {
2528     return true;
2529     }
2530   }
2531
2532   return false;
2533 }
2534
2535 //----------------------------------------------------------------------------
2536 bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
2537 {
2538   assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
2539   if(this->DebugMode)
2540     {
2541     fprintf(stderr, "Checking framework prefix [%s]\n", prefix_in.c_str());
2542     }
2543
2544   // Strip the trailing slash because the path generator is about to
2545   // add one.
2546   std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
2547
2548   // <prefix>/Foo.framework/Resources/
2549   {
2550   cmFindPackageFileList lister(this);
2551   lister
2552     / cmFileListGeneratorFixed(prefix)
2553     / cmFileListGeneratorMacProject(this->Names, ".framework")
2554     / cmFileListGeneratorFixed("Resources");
2555   if(lister.Search())
2556     {
2557     return true;
2558     }
2559   }
2560   // <prefix>/Foo.framework/Resources/CMake/
2561   {
2562   cmFindPackageFileList lister(this);
2563   lister
2564     / cmFileListGeneratorFixed(prefix)
2565     / cmFileListGeneratorMacProject(this->Names, ".framework")
2566     / cmFileListGeneratorFixed("Resources")
2567     / cmFileListGeneratorCaseInsensitive("cmake");
2568   if(lister.Search())
2569     {
2570     return true;
2571     }
2572   }
2573
2574   // <prefix>/Foo.framework/Versions/*/Resources/
2575   {
2576   cmFindPackageFileList lister(this);
2577   lister
2578     / cmFileListGeneratorFixed(prefix)
2579     / cmFileListGeneratorMacProject(this->Names, ".framework")
2580     / cmFileListGeneratorFixed("Versions")
2581     / cmFileListGeneratorGlob("*/Resources");
2582   if(lister.Search())
2583     {
2584     return true;
2585     }
2586   }
2587
2588   // <prefix>/Foo.framework/Versions/*/Resources/CMake/
2589   {
2590   cmFindPackageFileList lister(this);
2591   lister
2592     / cmFileListGeneratorFixed(prefix)
2593     / cmFileListGeneratorMacProject(this->Names, ".framework")
2594     / cmFileListGeneratorFixed("Versions")
2595     / cmFileListGeneratorGlob("*/Resources")
2596     / cmFileListGeneratorCaseInsensitive("cmake");
2597   if(lister.Search())
2598     {
2599     return true;
2600     }
2601   }
2602
2603   return false;
2604 }
2605
2606 //----------------------------------------------------------------------------
2607 bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
2608 {
2609   assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
2610   if(this->DebugMode)
2611     {
2612     fprintf(stderr, "Checking bundle prefix [%s]\n", prefix_in.c_str());
2613     }
2614
2615   // Strip the trailing slash because the path generator is about to
2616   // add one.
2617   std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
2618
2619   // <prefix>/Foo.app/Contents/Resources
2620   {
2621   cmFindPackageFileList lister(this);
2622   lister
2623     / cmFileListGeneratorFixed(prefix)
2624     / cmFileListGeneratorMacProject(this->Names, ".app")
2625     / cmFileListGeneratorFixed("Contents/Resources");
2626   if(lister.Search())
2627     {
2628     return true;
2629     }
2630   }
2631
2632   // <prefix>/Foo.app/Contents/Resources/CMake
2633   {
2634   cmFindPackageFileList lister(this);
2635   lister
2636     / cmFileListGeneratorFixed(prefix)
2637     / cmFileListGeneratorMacProject(this->Names, ".app")
2638     / cmFileListGeneratorFixed("Contents/Resources")
2639     / cmFileListGeneratorCaseInsensitive("cmake");
2640   if(lister.Search())
2641     {
2642     return true;
2643     }
2644   }
2645
2646   return false;
2647 }
2648
2649 // TODO: Debug cmsys::Glob double slash problem.