Example #1
0
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        callbacks.setExtensionName("Hello Burp")

        self.panel = JPanel()
        self.label = JLabel("Hello Burp")
        self.buttonOutput = Button("Print to Output",
                                   actionPerformed=self.printToOutput)
        self.buttonErrors = Button("Print to Errors",
                                   actionPerformed=self.printToErrors)
        self.buttonAlerts = Button("Print to Alerts",
                                   actionPerformed=self.printToAlerts)
        self.panel.add(self.label)
        self.panel.add(self.buttonOutput)
        self.panel.add(self.buttonErrors)
        self.panel.add(self.buttonAlerts)

        callbacks.customizeUiComponent(self.panel)
        callbacks.addSuiteTab(self)

        self.stdout = PrintWriter(callbacks.getStdout(), True)
        self.stderr = PrintWriter(callbacks.getStderr(), True)
        burpInfo = callbacks.getBurpVersion()
        self.stdout.println("Hello " + burpInfo[0] + " v" + burpInfo[1] + "." +
                            burpInfo[2] + "!")
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        self.stdout = PrintWriter(callbacks.getStdout(), True)
        self.stderr = PrintWriter(callbacks.getStderr(), True)

        callbacks.setExtensionName('Save URL List')
        self.panel = JPanel()
        self.myLabel = JLabel('Save URL List as a Text File', JLabel.CENTER)
        self.buttonFile = Button('Select File',
                                 actionPerformed=self.selectFile)
        self.buttonSaveProxy = Button('Save All Proxy History',
                                      actionPerformed=self.saveProxy)
        self.buttonSaveSiteTree = Button('Save All Target SiteTree ',
                                         actionPerformed=self.saveSiteTree)
        self.buttonSaveProxyScope = Button('Save In-Scope Proxy History',
                                           actionPerformed=self.saveProxyScope)
        self.buttonSaveSiteTreeScope = Button(
            'Save In-Scope Target SiteTree',
            actionPerformed=self.saveSiteTreeScope)
        self.panel.add(self.myLabel)
        self.panel.add(self.buttonFile)
        self.panel.add(self.buttonSaveProxy)
        self.panel.add(self.buttonSaveSiteTree)
        self.panel.add(self.buttonSaveProxyScope)
        self.panel.add(self.buttonSaveSiteTreeScope)
        callbacks.customizeUiComponent(self.panel)
        callbacks.addSuiteTab(self)
 def getUiComponent(self):
     panel = Panel()
     panel.setBackground(Color.gray)
     button = Button('Hello Burp Button!')
     panel.add(button)
     self.callbacks.customizeUiComponent(
         panel)  # customize UI components in line with Burp's UI style
     return panel
Example #4
0
	def createAndShowGUI(self):
		'''
		Create and display the gui.
		'''
		self.setLayout(FlowLayout())

		serverLabel = Label("BIAFlows host: ");
		serverField =TextField(30)
		serverField.setName('host')
		serverField.setText(self.biaflows.getHost())
		serverField.addTextListener(self)
		publicKeyLabel = Label("public key: ")
		publicKeyField=TextField(40)
		publicKeyField.setName('publicKey')
		publicKeyField.setText(self.biaflows.getPublicKey())
		publicKeyField.addTextListener(self)
		privateKeyLabel = Label("private key: ")
		privateKeyField=TextField(40)
		privateKeyField.setName('privateKey')
		privateKeyField.setEchoChar('*')
		privateKeyField.setText(self.biaflows.getPrivateKey())
		privateKeyField.addTextListener(self)

		closeButton = Button("Disconnect and close")
		closeButton.addActionListener(self)

		self.add(serverLabel)
		self.add(serverField)
		self.add(publicKeyLabel)
		self.add(publicKeyField)
		self.add(privateKeyLabel)
		self.add(privateKeyField)
		self.add(closeButton)
				
		self.setSize(400,250)
		self.setVisible(True)
Example #5
0
print 'Bad input to __import__ raises a Java exception #27'

try:
    __import__("")
    raise TestFailed
except ValueError:
    pass

print 'xrange implementation is broken for almost any complex case #29'

assert list(xrange(10)[9:1:-1]) == [9, 8, 7, 6, 5, 4, 3, 2]

print 'Trying to assign to a method of a Java instance throws a NullPointerException #30'

from java.awt import Button
b = Button()
try:
    b.setLabel = 4
    raise TestFailed
except TypeError:
    pass

print 'From 1.0.1 to 1.0.2'
print 'A threading test'

from java.lang import Thread


class TestThread(Thread):
    def run(self):
        for i in range(100):
#


class TestButtonAction(ActionListener):
    def actionPerformed(self, e):
        textArea.append("Test Button Clicked!\n")


#
# Create the Frame, Panel, Button,
# TextArea, and TestButtonAction objects.
#

frame = Frame("Hello World")
panel = Panel()
button = Button("Test Button")
buttonAction = TestButtonAction()
textArea = TextArea()

#
# Put everything together and show
# the window.
#

button.addActionListener(buttonAction)
panel.add(button)
panel.add(textArea)
frame.add(panel)
frame.pack()
frame.show()
print_test('Bad input to __import__ raises a Java exception #27')

try:
    __import__("")
    raise TestFailed
except ValueError:
    pass

print_test('xrange implementation is broken for almost any complex case #29')

assert list(xrange(10)[9:1:-1]) == [9, 8, 7, 6, 5, 4, 3, 2]

print_test('Trying to assign to a method of a Java instance throws a NullPointerException #30')

from java.awt import Button
b = Button()
try:
    b.setLabel = 4
    raise TestFailed
except TypeError:
    pass


