f9515ad22ba813f2af648c22241d8a2d674b6762
[iramuteq] / iramuteq.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2008-2012, Pierre Ratinaud
5 #License: GNU GPL
6
7 from optparse import OptionParser
8
9 parser = OptionParser()
10 parser.add_option("-f", "--file", dest="filename",
11                   help="open FILE", metavar="FILE", default=False)
12 (options, args) = parser.parse_args()
13
14 import sys
15 reload(sys)
16 import locale
17 import tempfile
18 import codecs
19 import os
20 from random import randint
21 from ConfigParser import ConfigParser, RawConfigParser
22 import webbrowser
23 import gettext
24 import logging
25 #------------------------------------
26 import wx
27 import wx.lib.agw.aui as aui
28 import wx.html
29 import wx.grid
30 import wx.lib.hyperlink as hl
31 #------------------------------------
32 from functions import BugReport, PlaySound, History
33 from checkversion import NewVersion
34 from guifunct import *
35 from tableau import Tableau
36 from dialog import PrefDialog
37 from tabfrequence import Frequences, FreqMultiple
38 from tabchi2 import ChiSquare
39 #from tabstudent import MakeStudent
40 from tabchddist import ChdCluster
41 from tabafcm import DoAFCM
42 from tabchdalc import AnalyseQuest
43 from tabsimi import DoSimi
44 from tabrsimple import InputText
45 from tabverges import Prototypical
46 from tabsplitvar import SplitMatrixFromVar
47 #from textdist import AnalysePam
48 from textstat import Stat
49 from textaslexico import Lexico
50 from textsimi import SimiTxt, SimiFromCluster
51 from textwordcloud import WordCloud, ClusterCloud
52 from textreinert import Reinert
53 #from textcheckcorpus import checkcorpus
54 from openanalyse import OpenAnalyse
55 from corpus import Builder, SubBuilder
56 from checkinstall import CreateIraDirectory, CheckRPath, FindRPAthWin32, FindRPathNix, CheckRPackages, IsNew, UpgradeConf, CopyConf, RLibsAreInstalled
57 from chemins import RscriptsPath, ConstructConfigPath, ConstructDicoPath, ConstructGlobalPath, PathOut
58 from parse_factiva_xml import ImportFactiva
59 from tools import Extract
60
61 from tree import LeftTree
62 ##########################################################
63 ID_OpenData = wx.NewId()
64 ID_Import = wx.NewId()
65 ID_OpenText = wx.NewId()
66 ID_OnOpenAnalyse = wx.NewId()
67 ID_Freq = wx.NewId()
68 ID_Chi2 = wx.NewId()
69 ID_Student = wx.NewId()
70 ID_CHDSIM = wx.NewId()
71 ID_CHDReinert = wx.NewId()
72 ID_TEXTAFCM = wx.NewId()
73 ID_TEXTSTAT = wx.NewId()
74 ID_ASLEX = wx.NewId()
75 ID_TEXTREINERT = wx.NewId()
76 ID_TEXTPAM = wx.NewId()
77 ID_CHECKCORPUS = wx.NewId()
78 ID_Tabcontent = wx.NewId()
79 ID_AFCM = wx.NewId()
80 ID_SIMI = wx.NewId()
81 ID_CloseTab = wx.NewId()
82 ID_SaveTab = wx.NewId()
83 ID_CreateText = wx.NewId()
84 ID_ACCEUIL = wx.NewId()
85 ID_RESULT = wx.NewId()
86 ID_HTMLcontent = wx.NewId()
87 ID_SimiTxt = wx.NewId()
88 ID_proto = wx.NewId()
89 ID_ImportTXM = wx.NewId()
90 ID_FreqMulti = wx.NewId()
91 ID_Splitfromvar = wx.NewId()
92 ID_Subtxtfrommeta = wx.NewId()
93 ID_Subtxtfromthem = wx.NewId()
94 ID_WC = wx.NewId()
95 ID_ImportEuro = wx.NewId()
96 ID_Fact_xml = wx.NewId()
97 ID_Fact_mail = wx.NewId()
98 ID_Fact_copy = wx.NewId()
99 ID_exportmeta = wx.NewId()
100 ##########################################################
101 #elements de configuration
102 ##########################################################
103 #encodage
104 if sys.platform == 'darwin' :
105     sys.setdefaultencoding('UTF-8')
106     wx.SetDefaultPyEncoding('UTF-8')
107 else :
108     sys.setdefaultencoding(locale.getpreferredencoding())
109
110 #chemin de l'application
111 AppliPath = os.path.abspath(os.path.dirname(os.path.realpath(sys.argv[0])))
112 #chemin des images
113 ImagePath = os.path.join(AppliPath, 'images')
114 #configuration generale
115 DictConfigPath = ConstructGlobalPath(AppliPath)
116 ConfigGlob = ConfigParser()
117 ConfigGlob.read(DictConfigPath['global'])
118 DefaultConf = ConfigParser()
119 DefaultConf.read(DictConfigPath['preferences'])
120 #repertoire de l'utilisateur
121 if os.getenv('HOME') != None:
122     user_home = os.getenv('HOME')
123 else:
124     user_home = os.getenv('HOMEPATH')
125 UserConfigPath = os.path.abspath(os.path.join(user_home, '.iramuteq'))
126 #Si pas de fichiers de config utilisateur, on cree le repertoire
127 CreateIraDirectory(UserConfigPath, AppliPath)
128 #fichiers log pour windows (py2exe)
129 log = logging.getLogger('iramuteq')
130 fh = logging.FileHandler(os.path.join(UserConfigPath,'stdout.log'))
131 formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
132 fh.setFormatter(formatter)
133 log.addHandler(fh)
134 if sys.platform != 'win32' and sys.platform != 'darwin':
135     ch = logging.StreamHandler()
136     ch.setFormatter(formatter)
137     log.addHandler(ch)
138 log.setLevel(logging.INFO)
139
140 class writer(object):
141     def write(self, data):
142         if data.strip() != '' :
143             log.info('ERROR : %s' % data)
144
145 class printer(object) :
146     def write(self, data) :
147         if data.strip() != '' :
148             log.info('Print : %s' % data)
149
150 sys.stderr = writer()
151 sys.stdout = printer()
152
153 ConfigPath = ConstructConfigPath(UserConfigPath)
154
155 langues = {'french' : wx.LANGUAGE_FRENCH,
156            'english' : wx.LANGUAGE_ENGLISH,
157            'portuguese' : wx.LANGUAGE_PORTUGUESE,
158            'italian' : wx.LANGUAGE_ITALIAN,
159            'spanish' : wx.LANGUAGE_SPANISH
160            }
161
162 code_langues = {'french' : 'fr_FR',
163                 'english' : 'en',
164                 'portuguese' : 'pt_PT',
165                 'italian' : 'it_IT',
166                 'spanish' : 'es_ES'
167                }
168
169 images_analyses = {
170         'textroot' : 'textroot.png',
171         'alceste' : 'reinert.png',
172         'corpus' : 'textcorpus.png',
173         'wordcloud' :'wordcloud.png',
174         'stat' :'stats.png',
175         'simitxt' : 'simitxt.png',
176         'clustersimitxt' :'clustersimitxt.png',
177         'clustercloud' : 'clustercloud.png',
178         'spec' : 'spec.png',
179         'matroot' : 'matroot.png',
180         'matrix' : 'matrix.png',
181         'freq' : 'frequences.png',
182         'freqmulti' : 'frequences.png',
183         'chi2' : 'chi2.png',
184         'reinertmatrix' : 'reinertmatrix.png',
185         'simimatrix' : 'simimatrix.png',
186         'simiclustermatrix' : 'simimatrix.png',
187         'proto' : 'proto.png',
188         'TXM' : 'TXM.png',
189         'europress' : 'europress.png',
190         'factiva_xml' : 'factiva_xml.png',
191         'factiva_copy' : 'factiva_copy.png',
192         'factiva_mail': 'factiva_mail.png',
193         'iramuteq' : 'iraicone.png',
194         'subcorpusmeta' : 'subcorpusmeta.png',
195         'subcorpusthema' : 'subcorpusthema.png',
196         'preferences' : 'preferences.png'
197          }
198 #####################################################################
199
200 class IraFrame(wx.Frame):
201     def __init__(self, parent, id= -1, title="", pos=wx.DefaultPosition,
202                  size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE | 
203                                             wx.SUNKEN_BORDER | 
204                                             wx.CLIP_CHILDREN):
205         log.info('Starting...')
206         wx.Frame.__init__(self, parent, id, title, pos, size, style)
207         #configuration
208         self.AppliPath = AppliPath
209         self.images_path = os.path.join(AppliPath,'images')
210         self.UserConfigPath = UserConfigPath
211         #self.RscriptsPath = ConstructRscriptsPath(AppliPath)
212         self.RscriptsPath = PathOut(dirout=os.path.join(AppliPath, 'Rscripts'))
213         self.RscriptsPath.basefiles(RscriptsPath)
214         #self.DictPath = ConstructDicoPath(AppliPath)
215         self.DictPath = ConstructDicoPath(UserConfigPath)
216         self.ConfigGlob = ConfigGlob
217         self.ConfigPath = ConstructConfigPath(UserConfigPath)
218         self.pref = RawConfigParser()
219         #workaround for import problem
220         self.SimiFromCluster = SimiFromCluster
221         #langues
222         gettext.install('iramuteq',  os.path.join(AppliPath,'locale'), unicode=True)
223         #langues = ['fr_FR', 'en', 'pt_PT']
224         #for l in langues :
225         #    pass
226         self.preslangue = {}
227         for langue in code_langues :
228             self.preslangue[langue] = gettext.translation("iramuteq", os.path.join(AppliPath,'locale'), languages=[code_langues[langue]])
229         self.setlangue()
230         #self.presLan_fr = gettext.translation("iramuteq", os.path.join(AppliPath,'locale'), languages=['fr_FR'])
231         #self.presLan_en = gettext.translation("iramuteq", os.path.join(AppliPath,'locale'), languages=['en'])
232         # tell FrameManager to manage this frame        
233         #self._mgr = wx.aui.AuiManager()
234         self._mgr = aui.AuiManager()
235         self._mgr.SetManagedWindow(self)
236         self.x = 0
237         # create menu
238 #--------------------------------------------------------------------------------
239         self.images_analyses = images_analyses
240         for img in images_analyses :
241             self.images_analyses[img] = wx.Image(os.path.join(self.images_path, self.images_analyses[img]), wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap()
242         self.mb = wx.MenuBar()
243
244         file_menu = wx.Menu()
245         item = wx.MenuItem(file_menu, ID_OpenData, _(u"Open a matrix").decode('utf8'), _(u"Open a matrix").decode('utf8'))
246         #item.SetBitmap(wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN))
247         item.SetBitmap(self.images_analyses['matroot'])
248         file_menu.AppendItem(item)
249         
250         item = wx.MenuItem(file_menu, ID_OpenText, _(u"Open a text corpus").decode('utf8'), _(u"Open a text corpus").decode('utf8'))
251         item.SetBitmap(self.images_analyses['textroot'])
252         file_menu.AppendItem(item)
253         
254         item = wx.MenuItem(file_menu, ID_OnOpenAnalyse, _(u"Open an analysis").decode('utf8'), _(u"Open an analysis").decode('utf8'))
255         item.SetBitmap(self.images_analyses['iramuteq'])
256         file_menu.AppendItem(item)
257
258         item = wx.MenuItem(file_menu, ID_ImportTXM, _(u"Import from TXM").decode('utf8'), _(u"Import from TXM").decode('utf8'))
259         item.SetBitmap(self.images_analyses['TXM'])
260         file_menu.AppendItem(item)
261         
262         item = wx.MenuItem(file_menu, ID_ImportEuro, _(u"Import from Europress").decode('utf8'), _(u"Import from Europress").decode('utf8'))
263         item.SetBitmap(self.images_analyses['europress'])
264         file_menu.AppendItem(item)        
265         
266         menuFactiva = wx.Menu()
267         fact_from_xml = wx.MenuItem(menuFactiva, ID_Fact_xml, _(u"from xml").decode('utf8'))
268         fact_from_xml.SetBitmap(self.images_analyses['factiva_xml'])
269         fact_from_mail = wx.MenuItem(menuFactiva, ID_Fact_mail, _(u"from mail").decode('utf8'))
270         fact_from_mail.SetBitmap(self.images_analyses['factiva_mail'])
271         fact_from_txt = wx.MenuItem(menuFactiva, ID_Fact_copy, _(u"from copy/paste").decode('utf8'))
272         fact_from_txt.SetBitmap(self.images_analyses['factiva_copy'])
273         menuFactiva.AppendItem(fact_from_xml)
274         menuFactiva.AppendItem(fact_from_mail)
275         menuFactiva.AppendItem(fact_from_txt)
276         file_menu.AppendMenu(-1, _(u"Import from factiva").decode('utf8'), menuFactiva)
277
278         menuTools = wx.Menu()
279         splitvar = wx.MenuItem(menuTools, wx.ID_ANY, _(u"Split from variable").decode('utf8'))
280         extractmod = wx.MenuItem(menuTools, wx.ID_ANY, _(u"Extract mods").decode('utf8'))
281         extractthem = wx.MenuItem(menuTools, wx.ID_ANY, _(u"Extract thematics").decode('utf8'))
282         menuTools.AppendItem(splitvar)
283         menuTools.AppendItem(extractmod)
284         menuTools.AppendItem(extractthem)
285         self.ID_splitvar = splitvar.GetId()
286         self.ID_extractmod = extractmod.GetId()
287         self.ID_extractthem = extractthem.GetId()
288         file_menu.AppendMenu(-1, _(u"Tools").decode('utf8'), menuTools)
289
290                
291         #item = wx.MenuItem(file_menu, ID_SaveTab, _(u"Save tab as...").decode('utf8'), _(u"Save tab as...").decode('utf8'))
292         #item.SetBitmap(wx.ArtProvider_GetBitmap(wx.ART_FILE_SAVE_AS))
293         #file_menu.AppendItem(item)
294         
295         file_menu.Append(wx.ID_EXIT, _(u"Exit").decode('utf8'))
296         
297         edit_menu = wx.Menu()
298         pref = wx.MenuItem(edit_menu, wx.ID_PREFERENCES, _(u'Preferences').decode('utf8'))
299         pref.SetBitmap(self.images_analyses['preferences'])
300         edit_menu.AppendItem(pref)
301         #edit_menu.Append(wx.ID_PREFERENCES, _(u'Preferences').decode('utf8'))
302         
303         view_menu = wx.Menu()
304         home = wx.MenuItem(view_menu, ID_ACCEUIL, _(u"Home page").decode('utf8'))
305         home.SetBitmap(wx.ArtProvider_GetBitmap(wx.ART_GO_HOME, size = (16,16)))
306         view_menu.AppendItem(home)
307         #view_menu.Append(ID_ACCEUIL, _(u"Home page").decode('utf8'))
308         results = wx.MenuItem(view_menu, ID_RESULT, _(u'Show results').decode('utf8'))
309         results.SetBitmap(wx.ArtProvider_GetBitmap(wx.ART_LIST_VIEW, size = (16,16)))
310         view_menu.AppendItem(results)
311         #view_menu.Append(ID_RESULT, _(u'Show results').decode('utf8'))
312         #view_menu.AppendSeparator()
313         matrix_menu = wx.Menu()
314         matanalyses = [[ID_Freq, _(u"Frequencies").decode('utf8'), 'freq'],
315                        [ID_Freq, _(u"Multiple  Frequencies").decode('utf8'), 'freqmulti'],
316                        [ID_Chi2, _(u"Chi2").decode('utf8'), 'chi2'],
317                        {'name' : _(u"Clustering").decode('utf8'),
318                         'content' : [[ID_CHDReinert, _(u"Reinert's Method").decode('utf8'), 'reinertmatrix']]},
319                        [ID_SIMI, _(u"Similarities Analysis").decode('utf8'), 'simimatrix'],
320                        [ID_proto, _(u"Prototypical Analysis").decode('utf8'), 'proto'],
321                        [ID_Splitfromvar, _(u"Split from variable").decode('utf8'), 'subcorpusmeta'],
322                         ]
323         
324         for analyse in matanalyses :
325             if not isinstance(analyse, dict) :
326                 item = wx.MenuItem(matrix_menu, analyse[0], analyse[1])
327                 item.SetBitmap(self.images_analyses.get(analyse[2], wx.EmptyBitmap(16,16)))
328                 matrix_menu.AppendItem(item)
329             else :
330                 nmenu = wx.Menu()
331                 for subana in analyse['content'] :
332                     item = wx.MenuItem(nmenu, subana[0], subana[1])
333                     item.SetBitmap(self.images_analyses.get(subana[2], wx.EmptyBitmap(16,16)))
334                     nmenu.AppendItem(item)
335                 matrix_menu.AppendMenu(-1, analyse['name'], nmenu)
336         #item = wx.MenuItem(matrix_menu, ID_Freq, _(u"Frequencies").decode('utf8'))
337         #item.SetBitmap(self.images_analyses['freq'])
338         #matrix_menu.AppendItem(item)
339         #matrix_menu.Append(ID_Freq, _(u"Frequencies").decode('utf8'))
340         #item = wx.MenuItem(matrix_menu, ID_Freq, _(u"Multiple  Frequencies").decode('utf8'))
341         #item.SetBitmap(self.images_analyses['freqmulti'])
342         #matrix_menu.Append(ID_FreqMulti, _(u'Multiple frequencies').decode('utf8'))
343         #matrix_menu.AppendItem(item)
344         #matrix_menu.Append(ID_Chi2, _(u"Chi2").decode('utf8'))
345         #matrix_menu.Append(ID_Student, u"t de Student")
346         #menu_classif = wx.Menu()
347         #menu_classif.Append(ID_CHDReinert, _(u"Reinert's Method").decode('utf8'))
348         #menu_classif.Append(ID_CHDSIM, u"Par matrice des distances")
349         #matrix_menu.AppendMenu(-1, _(u"Clustering").decode('utf8'), menu_classif)
350         #matrix_menu.Append(ID_AFCM, u"AFCM")
351         #matrix_menu.Append(ID_SIMI, _(u"Similarities Analysis").decode('utf8'))
352         #matrix_menu.Append(ID_proto, _(u"Prototypical Analysis").decode('utf8'))
353         ID_RCODE = wx.NewId()
354         #matrix_menu.Append(ID_RCODE, u"Code R...") 
355         #menu_splittab = wx.Menu()
356         #ID_SPLITVAR = wx.NewId()
357         #splitvar = wx.MenuItem(menu_splittab, ID_SPLITVAR, _(u"Split from variable").decode('utf8'))
358         #menu_splittab.AppendItem(splitvar)
359         #matrix_menu.AppendMenu(-1, _(u"Split matrix").decode('utf8'), menu_splittab)
360         self.matrix_menu = matrix_menu
361         
362         text_menu = wx.Menu()
363         analyses_text = [[ID_TEXTSTAT, _(u"Statistics").decode('utf8'), 'stat'],
364                          [ID_ASLEX, _(u"Specificities and CA").decode('utf8'), 'spec'],
365                          {'name' : _(u"Clustering").decode('utf8'),
366                           'content' : [[ID_TEXTREINERT, _(u"Reinert's Method").decode('utf8'), 'alceste']]},
367                          [ID_SimiTxt, _(u"Similarities Analysis").decode('utf8'), 'simitxt'],
368                          [ID_WC, _(u"WordCloud").decode('utf8'), 'wordcloud'],
369                          {'name' : _(u"Sub corpus").decode('utf8'),
370                           'content' : [[ID_Subtxtfrommeta, _(u'Sub corpus from metadata').decode('utf8'), 'subcorpusmeta'],
371                                        [ID_Subtxtfromthem, _(u'Sub corpus from thematic').decode('utf8'), 'subcorpusthema']]},
372                          [ID_exportmeta, _(u"Export meta-data table").decode('utf8'), None],
373                          ]
374         
375         for analyse in analyses_text :
376             if not isinstance(analyse, dict) :
377                 item = wx.MenuItem(text_menu, analyse[0], analyse[1])
378                 item.SetBitmap(self.images_analyses.get(analyse[2], wx.EmptyBitmap(16,16)))
379                 text_menu.AppendItem(item)
380             else :
381                 nmenu = wx.Menu()
382                 for subana in analyse['content'] :
383                     item = wx.MenuItem(nmenu, subana[0], subana[1])
384                     item.SetBitmap(self.images_analyses.get(subana[2], wx.EmptyBitmap(16,16)))
385                     nmenu.AppendItem(item)
386                 text_menu.AppendMenu(-1, analyse['name'], nmenu)
387         #text_menu.Append(ID_CHECKCORPUS, u"Vérifier le corpus")
388 #         text_menu.Append(ID_TEXTSTAT, _(u"Statistics").decode('utf8'))
389 #         text_menu.Append(ID_ASLEX, _(u"Specificities and CA").decode('utf8'))
390 #         #text_menu.Append(ID_TEXTAFCM, u"AFC sur UCI / Vocabulaire")
391 #         menu_classiftxt = wx.Menu()
392 #         menu_classiftxt.Append(ID_TEXTREINERT, _(u"Reinert's Method").decode('utf8'))
393 #         #menu_classiftxt.Append(ID_TEXTPAM, u"Par matrice des distances")
394 #         text_menu.AppendMenu(-1, _(u"Clustering").decode('utf8'), menu_classiftxt)
395 #         text_menu.Append(ID_SimiTxt, _(u"Similarities Analysis").decode('utf8')) 
396 #         
397 #         text_menu.Append(ID_WC, _(u"WordCloud").decode('utf8'))
398         self.text_menu = text_menu
399         
400         help_menu = wx.Menu()
401         about = wx.MenuItem(help_menu, wx.ID_ABOUT, _(u"About...").decode('utf8'))
402         about.SetBitmap(wx.ArtProvider_GetBitmap(wx.ART_INFORMATION, size = (16,16)))
403         help_menu.AppendItem(about)
404         #help_menu.Append(wx.ID_ABOUT, _(u"About...").decode('utf8'))
405         help = wx.MenuItem(help_menu, wx.ID_HELP, _(u"Online help...").decode('utf8'))
406         help.SetBitmap(wx.ArtProvider_GetBitmap(wx.ART_HELP, size = (16,16)))
407         help_menu.AppendItem(help)
408         #help_menu.Append(wx.ID_HELP, _(u"Online help...").decode('utf8'))
409         
410         self.mb.Append(file_menu, _(u"File").decode('utf8'))
411         self.mb.Append(edit_menu, _(u"Edition").decode('utf8'))
412         self.mb.Append(view_menu, _(u"View").decode('utf8'))
413         self.mb.Append(matrix_menu, _(u"Matrix analysis").decode('utf8'))
414         self.mb.Append(text_menu, _(u"Text analysis").decode('utf8'))
415         self.mb.Append(help_menu, _(u"Help").decode('utf8'))
416         
417         self.SetMenuBar(self.mb)
418 #--------------------------------------------------------------------
419         self.statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
420         self.statusbar.SetStatusWidths([-2, -3])
421         self.statusbar.SetStatusText(_(u"Ready").decode('utf8'), 0)
422         self.statusbar.SetStatusText(_(u"Welcome").decode('utf8'), 1)
423
424         # min size for the frame itself isn't completely done.
425         # see the end up FrameManager::Update() for the test
426         # code. For now, just hard code a frame minimum size
427         self.SetMinSize(wx.Size(400, 400))
428
429         # create some toolbars
430         tb1 = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize,
431                          wx.TB_FLAT | wx.TB_NODIVIDER)
432         tb1.SetToolBitmapSize(wx.Size(16, 16))
433         tb1.AddLabelTool(ID_OpenData, "OpenData", self.images_analyses['matroot'], shortHelp=_(u"Matrix").decode('utf8'), longHelp=_(u"Open a matrix").decode('utf8'))
434         tb1.AddSeparator()
435         tb1.AddLabelTool(ID_OpenText, "OpenText", self.images_analyses['textroot'], shortHelp=_(u"Text").decode('utf8'), longHelp=_(u"Open a text corpus").decode('utf8'))
436         tb1.AddSeparator()
437         tb1.AddLabelTool(ID_OnOpenAnalyse, "OpenAnalyse", self.images_analyses['iramuteq'], shortHelp= _(u"Open an analysis").decode('utf8'), longHelp=_(u"Open an analysis").decode('utf8'))
438         tb1.AddSeparator()
439         tb1.AddLabelTool(ID_ImportTXM, "ImportTXM", self.images_analyses['TXM'], shortHelp= _(u"Import from TXM").decode('utf8'), longHelp=_(u"Import from TXM").decode('utf8'))
440         tb1.AddSeparator()
441         tb1.AddLabelTool(ID_ImportEuro, "ImportEuro", self.images_analyses['europress'], shortHelp= _(u"Import from Europress").decode('utf8'), longHelp=_(u"Import from Europress").decode('utf8'))
442         tb1.AddSeparator()
443         tb1.AddLabelTool(ID_Fact_xml, "ImportFactxml", self.images_analyses['factiva_xml'], shortHelp= _(u"Factiva from xml").decode('utf8'), longHelp=_(u"Factiva from xml").decode('utf8'))
444         tb1.AddLabelTool(ID_Fact_mail, "ImportFactmail", self.images_analyses['factiva_mail'], shortHelp= _(u"Factiva from mail").decode('utf8'), longHelp=_(u"Factiva from mail").decode('utf8'))
445         tb1.AddLabelTool(ID_Fact_copy, "ImportFactcopy", self.images_analyses['factiva_copy'], shortHelp= _(u"Factiva from copy/paste").decode('utf8'), longHelp=_(u"Factiva from copy/paste").decode('utf8'))
446         tb1.AddSeparator()
447         tb1.AddLabelTool(wx.ID_PREFERENCES, "Preferences", self.images_analyses['preferences'], shortHelp= _(u"Preferences").decode('utf8'), longHelp=_(u"Preferences").decode('utf8'))
448         tb1.AddSeparator()
449         tb1.AddLabelTool(ID_ACCEUIL, "Home", wx.ArtProvider_GetBitmap(wx.ART_GO_HOME, size = (16,16)), shortHelp= _(u"Home page").decode('utf8'), longHelp=_(u"Home page").decode('utf8'))
450         tb1.AddLabelTool(ID_RESULT, "Results", wx.ArtProvider_GetBitmap(wx.ART_LIST_VIEW, size = (16,16)), shortHelp= _(u'Show results').decode('utf8'), longHelp=_(u'Show results').decode('utf8'))
451         tb1.Realize()
452         
453         tb_text = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize,
454                          wx.TB_FLAT | wx.TB_NODIVIDER)
455         for analyse in analyses_text :
456             if not isinstance(analyse, dict) :
457                 tb_text.AddLabelTool(analyse[0], analyse[1], self.images_analyses.get(analyse[2], wx.EmptyBitmap(16,16)), shortHelp = analyse[1], longHelp = analyse[1])
458             else :
459                 for subana in analyse['content'] :
460                     tb_text.AddLabelTool(subana[0], subana[1], self.images_analyses.get(subana[2], wx.EmptyBitmap(16,16)), shortHelp = subana[1], longHelp = subana[1])
461         tb_text.Realize()
462         
463         tb_mat = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize,
464                          wx.TB_FLAT | wx.TB_NODIVIDER)
465         for analyse in matanalyses :
466             if not isinstance(analyse, dict) :
467                 tb_mat.AddLabelTool(analyse[0], analyse[1], self.images_analyses.get(analyse[2], wx.EmptyBitmap(16,16)), shortHelp = analyse[1], longHelp = analyse[1])
468             else :
469                 for subana in analyse['content'] :
470                     tb_mat.AddLabelTool(subana[0], subana[1], self.images_analyses.get(subana[2], wx.EmptyBitmap(16,16)), shortHelp = subana[1], longHelp = subana[1])        
471         tb_mat.Realize()
472         
473         tb_help = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize,
474                          wx.TB_FLAT | wx.TB_NODIVIDER)
475         tb_help.AddLabelTool(wx.ID_ABOUT, "About", wx.ArtProvider_GetBitmap(wx.ART_INFORMATION, size=(16,16)), shortHelp=_(u"About...").decode('utf8'), longHelp=_(u"About...").decode('utf8'))
476         tb_help.AddLabelTool(wx.ID_HELP, "Help", wx.ArtProvider_GetBitmap(wx.ART_HELP, size=(16,16)), shortHelp=_(u"Online help...").decode('utf8'), longHelp=_(u"Online help...").decode('utf8'))
477         tb_help.Realize()
478 #------------------------------------------------------------------------------------------------
479
480         self.text_ctrl_txt = wx.TextCtrl(self, -1, "", wx.Point(0, 0), wx.Size(200, 200), wx.NO_BORDER | wx.TE_MULTILINE | wx.TE_RICH2 | wx.TE_READONLY)
481                       
482         #self._mgr.AddPane(self.text_ctrl_txt, wx.aui.AuiPaneInfo().
483         #                  Name("Text").CenterPane())                      
484         self._mgr.AddPane(self.text_ctrl_txt, aui.AuiPaneInfo().
485                           Name("Text").CenterPane())
486         #self._mgr.AddPane(IntroPanel(self), wx.aui.AuiPaneInfo().Name("Intro_Text").
487         #                  CenterPane())
488         self._mgr.AddPane(IntroPanel(self), aui.AuiPaneInfo().Name("Intro_Text").
489                           CenterPane())
490         #if not os.path.exists(os.path.join(UserConfigPath, 'history.db')) :
491         #    with open(os.path.join(UserConfigPath, 'history.db'), 'w') as f :
492         #        f.write('')
493         self.history = History(os.path.join(UserConfigPath, 'history.db'))
494         self.tree = LeftTree(self)
495         self._mgr.AddPane(self.tree, aui.AuiPaneInfo().Name("lefttree").Caption(_(u"Historic").decode('utf8')).
496                           Left().MinSize(wx.Size(200,500)).Layer(1).Position(1).CloseButton(False).MaximizeButton(True).
497                           MinimizeButton(True))
498         
499         #self.nb = wx.aui.AuiNotebook(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.aui.AUI_NB_DEFAULT_STYLE | wx.aui.AUI_NB_TAB_EXTERNAL_MOVE | wx.aui.AUI_NB_TAB_MOVE | wx.aui.AUI_NB_TAB_FLOAT| wx.NO_BORDER)
500         self.nb = aui.AuiNotebook(self, -1, wx.DefaultPosition, wx.DefaultSize, aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | aui.AUI_NB_TAB_MOVE | aui.AUI_NB_TAB_FLOAT| wx.NO_BORDER)
501         notebook_flags =  aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | aui.AUI_NB_TAB_MOVE | aui.AUI_NB_TAB_FLOAT| wx.NO_BORDER
502         self.nb.SetAGWWindowStyleFlag(notebook_flags)
503         self.nb.SetArtProvider(aui.ChromeTabArt())
504         #self.nb.SetArtProvider(aui.VC8TabArt())
505         #self.nb.parent = self
506         #self._notebook_style = aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | wx.NO_BORDER
507         #self._mgr.AddPane(self.nb, wx.aui.AuiPaneInfo().
508         #                      Name("Tab_content").
509         #                      CenterPane())
510         self._mgr.AddPane(self.nb, aui.AuiPaneInfo().
511                               Name("Tab_content").
512                               CenterPane())        
513         
514         #self._mgr.AddPane(self.Sheet, wx.aui.AuiPaneInfo().Name("Data").CenterPane())
515         #self._mgr.AddPane(self.Sheet, aui.AuiPaneInfo().Name("Data").CenterPane())
516         self.nb.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnCloseTab)
517         self.nb.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
518         # add the toolbars to the manager
519                         
520         #self._mgr.AddPane(tb1, wx.aui.AuiPaneInfo().
521         #                  Name("tb1").Caption("Fichiers").
522         #                  ToolbarPane().Top().
523         #                  LeftDockable(False).RightDockable(False))
524         self._mgr.AddPane(tb1, aui.AuiPaneInfo().
525                           Name("tb1").Caption("Fichiers").
526                           ToolbarPane().Top().
527                           LeftDockable(True).RightDockable(False))
528         
529         self._mgr.AddPane(tb_text, aui.AuiPaneInfo().
530                           Name("tb_text").Caption("analyse_text").
531                           ToolbarPane().Top().
532                           LeftDockable(True).RightDockable(False))
533         
534         self._mgr.AddPane(tb_mat, aui.AuiPaneInfo().
535                           Name("tb_mat").Caption("analyse_matrix").
536                           ToolbarPane().Top().
537                           LeftDockable(True).RightDockable(False))
538                 
539         self._mgr.AddPane(tb_help, aui.AuiPaneInfo().
540                           Name("tb_help").Caption("help").
541                           ToolbarPane().Top().
542                           LeftDockable(True).RightDockable(False))
543                 
544         self._mgr.GetPane('tb_text').Hide()
545         self._mgr.GetPane('tb_mat').Hide()
546         
547         self.ShowAPane("Intro_Text")
548         self._mgr.GetPane("lefttree").Show()
549         self._mgr.GetPane("classif_tb").Hide()
550         # "commit" all changes made to FrameManager   
551         self._mgr.Update()
552
553         # Show How To Use The Closing Panes Event
554 ##################################################################        
555         self.Bind(wx.EVT_MENU, self.OnAcceuil, id=ID_ACCEUIL)
556         self.Bind(wx.EVT_MENU, self.ShowTab, id=ID_RESULT)
557         self.Bind(wx.EVT_MENU, self.OnOpenData, id=ID_OpenData)
558         self.Bind(wx.EVT_MENU, self.OnOpenText, id=ID_OpenText)
559         self.Bind(wx.EVT_MENU, self.OnOpenAnalyse, id=ID_OnOpenAnalyse)
560         self.Bind(wx.EVT_MENU, self.import_factiva_xml, fact_from_xml)
561         self.Bind(wx.EVT_MENU, self.import_factiva_mail, fact_from_mail)
562         self.Bind(wx.EVT_MENU, self.import_factiva_txt, fact_from_txt)
563         self.Bind(wx.EVT_MENU, self.ExtractTools, splitvar)
564         self.Bind(wx.EVT_MENU, self.ExtractTools, extractmod)
565         self.Bind(wx.EVT_MENU, self.ExtractTools, extractthem)
566         self.Bind(wx.EVT_MENU, self.OnFreq, id=ID_Freq)
567         self.Bind(wx.EVT_MENU, self.OnFreqMulti, id=ID_FreqMulti)
568         self.Bind(wx.EVT_MENU, self.OnChi2, id=ID_Chi2)
569         self.Bind(wx.EVT_MENU, self.OnStudent, id=ID_Student)
570         self.Bind(wx.EVT_MENU, self.OnCHDSIM, id=ID_CHDSIM)
571         self.Bind(wx.EVT_MENU, self.OnCHDReinert, id=ID_CHDReinert)
572         self.Bind(wx.EVT_MENU, self.OnAFCM, id=ID_AFCM)
573         self.Bind(wx.EVT_MENU, self.OnProto, id=ID_proto)
574         self.Bind(wx.EVT_MENU, self.OnSplitVar, id = ID_Splitfromvar)
575         #self.Bind(wx.EVT_MENU, self.OnRCode, id=ID_RCODE)
576         #self.Bind(wx.EVT_MENU, self.OnSplitVar, id=ID_SPLITVAR)
577         #self.Bind(wx.EVT_MENU, self.OnCheckcorpus, id = ID_CHECKCORPUS)
578         self.Bind(wx.EVT_MENU, self.OnTextStat, id=ID_TEXTSTAT)
579         self.Bind(wx.EVT_MENU, self.OnTextSpec, id=ID_ASLEX)
580         self.Bind(wx.EVT_MENU, self.OnTextAfcm, id=ID_TEXTAFCM)
581         self.Bind(wx.EVT_MENU, self.OnTextReinert, id=ID_TEXTREINERT)
582         self.Bind(wx.EVT_MENU, self.OnPamSimple, id=ID_TEXTPAM)
583         self.Bind(wx.EVT_MENU, self.OnSimiTxt, id=ID_SimiTxt)
584         self.Bind(wx.EVT_MENU, self.OnWordCloud, id=ID_WC)
585         self.Bind(wx.EVT_MENU, self.OnSubText, id = ID_Subtxtfrommeta)
586         self.Bind(wx.EVT_MENU, self.OnSubText, id = ID_Subtxtfromthem)
587         self.Bind(wx.EVT_MENU, self.OnSimiTab, id=ID_SIMI)
588         self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
589         #self.Bind(wx.EVT_MENU, self.OnSaveTabAs, id=ID_SaveTab)
590         self.Bind(wx.EVT_MENU, self.OnAbout, id=wx.ID_ABOUT)
591         self.Bind(wx.EVT_MENU, self.OnHelp, id=wx.ID_HELP)
592         self.Bind(wx.EVT_MENU, self.OnPref, id=wx.ID_PREFERENCES)
593         self.Bind(wx.EVT_MENU, self.OnImportTXM, id=ID_ImportTXM)
594         self.Bind(wx.EVT_MENU, self.OnImportEuropress, id=ID_ImportEuro)
595         self.Bind(wx.EVT_MENU, self.OnExportMeta, id=ID_exportmeta)
596         self.Bind(wx.EVT_CLOSE, self.OnClose)
597 ##################################################################
598         flags = self._mgr.GetAGWFlags()
599         #flags &= ~wx.aui.AUI_MGR_TRANSPARENT_HINT
600         #flags &= ~wx.aui.AUI_MGR_VENETIAN_BLINDS_HINT
601         #flags &= ~wx.aui.AUI_MGR_RECTANGLE_HINT
602         flags &= ~(aui.AUI_MGR_RECTANGLE_HINT | aui.AUI_MGR_ALLOW_FLOATING)
603         self._mgr.SetAGWFlags(self._mgr.GetAGWFlags() ^ (aui.AUI_MGR_RECTANGLE_HINT | aui.AUI_MGR_ALLOW_FLOATING))
604         self._mgr.GetArtProvider().SetMetric(aui.AUI_DOCKART_GRADIENT_TYPE, aui.AUI_GRADIENT_HORIZONTAL)
605         self.GetDockArt().SetColor(aui.AUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR, "#00FFF9")
606         self.DoUpdate()
607
608         self._icon = wx.Icon(os.path.join(ImagePath, "iraicone.ico"), wx.BITMAP_TYPE_ICO)
609         self.SetIcon(self._icon)
610 ##########################
611         self.ctrl = ""
612         self.input_path = [False]
613         self.TEMPDIR = tempfile.mkdtemp('iramuteq')
614         self.FileTabList = []
615         self.listbar=[]
616         self.DictTab = {}
617         self.FreqNum = 0
618         self.colsep = ''
619         self.txtsep = ''
620         self.g_header = False
621         self.g_id = False
622         self.table = ''
623         self.fileforR = ''
624         self.filename = ''
625         self.nastrings = ''
626         self.encode = ''
627         self.SysEncoding = sys.getdefaultencoding()
628         self.syscoding = sys.getdefaultencoding()
629         #print 'SysEncoding',self.SysEncoding
630         if self.SysEncoding == 'mac-roman' : self.SysEncoding = 'MacRoman'
631         self.type = ''
632
633 ##############################################################@
634         self.ShowMenu('view', True)
635         self.ShowMenu('matrix', False)
636         self.ShowMenu('text', False)
637    
638         self._mgr.Update()
639
640         self.DataPop = False
641         self.DataTxt = False
642         self.Text = ''
643
644         self.lexique = None
645         self.corpus = None
646
647     def finish_init(self) :
648         try :
649             self.pref.read(self.ConfigPath['preferences'])
650             if IsNew(self) :
651                 UpgradeConf(self)
652                 self.pref.read(self.ConfigPath['preferences'])
653                 New = True
654             else :
655                 CopyConf(self)
656                 New = False
657         except :
658             UpgradeConf(self)
659             self.pref.read(self.ConfigPath['preferences'])
660             New = True
661         self.sound = self.pref.getboolean('iramuteq', 'sound')
662         self.check_update = self.pref.getboolean('iramuteq', 'checkupdate')
663         self.version = ConfigGlob.get('DEFAULT', 'version')
664         #configuration des chemins de R
665         self.PathPath = ConfigParser()
666         self.PathPath.read(ConfigPath['path'])
667         BestRPath = False
668         if not CheckRPath(self.PathPath) :
669             if sys.platform == 'win32':
670                 BestRPath = FindRPAthWin32()
671             else:
672                 BestRPath = FindRPathNix()
673             if BestRPath:
674                 self.PathPath.set('PATHS', 'rpath', BestRPath)
675                 with open(ConfigPath['path'], 'w') as f :
676                     self.PathPath.write(f)
677         else:
678             BestRPath = True 
679         if BestRPath :
680             self.RPath = self.PathPath.get('PATHS', 'rpath')
681             if New :
682                 CheckRPackages(self)
683             if not RLibsAreInstalled(self) :
684                 CheckRPackages(self)
685         else :
686             msg = '\n'.join([_(u"Can't find R executable"), _(u"If R is not installed, get it from http://www.r-project.org.").decode('utf8'),
687                              _(u"If R is installed, report its path in Preferences.").decode('utf8'),
688                              _(u"IRaMuTeQ does not work without R.").decode('utf8')])
689             dlg = wx.MessageDialog(self, msg, _(u"Problem").decode('utf8'), wx.OK | wx.NO_DEFAULT | wx.ICON_WARNING)
690             dlg.CenterOnParent()
691             if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]:
692                 pass
693             dlg.Destroy()
694
695     def setlangue(self) :
696         self.pref.read(self.ConfigPath['preferences'])
697         try :
698             guilangue = self.pref.get('iramuteq', 'guilanguage')
699         except :
700             guilangue = DefaultConf.get('iramuteq', 'guilanguage')
701         self.preslangue.get(guilangue, 'english').install()
702
703     def OnVerif(self, evt) :
704         pack = CheckRPackages(self)
705         if pack :
706             dlg = wx.MessageDialog(self, _(u"Installation OK").decode('utf8'), _(u"Installation").decode('utf8'), wx.OK | wx.ICON_INFORMATION | wx.STAY_ON_TOP)
707             dlg.CenterOnParent()
708             if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]:
709                 evt.Veto()
710
711     def ShowMenu(self, menu, Show=True):
712         if menu == 'text' :
713             menu_pos = 4
714             if Show :
715                 self._mgr.GetPane('tb_text').Show()
716             else :
717                 self._mgr.GetPane('tb_text').Hide()   
718         elif menu == 'matrix' :
719             menu_pos = 3
720             if Show :
721                 self._mgr.GetPane('tb_mat').Show()
722             else :
723                 self._mgr.GetPane('tb_mat').Hide()           
724         elif menu == 'view' :
725             menu_pos = 2
726         else :
727             menu_pos = None
728             
729         #menu_pos = self.mb.FindMenu(menu)
730         if not menu_pos is None :
731             self.mb.EnableTop(menu_pos, Show)
732             self.mb.UpdateMenus()
733         self._mgr.Update()
734
735 #--------------------------------------------------------------------
736     def OnClose(self, event):
737         print 'onclose'
738         with open(self.ConfigPath['path'], 'w') as f :
739             self.PathPath.write(f)
740         self._mgr.UnInit()
741         del self._mgr
742         self.Destroy()
743
744     def OnOpenData(self, event):
745         inputname, self.input_path = OnOpen(self, "Data")
746         if inputname:
747             #filename = self.input_path[0]
748             self.tableau = Tableau(self,os.path.abspath(self.input_path[0]))
749             val = get_table_param(self, self.input_path[0])
750             if val == wx.ID_OK :
751                 busy = wx.BusyInfo(_("Please wait...").decode('utf8'), self)
752                 wx.SafeYield()
753                 try :
754                     self.tableau.make_content()
755                     OpenAnalyse(self, self.tableau.parametres)
756                     self.tree.OnItemAppend(self.tableau.parametres)
757                     del busy 
758                 except :
759                     del busy
760                     BugReport(self)
761                 #self.tableau.show_tab()
762
763     def OnOpenAnalyse(self, event):
764         self.AnalysePath = OnOpen(self, "Analyse")
765         if self.AnalysePath :
766             OpenAnalyse(self, self.AnalysePath[1][0], True)
767             self.ShowMenu('view')
768
769     def OnOpenText(self, event):
770         inputname, self.input_path = OnOpen(self, "Texte")
771         self.filename = self.input_path[0]
772         if inputname:
773             self.OpenText()
774    
775     def OnSubText(self, evt, corpus = None, parametres = None):
776         if corpus is None :
777             corpus = self.tree.getcorpus()
778         if evt.GetId() == ID_Subtxtfrommeta :
779             parametres = {'frommeta' : True}
780         elif evt.GetId() == ID_Subtxtfromthem :
781             parametres = {'fromtheme' : True}
782         builder = SubBuilder(self, corpus, parametres)
783         if builder.res == wx.ID_OK :
784             busy = wx.BusyInfo(_("Please wait...").decode('utf8'), self)
785             wx.SafeYield()
786             corpus = builder.doanalyse()
787             self.history.add(corpus.parametres)
788             self.tree.OnItemAppend(corpus.parametres)
789             OpenAnalyse(self, corpus.parametres)
790             del busy
791             
792     def OpenText(self):
793         dlg = wx.ProgressDialog("Ouverture...",
794                                    "Veuillez patienter...",
795                                    maximum=2,
796                                    parent=self,
797                                    style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME | wx.PD_CAN_ABORT
798                                    )
799         
800         builder =  Builder(self, dlg)
801         if builder.res == wx.ID_OK :
802             try :
803                 corpus = builder.doanalyse()
804                 self.history.add(corpus.parametres)
805                 self.tree.OnItemAppend(corpus.parametres)
806                 OpenAnalyse(self, corpus.parametres)
807             except :
808                 dlg.Destroy()
809                 BugReport(self)
810             else :
811                 count = 1
812                 keepGoing = dlg.Update(count, u"Lecture du fichier")
813                 self.ShowMenu('view')
814                 self.ShowMenu('text')
815                 self.ShowMenu('matrix', False)
816                 self.type = "Texte"
817                 self.DataTxt = False
818                 self.Text = ''
819                 count += 1
820                 keepGoing = dlg.Update(count, u"Chargement du dictionnaire")
821                 dlg.Destroy()
822         
823     def OnExit(self, event):
824         self.Close()
825
826     def OnAbout(self, event):
827         info = wx.AboutDialogInfo()
828         info.Name = ConfigGlob.get('DEFAULT', 'name')
829         info.Version = ConfigGlob.get('DEFAULT', 'version')
830         info.Copyright = ConfigGlob.get('DEFAULT', 'copyright')
831         info.Translators = ConfigGlob.get('DEFAULT', 'translators').decode('utf8').split(';')
832         info.Description = u"""
833 Interface de R pour les Analyses Multidimensionnelles 
834 de Textes et de Questionnaires
835
836 Un logiciel libre
837 construit avec des logiciels libres.
838
839 Laboratoire LERASS
840
841 REPERE
842 """
843         info.WebSite = ("http://www.iramuteq.org", u"Site web IRaMuTeQ")
844         dev = ConfigGlob.get('DEFAULT', 'dev').decode('utf8').split(';')
845         info.Developers = dev
846         info.License = u"""Iramuteq est un logiciel libre ; vous pouvez le diffuser et/ou le modifier 
847 suivant les termes de la Licence Publique Générale GNU telle que publiée 
848 par la Free Software Foundation ; soit la version 2 de cette licence, 
849 soit (à votre convenance) une version ultérieure.
850
851 Iramuteq est diffusé dans l'espoir qu'il sera utile, 
852 mais SANS AUCUNE GARANTIE ; sans même une garantie implicite 
853 de COMMERCIALISATION ou d'ADÉQUATION Ã€ UN USAGE PARTICULIER. 
854 Voyez la Licence Publique Générale GNU pour plus de détails.
855
856 Vous devriez avoir reçu une copie de la Licence Publique Générale GNU
857 avec Iramuteq ; sinon, veuillez Ã©crire Ã  la Free Software Foundation,
858 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, Ã‰tats-Unis."""
859         wx.AboutBox(info)
860
861     def GetDockArt(self):
862         return self._mgr.GetArtProvider()
863
864     def DoUpdate(self):
865         self._mgr.Update()
866
867     def OnPageChanged(self, event) :
868         new = event.GetSelection()
869         nobject = event.GetEventObject()
870         parent = nobject.GetParent()
871         if isinstance(parent, IraFrame) :
872             npage = self.nb.GetPage(new)
873             if 'parametres' in dir(npage) :
874                 self.tree.GiveFocus(uuid=npage.parametres['uuid'])
875                 if npage.parametres.get('matrix', False) :
876                     self.ShowMenu('text', False)
877                     self.ShowMenu('matrix', True)
878                 elif npage.parametres.get('corpus', False) :
879                     self.ShowMenu('text')
880                     self.ShowMenu('matrix', False)
881
882     def OnCloseTab(self, evt):
883         #log.info('Closing tab %s' % str(evt.GetEventObject()))
884         ctrl = evt.GetEventObject()
885         if isinstance(ctrl.GetParent(), aui.AuiNotebook) or isinstance(ctrl.GetParent(), wx.Panel):
886             notebook = True
887         else :
888             notebook = False
889         page = self.nb.GetPage(self.nb.GetSelection())
890         if 'parametres' in dir(page) and isinstance(ctrl.GetParent(), IraFrame) :
891             self.history.rmtab(page.parametres)
892             self.tree.CloseItem(uuid = page.parametres['uuid'])
893         TabTitle = self.nb.GetPageText(self.nb.GetSelection())
894
895         if self.nb.GetPageCount() == 1 and not notebook :
896             self.LastTabClose()
897     
898     def LastTabClose(self) :
899         if self.nb.GetPageCount() == 1 :
900             if self.DataTxt :
901                 self.ShowAPane("Text")
902             elif self.DataPop :
903                 self.ShowAPane("Data")
904             else :
905                 self.ShowAPane("Intro_Text")
906
907     def GetStartPosition(self):
908
909         self.x = self.x + 20
910         x = self.x
911         pt = self.ClientToScreen(wx.Point(0, 0))
912         
913         return wx.Point(pt.x + x, pt.y + x)
914     
915     def ShowAPane(self, panel):
916         for pane in self._mgr.GetAllPanes() :
917             if not pane.IsToolbar() and pane.name != 'lefttree': 
918                 pane.Hide()
919         self._mgr.GetPane(panel).Show()
920         self._mgr.Update()
921         
922     def OnAcceuil(self, event):
923         self.ShowAPane(u"Intro_Text")
924         event.Skip()
925     
926     def CreateHTMLCtrl(self):
927         ctrl = wx.html.HtmlWindow(self, -1, wx.DefaultPosition, wx.Size(400, 300))
928         if "gtk2" in wx.PlatformInfo:
929             ctrl.SetStandardFonts()
930         ctrl.SetPage(u"text")        
931         return ctrl
932
933     def ShowTab(self, evt):
934         self.ShowAPane("Tab_content")
935
936 ################################################################
937 #debut des analyses
938 ################################################################
939     def analyse_matrix(self, analyse, analyse_type = '', matrix = None, parametres = None, dlgnb = 1):
940         if matrix is None :
941             matrix = self.tree.getmatrix()
942         if parametres is not None :
943             parametres['type'] = analyse_type
944         else :
945             parametres = {'type' : analyse_type}
946         try :
947         #print 'plus de bug@@@@@@@@@@@@@@@@@@@@@@'
948             analyse(self, matrix, parametres = parametres, dlg = dlgnb)
949         except:
950             BugReport(self)           
951
952     def OnFreq(self, event, matrix = None):
953         self.analyse_matrix(Frequences, analyse_type = 'freq', matrix = matrix, dlgnb = 3)
954     
955     def OnFreqMulti(self, event, matrix = None):
956         self.analyse_matrix(FreqMultiple, analyse_type = 'freqmulti', matrix = matrix, dlgnb = 3)
957
958     def OnChi2(self, event, matrix = None):
959         self.analyse_matrix(ChiSquare, matrix = matrix, analyse_type = 'chi2', dlgnb = 3) 
960
961     def OnSimiTab(self, event, matrix = None):
962         self.analyse_matrix(DoSimi, matrix = matrix, analyse_type = 'simimatrix', dlgnb = 5)
963
964     def OnCHDReinert(self, event, matrix = None):
965         #if matrix is None :
966         #    matrix = self.tree.getmatrix()
967         #AnalyseQuest(self, matrix, parametres = {'type' : 'reinertmatrix'}, dlg = 3)
968         self.analyse_matrix(AnalyseQuest, matrix = matrix, analyse_type = 'reinertmatrix', dlgnb = 5)
969             
970     def OnStudent(self, event):
971         try:
972             MakeStudent(self) 
973         except:
974             BugReport(self)
975
976     def OnRCode(self, event):
977         try:
978             InputText(self)
979         except:
980             BugReport(self)
981
982     def OnCHDSIM(self, event):
983         try:
984         #    print 'ATTENTION!!!!'
985             chdsim = ChdCluster(self)
986             if chdsim.val == wx.ID_OK:
987                 PlaySound(self)
988         except:
989             BugReport(self)
990  
991 #     def OnCHDReinert(self, event):
992 #         try:
993 #          #   print('PLUS DE BUG SUR ALCESTE QUESTIONNAIRE')
994 #             self.quest = AnalyseQuest(self)
995 #             if self.quest.val == wx.ID_OK:
996 #                 PlaySound(self)
997 #         except:
998 #             BugReport(self)
999     
1000     def OnProto(self, evt, matrix = None) :
1001         self.analyse_matrix(Prototypical, matrix = matrix, analyse_type = 'proto', dlgnb = 3) 
1002         #Prototypical(self, {'type' : 'proto'})
1003     
1004     def OnSplitVar(self, evt, matrix = None):
1005         if matrix is None :
1006             matrix = self.tree.getmatrix()
1007         self.analyse_matrix(SplitMatrixFromVar, matrix = matrix, analyse_type = 'splitvar', parametres = {'pathout': matrix.pathout.dirout}, dlgnb = 3)
1008         #matrix = self.tree.getmatrix()
1009         
1010
1011     def OnSimiTxt(self, evt, corpus = None) :
1012         #    print 'PLUS DE BUG SUR SIMITXT'
1013         try :
1014             #self.Text = SimiTxt(self)
1015             if corpus is None :
1016                 corpus = self.tree.getcorpus()            
1017             self.Text = SimiTxt(self, corpus, parametres = {'type': 'simitxt'}, dlg = 3)
1018             if self.Text.val == wx.ID_OK :
1019                 PlaySound(self)
1020         except :
1021             BugReport(self)
1022     
1023     def OnWordCloud(self, evt, corpus = None) :
1024         #    print 'PLUS DE BUG SUR WORDCLOUD'
1025         try :
1026             if corpus is None :
1027                 corpus = self.tree.getcorpus()            
1028             self.Text = WordCloud(self, corpus, parametres = {'type' : 'wordcloud'}, dlg = 3)
1029             if self.Text.val == wx.ID_OK :
1030                 PlaySound(self)
1031         except :
1032             BugReport(self)
1033
1034     def OnClusterCloud(self, corpus, parametres = None) :
1035         self.Text = ClusterCloud(self, corpus, parametres = parametres, dlg = 3)
1036
1037     def OnAFCM(self, event):
1038         try:
1039             DoAFCM(self)
1040         except:
1041             BugReport(self)
1042
1043     def OnTextStat(self, event, corpus = None):
1044             #print 'PAS DE BUG SUR TEXT STAT'
1045         try:
1046             if corpus is None :
1047                 corpus = self.tree.getcorpus()
1048             self.Text = Stat(self, corpus, parametres = {'type': 'stat'}, dlg = 7)
1049             
1050             if self.Text.val == wx.ID_OK :
1051                 PlaySound(self)
1052         except:
1053             BugReport(self)
1054         
1055     def OnTextSpec(self, event, corpus = None):  
1056         try:
1057             #self.Text = AsLexico(self)
1058             #print('ATTENTION : PLUS DE BUG SUR LEXICO')
1059             if corpus is None :
1060                 corpus = self.tree.getcorpus()
1061             self.Text = Lexico(self, corpus, parametres = {'type' : 'spec'}, dlg = 3)
1062             if self.Text.val == wx.ID_OK :
1063                 PlaySound(self)
1064         except:
1065             BugReport(self)
1066     
1067     def OnTextAfcm(self, event):
1068         try:
1069             AfcUci(self)
1070             PlaySound(self)
1071         except:
1072             BugReport(self)
1073
1074     def import_factiva_xml(self,event):
1075         try :
1076             ImportFactiva(self, 'xml')
1077         except :
1078             BugReport(self)
1079
1080     def import_factiva_mail(self, evt) :
1081         try :
1082             ImportFactiva(self, 'mail')
1083         except :
1084             BugReport(self)
1085
1086     def import_factiva_txt(self, evt) :
1087         try :
1088             ImportFactiva(self, 'txt')
1089         except :
1090             BugReport(self)
1091
1092     def OnImportTXM(self, evt) :
1093         try :
1094             ImportFactiva(self, 'txm')
1095         except :
1096             BugReport(self)
1097     
1098     def OnImportEuropress(self, evt) :
1099         try :
1100             ImportFactiva(self, 'euro')
1101         except :
1102             BugReport(self)
1103     
1104     def OnExportMeta(self, evt, corpus = None):
1105         if corpus is None :
1106             corpus = self.tree.getcorpus()
1107         try :
1108             ExportMetaTable(self, corpus)
1109         except :
1110             BugReport(self) 
1111
1112     def ExtractTools(self, evt) :
1113         ID = evt.GetId()
1114         if ID == self.ID_splitvar :
1115             Extract(self, 'splitvar')
1116         elif ID == self.ID_extractmod :
1117             Extract(self, 'mods')
1118         elif ID == self.ID_extractthem :
1119             Extract(self, 'them')
1120
1121     def OnTextReinert(self, event, corpus = None):
1122         try:
1123             #print('ATTENTION : PLUS DE BUG SUR ALCESTE')
1124             #RunAnalyse(self, corpus, Alceste, OptAlceste)
1125             if corpus is None :
1126                 corpus = self.tree.getcorpus()            
1127             self.Text = Reinert(self, corpus, parametres = {'type': 'alceste'}, dlg = 6)
1128             if self.Text.val == wx.ID_OK:
1129                 PlaySound(self)
1130         except:
1131             BugReport(self)
1132
1133     def OnPamSimple(self, event, corpus = None):
1134         try:
1135             if corpus is None :
1136                 corpus = self.tree.getcorpus()
1137             self.Text = AnalysePam(self, corpus, parametres = {'type' : 'pamtxt'}, dlg = 6)
1138             if self.Text.val == wx.ID_OK:
1139                 PlaySound(self)
1140         except:
1141             BugReport(self)
1142
1143     def SimiCluster(self, parametres = {}, fromprof = False, tableau = None) :
1144         self.analyse_matrix(DoSimi, parametres = parametres, analyse_type = 'simiclustermatrix', matrix = tableau, dlgnb = 5)
1145     
1146 #    def OnSimi(self,evt):
1147 #        try :
1148             #print 'ATTENTION !!!! VERGES'
1149             #print 'PLUS DE BUG SUR SIMI'
1150 #            self.res = DoSimi(self, param = None)
1151             #self.res = Verges(self)
1152 #            if self.res.val == wx.ID_OK :
1153 #                PlaySound(self)
1154 #        except :
1155 #            BugReport(self)
1156 #################################################################
1157
1158     def OnHelp(self, event):
1159         webbrowser.open('http://www.iramuteq.org/documentation')
1160     
1161     def OnPref(self, event):
1162         dlg = PrefDialog(self)
1163         dlg.CenterOnParent()
1164         self.val = dlg.ShowModal()
1165         dlg.Destroy()
1166
1167     def Upgrade(self) :
1168         if self.check_update:
1169             NewVersion(self)
1170         else:
1171             print 'pas de verif'    
1172         #IsNew(self)
1173         #CheckRPackages(self)
1174
1175     def OnOpenFromCmdl(self):
1176         truepath = True
1177         if options.filename :
1178             if os.path.exists(options.filename):
1179                 self.filename = os.path.abspath(options.filename)
1180             else:
1181                 truepath = False
1182         elif args :
1183             if os.path.exists(os.path.realpath(args[0])):
1184                 self.filename = os.path.abspath(os.path.realpath(args[0]))
1185             else:
1186                 truepath = False
1187         else:
1188             pass
1189         if truepath :
1190             if os.path.splitext(self.filename)[1] in ['.csv', '.xls', '.ods']:
1191                 self.tableau = Tableau(self, self.filename)
1192                 val = get_table_param(self, self.filename)
1193                 if val == wx.ID_OK :
1194                     self.tableau.make_content()
1195                     OpenAnalyse(self, self.tableau.parametres)
1196                     self.tree.OnItemAppend(self.tableau.parametres)
1197                 #get_table_param(self, self.filename)
1198                 #self.tableau.make_content()
1199                 #self.tableau.show_tab()
1200                 #open_data(self, self.filename)
1201             elif os.path.splitext(self.filename)[1] == '.txt':
1202                 self.OpenText()
1203             elif os.path.splitext(self.filename)[1] == '.ira' :
1204                 #self.corpus = Corpus(self)
1205                 #self.Text = OpenAnalyse(self, self.filename)
1206                 OpenAnalyse(self, self.filename)
1207         if not truepath:
1208             print 'ce fichier n\'existe pas'
1209             
1210         
1211
1212 class IntroPanel(wx.Panel):
1213     def __init__(self, parent):
1214         wx.Panel.__init__(self, parent)
1215         col = randint(0, 255)
1216         col1 = randint(0,255)
1217         col2 = randint(0,255)
1218         #col = 57
1219         bckgrdcolor = wx.Colour(col, col1, col2)
1220         self.SetBackgroundColour(bckgrdcolor)
1221         txtcolour = wx.Colour(250, 250, 250)
1222         linkcolor = wx.Colour(255, 0, 0)
1223         sizer1 = wx.BoxSizer(wx.VERTICAL)
1224         sizer2 = wx.BoxSizer(wx.VERTICAL)
1225         sizer3 = wx.BoxSizer(wx.HORIZONTAL)
1226         sizer4 = wx.BoxSizer(wx.HORIZONTAL)
1227         sizer5 = wx.BoxSizer(wx.HORIZONTAL)
1228         grid_sizer_1 = wx.FlexGridSizer(1, 4, 0, 0)
1229         grid_sizer_3 = wx.FlexGridSizer(1, 4, 0, 0)
1230         grid_sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
1231         PanelPres = wx.Panel(self)
1232         bckgrdcolor = wx.Colour(randint(0, 255), randint(0, 255), randint(0, 255))
1233         PanelPres.SetBackgroundColour(bckgrdcolor)
1234         label_1 = wx.StaticText(self, -1, u"IRaMuTeQ", size=(-1, -1))
1235         label_1.SetFont(wx.Font(46, wx.TELETYPE, wx.NORMAL, wx.BOLD, 0, "Purisa"))
1236         label_1.SetForegroundColour(wx.RED)
1237         iraicone = wx.Image(os.path.join(ImagePath,'iraicone248x248.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
1238         but_ira = wx.StaticBitmap(self, -1, bitmap = iraicone)
1239         label2 = wx.StaticText(PanelPres, -1 , u'\nVersion ' + ConfigGlob.get('DEFAULT', 'version') + '\n')
1240         label2.SetForegroundColour(txtcolour)
1241         label2.SetBackgroundColour(bckgrdcolor)
1242         #label3 = wx.StaticText(PanelPres, -1 , u'Equipe ')
1243         #label3.SetForegroundColour(txtcolour)
1244         #label3.SetBackgroundColour(bckgrdcolor)
1245         self.hyper2 = hl.HyperLinkCtrl(PanelPres, wx.ID_ANY, u"REPERE", URL="http://repere.no-ip.org/")
1246         self.hyper2.SetColours(linkcolor, linkcolor, "RED")
1247         self.hyper2.SetBackgroundColour(bckgrdcolor)
1248         self.hyper2.EnableRollover(True)
1249         self.hyper2.SetUnderlines(False, False, True)
1250         self.hyper2.SetBold(True)
1251         self.hyper2.UpdateLink()
1252         label_lerass = wx.StaticText(PanelPres, -1, u'Laboratoire ')
1253         label_lerass.SetForegroundColour(txtcolour)
1254         label_lerass.SetBackgroundColour(bckgrdcolor)
1255         self.hyper_lerass = hl.HyperLinkCtrl(PanelPres, -1, u'LERASS', URL="http://www.lerass.com")
1256         self.hyper_lerass.SetColours(linkcolor, linkcolor, "RED")
1257         self.hyper_lerass.SetBackgroundColour(bckgrdcolor)
1258         self.hyper_lerass.EnableRollover(True)
1259         self.hyper_lerass.SetUnderlines(False, False, True)
1260         self.hyper_lerass.SetBold(True)
1261         self.hyper_lerass.UpdateLink()
1262         blank = wx.StaticText(PanelPres, -1, u'\n')
1263         blank1 = wx.StaticText(PanelPres, -1, u'\n')
1264         labellicence = wx.StaticText(PanelPres, -1, _(u"License GNU GPL").decode('utf8'))
1265         labellicence.SetForegroundColour(txtcolour)
1266         labellicence.SetBackgroundColour(bckgrdcolor)
1267         labelcopy = wx.StaticText(PanelPres, -1, ConfigGlob.get('DEFAULT', 'copyright'))
1268         labelcopy.SetForegroundColour(txtcolour)
1269         labelcopy.SetBackgroundColour(bckgrdcolor)
1270         python_img = wx.Image(os.path.join(ImagePath,'python-logo.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
1271         r_img = wx.Image(os.path.join(ImagePath,'Rlogo.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
1272         lexique_img = wx.Image(os.path.join(ImagePath,'LexTexte4.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
1273         but_python = wx.BitmapButton(self, -1, python_img)
1274         but_lexique = wx.BitmapButton(self, -1, lexique_img)
1275         but_r = wx.BitmapButton(self, -1, r_img)
1276         self.Bind(wx.EVT_BUTTON, self.OnPython, but_python)
1277         self.Bind(wx.EVT_BUTTON, self.OnLexique, but_lexique)
1278         self.Bind(wx.EVT_BUTTON, self.OnR, but_r)
1279         
1280         
1281         #grid_sizer_1.Add(label3, 0, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL, 0)
1282         grid_sizer_1.Add(self.hyper2, 0, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL, 0)
1283         grid_sizer_3.Add(label_lerass, 0, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL, 0)
1284         grid_sizer_3.Add(self.hyper_lerass, 0, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL, 0)
1285         sizer4.Add(label_1, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
1286         
1287         sizer2.Add(label2, 0, wx.ALIGN_CENTER, 5)
1288         #sizer2.Add(wx.StaticText(PanelPres, -1, u''), 0, wx.ALIGN_CENTER, 5)
1289         sizer2.Add(wx.StaticText(PanelPres, -1, u''), 0, wx.ALIGN_CENTER, 5)
1290         sizer2.Add(wx.StaticText(PanelPres, -1, u''), 0, wx.ALIGN_CENTER, 5)
1291         sizer2.Add(grid_sizer_3, 0, wx.ALIGN_CENTER, 5)
1292         sizer2.Add(wx.StaticText(PanelPres, -1, u' '), 0, wx.ALIGN_CENTER, 5)
1293         #sizer2.Add(wx.StaticText(PanelPres, -1, u''), 0, wx.ALIGN_CENTER, 5)
1294         #sizer2.Add(wx.StaticText(PanelPres, -1, u''), 0, wx.ALIGN_CENTER, 5)
1295         sizer2.Add(grid_sizer_1, 0, wx.ALIGN_CENTER, 5)
1296         sizer2.Add(labellicence, 0, wx.ALIGN_CENTER, 5)
1297         sizer2.Add(labelcopy, 0, wx.ALIGN_CENTER, 5)
1298         sizer1.Add(sizer4, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
1299         sizer1.Add(but_ira, 1, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
1300         sizer2.Add(wx.StaticText(PanelPres, -1, u''), 0, wx.ALIGN_CENTER, 5)
1301         PanelPres.SetSizer(sizer2)
1302         #sizer5.Add(blank, 1, wx.EXPAND | wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 2)
1303         sizer5.Add(PanelPres, 1, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL, 0)
1304         #sizer5.Add(blank1, 1, wx.ALIGN_CENTER_HORIZONTAL,2)
1305         grid_sizer_2.Add(but_python, 1, wx.ALIGN_BOTTOM)
1306         grid_sizer_2.Add(but_lexique, 1, wx.ALIGN_BOTTOM)
1307         grid_sizer_2.Add(but_r, 1,  wx.ALIGN_BOTTOM)
1308         
1309         sizer1.Add(sizer5, 0, wx.EXPAND |wx.ALL, 10)
1310         sizer1.Add(grid_sizer_2, 2, wx.ALIGN_CENTER_HORIZONTAL|wx.ALL, 1)
1311         self.SetSizer(sizer1)
1312         sizer1.Fit(self)
1313     
1314     def OnPython(self,evt):
1315         webbrowser.open('http://www.python.org')
1316     
1317     def OnLexique(self,evt):
1318         webbrowser.open('http://www.lexique.org')
1319         
1320     def OnR(self,evt):
1321         webbrowser.open('http://www.r-project.org')
1322
1323 class MySplashScreen(wx.SplashScreen):
1324     def __init__(self):
1325         bmp = wx.Image(os.path.join(ImagePath, 'splash.png')).ConvertToBitmap()
1326         wx.SplashScreen.__init__(self, bmp,
1327                                  wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
1328                                  2000, None, -1)
1329         self.Bind(wx.EVT_CLOSE, self.OnClose)
1330         self.fc = wx.FutureCall(1, self.ShowMain)
1331
1332     def OnClose(self, evt):
1333         evt.Skip()
1334         self.Hide()
1335         
1336         if self.fc.IsRunning():
1337             self.fc.Stop()
1338             self.ShowMain()
1339
1340     def ShowMain(self):
1341         displaySize = wx.DisplaySize()
1342         w = displaySize[0]/1.2
1343         h = displaySize[1]/1.2
1344         frame = IraFrame(None, -1, "IRaMuTeQ " + ConfigGlob.get('DEFAULT', 'version'), size=(w, h))
1345         frame.Show()
1346         frame.finish_init()
1347         frame.Upgrade()
1348         frame.OnOpenFromCmdl()
1349 #        if self.fc.IsRunning():
1350 #            self.Raise()
1351         #wx.CallAfter(frame.ShowTip)
1352         
1353 class MyApp(wx.App):
1354     def OnInit(self):
1355         """
1356         Create and show the splash screen.  It will then create and show
1357         the main frame when it is time to do so.
1358         """
1359         wx.SystemOptions.SetOptionInt("mac.window-plain-transition", 1)
1360         self.SetAppName("Iramuteq")       
1361         splash = MySplashScreen()
1362         splash.Show()
1363         return True
1364
1365 def main():
1366     app = MyApp(False)
1367     app.MainLoop()
1368
1369 if __name__ == '__main__':
1370     __name__ = 'Main'
1371     main()