source: trunk/makeBat.py @ 4234

Last change on this file since 4234 was 4234, checked in by toby, 4 years ago

Cleanup registry stuff

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 8.1 KB
Line 
1'''
2*makeBat: Create GSAS-II Batch File*
3====================================
4
5This script creates a file named ``RunGSASII.bat`` and a desktop shortcut to that file.
6It registers the filetype .gpx so that the GSAS-II project files exhibit the
7GSAS-II icon and so that double-clicking on them opens them in GSAS-II.
8
9Run this script with no arguments; the path to the ``GSASII.py`` file
10is assumed to be the the same as the path to the ``makeBat.py`` file
11and the path to Python is determined from the version of Python
12used to run this script.
13
14'''
15version = "$Id: makeBat.py 4234 2020-01-03 23:09:46Z toby $"
16# creates Windows files to aid in running GSAS-II
17#   creates RunGSASII.bat and a desktop shortcut to that file
18#   registers the filetype .gpx so that the GSAS-II project files exhibit the
19#     GSAS-II icon and so that double-clicking on them opens them in GSAS-II
20#
21import os, sys
22import datetime
23import wx
24
25Script = '''@echo ========================================================================
26@echo                General Structure Analysis System-II
27@echo              by Robert B. Von Dreele and Brian H. Toby
28@echo                Argonne National Laboratory(C), 2010
29@echo  This product includes software developed by the UChicago Argonne, LLC,
30@echo             as Operator of Argonne National Laboratory.
31@echo                            Please cite:
32@echo      B.H. Toby and R.B. Von Dreele, J. Appl. Cryst. 46, 544-549 (2013)
33@echo                   for small angle use also cite:
34@echo      R.B. Von Dreele, J. Appl. Cryst. 47, 1784-9 (2014)
35@echo                   for DIFFaX use also cite:
36@echo      M.M.J. Treacy, J.M. Newsam and M.W. Deem,
37@echo                   Proc. Roy. Soc. Lond. 433A, 499-520 (1991)
38@echo ========================================================================
39@
40{:s}{:s} {:s} "%~1"
41@REM To keep the window from disappearing with any error messages
42pause
43
44'''
45
46if __name__ == '__main__':
47    try:
48        import _winreg as winreg
49    except ImportError:
50        import winreg
51    app = None # delay starting wx until we need it. Likely not needed.
52    gsaspath = os.path.split(sys.argv[0])[0]
53    if not gsaspath: gsaspath = os.path.curdir
54    gsaspath = os.path.abspath(os.path.expanduser(gsaspath))
55    G2script = os.path.join(gsaspath,'GSASII.py')
56    G2bat = os.path.join(gsaspath,'RunGSASII.bat')
57    G2icon = os.path.join(gsaspath,'gsas2.ico')
58    pythonexe = os.path.realpath(sys.executable)
59    print('Python installed at',pythonexe)
60    print('GSAS-II installed at',gsaspath)
61    # Bob reports a problem using pythonw.exe w/Canopy on Windows, so change that if used
62    if pythonexe.lower().endswith('pythonw.exe'):
63        print("  using python.exe rather than "+pythonexe)
64        pythonexe = os.path.join(os.path.split(pythonexe)[0],'python.exe')
65        print("  now pythonexe="+pythonexe)
66    # create a GSAS-II script
67    fp = open(os.path.join(G2bat),'w')
68    fp.write("@REM created by run of bootstrap.py on {:%d %b %Y %H:%M}\n".format(
69        datetime.datetime.now()))
70    activate = os.path.join(os.path.split(pythonexe)[0],'Scripts','activate')
71    print("Looking for",activate)
72    if os.path.exists(activate):
73        activate = os.path.realpath(activate)
74        if ' ' in activate:
75            activate = 'call "'+ activate + '"\n'
76        else:
77            activate = 'call '+ activate + '\n'
78        print('adding activate to .bat file ({})'.format(activate))
79    else:
80        print('Anaconda activate not found')
81        activate = ''
82    pexe = pythonexe
83    if ' ' in pythonexe: pexe = '"'+pythonexe+'"'
84    G2s = G2script
85    if ' ' in G2s: G2s = '"'+G2script+'"'
86    # is mingw-w64\bin present? If so add it to path.
87    #d = os.path.split(pexe)[0]
88    #mdir = os.path.join(d,'Library','mingw-w64','bin')
89    #if os.path.exists(mdir):
90    #    fp.write('@path={};%path%\n'.format(mdir))
91    fp.write(Script.format(activate,pexe,G2s))
92    fp.close()
93    print('\nCreated GSAS-II batch file RunGSASII.bat in '+gsaspath)
94   
95    new = False
96    oldBat = ''
97    # this code does not appear to work properly when paths have spaces
98    try:
99        oldgpx = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r'Software\CLASSES\GSAS-II.project') # throws FileNotFoundError
100        oldopen = winreg.OpenKey(oldgpx,r'shell\open\command')
101        # get previous value & strip %1 off end
102        oldBat = winreg.QueryValue(oldopen,None).strip()
103        pos = oldBat.rfind(' ')
104        if pos > 1:
105            oldBat = oldBat[:pos]
106        os.stat(oldBat)     #check if it is still around
107    except FileNotFoundError:
108        if oldBat:
109            print('old GPX assignment',oldBat, 'not found; registry entry will be made for new one')
110        new = True
111    if not new:
112        try:
113            if oldBat != G2bat:
114                if app is None:
115                    app = wx.App()
116                    app.MainLoop()
117                dlg = wx.MessageDialog(None,'gpx files already assigned in registry to: \n'+oldBat+'\n Replace with: '+G2bat+'?','GSAS-II gpx in use', 
118                        wx.YES_NO | wx.ICON_QUESTION)
119                if dlg.ShowModal() == wx.ID_YES:
120                    new = True
121                dlg.Destroy()
122        finally:
123            pass
124    if new:
125        # Associate a script and icon with .gpx files
126        gpxkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER,r'Software\CLASSES\.gpx')
127        winreg.SetValue(gpxkey, None, winreg.REG_SZ, 'GSAS-II.project')
128        winreg.CloseKey(gpxkey)
129        gpxkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER,r'Software\CLASSES\GSAS-II.project')
130        winreg.SetValue(gpxkey, None, winreg.REG_SZ, 'GSAS-II project')
131        iconkey = winreg.CreateKey(gpxkey, 'DefaultIcon')
132        winreg.SetValue(iconkey, None, winreg.REG_SZ, G2icon)
133        openkey = winreg.CreateKey(gpxkey, r'shell\open\command')
134        winreg.SetValue(openkey, None, winreg.REG_SZ, G2bat+' "%1"')
135        winreg.CloseKey(iconkey)
136        winreg.CloseKey(openkey)
137        winreg.CloseKey(gpxkey)
138        print('Assigned icon and batch file to .gpx files in registery')
139    else:
140        print('old assignment of icon and batch file in registery is retained')
141
142    try:
143        import win32com.shell.shell, win32com.shell.shellcon
144        win32com.shell.shell.SHChangeNotify(
145            win32com.shell.shellcon.SHCNE_ASSOCCHANGED, 0, None, None)
146    except ImportError:
147        print('Module pywin32 not present, login again to see file types properly')
148    except:
149        print('Unexpected error on explorer refresh. Please report:')
150        import traceback
151        print(traceback.format_exc())
152
153    # make a desktop shortcut to GSAS-II
154    try:
155        import win32com.shell.shell, win32com.shell.shellcon, win32com.client
156        desktop = win32com.shell.shell.SHGetFolderPath(
157            0, win32com.shell.shellcon.CSIDL_DESKTOP, None, 0)
158        shortbase = "GSAS-II.lnk"
159        shortcut = os.path.join(desktop, shortbase)
160        save = True
161        if win32com.shell.shell.SHGetFileInfo(shortcut,0,0)[0]:
162            print('GSAS-II shortcut exists!')
163            if app is None:
164                app = wx.App()
165                app.MainLoop()
166            dlg = wx.FileDialog(None, 'Choose new GSAS-II shortcut name',  desktop, shortbase,
167                wildcard='GSAS-II shortcut (*.lnk)|*.lnk',style=wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
168            try:
169                if dlg.ShowModal() == wx.ID_OK:
170                    shortcut = dlg.GetPath()
171                else:
172                    save = False
173            finally:
174                dlg.Destroy()
175        if save:
176            shell = win32com.client.Dispatch('WScript.Shell')
177            shobj = shell.CreateShortCut(shortcut)
178            shobj.Targetpath = G2bat
179            #shobj.WorkingDirectory = wDir # could specify a default project location here
180            shobj.IconLocation = G2icon
181            shobj.save()
182            print('Created shortcut to start GSAS-II on desktop')
183        else:
184            print('No shortcut for this GSAS-II created on desktop')
185    except ImportError:
186        print('Module pywin32 not present, will not make desktop shortcut')
187    except:
188        print('Unexpected error making desktop shortcut. Please report:')
189        import traceback
190        print(traceback.format_exc())
191   
Note: See TracBrowser for help on using the repository browser.