print_test('From 1.0.1 to 1.0.2', 1)
print_test('A threading test', 2)

from java.lang import Thread

class TestThread(Thread):
    def run(self):
	for i in range(100):
Example #8
0
	def __settings(self, imgName) :
		"""
		Lets the user to choose different measures to make, and displays it following the choice of the user.
		
		"""

		try : dico=self.__dictCells[imgName]
		except KeyError : 
			try : dico=self.__dictCells[imgName[:-4]]
			except KeyError : return False
			else : imgName=imgName[:-4]
		
		dico=self.__dictCells[imgName]
		for cellname in dico.keys() :
			self.__dictMeasures[dico[cellname]]={}
			
		# Represents the datas on a diagram
		def diagrambuttonPressed(event) :
			IJ.showMessage("Push 'Auto' button each time you want to see the diagram")
			x1=10
			y1=20
			x2=100
			y2=50
			x3=60
			y3=30
			xr=10
			yr=20
			wr=20
			hr=20

			
			rect=Rectangle(xr,yr,wr,hr)
			
			#img=IJ.getImage()
			#nbslices=self.__img.getImageStackSize()
			nbslices=self.__maxLife
			IJ.run("Hyperstack...", "title=Diagram type=32-bit display=Color width="+str(x2+(nbslices+1)*x3)+" height="+str(y2+y3*len(dico))+" channels=1 slices="+str(len(self.__measures))+" frames=1")
			im=IJ.getImage()
			ip=im.getProcessor()
			for i in range(len(self.__measures)) :
				indiceligne=0
				maxvalue=0
				minvalue=1000000
				im.setPosition(1,i+1,1)
				for cellname in self.__listcellname :
					indiceligne+=1
					for indicecolonne in range(1,nbslices+1):
						rect.setLocation(x2+indicecolonne*x3+int(x3/6),(y1+indiceligne*y3-int(y3/2)))
						# we create at the first iteration a dictionary with the rectangles (for a future use)
						if i==0 :
							self.__gridrectangle[(indiceligne,indicecolonne)]=Rectangle(rect)
						im.setRoi(rect)
						ipr=im.getProcessor()
						# we find the min and max values of the datas for a measure given.
						if self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]>maxvalue :
							maxvalue=self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]
						if self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]<minvalue :
							minvalue=self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]
						# we fill the rectangle with the value of the measure
						ipr.setValue(self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1])
						ipr.fill()
				# we write the names and the n of slices on the image with the maxvalue.
				ip.setValue(maxvalue)
				ip.moveTo(x1,y1)
				ip.drawString(self.__measures[i])
				for j in range(1,nbslices+1) :
					ip.moveTo(x2+j*x3,y1)
					ip.drawString("Slice "+str(j))
				j=0
				for cellname in self.__listcellname :
					ip.moveTo(x1,y2+j*y3)
					ip.drawString(cellname)
					j+=1
			im.killRoi()
			im=IJ.run(im,"Fire","")
			IJ.run("Brightness/Contrast...", "")
			#im.setMinAndMax(minvalue,maxvalue)
			#im.updateImage()
			
			#we add a mouse listener in order to be able to show the roi corresponding to a rectangle when the user clicks on it.
			listener = ML()
			listener.name=imgName
			for imp in map(WindowManager.getImage, WindowManager.getIDList()):
				if imp.getTitle().startswith("Diagram") : 
					win = imp.getWindow()
 					if win is None:
						continue
					win.getCanvas().addMouseListener(listener)
		
		# Represents the datas on a series of graphs.
		def graphbuttonPressed(event) :
			
			colors=[]
			#img=IJ.getImage()
			#nbslices=self.__img.getImageStackSize()
			nbslices=self.__maxLife

			acell=dico.values()[0]
			if self.__useTime : 
				x = acell.getListTimes()
				namex="Time sec"
			else : 
				x = range(1,nbslices+1)
				namex = "Frame"
			maxx=max(x)
			minx=min(x)
			
			#x=[i for i in range(1,nbslices+1)]
			font=Font("new", Font.BOLD, 14)
			tempname = WindowManager.getUniqueName(self.__img.getShortTitle())
			for i in range(len(self.__measures)) :
				#print "i", i, self.__measures[i]
				yarray=[]
				flag=True
				miny=10000000000
				maxy=-1000000000
				#we find the min and max values in order to set the scale.
				for cellname in self.__listcellname :	
					colors.append(dico[cellname].getColor())
					yarray.append(self.__dictMeasures[dico[cellname]][self.__measures[i]])
					#for meas in self.__dictMeasures[dico[cellname]][self.__measures[i]] :
					for meas in yarray[-1] :
						if (meas<miny) and (Double.isNaN(meas)==False) :
							miny=meas
					if max(yarray[-1])>maxy : maxy=max(yarray[-1])
				
				miny-=0.1*miny
				maxy+=0.1*maxy
				count=0.05
				
				for j in range(len(yarray)) :
					if j==0 :
						if len(self.__measures)>1 :
							plot=Plot("Plots-"+str(self.__measures[i]),namex,str(self.__measures[i]),x,yarray[j])
							
						else : 
							plot=Plot("Plot-"+tempname,namex,str(self.__measures[i]),x,yarray[j])
							
						plot.setLimits(minx,maxx,miny,maxy)
						plot.setColor(colors[j])
						plot.changeFont(font)
						plot.addLabel(0.05, count, self.__listcellname[j])
					else :
						plot.setColor(colors[j])
						plot.setLineWidth(3)
						plot.addPoints(x,yarray[j],Plot.LINE)
						plot.addLabel(0.05, count, self.__listcellname[j])

					count+=0.05
						
				plot.setColor(colors[0])
				plot.show()
				
			if len(self.__measures)>1 :
				IJ.run("Images to Stack", "name="+tempname+"-plots title=Plots- use")

		#def histbuttonPressed(event) :
		#	
		#	pass

		# Represents the values in a tab.
		def tabbuttonPressed(event) :
		
			tab="\t"
			headings=[]
			measures=[]
			#img=IJ.getImage()
			#for i in range(self.__img.getImageStackSize()+1) :
			for i in range(self.__maxLife+1) :
				headings.append("Slice "+str(i))
			
			headings[0]=WindowManager.getUniqueName(self.__img.getShortTitle())
			#for m in self.__measurescompl :
			for m in self.__dictMeasures[dico[self.__listcellname[0]]].keys() :
				
				headstring=""
				for head in headings: 
					headstring+=head+tab
				tw=TextWindow(self.__listfiles[0]+"-"+m,headstring,"",800,600)
				tp=tw.getTextPanel()
				#for cellname in dico.keys() :
				for cellname in self.__listcellname :
					line=[]
					line=[str(meas)+tab for meas in self.__dictMeasures[dico[cellname]][m]]
					line.insert(0, cellname+tab)
					linestr=""
					for s in line: linestr+=s
					tp.appendLine(linestr)
				tp.updateDisplay()

			if self.__measuresparambool_global[0] :
				tw=TextWindow("Latency","cell\tLatency", "",800,600)
				tp=tw.getTextPanel()
				for i in range(len(self.__listcellname)) :
					#if latencies[i][0] : line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					#else : line=self.__listcellname[i]+"\t"+"NaN"
					line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					tp.appendLine(line)
				tp.updateDisplay() 
				
		def helpbuttonPressed(event) :

			IJ.showMessage("TO DO")

		def newsetPressed(event) :
			gd0.dispose()
			self.__settings()

		def alignbuttonPressed(event) :
			IJ.showMessage("TO DO")


		def mergebuttonPressed(event) :
			IJ.showMessage("TO DO")

		def saveResults() :
			
			#if len(self.__listcellname) == 0 :
			
			nbslices=self.__maxLife
			acell=dico.values()[0]
			if self.__useTime : 
				x = acell.getListTimes()
				namex="Time_sec"
			else : 
				x = range(1,nbslices+1)
				namex = "Frame"
							
			if not path.exists(self.__rootpath+"Results"+os.path.sep) : os.makedirs(self.__rootpath+os.path.sep+"Results"+os.path.sep, mode=0777)
			tab="\t"
			nl="\n"
			measures=[]
			headstring=""
			#if self.__savemode : mode = "a"
			#else : mode ="w"
			mode = "a"
			
			#for i in range(1, self.__maxLife+1) :headstring += "Slice_"+str(i)+tab
			for i in range(self.__maxLife) :headstring += str(x[i])+tab
			
			#for m in self.__measurescompl :
			for m in self.__dictMeasures[dico[self.__listcellname[0]]].keys() :
				f = open(self.__rootpath+"Results"+os.path.sep+m+".txt", mode)
				#f.write(m+nl)
				f.write(imgName+"-"+self.__time+"-"+m+"-"+namex+tab+headstring+nl)
				if len(self.__listcellname) == 0 : f.write("no cells")
				else : 
					for cellname in self.__listcellname :
						linestr=cellname+tab
						for measure in self.__dictMeasures[dico[cellname]][m] :
							#print m, cellname, measure 
							linestr += str(measure)+tab
						linestr+=nl
						f.write(linestr)
				f.close()

			if self.__measuresparambool_global[0] :
				m = "Latency"
				f = open(self.__rootpath+"Results"+os.path.sep+m+".txt", mode)
				f.write(imgName+"-"+self.__time+"-"+m+nl)
				for i in range(len(self.__listcellname)) :
					#if latencies[i][0] : line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					#else : line=self.__listcellname[i]+"\t"+"NaN"
					line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					line+=nl
					f.write(line)
				f.close()
				
			

			

		#
		# ----------- main measures dialog -------------------------
		#
     		# Allows the user to choose the measures to make, etc..
		
		measureslabels_indep=["MaxFeret","MinFeret","AngleFeret","XFeret","YFeret","Area","Angle","Major","Minor","Solidity","AR","Round","Circ","XC","YC","FerCoord","FerAxis","MidAxis"]
		measureslabels_dep=["Mean","StdDev","IntDen","Kurt","Skew","XM","YM","Fprofil","MidProfil","NFoci","ListFoci","ListAreaFoci","ListPeaksFoci","ListMeanFoci"]
		measureslabels_global=["Latency", "velocity", "cumulatedDist"]
		measureslabels_dep_tabonly=set(["MidAxis","FerCoord","FerAxis","Fprofil","MidProfil","ListFoci","ListAreaFoci","ListPeaksFoci","ListMeanFoci"])
		ens_measures_global=set(measureslabels_global)
		ens_measures_indep=set(measureslabels_indep)
		ens_measures_dep=set(measureslabels_dep)
		measureslabels=[]
		
		for label in measureslabels_indep :
			measureslabels.append(label)

		for label in measureslabels_dep :
			measureslabels.append(label)

		#self.__defaultmeasures=[False for i in range(len(measureslabels))]
		#self.__defaultmeasures_global=[False for i in range(len(measureslabels_global))]

		gdmeasures=NonBlockingGenericDialog("MeasuresChoice")
		gdmeasures.setFont(Font("Courrier", 1, 10))
		gdmeasures.addMessage("*******     TIME SETTINGS     *******")
		gdmeasures.addCheckbox("Only starting at begining  :", self.__onlystart)				# 1 only start
		gdmeasures.addNumericField("Minimal Lifetime  : ",self.__minLife,0)
		gdmeasures.addNumericField("Maximal Lifetime  : ",self.__maxLife,0)
		#gdmeasures.addNumericField("Maximal Lifetime  : ",self.__img.getImageStackSize(),0)
		gdmeasures.addCheckbox("x axis in seconds", self.__useTime)				# 2 use time
		gdmeasures.addMessage("")
		gdmeasures.addMessage("")
		gdmeasures.addMessage("Choose the measures to make on the cells : ")			
		gdmeasures.addMessage("*******     TIME MEASURES     *******")
		gdmeasures.addCheckboxGroup(4,8,measureslabels,self.__defaultmeasures)
		gdmeasures.addMessage("")
		gdmeasures.addMessage("*******     GLOBAL MEASURES     *******")
		gdmeasures.addMessage("PLEASE : If you have selected movement parameters you MUST to select XC and YC !")
		gdmeasures.addCheckboxGroup(3,1,measureslabels_global,self.__defaultmeasures_global)
		gdmeasures.addNumericField("Noise value for maxima finder: ",self.__noise,0)
		gdmeasures.addMessage("")	
		gdmeasures.addMessage("*******     OPTIONS     *******")
		gdmeasures.addCheckbox("Select the cells in next dialog ?", self.__onlyselect)			# 3 only select
		gdmeasures.addCheckbox("Save results to text files ?", self.__savetables)			# 4 save files
		#gdmeasures.addCheckbox("Append mode ?", self.__savemode)					# 5 append mode
		gdmeasures.addCheckbox("Analyse in batch mode ?", self.__batchanalyse)				# 6 analysis batch mode
		gdmeasures.addCheckbox("Update overlay ?", self.__updateoverlay)				# 7 update overlay
		gdmeasures.addMessage("")
		gdmeasures.addMessage("")
		help_panel=Panel()
		helpbutton=Button("HELP")
		helpbutton.actionPerformed = helpbuttonPressed
		help_panel.add(helpbutton)	
		gdmeasures.addPanel(help_panel)	
		gdmeasures.hideCancelButton()

		if not self.__batchanalyse :
			gdmeasures.showDialog()
			self.__onlystart=gdmeasures.getNextBoolean() 						# 1 only start
			self.__minLife=gdmeasures.getNextNumber()
			self.__maxLife=gdmeasures.getNextNumber()
			self.__useTime=gdmeasures.getNextBoolean()						# 2 use time

			self.__measuresparambool=[]
			self.__measuresparambool_global=[]
			for i in range(len(measureslabels)) : 
				self.__measuresparambool.append(gdmeasures.getNextBoolean())
				self.__defaultmeasures[i]=self.__measuresparambool[-1]
			for i in range(len(measureslabels_global)) : 
				self.__measuresparambool_global.append(gdmeasures.getNextBoolean())
				self.__defaultmeasures_global[i] = self.__measuresparambool_global[i]
 
			self.__noise=gdmeasures.getNextNumber()
			self.__onlyselect=gdmeasures.getNextBoolean()						# 3 only select
			self.__savetables = gdmeasures.getNextBoolean()						# 4 save files
			#self.__savemode = gdmeasures.getNextBoolean()						# 5 append mode
			self.__batchanalyse = gdmeasures.getNextBoolean()					# 6 analyse mode
			self.__updateoverlay = gdmeasures.getNextBoolean()					# 7 update overlay

		# we update a list of all cells that have a lifetime corresponding to what the user chose.
		if len (self.__allcells) == 0 :
			for cellname in dico.keys() :
				if dico[cellname].getLifeTime()>=self.__minLife : #and dico[cellname].getLifeTime()<=self.__maxLife :
					if self.__onlystart :
						if dico[cellname].getSlideInit()<2 : self.__allcells.append(cellname)
						else : self.__allcells.append(cellname)

		
		if self.__noise == 0 : self.__noise = None
		if self.__batchanalyse : self.__onlyselect = False
		
		if self.__onlyselect : 
			
			try : 
				self.__gw
			except AttributeError :
				if not path.exists(self.__pathdir+"Selected-Cells"+os.path.sep) : os.makedirs(self.__pathdir+os.path.sep+"Selected-Cells"+os.path.sep, mode=0777)				
				self.__gw = CellsSelection()
				self.__gw.setTitle(imgName)
				self.__gw.run(self.__allcells, self.__pathdir+"ROIs"+os.path.sep)
				self.__gw.show()
				self.__gw.setSelected(self.__allcells)
				while not self.__gw.oked and self.__gw.isShowing() : 
					self.__gw.setLabel("Validate selection with OK !!")
					self.__listcellname = list(self.__gw.getSelected())
				self.__gw.resetok()
				self.__gw.setLabel("...")
				self.__gw.hide()
			else : 
				if self.__gw.getTitle() == imgName :
					self.__gw.show()
					self.__gw.setSelected(self.__listcellname)
					self.__listcellname[:]=[]
					while not self.__gw.oked and self.__gw.isShowing() : 
						self.__gw.setLabel("Validate selection with OK !!")
						self.__listcellname = list(self.__gw.getSelected())
					
					self.__gw.resetok()
					self.__gw.setLabel("...")
					self.__gw.hide()

				else : 
					self.__gw.dispose()
					if not path.exists(self.__pathdir+"Selected-Cells"+os.path.sep) : os.makedirs(self.__pathdir+os.path.sep+"Selected-Cells"+os.path.sep, mode=0777)				
					self.__gw = CellsSelection()
					self.__gw.setTitle(imgName)
					self.__gw.run(self.__allcells, self.__pathdir+"ROIs"+os.path.sep)
					self.__gw.show()
					self.__gw.setSelected(self.__allcells)
					self.__listcellname[:]=[]
					while not self.__gw.oked and self.__gw.isShowing() : 
						self.__gw.setLabel("Validate selection with OK !!")
						self.__listcellname = list(self.__gw.getSelected())
					self.__gw.resetok()
					self.__gw.setLabel("...")
					self.__gw.hide()

			filestodelet=glob.glob(self.__pathdir+"Selected-Cells"+os.path.sep+"*.cell")
			for f in filestodelet : os.remove(f)
			for cell in self.__listcellname :
				sourcestr = self.__pathdir+"Cells"+os.path.sep+cell+".cell"
				deststr =  self.__pathdir+"Selected-Cells"+os.path.sep+cell+".cell"
				#os.system("copy "+sourcestr+", "+deststr) 
				#shutil.copy(self.__pathdir+"Cells"+os.path.sep+cell+".cell",self.__pathdir+"Selected-Cells"+os.path.sep+cell+".cell")
				shutil.copy(sourcestr,deststr)

			self.__dictNcells[imgName] = len(self.__listcellname)
		
		else : 
			self.__listcellname = list(self.__allcells)
			self.__dictNcells[imgName] = len(self.__listcellname)

		if len(self.__listcellname) == 0 : 
			self.__dictNcells[imgName] = 0
			return False
		
		self.__img.hide()
		
		# we make the measures.
		for i in range(len(measureslabels)) :
			IJ.showProgress(i, len(measureslabels))
			if  self.__measuresparambool[i]==True :
				
				self.__measurescompl.append(measureslabels[i])
				
				if (measureslabels[i] in measureslabels_dep_tabonly)==False :
					self.__measures.append(measureslabels[i])
				
				if (i<18) and (measureslabels[i] in ens_measures_indep) :
					self.__measureAll(self.__img,measureslabels[i],False, imgName, self.__noise)
					ens_measures_indep.discard(measureslabels[i])
					
				if i>=18 :
					self.__measureAll(self.__img,measureslabels[i],True, imgName, self.__noise)
					
		if self.__measuresparambool_global[0] : # calculate latency
			latencies=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				latencies.append(self.latencie(self.__listcellname[i], self.__img, imgName, self.__useTime))

		if self.__measuresparambool_global[1] : # calculate velocity
			self.__measures.append("velocity")
			#velocities=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				self.__measureVelocity(self.__img,imgName)

		if self.__measuresparambool_global[2] : # calculate cumulatedDistance
			self.__measures.append("cumulatedDist")
			#velocities=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				self.__measurecumulDist(self.__img,imgName)	
				
		
		self.__img.show()

		self.__img.getProcessor().resetThreshold()		

		
		if self.__updateoverlay :
			if self.__img.getOverlay() is not None : self.__img.getOverlay().clear()
		
			outputrois=[]
			cellnames=[]
			self.__img.hide()
			for cellname in self.__listcellname :
				
				for r in dico[cellname].getListRoi():
					if isinstance(r,Roi) : 
						pos=r.getPosition()
						#print "MC overlay", cellname, r.getName(), pos
						#r.setPosition(0)
						#overlay.add(r)
						outputrois.append(r)
						if "cell" in r.getName() : cellnames.append(r.getName())
						else : cellnames.append(str(pos)+"-"+cellname)
						#print cellnames[-1]

			rm = RoiManager.getInstance()
			if (rm==None): rm = RoiManager()
			rm.show()
			self.__img.show()
			IJ.selectWindow(self.__img.getTitle())
			rm.runCommand("reset")
			for i in range(len(outputrois)) :
				outputrois[i].setName(cellnames[i])
				rm.addRoi(outputrois[i])
				rm.select(rm.getCount()-1)
				rm.runCommand("Rename", cellnames[i])
			
			IJ.run("Show Overlay", "")
			rm.runCommand("UseNames", "true")
			rm.runCommand("Associate", "true")
			IJ.run(self.__img, "Labels...", "color=red font=12 show use")
			IJ.run(self.__img, "From ROI Manager", "")
			rm.runCommand("Show None")
			rm.runCommand("Show All")


		# ----------- batch analyse ------------------------
		if self.__batchanalyse :
			if self.__savetables :  saveResults()
			self.__dictMeasures.clear()
     			self.__allcells[:]=[]
     			self.__measurescompl[:]=[]
     			self.__measures[:]=[] 
			return False
			
		# ---------- display methodes dialog ----------------
		# Allows the user to choose how to see the results of the measures.		
		
		gd0=NonBlockingGenericDialog("Display")

		gd0.addMessage("How do you want to see the results ?")
		
		panel0=Panel()
		
		diagrambutton=Button("Diagram")
		diagrambutton.actionPerformed = diagrambuttonPressed
		panel0.add(diagrambutton)

		graphbutton=Button("Graph")
		graphbutton.actionPerformed = graphbuttonPressed
		panel0.add(graphbutton)

		tabbutton=Button("Tab")
		tabbutton.actionPerformed = tabbuttonPressed
		panel0.add(tabbutton)
		gd0.addPanel(panel0)
		gd0.addCheckbox("Analyse next stack ?", self.__nextstack)
		gd0.hideCancelButton()	
		gd0.showDialog()

		self.__nextstack = gd0.getNextBoolean()

		# ---------- save tables ---------------------------
		if self.__savetables :  saveResults()
		
		# --------- re-start analysis -------------------
		
     		self.__dictMeasures.clear()
     		#self.__listcellname[:]=[]
     		self.__allcells[:]=[]
     		self.__measurescompl[:]=[]
     		self.__measures[:]=[]

     		if self.__nextstack : return False
     		else : return True
