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
|
//
// CProject.cs: C/C++ Project
//
// Authors:
// Marcos David Marin Amador <MarcosMarin@gmail.com>
//
// Copyright (C) 2007 Marcos David Marin Amador
//
//
// This source code is licenced under The MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.CodeDom.Compiler;
using Mono.Addins;
using MonoDevelop.Core;
using MonoDevelop.Core.Gui;
using MonoDevelop.Core.Execution;
using MonoDevelop.Core.ProgressMonitoring;
using MonoDevelop.Projects;
using MonoDevelop.Projects.Serialization;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Deployment;
using MonoDevelop.Deployment.Linux;
using CBinding.Parser;
namespace CBinding
{
public enum Language {
C,
CPP
}
public enum CProjectCommands {
AddPackage,
UpdateClassPad,
SwapSourceHeader,
ShowPackageDetails
}
[DataInclude(typeof(CProjectConfiguration))]
public class CProject : Project, IDeployable
{
[ItemProperty ("Compiler", ValueType = typeof(CCompiler))]
private ICompiler compiler_manager;
[ItemProperty ("Language")]
private Language language;
[ItemProperty("Target")]
CBinding.CompileTarget target = CBinding.CompileTarget.Bin;
private ProjectPackageCollection packages = new ProjectPackageCollection ();
public event ProjectPackageEventHandler PackageAddedToProject;
public event ProjectPackageEventHandler PackageRemovedFromProject;
/// <summary>
/// Extensions for C/C++ source files
/// </summary>
public static string[] SourceExtensions = { ".C", ".CC", ".CPP", ".CXX" };
/// <summary>
/// Extensions for C/C++ header files
/// </summary>
public static string[] HeaderExtensions = { ".H", ".HH", ".HPP", ".HXX" };
private void Init ()
{
packages.Project = this;
IdeApp.Workspace.ItemAddedToSolution += OnEntryAddedToCombine;
}
public CProject ()
{
Init ();
}
public CProject (ProjectCreateInformation info,
XmlElement projectOptions, string language)
{
Init ();
string binPath = ".";
if (info != null) {
Name = info.ProjectName;
binPath = info.BinPath;
}
switch (language)
{
case "C":
this.language = Language.C;
break;
case "CPP":
this.language = Language.CPP;
break;
}
Compiler = null; // use default compiler depending on language
CProjectConfiguration configuration =
(CProjectConfiguration)CreateConfiguration ("Debug");
configuration.DefineSymbols = "DEBUG MONODEVELOP";
configuration.DebugMode = true;
Configurations.Add (configuration);
configuration =
(CProjectConfiguration)CreateConfiguration ("Release");
configuration.DebugMode = false;
configuration.OptimizationLevel = 3;
configuration.DefineSymbols = "MONODEVELOP";
Configurations.Add (configuration);
foreach (CProjectConfiguration c in Configurations) {
c.OutputDirectory = Path.Combine (binPath, c.Id);
c.SourceDirectory = info.ProjectBasePath;
c.Output = Name;
if (projectOptions != null) {
if (projectOptions.Attributes["Target"] != null) {
c.CompileTarget = (CBinding.CompileTarget)Enum.Parse (
typeof(CBinding.CompileTarget),
projectOptions.Attributes["Target"].InnerText);
}
if (projectOptions.Attributes["PauseConsoleOutput"] != null) {
c.PauseConsoleOutput = bool.Parse (
projectOptions.Attributes["PauseConsoleOutput"].InnerText);
}
if (projectOptions.Attributes["CompilerArgs"].InnerText != null) {
c.ExtraCompilerArguments = projectOptions.Attributes["CompilerArgs"].InnerText;
}
if (projectOptions.Attributes["LinkerArgs"].InnerText != null) {
c.ExtraLinkerArguments = projectOptions.Attributes["LinkerArgs"].InnerText;
}
}
}
}
public override string ProjectType {
get { return "Native"; }
}
public override string[] SupportedLanguages {
get { return new string[] { "C", "CPP" }; }
}
public CompileTarget CompileTarget {
get { return target; }
set { target = value; }
}
public override bool IsCompileable (string fileName)
{
string ext = Path.GetExtension (fileName.ToUpper ());
if (language == Language.C) {
return (ext == ".C");
} else {
return (0 <= Array.IndexOf (SourceExtensions, ext));
}
}
public override IEnumerable<SolutionItem> GetReferencedItems (string configuration)
{
List<string> project_names = new List<string> ();
foreach (Package p in Packages) {
if (p.IsProject && p.Name != Name) {
project_names.Add (p.Name);
}
}
foreach (SolutionItem e in ParentFolder.Items) {
if (e is CProject && project_names.Contains (e.Name)) {
yield return e;
}
}
}
public static bool IsHeaderFile (string filename)
{
return (0 <= Array.IndexOf (HeaderExtensions, Path.GetExtension (filename.ToUpper ())));
}
/// <summary>
/// Ths pkg-config package is for internal MonoDevelop use only, it is not deployed.
/// </summary>
public void WriteMDPkgPackage (string configuration)
{
string pkgfile = Path.Combine (BaseDirectory, Name + ".md.pc");
CProjectConfiguration config = (CProjectConfiguration)GetConfiguration (configuration);
List<string> headerDirectories = new List<string> ();
foreach (ProjectFile f in Files) {
if (IsHeaderFile (f.Name)) {
string dir = Path.GetDirectoryName (f.FilePath);
if (!headerDirectories.Contains (dir)) {
headerDirectories.Add (dir);
}
}
}
using (StreamWriter writer = new StreamWriter (pkgfile)) {
writer.WriteLine ("Name: {0}", Name);
writer.WriteLine ("Description: {0}", Description);
writer.WriteLine ("Version: {0}", Version);
writer.WriteLine ("Libs: -L{0} -l{1}", config.OutputDirectory, config.Output);
// writer.WriteLine ("Cflags: -I{0}", BaseDirectory);
writer.WriteLine ("Cflags: -I{0}", string.Join (" -I", headerDirectories.ToArray ()));
}
// If this project compiles into a shared object we need to
// export the output path to the LD_LIBRARY_PATH
string literal = "LD_LIBRARY_PATH";
string ld_library_path = Environment.GetEnvironmentVariable (literal);
if (string.IsNullOrEmpty (ld_library_path)) {
Environment.SetEnvironmentVariable (literal, config.OutputDirectory);
} else if (!ld_library_path.Contains (config.OutputDirectory)) {
ld_library_path = string.Format ("{0}:{1}", config.OutputDirectory, ld_library_path);
Environment.SetEnvironmentVariable (literal, ld_library_path);
}
}
/// <summary>
/// This is the pkg-config package that gets deployed.
/// <returns>The pkg-config package's filename</returns>
/// </summary>
private string WriteDeployablePgkPackage (CProjectConfiguration config)
{
// FIXME: This should probably be grabed from somewhere.
string prefix = "/usr/local";
string pkgfile = Path.Combine (BaseDirectory, Name + ".pc");
using (StreamWriter writer = new StreamWriter (pkgfile)) {
writer.WriteLine ("prefix={0}", prefix);
writer.WriteLine ("exec_prefix=${prefix}");
writer.WriteLine ("libdir=${exec_prefix}/lib");
writer.WriteLine ("includedir=${prefix}/include");
writer.WriteLine ();
writer.WriteLine ("Name: {0}", Name);
writer.WriteLine ("Description: {0}", Description);
writer.WriteLine ("Version: {0}", Version);
writer.WriteLine ("Requires: {0}", string.Join (" ", Packages.ToStringArray ()));
// TODO: How should I get this?
writer.WriteLine ("Conflicts: {0}", string.Empty);
writer.Write ("Libs: -L${libdir} ");
writer.WriteLine ("-l{0}", config.Output);
writer.Write ("Cflags: -I${includedir}/");
writer.WriteLine ("{0} {1}", Name, Compiler.GetDefineFlags (config));
}
return pkgfile;
}
protected override BuildResult DoBuild (IProgressMonitor monitor, string configuration)
{
CProjectConfiguration pc = (CProjectConfiguration) GetConfiguration (configuration);
pc.SourceDirectory = BaseDirectory;
return compiler_manager.Compile (
Files, packages,
pc,
monitor);
}
protected override void DoExecute (IProgressMonitor monitor, ExecutionContext context, string configuration)
{
CProjectConfiguration conf = (CProjectConfiguration) GetConfiguration (configuration);
string command = conf.Output;
string args = conf.CommandLineParameters;
string dir = Path.GetFullPath (conf.OutputDirectory);
string platform = "Native";
bool pause = conf.PauseConsoleOutput;
IConsole console;
if (conf.CompileTarget != CBinding.CompileTarget.Bin) {
MessageService.ShowMessage ("Compile target is not an executable!");
return;
}
monitor.Log.WriteLine ("Running project...");
if (conf.ExternalConsole)
console = context.ExternalConsoleFactory.CreateConsole (!pause);
else
console = context.ConsoleFactory.CreateConsole (!pause);
AggregatedOperationMonitor operationMonitor = new AggregatedOperationMonitor (monitor);
try {
IExecutionHandler handler = context.ExecutionHandlerFactory.CreateExecutionHandler (platform);
if (handler == null) {
monitor.ReportError ("Cannot execute \"" + command + "\". The selected execution mode is not supported in the " + platform + " platform.", null);
return;
}
IProcessAsyncOperation op = handler.Execute (Path.Combine (dir, command), args, dir, null, console);
operationMonitor.AddOperation (op);
op.WaitForCompleted ();
monitor.Log.WriteLine ("The operation exited with code: {0}", op.ExitCode);
} catch (Exception ex) {
monitor.ReportError ("Cannot execute \"" + command + "\"", ex);
} finally {
operationMonitor.Dispose ();
console.Dispose ();
}
}
protected override string OnGetOutputFileName (string configuration)
{
CProjectConfiguration conf = (CProjectConfiguration) GetConfiguration (configuration);
return Path.Combine (conf.OutputDirectory, conf.CompiledOutputName);
}
public override SolutionItemConfiguration CreateConfiguration (string name)
{
CProjectConfiguration conf = new CProjectConfiguration ();
conf.Name = name;
return conf;
}
public Language Language {
get { return language; }
set { language = value; }
}
public ICompiler Compiler {
get { return compiler_manager; }
set {
if (value != null) {
compiler_manager = value;
} else {
object[] compilers = AddinManager.GetExtensionObjects ("/CBinding/Compilers");
string compiler;
if (language == Language.C)
compiler = PropertyService.Get ("CBinding.DefaultCCompiler", new GccCompiler ().Name);
else
compiler = PropertyService.Get ("CBinding.DefaultCppCompiler", new GppCompiler ().Name);
foreach (ICompiler c in compilers) {
if (compiler == c.Name) {
compiler_manager = c;
}
}
}
}
}
[Browsable(false)]
[ItemProperty ("Packages")]
public ProjectPackageCollection Packages {
get { return packages; }
set {
packages = value;
packages.Project = this;
}
}
protected override void OnFileAddedToProject (ProjectFileEventArgs e)
{
base.OnFileAddedToProject (e);
if (!Loading && !IsCompileable (e.ProjectFile.Name) &&
e.ProjectFile.BuildAction == BuildAction.Compile) {
e.ProjectFile.BuildAction = BuildAction.Nothing;
}
if (e.ProjectFile.BuildAction == BuildAction.Compile)
TagDatabaseManager.Instance.UpdateFileTags (this, e.ProjectFile.Name);
}
protected override void OnFileChangedInProject (ProjectFileEventArgs e)
{
base.OnFileChangedInProject (e);
TagDatabaseManager.Instance.UpdateFileTags (this, e.ProjectFile.Name);
}
private static void OnEntryAddedToCombine (object sender, SolutionItemEventArgs e)
{
CProject p = e.SolutionItem as CProject;
if (p == null)
return;
foreach (ProjectFile f in p.Files)
TagDatabaseManager.Instance.UpdateFileTags (p, f.Name);
}
internal void NotifyPackageRemovedFromProject (Package package)
{
PackageRemovedFromProject (this, new ProjectPackageEventArgs (this, package));
}
internal void NotifyPackageAddedToProject (Package package)
{
PackageAddedToProject (this, new ProjectPackageEventArgs (this, package));
}
public DeployFileCollection GetDeployFiles (string solutionConfiguration)
{
DeployFileCollection deployFiles = new DeployFileCollection ();
CProjectConfiguration conf = (CProjectConfiguration) GetActiveConfiguration (solutionConfiguration);
CompileTarget target = conf.CompileTarget;
// Headers and resources
foreach (ProjectFile f in Files) {
if (f.BuildAction == BuildAction.FileCopy) {
string targetDirectory =
(IsHeaderFile (f.Name) ? TargetDirectory.Include : TargetDirectory.ProgramFiles);
deployFiles.Add (new DeployFile (this, f.FilePath, f.RelativePath, targetDirectory));
}
}
// Output
string output = GetOutputFileName (solutionConfiguration);
if (!string.IsNullOrEmpty (output)) {
string targetDirectory = string.Empty;
switch (target) {
case CompileTarget.Bin:
targetDirectory = TargetDirectory.ProgramFiles;
break;
case CompileTarget.SharedLibrary:
targetDirectory = TargetDirectory.ProgramFiles;
break;
case CompileTarget.StaticLibrary:
targetDirectory = TargetDirectory.ProgramFiles;
break;
}
deployFiles.Add (new DeployFile (this, output, Path.GetFileName (output), targetDirectory));
}
// PkgPackage
if (target != CompileTarget.Bin) {
string pkgfile = WriteDeployablePgkPackage (conf);
deployFiles.Add (new DeployFile (this, Path.Combine (BaseDirectory, pkgfile), pkgfile, LinuxTargetDirectory.PkgConfig));
}
return deployFiles;
}
/// <summary>
/// Finds the corresponding source or header file
/// </summary>
/// <param name="sourceFile">
/// The name of the file to be matched
/// <see cref="System.String"/>
/// </param>
/// <returns>
/// The corresponding file, or null if not found
/// <see cref="System.String"/>
/// </returns>
public string MatchingFile (string sourceFile) {
string filenameStub = Path.GetFileNameWithoutExtension (sourceFile);
bool wantHeader = !CProject.IsHeaderFile (sourceFile);
foreach (ProjectFile file in this.Files) {
if (filenameStub == Path.GetFileNameWithoutExtension (file.Name)
&& (wantHeader == IsHeaderFile (file.Name))) {
return file.Name;
}
}
return null;
}
}
}
|