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