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