Example #9
0
#!/usr/bin/env python
# vim: set fileencoding=utf-8

from java.awt import Color
from java.lang import StringBuffer
from java.awt import Button

print("\nButton")

b = Button("label")
print(b.getLabel())
print(b.label)

b.setLabel("new label")
print(b.getLabel())
print(b.label)

b.label = "yet another label"
print(b.getLabel())
print(b.label)

print("\nb")
b.background = Color.RED
print(b.background)

print("\nb2")
b2 = Button(label="label", background=Color.GREEN)
print(b2.background)
#


class TestButtonAction(ActionListener):
    def actionPerformed(self, e):
        textArea.append("Test Button Clicked!\n")


#
# Create the Frame, Panel, Button,
# TextArea, and TestButtonAction objects.
#

frame = Frame("Hello World")
panel = Panel()
button = Button("Test Button")
buttonAction = TestButtonAction()
textArea = TextArea()


#
# Put everything together and show
# the window.
#

button.addActionListener(buttonAction)
panel.add(button)
panel.add(textArea)
frame.add(panel)
frame.pack()
frame.show()
def perform_user_qc(in_imp, edges, alt_edges, fixed_anchors_list, params):
	"""allow the user to intervene to fix erroneously identified membrane edges"""
	n_frames = in_imp.getNFrames();
	n_channels = in_imp.getNChannels();
	output_folder = params.output_path;
	current_edges = edges;
	rgbstack = ImageStack(in_imp.getWidth(), in_imp.getHeight());
	if n_frames > 1:
		for tidx in range(n_frames): 
			in_imp.setT(tidx+1);
			ip = in_imp.getProcessor();
			rgbip = ip.convertToRGB();
			rgbstack.addSlice(rgbip);
	else:
		for cidx in range(n_channels):
			in_imp.setC(cidx+1);
			ip = in_imp.getProcessor();
			rgbip = ip.convertToRGB();
			rgbstack.addSlice(rgbip);
	imp = ImagePlus(("RGB " + in_imp.getTitle()), rgbstack);
	IJ.run("Colors...", "foreground=red background=white selection=yellow");
	for tidx in range(imp.getNSlices()):
		imp.setSlice(tidx+1);
		for anchor in params.manual_anchor_positions:
			imp.setRoi(PointRoi(anchor[0], anchor[1]));
			IJ.run(imp, "Draw", "slice");
	imp.show();
	autoset_zoom(imp);
	imp.setPosition(1);
	imp.setRoi(current_edges[0]);
	if n_frames > 1:
		listener = UpdateRoiImageListener(current_edges);
		imp.addImageListener(listener);
	IJ.setTool("freeline");
	do_flip = True;
	while do_flip:
		dialog = NonBlockingGenericDialog("User quality control");
		dialog.enableYesNoCancel("Continue", "Flip all edges");
		dialog.setCancelLabel("Cancel analysis");
		dialog.addMessage("Please redraw the membrane edges as necessary, \n" + 
						"making sure to draw beyond anchor points at either end...\n" + 
						"Click OK when done. ");
		p = Panel();
		but = Button("Flip this edge");
		al = Listener(edges, alt_edges, imp);
		but.addActionListener(al);
		p.add(but);
		dialog.addPanel(p);
		dialog.showDialog();
		if dialog.wasCanceled():
			raise KeyboardInterrupt("Run canceled");
		elif dialog.wasOKed():
			do_flip = False;
		else:
			print("flip edges");
			do_flip = True;
			if n_frames > 1:
				imp.removeImageListener(listener);
			current_edges = alt_edges if (current_edges == edges) else edges;
			imp.setPosition(1);
			imp.setRoi(current_edges[0]);
			if n_frames > 1:
				listener = UpdateRoiImageListener(current_edges);
				imp.addImageListener(listener);

	last_roi = imp.getRoi();
	if n_frames > 1:
		qcd_edges = listener.getRoiList();
		if imp.getNFrames() > imp.getNSlices():
			qcd_edges[imp.getT() - 1] = last_roi;
		else:
			qcd_edges[imp.getZ() - 1] = last_roi;
		imp.removeImageListener(listener);
	else:
		qcd_edges = [last_roi];
	mbio.save_qcd_edges2(qcd_edges, output_folder);
	# next four lines are a quick and dirty hack...
	if n_frames > 1:
		nframes = imp.getNFrames() if imp.getNFrames()>imp.getNSlices() else imp.getNSlices();
	else:
		nframes = n_frames;
	for fridx in range(0, nframes):
		if (qcd_edges[fridx].getType()==Roi.FREELINE) or (qcd_edges[fridx].getType()==Roi.POLYLINE):
			if (fridx == 0) or params.constrain_anchors:
				anchors = params.manual_anchor_positions;
			else:
				anchors = fixed_anchors_list[fridx - 1];
			fixed_anchors = mb.fix_anchors_to_membrane(anchors, qcd_edges[fridx], params);
			fixed_anchors = mb.order_anchors(fixed_anchors, params.manual_anchor_midpoint);
			fixed_anchors_list[fridx] = fixed_anchors;
			poly =  qcd_edges[fridx].getInterpolatedPolygon(0.25, False);
			polypoints = [(x,y) for x,y in zip(poly.xpoints, poly.ypoints)];
			idx = [polypoints.index(fixed_anchors[0]), polypoints.index(fixed_anchors[1])];
			idx.sort();
			polypoints = polypoints[idx[0]:idx[1]];
			newedge = PolygonRoi([x for (x,y) in polypoints], 
									[y for (x,y) in polypoints], 
									Roi.POLYLINE);
			newedge = mb.check_edge_order(anchors, newedge);
			imp.setPosition(fridx + 1);
			imp.setRoi(newedge);
			IJ.run(imp, "Interpolate", "interval=1.0 smooth adjust");
			IJ.run(imp, "Fit Spline", "");
			qcd_edges[fridx] = imp.getRoi();
	mbio.save_qcd_edges2(qcd_edges, output_folder);
	imp.changes = False;
	imp.close();
	return qcd_edges, fixed_anchors_list;
