summaryrefslogtreecommitdiffstats
path: root/src/net/sf/antcontrib/cpptasks/devstudio/VisualStudioNETProjectWriter.java
blob: 898503e05420dea4cb8ff515cce9097d908ec89c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
/*
 *
 * Copyright 2004-2006 The Ant-Contrib project
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package net.sf.antcontrib.cpptasks.devstudio;

import net.sf.antcontrib.cpptasks.CCTask;
import net.sf.antcontrib.cpptasks.CUtil;
import net.sf.antcontrib.cpptasks.TargetInfo;
import net.sf.antcontrib.cpptasks.compiler.CommandLineCompilerConfiguration;
import net.sf.antcontrib.cpptasks.compiler.ProcessorConfiguration;
import net.sf.antcontrib.cpptasks.compiler.CommandLineLinkerConfiguration;
import net.sf.antcontrib.cpptasks.ide.ProjectDef;
import net.sf.antcontrib.cpptasks.ide.ProjectWriter;
import org.apache.tools.ant.BuildException;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.Serializer;
import org.apache.xml.serialize.XMLSerializer;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Writes a Visual Studio.NET project file.
 *
 * @author curta
 */
public final class VisualStudioNETProjectWriter
        implements ProjectWriter {
    /**
     * Version of VisualStudio.NET.
     */
    private final String version;

    /**
     * Literal to represent a true value.
     */
    private final String trueLiteral;

    /**
     * Literal to represent a false value.
     */
    private final String falseLiteral;

    /**
     * Constructor.
     *
     * @param versionArg String VisualStudio.NET version
     * @param trueArg    literal to represent true, "true" in VC 2005.
     * @param falseArg    literal to represent false, "false" in VC 2005.
     */
    public VisualStudioNETProjectWriter(final String versionArg,
                                        final String trueArg,
                                        final String falseArg) {
        if (versionArg == null) {
            throw new IllegalArgumentException("versionArg");
        }
        if (trueArg == null) {
            throw new IllegalArgumentException("trueArg");
        }
        if (falseArg == null) {
            throw new IllegalArgumentException("falseArg");
        }
        this.version = versionArg;
        this.trueLiteral = trueArg;
        this.falseLiteral = falseArg;
    }

    /**
     * Get configuration name.
     * @param task cc task, may not be null.
     * @return configuration name.
     */
    private String getConfigurationName(final CCTask task) {
        if (task.getDebug()) {
            return "Debug|Win32";
        }
        return "Release|Win32";
    }

    /**
     * Gets the configuration type.
     *
     * @param task cc task, may not be null.
     * @return configuration type
     */
    private String getConfigurationType(final CCTask task) {
        String outputType = task.getOuttype();
        String targtype = "2"; // Win32 (x86) Dynamic-Link Library";
        if ("executable".equals(outputType)) {
            targtype = "1"; // "Win32 (x86) Console Application";
        } else if ("static".equals(outputType)) {
            targtype = "4"; //"Win32 (x86) Static Library";
        }
        return targtype;
    }

    /**
     * Get output directory.
     * @param basePath path to parent of project file.
     * @param task cc task, may not be null.
     * @return  output directory relative path.
     */
    private String getOutputDirectory(final String basePath,
                                      final CCTask task) {
        File outFile = task.getOutfile();
        File buildDir = outFile.getParentFile();
        return CUtil.getRelativePath(basePath, buildDir);
    }

    /**
     * Get object file directory.
     * @param basePath path to parent of project file.
     * @param task cc task, may not be null.
     * @return  object file directory relative path.
     */
    private String getIntermediateDirectory(final String basePath,
                                            final CCTask task) {
        File objDir = task.getObjdir();
        return CUtil.getRelativePath(basePath, objDir);
    }


    /**
     * Get character set for Windows API.
     * @param compilerConfig compiler configuration, may not be null.
     * @return "1" is TCHAR is unicode, "0" if TCHAR is multi-byte.
     */
    private String getCharacterSet(
            final CommandLineCompilerConfiguration compilerConfig) {
        String[] args = compilerConfig.getPreArguments();
        String charset = "0";
        for (int i = 0; i < args.length; i++) {
            if ("/D_UNICODE".equals(args[i]) || "/DUNICODE".equals(args[i])) {
                charset = "1";
            }
            if ("/D_MBCS".equals(args[i])) {
                charset = "2";
            }
        }
        return charset;
    }

    /**
     * Write the start tag of the Configuration element.
     * @param content serialization content handler.
     * @param basePath path of directory containing project file.
     * @param task cc task.
     * @param compilerConfig compiler configuration.
     * @throws SAXException thrown if serialization error.
     */
    private void writeConfigurationStartTag(final ContentHandler content,
                                            final String basePath,
                                            final CCTask task,
                  final CommandLineCompilerConfiguration compilerConfig)
            throws SAXException {
        AttributesImpl attributes = new AttributesImpl();
        addAttribute(attributes, "Name",
                getConfigurationName(task));
        addAttribute(attributes, "OutputDirectory",
                getOutputDirectory(basePath, task));
        addAttribute(attributes, "IntermediateDirectory",
                getIntermediateDirectory(basePath, task));
        addAttribute(attributes, "ConfigurationType",
                getConfigurationType(task));
        addAttribute(attributes, "CharacterSet",
                getCharacterSet(compilerConfig));
        content.startElement(null,
                "Configuration", "Configuration", attributes);
    }

    /**
     * Get value of Optimization property.
     * @param compilerConfig compiler configuration, may not be null.
     * @return value of Optimization property.
     */
    private String getOptimization(
            final CommandLineCompilerConfiguration compilerConfig) {
        String[] args = compilerConfig.getPreArguments();
        String opt = "0";
        for (int i = 0; i < args.length; i++) {
            if ("/Od".equals(args[i])) {
                opt = "0";
            }
            if ("/O1".equals(args[i])) {
                opt = "1";
            }
            if ("/O2".equals(args[i])) {
                opt = "2";
            }
            if ("/Ox".equals(args[i])) {
                opt = "3";
            }
        }
        return opt;
    }

    /**
     * Get value of AdditionalIncludeDirectories property.
     * @param compilerConfig compiler configuration.
     * @return value of AdditionalIncludeDirectories property.
     */
    private String getAdditionalIncludeDirectories(
            final CommandLineCompilerConfiguration compilerConfig) {
        StringBuffer includeDirs = new StringBuffer();
        String[] args = compilerConfig.getPreArguments();
        for (int i = 0; i < args.length; i++) {
            if (args[i].startsWith("/I")) {
                includeDirs.append(args[i].substring(2));
                includeDirs.append(';');
            }
        }

        if (includeDirs.length() > 0) {
            includeDirs.setLength(includeDirs.length() - 1);
        }
        return includeDirs.toString();
    }

    /**
     * Get value of PreprocessorDefinitions property.
     * @param compilerConfig compiler configuration.
     * @return value of PreprocessorDefinitions property.
     */
    private String getPreprocessorDefinitions(
            final CommandLineCompilerConfiguration compilerConfig) {
        StringBuffer defines = new StringBuffer();
        String[] args = compilerConfig.getPreArguments();
        for (int i = 0; i < args.length; i++) {
            if (args[i].startsWith("/D")) {
                defines.append(args[i].substring(2));
                defines.append(";");
            }
        }

        if (defines.length() > 0) {
            defines.setLength(defines.length() - 1);
        }
        return defines.toString();
    }

    /**
     * Get value of RuntimeLibrary property.
     * @param compilerConfig compiler configuration.
     * @return value of RuntimeLibrary property.
     */
    private String getRuntimeLibrary(
            final CommandLineCompilerConfiguration compilerConfig) {
        String rtl = null;
        String[] args = compilerConfig.getPreArguments();
        for (int i = 0; i < args.length; i++) {
            if ("/MT".equals(args[i])) {
                rtl = "0";
            }
            if ("/MTd".equals(args[i])) {
                rtl = "1";
            }
            if ("/MD".equals(args[i])) {
                rtl = "2";
            }
            if ("/MDd".equals(args[i])) {
                rtl = "3";
            }
        }
        return rtl;
    }

    /**
     * Get value of UsePrecompiledHeader property.
     * @param compilerConfig compiler configuration.
     * @return value of UsePrecompiledHeader property.
     */
    private String getUsePrecompiledHeader(
            final CommandLineCompilerConfiguration compilerConfig) {
        String usePCH = "0";
        String[] args = compilerConfig.getPreArguments();
        for (int i = 0; i < args.length; i++) {
            if ("/Yc".equals(args[i])) {
                usePCH = "1";
            }
            if ("/Yu".equals(args[i])) {
                usePCH = "2";
            }
        }
        return usePCH;
    }

    /**
     * Get value of PrecompiledHeaderFile property.
     * @param compilerConfig compiler configuration.
     * @return value of PrecompiledHeaderFile property.
     */
    private String getPrecompiledHeaderFile(
            final CommandLineCompilerConfiguration compilerConfig) {
        String pch = null;
        String[] args = compilerConfig.getPreArguments();
        for (int i = 0; i < args.length; i++) {
            if (args[i].startsWith("/Fp")) {
                pch = args[i].substring(3);
            }
        }
        return pch;
    }


    /**
     * Get value of MinimalRebuild property.
     * @param compilerConfig compiler configuration.
     * @return value of MinimalRebuild property.
     */
    private String getMinimalRebuild(
            final CommandLineCompilerConfiguration compilerConfig) {
        return trueLiteral;
    }

    /**
     * Get value of BasicRuntimeChecks property.
     * @param compilerConfig compiler configuration.
     * @return value of BasicRuntimeChecks property.
     */
    private String getBasicRuntimeChecks(
            final CommandLineCompilerConfiguration compilerConfig) {
        String checks = "0";
        String[] args = compilerConfig.getPreArguments();
        for (int i = 0; i < args.length; i++) {
            if ("/RTCs".equals(args[i])) {
                checks = "1";
            }
            if ("/RTCu".equals(args[i])) {
                checks = "2";
            }
            if ("/RTC1".equals(args[i]) || "/GZ".equals(args[i])) {
                checks = "3";
            }
        }
        return checks;
    }

    /**
     * Get value of WarningLevel property.
     * @param compilerConfig compiler configuration.
     * @return value of WarningLevel property.
     */
    private String getWarningLevel(
            final CommandLineCompilerConfiguration compilerConfig) {
        String warn = null;
        String[] args = compilerConfig.getPreArguments();
        for (int i = 0; i < args.length; i++) {
            if ("/W0".equals(args[i])) {
                warn = "0";
            }
            if ("/W1".equals(args[i])) {
                warn = "1";
            }
            if ("/W2".equals(args[i])) {
                warn = "2";
            }
            if ("/W3".equals(args[i])) {
                warn = "3";
            }
        }
        return warn;
    }

    /**
     * Get value of Detect64BitPortabilityProblems property.
     * @param compilerConfig compiler configuration.
     * @return value of Detect64BitPortabilityProblems property.
     */
    private String getDetect64BitPortabilityProblems(
            final CommandLineCompilerConfiguration compilerConfig) {
        String warn64 = null;
        String[] args = compilerConfig.getPreArguments();
        for (int i = 0; i < args.length; i++) {
            if ("/Wp64".equals(args[i])) {
                warn64 = trueLiteral;
            }
        }
        return warn64;
    }

    /**
     * Get value of DebugInformationFormat property.
     * @param compilerConfig compiler configuration.
     * @return value of DebugInformationFormat property.
     */
    private String getDebugInformationFormat(
            final CommandLineCompilerConfiguration compilerConfig) {
        String format = "0";
        String[] args = compilerConfig.getPreArguments();
        for (int i = 0; i < args.length; i++) {
            if ("/Z7".equals(args[i])) {
                format = "1";
            }
            if ("/Zi".equals(args[i])) {
                format = "3";
            }
            if ("/ZI".equals(args[i])) {
                format = "4";
            }
        }
        return format;
    }

    /**
     * write the Compiler element.
     * @param content serialization content handler.
     * @param compilerConfig compiler configuration.
     * @throws SAXException thrown if error during serialization.
     */
    private void writeCompilerElement(final ContentHandler content,
            final CommandLineCompilerConfiguration compilerConfig)
            throws SAXException {
        AttributesImpl attributes = new AttributesImpl();
        addAttribute(attributes, "Name", "VCCLCompilerTool");
        addAttribute(attributes, "Optimization",
                getOptimization(compilerConfig));
        addAttribute(attributes, "AdditionalIncludeDirectories",
                getAdditionalIncludeDirectories(compilerConfig));
        addAttribute(attributes, "PreprocessorDefinitions",
                getPreprocessorDefinitions(compilerConfig));
        addAttribute(attributes, "MinimalRebuild",
                getMinimalRebuild(compilerConfig));
        addAttribute(attributes, "BasicRuntimeChecks",
                getBasicRuntimeChecks(compilerConfig));
        addAttribute(attributes, "RuntimeLibrary",
                getRuntimeLibrary(compilerConfig));
        addAttribute(attributes, "UsePrecompiledHeader",
                getUsePrecompiledHeader(compilerConfig));
        addAttribute(attributes, "PrecompiledHeaderFile",
                getPrecompiledHeaderFile(compilerConfig));
        addAttribute(attributes, "WarningLevel",
                getWarningLevel(compilerConfig));
        addAttribute(attributes, "Detect64BitPortabilityProblems",
                getDetect64BitPortabilityProblems(compilerConfig));
        addAttribute(attributes, "DebugInformationFormat",
                getDebugInformationFormat(compilerConfig));
        content.startElement(null, "Tool", "Tool", attributes);
        content.endElement(null, "Tool", "Tool");

    }


    /**
     * Get value of LinkIncremental property.
     * @param linkerConfig linker configuration.
     * @return value of LinkIncremental property
     */
    private String getLinkIncremental(
            final CommandLineLinkerConfiguration linkerConfig) {
        String incremental = "0";
        String[] args = linkerConfig.getPreArguments();
        for (int i = 0; i < args.length; i++) {
            if ("/INCREMENTAL:NO".equals(args[i])) {
                incremental = "1";
            }
            if ("/INCREMENTAL:YES".equals(args[i])) {
                incremental = "2";
            }
        }
        return incremental;
    }

    /**
     * Get value of GenerateDebugInformation property.
     * @param linkerConfig linker configuration.
     * @return value of GenerateDebugInformation property
     */
    private String getGenerateDebugInformation(
            final CommandLineLinkerConfiguration linkerConfig) {
        String debug = falseLiteral;
        String[] args = linkerConfig.getPreArguments();
        for (int i = 0; i < args.length; i++) {
            if ("/DEBUG".equals(args[i])) {
                debug = trueLiteral;
            }
        }
        return debug;
    }

    /**
     * Get value of Subsystem property.
     * @param linkerConfig linker configuration.
     * @return value of Subsystem property
     */
    private String getSubsystem(
            final CommandLineLinkerConfiguration linkerConfig) {
        String subsystem = "0";
        String[] args = linkerConfig.getPreArguments();
        for (int i = 0; i < args.length; i++) {
            if ("/SUBSYSTEM:CONSOLE".equals(args[i])) {
                subsystem = "1";
            }
            if ("/SUBSYSTEM:WINDOWS".equals(args[i])) {
                subsystem = "2";
            }
            if ("/SUBSYSTEM:WINDOWSCE".equals(args[i])) {
                subsystem = "9";
            }
        }
        return subsystem;
    }

    /**
     * Get value of TargetMachine property.
     * @param linkerConfig linker configuration.
     * @return value of TargetMachine property
     */
    private String getTargetMachine(
            final CommandLineLinkerConfiguration linkerConfig) {
        String subsystem = "0";
        String[] args = linkerConfig.getPreArguments();
        for (int i = 0; i < args.length; i++) {
            if ("/MACHINE:X86".equals(args[i])) {
                subsystem = "1";
            }
        }
        return subsystem;
    }

    /**
     * Get value of AdditionalDependencies property.
     * @param linkTarget link target.
     * @param targets all targets.
     * @param basePath path to directory containing project file.
     * @return value of AdditionalDependencies property.
     */
    private String getAdditionalDependencies(final TargetInfo linkTarget,
                                             final Map targets,
                                             final String basePath) {
      String dependencies = null;
        File[] linkSources = linkTarget.getAllSources();
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < linkSources.length; i++) {
          //
          //   if file was not compiled or otherwise generated
          //
          if (targets.get(linkSources[i].getName()) == null) {
            String relPath = CUtil.getRelativePath(basePath, linkSources[i]);
            //
            //   if path has an embedded space then
            //      must quote
            if (relPath.indexOf(' ') > 0) {
              buf.append('\"');
              buf.append(relPath);
              buf.append('\"');
            } else {
               buf.append(relPath);
            }
            buf.append(';');
          }
        }
        if (buf.length() > 0) {
          buf.setLength(buf.length() - 1);
          dependencies = buf.toString();
        }
      return dependencies;

    }

    /**
     * Write Tool element for linker.
     * @param content serialization content handler.
     * @param basePath path to directory containing project file.
     * @param linkTarget link target.
     * @param targets  all targets.
     * @throws SAXException thrown if error during serialization.
     */
    private void writeLinkerElement(final ContentHandler content,
                                    final String basePath,
                                    final TargetInfo linkTarget,
                                    final Map targets) throws SAXException {
        AttributesImpl attributes = new AttributesImpl();
        addAttribute(attributes, "Name", "VCLinkerTool");

        ProcessorConfiguration config = linkTarget.getConfiguration();
        if (config instanceof CommandLineLinkerConfiguration) {
            CommandLineLinkerConfiguration linkerConfig =
                    (CommandLineLinkerConfiguration) config;
            if (linkerConfig.getLinker() instanceof DevStudioCompatibleLinker) {
                addAttribute(attributes, "LinkIncremental",
                        getLinkIncremental(linkerConfig));
                addAttribute(attributes, "GenerateDebugInformation",
                        getGenerateDebugInformation(linkerConfig));
                addAttribute(attributes, "SubSystem",
                        getSubsystem(linkerConfig));
                addAttribute(attributes, "TargetMachine",
                        getTargetMachine(linkerConfig));
            }
        }
        addAttribute(attributes, "AdditionalDependencies",
                getAdditionalDependencies(linkTarget, targets, basePath));
        content.startElement(null, "Tool", "Tool", attributes);
        content.endElement(null, "Tool", "Tool");
    }

    /**
     * Writes a project definition file.
     *
     * @param fileName   project name for file, should has .cbx extension
     * @param task       cc task for which to write project
     * @param projectDef project element
     * @param sources    source files
     * @param targets    compilation targets
     * @param linkTarget link target
     * @throws IOException  if I/O error
     * @throws SAXException if XML serialization error
     */
    public void writeProject(final File fileName,
                             final CCTask task,
                             final ProjectDef projectDef,
                             final List sources,
                             final Hashtable targets,
                             final TargetInfo linkTarget) throws
            IOException,
            SAXException {

        String projectName = projectDef.getName();
        if (projectName == null) {
            projectName = fileName.getName();
        }


        File vcprojFile = new File(fileName + ".vcproj");
        if (!projectDef.getOverwrite() && vcprojFile.exists()) {
            throw new BuildException("Not allowed to overwrite project file "
                    + vcprojFile.toString());
        }
        File slnFile = new File(fileName + ".sln");
        if (!projectDef.getOverwrite() && slnFile.exists()) {
            throw new BuildException("Not allowed to overwrite project file "
                    + slnFile.toString());
        }

        CommandLineCompilerConfiguration compilerConfig =
                getBaseCompilerConfiguration(targets);
        if (compilerConfig == null) {
            throw new BuildException(
                    "Unable to generate Visual Studio.NET project "
                            + "when Microsoft C++ is not used.");
        }

        OutputStream outStream = new FileOutputStream(fileName + ".vcproj");
        OutputFormat format = new OutputFormat("xml", "UTF-8", true);
        Serializer serializer = new XMLSerializer(outStream, format);
        ContentHandler content = serializer.asContentHandler();
        String basePath = fileName.getParentFile().getAbsolutePath();
        content.startDocument();
        AttributesImpl emptyAttrs = new AttributesImpl();

        AttributesImpl attributes = new AttributesImpl();
        addAttribute(attributes, "ProjectType", "Visual C++");
        addAttribute(attributes, "Version", version);
        addAttribute(attributes, "Name", projectName);
        content.startElement(null, "VisualStudioProject",
                "VisualStudioProject", attributes);

        content.startElement(null, "Platforms", "Platforms", emptyAttrs);
        attributes.clear();
        addAttribute(attributes, "Name", "Win32");
        content.startElement(null, "Platform", "Platform", attributes);
        content.endElement(null, "Platform", "Platform");
        content.endElement(null, "Platforms", "Platforms");
        content.startElement(null, "Configurations",
                "Configurations", emptyAttrs);

        writeConfigurationStartTag(content, basePath, task, compilerConfig);

        writeCompilerElement(content, compilerConfig);

        writeLinkerElement(content, basePath, linkTarget, targets);

        content.endElement(null, "Configuration", "Configuration");
        content.endElement(null, "Configurations", "Configurations");
        content.startElement(null, "References", "References", emptyAttrs);
        content.endElement(null, "References", "References");
        content.startElement(null, "Files", "Files", emptyAttrs);


        File[] sortedSources = new File[sources.size()];
        sources.toArray(sortedSources);
        Arrays.sort(sortedSources, new Comparator() {
            public int compare(final Object o1, final Object o2) {
                return ((File) o1).getName().compareTo(((File) o2).getName());
            }
        });

        writeFilteredSources("Source Files",
                "cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx",
                basePath, sortedSources, content);

        writeFilteredSources("Header Files", "h;hpp;hxx;hm;inl;inc;xsd",
                basePath, sortedSources, content);

        writeFilteredSources("Resource Files",
                "rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx",
                basePath, sortedSources, content);

        content.endElement(null, "Files", "Files");
        content.startElement(null, "Globals", "Globals", emptyAttrs);
        content.endElement(null, "Globals", "Globals");
        content.endElement(null, "VisualStudioProject", "VisualStudioProject");
        content.endDocument();
    }

    /**
     * Writes a cluster of source files to the project.
     *
     * @param name          name of filter
     * @param filter        file extensions
     * @param basePath      base path for files
     * @param sortedSources array of source files
     * @param content       generated project
     * @throws SAXException if invalid content
     */
    private void writeFilteredSources(final String name, final String filter,
                                      final String basePath,
                                      final File[] sortedSources,
                                      final ContentHandler content)
            throws SAXException {
        AttributesImpl filterAttrs = new AttributesImpl();
        filterAttrs.addAttribute(null, "Name", "Name", "#PCDATA", name);
        filterAttrs.addAttribute(null, "Filter", "Filter", "#PCDATA", filter);
        content.startElement(null, "Filter", "Filter", filterAttrs);


        AttributesImpl fileAttrs = new AttributesImpl();
        fileAttrs.addAttribute(null, "RelativePath", "RelativePath",
                "#PCDATA", "");


        for (int i = 0; i < sortedSources.length; i++) {
            if (isGroupMember(filter, sortedSources[i])) {
                String relativePath = CUtil.getRelativePath(basePath,
                        sortedSources[i]);
                fileAttrs.setValue(0, relativePath);
                content.startElement(null, "File", "File", fileAttrs);
                content.endElement(null, "File", "File");
            }
        }
        content.endElement(null, "Filter", "Filter");

    }

    /**
     * Returns true if the file has an extension that
     *   appears in the group filter.
     *
     * @param filter    String group filter
     * @param candidate File file
     * @return boolean true if member of group
     */
    private boolean isGroupMember(final String filter, final File candidate) {
        String fileName = candidate.getName();
        int lastDot = fileName.lastIndexOf('.');
        if (lastDot >= 0 && lastDot < fileName.length() - 1) {
            String extension =
                    ";" + fileName.substring(lastDot + 1).toLowerCase() + ";";
            String semiFilter = ";" + filter + ";";
            return semiFilter.indexOf(extension) >= 0;
        }
        return false;
    }


    /**
     * Adds an non-namespace-qualified attribute to attribute list.
     * @param attributes list of attributes.
     * @param attrName attribute name, may not be null.
     * @param attrValue attribute value, if null attribute is not added.
     */
    private static void addAttribute(final AttributesImpl attributes,
                                     final String attrName,
                                     final String attrValue) {
        if (attrName == null) {
            throw new IllegalArgumentException("attrName");
        }
        if (attrValue != null) {
            attributes.addAttribute(null, attrName, attrName,
                    "#PCDATA", attrValue);
        }
    }

    /**
     * Gets the first recognized compiler from the
     * compilation targets.
     * @param targets compilation targets
     * @return representative (hopefully) compiler configuration
     */
    private CommandLineCompilerConfiguration
            getBaseCompilerConfiguration(final Hashtable targets) {
        //
        //   get the first target and assume that it is representative
        //
        Iterator targetIter = targets.values().iterator();
        while (targetIter.hasNext()) {
            TargetInfo targetInfo = (TargetInfo) targetIter.next();
            ProcessorConfiguration config = targetInfo.getConfiguration();
            //
            //   for the first cl compiler
            //
            if (config instanceof CommandLineCompilerConfiguration) {
                CommandLineCompilerConfiguration compilerConfig =
                        (CommandLineCompilerConfiguration) config;
                if (compilerConfig.getCompiler()
                        instanceof DevStudioCCompiler) {
                    return compilerConfig;
                }
            }
        }
        return null;
  }
}