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