search
[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         self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self)
63         
64         # for wxMSW
65         self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick)
66
67         # for wxGTK
68         self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
69         
70         
71         self.itemDataMap = dlist
72         self.itemIndexMap = dlist.keys()
73         self.SetItemCount(len(dlist))
74         
75         listmix.ListCtrlAutoWidthMixin.__init__(self)
76         listmix.ColumnSorterMixin.__init__(self, len(first))
77         self.SortListItems(1, False)
78         
79 #-----------------------------------------------------------------------------------------    
80
81         i=0
82         for name in first :
83             self.InsertColumn(i,name,wx.LIST_FORMAT_LEFT)
84             i+=1
85             
86         self.SetColumnWidth(0, 180)
87
88         for i in range(1,len(first)-1):
89             self.SetColumnWidth(i, len(first[i]) * 10)
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
112     def OnRightDown(self, event):
113         x = event.GetX()
114         y = event.GetY()
115         item, flags = self.HitTest((x, y))
116
117         if flags & wx.LIST_HITTEST_ONITEM:
118             self.Select(item)
119
120         event.Skip()
121
122     def getColumnText(self, index, col):
123         item = self.GetItem(index, col)
124         return item.GetText()
125
126     def GetItemData(self, item) :
127         index=self.itemIndexMap[item]
128         s = self.itemDataMap[index]
129         return s
130
131     def OnItemSelected(self, event):
132         self.currentItem = event.m_itemIndex
133         event.Skip()
134
135     def onsearch(self, evt) :
136         self.dial = SearchDial(self, self, 0, True)
137         self.dial.CenterOnParent()
138         self.dial.ShowModal()
139         self.dial.Destroy()
140     
141     def OnRightClick(self, event):
142
143         # only do this part the first time so the events are only bound once
144         if not hasattr(self, "popupID1"):
145             self.popupID1 = wx.NewId()
146             self.popupID2 = wx.NewId()
147             self.popupID3 = wx.NewId()
148             self.popup_Tgen_glob = wx.NewId()
149
150             self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
151             self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
152             self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
153             self.Bind(wx.EVT_MENU, self.OnTgen_glob, id=self.popup_Tgen_glob)
154         # make a menu
155         menu = wx.Menu()
156         # add some items
157         menu.Append(self.popupID1, u"Formes associĆ©es")
158         menu.Append(self.popupID2, u"Concordancier")
159         menu.Append(self.popupID3, "Graphique")
160         #menu.Append(self.popup_Tgen_glob, "Tgen global")
161
162         self.PopupMenu(menu)
163         menu.Destroy()
164
165
166     def OnPopupOne(self, event):
167         activenotebook = self.parent.nb.GetSelection()
168         page = self.parent.nb.GetPage(activenotebook)
169         corpus = page.corpus
170         word = self.getColumnText(self.GetFirstSelected(), 0)
171         lems = corpus.getlems()
172         rep = []
173         for forme in lems[word].formes :
174              rep.append([corpus.getforme(forme).forme, corpus.getforme(forme).freq])
175         win = message(self, -1, u"Formes associĆ©es", size=(300, 200), style=wx.DEFAULT_FRAME_STYLE)
176         win.html = '<html>\n' + '<br>'.join([' : '.join([str(val) for val in forme]) for forme in rep]) + '\n</html>'
177         win.HtmlPage.SetPage(win.html)
178         win.Show(True)
179
180     def OnPopupTwo(self, event):
181         activenotebook = self.parent.nb.GetSelection()
182         page = self.parent.nb.GetPage(activenotebook)
183         item=self.getColumnText(self.GetFirstSelected(), 0)
184         corpus = page.corpus
185         win = message(self, -1, u"Concordancier", size=(600, 200),style = wx.DEFAULT_FRAME_STYLE)
186         avap=60
187         listmot = corpus.getlems()[item].formes       
188         uce_ok = corpus.getlemuces(item)
189         txt = '<h1>Concordancier</h1>'
190         res = corpus.getconcorde(uce_ok)
191         for uce in res :
192             ucetxt = ' '+uce[1]+' '
193             txt += ' '.join(corpus.ucis[corpus.getucefromid(uce[0]).uci].etoiles) + '<br>'
194             for forme in listmot :
195                 forme = corpus.getforme(forme).forme
196                 ucetxt = ucetxt.replace(' '+forme+' ', '<font color=red> ' + forme + ' </font>')
197             txt += ucetxt + '<br><br>'        
198         win.HtmlPage.SetPage(txt)
199         win.Show(True)
200
201     def OnPopupThree(self, event) :
202         print self.GetFirstSelected()
203         datas = [self.GetItemData(self.GetFirstSelected())]
204         print datas
205         last = self.GetFirstSelected()
206         while self.GetNextSelected(last) != -1:
207             last = self.GetNextSelected(last)
208             data = self.GetItemData(last)
209             datas += [data]
210         colnames = self.first[1:]
211         table = [[str(val) for val in line[1:]] for line in datas]
212         rownames = [val[0] for val in datas]
213         tmpgraph = tempfile.mktemp(dir=self.parent.TEMPDIR)
214
215         txt = barplot(table, rownames, colnames, self.parent.RscriptsPath['Rgraph'], tmpgraph)
216
217         tmpscript = tempfile.mktemp(dir=self.parent.TEMPDIR)
218         file = open(tmpscript,'w')
219         file.write(txt)
220         file.close()
221         exec_rcode(self.parent.RPath, tmpscript, wait = True)
222         win = MessageImage(self, -1, u"Graphique", size=(700, 500),style = wx.DEFAULT_FRAME_STYLE)
223         win.addsaveimage(tmpgraph)
224         txt = "<img src='%s'>" % tmpgraph
225         win.HtmlPage.SetPage(txt)
226         win.Show(True)
227
228     def OnTgen_glob(self, evt) :
229         activenotebook = self.parent.nb.GetSelection()
230         page = self.parent.nb.GetPage(activenotebook)
231         corpus = page.corpus
232
233         tmpgraph = tempfile.mktemp(dir=self.gparent.parent.TEMPDIR)
234         intxt = """
235         load("%s")
236         """ % corpus.dictpathout['RData']
237         intxt += """
238         Tgen.glob = NULL
239         tovire <- NULL
240         for (i in 1:ncol(dmf)) {
241             Tgen.glob <- rbind(Tgen.glob,colSums(dmf[which(specf[,i] > 3),]))
242             tovire <- append(tovire, which(specf[,i] > 3))
243         }
244         rownames(Tgen.glob) <- colnames(dmf)
245         Tgen.table <- dmf[-unique(tovire),]
246         Tgen.table<- rbind(Tgen.table, Tgen.glob)
247         spec.Tgen.glob <- AsLexico2(Tgen.table)
248         spec.Tgen.glob <- spec.Tgen.glob[[1]][((nrow(Tgen.table)-ncol(Tgen.table))+1):nrow(Tgen.table),]
249         di <- spec.Tgen.glob
250         """
251         txt = barplot('', '', '', self.gparent.parent.RscriptsPath['Rgraph'], tmpgraph, intxt = intxt) 
252         tmpscript = tempfile.mktemp(dir=self.gparent.parent.TEMPDIR)
253         with open(tmpscript, 'w') as f :
254             f.write(txt)
255         exec_rcode(self.gparent.parent.RPath, tmpscript, wait = True)
256         win = MessageImage(self, -1, u"Graphique", size=(700, 500),style = wx.DEFAULT_FRAME_STYLE)
257         win.addsaveimage(tmpgraph)
258         txt = "<img src='%s'>" % tmpgraph
259         win.HtmlPage.SetPage(txt)
260         win.Show(True)
261
262     def SortItems(self,sorter=cmp):
263         items = list(self.itemDataMap.keys())
264         items.sort(sorter)
265         self.itemIndexMap = items
266         # redraw the list
267         self.Refresh()
268
269 class message(wx.Frame):
270     def __init__(self, *args, **kwds):
271         # begin wxGlade: MyFrame.__init__
272         kwds["style"] = wx.DEFAULT_FRAME_STYLE
273         wx.Frame.__init__(self, *args, **kwds)
274         #self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
275         self.HtmlPage=wx.html.HtmlWindow(self, -1)
276         if "gtk2" in wx.PlatformInfo:
277             self.HtmlPage.SetStandardFonts()
278         self.HtmlPage.SetFonts('Courier','Courier')
279         
280         
281         self.button_1 = wx.Button(self, -1, "Fermer")
282         self.Bind(wx.EVT_BUTTON, self.OnCloseMe, self.button_1)
283         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
284         self.__do_layout()
285         # end wxGlade
286
287     def __do_layout(self):
288         # begin wxGlade: MyFrame.__do_layout
289         sizer_1 = wx.BoxSizer(wx.VERTICAL)
290         sizer_2 = wx.BoxSizer(wx.VERTICAL)
291         sizer_2.Add(self.HtmlPage, 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
292         sizer_2.Add(self.button_1, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ADJUST_MINSIZE, 0)
293         sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
294         self.SetAutoLayout(True)
295         self.SetSizer(sizer_1)
296         self.Layout()
297         # end wxGlade
298         
299     def OnCloseMe(self, event):
300         self.Close(True)
301
302     def OnCloseWindow(self, event):
303         self.Destroy()