correction tgens
[iramuteq] / checkinstall.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2008 Pierre Ratinaud
5 #License: GNU/GPL
6
7 import os
8 import sys
9 import shutil
10 from chemins import ConstructConfigPath, ConstructDicoPath
11 from functions import exec_rcode, exec_RCMD
12 import wx
13 import tempfile
14 from ConfigParser import *
15 from time import sleep
16 import logging
17
18 log = logging.getLogger('iramuteq.checkinstall')
19
20 def IsNew(self):
21     version_glob = self.ConfigGlob.get('DEFAULT', 'version_nb').split('.')
22     try :
23         version_user = self.pref.get('iramuteq','version_nb').split('.')
24     except NoOptionError :
25         return True
26     userab = False
27     globab = False
28     if version_user :
29         version_user[0] = int(version_user[0])
30         version_user[1] = int(version_user[1])
31         version_glob[0] = int(version_glob[0])
32         version_glob[1] = int(version_glob[1])
33         if len(version_user) == 3 :
34             if 'a' in version_user[2] :
35                 userab = 'a'
36                 version_user[2] = int(version_user[2].replace('a', ''))
37             elif 'b' in version_user[2] :
38                 userab = 'b'
39                 version_user[2] = int(version_user[2].replace('b', ''))
40             else :
41                 version_user[2] = int(version_user[2])
42         if len(version_glob) == 3 :
43             if 'a' in version_glob[2] :
44                 globab = 'a'
45                 version_glob[2] = int(version_glob[2].replace('a', ''))
46             elif 'b' in version_glob[2] :
47                 globab = 'b'
48                 version_glob[2] = int(version_glob[2].replace('b', ''))
49             else :
50                 version_glob[2] = int(version_glob[2])
51         if len(version_user) == len(version_glob) :
52             if version_glob > version_user :
53                 return True
54             elif version_glob == version_user :
55                 if globab == userab :
56                     return False
57                 elif globab > userab :
58                     return True
59                 else :
60                     return False
61             else :
62                 return False
63         else :
64             if version_glob > version_user :
65                 return True
66             else :
67                 return False
68
69 def UpgradeConf(self) :
70     log.info('upgrade conf')
71     dictuser = self.ConfigPath
72     dictappli = ConstructConfigPath(self.AppliPath, user = False)
73     for item,filein in dictuser.iteritems():
74         if not item == u'global' and not item == u'history':
75             shutil.copyfile(dictappli[item], filein)
76     dicoUser = self.DictPath
77     dicoAppli = ConstructDicoPath(self.AppliPath)
78     for fi in dicoUser :
79         if not os.path.exists(dicoUser[fi]) and os.path.exists(dicoAppli[fi]):
80             shutil.copyfile(dicoAppli[fi], dicoUser[fi])
81
82 def CreateIraDirectory(UserConfigPath,AppliPath):
83     if not os.path.exists(UserConfigPath):
84         os.mkdir(UserConfigPath)
85     if not os.path.exists(os.path.join(UserConfigPath, 'dictionnaires')) :
86         os.mkdir(os.path.join(UserConfigPath, 'dictionnaires'))
87
88 def CopyConf(self) :
89     DictUser = self.ConfigPath
90     DictAppli = ConstructConfigPath(self.AppliPath,user=False)
91     for item, filein in DictUser.iteritems():
92         if not item == u'global' and not item == u'path' and not item == u'preferences' and not item == u'history' :
93             shutil.copyfile(DictAppli[item],filein)
94         if item == u'path':
95             if not os.path.exists(filein):
96                 shutil.copyfile(DictAppli[item],filein)
97         if item == u'preferences' :
98             if not os.path.exists(filein) :
99                 shutil.copyfile(DictAppli[item],filein)
100     dicoUser = self.DictPath
101     dicoAppli = ConstructDicoPath(self.AppliPath)
102     for fi in dicoUser :
103         if not os.path.exists(dicoUser[fi]) and os.path.exists(dicoAppli[fi]):
104             shutil.copyfile(dicoAppli[fi], dicoUser[fi])
105
106 def CheckRPath(PathPath):
107     if not os.path.exists(PathPath.get('PATHS','rpath')):
108         return False
109     else :
110         return True
111         
112 def FindRPAthWin32():
113     BestPath=False
114     progpaths=[]
115     if 'ProgramFiles' in os.environ :
116         progpaths.append(os.environ['ProgramFiles'])
117     if 'ProgramFiles(x86)' in os.environ :
118         progpaths.append(os.environ['ProgramFiles(x86)'])
119     if 'ProgramW6432' in os.environ :
120         progpaths.append(os.environ['ProgramW6432'])
121     progpaths = list(set(progpaths))
122     if progpaths != [] :
123         for progpath in progpaths :
124             rpath = os.path.join(progpath, "R")
125             if os.path.exists(rpath) :
126                 for maj in range(2,4) :
127                     for i in range(0,30):
128                         for j in range(0,20):
129                             for poss in ['', 'i386', 'x64'] :
130                                 path=os.path.join(rpath,"R-%i.%i.%i" % (maj, i, j),'bin',poss,'R.exe')
131                                 if os.path.exists(path):
132                                     BestPath=path
133     return BestPath
134
135 def FindRPathNix():
136     BestPath=False
137     if os.path.exists('/usr/bin/R'):
138         BestPath='/usr/bin/R'
139     elif os.path.exists('/usr/local/bin/R'):
140         BestPath='/usr/local/bin/R'
141     return BestPath
142
143 def RLibsAreInstalled(self) :
144     rlibs = self.pref.get('iramuteq', 'rlibs')
145     if rlibs == 'false' or rlibs == 'False' :
146         return False
147     else :
148         return True
149
150 def CheckRPackages(self):
151     listdep = ['ca', 'rgl', 'gee', 'ape', 'igraph','proxy', 'wordcloud', 'irlba', 'textometry']
152     nolib = []
153     i=0
154     dlg = wx.ProgressDialog("Test des librairies de R", "test en cours...", maximum = len(listdep), parent=self, style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME | wx.PD_CAN_ABORT)
155     for bib in listdep :
156         dlg.Center()
157         i+=1
158         dlg.Update(i, "test de %s" % bib)
159         txt = """library("%s")""" % bib
160         tmpscript = tempfile.mktemp(dir=self.TEMPDIR)
161         with open(tmpscript, 'w') as f :
162             f.write(txt)
163         test = exec_rcode(self.RPath, tmpscript, wait = True)
164         if test :
165             log.info('packages %s : NOT INSTALLED' % bib)
166             nolib.append(bib)
167         else :
168             log.info('packages %s : OK' % bib)
169     dlg.Update(len(listdep),'fini')
170     dlg.Destroy()
171     if nolib != [] :
172         txt = '\n'.join(nolib)
173         msg = u"""Les bibliothèques de R suivantes sont manquantes :
174 %s
175
176 Sans ces bibliothèques, IRamuteq ne fonctionnera pas.
177     
178 - Vous pouvez installer ces bibliothèques manuellement :
179         Cliquez sur Annuler
180         Lancez R
181         Tapez install.packages('nom de la bibiothèque')
182         
183 - ou laisser IRamuteq les installer automatiquement en cliquant sur VALIDER .
184         Les bibliothèques seront téléchargées depuis le site miroir de R %s.
185         """ % (txt, self.pref.get('iramuteq','rmirror'))
186         dial = wx.MessageDialog(self, msg, u"Installation incomplète", wx.OK | wx.CANCEL | wx.ICON_WARNING)
187         dial.CenterOnParent()
188         val = dial.ShowModal()
189         if val == wx.ID_OK :
190             dlg = wx.ProgressDialog("Installation",
191                                        "Veuillez patientez...",
192                                        maximum=len(nolib) + 1,
193                                        parent=self,
194                                        style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME | wx.PD_CAN_ABORT
195                                        )
196             dlg.Center()
197             dlg.Update(1, u"installation...") 
198             compt = 0
199
200             for bib in nolib :
201                 compt += 1
202                 dlg.Update(compt, u"installation librairie %s" % bib)
203                 txt = """
204                 userdir <- unlist(strsplit(Sys.getenv("R_LIBS_USER"), .Platform$path.sep))[1]
205                 if (!file.exists(userdir)) {
206                     if (!dir.create(userdir, recursive = TRUE)) 
207                         print('pas possible')
208                     lib <- userdir
209                     .libPaths(c(userdir, .libPaths()))
210                 }
211                 print(userdir)
212                 .libPaths
213                 """
214                 txt += """
215                 install.packages("%s", repos = "%s")
216                 """ % (bib, self.pref.get('iramuteq','rmirror'))
217                 tmpscript = tempfile.mktemp(dir=self.TEMPDIR)
218                 with open(tmpscript, 'w') as f :
219                     f.write(txt)
220                 test = exec_rcode(self.RPath, tmpscript, wait = False)
221                 while test.poll() == None :
222                     dlg.Pulse(u"installation librairie %s" % bib)
223                     sleep(0.2)
224             dlg.Update(len(nolib) + 1, 'fin')
225             dlg.Destroy()
226         dial.Destroy()
227     if nolib == [] : 
228         self.pref.set('iramuteq', 'rlibs', True)
229         with open(self.ConfigPath['preferences'], 'w') as f :
230             self.pref.write(f)
231         return True