1#!/bin/bash
2##
3##  Copyright (c) 2013 The WebM project authors. All Rights Reserved.
4##
5##  Use of this source code is governed by a BSD-style license
6##  that can be found in the LICENSE file in the root of the source
7##  tree. An additional intellectual property rights grant can be found
8##  in the file PATENTS.  All contributing project authors may
9##  be found in the AUTHORS file in the root of the source tree.
10##
11
12self=$0
13self_basename=${self##*/}
14self_dirname=$(dirname "$0")
15
16. "$self_dirname/msvs_common.sh"|| exit 127
17
18show_help() {
19    cat <<EOF
20Usage: ${self_basename} --name=projname [options] file1 [file2 ...]
21
22This script generates a Visual Studio project file from a list of source
23code files.
24
25Options:
26    --help                      Print this message
27    --exe                       Generate a project for building an Application
28    --lib                       Generate a project for creating a static library
29    --dll                       Generate a project for creating a dll
30    --static-crt                Use the static C runtime (/MT)
31    --enable-werror             Treat warnings as errors (/WX)
32    --target=isa-os-cc          Target specifier (required)
33    --out=filename              Write output to a file [stdout]
34    --name=project_name         Name of the project (required)
35    --proj-guid=GUID            GUID to use for the project
36    --module-def=filename       File containing export definitions (for DLLs)
37    --ver=version               Version (14-16) of visual studio to generate for
38    --src-path-bare=dir         Path to root of source tree
39    -Ipath/to/include           Additional include directories
40    -DFLAG[=value]              Preprocessor macros to define
41    -Lpath/to/lib               Additional library search paths
42    -llibname                   Library to link against
43EOF
44    exit 1
45}
46
47tag_content() {
48    local tag=$1
49    local content=$2
50    shift
51    shift
52    if [ $# -ne 0 ]; then
53        echo "${indent}<${tag}"
54        indent_push
55        tag_attributes "$@"
56        echo "${indent}>${content}</${tag}>"
57        indent_pop
58    else
59        echo "${indent}<${tag}>${content}</${tag}>"
60    fi
61}
62
63generate_filter() {
64    local name=$1
65    local pats=$2
66    local file_list_sz
67    local i
68    local f
69    local saveIFS="$IFS"
70    local pack
71    echo "generating filter '$name' from ${#file_list[@]} files" >&2
72    IFS=*
73
74    file_list_sz=${#file_list[@]}
75    for i in ${!file_list[@]}; do
76        f=${file_list[i]}
77        for pat in ${pats//;/$IFS}; do
78            if [ "${f##*.}" == "$pat" ]; then
79                unset file_list[i]
80
81                objf=$(echo ${f%.*}.obj \
82                       | sed -e "s,$src_path_bare,," \
83                             -e 's/^[\./]\+//g' -e 's,[:/ ],_,g')
84
85                if ([ "$pat" == "asm" ] || [ "$pat" == "s" ] || [ "$pat" == "S" ]) && $uses_asm; then
86                    # Avoid object file name collisions, i.e. vpx_config.c and
87                    # vpx_config.asm produce the same object file without
88                    # this additional suffix.
89                    objf=${objf%.obj}_asm.obj
90                    open_tag CustomBuild \
91                        Include="$f"
92                    for plat in "${platforms[@]}"; do
93                        for cfg in Debug Release; do
94                            tag_content Message "Assembling %(Filename)%(Extension)" \
95                                Condition="'\$(Configuration)|\$(Platform)'=='$cfg|$plat'"
96                            tag_content Command "$(eval echo \$asm_${cfg}_cmdline) -o \$(IntDir)$objf" \
97                                Condition="'\$(Configuration)|\$(Platform)'=='$cfg|$plat'"
98                            tag_content Outputs "\$(IntDir)$objf" \
99                                Condition="'\$(Configuration)|\$(Platform)'=='$cfg|$plat'"
100                        done
101                    done
102                    close_tag CustomBuild
103                elif [ "$pat" == "c" ] || \
104                     [ "$pat" == "cc" ] || [ "$pat" == "cpp" ]; then
105                    open_tag ClCompile \
106                        Include="$f"
107                    # Separate file names with Condition?
108                    tag_content ObjectFileName "\$(IntDir)$objf"
109                    # Check for AVX and turn it on to avoid warnings.
110                    if [[ $f =~ avx.?\.c$ ]]; then
111                        tag_content AdditionalOptions "/arch:AVX"
112                    fi
113                    close_tag ClCompile
114                elif [ "$pat" == "h" ] ; then
115                    tag ClInclude \
116                        Include="$f"
117                elif [ "$pat" == "vcxproj" ] ; then
118                    open_tag ProjectReference \
119                        Include="$f"
120                    depguid=`grep ProjectGuid "$f" | sed 's,.*<.*>\(.*\)</.*>.*,\1,'`
121                    tag_content Project "$depguid"
122                    tag_content ReferenceOutputAssembly false
123                    close_tag ProjectReference
124                else
125                    tag None \
126                        Include="$f"
127                fi
128
129                break
130            fi
131        done
132    done
133
134    IFS="$saveIFS"
135}
136
137# Process command line
138unset target
139for opt in "$@"; do
140    optval="${opt#*=}"
141    case "$opt" in
142        --help|-h) show_help
143        ;;
144        --target=*) target="${optval}"
145        ;;
146        --out=*) outfile="$optval"
147        ;;
148        --name=*) name="${optval}"
149        ;;
150        --proj-guid=*) guid="${optval}"
151        ;;
152        --module-def=*) module_def="${optval}"
153        ;;
154        --exe) proj_kind="exe"
155        ;;
156        --dll) proj_kind="dll"
157        ;;
158        --lib) proj_kind="lib"
159        ;;
160        --src-path-bare=*)
161            src_path_bare=$(fix_path "$optval")
162            src_path_bare=${src_path_bare%/}
163        ;;
164        --static-crt) use_static_runtime=true
165        ;;
166        --enable-werror) werror=true
167        ;;
168        --ver=*)
169            vs_ver="$optval"
170            case "$optval" in
171                1[4-6])
172                ;;
173                *) die Unrecognized Visual Studio Version in $opt
174                ;;
175            esac
176        ;;
177        -I*)
178            opt=${opt##-I}
179            opt=$(fix_path "$opt")
180            opt="${opt%/}"
181            incs="${incs}${incs:+;}&quot;${opt}&quot;"
182            yasmincs="${yasmincs} -I&quot;${opt}&quot;"
183        ;;
184        -D*) defines="${defines}${defines:+;}${opt##-D}"
185        ;;
186        -L*) # fudge . to $(OutDir)
187            if [ "${opt##-L}" == "." ]; then
188                libdirs="${libdirs}${libdirs:+;}&quot;\$(OutDir)&quot;"
189            else
190                 # Also try directories for this platform/configuration
191                 opt=${opt##-L}
192                 opt=$(fix_path "$opt")
193                 libdirs="${libdirs}${libdirs:+;}&quot;${opt}&quot;"
194                 libdirs="${libdirs}${libdirs:+;}&quot;${opt}/\$(PlatformName)/\$(Configuration)&quot;"
195                 libdirs="${libdirs}${libdirs:+;}&quot;${opt}/\$(PlatformName)&quot;"
196            fi
197        ;;
198        -l*) libs="${libs}${libs:+ }${opt##-l}.lib"
199        ;;
200        -*) die_unknown $opt
201        ;;
202        *)
203            # The paths in file_list are fixed outside of the loop.
204            file_list[${#file_list[@]}]="$opt"
205            case "$opt" in
206                 *.asm|*.[Ss]) uses_asm=true
207                 ;;
208            esac
209        ;;
210    esac
211done
212
213# Make one call to fix_path for file_list to improve performance.
214fix_file_list file_list
215
216outfile=${outfile:-/dev/stdout}
217guid=${guid:-`generate_uuid`}
218uses_asm=${uses_asm:-false}
219
220[ -n "$name" ] || die "Project name (--name) must be specified!"
221[ -n "$target" ] || die "Target (--target) must be specified!"
222
223if ${use_static_runtime:-false}; then
224    release_runtime=MultiThreaded
225    debug_runtime=MultiThreadedDebug
226    lib_sfx=mt
227else
228    release_runtime=MultiThreadedDLL
229    debug_runtime=MultiThreadedDebugDLL
230    lib_sfx=md
231fi
232
233# Calculate debug lib names: If a lib ends in ${lib_sfx}.lib, then rename
234# it to ${lib_sfx}d.lib. This precludes linking to release libs from a
235# debug exe, so this may need to be refactored later.
236for lib in ${libs}; do
237    if [ "$lib" != "${lib%${lib_sfx}.lib}" ]; then
238        lib=${lib%.lib}d.lib
239    fi
240    debug_libs="${debug_libs}${debug_libs:+ }${lib}"
241done
242debug_libs=${debug_libs// /;}
243libs=${libs// /;}
244
245
246# List of all platforms supported for this target
247case "$target" in
248    x86_64*)
249        platforms[0]="x64"
250        asm_Debug_cmdline="yasm -Xvc -g cv8 -f win64 ${yasmincs} &quot;%(FullPath)&quot;"
251        asm_Release_cmdline="yasm -Xvc -f win64 ${yasmincs} &quot;%(FullPath)&quot;"
252    ;;
253    x86*)
254        platforms[0]="Win32"
255        asm_Debug_cmdline="yasm -Xvc -g cv8 -f win32 ${yasmincs} &quot;%(FullPath)&quot;"
256        asm_Release_cmdline="yasm -Xvc -f win32 ${yasmincs} &quot;%(FullPath)&quot;"
257    ;;
258    arm64*)
259        platforms[0]="ARM64"
260        asm_Debug_cmdline="armasm64 -nologo -oldit &quot;%(FullPath)&quot;"
261        asm_Release_cmdline="armasm64 -nologo -oldit &quot;%(FullPath)&quot;"
262    ;;
263    arm*)
264        platforms[0]="ARM"
265        asm_Debug_cmdline="armasm -nologo -oldit &quot;%(FullPath)&quot;"
266        asm_Release_cmdline="armasm -nologo -oldit &quot;%(FullPath)&quot;"
267    ;;
268    *) die "Unsupported target $target!"
269    ;;
270esac
271
272generate_vcxproj() {
273    echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
274    open_tag Project \
275        DefaultTargets="Build" \
276        ToolsVersion="4.0" \
277        xmlns="http://schemas.microsoft.com/developer/msbuild/2003" \
278
279    open_tag ItemGroup \
280        Label="ProjectConfigurations"
281    for plat in "${platforms[@]}"; do
282        for config in Debug Release; do
283            open_tag ProjectConfiguration \
284                Include="$config|$plat"
285            tag_content Configuration $config
286            tag_content Platform $plat
287            close_tag ProjectConfiguration
288        done
289    done
290    close_tag ItemGroup
291
292    open_tag PropertyGroup \
293        Label="Globals"
294        tag_content ProjectGuid "{${guid}}"
295        tag_content RootNamespace ${name}
296        tag_content Keyword ManagedCProj
297        if [ $vs_ver -ge 12 ] && [ "${platforms[0]}" = "ARM" ]; then
298            tag_content AppContainerApplication true
299            # The application type can be one of "Windows Store",
300            # "Windows Phone" or "Windows Phone Silverlight". The
301            # actual value doesn't matter from the libvpx point of view,
302            # since a static library built for one works on the others.
303            # The PlatformToolset field needs to be set in sync with this;
304            # for Windows Store and Windows Phone Silverlight it should be
305            # v120 while it should be v120_wp81 if the type is Windows Phone.
306            tag_content ApplicationType "Windows Store"
307            tag_content ApplicationTypeRevision 8.1
308        fi
309        if [ "${platforms[0]}" = "ARM64" ]; then
310            # Require the first Visual Studio version to have ARM64 support.
311            tag_content MinimumVisualStudioVersion 15.9
312        fi
313        if [ $vs_ver -eq 15 ] && [ "${platforms[0]}" = "ARM64" ]; then
314            # Since VS 15 does not have a 'use latest SDK version' facility,
315            # specifically require the contemporaneous SDK with official ARM64
316            # support.
317            tag_content WindowsTargetPlatformVersion 10.0.17763.0
318        fi
319    close_tag PropertyGroup
320
321    tag Import \
322        Project="\$(VCTargetsPath)\\Microsoft.Cpp.Default.props"
323
324    for plat in "${platforms[@]}"; do
325        for config in Release Debug; do
326            open_tag PropertyGroup \
327                Condition="'\$(Configuration)|\$(Platform)'=='$config|$plat'" \
328                Label="Configuration"
329            if [ "$proj_kind" = "exe" ]; then
330                tag_content ConfigurationType Application
331            elif [ "$proj_kind" = "dll" ]; then
332                tag_content ConfigurationType DynamicLibrary
333            else
334                tag_content ConfigurationType StaticLibrary
335            fi
336            if [ "$vs_ver" = "14" ]; then
337                tag_content PlatformToolset v140
338            fi
339            if [ "$vs_ver" = "15" ]; then
340                tag_content PlatformToolset v141
341            fi
342            if [ "$vs_ver" = "16" ]; then
343                tag_content PlatformToolset v142
344            fi
345            tag_content CharacterSet Unicode
346            if [ "$config" = "Release" ]; then
347                tag_content WholeProgramOptimization true
348            fi
349            close_tag PropertyGroup
350        done
351    done
352
353    tag Import \
354        Project="\$(VCTargetsPath)\\Microsoft.Cpp.props"
355
356    open_tag ImportGroup \
357        Label="PropertySheets"
358        tag Import \
359            Project="\$(UserRootDir)\\Microsoft.Cpp.\$(Platform).user.props" \
360            Condition="exists('\$(UserRootDir)\\Microsoft.Cpp.\$(Platform).user.props')" \
361            Label="LocalAppDataPlatform"
362    close_tag ImportGroup
363
364    tag PropertyGroup \
365        Label="UserMacros"
366
367    for plat in "${platforms[@]}"; do
368        plat_no_ws=`echo $plat | sed 's/[^A-Za-z0-9_]/_/g'`
369        for config in Debug Release; do
370            open_tag PropertyGroup \
371                Condition="'\$(Configuration)|\$(Platform)'=='$config|$plat'"
372            tag_content OutDir "\$(SolutionDir)$plat_no_ws\\\$(Configuration)\\"
373            tag_content IntDir "$plat_no_ws\\\$(Configuration)\\${name}\\"
374            if [ "$proj_kind" == "lib" ]; then
375              if [ "$config" == "Debug" ]; then
376                config_suffix=d
377              else
378                config_suffix=""
379              fi
380              tag_content TargetName "${name}${lib_sfx}${config_suffix}"
381            fi
382            close_tag PropertyGroup
383        done
384    done
385
386    for plat in "${platforms[@]}"; do
387        for config in Debug Release; do
388            open_tag ItemDefinitionGroup \
389                Condition="'\$(Configuration)|\$(Platform)'=='$config|$plat'"
390            if [ "$name" == "vpx" ]; then
391                hostplat=$plat
392                if [ "$hostplat" == "ARM" ]; then
393                    hostplat=Win32
394                fi
395            fi
396            open_tag ClCompile
397            if [ "$config" = "Debug" ]; then
398                opt=Disabled
399                runtime=$debug_runtime
400                curlibs=$debug_libs
401                debug=_DEBUG
402            else
403                opt=MaxSpeed
404                runtime=$release_runtime
405                curlibs=$libs
406                tag_content FavorSizeOrSpeed Speed
407                debug=NDEBUG
408            fi
409            extradefines=";$defines"
410            tag_content Optimization $opt
411            tag_content AdditionalIncludeDirectories "$incs;%(AdditionalIncludeDirectories)"
412            tag_content PreprocessorDefinitions "WIN32;$debug;_CRT_SECURE_NO_WARNINGS;_CRT_SECURE_NO_DEPRECATE$extradefines;%(PreprocessorDefinitions)"
413            tag_content RuntimeLibrary $runtime
414            tag_content WarningLevel Level3
415            if ${werror:-false}; then
416                tag_content TreatWarningAsError true
417            fi
418            if [ $vs_ver -ge 11 ]; then
419                # We need to override the defaults for these settings
420                # if AppContainerApplication is set.
421                tag_content CompileAsWinRT false
422                tag_content PrecompiledHeader NotUsing
423                tag_content SDLCheck false
424            fi
425            close_tag ClCompile
426            case "$proj_kind" in
427            exe)
428                open_tag Link
429                tag_content GenerateDebugInformation true
430                # Console is the default normally, but if
431                # AppContainerApplication is set, we need to override it.
432                tag_content SubSystem Console
433                close_tag Link
434                ;;
435            dll)
436                open_tag Link
437                tag_content GenerateDebugInformation true
438                tag_content ModuleDefinitionFile $module_def
439                close_tag Link
440                ;;
441            lib)
442                ;;
443            esac
444            close_tag ItemDefinitionGroup
445        done
446
447    done
448
449    open_tag ItemGroup
450    generate_filter "Source Files"   "c;cc;cpp;def;odl;idl;hpj;bat;asm;asmx;s;S"
451    close_tag ItemGroup
452    open_tag ItemGroup
453    generate_filter "Header Files"   "h;hm;inl;inc;xsd"
454    close_tag ItemGroup
455    open_tag ItemGroup
456    generate_filter "Build Files"    "mk"
457    close_tag ItemGroup
458    open_tag ItemGroup
459    generate_filter "References"     "vcxproj"
460    close_tag ItemGroup
461
462    tag Import \
463        Project="\$(VCTargetsPath)\\Microsoft.Cpp.targets"
464
465    open_tag ImportGroup \
466        Label="ExtensionTargets"
467    close_tag ImportGroup
468
469    close_tag Project
470
471    # This must be done from within the {} subshell
472    echo "Ignored files list (${#file_list[@]} items) is:" >&2
473    for f in "${file_list[@]}"; do
474        echo "    $f" >&2
475    done
476}
477
478# This regexp doesn't catch most of the strings in the vcxproj format,
479# since they're like <tag>path</tag> instead of <tag attr="path" />
480# as previously. It still seems to work ok despite this.
481generate_vcxproj |
482    sed  -e '/"/s;\([^ "]\)/;\1\\;g' |
483    sed  -e '/xmlns/s;\\;/;g' > ${outfile}
484
485exit
486