Merge branch 'master' of http://www.netdig.org/git/iramuteq
[iramuteq] / listlex.py
1 # -*- coding: utf-8 -*-
2
3 #----------------------------------------------------------------------------
4 # Author:       Pierre Ratinaud
5
6
7 #comes from ListCtrl.py from the demo tool of wxPython:
8 # Author:       Robin Dunn & Gary Dumer
9 #
10 # Created:
11 # Copyright:    (c) 1998 by Total Control Software
12 # Licence:      wxWindows license
13 #----------------------------------------------------------------------------
14
15 import os
16 import sys
17 import  wx
18 import  wx.lib.mixins.listctrl  as  listmix
19 import cStringIO
20 import tempfile
21 from functions import exec_rcode, MessageImage
22 from chemins import ffr
23 from PrintRScript import barplot
24 from dialog import SearchDial
25 #---------------------------------------------------------------------------
26
27 #class List(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
28 #    def __init__(self, parent, ID, pos=wx.DefaultPosition,
29 #                 size=wx.DefaultSize, style=0):
30 #        wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
31 #        listmix.ListCtrlAutoWidthMixin.__init__(self)
32
33 class ListForSpec(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin):
34     def __init__(self, parent,gparent, dlist,first):
35         wx.ListCtrl.__init__( self, parent, -1, style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES)
36         self.parent=parent
37         self.gparent=gparent
38         self.dlist=dlist
39         self.first = first
40
41         search_id = wx.NewId()
42         self.parent.Bind(wx.EVT_MENU, self.onsearch, id = search_id)
43         self.accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('F'), search_id)])
44         self.SetAcceleratorTable(self.accel_tbl)
45
46         self.il = wx.ImageList(16, 16)
47         a={"sm_up":"GO_UP","sm_dn":"GO_DOWN","w_idx":"WARNING","e_idx":"ERROR","i_idx":"QUESTION"}
48         for k,v in a.items():
49             s="self.%s= self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_%s,wx.ART_TOOLBAR,(16,16)))" % (k,v)
50             exec(s)
51         self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
52
53         tID = wx.NewId()
54
55         self.attr1 = wx.ListItemAttr()
56         self.attr1.SetBackgroundColour((230, 230, 230))
57         self.attr2 = wx.ListItemAttr()
58         self.attr2.SetBackgroundColour("light blue")
59         
60         self.dlist = dlist 
61
62         i=0
63         for name in first :
64             self.InsertColumn(i,name,wx.LIST_FORMAT_LEFT)
65             i+=1
66             
67         self.SetColumnWidth(0, 180)
68
69         for i in range(1,len(first)-1):
70             self.SetColumnWidth(i, len(first[i]) * 10)
71         
72         self.itemDataMap = dlist
73         self.itemIndexMap = dlist.keys()
74         self.SetItemCount(len(dlist))
75         
76         #listmix.ListCtrlAutoWidthMixin.__init__(self)
77         listmix.ColumnSorterMixin.__init__(self, len(first))
78         self.SortListItems(1, 0)
79         
80 #-----------------------------------------------------------------------------------------    
81         self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self)
82         
83         # for wxMSW
84         self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick)
85
86         # for wxGTK
87         self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
88
89 #-----------------------------------------------------------------------------------------    
90         
91     def OnGetItemText(self, item, col):
92         index=self.itemIndexMap[item]
93         s = self.itemDataMap[index][col]
94         return s
95
96     def OnGetItemAttr(self, item):
97         if item % 2 :
98             return self.attr1
99         else :
100             return self.attr2
101
102
103     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
104     def GetListCtrl(self):
105         return self
106
107     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
108     def GetSortImages(self):
109         return (self.sm_dn, self.sm_up)
110     
111     def OnRightDown(self, event):
112         x = event.GetX()
113         y = event.GetY()
114         item, flags = self.HitTest((x, y))
115
116         if flags & wx.LIST_HITTEST_ONITEM:
117             self.Select(item)
118
119         event.Skip()
120
121     def getColumnText(self, index, col):
122         item = self.GetItem(index, col)
123         return item.GetText()
124
125     def GetItemData(self, item) :
126         index=self.itemIndexMap[item]
127         s = self.itemDataMap[index]
128         return s
129     
130     def SortItems(self,sorter=cmp):
131         items = list(self.itemDataMap.keys())
132         items.sort(sorter)
133         self.itemIndexMap = items
134         # redraw the list
135         self.Refresh()
136     
137     def OnItemSelected(self, event):
138         self.currentItem = event.m_itemIndex
139         event.Skip()
140
141     def onsearch(self, evt) :
142         self.dial = SearchDial(self, self, 0, True)
143         self.dial.CenterOnParent()
144         self.dial.ShowModal()
145         self.dial.Destroy()
146     
147     def OnRightClick(self, event):
148
149         # only do this part the first time so the events are only bound once
150         if not hasattr(self, "popupID1"):
151             self.popupID1 = wx.NewId()
152             self.popupID2 = wx.NewId()
153             self.popupID3 = wx.NewId()
154             self.popup_Tgen_glob = wx.NewId()
155
156             self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
157             self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
158             self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
159             self.Bind(wx.EVT_MENU, self.OnTgen_glob, id=self.popup_Tgen_glob)
160         # make a menu
161         menu = wx.Menu()
162         # add some items
163         menu.Append(self.popupID1, u"Formes associĆ©es")
164         menu.Append(self.popupID2, u"Concordancier")
165         menu.Append(self.popupID3, "Graphique")
166         #menu.Append(self.popup_Tgen_glob, "Tgen global")
167
168         self.PopupMenu(menu)
169         menu.Destroy()
170
171     def getselectedwords(self) :
172         words = [self.getColumnText(self.GetFirstSelected(), 0)]
173         last = self.GetFirstSelected()
174         while self.GetNextSelected(last) != -1:
175             last = self.GetNextSelected(last)
176             words.append(self.getColumnText(last, 1))
177         return words
178
179     def OnPopupOne(self, event):
180         activenotebook = self.parent.nb.GetSelection()
181         page = self.parent.nb.GetPage(activenotebook)
182         corpus = page.corpus
183         word = self.getselectedwords()[0]
184         lems = corpus.getlems()
185         rep = []
186         for forme in lems[word].formes :
187              rep.append([corpus.getforme(forme).forme, corpus.getforme(forme).freq])
188         win = message(self, -1, u"Formes associĆ©es", size=(300, 200), style=wx.DEFAULT_FRAME_STYLE)
189         win.html = '<html>\n' + '<br>'.join([' : '.join([str(val) for val in forme]) for forme in rep]) + '\n</html>'
190         win.HtmlPage.SetPage(win.html)
191         win.Show(True)
192
193     def OnPopupTwo(self, event):
194         activenotebook = self.parent.nb.GetSelection()
195         page = self.parent.nb.GetPage(activenotebook)
196         item=self.getColumnText(self.GetFirstSelected(), 0)
197         corpus = page.corpus
198         win = message(self, -1, u"Concordancier", size=(600, 200),style = wx.DEFAULT_FRAME_STYLE)
199         avap=60
200         listmot = corpus.getlems()[item].formes       
201         uce_ok = corpus.getlemuces(item)
202         txt = '<h1>Concordancier</h1>'
203         res = corpus.getconcorde(uce_ok)
204         for uce in res :
205             ucetxt = ' '+uce[1]+' '
206             txt += ' '.join(corpus.ucis[corpus.getucefromid(uce[0]).uci].etoiles) + '<br>'
207             for forme in listmot :
208                 forme = corpus.getforme(forme).forme
209                 ucetxt = ucetxt.replace(' '+forme+' ', '<font color=red> ' + forme + ' </font>')
210             txt += ucetxt + '<br><br>'        
211         win.HtmlPage.SetPage(txt)
212         win.Show(True)
213
214     def getinf(self, txt) :
215         if txt == float('Inf') :
216             return 'Inf'
217         elif txt == float('-Inf') :
218             return '-Inf'
219         else :
220             return `txt`
221
222     def OnPopupThree(self, event) :
223         datas = [self.GetItemData(self.GetFirstSelected())]
224         last = self.GetFirstSelected()
225         while self.GetNextSelected(last) != -1:
226             last = self.GetNextSelected(last)
227             data = self.GetItemData(last)
228             datas += [data]
229         colnames = self.first[1:]
230         table = [[self.getinf(val) for val in line[1:]] for line in datas]
231         rownames = [val[0] for val in datas]
232         tmpgraph = tempfile.mktemp(dir=self.parent.TEMPDIR)
233         txt = barplot(table, rownames, colnames, self.parent.RscriptsPath['Rgraph'], tmpgraph)
234         tmpscript = tempfile.mktemp(dir=self.parent.TEMPDIR)
235         with open(tmpscript,'w') as f :
236             f.write(txt)
237         exec_rcode(self.parent.RPath, tmpscript, wait = True)
238         win = MessageImage(self, u"Graphique", size=(700, 500))
239         win.addsaveimage(tmpgraph)
240         txt = "<img src='%s'>" % tmpgraph
241         win.HtmlPage.SetPage(txt)
242         win.Show(True)
243
244     def OnTgen_glob(self, evt) :
245         activenotebook = self.parent.nb.GetSelection()
246         page = self.parent.nb.GetPage(activenotebook)
247         corpus = page.corpus
248
249         tmpgraph = tempfile.mktemp(dir=self.gparent.parent.TEMPDIR)
250         intxt = """
251         load("%s")
252         """ % corpus.dictpathout['RData']
253         intxt += """
254         Tgen.glob = NULL
255         tovire <- NULL
256         for (i in 1:ncol(dmf)) {
257             Tgen.glob <- rbind(Tgen.glob,colSums(dmf[which(specf[,i] > 3),]))
258             tovire <- append(tovire, which(specf[,i] > 3))
259         }
260         rownames(Tgen.glob) <- colnames(dmf)
261         Tgen.table <- dmf[-unique(tovire),]
262         Tgen.table<- rbind(Tgen.table, Tgen.glob)
263         spec.Tgen.glob <- AsLexico2(Tgen.table)
264         spec.Tgen.glob <- spec.Tgen.glob[[1]][((nrow(Tgen.table)-ncol(Tgen.table))+1):nrow(Tgen.table),]
265         di <- spec.Tgen.glob
266         """
267         txt = barplot('', '', '', self.gparent.parent.RscriptsPath['Rgraph'], tmpgraph, intxt = intxt) 
268         tmpscript = tempfile.mktemp(dir=self.gparent.parent.TEMPDIR)
269         with open(tmpscript, 'w') as f :
270             f.write(txt)
271         exec_rcode(self.gparent.parent.RPath, tmpscript, wait = True)
272         win = MessageImage(self, -1, u"Graphique", size=(700, 500),style = wx.DEFAULT_FRAME_STYLE)
273         win.addsaveimage(tmpgraph)
274         txt = "<img src='%s'>" % tmpgraph
275         win.HtmlPage.SetPage(txt)
276         win.Show(True)
277
278
279
280 class message(wx.Frame):
281     def __init__(self, *args, **kwds):
282         # begin wxGlade: MyFrame.__init__
283         kwds["style"] = wx.DEFAULT_FRAME_STYLE
284         wx.Frame.__init__(self, *args, **kwds)
285         #self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
286         self.HtmlPage=wx.html.HtmlWindow(self, -1)
287         if "gtk2" in wx.PlatformInfo:
288             self.HtmlPage.SetStandardFonts()
289         self.HtmlPage.SetFonts('Courier','Courier')
290         
291         
292         self.button_1 = wx.Button(self, -1, "Fermer")
293         self.Bind(wx.EVT_BUTTON, self.OnCloseMe, self.button_1)
294         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
295         self.__do_layout()
296         # end wxGlade
297
298     def __do_layout(self):
299         # begin wxGlade: MyFrame.__do_layout
300         sizer_1 = wx.BoxSizer(wx.VERTICAL)
301         sizer_2 = wx.BoxSizer(wx.VERTICAL)
302         sizer_2.Add(self.HtmlPage, 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
303         sizer_2.Add(self.button_1, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ADJUST_MINSIZE, 0)
304         sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
305         self.SetAutoLayout(True)
306         self.SetSizer(sizer_1)
307         self.Layout()
308         # end wxGlade
309         
310     def OnCloseMe(self, event):
311         self.Close(True)
312
313     def OnCloseWindow(self, event):
314         self.Destroy()