"""
     python/ui/rebuild.py: CCP4MG Molecular Graphics Program
     Copyright (C) 2001-2008 University of York, CCLRC
     Copyright (C) 2009-2010 University of York

     This library is free software: you can redistribute it and/or
     modify it under the terms of the GNU Lesser General Public License
     version 3, modified in accordance with the provisions of the 
     license to address the requirements of UK law.
 
     You should have received a copy of the modified GNU Lesser General 
     Public License along with this library.  If not, copies may be 
     downloaded from http://www.ccp4.ac.uk/ccp4license.php
 
     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU Lesser General Public License for more details.
"""
from global_definitions import *
import UtilityThread
import sys
from PyQt4 import QtCore, QtGui
import time


threads = []
useThreadedDraw=False

class ThreadedDraw:
	def stopRebuild(self):
		import mginterrupt
		mginterrupt.mginterrupt.SetStatus(1)

	def addStopSign(self):
		if not self.mt.isRunning(): return
		import MGApplication,os
		win = MGApplication.GetMainWindow()
		statusBarMessages.append(self.mt.tr("Recalculating display object "+self.target.name))
		try:
			win.statusBar().showMessage(statusBarMessages[len(statusBarMessages)-1])
		except:
			win.statusBar().showMessage("")
		stopSign = QtGui.QIcon(os.path.join(os.environ['CCP4MG'],'qticons','stop_sign_128x128.png'))
		self.mtStopAction = win.toolbar.addAction(stopSign,self.mt.tr("Stop calculation on "+self.target.name))
		self.mt.connect(self.mtStopAction,QtCore.SIGNAL("triggered(bool)"),self.stopRebuild)

	def __init__(self,target,controllingWidget):
		self.mt = UtilityThread.UtilityThread(target.draw)
		self.mt.connect(self.mt,QtCore.SIGNAL('finished()'),self.updateAfterThread)
		self.target = target
		self.controllingWidget = controllingWidget
		self.controllingWidget.setEnabled(False)
		app = QtGui.QApplication.instance()
		import MGApplication
		win = MGApplication.GetMainWindow()
		QtCore.QTimer.singleShot(500,self.addStopSign);
		app.flush()
		self.mt.start()

	def updateAfterThread(self):
		win = MAINWINDOW()
		self.controllingWidget.setEnabled(True)
      		self.target.rebuildGLDisplayObject(win)
		win.statusBar().showMessage(self.mt.tr(""))
		import mginterrupt
		mginterrupt.mginterrupt.SetStatus(0)
		if hasattr(self,'mtStopAction'): win.toolbar.removeAction(self.mtStopAction)
		try:
			statusBarMessages.pop()
			win.statusBar().showMessage(statusBarMessages[len(statusBarMessages)-1])
		except:
			win.statusBar().showMessage("")
		if threads.count(self): threads.pop(threads.index(self))
		win.updateGLWindows()

#----------------------------------------------------------------------
def UpdateDisplay(auto_save=1,target=None,controllingWidget=None):
#----------------------------------------------------------------------
  import Application
  import dataobj,services


  # This function called once every event loop after the input
  # command has been executed
  
  # Draw any application display objects
  for app in Application.Application.application_insts:
    app.draw()
    for dispobj in app.objinsts:
      if dispobj.visible:
        rebuild = dispobj.draw()
	if rebuild>0:
	  win.rebuildGLDisplayObject(dispobj.graphmod)

  win = MAINWINDOW()

  # Invoke the draw method for each display object - this
  # will redraw the object if necessary
  for datobj in dataobj.DataObj.dataobj_insts:
    for dispobj in datobj.objinsts:
      if dispobj.set_graphmod_visibility():
        dispobj.unthreadedDraw()
	if useThreadedDraw and target and target is dispobj and controllingWidget:
		threads.append(ThreadedDraw(target,controllingWidget))
	else:
        	dispobj.draw()
		#dispobj.resetUpdatedOpacity()
   	        #print 'UpdateDisplay after draw',dispobj.name,rebuild
			#start_time = time.clock()
	        dispobj.rebuildGLDisplayObject(win)
			#print 'rebuildGLDisplayObject',dispobj.name,time.clock()-start_time

  # Invoke the draw method for all 'service' display objects
  for tempobj in services.TempObjs.objinsts:
     tempobj.draw()

  
  # Get Qt main window to call updateGL on glWidgets and whatever else that is necessary.
  if auto_save:
    HISTORY().autoSave()
    win.setDisplayActionsEnabled()
  
  win.updateGLWindows()

  
#----------------------------------------------------------------------
def Rebuild():	
#----------------------------------------------------------------------
    # Get the display list redrawn
    # e.g. This function is used to redraw with changed render quality
    # ???? Any other display objects from Applications ???
    import dataobj
    win = MAINWINDOW()
    for datobj in dataobj.DataObj.dataobj_insts:
      for dispobj in datobj.objinsts:
        if dispobj.set_graphmod_visibility():
	  win.rebuildGLDisplayObject(dispobj.graphmod)
    win.updateGLWindows()
