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