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