You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1999 lines
78 KiB

6 years ago
  1. """SCons.Tool.msvs
  2. Tool-specific initialization for Microsoft Visual Studio project files.
  3. There normally shouldn't be any need to import this module directly.
  4. It will usually be imported through the generic SCons.Tool.Tool()
  5. selection method.
  6. """
  7. #
  8. # Copyright (c) 2001 - 2017 The SCons Foundation
  9. #
  10. # Permission is hereby granted, free of charge, to any person obtaining
  11. # a copy of this software and associated documentation files (the
  12. # "Software"), to deal in the Software without restriction, including
  13. # without limitation the rights to use, copy, modify, merge, publish,
  14. # distribute, sublicense, and/or sell copies of the Software, and to
  15. # permit persons to whom the Software is furnished to do so, subject to
  16. # the following conditions:
  17. #
  18. # The above copyright notice and this permission notice shall be included
  19. # in all copies or substantial portions of the Software.
  20. #
  21. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  22. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  23. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. from __future__ import print_function
  29. __revision__ = "src/engine/SCons/Tool/msvs.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  30. import SCons.compat
  31. import base64
  32. import hashlib
  33. import ntpath
  34. import os
  35. import pickle
  36. import re
  37. import sys
  38. import SCons.Builder
  39. import SCons.Node.FS
  40. import SCons.Platform.win32
  41. import SCons.Script.SConscript
  42. import SCons.PathList
  43. import SCons.Util
  44. import SCons.Warnings
  45. from .MSCommon import msvc_exists, msvc_setup_env_once
  46. from SCons.Defaults import processDefines
  47. from SCons.compat import PICKLE_PROTOCOL
  48. ##############################################################################
  49. # Below here are the classes and functions for generation of
  50. # DSP/DSW/SLN/VCPROJ files.
  51. ##############################################################################
  52. def xmlify(s):
  53. s = s.replace("&", "&") # do this first
  54. s = s.replace("'", "'")
  55. s = s.replace('"', """)
  56. s = s.replace('<', "&lt;")
  57. s = s.replace('>', "&gt;")
  58. s = s.replace('\n', '&#x0A;')
  59. return s
  60. # Process a CPPPATH list in includes, given the env, target and source.
  61. # Returns a tuple of nodes.
  62. def processIncludes(includes, env, target, source):
  63. return SCons.PathList.PathList(includes).subst_path(env, target, source)
  64. external_makefile_guid = '{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}'
  65. def _generateGUID(slnfile, name):
  66. """This generates a dummy GUID for the sln file to use. It is
  67. based on the MD5 signatures of the sln filename plus the name of
  68. the project. It basically just needs to be unique, and not
  69. change with each invocation."""
  70. m = hashlib.md5()
  71. # Normalize the slnfile path to a Windows path (\ separators) so
  72. # the generated file has a consistent GUID even if we generate
  73. # it on a non-Windows platform.
  74. m.update(bytearray(ntpath.normpath(str(slnfile)) + str(name),'utf-8'))
  75. solution = m.hexdigest().upper()
  76. # convert most of the signature to GUID form (discard the rest)
  77. solution = "{" + solution[:8] + "-" + solution[8:12] + "-" + solution[12:16] + "-" + solution[16:20] + "-" + solution[20:32] + "}"
  78. return solution
  79. version_re = re.compile(r'(\d+\.\d+)(.*)')
  80. def msvs_parse_version(s):
  81. """
  82. Split a Visual Studio version, which may in fact be something like
  83. '7.0Exp', into is version number (returned as a float) and trailing
  84. "suite" portion.
  85. """
  86. num, suite = version_re.match(s).groups()
  87. return float(num), suite
  88. # This is how we re-invoke SCons from inside MSVS Project files.
  89. # The problem is that we might have been invoked as either scons.bat
  90. # or scons.py. If we were invoked directly as scons.py, then we could
  91. # use sys.argv[0] to find the SCons "executable," but that doesn't work
  92. # if we were invoked as scons.bat, which uses "python -c" to execute
  93. # things and ends up with "-c" as sys.argv[0]. Consequently, we have
  94. # the MSVS Project file invoke SCons the same way that scons.bat does,
  95. # which works regardless of how we were invoked.
  96. def getExecScriptMain(env, xml=None):
  97. scons_home = env.get('SCONS_HOME')
  98. if not scons_home and 'SCONS_LIB_DIR' in os.environ:
  99. scons_home = os.environ['SCONS_LIB_DIR']
  100. if scons_home:
  101. exec_script_main = "from os.path import join; import sys; sys.path = [ r'%s' ] + sys.path; import SCons.Script; SCons.Script.main()" % scons_home
  102. else:
  103. version = SCons.__version__
  104. exec_script_main = "from os.path import join; import sys; sys.path = [ join(sys.prefix, 'Lib', 'site-packages', 'scons-%(version)s'), join(sys.prefix, 'scons-%(version)s'), join(sys.prefix, 'Lib', 'site-packages', 'scons'), join(sys.prefix, 'scons') ] + sys.path; import SCons.Script; SCons.Script.main()" % locals()
  105. if xml:
  106. exec_script_main = xmlify(exec_script_main)
  107. return exec_script_main
  108. # The string for the Python executable we tell the Project file to use
  109. # is either sys.executable or, if an external PYTHON_ROOT environment
  110. # variable exists, $(PYTHON)ROOT\\python.exe (generalized a little to
  111. # pluck the actual executable name from sys.executable).
  112. try:
  113. python_root = os.environ['PYTHON_ROOT']
  114. except KeyError:
  115. python_executable = sys.executable
  116. else:
  117. python_executable = os.path.join('$$(PYTHON_ROOT)',
  118. os.path.split(sys.executable)[1])
  119. class Config(object):
  120. pass
  121. def splitFully(path):
  122. dir, base = os.path.split(path)
  123. if dir and dir != '' and dir != path:
  124. return splitFully(dir)+[base]
  125. if base == '':
  126. return []
  127. return [base]
  128. def makeHierarchy(sources):
  129. '''Break a list of files into a hierarchy; for each value, if it is a string,
  130. then it is a file. If it is a dictionary, it is a folder. The string is
  131. the original path of the file.'''
  132. hierarchy = {}
  133. for file in sources:
  134. path = splitFully(file)
  135. if len(path):
  136. dict = hierarchy
  137. for part in path[:-1]:
  138. if part not in dict:
  139. dict[part] = {}
  140. dict = dict[part]
  141. dict[path[-1]] = file
  142. #else:
  143. # print 'Warning: failed to decompose path for '+str(file)
  144. return hierarchy
  145. class _UserGenerator(object):
  146. '''
  147. Base class for .dsp.user file generator
  148. '''
  149. # Default instance values.
  150. # Ok ... a bit defensive, but it does not seem reasonable to crash the
  151. # build for a workspace user file. :-)
  152. usrhead = None
  153. usrdebg = None
  154. usrconf = None
  155. createfile = False
  156. def __init__(self, dspfile, source, env):
  157. # DebugSettings should be a list of debug dictionary sorted in the same order
  158. # as the target list and variants
  159. if 'variant' not in env:
  160. raise SCons.Errors.InternalError("You must specify a 'variant' argument (i.e. 'Debug' or " +\
  161. "'Release') to create an MSVSProject.")
  162. elif SCons.Util.is_String(env['variant']):
  163. variants = [env['variant']]
  164. elif SCons.Util.is_List(env['variant']):
  165. variants = env['variant']
  166. if 'DebugSettings' not in env or env['DebugSettings'] == None:
  167. dbg_settings = []
  168. elif SCons.Util.is_Dict(env['DebugSettings']):
  169. dbg_settings = [env['DebugSettings']]
  170. elif SCons.Util.is_List(env['DebugSettings']):
  171. if len(env['DebugSettings']) != len(variants):
  172. raise SCons.Errors.InternalError("Sizes of 'DebugSettings' and 'variant' lists must be the same.")
  173. dbg_settings = []
  174. for ds in env['DebugSettings']:
  175. if SCons.Util.is_Dict(ds):
  176. dbg_settings.append(ds)
  177. else:
  178. dbg_settings.append({})
  179. else:
  180. dbg_settings = []
  181. if len(dbg_settings) == 1:
  182. dbg_settings = dbg_settings * len(variants)
  183. self.createfile = self.usrhead and self.usrdebg and self.usrconf and \
  184. dbg_settings and bool([ds for ds in dbg_settings if ds])
  185. if self.createfile:
  186. dbg_settings = dict(list(zip(variants, dbg_settings)))
  187. for var, src in dbg_settings.items():
  188. # Update only expected keys
  189. trg = {}
  190. for key in [k for k in list(self.usrdebg.keys()) if k in src]:
  191. trg[key] = str(src[key])
  192. self.configs[var].debug = trg
  193. def UserHeader(self):
  194. encoding = self.env.subst('$MSVSENCODING')
  195. versionstr = self.versionstr
  196. self.usrfile.write(self.usrhead % locals())
  197. def UserProject(self):
  198. pass
  199. def Build(self):
  200. if not self.createfile:
  201. return
  202. try:
  203. filename = self.dspabs +'.user'
  204. self.usrfile = open(filename, 'w')
  205. except IOError as detail:
  206. raise SCons.Errors.InternalError('Unable to open "' + filename + '" for writing:' + str(detail))
  207. else:
  208. self.UserHeader()
  209. self.UserProject()
  210. self.usrfile.close()
  211. V9UserHeader = """\
  212. <?xml version="1.0" encoding="%(encoding)s"?>
  213. <VisualStudioUserFile
  214. \tProjectType="Visual C++"
  215. \tVersion="%(versionstr)s"
  216. \tShowAllFiles="false"
  217. \t>
  218. \t<Configurations>
  219. """
  220. V9UserConfiguration = """\
  221. \t\t<Configuration
  222. \t\t\tName="%(variant)s|%(platform)s"
  223. \t\t\t>
  224. \t\t\t<DebugSettings
  225. %(debug_settings)s
  226. \t\t\t/>
  227. \t\t</Configuration>
  228. """
  229. V9DebugSettings = {
  230. 'Command':'$(TargetPath)',
  231. 'WorkingDirectory': None,
  232. 'CommandArguments': None,
  233. 'Attach':'false',
  234. 'DebuggerType':'3',
  235. 'Remote':'1',
  236. 'RemoteMachine': None,
  237. 'RemoteCommand': None,
  238. 'HttpUrl': None,
  239. 'PDBPath': None,
  240. 'SQLDebugging': None,
  241. 'Environment': None,
  242. 'EnvironmentMerge':'true',
  243. 'DebuggerFlavor': None,
  244. 'MPIRunCommand': None,
  245. 'MPIRunArguments': None,
  246. 'MPIRunWorkingDirectory': None,
  247. 'ApplicationCommand': None,
  248. 'ApplicationArguments': None,
  249. 'ShimCommand': None,
  250. 'MPIAcceptMode': None,
  251. 'MPIAcceptFilter': None,
  252. }
  253. class _GenerateV7User(_UserGenerator):
  254. """Generates a Project file for MSVS .NET"""
  255. def __init__(self, dspfile, source, env):
  256. if self.version_num >= 9.0:
  257. self.usrhead = V9UserHeader
  258. self.usrconf = V9UserConfiguration
  259. self.usrdebg = V9DebugSettings
  260. _UserGenerator.__init__(self, dspfile, source, env)
  261. def UserProject(self):
  262. confkeys = sorted(self.configs.keys())
  263. for kind in confkeys:
  264. variant = self.configs[kind].variant
  265. platform = self.configs[kind].platform
  266. debug = self.configs[kind].debug
  267. if debug:
  268. debug_settings = '\n'.join(['\t\t\t\t%s="%s"' % (key, xmlify(value))
  269. for key, value in debug.items()
  270. if value is not None])
  271. self.usrfile.write(self.usrconf % locals())
  272. self.usrfile.write('\t</Configurations>\n</VisualStudioUserFile>')
  273. V10UserHeader = """\
  274. <?xml version="1.0" encoding="%(encoding)s"?>
  275. <Project ToolsVersion="%(versionstr)s" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  276. """
  277. V10UserConfiguration = """\
  278. \t<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">
  279. %(debug_settings)s
  280. \t</PropertyGroup>
  281. """
  282. V10DebugSettings = {
  283. 'LocalDebuggerCommand': None,
  284. 'LocalDebuggerCommandArguments': None,
  285. 'LocalDebuggerEnvironment': None,
  286. 'DebuggerFlavor': 'WindowsLocalDebugger',
  287. 'LocalDebuggerWorkingDirectory': None,
  288. 'LocalDebuggerAttach': None,
  289. 'LocalDebuggerDebuggerType': None,
  290. 'LocalDebuggerMergeEnvironment': None,
  291. 'LocalDebuggerSQLDebugging': None,
  292. 'RemoteDebuggerCommand': None,
  293. 'RemoteDebuggerCommandArguments': None,
  294. 'RemoteDebuggerWorkingDirectory': None,
  295. 'RemoteDebuggerServerName': None,
  296. 'RemoteDebuggerConnection': None,
  297. 'RemoteDebuggerDebuggerType': None,
  298. 'RemoteDebuggerAttach': None,
  299. 'RemoteDebuggerSQLDebugging': None,
  300. 'DeploymentDirectory': None,
  301. 'AdditionalFiles': None,
  302. 'RemoteDebuggerDeployDebugCppRuntime': None,
  303. 'WebBrowserDebuggerHttpUrl': None,
  304. 'WebBrowserDebuggerDebuggerType': None,
  305. 'WebServiceDebuggerHttpUrl': None,
  306. 'WebServiceDebuggerDebuggerType': None,
  307. 'WebServiceDebuggerSQLDebugging': None,
  308. }
  309. class _GenerateV10User(_UserGenerator):
  310. """Generates a Project'user file for MSVS 2010"""
  311. def __init__(self, dspfile, source, env):
  312. self.versionstr = '4.0'
  313. self.usrhead = V10UserHeader
  314. self.usrconf = V10UserConfiguration
  315. self.usrdebg = V10DebugSettings
  316. _UserGenerator.__init__(self, dspfile, source, env)
  317. def UserProject(self):
  318. confkeys = sorted(self.configs.keys())
  319. for kind in confkeys:
  320. variant = self.configs[kind].variant
  321. platform = self.configs[kind].platform
  322. debug = self.configs[kind].debug
  323. if debug:
  324. debug_settings = '\n'.join(['\t\t<%s>%s</%s>' % (key, xmlify(value), key)
  325. for key, value in debug.items()
  326. if value is not None])
  327. self.usrfile.write(self.usrconf % locals())
  328. self.usrfile.write('</Project>')
  329. class _DSPGenerator(object):
  330. """ Base class for DSP generators """
  331. srcargs = [
  332. 'srcs',
  333. 'incs',
  334. 'localincs',
  335. 'resources',
  336. 'misc']
  337. def __init__(self, dspfile, source, env):
  338. self.dspfile = str(dspfile)
  339. try:
  340. get_abspath = dspfile.get_abspath
  341. except AttributeError:
  342. self.dspabs = os.path.abspath(dspfile)
  343. else:
  344. self.dspabs = get_abspath()
  345. if 'variant' not in env:
  346. raise SCons.Errors.InternalError("You must specify a 'variant' argument (i.e. 'Debug' or " +\
  347. "'Release') to create an MSVSProject.")
  348. elif SCons.Util.is_String(env['variant']):
  349. variants = [env['variant']]
  350. elif SCons.Util.is_List(env['variant']):
  351. variants = env['variant']
  352. if 'buildtarget' not in env or env['buildtarget'] == None:
  353. buildtarget = ['']
  354. elif SCons.Util.is_String(env['buildtarget']):
  355. buildtarget = [env['buildtarget']]
  356. elif SCons.Util.is_List(env['buildtarget']):
  357. if len(env['buildtarget']) != len(variants):
  358. raise SCons.Errors.InternalError("Sizes of 'buildtarget' and 'variant' lists must be the same.")
  359. buildtarget = []
  360. for bt in env['buildtarget']:
  361. if SCons.Util.is_String(bt):
  362. buildtarget.append(bt)
  363. else:
  364. buildtarget.append(bt.get_abspath())
  365. else:
  366. buildtarget = [env['buildtarget'].get_abspath()]
  367. if len(buildtarget) == 1:
  368. bt = buildtarget[0]
  369. buildtarget = []
  370. for _ in variants:
  371. buildtarget.append(bt)
  372. if 'outdir' not in env or env['outdir'] == None:
  373. outdir = ['']
  374. elif SCons.Util.is_String(env['outdir']):
  375. outdir = [env['outdir']]
  376. elif SCons.Util.is_List(env['outdir']):
  377. if len(env['outdir']) != len(variants):
  378. raise SCons.Errors.InternalError("Sizes of 'outdir' and 'variant' lists must be the same.")
  379. outdir = []
  380. for s in env['outdir']:
  381. if SCons.Util.is_String(s):
  382. outdir.append(s)
  383. else:
  384. outdir.append(s.get_abspath())
  385. else:
  386. outdir = [env['outdir'].get_abspath()]
  387. if len(outdir) == 1:
  388. s = outdir[0]
  389. outdir = []
  390. for v in variants:
  391. outdir.append(s)
  392. if 'runfile' not in env or env['runfile'] == None:
  393. runfile = buildtarget[-1:]
  394. elif SCons.Util.is_String(env['runfile']):
  395. runfile = [env['runfile']]
  396. elif SCons.Util.is_List(env['runfile']):
  397. if len(env['runfile']) != len(variants):
  398. raise SCons.Errors.InternalError("Sizes of 'runfile' and 'variant' lists must be the same.")
  399. runfile = []
  400. for s in env['runfile']:
  401. if SCons.Util.is_String(s):
  402. runfile.append(s)
  403. else:
  404. runfile.append(s.get_abspath())
  405. else:
  406. runfile = [env['runfile'].get_abspath()]
  407. if len(runfile) == 1:
  408. s = runfile[0]
  409. runfile = []
  410. for v in variants:
  411. runfile.append(s)
  412. self.sconscript = env['MSVSSCONSCRIPT']
  413. if 'cmdargs' not in env or env['cmdargs'] == None:
  414. cmdargs = [''] * len(variants)
  415. elif SCons.Util.is_String(env['cmdargs']):
  416. cmdargs = [env['cmdargs']] * len(variants)
  417. elif SCons.Util.is_List(env['cmdargs']):
  418. if len(env['cmdargs']) != len(variants):
  419. raise SCons.Errors.InternalError("Sizes of 'cmdargs' and 'variant' lists must be the same.")
  420. else:
  421. cmdargs = env['cmdargs']
  422. self.env = env
  423. if 'name' in self.env:
  424. self.name = self.env['name']
  425. else:
  426. self.name = os.path.basename(SCons.Util.splitext(self.dspfile)[0])
  427. self.name = self.env.subst(self.name)
  428. sourcenames = [
  429. 'Source Files',
  430. 'Header Files',
  431. 'Local Headers',
  432. 'Resource Files',
  433. 'Other Files']
  434. self.sources = {}
  435. for n in sourcenames:
  436. self.sources[n] = []
  437. self.configs = {}
  438. self.nokeep = 0
  439. if 'nokeep' in env and env['variant'] != 0:
  440. self.nokeep = 1
  441. if self.nokeep == 0 and os.path.exists(self.dspabs):
  442. self.Parse()
  443. for t in zip(sourcenames,self.srcargs):
  444. if t[1] in self.env:
  445. if SCons.Util.is_List(self.env[t[1]]):
  446. for i in self.env[t[1]]:
  447. if not i in self.sources[t[0]]:
  448. self.sources[t[0]].append(i)
  449. else:
  450. if not self.env[t[1]] in self.sources[t[0]]:
  451. self.sources[t[0]].append(self.env[t[1]])
  452. for n in sourcenames:
  453. self.sources[n].sort(key=lambda a: a.lower())
  454. def AddConfig(self, variant, buildtarget, outdir, runfile, cmdargs, dspfile=dspfile):
  455. config = Config()
  456. config.buildtarget = buildtarget
  457. config.outdir = outdir
  458. config.cmdargs = cmdargs
  459. config.runfile = runfile
  460. match = re.match('(.*)\|(.*)', variant)
  461. if match:
  462. config.variant = match.group(1)
  463. config.platform = match.group(2)
  464. else:
  465. config.variant = variant
  466. config.platform = 'Win32'
  467. self.configs[variant] = config
  468. print("Adding '" + self.name + ' - ' + config.variant + '|' + config.platform + "' to '" + str(dspfile) + "'")
  469. for i in range(len(variants)):
  470. AddConfig(self, variants[i], buildtarget[i], outdir[i], runfile[i], cmdargs[i])
  471. self.platforms = []
  472. for key in list(self.configs.keys()):
  473. platform = self.configs[key].platform
  474. if not platform in self.platforms:
  475. self.platforms.append(platform)
  476. def Build(self):
  477. pass
  478. V6DSPHeader = """\
  479. # Microsoft Developer Studio Project File - Name="%(name)s" - Package Owner=<4>
  480. # Microsoft Developer Studio Generated Build File, Format Version 6.00
  481. # ** DO NOT EDIT **
  482. # TARGTYPE "Win32 (x86) External Target" 0x0106
  483. CFG=%(name)s - Win32 %(confkey)s
  484. !MESSAGE This is not a valid makefile. To build this project using NMAKE,
  485. !MESSAGE use the Export Makefile command and run
  486. !MESSAGE
  487. !MESSAGE NMAKE /f "%(name)s.mak".
  488. !MESSAGE
  489. !MESSAGE You can specify a configuration when running NMAKE
  490. !MESSAGE by defining the macro CFG on the command line. For example:
  491. !MESSAGE
  492. !MESSAGE NMAKE /f "%(name)s.mak" CFG="%(name)s - Win32 %(confkey)s"
  493. !MESSAGE
  494. !MESSAGE Possible choices for configuration are:
  495. !MESSAGE
  496. """
  497. class _GenerateV6DSP(_DSPGenerator):
  498. """Generates a Project file for MSVS 6.0"""
  499. def PrintHeader(self):
  500. # pick a default config
  501. confkeys = sorted(self.configs.keys())
  502. name = self.name
  503. confkey = confkeys[0]
  504. self.file.write(V6DSPHeader % locals())
  505. for kind in confkeys:
  506. self.file.write('!MESSAGE "%s - Win32 %s" (based on "Win32 (x86) External Target")\n' % (name, kind))
  507. self.file.write('!MESSAGE \n\n')
  508. def PrintProject(self):
  509. name = self.name
  510. self.file.write('# Begin Project\n'
  511. '# PROP AllowPerConfigDependencies 0\n'
  512. '# PROP Scc_ProjName ""\n'
  513. '# PROP Scc_LocalPath ""\n\n')
  514. first = 1
  515. confkeys = sorted(self.configs.keys())
  516. for kind in confkeys:
  517. outdir = self.configs[kind].outdir
  518. buildtarget = self.configs[kind].buildtarget
  519. if first == 1:
  520. self.file.write('!IF "$(CFG)" == "%s - Win32 %s"\n\n' % (name, kind))
  521. first = 0
  522. else:
  523. self.file.write('\n!ELSEIF "$(CFG)" == "%s - Win32 %s"\n\n' % (name, kind))
  524. env_has_buildtarget = 'MSVSBUILDTARGET' in self.env
  525. if not env_has_buildtarget:
  526. self.env['MSVSBUILDTARGET'] = buildtarget
  527. # have to write this twice, once with the BASE settings, and once without
  528. for base in ("BASE ",""):
  529. self.file.write('# PROP %sUse_MFC 0\n'
  530. '# PROP %sUse_Debug_Libraries ' % (base, base))
  531. if kind.lower().find('debug') < 0:
  532. self.file.write('0\n')
  533. else:
  534. self.file.write('1\n')
  535. self.file.write('# PROP %sOutput_Dir "%s"\n'
  536. '# PROP %sIntermediate_Dir "%s"\n' % (base,outdir,base,outdir))
  537. cmd = 'echo Starting SCons && ' + self.env.subst('$MSVSBUILDCOM', 1)
  538. self.file.write('# PROP %sCmd_Line "%s"\n'
  539. '# PROP %sRebuild_Opt "-c && %s"\n'
  540. '# PROP %sTarget_File "%s"\n'
  541. '# PROP %sBsc_Name ""\n'
  542. '# PROP %sTarget_Dir ""\n'\
  543. %(base,cmd,base,cmd,base,buildtarget,base,base))
  544. if not env_has_buildtarget:
  545. del self.env['MSVSBUILDTARGET']
  546. self.file.write('\n!ENDIF\n\n'
  547. '# Begin Target\n\n')
  548. for kind in confkeys:
  549. self.file.write('# Name "%s - Win32 %s"\n' % (name,kind))
  550. self.file.write('\n')
  551. first = 0
  552. for kind in confkeys:
  553. if first == 0:
  554. self.file.write('!IF "$(CFG)" == "%s - Win32 %s"\n\n' % (name,kind))
  555. first = 1
  556. else:
  557. self.file.write('!ELSEIF "$(CFG)" == "%s - Win32 %s"\n\n' % (name,kind))
  558. self.file.write('!ENDIF \n\n')
  559. self.PrintSourceFiles()
  560. self.file.write('# End Target\n'
  561. '# End Project\n')
  562. if self.nokeep == 0:
  563. # now we pickle some data and add it to the file -- MSDEV will ignore it.
  564. pdata = pickle.dumps(self.configs,PICKLE_PROTOCOL)
  565. pdata = base64.encodestring(pdata).decode()
  566. self.file.write(pdata + '\n')
  567. pdata = pickle.dumps(self.sources,PICKLE_PROTOCOL)
  568. pdata = base64.encodestring(pdata).decode()
  569. self.file.write(pdata + '\n')
  570. def PrintSourceFiles(self):
  571. categories = {'Source Files': 'cpp|c|cxx|l|y|def|odl|idl|hpj|bat',
  572. 'Header Files': 'h|hpp|hxx|hm|inl',
  573. 'Local Headers': 'h|hpp|hxx|hm|inl',
  574. 'Resource Files': 'r|rc|ico|cur|bmp|dlg|rc2|rct|bin|cnt|rtf|gif|jpg|jpeg|jpe',
  575. 'Other Files': ''}
  576. for kind in sorted(list(categories.keys()), key=lambda a: a.lower()):
  577. if not self.sources[kind]:
  578. continue # skip empty groups
  579. self.file.write('# Begin Group "' + kind + '"\n\n')
  580. typelist = categories[kind].replace('|', ';')
  581. self.file.write('# PROP Default_Filter "' + typelist + '"\n')
  582. for file in self.sources[kind]:
  583. file = os.path.normpath(file)
  584. self.file.write('# Begin Source File\n\n'
  585. 'SOURCE="' + file + '"\n'
  586. '# End Source File\n')
  587. self.file.write('# End Group\n')
  588. # add the SConscript file outside of the groups
  589. self.file.write('# Begin Source File\n\n'
  590. 'SOURCE="' + str(self.sconscript) + '"\n'
  591. '# End Source File\n')
  592. def Parse(self):
  593. try:
  594. dspfile = open(self.dspabs,'r')
  595. except IOError:
  596. return # doesn't exist yet, so can't add anything to configs.
  597. line = dspfile.readline()
  598. while line:
  599. if line.find("# End Project") > -1:
  600. break
  601. line = dspfile.readline()
  602. line = dspfile.readline()
  603. datas = line
  604. while line and line != '\n':
  605. line = dspfile.readline()
  606. datas = datas + line
  607. # OK, we've found our little pickled cache of data.
  608. try:
  609. datas = base64.decodestring(datas)
  610. data = pickle.loads(datas)
  611. except KeyboardInterrupt:
  612. raise
  613. except:
  614. return # unable to unpickle any data for some reason
  615. self.configs.update(data)
  616. data = None
  617. line = dspfile.readline()
  618. datas = line
  619. while line and line != '\n':
  620. line = dspfile.readline()
  621. datas = datas + line
  622. # OK, we've found our little pickled cache of data.
  623. # it has a "# " in front of it, so we strip that.
  624. try:
  625. datas = base64.decodestring(datas)
  626. data = pickle.loads(datas)
  627. except KeyboardInterrupt:
  628. raise
  629. except:
  630. return # unable to unpickle any data for some reason
  631. self.sources.update(data)
  632. def Build(self):
  633. try:
  634. self.file = open(self.dspabs,'w')
  635. except IOError as detail:
  636. raise SCons.Errors.InternalError('Unable to open "' + self.dspabs + '" for writing:' + str(detail))
  637. else:
  638. self.PrintHeader()
  639. self.PrintProject()
  640. self.file.close()
  641. V7DSPHeader = """\
  642. <?xml version="1.0" encoding="%(encoding)s"?>
  643. <VisualStudioProject
  644. \tProjectType="Visual C++"
  645. \tVersion="%(versionstr)s"
  646. \tName="%(name)s"
  647. \tProjectGUID="%(project_guid)s"
  648. %(scc_attrs)s
  649. \tKeyword="MakeFileProj">
  650. """
  651. V7DSPConfiguration = """\
  652. \t\t<Configuration
  653. \t\t\tName="%(variant)s|%(platform)s"
  654. \t\t\tOutputDirectory="%(outdir)s"
  655. \t\t\tIntermediateDirectory="%(outdir)s"
  656. \t\t\tConfigurationType="0"
  657. \t\t\tUseOfMFC="0"
  658. \t\t\tATLMinimizesCRunTimeLibraryUsage="FALSE">
  659. \t\t\t<Tool
  660. \t\t\t\tName="VCNMakeTool"
  661. \t\t\t\tBuildCommandLine="%(buildcmd)s"
  662. \t\t\t\tReBuildCommandLine="%(rebuildcmd)s"
  663. \t\t\t\tCleanCommandLine="%(cleancmd)s"
  664. \t\t\t\tOutput="%(runfile)s"/>
  665. \t\t</Configuration>
  666. """
  667. V8DSPHeader = """\
  668. <?xml version="1.0" encoding="%(encoding)s"?>
  669. <VisualStudioProject
  670. \tProjectType="Visual C++"
  671. \tVersion="%(versionstr)s"
  672. \tName="%(name)s"
  673. \tProjectGUID="%(project_guid)s"
  674. \tRootNamespace="%(name)s"
  675. %(scc_attrs)s
  676. \tKeyword="MakeFileProj">
  677. """
  678. V8DSPConfiguration = """\
  679. \t\t<Configuration
  680. \t\t\tName="%(variant)s|%(platform)s"
  681. \t\t\tConfigurationType="0"
  682. \t\t\tUseOfMFC="0"
  683. \t\t\tATLMinimizesCRunTimeLibraryUsage="false"
  684. \t\t\t>
  685. \t\t\t<Tool
  686. \t\t\t\tName="VCNMakeTool"
  687. \t\t\t\tBuildCommandLine="%(buildcmd)s"
  688. \t\t\t\tReBuildCommandLine="%(rebuildcmd)s"
  689. \t\t\t\tCleanCommandLine="%(cleancmd)s"
  690. \t\t\t\tOutput="%(runfile)s"
  691. \t\t\t\tPreprocessorDefinitions="%(preprocdefs)s"
  692. \t\t\t\tIncludeSearchPath="%(includepath)s"
  693. \t\t\t\tForcedIncludes=""
  694. \t\t\t\tAssemblySearchPath=""
  695. \t\t\t\tForcedUsingAssemblies=""
  696. \t\t\t\tCompileAsManaged=""
  697. \t\t\t/>
  698. \t\t</Configuration>
  699. """
  700. class _GenerateV7DSP(_DSPGenerator, _GenerateV7User):
  701. """Generates a Project file for MSVS .NET"""
  702. def __init__(self, dspfile, source, env):
  703. _DSPGenerator.__init__(self, dspfile, source, env)
  704. self.version = env['MSVS_VERSION']
  705. self.version_num, self.suite = msvs_parse_version(self.version)
  706. if self.version_num >= 9.0:
  707. self.versionstr = '9.00'
  708. self.dspheader = V8DSPHeader
  709. self.dspconfiguration = V8DSPConfiguration
  710. elif self.version_num >= 8.0:
  711. self.versionstr = '8.00'
  712. self.dspheader = V8DSPHeader
  713. self.dspconfiguration = V8DSPConfiguration
  714. else:
  715. if self.version_num >= 7.1:
  716. self.versionstr = '7.10'
  717. else:
  718. self.versionstr = '7.00'
  719. self.dspheader = V7DSPHeader
  720. self.dspconfiguration = V7DSPConfiguration
  721. self.file = None
  722. _GenerateV7User.__init__(self, dspfile, source, env)
  723. def PrintHeader(self):
  724. env = self.env
  725. versionstr = self.versionstr
  726. name = self.name
  727. encoding = self.env.subst('$MSVSENCODING')
  728. scc_provider = env.get('MSVS_SCC_PROVIDER', '')
  729. scc_project_name = env.get('MSVS_SCC_PROJECT_NAME', '')
  730. scc_aux_path = env.get('MSVS_SCC_AUX_PATH', '')
  731. # MSVS_SCC_LOCAL_PATH is kept for backwards compatibility purpose and should
  732. # be deprecated as soon as possible.
  733. scc_local_path_legacy = env.get('MSVS_SCC_LOCAL_PATH', '')
  734. scc_connection_root = env.get('MSVS_SCC_CONNECTION_ROOT', os.curdir)
  735. scc_local_path = os.path.relpath(scc_connection_root, os.path.dirname(self.dspabs))
  736. project_guid = env.get('MSVS_PROJECT_GUID', '')
  737. if not project_guid:
  738. project_guid = _generateGUID(self.dspfile, '')
  739. if scc_provider != '':
  740. scc_attrs = '\tSccProjectName="%s"\n' % scc_project_name
  741. if scc_aux_path != '':
  742. scc_attrs += '\tSccAuxPath="%s"\n' % scc_aux_path
  743. scc_attrs += ('\tSccLocalPath="%s"\n'
  744. '\tSccProvider="%s"' % (scc_local_path, scc_provider))
  745. elif scc_local_path_legacy != '':
  746. # This case is kept for backwards compatibility purpose and should
  747. # be deprecated as soon as possible.
  748. scc_attrs = ('\tSccProjectName="%s"\n'
  749. '\tSccLocalPath="%s"' % (scc_project_name, scc_local_path_legacy))
  750. else:
  751. self.dspheader = self.dspheader.replace('%(scc_attrs)s\n', '')
  752. self.file.write(self.dspheader % locals())
  753. self.file.write('\t<Platforms>\n')
  754. for platform in self.platforms:
  755. self.file.write(
  756. '\t\t<Platform\n'
  757. '\t\t\tName="%s"/>\n' % platform)
  758. self.file.write('\t</Platforms>\n')
  759. if self.version_num >= 8.0:
  760. self.file.write('\t<ToolFiles>\n'
  761. '\t</ToolFiles>\n')
  762. def PrintProject(self):
  763. self.file.write('\t<Configurations>\n')
  764. confkeys = sorted(self.configs.keys())
  765. for kind in confkeys:
  766. variant = self.configs[kind].variant
  767. platform = self.configs[kind].platform
  768. outdir = self.configs[kind].outdir
  769. buildtarget = self.configs[kind].buildtarget
  770. runfile = self.configs[kind].runfile
  771. cmdargs = self.configs[kind].cmdargs
  772. env_has_buildtarget = 'MSVSBUILDTARGET' in self.env
  773. if not env_has_buildtarget:
  774. self.env['MSVSBUILDTARGET'] = buildtarget
  775. starting = 'echo Starting SCons && '
  776. if cmdargs:
  777. cmdargs = ' ' + cmdargs
  778. else:
  779. cmdargs = ''
  780. buildcmd = xmlify(starting + self.env.subst('$MSVSBUILDCOM', 1) + cmdargs)
  781. rebuildcmd = xmlify(starting + self.env.subst('$MSVSREBUILDCOM', 1) + cmdargs)
  782. cleancmd = xmlify(starting + self.env.subst('$MSVSCLEANCOM', 1) + cmdargs)
  783. # This isn't perfect; CPPDEFINES and CPPPATH can contain $TARGET and $SOURCE,
  784. # so they could vary depending on the command being generated. This code
  785. # assumes they don't.
  786. preprocdefs = xmlify(';'.join(processDefines(self.env.get('CPPDEFINES', []))))
  787. includepath_Dirs = processIncludes(self.env.get('CPPPATH', []), self.env, None, None)
  788. includepath = xmlify(';'.join([str(x) for x in includepath_Dirs]))
  789. if not env_has_buildtarget:
  790. del self.env['MSVSBUILDTARGET']
  791. self.file.write(self.dspconfiguration % locals())
  792. self.file.write('\t</Configurations>\n')
  793. if self.version_num >= 7.1:
  794. self.file.write('\t<References>\n'
  795. '\t</References>\n')
  796. self.PrintSourceFiles()
  797. self.file.write('</VisualStudioProject>\n')
  798. if self.nokeep == 0:
  799. # now we pickle some data and add it to the file -- MSDEV will ignore it.
  800. pdata = pickle.dumps(self.configs,PICKLE_PROTOCOL)
  801. pdata = base64.encodestring(pdata).decode()
  802. self.file.write('<!-- SCons Data:\n' + pdata + '\n')
  803. pdata = pickle.dumps(self.sources,PICKLE_PROTOCOL)
  804. pdata = base64.encodestring(pdata).decode()
  805. self.file.write(pdata + '-->\n')
  806. def printSources(self, hierarchy, commonprefix):
  807. sorteditems = sorted(hierarchy.items(), key=lambda a: a[0].lower())
  808. # First folders, then files
  809. for key, value in sorteditems:
  810. if SCons.Util.is_Dict(value):
  811. self.file.write('\t\t\t<Filter\n'
  812. '\t\t\t\tName="%s"\n'
  813. '\t\t\t\tFilter="">\n' % (key))
  814. self.printSources(value, commonprefix)
  815. self.file.write('\t\t\t</Filter>\n')
  816. for key, value in sorteditems:
  817. if SCons.Util.is_String(value):
  818. file = value
  819. if commonprefix:
  820. file = os.path.join(commonprefix, value)
  821. file = os.path.normpath(file)
  822. self.file.write('\t\t\t<File\n'
  823. '\t\t\t\tRelativePath="%s">\n'
  824. '\t\t\t</File>\n' % (file))
  825. def PrintSourceFiles(self):
  826. categories = {'Source Files': 'cpp;c;cxx;l;y;def;odl;idl;hpj;bat',
  827. 'Header Files': 'h;hpp;hxx;hm;inl',
  828. 'Local Headers': 'h;hpp;hxx;hm;inl',
  829. 'Resource Files': 'r;rc;ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe',
  830. 'Other Files': ''}
  831. self.file.write('\t<Files>\n')
  832. cats = sorted([k for k in list(categories.keys()) if self.sources[k]],
  833. key=lambda a: a.lower())
  834. for kind in cats:
  835. if len(cats) > 1:
  836. self.file.write('\t\t<Filter\n'
  837. '\t\t\tName="%s"\n'
  838. '\t\t\tFilter="%s">\n' % (kind, categories[kind]))
  839. sources = self.sources[kind]
  840. # First remove any common prefix
  841. commonprefix = None
  842. s = list(map(os.path.normpath, sources))
  843. # take the dirname because the prefix may include parts
  844. # of the filenames (e.g. if you have 'dir\abcd' and
  845. # 'dir\acde' then the cp will be 'dir\a' )
  846. cp = os.path.dirname( os.path.commonprefix(s) )
  847. if cp and s[0][len(cp)] == os.sep:
  848. # +1 because the filename starts after the separator
  849. sources = [s[len(cp)+1:] for s in sources]
  850. commonprefix = cp
  851. hierarchy = makeHierarchy(sources)
  852. self.printSources(hierarchy, commonprefix=commonprefix)
  853. if len(cats)>1:
  854. self.file.write('\t\t</Filter>\n')
  855. # add the SConscript file outside of the groups
  856. self.file.write('\t\t<File\n'
  857. '\t\t\tRelativePath="%s">\n'
  858. '\t\t</File>\n' % str(self.sconscript))
  859. self.file.write('\t</Files>\n'
  860. '\t<Globals>\n'
  861. '\t</Globals>\n')
  862. def Parse(self):
  863. try:
  864. dspfile = open(self.dspabs,'r')
  865. except IOError:
  866. return # doesn't exist yet, so can't add anything to configs.
  867. line = dspfile.readline()
  868. while line:
  869. if line.find('<!-- SCons Data:') > -1:
  870. break
  871. line = dspfile.readline()
  872. line = dspfile.readline()
  873. datas = line
  874. while line and line != '\n':
  875. line = dspfile.readline()
  876. datas = datas + line
  877. # OK, we've found our little pickled cache of data.
  878. try:
  879. datas = base64.decodestring(datas)
  880. data = pickle.loads(datas)
  881. except KeyboardInterrupt:
  882. raise
  883. except:
  884. return # unable to unpickle any data for some reason
  885. self.configs.update(data)
  886. data = None
  887. line = dspfile.readline()
  888. datas = line
  889. while line and line != '\n':
  890. line = dspfile.readline()
  891. datas = datas + line
  892. # OK, we've found our little pickled cache of data.
  893. try:
  894. datas = base64.decodestring(datas)
  895. data = pickle.loads(datas)
  896. except KeyboardInterrupt:
  897. raise
  898. except:
  899. return # unable to unpickle any data for some reason
  900. self.sources.update(data)
  901. def Build(self):
  902. try:
  903. self.file = open(self.dspabs,'w')
  904. except IOError as detail:
  905. raise SCons.Errors.InternalError('Unable to open "' + self.dspabs + '" for writing:' + str(detail))
  906. else:
  907. self.PrintHeader()
  908. self.PrintProject()
  909. self.file.close()
  910. _GenerateV7User.Build(self)
  911. V10DSPHeader = """\
  912. <?xml version="1.0" encoding="%(encoding)s"?>
  913. <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  914. """
  915. V10DSPProjectConfiguration = """\
  916. \t\t<ProjectConfiguration Include="%(variant)s|%(platform)s">
  917. \t\t\t<Configuration>%(variant)s</Configuration>
  918. \t\t\t<Platform>%(platform)s</Platform>
  919. \t\t</ProjectConfiguration>
  920. """
  921. V10DSPGlobals = """\
  922. \t<PropertyGroup Label="Globals">
  923. \t\t<ProjectGuid>%(project_guid)s</ProjectGuid>
  924. %(scc_attrs)s\t\t<RootNamespace>%(name)s</RootNamespace>
  925. \t\t<Keyword>MakeFileProj</Keyword>
  926. \t</PropertyGroup>
  927. """
  928. V10DSPPropertyGroupCondition = """\
  929. \t<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'" Label="Configuration">
  930. \t\t<ConfigurationType>Makefile</ConfigurationType>
  931. \t\t<UseOfMfc>false</UseOfMfc>
  932. \t\t<PlatformToolset>%(toolset)s</PlatformToolset>
  933. \t</PropertyGroup>
  934. """
  935. V10DSPImportGroupCondition = """\
  936. \t<ImportGroup Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'" Label="PropertySheets">
  937. \t\t<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  938. \t</ImportGroup>
  939. """
  940. V10DSPCommandLine = """\
  941. \t\t<NMakeBuildCommandLine Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">%(buildcmd)s</NMakeBuildCommandLine>
  942. \t\t<NMakeReBuildCommandLine Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">%(rebuildcmd)s</NMakeReBuildCommandLine>
  943. \t\t<NMakeCleanCommandLine Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">%(cleancmd)s</NMakeCleanCommandLine>
  944. \t\t<NMakeOutput Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">%(runfile)s</NMakeOutput>
  945. \t\t<NMakePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">%(preprocdefs)s</NMakePreprocessorDefinitions>
  946. \t\t<NMakeIncludeSearchPath Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">%(includepath)s</NMakeIncludeSearchPath>
  947. \t\t<NMakeForcedIncludes Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">$(NMakeForcedIncludes)</NMakeForcedIncludes>
  948. \t\t<NMakeAssemblySearchPath Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">$(NMakeAssemblySearchPath)</NMakeAssemblySearchPath>
  949. \t\t<NMakeForcedUsingAssemblies Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">$(NMakeForcedUsingAssemblies)</NMakeForcedUsingAssemblies>
  950. """
  951. class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
  952. """Generates a Project file for MSVS 2010"""
  953. def __init__(self, dspfile, source, env):
  954. _DSPGenerator.__init__(self, dspfile, source, env)
  955. self.dspheader = V10DSPHeader
  956. self.dspconfiguration = V10DSPProjectConfiguration
  957. self.dspglobals = V10DSPGlobals
  958. _GenerateV10User.__init__(self, dspfile, source, env)
  959. def PrintHeader(self):
  960. env = self.env
  961. name = self.name
  962. encoding = env.subst('$MSVSENCODING')
  963. project_guid = env.get('MSVS_PROJECT_GUID', '')
  964. scc_provider = env.get('MSVS_SCC_PROVIDER', '')
  965. scc_project_name = env.get('MSVS_SCC_PROJECT_NAME', '')
  966. scc_aux_path = env.get('MSVS_SCC_AUX_PATH', '')
  967. # MSVS_SCC_LOCAL_PATH is kept for backwards compatibility purpose and should
  968. # be deprecated as soon as possible.
  969. scc_local_path_legacy = env.get('MSVS_SCC_LOCAL_PATH', '')
  970. scc_connection_root = env.get('MSVS_SCC_CONNECTION_ROOT', os.curdir)
  971. scc_local_path = os.path.relpath(scc_connection_root, os.path.dirname(self.dspabs))
  972. if not project_guid:
  973. project_guid = _generateGUID(self.dspfile, '')
  974. if scc_provider != '':
  975. scc_attrs = '\t\t<SccProjectName>%s</SccProjectName>\n' % scc_project_name
  976. if scc_aux_path != '':
  977. scc_attrs += '\t\t<SccAuxPath>%s</SccAuxPath>\n' % scc_aux_path
  978. scc_attrs += ('\t\t<SccLocalPath>%s</SccLocalPath>\n'
  979. '\t\t<SccProvider>%s</SccProvider>\n' % (scc_local_path, scc_provider))
  980. elif scc_local_path_legacy != '':
  981. # This case is kept for backwards compatibility purpose and should
  982. # be deprecated as soon as possible.
  983. scc_attrs = ('\t\t<SccProjectName>%s</SccProjectName>\n'
  984. '\t\t<SccLocalPath>%s</SccLocalPath>\n' % (scc_project_name, scc_local_path_legacy))
  985. else:
  986. self.dspglobals = self.dspglobals.replace('%(scc_attrs)s', '')
  987. self.file.write(self.dspheader % locals())
  988. self.file.write('\t<ItemGroup Label="ProjectConfigurations">\n')
  989. confkeys = sorted(self.configs.keys())
  990. for kind in confkeys:
  991. variant = self.configs[kind].variant
  992. platform = self.configs[kind].platform
  993. self.file.write(self.dspconfiguration % locals())
  994. self.file.write('\t</ItemGroup>\n')
  995. self.file.write(self.dspglobals % locals())
  996. def PrintProject(self):
  997. name = self.name
  998. confkeys = sorted(self.configs.keys())
  999. self.file.write('\t<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />\n')
  1000. toolset = ''
  1001. if 'MSVC_VERSION' in self.env:
  1002. version_num, suite = msvs_parse_version(self.env['MSVC_VERSION'])
  1003. toolset = 'v%d' % (version_num * 10)
  1004. for kind in confkeys:
  1005. variant = self.configs[kind].variant
  1006. platform = self.configs[kind].platform
  1007. self.file.write(V10DSPPropertyGroupCondition % locals())
  1008. self.file.write('\t<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />\n')
  1009. self.file.write('\t<ImportGroup Label="ExtensionSettings">\n')
  1010. self.file.write('\t</ImportGroup>\n')
  1011. for kind in confkeys:
  1012. variant = self.configs[kind].variant
  1013. platform = self.configs[kind].platform
  1014. self.file.write(V10DSPImportGroupCondition % locals())
  1015. self.file.write('\t<PropertyGroup Label="UserMacros" />\n')
  1016. self.file.write('\t<PropertyGroup>\n')
  1017. self.file.write('\t<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>\n')
  1018. for kind in confkeys:
  1019. variant = self.configs[kind].variant
  1020. platform = self.configs[kind].platform
  1021. outdir = self.configs[kind].outdir
  1022. buildtarget = self.configs[kind].buildtarget
  1023. runfile = self.configs[kind].runfile
  1024. cmdargs = self.configs[kind].cmdargs
  1025. env_has_buildtarget = 'MSVSBUILDTARGET' in self.env
  1026. if not env_has_buildtarget:
  1027. self.env['MSVSBUILDTARGET'] = buildtarget
  1028. starting = 'echo Starting SCons && '
  1029. if cmdargs:
  1030. cmdargs = ' ' + cmdargs
  1031. else:
  1032. cmdargs = ''
  1033. buildcmd = xmlify(starting + self.env.subst('$MSVSBUILDCOM', 1) + cmdargs)
  1034. rebuildcmd = xmlify(starting + self.env.subst('$MSVSREBUILDCOM', 1) + cmdargs)
  1035. cleancmd = xmlify(starting + self.env.subst('$MSVSCLEANCOM', 1) + cmdargs)
  1036. # This isn't perfect; CPPDEFINES and CPPPATH can contain $TARGET and $SOURCE,
  1037. # so they could vary depending on the command being generated. This code
  1038. # assumes they don't.
  1039. preprocdefs = xmlify(';'.join(processDefines(self.env.get('CPPDEFINES', []))))
  1040. includepath_Dirs = processIncludes(self.env.get('CPPPATH', []), self.env, None, None)
  1041. includepath = xmlify(';'.join([str(x) for x in includepath_Dirs]))
  1042. if not env_has_buildtarget:
  1043. del self.env['MSVSBUILDTARGET']
  1044. self.file.write(V10DSPCommandLine % locals())
  1045. self.file.write('\t</PropertyGroup>\n')
  1046. #filter settings in MSVS 2010 are stored in separate file
  1047. self.filtersabs = self.dspabs + '.filters'
  1048. try:
  1049. self.filters_file = open(self.filtersabs, 'w')
  1050. except IOError as detail:
  1051. raise SCons.Errors.InternalError('Unable to open "' + self.filtersabs + '" for writing:' + str(detail))
  1052. self.filters_file.write('<?xml version="1.0" encoding="utf-8"?>\n'
  1053. '<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n')
  1054. self.PrintSourceFiles()
  1055. self.filters_file.write('</Project>')
  1056. self.filters_file.close()
  1057. self.file.write('\t<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\n'
  1058. '\t<ImportGroup Label="ExtensionTargets">\n'
  1059. '\t</ImportGroup>\n'
  1060. '</Project>\n')
  1061. if self.nokeep == 0:
  1062. # now we pickle some data and add it to the file -- MSDEV will ignore it.
  1063. pdata = pickle.dumps(self.configs,PICKLE_PROTOCOL)
  1064. pdata = base64.encodestring(pdata).decode()
  1065. self.file.write('<!-- SCons Data:\n' + pdata + '\n')
  1066. pdata = pickle.dumps(self.sources,PICKLE_PROTOCOL)
  1067. pdata = base64.encodestring(pdata).decode()
  1068. self.file.write(pdata + '-->\n')
  1069. def printFilters(self, hierarchy, name):
  1070. sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower())
  1071. for key, value in sorteditems:
  1072. if SCons.Util.is_Dict(value):
  1073. filter_name = name + '\\' + key
  1074. self.filters_file.write('\t\t<Filter Include="%s">\n'
  1075. '\t\t\t<UniqueIdentifier>%s</UniqueIdentifier>\n'
  1076. '\t\t</Filter>\n' % (filter_name, _generateGUID(self.dspabs, filter_name)))
  1077. self.printFilters(value, filter_name)
  1078. def printSources(self, hierarchy, kind, commonprefix, filter_name):
  1079. keywords = {'Source Files': 'ClCompile',
  1080. 'Header Files': 'ClInclude',
  1081. 'Local Headers': 'ClInclude',
  1082. 'Resource Files': 'None',
  1083. 'Other Files': 'None'}
  1084. sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower())
  1085. # First folders, then files
  1086. for key, value in sorteditems:
  1087. if SCons.Util.is_Dict(value):
  1088. self.printSources(value, kind, commonprefix, filter_name + '\\' + key)
  1089. for key, value in sorteditems:
  1090. if SCons.Util.is_String(value):
  1091. file = value
  1092. if commonprefix:
  1093. file = os.path.join(commonprefix, value)
  1094. file = os.path.normpath(file)
  1095. self.file.write('\t\t<%s Include="%s" />\n' % (keywords[kind], file))
  1096. self.filters_file.write('\t\t<%s Include="%s">\n'
  1097. '\t\t\t<Filter>%s</Filter>\n'
  1098. '\t\t</%s>\n' % (keywords[kind], file, filter_name, keywords[kind]))
  1099. def PrintSourceFiles(self):
  1100. categories = {'Source Files': 'cpp;c;cxx;l;y;def;odl;idl;hpj;bat',
  1101. 'Header Files': 'h;hpp;hxx;hm;inl',
  1102. 'Local Headers': 'h;hpp;hxx;hm;inl',
  1103. 'Resource Files': 'r;rc;ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe',
  1104. 'Other Files': ''}
  1105. cats = sorted([k for k in list(categories.keys()) if self.sources[k]],
  1106. key = lambda a: a.lower())
  1107. # print vcxproj.filters file first
  1108. self.filters_file.write('\t<ItemGroup>\n')
  1109. for kind in cats:
  1110. self.filters_file.write('\t\t<Filter Include="%s">\n'
  1111. '\t\t\t<UniqueIdentifier>{7b42d31d-d53c-4868-8b92-ca2bc9fc052f}</UniqueIdentifier>\n'
  1112. '\t\t\t<Extensions>%s</Extensions>\n'
  1113. '\t\t</Filter>\n' % (kind, categories[kind]))
  1114. # First remove any common prefix
  1115. sources = self.sources[kind]
  1116. commonprefix = None
  1117. s = list(map(os.path.normpath, sources))
  1118. # take the dirname because the prefix may include parts
  1119. # of the filenames (e.g. if you have 'dir\abcd' and
  1120. # 'dir\acde' then the cp will be 'dir\a' )
  1121. cp = os.path.dirname( os.path.commonprefix(s) )
  1122. if cp and s[0][len(cp)] == os.sep:
  1123. # +1 because the filename starts after the separator
  1124. sources = [s[len(cp)+1:] for s in sources]
  1125. commonprefix = cp
  1126. hierarchy = makeHierarchy(sources)
  1127. self.printFilters(hierarchy, kind)
  1128. self.filters_file.write('\t</ItemGroup>\n')
  1129. # then print files and filters
  1130. for kind in cats:
  1131. self.file.write('\t<ItemGroup>\n')
  1132. self.filters_file.write('\t<ItemGroup>\n')
  1133. # First remove any common prefix
  1134. sources = self.sources[kind]
  1135. commonprefix = None
  1136. s = list(map(os.path.normpath, sources))
  1137. # take the dirname because the prefix may include parts
  1138. # of the filenames (e.g. if you have 'dir\abcd' and
  1139. # 'dir\acde' then the cp will be 'dir\a' )
  1140. cp = os.path.dirname( os.path.commonprefix(s) )
  1141. if cp and s[0][len(cp)] == os.sep:
  1142. # +1 because the filename starts after the separator
  1143. sources = [s[len(cp)+1:] for s in sources]
  1144. commonprefix = cp
  1145. hierarchy = makeHierarchy(sources)
  1146. self.printSources(hierarchy, kind, commonprefix, kind)
  1147. self.file.write('\t</ItemGroup>\n')
  1148. self.filters_file.write('\t</ItemGroup>\n')
  1149. # add the SConscript file outside of the groups
  1150. self.file.write('\t<ItemGroup>\n'
  1151. '\t\t<None Include="%s" />\n'
  1152. #'\t\t<None Include="SConstruct" />\n'
  1153. '\t</ItemGroup>\n' % str(self.sconscript))
  1154. def Parse(self):
  1155. print("_GenerateV10DSP.Parse()")
  1156. def Build(self):
  1157. try:
  1158. self.file = open(self.dspabs, 'w')
  1159. except IOError as detail:
  1160. raise SCons.Errors.InternalError('Unable to open "' + self.dspabs + '" for writing:' + str(detail))
  1161. else:
  1162. self.PrintHeader()
  1163. self.PrintProject()
  1164. self.file.close()
  1165. _GenerateV10User.Build(self)
  1166. class _DSWGenerator(object):
  1167. """ Base class for DSW generators """
  1168. def __init__(self, dswfile, source, env):
  1169. self.dswfile = os.path.normpath(str(dswfile))
  1170. self.dsw_folder_path = os.path.dirname(os.path.abspath(self.dswfile))
  1171. self.env = env
  1172. if 'projects' not in env:
  1173. raise SCons.Errors.UserError("You must specify a 'projects' argument to create an MSVSSolution.")
  1174. projects = env['projects']
  1175. if not SCons.Util.is_List(projects):
  1176. raise SCons.Errors.InternalError("The 'projects' argument must be a list of nodes.")
  1177. projects = SCons.Util.flatten(projects)
  1178. if len(projects) < 1:
  1179. raise SCons.Errors.UserError("You must specify at least one project to create an MSVSSolution.")
  1180. self.dspfiles = list(map(str, projects))
  1181. if 'name' in self.env:
  1182. self.name = self.env['name']
  1183. else:
  1184. self.name = os.path.basename(SCons.Util.splitext(self.dswfile)[0])
  1185. self.name = self.env.subst(self.name)
  1186. def Build(self):
  1187. pass
  1188. class _GenerateV7DSW(_DSWGenerator):
  1189. """Generates a Solution file for MSVS .NET"""
  1190. def __init__(self, dswfile, source, env):
  1191. _DSWGenerator.__init__(self, dswfile, source, env)
  1192. self.file = None
  1193. self.version = self.env['MSVS_VERSION']
  1194. self.version_num, self.suite = msvs_parse_version(self.version)
  1195. self.versionstr = '7.00'
  1196. if self.version_num >= 11.0:
  1197. self.versionstr = '12.00'
  1198. elif self.version_num >= 10.0:
  1199. self.versionstr = '11.00'
  1200. elif self.version_num >= 9.0:
  1201. self.versionstr = '10.00'
  1202. elif self.version_num >= 8.0:
  1203. self.versionstr = '9.00'
  1204. elif self.version_num >= 7.1:
  1205. self.versionstr = '8.00'
  1206. if 'slnguid' in env and env['slnguid']:
  1207. self.slnguid = env['slnguid']
  1208. else:
  1209. self.slnguid = _generateGUID(dswfile, self.name)
  1210. self.configs = {}
  1211. self.nokeep = 0
  1212. if 'nokeep' in env and env['variant'] != 0:
  1213. self.nokeep = 1
  1214. if self.nokeep == 0 and os.path.exists(self.dswfile):
  1215. self.Parse()
  1216. def AddConfig(self, variant, dswfile=dswfile):
  1217. config = Config()
  1218. match = re.match('(.*)\|(.*)', variant)
  1219. if match:
  1220. config.variant = match.group(1)
  1221. config.platform = match.group(2)
  1222. else:
  1223. config.variant = variant
  1224. config.platform = 'Win32'
  1225. self.configs[variant] = config
  1226. print("Adding '" + self.name + ' - ' + config.variant + '|' + config.platform + "' to '" + str(dswfile) + "'")
  1227. if 'variant' not in env:
  1228. raise SCons.Errors.InternalError("You must specify a 'variant' argument (i.e. 'Debug' or " +\
  1229. "'Release') to create an MSVS Solution File.")
  1230. elif SCons.Util.is_String(env['variant']):
  1231. AddConfig(self, env['variant'])
  1232. elif SCons.Util.is_List(env['variant']):
  1233. for variant in env['variant']:
  1234. AddConfig(self, variant)
  1235. self.platforms = []
  1236. for key in list(self.configs.keys()):
  1237. platform = self.configs[key].platform
  1238. if not platform in self.platforms:
  1239. self.platforms.append(platform)
  1240. def GenerateProjectFilesInfo(self):
  1241. for dspfile in self.dspfiles:
  1242. dsp_folder_path, name = os.path.split(dspfile)
  1243. dsp_folder_path = os.path.abspath(dsp_folder_path)
  1244. dsp_relative_folder_path = os.path.relpath(dsp_folder_path, self.dsw_folder_path)
  1245. if dsp_relative_folder_path == os.curdir:
  1246. dsp_relative_file_path = name
  1247. else:
  1248. dsp_relative_file_path = os.path.join(dsp_relative_folder_path, name)
  1249. dspfile_info = {'NAME': name,
  1250. 'GUID': _generateGUID(dspfile, ''),
  1251. 'FOLDER_PATH': dsp_folder_path,
  1252. 'FILE_PATH': dspfile,
  1253. 'SLN_RELATIVE_FOLDER_PATH': dsp_relative_folder_path,
  1254. 'SLN_RELATIVE_FILE_PATH': dsp_relative_file_path}
  1255. self.dspfiles_info.append(dspfile_info)
  1256. self.dspfiles_info = []
  1257. GenerateProjectFilesInfo(self)
  1258. def Parse(self):
  1259. try:
  1260. dswfile = open(self.dswfile,'r')
  1261. except IOError:
  1262. return # doesn't exist yet, so can't add anything to configs.
  1263. line = dswfile.readline()
  1264. while line:
  1265. if line[:9] == "EndGlobal":
  1266. break
  1267. line = dswfile.readline()
  1268. line = dswfile.readline()
  1269. datas = line
  1270. while line:
  1271. line = dswfile.readline()
  1272. datas = datas + line
  1273. # OK, we've found our little pickled cache of data.
  1274. try:
  1275. datas = base64.decodestring(datas)
  1276. data = pickle.loads(datas)
  1277. except KeyboardInterrupt:
  1278. raise
  1279. except:
  1280. return # unable to unpickle any data for some reason
  1281. self.configs.update(data)
  1282. def PrintSolution(self):
  1283. """Writes a solution file"""
  1284. self.file.write('Microsoft Visual Studio Solution File, Format Version %s\n' % self.versionstr)
  1285. if self.version_num >= 12.0:
  1286. self.file.write('# Visual Studio 14\n')
  1287. elif self.version_num >= 11.0:
  1288. self.file.write('# Visual Studio 11\n')
  1289. elif self.version_num >= 10.0:
  1290. self.file.write('# Visual Studio 2010\n')
  1291. elif self.version_num >= 9.0:
  1292. self.file.write('# Visual Studio 2008\n')
  1293. elif self.version_num >= 8.0:
  1294. self.file.write('# Visual Studio 2005\n')
  1295. for dspinfo in self.dspfiles_info:
  1296. name = dspinfo['NAME']
  1297. base, suffix = SCons.Util.splitext(name)
  1298. if suffix == '.vcproj':
  1299. name = base
  1300. self.file.write('Project("%s") = "%s", "%s", "%s"\n'
  1301. % (external_makefile_guid, name, dspinfo['SLN_RELATIVE_FILE_PATH'], dspinfo['GUID']))
  1302. if self.version_num >= 7.1 and self.version_num < 8.0:
  1303. self.file.write('\tProjectSection(ProjectDependencies) = postProject\n'
  1304. '\tEndProjectSection\n')
  1305. self.file.write('EndProject\n')
  1306. self.file.write('Global\n')
  1307. env = self.env
  1308. if 'MSVS_SCC_PROVIDER' in env:
  1309. scc_number_of_projects = len(self.dspfiles) + 1
  1310. slnguid = self.slnguid
  1311. scc_provider = env.get('MSVS_SCC_PROVIDER', '').replace(' ', r'\u0020')
  1312. scc_project_name = env.get('MSVS_SCC_PROJECT_NAME', '').replace(' ', r'\u0020')
  1313. scc_connection_root = env.get('MSVS_SCC_CONNECTION_ROOT', os.curdir)
  1314. scc_local_path = os.path.relpath(scc_connection_root, self.dsw_folder_path).replace('\\', '\\\\')
  1315. self.file.write('\tGlobalSection(SourceCodeControl) = preSolution\n'
  1316. '\t\tSccNumberOfProjects = %(scc_number_of_projects)d\n'
  1317. '\t\tSccProjectName0 = %(scc_project_name)s\n'
  1318. '\t\tSccLocalPath0 = %(scc_local_path)s\n'
  1319. '\t\tSccProvider0 = %(scc_provider)s\n'
  1320. '\t\tCanCheckoutShared = true\n' % locals())
  1321. sln_relative_path_from_scc = os.path.relpath(self.dsw_folder_path, scc_connection_root)
  1322. if sln_relative_path_from_scc != os.curdir:
  1323. self.file.write('\t\tSccProjectFilePathRelativizedFromConnection0 = %s\\\\\n'
  1324. % sln_relative_path_from_scc.replace('\\', '\\\\'))
  1325. if self.version_num < 8.0:
  1326. # When present, SolutionUniqueID is automatically removed by VS 2005
  1327. # TODO: check for Visual Studio versions newer than 2005
  1328. self.file.write('\t\tSolutionUniqueID = %s\n' % slnguid)
  1329. for dspinfo in self.dspfiles_info:
  1330. i = self.dspfiles_info.index(dspinfo) + 1
  1331. dsp_relative_file_path = dspinfo['SLN_RELATIVE_FILE_PATH'].replace('\\', '\\\\')
  1332. dsp_scc_relative_folder_path = os.path.relpath(dspinfo['FOLDER_PATH'], scc_connection_root).replace('\\', '\\\\')
  1333. self.file.write('\t\tSccProjectUniqueName%(i)s = %(dsp_relative_file_path)s\n'
  1334. '\t\tSccLocalPath%(i)d = %(scc_local_path)s\n'
  1335. '\t\tCanCheckoutShared = true\n'
  1336. '\t\tSccProjectFilePathRelativizedFromConnection%(i)s = %(dsp_scc_relative_folder_path)s\\\\\n'
  1337. % locals())
  1338. self.file.write('\tEndGlobalSection\n')
  1339. if self.version_num >= 8.0:
  1340. self.file.write('\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n')
  1341. else:
  1342. self.file.write('\tGlobalSection(SolutionConfiguration) = preSolution\n')
  1343. confkeys = sorted(self.configs.keys())
  1344. cnt = 0
  1345. for name in confkeys:
  1346. variant = self.configs[name].variant
  1347. platform = self.configs[name].platform
  1348. if self.version_num >= 8.0:
  1349. self.file.write('\t\t%s|%s = %s|%s\n' % (variant, platform, variant, platform))
  1350. else:
  1351. self.file.write('\t\tConfigName.%d = %s\n' % (cnt, variant))
  1352. cnt = cnt + 1
  1353. self.file.write('\tEndGlobalSection\n')
  1354. if self.version_num <= 7.1:
  1355. self.file.write('\tGlobalSection(ProjectDependencies) = postSolution\n'
  1356. '\tEndGlobalSection\n')
  1357. if self.version_num >= 8.0:
  1358. self.file.write('\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n')
  1359. else:
  1360. self.file.write('\tGlobalSection(ProjectConfiguration) = postSolution\n')
  1361. for name in confkeys:
  1362. variant = self.configs[name].variant
  1363. platform = self.configs[name].platform
  1364. if self.version_num >= 8.0:
  1365. for dspinfo in self.dspfiles_info:
  1366. guid = dspinfo['GUID']
  1367. self.file.write('\t\t%s.%s|%s.ActiveCfg = %s|%s\n'
  1368. '\t\t%s.%s|%s.Build.0 = %s|%s\n' % (guid,variant,platform,variant,platform,guid,variant,platform,variant,platform))
  1369. else:
  1370. for dspinfo in self.dspfiles_info:
  1371. guid = dspinfo['GUID']
  1372. self.file.write('\t\t%s.%s.ActiveCfg = %s|%s\n'
  1373. '\t\t%s.%s.Build.0 = %s|%s\n' %(guid,variant,variant,platform,guid,variant,variant,platform))
  1374. self.file.write('\tEndGlobalSection\n')
  1375. if self.version_num >= 8.0:
  1376. self.file.write('\tGlobalSection(SolutionProperties) = preSolution\n'
  1377. '\t\tHideSolutionNode = FALSE\n'
  1378. '\tEndGlobalSection\n')
  1379. else:
  1380. self.file.write('\tGlobalSection(ExtensibilityGlobals) = postSolution\n'
  1381. '\tEndGlobalSection\n'
  1382. '\tGlobalSection(ExtensibilityAddIns) = postSolution\n'
  1383. '\tEndGlobalSection\n')
  1384. self.file.write('EndGlobal\n')
  1385. if self.nokeep == 0:
  1386. pdata = pickle.dumps(self.configs,PICKLE_PROTOCOL)
  1387. pdata = base64.encodestring(pdata).decode()
  1388. self.file.write(pdata)
  1389. self.file.write('\n')
  1390. def Build(self):
  1391. try:
  1392. self.file = open(self.dswfile,'w')
  1393. except IOError as detail:
  1394. raise SCons.Errors.InternalError('Unable to open "' + self.dswfile + '" for writing:' + str(detail))
  1395. else:
  1396. self.PrintSolution()
  1397. self.file.close()
  1398. V6DSWHeader = """\
  1399. Microsoft Developer Studio Workspace File, Format Version 6.00
  1400. # WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
  1401. ###############################################################################
  1402. Project: "%(name)s"="%(dspfile)s" - Package Owner=<4>
  1403. Package=<5>
  1404. {{{
  1405. }}}
  1406. Package=<4>
  1407. {{{
  1408. }}}
  1409. ###############################################################################
  1410. Global:
  1411. Package=<5>
  1412. {{{
  1413. }}}
  1414. Package=<3>
  1415. {{{
  1416. }}}
  1417. ###############################################################################
  1418. """
  1419. class _GenerateV6DSW(_DSWGenerator):
  1420. """Generates a Workspace file for MSVS 6.0"""
  1421. def PrintWorkspace(self):
  1422. """ writes a DSW file """
  1423. name = self.name
  1424. dspfile = os.path.relpath(self.dspfiles[0], self.dsw_folder_path)
  1425. self.file.write(V6DSWHeader % locals())
  1426. def Build(self):
  1427. try:
  1428. self.file = open(self.dswfile,'w')
  1429. except IOError as detail:
  1430. raise SCons.Errors.InternalError('Unable to open "' + self.dswfile + '" for writing:' + str(detail))
  1431. else:
  1432. self.PrintWorkspace()
  1433. self.file.close()
  1434. def GenerateDSP(dspfile, source, env):
  1435. """Generates a Project file based on the version of MSVS that is being used"""
  1436. version_num = 6.0
  1437. if 'MSVS_VERSION' in env:
  1438. version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
  1439. if version_num >= 10.0:
  1440. g = _GenerateV10DSP(dspfile, source, env)
  1441. g.Build()
  1442. elif version_num >= 7.0:
  1443. g = _GenerateV7DSP(dspfile, source, env)
  1444. g.Build()
  1445. else:
  1446. g = _GenerateV6DSP(dspfile, source, env)
  1447. g.Build()
  1448. def GenerateDSW(dswfile, source, env):
  1449. """Generates a Solution/Workspace file based on the version of MSVS that is being used"""
  1450. version_num = 6.0
  1451. if 'MSVS_VERSION' in env:
  1452. version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
  1453. if version_num >= 7.0:
  1454. g = _GenerateV7DSW(dswfile, source, env)
  1455. g.Build()
  1456. else:
  1457. g = _GenerateV6DSW(dswfile, source, env)
  1458. g.Build()
  1459. ##############################################################################
  1460. # Above here are the classes and functions for generation of
  1461. # DSP/DSW/SLN/VCPROJ files.
  1462. ##############################################################################
  1463. def GetMSVSProjectSuffix(target, source, env, for_signature):
  1464. return env['MSVS']['PROJECTSUFFIX']
  1465. def GetMSVSSolutionSuffix(target, source, env, for_signature):
  1466. return env['MSVS']['SOLUTIONSUFFIX']
  1467. def GenerateProject(target, source, env):
  1468. # generate the dsp file, according to the version of MSVS.
  1469. builddspfile = target[0]
  1470. dspfile = builddspfile.srcnode()
  1471. # this detects whether or not we're using a VariantDir
  1472. if not dspfile is builddspfile:
  1473. try:
  1474. bdsp = open(str(builddspfile), "w+")
  1475. except IOError as detail:
  1476. print('Unable to open "' + str(dspfile) + '" for writing:',detail,'\n')
  1477. raise
  1478. bdsp.write("This is just a placeholder file.\nThe real project file is here:\n%s\n" % dspfile.get_abspath())
  1479. GenerateDSP(dspfile, source, env)
  1480. if env.get('auto_build_solution', 1):
  1481. builddswfile = target[1]
  1482. dswfile = builddswfile.srcnode()
  1483. if not dswfile is builddswfile:
  1484. try:
  1485. bdsw = open(str(builddswfile), "w+")
  1486. except IOError as detail:
  1487. print('Unable to open "' + str(dspfile) + '" for writing:',detail,'\n')
  1488. raise
  1489. bdsw.write("This is just a placeholder file.\nThe real workspace file is here:\n%s\n" % dswfile.get_abspath())
  1490. GenerateDSW(dswfile, source, env)
  1491. def GenerateSolution(target, source, env):
  1492. GenerateDSW(target[0], source, env)
  1493. def projectEmitter(target, source, env):
  1494. """Sets up the DSP dependencies."""
  1495. # todo: Not sure what sets source to what user has passed as target,
  1496. # but this is what happens. When that is fixed, we also won't have
  1497. # to make the user always append env['MSVSPROJECTSUFFIX'] to target.
  1498. if source[0] == target[0]:
  1499. source = []
  1500. # make sure the suffix is correct for the version of MSVS we're running.
  1501. (base, suff) = SCons.Util.splitext(str(target[0]))
  1502. suff = env.subst('$MSVSPROJECTSUFFIX')
  1503. target[0] = base + suff
  1504. if not source:
  1505. source = 'prj_inputs:'
  1506. source = source + env.subst('$MSVSSCONSCOM', 1)
  1507. source = source + env.subst('$MSVSENCODING', 1)
  1508. # Project file depends on CPPDEFINES and CPPPATH
  1509. preprocdefs = xmlify(';'.join(processDefines(env.get('CPPDEFINES', []))))
  1510. includepath_Dirs = processIncludes(env.get('CPPPATH', []), env, None, None)
  1511. includepath = xmlify(';'.join([str(x) for x in includepath_Dirs]))
  1512. source = source + "; ppdefs:%s incpath:%s"%(preprocdefs, includepath)
  1513. if 'buildtarget' in env and env['buildtarget'] != None:
  1514. if SCons.Util.is_String(env['buildtarget']):
  1515. source = source + ' "%s"' % env['buildtarget']
  1516. elif SCons.Util.is_List(env['buildtarget']):
  1517. for bt in env['buildtarget']:
  1518. if SCons.Util.is_String(bt):
  1519. source = source + ' "%s"' % bt
  1520. else:
  1521. try: source = source + ' "%s"' % bt.get_abspath()
  1522. except AttributeError: raise SCons.Errors.InternalError("buildtarget can be a string, a node, a list of strings or nodes, or None")
  1523. else:
  1524. try: source = source + ' "%s"' % env['buildtarget'].get_abspath()
  1525. except AttributeError: raise SCons.Errors.InternalError("buildtarget can be a string, a node, a list of strings or nodes, or None")
  1526. if 'outdir' in env and env['outdir'] != None:
  1527. if SCons.Util.is_String(env['outdir']):
  1528. source = source + ' "%s"' % env['outdir']
  1529. elif SCons.Util.is_List(env['outdir']):
  1530. for s in env['outdir']:
  1531. if SCons.Util.is_String(s):
  1532. source = source + ' "%s"' % s
  1533. else:
  1534. try: source = source + ' "%s"' % s.get_abspath()
  1535. except AttributeError: raise SCons.Errors.InternalError("outdir can be a string, a node, a list of strings or nodes, or None")
  1536. else:
  1537. try: source = source + ' "%s"' % env['outdir'].get_abspath()
  1538. except AttributeError: raise SCons.Errors.InternalError("outdir can be a string, a node, a list of strings or nodes, or None")
  1539. if 'name' in env:
  1540. if SCons.Util.is_String(env['name']):
  1541. source = source + ' "%s"' % env['name']
  1542. else:
  1543. raise SCons.Errors.InternalError("name must be a string")
  1544. if 'variant' in env:
  1545. if SCons.Util.is_String(env['variant']):
  1546. source = source + ' "%s"' % env['variant']
  1547. elif SCons.Util.is_List(env['variant']):
  1548. for variant in env['variant']:
  1549. if SCons.Util.is_String(variant):
  1550. source = source + ' "%s"' % variant
  1551. else:
  1552. raise SCons.Errors.InternalError("name must be a string or a list of strings")
  1553. else:
  1554. raise SCons.Errors.InternalError("variant must be a string or a list of strings")
  1555. else:
  1556. raise SCons.Errors.InternalError("variant must be specified")
  1557. for s in _DSPGenerator.srcargs:
  1558. if s in env:
  1559. if SCons.Util.is_String(env[s]):
  1560. source = source + ' "%s' % env[s]
  1561. elif SCons.Util.is_List(env[s]):
  1562. for t in env[s]:
  1563. if SCons.Util.is_String(t):
  1564. source = source + ' "%s"' % t
  1565. else:
  1566. raise SCons.Errors.InternalError(s + " must be a string or a list of strings")
  1567. else:
  1568. raise SCons.Errors.InternalError(s + " must be a string or a list of strings")
  1569. source = source + ' "%s"' % str(target[0])
  1570. source = [SCons.Node.Python.Value(source)]
  1571. targetlist = [target[0]]
  1572. sourcelist = source
  1573. if env.get('auto_build_solution', 1):
  1574. env['projects'] = [env.File(t).srcnode() for t in targetlist]
  1575. t, s = solutionEmitter(target, target, env)
  1576. targetlist = targetlist + t
  1577. # Beginning with Visual Studio 2010 for each project file (.vcxproj) we have additional file (.vcxproj.filters)
  1578. version_num = 6.0
  1579. if 'MSVS_VERSION' in env:
  1580. version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
  1581. if version_num >= 10.0:
  1582. targetlist.append(targetlist[0] + '.filters')
  1583. return (targetlist, sourcelist)
  1584. def solutionEmitter(target, source, env):
  1585. """Sets up the DSW dependencies."""
  1586. # todo: Not sure what sets source to what user has passed as target,
  1587. # but this is what happens. When that is fixed, we also won't have
  1588. # to make the user always append env['MSVSSOLUTIONSUFFIX'] to target.
  1589. if source[0] == target[0]:
  1590. source = []
  1591. # make sure the suffix is correct for the version of MSVS we're running.
  1592. (base, suff) = SCons.Util.splitext(str(target[0]))
  1593. suff = env.subst('$MSVSSOLUTIONSUFFIX')
  1594. target[0] = base + suff
  1595. if not source:
  1596. source = 'sln_inputs:'
  1597. if 'name' in env:
  1598. if SCons.Util.is_String(env['name']):
  1599. source = source + ' "%s"' % env['name']
  1600. else:
  1601. raise SCons.Errors.InternalError("name must be a string")
  1602. if 'variant' in env:
  1603. if SCons.Util.is_String(env['variant']):
  1604. source = source + ' "%s"' % env['variant']
  1605. elif SCons.Util.is_List(env['variant']):
  1606. for variant in env['variant']:
  1607. if SCons.Util.is_String(variant):
  1608. source = source + ' "%s"' % variant
  1609. else:
  1610. raise SCons.Errors.InternalError("name must be a string or a list of strings")
  1611. else:
  1612. raise SCons.Errors.InternalError("variant must be a string or a list of strings")
  1613. else:
  1614. raise SCons.Errors.InternalError("variant must be specified")
  1615. if 'slnguid' in env:
  1616. if SCons.Util.is_String(env['slnguid']):
  1617. source = source + ' "%s"' % env['slnguid']
  1618. else:
  1619. raise SCons.Errors.InternalError("slnguid must be a string")
  1620. if 'projects' in env:
  1621. if SCons.Util.is_String(env['projects']):
  1622. source = source + ' "%s"' % env['projects']
  1623. elif SCons.Util.is_List(env['projects']):
  1624. for t in env['projects']:
  1625. if SCons.Util.is_String(t):
  1626. source = source + ' "%s"' % t
  1627. source = source + ' "%s"' % str(target[0])
  1628. source = [SCons.Node.Python.Value(source)]
  1629. return ([target[0]], source)
  1630. projectAction = SCons.Action.Action(GenerateProject, None)
  1631. solutionAction = SCons.Action.Action(GenerateSolution, None)
  1632. projectBuilder = SCons.Builder.Builder(action = '$MSVSPROJECTCOM',
  1633. suffix = '$MSVSPROJECTSUFFIX',
  1634. emitter = projectEmitter)
  1635. solutionBuilder = SCons.Builder.Builder(action = '$MSVSSOLUTIONCOM',
  1636. suffix = '$MSVSSOLUTIONSUFFIX',
  1637. emitter = solutionEmitter)
  1638. default_MSVS_SConscript = None
  1639. def generate(env):
  1640. """Add Builders and construction variables for Microsoft Visual
  1641. Studio project files to an Environment."""
  1642. try:
  1643. env['BUILDERS']['MSVSProject']
  1644. except KeyError:
  1645. env['BUILDERS']['MSVSProject'] = projectBuilder
  1646. try:
  1647. env['BUILDERS']['MSVSSolution']
  1648. except KeyError:
  1649. env['BUILDERS']['MSVSSolution'] = solutionBuilder
  1650. env['MSVSPROJECTCOM'] = projectAction
  1651. env['MSVSSOLUTIONCOM'] = solutionAction
  1652. if SCons.Script.call_stack:
  1653. # XXX Need to find a way to abstract this; the build engine
  1654. # shouldn't depend on anything in SCons.Script.
  1655. env['MSVSSCONSCRIPT'] = SCons.Script.call_stack[0].sconscript
  1656. else:
  1657. global default_MSVS_SConscript
  1658. if default_MSVS_SConscript is None:
  1659. default_MSVS_SConscript = env.File('SConstruct')
  1660. env['MSVSSCONSCRIPT'] = default_MSVS_SConscript
  1661. env['MSVSSCONS'] = '"%s" -c "%s"' % (python_executable, getExecScriptMain(env))
  1662. env['MSVSSCONSFLAGS'] = '-C "${MSVSSCONSCRIPT.dir.get_abspath()}" -f ${MSVSSCONSCRIPT.name}'
  1663. env['MSVSSCONSCOM'] = '$MSVSSCONS $MSVSSCONSFLAGS'
  1664. env['MSVSBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"'
  1665. env['MSVSREBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"'
  1666. env['MSVSCLEANCOM'] = '$MSVSSCONSCOM -c "$MSVSBUILDTARGET"'
  1667. # Set-up ms tools paths for default version
  1668. msvc_setup_env_once(env)
  1669. if 'MSVS_VERSION' in env:
  1670. version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
  1671. else:
  1672. (version_num, suite) = (7.0, None) # guess at a default
  1673. if 'MSVS' not in env:
  1674. env['MSVS'] = {}
  1675. if (version_num < 7.0):
  1676. env['MSVS']['PROJECTSUFFIX'] = '.dsp'
  1677. env['MSVS']['SOLUTIONSUFFIX'] = '.dsw'
  1678. elif (version_num < 10.0):
  1679. env['MSVS']['PROJECTSUFFIX'] = '.vcproj'
  1680. env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
  1681. else:
  1682. env['MSVS']['PROJECTSUFFIX'] = '.vcxproj'
  1683. env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
  1684. if (version_num >= 10.0):
  1685. env['MSVSENCODING'] = 'utf-8'
  1686. else:
  1687. env['MSVSENCODING'] = 'Windows-1252'
  1688. env['GET_MSVSPROJECTSUFFIX'] = GetMSVSProjectSuffix
  1689. env['GET_MSVSSOLUTIONSUFFIX'] = GetMSVSSolutionSuffix
  1690. env['MSVSPROJECTSUFFIX'] = '${GET_MSVSPROJECTSUFFIX}'
  1691. env['MSVSSOLUTIONSUFFIX'] = '${GET_MSVSSOLUTIONSUFFIX}'
  1692. env['SCONS_HOME'] = os.environ.get('SCONS_HOME')
  1693. def exists(env):
  1694. return msvc_exists()
  1695. # Local Variables:
  1696. # tab-width:4
  1697. # indent-tabs-mode:nil
  1698. # End:
  1699. # vim: set expandtab tabstop=4 shiftwidth=4: