scrolling !
[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, message
25 from operator import itemgetter
26 #---------------------------------------------------------------------------
27
28 class ListForSpec(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin):
29     def __init__(self, parent,gparent, dlist, first, menu = True):
30         wx.ListCtrl.__init__( self, parent, -1, style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES)
31         self.parent=parent
32         self.gparent=gparent
33         self.dlist=dlist
34         self.first = first
35         self.menu = menu
36
37         search_id = wx.NewId()
38         self.parent.Bind(wx.EVT_MENU, self.onsearch, id = search_id)
39         self.accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('F'), search_id)])
40         self.SetAcceleratorTable(self.accel_tbl)
41
42         self.il = wx.ImageList(16, 16)
43         a={"sm_up":"GO_UP","sm_dn":"GO_DOWN","w_idx":"WARNING","e_idx":"ERROR","i_idx":"QUESTION"}
44         for k,v in a.items():
45             s="self.%s= self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_%s,wx.ART_TOOLBAR,(16,16)))" % (k,v)
46             exec(s)
47         self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
48
49         tID = wx.NewId()
50
51         self.attr1 = wx.ListItemAttr()
52         self.attr1.SetBackgroundColour((230, 230, 230))
53         self.attr2 = wx.ListItemAttr()
54         self.attr2.SetBackgroundColour("light blue")
55         
56         self.dlist = dlist 
57
58         i=0
59         for name in first :
60             self.InsertColumn(i,name,wx.LIST_FORMAT_LEFT)
61             i+=1
62             
63         self.SetColumnWidth(0, 180)
64
65         for i in range(1,len(first)-1):
66             self.SetColumnWidth(i, self.checkcolumnwidth(len(first[i]) * 10))
67         
68         self.itemDataMap = dlist
69         self.itemIndexMap = dlist.keys()
70         self.SetItemCount(len(dlist))
71         
72         #listmix.ListCtrlAutoWidthMixin.__init__(self)
73         listmix.ColumnSorterMixin.__init__(self, len(first))
74         self.SortListItems(1, 0)
75         
76 #-----------------------------------------------------------------------------------------    
77         self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self)
78         
79         # for wxMSW
80         self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick)
81
82         # for wxGTK
83         self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
84
85 #-----------------------------------------------------------------------------------------    
86         
87     def checkcolumnwidth(self, width) :
88         if width < 80 :
89             return 80
90         else :
91             return width
92
93     def OnGetItemText(self, item, col):
94         index=self.itemIndexMap[item]
95         s = self.itemDataMap[index][col]
96         return s
97
98     def OnGetItemAttr(self, item):
99         if item % 2 :
100             return self.attr1
101         else :
102             return self.attr2
103
104
105     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
106     def GetListCtrl(self):
107         return self
108
109     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
110     def GetSortImages(self):
111         return (self.sm_dn, self.sm_up)
112     
113     def OnRightDown(self, event):
114         x = event.GetX()
115         y = event.GetY()
116         item, flags = self.HitTest((x, y))
117
118         if flags & wx.LIST_HITTEST_ONITEM:
119             self.Select(item)
120
121         event.Skip()
122
123     def getColumnText(self, index, col):
124         item = self.GetItem(index, col)
125         return item.GetText()
126
127     def GetItemData(self, item) :
128         index=self.itemIndexMap[item]
129         s = self.itemDataMap[index]
130         return s
131     
132     def SortItems(self,sorter=cmp):
133         items = list(self.itemDataMap.keys())
134         items.sort(sorter)
135         self.itemIndexMap = items
136         # redraw the list
137         self.Refresh()
138     
139     def OnItemSelected(self, event):
140         self.currentItem = event.m_itemIndex
141         event.Skip()
142
143     def onsearch(self, evt) :
144         self.dial = SearchDial(self, self, 0, True)
145         self.dial.CenterOnParent()
146         self.dial.ShowModal()
147         self.dial.Destroy()
148     
149     def OnRightClick(self, event):
150         if self.menu :
151             # only do this part the first time so the events are only bound once
152             if not hasattr(self, "popupID1"):
153                 self.popupID1 = wx.NewId()
154                 self.popupID2 = wx.NewId()
155                 self.popupID3 = wx.NewId()
156                 self.popup_Tgen_glob = wx.NewId()
157
158                 self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
159                 self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
160                 self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
161                 self.Bind(wx.EVT_MENU, self.OnTgen_glob, id=self.popup_Tgen_glob)
162             # make a menu
163             menu = wx.Menu()
164             # add some items
165             menu.Append(self.popupID1, u"Formes associĆ©es")
166             menu.Append(self.popupID2, u"Concordancier")
167             menu.Append(self.popupID3, "Graphique")
168             #menu.Append(self.popup_Tgen_glob, "Tgen global")
169
170             self.PopupMenu(menu)
171             menu.Destroy()
172
173     def getselectedwords(self) :
174         words = [self.getColumnText(self.GetFirstSelected(), 0)]
175         last = self.GetFirstSelected()
176         while self.GetNextSelected(last) != -1:
177             last = self.GetNextSelected(last)
178             words.append(self.getColumnText(last, 1))
179         return words
180
181     def OnPopupOne(self, event):
182         activenotebook = self.parent.nb.GetSelection()
183         page = self.parent.nb.GetPage(activenotebook)
184         corpus = page.corpus
185         word = self.getselectedwords()[0]
186         lems = corpus.getlems()
187         rep = []
188         for forme in lems[word].formes :
189              rep.append([corpus.getforme(forme).forme, corpus.getforme(forme).freq])
190         rep.sort(key = itemgetter(1), reverse = True)
191         win = message(self, u"Formes associĆ©es", (300, 200))
192         win.html = '<html>\n' + '<br>'.join([' : '.join([str(val) for val in forme]) for forme in rep]) + '\n</html>'
193         win.HtmlPage.SetPage(win.html)
194         win.Show(True)
195
196     def OnPopupTwo(self, event):
197         activenotebook = self.parent.nb.GetSelection()
198         page = self.parent.nb.GetPage(activenotebook)
199         item=self.getColumnText(self.GetFirstSelected(), 0)
200         corpus = page.corpus
201         win = message(self, u"Concordancier", (750, 600))
202         avap=60
203         listmot = corpus.getlems()[item].formes       
204         uce_ok = corpus.getlemuces(item)
205         txt = '<h1>Concordancier</h1>'
206         res = corpus.getconcorde(uce_ok)
207         for uce in res :
208             ucetxt = ' '+uce[1]+' '
209             txt += ' '.join(corpus.ucis[corpus.getucefromid(uce[0]).uci].etoiles) + '<br>'
210             for forme in listmot :
211                 forme = corpus.getforme(forme).forme
212                 ucetxt = ucetxt.replace(' '+forme+' ', '<font color=red> ' + forme + ' </font>')
213             txt += ucetxt + '<br><br>'        
214         win.HtmlPage.SetPage(txt)
215         win.Show(True)
216
217     def getinf(self, txt) :
218         if txt == float('Inf') :
219             return 'Inf'
220         elif txt == float('-Inf') :
221             return '-Inf'
222         else :
223             return `txt`
224
225     def OnPopupThree(self, event) :
226         datas = [self.GetItemData(self.GetFirstSelected())]
227         last = self.GetFirstSelected()
228         while self.GetNextSelected(last) != -1:
229             last = self.GetNextSelected(last)
230             data = self.GetItemData(last)
231             datas += [data]
232         colnames = self.first[1:]
233         table = [[self.getinf(val) for val in line[1:]] for line in datas]
234         rownames = [val[0] for val in datas]
235         tmpgraph = tempfile.mktemp(dir=self.parent.TEMPDIR)
236         txt = barplot(table, rownames, colnames, self.parent.RscriptsPath['Rgraph'], tmpgraph)
237         tmpscript = tempfile.mktemp(dir=self.parent.TEMPDIR)
238         with open(tmpscript,'w') as f :
239             f.write(txt)
240         exec_rcode(self.parent.RPath, tmpscript, wait = True)
241         win = MessageImage(self, u"Graphique", size=(700, 500))
242         win.addsaveimage(tmpgraph)
243         txt = "<img src='%s'>" % tmpgraph
244         win.HtmlPage.SetPage(txt)
245         win.Show(True)
246
247     def OnTgen_glob(self, evt) :
248         activenotebook = self.parent.nb.GetSelection()
249         page = self.parent.nb.GetPage(activenotebook)
250         corpus = page.corpus
251
252         tmpgraph = tempfile.mktemp(dir=self.gparent.parent.TEMPDIR)
253         intxt = """
254         load("%s")
255         """ % corpus.dictpathout['RData']
256         intxt += """
257         Tgen.glob = NULL
258         tovire <- NULL
259         for (i in 1:ncol(dmf)) {
260             Tgen.glob <- rbind(Tgen.glob,colSums(dmf[which(specf[,i] > 3),]))
261             tovire <- append(tovire, which(specf[,i] > 3))
262         }
263         rownames(Tgen.glob) <- colnames(dmf)
264         Tgen.table <- dmf[-unique(tovire),]
265         Tgen.table<- rbind(Tgen.table, Tgen.glob)
266         spec.Tgen.glob <- AsLexico2(Tgen.table)
267         spec.Tgen.glob <- spec.Tgen.glob[[1]][((nrow(Tgen.table)-ncol(Tgen.table))+1):nrow(Tgen.table),]
268         di <- spec.Tgen.glob
269         """
270         txt = barplot('', '', '', self.gparent.parent.RscriptsPath['Rgraph'], tmpgraph, intxt = intxt) 
271         tmpscript = tempfile.mktemp(dir=self.gparent.parent.TEMPDIR)
272         with open(tmpscript, 'w') as f :
273             f.write(txt)
274         exec_rcode(self.gparent.parent.RPath, tmpscript, wait = True)
275         win = MessageImage(self, -1, u"Graphique", size=(700, 500),style = wx.DEFAULT_FRAME_STYLE)
276         win.addsaveimage(tmpgraph)
277         txt = "<img src='%s'>" % tmpgraph
278         win.HtmlPage.SetPage(txt)
279         win.Show(True)