# This script shows the f-table generated by Csound
# for the selected text in a csd file

import PythonQt.QtGui as pqt
import PythonQt.QtCore as pqtc
import csnd

ftable_text = q.getSelectedText().strip()

if not ftable_text.startswith('f'):
    pqt.QMessageBox.critical(0,"ftable viewer script",
         'Please select ftable text')
    raise Exception('Please select ftable text')

parts = ftable_text.split(' ')
if parts[0] == 'f':
    tabnum = abs(int(parts[1]))
else:
    tabnum = abs(int(parts[0][1:]))
# create empty orchestra and score
orc = ''' sr = 44100
ksmps = 64
nchnls = 2

instr 1
endin
'''

sco = '''
%s
e 3600
'''%ftable_text

tabnum = 1
# start csound engine
c = csnd.CppSound()
c.setOrchestra(orc)
c.setScore(sco.encode())
c.setCommand("csound -odac -d tmp.orc tmp.sco")
c.exportForPerformance()
c.compile()
c.PerformKsmps() # Must perform one control block to have tables created
# There must be a better way to do this!
len = c.TableLength(tabnum)
tab = []
for i in range(len):
    tab.append(-c.TableGet(tabnum, i))
c.Stop()
c.Cleanup()

w = pqt.QWidget() # Create main widget
w.setGeometry(50,50, 400,200)
l = pqt.QGridLayout(w) # Layout to organize widgets
w.setLayout(l)
w.setWindowTitle("f-table")
w.setWindowFlags(w.windowFlags() |  pqtc.Qt.WindowStaysOnTopHint);

scene = pqt.QGraphicsScene(w)

view = pqt.QGraphicsView(scene, w)
l.addWidget(view)
view.show()
w.show()

path = pqt.QPainterPath()
# must switch y axis!
[path.lineTo(x,-y) for (x,y) in enumerate(tab)]
pathItem = scene.addPath(path)
view.fitInView(pathItem)
#def update():
    