Example #12
0
	def createAndShowGUI(self):
		'''
		Create and display the gui.
		'''
		layout = GridBagLayout()
		c = GridBagConstraints()
		self.setLayout(layout)
		projectLabel = Label("Project: ")
		c.gridx = 0
		c.gridy = 0
		c.ipady = 5
		c.ipadx = 5
		c.anchor = GridBagConstraints.EAST
		layout.setConstraints(projectLabel, c)
		self.projectChoice = Choice()
		for name in self.projectNames:
			self.projectChoice.add(name)
		c.gridx = 1
		c.gridy = 0
		c.fill = GridBagConstraints.HORIZONTAL 
		layout.setConstraints(self.projectChoice, c)
		storageLabel = Label("Storage: ")
		c.gridx = 0
		c.gridy = 1
		c.fill = GridBagConstraints.NONE 
		c.anchor = GridBagConstraints.EAST
		layout.setConstraints(storageLabel, c)
		self.storageChoice = Choice()
		for name in self.storageNames:
			self.storageChoice.add(name)	
		c.gridx = 1
		c.gridy = 1
		c.fill = GridBagConstraints.HORIZONTAL 
		layout.setConstraints(self.storageChoice, c)
		self.convertToOMETIFCheckBox = Checkbox("convert to OME-TIF", True)
		c.gridx = 1
		c.gridy = 2
		layout.setConstraints(self.convertToOMETIFCheckBox, c)
		self.uploadAsGroundTruthCheckBox = Checkbox("upload as ground-truth images")
		c.gridx = 1
		c.gridy = 3
		layout.setConstraints(self.uploadAsGroundTruthCheckBox, c)
		self.folderTextField = TextField("", 15)
		self.folderTextField.setText("<Image-Folder>")
		c.gridx = 0
		c.gridy = 4
		layout.setConstraints(self.folderTextField, c)
		self.folderTextField.setEditable(False)
		browseButton = Button('Browse...')
		browseButton.addActionListener(self)
		c.gridx = 1
		c.gridy = 4
		layout.setConstraints(browseButton, c)
		statusLabel = Label("Status:")
		c.gridy = 5
		c.gridx = 0
		c.fill = GridBagConstraints.NONE 
		c.anchor = GridBagConstraints.EAST
		layout.setConstraints(statusLabel, c)
		self.statusTextField = TextField("Select a folder!", 20)
		c.gridy = 5
		c.gridx = 1
		c.fill = GridBagConstraints.HORIZONTAL 
		layout.setConstraints(self.statusTextField, c)
		self.statusTextField.setEditable(False)
		self.uploadButton = Button("Upload Images")
		self.uploadButton.addActionListener(self)
		c.gridwidth = 2
		c.gridheight = 2
		c.gridy = 6
		c.gridx = 0
		c.weighty = 1.0
		layout.setConstraints(self.uploadButton, c)
		self.add(projectLabel)
		self.add(self.projectChoice)
		self.add(storageLabel)
		self.add(self.storageChoice)
		self.add(self.convertToOMETIFCheckBox)
		self.add(self.uploadAsGroundTruthCheckBox)
		self.add(self.folderTextField)
		self.add(browseButton)
		self.add(statusLabel)
		self.add(self.statusTextField)
		self.add(self.uploadButton)
		self.setSize(400,300)
		self.setVisible(True)		
