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