Example #13
0
class UploadWindow(Frame, WindowListener, ActionListener):
	'''
	A window to upload images to the biaflows server.

	The images can be uploaded as inut or as ground-truth images. Input images can
	be converted to the ome-tif format. Ground-truth images are always converted to
	ome-tif, if they are not alread in ome-tif format.
	'''
	def __init__(self): 
		'''
		Create and display the upload window.
		'''
		super(UploadWindow, self).__init__("BIAFlows Image Upload")
		self.biaflows = ConnectionWindow.getInstance().getBiaflows()
		self.nrOfImagesToUpload = 0
		projects = Projects()
		self.projectNames = projects.getNames()
		self.projectIDs = projects.getIDs()
		storages = Storages()
		self.storageNames = storages.getNames()
		self.storageIDs = storages.getIDs()
		self.createAndShowGUI()
		self.addWindowListener(self)
		WindowManager.addWindow(self)

	def windowClosing(self, e):   
		'''
		Close the image upload window and dispose of it. 

		Also remove it from the ij-window-manager.
		'''
		self.dispose()
		WindowManager.removeWindow(self)
		
	def windowActivated(self, e):  
		'''
		Nothing to do.
		'''
		pass

	def windowDeactivated(self, e):  
		'''
		Nothing to do.
		'''
		pass

	def windowClosed(self, e):  
		'''
		Nothing to do.
		'''
		pass

	def createAndShowGUI(self):
		'''
		Create and display the gui.
		'''
		layout = GridBagLayout()
		c = GridBagConstraints()
		self.setLayout(layout)
		projectLabel = Label("Project: ")
		c.gridx = 0
		c.gridy = 0
		c.ipady = 5
		c.ipadx = 5
		c.anchor = GridBagConstraints.EAST
		layout.setConstraints(projectLabel, c)
		self.projectChoice = Choice()
		for name in self.projectNames:
			self.projectChoice.add(name)
		c.gridx = 1
		c.gridy = 0
		c.fill = GridBagConstraints.HORIZONTAL 
		layout.setConstraints(self.projectChoice, c)
		storageLabel = Label("Storage: ")
		c.gridx = 0
		c.gridy = 1
		c.fill = GridBagConstraints.NONE 
		c.anchor = GridBagConstraints.EAST
		layout.setConstraints(storageLabel, c)
		self.storageChoice = Choice()
		for name in self.storageNames:
			self.storageChoice.add(name)	
		c.gridx = 1
		c.gridy = 1
		c.fill = GridBagConstraints.HORIZONTAL 
		layout.setConstraints(self.storageChoice, c)
		self.convertToOMETIFCheckBox = Checkbox("convert to OME-TIF", True)
		c.gridx = 1
		c.gridy = 2
		layout.setConstraints(self.convertToOMETIFCheckBox, c)
		self.uploadAsGroundTruthCheckBox = Checkbox("upload as ground-truth images")
		c.gridx = 1
		c.gridy = 3
		layout.setConstraints(self.uploadAsGroundTruthCheckBox, c)
		self.folderTextField = TextField("", 15)
		self.folderTextField.setText("<Image-Folder>")
		c.gridx = 0
		c.gridy = 4
		layout.setConstraints(self.folderTextField, c)
		self.folderTextField.setEditable(False)
		browseButton = Button('Browse...')
		browseButton.addActionListener(self)
		c.gridx = 1
		c.gridy = 4
		layout.setConstraints(browseButton, c)
		statusLabel = Label("Status:")
		c.gridy = 5
		c.gridx = 0
		c.fill = GridBagConstraints.NONE 
		c.anchor = GridBagConstraints.EAST
		layout.setConstraints(statusLabel, c)
		self.statusTextField = TextField("Select a folder!", 20)
		c.gridy = 5
		c.gridx = 1
		c.fill = GridBagConstraints.HORIZONTAL 
		layout.setConstraints(self.statusTextField, c)
		self.statusTextField.setEditable(False)
		self.uploadButton = Button("Upload Images")
		self.uploadButton.addActionListener(self)
		c.gridwidth = 2
		c.gridheight = 2
		c.gridy = 6
		c.gridx = 0
		c.weighty = 1.0
		layout.setConstraints(self.uploadButton, c)
		self.add(projectLabel)
		self.add(self.projectChoice)
		self.add(storageLabel)
		self.add(self.storageChoice)
		self.add(self.convertToOMETIFCheckBox)
		self.add(self.uploadAsGroundTruthCheckBox)
		self.add(self.folderTextField)
		self.add(browseButton)
		self.add(statusLabel)
		self.add(self.statusTextField)
		self.add(self.uploadButton)
		self.setSize(400,300)
		self.setVisible(True)		

	def changed(self, sender, aspect, newValue):
		if aspect=='image upload':
			self.statusTextField.setText('Uploading image ' + str(newValue) + '.')
		if aspect=='image upload finished':
			self.statusTextField.setText('Upload finished, ' + str(newValue) + ' images uploaded.')
			self.removeTmpFiles()
			
		if aspect=='image upload error':
			self.statusTextField.setText('Error uploading ' + str(newValue) + '.')

	def removeTmpFiles(self):
		if self.convertToOMETIFCheckBox.getState():
			shutil.rmtree(self.tmpFolder)		
	
	def actionPerformed(self, e):
		'''
		Event handler for the buttons.
		'''
		cmd = e.getActionCommand()
		if cmd=='Browse...':
			folder = IJ.getDirectory("Select the image folder")
			if not folder:
				return
			self.folderTextField.setText(folder)
			images = Uploader.getImageList(folder)
			self.nrOfImagesToUpload = len(images)
			self.inputFolder = folder
			self.statusTextField.setText(str(self.nrOfImagesToUpload) + ' images to upload...')
		if cmd=='Upload Images':
			print('upload')
			if self.nrOfImagesToUpload < 1:
				return
			else:
				# convert if ome checked. Add _lbl if ground-truth checked. upload
				self.statusTextField.setText('Uploading ' + str(self.nrOfImagesToUpload) + ' images...')
				imageFolder = self.folderTextField.getText()
				uploader = Uploader.getInstance(self.biaflows)
				uploader.addObserver(self)
				self.tmpFolder = None
				if self.convertToOMETIFCheckBox.getState() or self.uploadAsGroundTruthCheckBox.getState():
					self.statusTextField.setText('Converting ' + str(self.nrOfImagesToUpload) + ' images...')
					# convert and add '_lbl' if ground truth
					self.tmpFolder = imageFolder + 'biaflows_tmp/'
					suffix = ''
					if self.uploadAsGroundTruthCheckBox.getState():
						suffix = '_lbl'
					uploader.convertImagesInFolderToOME(imageFolder, self.tmpFolder, suffix)
					imageFolder = self.tmpFolder
				# upload
				pid = self.projectIDs[self.projectChoice.getSelectedIndex()]
				sid = self.storageIDs[self.storageChoice.getSelectedIndex()]
				self.statusTextField.setText('Uploading ' + str(self.nrOfImagesToUpload) + ' images...')
				uploader.setInputFolder(imageFolder)
				uploader.setProject(str(pid))
				uploader.setStorage(str(sid))
				thread = Thread(uploader)
				thread.start()
				# cleanup
				self.statusTextField.setText('Upload started.')